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