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