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