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