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