]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/staging/rtl8192e/r8192E_core.c
630b1c7c8e72288f7f39ec06a71b785038c231eb
[karo-tx-linux.git] / drivers / staging / rtl8192e / r8192E_core.c
1 /******************************************************************************
2  * Copyright(c) 2008 - 2010 Realtek Corporation. All rights reserved.
3  * Linux device driver for RTL8192E
4  *
5  * Based on the r8180 driver, which is:
6  * Copyright 2004-2005 Andrea Merello <andreamrl@tiscali.it>, et al.
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of version 2 of the GNU General Public License as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
19  *
20  * The full GNU General Public License is included in this distribution in the
21  * file called LICENSE.
22  *
23  * Contact Information:
24  * Jerry chuang <wlanfae@realtek.com>
25  */
26
27 //#define CONFIG_RTL8192_IO_MAP
28 #include <linux/vmalloc.h>
29 #include <linux/slab.h>
30 #include <asm/uaccess.h>
31 #include "r8192E_hw.h"
32 #include "r8192E.h"
33 #include "r8190_rtl8256.h" /* RTL8225 Radio frontend */
34 #include "r8180_93cx6.h"   /* Card EEPROM */
35 #include "r8192E_wx.h"
36 #include "r819xE_phy.h" //added by WB 4.30.2008
37 #include "r819xE_phyreg.h"
38 #include "r819xE_cmdpkt.h"
39 #include "r8192E_dm.h"
40
41 #ifdef CONFIG_PM
42 #include "r8192_pm.h"
43 #endif
44
45 #ifdef ENABLE_DOT11D
46 #include "ieee80211/dot11d.h"
47 #endif
48
49 //set here to open your trace code. //WB
50 u32 rt_global_debug_component = COMP_ERR ; //always open err flags on
51
52 static DEFINE_PCI_DEVICE_TABLE(rtl8192_pci_id_tbl) = {
53         /* Realtek */
54         { PCI_DEVICE(0x10ec, 0x8192) },
55
56         /* Corega */
57         { PCI_DEVICE(0x07aa, 0x0044) },
58         { PCI_DEVICE(0x07aa, 0x0047) },
59         {}
60 };
61
62 static char ifname[IFNAMSIZ] = "wlan%d";
63 static int hwwep = 1; //default use hw. set 0 to use software security
64 static int channels = 0x3fff;
65
66 MODULE_LICENSE("GPL");
67 MODULE_VERSION("V 1.1");
68 MODULE_DEVICE_TABLE(pci, rtl8192_pci_id_tbl);
69 //MODULE_AUTHOR("Andrea Merello <andreamrl@tiscali.it>");
70 MODULE_DESCRIPTION("Linux driver for Realtek RTL819x WiFi cards");
71
72
73 module_param_string(ifname, ifname, sizeof(ifname), S_IRUGO|S_IWUSR);
74 module_param(hwwep,int, S_IRUGO|S_IWUSR);
75 module_param(channels,int, S_IRUGO|S_IWUSR);
76
77 MODULE_PARM_DESC(ifname," Net interface name, wlan%d=default");
78 MODULE_PARM_DESC(hwwep," Try to use hardware WEP support. Still broken and not available on all cards");
79 MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
80
81 static int __devinit rtl8192_pci_probe(struct pci_dev *pdev,
82                          const struct pci_device_id *id);
83 static void __devexit rtl8192_pci_disconnect(struct pci_dev *pdev);
84
85 static struct pci_driver rtl8192_pci_driver = {
86         .name           = RTL819xE_MODULE_NAME,           /* Driver name   */
87         .id_table       = rtl8192_pci_id_tbl,             /* PCI_ID table  */
88         .probe          = rtl8192_pci_probe,              /* probe fn      */
89         .remove         = __devexit_p(rtl8192_pci_disconnect),    /* remove fn     */
90 #ifdef CONFIG_PM
91         .suspend        = rtl8192E_suspend,               /* PM suspend fn */
92         .resume         = rtl8192E_resume,                 /* PM resume fn  */
93 #else
94         .suspend        = NULL,                           /* PM suspend fn */
95         .resume         = NULL,                           /* PM resume fn  */
96 #endif
97 };
98
99 static void rtl8192_start_beacon(struct net_device *dev);
100 static void rtl8192_stop_beacon(struct net_device *dev);
101 static void rtl819x_watchdog_wqcallback(struct work_struct *work);
102 static void rtl8192_irq_rx_tasklet(unsigned long arg);
103 static void rtl8192_irq_tx_tasklet(unsigned long arg);
104 static void rtl8192_prepare_beacon(unsigned long arg);
105 static irqreturn_t rtl8192_interrupt(int irq, void *netdev);
106 static void rtl819xE_tx_cmd(struct net_device *dev, struct sk_buff *skb);
107 static void rtl8192_update_ratr_table(struct net_device* dev);
108 static void rtl8192_restart(struct work_struct *work);
109 static void watch_dog_timer_callback(unsigned long data);
110 static int _rtl8192_up(struct net_device *dev);
111 static void rtl8192_cancel_deferred_work(struct r8192_priv* priv);
112
113 #ifdef ENABLE_DOT11D
114
115 typedef struct _CHANNEL_LIST
116 {
117         u8      Channel[32];
118         u8      Len;
119 }CHANNEL_LIST, *PCHANNEL_LIST;
120
121 static const CHANNEL_LIST ChannelPlan[] = {
122         {{1,2,3,4,5,6,7,8,9,10,11,36,40,44,48,52,56,60,64,149,153,157,161,165},24},             //FCC
123         {{1,2,3,4,5,6,7,8,9,10,11},11},                                                 //IC
124         {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //ETSI
125         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},    //Spain. Change to ETSI.
126         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //France. Change to ETSI.
127         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},        //MKK                                   //MKK
128         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},//MKK1
129         {{1,2,3,4,5,6,7,8,9,10,11,12,13},13},   //Israel.
130         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64},22},                        // For 11a , TELEC
131         {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,36,40,44,48,52,56,60,64}, 22},    //MIC
132         {{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
133 };
134
135 static void rtl819x_set_channel_map(u8 channel_plan, struct r8192_priv* priv)
136 {
137         int i, max_chan=-1, min_chan=-1;
138         struct ieee80211_device* ieee = priv->ieee80211;
139         switch (channel_plan)
140         {
141                 case COUNTRY_CODE_FCC:
142                 case COUNTRY_CODE_IC:
143                 case COUNTRY_CODE_ETSI:
144                 case COUNTRY_CODE_SPAIN:
145                 case COUNTRY_CODE_FRANCE:
146                 case COUNTRY_CODE_MKK:
147                 case COUNTRY_CODE_MKK1:
148                 case COUNTRY_CODE_ISRAEL:
149                 case COUNTRY_CODE_TELEC:
150                 case COUNTRY_CODE_MIC:
151                 {
152                         Dot11d_Init(ieee);
153                         ieee->bGlobalDomain = false;
154                         //acturally 8225 & 8256 rf chip only support B,G,24N mode
155                         min_chan = 1;
156                         max_chan = 14;
157
158                         if (ChannelPlan[channel_plan].Len != 0){
159                                 // Clear old channel map
160                                 memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
161                                 // Set new channel map
162                                 for (i=0;i<ChannelPlan[channel_plan].Len;i++)
163                                 {
164                                         if (ChannelPlan[channel_plan].Channel[i] < min_chan || ChannelPlan[channel_plan].Channel[i] > max_chan)
165                                             break;
166                                         GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
167                                 }
168                         }
169                         break;
170                 }
171                 case COUNTRY_CODE_GLOBAL_DOMAIN:
172                 {
173                         GET_DOT11D_INFO(ieee)->bEnabled = 0; //this flag enabled to follow 11d country IE setting, otherwise, it shall follow global domain setting
174                         Dot11d_Reset(ieee);
175                         ieee->bGlobalDomain = true;
176                         break;
177                 }
178                 default:
179                         break;
180         }
181 }
182 #endif
183
184 static inline bool rx_hal_is_cck_rate(prx_fwinfo_819x_pci pdrvinfo)
185 {
186         return (pdrvinfo->RxRate == DESC90_RATE1M ||
187                 pdrvinfo->RxRate == DESC90_RATE2M ||
188                 pdrvinfo->RxRate == DESC90_RATE5_5M ||
189                 pdrvinfo->RxRate == DESC90_RATE11M) &&
190                 !pdrvinfo->RxHT;
191 }
192
193 void CamResetAllEntry(struct net_device *dev)
194 {
195         struct r8192_priv* priv = ieee80211_priv(dev);
196         write_nic_dword(priv, RWCAM, BIT31|BIT30);
197 }
198
199 void write_cam(struct r8192_priv *priv, u8 addr, u32 data)
200 {
201         write_nic_dword(priv, WCAMI, data);
202         write_nic_dword(priv, RWCAM, BIT31|BIT16|(addr&0xff) );
203 }
204
205 u32 read_cam(struct r8192_priv *priv, u8 addr)
206 {
207         write_nic_dword(priv, RWCAM, 0x80000000|(addr&0xff) );
208         return read_nic_dword(priv, 0xa8);
209 }
210
211 #ifdef CONFIG_RTL8180_IO_MAP
212
213 u8 read_nic_byte(struct r8192_priv *priv, int x)
214 {
215         struct net_device *dev = priv->ieee80211->dev;
216         return 0xff&inb(dev->base_addr +x);
217 }
218
219 u32 read_nic_dword(struct r8192_priv *priv, int x)
220 {
221         struct net_device *dev = priv->ieee80211->dev;
222         return inl(dev->base_addr +x);
223 }
224
225 u16 read_nic_word(struct r8192_priv *priv, int x)
226 {
227         struct net_device *dev = priv->ieee80211->dev;
228         return inw(dev->base_addr +x);
229 }
230
231 void write_nic_byte(struct r8192_priv *priv, int x,u8 y)
232 {
233         struct net_device *dev = priv->ieee80211->dev;
234         outb(y&0xff,dev->base_addr +x);
235 }
236
237 void write_nic_word(struct r8192_priv *priv, int x,u16 y)
238 {
239         struct net_device *dev = priv->ieee80211->dev;
240         outw(y,dev->base_addr +x);
241 }
242
243 void write_nic_dword(struct r8192_priv *priv, int x,u32 y)
244 {
245         struct net_device *dev = priv->ieee80211->dev;
246         outl(y,dev->base_addr +x);
247 }
248
249 #else /* RTL_IO_MAP */
250
251 u8 read_nic_byte(struct r8192_priv *priv, int x)
252 {
253         struct net_device *dev = priv->ieee80211->dev;
254         return 0xff&readb((u8*)dev->mem_start +x);
255 }
256
257 u32 read_nic_dword(struct r8192_priv *priv, int x)
258 {
259         struct net_device *dev = priv->ieee80211->dev;
260         return readl((u8*)dev->mem_start +x);
261 }
262
263 u16 read_nic_word(struct r8192_priv *priv, int x)
264 {
265         struct net_device *dev = priv->ieee80211->dev;
266         return readw((u8*)dev->mem_start +x);
267 }
268
269 void write_nic_byte(struct r8192_priv *priv, int x,u8 y)
270 {
271         struct net_device *dev = priv->ieee80211->dev;
272         writeb(y,(u8*)dev->mem_start +x);
273         udelay(20);
274 }
275
276 void write_nic_dword(struct r8192_priv *priv, int x,u32 y)
277 {
278         struct net_device *dev = priv->ieee80211->dev;
279         writel(y,(u8*)dev->mem_start +x);
280         udelay(20);
281 }
282
283 void write_nic_word(struct r8192_priv *priv, int x,u16 y)
284 {
285         struct net_device *dev = priv->ieee80211->dev;
286         writew(y,(u8*)dev->mem_start +x);
287         udelay(20);
288 }
289
290 #endif /* RTL_IO_MAP */
291
292 u8 rtl8192e_ap_sec_type(struct ieee80211_device *ieee)
293 {
294         static const u8 ccmp_ie[4] = {0x00,0x50,0xf2,0x04};
295         static const u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
296         int wpa_ie_len= ieee->wpa_ie_len;
297         struct ieee80211_crypt_data* crypt;
298         int encrypt;
299
300         crypt = ieee->crypt[ieee->tx_keyidx];
301
302         encrypt = (ieee->current_network.capability & WLAN_CAPABILITY_PRIVACY) ||
303                   (ieee->host_encrypt && crypt && crypt->ops &&
304                    (0 == strcmp(crypt->ops->name,"WEP")));
305
306         /* simply judge  */
307         if(encrypt && (wpa_ie_len == 0)) {
308                 // wep encryption, no N mode setting */
309                 return SEC_ALG_WEP;
310         } else if((wpa_ie_len != 0)) {
311                 // parse pairwise key type */
312                 if (((ieee->wpa_ie[0] == 0xdd) && (!memcmp(&(ieee->wpa_ie[14]),ccmp_ie,4))) ||
313                                 ((ieee->wpa_ie[0] == 0x30) && (!memcmp(&ieee->wpa_ie[10],ccmp_rsn_ie, 4))))
314                         return SEC_ALG_CCMP;
315                 else
316                         return SEC_ALG_TKIP;
317         } else {
318                 return SEC_ALG_NONE;
319         }
320 }
321
322 void
323 rtl8192e_SetHwReg(struct net_device *dev,u8 variable,u8* val)
324 {
325         struct r8192_priv* priv = ieee80211_priv(dev);
326
327         switch(variable)
328         {
329
330                 case HW_VAR_BSSID:
331                         write_nic_dword(priv, BSSIDR, ((u32*)(val))[0]);
332                         write_nic_word(priv, BSSIDR+2, ((u16*)(val+2))[0]);
333                 break;
334
335                 case HW_VAR_MEDIA_STATUS:
336                 {
337                         RT_OP_MODE      OpMode = *((RT_OP_MODE *)(val));
338                         u8              btMsr = read_nic_byte(priv, MSR);
339
340                         btMsr &= 0xfc;
341
342                         switch(OpMode)
343                         {
344                         case RT_OP_MODE_INFRASTRUCTURE:
345                                 btMsr |= MSR_INFRA;
346                                 break;
347
348                         case RT_OP_MODE_IBSS:
349                                 btMsr |= MSR_ADHOC;
350                                 break;
351
352                         case RT_OP_MODE_AP:
353                                 btMsr |= MSR_AP;
354                                 break;
355
356                         default:
357                                 btMsr |= MSR_NOLINK;
358                                 break;
359                         }
360
361                         write_nic_byte(priv, MSR, btMsr);
362                 }
363                 break;
364
365                 case HW_VAR_CHECK_BSSID:
366                 {
367                         u32     RegRCR, Type;
368
369                         Type = ((u8*)(val))[0];
370                         RegRCR = read_nic_dword(priv, RCR);
371                         priv->ReceiveConfig = RegRCR;
372
373                         if (Type == true)
374                                 RegRCR |= (RCR_CBSSID);
375                         else if (Type == false)
376                                 RegRCR &= (~RCR_CBSSID);
377
378                         write_nic_dword(priv, RCR,RegRCR);
379                         priv->ReceiveConfig = RegRCR;
380
381                 }
382                 break;
383
384                 case HW_VAR_SLOT_TIME:
385                 {
386                         priv->slot_time = val[0];
387                         write_nic_byte(priv, SLOT_TIME, val[0]);
388
389                 }
390                 break;
391
392                 case HW_VAR_ACK_PREAMBLE:
393                 {
394                         u32 regTmp = 0;
395                         priv->short_preamble = (bool)(*(u8*)val );
396                         regTmp = priv->basic_rate;
397                         if (priv->short_preamble)
398                                 regTmp |= BRSR_AckShortPmb;
399                         write_nic_dword(priv, RRSR, regTmp);
400                 }
401                 break;
402
403                 case HW_VAR_CPU_RST:
404                         write_nic_dword(priv, CPU_GEN, ((u32*)(val))[0]);
405                 break;
406
407                 default:
408                 break;
409         }
410
411 }
412
413 static struct proc_dir_entry *rtl8192_proc = NULL;
414
415 static int proc_get_stats_ap(char *page, char **start,
416                           off_t offset, int count,
417                           int *eof, void *data)
418 {
419         struct net_device *dev = data;
420         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
421         struct ieee80211_device *ieee = priv->ieee80211;
422         struct ieee80211_network *target;
423         int len = 0;
424
425         list_for_each_entry(target, &ieee->network_list, list) {
426
427                 len += snprintf(page + len, count - len,
428                 "%s ", target->ssid);
429
430                 if(target->wpa_ie_len>0 || target->rsn_ie_len>0){
431                         len += snprintf(page + len, count - len,
432                         "WPA\n");
433                 }
434                 else{
435                         len += snprintf(page + len, count - len,
436                         "non_WPA\n");
437                 }
438
439         }
440
441         *eof = 1;
442         return len;
443 }
444
445 static int proc_get_registers(char *page, char **start,
446                           off_t offset, int count,
447                           int *eof, void *data)
448 {
449         struct net_device *dev = data;
450         struct r8192_priv *priv = ieee80211_priv(dev);
451         int len = 0;
452         int i,n;
453         int max=0xff;
454
455         /* This dump the current register page */
456         len += snprintf(page + len, count - len,
457                         "\n####################page 0##################\n ");
458
459         for(n=0;n<=max;)
460         {
461                 len += snprintf(page + len, count - len,
462                         "\nD:  %2x > ",n);
463
464                 for(i=0;i<16 && n<=max;i++,n++)
465                 len += snprintf(page + len, count - len,
466                         "%2x ",read_nic_byte(priv,n));
467         }
468         len += snprintf(page + len, count - len,"\n");
469         len += snprintf(page + len, count - len,
470                         "\n####################page 1##################\n ");
471         for(n=0;n<=max;)
472         {
473                 len += snprintf(page + len, count - len,
474                         "\nD:  %2x > ",n);
475
476                 for(i=0;i<16 && n<=max;i++,n++)
477                 len += snprintf(page + len, count - len,
478                         "%2x ",read_nic_byte(priv,0x100|n));
479         }
480
481         len += snprintf(page + len, count - len,
482                         "\n####################page 3##################\n ");
483         for(n=0;n<=max;)
484         {
485                 len += snprintf(page + len, count - len,
486                         "\nD:  %2x > ",n);
487
488                 for(i=0;i<16 && n<=max;i++,n++)
489                 len += snprintf(page + len, count - len,
490                         "%2x ",read_nic_byte(priv,0x300|n));
491         }
492
493         *eof = 1;
494         return len;
495
496 }
497
498 static int proc_get_stats_tx(char *page, char **start,
499                           off_t offset, int count,
500                           int *eof, void *data)
501 {
502         struct net_device *dev = data;
503         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
504
505         int len = 0;
506
507         len += snprintf(page + len, count - len,
508                 "TX VI priority ok int: %lu\n"
509                 "TX VO priority ok int: %lu\n"
510                 "TX BE priority ok int: %lu\n"
511                 "TX BK priority ok int: %lu\n"
512                 "TX MANAGE priority ok int: %lu\n"
513                 "TX BEACON priority ok int: %lu\n"
514                 "TX BEACON priority error int: %lu\n"
515                 "TX CMDPKT priority ok int: %lu\n"
516                 "TX queue stopped?: %d\n"
517                 "TX fifo overflow: %lu\n"
518                 "TX total data packets %lu\n"
519                 "TX total data bytes :%lu\n",
520                 priv->stats.txviokint,
521                 priv->stats.txvookint,
522                 priv->stats.txbeokint,
523                 priv->stats.txbkokint,
524                 priv->stats.txmanageokint,
525                 priv->stats.txbeaconokint,
526                 priv->stats.txbeaconerr,
527                 priv->stats.txcmdpktokint,
528                 netif_queue_stopped(dev),
529                 priv->stats.txoverflow,
530                 priv->ieee80211->stats.tx_packets,
531                 priv->ieee80211->stats.tx_bytes);
532
533         *eof = 1;
534         return len;
535 }
536
537
538
539 static int proc_get_stats_rx(char *page, char **start,
540                           off_t offset, int count,
541                           int *eof, void *data)
542 {
543         struct net_device *dev = data;
544         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
545
546         int len = 0;
547
548         len += snprintf(page + len, count - len,
549                 "RX packets: %lu\n"
550                 "RX desc err: %lu\n"
551                 "RX rx overflow error: %lu\n",
552                 priv->stats.rxint,
553                 priv->stats.rxrdu,
554                 priv->stats.rxoverflow);
555
556         *eof = 1;
557         return len;
558 }
559
560 static void rtl8192_proc_module_init(void)
561 {
562         RT_TRACE(COMP_INIT, "Initializing proc filesystem");
563         rtl8192_proc=create_proc_entry(RTL819xE_MODULE_NAME, S_IFDIR, init_net.proc_net);
564 }
565
566
567 static void rtl8192_proc_module_remove(void)
568 {
569         remove_proc_entry(RTL819xE_MODULE_NAME, init_net.proc_net);
570 }
571
572
573 static void rtl8192_proc_remove_one(struct net_device *dev)
574 {
575         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
576
577         printk("dev name=======> %s\n",dev->name);
578
579         if (priv->dir_dev) {
580                 remove_proc_entry("stats-tx", priv->dir_dev);
581                 remove_proc_entry("stats-rx", priv->dir_dev);
582                 remove_proc_entry("stats-ap", priv->dir_dev);
583                 remove_proc_entry("registers", priv->dir_dev);
584                 remove_proc_entry("wlan0", rtl8192_proc);
585                 priv->dir_dev = NULL;
586         }
587 }
588
589
590 static void rtl8192_proc_init_one(struct net_device *dev)
591 {
592         struct proc_dir_entry *e;
593         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
594         priv->dir_dev = create_proc_entry(dev->name,
595                                           S_IFDIR | S_IRUGO | S_IXUGO,
596                                           rtl8192_proc);
597         if (!priv->dir_dev) {
598                 RT_TRACE(COMP_ERR, "Unable to initialize /proc/net/rtl8192/%s\n",
599                       dev->name);
600                 return;
601         }
602         e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
603                                    priv->dir_dev, proc_get_stats_rx, dev);
604
605         if (!e) {
606                 RT_TRACE(COMP_ERR,"Unable to initialize "
607                       "/proc/net/rtl8192/%s/stats-rx\n",
608                       dev->name);
609         }
610
611
612         e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
613                                    priv->dir_dev, proc_get_stats_tx, dev);
614
615         if (!e) {
616                 RT_TRACE(COMP_ERR, "Unable to initialize "
617                       "/proc/net/rtl8192/%s/stats-tx\n",
618                       dev->name);
619         }
620
621         e = create_proc_read_entry("stats-ap", S_IFREG | S_IRUGO,
622                                    priv->dir_dev, proc_get_stats_ap, dev);
623
624         if (!e) {
625                 RT_TRACE(COMP_ERR, "Unable to initialize "
626                       "/proc/net/rtl8192/%s/stats-ap\n",
627                       dev->name);
628         }
629
630         e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
631                                    priv->dir_dev, proc_get_registers, dev);
632         if (!e) {
633                 RT_TRACE(COMP_ERR, "Unable to initialize "
634                       "/proc/net/rtl8192/%s/registers\n",
635                       dev->name);
636         }
637 }
638
639 short check_nic_enough_desc(struct net_device *dev, int prio)
640 {
641     struct r8192_priv *priv = ieee80211_priv(dev);
642     struct rtl8192_tx_ring *ring = &priv->tx_ring[prio];
643
644     /* for now we reserve two free descriptor as a safety boundary
645      * between the tail and the head
646      */
647     return (ring->entries - skb_queue_len(&ring->queue) >= 2);
648 }
649
650 static void tx_timeout(struct net_device *dev)
651 {
652         struct r8192_priv *priv = ieee80211_priv(dev);
653
654         schedule_work(&priv->reset_wq);
655         printk("TXTIMEOUT");
656 }
657
658 static void rtl8192_irq_enable(struct net_device *dev)
659 {
660         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
661         priv->irq_enabled = 1;
662         write_nic_dword(priv, INTA_MASK, priv->irq_mask);
663 }
664
665 void rtl8192_irq_disable(struct net_device *dev)
666 {
667         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
668
669         write_nic_dword(priv, INTA_MASK, 0);
670         priv->irq_enabled = 0;
671 }
672
673 void rtl8192_update_msr(struct net_device *dev)
674 {
675         struct r8192_priv *priv = ieee80211_priv(dev);
676         u8 msr;
677
678         msr  = read_nic_byte(priv, MSR);
679         msr &= ~ MSR_LINK_MASK;
680
681         /* do not change in link_state != WLAN_LINK_ASSOCIATED.
682          * msr must be updated if the state is ASSOCIATING.
683          * this is intentional and make sense for ad-hoc and
684          * master (see the create BSS/IBSS func)
685          */
686         if (priv->ieee80211->state == IEEE80211_LINKED){
687
688                 if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
689                         msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
690                 else if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
691                         msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
692                 else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
693                         msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
694
695         }else
696                 msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
697
698         write_nic_byte(priv, MSR, msr);
699 }
700
701 void rtl8192_set_chan(struct net_device *dev,short ch)
702 {
703         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
704
705         priv->chan = ch;
706
707         /* need to implement rf set channel here WB */
708
709         if (priv->rf_set_chan)
710                 priv->rf_set_chan(dev, priv->chan);
711 }
712
713 void rtl8192_rx_enable(struct net_device *dev)
714 {
715         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
716
717         write_nic_dword(priv, RDQDA,priv->rx_ring_dma);
718 }
719
720 /* the TX_DESC_BASE setting is according to the following queue index
721  *  BK_QUEUE       ===>                        0
722  *  BE_QUEUE       ===>                        1
723  *  VI_QUEUE       ===>                        2
724  *  VO_QUEUE       ===>                        3
725  *  HCCA_QUEUE     ===>                        4
726  *  TXCMD_QUEUE    ===>                        5
727  *  MGNT_QUEUE     ===>                        6
728  *  HIGH_QUEUE     ===>                        7
729  *  BEACON_QUEUE   ===>                        8
730  *  */
731 static const u32 TX_DESC_BASE[] = {BKQDA, BEQDA, VIQDA, VOQDA, HCCAQDA, CQDA, MQDA, HQDA, BQDA};
732 void rtl8192_tx_enable(struct net_device *dev)
733 {
734         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
735         u32 i;
736
737         for (i = 0; i < MAX_TX_QUEUE_COUNT; i++)
738                 write_nic_dword(priv, TX_DESC_BASE[i], priv->tx_ring[i].dma);
739
740         ieee80211_reset_queue(priv->ieee80211);
741 }
742
743
744 static void rtl8192_free_rx_ring(struct net_device *dev)
745 {
746         struct r8192_priv *priv = ieee80211_priv(dev);
747         int i;
748
749         for (i = 0; i < priv->rxringcount; i++) {
750                 struct sk_buff *skb = priv->rx_buf[i];
751                 if (!skb)
752                         continue;
753
754                 pci_unmap_single(priv->pdev,
755                                  *((dma_addr_t *)skb->cb),
756                                  priv->rxbuffersize, PCI_DMA_FROMDEVICE);
757                 kfree_skb(skb);
758         }
759
760         pci_free_consistent(priv->pdev, sizeof(*priv->rx_ring) * priv->rxringcount,
761                             priv->rx_ring, priv->rx_ring_dma);
762         priv->rx_ring = NULL;
763 }
764
765 static void rtl8192_free_tx_ring(struct net_device *dev, unsigned int prio)
766 {
767         struct r8192_priv *priv = ieee80211_priv(dev);
768         struct rtl8192_tx_ring *ring = &priv->tx_ring[prio];
769
770         while (skb_queue_len(&ring->queue)) {
771                 tx_desc_819x_pci *entry = &ring->desc[ring->idx];
772                 struct sk_buff *skb = __skb_dequeue(&ring->queue);
773
774                 pci_unmap_single(priv->pdev, le32_to_cpu(entry->TxBuffAddr),
775                                  skb->len, PCI_DMA_TODEVICE);
776                 kfree_skb(skb);
777                 ring->idx = (ring->idx + 1) % ring->entries;
778         }
779
780         pci_free_consistent(priv->pdev, sizeof(*ring->desc)*ring->entries,
781                             ring->desc, ring->dma);
782         ring->desc = NULL;
783 }
784
785 void PHY_SetRtl8192eRfOff(struct net_device* dev)
786 {
787         struct r8192_priv *priv = ieee80211_priv(dev);
788
789         //disable RF-Chip A/B
790         rtl8192_setBBreg(dev, rFPGA0_XA_RFInterfaceOE, BIT4, 0x0);
791         //analog to digital off, for power save
792         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter4, 0x300, 0x0);
793         //digital to analog off, for power save
794         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x18, 0x0);
795         //rx antenna off
796         rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0xf, 0x0);
797         //rx antenna off
798         rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0xf, 0x0);
799         //analog to digital part2 off, for power save
800         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x60, 0x0);
801         rtl8192_setBBreg(dev, rFPGA0_AnalogParameter1, 0x4, 0x0);
802         // Analog parameter!!Change bias and Lbus control.
803         write_nic_byte(priv, ANAPAR_FOR_8192PciE, 0x07);
804
805 }
806
807 void rtl8192_halt_adapter(struct net_device *dev, bool reset)
808 {
809         struct r8192_priv *priv = ieee80211_priv(dev);
810         int i;
811         u8 OpMode;
812         u32 ulRegRead;
813
814         OpMode = RT_OP_MODE_NO_LINK;
815         priv->ieee80211->SetHwRegHandler(dev, HW_VAR_MEDIA_STATUS, &OpMode);
816
817         if (!priv->ieee80211->bSupportRemoteWakeUp) {
818                 /*
819                  * disable tx/rx. In 8185 we write 0x10 (Reset bit),
820                  * but here we make reference to WMAC and wirte 0x0
821                  */
822                 write_nic_byte(priv, CMDR, 0);
823         }
824
825         mdelay(20);
826
827         if (!reset) {
828                 mdelay(150);
829
830                 priv->bHwRfOffAction = 2;
831
832                 /*
833                  * Call MgntActSet_RF_State instead to
834                  * prevent RF config race condition.
835                  */
836                 if (!priv->ieee80211->bSupportRemoteWakeUp) {
837                         PHY_SetRtl8192eRfOff(dev);
838                         ulRegRead = read_nic_dword(priv, CPU_GEN);
839                         ulRegRead |= CPU_GEN_SYSTEM_RESET;
840                         write_nic_dword(priv,CPU_GEN, ulRegRead);
841                 } else {
842                         /* for WOL */
843                         write_nic_dword(priv, WFCRC0, 0xffffffff);
844                         write_nic_dword(priv, WFCRC1, 0xffffffff);
845                         write_nic_dword(priv, WFCRC2, 0xffffffff);
846
847                         /* Write PMR register */
848                         write_nic_byte(priv, PMR, 0x5);
849                         /* Disable tx, enanble rx */
850                         write_nic_byte(priv, MacBlkCtrl, 0xa);
851                 }
852         }
853
854         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
855                 skb_queue_purge(&priv->ieee80211->skb_waitQ [i]);
856         }
857         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
858                 skb_queue_purge(&priv->ieee80211->skb_aggQ [i]);
859         }
860
861         skb_queue_purge(&priv->skb_queue);
862 }
863
864 static const u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540};
865 inline u16 rtl8192_rate2rate(short rate)
866 {
867         if (rate >11) return 0;
868         return rtl_rate[rate];
869 }
870
871 static void rtl8192_data_hard_stop(struct net_device *dev)
872 {
873 }
874
875 static void rtl8192_data_hard_resume(struct net_device *dev)
876 {
877 }
878
879 /*
880  * this function TX data frames when the ieee80211 stack requires this.
881  * It checks also if we need to stop the ieee tx queue, eventually do it
882  */
883 static void rtl8192_hard_data_xmit(struct sk_buff *skb, struct net_device *dev, int rate)
884 {
885         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
886         int ret;
887         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
888         u8 queue_index = tcb_desc->queue_index;
889
890         /* shall not be referred by command packet */
891         BUG_ON(queue_index == TXCMD_QUEUE);
892
893         if (priv->bHwRadioOff || (!priv->up))
894         {
895                 kfree_skb(skb);
896                 return;
897         }
898
899         memcpy(skb->cb, &dev, sizeof(dev));
900
901         skb_push(skb, priv->ieee80211->tx_headroom);
902         ret = rtl8192_tx(dev, skb);
903         if (ret != 0) {
904                 kfree_skb(skb);
905         }
906
907         if (queue_index != MGNT_QUEUE) {
908                 priv->ieee80211->stats.tx_bytes += (skb->len - priv->ieee80211->tx_headroom);
909                 priv->ieee80211->stats.tx_packets++;
910         }
911 }
912
913 /*
914  * This is a rough attempt to TX a frame
915  * This is called by the ieee 80211 stack to TX management frames.
916  * If the ring is full packet are dropped (for data frame the queue
917  * is stopped before this can happen).
918  */
919 static int rtl8192_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
920 {
921         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
922         int ret;
923         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
924         u8 queue_index = tcb_desc->queue_index;
925
926         if (queue_index != TXCMD_QUEUE) {
927                 if (priv->bHwRadioOff || (!priv->up))
928                 {
929                         kfree_skb(skb);
930                         return 0;
931                 }
932         }
933
934         memcpy(skb->cb, &dev, sizeof(dev));
935         if (queue_index == TXCMD_QUEUE) {
936                 rtl819xE_tx_cmd(dev, skb);
937                 ret = 0;
938                 return ret;
939         } else {
940                 tcb_desc->RATRIndex = 7;
941                 tcb_desc->bTxDisableRateFallBack = 1;
942                 tcb_desc->bTxUseDriverAssingedRate = 1;
943                 tcb_desc->bTxEnableFwCalcDur = 1;
944                 skb_push(skb, priv->ieee80211->tx_headroom);
945                 ret = rtl8192_tx(dev, skb);
946                 if (ret != 0) {
947                         kfree_skb(skb);
948                 }
949         }
950
951         return ret;
952 }
953
954
955 static void rtl8192_tx_isr(struct net_device *dev, int prio)
956 {
957         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
958         struct rtl8192_tx_ring *ring = &priv->tx_ring[prio];
959
960         while (skb_queue_len(&ring->queue)) {
961                 tx_desc_819x_pci *entry = &ring->desc[ring->idx];
962                 struct sk_buff *skb;
963
964                 /*
965                  * beacon packet will only use the first descriptor defaultly,
966                  * and the OWN may not be cleared by the hardware
967                  */
968                 if (prio != BEACON_QUEUE) {
969                         if (entry->OWN)
970                                 return;
971                         ring->idx = (ring->idx + 1) % ring->entries;
972                 }
973
974                 skb = __skb_dequeue(&ring->queue);
975                 pci_unmap_single(priv->pdev, le32_to_cpu(entry->TxBuffAddr),
976                                  skb->len, PCI_DMA_TODEVICE);
977
978                 kfree_skb(skb);
979         }
980
981         if (prio != BEACON_QUEUE) {
982                 /* try to deal with the pending packets  */
983                 tasklet_schedule(&priv->irq_tx_tasklet);
984         }
985 }
986
987 static void rtl8192_stop_beacon(struct net_device *dev)
988 {
989 }
990
991 static void rtl8192_config_rate(struct net_device* dev, u16* rate_config)
992 {
993          struct r8192_priv *priv = ieee80211_priv(dev);
994          struct ieee80211_network *net;
995          u8 i=0, basic_rate = 0;
996          net = & priv->ieee80211->current_network;
997
998          for (i=0; i<net->rates_len; i++)
999          {
1000                  basic_rate = net->rates[i]&0x7f;
1001                  switch(basic_rate)
1002                  {
1003                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1004                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1005                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1006                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1007                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1008                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1009                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1010                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1011                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1012                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1013                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1014                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1015                  }
1016          }
1017          for (i=0; i<net->rates_ex_len; i++)
1018          {
1019                  basic_rate = net->rates_ex[i]&0x7f;
1020                  switch(basic_rate)
1021                  {
1022                          case MGN_1M:   *rate_config |= RRSR_1M;        break;
1023                          case MGN_2M:   *rate_config |= RRSR_2M;        break;
1024                          case MGN_5_5M: *rate_config |= RRSR_5_5M;      break;
1025                          case MGN_11M:  *rate_config |= RRSR_11M;       break;
1026                          case MGN_6M:   *rate_config |= RRSR_6M;        break;
1027                          case MGN_9M:   *rate_config |= RRSR_9M;        break;
1028                          case MGN_12M:  *rate_config |= RRSR_12M;       break;
1029                          case MGN_18M:  *rate_config |= RRSR_18M;       break;
1030                          case MGN_24M:  *rate_config |= RRSR_24M;       break;
1031                          case MGN_36M:  *rate_config |= RRSR_36M;       break;
1032                          case MGN_48M:  *rate_config |= RRSR_48M;       break;
1033                          case MGN_54M:  *rate_config |= RRSR_54M;       break;
1034                  }
1035          }
1036 }
1037
1038
1039 #define SHORT_SLOT_TIME 9
1040 #define NON_SHORT_SLOT_TIME 20
1041
1042 static void rtl8192_update_cap(struct net_device* dev, u16 cap)
1043 {
1044         u32 tmp = 0;
1045         struct r8192_priv *priv = ieee80211_priv(dev);
1046         struct ieee80211_network *net = &priv->ieee80211->current_network;
1047         priv->short_preamble = cap & WLAN_CAPABILITY_SHORT_PREAMBLE;
1048         tmp = priv->basic_rate;
1049         if (priv->short_preamble)
1050                 tmp |= BRSR_AckShortPmb;
1051         write_nic_dword(priv, RRSR, tmp);
1052
1053         if (net->mode & (IEEE_G|IEEE_N_24G))
1054         {
1055                 u8 slot_time = 0;
1056                 if ((cap & WLAN_CAPABILITY_SHORT_SLOT)&&(!priv->ieee80211->pHTInfo->bCurrentRT2RTLongSlotTime))
1057                 {//short slot time
1058                         slot_time = SHORT_SLOT_TIME;
1059                 }
1060                 else //long slot time
1061                         slot_time = NON_SHORT_SLOT_TIME;
1062                 priv->slot_time = slot_time;
1063                 write_nic_byte(priv, SLOT_TIME, slot_time);
1064         }
1065
1066 }
1067
1068 static void rtl8192_net_update(struct net_device *dev)
1069 {
1070         struct r8192_priv *priv = ieee80211_priv(dev);
1071         struct ieee80211_network *net;
1072         u16 BcnTimeCfg = 0, BcnCW = 6, BcnIFS = 0xf;
1073         u16 rate_config = 0;
1074         net = &priv->ieee80211->current_network;
1075
1076         /* update Basic rate: RR, BRSR */
1077         rtl8192_config_rate(dev, &rate_config);
1078
1079         /*
1080          * Select RRSR (in Legacy-OFDM and CCK)
1081          * For 8190, we select only 24M, 12M, 6M, 11M, 5.5M,
1082          * 2M, and 1M from the Basic rate.
1083          * We do not use other rates.
1084          */
1085         priv->basic_rate = rate_config &= 0x15f;
1086
1087         /* BSSID */
1088         write_nic_dword(priv, BSSIDR, ((u32 *)net->bssid)[0]);
1089         write_nic_word(priv, BSSIDR+4, ((u16 *)net->bssid)[2]);
1090
1091         if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
1092         {
1093                 write_nic_word(priv, ATIMWND, 2);
1094                 write_nic_word(priv, BCN_DMATIME, 256);
1095                 write_nic_word(priv, BCN_INTERVAL, net->beacon_interval);
1096                 /*
1097                  * BIT15 of BCN_DRV_EARLY_INT will indicate
1098                  * whether software beacon or hw beacon is applied.
1099                  */
1100                 write_nic_word(priv, BCN_DRV_EARLY_INT, 10);
1101                 write_nic_byte(priv, BCN_ERR_THRESH, 100);
1102
1103                 BcnTimeCfg |= (BcnCW<<BCN_TCFG_CW_SHIFT);
1104                 /* TODO: BcnIFS may required to be changed on ASIC */
1105                 BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
1106                 write_nic_word(priv, BCN_TCFG, BcnTimeCfg);
1107         }
1108 }
1109
1110 void rtl819xE_tx_cmd(struct net_device *dev, struct sk_buff *skb)
1111 {
1112     struct r8192_priv *priv = ieee80211_priv(dev);
1113     struct rtl8192_tx_ring *ring;
1114     tx_desc_819x_pci *entry;
1115     unsigned int idx;
1116     dma_addr_t mapping;
1117     cb_desc *tcb_desc;
1118     unsigned long flags;
1119
1120     ring = &priv->tx_ring[TXCMD_QUEUE];
1121     mapping = pci_map_single(priv->pdev, skb->data, skb->len, PCI_DMA_TODEVICE);
1122
1123     spin_lock_irqsave(&priv->irq_th_lock,flags);
1124     idx = (ring->idx + skb_queue_len(&ring->queue)) % ring->entries;
1125     entry = &ring->desc[idx];
1126
1127     tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1128     memset(entry,0,12);
1129     entry->LINIP = tcb_desc->bLastIniPkt;
1130     entry->FirstSeg = 1;//first segment
1131     entry->LastSeg = 1; //last segment
1132     if(tcb_desc->bCmdOrInit == DESC_PACKET_TYPE_INIT) {
1133         entry->CmdInit = DESC_PACKET_TYPE_INIT;
1134     } else {
1135         entry->CmdInit = DESC_PACKET_TYPE_NORMAL;
1136         entry->Offset = sizeof(TX_FWINFO_8190PCI) + 8;
1137         entry->PktSize = (u16)(tcb_desc->pkt_size + entry->Offset);
1138         entry->QueueSelect = QSLT_CMD;
1139         entry->TxFWInfoSize = 0x08;
1140         entry->RATid = (u8)DESC_PACKET_TYPE_INIT;
1141     }
1142     entry->TxBufferSize = skb->len;
1143     entry->TxBuffAddr = cpu_to_le32(mapping);
1144     entry->OWN = 1;
1145
1146     __skb_queue_tail(&ring->queue, skb);
1147     spin_unlock_irqrestore(&priv->irq_th_lock,flags);
1148
1149     write_nic_byte(priv, TPPoll, TPPoll_CQ);
1150
1151     return;
1152 }
1153
1154 /*
1155  * Mapping Software/Hardware descriptor queue id to "Queue Select Field"
1156  * in TxFwInfo data structure
1157  */
1158 static u8 MapHwQueueToFirmwareQueue(u8 QueueID)
1159 {
1160         u8 QueueSelect = 0;
1161
1162         switch (QueueID) {
1163         case BE_QUEUE:
1164                 QueueSelect = QSLT_BE;
1165                 break;
1166
1167         case BK_QUEUE:
1168                 QueueSelect = QSLT_BK;
1169                 break;
1170
1171         case VO_QUEUE:
1172                 QueueSelect = QSLT_VO;
1173                 break;
1174
1175         case VI_QUEUE:
1176                 QueueSelect = QSLT_VI;
1177                 break;
1178
1179         case MGNT_QUEUE:
1180                 QueueSelect = QSLT_MGNT;
1181                 break;
1182
1183         case BEACON_QUEUE:
1184                 QueueSelect = QSLT_BEACON;
1185                 break;
1186
1187         case TXCMD_QUEUE:
1188                 QueueSelect = QSLT_CMD;
1189                 break;
1190
1191         case HIGH_QUEUE:
1192         default:
1193                 RT_TRACE(COMP_ERR, "Impossible Queue Selection: %d\n", QueueID);
1194                 break;
1195         }
1196         return QueueSelect;
1197 }
1198
1199 static u8 MRateToHwRate8190Pci(u8 rate)
1200 {
1201         u8  ret = DESC90_RATE1M;
1202
1203         switch(rate) {
1204                 case MGN_1M:    ret = DESC90_RATE1M;            break;
1205                 case MGN_2M:    ret = DESC90_RATE2M;            break;
1206                 case MGN_5_5M:  ret = DESC90_RATE5_5M;  break;
1207                 case MGN_11M:   ret = DESC90_RATE11M;   break;
1208                 case MGN_6M:    ret = DESC90_RATE6M;            break;
1209                 case MGN_9M:    ret = DESC90_RATE9M;            break;
1210                 case MGN_12M:   ret = DESC90_RATE12M;   break;
1211                 case MGN_18M:   ret = DESC90_RATE18M;   break;
1212                 case MGN_24M:   ret = DESC90_RATE24M;   break;
1213                 case MGN_36M:   ret = DESC90_RATE36M;   break;
1214                 case MGN_48M:   ret = DESC90_RATE48M;   break;
1215                 case MGN_54M:   ret = DESC90_RATE54M;   break;
1216
1217                 // HT rate since here
1218                 case MGN_MCS0:  ret = DESC90_RATEMCS0;  break;
1219                 case MGN_MCS1:  ret = DESC90_RATEMCS1;  break;
1220                 case MGN_MCS2:  ret = DESC90_RATEMCS2;  break;
1221                 case MGN_MCS3:  ret = DESC90_RATEMCS3;  break;
1222                 case MGN_MCS4:  ret = DESC90_RATEMCS4;  break;
1223                 case MGN_MCS5:  ret = DESC90_RATEMCS5;  break;
1224                 case MGN_MCS6:  ret = DESC90_RATEMCS6;  break;
1225                 case MGN_MCS7:  ret = DESC90_RATEMCS7;  break;
1226                 case MGN_MCS8:  ret = DESC90_RATEMCS8;  break;
1227                 case MGN_MCS9:  ret = DESC90_RATEMCS9;  break;
1228                 case MGN_MCS10: ret = DESC90_RATEMCS10; break;
1229                 case MGN_MCS11: ret = DESC90_RATEMCS11; break;
1230                 case MGN_MCS12: ret = DESC90_RATEMCS12; break;
1231                 case MGN_MCS13: ret = DESC90_RATEMCS13; break;
1232                 case MGN_MCS14: ret = DESC90_RATEMCS14; break;
1233                 case MGN_MCS15: ret = DESC90_RATEMCS15; break;
1234                 case (0x80|0x20): ret = DESC90_RATEMCS32; break;
1235
1236                 default:       break;
1237         }
1238         return ret;
1239 }
1240
1241
1242 static u8 QueryIsShort(u8 TxHT, u8 TxRate, cb_desc *tcb_desc)
1243 {
1244         u8   tmp_Short;
1245
1246         tmp_Short = (TxHT==1)?((tcb_desc->bUseShortGI)?1:0):((tcb_desc->bUseShortPreamble)?1:0);
1247
1248         if(TxHT==1 && TxRate != DESC90_RATEMCS15)
1249                 tmp_Short = 0;
1250
1251         return tmp_Short;
1252 }
1253
1254 /*
1255  * The tx procedure is just as following,
1256  * skb->cb will contain all the following information,
1257  * priority, morefrag, rate, &dev.
1258  */
1259 short rtl8192_tx(struct net_device *dev, struct sk_buff* skb)
1260 {
1261         struct r8192_priv *priv = ieee80211_priv(dev);
1262         struct rtl8192_tx_ring *ring;
1263         unsigned long flags;
1264         cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE);
1265         tx_desc_819x_pci *pdesc = NULL;
1266         TX_FWINFO_8190PCI *pTxFwInfo = NULL;
1267         dma_addr_t mapping;
1268         bool multi_addr = false, broad_addr = false, uni_addr = false;
1269         u8 *pda_addr = NULL;
1270         int idx;
1271
1272         if (priv->bdisable_nic) {
1273                 RT_TRACE(COMP_ERR, "Nic is disabled! Can't tx packet len=%d qidx=%d!!!\n",
1274                          skb->len, tcb_desc->queue_index);
1275                 return skb->len;
1276         }
1277
1278 #ifdef ENABLE_LPS
1279         priv->ieee80211->bAwakePktSent = true;
1280 #endif
1281
1282         mapping = pci_map_single(priv->pdev, skb->data, skb->len, PCI_DMA_TODEVICE);
1283
1284         /* collect the tx packets statitcs */
1285         pda_addr = ((u8 *)skb->data) + sizeof(TX_FWINFO_8190PCI);
1286         if (is_multicast_ether_addr(pda_addr))
1287                 multi_addr = true;
1288         else if (is_broadcast_ether_addr(pda_addr))
1289                 broad_addr = true;
1290         else
1291                 uni_addr = true;
1292
1293         if (uni_addr)
1294                 priv->stats.txbytesunicast += (u8)(skb->len) - sizeof(TX_FWINFO_8190PCI);
1295
1296         /* fill tx firmware */
1297         pTxFwInfo = (PTX_FWINFO_8190PCI)skb->data;
1298         memset(pTxFwInfo, 0, sizeof(TX_FWINFO_8190PCI));
1299         pTxFwInfo->TxHT = (tcb_desc->data_rate&0x80) ? 1 : 0;
1300         pTxFwInfo->TxRate = MRateToHwRate8190Pci((u8)tcb_desc->data_rate);
1301         pTxFwInfo->EnableCPUDur = tcb_desc->bTxEnableFwCalcDur;
1302         pTxFwInfo->Short = QueryIsShort(pTxFwInfo->TxHT, pTxFwInfo->TxRate, tcb_desc);
1303
1304         /* Aggregation related */
1305         if (tcb_desc->bAMPDUEnable) {
1306                 pTxFwInfo->AllowAggregation = 1;
1307                 pTxFwInfo->RxMF = tcb_desc->ampdu_factor;
1308                 pTxFwInfo->RxAMD = tcb_desc->ampdu_density;
1309         } else {
1310                 pTxFwInfo->AllowAggregation = 0;
1311                 pTxFwInfo->RxMF = 0;
1312                 pTxFwInfo->RxAMD = 0;
1313         }
1314
1315         /* Protection mode related */
1316         pTxFwInfo->RtsEnable = (tcb_desc->bRTSEnable) ? 1 : 0;
1317         pTxFwInfo->CtsEnable = (tcb_desc->bCTSEnable) ? 1 : 0;
1318         pTxFwInfo->RtsSTBC = (tcb_desc->bRTSSTBC) ? 1 : 0;
1319         pTxFwInfo->RtsHT = (tcb_desc->rts_rate&0x80) ? 1 : 0;
1320         pTxFwInfo->RtsRate = MRateToHwRate8190Pci((u8)tcb_desc->rts_rate);
1321         pTxFwInfo->RtsBandwidth = 0;
1322         pTxFwInfo->RtsSubcarrier = tcb_desc->RTSSC;
1323         pTxFwInfo->RtsShort = (pTxFwInfo->RtsHT == 0) ? (tcb_desc->bRTSUseShortPreamble ? 1 : 0) : (tcb_desc->bRTSUseShortGI? 1 : 0);
1324
1325         /* Set Bandwidth and sub-channel settings. */
1326         if (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20_40) {
1327                 if (tcb_desc->bPacketBW) {
1328                         pTxFwInfo->TxBandwidth = 1;
1329                         /* use duplicated mode */
1330                         pTxFwInfo->TxSubCarrier = 0;
1331                 } else {
1332                         pTxFwInfo->TxBandwidth = 0;
1333                         pTxFwInfo->TxSubCarrier = priv->nCur40MhzPrimeSC;
1334                 }
1335         } else {
1336                 pTxFwInfo->TxBandwidth = 0;
1337                 pTxFwInfo->TxSubCarrier = 0;
1338         }
1339
1340         spin_lock_irqsave(&priv->irq_th_lock, flags);
1341         ring = &priv->tx_ring[tcb_desc->queue_index];
1342         if (tcb_desc->queue_index != BEACON_QUEUE)
1343                 idx = (ring->idx + skb_queue_len(&ring->queue)) % ring->entries;
1344         else
1345                 idx = 0;
1346
1347         pdesc = &ring->desc[idx];
1348         if ((pdesc->OWN == 1) && (tcb_desc->queue_index != BEACON_QUEUE)) {
1349                 RT_TRACE(COMP_ERR, "No more TX desc@%d, ring->idx = %d,idx = %d,%x",
1350                          tcb_desc->queue_index, ring->idx, idx, skb->len);
1351                 spin_unlock_irqrestore(&priv->irq_th_lock, flags);
1352                 return skb->len;
1353         }
1354
1355         /* fill tx descriptor */
1356         memset(pdesc, 0, 12);
1357
1358         /*DWORD 0*/
1359         pdesc->LINIP = 0;
1360         pdesc->CmdInit = 1;
1361         pdesc->Offset = sizeof(TX_FWINFO_8190PCI) + 8; /* We must add 8!! */
1362         pdesc->PktSize = (u16)skb->len-sizeof(TX_FWINFO_8190PCI);
1363
1364         /*DWORD 1*/
1365         pdesc->SecCAMID = 0;
1366         pdesc->RATid = tcb_desc->RATRIndex;
1367
1368         pdesc->NoEnc = 1;
1369         pdesc->SecType = 0x0;
1370         if (tcb_desc->bHwSec) {
1371                 switch (priv->ieee80211->pairwise_key_type) {
1372                 case KEY_TYPE_WEP40:
1373                 case KEY_TYPE_WEP104:
1374                         pdesc->SecType = 0x1;
1375                         pdesc->NoEnc = 0;
1376                         break;
1377                 case KEY_TYPE_TKIP:
1378                         pdesc->SecType = 0x2;
1379                         pdesc->NoEnc = 0;
1380                         break;
1381                 case KEY_TYPE_CCMP:
1382                         pdesc->SecType = 0x3;
1383                         pdesc->NoEnc = 0;
1384                         break;
1385                 case KEY_TYPE_NA:
1386                         pdesc->SecType = 0x0;
1387                         pdesc->NoEnc = 1;
1388                         break;
1389                 }
1390         }
1391
1392         /* Set Packet ID */
1393         pdesc->PktId = 0x0;
1394
1395         pdesc->QueueSelect = MapHwQueueToFirmwareQueue(tcb_desc->queue_index);
1396         pdesc->TxFWInfoSize = sizeof(TX_FWINFO_8190PCI);
1397
1398         pdesc->DISFB = tcb_desc->bTxDisableRateFallBack;
1399         pdesc->USERATE = tcb_desc->bTxUseDriverAssingedRate;
1400
1401         pdesc->FirstSeg = 1;
1402         pdesc->LastSeg = 1;
1403         pdesc->TxBufferSize = skb->len;
1404
1405         pdesc->TxBuffAddr = cpu_to_le32(mapping);
1406         __skb_queue_tail(&ring->queue, skb);
1407         pdesc->OWN = 1;
1408         spin_unlock_irqrestore(&priv->irq_th_lock, flags);
1409         dev->trans_start = jiffies;
1410         write_nic_word(priv, TPPoll, 0x01<<tcb_desc->queue_index);
1411         return 0;
1412 }
1413
1414 static short rtl8192_alloc_rx_desc_ring(struct net_device *dev)
1415 {
1416     struct r8192_priv *priv = ieee80211_priv(dev);
1417     rx_desc_819x_pci *entry = NULL;
1418     int i;
1419
1420     priv->rx_ring = pci_alloc_consistent(priv->pdev,
1421             sizeof(*priv->rx_ring) * priv->rxringcount, &priv->rx_ring_dma);
1422
1423     if (!priv->rx_ring || (unsigned long)priv->rx_ring & 0xFF) {
1424         RT_TRACE(COMP_ERR,"Cannot allocate RX ring\n");
1425         return -ENOMEM;
1426     }
1427
1428     memset(priv->rx_ring, 0, sizeof(*priv->rx_ring) * priv->rxringcount);
1429     priv->rx_idx = 0;
1430
1431     for (i = 0; i < priv->rxringcount; i++) {
1432         struct sk_buff *skb = dev_alloc_skb(priv->rxbuffersize);
1433         dma_addr_t *mapping;
1434         entry = &priv->rx_ring[i];
1435         if (!skb)
1436             return 0;
1437         priv->rx_buf[i] = skb;
1438         mapping = (dma_addr_t *)skb->cb;
1439         *mapping = pci_map_single(priv->pdev, skb_tail_pointer(skb),
1440                 priv->rxbuffersize, PCI_DMA_FROMDEVICE);
1441
1442         entry->BufferAddress = cpu_to_le32(*mapping);
1443
1444         entry->Length = priv->rxbuffersize;
1445         entry->OWN = 1;
1446     }
1447
1448     entry->EOR = 1;
1449     return 0;
1450 }
1451
1452 static int rtl8192_alloc_tx_desc_ring(struct net_device *dev,
1453         unsigned int prio, unsigned int entries)
1454 {
1455     struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
1456     tx_desc_819x_pci *ring;
1457     dma_addr_t dma;
1458     int i;
1459
1460     ring = pci_alloc_consistent(priv->pdev, sizeof(*ring) * entries, &dma);
1461     if (!ring || (unsigned long)ring & 0xFF) {
1462         RT_TRACE(COMP_ERR, "Cannot allocate TX ring (prio = %d)\n", prio);
1463         return -ENOMEM;
1464     }
1465
1466     memset(ring, 0, sizeof(*ring)*entries);
1467     priv->tx_ring[prio].desc = ring;
1468     priv->tx_ring[prio].dma = dma;
1469     priv->tx_ring[prio].idx = 0;
1470     priv->tx_ring[prio].entries = entries;
1471     skb_queue_head_init(&priv->tx_ring[prio].queue);
1472
1473     for (i = 0; i < entries; i++)
1474         ring[i].NextDescAddress =
1475             cpu_to_le32((u32)dma + ((i + 1) % entries) * sizeof(*ring));
1476
1477     return 0;
1478 }
1479
1480 static short rtl8192_pci_initdescring(struct net_device *dev)
1481 {
1482         u32 ret;
1483         int i;
1484         struct r8192_priv *priv = ieee80211_priv(dev);
1485
1486         ret = rtl8192_alloc_rx_desc_ring(dev);
1487         if (ret)
1488                 return ret;
1489
1490         /* general process for other queue */
1491         for (i = 0; i < MAX_TX_QUEUE_COUNT; i++) {
1492                 ret = rtl8192_alloc_tx_desc_ring(dev, i, priv->txringcount);
1493                 if (ret)
1494                         goto err_free_rings;
1495         }
1496
1497         return 0;
1498
1499 err_free_rings:
1500         rtl8192_free_rx_ring(dev);
1501         for (i = 0; i < MAX_TX_QUEUE_COUNT; i++)
1502                 if (priv->tx_ring[i].desc)
1503                         rtl8192_free_tx_ring(dev, i);
1504         return 1;
1505 }
1506
1507 static void rtl8192_pci_resetdescring(struct net_device *dev)
1508 {
1509     struct r8192_priv *priv = ieee80211_priv(dev);
1510     int i;
1511
1512     /* force the rx_idx to the first one */
1513     if(priv->rx_ring) {
1514         rx_desc_819x_pci *entry = NULL;
1515         for (i = 0; i < priv->rxringcount; i++) {
1516             entry = &priv->rx_ring[i];
1517             entry->OWN = 1;
1518         }
1519         priv->rx_idx = 0;
1520     }
1521
1522     /* after reset, release previous pending packet, and force the
1523      * tx idx to the first one */
1524     for (i = 0; i < MAX_TX_QUEUE_COUNT; i++) {
1525         if (priv->tx_ring[i].desc) {
1526             struct rtl8192_tx_ring *ring = &priv->tx_ring[i];
1527
1528             while (skb_queue_len(&ring->queue)) {
1529                 tx_desc_819x_pci *entry = &ring->desc[ring->idx];
1530                 struct sk_buff *skb = __skb_dequeue(&ring->queue);
1531
1532                 pci_unmap_single(priv->pdev, le32_to_cpu(entry->TxBuffAddr),
1533                         skb->len, PCI_DMA_TODEVICE);
1534                 kfree_skb(skb);
1535                 ring->idx = (ring->idx + 1) % ring->entries;
1536             }
1537             ring->idx = 0;
1538         }
1539     }
1540 }
1541
1542 static void rtl8192_link_change(struct net_device *dev)
1543 {
1544         struct r8192_priv *priv = ieee80211_priv(dev);
1545         struct ieee80211_device* ieee = priv->ieee80211;
1546
1547         if (ieee->state == IEEE80211_LINKED)
1548         {
1549                 rtl8192_net_update(dev);
1550                 rtl8192_update_ratr_table(dev);
1551
1552                 //add this as in pure N mode, wep encryption will use software way, but there is no chance to set this as wep will not set group key in wext. WB.2008.07.08
1553                 if ((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type))
1554                 EnableHWSecurityConfig8192(dev);
1555         }
1556         else
1557         {
1558                 write_nic_byte(priv, 0x173, 0);
1559         }
1560
1561         rtl8192_update_msr(dev);
1562
1563         // 2007/10/16 MH MAC Will update TSF according to all received beacon, so we have
1564         //      // To set CBSSID bit when link with any AP or STA.
1565         if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC)
1566         {
1567                 u32 reg = 0;
1568                 reg = read_nic_dword(priv, RCR);
1569                 if (priv->ieee80211->state == IEEE80211_LINKED)
1570                         priv->ReceiveConfig = reg |= RCR_CBSSID;
1571                 else
1572                         priv->ReceiveConfig = reg &= ~RCR_CBSSID;
1573                 write_nic_dword(priv, RCR, reg);
1574         }
1575 }
1576
1577
1578 static const struct ieee80211_qos_parameters def_qos_parameters = {
1579         {3,3,3,3},/* cw_min */
1580         {7,7,7,7},/* cw_max */
1581         {2,2,2,2},/* aifs */
1582         {0,0,0,0},/* flags */
1583         {0,0,0,0} /* tx_op_limit */
1584 };
1585
1586 static void rtl8192_update_beacon(struct work_struct * work)
1587 {
1588         struct r8192_priv *priv = container_of(work, struct r8192_priv, update_beacon_wq.work);
1589         struct net_device *dev = priv->ieee80211->dev;
1590         struct ieee80211_device* ieee = priv->ieee80211;
1591         struct ieee80211_network* net = &ieee->current_network;
1592
1593         if (ieee->pHTInfo->bCurrentHTSupport)
1594                 HTUpdateSelfAndPeerSetting(ieee, net);
1595         ieee->pHTInfo->bCurrentRT2RTLongSlotTime = net->bssht.bdRT2RTLongSlotTime;
1596         rtl8192_update_cap(dev, net->capability);
1597 }
1598
1599 /*
1600 * background support to run QoS activate functionality
1601 */
1602 static const int WDCAPARA_ADD[] = {EDCAPARA_BE,EDCAPARA_BK,EDCAPARA_VI,EDCAPARA_VO};
1603 static void rtl8192_qos_activate(struct work_struct * work)
1604 {
1605         struct r8192_priv *priv = container_of(work, struct r8192_priv, qos_activate);
1606         struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
1607         u8 mode = priv->ieee80211->current_network.mode;
1608         u8  u1bAIFS;
1609         u32 u4bAcParam;
1610         int i;
1611
1612         mutex_lock(&priv->mutex);
1613         if(priv->ieee80211->state != IEEE80211_LINKED)
1614                 goto success;
1615         RT_TRACE(COMP_QOS,"qos active process with associate response received\n");
1616         /* It better set slot time at first */
1617         /* For we just support b/g mode at present, let the slot time at 9/20 selection */
1618         /* update the ac parameter to related registers */
1619         for(i = 0; i <  QOS_QUEUE_NUM; i++) {
1620                 //Mode G/A: slotTimeTimer = 9; Mode B: 20
1621                 u1bAIFS = qos_parameters->aifs[i] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
1622                 u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[i]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
1623                                 (((u32)(qos_parameters->cw_max[i]))<< AC_PARAM_ECW_MAX_OFFSET)|
1624                                 (((u32)(qos_parameters->cw_min[i]))<< AC_PARAM_ECW_MIN_OFFSET)|
1625                                 ((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
1626                 write_nic_dword(priv, WDCAPARA_ADD[i], u4bAcParam);
1627         }
1628
1629 success:
1630         mutex_unlock(&priv->mutex);
1631 }
1632
1633 static int rtl8192_qos_handle_probe_response(struct r8192_priv *priv,
1634                 int active_network,
1635                 struct ieee80211_network *network)
1636 {
1637         int ret = 0;
1638         u32 size = sizeof(struct ieee80211_qos_parameters);
1639
1640         if(priv->ieee80211->state !=IEEE80211_LINKED)
1641                 return ret;
1642
1643         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
1644                 return ret;
1645
1646         if (network->flags & NETWORK_HAS_QOS_MASK) {
1647                 if (active_network &&
1648                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS))
1649                         network->qos_data.active = network->qos_data.supported;
1650
1651                 if ((network->qos_data.active == 1) && (active_network == 1) &&
1652                                 (network->flags & NETWORK_HAS_QOS_PARAMETERS) &&
1653                                 (network->qos_data.old_param_count !=
1654                                  network->qos_data.param_count)) {
1655                         network->qos_data.old_param_count =
1656                                 network->qos_data.param_count;
1657                         queue_work(priv->priv_wq, &priv->qos_activate);
1658                         RT_TRACE (COMP_QOS, "QoS parameters change call "
1659                                         "qos_activate\n");
1660                 }
1661         } else {
1662                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,
1663                        &def_qos_parameters, size);
1664
1665                 if ((network->qos_data.active == 1) && (active_network == 1)) {
1666                         queue_work(priv->priv_wq, &priv->qos_activate);
1667                         RT_TRACE(COMP_QOS, "QoS was disabled call qos_activate \n");
1668                 }
1669                 network->qos_data.active = 0;
1670                 network->qos_data.supported = 0;
1671         }
1672
1673         return 0;
1674 }
1675
1676 /* handle manage frame frame beacon and probe response */
1677 static int rtl8192_handle_beacon(struct net_device * dev,
1678                               struct ieee80211_beacon * beacon,
1679                               struct ieee80211_network * network)
1680 {
1681         struct r8192_priv *priv = ieee80211_priv(dev);
1682
1683         rtl8192_qos_handle_probe_response(priv,1,network);
1684
1685         queue_delayed_work(priv->priv_wq, &priv->update_beacon_wq, 0);
1686         return 0;
1687
1688 }
1689
1690 /*
1691  * handling the beaconing responses. if we get different QoS setting
1692  * off the network from the associated setting, adjust the QoS setting
1693  */
1694 static int rtl8192_qos_association_resp(struct r8192_priv *priv,
1695                                     struct ieee80211_network *network)
1696 {
1697         int ret = 0;
1698         unsigned long flags;
1699         u32 size = sizeof(struct ieee80211_qos_parameters);
1700         int set_qos_param = 0;
1701
1702         if ((priv == NULL) || (network == NULL))
1703                 return ret;
1704
1705         if (priv->ieee80211->state != IEEE80211_LINKED)
1706                 return ret;
1707
1708         if ((priv->ieee80211->iw_mode != IW_MODE_INFRA))
1709                 return ret;
1710
1711         spin_lock_irqsave(&priv->ieee80211->lock, flags);
1712         if (network->flags & NETWORK_HAS_QOS_PARAMETERS) {
1713                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,
1714                          &network->qos_data.parameters,
1715                         sizeof(struct ieee80211_qos_parameters));
1716                 priv->ieee80211->current_network.qos_data.active = 1;
1717                 set_qos_param = 1;
1718                 /* update qos parameter for current network */
1719                 priv->ieee80211->current_network.qos_data.old_param_count =
1720                         priv->ieee80211->current_network.qos_data.param_count;
1721                 priv->ieee80211->current_network.qos_data.param_count =
1722                         network->qos_data.param_count;
1723
1724         } else {
1725                 memcpy(&priv->ieee80211->current_network.qos_data.parameters,
1726                        &def_qos_parameters, size);
1727                 priv->ieee80211->current_network.qos_data.active = 0;
1728                 priv->ieee80211->current_network.qos_data.supported = 0;
1729                 set_qos_param = 1;
1730         }
1731
1732         spin_unlock_irqrestore(&priv->ieee80211->lock, flags);
1733
1734         RT_TRACE(COMP_QOS, "%s: network->flags = %d,%d\n", __FUNCTION__,
1735                 network->flags, priv->ieee80211->current_network.qos_data.active);
1736         if (set_qos_param == 1)
1737                 queue_work(priv->priv_wq, &priv->qos_activate);
1738
1739         return ret;
1740 }
1741
1742
1743 static int rtl8192_handle_assoc_response(struct net_device *dev,
1744                                      struct ieee80211_assoc_response_frame *resp,
1745                                      struct ieee80211_network *network)
1746 {
1747         struct r8192_priv *priv = ieee80211_priv(dev);
1748         rtl8192_qos_association_resp(priv, network);
1749         return 0;
1750 }
1751
1752
1753 /* updateRATRTabel for MCS only. Basic rate is not implemented. */
1754 static void rtl8192_update_ratr_table(struct net_device* dev)
1755 {
1756         struct r8192_priv* priv = ieee80211_priv(dev);
1757         struct ieee80211_device* ieee = priv->ieee80211;
1758         u8* pMcsRate = ieee->dot11HTOperationalRateSet;
1759         u32 ratr_value = 0;
1760         u8 rate_index = 0;
1761
1762         rtl8192_config_rate(dev, (u16*)(&ratr_value));
1763         ratr_value |= (*(u16*)(pMcsRate)) << 12;
1764
1765         switch (ieee->mode)
1766         {
1767                 case IEEE_A:
1768                         ratr_value &= 0x00000FF0;
1769                         break;
1770                 case IEEE_B:
1771                         ratr_value &= 0x0000000F;
1772                         break;
1773                 case IEEE_G:
1774                         ratr_value &= 0x00000FF7;
1775                         break;
1776                 case IEEE_N_24G:
1777                 case IEEE_N_5G:
1778                         if (ieee->pHTInfo->PeerMimoPs == 0) //MIMO_PS_STATIC
1779                                 ratr_value &= 0x0007F007;
1780                         else{
1781                                 if (priv->rf_type == RF_1T2R)
1782                                         ratr_value &= 0x000FF007;
1783                                 else
1784                                         ratr_value &= 0x0F81F007;
1785                         }
1786                         break;
1787                 default:
1788                         break;
1789         }
1790         ratr_value &= 0x0FFFFFFF;
1791         if(ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI40MHz){
1792                 ratr_value |= 0x80000000;
1793         }else if(!ieee->pHTInfo->bCurTxBW40MHz && ieee->pHTInfo->bCurShortGI20MHz){
1794                 ratr_value |= 0x80000000;
1795         }
1796         write_nic_dword(priv, RATR0+rate_index*4, ratr_value);
1797         write_nic_byte(priv, UFWP, 1);
1798 }
1799
1800 static bool GetNmodeSupportBySecCfg8190Pci(struct net_device*dev)
1801 {
1802         struct r8192_priv *priv = ieee80211_priv(dev);
1803         struct ieee80211_device *ieee = priv->ieee80211;
1804
1805         return !(ieee->rtllib_ap_sec_type &&
1806                  (ieee->rtllib_ap_sec_type(ieee)&(SEC_ALG_WEP|SEC_ALG_TKIP)));
1807 }
1808
1809 static void rtl8192_refresh_supportrate(struct r8192_priv* priv)
1810 {
1811         struct ieee80211_device* ieee = priv->ieee80211;
1812         //we donot consider set support rate for ABG mode, only HT MCS rate is set here.
1813         if (ieee->mode == WIRELESS_MODE_N_24G || ieee->mode == WIRELESS_MODE_N_5G)
1814         {
1815                 memcpy(ieee->Regdot11HTOperationalRateSet, ieee->RegHTSuppRateSet, 16);
1816         }
1817         else
1818                 memset(ieee->Regdot11HTOperationalRateSet, 0, 16);
1819 }
1820
1821 static u8 rtl8192_getSupportedWireleeMode(struct net_device *dev)
1822 {
1823         return (WIRELESS_MODE_N_24G|WIRELESS_MODE_G|WIRELESS_MODE_B);
1824 }
1825
1826 static void rtl8192_SetWirelessMode(struct net_device* dev, u8 wireless_mode)
1827 {
1828         struct r8192_priv *priv = ieee80211_priv(dev);
1829         u8 bSupportMode = rtl8192_getSupportedWireleeMode(dev);
1830
1831         if ((wireless_mode == WIRELESS_MODE_AUTO) || ((wireless_mode&bSupportMode)==0))
1832         {
1833                 if(bSupportMode & WIRELESS_MODE_N_24G)
1834                 {
1835                         wireless_mode = WIRELESS_MODE_N_24G;
1836                 }
1837                 else if(bSupportMode & WIRELESS_MODE_N_5G)
1838                 {
1839                         wireless_mode = WIRELESS_MODE_N_5G;
1840                 }
1841                 else if((bSupportMode & WIRELESS_MODE_A))
1842                 {
1843                         wireless_mode = WIRELESS_MODE_A;
1844                 }
1845                 else if((bSupportMode & WIRELESS_MODE_G))
1846                 {
1847                         wireless_mode = WIRELESS_MODE_G;
1848                 }
1849                 else if((bSupportMode & WIRELESS_MODE_B))
1850                 {
1851                         wireless_mode = WIRELESS_MODE_B;
1852                 }
1853                 else{
1854                         RT_TRACE(COMP_ERR, "%s(), No valid wireless mode supported, SupportedWirelessMode(%x)!!!\n", __FUNCTION__,bSupportMode);
1855                         wireless_mode = WIRELESS_MODE_B;
1856                 }
1857         }
1858         priv->ieee80211->mode = wireless_mode;
1859
1860         if ((wireless_mode == WIRELESS_MODE_N_24G) ||  (wireless_mode == WIRELESS_MODE_N_5G))
1861                 priv->ieee80211->pHTInfo->bEnableHT = 1;
1862         else
1863                 priv->ieee80211->pHTInfo->bEnableHT = 0;
1864         RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
1865         rtl8192_refresh_supportrate(priv);
1866 }
1867
1868 static bool GetHalfNmodeSupportByAPs819xPci(struct net_device* dev)
1869 {
1870         struct r8192_priv* priv = ieee80211_priv(dev);
1871         struct ieee80211_device* ieee = priv->ieee80211;
1872
1873         return ieee->bHalfWirelessN24GMode;
1874 }
1875
1876 short rtl8192_is_tx_queue_empty(struct net_device *dev)
1877 {
1878         int i=0;
1879         struct r8192_priv *priv = ieee80211_priv(dev);
1880         for (i=0; i<=MGNT_QUEUE; i++)
1881         {
1882                 if ((i== TXCMD_QUEUE) || (i == HCCA_QUEUE) )
1883                         continue;
1884                 if (skb_queue_len(&(&priv->tx_ring[i])->queue) > 0){
1885                         printk("===>tx queue is not empty:%d, %d\n", i, skb_queue_len(&(&priv->tx_ring[i])->queue));
1886                         return 0;
1887                 }
1888         }
1889         return 1;
1890 }
1891
1892 static void rtl8192_hw_sleep_down(struct net_device *dev)
1893 {
1894         struct r8192_priv *priv = ieee80211_priv(dev);
1895         unsigned long flags = 0;
1896
1897         spin_lock_irqsave(&priv->rf_ps_lock,flags);
1898         if (priv->RFChangeInProgress) {
1899                 spin_unlock_irqrestore(&priv->rf_ps_lock,flags);
1900                 RT_TRACE(COMP_RF, "rtl8192_hw_sleep_down(): RF Change in progress! \n");
1901                 printk("rtl8192_hw_sleep_down(): RF Change in progress!\n");
1902                 return;
1903         }
1904         spin_unlock_irqrestore(&priv->rf_ps_lock,flags);
1905
1906         MgntActSet_RF_State(dev, eRfSleep, RF_CHANGE_BY_PS);
1907 }
1908
1909 static void rtl8192_hw_sleep_wq (struct work_struct *work)
1910 {
1911         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
1912         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_sleep_wq);
1913         struct net_device *dev = ieee->dev;
1914
1915         rtl8192_hw_sleep_down(dev);
1916 }
1917
1918 static void rtl8192_hw_wakeup(struct net_device* dev)
1919 {
1920         struct r8192_priv *priv = ieee80211_priv(dev);
1921         unsigned long flags = 0;
1922
1923         spin_lock_irqsave(&priv->rf_ps_lock,flags);
1924         if (priv->RFChangeInProgress) {
1925                 spin_unlock_irqrestore(&priv->rf_ps_lock,flags);
1926                 RT_TRACE(COMP_RF, "rtl8192_hw_wakeup(): RF Change in progress! \n");
1927                 printk("rtl8192_hw_wakeup(): RF Change in progress! schedule wake up task again\n");
1928                 queue_delayed_work(priv->ieee80211->wq,&priv->ieee80211->hw_wakeup_wq,MSECS(10));//PowerSave is not supported if kernel version is below 2.6.20
1929                 return;
1930         }
1931         spin_unlock_irqrestore(&priv->rf_ps_lock,flags);
1932
1933         MgntActSet_RF_State(dev, eRfOn, RF_CHANGE_BY_PS);
1934 }
1935
1936 void rtl8192_hw_wakeup_wq (struct work_struct *work)
1937 {
1938         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
1939         struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_wakeup_wq);
1940         struct net_device *dev = ieee->dev;
1941         rtl8192_hw_wakeup(dev);
1942
1943 }
1944
1945 #define MIN_SLEEP_TIME 50
1946 #define MAX_SLEEP_TIME 10000
1947 static void rtl8192_hw_to_sleep(struct net_device *dev, u32 th, u32 tl)
1948 {
1949         struct r8192_priv *priv = ieee80211_priv(dev);
1950         u32 tmp;
1951         u32 rb = jiffies;
1952
1953         spin_lock(&priv->ps_lock);
1954
1955         // Writing HW register with 0 equals to disable
1956         // the timer, that is not really what we want
1957         //
1958         tl -= MSECS(8+16+7);
1959
1960         // If the interval in witch we are requested to sleep is too
1961         // short then give up and remain awake
1962         // when we sleep after send null frame, the timer will be too short to sleep.
1963         //
1964         if(((tl>=rb)&& (tl-rb) <= MSECS(MIN_SLEEP_TIME))
1965                         ||((rb>tl)&& (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
1966                 printk("too short to sleep::%x, %x, %lx\n",tl, rb,  MSECS(MIN_SLEEP_TIME));
1967                 goto out_unlock;
1968         }
1969
1970         if(((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME)))||
1971                         ((tl < rb) && (tl>MSECS(69)) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))||
1972                         ((tl<rb)&&(tl<MSECS(69))&&((tl+0xffffffff-rb)>MSECS(MAX_SLEEP_TIME)))) {
1973                 printk("========>too long to sleep:%x, %x, %lx\n", tl, rb,  MSECS(MAX_SLEEP_TIME));
1974                 goto out_unlock;
1975         }
1976
1977         tmp = (tl>rb)?(tl-rb):(rb-tl);
1978         queue_delayed_work(priv->ieee80211->wq,
1979                            &priv->ieee80211->hw_wakeup_wq,tmp);
1980
1981         queue_delayed_work(priv->ieee80211->wq,
1982                         (void *)&priv->ieee80211->hw_sleep_wq,0);
1983 out_unlock:
1984         spin_unlock(&priv->ps_lock);
1985 }
1986
1987 static void rtl8192_init_priv_variable(struct net_device* dev)
1988 {
1989         struct r8192_priv *priv = ieee80211_priv(dev);
1990         u8 i;
1991         PRT_POWER_SAVE_CONTROL  pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
1992
1993         // Default Halt the NIC if RF is OFF.
1994         pPSC->RegRfPsLevel |= RT_RF_OFF_LEVL_HALT_NIC;
1995         pPSC->RegRfPsLevel |= RT_RF_OFF_LEVL_CLK_REQ;
1996         pPSC->RegRfPsLevel |= RT_RF_OFF_LEVL_ASPM;
1997         pPSC->RegRfPsLevel |= RT_RF_LPS_LEVEL_ASPM;
1998         pPSC->bLeisurePs = true;
1999         pPSC->RegMaxLPSAwakeIntvl = 5;
2000         priv->bHwRadioOff = false;
2001
2002         priv->being_init_adapter = false;
2003         priv->txringcount = 64;//32;
2004         priv->rxbuffersize = 9100;//2048;//1024;
2005         priv->rxringcount = MAX_RX_COUNT;//64;
2006         priv->irq_enabled=0;
2007         priv->rx_skb_complete = 1;
2008         priv->chan = 1; //set to channel 1
2009         priv->RegWirelessMode = WIRELESS_MODE_AUTO;
2010         priv->RegChannelPlan = 0xf;
2011         priv->ieee80211->mode = WIRELESS_MODE_AUTO; //SET AUTO
2012         priv->ieee80211->iw_mode = IW_MODE_INFRA;
2013         priv->ieee80211->ieee_up=0;
2014         priv->retry_rts = DEFAULT_RETRY_RTS;
2015         priv->retry_data = DEFAULT_RETRY_DATA;
2016         priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
2017         priv->ieee80211->rate = 110; //11 mbps
2018         priv->ieee80211->short_slot = 1;
2019         priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
2020         priv->bcck_in_ch14 = false;
2021         priv->CCKPresentAttentuation = 0;
2022         priv->rfa_txpowertrackingindex = 0;
2023         priv->rfc_txpowertrackingindex = 0;
2024         priv->CckPwEnl = 6;
2025         //added by amy for silent reset
2026         priv->ResetProgress = RESET_TYPE_NORESET;
2027         priv->bForcedSilentReset = 0;
2028         priv->bDisableNormalResetCheck = false;
2029         priv->force_reset = false;
2030         //added by amy for power save
2031         priv->ieee80211->RfOffReason = 0;
2032         priv->RFChangeInProgress = false;
2033         priv->bHwRfOffAction = 0;
2034         priv->SetRFPowerStateInProgress = false;
2035         priv->ieee80211->PowerSaveControl.bInactivePs = true;
2036         priv->ieee80211->PowerSaveControl.bIPSModeBackup = false;
2037
2038         priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
2039         priv->ieee80211->iw_mode = IW_MODE_INFRA;
2040         priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
2041                 IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
2042                 IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE;/* |
2043                 IEEE_SOFTMAC_BEACONS;*///added by amy 080604 //|  //IEEE_SOFTMAC_SINGLE_QUEUE;
2044
2045         priv->ieee80211->active_scan = 1;
2046         priv->ieee80211->modulation = IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
2047         priv->ieee80211->host_encrypt = 1;
2048         priv->ieee80211->host_decrypt = 1;
2049         priv->ieee80211->start_send_beacons = rtl8192_start_beacon;//+by david 081107
2050         priv->ieee80211->stop_send_beacons = rtl8192_stop_beacon;//+by david 081107
2051         priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
2052         priv->ieee80211->set_chan = rtl8192_set_chan;
2053         priv->ieee80211->link_change = rtl8192_link_change;
2054         priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
2055         priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
2056         priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
2057         priv->ieee80211->init_wmmparam_flag = 0;
2058         priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
2059         priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
2060         priv->ieee80211->tx_headroom = sizeof(TX_FWINFO_8190PCI);
2061         priv->ieee80211->qos_support = 1;
2062         priv->ieee80211->dot11PowerSaveMode = 0;
2063         priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
2064         priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
2065         priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
2066
2067         priv->ieee80211->sta_wake_up = rtl8192_hw_wakeup;
2068         priv->ieee80211->enter_sleep_state = rtl8192_hw_to_sleep;
2069         priv->ieee80211->ps_is_queue_empty = rtl8192_is_tx_queue_empty;
2070         priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8190Pci;
2071         priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
2072         priv->ieee80211->GetHalfNmodeSupportByAPsHandler = GetHalfNmodeSupportByAPs819xPci;
2073
2074         priv->ieee80211->InitialGainHandler = InitialGain819xPci;
2075
2076 #ifdef ENABLE_IPS
2077         priv->ieee80211->ieee80211_ips_leave_wq = ieee80211_ips_leave_wq;
2078         priv->ieee80211->ieee80211_ips_leave = ieee80211_ips_leave;
2079 #endif
2080 #ifdef ENABLE_LPS
2081         priv->ieee80211->LeisurePSLeave            = LeisurePSLeave;
2082 #endif
2083
2084         priv->ieee80211->SetHwRegHandler = rtl8192e_SetHwReg;
2085         priv->ieee80211->rtllib_ap_sec_type = rtl8192e_ap_sec_type;
2086
2087         priv->ShortRetryLimit = 0x30;
2088         priv->LongRetryLimit = 0x30;
2089
2090         priv->ReceiveConfig = RCR_ADD3  |
2091                 RCR_AMF | RCR_ADF |             //accept management/data
2092                 RCR_AICV |                      //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
2093                 RCR_AB | RCR_AM | RCR_APM |     //accept BC/MC/UC
2094                 RCR_AAP | ((u32)7<<RCR_MXDMA_OFFSET) |
2095                 ((u32)7 << RCR_FIFO_OFFSET) | RCR_ONLYERLPKT;
2096
2097         priv->irq_mask =        (u32)(IMR_ROK | IMR_VODOK | IMR_VIDOK | IMR_BEDOK | IMR_BKDOK |
2098                                 IMR_HCCADOK | IMR_MGNTDOK | IMR_COMDOK | IMR_HIGHDOK |
2099                                 IMR_BDOK | IMR_RXCMDOK | IMR_TIMEOUT0 | IMR_RDU | IMR_RXFOVW |
2100                                 IMR_TXFOVW | IMR_BcnInt | IMR_TBDOK | IMR_TBDER);
2101
2102         priv->pFirmware = vzalloc(sizeof(rt_firmware));
2103
2104         /* rx related queue */
2105         skb_queue_head_init(&priv->skb_queue);
2106
2107         /* Tx related queue */
2108         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
2109                 skb_queue_head_init(&priv->ieee80211->skb_waitQ [i]);
2110         }
2111         for(i = 0; i < MAX_QUEUE_SIZE; i++) {
2112                 skb_queue_head_init(&priv->ieee80211->skb_aggQ [i]);
2113         }
2114         priv->rf_set_chan = rtl8192_phy_SwChnl;
2115 }
2116
2117 static void rtl8192_init_priv_lock(struct r8192_priv* priv)
2118 {
2119         spin_lock_init(&priv->tx_lock);
2120         spin_lock_init(&priv->irq_th_lock);
2121         spin_lock_init(&priv->rf_ps_lock);
2122         spin_lock_init(&priv->ps_lock);
2123         sema_init(&priv->wx_sem,1);
2124         sema_init(&priv->rf_sem,1);
2125         mutex_init(&priv->mutex);
2126 }
2127
2128 /* init tasklet and wait_queue here */
2129 #define DRV_NAME "wlan0"
2130 static void rtl8192_init_priv_task(struct net_device* dev)
2131 {
2132         struct r8192_priv *priv = ieee80211_priv(dev);
2133
2134         priv->priv_wq = create_workqueue(DRV_NAME);
2135
2136 #ifdef ENABLE_IPS
2137         INIT_WORK(&priv->ieee80211->ips_leave_wq, IPSLeave_wq);
2138 #endif
2139
2140         INIT_WORK(&priv->reset_wq,  rtl8192_restart);
2141         INIT_DELAYED_WORK(&priv->watch_dog_wq, rtl819x_watchdog_wqcallback);
2142         INIT_DELAYED_WORK(&priv->txpower_tracking_wq,  dm_txpower_trackingcallback);
2143         INIT_DELAYED_WORK(&priv->rfpath_check_wq,  dm_rf_pathcheck_workitemcallback);
2144         INIT_DELAYED_WORK(&priv->update_beacon_wq, rtl8192_update_beacon);
2145         INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
2146         INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq, rtl8192_hw_wakeup_wq);
2147         INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq, rtl8192_hw_sleep_wq);
2148
2149         tasklet_init(&priv->irq_rx_tasklet, rtl8192_irq_rx_tasklet,
2150                      (unsigned long) priv);
2151         tasklet_init(&priv->irq_tx_tasklet, rtl8192_irq_tx_tasklet,
2152                      (unsigned long) priv);
2153         tasklet_init(&priv->irq_prepare_beacon_tasklet, rtl8192_prepare_beacon,
2154                      (unsigned long) priv);
2155 }
2156
2157 static void rtl8192_get_eeprom_size(struct net_device* dev)
2158 {
2159         u16 curCR = 0;
2160         struct r8192_priv *priv = ieee80211_priv(dev);
2161         RT_TRACE(COMP_INIT, "===========>%s()\n", __FUNCTION__);
2162         curCR = read_nic_dword(priv, EPROM_CMD);
2163         RT_TRACE(COMP_INIT, "read from Reg Cmd9346CR(%x):%x\n", EPROM_CMD, curCR);
2164         //whether need I consider BIT5?
2165         priv->epromtype = (curCR & EPROM_CMD_9356SEL) ? EPROM_93c56 : EPROM_93c46;
2166         RT_TRACE(COMP_INIT, "<===========%s(), epromtype:%d\n", __FUNCTION__, priv->epromtype);
2167 }
2168
2169 /*
2170  * Adapter->EEPROMAddressSize should be set before this function call.
2171  *  EEPROM address size can be got through GetEEPROMSize8185()
2172  */
2173 static void rtl8192_read_eeprom_info(struct r8192_priv *priv)
2174 {
2175         struct net_device *dev = priv->ieee80211->dev;
2176         u8                      tempval;
2177         u8                      ICVer8192, ICVer8256;
2178         u16                     i,usValue, IC_Version;
2179         u16                     EEPROMId;
2180         u8 bMac_Tmp_Addr[6] = {0x00, 0xe0, 0x4c, 0x00, 0x00, 0x01};
2181         RT_TRACE(COMP_INIT, "====> rtl8192_read_eeprom_info\n");
2182
2183
2184         // TODO: I don't know if we need to apply EF function to EEPROM read function
2185
2186         //2 Read EEPROM ID to make sure autoload is success
2187         EEPROMId = eprom_read(dev, 0);
2188         if( EEPROMId != RTL8190_EEPROM_ID )
2189         {
2190                 RT_TRACE(COMP_ERR, "EEPROM ID is invalid:%x, %x\n", EEPROMId, RTL8190_EEPROM_ID);
2191                 priv->AutoloadFailFlag=true;
2192         }
2193         else
2194         {
2195                 priv->AutoloadFailFlag=false;
2196         }
2197
2198         //
2199         // Assign Chip Version ID
2200         //
2201         // Read IC Version && Channel Plan
2202         if(!priv->AutoloadFailFlag)
2203         {
2204                 // VID, PID
2205                 priv->eeprom_vid = eprom_read(dev, (EEPROM_VID >> 1));
2206                 priv->eeprom_did = eprom_read(dev, (EEPROM_DID >> 1));
2207
2208                 usValue = eprom_read(dev, (u16)(EEPROM_Customer_ID>>1)) >> 8 ;
2209                 priv->eeprom_CustomerID = (u8)( usValue & 0xff);
2210                 usValue = eprom_read(dev, (EEPROM_ICVersion_ChannelPlan>>1));
2211                 priv->eeprom_ChannelPlan = usValue&0xff;
2212                 IC_Version = ((usValue&0xff00)>>8);
2213
2214                 ICVer8192 = (IC_Version&0xf);           //bit0~3; 1:A cut, 2:B cut, 3:C cut...
2215                 ICVer8256 = ((IC_Version&0xf0)>>4);//bit4~6, bit7 reserved for other RF chip; 1:A cut, 2:B cut, 3:C cut...
2216                 RT_TRACE(COMP_INIT, "\nICVer8192 = 0x%x\n", ICVer8192);
2217                 RT_TRACE(COMP_INIT, "\nICVer8256 = 0x%x\n", ICVer8256);
2218                 if(ICVer8192 == 0x2)    //B-cut
2219                 {
2220                         if(ICVer8256 == 0x5) //E-cut
2221                                 priv->card_8192_version= VERSION_8190_BE;
2222                 }
2223
2224                 switch(priv->card_8192_version)
2225                 {
2226                         case VERSION_8190_BD:
2227                         case VERSION_8190_BE:
2228                                 break;
2229                         default:
2230                                 priv->card_8192_version = VERSION_8190_BD;
2231                                 break;
2232                 }
2233                 RT_TRACE(COMP_INIT, "\nIC Version = 0x%x\n", priv->card_8192_version);
2234         }
2235         else
2236         {
2237                 priv->card_8192_version = VERSION_8190_BD;
2238                 priv->eeprom_vid = 0;
2239                 priv->eeprom_did = 0;
2240                 priv->eeprom_CustomerID = 0;
2241                 priv->eeprom_ChannelPlan = 0;
2242                 RT_TRACE(COMP_INIT, "\nIC Version = 0x%x\n", 0xff);
2243         }
2244
2245         RT_TRACE(COMP_INIT, "EEPROM VID = 0x%4x\n", priv->eeprom_vid);
2246         RT_TRACE(COMP_INIT, "EEPROM DID = 0x%4x\n", priv->eeprom_did);
2247         RT_TRACE(COMP_INIT,"EEPROM Customer ID: 0x%2x\n", priv->eeprom_CustomerID);
2248
2249         //2 Read Permanent MAC address
2250         if(!priv->AutoloadFailFlag)
2251         {
2252                 for(i = 0; i < 6; i += 2)
2253                 {
2254                         usValue = eprom_read(dev, (u16) ((EEPROM_NODE_ADDRESS_BYTE_0+i)>>1));
2255                         *(u16*)(&dev->dev_addr[i]) = usValue;
2256                 }
2257         } else {
2258                 // when auto load failed,  the last address byte set to be a random one.
2259                 // added by david woo.2007/11/7
2260                 memcpy(dev->dev_addr, bMac_Tmp_Addr, 6);
2261         }
2262
2263         RT_TRACE(COMP_INIT, "Permanent Address = %pM\n", dev->dev_addr);
2264
2265                 //2 TX Power Check EEPROM Fail or not
2266         if(priv->card_8192_version > VERSION_8190_BD) {
2267                 priv->bTXPowerDataReadFromEEPORM = true;
2268         } else {
2269                 priv->bTXPowerDataReadFromEEPORM = false;
2270         }
2271
2272         // 2007/11/15 MH 8190PCI Default=2T4R, 8192PCIE default=1T2R
2273         priv->rf_type = RTL819X_DEFAULT_RF_TYPE;
2274
2275         if(priv->card_8192_version > VERSION_8190_BD)
2276         {
2277                 // Read RF-indication and Tx Power gain index diff of legacy to HT OFDM rate.
2278                 if(!priv->AutoloadFailFlag)
2279                 {
2280                         tempval = (eprom_read(dev, (EEPROM_RFInd_PowerDiff>>1))) & 0xff;
2281                         priv->EEPROMLegacyHTTxPowerDiff = tempval & 0xf;        // bit[3:0]
2282
2283                         if (tempval&0x80)       //RF-indication, bit[7]
2284                                 priv->rf_type = RF_1T2R;
2285                         else
2286                                 priv->rf_type = RF_2T4R;
2287                 }
2288                 else
2289                 {
2290                         priv->EEPROMLegacyHTTxPowerDiff = EEPROM_Default_LegacyHTTxPowerDiff;
2291                 }
2292                 RT_TRACE(COMP_INIT, "EEPROMLegacyHTTxPowerDiff = %d\n",
2293                         priv->EEPROMLegacyHTTxPowerDiff);
2294
2295                 // Read ThermalMeter from EEPROM
2296                 if(!priv->AutoloadFailFlag)
2297                 {
2298                         priv->EEPROMThermalMeter = (u8)(((eprom_read(dev, (EEPROM_ThermalMeter>>1))) & 0xff00)>>8);
2299                 }
2300                 else
2301                 {
2302                         priv->EEPROMThermalMeter = EEPROM_Default_ThermalMeter;
2303                 }
2304                 RT_TRACE(COMP_INIT, "ThermalMeter = %d\n", priv->EEPROMThermalMeter);
2305                 //vivi, for tx power track
2306                 priv->TSSI_13dBm = priv->EEPROMThermalMeter *100;
2307
2308                 if(priv->epromtype == EPROM_93c46)
2309                 {
2310                 // Read antenna tx power offset of B/C/D to A and CrystalCap from EEPROM
2311                 if(!priv->AutoloadFailFlag)
2312                 {
2313                                 usValue = eprom_read(dev, (EEPROM_TxPwDiff_CrystalCap>>1));
2314                                 priv->EEPROMAntPwDiff = (usValue&0x0fff);
2315                                 priv->EEPROMCrystalCap = (u8)((usValue&0xf000)>>12);
2316                 }
2317                 else
2318                 {
2319                                 priv->EEPROMAntPwDiff = EEPROM_Default_AntTxPowerDiff;
2320                                 priv->EEPROMCrystalCap = EEPROM_Default_TxPwDiff_CrystalCap;
2321                 }
2322                         RT_TRACE(COMP_INIT, "EEPROMAntPwDiff = %d\n", priv->EEPROMAntPwDiff);
2323                         RT_TRACE(COMP_INIT, "EEPROMCrystalCap = %d\n", priv->EEPROMCrystalCap);
2324
2325                 //
2326                 // Get per-channel Tx Power Level
2327                 //
2328                 for(i=0; i<14; i+=2)
2329                 {
2330                         if(!priv->AutoloadFailFlag)
2331                         {
2332                                 usValue = eprom_read(dev, (u16) ((EEPROM_TxPwIndex_CCK+i)>>1) );
2333                         }
2334                         else
2335                         {
2336                                 usValue = EEPROM_Default_TxPower;
2337                         }
2338                         *((u16*)(&priv->EEPROMTxPowerLevelCCK[i])) = usValue;
2339                         RT_TRACE(COMP_INIT,"CCK Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK[i]);
2340                         RT_TRACE(COMP_INIT, "CCK Tx Power Level, Index %d = 0x%02x\n", i+1, priv->EEPROMTxPowerLevelCCK[i+1]);
2341                 }
2342                 for(i=0; i<14; i+=2)
2343                 {
2344                         if(!priv->AutoloadFailFlag)
2345                         {
2346                                 usValue = eprom_read(dev, (u16) ((EEPROM_TxPwIndex_OFDM_24G+i)>>1) );
2347                         }
2348                         else
2349                         {
2350                                 usValue = EEPROM_Default_TxPower;
2351                         }
2352                         *((u16*)(&priv->EEPROMTxPowerLevelOFDM24G[i])) = usValue;
2353                         RT_TRACE(COMP_INIT, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelOFDM24G[i]);
2354                         RT_TRACE(COMP_INIT, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i+1, priv->EEPROMTxPowerLevelOFDM24G[i+1]);
2355                 }
2356                 }
2357
2358                 //
2359                 // Update HAL variables.
2360                 //
2361                 if(priv->epromtype == EPROM_93c46)
2362                 {
2363                         for(i=0; i<14; i++)
2364                         {
2365                                 priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK[i];
2366                                 priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[i];
2367                         }
2368                         priv->LegacyHTTxPowerDiff = priv->EEPROMLegacyHTTxPowerDiff;
2369                 // Antenna B gain offset to antenna A, bit0~3
2370                         priv->AntennaTxPwDiff[0] = (priv->EEPROMAntPwDiff & 0xf);
2371                 // Antenna C gain offset to antenna A, bit4~7
2372                         priv->AntennaTxPwDiff[1] = ((priv->EEPROMAntPwDiff & 0xf0)>>4);
2373                 // Antenna D gain offset to antenna A, bit8~11
2374                         priv->AntennaTxPwDiff[2] = ((priv->EEPROMAntPwDiff & 0xf00)>>8);
2375                 // CrystalCap, bit12~15
2376                         priv->CrystalCap = priv->EEPROMCrystalCap;
2377                 // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
2378                         priv->ThermalMeter[0] = (priv->EEPROMThermalMeter & 0xf);
2379                         priv->ThermalMeter[1] = ((priv->EEPROMThermalMeter & 0xf0)>>4);
2380                 }
2381                 else if(priv->epromtype == EPROM_93c56)
2382                 {
2383                         for(i=0; i<3; i++)      // channel 1~3 use the same Tx Power Level.
2384                         {
2385                                 priv->TxPowerLevelCCK_A[i]  = priv->EEPROMRfACCKChnl1TxPwLevel[0];
2386                                 priv->TxPowerLevelOFDM24G_A[i] = priv->EEPROMRfAOfdmChnlTxPwLevel[0];
2387                                 priv->TxPowerLevelCCK_C[i] =  priv->EEPROMRfCCCKChnl1TxPwLevel[0];
2388                                 priv->TxPowerLevelOFDM24G_C[i] = priv->EEPROMRfCOfdmChnlTxPwLevel[0];
2389                         }
2390                         for(i=3; i<9; i++)      // channel 4~9 use the same Tx Power Level
2391                         {
2392                                 priv->TxPowerLevelCCK_A[i]  = priv->EEPROMRfACCKChnl1TxPwLevel[1];
2393                                 priv->TxPowerLevelOFDM24G_A[i] = priv->EEPROMRfAOfdmChnlTxPwLevel[1];
2394                                 priv->TxPowerLevelCCK_C[i] =  priv->EEPROMRfCCCKChnl1TxPwLevel[1];
2395                                 priv->TxPowerLevelOFDM24G_C[i] = priv->EEPROMRfCOfdmChnlTxPwLevel[1];
2396                         }
2397                         for(i=9; i<14; i++)     // channel 10~14 use the same Tx Power Level
2398                         {
2399                                 priv->TxPowerLevelCCK_A[i]  = priv->EEPROMRfACCKChnl1TxPwLevel[2];
2400                                 priv->TxPowerLevelOFDM24G_A[i] = priv->EEPROMRfAOfdmChnlTxPwLevel[2];
2401                                 priv->TxPowerLevelCCK_C[i] =  priv->EEPROMRfCCCKChnl1TxPwLevel[2];
2402                                 priv->TxPowerLevelOFDM24G_C[i] = priv->EEPROMRfCOfdmChnlTxPwLevel[2];
2403                         }
2404                         for(i=0; i<14; i++)
2405                                 RT_TRACE(COMP_INIT, "priv->TxPowerLevelCCK_A[%d] = 0x%x\n", i, priv->TxPowerLevelCCK_A[i]);
2406                         for(i=0; i<14; i++)
2407                                 RT_TRACE(COMP_INIT,"priv->TxPowerLevelOFDM24G_A[%d] = 0x%x\n", i, priv->TxPowerLevelOFDM24G_A[i]);
2408                         for(i=0; i<14; i++)
2409                                 RT_TRACE(COMP_INIT, "priv->TxPowerLevelCCK_C[%d] = 0x%x\n", i, priv->TxPowerLevelCCK_C[i]);
2410                         for(i=0; i<14; i++)
2411                                 RT_TRACE(COMP_INIT, "priv->TxPowerLevelOFDM24G_C[%d] = 0x%x\n", i, priv->TxPowerLevelOFDM24G_C[i]);
2412                         priv->LegacyHTTxPowerDiff = priv->EEPROMLegacyHTTxPowerDiff;
2413                         priv->AntennaTxPwDiff[0] = 0;
2414                         priv->AntennaTxPwDiff[1] = 0;
2415                         priv->AntennaTxPwDiff[2] = 0;
2416                         priv->CrystalCap = priv->EEPROMCrystalCap;
2417                         // ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
2418                         priv->ThermalMeter[0] = (priv->EEPROMThermalMeter & 0xf);
2419                         priv->ThermalMeter[1] = ((priv->EEPROMThermalMeter & 0xf0)>>4);
2420                 }
2421         }
2422
2423         if(priv->rf_type == RF_1T2R)
2424         {
2425                 RT_TRACE(COMP_INIT, "\n1T2R config\n");
2426         }
2427         else if (priv->rf_type == RF_2T4R)
2428         {
2429                 RT_TRACE(COMP_INIT, "\n2T4R config\n");
2430         }
2431
2432         // 2008/01/16 MH We can only know RF type in the function. So we have to init
2433         // DIG RATR table again.
2434         init_rate_adaptive(dev);
2435
2436         //1 Make a copy for following variables and we can change them if we want
2437
2438         if(priv->RegChannelPlan == 0xf)
2439         {
2440                 priv->ChannelPlan = priv->eeprom_ChannelPlan;
2441         }
2442         else
2443         {
2444                 priv->ChannelPlan = priv->RegChannelPlan;
2445         }
2446
2447         //
2448         //  Used PID and DID to Set CustomerID
2449         //
2450         if( priv->eeprom_vid == 0x1186 &&  priv->eeprom_did == 0x3304 )
2451         {
2452                 priv->CustomerID =  RT_CID_DLINK;
2453         }
2454
2455         switch(priv->eeprom_CustomerID)
2456         {
2457                 case EEPROM_CID_DEFAULT:
2458                         priv->CustomerID = RT_CID_DEFAULT;
2459                         break;
2460                 case EEPROM_CID_CAMEO:
2461                         priv->CustomerID = RT_CID_819x_CAMEO;
2462                         break;
2463                 case  EEPROM_CID_RUNTOP:
2464                         priv->CustomerID = RT_CID_819x_RUNTOP;
2465                         break;
2466                 case EEPROM_CID_NetCore:
2467                         priv->CustomerID = RT_CID_819x_Netcore;
2468                         break;
2469                 case EEPROM_CID_TOSHIBA:        // Merge by Jacken, 2008/01/31
2470                         priv->CustomerID = RT_CID_TOSHIBA;
2471                         if(priv->eeprom_ChannelPlan&0x80)
2472                                 priv->ChannelPlan = priv->eeprom_ChannelPlan&0x7f;
2473                         else
2474                                 priv->ChannelPlan = 0x0;
2475                         RT_TRACE(COMP_INIT, "Toshiba ChannelPlan = 0x%x\n",
2476                                 priv->ChannelPlan);
2477                         break;
2478                 case EEPROM_CID_Nettronix:
2479                         priv->CustomerID = RT_CID_Nettronix;
2480                         break;
2481                 case EEPROM_CID_Pronet:
2482                         priv->CustomerID = RT_CID_PRONET;
2483                         break;
2484                 case EEPROM_CID_DLINK:
2485                         priv->CustomerID = RT_CID_DLINK;
2486                         break;
2487
2488                 case EEPROM_CID_WHQL:
2489                         break;
2490                 default:
2491                         // value from RegCustomerID
2492                         break;
2493         }
2494
2495         //Avoid the channel plan array overflow, by Bruce, 2007-08-27.
2496         if(priv->ChannelPlan > CHANNEL_PLAN_LEN - 1)
2497                 priv->ChannelPlan = 0; //FCC
2498
2499         switch(priv->CustomerID)
2500         {
2501                 case RT_CID_DEFAULT:
2502                         priv->LedStrategy = SW_LED_MODE1;
2503                         break;
2504
2505                 case RT_CID_819x_CAMEO:
2506                         priv->LedStrategy = SW_LED_MODE2;
2507                         break;
2508
2509                 case RT_CID_819x_RUNTOP:
2510                         priv->LedStrategy = SW_LED_MODE3;
2511                         break;
2512
2513                 case RT_CID_819x_Netcore:
2514                         priv->LedStrategy = SW_LED_MODE4;
2515                         break;
2516
2517                 case RT_CID_Nettronix:
2518                         priv->LedStrategy = SW_LED_MODE5;
2519                         break;
2520
2521                 case RT_CID_PRONET:
2522                         priv->LedStrategy = SW_LED_MODE6;
2523                         break;
2524
2525                 case RT_CID_TOSHIBA:   //Modify by Jacken 2008/01/31
2526                         // Do nothing.
2527                         //break;
2528
2529                 default:
2530                         priv->LedStrategy = SW_LED_MODE1;
2531                         break;
2532         }
2533
2534
2535         if( priv->eeprom_vid == 0x1186 &&  priv->eeprom_did == 0x3304)
2536                 priv->ieee80211->bSupportRemoteWakeUp = true;
2537         else
2538                 priv->ieee80211->bSupportRemoteWakeUp = false;
2539
2540
2541         RT_TRACE(COMP_INIT, "RegChannelPlan(%d)\n", priv->RegChannelPlan);
2542         RT_TRACE(COMP_INIT, "ChannelPlan = %d \n", priv->ChannelPlan);
2543         RT_TRACE(COMP_INIT, "LedStrategy = %d \n", priv->LedStrategy);
2544         RT_TRACE(COMP_TRACE, "<==== ReadAdapterInfo\n");
2545
2546         return ;
2547 }
2548
2549
2550 static short rtl8192_get_channel_map(struct net_device * dev)
2551 {
2552         struct r8192_priv *priv = ieee80211_priv(dev);
2553 #ifdef ENABLE_DOT11D
2554         if(priv->ChannelPlan> COUNTRY_CODE_GLOBAL_DOMAIN){
2555                 printk("rtl8180_init:Error channel plan! Set to default.\n");
2556                 priv->ChannelPlan= 0;
2557         }
2558         RT_TRACE(COMP_INIT, "Channel plan is %d\n",priv->ChannelPlan);
2559
2560         rtl819x_set_channel_map(priv->ChannelPlan, priv);
2561 #else
2562         int ch,i;
2563         //Set Default Channel Plan
2564         if(!channels){
2565                 DMESG("No channels, aborting");
2566                 return -1;
2567         }
2568         ch=channels;
2569         priv->ChannelPlan= 0;//hikaru
2570          // set channels 1..14 allowed in given locale
2571         for (i=1; i<=14; i++) {
2572                 (priv->ieee80211->channel_map)[i] = (u8)(ch & 0x01);
2573                 ch >>= 1;
2574         }
2575 #endif
2576         return 0;
2577 }
2578
2579 static short rtl8192_init(struct net_device *dev)
2580 {
2581         struct r8192_priv *priv = ieee80211_priv(dev);
2582         memset(&(priv->stats),0,sizeof(struct Stats));
2583         rtl8192_init_priv_variable(dev);
2584         rtl8192_init_priv_lock(priv);
2585         rtl8192_init_priv_task(dev);
2586         rtl8192_get_eeprom_size(dev);
2587         rtl8192_read_eeprom_info(priv);
2588         rtl8192_get_channel_map(dev);
2589         init_hal_dm(dev);
2590         init_timer(&priv->watch_dog_timer);
2591         priv->watch_dog_timer.data = (unsigned long)dev;
2592         priv->watch_dog_timer.function = watch_dog_timer_callback;
2593         if (request_irq(dev->irq, rtl8192_interrupt, IRQF_SHARED, dev->name, dev)) {
2594                 printk("Error allocating IRQ %d",dev->irq);
2595                 return -1;
2596         }else{
2597                 priv->irq=dev->irq;
2598                 printk("IRQ %d",dev->irq);
2599         }
2600         if(rtl8192_pci_initdescring(dev)!=0){
2601                 printk("Endopoints initialization failed");
2602                 return -1;
2603         }
2604
2605         return 0;
2606 }
2607
2608 /*
2609  * Actually only set RRSR, RATR and BW_OPMODE registers
2610  *  not to do all the hw config as its name says
2611  * This part need to modified according to the rate set we filtered
2612  */
2613 static void rtl8192_hwconfig(struct net_device* dev)
2614 {
2615         u32 regRATR = 0, regRRSR = 0;
2616         u8 regBwOpMode = 0, regTmp = 0;
2617         struct r8192_priv *priv = ieee80211_priv(dev);
2618
2619 // Set RRSR, RATR, and BW_OPMODE registers
2620         //
2621         switch(priv->ieee80211->mode)
2622         {
2623         case WIRELESS_MODE_B:
2624                 regBwOpMode = BW_OPMODE_20MHZ;
2625                 regRATR = RATE_ALL_CCK;
2626                 regRRSR = RATE_ALL_CCK;
2627                 break;
2628         case WIRELESS_MODE_A:
2629                 regBwOpMode = BW_OPMODE_5G |BW_OPMODE_20MHZ;
2630                 regRATR = RATE_ALL_OFDM_AG;
2631                 regRRSR = RATE_ALL_OFDM_AG;
2632                 break;
2633         case WIRELESS_MODE_G:
2634                 regBwOpMode = BW_OPMODE_20MHZ;
2635                 regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2636                 regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2637                 break;
2638         case WIRELESS_MODE_AUTO:
2639         case WIRELESS_MODE_N_24G:
2640                 // It support CCK rate by default.
2641                 // CCK rate will be filtered out only when associated AP does not support it.
2642                 regBwOpMode = BW_OPMODE_20MHZ;
2643                         regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
2644                         regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2645                 break;
2646         case WIRELESS_MODE_N_5G:
2647                 regBwOpMode = BW_OPMODE_5G;
2648                 regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
2649                 regRRSR = RATE_ALL_OFDM_AG;
2650                 break;
2651         }
2652
2653         write_nic_byte(priv, BW_OPMODE, regBwOpMode);
2654         {
2655                 u32 ratr_value = 0;
2656                 ratr_value = regRATR;
2657                 if (priv->rf_type == RF_1T2R)
2658                 {
2659                         ratr_value &= ~(RATE_ALL_OFDM_2SS);
2660                 }
2661                 write_nic_dword(priv, RATR0, ratr_value);
2662                 write_nic_byte(priv, UFWP, 1);
2663         }
2664         regTmp = read_nic_byte(priv, 0x313);
2665         regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
2666         write_nic_dword(priv, RRSR, regRRSR);
2667
2668         //
2669         // Set Retry Limit here
2670         //
2671         write_nic_word(priv, RETRY_LIMIT,
2672                         priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT |
2673                         priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
2674         // Set Contention Window here
2675
2676         // Set Tx AGC
2677
2678         // Set Tx Antenna including Feedback control
2679
2680         // Set Auto Rate fallback control
2681
2682
2683 }
2684
2685
2686 static RT_STATUS rtl8192_adapter_start(struct net_device *dev)
2687 {
2688         struct r8192_priv *priv = ieee80211_priv(dev);
2689         u32 ulRegRead;
2690         RT_STATUS rtStatus = RT_STATUS_SUCCESS;
2691         u8 tmpvalue;
2692         u8 ICVersion,SwitchingRegulatorOutput;
2693         bool bfirmwareok = true;
2694         u32     tmpRegA, tmpRegC, TempCCk;
2695         int     i =0;
2696
2697         RT_TRACE(COMP_INIT, "====>%s()\n", __FUNCTION__);
2698         priv->being_init_adapter = true;
2699         rtl8192_pci_resetdescring(dev);
2700         // 2007/11/02 MH Before initalizing RF. We can not use FW to do RF-R/W.
2701         priv->Rf_Mode = RF_OP_By_SW_3wire;
2702
2703         //dPLL on
2704         if(priv->ResetProgress == RESET_TYPE_NORESET)
2705         {
2706             write_nic_byte(priv, ANAPAR, 0x37);
2707             // Accordign to designer's explain, LBUS active will never > 10ms. We delay 10ms
2708             // Joseph increae the time to prevent firmware download fail
2709             mdelay(500);
2710         }
2711
2712         //PlatformSleepUs(10000);
2713         // For any kind of InitializeAdapter process, we shall use system now!!
2714         priv->pFirmware->firmware_status = FW_STATUS_0_INIT;
2715
2716         //
2717         //3 //Config CPUReset Register
2718         //3//
2719         //3 Firmware Reset Or Not
2720         ulRegRead = read_nic_dword(priv, CPU_GEN);
2721         if(priv->pFirmware->firmware_status == FW_STATUS_0_INIT)
2722         {       //called from MPInitialized. do nothing
2723                 ulRegRead |= CPU_GEN_SYSTEM_RESET;
2724         }else if(priv->pFirmware->firmware_status == FW_STATUS_5_READY)
2725                 ulRegRead |= CPU_GEN_FIRMWARE_RESET;    // Called from MPReset
2726         else
2727                 RT_TRACE(COMP_ERR, "ERROR in %s(): undefined firmware state(%d)\n", __FUNCTION__,   priv->pFirmware->firmware_status);
2728
2729         write_nic_dword(priv, CPU_GEN, ulRegRead);
2730
2731         //3//
2732         //3 //Fix the issue of E-cut high temperature issue
2733         //3//
2734         // TODO: E cut only
2735         ICVersion = read_nic_byte(priv, IC_VERRSION);
2736         if(ICVersion >= 0x4) //E-cut only
2737         {
2738                 // HW SD suggest that we should not wirte this register too often, so driver
2739                 // should readback this register. This register will be modified only when
2740                 // power on reset
2741                 SwitchingRegulatorOutput = read_nic_byte(priv, SWREGULATOR);
2742                 if(SwitchingRegulatorOutput  != 0xb8)
2743                 {
2744                         write_nic_byte(priv, SWREGULATOR, 0xa8);
2745                         mdelay(1);
2746                         write_nic_byte(priv, SWREGULATOR, 0xb8);
2747                 }
2748         }
2749
2750         //3//
2751         //3// Initialize BB before MAC
2752         //3//
2753         RT_TRACE(COMP_INIT, "BB Config Start!\n");
2754         rtStatus = rtl8192_BBConfig(dev);
2755         if(rtStatus != RT_STATUS_SUCCESS)
2756         {
2757                 RT_TRACE(COMP_ERR, "BB Config failed\n");
2758                 return rtStatus;
2759         }
2760         RT_TRACE(COMP_INIT,"BB Config Finished!\n");
2761
2762         //3//Set Loopback mode or Normal mode
2763         //3//
2764         //2006.12.13 by emily. Note!We should not merge these two CPU_GEN register writings
2765         //      because setting of System_Reset bit reset MAC to default transmission mode.
2766                 //Loopback mode or not
2767         priv->LoopbackMode = RTL819X_NO_LOOPBACK;
2768         if(priv->ResetProgress == RESET_TYPE_NORESET)
2769         {
2770         ulRegRead = read_nic_dword(priv, CPU_GEN);
2771         if(priv->LoopbackMode == RTL819X_NO_LOOPBACK)
2772         {
2773                 ulRegRead = ((ulRegRead & CPU_GEN_NO_LOOPBACK_MSK) | CPU_GEN_NO_LOOPBACK_SET);
2774         }
2775         else if (priv->LoopbackMode == RTL819X_MAC_LOOPBACK )
2776         {
2777                 ulRegRead |= CPU_CCK_LOOPBACK;
2778         }
2779         else
2780         {
2781                 RT_TRACE(COMP_ERR,"Serious error: wrong loopback mode setting\n");
2782         }
2783
2784         //2008.06.03, for WOL
2785         //ulRegRead &= (~(CPU_GEN_GPIO_UART));
2786         write_nic_dword(priv, CPU_GEN, ulRegRead);
2787
2788         // 2006.11.29. After reset cpu, we sholud wait for a second, otherwise, it may fail to write registers. Emily
2789         udelay(500);
2790         }
2791         //3Set Hardware(Do nothing now)
2792         rtl8192_hwconfig(dev);
2793         //2=======================================================
2794         // Common Setting for all of the FPGA platform. (part 1)
2795         //2=======================================================
2796         // If there is changes, please make sure it applies to all of the FPGA version
2797         //3 Turn on Tx/Rx
2798         write_nic_byte(priv, CMDR, CR_RE|CR_TE);
2799
2800         //2Set Tx dma burst
2801         write_nic_byte(priv, PCIF, ((MXDMA2_NoLimit<<MXDMA2_RX_SHIFT) |
2802                                    (MXDMA2_NoLimit<<MXDMA2_TX_SHIFT) ));
2803
2804         //set IDR0 here
2805         write_nic_dword(priv, MAC0, ((u32*)dev->dev_addr)[0]);
2806         write_nic_word(priv, MAC4, ((u16*)(dev->dev_addr + 4))[0]);
2807         //set RCR
2808         write_nic_dword(priv, RCR, priv->ReceiveConfig);
2809
2810         //3 Initialize Number of Reserved Pages in Firmware Queue
2811                 write_nic_dword(priv, RQPN1,  NUM_OF_PAGE_IN_FW_QUEUE_BK << RSVD_FW_QUEUE_PAGE_BK_SHIFT |
2812                                         NUM_OF_PAGE_IN_FW_QUEUE_BE << RSVD_FW_QUEUE_PAGE_BE_SHIFT |
2813                                         NUM_OF_PAGE_IN_FW_QUEUE_VI << RSVD_FW_QUEUE_PAGE_VI_SHIFT |
2814                                         NUM_OF_PAGE_IN_FW_QUEUE_VO <<RSVD_FW_QUEUE_PAGE_VO_SHIFT);
2815                 write_nic_dword(priv, RQPN2, NUM_OF_PAGE_IN_FW_QUEUE_MGNT << RSVD_FW_QUEUE_PAGE_MGNT_SHIFT);
2816                 write_nic_dword(priv, RQPN3, APPLIED_RESERVED_QUEUE_IN_FW|
2817                                         NUM_OF_PAGE_IN_FW_QUEUE_BCN<<RSVD_FW_QUEUE_PAGE_BCN_SHIFT|
2818                                         NUM_OF_PAGE_IN_FW_QUEUE_PUB<<RSVD_FW_QUEUE_PAGE_PUB_SHIFT);
2819
2820         rtl8192_tx_enable(dev);
2821         rtl8192_rx_enable(dev);
2822         //3Set Response Rate Setting Register
2823         // CCK rate is supported by default.
2824         // CCK rate will be filtered out only when associated AP does not support it.
2825         ulRegRead = (0xFFF00000 & read_nic_dword(priv, RRSR))  | RATE_ALL_OFDM_AG | RATE_ALL_CCK;
2826         write_nic_dword(priv, RRSR, ulRegRead);
2827         write_nic_dword(priv, RATR0+4*7, (RATE_ALL_OFDM_AG | RATE_ALL_CCK));
2828
2829         //2Set AckTimeout
2830         // TODO: (it value is only for FPGA version). need to be changed!!2006.12.18, by Emily
2831         write_nic_byte(priv, ACK_TIMEOUT, 0x30);
2832
2833         if(priv->ResetProgress == RESET_TYPE_NORESET)
2834         rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);
2835         //-----------------------------------------------------------------------------
2836         // Set up security related. 070106, by rcnjko:
2837         // 1. Clear all H/W keys.
2838         // 2. Enable H/W encryption/decryption.
2839         //-----------------------------------------------------------------------------
2840         CamResetAllEntry(dev);
2841         {
2842                 u8 SECR_value = 0x0;
2843                 SECR_value |= SCR_TxEncEnable;
2844                 SECR_value |= SCR_RxDecEnable;
2845                 SECR_value |= SCR_NoSKMC;
2846                 write_nic_byte(priv, SECR, SECR_value);
2847         }
2848         //3Beacon related
2849         write_nic_word(priv, ATIMWND, 2);
2850         write_nic_word(priv, BCN_INTERVAL, 100);
2851         for (i=0; i<QOS_QUEUE_NUM; i++)
2852                 write_nic_dword(priv, WDCAPARA_ADD[i], 0x005e4332);
2853         //
2854         // Switching regulator controller: This is set temporarily.
2855         // It's not sure if this can be removed in the future.
2856         // PJ advised to leave it by default.
2857         //
2858         write_nic_byte(priv, 0xbe, 0xc0);
2859
2860         //2=======================================================
2861         // Set PHY related configuration defined in MAC register bank
2862         //2=======================================================
2863         rtl8192_phy_configmac(dev);
2864
2865         if (priv->card_8192_version > (u8) VERSION_8190_BD) {
2866                 rtl8192_phy_getTxPower(dev);
2867                 rtl8192_phy_setTxPower(dev, priv->chan);
2868         }
2869
2870         //if D or C cut
2871                 tmpvalue = read_nic_byte(priv, IC_VERRSION);
2872                 priv->IC_Cut = tmpvalue;
2873                 RT_TRACE(COMP_INIT, "priv->IC_Cut = 0x%x\n", priv->IC_Cut);
2874                 if(priv->IC_Cut >= IC_VersionCut_D)
2875                 {
2876                         //pHalData->bDcut = TRUE;
2877                         if(priv->IC_Cut == IC_VersionCut_D)
2878                                 RT_TRACE(COMP_INIT, "D-cut\n");
2879                         if(priv->IC_Cut == IC_VersionCut_E)
2880                         {
2881                                 RT_TRACE(COMP_INIT, "E-cut\n");
2882                                 // HW SD suggest that we should not wirte this register too often, so driver
2883                                 // should readback this register. This register will be modified only when
2884                                 // power on reset
2885                         }
2886                 }
2887                 else
2888                 {
2889                         //pHalData->bDcut = FALSE;
2890                         RT_TRACE(COMP_INIT, "Before C-cut\n");
2891                 }
2892
2893         //Firmware download
2894         RT_TRACE(COMP_INIT, "Load Firmware!\n");
2895         bfirmwareok = init_firmware(dev);
2896         if(bfirmwareok != true) {
2897                 rtStatus = RT_STATUS_FAILURE;
2898                 return rtStatus;
2899         }
2900         RT_TRACE(COMP_INIT, "Load Firmware finished!\n");
2901
2902         //RF config
2903         if(priv->ResetProgress == RESET_TYPE_NORESET)
2904         {
2905         RT_TRACE(COMP_INIT, "RF Config Started!\n");
2906         rtStatus = rtl8192_phy_RFConfig(dev);
2907         if(rtStatus != RT_STATUS_SUCCESS)
2908         {
2909                 RT_TRACE(COMP_ERR, "RF Config failed\n");
2910                         return rtStatus;
2911         }
2912         RT_TRACE(COMP_INIT, "RF Config Finished!\n");
2913         }
2914         rtl8192_phy_updateInitGain(dev);
2915
2916         /*---- Set CCK and OFDM Block "ON"----*/
2917         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
2918         rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
2919
2920         //Enable Led
2921         write_nic_byte(priv, 0x87, 0x0);
2922
2923         //2=======================================================
2924         // RF Power Save
2925         //2=======================================================
2926 #ifdef ENABLE_IPS
2927
2928 {
2929         if(priv->ieee80211->RfOffReason > RF_CHANGE_BY_PS)
2930         { // H/W or S/W RF OFF before sleep.
2931                 RT_TRACE((COMP_INIT|COMP_RF|COMP_POWER), "%s(): Turn off RF for RfOffReason(%d) ----------\n", __FUNCTION__,priv->ieee80211->RfOffReason);
2932                 MgntActSet_RF_State(dev, eRfOff, priv->ieee80211->RfOffReason);
2933         }
2934         else if(priv->ieee80211->RfOffReason >= RF_CHANGE_BY_IPS)
2935         { // H/W or S/W RF OFF before sleep.
2936                 RT_TRACE((COMP_INIT|COMP_RF|COMP_POWER), "%s(): Turn off RF for RfOffReason(%d) ----------\n", __FUNCTION__,priv->ieee80211->RfOffReason);
2937                 MgntActSet_RF_State(dev, eRfOff, priv->ieee80211->RfOffReason);
2938         }
2939         else
2940         {
2941                 RT_TRACE((COMP_INIT|COMP_RF|COMP_POWER), "%s(): RF-ON \n",__FUNCTION__);
2942                 priv->ieee80211->eRFPowerState = eRfOn;
2943                 priv->ieee80211->RfOffReason = 0;
2944         }
2945 }
2946 #endif
2947         // We can force firmware to do RF-R/W
2948         if(priv->ieee80211->FwRWRF)
2949                 priv->Rf_Mode = RF_OP_By_FW;
2950         else
2951                 priv->Rf_Mode = RF_OP_By_SW_3wire;
2952
2953         if(priv->ResetProgress == RESET_TYPE_NORESET)
2954         {
2955                 dm_initialize_txpower_tracking(dev);
2956
2957                 if(priv->IC_Cut >= IC_VersionCut_D)
2958                 {
2959                         tmpRegA= rtl8192_QueryBBReg(dev,rOFDM0_XATxIQImbalance,bMaskDWord);
2960                         tmpRegC= rtl8192_QueryBBReg(dev,rOFDM0_XCTxIQImbalance,bMaskDWord);
2961                         for(i = 0; i<TxBBGainTableLength; i++)
2962                         {
2963                                 if(tmpRegA == priv->txbbgain_table[i].txbbgain_value)
2964                                 {
2965                                         priv->rfa_txpowertrackingindex= (u8)i;
2966                                         priv->rfa_txpowertrackingindex_real= (u8)i;
2967                                         priv->rfa_txpowertracking_default = priv->rfa_txpowertrackingindex;
2968                                         break;
2969                                 }
2970                         }
2971
2972                 TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
2973
2974                 for(i=0 ; i<CCKTxBBGainTableLength ; i++)
2975                 {
2976                         if(TempCCk == priv->cck_txbbgain_table[i].ccktxbb_valuearray[0])
2977                         {
2978                                 priv->CCKPresentAttentuation_20Mdefault =(u8) i;
2979                                 break;
2980                         }
2981                 }
2982                 priv->CCKPresentAttentuation_40Mdefault = 0;
2983                 priv->CCKPresentAttentuation_difference = 0;
2984                 priv->CCKPresentAttentuation = priv->CCKPresentAttentuation_20Mdefault;
2985                         RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_initial = %d\n", priv->rfa_txpowertrackingindex);
2986                         RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_real__initial = %d\n", priv->rfa_txpowertrackingindex_real);
2987                         RT_TRACE(COMP_POWER_TRACKING, "priv->CCKPresentAttentuation_difference_initial = %d\n", priv->CCKPresentAttentuation_difference);
2988                         RT_TRACE(COMP_POWER_TRACKING, "priv->CCKPresentAttentuation_initial = %d\n", priv->CCKPresentAttentuation);
2989                         priv->btxpower_tracking = FALSE;//TEMPLY DISABLE
2990                 }
2991         }
2992
2993         rtl8192_irq_enable(dev);
2994         priv->being_init_adapter = false;
2995         return rtStatus;
2996
2997 }
2998
2999 static void rtl8192_prepare_beacon(unsigned long arg)
3000 {
3001         struct r8192_priv *priv = (struct r8192_priv*) arg;
3002         struct sk_buff *skb;
3003         //unsigned long flags;
3004         cb_desc *tcb_desc;
3005
3006         skb = ieee80211_get_beacon(priv->ieee80211);
3007         tcb_desc = (cb_desc *)(skb->cb + 8);
3008         //spin_lock_irqsave(&priv->tx_lock,flags);
3009         /* prepare misc info for the beacon xmit */
3010         tcb_desc->queue_index = BEACON_QUEUE;
3011         /* IBSS does not support HT yet, use 1M defaultly */
3012         tcb_desc->data_rate = 2;
3013         tcb_desc->RATRIndex = 7;
3014         tcb_desc->bTxDisableRateFallBack = 1;
3015         tcb_desc->bTxUseDriverAssingedRate = 1;
3016
3017         skb_push(skb, priv->ieee80211->tx_headroom);
3018         if(skb){
3019                 rtl8192_tx(priv->ieee80211->dev,skb);
3020         }
3021         //spin_unlock_irqrestore (&priv->tx_lock, flags);
3022 }
3023
3024
3025 /*
3026  * configure registers for beacon tx and enables it via
3027  * rtl8192_beacon_tx_enable(). rtl8192_beacon_tx_disable() might
3028  * be used to stop beacon transmission
3029  */
3030 static void rtl8192_start_beacon(struct net_device *dev)
3031 {
3032         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3033         struct ieee80211_network *net = &priv->ieee80211->current_network;
3034         u16 BcnTimeCfg = 0;
3035         u16 BcnCW = 6;
3036         u16 BcnIFS = 0xf;
3037
3038         DMESG("Enabling beacon TX");
3039         rtl8192_irq_disable(dev);
3040         //rtl8192_beacon_tx_enable(dev);
3041
3042         /* ATIM window */
3043         write_nic_word(priv, ATIMWND, 2);
3044
3045         /* Beacon interval (in unit of TU) */
3046         write_nic_word(priv, BCN_INTERVAL, net->beacon_interval);
3047
3048         /*
3049          * DrvErlyInt (in unit of TU).
3050          * (Time to send interrupt to notify driver to c
3051          * hange beacon content)
3052          * */
3053         write_nic_word(priv, BCN_DRV_EARLY_INT, 10);
3054
3055         /*
3056          * BcnDMATIM(in unit of us).
3057          * Indicates the time before TBTT to perform beacon queue DMA
3058          * */
3059         write_nic_word(priv, BCN_DMATIME, 256);
3060
3061         /*
3062          * Force beacon frame transmission even after receiving
3063          * beacon frame from other ad hoc STA
3064          * */
3065         write_nic_byte(priv, BCN_ERR_THRESH, 100);
3066
3067         /* Set CW and IFS */
3068         BcnTimeCfg |= BcnCW<<BCN_TCFG_CW_SHIFT;
3069         BcnTimeCfg |= BcnIFS<<BCN_TCFG_IFS;
3070         write_nic_word(priv, BCN_TCFG, BcnTimeCfg);
3071
3072
3073         /* enable the interrupt for ad-hoc process */
3074         rtl8192_irq_enable(dev);
3075 }
3076
3077 static bool HalTxCheckStuck8190Pci(struct net_device *dev)
3078 {
3079         struct r8192_priv *priv = ieee80211_priv(dev);
3080         u16 RegTxCounter = read_nic_word(priv, 0x128);
3081         bool                            bStuck = FALSE;
3082         RT_TRACE(COMP_RESET,"%s():RegTxCounter is %d,TxCounter is %d\n",__FUNCTION__,RegTxCounter,priv->TxCounter);
3083         if(priv->TxCounter==RegTxCounter)
3084                 bStuck = TRUE;
3085
3086         priv->TxCounter = RegTxCounter;
3087
3088         return bStuck;
3089 }
3090
3091 /*
3092  * Assumption: RT_TX_SPINLOCK is acquired.
3093  */
3094 static RESET_TYPE
3095 TxCheckStuck(struct net_device *dev)
3096 {
3097         struct r8192_priv *priv = ieee80211_priv(dev);
3098         u8                      ResetThreshold = NIC_SEND_HANG_THRESHOLD_POWERSAVE;
3099         bool                    bCheckFwTxCnt = false;
3100
3101         //
3102         // Decide Stuch threshold according to current power save mode
3103         //
3104         switch (priv->ieee80211->dot11PowerSaveMode)
3105         {
3106                 // The threshold value  may required to be adjusted .
3107                 case eActive:           // Active/Continuous access.
3108                         ResetThreshold = NIC_SEND_HANG_THRESHOLD_NORMAL;
3109                         break;
3110                 case eMaxPs:            // Max power save mode.
3111                         ResetThreshold = NIC_SEND_HANG_THRESHOLD_POWERSAVE;
3112                         break;
3113                 case eFastPs:   // Fast power save mode.
3114                         ResetThreshold = NIC_SEND_HANG_THRESHOLD_POWERSAVE;
3115                         break;
3116         }
3117
3118         if(bCheckFwTxCnt)
3119         {
3120                 if(HalTxCheckStuck8190Pci(dev))
3121                 {
3122                         RT_TRACE(COMP_RESET, "TxCheckStuck(): Fw indicates no Tx condition! \n");
3123                         return RESET_TYPE_SILENT;
3124                 }
3125         }
3126
3127         return RESET_TYPE_NORESET;
3128 }
3129
3130
3131 static bool HalRxCheckStuck8190Pci(struct net_device *dev)
3132 {
3133         struct r8192_priv *priv = ieee80211_priv(dev);
3134         u16 RegRxCounter = read_nic_word(priv, 0x130);
3135         bool                            bStuck = FALSE;
3136
3137         RT_TRACE(COMP_RESET,"%s(): RegRxCounter is %d,RxCounter is %d\n",__FUNCTION__,RegRxCounter,priv->RxCounter);
3138         // If rssi is small, we should check rx for long time because of bad rx.
3139         // or maybe it will continuous silent reset every 2 seconds.
3140         priv->rx_chk_cnt++;
3141         if(priv->undecorated_smoothed_pwdb >= (RateAdaptiveTH_High+5))
3142         {
3143                 priv->rx_chk_cnt = 0;   /* high rssi, check rx stuck right now. */
3144         }
3145         else if(priv->undecorated_smoothed_pwdb < (RateAdaptiveTH_High+5) &&
3146                 ((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_40M) ||
3147                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb>=RateAdaptiveTH_Low_20M)) )
3148
3149         {
3150                 if(priv->rx_chk_cnt < 2)
3151                 {
3152                         return bStuck;
3153                 }
3154                 else
3155                 {
3156                         priv->rx_chk_cnt = 0;
3157                 }
3158         }
3159         else if(((priv->CurrentChannelBW!=HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_40M) ||
3160                 (priv->CurrentChannelBW==HT_CHANNEL_WIDTH_20&&priv->undecorated_smoothed_pwdb<RateAdaptiveTH_Low_20M)) &&
3161                 priv->undecorated_smoothed_pwdb >= VeryLowRSSI)
3162         {
3163                 if(priv->rx_chk_cnt < 4)
3164                 {
3165                         return bStuck;
3166                 }
3167                 else
3168                 {
3169                         priv->rx_chk_cnt = 0;
3170                 }
3171         }
3172         else
3173         {
3174                 if(priv->rx_chk_cnt < 8)
3175                 {
3176                         return bStuck;
3177                 }
3178                 else
3179                 {
3180                         priv->rx_chk_cnt = 0;
3181                 }
3182         }
3183         if(priv->RxCounter==RegRxCounter)
3184                 bStuck = TRUE;
3185
3186         priv->RxCounter = RegRxCounter;
3187
3188         return bStuck;
3189 }
3190
3191 static RESET_TYPE RxCheckStuck(struct net_device *dev)
3192 {
3193
3194         if(HalRxCheckStuck8190Pci(dev))
3195         {
3196                 RT_TRACE(COMP_RESET, "RxStuck Condition\n");
3197                 return RESET_TYPE_SILENT;
3198         }
3199
3200         return RESET_TYPE_NORESET;
3201 }
3202
3203 static RESET_TYPE
3204 rtl819x_ifcheck_resetornot(struct net_device *dev)
3205 {
3206         struct r8192_priv *priv = ieee80211_priv(dev);
3207         RESET_TYPE      TxResetType = RESET_TYPE_NORESET;
3208         RESET_TYPE      RxResetType = RESET_TYPE_NORESET;
3209         RT_RF_POWER_STATE       rfState;
3210
3211         rfState = priv->ieee80211->eRFPowerState;
3212
3213         TxResetType = TxCheckStuck(dev);
3214
3215         if( rfState != eRfOff &&
3216                 /*ADAPTER_TEST_STATUS_FLAG(Adapter, ADAPTER_STATUS_FW_DOWNLOAD_FAILURE)) &&*/
3217                 (priv->ieee80211->iw_mode != IW_MODE_ADHOC))
3218         {
3219                 // If driver is in the status of firmware download failure , driver skips RF initialization and RF is
3220                 // in turned off state. Driver should check whether Rx stuck and do silent reset. And
3221                 // if driver is in firmware download failure status, driver should initialize RF in the following
3222                 // silent reset procedure Emily, 2008.01.21
3223
3224                 // Driver should not check RX stuck in IBSS mode because it is required to
3225                 // set Check BSSID in order to send beacon, however, if check BSSID is
3226                 // set, STA cannot hear any packet a all. Emily, 2008.04.12
3227                 RxResetType = RxCheckStuck(dev);
3228         }
3229
3230         RT_TRACE(COMP_RESET,"%s(): TxResetType is %d, RxResetType is %d\n",__FUNCTION__,TxResetType,RxResetType);
3231         if(TxResetType==RESET_TYPE_NORMAL || RxResetType==RESET_TYPE_NORMAL)
3232                 return RESET_TYPE_NORMAL;
3233         else if(TxResetType==RESET_TYPE_SILENT || RxResetType==RESET_TYPE_SILENT)
3234                 return RESET_TYPE_SILENT;
3235         else
3236                 return RESET_TYPE_NORESET;
3237
3238 }
3239
3240
3241 static void CamRestoreAllEntry(struct net_device *dev)
3242 {
3243         u8 EntryId = 0;
3244         struct r8192_priv *priv = ieee80211_priv(dev);
3245         const u8*       MacAddr = priv->ieee80211->current_network.bssid;
3246
3247         static const u8 CAM_CONST_ADDR[4][6] = {
3248                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
3249                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
3250                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
3251                 {0x00, 0x00, 0x00, 0x00, 0x00, 0x03}};
3252         static const u8 CAM_CONST_BROAD[] =
3253                 {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3254
3255         RT_TRACE(COMP_SEC, "CamRestoreAllEntry: \n");
3256
3257
3258         if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40)||
3259             (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104))
3260         {
3261
3262                 for(EntryId=0; EntryId<4; EntryId++)
3263                 {
3264                         {
3265                                 MacAddr = CAM_CONST_ADDR[EntryId];
3266                                 setKey(dev,
3267                                                 EntryId ,
3268                                                 EntryId,
3269                                                 priv->ieee80211->pairwise_key_type,
3270                                                 MacAddr,
3271                                                 0,
3272                                                 NULL);
3273                         }
3274                 }
3275
3276         }
3277         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP)
3278         {
3279
3280                 {
3281                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3282                                 setKey(dev,
3283                                                 4,
3284                                                 0,
3285                                                 priv->ieee80211->pairwise_key_type,
3286                                                 (u8*)dev->dev_addr,
3287                                                 0,
3288                                                 NULL);
3289                         else
3290                                 setKey(dev,
3291                                                 4,
3292                                                 0,
3293                                                 priv->ieee80211->pairwise_key_type,
3294                                                 MacAddr,
3295                                                 0,
3296                                                 NULL);
3297                 }
3298         }
3299         else if(priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP)
3300         {
3301
3302                 {
3303                         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3304                                 setKey(dev,
3305                                                 4,
3306                                                 0,
3307                                                 priv->ieee80211->pairwise_key_type,
3308                                                 (u8*)dev->dev_addr,
3309                                                 0,
3310                                                 NULL);
3311                         else
3312                                 setKey(dev,
3313                                                 4,
3314                                                 0,
3315                                                 priv->ieee80211->pairwise_key_type,
3316                                                 MacAddr,
3317                                                 0,
3318                                                 NULL);
3319                 }
3320         }
3321
3322
3323
3324         if(priv->ieee80211->group_key_type == KEY_TYPE_TKIP)
3325         {
3326                 MacAddr = CAM_CONST_BROAD;
3327                 for(EntryId=1 ; EntryId<4 ; EntryId++)
3328                 {
3329                         {
3330                                 setKey(dev,
3331                                                 EntryId,
3332                                                 EntryId,
3333                                                 priv->ieee80211->group_key_type,
3334                                                 MacAddr,
3335                                                 0,
3336                                                 NULL);
3337                         }
3338                 }
3339                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3340                                 setKey(dev,
3341                                                 0,
3342                                                 0,
3343                                                 priv->ieee80211->group_key_type,
3344                                                 CAM_CONST_ADDR[0],
3345                                                 0,
3346                                                 NULL);
3347         }
3348         else if(priv->ieee80211->group_key_type == KEY_TYPE_CCMP)
3349         {
3350                 MacAddr = CAM_CONST_BROAD;
3351                 for(EntryId=1; EntryId<4 ; EntryId++)
3352                 {
3353                         {
3354                                 setKey(dev,
3355                                                 EntryId ,
3356                                                 EntryId,
3357                                                 priv->ieee80211->group_key_type,
3358                                                 MacAddr,
3359                                                 0,
3360                                                 NULL);
3361                         }
3362                 }
3363
3364                 if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3365                                 setKey(dev,
3366                                                 0 ,
3367                                                 0,
3368                                                 priv->ieee80211->group_key_type,
3369                                                 CAM_CONST_ADDR[0],
3370                                                 0,
3371                                                 NULL);
3372         }
3373 }
3374
3375 /*
3376  * This function is used to fix Tx/Rx stop bug temporarily.
3377  * This function will do "system reset" to NIC when Tx or Rx is stuck.
3378  * The method checking Tx/Rx stuck of this function is supported by FW,
3379  * which reports Tx and Rx counter to register 0x128 and 0x130.
3380  */
3381 static void rtl819x_ifsilentreset(struct net_device *dev)
3382 {
3383         struct r8192_priv *priv = ieee80211_priv(dev);
3384         u8      reset_times = 0;
3385         int reset_status = 0;
3386         struct ieee80211_device *ieee = priv->ieee80211;
3387
3388
3389         return;
3390
3391         // 2007.07.20. If we need to check CCK stop, please uncomment this line.
3392         //bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter);
3393
3394         if(priv->ResetProgress==RESET_TYPE_NORESET)
3395         {
3396 RESET_START:
3397 #ifdef ENABLE_LPS
3398                 //LZM for PS-Poll AID issue. 090429
3399                 if(priv->ieee80211->state == IEEE80211_LINKED)
3400                     LeisurePSLeave(dev);
3401 #endif
3402
3403                 RT_TRACE(COMP_RESET,"=========>Reset progress!! \n");
3404
3405                 // Set the variable for reset.
3406                 priv->ResetProgress = RESET_TYPE_SILENT;
3407 //              rtl8192_close(dev);
3408
3409                 down(&priv->wx_sem);
3410                 if(priv->up == 0)
3411                 {
3412                         RT_TRACE(COMP_ERR,"%s():the driver is not up! return\n",__FUNCTION__);
3413                         up(&priv->wx_sem);
3414                         return ;
3415                 }
3416                 priv->up = 0;
3417                 RT_TRACE(COMP_RESET,"%s():======>start to down the driver\n",__FUNCTION__);
3418                 if(!netif_queue_stopped(dev))
3419                         netif_stop_queue(dev);
3420
3421                 dm_backup_dynamic_mechanism_state(dev);
3422
3423                 rtl8192_irq_disable(dev);
3424                 rtl8192_cancel_deferred_work(priv);
3425                 deinit_hal_dm(dev);
3426                 del_timer_sync(&priv->watch_dog_timer);
3427                 ieee->sync_scan_hurryup = 1;
3428                 if(ieee->state == IEEE80211_LINKED)
3429                 {
3430                         down(&ieee->wx_sem);
3431                         printk("ieee->state is IEEE80211_LINKED\n");
3432                         ieee80211_stop_send_beacons(priv->ieee80211);
3433                         del_timer_sync(&ieee->associate_timer);
3434                         cancel_delayed_work(&ieee->associate_retry_wq);
3435                         ieee80211_stop_scan(ieee);
3436                         up(&ieee->wx_sem);
3437                 }
3438                 else{
3439                         printk("ieee->state is NOT LINKED\n");
3440                         ieee80211_softmac_stop_protocol(priv->ieee80211,true);
3441                 }
3442                 rtl8192_halt_adapter(dev, true);
3443                 up(&priv->wx_sem);
3444                 RT_TRACE(COMP_RESET,"%s():<==========down process is finished\n",__FUNCTION__);
3445                 RT_TRACE(COMP_RESET,"%s():===========>start to up the driver\n",__FUNCTION__);
3446                 reset_status = _rtl8192_up(dev);
3447
3448                 RT_TRACE(COMP_RESET,"%s():<===========up process is finished\n",__FUNCTION__);
3449                 if(reset_status == -1)
3450                 {
3451                         if(reset_times < 3)
3452                         {
3453                                 reset_times++;
3454                                 goto RESET_START;
3455                         }
3456                         else
3457                         {
3458                                 RT_TRACE(COMP_ERR," ERR!!! %s():  Reset Failed!!\n",__FUNCTION__);
3459                         }
3460                 }
3461                 ieee->is_silent_reset = 1;
3462                 EnableHWSecurityConfig8192(dev);
3463                 if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
3464                 {
3465                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
3466
3467                         queue_work(ieee->wq, &ieee->associate_complete_wq);
3468
3469                 }
3470                 else if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_ADHOC)
3471                 {
3472                         ieee->set_chan(ieee->dev, ieee->current_network.channel);
3473                         ieee->link_change(ieee->dev);
3474
3475                 //      notify_wx_assoc_event(ieee);
3476
3477                         ieee80211_start_send_beacons(ieee);
3478
3479                         if (ieee->data_hard_resume)
3480                                 ieee->data_hard_resume(ieee->dev);
3481                         netif_carrier_on(ieee->dev);
3482                 }
3483
3484                 CamRestoreAllEntry(dev);
3485
3486                 // Restore the previous setting for all dynamic mechanism
3487                 dm_restore_dynamic_mechanism_state(dev);
3488
3489                 priv->ResetProgress = RESET_TYPE_NORESET;
3490                 priv->reset_count++;
3491
3492                 priv->bForcedSilentReset =false;
3493                 priv->bResetInProgress = false;
3494
3495                 // For test --> force write UFWP.
3496                 write_nic_byte(priv, UFWP, 1);
3497                 RT_TRACE(COMP_RESET, "Reset finished!! ====>[%d]\n", priv->reset_count);
3498         }
3499 }
3500
3501 #ifdef ENABLE_IPS
3502 void InactivePsWorkItemCallback(struct net_device *dev)
3503 {
3504         struct r8192_priv *priv = ieee80211_priv(dev);
3505         PRT_POWER_SAVE_CONTROL  pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
3506
3507         RT_TRACE(COMP_POWER, "InactivePsWorkItemCallback() ---------> \n");
3508         //
3509         // This flag "bSwRfProcessing", indicates the status of IPS procedure, should be set if the IPS workitem
3510         // is really scheduled.
3511         // The old code, sets this flag before scheduling the IPS workitem and however, at the same time the
3512         // previous IPS workitem did not end yet, fails to schedule the current workitem. Thus, bSwRfProcessing
3513         // blocks the IPS procedure of switching RF.
3514         // By Bruce, 2007-12-25.
3515         //
3516         pPSC->bSwRfProcessing = TRUE;
3517
3518         RT_TRACE(COMP_RF, "InactivePsWorkItemCallback(): Set RF to %s.\n",
3519                         pPSC->eInactivePowerState == eRfOff?"OFF":"ON");
3520
3521
3522         MgntActSet_RF_State(dev, pPSC->eInactivePowerState, RF_CHANGE_BY_IPS);
3523
3524         //
3525         // To solve CAM values miss in RF OFF, rewrite CAM values after RF ON. By Bruce, 2007-09-20.
3526         //
3527         pPSC->bSwRfProcessing = FALSE;
3528         RT_TRACE(COMP_POWER, "InactivePsWorkItemCallback() <--------- \n");
3529 }
3530
3531 #ifdef ENABLE_LPS
3532 /* Change current and default preamble mode. */
3533 bool MgntActSet_802_11_PowerSaveMode(struct net_device *dev,    u8 rtPsMode)
3534 {
3535         struct r8192_priv *priv = ieee80211_priv(dev);
3536
3537         // Currently, we do not change power save mode on IBSS mode.
3538         if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3539         {
3540                 return false;
3541         }
3542
3543         //
3544         // <RJ_NOTE> If we make HW to fill up the PwrMgt bit for us,
3545         // some AP will not response to our mgnt frames with PwrMgt bit set,
3546         // e.g. cannot associate the AP.
3547         // So I commented out it. 2005.02.16, by rcnjko.
3548         //
3549 //      // Change device's power save mode.
3550 //      Adapter->HalFunc.SetPSModeHandler( Adapter, rtPsMode );
3551
3552         // Update power save mode configured.
3553         //RT_TRACE(COMP_LPS,"%s(): set ieee->ps = %x\n",__FUNCTION__,rtPsMode);
3554         if(!priv->ps_force) {
3555                 priv->ieee80211->ps = rtPsMode;
3556         }
3557
3558         // Awake immediately
3559         if(priv->ieee80211->sta_sleep != 0 && rtPsMode == IEEE80211_PS_DISABLED)
3560         {
3561                 unsigned long flags;
3562
3563                 // Notify the AP we awke.
3564                 rtl8192_hw_wakeup(dev);
3565                 priv->ieee80211->sta_sleep = 0;
3566
3567                 spin_lock_irqsave(&(priv->ieee80211->mgmt_tx_lock), flags);
3568                 printk("LPS leave: notify AP we are awaked ++++++++++ SendNullFunctionData\n");
3569                 ieee80211_sta_ps_send_null_frame(priv->ieee80211, 0);
3570                 spin_unlock_irqrestore(&(priv->ieee80211->mgmt_tx_lock), flags);
3571         }
3572
3573         return true;
3574 }
3575
3576 /* Enter the leisure power save mode. */
3577 void LeisurePSEnter(struct net_device *dev)
3578 {
3579         struct r8192_priv *priv = ieee80211_priv(dev);
3580         PRT_POWER_SAVE_CONTROL pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
3581
3582         if(!((priv->ieee80211->iw_mode == IW_MODE_INFRA) &&
3583                 (priv->ieee80211->state == IEEE80211_LINKED)) ||
3584                 (priv->ieee80211->iw_mode == IW_MODE_ADHOC) ||
3585                 (priv->ieee80211->iw_mode == IW_MODE_MASTER))
3586                 return;
3587
3588         if (pPSC->bLeisurePs)
3589         {
3590                 // Idle for a while if we connect to AP a while ago.
3591                 if(pPSC->LpsIdleCount >= RT_CHECK_FOR_HANG_PERIOD) //  4 Sec
3592                 {
3593
3594                         if(priv->ieee80211->ps == IEEE80211_PS_DISABLED)
3595                         {
3596                                 MgntActSet_802_11_PowerSaveMode(dev, IEEE80211_PS_MBCAST|IEEE80211_PS_UNICAST);
3597
3598                         }
3599                 }
3600                 else
3601                         pPSC->LpsIdleCount++;
3602         }
3603 }
3604
3605
3606 /* Leave leisure power save mode. */
3607 void LeisurePSLeave(struct net_device *dev)
3608 {
3609         struct r8192_priv *priv = ieee80211_priv(dev);
3610         PRT_POWER_SAVE_CONTROL pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
3611
3612         if (pPSC->bLeisurePs)
3613         {
3614                 if(priv->ieee80211->ps != IEEE80211_PS_DISABLED)
3615                 {
3616                         // move to lps_wakecomplete()
3617                         MgntActSet_802_11_PowerSaveMode(dev, IEEE80211_PS_DISABLED);
3618
3619                 }
3620         }
3621 }
3622 #endif
3623
3624
3625 /* Enter the inactive power save mode. RF will be off */
3626 void
3627 IPSEnter(struct net_device *dev)
3628 {
3629         struct r8192_priv *priv = ieee80211_priv(dev);
3630         PRT_POWER_SAVE_CONTROL          pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
3631         RT_RF_POWER_STATE                       rtState;
3632
3633         if (pPSC->bInactivePs)
3634         {
3635                 rtState = priv->ieee80211->eRFPowerState;
3636                 //
3637                 // Added by Bruce, 2007-12-25.
3638                 // Do not enter IPS in the following conditions:
3639                 // (1) RF is already OFF or Sleep
3640                 // (2) bSwRfProcessing (indicates the IPS is still under going)
3641                 // (3) Connectted (only disconnected can trigger IPS)
3642                 // (4) IBSS (send Beacon)
3643                 // (5) AP mode (send Beacon)
3644                 //
3645                 if (rtState == eRfOn && !pPSC->bSwRfProcessing
3646                         && (priv->ieee80211->state != IEEE80211_LINKED) )
3647                 {
3648                         RT_TRACE(COMP_RF,"IPSEnter(): Turn off RF.\n");
3649                         pPSC->eInactivePowerState = eRfOff;
3650 //                      queue_work(priv->priv_wq,&(pPSC->InactivePsWorkItem));
3651                         InactivePsWorkItemCallback(dev);
3652                 }
3653         }
3654 }
3655
3656 //
3657 //      Description:
3658 //              Leave the inactive power save mode, RF will be on.
3659 //      2007.08.17, by shien chang.
3660 //
3661 void
3662 IPSLeave(struct net_device *dev)
3663 {
3664         struct r8192_priv *priv = ieee80211_priv(dev);
3665         PRT_POWER_SAVE_CONTROL  pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
3666         RT_RF_POWER_STATE       rtState;
3667
3668         if (pPSC->bInactivePs)
3669         {
3670                 rtState = priv->ieee80211->eRFPowerState;
3671                 if (rtState != eRfOn  && !pPSC->bSwRfProcessing && priv->ieee80211->RfOffReason <= RF_CHANGE_BY_IPS)
3672                 {
3673                         RT_TRACE(COMP_POWER, "IPSLeave(): Turn on RF.\n");
3674                         pPSC->eInactivePowerState = eRfOn;
3675                         InactivePsWorkItemCallback(dev);
3676                 }
3677         }
3678 }
3679
3680 void IPSLeave_wq(struct work_struct *work)
3681 {
3682         struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, ips_leave_wq);
3683         struct net_device *dev = ieee->dev;
3684
3685         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3686         down(&priv->ieee80211->ips_sem);
3687         IPSLeave(dev);
3688         up(&priv->ieee80211->ips_sem);
3689 }
3690
3691 void ieee80211_ips_leave_wq(struct net_device *dev)
3692 {
3693         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3694         RT_RF_POWER_STATE       rtState;
3695         rtState = priv->ieee80211->eRFPowerState;
3696
3697         if(priv->ieee80211->PowerSaveControl.bInactivePs){
3698                 if(rtState == eRfOff){
3699                         if(priv->ieee80211->RfOffReason > RF_CHANGE_BY_IPS)
3700                         {
3701                                 RT_TRACE(COMP_ERR, "%s(): RF is OFF.\n",__FUNCTION__);
3702                                 return;
3703                         }
3704                         else{
3705                                 printk("=========>%s(): IPSLeave\n",__FUNCTION__);
3706                                 queue_work(priv->ieee80211->wq,&priv->ieee80211->ips_leave_wq);
3707                         }
3708                 }
3709         }
3710 }
3711 //added by amy 090331 end
3712 void ieee80211_ips_leave(struct net_device *dev)
3713 {
3714         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3715         down(&priv->ieee80211->ips_sem);
3716         IPSLeave(dev);
3717         up(&priv->ieee80211->ips_sem);
3718 }
3719 #endif
3720
3721 static void rtl819x_update_rxcounts(
3722         struct r8192_priv *priv,
3723         u32* TotalRxBcnNum,
3724         u32* TotalRxDataNum
3725 )
3726 {
3727         u16                     SlotIndex;
3728         u8                      i;
3729
3730         *TotalRxBcnNum = 0;
3731         *TotalRxDataNum = 0;
3732
3733         SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++)%(priv->ieee80211->LinkDetectInfo.SlotNum);
3734         priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
3735         priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] = priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
3736         for( i=0; i<priv->ieee80211->LinkDetectInfo.SlotNum; i++ ){
3737                 *TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
3738                 *TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
3739         }
3740 }
3741
3742
3743 static void rtl819x_watchdog_wqcallback(struct work_struct *work)
3744 {
3745         struct delayed_work *dwork = container_of(work,struct delayed_work,work);
3746        struct r8192_priv *priv = container_of(dwork,struct r8192_priv,watch_dog_wq);
3747        struct net_device *dev = priv->ieee80211->dev;
3748         struct ieee80211_device* ieee = priv->ieee80211;
3749         RESET_TYPE      ResetType = RESET_TYPE_NORESET;
3750         unsigned long flags;
3751         bool bBusyTraffic = false;
3752         bool bEnterPS = false;
3753
3754         if ((!priv->up) || priv->bHwRadioOff)
3755                 return;
3756
3757         if(!priv->up)
3758                 return;
3759         hal_dm_watchdog(dev);
3760 #ifdef ENABLE_IPS
3761         if(ieee->actscanning == false){
3762                 if((ieee->iw_mode == IW_MODE_INFRA) && (ieee->state == IEEE80211_NOLINK) &&
3763                     (ieee->eRFPowerState == eRfOn)&&!ieee->is_set_key &&
3764                     (!ieee->proto_stoppping) && !ieee->wx_set_enc){
3765                         if(ieee->PowerSaveControl.ReturnPoint == IPS_CALLBACK_NONE){
3766                                 IPSEnter(dev);
3767                         }
3768                 }
3769         }
3770 #endif
3771         {//to get busy traffic condition
3772                 if(ieee->state == IEEE80211_LINKED)
3773                 {
3774                         if(     ieee->LinkDetectInfo.NumRxOkInPeriod> 100 ||
3775                                 ieee->LinkDetectInfo.NumTxOkInPeriod> 100 ) {
3776                                 bBusyTraffic = true;
3777                         }
3778
3779 #ifdef ENABLE_LPS
3780                         //added by amy for Leisure PS
3781                         if(     ((ieee->LinkDetectInfo.NumRxUnicastOkInPeriod + ieee->LinkDetectInfo.NumTxOkInPeriod) > 8 ) ||
3782                                 (ieee->LinkDetectInfo.NumRxUnicastOkInPeriod > 2) )
3783                         {
3784                                 bEnterPS= false;
3785                         }
3786                         else
3787                         {
3788                                 bEnterPS= true;
3789                         }
3790
3791                         // LeisurePS only work in infra mode.
3792                         if(bEnterPS)
3793                         {
3794                                 LeisurePSEnter(dev);
3795                         }
3796                         else
3797                         {
3798                                 LeisurePSLeave(dev);
3799                         }
3800 #endif
3801
3802                 }
3803                 else
3804                 {
3805 #ifdef ENABLE_LPS
3806                         LeisurePSLeave(dev);
3807 #endif
3808                 }
3809
3810                 ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
3811                 ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
3812                 ieee->LinkDetectInfo.NumRxUnicastOkInPeriod = 0;
3813                 ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
3814         }
3815
3816
3817         //added by amy for AP roaming
3818                 if(ieee->state == IEEE80211_LINKED && ieee->iw_mode == IW_MODE_INFRA)
3819                 {
3820                         u32     TotalRxBcnNum = 0;
3821                         u32     TotalRxDataNum = 0;
3822
3823                         rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
3824                         if((TotalRxBcnNum+TotalRxDataNum) == 0)
3825                         {
3826                                 if( ieee->eRFPowerState == eRfOff)
3827                                         RT_TRACE(COMP_ERR,"========>%s()\n",__FUNCTION__);
3828                                 printk("===>%s(): AP is power off,connect another one\n",__FUNCTION__);
3829                                 //              Dot11d_Reset(dev);
3830                                 ieee->state = IEEE80211_ASSOCIATING;
3831                                 notify_wx_assoc_event(priv->ieee80211);
3832                                 RemovePeerTS(priv->ieee80211,priv->ieee80211->current_network.bssid);
3833                                 ieee->is_roaming = true;
3834                                 ieee->is_set_key = false;
3835                                 ieee->link_change(dev);
3836                                 queue_work(ieee->wq, &ieee->associate_procedure_wq);
3837                         }
3838                 }
3839               ieee->LinkDetectInfo.NumRecvBcnInPeriod=0;
3840               ieee->LinkDetectInfo.NumRecvDataInPeriod=0;
3841
3842         //check if reset the driver
3843         spin_lock_irqsave(&priv->tx_lock,flags);
3844         if (priv->watchdog_check_reset_cnt++ >= 3 && !ieee->is_roaming && 
3845             priv->watchdog_last_time != 1)
3846         {
3847                 ResetType = rtl819x_ifcheck_resetornot(dev);
3848                 priv->watchdog_check_reset_cnt = 3;
3849         }
3850         spin_unlock_irqrestore(&priv->tx_lock,flags);
3851         if(!priv->bDisableNormalResetCheck && ResetType == RESET_TYPE_NORMAL)
3852         {
3853                 priv->ResetProgress = RESET_TYPE_NORMAL;
3854                 RT_TRACE(COMP_RESET,"%s(): NOMAL RESET\n",__FUNCTION__);
3855                 return;
3856         }
3857         /* disable silent reset temply 2008.9.11*/
3858
3859         if( ((priv->force_reset) || (!priv->bDisableNormalResetCheck && ResetType==RESET_TYPE_SILENT))) // This is control by OID set in Pomelo
3860         {
3861                 priv->watchdog_last_time = 1;
3862                 rtl819x_ifsilentreset(dev);
3863         }
3864         else
3865                 priv->watchdog_last_time = 0;
3866
3867         priv->force_reset = false;
3868         priv->bForcedSilentReset = false;
3869         priv->bResetInProgress = false;
3870         RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
3871
3872 }
3873
3874 void watch_dog_timer_callback(unsigned long data)
3875 {
3876         struct r8192_priv *priv = ieee80211_priv((struct net_device *) data);
3877         queue_delayed_work(priv->priv_wq,&priv->watch_dog_wq,0);
3878         mod_timer(&priv->watch_dog_timer, jiffies + MSECS(IEEE80211_WATCH_DOG_TIME));
3879
3880 }
3881
3882 static int _rtl8192_up(struct net_device *dev)
3883 {
3884         struct r8192_priv *priv = ieee80211_priv(dev);
3885         RT_STATUS init_status = RT_STATUS_SUCCESS;
3886         priv->up=1;
3887         priv->ieee80211->ieee_up=1;
3888         priv->bdisable_nic = false;  //YJ,add,091111
3889         RT_TRACE(COMP_INIT, "Bringing up iface");
3890
3891         init_status = rtl8192_adapter_start(dev);
3892         if(init_status != RT_STATUS_SUCCESS)
3893         {
3894                 RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n",__FUNCTION__);
3895                 return -1;
3896         }
3897         RT_TRACE(COMP_INIT, "start adapter finished\n");
3898
3899         if(priv->ieee80211->eRFPowerState!=eRfOn)
3900                 MgntActSet_RF_State(dev, eRfOn, priv->ieee80211->RfOffReason);
3901
3902         if(priv->ieee80211->state != IEEE80211_LINKED)
3903         ieee80211_softmac_start_protocol(priv->ieee80211);
3904         ieee80211_reset_queue(priv->ieee80211);
3905         watch_dog_timer_callback((unsigned long) dev);
3906         if(!netif_queue_stopped(dev))
3907                 netif_start_queue(dev);
3908         else
3909                 netif_wake_queue(dev);
3910
3911         return 0;
3912 }
3913
3914
3915 static int rtl8192_open(struct net_device *dev)
3916 {
3917         struct r8192_priv *priv = ieee80211_priv(dev);
3918         int ret;
3919
3920         down(&priv->wx_sem);
3921         ret = rtl8192_up(dev);
3922         up(&priv->wx_sem);
3923         return ret;
3924
3925 }
3926
3927
3928 int rtl8192_up(struct net_device *dev)
3929 {
3930         struct r8192_priv *priv = ieee80211_priv(dev);
3931
3932         if (priv->up == 1) return -1;
3933
3934         return _rtl8192_up(dev);
3935 }
3936
3937
3938 static int rtl8192_close(struct net_device *dev)
3939 {
3940         struct r8192_priv *priv = ieee80211_priv(dev);
3941         int ret;
3942
3943         down(&priv->wx_sem);
3944
3945         ret = rtl8192_down(dev);
3946
3947         up(&priv->wx_sem);
3948
3949         return ret;
3950
3951 }
3952
3953 int rtl8192_down(struct net_device *dev)
3954 {
3955         struct r8192_priv *priv = ieee80211_priv(dev);
3956
3957         if (priv->up == 0) return -1;
3958
3959 #ifdef ENABLE_LPS
3960         //LZM for PS-Poll AID issue. 090429
3961         if(priv->ieee80211->state == IEEE80211_LINKED)
3962                 LeisurePSLeave(dev);
3963 #endif
3964
3965         priv->up=0;
3966         priv->ieee80211->ieee_up = 0;
3967         RT_TRACE(COMP_DOWN, "==========>%s()\n", __FUNCTION__);
3968 /* FIXME */
3969         if (!netif_queue_stopped(dev))
3970                 netif_stop_queue(dev);
3971
3972         rtl8192_irq_disable(dev);
3973         rtl8192_cancel_deferred_work(priv);
3974         deinit_hal_dm(dev);
3975         del_timer_sync(&priv->watch_dog_timer);
3976
3977         ieee80211_softmac_stop_protocol(priv->ieee80211,true);
3978
3979         rtl8192_halt_adapter(dev,false);
3980         memset(&priv->ieee80211->current_network, 0 , offsetof(struct ieee80211_network, list));
3981
3982         RT_TRACE(COMP_DOWN, "<==========%s()\n", __FUNCTION__);
3983
3984         return 0;
3985 }
3986
3987
3988 void rtl8192_commit(struct net_device *dev)
3989 {
3990         struct r8192_priv *priv = ieee80211_priv(dev);
3991
3992         if (priv->up == 0) return ;
3993
3994
3995         ieee80211_softmac_stop_protocol(priv->ieee80211,true);
3996
3997         rtl8192_irq_disable(dev);
3998         rtl8192_halt_adapter(dev,true);
3999         _rtl8192_up(dev);
4000 }
4001
4002 static void rtl8192_restart(struct work_struct *work)
4003 {
4004         struct r8192_priv *priv = container_of(work, struct r8192_priv, reset_wq);
4005         struct net_device *dev = priv->ieee80211->dev;
4006
4007         down(&priv->wx_sem);
4008
4009         rtl8192_commit(dev);
4010
4011         up(&priv->wx_sem);
4012 }
4013
4014 static void r8192_set_multicast(struct net_device *dev)
4015 {
4016         struct r8192_priv *priv = ieee80211_priv(dev);
4017
4018         priv->promisc = (dev->flags & IFF_PROMISC) ? 1 : 0;
4019 }
4020
4021
4022 static int r8192_set_mac_adr(struct net_device *dev, void *mac)
4023 {
4024         struct r8192_priv *priv = ieee80211_priv(dev);
4025         struct sockaddr *addr = mac;
4026
4027         down(&priv->wx_sem);
4028
4029         memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
4030
4031         schedule_work(&priv->reset_wq);
4032         up(&priv->wx_sem);
4033
4034         return 0;
4035 }
4036
4037 /* based on ipw2200 driver */
4038 static int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
4039 {
4040         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4041         struct iwreq *wrq = (struct iwreq *)rq;
4042         int ret=-1;
4043         struct ieee80211_device *ieee = priv->ieee80211;
4044         u32 key[4];
4045         u8 broadcast_addr[6] = {0xff,0xff,0xff,0xff,0xff,0xff};
4046         struct iw_point *p = &wrq->u.data;
4047         struct ieee_param *ipw = NULL;//(struct ieee_param *)wrq->u.data.pointer;
4048
4049         down(&priv->wx_sem);
4050
4051
4052      if (p->length < sizeof(struct ieee_param) || !p->pointer){
4053              ret = -EINVAL;
4054              goto out;
4055      }
4056
4057      ipw = kmalloc(p->length, GFP_KERNEL);
4058      if (ipw == NULL){
4059              ret = -ENOMEM;
4060              goto out;
4061      }
4062      if (copy_from_user(ipw, p->pointer, p->length)) {
4063             kfree(ipw);
4064             ret = -EFAULT;
4065             goto out;
4066      }
4067
4068         switch (cmd) {
4069             case RTL_IOCTL_WPA_SUPPLICANT:
4070                 //parse here for HW security
4071                         if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION)
4072                         {
4073                                 if (ipw->u.crypt.set_tx)
4074                                 {
4075                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
4076                                                 ieee->pairwise_key_type = KEY_TYPE_CCMP;
4077                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
4078                                                 ieee->pairwise_key_type = KEY_TYPE_TKIP;
4079                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
4080                                         {
4081                                                 if (ipw->u.crypt.key_len == 13)
4082                                                         ieee->pairwise_key_type = KEY_TYPE_WEP104;
4083                                                 else if (ipw->u.crypt.key_len == 5)
4084                                                         ieee->pairwise_key_type = KEY_TYPE_WEP40;
4085                                         }
4086                                         else
4087                                                 ieee->pairwise_key_type = KEY_TYPE_NA;
4088
4089                                         if (ieee->pairwise_key_type)
4090                                         {
4091                                                 memcpy((u8*)key, ipw->u.crypt.key, 16);
4092                                                 EnableHWSecurityConfig8192(dev);
4093                                         //we fill both index entry and 4th entry for pairwise key as in IPW interface, adhoc will only get here, so we need index entry for its default key serching!
4094                                         //added by WB.
4095                                                 setKey(dev, 4, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
4096                                                 if (ieee->auth_mode != 2)  //LEAP WEP will never set this.
4097                                                 setKey(dev, ipw->u.crypt.idx, ipw->u.crypt.idx, ieee->pairwise_key_type, (u8*)ieee->ap_mac_addr, 0, key);
4098                                         }
4099                                         if ((ieee->pairwise_key_type == KEY_TYPE_CCMP) && ieee->pHTInfo->bCurrentHTSupport){
4100                                                         write_nic_byte(priv, 0x173, 1); //fix aes bug
4101                                                 }
4102
4103                                 }
4104                                 else //if (ipw->u.crypt.idx) //group key use idx > 0
4105                                 {
4106                                         memcpy((u8*)key, ipw->u.crypt.key, 16);
4107                                         if (strcmp(ipw->u.crypt.alg, "CCMP") == 0)
4108                                                 ieee->group_key_type= KEY_TYPE_CCMP;
4109                                         else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0)
4110                                                 ieee->group_key_type = KEY_TYPE_TKIP;
4111                                         else if (strcmp(ipw->u.crypt.alg, "WEP") == 0)
4112                                         {
4113                                                 if (ipw->u.crypt.key_len == 13)
4114                                                         ieee->group_key_type = KEY_TYPE_WEP104;
4115                                                 else if (ipw->u.crypt.key_len == 5)
4116                                                         ieee->group_key_type = KEY_TYPE_WEP40;
4117                                         }
4118                                         else
4119                                                 ieee->group_key_type = KEY_TYPE_NA;
4120
4121                                         if (ieee->group_key_type)
4122                                         {
4123                                                         setKey( dev,
4124                                                                 ipw->u.crypt.idx,
4125                                                                 ipw->u.crypt.idx,               //KeyIndex
4126                                                                 ieee->group_key_type,   //KeyType
4127                                                                 broadcast_addr, //MacAddr
4128                                                                 0,              //DefaultKey
4129                                                                 key);           //KeyContent
4130                                         }
4131                                 }
4132                         }
4133                 ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
4134                 break;
4135
4136             default:
4137                 ret = -EOPNOTSUPP;
4138                 break;
4139         }
4140
4141         kfree(ipw);
4142 out:
4143         up(&priv->wx_sem);
4144
4145         return ret;
4146 }
4147
4148 static u8 HwRateToMRate90(bool bIsHT, u8 rate)
4149 {
4150         u8  ret_rate = 0x02;
4151
4152         if(!bIsHT) {
4153                 switch(rate) {
4154                         case DESC90_RATE1M:   ret_rate = MGN_1M;         break;
4155                         case DESC90_RATE2M:   ret_rate = MGN_2M;         break;
4156                         case DESC90_RATE5_5M: ret_rate = MGN_5_5M;       break;
4157                         case DESC90_RATE11M:  ret_rate = MGN_11M;        break;
4158                         case DESC90_RATE6M:   ret_rate = MGN_6M;         break;
4159                         case DESC90_RATE9M:   ret_rate = MGN_9M;         break;
4160                         case DESC90_RATE12M:  ret_rate = MGN_12M;        break;
4161                         case DESC90_RATE18M:  ret_rate = MGN_18M;        break;
4162                         case DESC90_RATE24M:  ret_rate = MGN_24M;        break;
4163                         case DESC90_RATE36M:  ret_rate = MGN_36M;        break;
4164                         case DESC90_RATE48M:  ret_rate = MGN_48M;        break;
4165                         case DESC90_RATE54M:  ret_rate = MGN_54M;        break;
4166
4167                         default:
4168                                               RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n", rate, bIsHT);
4169                                               break;
4170                 }
4171
4172         } else {
4173                 switch(rate) {
4174                         case DESC90_RATEMCS0:   ret_rate = MGN_MCS0;    break;
4175                         case DESC90_RATEMCS1:   ret_rate = MGN_MCS1;    break;
4176                         case DESC90_RATEMCS2:   ret_rate = MGN_MCS2;    break;
4177                         case DESC90_RATEMCS3:   ret_rate = MGN_MCS3;    break;
4178                         case DESC90_RATEMCS4:   ret_rate = MGN_MCS4;    break;
4179                         case DESC90_RATEMCS5:   ret_rate = MGN_MCS5;    break;
4180                         case DESC90_RATEMCS6:   ret_rate = MGN_MCS6;    break;
4181                         case DESC90_RATEMCS7:   ret_rate = MGN_MCS7;    break;
4182                         case DESC90_RATEMCS8:   ret_rate = MGN_MCS8;    break;
4183                         case DESC90_RATEMCS9:   ret_rate = MGN_MCS9;    break;
4184                         case DESC90_RATEMCS10:  ret_rate = MGN_MCS10;   break;
4185                         case DESC90_RATEMCS11:  ret_rate = MGN_MCS11;   break;
4186                         case DESC90_RATEMCS12:  ret_rate = MGN_MCS12;   break;
4187                         case DESC90_RATEMCS13:  ret_rate = MGN_MCS13;   break;
4188                         case DESC90_RATEMCS14:  ret_rate = MGN_MCS14;   break;
4189                         case DESC90_RATEMCS15:  ret_rate = MGN_MCS15;   break;
4190                         case DESC90_RATEMCS32:  ret_rate = (0x80|0x20); break;
4191
4192                         default:
4193                                                 RT_TRACE(COMP_RECV, "HwRateToMRate90(): Non supported Rate [%x], bIsHT = %d!!!\n",rate, bIsHT);
4194                                                 break;
4195                 }
4196         }
4197
4198         return ret_rate;
4199 }
4200
4201 /* Record the TSF time stamp when receiving a packet */
4202 static void UpdateRxPktTimeStamp8190 (struct net_device *dev, struct ieee80211_rx_stats *stats)
4203 {
4204         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4205
4206         if(stats->bIsAMPDU && !stats->bFirstMPDU) {
4207                 stats->mac_time[0] = priv->LastRxDescTSFLow;
4208                 stats->mac_time[1] = priv->LastRxDescTSFHigh;
4209         } else {
4210                 priv->LastRxDescTSFLow = stats->mac_time[0];
4211                 priv->LastRxDescTSFHigh = stats->mac_time[1];
4212         }
4213 }
4214
4215 static long rtl819x_translate_todbm(u8 signal_strength_index)// 0-100 index.
4216 {
4217         long    signal_power; // in dBm.
4218
4219         // Translate to dBm (x=0.5y-95).
4220         signal_power = (long)((signal_strength_index + 1) >> 1);
4221         signal_power -= 95;
4222
4223         return signal_power;
4224 }
4225
4226 /* 2008/01/22 MH We can not delcare RSSI/EVM total value of sliding window to
4227         be a local static. Otherwise, it may increase when we return from S3/S4. The
4228         value will be kept in memory or disk. We must delcare the value in adapter
4229         and it will be reinitialized when return from S3/S4. */
4230 static void rtl8192_process_phyinfo(struct r8192_priv * priv, u8* buffer,struct ieee80211_rx_stats * pprevious_stats, struct ieee80211_rx_stats * pcurrent_stats)
4231 {
4232         bool bcheck = false;
4233         u8      rfpath;
4234         u32 nspatial_stream, tmp_val;
4235         static u32 slide_rssi_index=0, slide_rssi_statistics=0;
4236         static u32 slide_evm_index=0, slide_evm_statistics=0;
4237         static u32 last_rssi=0, last_evm=0;
4238         //cosa add for beacon rssi smoothing
4239         static u32 slide_beacon_adc_pwdb_index=0, slide_beacon_adc_pwdb_statistics=0;
4240         static u32 last_beacon_adc_pwdb=0;
4241
4242         struct ieee80211_hdr_3addr *hdr;
4243         u16 sc ;
4244         unsigned int frag,seq;
4245         hdr = (struct ieee80211_hdr_3addr *)buffer;
4246         sc = le16_to_cpu(hdr->seq_ctl);
4247         frag = WLAN_GET_SEQ_FRAG(sc);
4248         seq = WLAN_GET_SEQ_SEQ(sc);
4249         //cosa add 04292008 to record the sequence number
4250         pcurrent_stats->Seq_Num = seq;
4251         //
4252         // Check whether we should take the previous packet into accounting
4253         //
4254         if(!pprevious_stats->bIsAMPDU)
4255         {
4256                 // if previous packet is not aggregated packet
4257                 bcheck = true;
4258         }
4259
4260         if(slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX)
4261         {
4262                 slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
4263                 last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
4264                 priv->stats.slide_rssi_total -= last_rssi;
4265         }
4266         priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
4267
4268         priv->stats.slide_signal_strength[slide_rssi_index++] = pprevious_stats->SignalStrength;
4269         if(slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
4270                 slide_rssi_index = 0;
4271
4272         // <1> Showed on UI for user, in dbm
4273         tmp_val = priv->stats.slide_rssi_total/slide_rssi_statistics;
4274         priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
4275         pcurrent_stats->rssi = priv->stats.signal_strength;
4276         //
4277         // If the previous packet does not match the criteria, neglect it
4278         //
4279         if(!pprevious_stats->bPacketMatchBSSID)
4280         {
4281                 if(!pprevious_stats->bToSelfBA)
4282                         return;
4283         }
4284
4285         if(!bcheck)
4286                 return;
4287
4288         // <2> Showed on UI for engineering
4289         // hardware does not provide rssi information for each rf path in CCK
4290         if(!pprevious_stats->bIsCCK && pprevious_stats->bPacketToSelf)
4291         {
4292                 for (rfpath = RF90_PATH_A; rfpath < RF90_PATH_C; rfpath++)
4293                 {
4294                         if (!rtl8192_phy_CheckIsLegalRFPath(priv->ieee80211->dev, rfpath))
4295                                 continue;
4296                         RT_TRACE(COMP_DBG,"Jacken -> pPreviousstats->RxMIMOSignalStrength[rfpath]  = %d \n" ,pprevious_stats->RxMIMOSignalStrength[rfpath] );
4297                         //Fixed by Jacken 2008-03-20
4298                         if(priv->stats.rx_rssi_percentage[rfpath] == 0)
4299                         {
4300                                 priv->stats.rx_rssi_percentage[rfpath] = pprevious_stats->RxMIMOSignalStrength[rfpath];
4301                         }
4302                         if(pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath])
4303                         {
4304                                 priv->stats.rx_rssi_percentage[rfpath] =
4305                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
4306                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
4307                                 priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
4308                         }
4309                         else
4310                         {
4311                                 priv->stats.rx_rssi_percentage[rfpath] =
4312                                         ( (priv->stats.rx_rssi_percentage[rfpath]*(Rx_Smooth_Factor-1)) +
4313                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) /(Rx_Smooth_Factor);
4314                         }
4315                         RT_TRACE(COMP_DBG,"Jacken -> priv->RxStats.RxRSSIPercentage[rfPath]  = %d \n" ,priv->stats.rx_rssi_percentage[rfpath] );
4316                 }
4317         }
4318
4319
4320         //
4321         // Check PWDB.
4322         //
4323         //cosa add for beacon rssi smoothing by average.
4324         if(pprevious_stats->bPacketBeacon)
4325         {
4326                 /* record the beacon pwdb to the sliding window. */
4327                 if(slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX)
4328                 {
4329                         slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
4330                         last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
4331                         priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
4332                         //      slide_beacon_adc_pwdb_index, last_beacon_adc_pwdb, Adapter->RxStats.Slide_Beacon_Total);
4333                 }
4334                 priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
4335                 priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
4336                 slide_beacon_adc_pwdb_index++;
4337                 if(slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
4338                         slide_beacon_adc_pwdb_index = 0;
4339                 pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total/slide_beacon_adc_pwdb_statistics;
4340                 if(pprevious_stats->RxPWDBAll >= 3)
4341                         pprevious_stats->RxPWDBAll -= 3;
4342         }
4343
4344         RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
4345                                 pprevious_stats->bIsCCK? "CCK": "OFDM",
4346                                 pprevious_stats->RxPWDBAll);
4347
4348         if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
4349         {
4350                 if(priv->undecorated_smoothed_pwdb < 0) // initialize
4351                 {
4352                         priv->undecorated_smoothed_pwdb = pprevious_stats->RxPWDBAll;
4353                 }
4354
4355                 if(pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb)
4356                 {
4357                         priv->undecorated_smoothed_pwdb =
4358                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
4359                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
4360                         priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
4361                 }
4362                 else
4363                 {
4364                         priv->undecorated_smoothed_pwdb =
4365                                         ( ((priv->undecorated_smoothed_pwdb)*(Rx_Smooth_Factor-1)) +
4366                                         (pprevious_stats->RxPWDBAll)) /(Rx_Smooth_Factor);
4367                 }
4368         }
4369
4370         //
4371         // Check EVM
4372         //
4373         /* record the general EVM to the sliding window. */
4374         if(pprevious_stats->SignalQuality == 0)
4375         {
4376         }
4377         else
4378         {
4379                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA){
4380                         if(slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX){
4381                                 slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
4382                                 last_evm = priv->stats.slide_evm[slide_evm_index];
4383                                 priv->stats.slide_evm_total -= last_evm;
4384                         }
4385
4386                         priv->stats.slide_evm_total += pprevious_stats->SignalQuality;
4387
4388                         priv->stats.slide_evm[slide_evm_index++] = pprevious_stats->SignalQuality;
4389                         if(slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
4390                                 slide_evm_index = 0;
4391
4392                         // <1> Showed on UI for user, in percentage.
4393                         tmp_val = priv->stats.slide_evm_total/slide_evm_statistics;
4394                         //cosa add 10/11/2007, Showed on UI for user in Windows Vista, for Link quality.
4395                 }
4396
4397                 // <2> Showed on UI for engineering
4398                 if(pprevious_stats->bPacketToSelf || pprevious_stats->bPacketBeacon || pprevious_stats->bToSelfBA)
4399                 {
4400                         for(nspatial_stream = 0; nspatial_stream<2 ; nspatial_stream++) // 2 spatial stream
4401                         {
4402                                 if(pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1)
4403                                 {
4404                                         if(priv->stats.rx_evm_percentage[nspatial_stream] == 0) // initialize
4405                                         {
4406                                                 priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
4407                                         }
4408                                         priv->stats.rx_evm_percentage[nspatial_stream] =
4409                                                 ( (priv->stats.rx_evm_percentage[nspatial_stream]* (Rx_Smooth_Factor-1)) +
4410                                                 (pprevious_stats->RxMIMOSignalQuality[nspatial_stream]* 1)) / (Rx_Smooth_Factor);
4411                                 }
4412                         }
4413                 }
4414         }
4415
4416 }
4417
4418 static u8 rtl819x_query_rxpwrpercentage(
4419         char            antpower
4420         )
4421 {
4422         if ((antpower <= -100) || (antpower >= 20))
4423         {
4424                 return  0;
4425         }
4426         else if (antpower >= 0)
4427         {
4428                 return  100;
4429         }
4430         else
4431         {
4432                 return  (100+antpower);
4433         }
4434
4435 }
4436
4437 static u8
4438 rtl819x_evm_dbtopercentage(
4439         char value
4440         )
4441 {
4442         char ret_val;
4443
4444         ret_val = value;
4445
4446         if(ret_val >= 0)
4447                 ret_val = 0;
4448         if(ret_val <= -33)
4449                 ret_val = -33;
4450         ret_val = 0 - ret_val;
4451         ret_val*=3;
4452         if(ret_val == 99)
4453                 ret_val = 100;
4454         return ret_val;
4455 }
4456
4457 /* We want good-looking for signal strength/quality */
4458 static long rtl819x_signal_scale_mapping(long currsig)
4459 {
4460         long retsig;
4461
4462         // Step 1. Scale mapping.
4463         if(currsig >= 61 && currsig <= 100)
4464         {
4465                 retsig = 90 + ((currsig - 60) / 4);
4466         }
4467         else if(currsig >= 41 && currsig <= 60)
4468         {
4469                 retsig = 78 + ((currsig - 40) / 2);
4470         }
4471         else if(currsig >= 31 && currsig <= 40)
4472         {
4473                 retsig = 66 + (currsig - 30);
4474         }
4475         else if(currsig >= 21 && currsig <= 30)
4476         {
4477                 retsig = 54 + (currsig - 20);
4478         }
4479         else if(currsig >= 5 && currsig <= 20)
4480         {
4481                 retsig = 42 + (((currsig - 5) * 2) / 3);
4482         }
4483         else if(currsig == 4)
4484         {
4485                 retsig = 36;
4486         }
4487         else if(currsig == 3)
4488         {
4489                 retsig = 27;
4490         }
4491         else if(currsig == 2)
4492         {
4493                 retsig = 18;
4494         }
4495         else if(currsig == 1)
4496         {
4497                 retsig = 9;
4498         }
4499         else
4500         {
4501                 retsig = currsig;
4502         }
4503
4504         return retsig;
4505 }
4506
4507 static void rtl8192_query_rxphystatus(
4508         struct r8192_priv * priv,
4509         struct ieee80211_rx_stats * pstats,
4510         prx_desc_819x_pci  pdesc,
4511         prx_fwinfo_819x_pci   pdrvinfo,
4512         struct ieee80211_rx_stats * precord_stats,
4513         bool bpacket_match_bssid,
4514         bool bpacket_toself,
4515         bool bPacketBeacon,
4516         bool bToSelfBA
4517         )
4518 {
4519         //PRT_RFD_STATUS                pRtRfdStatus = &(pRfd->Status);
4520         phy_sts_ofdm_819xpci_t* pofdm_buf;
4521         phy_sts_cck_819xpci_t   *       pcck_buf;
4522         phy_ofdm_rx_status_rxsc_sgien_exintfflag* prxsc;
4523         u8                              *prxpkt;
4524         u8                              i,max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
4525         char                            rx_pwr[4], rx_pwr_all=0;
4526         //long                          rx_avg_pwr = 0;
4527         char                            rx_snrX, rx_evmX;
4528         u8                              evm, pwdb_all;
4529         u32                     RSSI, total_rssi=0;//, total_evm=0;
4530 //      long                            signal_strength_index = 0;
4531         u8                              is_cck_rate=0;
4532         u8                              rf_rx_num = 0;
4533
4534         is_cck_rate = rx_hal_is_cck_rate(pdrvinfo);
4535
4536         // Record it for next packet processing
4537         memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
4538         pstats->bPacketMatchBSSID = precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
4539         pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
4540         pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;//RX_HAL_IS_CCK_RATE(pDrvInfo);
4541         pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
4542         pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
4543         /*2007.08.30 requested by SD3 Jerry */
4544         if (priv->phy_check_reg824 == 0)
4545         {
4546                 priv->phy_reg824_bit9 = rtl8192_QueryBBReg(priv->ieee80211->dev, rFPGA0_XA_HSSIParameter2, 0x200);
4547                 priv->phy_check_reg824 = 1;
4548         }
4549
4550
4551         prxpkt = (u8*)pdrvinfo;
4552
4553         /* Move pointer to the 16th bytes. Phy status start address. */
4554         prxpkt += sizeof(rx_fwinfo_819x_pci);
4555
4556         /* Initial the cck and ofdm buffer pointer */
4557         pcck_buf = (phy_sts_cck_819xpci_t *)prxpkt;
4558         pofdm_buf = (phy_sts_ofdm_819xpci_t *)prxpkt;
4559
4560         pstats->RxMIMOSignalQuality[0] = -1;
4561         pstats->RxMIMOSignalQuality[1] = -1;
4562         precord_stats->RxMIMOSignalQuality[0] = -1;
4563         precord_stats->RxMIMOSignalQuality[1] = -1;
4564
4565         if(is_cck_rate)
4566         {
4567                 //
4568                 // (1)Hardware does not provide RSSI for CCK
4569                 //
4570
4571                 //
4572                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
4573                 //
4574                 u8 report;//, cck_agc_rpt;
4575
4576                 if (!priv->phy_reg824_bit9)
4577                 {
4578                         report = pcck_buf->cck_agc_rpt & 0xc0;
4579                         report = report>>6;
4580                         switch(report)
4581                         {
4582                                 //Fixed by Jacken from Bryant 2008-03-20
4583                                 //Original value is -38 , -26 , -14 , -2
4584                                 //Fixed value is -35 , -23 , -11 , 6
4585                                 case 0x3:
4586                                         rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
4587                                         break;
4588                                 case 0x2:
4589                                         rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
4590                                         break;
4591                                 case 0x1:
4592                                         rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
4593                                         break;
4594                                 case 0x0:
4595                                         rx_pwr_all = 8 - (pcck_buf->cck_agc_rpt & 0x3e);
4596                                         break;
4597                         }
4598                 }
4599                 else
4600                 {
4601                         report = pcck_buf->cck_agc_rpt & 0x60;
4602                         report = report>>5;
4603                         switch(report)
4604                         {
4605                                 case 0x3:
4606                                         rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
4607                                         break;
4608                                 case 0x2:
4609                                         rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1);
4610                                         break;
4611                                 case 0x1:
4612                                         rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
4613                                         break;
4614                                 case 0x0:
4615                                         rx_pwr_all = -8 - ((pcck_buf->cck_agc_rpt & 0x1f)<<1) ;
4616                                         break;
4617                         }
4618                 }
4619
4620                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
4621                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
4622                 pstats->RecvSignalPower = rx_pwr_all;
4623
4624                 //
4625                 // (3) Get Signal Quality (EVM)
4626                 //
4627                 if(bpacket_match_bssid)
4628                 {
4629                         u8      sq;
4630
4631                         if(pstats->RxPWDBAll > 40)
4632                         {
4633                                 sq = 100;
4634                         }else
4635                         {
4636                                 sq = pcck_buf->sq_rpt;
4637
4638                                 if(pcck_buf->sq_rpt > 64)
4639                                         sq = 0;
4640                                 else if (pcck_buf->sq_rpt < 20)
4641                                         sq = 100;
4642                                 else
4643                                         sq = ((64-sq) * 100) / 44;
4644                         }
4645                         pstats->SignalQuality = precord_stats->SignalQuality = sq;
4646                         pstats->RxMIMOSignalQuality[0] = precord_stats->RxMIMOSignalQuality[0] = sq;
4647                         pstats->RxMIMOSignalQuality[1] = precord_stats->RxMIMOSignalQuality[1] = -1;
4648                 }
4649         }
4650         else
4651         {
4652                 //
4653                 // (1)Get RSSI for HT rate
4654                 //
4655                 for(i=RF90_PATH_A; i<RF90_PATH_MAX; i++)
4656                 {
4657                         // 2008/01/30 MH we will judge RF RX path now.
4658                         if (priv->brfpath_rxenable[i])
4659                                 rf_rx_num++;
4660                         //else
4661                                 //continue;
4662
4663                         //Fixed by Jacken from Bryant 2008-03-20
4664                         //Original value is 106
4665                         rx_pwr[i] = ((pofdm_buf->trsw_gain_X[i]&0x3F)*2) - 110;
4666
4667                         //Get Rx snr value in DB
4668                         tmp_rxsnr = pofdm_buf->rxsnr_X[i];
4669                         rx_snrX = (char)(tmp_rxsnr);
4670                         rx_snrX /= 2;
4671
4672                         /* Translate DBM to percentage. */
4673                         RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
4674                         if (priv->brfpath_rxenable[i])
4675                                 total_rssi += RSSI;
4676
4677                         /* Record Signal Strength for next packet */
4678                         if(bpacket_match_bssid)
4679                         {
4680                                 pstats->RxMIMOSignalStrength[i] =(u8) RSSI;
4681                                 precord_stats->RxMIMOSignalStrength[i] =(u8) RSSI;
4682                         }
4683                 }
4684
4685
4686                 //
4687                 // (2)PWDB, Average PWDB cacluated by hardware (for rate adaptive)
4688                 //
4689                 //Fixed by Jacken from Bryant 2008-03-20
4690                 //Original value is 106
4691                 rx_pwr_all = (((pofdm_buf->pwdb_all ) >> 1 )& 0x7f) -106;
4692                 pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
4693
4694                 pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
4695                 pstats->RxPower = precord_stats->RxPower =      rx_pwr_all;
4696                 pstats->RecvSignalPower = rx_pwr_all;
4697                 //
4698                 // (3)EVM of HT rate
4699                 //
4700                 if(pdrvinfo->RxHT && pdrvinfo->RxRate>=DESC90_RATEMCS8 &&
4701                         pdrvinfo->RxRate<=DESC90_RATEMCS15)
4702                         max_spatial_stream = 2; //both spatial stream make sense
4703                 else
4704                         max_spatial_stream = 1; //only spatial stream 1 makes sense
4705
4706                 for(i=0; i<max_spatial_stream; i++)
4707                 {
4708                         tmp_rxevm = pofdm_buf->rxevm_X[i];
4709                         rx_evmX = (char)(tmp_rxevm);
4710
4711                         // Do not use shift operation like "rx_evmX >>= 1" because the compilor of free build environment
4712                         // fill most significant bit to "zero" when doing shifting operation which may change a negative
4713                         // value to positive one, then the dbm value (which is supposed to be negative)  is not correct anymore.
4714                         rx_evmX /= 2;   //dbm
4715
4716                         evm = rtl819x_evm_dbtopercentage(rx_evmX);
4717                         if(bpacket_match_bssid)
4718                         {
4719                                 if(i==0) // Fill value in RFD, Get the first spatial stream only
4720                                         pstats->SignalQuality = precord_stats->SignalQuality = (u8)(evm & 0xff);
4721                                 pstats->RxMIMOSignalQuality[i] = precord_stats->RxMIMOSignalQuality[i] = (u8)(evm & 0xff);
4722                         }
4723                 }
4724
4725
4726                 /* record rx statistics for debug */
4727                 rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
4728                 prxsc = (phy_ofdm_rx_status_rxsc_sgien_exintfflag *)&rxsc_sgien_exflg;
4729         }
4730
4731         //UI BSS List signal strength(in percentage), make it good looking, from 0~100.
4732         //It is assigned to the BSS List in GetValueFromBeaconOrProbeRsp().
4733         if(is_cck_rate)
4734         {
4735                 pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));//PWDB_ALL;
4736
4737         }
4738         else
4739         {
4740                 //pRfd->Status.SignalStrength = pRecordRfd->Status.SignalStrength = (u1Byte)(SignalScaleMapping(total_rssi/=RF90_PATH_MAX));//(u1Byte)(total_rssi/=RF90_PATH_MAX);
4741                 // We can judge RX path number now.
4742                 if (rf_rx_num != 0)
4743                         pstats->SignalStrength = precord_stats->SignalStrength = (u8)(rtl819x_signal_scale_mapping((long)(total_rssi/=rf_rx_num)));
4744         }
4745 }
4746
4747 static void
4748 rtl8192_record_rxdesc_forlateruse(
4749         struct ieee80211_rx_stats * psrc_stats,
4750         struct ieee80211_rx_stats * ptarget_stats
4751 )
4752 {
4753         ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
4754         ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
4755         //ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
4756 }
4757
4758
4759
4760 static void TranslateRxSignalStuff819xpci(struct net_device *dev,
4761         struct sk_buff *skb,
4762         struct ieee80211_rx_stats * pstats,
4763         prx_desc_819x_pci pdesc,
4764         prx_fwinfo_819x_pci pdrvinfo)
4765 {
4766     // TODO: We must only check packet for current MAC address. Not finish
4767     struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4768     bool bpacket_match_bssid, bpacket_toself;
4769     bool bPacketBeacon=false, bToSelfBA=false;
4770     struct ieee80211_hdr_3addr *hdr;
4771     u16 fc,type;
4772
4773     // Get Signal Quality for only RX data queue (but not command queue)
4774
4775     u8* tmp_buf;
4776     u8  *praddr;
4777
4778     /* Get MAC frame start address. */
4779     tmp_buf = skb->data;
4780
4781     hdr = (struct ieee80211_hdr_3addr *)tmp_buf;
4782     fc = le16_to_cpu(hdr->frame_ctl);
4783     type = WLAN_FC_GET_TYPE(fc);
4784     praddr = hdr->addr1;
4785
4786     /* Check if the received packet is acceptabe. */
4787     bpacket_match_bssid = ((IEEE80211_FTYPE_CTL != type) &&
4788             (!compare_ether_addr(priv->ieee80211->current_network.bssid,        (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
4789             && (!pstats->bHwError) && (!pstats->bCRC)&& (!pstats->bICV));
4790     bpacket_toself =  bpacket_match_bssid & (!compare_ether_addr(praddr, priv->ieee80211->dev->dev_addr));
4791
4792     if(WLAN_FC_GET_FRAMETYPE(fc)== IEEE80211_STYPE_BEACON)
4793     {
4794         bPacketBeacon = true;
4795     }
4796     if(WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK)
4797     {
4798         if((!compare_ether_addr(praddr,dev->dev_addr)))
4799             bToSelfBA = true;
4800     }
4801
4802     //
4803     // Process PHY information for previous packet (RSSI/PWDB/EVM)
4804     //
4805     // Because phy information is contained in the last packet of AMPDU only, so driver
4806     // should process phy information of previous packet
4807     rtl8192_process_phyinfo(priv, tmp_buf, &priv->previous_stats, pstats);
4808     rtl8192_query_rxphystatus(priv, pstats, pdesc, pdrvinfo, &priv->previous_stats, bpacket_match_bssid,
4809             bpacket_toself ,bPacketBeacon, bToSelfBA);
4810     rtl8192_record_rxdesc_forlateruse(pstats, &priv->previous_stats);
4811
4812 }
4813
4814
4815 static void rtl8192_tx_resume(struct net_device *dev)
4816 {
4817         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4818         struct ieee80211_device *ieee = priv->ieee80211;
4819         struct sk_buff *skb;
4820         int queue_index;
4821
4822         for(queue_index = BK_QUEUE; queue_index < TXCMD_QUEUE;queue_index++) {
4823                 while((!skb_queue_empty(&ieee->skb_waitQ[queue_index]))&&
4824                                 (priv->ieee80211->check_nic_enough_desc(dev,queue_index) > 0)) {
4825                         /* 1. dequeue the packet from the wait queue */
4826                         skb = skb_dequeue(&ieee->skb_waitQ[queue_index]);
4827                         /* 2. tx the packet directly */
4828                         ieee->softmac_data_hard_start_xmit(skb,dev,0/* rate useless now*/);
4829                 }
4830         }
4831 }
4832
4833 static void rtl8192_irq_tx_tasklet(unsigned long arg)
4834 {
4835         struct r8192_priv *priv = (struct r8192_priv*) arg;
4836         struct rtl8192_tx_ring *mgnt_ring = &priv->tx_ring[MGNT_QUEUE];
4837         struct net_device *dev = priv->ieee80211->dev;
4838         unsigned long flags;
4839
4840         /* check if we need to report that the management queue is drained */
4841         spin_lock_irqsave(&priv->irq_th_lock, flags);
4842
4843         if (!skb_queue_len(&mgnt_ring->queue) &&
4844             priv->ieee80211->ack_tx_to_ieee &&
4845             rtl8192_is_tx_queue_empty(dev)) {
4846                 priv->ieee80211->ack_tx_to_ieee = 0;
4847                 ieee80211_ps_tx_ack(priv->ieee80211, 1);
4848         }
4849
4850         spin_unlock_irqrestore(&priv->irq_th_lock, flags);
4851
4852         rtl8192_tx_resume(dev);
4853 }
4854
4855 /* Record the received data rate */
4856 static void UpdateReceivedRateHistogramStatistics8190(
4857         struct net_device *dev,
4858         struct ieee80211_rx_stats* pstats
4859         )
4860 {
4861         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4862         u32 rcvType=1;   //0: Total, 1:OK, 2:CRC, 3:ICV
4863         u32 rateIndex;
4864         u32 preamble_guardinterval;  //1: short preamble/GI, 0: long preamble/GI
4865
4866         if(pstats->bCRC)
4867                 rcvType = 2;
4868         else if(pstats->bICV)
4869                 rcvType = 3;
4870
4871         if(pstats->bShortPreamble)
4872                 preamble_guardinterval = 1;// short
4873         else
4874                 preamble_guardinterval = 0;// long
4875
4876         switch(pstats->rate)
4877         {
4878                 //
4879                 // CCK rate
4880                 //
4881                 case MGN_1M:    rateIndex = 0;  break;
4882                 case MGN_2M:    rateIndex = 1;  break;
4883                 case MGN_5_5M:  rateIndex = 2;  break;
4884                 case MGN_11M:   rateIndex = 3;  break;
4885                 //
4886                 // Legacy OFDM rate
4887                 //
4888                 case MGN_6M:    rateIndex = 4;  break;
4889                 case MGN_9M:    rateIndex = 5;  break;
4890                 case MGN_12M:   rateIndex = 6;  break;
4891                 case MGN_18M:   rateIndex = 7;  break;
4892                 case MGN_24M:   rateIndex = 8;  break;
4893                 case MGN_36M:   rateIndex = 9;  break;
4894                 case MGN_48M:   rateIndex = 10; break;
4895                 case MGN_54M:   rateIndex = 11; break;
4896                 //
4897                 // 11n High throughput rate
4898                 //
4899                 case MGN_MCS0:  rateIndex = 12; break;
4900                 case MGN_MCS1:  rateIndex = 13; break;
4901                 case MGN_MCS2:  rateIndex = 14; break;
4902                 case MGN_MCS3:  rateIndex = 15; break;
4903                 case MGN_MCS4:  rateIndex = 16; break;
4904                 case MGN_MCS5:  rateIndex = 17; break;
4905                 case MGN_MCS6:  rateIndex = 18; break;
4906                 case MGN_MCS7:  rateIndex = 19; break;
4907                 case MGN_MCS8:  rateIndex = 20; break;
4908                 case MGN_MCS9:  rateIndex = 21; break;
4909                 case MGN_MCS10: rateIndex = 22; break;
4910                 case MGN_MCS11: rateIndex = 23; break;
4911                 case MGN_MCS12: rateIndex = 24; break;
4912                 case MGN_MCS13: rateIndex = 25; break;
4913                 case MGN_MCS14: rateIndex = 26; break;
4914                 case MGN_MCS15: rateIndex = 27; break;
4915                 default:        rateIndex = 28; break;
4916         }
4917         priv->stats.received_rate_histogram[0][rateIndex]++; //total
4918         priv->stats.received_rate_histogram[rcvType][rateIndex]++;
4919 }
4920
4921 static void rtl8192_rx(struct net_device *dev)
4922 {
4923     struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4924     struct ieee80211_hdr_1addr *ieee80211_hdr = NULL;
4925     bool unicast_packet = false;
4926     struct ieee80211_rx_stats stats = {
4927         .signal = 0,
4928         .noise = -98,
4929         .rate = 0,
4930         .freq = IEEE80211_24GHZ_BAND,
4931     };
4932     unsigned int count = priv->rxringcount;
4933     prx_fwinfo_819x_pci pDrvInfo = NULL;
4934     struct sk_buff *new_skb;
4935
4936     while (count--) {
4937         rx_desc_819x_pci *pdesc = &priv->rx_ring[priv->rx_idx];//rx descriptor
4938         struct sk_buff *skb = priv->rx_buf[priv->rx_idx];//rx pkt
4939
4940         if (pdesc->OWN)
4941             /* wait data to be filled by hardware */
4942             return;
4943
4944             stats.bICV = pdesc->ICV;
4945             stats.bCRC = pdesc->CRC32;
4946             stats.bHwError = pdesc->CRC32 | pdesc->ICV;
4947
4948             stats.Length = pdesc->Length;
4949             if(stats.Length < 24)
4950                 stats.bHwError |= 1;
4951
4952             if(stats.bHwError) {
4953                 stats.bShift = false;
4954                 goto done;
4955             }
4956                 pDrvInfo = NULL;
4957                 new_skb = dev_alloc_skb(priv->rxbuffersize);
4958
4959                 if (unlikely(!new_skb))
4960                     goto done;
4961
4962                 stats.RxDrvInfoSize = pdesc->RxDrvInfoSize;
4963                 stats.RxBufShift = ((pdesc->Shift)&0x03);
4964                 stats.Decrypted = !pdesc->SWDec;
4965
4966                 pci_dma_sync_single_for_cpu(priv->pdev,
4967                      *((dma_addr_t *)skb->cb),
4968                      priv->rxbuffersize,
4969                      PCI_DMA_FROMDEVICE);
4970                 skb_put(skb, pdesc->Length);
4971                 pDrvInfo = (rx_fwinfo_819x_pci *)(skb->data + stats.RxBufShift);
4972                 skb_reserve(skb, stats.RxDrvInfoSize + stats.RxBufShift);
4973
4974                 stats.rate = HwRateToMRate90((bool)pDrvInfo->RxHT, (u8)pDrvInfo->RxRate);
4975                 stats.bShortPreamble = pDrvInfo->SPLCP;
4976
4977                 /* it is debug only. It should be disabled in released driver.
4978                  * 2007.1.11 by Emily
4979                  * */
4980                 UpdateReceivedRateHistogramStatistics8190(dev, &stats);
4981
4982                 stats.bIsAMPDU = (pDrvInfo->PartAggr==1);
4983                 stats.bFirstMPDU = (pDrvInfo->PartAggr==1) && (pDrvInfo->FirstAGGR==1);
4984
4985                 stats.TimeStampLow = pDrvInfo->TSFL;
4986                 stats.TimeStampHigh = read_nic_dword(priv, TSFR+4);
4987
4988                 UpdateRxPktTimeStamp8190(dev, &stats);
4989
4990                 //
4991                 // Get Total offset of MPDU Frame Body
4992                 //
4993                 if((stats.RxBufShift + stats.RxDrvInfoSize) > 0)
4994                     stats.bShift = 1;
4995
4996                 stats.RxIs40MHzPacket = pDrvInfo->BW;
4997
4998                 /* ???? */
4999                 TranslateRxSignalStuff819xpci(dev,skb, &stats, pdesc, pDrvInfo);
5000
5001                 /* Rx A-MPDU */
5002                 if(pDrvInfo->FirstAGGR==1 || pDrvInfo->PartAggr == 1)
5003                     RT_TRACE(COMP_RXDESC, "pDrvInfo->FirstAGGR = %d, pDrvInfo->PartAggr = %d\n",
5004                             pDrvInfo->FirstAGGR, pDrvInfo->PartAggr);
5005                    skb_trim(skb, skb->len - 4/*sCrcLng*/);
5006                 /* rx packets statistics */
5007                 ieee80211_hdr = (struct ieee80211_hdr_1addr *)skb->data;
5008                 unicast_packet = false;
5009
5010                 if(is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
5011                     //TODO
5012                 }else if(is_multicast_ether_addr(ieee80211_hdr->addr1)){
5013                     //TODO
5014                 }else {
5015                     /* unicast packet */
5016                     unicast_packet = true;
5017                 }
5018
5019                 stats.packetlength = stats.Length-4;
5020                 stats.fraglength = stats.packetlength;
5021                 stats.fragoffset = 0;
5022                 stats.ntotalfrag = 1;
5023
5024                 if(!ieee80211_rtl_rx(priv->ieee80211, skb, &stats)){
5025                     dev_kfree_skb_any(skb);
5026                 } else {
5027                     priv->stats.rxok++;
5028                     if(unicast_packet) {
5029                         priv->stats.rxbytesunicast += skb->len;
5030                     }
5031                 }
5032
5033                 pci_unmap_single(priv->pdev, *((dma_addr_t *) skb->cb),
5034                         priv->rxbuffersize, PCI_DMA_FROMDEVICE);
5035
5036                 skb = new_skb;
5037                 priv->rx_buf[priv->rx_idx] = skb;
5038                 *((dma_addr_t *) skb->cb) = pci_map_single(priv->pdev, skb_tail_pointer(skb), priv->rxbuffersize, PCI_DMA_FROMDEVICE);
5039
5040 done:
5041         pdesc->BufferAddress = cpu_to_le32(*((dma_addr_t *)skb->cb));
5042         pdesc->OWN = 1;
5043         pdesc->Length = priv->rxbuffersize;
5044         if (priv->rx_idx == priv->rxringcount-1)
5045             pdesc->EOR = 1;
5046         priv->rx_idx = (priv->rx_idx + 1) % priv->rxringcount;
5047     }
5048
5049 }
5050
5051 static void rtl8192_irq_rx_tasklet(unsigned long arg)
5052 {
5053         struct r8192_priv *priv = (struct r8192_priv*) arg;
5054        rtl8192_rx(priv->ieee80211->dev);
5055         /* unmask RDU */
5056        write_nic_dword(priv, INTA_MASK, read_nic_dword(priv, INTA_MASK) | IMR_RDU);
5057 }
5058
5059 static const struct net_device_ops rtl8192_netdev_ops = {
5060         .ndo_open =                     rtl8192_open,
5061         .ndo_stop =                     rtl8192_close,
5062         .ndo_tx_timeout =               tx_timeout,
5063         .ndo_do_ioctl =                 rtl8192_ioctl,
5064         .ndo_set_multicast_list =       r8192_set_multicast,
5065         .ndo_set_mac_address =          r8192_set_mac_adr,
5066         .ndo_start_xmit =               ieee80211_rtl_xmit,
5067 };
5068
5069 static int __devinit rtl8192_pci_probe(struct pci_dev *pdev,
5070                          const struct pci_device_id *id)
5071 {
5072         unsigned long ioaddr = 0;
5073         struct net_device *dev = NULL;
5074         struct r8192_priv *priv= NULL;
5075         u8 unit = 0;
5076         int ret = -ENODEV;
5077
5078 #ifdef CONFIG_RTL8192_IO_MAP
5079         unsigned long pio_start, pio_len, pio_flags;
5080 #else
5081         unsigned long pmem_start, pmem_len, pmem_flags;
5082 #endif //end #ifdef RTL_IO_MAP
5083
5084         RT_TRACE(COMP_INIT,"Configuring chip resources");
5085
5086         if( pci_enable_device (pdev) ){
5087                 RT_TRACE(COMP_ERR,"Failed to enable PCI device");
5088                 return -EIO;
5089         }
5090
5091         pci_set_master(pdev);
5092         //pci_set_wmi(pdev);
5093         pci_set_dma_mask(pdev, 0xffffff00ULL);
5094         pci_set_consistent_dma_mask(pdev,0xffffff00ULL);
5095         dev = alloc_ieee80211(sizeof(struct r8192_priv));
5096         if (!dev) {
5097                 ret = -ENOMEM;
5098                 goto fail_free;
5099         }
5100
5101         pci_set_drvdata(pdev, dev);
5102         SET_NETDEV_DEV(dev, &pdev->dev);
5103         priv = ieee80211_priv(dev);
5104         priv->ieee80211 = netdev_priv(dev);
5105         priv->pdev=pdev;
5106         if((pdev->subsystem_vendor == PCI_VENDOR_ID_DLINK)&&(pdev->subsystem_device == 0x3304)){
5107                 priv->ieee80211->bSupportRemoteWakeUp = 1;
5108         } else
5109         {
5110                 priv->ieee80211->bSupportRemoteWakeUp = 0;
5111         }
5112
5113 #ifdef CONFIG_RTL8192_IO_MAP
5114
5115         pio_start = (unsigned long)pci_resource_start (pdev, 0);
5116         pio_len = (unsigned long)pci_resource_len (pdev, 0);
5117         pio_flags = (unsigned long)pci_resource_flags (pdev, 0);
5118
5119         if (!(pio_flags & IORESOURCE_IO)) {
5120                 RT_TRACE(COMP_ERR,"region #0 not a PIO resource, aborting");
5121                 goto fail;
5122         }
5123
5124         //DMESG("IO space @ 0x%08lx", pio_start );
5125         if( ! request_region( pio_start, pio_len, RTL819xE_MODULE_NAME ) ){
5126                 RT_TRACE(COMP_ERR,"request_region failed!");
5127                 goto fail;
5128         }
5129
5130         ioaddr = pio_start;
5131         dev->base_addr = ioaddr; // device I/O address
5132
5133 #else
5134
5135         pmem_start = pci_resource_start(pdev, 1);
5136         pmem_len = pci_resource_len(pdev, 1);
5137         pmem_flags = pci_resource_flags (pdev, 1);
5138
5139         if (!(pmem_flags & IORESOURCE_MEM)) {
5140                 RT_TRACE(COMP_ERR,"region #1 not a MMIO resource, aborting");
5141                 goto fail;
5142         }
5143
5144         //DMESG("Memory mapped space @ 0x%08lx ", pmem_start);
5145         if( ! request_mem_region(pmem_start, pmem_len, RTL819xE_MODULE_NAME)) {
5146                 RT_TRACE(COMP_ERR,"request_mem_region failed!");
5147                 goto fail;
5148         }
5149
5150
5151         ioaddr = (unsigned long)ioremap_nocache( pmem_start, pmem_len);
5152         if( ioaddr == (unsigned long)NULL ){
5153                 RT_TRACE(COMP_ERR,"ioremap failed!");
5154                // release_mem_region( pmem_start, pmem_len );
5155                 goto fail1;
5156         }
5157
5158         dev->mem_start = ioaddr; // shared mem start
5159         dev->mem_end = ioaddr + pci_resource_len(pdev, 0); // shared mem end
5160
5161 #endif //end #ifdef RTL_IO_MAP
5162
5163         /* We disable the RETRY_TIMEOUT register (0x41) to keep
5164          * PCI Tx retries from interfering with C3 CPU state */
5165          pci_write_config_byte(pdev, 0x41, 0x00);
5166
5167
5168         pci_read_config_byte(pdev, 0x05, &unit);
5169         pci_write_config_byte(pdev, 0x05, unit & (~0x04));
5170
5171         dev->irq = pdev->irq;
5172         priv->irq = 0;
5173
5174         dev->netdev_ops = &rtl8192_netdev_ops;
5175
5176         dev->wireless_handlers = &r8192_wx_handlers_def;
5177         dev->type=ARPHRD_ETHER;
5178
5179         dev->watchdog_timeo = HZ*3;
5180
5181         if (dev_alloc_name(dev, ifname) < 0){
5182                 RT_TRACE(COMP_INIT, "Oops: devname already taken! Trying wlan%%d...\n");
5183                 strcpy(ifname, "wlan%d");
5184                 dev_alloc_name(dev, ifname);
5185         }
5186
5187         RT_TRACE(COMP_INIT, "Driver probe completed1\n");
5188         if(rtl8192_init(dev)!=0){
5189                 RT_TRACE(COMP_ERR, "Initialization failed");
5190                 goto fail;
5191         }
5192
5193         register_netdev(dev);
5194         RT_TRACE(COMP_INIT, "dev name=======> %s\n",dev->name);
5195         rtl8192_proc_init_one(dev);
5196
5197
5198         RT_TRACE(COMP_INIT, "Driver probe completed\n");
5199         return 0;
5200
5201 fail1:
5202
5203 #ifdef CONFIG_RTL8180_IO_MAP
5204
5205         if( dev->base_addr != 0 ){
5206
5207                 release_region(dev->base_addr,
5208                pci_resource_len(pdev, 0) );
5209         }
5210 #else
5211         if( dev->mem_start != (unsigned long)NULL ){
5212                 iounmap( (void *)dev->mem_start );
5213                 release_mem_region( pci_resource_start(pdev, 1),
5214                                     pci_resource_len(pdev, 1) );
5215         }
5216 #endif //end #ifdef RTL_IO_MAP
5217
5218 fail:
5219         if(dev){
5220
5221                 if (priv->irq) {
5222                         free_irq(dev->irq, dev);
5223                         dev->irq=0;
5224                 }
5225                 free_ieee80211(dev);
5226         }
5227
5228 fail_free:
5229         pci_disable_device(pdev);
5230
5231         DMESG("wlan driver load failed\n");
5232         pci_set_drvdata(pdev, NULL);
5233         return ret;
5234
5235 }
5236
5237 /* detach all the work and timer structure declared or inititialized
5238  * in r8192_init function.
5239  * */
5240 static void rtl8192_cancel_deferred_work(struct r8192_priv* priv)
5241 {
5242         /* call cancel_work_sync instead of cancel_delayed_work if and only if Linux_version_code
5243          * is  or is newer than 2.6.20 and work structure is defined to be struct work_struct.
5244          * Otherwise call cancel_delayed_work is enough.
5245          * FIXME (2.6.20 should 2.6.22, work_struct should not cancel)
5246          * */
5247         cancel_delayed_work(&priv->watch_dog_wq);
5248         cancel_delayed_work(&priv->update_beacon_wq);
5249         cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
5250         cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
5251         cancel_delayed_work(&priv->gpio_change_rf_wq);
5252         cancel_work_sync(&priv->reset_wq);
5253         cancel_work_sync(&priv->qos_activate);
5254 }
5255
5256
5257 static void __devexit rtl8192_pci_disconnect(struct pci_dev *pdev)
5258 {
5259         struct net_device *dev = pci_get_drvdata(pdev);
5260         struct r8192_priv *priv ;
5261         u32 i;
5262
5263         if (dev) {
5264
5265                 unregister_netdev(dev);
5266
5267                 priv = ieee80211_priv(dev);
5268
5269                 rtl8192_proc_remove_one(dev);
5270
5271                 rtl8192_down(dev);
5272                 if (priv->pFirmware)
5273                 {
5274                         vfree(priv->pFirmware);
5275                         priv->pFirmware = NULL;
5276                 }
5277                 destroy_workqueue(priv->priv_wq);
5278
5279                 /* free tx/rx rings */
5280                 rtl8192_free_rx_ring(dev);
5281                 for (i = 0; i < MAX_TX_QUEUE_COUNT; i++)
5282                         rtl8192_free_tx_ring(dev, i);
5283
5284                 if (priv->irq) {
5285                         printk("Freeing irq %d\n",dev->irq);
5286                         free_irq(dev->irq, dev);
5287                         priv->irq=0;
5288                 }
5289
5290 #ifdef CONFIG_RTL8180_IO_MAP
5291
5292                 if( dev->base_addr != 0 ){
5293
5294                         release_region(dev->base_addr,
5295                                        pci_resource_len(pdev, 0) );
5296                 }
5297 #else
5298                 if( dev->mem_start != (unsigned long)NULL ){
5299                         iounmap( (void *)dev->mem_start );
5300                         release_mem_region( pci_resource_start(pdev, 1),
5301                                             pci_resource_len(pdev, 1) );
5302                 }
5303 #endif /*end #ifdef RTL_IO_MAP*/
5304                 free_ieee80211(dev);
5305
5306         }
5307
5308         pci_disable_device(pdev);
5309         RT_TRACE(COMP_DOWN, "wlan driver removed\n");
5310 }
5311
5312 extern int ieee80211_rtl_init(void);
5313 extern void ieee80211_rtl_exit(void);
5314
5315 static int __init rtl8192_pci_module_init(void)
5316 {
5317         int retval;
5318
5319         retval = ieee80211_rtl_init();
5320         if (retval)
5321                 return retval;
5322
5323         printk(KERN_INFO "\nLinux kernel driver for RTL8192 based WLAN cards\n");
5324         printk(KERN_INFO "Copyright (c) 2007-2008, Realsil Wlan\n");
5325         RT_TRACE(COMP_INIT, "Initializing module");
5326         rtl8192_proc_module_init();
5327       if(0!=pci_register_driver(&rtl8192_pci_driver))
5328         {
5329                 DMESG("No device found");
5330                 /*pci_unregister_driver (&rtl8192_pci_driver);*/
5331                 return -ENODEV;
5332         }
5333         return 0;
5334 }
5335
5336
5337 static void __exit rtl8192_pci_module_exit(void)
5338 {
5339         pci_unregister_driver(&rtl8192_pci_driver);
5340
5341         RT_TRACE(COMP_DOWN, "Exiting");
5342         rtl8192_proc_module_remove();
5343         ieee80211_rtl_exit();
5344 }
5345
5346 static irqreturn_t rtl8192_interrupt(int irq, void *netdev)
5347 {
5348         struct net_device *dev = (struct net_device *) netdev;
5349         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5350         unsigned long flags;
5351         u32 inta;
5352         irqreturn_t ret = IRQ_HANDLED;
5353
5354         spin_lock_irqsave(&priv->irq_th_lock, flags);
5355
5356         /* We should return IRQ_NONE, but for now let me keep this */
5357         if (priv->irq_enabled == 0)
5358                 goto out_unlock;
5359
5360         /* ISR: 4bytes */
5361
5362         inta = read_nic_dword(priv, ISR); /* & priv->IntrMask; */
5363         write_nic_dword(priv, ISR, inta); /* reset int situation */
5364
5365         if (!inta) {
5366                 /*
5367                  * most probably we can safely return IRQ_NONE,
5368                  * but for now is better to avoid problems
5369                  */
5370                 goto out_unlock;
5371         }
5372
5373         if (inta == 0xffff) {
5374                 /* HW disappared */
5375                 goto out_unlock;
5376         }
5377
5378         if (!netif_running(dev))
5379                 goto out_unlock;
5380
5381         if (inta & IMR_TBDOK) {
5382                 RT_TRACE(COMP_INTR, "beacon ok interrupt!\n");
5383                 rtl8192_tx_isr(dev, BEACON_QUEUE);
5384                 priv->stats.txbeaconokint++;
5385         }
5386
5387         if (inta & IMR_TBDER) {
5388                 RT_TRACE(COMP_INTR, "beacon ok interrupt!\n");
5389                 rtl8192_tx_isr(dev, BEACON_QUEUE);
5390                 priv->stats.txbeaconerr++;
5391         }
5392
5393         if (inta & IMR_MGNTDOK ) {
5394                 RT_TRACE(COMP_INTR, "Manage ok interrupt!\n");
5395                 priv->stats.txmanageokint++;
5396                 rtl8192_tx_isr(dev,MGNT_QUEUE);
5397         }
5398
5399         if (inta & IMR_COMDOK)
5400         {
5401                 priv->stats.txcmdpktokint++;
5402                 rtl8192_tx_isr(dev, TXCMD_QUEUE);
5403         }
5404
5405         if (inta & IMR_ROK) {
5406                 priv->stats.rxint++;
5407                 tasklet_schedule(&priv->irq_rx_tasklet);
5408         }
5409
5410         if (inta & IMR_BcnInt) {
5411                 RT_TRACE(COMP_INTR, "prepare beacon for interrupt!\n");
5412                 tasklet_schedule(&priv->irq_prepare_beacon_tasklet);
5413         }
5414
5415         if (inta & IMR_RDU) {
5416                 RT_TRACE(COMP_INTR, "rx descriptor unavailable!\n");
5417                 priv->stats.rxrdu++;
5418                 /* reset int situation */
5419                 write_nic_dword(priv, INTA_MASK, read_nic_dword(priv, INTA_MASK) & ~IMR_RDU);
5420                 tasklet_schedule(&priv->irq_rx_tasklet);
5421         }
5422
5423         if (inta & IMR_RXFOVW) {
5424                 RT_TRACE(COMP_INTR, "rx overflow !\n");
5425                 priv->stats.rxoverflow++;
5426                 tasklet_schedule(&priv->irq_rx_tasklet);
5427         }
5428
5429         if (inta & IMR_TXFOVW)
5430                 priv->stats.txoverflow++;
5431
5432         if (inta & IMR_BKDOK) {
5433                 RT_TRACE(COMP_INTR, "BK Tx OK interrupt!\n");
5434                 priv->stats.txbkokint++;
5435                 priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
5436                 rtl8192_tx_isr(dev, BK_QUEUE);
5437         }
5438
5439         if (inta & IMR_BEDOK) {
5440                 RT_TRACE(COMP_INTR, "BE TX OK interrupt!\n");
5441                 priv->stats.txbeokint++;
5442                 priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
5443                 rtl8192_tx_isr(dev, BE_QUEUE);
5444         }
5445
5446         if (inta & IMR_VIDOK) {
5447                 RT_TRACE(COMP_INTR, "VI TX OK interrupt!\n");
5448                 priv->stats.txviokint++;
5449                 priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
5450                 rtl8192_tx_isr(dev, VI_QUEUE);
5451         }
5452
5453         if (inta & IMR_VODOK) {
5454                 priv->stats.txvookint++;
5455                 priv->ieee80211->LinkDetectInfo.NumTxOkInPeriod++;
5456                 rtl8192_tx_isr(dev, VO_QUEUE);
5457         }
5458
5459 out_unlock:
5460         spin_unlock_irqrestore(&priv->irq_th_lock, flags);
5461
5462         return ret;
5463 }
5464
5465 void EnableHWSecurityConfig8192(struct net_device *dev)
5466 {
5467         u8 SECR_value = 0x0;
5468         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5469         struct ieee80211_device* ieee = priv->ieee80211;
5470
5471         SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
5472
5473         if (((KEY_TYPE_WEP40 == ieee->pairwise_key_type) || (KEY_TYPE_WEP104 == ieee->pairwise_key_type)) && (priv->ieee80211->auth_mode != 2))
5474         {
5475                 SECR_value |= SCR_RxUseDK;
5476                 SECR_value |= SCR_TxUseDK;
5477         }
5478         else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP)))
5479         {
5480                 SECR_value |= SCR_RxUseDK;
5481                 SECR_value |= SCR_TxUseDK;
5482         }
5483
5484         //add HWSec active enable here.
5485 //default using hwsec. when peer AP is in N mode only and pairwise_key_type is none_aes(which HT_IOT_ACT_PURE_N_MODE indicates it), use software security. when peer AP is in b,g,n mode mixed and pairwise_key_type is none_aes, use g mode hw security. WB on 2008.7.4
5486         ieee->hwsec_active = 1;
5487
5488         if ((ieee->pHTInfo->IOTAction&HT_IOT_ACT_PURE_N_MODE) || !hwwep)//!ieee->hwsec_support) //add hwsec_support flag to totol control hw_sec on/off
5489         {
5490                 ieee->hwsec_active = 0;
5491                 SECR_value &= ~SCR_RxDecEnable;
5492         }
5493
5494         RT_TRACE(COMP_SEC,"%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n", __FUNCTION__,
5495                         ieee->hwsec_active, ieee->pairwise_key_type, SECR_value);
5496         {
5497                 write_nic_byte(priv, SECR,  SECR_value);//SECR_value |  SCR_UseDK );
5498         }
5499
5500 }
5501 #define TOTAL_CAM_ENTRY 32
5502 //#define CAM_CONTENT_COUNT 8
5503 void setKey(    struct net_device *dev,
5504                 u8 EntryNo,
5505                 u8 KeyIndex,
5506                 u16 KeyType,
5507                 const u8 *MacAddr,
5508                 u8 DefaultKey,
5509                 u32 *KeyContent )
5510 {
5511         u32 TargetCommand = 0;
5512         u32 TargetContent = 0;
5513         u16 usConfig = 0;
5514         u8 i;
5515 #ifdef ENABLE_IPS
5516         struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5517         RT_RF_POWER_STATE       rtState;
5518         rtState = priv->ieee80211->eRFPowerState;
5519         if(priv->ieee80211->PowerSaveControl.bInactivePs){
5520                 if(rtState == eRfOff){
5521                         if(priv->ieee80211->RfOffReason > RF_CHANGE_BY_IPS)
5522                         {
5523                                 RT_TRACE(COMP_ERR, "%s(): RF is OFF.\n",__FUNCTION__);
5524                                 //up(&priv->wx_sem);
5525                                 return ;
5526                         }
5527                         else{
5528                                 down(&priv->ieee80211->ips_sem);
5529                                 IPSLeave(dev);
5530                                 up(&priv->ieee80211->ips_sem);
5531                         }
5532                 }
5533         }
5534         priv->ieee80211->is_set_key = true;
5535 #endif
5536         if (EntryNo >= TOTAL_CAM_ENTRY)
5537                 RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
5538
5539         RT_TRACE(COMP_SEC, "====>to setKey(), dev:%p, EntryNo:%d, KeyIndex:%d, KeyType:%d, MacAddr%pM\n", dev,EntryNo, KeyIndex, KeyType, MacAddr);
5540
5541         if (DefaultKey)
5542                 usConfig |= BIT15 | (KeyType<<2);
5543         else
5544                 usConfig |= BIT15 | (KeyType<<2) | KeyIndex;
5545 //      usConfig |= BIT15 | (KeyType<<2) | (DefaultKey<<5) | KeyIndex;
5546
5547
5548         for(i=0 ; i<CAM_CONTENT_COUNT; i++){
5549                 TargetCommand  = i+CAM_CONTENT_COUNT*EntryNo;
5550                 TargetCommand |= BIT31|BIT16;
5551
5552                 if(i==0){//MAC|Config
5553                         TargetContent = (u32)(*(MacAddr+0)) << 16|
5554                                         (u32)(*(MacAddr+1)) << 24|
5555                                         (u32)usConfig;
5556
5557                         write_nic_dword(priv, WCAMI, TargetContent);
5558                         write_nic_dword(priv, RWCAM, TargetCommand);
5559                 }
5560                 else if(i==1){//MAC
5561                         TargetContent = (u32)(*(MacAddr+2))      |
5562                                         (u32)(*(MacAddr+3)) <<  8|
5563                                         (u32)(*(MacAddr+4)) << 16|
5564                                         (u32)(*(MacAddr+5)) << 24;
5565                         write_nic_dword(priv, WCAMI, TargetContent);
5566                         write_nic_dword(priv, RWCAM, TargetCommand);
5567                 }
5568                 else {  //Key Material
5569                         if(KeyContent != NULL)
5570                         {
5571                         write_nic_dword(priv, WCAMI, (u32)(*(KeyContent+i-2)) );
5572                         write_nic_dword(priv, RWCAM, TargetCommand);
5573                 }
5574         }
5575         }
5576         RT_TRACE(COMP_SEC,"=========>after set key, usconfig:%x\n", usConfig);
5577 }
5578
5579 bool NicIFEnableNIC(struct net_device* dev)
5580 {
5581         RT_STATUS init_status = RT_STATUS_SUCCESS;
5582         struct r8192_priv* priv = ieee80211_priv(dev);
5583         PRT_POWER_SAVE_CONTROL pPSC = (PRT_POWER_SAVE_CONTROL)(&(priv->ieee80211->PowerSaveControl));
5584
5585         //YJ,add,091109
5586         if (priv->up == 0){
5587                 RT_TRACE(COMP_ERR, "ERR!!! %s(): Driver is already down!\n",__FUNCTION__);
5588                 priv->bdisable_nic = false;  //YJ,add,091111
5589                 return false;
5590         }
5591         // <1> Reset memory: descriptor, buffer,..
5592         //NicIFResetMemory(Adapter);
5593
5594         // <2> Enable Adapter
5595         //priv->bfirst_init = true;
5596         init_status = rtl8192_adapter_start(dev);
5597         if (init_status != RT_STATUS_SUCCESS) {
5598                 RT_TRACE(COMP_ERR,"ERR!!! %s(): initialization is failed!\n",__FUNCTION__);
5599                 priv->bdisable_nic = false;  //YJ,add,091111
5600                 return -1;
5601         }
5602         RT_CLEAR_PS_LEVEL(pPSC, RT_RF_OFF_LEVL_HALT_NIC);
5603         //priv->bfirst_init = false;
5604
5605         // <3> Enable Interrupt
5606         rtl8192_irq_enable(dev);
5607         priv->bdisable_nic = false;
5608
5609         return (init_status == RT_STATUS_SUCCESS);
5610 }
5611
5612 bool NicIFDisableNIC(struct net_device* dev)
5613 {
5614         bool    status = true;
5615         struct r8192_priv* priv = ieee80211_priv(dev);
5616         u8 tmp_state = 0;
5617         // <1> Disable Interrupt
5618
5619         priv->bdisable_nic = true;      //YJ,move,091109
5620         tmp_state = priv->ieee80211->state;
5621
5622         ieee80211_softmac_stop_protocol(priv->ieee80211, false);
5623
5624         priv->ieee80211->state = tmp_state;
5625         rtl8192_cancel_deferred_work(priv);
5626         rtl8192_irq_disable(dev);
5627         // <2> Stop all timer
5628
5629         // <3> Disable Adapter
5630         rtl8192_halt_adapter(dev, false);
5631 //      priv->bdisable_nic = true;
5632
5633         return status;
5634 }
5635
5636 module_init(rtl8192_pci_module_init);
5637 module_exit(rtl8192_pci_module_exit);