Merge git://git.infradead.org/users/willy/linux-nvme
[cascardo/linux.git] / drivers / staging / rtl8187se / r8180_core.c
1 /*
2    This is part of rtl818x pci OpenSource driver - v 0.1
3    Copyright (C) Andrea Merello 2004-2005  <andrea.merello@gmail.com>
4    Released under the terms of GPL (General Public License)
5
6    Parts of this driver are based on the GPL part of the official
7    Realtek driver.
8
9    Parts of this driver are based on the rtl8180 driver skeleton
10    from Patric Schenke & Andres Salomon.
11
12    Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver.
13
14    Parts of BB/RF code are derived from David Young rtl8180 netbsd driver.
15
16    RSSI calc function from 'The Deuce'
17
18    Some ideas borrowed from the 8139too.c driver included in linux kernel.
19
20    We (I?) want to thanks the Authors of those projecs and also the
21    Ndiswrapper's project Authors.
22
23    A big big thanks goes also to Realtek corp. for their help in my attempt to
24    add RTL8185 and RTL8225 support, and to David Young also.
25
26    Power management interface routines.
27    Written by Mariusz Matuszek.
28 */
29
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31
32 #undef RX_DONT_PASS_UL
33 #undef DUMMY_RX
34
35 #include <linux/slab.h>
36 #include <linux/syscalls.h>
37 #include <linux/eeprom_93cx6.h>
38 #include <linux/interrupt.h>
39 #include <linux/proc_fs.h>
40 #include <linux/seq_file.h>
41
42 #include "r8180_hw.h"
43 #include "r8180.h"
44 #include "r8180_rtl8225.h" /* RTL8225 Radio frontend */
45 #include "r8180_93cx6.h"   /* Card EEPROM */
46 #include "r8180_wx.h"
47 #include "r8180_dm.h"
48
49 #include "ieee80211/dot11d.h"
50
51 static struct pci_device_id rtl8180_pci_id_tbl[] = {
52         {
53                 .vendor = PCI_VENDOR_ID_REALTEK,
54                 .device = 0x8199,
55                 .subvendor = PCI_ANY_ID,
56                 .subdevice = PCI_ANY_ID,
57                 .driver_data = 0,
58         },
59         {
60                 .vendor = 0,
61                 .device = 0,
62                 .subvendor = 0,
63                 .subdevice = 0,
64                 .driver_data = 0,
65         }
66 };
67
68 static char ifname[IFNAMSIZ] = "wlan%d";
69 static int hwwep;
70
71 MODULE_LICENSE("GPL");
72 MODULE_DEVICE_TABLE(pci, rtl8180_pci_id_tbl);
73 MODULE_AUTHOR("Andrea Merello <andrea.merello@gmail.com>");
74 MODULE_DESCRIPTION("Linux driver for Realtek RTL8187SE WiFi cards");
75
76 module_param_string(ifname, ifname, sizeof(ifname), S_IRUGO|S_IWUSR);
77 module_param(hwwep, int, S_IRUGO|S_IWUSR);
78
79 MODULE_PARM_DESC(hwwep, " Try to use hardware WEP support. Still broken and not available on all cards");
80
81 static int rtl8180_pci_probe(struct pci_dev *pdev,
82                              const struct pci_device_id *id);
83
84 static void rtl8180_pci_remove(struct pci_dev *pdev);
85
86 static void rtl8180_shutdown(struct pci_dev *pdev)
87 {
88         struct net_device *dev = pci_get_drvdata(pdev);
89         if (dev->netdev_ops->ndo_stop)
90                 dev->netdev_ops->ndo_stop(dev);
91         pci_disable_device(pdev);
92 }
93
94 static int rtl8180_suspend(struct pci_dev *pdev, pm_message_t state)
95 {
96         struct net_device *dev = pci_get_drvdata(pdev);
97
98         if (!netif_running(dev))
99                 goto out_pci_suspend;
100
101         if (dev->netdev_ops->ndo_stop)
102                 dev->netdev_ops->ndo_stop(dev);
103
104         netif_device_detach(dev);
105
106 out_pci_suspend:
107         pci_save_state(pdev);
108         pci_disable_device(pdev);
109         pci_set_power_state(pdev, pci_choose_state(pdev, state));
110         return 0;
111 }
112
113 static int rtl8180_resume(struct pci_dev *pdev)
114 {
115         struct net_device *dev = pci_get_drvdata(pdev);
116         int err;
117         u32 val;
118
119         pci_set_power_state(pdev, PCI_D0);
120
121         err = pci_enable_device(pdev);
122         if (err) {
123                 dev_err(&pdev->dev, "pci_enable_device failed on resume\n");
124
125                 return err;
126         }
127
128         pci_restore_state(pdev);
129
130         /*
131          * Suspend/Resume resets the PCI configuration space, so we have to
132          * re-disable the RETRY_TIMEOUT register (0x41) to keep PCI Tx retries
133          * from interfering with C3 CPU state. pci_restore_state won't help
134          * here since it only restores the first 64 bytes pci config header.
135          */
136         pci_read_config_dword(pdev, 0x40, &val);
137         if ((val & 0x0000ff00) != 0)
138                 pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
139
140         if (!netif_running(dev))
141                 goto out;
142
143         if (dev->netdev_ops->ndo_open)
144                 dev->netdev_ops->ndo_open(dev);
145
146         netif_device_attach(dev);
147 out:
148         return 0;
149 }
150
151 static struct pci_driver rtl8180_pci_driver = {
152         .name           = RTL8180_MODULE_NAME,
153         .id_table       = rtl8180_pci_id_tbl,
154         .probe          = rtl8180_pci_probe,
155         .remove         = rtl8180_pci_remove,
156         .suspend        = rtl8180_suspend,
157         .resume         = rtl8180_resume,
158         .shutdown       = rtl8180_shutdown,
159 };
160
161 u8 read_nic_byte(struct net_device *dev, int x)
162 {
163         return 0xff&readb((u8 __iomem *)dev->mem_start + x);
164 }
165
166 u32 read_nic_dword(struct net_device *dev, int x)
167 {
168         return readl((u8 __iomem *)dev->mem_start + x);
169 }
170
171 u16 read_nic_word(struct net_device *dev, int x)
172 {
173         return readw((u8 __iomem *)dev->mem_start + x);
174 }
175
176 void write_nic_byte(struct net_device *dev, int x, u8 y)
177 {
178         writeb(y, (u8 __iomem *)dev->mem_start + x);
179         udelay(20);
180 }
181
182 void write_nic_dword(struct net_device *dev, int x, u32 y)
183 {
184         writel(y, (u8 __iomem *)dev->mem_start + x);
185         udelay(20);
186 }
187
188 void write_nic_word(struct net_device *dev, int x, u16 y)
189 {
190         writew(y, (u8 __iomem *)dev->mem_start + x);
191         udelay(20);
192 }
193
194 inline void force_pci_posting(struct net_device *dev)
195 {
196         read_nic_byte(dev, EPROM_CMD);
197         mb();
198 }
199
200 static irqreturn_t rtl8180_interrupt(int irq, void *netdev);
201 void set_nic_rxring(struct net_device *dev);
202 void set_nic_txring(struct net_device *dev);
203 static struct net_device_stats *rtl8180_stats(struct net_device *dev);
204 void rtl8180_commit(struct net_device *dev);
205 void rtl8180_start_tx_beacon(struct net_device *dev);
206
207 static struct proc_dir_entry *rtl8180_proc;
208
209 static int proc_get_registers(struct seq_file *m, void *v)
210 {
211         struct net_device *dev = m->private;
212         int i, n, max = 0xff;
213
214         /* This dump the current register page */
215         for (n = 0; n <= max;) {
216                 seq_printf(m, "\nD:  %2x > ", n);
217
218                 for (i = 0; i < 16 && n <= max; i++, n++)
219                         seq_printf(m, "%2x ", read_nic_byte(dev, n));
220         }
221         seq_putc(m, '\n');
222         return 0;
223 }
224
225 int get_curr_tx_free_desc(struct net_device *dev, int priority);
226
227 static int proc_get_stats_hw(struct seq_file *m, void *v)
228 {
229         return 0;
230 }
231
232 static int proc_get_stats_rx(struct seq_file *m, void *v)
233 {
234         struct net_device *dev = m->private;
235         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
236
237         seq_printf(m,
238                 "RX OK: %lu\n"
239                 "RX Retry: %lu\n"
240                 "RX CRC Error(0-500): %lu\n"
241                 "RX CRC Error(500-1000): %lu\n"
242                 "RX CRC Error(>1000): %lu\n"
243                 "RX ICV Error: %lu\n",
244                 priv->stats.rxint,
245                 priv->stats.rxerr,
246                 priv->stats.rxcrcerrmin,
247                 priv->stats.rxcrcerrmid,
248                 priv->stats.rxcrcerrmax,
249                 priv->stats.rxicverr
250                 );
251
252         return 0;
253 }
254
255 static int proc_get_stats_tx(struct seq_file *m, void *v)
256 {
257         struct net_device *dev = m->private;
258         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
259         unsigned long totalOK;
260
261         totalOK = priv->stats.txnpokint+priv->stats.txhpokint+priv->stats.txlpokint;
262         seq_printf(m,
263                 "TX OK: %lu\n"
264                 "TX Error: %lu\n"
265                 "TX Retry: %lu\n"
266                 "TX beacon OK: %lu\n"
267                 "TX beacon error: %lu\n",
268                 totalOK,
269                 priv->stats.txnperr+priv->stats.txhperr+priv->stats.txlperr,
270                 priv->stats.txretry,
271                 priv->stats.txbeacon,
272                 priv->stats.txbeaconerr
273         );
274
275         return 0;
276 }
277
278 static void rtl8180_proc_module_init(void)
279 {
280         DMESG("Initializing proc filesystem");
281         rtl8180_proc = proc_mkdir(RTL8180_MODULE_NAME, init_net.proc_net);
282 }
283
284 static void rtl8180_proc_module_remove(void)
285 {
286         remove_proc_entry(RTL8180_MODULE_NAME, init_net.proc_net);
287 }
288
289 static void rtl8180_proc_remove_one(struct net_device *dev)
290 {
291         remove_proc_subtree(dev->name, rtl8180_proc);
292 }
293
294 /*
295  * seq_file wrappers for procfile show routines.
296  */
297 static int rtl8180_proc_open(struct inode *inode, struct file *file)
298 {
299         struct net_device *dev = proc_get_parent_data(inode);
300         int (*show)(struct seq_file *, void *) = PDE_DATA(inode);
301
302         return single_open(file, show, dev);
303 }
304
305 static const struct file_operations rtl8180_proc_fops = {
306         .open           = rtl8180_proc_open,
307         .read           = seq_read,
308         .llseek         = seq_lseek,
309         .release        = single_release,
310 };
311
312 /*
313  * Table of proc files we need to create.
314  */
315 struct rtl8180_proc_file {
316         char name[12];
317         int (*show)(struct seq_file *, void *);
318 };
319
320 static const struct rtl8180_proc_file rtl8180_proc_files[] = {
321         { "stats-hw",   &proc_get_stats_hw },
322         { "stats-rx",   &proc_get_stats_rx },
323         { "stats-tx",   &proc_get_stats_tx },
324         { "registers",  &proc_get_registers },
325         { "" }
326 };
327
328 static void rtl8180_proc_init_one(struct net_device *dev)
329 {
330         const struct rtl8180_proc_file *f;
331         struct proc_dir_entry *dir;
332
333         dir = proc_mkdir_data(dev->name, 0, rtl8180_proc, dev);
334         if (!dir) {
335                 DMESGE("Unable to initialize /proc/net/r8180/%s\n", dev->name);
336                 return;
337         }
338
339         for (f = rtl8180_proc_files; f->name[0]; f++) {
340                 if (!proc_create_data(f->name, S_IFREG | S_IRUGO, dir,
341                                       &rtl8180_proc_fops, f->show)) {
342                         DMESGE("Unable to initialize /proc/net/r8180/%s/%s\n",
343                                dev->name, f->name);
344                         return;
345                 }
346         }
347 }
348
349 /*
350   FIXME: check if we can use some standard already-existent
351   data type+functions in kernel
352 */
353
354 static short buffer_add(struct buffer **buffer, u32 *buf, dma_addr_t dma,
355                         struct buffer **bufferhead)
356 {
357         struct buffer *tmp;
358
359         if (!*buffer) {
360
361                 *buffer = kmalloc(sizeof(struct buffer), GFP_KERNEL);
362
363                 if (*buffer == NULL) {
364                         DMESGE("Failed to kmalloc head of TX/RX struct");
365                         return -1;
366                 }
367                 (*buffer)->next = *buffer;
368                 (*buffer)->buf = buf;
369                 (*buffer)->dma = dma;
370                 if (bufferhead != NULL)
371                         (*bufferhead) = (*buffer);
372                 return 0;
373         }
374         tmp = *buffer;
375
376         while (tmp->next != (*buffer))
377                 tmp = tmp->next;
378         tmp->next = kmalloc(sizeof(struct buffer), GFP_KERNEL);
379         if (tmp->next == NULL) {
380                 DMESGE("Failed to kmalloc TX/RX struct");
381                 return -1;
382         }
383         tmp->next->buf = buf;
384         tmp->next->dma = dma;
385         tmp->next->next = *buffer;
386
387         return 0;
388 }
389
390 static void buffer_free(struct net_device *dev, struct buffer **buffer, int len,
391                  short consistent)
392 {
393
394         struct buffer *tmp, *next;
395         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
396         struct pci_dev *pdev = priv->pdev;
397
398         if (!*buffer)
399                 return;
400
401         tmp = *buffer;
402
403         do {
404                 next = tmp->next;
405                 if (consistent) {
406                         pci_free_consistent(pdev, len,
407                                     tmp->buf, tmp->dma);
408                 } else {
409                         pci_unmap_single(pdev, tmp->dma,
410                         len, PCI_DMA_FROMDEVICE);
411                         kfree(tmp->buf);
412                 }
413                 kfree(tmp);
414                 tmp = next;
415         } while (next != *buffer);
416
417         *buffer = NULL;
418 }
419
420 int get_curr_tx_free_desc(struct net_device *dev, int priority)
421 {
422         struct r8180_priv *priv = ieee80211_priv(dev);
423         u32 *tail;
424         u32 *head;
425         int ret;
426
427         switch (priority) {
428         case MANAGE_PRIORITY:
429                 head = priv->txmapringhead;
430                 tail = priv->txmapringtail;
431                 break;
432         case BK_PRIORITY:
433                 head = priv->txbkpringhead;
434                 tail = priv->txbkpringtail;
435                 break;
436         case BE_PRIORITY:
437                 head = priv->txbepringhead;
438                 tail = priv->txbepringtail;
439                 break;
440         case VI_PRIORITY:
441                 head = priv->txvipringhead;
442                 tail = priv->txvipringtail;
443                 break;
444         case VO_PRIORITY:
445                 head = priv->txvopringhead;
446                 tail = priv->txvopringtail;
447                 break;
448         case HI_PRIORITY:
449                 head = priv->txhpringhead;
450                 tail = priv->txhpringtail;
451                 break;
452         default:
453                 return -1;
454         }
455
456         if (head <= tail)
457                 ret = priv->txringcount - (tail - head)/8;
458         else
459                 ret = (head - tail)/8;
460
461         if (ret > priv->txringcount)
462                 DMESG("BUG");
463
464         return ret;
465 }
466
467 static short check_nic_enought_desc(struct net_device *dev, int priority)
468 {
469         struct r8180_priv *priv = ieee80211_priv(dev);
470         struct ieee80211_device *ieee = netdev_priv(dev);
471         int requiredbyte, required;
472
473         requiredbyte = priv->ieee80211->fts + sizeof(struct ieee80211_header_data);
474
475         if (ieee->current_network.QoS_Enable)
476                 requiredbyte += 2;
477
478         required = requiredbyte / (priv->txbuffsize-4);
479
480         if (requiredbyte % priv->txbuffsize)
481                 required++;
482
483         /* for now we keep two free descriptor as a safety boundary
484          * between the tail and the head
485          */
486
487         return (required+2 < get_curr_tx_free_desc(dev, priority));
488 }
489
490 void fix_tx_fifo(struct net_device *dev)
491 {
492         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
493         u32 *tmp;
494         int i;
495
496         for (tmp = priv->txmapring, i = 0;
497              i < priv->txringcount;
498              tmp += 8, i++) {
499                 *tmp = *tmp & ~(1<<31);
500         }
501
502         for (tmp = priv->txbkpring, i = 0;
503              i < priv->txringcount;
504              tmp += 8, i++) {
505                 *tmp = *tmp & ~(1<<31);
506         }
507
508         for (tmp = priv->txbepring, i = 0;
509              i < priv->txringcount;
510              tmp += 8, i++) {
511                 *tmp = *tmp & ~(1<<31);
512         }
513         for (tmp = priv->txvipring, i = 0;
514              i < priv->txringcount;
515              tmp += 8, i++) {
516                 *tmp = *tmp & ~(1<<31);
517         }
518
519         for (tmp = priv->txvopring, i = 0;
520              i < priv->txringcount;
521              tmp += 8, i++) {
522                 *tmp = *tmp & ~(1<<31);
523         }
524
525         for (tmp = priv->txhpring, i = 0;
526              i < priv->txringcount;
527              tmp += 8, i++) {
528                 *tmp = *tmp & ~(1<<31);
529         }
530
531         for (tmp = priv->txbeaconring, i = 0;
532              i < priv->txbeaconcount;
533              tmp += 8, i++) {
534                 *tmp = *tmp & ~(1<<31);
535         }
536
537         priv->txmapringtail = priv->txmapring;
538         priv->txmapringhead = priv->txmapring;
539         priv->txmapbufstail = priv->txmapbufs;
540
541         priv->txbkpringtail = priv->txbkpring;
542         priv->txbkpringhead = priv->txbkpring;
543         priv->txbkpbufstail = priv->txbkpbufs;
544
545         priv->txbepringtail = priv->txbepring;
546         priv->txbepringhead = priv->txbepring;
547         priv->txbepbufstail = priv->txbepbufs;
548
549         priv->txvipringtail = priv->txvipring;
550         priv->txvipringhead = priv->txvipring;
551         priv->txvipbufstail = priv->txvipbufs;
552
553         priv->txvopringtail = priv->txvopring;
554         priv->txvopringhead = priv->txvopring;
555         priv->txvopbufstail = priv->txvopbufs;
556
557         priv->txhpringtail = priv->txhpring;
558         priv->txhpringhead = priv->txhpring;
559         priv->txhpbufstail = priv->txhpbufs;
560
561         priv->txbeaconringtail = priv->txbeaconring;
562         priv->txbeaconbufstail = priv->txbeaconbufs;
563         set_nic_txring(dev);
564
565         ieee80211_reset_queue(priv->ieee80211);
566         priv->ack_tx_to_ieee = 0;
567 }
568
569 void fix_rx_fifo(struct net_device *dev)
570 {
571         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
572         u32 *tmp;
573         struct buffer *rxbuf;
574         u8 rx_desc_size;
575
576         rx_desc_size = 8; /* 4*8 = 32 bytes */
577
578         for (tmp = priv->rxring, rxbuf = priv->rxbufferhead;
579              (tmp < (priv->rxring)+(priv->rxringcount)*rx_desc_size);
580              tmp += rx_desc_size, rxbuf = rxbuf->next) {
581                 *(tmp+2) = rxbuf->dma;
582                 *tmp = *tmp & ~0xfff;
583                 *tmp = *tmp | priv->rxbuffersize;
584                 *tmp |= (1<<31);
585         }
586
587         priv->rxringtail = priv->rxring;
588         priv->rxbuffer = priv->rxbufferhead;
589         priv->rx_skb_complete = 1;
590         set_nic_rxring(dev);
591 }
592
593 static void rtl8180_irq_disable(struct net_device *dev)
594 {
595         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
596
597         write_nic_dword(dev, IMR, 0);
598         force_pci_posting(dev);
599         priv->irq_enabled = 0;
600 }
601
602 void rtl8180_set_mode(struct net_device *dev, int mode)
603 {
604         u8 ecmd;
605
606         ecmd = read_nic_byte(dev, EPROM_CMD);
607         ecmd = ecmd & ~EPROM_CMD_OPERATING_MODE_MASK;
608         ecmd = ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
609         ecmd = ecmd & ~(1<<EPROM_CS_SHIFT);
610         ecmd = ecmd & ~(1<<EPROM_CK_SHIFT);
611         write_nic_byte(dev, EPROM_CMD, ecmd);
612 }
613
614 void rtl8180_beacon_tx_enable(struct net_device *dev);
615
616 void rtl8180_update_msr(struct net_device *dev)
617 {
618         struct r8180_priv *priv = ieee80211_priv(dev);
619         u8 msr;
620         u32 rxconf;
621
622         msr  = read_nic_byte(dev, MSR);
623         msr &= ~MSR_LINK_MASK;
624
625         rxconf = read_nic_dword(dev, RX_CONF);
626
627         if (priv->ieee80211->state == IEEE80211_LINKED) {
628                 if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
629                         msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
630                 else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
631                         msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
632                 else if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
633                         msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
634                 else
635                         msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
636                 rxconf |= (1<<RX_CHECK_BSSID_SHIFT);
637
638         } else {
639                 msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
640                 rxconf &= ~(1<<RX_CHECK_BSSID_SHIFT);
641         }
642
643         write_nic_byte(dev, MSR, msr);
644         write_nic_dword(dev, RX_CONF, rxconf);
645 }
646
647 void rtl8180_set_chan(struct net_device *dev, short ch)
648 {
649         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
650
651         if ((ch > 14) || (ch < 1)) {
652                 printk("In %s: Invalid chnanel %d\n", __func__, ch);
653                 return;
654         }
655
656         priv->chan = ch;
657         priv->rf_set_chan(dev, priv->chan);
658 }
659
660 void set_nic_txring(struct net_device *dev)
661 {
662         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
663
664         write_nic_dword(dev, TX_MANAGEPRIORITY_RING_ADDR, priv->txmapringdma);
665         write_nic_dword(dev, TX_BKPRIORITY_RING_ADDR, priv->txbkpringdma);
666         write_nic_dword(dev, TX_BEPRIORITY_RING_ADDR, priv->txbepringdma);
667         write_nic_dword(dev, TX_VIPRIORITY_RING_ADDR, priv->txvipringdma);
668         write_nic_dword(dev, TX_VOPRIORITY_RING_ADDR, priv->txvopringdma);
669         write_nic_dword(dev, TX_HIGHPRIORITY_RING_ADDR, priv->txhpringdma);
670         write_nic_dword(dev, TX_BEACON_RING_ADDR, priv->txbeaconringdma);
671 }
672
673 void rtl8180_beacon_tx_enable(struct net_device *dev)
674 {
675         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
676
677         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
678         priv->dma_poll_stop_mask &= ~(TPPOLLSTOP_BQ);
679         write_nic_byte(dev, TPPollStop, priv->dma_poll_mask);
680         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
681 }
682
683 void rtl8180_beacon_tx_disable(struct net_device *dev)
684 {
685         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
686
687         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
688         priv->dma_poll_stop_mask |= TPPOLLSTOP_BQ;
689         write_nic_byte(dev, TPPollStop, priv->dma_poll_stop_mask);
690         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
691
692 }
693
694 void rtl8180_rtx_disable(struct net_device *dev)
695 {
696         u8 cmd;
697         struct r8180_priv *priv = ieee80211_priv(dev);
698
699         cmd = read_nic_byte(dev, CMD);
700         write_nic_byte(dev, CMD, cmd &
701                        ~((1<<CMD_RX_ENABLE_SHIFT)|(1<<CMD_TX_ENABLE_SHIFT)));
702         force_pci_posting(dev);
703         mdelay(10);
704
705         if (!priv->rx_skb_complete)
706                 dev_kfree_skb_any(priv->rx_skb);
707 }
708
709 static short alloc_tx_desc_ring(struct net_device *dev, int bufsize, int count,
710                                 int addr)
711 {
712         int i;
713         u32 *desc;
714         u32 *tmp;
715         dma_addr_t dma_desc, dma_tmp;
716         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
717         struct pci_dev *pdev = priv->pdev;
718         void *buf;
719
720         if ((bufsize & 0xfff) != bufsize) {
721                 DMESGE("TX buffer allocation too large");
722                 return 0;
723         }
724         desc = (u32 *)pci_alloc_consistent(pdev,
725                                           sizeof(u32)*8*count+256, &dma_desc);
726         if (desc == NULL)
727                 return -1;
728
729         if (dma_desc & 0xff)
730                 /*
731                  * descriptor's buffer must be 256 byte aligned
732                  * we shouldn't be here, since we set DMA mask !
733                  */
734                 WARN(1, "DMA buffer is not aligned\n");
735
736         tmp = desc;
737
738         for (i = 0; i < count; i++) {
739                 buf = (void *)pci_alloc_consistent(pdev, bufsize, &dma_tmp);
740                 if (buf == NULL)
741                         return -ENOMEM;
742
743                 switch (addr) {
744                 case TX_MANAGEPRIORITY_RING_ADDR:
745                         if (-1 == buffer_add(&(priv->txmapbufs), buf, dma_tmp, NULL)) {
746                                 DMESGE("Unable to allocate mem for buffer NP");
747                                 return -ENOMEM;
748                         }
749                         break;
750                 case TX_BKPRIORITY_RING_ADDR:
751                         if (-1 == buffer_add(&(priv->txbkpbufs), buf, dma_tmp, NULL)) {
752                                 DMESGE("Unable to allocate mem for buffer LP");
753                                 return -ENOMEM;
754                         }
755                         break;
756                 case TX_BEPRIORITY_RING_ADDR:
757                         if (-1 == buffer_add(&(priv->txbepbufs), buf, dma_tmp, NULL)) {
758                                 DMESGE("Unable to allocate mem for buffer NP");
759                                 return -ENOMEM;
760                         }
761                         break;
762                 case TX_VIPRIORITY_RING_ADDR:
763                         if (-1 == buffer_add(&(priv->txvipbufs), buf, dma_tmp, NULL)) {
764                                 DMESGE("Unable to allocate mem for buffer LP");
765                                 return -ENOMEM;
766                         }
767                         break;
768                 case TX_VOPRIORITY_RING_ADDR:
769                         if (-1 == buffer_add(&(priv->txvopbufs), buf, dma_tmp, NULL)) {
770                                 DMESGE("Unable to allocate mem for buffer NP");
771                                 return -ENOMEM;
772                         }
773                         break;
774                 case TX_HIGHPRIORITY_RING_ADDR:
775                         if (-1 == buffer_add(&(priv->txhpbufs), buf, dma_tmp, NULL)) {
776                                 DMESGE("Unable to allocate mem for buffer HP");
777                                 return -ENOMEM;
778                         }
779                         break;
780                 case TX_BEACON_RING_ADDR:
781                         if (-1 == buffer_add(&(priv->txbeaconbufs), buf, dma_tmp, NULL)) {
782                                 DMESGE("Unable to allocate mem for buffer BP");
783                                 return -ENOMEM;
784                         }
785                         break;
786                 }
787                 *tmp = *tmp & ~(1<<31); /* descriptor empty, owned by the drv */
788                 *(tmp+2) = (u32)dma_tmp;
789                 *(tmp+3) = bufsize;
790
791                 if (i+1 < count)
792                         *(tmp+4) = (u32)dma_desc+((i+1)*8*4);
793                 else
794                         *(tmp+4) = (u32)dma_desc;
795
796                 tmp = tmp+8;
797         }
798
799         switch (addr) {
800         case TX_MANAGEPRIORITY_RING_ADDR:
801                 priv->txmapringdma = dma_desc;
802                 priv->txmapring = desc;
803                 break;
804         case TX_BKPRIORITY_RING_ADDR:
805                 priv->txbkpringdma = dma_desc;
806                 priv->txbkpring = desc;
807                 break;
808         case TX_BEPRIORITY_RING_ADDR:
809                 priv->txbepringdma = dma_desc;
810                 priv->txbepring = desc;
811                 break;
812         case TX_VIPRIORITY_RING_ADDR:
813                 priv->txvipringdma = dma_desc;
814                 priv->txvipring = desc;
815                 break;
816         case TX_VOPRIORITY_RING_ADDR:
817                 priv->txvopringdma = dma_desc;
818                 priv->txvopring = desc;
819                 break;
820         case TX_HIGHPRIORITY_RING_ADDR:
821                 priv->txhpringdma = dma_desc;
822                 priv->txhpring = desc;
823                 break;
824         case TX_BEACON_RING_ADDR:
825                 priv->txbeaconringdma = dma_desc;
826                 priv->txbeaconring = desc;
827                 break;
828
829         }
830
831         return 0;
832 }
833
834 static void free_tx_desc_rings(struct net_device *dev)
835 {
836         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
837         struct pci_dev *pdev = priv->pdev;
838         int count = priv->txringcount;
839
840         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
841                             priv->txmapring, priv->txmapringdma);
842         buffer_free(dev, &(priv->txmapbufs), priv->txbuffsize, 1);
843
844         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
845                             priv->txbkpring, priv->txbkpringdma);
846         buffer_free(dev, &(priv->txbkpbufs), priv->txbuffsize, 1);
847
848         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
849                             priv->txbepring, priv->txbepringdma);
850         buffer_free(dev, &(priv->txbepbufs), priv->txbuffsize, 1);
851
852         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
853                             priv->txvipring, priv->txvipringdma);
854         buffer_free(dev, &(priv->txvipbufs), priv->txbuffsize, 1);
855
856         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
857                             priv->txvopring, priv->txvopringdma);
858         buffer_free(dev, &(priv->txvopbufs), priv->txbuffsize, 1);
859
860         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
861                             priv->txhpring, priv->txhpringdma);
862         buffer_free(dev, &(priv->txhpbufs), priv->txbuffsize, 1);
863
864         count = priv->txbeaconcount;
865         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
866                             priv->txbeaconring, priv->txbeaconringdma);
867         buffer_free(dev, &(priv->txbeaconbufs), priv->txbuffsize, 1);
868 }
869
870 static void free_rx_desc_ring(struct net_device *dev)
871 {
872         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
873         struct pci_dev *pdev = priv->pdev;
874         int count = priv->rxringcount;
875
876         pci_free_consistent(pdev, sizeof(u32)*8*count+256,
877                             priv->rxring, priv->rxringdma);
878
879         buffer_free(dev, &(priv->rxbuffer), priv->rxbuffersize, 0);
880 }
881
882 static short alloc_rx_desc_ring(struct net_device *dev, u16 bufsize, int count)
883 {
884         int i;
885         u32 *desc;
886         u32 *tmp;
887         dma_addr_t dma_desc, dma_tmp;
888         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
889         struct pci_dev *pdev = priv->pdev;
890         void *buf;
891         u8 rx_desc_size;
892
893         rx_desc_size = 8; /* 4*8 = 32 bytes */
894
895         if ((bufsize & 0xfff) != bufsize) {
896                 DMESGE("RX buffer allocation too large");
897                 return -1;
898         }
899
900         desc = (u32 *)pci_alloc_consistent(pdev, sizeof(u32)*rx_desc_size*count+256,
901                                           &dma_desc);
902
903         if (dma_desc & 0xff)
904                 /*
905                  * descriptor's buffer must be 256 byte aligned
906                  * should never happen since we specify the DMA mask
907                  */
908                 WARN(1, "DMA buffer is not aligned\n");
909
910         priv->rxring = desc;
911         priv->rxringdma = dma_desc;
912         tmp = desc;
913
914         for (i = 0; i < count; i++) {
915                 buf = kmalloc(bufsize * sizeof(u8), GFP_ATOMIC);
916                 if (buf == NULL) {
917                         DMESGE("Failed to kmalloc RX buffer");
918                         return -1;
919                 }
920
921                 dma_tmp = pci_map_single(pdev, buf, bufsize * sizeof(u8),
922                                          PCI_DMA_FROMDEVICE);
923                 if (pci_dma_mapping_error(pdev, dma_tmp))
924                         return -1;
925                 if (-1 == buffer_add(&(priv->rxbuffer), buf, dma_tmp,
926                            &(priv->rxbufferhead))) {
927                         DMESGE("Unable to allocate mem RX buf");
928                         return -1;
929                 }
930                 *tmp = 0; /* zero pads the header of the descriptor */
931                 *tmp = *tmp | (bufsize&0xfff);
932                 *(tmp+2) = (u32)dma_tmp;
933                 *tmp = *tmp | (1<<31); /* descriptor void, owned by the NIC */
934
935                 tmp = tmp+rx_desc_size;
936         }
937
938         *(tmp-rx_desc_size) = *(tmp-rx_desc_size) | (1<<30); /* this is the last descriptor */
939
940         return 0;
941 }
942
943
944 void set_nic_rxring(struct net_device *dev)
945 {
946         u8 pgreg;
947         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
948
949         pgreg = read_nic_byte(dev, PGSELECT);
950         write_nic_byte(dev, PGSELECT, pgreg & ~(1<<PGSELECT_PG_SHIFT));
951
952         write_nic_dword(dev, RXRING_ADDR, priv->rxringdma);
953 }
954
955 void rtl8180_reset(struct net_device *dev)
956 {
957         u8 cr;
958
959         rtl8180_irq_disable(dev);
960
961         cr = read_nic_byte(dev, CMD);
962         cr = cr & 2;
963         cr = cr | (1<<CMD_RST_SHIFT);
964         write_nic_byte(dev, CMD, cr);
965
966         force_pci_posting(dev);
967
968         mdelay(200);
969
970         if (read_nic_byte(dev, CMD) & (1<<CMD_RST_SHIFT))
971                 DMESGW("Card reset timeout!");
972         else
973                 DMESG("Card successfully reset");
974
975         rtl8180_set_mode(dev, EPROM_CMD_LOAD);
976         force_pci_posting(dev);
977         mdelay(200);
978 }
979
980 inline u16 ieeerate2rtlrate(int rate)
981 {
982         switch (rate) {
983         case 10:
984                 return 0;
985         case 20:
986                 return 1;
987         case 55:
988                 return 2;
989         case 110:
990                 return 3;
991         case 60:
992                 return 4;
993         case 90:
994                 return 5;
995         case 120:
996                 return 6;
997         case 180:
998                 return 7;
999         case 240:
1000                 return 8;
1001         case 360:
1002                 return 9;
1003         case 480:
1004                 return 10;
1005         case 540:
1006                 return 11;
1007         default:
1008                 return 3;
1009         }
1010 }
1011
1012 static u16 rtl_rate[] = {10, 20, 55, 110, 60, 90, 120, 180, 240, 360, 480, 540, 720};
1013
1014 inline u16 rtl8180_rate2rate(short rate)
1015 {
1016         if (rate > 12)
1017                 return 10;
1018         return rtl_rate[rate];
1019 }
1020
1021 inline u8 rtl8180_IsWirelessBMode(u16 rate)
1022 {
1023         if (((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220))
1024                 return 1;
1025         else
1026                 return 0;
1027 }
1028
1029 u16 N_DBPSOfRate(u16 DataRate);
1030
1031 static u16 ComputeTxTime(u16 FrameLength, u16 DataRate, u8 bManagementFrame,
1032                   u8 bShortPreamble)
1033 {
1034         u16     FrameTime;
1035         u16     N_DBPS;
1036         u16     Ceiling;
1037
1038         if (rtl8180_IsWirelessBMode(DataRate)) {
1039                 if (bManagementFrame || !bShortPreamble || DataRate == 10)
1040                         /* long preamble */
1041                         FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
1042                 else
1043                         /* short preamble */
1044                         FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
1045
1046                 if ((FrameLength*8 % (DataRate/10)) != 0) /* get the ceilling */
1047                         FrameTime++;
1048         } else {        /* 802.11g DSSS-OFDM PLCP length field calculation. */
1049                 N_DBPS = N_DBPSOfRate(DataRate);
1050                 Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
1051                                 + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
1052                 FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
1053         }
1054         return FrameTime;
1055 }
1056
1057 u16 N_DBPSOfRate(u16 DataRate)
1058 {
1059          u16 N_DBPS = 24;
1060
1061         switch (DataRate) {
1062         case 60:
1063                 N_DBPS = 24;
1064                 break;
1065         case 90:
1066                 N_DBPS = 36;
1067                 break;
1068         case 120:
1069                 N_DBPS = 48;
1070                 break;
1071         case 180:
1072                 N_DBPS = 72;
1073                 break;
1074         case 240:
1075                 N_DBPS = 96;
1076                 break;
1077         case 360:
1078                 N_DBPS = 144;
1079                 break;
1080         case 480:
1081                 N_DBPS = 192;
1082                 break;
1083         case 540:
1084                 N_DBPS = 216;
1085                 break;
1086         default:
1087                 break;
1088         }
1089
1090         return N_DBPS;
1091 }
1092
1093 /*
1094  * For Netgear case, they want good-looking signal strength.
1095  */
1096 static long NetgearSignalStrengthTranslate(long LastSS, long CurrSS)
1097 {
1098         long RetSS;
1099
1100         /* Step 1. Scale mapping. */
1101         if (CurrSS >= 71 && CurrSS <= 100)
1102                 RetSS = 90 + ((CurrSS - 70) / 3);
1103         else if (CurrSS >= 41 && CurrSS <= 70)
1104                 RetSS = 78 + ((CurrSS - 40) / 3);
1105         else if (CurrSS >= 31 && CurrSS <= 40)
1106                 RetSS = 66 + (CurrSS - 30);
1107         else if (CurrSS >= 21 && CurrSS <= 30)
1108                 RetSS = 54 + (CurrSS - 20);
1109         else if (CurrSS >= 5 && CurrSS <= 20)
1110                 RetSS = 42 + (((CurrSS - 5) * 2) / 3);
1111         else if (CurrSS == 4)
1112                 RetSS = 36;
1113         else if (CurrSS == 3)
1114                 RetSS = 27;
1115         else if (CurrSS == 2)
1116                 RetSS = 18;
1117         else if (CurrSS == 1)
1118                 RetSS = 9;
1119         else
1120                 RetSS = CurrSS;
1121
1122         /* Step 2. Smoothing. */
1123         if (LastSS > 0)
1124                 RetSS = ((LastSS * 5) + (RetSS) + 5) / 6;
1125
1126         return RetSS;
1127 }
1128
1129 /*
1130  * Translate 0-100 signal strength index into dBm.
1131  */
1132 static long TranslateToDbm8185(u8 SignalStrengthIndex)
1133 {
1134         long SignalPower;
1135
1136         /* Translate to dBm (x=0.5y-95). */
1137         SignalPower = (long)((SignalStrengthIndex + 1) >> 1);
1138         SignalPower -= 95;
1139
1140         return SignalPower;
1141 }
1142
1143 /*
1144  * Perform signal smoothing for dynamic mechanism.
1145  * This is different with PerformSignalSmoothing8185 in smoothing formula.
1146  * No dramatic adjustion is apply because dynamic mechanism need some degree
1147  * of correctness. Ported from 8187B.
1148  */
1149 static void PerformUndecoratedSignalSmoothing8185(struct r8180_priv *priv,
1150                                                   bool bCckRate)
1151 {
1152         /* Determin the current packet is CCK rate. */
1153         priv->bCurCCKPkt = bCckRate;
1154
1155         if (priv->UndecoratedSmoothedSS >= 0)
1156                 priv->UndecoratedSmoothedSS = ((priv->UndecoratedSmoothedSS * 5) +
1157                                                (priv->SignalStrength * 10)) / 6;
1158         else
1159                 priv->UndecoratedSmoothedSS = priv->SignalStrength * 10;
1160
1161         priv->UndercorateSmoothedRxPower = ((priv->UndercorateSmoothedRxPower * 50) +
1162                                             (priv->RxPower * 11)) / 60;
1163
1164         if (bCckRate)
1165                 priv->CurCCKRSSI = priv->RSSI;
1166         else
1167                 priv->CurCCKRSSI = 0;
1168 }
1169
1170
1171 /*
1172  * This is rough RX isr handling routine
1173  */
1174 static void rtl8180_rx(struct net_device *dev)
1175 {
1176         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1177         struct sk_buff *tmp_skb;
1178         short first, last;
1179         u32 len;
1180         int lastlen;
1181         unsigned char quality, signal;
1182         u8 rate;
1183         u32 *tmp, *tmp2;
1184         u8 rx_desc_size;
1185         u8 padding;
1186         char rxpower = 0;
1187         u32 RXAGC = 0;
1188         long RxAGC_dBm = 0;
1189         u8      LNA = 0, BB = 0;
1190         u8      LNA_gain[4] = {02, 17, 29, 39};
1191         u8  Antenna = 0;
1192         struct ieee80211_hdr_4addr *hdr;
1193         u16 fc, type;
1194         u8 bHwError = 0, bCRC = 0, bICV = 0;
1195         bool    bCckRate = false;
1196         u8     RSSI = 0;
1197         long    SignalStrengthIndex = 0;
1198         struct ieee80211_rx_stats stats = {
1199                 .signal = 0,
1200                 .noise = -98,
1201                 .rate = 0,
1202                 .freq = IEEE80211_24GHZ_BAND,
1203         };
1204
1205         stats.nic_type = NIC_8185B;
1206         rx_desc_size = 8;
1207
1208         if ((*(priv->rxringtail)) & (1<<31)) {
1209                 /* we have got an RX int, but the descriptor
1210                  * we are pointing is empty */
1211
1212                 priv->stats.rxnodata++;
1213                 priv->ieee80211->stats.rx_errors++;
1214
1215                 tmp2 = NULL;
1216                 tmp = priv->rxringtail;
1217                 do {
1218                         if (tmp == priv->rxring)
1219                                 tmp  = priv->rxring + (priv->rxringcount - 1)*rx_desc_size;
1220                         else
1221                                 tmp -= rx_desc_size;
1222
1223                         if (!(*tmp & (1<<31)))
1224                                 tmp2 = tmp;
1225                 } while (tmp != priv->rxring);
1226
1227                 if (tmp2)
1228                         priv->rxringtail = tmp2;
1229         }
1230
1231         /* while there are filled descriptors */
1232         while (!(*(priv->rxringtail) & (1<<31))) {
1233                 if (*(priv->rxringtail) & (1<<26))
1234                         DMESGW("RX buffer overflow");
1235                 if (*(priv->rxringtail) & (1<<12))
1236                         priv->stats.rxicverr++;
1237
1238                 if (*(priv->rxringtail) & (1<<27)) {
1239                         priv->stats.rxdmafail++;
1240                         /* DMESG("EE: RX DMA FAILED at buffer pointed by descriptor %x",(u32)priv->rxringtail); */
1241                         goto drop;
1242                 }
1243
1244                 pci_dma_sync_single_for_cpu(priv->pdev,
1245                                     priv->rxbuffer->dma,
1246                                     priv->rxbuffersize * sizeof(u8),
1247                                     PCI_DMA_FROMDEVICE);
1248
1249                 first = *(priv->rxringtail) & (1<<29) ? 1 : 0;
1250                 if (first)
1251                         priv->rx_prevlen = 0;
1252
1253                 last = *(priv->rxringtail) & (1<<28) ? 1 : 0;
1254                 if (last) {
1255                         lastlen = ((*priv->rxringtail) & 0xfff);
1256
1257                         /* if the last descriptor (that should
1258                          * tell us the total packet len) tell
1259                          * us something less than the descriptors
1260                          * len we had until now, then there is some
1261                          * problem..
1262                          * workaround to prevent kernel panic
1263                          */
1264                         if (lastlen < priv->rx_prevlen)
1265                                 len = 0;
1266                         else
1267                                 len = lastlen-priv->rx_prevlen;
1268
1269                         if (*(priv->rxringtail) & (1<<13)) {
1270                                 if ((*(priv->rxringtail) & 0xfff) < 500)
1271                                         priv->stats.rxcrcerrmin++;
1272                                 else if ((*(priv->rxringtail) & 0x0fff) > 1000)
1273                                         priv->stats.rxcrcerrmax++;
1274                                 else
1275                                         priv->stats.rxcrcerrmid++;
1276
1277                         }
1278
1279                 } else {
1280                         len = priv->rxbuffersize;
1281                 }
1282
1283                 if (first && last) {
1284                         padding = ((*(priv->rxringtail+3))&(0x04000000))>>26;
1285                 } else if (first) {
1286                         padding = ((*(priv->rxringtail+3))&(0x04000000))>>26;
1287                         if (padding)
1288                                 len -= 2;
1289                 } else {
1290                         padding = 0;
1291                 }
1292                 padding = 0;
1293                 priv->rx_prevlen += len;
1294
1295                 if (priv->rx_prevlen > MAX_FRAG_THRESHOLD + 100) {
1296                         /* HW is probably passing several buggy frames
1297                         * without FD or LD flag set.
1298                         * Throw this garbage away to prevent skb
1299                         * memory exhausting
1300                         */
1301                         if (!priv->rx_skb_complete)
1302                                 dev_kfree_skb_any(priv->rx_skb);
1303                         priv->rx_skb_complete = 1;
1304                 }
1305
1306                 signal = (unsigned char)(((*(priv->rxringtail+3)) & (0x00ff0000))>>16);
1307                 signal = (signal & 0xfe) >> 1;
1308
1309                 quality = (unsigned char)((*(priv->rxringtail+3)) & (0xff));
1310
1311                 stats.mac_time[0] = *(priv->rxringtail+1);
1312                 stats.mac_time[1] = *(priv->rxringtail+2);
1313                 rxpower = ((char)(((*(priv->rxringtail+4)) & (0x00ff0000))>>16))/2 - 42;
1314                 RSSI = ((u8)(((*(priv->rxringtail+3)) & (0x0000ff00))>>8)) & (0x7f);
1315
1316                 rate = ((*(priv->rxringtail)) &
1317                         ((1<<23)|(1<<22)|(1<<21)|(1<<20)))>>20;
1318
1319                 stats.rate = rtl8180_rate2rate(rate);
1320                 Antenna = (((*(priv->rxringtail+3)) & (0x00008000)) == 0) ? 0 : 1;
1321                 if (!rtl8180_IsWirelessBMode(stats.rate)) { /* OFDM rate. */
1322                         RxAGC_dBm = rxpower+1;  /* bias */
1323                 } else { /* CCK rate. */
1324                         RxAGC_dBm = signal; /* bit 0 discard */
1325
1326                         LNA = (u8) (RxAGC_dBm & 0x60) >> 5; /* bit 6~ bit 5 */
1327                         BB  = (u8) (RxAGC_dBm & 0x1F); /* bit 4 ~ bit 0 */
1328
1329                         RxAGC_dBm = -(LNA_gain[LNA] + (BB*2)); /* Pin_11b=-(LNA_gain+BB_gain) (dBm) */
1330
1331                         RxAGC_dBm += 4; /* bias */
1332                 }
1333
1334                 if (RxAGC_dBm & 0x80) /* absolute value */
1335                         RXAGC = ~(RxAGC_dBm)+1;
1336                 bCckRate = rtl8180_IsWirelessBMode(stats.rate);
1337                 /* Translate RXAGC into 1-100. */
1338                 if (!rtl8180_IsWirelessBMode(stats.rate)) { /* OFDM rate. */
1339                         if (RXAGC > 90)
1340                                 RXAGC = 90;
1341                         else if (RXAGC < 25)
1342                                 RXAGC = 25;
1343                         RXAGC = (90-RXAGC)*100/65;
1344                 } else { /* CCK rate. */
1345                         if (RXAGC > 95)
1346                                 RXAGC = 95;
1347                         else if (RXAGC < 30)
1348                                 RXAGC = 30;
1349                         RXAGC = (95-RXAGC)*100/65;
1350                 }
1351                 priv->SignalStrength = (u8)RXAGC;
1352                 priv->RecvSignalPower = RxAGC_dBm;
1353                 priv->RxPower = rxpower;
1354                 priv->RSSI = RSSI;
1355                 /* SQ translation formula is provided by SD3 DZ. 2006.06.27 */
1356                 if (quality >= 127)
1357                         quality = 1; /*0; */ /* 0 will cause epc to show signal zero , walk around now; */
1358                 else if (quality < 27)
1359                         quality = 100;
1360                 else
1361                         quality = 127 - quality;
1362                 priv->SignalQuality = quality;
1363
1364                 stats.signal = (u8)quality; /*priv->wstats.qual.level = priv->SignalStrength; */
1365                 stats.signalstrength = RXAGC;
1366                 if (stats.signalstrength > 100)
1367                         stats.signalstrength = 100;
1368                 stats.signalstrength = (stats.signalstrength * 70)/100 + 30;
1369                 /* printk("==========================>rx : RXAGC is %d,signalstrength is %d\n",RXAGC,stats.signalstrength); */
1370                 stats.rssi = priv->wstats.qual.qual = priv->SignalQuality;
1371                 stats.noise = priv->wstats.qual.noise = 100 - priv->wstats.qual.qual;
1372                 bHwError = (((*(priv->rxringtail)) & (0x00000fff)) == 4080) |
1373                            (((*(priv->rxringtail)) & (0x04000000)) != 0) |
1374                            (((*(priv->rxringtail)) & (0x08000000)) != 0) |
1375                            (((~(*(priv->rxringtail))) & (0x10000000)) != 0) |
1376                            (((~(*(priv->rxringtail))) & (0x20000000)) != 0);
1377                 bCRC = ((*(priv->rxringtail)) & (0x00002000)) >> 13;
1378                 bICV = ((*(priv->rxringtail)) & (0x00001000)) >> 12;
1379                 hdr = (struct ieee80211_hdr_4addr *)priv->rxbuffer->buf;
1380                     fc = le16_to_cpu(hdr->frame_ctl);
1381                 type = WLAN_FC_GET_TYPE(fc);
1382
1383                 if (IEEE80211_FTYPE_CTL != type &&
1384                     !bHwError && !bCRC && !bICV &&
1385                     eqMacAddr(priv->ieee80211->current_network.bssid,
1386                         fc & IEEE80211_FCTL_TODS ? hdr->addr1 :
1387                         fc & IEEE80211_FCTL_FROMDS ? hdr->addr2 :
1388                         hdr->addr3)) {
1389
1390                         /* Perform signal smoothing for dynamic
1391                          * mechanism on demand. This is different
1392                          * with PerformSignalSmoothing8185 in smoothing
1393                          * fomula. No dramatic adjustion is apply
1394                          * because dynamic mechanism need some degree
1395                          * of correctness. */
1396                         PerformUndecoratedSignalSmoothing8185(priv, bCckRate);
1397
1398                         /* For good-looking singal strength. */
1399                         SignalStrengthIndex = NetgearSignalStrengthTranslate(
1400                                                         priv->LastSignalStrengthInPercent,
1401                                                         priv->SignalStrength);
1402
1403                         priv->LastSignalStrengthInPercent = SignalStrengthIndex;
1404                         priv->Stats_SignalStrength = TranslateToDbm8185((u8)SignalStrengthIndex);
1405                 /*
1406                  * We need more correct power of received packets and the  "SignalStrength" of RxStats is beautified,
1407                  * so we record the correct power here.
1408                  */
1409                         priv->Stats_SignalQuality = (long)(priv->Stats_SignalQuality * 5 + (long)priv->SignalQuality + 5) / 6;
1410                         priv->Stats_RecvSignalPower = (long)(priv->Stats_RecvSignalPower * 5 + priv->RecvSignalPower - 1) / 6;
1411
1412                 /* Figure out which antenna that received the last packet. */
1413                         priv->LastRxPktAntenna = Antenna ? 1 : 0; /* 0: aux, 1: main. */
1414                         SwAntennaDiversityRxOk8185(dev, priv->SignalStrength);
1415                 }
1416
1417                 if (first) {
1418                         if (!priv->rx_skb_complete) {
1419                                 /* seems that HW sometimes fails to receive and
1420                                    doesn't provide the last descriptor */
1421                                 dev_kfree_skb_any(priv->rx_skb);
1422                                 priv->stats.rxnolast++;
1423                         }
1424                         priv->rx_skb = dev_alloc_skb(len+2);
1425                         if (!priv->rx_skb)
1426                                 goto drop;
1427
1428                         priv->rx_skb_complete = 0;
1429                         priv->rx_skb->dev = dev;
1430                 } else {
1431                         /* if we are here we should have already RXed
1432                         * the first frame.
1433                         * If we get here and the skb is not allocated then
1434                         * we have just throw out garbage (skb not allocated)
1435                         * and we are still rxing garbage....
1436                         */
1437                         if (!priv->rx_skb_complete) {
1438
1439                                 tmp_skb = dev_alloc_skb(priv->rx_skb->len+len+2);
1440
1441                                 if (!tmp_skb)
1442                                         goto drop;
1443
1444                                 tmp_skb->dev = dev;
1445
1446                                 memcpy(skb_put(tmp_skb, priv->rx_skb->len),
1447                                         priv->rx_skb->data,
1448                                         priv->rx_skb->len);
1449
1450                                 dev_kfree_skb_any(priv->rx_skb);
1451
1452                                 priv->rx_skb = tmp_skb;
1453                         }
1454                 }
1455
1456                 if (!priv->rx_skb_complete) {
1457                         if (padding) {
1458                                 memcpy(skb_put(priv->rx_skb, len),
1459                                         (((unsigned char *)priv->rxbuffer->buf) + 2), len);
1460                         } else {
1461                                 memcpy(skb_put(priv->rx_skb, len),
1462                                         priv->rxbuffer->buf, len);
1463                         }
1464                 }
1465
1466                 if (last && !priv->rx_skb_complete) {
1467                         if (priv->rx_skb->len > 4)
1468                                 skb_trim(priv->rx_skb, priv->rx_skb->len-4);
1469                         if (!ieee80211_rtl_rx(priv->ieee80211,
1470                                          priv->rx_skb, &stats))
1471                                 dev_kfree_skb_any(priv->rx_skb);
1472                         priv->rx_skb_complete = 1;
1473                 }
1474
1475                 pci_dma_sync_single_for_device(priv->pdev,
1476                                     priv->rxbuffer->dma,
1477                                     priv->rxbuffersize * sizeof(u8),
1478                                     PCI_DMA_FROMDEVICE);
1479
1480 drop: /* this is used when we have not enough mem */
1481                 /* restore the descriptor */
1482                 *(priv->rxringtail+2) = priv->rxbuffer->dma;
1483                 *(priv->rxringtail) = *(priv->rxringtail) & ~0xfff;
1484                 *(priv->rxringtail) =
1485                         *(priv->rxringtail) | priv->rxbuffersize;
1486
1487                 *(priv->rxringtail) =
1488                         *(priv->rxringtail) | (1<<31);
1489
1490                 priv->rxringtail += rx_desc_size;
1491                 if (priv->rxringtail >=
1492                    (priv->rxring)+(priv->rxringcount)*rx_desc_size)
1493                         priv->rxringtail = priv->rxring;
1494
1495                 priv->rxbuffer = (priv->rxbuffer->next);
1496         }
1497 }
1498
1499
1500 static void rtl8180_dma_kick(struct net_device *dev, int priority)
1501 {
1502         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1503
1504         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
1505         write_nic_byte(dev, TX_DMA_POLLING,
1506                         (1 << (priority + 1)) | priv->dma_poll_mask);
1507         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
1508
1509         force_pci_posting(dev);
1510 }
1511
1512 static void rtl8180_data_hard_stop(struct net_device *dev)
1513 {
1514         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1515
1516         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
1517         priv->dma_poll_stop_mask |= TPPOLLSTOP_AC_VIQ;
1518         write_nic_byte(dev, TPPollStop, priv->dma_poll_stop_mask);
1519         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
1520 }
1521
1522 static void rtl8180_data_hard_resume(struct net_device *dev)
1523 {
1524         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1525
1526         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
1527         priv->dma_poll_stop_mask &= ~(TPPOLLSTOP_AC_VIQ);
1528         write_nic_byte(dev, TPPollStop, priv->dma_poll_stop_mask);
1529         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
1530 }
1531
1532 /*
1533  * This function TX data frames when the ieee80211 stack requires this.
1534  * It checks also if we need to stop the ieee tx queue, eventually do it
1535  */
1536 static void rtl8180_hard_data_xmit(struct sk_buff *skb, struct net_device *dev,
1537                                    int rate)
1538 {
1539         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1540         int mode;
1541         struct ieee80211_hdr_3addr *h = (struct ieee80211_hdr_3addr *) skb->data;
1542         short morefrag = (h->frame_control) & IEEE80211_FCTL_MOREFRAGS;
1543         unsigned long flags;
1544         int priority;
1545
1546         mode = priv->ieee80211->iw_mode;
1547
1548         rate = ieeerate2rtlrate(rate);
1549         /*
1550          * This function doesn't require lock because we make
1551          * sure it's called with the tx_lock already acquired.
1552          * this come from the kernel's hard_xmit callback (through
1553          * the ieee stack, or from the try_wake_queue (again through
1554          * the ieee stack.
1555          */
1556         priority = AC2Q(skb->priority);
1557         spin_lock_irqsave(&priv->tx_lock, flags);
1558
1559         if (priv->ieee80211->bHwRadioOff) {
1560                 spin_unlock_irqrestore(&priv->tx_lock, flags);
1561
1562                 return;
1563         }
1564
1565         if (!check_nic_enought_desc(dev, priority)) {
1566                 DMESGW("Error: no descriptor left by previous TX (avail %d) ",
1567                         get_curr_tx_free_desc(dev, priority));
1568                 ieee80211_rtl_stop_queue(priv->ieee80211);
1569         }
1570         rtl8180_tx(dev, skb->data, skb->len, priority, morefrag, 0, rate);
1571         if (!check_nic_enought_desc(dev, priority))
1572                 ieee80211_rtl_stop_queue(priv->ieee80211);
1573
1574         spin_unlock_irqrestore(&priv->tx_lock, flags);
1575 }
1576
1577 /*
1578  * This is a rough attempt to TX a frame
1579  * This is called by the ieee 80211 stack to TX management frames.
1580  * If the ring is full packets are dropped (for data frame the queue
1581  * is stopped before this can happen). For this reason it is better
1582  * if the descriptors are larger than the largest management frame
1583  * we intend to TX: i'm unsure what the HW does if it will not find
1584  * the last fragment of a frame because it has been dropped...
1585  * Since queues for Management and Data frames are different we
1586  * might use a different lock than tx_lock (for example mgmt_tx_lock)
1587  */
1588 /* these function may loop if invoked with 0 descriptors or 0 len buffer */
1589 static int rtl8180_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
1590 {
1591         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1592         unsigned long flags;
1593         int priority;
1594
1595         priority = MANAGE_PRIORITY;
1596
1597         spin_lock_irqsave(&priv->tx_lock, flags);
1598
1599         if (priv->ieee80211->bHwRadioOff) {
1600                 spin_unlock_irqrestore(&priv->tx_lock, flags);
1601                 dev_kfree_skb_any(skb);
1602                 return NETDEV_TX_OK;
1603         }
1604
1605         rtl8180_tx(dev, skb->data, skb->len, priority,
1606                 0, 0, ieeerate2rtlrate(priv->ieee80211->basic_rate));
1607
1608         priv->ieee80211->stats.tx_bytes += skb->len;
1609         priv->ieee80211->stats.tx_packets++;
1610         spin_unlock_irqrestore(&priv->tx_lock, flags);
1611
1612         dev_kfree_skb_any(skb);
1613         return NETDEV_TX_OK;
1614 }
1615
1616 /* longpre 144+48 shortpre 72+24 */
1617 u16 rtl8180_len2duration(u32 len, short rate, short *ext)
1618 {
1619         u16 duration;
1620         u16 drift;
1621         *ext = 0;
1622
1623         switch (rate) {
1624         case 0: /* 1mbps */
1625                 *ext = 0;
1626                 duration = ((len+4)<<4) / 0x2;
1627                 drift = ((len+4)<<4) % 0x2;
1628                 if (drift == 0)
1629                         break;
1630                 duration++;
1631                 break;
1632         case 1: /* 2mbps */
1633                 *ext = 0;
1634                 duration = ((len+4)<<4) / 0x4;
1635                 drift = ((len+4)<<4) % 0x4;
1636                 if (drift == 0)
1637                         break;
1638                 duration++;
1639                 break;
1640         case 2: /* 5.5mbps */
1641                 *ext = 0;
1642                 duration = ((len+4)<<4) / 0xb;
1643                 drift = ((len+4)<<4) % 0xb;
1644                 if (drift == 0)
1645                         break;
1646                 duration++;
1647                 break;
1648         default:
1649         case 3: /* 11mbps */
1650                 *ext = 0;
1651                 duration = ((len+4)<<4) / 0x16;
1652                 drift = ((len+4)<<4) % 0x16;
1653                 if (drift == 0)
1654                         break;
1655                 duration++;
1656                 if (drift > 6)
1657                         break;
1658                 *ext = 1;
1659                 break;
1660         }
1661
1662         return duration;
1663 }
1664
1665 static void rtl8180_prepare_beacon(struct net_device *dev)
1666 {
1667         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1668         struct sk_buff *skb;
1669
1670         u16 word  = read_nic_word(dev, BcnItv);
1671         word &= ~BcnItv_BcnItv; /* clear Bcn_Itv */
1672         word |= cpu_to_le16(priv->ieee80211->current_network.beacon_interval); /* 0x64; */
1673         write_nic_word(dev, BcnItv, word);
1674
1675         skb = ieee80211_get_beacon(priv->ieee80211);
1676         if (skb) {
1677                 rtl8180_tx(dev, skb->data, skb->len, BEACON_PRIORITY,
1678                         0, 0, ieeerate2rtlrate(priv->ieee80211->basic_rate));
1679                 dev_kfree_skb_any(skb);
1680         }
1681 }
1682
1683 /*
1684  * This function do the real dirty work: it enqueues a TX command
1685  * descriptor in the ring buffer, copyes the frame in a TX buffer
1686  * and kicks the NIC to ensure it does the DMA transfer.
1687  */
1688 short rtl8180_tx(struct net_device *dev, u8 *txbuf, int len, int priority,
1689                  short morefrag, short descfrag, int rate)
1690 {
1691         struct r8180_priv *priv = ieee80211_priv(dev);
1692         u32 *tail, *temp_tail;
1693         u32 *begin;
1694         u32 *buf;
1695         int i;
1696         int remain;
1697         int buflen;
1698         int count;
1699         struct buffer *buflist;
1700         struct ieee80211_hdr_3addr *frag_hdr = (struct ieee80211_hdr_3addr *)txbuf;
1701         u8 dest[ETH_ALEN];
1702         u8                      bUseShortPreamble = 0;
1703         u8                      bCTSEnable = 0;
1704         u8                      bRTSEnable = 0;
1705         u16                     Duration = 0;
1706         u16                     RtsDur = 0;
1707         u16                     ThisFrameTime = 0;
1708         u16                     TxDescDuration = 0;
1709         bool                    ownbit_flag = false;
1710
1711         switch (priority) {
1712         case MANAGE_PRIORITY:
1713                 tail = priv->txmapringtail;
1714                 begin = priv->txmapring;
1715                 buflist = priv->txmapbufstail;
1716                 count = priv->txringcount;
1717                 break;
1718         case BK_PRIORITY:
1719                 tail = priv->txbkpringtail;
1720                 begin = priv->txbkpring;
1721                 buflist = priv->txbkpbufstail;
1722                 count = priv->txringcount;
1723                 break;
1724         case BE_PRIORITY:
1725                 tail = priv->txbepringtail;
1726                 begin = priv->txbepring;
1727                 buflist = priv->txbepbufstail;
1728                 count = priv->txringcount;
1729                 break;
1730         case VI_PRIORITY:
1731                 tail = priv->txvipringtail;
1732                 begin = priv->txvipring;
1733                 buflist = priv->txvipbufstail;
1734                 count = priv->txringcount;
1735                 break;
1736         case VO_PRIORITY:
1737                 tail = priv->txvopringtail;
1738                 begin = priv->txvopring;
1739                 buflist = priv->txvopbufstail;
1740                 count = priv->txringcount;
1741                 break;
1742         case HI_PRIORITY:
1743                 tail = priv->txhpringtail;
1744                 begin = priv->txhpring;
1745                 buflist = priv->txhpbufstail;
1746                 count = priv->txringcount;
1747                 break;
1748         case BEACON_PRIORITY:
1749                 tail = priv->txbeaconringtail;
1750                 begin = priv->txbeaconring;
1751                 buflist = priv->txbeaconbufstail;
1752                 count = priv->txbeaconcount;
1753                 break;
1754         default:
1755                 return -1;
1756                 break;
1757         }
1758
1759                 memcpy(&dest, frag_hdr->addr1, ETH_ALEN);
1760                 if (is_multicast_ether_addr(dest)) {
1761                         Duration = 0;
1762                         RtsDur = 0;
1763                         bRTSEnable = 0;
1764                         bCTSEnable = 0;
1765
1766                         ThisFrameTime = ComputeTxTime(len + sCrcLng, rtl8180_rate2rate(rate),
1767                                                       0, bUseShortPreamble);
1768                         TxDescDuration = ThisFrameTime;
1769                 } else { /* Unicast packet */
1770                         u16 AckTime;
1771
1772                         /* YJ,add,080828,for Keep alive */
1773                         priv->NumTxUnicast++;
1774
1775                         /* Figure out ACK rate according to BSS basic rate
1776                          * and Tx rate. */
1777                         AckTime = ComputeTxTime(14, 10, 0, 0);  /* AckCTSLng = 14 use 1M bps send */
1778
1779                         if (((len + sCrcLng) > priv->rts) && priv->rts) { /* RTS/CTS. */
1780                                 u16 RtsTime, CtsTime;
1781                                 /* u16 CtsRate; */
1782                                 bRTSEnable = 1;
1783                                 bCTSEnable = 0;
1784
1785                                 /* Rate and time required for RTS. */
1786                                 RtsTime = ComputeTxTime(sAckCtsLng/8, priv->ieee80211->basic_rate, 0, 0);
1787                                 /* Rate and time required for CTS. */
1788                                 CtsTime = ComputeTxTime(14, 10, 0, 0);  /* AckCTSLng = 14 use 1M bps send */
1789
1790                                 /* Figure out time required to transmit this frame. */
1791                                 ThisFrameTime = ComputeTxTime(len + sCrcLng,
1792                                                 rtl8180_rate2rate(rate),
1793                                                 0,
1794                                                 bUseShortPreamble);
1795
1796                                 /* RTS-CTS-ThisFrame-ACK. */
1797                                 RtsDur = CtsTime + ThisFrameTime + AckTime + 3*aSifsTime;
1798
1799                                 TxDescDuration = RtsTime + RtsDur;
1800                         } else { /* Normal case. */
1801                                 bCTSEnable = 0;
1802                                 bRTSEnable = 0;
1803                                 RtsDur = 0;
1804
1805                                 ThisFrameTime = ComputeTxTime(len + sCrcLng, rtl8180_rate2rate(rate),
1806                                                               0, bUseShortPreamble);
1807                                 TxDescDuration = ThisFrameTime + aSifsTime + AckTime;
1808                         }
1809
1810                         if (!(frag_hdr->frame_control & IEEE80211_FCTL_MOREFRAGS)) {
1811                                 /* ThisFrame-ACK. */
1812                                 Duration = aSifsTime + AckTime;
1813                         } else { /* One or more fragments remained. */
1814                                 u16 NextFragTime;
1815                                 NextFragTime = ComputeTxTime(len + sCrcLng, /* pretend following packet length equal current packet */
1816                                                 rtl8180_rate2rate(rate),
1817                                                 0,
1818                                                 bUseShortPreamble);
1819
1820                                 /* ThisFrag-ACk-NextFrag-ACK. */
1821                                 Duration = NextFragTime + 3*aSifsTime + 2*AckTime;
1822                         }
1823
1824                 } /* End of Unicast packet */
1825
1826                 frag_hdr->duration_id = Duration;
1827
1828         buflen = priv->txbuffsize;
1829         remain = len;
1830         temp_tail = tail;
1831
1832         while (remain != 0) {
1833                 mb();
1834                 if (!buflist) {
1835                         DMESGE("TX buffer error, cannot TX frames. pri %d.", priority);
1836                         return -1;
1837                 }
1838                 buf = buflist->buf;
1839
1840                 if ((*tail & (1 << 31)) && (priority != BEACON_PRIORITY)) {
1841                         DMESGW("No more TX desc, returning %x of %x",
1842                                remain, len);
1843                         priv->stats.txrdu++;
1844                         return remain;
1845                 }
1846
1847                 *tail = 0; /* zeroes header */
1848                 *(tail+1) = 0;
1849                 *(tail+3) = 0;
1850                 *(tail+5) = 0;
1851                 *(tail+6) = 0;
1852                 *(tail+7) = 0;
1853
1854                 /* FIXME: this should be triggered by HW encryption parameters.*/
1855                 *tail |= (1<<15); /* no encrypt */
1856
1857                 if (remain == len && !descfrag) {
1858                         ownbit_flag = false;
1859                         *tail = *tail | (1<<29); /* fist segment of the packet */
1860                         *tail = *tail | (len);
1861                 } else {
1862                         ownbit_flag = true;
1863                 }
1864
1865                 for (i = 0; i < buflen && remain > 0; i++, remain--) {
1866                         ((u8 *)buf)[i] = txbuf[i]; /* copy data into descriptor pointed DMAble buffer */
1867                         if (remain == 4 && i+4 >= buflen)
1868                                 break;
1869                         /* ensure the last desc has at least 4 bytes payload */
1870
1871                 }
1872                 txbuf = txbuf + i;
1873                 *(tail+3) = *(tail+3) & ~0xfff;
1874                 *(tail+3) = *(tail+3) | i; /* buffer length */
1875                 /* Use short preamble or not */
1876                 if (priv->ieee80211->current_network.capability&WLAN_CAPABILITY_SHORT_PREAMBLE)
1877                         if (priv->plcp_preamble_mode == 1 && rate != 0) /*  short mode now, not long! */
1878                         ; /* *tail |= (1<<16); */                               /* enable short preamble mode. */
1879
1880                 if (bCTSEnable)
1881                         *tail |= (1<<18);
1882
1883                 if (bRTSEnable) { /* rts enable */
1884                         *tail |= ((ieeerate2rtlrate(priv->ieee80211->basic_rate))<<19); /* RTS RATE */
1885                         *tail |= (1<<23); /* rts enable */
1886                         *(tail+1) |= (RtsDur&0xffff); /* RTS Duration */
1887                 }
1888                 *(tail+3) |= ((TxDescDuration&0xffff)<<16); /* DURATION */
1889                 /* *(tail+3) |= (0xe6<<16); */
1890                 *(tail+5) |= (11<<8); /* (priv->retry_data<<8); */ /* retry lim; */
1891
1892                 *tail = *tail | ((rate&0xf) << 24);
1893
1894                 if (morefrag)
1895                         *tail = (*tail) | (1<<17); /* more fragment */
1896                 if (!remain)
1897                         *tail = (*tail) | (1<<28); /* last segment of frame */
1898
1899                 *(tail+5) = *(tail+5)|(2<<27);
1900                 *(tail+7) = *(tail+7)|(1<<4);
1901
1902                 wmb();
1903                 if (ownbit_flag)
1904                         *tail = *tail | (1<<31); /* descriptor ready to be txed */
1905
1906                 if ((tail - begin)/8 == count-1)
1907                         tail = begin;
1908                 else
1909                         tail = tail+8;
1910
1911                 buflist = buflist->next;
1912
1913                 mb();
1914
1915                 switch (priority) {
1916                 case MANAGE_PRIORITY:
1917                         priv->txmapringtail = tail;
1918                         priv->txmapbufstail = buflist;
1919                         break;
1920                 case BK_PRIORITY:
1921                         priv->txbkpringtail = tail;
1922                         priv->txbkpbufstail = buflist;
1923                         break;
1924                 case BE_PRIORITY:
1925                         priv->txbepringtail = tail;
1926                         priv->txbepbufstail = buflist;
1927                         break;
1928                 case VI_PRIORITY:
1929                         priv->txvipringtail = tail;
1930                         priv->txvipbufstail = buflist;
1931                         break;
1932                 case VO_PRIORITY:
1933                         priv->txvopringtail = tail;
1934                         priv->txvopbufstail = buflist;
1935                         break;
1936                 case HI_PRIORITY:
1937                         priv->txhpringtail = tail;
1938                         priv->txhpbufstail = buflist;
1939                         break;
1940                 case BEACON_PRIORITY:
1941                         /*
1942                          * The HW seems to be happy with the 1st
1943                          * descriptor filled and the 2nd empty...
1944                          * So always update descriptor 1 and never
1945                          * touch 2nd
1946                          */
1947                         break;
1948                 }
1949         }
1950         *temp_tail = *temp_tail | (1<<31); /* descriptor ready to be txed */
1951         rtl8180_dma_kick(dev, priority);
1952
1953         return 0;
1954 }
1955
1956 void rtl8180_irq_rx_tasklet(struct r8180_priv *priv);
1957
1958 static void rtl8180_link_change(struct net_device *dev)
1959 {
1960         struct r8180_priv *priv = ieee80211_priv(dev);
1961         u16 beacon_interval;
1962         struct ieee80211_network *net = &priv->ieee80211->current_network;
1963
1964         rtl8180_update_msr(dev);
1965
1966         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
1967
1968         write_nic_dword(dev, BSSID, ((u32 *)net->bssid)[0]);
1969         write_nic_word(dev, BSSID+4, ((u16 *)net->bssid)[2]);
1970
1971         beacon_interval  = read_nic_word(dev, BEACON_INTERVAL);
1972         beacon_interval &= ~BEACON_INTERVAL_MASK;
1973         beacon_interval |= net->beacon_interval;
1974         write_nic_word(dev, BEACON_INTERVAL, beacon_interval);
1975
1976         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
1977
1978         rtl8180_set_chan(dev, priv->chan);
1979 }
1980
1981 static void rtl8180_rq_tx_ack(struct net_device *dev)
1982 {
1983
1984         struct r8180_priv *priv = ieee80211_priv(dev);
1985
1986         write_nic_byte(dev, CONFIG4, read_nic_byte(dev, CONFIG4) | CONFIG4_PWRMGT);
1987         priv->ack_tx_to_ieee = 1;
1988 }
1989
1990 static short rtl8180_is_tx_queue_empty(struct net_device *dev)
1991 {
1992
1993         struct r8180_priv *priv = ieee80211_priv(dev);
1994         u32 *d;
1995
1996         for (d = priv->txmapring;
1997                 d < priv->txmapring + priv->txringcount; d += 8)
1998                         if (*d & (1<<31))
1999                                 return 0;
2000
2001         for (d = priv->txbkpring;
2002                 d < priv->txbkpring + priv->txringcount; d += 8)
2003                         if (*d & (1<<31))
2004                                 return 0;
2005
2006         for (d = priv->txbepring;
2007                 d < priv->txbepring + priv->txringcount; d += 8)
2008                         if (*d & (1<<31))
2009                                 return 0;
2010
2011         for (d = priv->txvipring;
2012                 d < priv->txvipring + priv->txringcount; d += 8)
2013                         if (*d & (1<<31))
2014                                 return 0;
2015
2016         for (d = priv->txvopring;
2017                 d < priv->txvopring + priv->txringcount; d += 8)
2018                         if (*d & (1<<31))
2019                                 return 0;
2020
2021         for (d = priv->txhpring;
2022                 d < priv->txhpring + priv->txringcount; d += 8)
2023                         if (*d & (1<<31))
2024                                 return 0;
2025         return 1;
2026 }
2027
2028 static void rtl8180_hw_wakeup(struct net_device *dev)
2029 {
2030         unsigned long flags;
2031         struct r8180_priv *priv = ieee80211_priv(dev);
2032
2033         spin_lock_irqsave(&priv->ps_lock, flags);
2034         write_nic_byte(dev, CONFIG4, read_nic_byte(dev, CONFIG4) & ~CONFIG4_PWRMGT);
2035         if (priv->rf_wakeup)
2036                 priv->rf_wakeup(dev);
2037         spin_unlock_irqrestore(&priv->ps_lock, flags);
2038 }
2039
2040 static void rtl8180_hw_sleep_down(struct net_device *dev)
2041 {
2042         unsigned long flags;
2043         struct r8180_priv *priv = ieee80211_priv(dev);
2044
2045         spin_lock_irqsave(&priv->ps_lock, flags);
2046         if (priv->rf_sleep)
2047                 priv->rf_sleep(dev);
2048         spin_unlock_irqrestore(&priv->ps_lock, flags);
2049 }
2050
2051 static void rtl8180_hw_sleep(struct net_device *dev, u32 th, u32 tl)
2052 {
2053         struct r8180_priv *priv = ieee80211_priv(dev);
2054         u32 rb = jiffies;
2055         unsigned long flags;
2056
2057         spin_lock_irqsave(&priv->ps_lock, flags);
2058
2059         /*
2060          * Writing HW register with 0 equals to disable
2061          * the timer, that is not really what we want
2062          */
2063         tl -= MSECS(4+16+7);
2064
2065         /*
2066          * If the interval in witch we are requested to sleep is too
2067          * short then give up and remain awake
2068          */
2069         if (((tl >= rb) && (tl-rb) <= MSECS(MIN_SLEEP_TIME))
2070                 || ((rb > tl) && (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
2071                 spin_unlock_irqrestore(&priv->ps_lock, flags);
2072                 printk("too short to sleep\n");
2073                 return;
2074         }
2075
2076         {
2077                 u32 tmp = (tl > rb) ? (tl-rb) : (rb-tl);
2078
2079                 priv->DozePeriodInPast2Sec += jiffies_to_msecs(tmp);
2080                 /* as tl may be less than rb */
2081                 queue_delayed_work(priv->ieee80211->wq, &priv->ieee80211->hw_wakeup_wq, tmp);
2082         }
2083         /*
2084          * If we suspect the TimerInt is gone beyond tl
2085          * while setting it, then give up
2086          */
2087
2088         if (((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME))) ||
2089                 ((tl < rb) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))) {
2090                 spin_unlock_irqrestore(&priv->ps_lock, flags);
2091                 return;
2092         }
2093
2094         queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_sleep_wq);
2095         spin_unlock_irqrestore(&priv->ps_lock, flags);
2096 }
2097
2098 static void rtl8180_wmm_param_update(struct work_struct *work)
2099 {
2100         struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, wmm_param_update_wq);
2101         struct net_device *dev = ieee->dev;
2102         u8 *ac_param = (u8 *)(ieee->current_network.wmm_param);
2103         u8 mode = ieee->current_network.mode;
2104         AC_CODING       eACI;
2105         AC_PARAM        AcParam;
2106         PAC_PARAM       pAcParam;
2107         u8 i;
2108
2109         if (!ieee->current_network.QoS_Enable) {
2110                 /* legacy ac_xx_param update */
2111                 AcParam.longData = 0;
2112                 AcParam.f.AciAifsn.f.AIFSN = 2; /* Follow 802.11 DIFS. */
2113                 AcParam.f.AciAifsn.f.ACM = 0;
2114                 AcParam.f.Ecw.f.ECWmin = 3; /* Follow 802.11 CWmin. */
2115                 AcParam.f.Ecw.f.ECWmax = 7; /* Follow 802.11 CWmax. */
2116                 AcParam.f.TXOPLimit = 0;
2117                 for (eACI = 0; eACI < AC_MAX; eACI++) {
2118                         AcParam.f.AciAifsn.f.ACI = (u8)eACI;
2119                         {
2120                                 u8              u1bAIFS;
2121                                 u32             u4bAcParam;
2122                                 pAcParam = (PAC_PARAM)(&AcParam);
2123                                 /* Retrieve parameters to update. */
2124                                 u1bAIFS = pAcParam->f.AciAifsn.f.AIFSN * (((mode&IEEE_G) == IEEE_G) ? 9 : 20) + aSifsTime;
2125                                 u4bAcParam = ((((u32)(pAcParam->f.TXOPLimit))<<AC_PARAM_TXOP_LIMIT_OFFSET)|
2126                                               (((u32)(pAcParam->f.Ecw.f.ECWmax))<<AC_PARAM_ECW_MAX_OFFSET)|
2127                                               (((u32)(pAcParam->f.Ecw.f.ECWmin))<<AC_PARAM_ECW_MIN_OFFSET)|
2128                                                (((u32)u1bAIFS) << AC_PARAM_AIFS_OFFSET));
2129                                 switch (eACI) {
2130                                 case AC1_BK:
2131                                         write_nic_dword(dev, AC_BK_PARAM, u4bAcParam);
2132                                         break;
2133                                 case AC0_BE:
2134                                         write_nic_dword(dev, AC_BE_PARAM, u4bAcParam);
2135                                         break;
2136                                 case AC2_VI:
2137                                         write_nic_dword(dev, AC_VI_PARAM, u4bAcParam);
2138                                         break;
2139                                 case AC3_VO:
2140                                         write_nic_dword(dev, AC_VO_PARAM, u4bAcParam);
2141                                         break;
2142                                 default:
2143                                         pr_warn("SetHwReg8185():invalid ACI: %d!\n",
2144                                                 eACI);
2145                                         break;
2146                                 }
2147                         }
2148                 }
2149                 return;
2150         }
2151
2152         for (i = 0; i < AC_MAX; i++) {
2153                 /* AcParam.longData = 0; */
2154                 pAcParam = (AC_PARAM *)ac_param;
2155                 {
2156                         AC_CODING       eACI;
2157                         u8              u1bAIFS;
2158                         u32             u4bAcParam;
2159
2160                         /* Retrieve parameters to update. */
2161                         eACI = pAcParam->f.AciAifsn.f.ACI;
2162                         /* Mode G/A: slotTimeTimer = 9; Mode B: 20 */
2163                         u1bAIFS = pAcParam->f.AciAifsn.f.AIFSN * (((mode&IEEE_G) == IEEE_G) ? 9 : 20) + aSifsTime;
2164                         u4bAcParam = ((((u32)(pAcParam->f.TXOPLimit)) << AC_PARAM_TXOP_LIMIT_OFFSET)    |
2165                                         (((u32)(pAcParam->f.Ecw.f.ECWmax)) << AC_PARAM_ECW_MAX_OFFSET)  |
2166                                         (((u32)(pAcParam->f.Ecw.f.ECWmin)) << AC_PARAM_ECW_MIN_OFFSET)  |
2167                                         (((u32)u1bAIFS) << AC_PARAM_AIFS_OFFSET));
2168
2169                         switch (eACI) {
2170                         case AC1_BK:
2171                                 write_nic_dword(dev, AC_BK_PARAM, u4bAcParam);
2172                                 break;
2173                         case AC0_BE:
2174                                 write_nic_dword(dev, AC_BE_PARAM, u4bAcParam);
2175                                 break;
2176                         case AC2_VI:
2177                                 write_nic_dword(dev, AC_VI_PARAM, u4bAcParam);
2178                                 break;
2179                         case AC3_VO:
2180                                 write_nic_dword(dev, AC_VO_PARAM, u4bAcParam);
2181                                 break;
2182                         default:
2183                                 pr_warn("SetHwReg8185(): invalid ACI: %d !\n",
2184                                         eACI);
2185                                 break;
2186                         }
2187                 }
2188                 ac_param += (sizeof(AC_PARAM));
2189         }
2190 }
2191
2192 void rtl8180_restart_wq(struct work_struct *work);
2193 /* void rtl8180_rq_tx_ack(struct work_struct *work); */
2194 void rtl8180_watch_dog_wq(struct work_struct *work);
2195 void rtl8180_hw_wakeup_wq(struct work_struct *work);
2196 void rtl8180_hw_sleep_wq(struct work_struct *work);
2197 void rtl8180_sw_antenna_wq(struct work_struct *work);
2198 void rtl8180_watch_dog(struct net_device *dev);
2199
2200 static void watch_dog_adaptive(unsigned long data)
2201 {
2202         struct r8180_priv *priv = ieee80211_priv((struct net_device *)data);
2203
2204         if (!priv->up) {
2205                 DMESG("<----watch_dog_adaptive():driver is not up!\n");
2206                 return;
2207         }
2208
2209         /* Tx High Power Mechanism. */
2210         if (CheckHighPower((struct net_device *)data))
2211                 queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->tx_pw_wq);
2212
2213         /* Tx Power Tracking on 87SE. */
2214         if (CheckTxPwrTracking((struct net_device *)data))
2215                 TxPwrTracking87SE((struct net_device *)data);
2216
2217         /* Perform DIG immediately. */
2218         if (CheckDig((struct net_device *)data))
2219                 queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_dig_wq);
2220         rtl8180_watch_dog((struct net_device *)data);
2221
2222         queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->GPIOChangeRFWorkItem);
2223
2224         priv->watch_dog_timer.expires = jiffies + MSECS(IEEE80211_WATCH_DOG_TIME);
2225         add_timer(&priv->watch_dog_timer);
2226 }
2227
2228 static CHANNEL_LIST ChannelPlan[] = {
2229         {{1,2,3,4,5,6,7,8,9,10,11,36,40,44,48,52,56,60,64},19},         /* FCC */
2230         {{1,2,3,4,5,6,7,8,9,10,11},11},                                 /* IC */
2231         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   /* ETSI */
2232         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   /* Spain. Change to ETSI. */
2233         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   /* France. Change to ETSI. */
2234         {{14,36,40,44,48,52,56,60,64},9},                               /* MKK */
2235         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14, 36,40,44,48,52,56,60,64},22},/* MKK1 */
2236         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   /* Israel. */
2237         {{1,2,3,4,5,6,7,8,9,10,11,12,13,34,38,42,46},17},               /* For 11a , TELEC */
2238         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14},14},  /* For Global Domain. 1-11:active scan, 12-14 passive scan. //+YJ, 080626 */
2239         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13} /* world wide 13: ch1~ch11 active scan, ch12~13 passive //lzm add 080826 */
2240 };
2241
2242 static void rtl8180_set_channel_map(u8 channel_plan,
2243                                     struct ieee80211_device *ieee)
2244 {
2245         int i;
2246
2247         /* lzm add 080826 */
2248         ieee->MinPassiveChnlNum = MAX_CHANNEL_NUMBER+1;
2249         ieee->IbssStartChnl = 0;
2250
2251         switch (channel_plan) {
2252         case COUNTRY_CODE_FCC:
2253         case COUNTRY_CODE_IC:
2254         case COUNTRY_CODE_ETSI:
2255         case COUNTRY_CODE_SPAIN:
2256         case COUNTRY_CODE_FRANCE:
2257         case COUNTRY_CODE_MKK:
2258         case COUNTRY_CODE_MKK1:
2259         case COUNTRY_CODE_ISRAEL:
2260         case COUNTRY_CODE_TELEC:
2261                 {
2262                         Dot11d_Init(ieee);
2263                         ieee->bGlobalDomain = false;
2264                         if (ChannelPlan[channel_plan].Len != 0) {
2265                                 /* Clear old channel map */
2266                                 memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
2267                                 /* Set new channel map */
2268                                 for (i = 0; i < ChannelPlan[channel_plan].Len; i++) {
2269                                         if (ChannelPlan[channel_plan].Channel[i] <= 14)
2270                                                 GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
2271                                 }
2272                         }
2273                         break;
2274                 }
2275         case COUNTRY_CODE_GLOBAL_DOMAIN:
2276                 {
2277                         GET_DOT11D_INFO(ieee)->bEnabled = false;
2278                         Dot11d_Reset(ieee);
2279                         ieee->bGlobalDomain = true;
2280                         break;
2281                 }
2282         case COUNTRY_CODE_WORLD_WIDE_13_INDEX:/* lzm add 080826 */
2283                 {
2284                         ieee->MinPassiveChnlNum = 12;
2285                         ieee->IbssStartChnl = 10;
2286                         break;
2287                 }
2288         default:
2289                 {
2290                         Dot11d_Init(ieee);
2291                         ieee->bGlobalDomain = false;
2292                         memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
2293                         for (i = 1; i <= 14; i++)
2294                                 GET_DOT11D_INFO(ieee)->channel_map[i] = 1;
2295                         break;
2296                 }
2297         }
2298 }
2299
2300 void GPIOChangeRFWorkItemCallBack(struct work_struct *work);
2301
2302 /* YJ,add,080828 */
2303 static void rtl8180_statistics_init(struct Stats *pstats)
2304 {
2305         memset(pstats, 0, sizeof(struct Stats));
2306 }
2307
2308 static void rtl8180_link_detect_init(plink_detect_t plink_detect)
2309 {
2310         memset(plink_detect, 0, sizeof(link_detect_t));
2311         plink_detect->SlotNum = DEFAULT_SLOT_NUM;
2312 }
2313
2314 /* YJ,add,080828,end */
2315 static void rtl8187se_eeprom_register_read(struct eeprom_93cx6 *eeprom)
2316 {
2317         struct net_device *dev = eeprom->data;
2318         u8 reg = read_nic_byte(dev, EPROM_CMD);
2319
2320         eeprom->reg_data_in = reg & RTL818X_EEPROM_CMD_WRITE;
2321         eeprom->reg_data_out = reg & RTL818X_EEPROM_CMD_READ;
2322         eeprom->reg_data_clock = reg & RTL818X_EEPROM_CMD_CK;
2323         eeprom->reg_chip_select = reg & RTL818X_EEPROM_CMD_CS;
2324 }
2325
2326 static void rtl8187se_eeprom_register_write(struct eeprom_93cx6 *eeprom)
2327 {
2328         struct net_device *dev = eeprom->data;
2329         u8 reg = 2 << 6;
2330
2331         if (eeprom->reg_data_in)
2332                 reg |= RTL818X_EEPROM_CMD_WRITE;
2333         if (eeprom->reg_data_out)
2334                 reg |= RTL818X_EEPROM_CMD_READ;
2335         if (eeprom->reg_data_clock)
2336                 reg |= RTL818X_EEPROM_CMD_CK;
2337         if (eeprom->reg_chip_select)
2338                 reg |= RTL818X_EEPROM_CMD_CS;
2339
2340         write_nic_byte(dev, EPROM_CMD, reg);
2341         read_nic_byte(dev, EPROM_CMD);
2342         udelay(10);
2343 }
2344
2345 static short rtl8180_init(struct net_device *dev)
2346 {
2347         struct r8180_priv *priv = ieee80211_priv(dev);
2348         u16 word;
2349         u16 usValue;
2350         u16 tmpu16;
2351         int i, j;
2352         struct eeprom_93cx6 eeprom;
2353         u16 eeprom_val;
2354
2355         eeprom.data = dev;
2356         eeprom.register_read = rtl8187se_eeprom_register_read;
2357         eeprom.register_write = rtl8187se_eeprom_register_write;
2358         eeprom.width = PCI_EEPROM_WIDTH_93C46;
2359
2360         eeprom_93cx6_read(&eeprom, EEPROM_COUNTRY_CODE>>1, &eeprom_val);
2361         priv->channel_plan = eeprom_val & 0xFF;
2362         if (priv->channel_plan > COUNTRY_CODE_GLOBAL_DOMAIN) {
2363                 printk("rtl8180_init:Error channel plan! Set to default.\n");
2364                 priv->channel_plan = 0;
2365         }
2366
2367         DMESG("Channel plan is %d\n", priv->channel_plan);
2368         rtl8180_set_channel_map(priv->channel_plan, priv->ieee80211);
2369
2370         /* FIXME: these constants are placed in a bad pleace. */
2371         priv->txbuffsize = 2048;        /* 1024; */
2372         priv->txringcount = 32;         /* 32; */
2373         priv->rxbuffersize = 2048;      /* 1024; */
2374         priv->rxringcount = 64;         /* 32; */
2375         priv->txbeaconcount = 2;
2376         priv->rx_skb_complete = 1;
2377
2378         priv->RFChangeInProgress = false;
2379         priv->SetRFPowerStateInProgress = false;
2380         priv->RFProgType = 0;
2381
2382         priv->irq_enabled = 0;
2383
2384         rtl8180_statistics_init(&priv->stats);
2385         rtl8180_link_detect_init(&priv->link_detect);
2386
2387         priv->ack_tx_to_ieee = 0;
2388         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
2389         priv->ieee80211->iw_mode = IW_MODE_INFRA;
2390         priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
2391                 IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
2392                 IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE;
2393         priv->ieee80211->active_scan = 1;
2394         priv->ieee80211->rate = 110; /* 11 mbps */
2395         priv->ieee80211->modulation = IEEE80211_CCK_MODULATION;
2396         priv->ieee80211->host_encrypt = 1;
2397         priv->ieee80211->host_decrypt = 1;
2398         priv->ieee80211->sta_wake_up = rtl8180_hw_wakeup;
2399         priv->ieee80211->ps_request_tx_ack = rtl8180_rq_tx_ack;
2400         priv->ieee80211->enter_sleep_state = rtl8180_hw_sleep;
2401         priv->ieee80211->ps_is_queue_empty = rtl8180_is_tx_queue_empty;
2402
2403         priv->hw_wep = hwwep;
2404         priv->dev = dev;
2405         priv->retry_rts = DEFAULT_RETRY_RTS;
2406         priv->retry_data = DEFAULT_RETRY_DATA;
2407         priv->RFChangeInProgress = false;
2408         priv->SetRFPowerStateInProgress = false;
2409         priv->RFProgType = 0;
2410         priv->bInactivePs = true; /* false; */
2411         priv->ieee80211->bInactivePs = priv->bInactivePs;
2412         priv->bSwRfProcessing = false;
2413         priv->eRFPowerState = eRfOff;
2414         priv->RfOffReason = 0;
2415         priv->LedStrategy = SW_LED_MODE0;
2416         priv->TxPollingTimes = 0; /* lzm add 080826 */
2417         priv->bLeisurePs = true;
2418         priv->dot11PowerSaveMode = eActive;
2419         priv->AdMinCheckPeriod = 5;
2420         priv->AdMaxCheckPeriod = 10;
2421         priv->AdMaxRxSsThreshold = 30;  /* 60->30 */
2422         priv->AdRxSsThreshold = 20;     /* 50->20 */
2423         priv->AdCheckPeriod = priv->AdMinCheckPeriod;
2424         priv->AdTickCount = 0;
2425         priv->AdRxSignalStrength = -1;
2426         priv->RegSwAntennaDiversityMechanism = 0;
2427         priv->RegDefaultAntenna = 0;
2428         priv->SignalStrength = 0;
2429         priv->AdRxOkCnt = 0;
2430         priv->CurrAntennaIndex = 0;
2431         priv->AdRxSsBeforeSwitched = 0;
2432         init_timer(&priv->SwAntennaDiversityTimer);
2433         priv->SwAntennaDiversityTimer.data = (unsigned long)dev;
2434         priv->SwAntennaDiversityTimer.function = (void *)SwAntennaDiversityTimerCallback;
2435         priv->bDigMechanism = true;
2436         priv->InitialGain = 6;
2437         priv->bXtalCalibration = false;
2438         priv->XtalCal_Xin = 0;
2439         priv->XtalCal_Xout = 0;
2440         priv->bTxPowerTrack = false;
2441         priv->ThermalMeter = 0;
2442         priv->FalseAlarmRegValue = 0;
2443         priv->RegDigOfdmFaUpTh = 0xc; /* Upper threshold of OFDM false alarm, which is used in DIG. */
2444         priv->DIG_NumberFallbackVote = 0;
2445         priv->DIG_NumberUpgradeVote = 0;
2446         priv->LastSignalStrengthInPercent = 0;
2447         priv->Stats_SignalStrength = 0;
2448         priv->LastRxPktAntenna = 0;
2449         priv->SignalQuality = 0; /* in 0-100 index. */
2450         priv->Stats_SignalQuality = 0;
2451         priv->RecvSignalPower = 0; /* in dBm. */
2452         priv->Stats_RecvSignalPower = 0;
2453         priv->AdMainAntennaRxOkCnt = 0;
2454         priv->AdAuxAntennaRxOkCnt = 0;
2455         priv->bHWAdSwitched = false;
2456         priv->bRegHighPowerMechanism = true;
2457         priv->RegHiPwrUpperTh = 77;
2458         priv->RegHiPwrLowerTh = 75;
2459         priv->RegRSSIHiPwrUpperTh = 70;
2460         priv->RegRSSIHiPwrLowerTh = 20;
2461         priv->bCurCCKPkt = false;
2462         priv->UndecoratedSmoothedSS = -1;
2463         priv->bToUpdateTxPwr = false;
2464         priv->CurCCKRSSI = 0;
2465         priv->RxPower = 0;
2466         priv->RSSI = 0;
2467         priv->NumTxOkTotal = 0;
2468         priv->NumTxUnicast = 0;
2469         priv->keepAliveLevel = DEFAULT_KEEP_ALIVE_LEVEL;
2470         priv->CurrRetryCnt = 0;
2471         priv->LastRetryCnt = 0;
2472         priv->LastTxokCnt = 0;
2473         priv->LastRxokCnt = 0;
2474         priv->LastRetryRate = 0;
2475         priv->bTryuping = 0;
2476         priv->CurrTxRate = 0;
2477         priv->CurrRetryRate = 0;
2478         priv->TryupingCount = 0;
2479         priv->TryupingCountNoData = 0;
2480         priv->TryDownCountLowData = 0;
2481         priv->LastTxOKBytes = 0;
2482         priv->LastFailTxRate = 0;
2483         priv->LastFailTxRateSS = 0;
2484         priv->FailTxRateCount = 0;
2485         priv->LastTxThroughput = 0;
2486         priv->NumTxOkBytesTotal = 0;
2487         priv->ForcedDataRate = 0;
2488         priv->RegBModeGainStage = 1;
2489
2490         priv->promisc = (dev->flags & IFF_PROMISC) ? 1 : 0;
2491         spin_lock_init(&priv->irq_th_lock);
2492         spin_lock_init(&priv->tx_lock);
2493         spin_lock_init(&priv->ps_lock);
2494         spin_lock_init(&priv->rf_ps_lock);
2495         sema_init(&priv->wx_sem, 1);
2496         INIT_WORK(&priv->reset_wq, (void *)rtl8180_restart_wq);
2497         INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq,
2498                           (void *)rtl8180_hw_wakeup_wq);
2499         INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq,
2500                           (void *)rtl8180_hw_sleep_wq);
2501         INIT_WORK(&priv->ieee80211->wmm_param_update_wq,
2502                   (void *)rtl8180_wmm_param_update);
2503         INIT_DELAYED_WORK(&priv->ieee80211->rate_adapter_wq,
2504                           (void *)rtl8180_rate_adapter);
2505         INIT_DELAYED_WORK(&priv->ieee80211->hw_dig_wq,
2506                          (void *)rtl8180_hw_dig_wq);
2507         INIT_DELAYED_WORK(&priv->ieee80211->tx_pw_wq,
2508                          (void *)rtl8180_tx_pw_wq);
2509         INIT_DELAYED_WORK(&priv->ieee80211->GPIOChangeRFWorkItem,
2510                          (void *) GPIOChangeRFWorkItemCallBack);
2511         tasklet_init(&priv->irq_rx_tasklet,
2512                      (void(*)(unsigned long)) rtl8180_irq_rx_tasklet,
2513                      (unsigned long)priv);
2514
2515         init_timer(&priv->watch_dog_timer);
2516         priv->watch_dog_timer.data = (unsigned long)dev;
2517         priv->watch_dog_timer.function = watch_dog_adaptive;
2518
2519         init_timer(&priv->rateadapter_timer);
2520         priv->rateadapter_timer.data = (unsigned long)dev;
2521         priv->rateadapter_timer.function = timer_rate_adaptive;
2522         priv->RateAdaptivePeriod = RATE_ADAPTIVE_TIMER_PERIOD;
2523         priv->bEnhanceTxPwr = false;
2524
2525         priv->ieee80211->softmac_hard_start_xmit = rtl8180_hard_start_xmit;
2526         priv->ieee80211->set_chan = rtl8180_set_chan;
2527         priv->ieee80211->link_change = rtl8180_link_change;
2528         priv->ieee80211->softmac_data_hard_start_xmit = rtl8180_hard_data_xmit;
2529         priv->ieee80211->data_hard_stop = rtl8180_data_hard_stop;
2530         priv->ieee80211->data_hard_resume = rtl8180_data_hard_resume;
2531
2532         priv->ieee80211->init_wmmparam_flag = 0;
2533
2534         priv->ieee80211->start_send_beacons = rtl8180_start_tx_beacon;
2535         priv->ieee80211->stop_send_beacons = rtl8180_beacon_tx_disable;
2536         priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
2537
2538         priv->ShortRetryLimit = 7;
2539         priv->LongRetryLimit = 7;
2540         priv->EarlyRxThreshold = 7;
2541
2542         priv->TransmitConfig =  (1<<TCR_DurProcMode_OFFSET) |
2543                                 (7<<TCR_MXDMA_OFFSET) |
2544                                 (priv->ShortRetryLimit<<TCR_SRL_OFFSET) |
2545                                 (priv->LongRetryLimit<<TCR_LRL_OFFSET);
2546
2547         priv->ReceiveConfig =   RCR_AMF | RCR_ADF | RCR_ACF |
2548                                 RCR_AB | RCR_AM | RCR_APM |
2549                                 (7<<RCR_MXDMA_OFFSET) |
2550                                 (priv->EarlyRxThreshold<<RCR_FIFO_OFFSET) |
2551                                 (priv->EarlyRxThreshold == 7 ?
2552                                          RCR_ONLYERLPKT : 0);
2553
2554         priv->IntrMask          = IMR_TMGDOK | IMR_TBDER |
2555                                   IMR_THPDER | IMR_THPDOK |
2556                                   IMR_TVODER | IMR_TVODOK |
2557                                   IMR_TVIDER | IMR_TVIDOK |
2558                                   IMR_TBEDER | IMR_TBEDOK |
2559                                   IMR_TBKDER | IMR_TBKDOK |
2560                                   IMR_RDU |
2561                                   IMR_RER | IMR_ROK |
2562                                   IMR_RQoSOK;
2563
2564         priv->InitialGain = 6;
2565
2566         DMESG("MAC controller is a RTL8187SE b/g");
2567
2568         priv->ieee80211->modulation |= IEEE80211_OFDM_MODULATION;
2569         priv->ieee80211->short_slot = 1;
2570
2571         eeprom_93cx6_read(&eeprom, EEPROM_SW_REVD_OFFSET, &usValue);
2572         DMESG("usValue is %#hx\n", usValue);
2573         /* 3Read AntennaDiversity */
2574
2575         /* SW Antenna Diversity. */
2576         priv->EEPROMSwAntennaDiversity = (usValue & EEPROM_SW_AD_MASK) ==
2577                 EEPROM_SW_AD_ENABLE;
2578
2579         /* Default Antenna to use. */
2580         priv->EEPROMDefaultAntenna1 = (usValue & EEPROM_DEF_ANT_MASK) ==
2581                 EEPROM_DEF_ANT_1;
2582
2583         if (priv->RegSwAntennaDiversityMechanism == 0) /* Auto */
2584                 /* 0: default from EEPROM. */
2585                 priv->bSwAntennaDiverity = priv->EEPROMSwAntennaDiversity;
2586         else
2587                 /* 1:disable antenna diversity, 2: enable antenna diversity. */
2588                 priv->bSwAntennaDiverity = priv->RegSwAntennaDiversityMechanism == 2;
2589
2590         if (priv->RegDefaultAntenna == 0)
2591                 /* 0: default from EEPROM. */
2592                 priv->bDefaultAntenna1 = priv->EEPROMDefaultAntenna1;
2593         else
2594                 /* 1: main, 2: aux. */
2595                 priv->bDefaultAntenna1 = priv->RegDefaultAntenna == 2;
2596
2597         priv->plcp_preamble_mode = 2;
2598         /* the eeprom type is stored in RCR register bit #6 */
2599         if (RCR_9356SEL & read_nic_dword(dev, RCR))
2600                 priv->epromtype = EPROM_93c56;
2601         else
2602                 priv->epromtype = EPROM_93c46;
2603
2604         eeprom_93cx6_multiread(&eeprom, 0x7, (__le16 *)
2605                                dev->dev_addr, 3);
2606
2607         for (i = 1, j = 0; i < 14; i += 2, j++) {
2608                 eeprom_93cx6_read(&eeprom, EPROM_TXPW_CH1_2 + j, &word);
2609                 priv->chtxpwr[i] = word & 0xff;
2610                 priv->chtxpwr[i+1] = (word & 0xff00)>>8;
2611         }
2612         for (i = 1, j = 0; i < 14; i += 2, j++) {
2613                 eeprom_93cx6_read(&eeprom, EPROM_TXPW_OFDM_CH1_2 + j, &word);
2614                 priv->chtxpwr_ofdm[i] = word & 0xff;
2615                 priv->chtxpwr_ofdm[i+1] = (word & 0xff00) >> 8;
2616         }
2617
2618         /* 3Read crystal calibration and thermal meter indication on 87SE. */
2619         eeprom_93cx6_read(&eeprom, EEPROM_RSV>>1, &tmpu16);
2620
2621         /* Crystal calibration for Xin and Xout resp. */
2622         priv->XtalCal_Xout = tmpu16 & EEPROM_XTAL_CAL_XOUT_MASK;
2623         priv->XtalCal_Xin = (tmpu16 & EEPROM_XTAL_CAL_XIN_MASK) >> 4;
2624         if ((tmpu16 & EEPROM_XTAL_CAL_ENABLE) >> 12)
2625                 priv->bXtalCalibration = true;
2626
2627         /* Thermal meter reference indication. */
2628         priv->ThermalMeter =  (u8)((tmpu16 & EEPROM_THERMAL_METER_MASK) >> 8);
2629         if ((tmpu16 & EEPROM_THERMAL_METER_ENABLE) >> 13)
2630                 priv->bTxPowerTrack = true;
2631
2632         priv->rf_sleep = rtl8225z4_rf_sleep;
2633         priv->rf_wakeup = rtl8225z4_rf_wakeup;
2634         DMESGW("**PLEASE** REPORT SUCCESSFUL/UNSUCCESSFUL TO Realtek!");
2635
2636         priv->rf_close = rtl8225z2_rf_close;
2637         priv->rf_init = rtl8225z2_rf_init;
2638         priv->rf_set_chan = rtl8225z2_rf_set_chan;
2639         priv->rf_set_sens = NULL;
2640
2641         if (0 != alloc_rx_desc_ring(dev, priv->rxbuffersize, priv->rxringcount))
2642                 return -ENOMEM;
2643
2644         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2645                                   TX_MANAGEPRIORITY_RING_ADDR))
2646                 return -ENOMEM;
2647
2648         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2649                                  TX_BKPRIORITY_RING_ADDR))
2650                 return -ENOMEM;
2651
2652         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2653                                  TX_BEPRIORITY_RING_ADDR))
2654                 return -ENOMEM;
2655
2656         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2657                                   TX_VIPRIORITY_RING_ADDR))
2658                 return -ENOMEM;
2659
2660         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2661                                   TX_VOPRIORITY_RING_ADDR))
2662                 return -ENOMEM;
2663
2664         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
2665                                   TX_HIGHPRIORITY_RING_ADDR))
2666                 return -ENOMEM;
2667
2668         if (0 != alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txbeaconcount,
2669                                   TX_BEACON_RING_ADDR))
2670                 return -ENOMEM;
2671
2672         if (request_irq(dev->irq, rtl8180_interrupt, IRQF_SHARED, dev->name, dev)) {
2673                 DMESGE("Error allocating IRQ %d", dev->irq);
2674                 return -1;
2675         } else {
2676                 priv->irq = dev->irq;
2677                 DMESG("IRQ %d", dev->irq);
2678         }
2679
2680         return 0;
2681 }
2682
2683 void rtl8180_no_hw_wep(struct net_device *dev)
2684 {
2685 }
2686
2687 void rtl8180_set_hw_wep(struct net_device *dev)
2688 {
2689         struct r8180_priv *priv = ieee80211_priv(dev);
2690         u8 pgreg;
2691         u8 security;
2692         u32 key0_word4;
2693
2694         pgreg = read_nic_byte(dev, PGSELECT);
2695         write_nic_byte(dev, PGSELECT, pgreg & ~(1<<PGSELECT_PG_SHIFT));
2696
2697         key0_word4 = read_nic_dword(dev, KEY0+4+4+4);
2698         key0_word4 &= ~0xff;
2699         key0_word4 |= priv->key0[3] & 0xff;
2700         write_nic_dword(dev, KEY0, (priv->key0[0]));
2701         write_nic_dword(dev, KEY0+4, (priv->key0[1]));
2702         write_nic_dword(dev, KEY0+4+4, (priv->key0[2]));
2703         write_nic_dword(dev, KEY0+4+4+4, (key0_word4));
2704
2705         security  = read_nic_byte(dev, SECURITY);
2706         security |= (1<<SECURITY_WEP_TX_ENABLE_SHIFT);
2707         security |= (1<<SECURITY_WEP_RX_ENABLE_SHIFT);
2708         security &= ~SECURITY_ENCRYP_MASK;
2709         security |= (SECURITY_ENCRYP_104<<SECURITY_ENCRYP_SHIFT);
2710
2711         write_nic_byte(dev, SECURITY, security);
2712
2713         DMESG("key %x %x %x %x", read_nic_dword(dev, KEY0+4+4+4),
2714               read_nic_dword(dev, KEY0+4+4), read_nic_dword(dev, KEY0+4),
2715               read_nic_dword(dev, KEY0));
2716 }
2717
2718
2719 void rtl8185_rf_pins_enable(struct net_device *dev)
2720 {
2721         /* u16 tmp; */
2722         /* tmp = read_nic_word(dev, RFPinsEnable); */
2723         write_nic_word(dev, RFPinsEnable, 0x1fff); /* | tmp); */
2724 }
2725
2726 void rtl8185_set_anaparam2(struct net_device *dev, u32 a)
2727 {
2728         u8 conf3;
2729
2730         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
2731
2732         conf3 = read_nic_byte(dev, CONFIG3);
2733         write_nic_byte(dev, CONFIG3, conf3 | (1<<CONFIG3_ANAPARAM_W_SHIFT));
2734         write_nic_dword(dev, ANAPARAM2, a);
2735
2736         conf3 = read_nic_byte(dev, CONFIG3);
2737         write_nic_byte(dev, CONFIG3, conf3 & ~(1<<CONFIG3_ANAPARAM_W_SHIFT));
2738         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
2739 }
2740
2741 void rtl8180_set_anaparam(struct net_device *dev, u32 a)
2742 {
2743         u8 conf3;
2744
2745         rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
2746
2747         conf3 = read_nic_byte(dev, CONFIG3);
2748         write_nic_byte(dev, CONFIG3, conf3 | (1<<CONFIG3_ANAPARAM_W_SHIFT));
2749         write_nic_dword(dev, ANAPARAM, a);
2750
2751         conf3 = read_nic_byte(dev, CONFIG3);
2752         write_nic_byte(dev, CONFIG3, conf3 & ~(1<<CONFIG3_ANAPARAM_W_SHIFT));
2753         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
2754 }
2755
2756 void rtl8185_tx_antenna(struct net_device *dev, u8 ant)
2757 {
2758         write_nic_byte(dev, TX_ANTENNA, ant);
2759         force_pci_posting(dev);
2760         mdelay(1);
2761 }
2762
2763 static void rtl8185_write_phy(struct net_device *dev, u8 adr, u32 data)
2764 {
2765         u32 phyw;
2766
2767         adr |= 0x80;
2768
2769         phyw = ((data<<8) | adr);
2770
2771         /* Note that, we must write 0xff7c after 0x7d-0x7f to write BB register. */
2772         write_nic_byte(dev, 0x7f, ((phyw & 0xff000000) >> 24));
2773         write_nic_byte(dev, 0x7e, ((phyw & 0x00ff0000) >> 16));
2774         write_nic_byte(dev, 0x7d, ((phyw & 0x0000ff00) >> 8));
2775         write_nic_byte(dev, 0x7c, ((phyw & 0x000000ff)));
2776
2777         /* this is ok to fail when we write AGC table. check for AGC table might be
2778          * done by masking with 0x7f instead of 0xff
2779          */
2780         /* if (phyr != (data&0xff)) DMESGW("Phy write timeout %x %x %x", phyr, data, adr); */
2781 }
2782
2783 inline void write_phy_ofdm(struct net_device *dev, u8 adr, u32 data)
2784 {
2785         data = data & 0xff;
2786         rtl8185_write_phy(dev, adr, data);
2787 }
2788
2789 void write_phy_cck(struct net_device *dev, u8 adr, u32 data)
2790 {
2791         data = data & 0xff;
2792         rtl8185_write_phy(dev, adr, data | 0x10000);
2793 }
2794
2795 /*
2796  * This configures registers for beacon tx and enables it via
2797  * rtl8180_beacon_tx_enable(). rtl8180_beacon_tx_disable() might
2798  * be used to stop beacon transmission
2799  */
2800 void rtl8180_start_tx_beacon(struct net_device *dev)
2801 {
2802         u16 word;
2803
2804         DMESG("Enabling beacon TX");
2805         rtl8180_prepare_beacon(dev);
2806         rtl8180_irq_disable(dev);
2807         rtl8180_beacon_tx_enable(dev);
2808
2809         word = read_nic_word(dev, AtimWnd) & ~AtimWnd_AtimWnd;
2810         write_nic_word(dev, AtimWnd, word); /* word |= */
2811
2812         word  = read_nic_word(dev, BintrItv);
2813         word &= ~BintrItv_BintrItv;
2814         word |= 1000; /* priv->ieee80211->current_network.beacon_interval *
2815                 ((priv->txbeaconcount > 1)?(priv->txbeaconcount-1):1);
2816         // FIXME: check if correct ^^ worked with 0x3e8;
2817         */
2818         write_nic_word(dev, BintrItv, word);
2819
2820         rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
2821
2822         rtl8185b_irq_enable(dev);
2823 }
2824
2825 static struct net_device_stats *rtl8180_stats(struct net_device *dev)
2826 {
2827         struct r8180_priv *priv = ieee80211_priv(dev);
2828
2829         return &priv->ieee80211->stats;
2830 }
2831
2832 /*
2833  * Change current and default preamble mode.
2834  */
2835 static bool MgntActSet_802_11_PowerSaveMode(struct r8180_priv *priv,
2836                                      RT_PS_MODE rtPsMode)
2837 {
2838         /* Currently, we do not change power save mode on IBSS mode. */
2839         if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
2840                 return false;
2841
2842         priv->ieee80211->ps = rtPsMode;
2843
2844         return true;
2845 }
2846
2847 static void LeisurePSEnter(struct r8180_priv *priv)
2848 {
2849         if (priv->bLeisurePs) {
2850                 if (priv->ieee80211->ps == IEEE80211_PS_DISABLED)
2851                         /* IEEE80211_PS_ENABLE */
2852                         MgntActSet_802_11_PowerSaveMode(priv, IEEE80211_PS_MBCAST|IEEE80211_PS_UNICAST);
2853         }
2854 }
2855
2856 static void LeisurePSLeave(struct r8180_priv *priv)
2857 {
2858         if (priv->bLeisurePs) {
2859                 if (priv->ieee80211->ps != IEEE80211_PS_DISABLED)
2860                         MgntActSet_802_11_PowerSaveMode(priv, IEEE80211_PS_DISABLED);
2861         }
2862 }
2863
2864 void rtl8180_hw_wakeup_wq(struct work_struct *work)
2865 {
2866         struct delayed_work *dwork = to_delayed_work(work);
2867         struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, hw_wakeup_wq);
2868         struct net_device *dev = ieee->dev;
2869
2870         rtl8180_hw_wakeup(dev);
2871 }
2872
2873 void rtl8180_hw_sleep_wq(struct work_struct *work)
2874 {
2875         struct delayed_work *dwork = to_delayed_work(work);
2876         struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, hw_sleep_wq);
2877         struct net_device *dev = ieee->dev;
2878
2879         rtl8180_hw_sleep_down(dev);
2880 }
2881
2882 static void MgntLinkKeepAlive(struct r8180_priv *priv)
2883 {
2884         if (priv->keepAliveLevel == 0)
2885                 return;
2886
2887         if (priv->ieee80211->state == IEEE80211_LINKED) {
2888                 /*
2889                  * Keep-Alive.
2890                  */
2891
2892                 if ((priv->keepAliveLevel == 2) ||
2893                         (priv->link_detect.LastNumTxUnicast == priv->NumTxUnicast &&
2894                         priv->link_detect.LastNumRxUnicast == priv->ieee80211->NumRxUnicast)
2895                         ) {
2896                         priv->link_detect.IdleCount++;
2897
2898                         /*
2899                          * Send a Keep-Alive packet packet to AP if we had been idle for a while.
2900                          */
2901                         if (priv->link_detect.IdleCount >= ((KEEP_ALIVE_INTERVAL / CHECK_FOR_HANG_PERIOD)-1)) {
2902                                 priv->link_detect.IdleCount = 0;
2903                                 ieee80211_sta_ps_send_null_frame(priv->ieee80211, false);
2904                         }
2905                 } else {
2906                         priv->link_detect.IdleCount = 0;
2907                 }
2908                 priv->link_detect.LastNumTxUnicast = priv->NumTxUnicast;
2909                 priv->link_detect.LastNumRxUnicast = priv->ieee80211->NumRxUnicast;
2910         }
2911 }
2912
2913 void rtl8180_watch_dog(struct net_device *dev)
2914 {
2915         struct r8180_priv *priv = ieee80211_priv(dev);
2916         bool bEnterPS = false;
2917         bool bBusyTraffic = false;
2918         u32 TotalRxNum = 0;
2919         u16 SlotIndex = 0;
2920         u16 i = 0;
2921         if (priv->ieee80211->actscanning == false) {
2922                 if ((priv->ieee80211->iw_mode != IW_MODE_ADHOC) &&
2923                     (priv->ieee80211->state == IEEE80211_NOLINK) &&
2924                     (priv->ieee80211->beinretry == false) &&
2925                     (priv->eRFPowerState == eRfOn))
2926                         IPSEnter(dev);
2927         }
2928         /* YJ,add,080828,for link state check */
2929         if ((priv->ieee80211->state == IEEE80211_LINKED) && (priv->ieee80211->iw_mode == IW_MODE_INFRA)) {
2930                 SlotIndex = (priv->link_detect.SlotIndex++) % priv->link_detect.SlotNum;
2931                 priv->link_detect.RxFrameNum[SlotIndex] = priv->ieee80211->NumRxDataInPeriod + priv->ieee80211->NumRxBcnInPeriod;
2932                 for (i = 0; i < priv->link_detect.SlotNum; i++)
2933                         TotalRxNum += priv->link_detect.RxFrameNum[i];
2934
2935                 if (TotalRxNum == 0) {
2936                         priv->ieee80211->state = IEEE80211_ASSOCIATING;
2937                         queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
2938                 }
2939         }
2940
2941         /* YJ,add,080828,for KeepAlive */
2942         MgntLinkKeepAlive(priv);
2943
2944         /* YJ,add,080828,for LPS */
2945         LeisurePSLeave(priv);
2946
2947         if (priv->ieee80211->state == IEEE80211_LINKED) {
2948                 priv->link_detect.NumRxOkInPeriod = priv->ieee80211->NumRxDataInPeriod;
2949                 if (priv->link_detect.NumRxOkInPeriod > 666 ||
2950                         priv->link_detect.NumTxOkInPeriod > 666) {
2951                         bBusyTraffic = true;
2952                 }
2953                 if (((priv->link_detect.NumRxOkInPeriod + priv->link_detect.NumTxOkInPeriod) > 8)
2954                         || (priv->link_detect.NumRxOkInPeriod > 2)) {
2955                         bEnterPS = false;
2956                 } else
2957                         bEnterPS = true;
2958
2959                 if (bEnterPS)
2960                         LeisurePSEnter(priv);
2961                 else
2962                         LeisurePSLeave(priv);
2963         } else
2964                 LeisurePSLeave(priv);
2965         priv->link_detect.bBusyTraffic = bBusyTraffic;
2966         priv->link_detect.NumRxOkInPeriod = 0;
2967         priv->link_detect.NumTxOkInPeriod = 0;
2968         priv->ieee80211->NumRxDataInPeriod = 0;
2969         priv->ieee80211->NumRxBcnInPeriod = 0;
2970 }
2971
2972 static int _rtl8180_up(struct net_device *dev)
2973 {
2974         struct r8180_priv *priv = ieee80211_priv(dev);
2975
2976         priv->up = 1;
2977
2978         DMESG("Bringing up iface");
2979         rtl8185b_adapter_start(dev);
2980         rtl8185b_rx_enable(dev);
2981         rtl8185b_tx_enable(dev);
2982         if (priv->bInactivePs) {
2983                 if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
2984                         IPSLeave(dev);
2985         }
2986         timer_rate_adaptive((unsigned long)dev);
2987         watch_dog_adaptive((unsigned long)dev);
2988         if (priv->bSwAntennaDiverity)
2989                         SwAntennaDiversityTimerCallback(dev);
2990         ieee80211_softmac_start_protocol(priv->ieee80211);
2991         return 0;
2992 }
2993
2994 static int rtl8180_open(struct net_device *dev)
2995 {
2996         struct r8180_priv *priv = ieee80211_priv(dev);
2997         int ret;
2998
2999         down(&priv->wx_sem);
3000         ret = rtl8180_up(dev);
3001         up(&priv->wx_sem);
3002         return ret;
3003 }
3004
3005 int rtl8180_up(struct net_device *dev)
3006 {
3007         struct r8180_priv *priv = ieee80211_priv(dev);
3008
3009         if (priv->up == 1)
3010                 return -1;
3011
3012         return _rtl8180_up(dev);
3013 }
3014
3015 static int rtl8180_close(struct net_device *dev)
3016 {
3017         struct r8180_priv *priv = ieee80211_priv(dev);
3018         int ret;
3019
3020         down(&priv->wx_sem);
3021         ret = rtl8180_down(dev);
3022         up(&priv->wx_sem);
3023
3024         return ret;
3025 }
3026
3027 int rtl8180_down(struct net_device *dev)
3028 {
3029         struct r8180_priv *priv = ieee80211_priv(dev);
3030
3031         if (priv->up == 0)
3032                 return -1;
3033
3034         priv->up = 0;
3035
3036         ieee80211_softmac_stop_protocol(priv->ieee80211);
3037         /* FIXME */
3038         if (!netif_queue_stopped(dev))
3039                 netif_stop_queue(dev);
3040         rtl8180_rtx_disable(dev);
3041         rtl8180_irq_disable(dev);
3042         del_timer_sync(&priv->watch_dog_timer);
3043         del_timer_sync(&priv->rateadapter_timer);
3044         cancel_delayed_work(&priv->ieee80211->rate_adapter_wq);
3045         cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
3046         cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
3047         cancel_delayed_work(&priv->ieee80211->hw_dig_wq);
3048         cancel_delayed_work(&priv->ieee80211->tx_pw_wq);
3049         del_timer_sync(&priv->SwAntennaDiversityTimer);
3050         SetZebraRFPowerState8185(dev, eRfOff);
3051         memset(&(priv->ieee80211->current_network), 0, sizeof(struct ieee80211_network));
3052         priv->ieee80211->state = IEEE80211_NOLINK;
3053         return 0;
3054 }
3055
3056 void rtl8180_restart_wq(struct work_struct *work)
3057 {
3058         struct r8180_priv *priv = container_of(work, struct r8180_priv, reset_wq);
3059         struct net_device *dev = priv->dev;
3060
3061         down(&priv->wx_sem);
3062
3063         rtl8180_commit(dev);
3064
3065         up(&priv->wx_sem);
3066 }
3067
3068 static void rtl8180_restart(struct net_device *dev)
3069 {
3070         struct r8180_priv *priv = ieee80211_priv(dev);
3071
3072         schedule_work(&priv->reset_wq);
3073 }
3074
3075 void rtl8180_commit(struct net_device *dev)
3076 {
3077         struct r8180_priv *priv = ieee80211_priv(dev);
3078
3079         if (priv->up == 0)
3080                 return;
3081
3082         del_timer_sync(&priv->watch_dog_timer);
3083         del_timer_sync(&priv->rateadapter_timer);
3084         cancel_delayed_work(&priv->ieee80211->rate_adapter_wq);
3085         cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
3086         cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
3087         cancel_delayed_work(&priv->ieee80211->hw_dig_wq);
3088         cancel_delayed_work(&priv->ieee80211->tx_pw_wq);
3089         del_timer_sync(&priv->SwAntennaDiversityTimer);
3090         ieee80211_softmac_stop_protocol(priv->ieee80211);
3091         rtl8180_irq_disable(dev);
3092         rtl8180_rtx_disable(dev);
3093         _rtl8180_up(dev);
3094 }
3095
3096 static void r8180_set_multicast(struct net_device *dev)
3097 {
3098         struct r8180_priv *priv = ieee80211_priv(dev);
3099         short promisc;
3100
3101         promisc = (dev->flags & IFF_PROMISC) ? 1 : 0;
3102
3103         if (promisc != priv->promisc)
3104                 rtl8180_restart(dev);
3105
3106         priv->promisc = promisc;
3107 }
3108
3109 static int r8180_set_mac_adr(struct net_device *dev, void *mac)
3110 {
3111         struct r8180_priv *priv = ieee80211_priv(dev);
3112         struct sockaddr *addr = mac;
3113
3114         down(&priv->wx_sem);
3115
3116         memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
3117
3118         if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
3119                 memcpy(priv->ieee80211->current_network.bssid, dev->dev_addr, ETH_ALEN);
3120
3121         if (priv->up) {
3122                 rtl8180_down(dev);
3123                 rtl8180_up(dev);
3124         }
3125
3126         up(&priv->wx_sem);
3127
3128         return 0;
3129 }
3130
3131 /* based on ipw2200 driver */
3132 static int rtl8180_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
3133 {
3134         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
3135         struct iwreq *wrq = (struct iwreq *) rq;
3136         int ret = -1;
3137
3138         switch (cmd) {
3139         case RTL_IOCTL_WPA_SUPPLICANT:
3140                 ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
3141                 return ret;
3142         default:
3143                 return -EOPNOTSUPP;
3144         }
3145
3146         return -EOPNOTSUPP;
3147 }
3148
3149 static const struct net_device_ops rtl8180_netdev_ops = {
3150         .ndo_open               = rtl8180_open,
3151         .ndo_stop               = rtl8180_close,
3152         .ndo_get_stats          = rtl8180_stats,
3153         .ndo_tx_timeout         = rtl8180_restart,
3154         .ndo_do_ioctl           = rtl8180_ioctl,
3155         .ndo_set_rx_mode        = r8180_set_multicast,
3156         .ndo_set_mac_address    = r8180_set_mac_adr,
3157         .ndo_validate_addr      = eth_validate_addr,
3158         .ndo_change_mtu         = eth_change_mtu,
3159         .ndo_start_xmit         = ieee80211_rtl_xmit,
3160 };
3161
3162 static int rtl8180_pci_probe(struct pci_dev *pdev,
3163                              const struct pci_device_id *id)
3164 {
3165         unsigned long ioaddr = 0;
3166         struct net_device *dev = NULL;
3167         struct r8180_priv *priv = NULL;
3168         u8 unit = 0;
3169         int ret = -ENODEV;
3170
3171         unsigned long pmem_start, pmem_len, pmem_flags;
3172
3173         DMESG("Configuring chip resources");
3174
3175         if (pci_enable_device(pdev)) {
3176                 DMESG("Failed to enable PCI device");
3177                 return -EIO;
3178         }
3179
3180         pci_set_master(pdev);
3181         pci_set_dma_mask(pdev, 0xffffff00ULL);
3182         pci_set_consistent_dma_mask(pdev, 0xffffff00ULL);
3183         dev = alloc_ieee80211(sizeof(struct r8180_priv));
3184         if (!dev) {
3185                 ret = -ENOMEM;
3186                 goto fail_free;
3187         }
3188         priv = ieee80211_priv(dev);
3189         priv->ieee80211 = netdev_priv(dev);
3190
3191         pci_set_drvdata(pdev, dev);
3192         SET_NETDEV_DEV(dev, &pdev->dev);
3193
3194         priv = ieee80211_priv(dev);
3195         priv->pdev = pdev;
3196
3197         pmem_start = pci_resource_start(pdev, 1);
3198         pmem_len = pci_resource_len(pdev, 1);
3199         pmem_flags = pci_resource_flags(pdev, 1);
3200
3201         if (!(pmem_flags & IORESOURCE_MEM)) {
3202                 DMESG("region #1 not a MMIO resource, aborting");
3203                 goto fail;
3204         }
3205
3206         if (!request_mem_region(pmem_start, pmem_len, RTL8180_MODULE_NAME)) {
3207                 DMESG("request_mem_region failed!");
3208                 goto fail;
3209         }
3210
3211         ioaddr = (unsigned long)ioremap_nocache(pmem_start, pmem_len);
3212         if (ioaddr == (unsigned long)NULL) {
3213                 DMESG("ioremap failed!");
3214                 goto fail1;
3215         }
3216
3217         dev->mem_start = ioaddr; /* shared mem start */
3218         dev->mem_end = ioaddr + pci_resource_len(pdev, 0); /* shared mem end */
3219
3220         pci_read_config_byte(pdev, 0x05, &unit);
3221         pci_write_config_byte(pdev, 0x05, unit & (~0x04));
3222
3223         dev->irq = pdev->irq;
3224         priv->irq = 0;
3225
3226         dev->netdev_ops = &rtl8180_netdev_ops;
3227         dev->wireless_handlers = &r8180_wx_handlers_def;
3228
3229         dev->type = ARPHRD_ETHER;
3230         dev->watchdog_timeo = HZ*3;
3231
3232         if (dev_alloc_name(dev, ifname) < 0) {
3233                 DMESG("Oops: devname already taken! Trying wlan%%d...\n");
3234                 strcpy(ifname, "wlan%d");
3235                 dev_alloc_name(dev, ifname);
3236         }
3237
3238         if (rtl8180_init(dev) != 0) {
3239                 DMESG("Initialization failed");
3240                 goto fail1;
3241         }
3242
3243         netif_carrier_off(dev);
3244
3245         if (register_netdev(dev))
3246                 goto fail1;
3247
3248         rtl8180_proc_init_one(dev);
3249
3250         DMESG("Driver probe completed\n");
3251         return 0;
3252 fail1:
3253         if (dev->mem_start != (unsigned long)NULL) {
3254                 iounmap((void __iomem *)dev->mem_start);
3255                 release_mem_region(pci_resource_start(pdev, 1),
3256                                    pci_resource_len(pdev, 1));
3257         }
3258 fail:
3259         if (dev) {
3260                 if (priv->irq) {
3261                         free_irq(dev->irq, dev);
3262                         dev->irq = 0;
3263                 }
3264                 free_ieee80211(dev);
3265         }
3266
3267 fail_free:
3268         pci_disable_device(pdev);
3269
3270         DMESG("wlan driver load failed\n");
3271         return ret;
3272 }
3273
3274 static void rtl8180_pci_remove(struct pci_dev *pdev)
3275 {
3276         struct r8180_priv *priv;
3277         struct net_device *dev = pci_get_drvdata(pdev);
3278
3279         if (dev) {
3280                 unregister_netdev(dev);
3281
3282                 priv = ieee80211_priv(dev);
3283
3284                 rtl8180_proc_remove_one(dev);
3285                 rtl8180_down(dev);
3286                 priv->rf_close(dev);
3287                 rtl8180_reset(dev);
3288                 mdelay(10);
3289
3290                 if (priv->irq) {
3291                         DMESG("Freeing irq %d", dev->irq);
3292                         free_irq(dev->irq, dev);
3293                         priv->irq = 0;
3294                 }
3295
3296                 free_rx_desc_ring(dev);
3297                 free_tx_desc_rings(dev);
3298
3299                 if (dev->mem_start != (unsigned long)NULL) {
3300                         iounmap((void __iomem *)dev->mem_start);
3301                         release_mem_region(pci_resource_start(pdev, 1),
3302                                            pci_resource_len(pdev, 1));
3303                 }
3304
3305                 free_ieee80211(dev);
3306         }
3307         pci_disable_device(pdev);
3308
3309         DMESG("wlan driver removed\n");
3310 }
3311
3312 static int __init rtl8180_pci_module_init(void)
3313 {
3314         int ret;
3315
3316         ret = ieee80211_crypto_init();
3317         if (ret) {
3318                 pr_err("ieee80211_crypto_init() failed %d\n", ret);
3319                 return ret;
3320         }
3321         ret = ieee80211_crypto_tkip_init();
3322         if (ret) {
3323                 pr_err("ieee80211_crypto_tkip_init() failed %d\n", ret);
3324                 return ret;
3325         }
3326         ret = ieee80211_crypto_ccmp_init();
3327         if (ret) {
3328                 pr_err("ieee80211_crypto_ccmp_init() failed %d\n", ret);
3329                 return ret;
3330         }
3331         ret = ieee80211_crypto_wep_init();
3332         if (ret) {
3333                 pr_err("ieee80211_crypto_wep_init() failed %d\n", ret);
3334                 return ret;
3335         }
3336
3337         pr_info("\nLinux kernel driver for RTL8180 / RTL8185 based WLAN cards\n");
3338         pr_info("Copyright (c) 2004-2005, Andrea Merello\n");
3339         DMESG("Initializing module");
3340         DMESG("Wireless extensions version %d", WIRELESS_EXT);
3341         rtl8180_proc_module_init();
3342
3343         if (pci_register_driver(&rtl8180_pci_driver)) {
3344                 DMESG("No device found");
3345                 return -ENODEV;
3346         }
3347         return 0;
3348 }
3349
3350 static void __exit rtl8180_pci_module_exit(void)
3351 {
3352         pci_unregister_driver(&rtl8180_pci_driver);
3353         rtl8180_proc_module_remove();
3354         ieee80211_crypto_tkip_exit();
3355         ieee80211_crypto_ccmp_exit();
3356         ieee80211_crypto_wep_exit();
3357         ieee80211_crypto_deinit();
3358         DMESG("Exiting");
3359 }
3360
3361 static void rtl8180_try_wake_queue(struct net_device *dev, int pri)
3362 {
3363         unsigned long flags;
3364         short enough_desc;
3365         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
3366
3367         spin_lock_irqsave(&priv->tx_lock, flags);
3368         enough_desc = check_nic_enought_desc(dev, pri);
3369         spin_unlock_irqrestore(&priv->tx_lock, flags);
3370
3371         if (enough_desc)
3372                 ieee80211_rtl_wake_queue(priv->ieee80211);
3373 }
3374
3375 static void rtl8180_tx_isr(struct net_device *dev, int pri, short error)
3376 {
3377         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
3378         u32 *tail; /* tail virtual addr */
3379         u32 *head; /* head virtual addr */
3380         u32 *begin; /* start of ring virtual addr */
3381         u32 *nicv; /* nic pointer virtual addr */
3382         u32 nic; /* nic pointer physical addr */
3383         u32 nicbegin; /* start of ring physical addr */
3384         unsigned long flag;
3385         /* physical addr are ok on 32 bits since we set DMA mask */
3386         int offs;
3387         int j, i;
3388         int hd;
3389         if (error)
3390                 priv->stats.txretry++; /* tony 20060601 */
3391         spin_lock_irqsave(&priv->tx_lock, flag);
3392         switch (pri) {
3393         case MANAGE_PRIORITY:
3394                 tail = priv->txmapringtail;
3395                 begin = priv->txmapring;
3396                 head = priv->txmapringhead;
3397                 nic = read_nic_dword(dev, TX_MANAGEPRIORITY_RING_ADDR);
3398                 nicbegin = priv->txmapringdma;
3399                 break;
3400         case BK_PRIORITY:
3401                 tail = priv->txbkpringtail;
3402                 begin = priv->txbkpring;
3403                 head = priv->txbkpringhead;
3404                 nic = read_nic_dword(dev, TX_BKPRIORITY_RING_ADDR);
3405                 nicbegin = priv->txbkpringdma;
3406                 break;
3407         case BE_PRIORITY:
3408                 tail = priv->txbepringtail;
3409                 begin = priv->txbepring;
3410                 head = priv->txbepringhead;
3411                 nic = read_nic_dword(dev, TX_BEPRIORITY_RING_ADDR);
3412                 nicbegin = priv->txbepringdma;
3413                 break;
3414         case VI_PRIORITY:
3415                 tail = priv->txvipringtail;
3416                 begin = priv->txvipring;
3417                 head = priv->txvipringhead;
3418                 nic = read_nic_dword(dev, TX_VIPRIORITY_RING_ADDR);
3419                 nicbegin = priv->txvipringdma;
3420                 break;
3421         case VO_PRIORITY:
3422                 tail = priv->txvopringtail;
3423                 begin = priv->txvopring;
3424                 head = priv->txvopringhead;
3425                 nic = read_nic_dword(dev, TX_VOPRIORITY_RING_ADDR);
3426                 nicbegin = priv->txvopringdma;
3427                 break;
3428         case HI_PRIORITY:
3429                 tail = priv->txhpringtail;
3430                 begin = priv->txhpring;
3431                 head = priv->txhpringhead;
3432                 nic = read_nic_dword(dev, TX_HIGHPRIORITY_RING_ADDR);
3433                 nicbegin = priv->txhpringdma;
3434                 break;
3435
3436         default:
3437                 spin_unlock_irqrestore(&priv->tx_lock, flag);
3438                 return;
3439         }
3440
3441         nicv = (u32 *)((nic - nicbegin) + (u8 *)begin);
3442         if ((head <= tail && (nicv > tail || nicv < head)) ||
3443                 (head > tail && (nicv > tail && nicv < head))) {
3444                         DMESGW("nic has lost pointer");
3445                         spin_unlock_irqrestore(&priv->tx_lock, flag);
3446                         rtl8180_restart(dev);
3447                         return;
3448                 }
3449
3450         /*
3451          * We check all the descriptors between the head and the nic,
3452          * but not the currently pointed by the nic (the next to be txed)
3453          * and the previous of the pointed (might be in process ??)
3454          */
3455         offs = (nic - nicbegin);
3456         offs = offs / 8 / 4;
3457         hd = (head - begin) / 8;
3458
3459         if (offs >= hd)
3460                 j = offs - hd;
3461         else
3462                 j = offs + (priv->txringcount-1-hd);
3463
3464         j -= 2;
3465         if (j < 0)
3466                 j = 0;
3467
3468         for (i = 0; i < j; i++) {
3469                 if ((*head) & (1<<31))
3470                         break;
3471                 if (((*head)&(0x10000000)) != 0) {
3472                         priv->CurrRetryCnt += (u16)((*head) & (0x000000ff));
3473                         if (!error)
3474                                 priv->NumTxOkTotal++;
3475                 }
3476
3477                 if (!error)
3478                         priv->NumTxOkBytesTotal += (*(head+3)) & (0x00000fff);
3479
3480                 *head = *head & ~(1<<31);
3481
3482                 if ((head - begin)/8 == priv->txringcount-1)
3483                         head = begin;
3484                 else
3485                         head += 8;
3486         }
3487
3488         /*
3489          * The head has been moved to the last certainly TXed
3490          * (or at least processed by the nic) packet.
3491          * The driver take forcefully owning of all these packets
3492          * If the packet previous of the nic pointer has been
3493          * processed this doesn't matter: it will be checked
3494          * here at the next round. Anyway if no more packet are
3495          * TXed no memory leak occur at all.
3496          */
3497
3498         switch (pri) {
3499         case MANAGE_PRIORITY:
3500                 priv->txmapringhead = head;
3501
3502                 if (priv->ack_tx_to_ieee) {
3503                         if (rtl8180_is_tx_queue_empty(dev)) {
3504                                 priv->ack_tx_to_ieee = 0;
3505                                 ieee80211_ps_tx_ack(priv->ieee80211, !error);
3506                         }
3507                 }
3508                 break;
3509         case BK_PRIORITY:
3510                 priv->txbkpringhead = head;
3511                 break;
3512         case BE_PRIORITY:
3513                 priv->txbepringhead = head;
3514                 break;
3515         case VI_PRIORITY:
3516                 priv->txvipringhead = head;
3517                 break;
3518         case VO_PRIORITY:
3519                 priv->txvopringhead = head;
3520                 break;
3521         case HI_PRIORITY:
3522                 priv->txhpringhead = head;
3523                 break;
3524         }
3525
3526         spin_unlock_irqrestore(&priv->tx_lock, flag);
3527 }
3528
3529 static irqreturn_t rtl8180_interrupt(int irq, void *netdev)
3530 {
3531         struct net_device *dev = (struct net_device *) netdev;
3532         struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
3533         unsigned long flags;
3534         u32 inta;
3535
3536         /* We should return IRQ_NONE, but for now let me keep this */
3537         if (priv->irq_enabled == 0)
3538                 return IRQ_HANDLED;
3539
3540         spin_lock_irqsave(&priv->irq_th_lock, flags);
3541
3542         /* ISR: 4bytes */
3543         inta = read_nic_dword(dev, ISR); /* & priv->IntrMask; */
3544         write_nic_dword(dev, ISR, inta); /* reset int situation */
3545
3546         priv->stats.shints++;
3547
3548         if (!inta) {
3549                 spin_unlock_irqrestore(&priv->irq_th_lock, flags);
3550                 return IRQ_HANDLED;
3551         /*
3552          * most probably we can safely return IRQ_NONE,
3553          * but for now is better to avoid problems
3554          */
3555         }
3556
3557         if (inta == 0xffff) {
3558                 /* HW disappeared */
3559                 spin_unlock_irqrestore(&priv->irq_th_lock, flags);
3560                 return IRQ_HANDLED;
3561         }
3562
3563         priv->stats.ints++;
3564
3565         if (!netif_running(dev)) {
3566                 spin_unlock_irqrestore(&priv->irq_th_lock, flags);
3567                 return IRQ_HANDLED;
3568         }
3569
3570         if (inta & ISR_TimeOut)
3571                 write_nic_dword(dev, TimerInt, 0);
3572
3573         if (inta & ISR_TBDOK)
3574                 priv->stats.txbeacon++;
3575
3576         if (inta & ISR_TBDER)
3577                 priv->stats.txbeaconerr++;
3578
3579         if (inta & IMR_TMGDOK)
3580                 rtl8180_tx_isr(dev, MANAGE_PRIORITY, 0);
3581
3582         if (inta & ISR_THPDER) {
3583                 priv->stats.txhperr++;
3584                 rtl8180_tx_isr(dev, HI_PRIORITY, 1);
3585                 priv->ieee80211->stats.tx_errors++;
3586         }
3587
3588         if (inta & ISR_THPDOK) { /* High priority tx ok */
3589                 priv->link_detect.NumTxOkInPeriod++; /* YJ,add,080828 */
3590                 priv->stats.txhpokint++;
3591                 rtl8180_tx_isr(dev, HI_PRIORITY, 0);
3592         }
3593
3594         if (inta & ISR_RER)
3595                 priv->stats.rxerr++;
3596
3597         if (inta & ISR_TBKDER) { /* corresponding to BK_PRIORITY */
3598                 priv->stats.txbkperr++;
3599                 priv->ieee80211->stats.tx_errors++;
3600                 rtl8180_tx_isr(dev, BK_PRIORITY, 1);
3601                 rtl8180_try_wake_queue(dev, BK_PRIORITY);
3602         }
3603
3604         if (inta & ISR_TBEDER) { /* corresponding to BE_PRIORITY */
3605                 priv->stats.txbeperr++;
3606                 priv->ieee80211->stats.tx_errors++;
3607                 rtl8180_tx_isr(dev, BE_PRIORITY, 1);
3608                 rtl8180_try_wake_queue(dev, BE_PRIORITY);
3609         }
3610         if (inta & ISR_TNPDER) { /* corresponding to VO_PRIORITY */
3611                 priv->stats.txnperr++;
3612                 priv->ieee80211->stats.tx_errors++;
3613                 rtl8180_tx_isr(dev, NORM_PRIORITY, 1);
3614                 rtl8180_try_wake_queue(dev, NORM_PRIORITY);
3615         }
3616
3617         if (inta & ISR_TLPDER) { /* corresponding to VI_PRIORITY */
3618                 priv->stats.txlperr++;
3619                 priv->ieee80211->stats.tx_errors++;
3620                 rtl8180_tx_isr(dev, LOW_PRIORITY, 1);
3621                 rtl8180_try_wake_queue(dev, LOW_PRIORITY);
3622         }
3623
3624         if (inta & ISR_ROK) {
3625                 priv->stats.rxint++;
3626                 tasklet_schedule(&priv->irq_rx_tasklet);
3627         }
3628
3629         if (inta & ISR_RQoSOK) {
3630                 priv->stats.rxint++;
3631                 tasklet_schedule(&priv->irq_rx_tasklet);
3632         }
3633
3634         if (inta & ISR_BcnInt)
3635                 rtl8180_prepare_beacon(dev);
3636
3637         if (inta & ISR_RDU) {
3638                 DMESGW("No RX descriptor available");
3639                 priv->stats.rxrdu++;
3640                 tasklet_schedule(&priv->irq_rx_tasklet);
3641         }
3642
3643         if (inta & ISR_RXFOVW) {
3644                 priv->stats.rxoverflow++;
3645                 tasklet_schedule(&priv->irq_rx_tasklet);
3646         }
3647
3648         if (inta & ISR_TXFOVW)
3649                 priv->stats.txoverflow++;
3650
3651         if (inta & ISR_TNPDOK) { /* Normal priority tx ok */
3652                 priv->link_detect.NumTxOkInPeriod++; /* YJ,add,080828 */
3653                 priv->stats.txnpokint++;
3654                 rtl8180_tx_isr(dev, NORM_PRIORITY, 0);
3655                 rtl8180_try_wake_queue(dev, NORM_PRIORITY);
3656         }
3657
3658         if (inta & ISR_TLPDOK) { /* Low priority tx ok */
3659                 priv->link_detect.NumTxOkInPeriod++; /* YJ,add,080828 */
3660                 priv->stats.txlpokint++;
3661                 rtl8180_tx_isr(dev, LOW_PRIORITY, 0);
3662                 rtl8180_try_wake_queue(dev, LOW_PRIORITY);
3663         }
3664
3665         if (inta & ISR_TBKDOK) { /* corresponding to BK_PRIORITY */
3666                 priv->stats.txbkpokint++;
3667                 priv->link_detect.NumTxOkInPeriod++; /* YJ,add,080828 */
3668                 rtl8180_tx_isr(dev, BK_PRIORITY, 0);
3669                 rtl8180_try_wake_queue(dev, BE_PRIORITY);
3670         }
3671
3672         if (inta & ISR_TBEDOK) { /* corresponding to BE_PRIORITY */
3673                 priv->stats.txbeperr++;
3674                 priv->link_detect.NumTxOkInPeriod++; /* YJ,add,080828 */
3675                 rtl8180_tx_isr(dev, BE_PRIORITY, 0);
3676                 rtl8180_try_wake_queue(dev, BE_PRIORITY);
3677         }
3678         force_pci_posting(dev);
3679         spin_unlock_irqrestore(&priv->irq_th_lock, flags);
3680
3681         return IRQ_HANDLED;
3682 }
3683
3684 void rtl8180_irq_rx_tasklet(struct r8180_priv *priv)
3685 {
3686         rtl8180_rx(priv->dev);
3687 }
3688
3689 void GPIOChangeRFWorkItemCallBack(struct work_struct *work)
3690 {
3691         struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, GPIOChangeRFWorkItem.work);
3692         struct net_device *dev = ieee->dev;
3693         struct r8180_priv *priv = ieee80211_priv(dev);
3694         u8 btPSR;
3695         u8 btConfig0;
3696         RT_RF_POWER_STATE       eRfPowerStateToSet;
3697         bool bActuallySet = false;
3698
3699         char *argv[3];
3700         static char *RadioPowerPath = "/etc/acpi/events/RadioPower.sh";
3701         static char *envp[] = {"HOME=/", "TERM=linux", "PATH=/usr/bin:/bin", NULL};
3702         static int readf_count;
3703
3704         readf_count = (readf_count+1)%0xffff;
3705         /* We should turn off LED before polling FF51[4]. */
3706
3707         /* Turn off LED. */
3708         btPSR = read_nic_byte(dev, PSR);
3709         write_nic_byte(dev, PSR, (btPSR & ~BIT3));
3710
3711         /* It need to delay 4us suggested by Jong, 2008-01-16 */
3712         udelay(4);
3713
3714         /* HW radio On/Off according to the value of FF51[4](config0) */
3715         btConfig0 = btPSR = read_nic_byte(dev, CONFIG0);
3716
3717         eRfPowerStateToSet = (btConfig0 & BIT4) ?  eRfOn : eRfOff;
3718
3719         /* Turn LED back on when radio enabled */
3720         if (eRfPowerStateToSet == eRfOn)
3721                 write_nic_byte(dev, PSR, btPSR | BIT3);
3722
3723         if ((priv->ieee80211->bHwRadioOff == true) &&
3724            (eRfPowerStateToSet == eRfOn)) {
3725                 priv->ieee80211->bHwRadioOff = false;
3726                 bActuallySet = true;
3727         } else if ((priv->ieee80211->bHwRadioOff == false) &&
3728                   (eRfPowerStateToSet == eRfOff)) {
3729                 priv->ieee80211->bHwRadioOff = true;
3730                 bActuallySet = true;
3731         }
3732
3733         if (bActuallySet) {
3734                 MgntActSet_RF_State(dev, eRfPowerStateToSet, RF_CHANGE_BY_HW);
3735
3736                 /* To update the UI status for Power status changed */
3737                 if (priv->ieee80211->bHwRadioOff == true)
3738                         argv[1] = "RFOFF";
3739                 else
3740                         argv[1] = "RFON";
3741                 argv[0] = RadioPowerPath;
3742                 argv[2] = NULL;
3743
3744                 call_usermodehelper(RadioPowerPath, argv, envp, UMH_WAIT_PROC);
3745         }
3746 }
3747
3748 module_init(rtl8180_pci_module_init);
3749 module_exit(rtl8180_pci_module_exit);