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