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