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