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