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