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