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