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