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