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