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