linux/drivers/staging/rtl8192u/r8192U_core.c
<<
>>
Prefs
   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
  14double __floatsidf(int i)
  15{
  16        return i;
  17}
  18
  19unsigned int __fixunsdfsi(double d)
  20{
  21        return d;
  22}
  23
  24double __adddf3(double a, double b)
  25{
  26        return a + b;
  27}
  28
  29double __addsf3(float a, float b)
  30{
  31        return a + b;
  32}
  33
  34double __subdf3(double a, double b)
  35{
  36        return a - b;
  37}
  38
  39double __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. */
  65u32 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
  72static 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
  92MODULE_LICENSE("GPL");
  93MODULE_VERSION("V 1.1");
  94MODULE_DEVICE_TABLE(usb, rtl8192_usb_id_tbl);
  95MODULE_DESCRIPTION("Linux driver for Realtek RTL8192 USB WiFi cards");
  96
  97static char *ifname = "wlan%d";
  98static int hwwep = 1;  /* default use hw. set 0 to use software security */
  99static int channels = 0x3fff;
 100
 101
 102
 103module_param(ifname, charp, 0644);
 104module_param(hwwep, int, 0644);
 105module_param(channels, int, 0644);
 106
 107MODULE_PARM_DESC(ifname, " Net interface name, wlan%d=default");
 108MODULE_PARM_DESC(hwwep, " Try to use hardware security support. ");
 109MODULE_PARM_DESC(channels, " Channel bitmask for specific locales. NYI");
 110
 111static int rtl8192_usb_probe(struct usb_interface *intf,
 112                             const struct usb_device_id *id);
 113static void rtl8192_usb_disconnect(struct usb_interface *intf);
 114
 115
 116static 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
 126struct CHANNEL_LIST {
 127        u8      Channel[32];
 128        u8      Len;
 129};
 130
 131static 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
 156static 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
 213static 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
 226int 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
 249int 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. */
 274int 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
 301int 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
 328int 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
 357int 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
 384int 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
 409static 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
 433int 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 */
 464inline void force_pci_posting(struct net_device *dev)
 465{
 466}
 467
 468static struct net_device_stats *rtl8192_stats(struct net_device *dev);
 469static void rtl8192_restart(struct work_struct *work);
 470static void watch_dog_timer_callback(struct timer_list *t);
 471
 472/****************************************************************************
 473 *   -----------------------------PROCFS STUFF-------------------------
 474 ****************************************************************************/
 475
 476static struct proc_dir_entry *rtl8192_proc;
 477
 478static 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
 497static 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
 538static 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
 597static 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
 613static 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
 619static 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
 640static 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
 649short 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
 657static 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
 664void 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
 692void 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
 708static void rtl8192_rx_isr(struct urb *urb);
 709
 710static 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
 716void 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
 768void 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
 811void 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 */
 839static 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
 892static 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
 905static void rtl8192_data_hard_stop(struct net_device *dev)
 906{
 907        /* FIXME !! */
 908}
 909
 910
 911static 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 */
 919static 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 */
 946static 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
 972static 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
1034static 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
1130static 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
1156static 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 */
1189void rtl819xusb_beacon_tx(struct net_device *dev, u16  tx_rate)
1190{
1191
1192}
1193
1194short 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 */
1245static 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
1291static 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
1393static 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
1407static 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 */
1416short 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
1594static 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
1658static 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
1678void 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
1707static void rtl8192_update_ratr_table(struct net_device *dev);
1708static 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
1737static 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
1746static 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 */
1764static int WDCAPARA_ADD[] = {EDCAPARA_BE, EDCAPARA_BK,
1765                             EDCAPARA_VI, EDCAPARA_VO};
1766static 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
1807success:
1808        mutex_unlock(&priv->mutex);
1809}
1810
1811static 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 */
1856static 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 */
1872static 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
1921static 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
1933static 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
1977static u8 ccmp_ie[4] = {0x00, 0x50, 0xf2, 0x04};
1978static u8 ccmp_rsn_ie[4] = {0x00, 0x0f, 0xac, 0x04};
1979static 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
2013static bool GetHalfNmodeSupportByAPs819xUsb(struct net_device *dev)
2014{
2015        struct r8192_priv *priv = ieee80211_priv(dev);
2016
2017        return priv->ieee80211->bHalfWirelessN24GMode;
2018}
2019
2020static 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
2034static 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
2055static 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#ifdef TO_DO_LIST
2080        /* TODO: this function doesn't work well at this time,
2081         * we should wait for FPGA
2082         */
2083        ActUpdateChannelAccessSetting(
2084                        pAdapter, pHalData->CurrentWirelessMode,
2085                        &pAdapter->MgntInfo.Info8185.ChannelAccessSetting);
2086#endif
2087        priv->ieee80211->mode = wireless_mode;
2088
2089        if (wireless_mode == WIRELESS_MODE_N_24G ||
2090            wireless_mode == WIRELESS_MODE_N_5G)
2091                priv->ieee80211->pHTInfo->bEnableHT = 1;
2092        else
2093                priv->ieee80211->pHTInfo->bEnableHT = 0;
2094        RT_TRACE(COMP_INIT, "Current Wireless Mode is %x\n", wireless_mode);
2095        rtl8192_refresh_supportrate(priv);
2096}
2097
2098/* init priv variables here. only non_zero value should be initialized here. */
2099static void rtl8192_init_priv_variable(struct net_device *dev)
2100{
2101        struct r8192_priv *priv = ieee80211_priv(dev);
2102        u8 i;
2103
2104        priv->card_8192 = NIC_8192U;
2105        priv->chan = 1; /* set to channel 1 */
2106        priv->ieee80211->mode = WIRELESS_MODE_AUTO; /* SET AUTO */
2107        priv->ieee80211->iw_mode = IW_MODE_INFRA;
2108        priv->ieee80211->ieee_up = 0;
2109        priv->retry_rts = DEFAULT_RETRY_RTS;
2110        priv->retry_data = DEFAULT_RETRY_DATA;
2111        priv->ieee80211->rts = DEFAULT_RTS_THRESHOLD;
2112        priv->ieee80211->rate = 110; /* 11 mbps */
2113        priv->ieee80211->short_slot = 1;
2114        priv->promisc = (dev->flags & IFF_PROMISC) ? 1 : 0;
2115        priv->CckPwEnl = 6;
2116        /* for silent reset */
2117        priv->IrpPendingCount = 1;
2118        priv->ResetProgress = RESET_TYPE_NORESET;
2119        priv->bForcedSilentReset = false;
2120        priv->bDisableNormalResetCheck = false;
2121        priv->force_reset = false;
2122
2123        /* we don't use FW read/write RF until stable firmware is available. */
2124        priv->ieee80211->FwRWRF = 0;
2125        priv->ieee80211->current_network.beacon_interval =
2126                DEFAULT_BEACONINTERVAL;
2127        priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
2128                IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
2129                IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE |
2130                IEEE_SOFTMAC_BEACONS;
2131
2132        priv->ieee80211->active_scan = 1;
2133        priv->ieee80211->modulation =
2134                IEEE80211_CCK_MODULATION | IEEE80211_OFDM_MODULATION;
2135        priv->ieee80211->host_encrypt = 1;
2136        priv->ieee80211->host_decrypt = 1;
2137        priv->ieee80211->start_send_beacons = NULL;
2138        priv->ieee80211->stop_send_beacons = NULL;
2139        priv->ieee80211->softmac_hard_start_xmit = rtl8192_hard_start_xmit;
2140        priv->ieee80211->set_chan = rtl8192_set_chan;
2141        priv->ieee80211->link_change = rtl8192_link_change;
2142        priv->ieee80211->softmac_data_hard_start_xmit = rtl8192_hard_data_xmit;
2143        priv->ieee80211->data_hard_stop = rtl8192_data_hard_stop;
2144        priv->ieee80211->data_hard_resume = rtl8192_data_hard_resume;
2145        priv->ieee80211->init_wmmparam_flag = 0;
2146        priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
2147        priv->ieee80211->check_nic_enough_desc = check_nic_enough_desc;
2148        priv->ieee80211->tx_headroom = TX_PACKET_SHIFT_BYTES;
2149        priv->ieee80211->qos_support = 1;
2150
2151        priv->ieee80211->SetBWModeHandler = rtl8192_SetBWMode;
2152        priv->ieee80211->handle_assoc_response = rtl8192_handle_assoc_response;
2153        priv->ieee80211->handle_beacon = rtl8192_handle_beacon;
2154
2155        priv->ieee80211->GetNmodeSupportBySecCfg = GetNmodeSupportBySecCfg8192;
2156        priv->ieee80211->GetHalfNmodeSupportByAPsHandler =
2157                GetHalfNmodeSupportByAPs819xUsb;
2158        priv->ieee80211->SetWirelessMode = rtl8192_SetWirelessMode;
2159
2160        priv->ieee80211->InitialGainHandler = InitialGain819xUsb;
2161        priv->card_type = USB;
2162#ifdef TO_DO_LIST
2163        if (Adapter->bInHctTest) {
2164                pHalData->ShortRetryLimit = 7;
2165                pHalData->LongRetryLimit = 7;
2166        }
2167#endif
2168        priv->ShortRetryLimit = 0x30;
2169        priv->LongRetryLimit = 0x30;
2170        priv->EarlyRxThreshold = 7;
2171        priv->enable_gpio0 = 0;
2172        priv->TransmitConfig =
2173                /* Max DMA Burst Size per Tx DMA Burst, 7: reserved. */
2174                (TCR_MXDMA_2048 << TCR_MXDMA_OFFSET)      |
2175                /* Short retry limit */
2176                (priv->ShortRetryLimit << TCR_SRL_OFFSET) |
2177                /* Long retry limit */
2178                (priv->LongRetryLimit << TCR_LRL_OFFSET)  |
2179                /* FALSE: HW provides PLCP length and LENGEXT
2180                 * TRUE: SW provides them
2181                 */
2182                (false ? TCR_SAT : 0);
2183#ifdef TO_DO_LIST
2184        if (Adapter->bInHctTest)
2185                pHalData->ReceiveConfig =
2186                        pHalData->CSMethod |
2187                        /* accept management/data */
2188                        RCR_AMF | RCR_ADF |
2189                        /* accept control frame for SW
2190                         * AP needs PS-poll
2191                         */
2192                        RCR_ACF |
2193                        /* accept BC/MC/UC */
2194                        RCR_AB | RCR_AM | RCR_APM |
2195                        /* accept ICV/CRC error
2196                         * packet
2197                         */
2198                        RCR_AICV | RCR_ACRC32 |
2199                        /* Max DMA Burst Size per Tx
2200                         * DMA Burst, 7: unlimited.
2201                         */
2202                        ((u32)7 << RCR_MXDMA_OFFSET) |
2203                        /* Rx FIFO Threshold,
2204                         * 7: No Rx threshold.
2205                         */
2206                        (pHalData->EarlyRxThreshold << RCR_FIFO_OFFSET) |
2207                        (pHalData->EarlyRxThreshold == 7 ? RCR_OnlyErlPkt : 0);
2208        else
2209
2210#endif
2211        priv->ReceiveConfig     =
2212                /* accept management/data */
2213                RCR_AMF | RCR_ADF |
2214                /* accept control frame for SW AP needs PS-poll */
2215                RCR_ACF |
2216                /* accept BC/MC/UC */
2217                RCR_AB | RCR_AM | RCR_APM |
2218                /* Max DMA Burst Size per Rx DMA Burst, 7: unlimited. */
2219                ((u32)7 << RCR_MXDMA_OFFSET) |
2220                /* Rx FIFO Threshold, 7: No Rx threshold. */
2221                (priv->EarlyRxThreshold << RX_FIFO_THRESHOLD_SHIFT) |
2222                (priv->EarlyRxThreshold == 7 ? RCR_ONLYERLPKT : 0);
2223
2224        priv->AcmControl = 0;
2225        priv->pFirmware = kzalloc(sizeof(rt_firmware), GFP_KERNEL);
2226
2227        /* rx related queue */
2228        skb_queue_head_init(&priv->rx_queue);
2229        skb_queue_head_init(&priv->skb_queue);
2230
2231        /* Tx related queue */
2232        for (i = 0; i < MAX_QUEUE_SIZE; i++)
2233                skb_queue_head_init(&priv->ieee80211->skb_waitQ[i]);
2234        for (i = 0; i < MAX_QUEUE_SIZE; i++)
2235                skb_queue_head_init(&priv->ieee80211->skb_aggQ[i]);
2236        for (i = 0; i < MAX_QUEUE_SIZE; i++)
2237                skb_queue_head_init(&priv->ieee80211->skb_drv_aggQ[i]);
2238        priv->rf_set_chan = rtl8192_phy_SwChnl;
2239}
2240
2241/* init lock here */
2242static void rtl8192_init_priv_lock(struct r8192_priv *priv)
2243{
2244        spin_lock_init(&priv->tx_lock);
2245        spin_lock_init(&priv->irq_lock);
2246        mutex_init(&priv->wx_mutex);
2247        mutex_init(&priv->mutex);
2248}
2249
2250static void rtl819x_watchdog_wqcallback(struct work_struct *work);
2251
2252static void rtl8192_irq_rx_tasklet(struct r8192_priv *priv);
2253/* init tasklet and wait_queue here. only 2.6 above kernel is considered */
2254#define DRV_NAME "wlan0"
2255static void rtl8192_init_priv_task(struct net_device *dev)
2256{
2257        struct r8192_priv *priv = ieee80211_priv(dev);
2258
2259
2260        INIT_WORK(&priv->reset_wq, rtl8192_restart);
2261
2262        INIT_DELAYED_WORK(&priv->watch_dog_wq,
2263                          rtl819x_watchdog_wqcallback);
2264        INIT_DELAYED_WORK(&priv->txpower_tracking_wq,
2265                          dm_txpower_trackingcallback);
2266        INIT_DELAYED_WORK(&priv->rfpath_check_wq,
2267                          dm_rf_pathcheck_workitemcallback);
2268        INIT_DELAYED_WORK(&priv->update_beacon_wq,
2269                          rtl8192_update_beacon);
2270        INIT_DELAYED_WORK(&priv->initialgain_operate_wq,
2271                          InitialGainOperateWorkItemCallBack);
2272        INIT_WORK(&priv->qos_activate, rtl8192_qos_activate);
2273
2274        tasklet_init(&priv->irq_rx_tasklet,
2275                     (void(*)(unsigned long))rtl8192_irq_rx_tasklet,
2276                     (unsigned long)priv);
2277}
2278
2279static void rtl8192_get_eeprom_size(struct net_device *dev)
2280{
2281        u16 curCR = 0;
2282        struct r8192_priv *priv = ieee80211_priv(dev);
2283
2284        RT_TRACE(COMP_EPROM, "===========>%s()\n", __func__);
2285        read_nic_word_E(dev, EPROM_CMD, &curCR);
2286        RT_TRACE(COMP_EPROM,
2287                 "read from Reg EPROM_CMD(%x):%x\n", EPROM_CMD, curCR);
2288        /* whether need I consider BIT(5?) */
2289        priv->epromtype =
2290                (curCR & Cmd9346CR_9356SEL) ? EPROM_93c56 : EPROM_93c46;
2291        RT_TRACE(COMP_EPROM,
2292                 "<===========%s(), epromtype:%d\n", __func__, priv->epromtype);
2293}
2294
2295/* used to swap endian. as ntohl & htonl are not necessary
2296 * to swap endian, so use this instead.
2297 */
2298static inline u16 endian_swap(u16 *data)
2299{
2300        u16 tmp = *data;
2301        *data = (tmp >> 8) | (tmp << 8);
2302        return *data;
2303}
2304
2305static int rtl8192_read_eeprom_info(struct net_device *dev)
2306{
2307        u16 wEPROM_ID = 0;
2308        u8 bMac_Tmp_Addr[6] = {0x00, 0xe0, 0x4c, 0x00, 0x00, 0x02};
2309        u8 bLoad_From_EEPOM = false;
2310        struct r8192_priv *priv = ieee80211_priv(dev);
2311        u16 tmpValue = 0;
2312        int i;
2313        int ret;
2314
2315        RT_TRACE(COMP_EPROM, "===========>%s()\n", __func__);
2316        ret = eprom_read(dev, 0); /* first read EEPROM ID out; */
2317        if (ret < 0)
2318                return ret;
2319        wEPROM_ID = (u16)ret;
2320        RT_TRACE(COMP_EPROM, "EEPROM ID is 0x%x\n", wEPROM_ID);
2321
2322        if (wEPROM_ID != RTL8190_EEPROM_ID)
2323                RT_TRACE(COMP_ERR,
2324                         "EEPROM ID is invalid(is 0x%x(should be 0x%x)\n",
2325                         wEPROM_ID, RTL8190_EEPROM_ID);
2326        else
2327                bLoad_From_EEPOM = true;
2328
2329        if (bLoad_From_EEPOM) {
2330                tmpValue = eprom_read(dev, EEPROM_VID >> 1);
2331                ret = eprom_read(dev, EEPROM_VID >> 1);
2332                if (ret < 0)
2333                        return ret;
2334                tmpValue = (u16)ret;
2335                priv->eeprom_vid = endian_swap(&tmpValue);
2336                ret = eprom_read(dev, EEPROM_PID >> 1);
2337                if (ret < 0)
2338                        return ret;
2339                priv->eeprom_pid = (u16)ret;
2340                ret = eprom_read(dev, EEPROM_CHANNEL_PLAN >> 1);
2341                if (ret < 0)
2342                        return ret;
2343                tmpValue = (u16)ret;
2344                priv->eeprom_ChannelPlan = (tmpValue & 0xff00) >> 8;
2345                priv->btxpowerdata_readfromEEPORM = true;
2346                ret = eprom_read(dev, (EEPROM_CUSTOMER_ID >> 1)) >> 8;
2347                if (ret < 0)
2348                        return ret;
2349                priv->eeprom_CustomerID = (u16)ret;
2350        } else {
2351                priv->eeprom_vid = 0;
2352                priv->eeprom_pid = 0;
2353                priv->card_8192_version = VERSION_819XU_B;
2354                priv->eeprom_ChannelPlan = 0;
2355                priv->eeprom_CustomerID = 0;
2356        }
2357        RT_TRACE(COMP_EPROM,
2358                 "vid:0x%4x, pid:0x%4x, CustomID:0x%2x, ChanPlan:0x%x\n",
2359                 priv->eeprom_vid, priv->eeprom_pid, priv->eeprom_CustomerID,
2360                 priv->eeprom_ChannelPlan);
2361        /* set channelplan from eeprom */
2362        priv->ChannelPlan = priv->eeprom_ChannelPlan;
2363        if (bLoad_From_EEPOM) {
2364                int i;
2365
2366                for (i = 0; i < 6; i += 2) {
2367                        ret = eprom_read(dev, (u16)((EEPROM_NODE_ADDRESS_BYTE_0 + i) >> 1));
2368                        if (ret < 0)
2369                                return ret;
2370                        *(u16 *)(&dev->dev_addr[i]) = (u16)ret;
2371                }
2372        } else {
2373                memcpy(dev->dev_addr, bMac_Tmp_Addr, 6);
2374                /* should I set IDR0 here? */
2375        }
2376        RT_TRACE(COMP_EPROM, "MAC addr:%pM\n", dev->dev_addr);
2377        priv->rf_type = RTL819X_DEFAULT_RF_TYPE; /* default 1T2R */
2378        priv->rf_chip = RF_8256;
2379
2380        if (priv->card_8192_version == VERSION_819XU_A) {
2381                /* read Tx power gain offset of legacy OFDM to HT rate */
2382                if (bLoad_From_EEPOM) {
2383                        ret = eprom_read(dev, (EEPROM_TX_POWER_DIFF >> 1));
2384                        if (ret < 0)
2385                                return ret;
2386                        priv->EEPROMTxPowerDiff = ((u16)ret & 0xff00) >> 8;
2387                } else
2388                        priv->EEPROMTxPowerDiff = EEPROM_DEFAULT_TX_POWER;
2389                RT_TRACE(COMP_EPROM, "TxPowerDiff:%d\n", priv->EEPROMTxPowerDiff);
2390                /* read ThermalMeter from EEPROM */
2391                if (bLoad_From_EEPOM) {
2392                        ret = eprom_read(dev, (EEPROM_THERMAL_METER >> 1));
2393                        if (ret < 0)
2394                                return ret;
2395                        priv->EEPROMThermalMeter = (u8)((u16)ret & 0x00ff);
2396                } else
2397                        priv->EEPROMThermalMeter = EEPROM_DEFAULT_THERNAL_METER;
2398                RT_TRACE(COMP_EPROM, "ThermalMeter:%d\n", priv->EEPROMThermalMeter);
2399                /* for tx power track */
2400                priv->TSSI_13dBm = priv->EEPROMThermalMeter * 100;
2401                /* read antenna tx power offset of B/C/D to A from EEPROM */
2402                if (bLoad_From_EEPOM) {
2403                        ret = eprom_read(dev, (EEPROM_PW_DIFF >> 1));
2404                        if (ret < 0)
2405                                return ret;
2406                        priv->EEPROMPwDiff = ((u16)ret & 0x0f00) >> 8;
2407                } else
2408                        priv->EEPROMPwDiff = EEPROM_DEFAULT_PW_DIFF;
2409                RT_TRACE(COMP_EPROM, "TxPwDiff:%d\n", priv->EEPROMPwDiff);
2410                /* Read CrystalCap from EEPROM */
2411                if (bLoad_From_EEPOM) {
2412                        ret = eprom_read(dev, (EEPROM_CRYSTAL_CAP >> 1));
2413                        if (ret < 0)
2414                                return ret;
2415                        priv->EEPROMCrystalCap = (u16)ret & 0x0f;
2416                } else
2417                        priv->EEPROMCrystalCap = EEPROM_DEFAULT_CRYSTAL_CAP;
2418                RT_TRACE(COMP_EPROM, "CrystalCap = %d\n", priv->EEPROMCrystalCap);
2419                /* get per-channel Tx power level */
2420                if (bLoad_From_EEPOM) {
2421                        ret = eprom_read(dev, (EEPROM_TX_PW_INDEX_VER >> 1));
2422                        if (ret < 0)
2423                                return ret;
2424                        priv->EEPROM_Def_Ver = ((u16)ret & 0xff00) >> 8;
2425                } else
2426                        priv->EEPROM_Def_Ver = 1;
2427                RT_TRACE(COMP_EPROM, "EEPROM_DEF_VER:%d\n", priv->EEPROM_Def_Ver);
2428                if (priv->EEPROM_Def_Ver == 0) { /* old eeprom definition */
2429                        int i;
2430
2431                        if (bLoad_From_EEPOM) {
2432                                ret = eprom_read(dev, (EEPROM_TX_PW_INDEX_CCK >> 1));
2433                                if (ret < 0)
2434                                        return ret;
2435                                priv->EEPROMTxPowerLevelCCK = ((u16)ret & 0xff) >> 8;
2436                        } else
2437                                priv->EEPROMTxPowerLevelCCK = 0x10;
2438                        RT_TRACE(COMP_EPROM, "CCK Tx Power Levl: 0x%02x\n", priv->EEPROMTxPowerLevelCCK);
2439                        for (i = 0; i < 3; i++) {
2440                                if (bLoad_From_EEPOM) {
2441                                        ret = eprom_read(dev, (EEPROM_TX_PW_INDEX_OFDM_24G + i) >> 1);
2442                                        if (ret < 0)
2443                                                return ret;
2444                                        if (((EEPROM_TX_PW_INDEX_OFDM_24G + i) % 2) == 0)
2445                                                tmpValue = (u16)ret & 0x00ff;
2446                                        else
2447                                                tmpValue = ((u16)ret & 0xff00) >> 8;
2448                                } else {
2449                                        tmpValue = 0x10;
2450                                }
2451                                priv->EEPROMTxPowerLevelOFDM24G[i] = (u8)tmpValue;
2452                                RT_TRACE(COMP_EPROM, "OFDM 2.4G Tx Power Level, Index %d = 0x%02x\n", i, priv->EEPROMTxPowerLevelCCK);
2453                        }
2454                } else if (priv->EEPROM_Def_Ver == 1) {
2455                        if (bLoad_From_EEPOM) {
2456                                ret = eprom_read(dev, EEPROM_TX_PW_INDEX_CCK_V1 >> 1);
2457                                if (ret < 0)
2458                                        return ret;
2459                                tmpValue = ((u16)ret & 0xff00) >> 8;
2460                        } else {
2461                                tmpValue = 0x10;
2462                        }
2463                        priv->EEPROMTxPowerLevelCCK_V1[0] = (u8)tmpValue;
2464
2465                        if (bLoad_From_EEPOM) {
2466                                ret = eprom_read(dev, (EEPROM_TX_PW_INDEX_CCK_V1 + 2) >> 1);
2467                                if (ret < 0)
2468                                        return ret;
2469                                tmpValue = (u16)ret;
2470                        } else
2471                                tmpValue = 0x1010;
2472                        *((u16 *)(&priv->EEPROMTxPowerLevelCCK_V1[1])) = tmpValue;
2473                        if (bLoad_From_EEPOM)
2474                                tmpValue = eprom_read(dev,
2475                                        EEPROM_TX_PW_INDEX_OFDM_24G_V1 >> 1);
2476                        else
2477                                tmpValue = 0x1010;
2478                        *((u16 *)(&priv->EEPROMTxPowerLevelOFDM24G[0])) = tmpValue;
2479                        if (bLoad_From_EEPOM)
2480                                tmpValue = eprom_read(dev, (EEPROM_TX_PW_INDEX_OFDM_24G_V1 + 2) >> 1);
2481                        else
2482                                tmpValue = 0x10;
2483                        priv->EEPROMTxPowerLevelOFDM24G[2] = (u8)tmpValue;
2484                } /* endif EEPROM_Def_Ver == 1 */
2485
2486                /* update HAL variables */
2487                for (i = 0; i < 14; i++) {
2488                        if (i <= 3)
2489                                priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[0];
2490                        else if (i >= 4 && i <= 9)
2491                                priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[1];
2492                        else
2493                                priv->TxPowerLevelOFDM24G[i] = priv->EEPROMTxPowerLevelOFDM24G[2];
2494                }
2495
2496                for (i = 0; i < 14; i++) {
2497                        if (priv->EEPROM_Def_Ver == 0) {
2498                                if (i <= 3)
2499                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[0] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
2500                                else if (i >= 4 && i <= 9)
2501                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK;
2502                                else
2503                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelOFDM24G[2] + (priv->EEPROMTxPowerLevelCCK - priv->EEPROMTxPowerLevelOFDM24G[1]);
2504                        } else if (priv->EEPROM_Def_Ver == 1) {
2505                                if (i <= 3)
2506                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[0];
2507                                else if (i >= 4 && i <= 9)
2508                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[1];
2509                                else
2510                                        priv->TxPowerLevelCCK[i] = priv->EEPROMTxPowerLevelCCK_V1[2];
2511                        }
2512                }
2513                priv->TxPowerDiff = priv->EEPROMPwDiff;
2514                /* Antenna B gain offset to antenna A, bit0~3 */
2515                priv->AntennaTxPwDiff[0] = (priv->EEPROMTxPowerDiff & 0xf);
2516                /* Antenna C gain offset to antenna A, bit4~7 */
2517                priv->AntennaTxPwDiff[1] =
2518                        (priv->EEPROMTxPowerDiff & 0xf0) >> 4;
2519                /* CrystalCap, bit12~15 */
2520                priv->CrystalCap = priv->EEPROMCrystalCap;
2521                /* ThermalMeter, bit0~3 for RFIC1, bit4~7 for RFIC2
2522                 * 92U does not enable TX power tracking.
2523                 */
2524                priv->ThermalMeter[0] = priv->EEPROMThermalMeter;
2525        } /* end if VersionID == VERSION_819XU_A */
2526
2527        /* for dlink led */
2528        switch (priv->eeprom_CustomerID) {
2529        case EEPROM_CID_RUNTOP:
2530                priv->CustomerID = RT_CID_819x_RUNTOP;
2531                break;
2532
2533        case EEPROM_CID_DLINK:
2534                priv->CustomerID = RT_CID_DLINK;
2535                break;
2536
2537        default:
2538                priv->CustomerID = RT_CID_DEFAULT;
2539                break;
2540        }
2541
2542        switch (priv->CustomerID) {
2543        case RT_CID_819x_RUNTOP:
2544                priv->LedStrategy = SW_LED_MODE2;
2545                break;
2546
2547        case RT_CID_DLINK:
2548                priv->LedStrategy = SW_LED_MODE4;
2549                break;
2550
2551        default:
2552                priv->LedStrategy = SW_LED_MODE0;
2553                break;
2554        }
2555
2556
2557        if (priv->rf_type == RF_1T2R)
2558                RT_TRACE(COMP_EPROM, "\n1T2R config\n");
2559        else
2560                RT_TRACE(COMP_EPROM, "\n2T4R config\n");
2561
2562        /* We can only know RF type in the function. So we have to init
2563         * DIG RATR table again.
2564         */
2565        init_rate_adaptive(dev);
2566
2567        RT_TRACE(COMP_EPROM, "<===========%s()\n", __func__);
2568
2569        return 0;
2570}
2571
2572static short rtl8192_get_channel_map(struct net_device *dev)
2573{
2574        struct r8192_priv *priv = ieee80211_priv(dev);
2575
2576        if (priv->ChannelPlan > COUNTRY_CODE_GLOBAL_DOMAIN) {
2577                netdev_err(dev,
2578                           "rtl8180_init: Error channel plan! Set to default.\n");
2579                priv->ChannelPlan = 0;
2580        }
2581        RT_TRACE(COMP_INIT, "Channel plan is %d\n", priv->ChannelPlan);
2582
2583        rtl819x_set_channel_map(priv->ChannelPlan, priv);
2584        return 0;
2585}
2586
2587static short rtl8192_init(struct net_device *dev)
2588{
2589        struct r8192_priv *priv = ieee80211_priv(dev);
2590        int err;
2591
2592        memset(&(priv->stats), 0, sizeof(struct Stats));
2593        memset(priv->txqueue_to_outpipemap, 0, 9);
2594#ifdef PIPE12
2595        {
2596                int i = 0;
2597                u8 queuetopipe[] = {3, 2, 1, 0, 4, 8, 7, 6, 5};
2598
2599                memcpy(priv->txqueue_to_outpipemap, queuetopipe, 9);
2600        }
2601#else
2602        {
2603                u8 queuetopipe[] = {3, 2, 1, 0, 4, 4, 0, 4, 4};
2604
2605                memcpy(priv->txqueue_to_outpipemap, queuetopipe, 9);
2606        }
2607#endif
2608        rtl8192_init_priv_variable(dev);
2609        rtl8192_init_priv_lock(priv);
2610        rtl8192_init_priv_task(dev);
2611        rtl8192_get_eeprom_size(dev);
2612        err = rtl8192_read_eeprom_info(dev);
2613        if (err) {
2614                DMESG("Reading EEPROM info failed");
2615                return err;
2616        }
2617        rtl8192_get_channel_map(dev);
2618        init_hal_dm(dev);
2619        timer_setup(&priv->watch_dog_timer, watch_dog_timer_callback, 0);
2620        if (rtl8192_usb_initendpoints(dev) != 0) {
2621                DMESG("Endopoints initialization failed");
2622                return -ENOMEM;
2623        }
2624
2625        return 0;
2626}
2627
2628/******************************************************************************
2629 *function:  This function actually only set RRSR, RATR and BW_OPMODE registers
2630 *           not to do all the hw config as its name says
2631 *   input:  net_device dev
2632 *  output:  none
2633 *  return:  none
2634 *  notice:  This part need to modified according to the rate set we filtered
2635 * ****************************************************************************/
2636static void rtl8192_hwconfig(struct net_device *dev)
2637{
2638        u32 regRATR = 0, regRRSR = 0;
2639        u8 regBwOpMode = 0, regTmp = 0;
2640        struct r8192_priv *priv = ieee80211_priv(dev);
2641        u32 ratr_value = 0;
2642
2643        /* Set RRSR, RATR, and BW_OPMODE registers */
2644        switch (priv->ieee80211->mode) {
2645        case WIRELESS_MODE_B:
2646                regBwOpMode = BW_OPMODE_20MHZ;
2647                regRATR = RATE_ALL_CCK;
2648                regRRSR = RATE_ALL_CCK;
2649                break;
2650        case WIRELESS_MODE_A:
2651                regBwOpMode = BW_OPMODE_5G | BW_OPMODE_20MHZ;
2652                regRATR = RATE_ALL_OFDM_AG;
2653                regRRSR = RATE_ALL_OFDM_AG;
2654                break;
2655        case WIRELESS_MODE_G:
2656                regBwOpMode = BW_OPMODE_20MHZ;
2657                regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2658                regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2659                break;
2660        case WIRELESS_MODE_AUTO:
2661#ifdef TO_DO_LIST
2662                if (Adapter->bInHctTest) {
2663                        regBwOpMode = BW_OPMODE_20MHZ;
2664                        regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2665                        regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2666                } else
2667#endif
2668                {
2669                        regBwOpMode = BW_OPMODE_20MHZ;
2670                        regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG |
2671                                  RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
2672                        regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2673                }
2674                break;
2675        case WIRELESS_MODE_N_24G:
2676                /* It support CCK rate by default. CCK rate will be filtered
2677                 * out only when associated AP does not support it.
2678                 */
2679                regBwOpMode = BW_OPMODE_20MHZ;
2680                regRATR = RATE_ALL_CCK | RATE_ALL_OFDM_AG |
2681                          RATE_ALL_OFDM_1SS | RATE_ALL_OFDM_2SS;
2682                regRRSR = RATE_ALL_CCK | RATE_ALL_OFDM_AG;
2683                break;
2684        case WIRELESS_MODE_N_5G:
2685                regBwOpMode = BW_OPMODE_5G;
2686                regRATR = RATE_ALL_OFDM_AG | RATE_ALL_OFDM_1SS |
2687                          RATE_ALL_OFDM_2SS;
2688                regRRSR = RATE_ALL_OFDM_AG;
2689                break;
2690        }
2691
2692        write_nic_byte(dev, BW_OPMODE, regBwOpMode);
2693        ratr_value = regRATR;
2694        if (priv->rf_type == RF_1T2R)
2695                ratr_value &= ~(RATE_ALL_OFDM_2SS);
2696        write_nic_dword(dev, RATR0, ratr_value);
2697        write_nic_byte(dev, UFWP, 1);
2698        read_nic_byte(dev, 0x313, &regTmp);
2699        regRRSR = ((regTmp) << 24) | (regRRSR & 0x00ffffff);
2700        write_nic_dword(dev, RRSR, regRRSR);
2701
2702        /* Set Retry Limit here */
2703        write_nic_word(dev, RETRY_LIMIT,
2704                       priv->ShortRetryLimit << RETRY_LIMIT_SHORT_SHIFT |
2705                       priv->LongRetryLimit << RETRY_LIMIT_LONG_SHIFT);
2706        /* Set Contention Window here */
2707
2708        /* Set Tx AGC */
2709
2710        /* Set Tx Antenna including Feedback control */
2711
2712        /* Set Auto Rate fallback control */
2713}
2714
2715
2716/* InitializeAdapter and PhyCfg */
2717static bool rtl8192_adapter_start(struct net_device *dev)
2718{
2719        struct r8192_priv *priv = ieee80211_priv(dev);
2720        u32 dwRegRead = 0;
2721        bool init_status = true;
2722        u8 SECR_value = 0x0;
2723        u8 tmp;
2724
2725        RT_TRACE(COMP_INIT, "====>%s()\n", __func__);
2726        priv->Rf_Mode = RF_OP_By_SW_3wire;
2727        /* for ASIC power on sequence */
2728        write_nic_byte_E(dev, 0x5f, 0x80);
2729        mdelay(50);
2730        write_nic_byte_E(dev, 0x5f, 0xf0);
2731        write_nic_byte_E(dev, 0x5d, 0x00);
2732        write_nic_byte_E(dev, 0x5e, 0x80);
2733        write_nic_byte(dev, 0x17, 0x37);
2734        mdelay(10);
2735        priv->pFirmware->firmware_status = FW_STATUS_0_INIT;
2736        /* config CPUReset Register */
2737        /* Firmware Reset or not? */
2738        read_nic_dword(dev, CPU_GEN, &dwRegRead);
2739        if (priv->pFirmware->firmware_status == FW_STATUS_0_INIT)
2740                dwRegRead |= CPU_GEN_SYSTEM_RESET; /* do nothing here? */
2741        else if (priv->pFirmware->firmware_status == FW_STATUS_5_READY)
2742                dwRegRead |= CPU_GEN_FIRMWARE_RESET;
2743        else
2744                RT_TRACE(COMP_ERR,
2745                         "ERROR in %s(): undefined firmware state(%d)\n",
2746                         __func__,   priv->pFirmware->firmware_status);
2747
2748        write_nic_dword(dev, CPU_GEN, dwRegRead);
2749        /* config BB. */
2750        rtl8192_BBConfig(dev);
2751
2752        /* Loopback mode or not */
2753        priv->LoopbackMode = RTL819xU_NO_LOOPBACK;
2754
2755        read_nic_dword(dev, CPU_GEN, &dwRegRead);
2756        if (priv->LoopbackMode == RTL819xU_NO_LOOPBACK)
2757                dwRegRead = (dwRegRead & CPU_GEN_NO_LOOPBACK_MSK) |
2758                            CPU_GEN_NO_LOOPBACK_SET;
2759        else if (priv->LoopbackMode == RTL819xU_MAC_LOOPBACK)
2760                dwRegRead |= CPU_CCK_LOOPBACK;
2761        else
2762                RT_TRACE(COMP_ERR,
2763                         "Serious error in %s(): wrong loopback mode setting(%d)\n",
2764                         __func__,  priv->LoopbackMode);
2765
2766        write_nic_dword(dev, CPU_GEN, dwRegRead);
2767
2768        /* after reset cpu, we need wait for a seconds to write in register. */
2769        udelay(500);
2770
2771        /* add for new bitfile:usb suspend reset pin set to 1. Do we need? */
2772        read_nic_byte_E(dev, 0x5f, &tmp);
2773        write_nic_byte_E(dev, 0x5f, tmp | 0x20);
2774
2775        /* Set Hardware */
2776        rtl8192_hwconfig(dev);
2777
2778        /* turn on Tx/Rx */
2779        write_nic_byte(dev, CMDR, CR_RE | CR_TE);
2780
2781        /* set IDR0 here */
2782        write_nic_dword(dev, MAC0, ((u32 *)dev->dev_addr)[0]);
2783        write_nic_word(dev, MAC4, ((u16 *)(dev->dev_addr + 4))[0]);
2784
2785        /* set RCR */
2786        write_nic_dword(dev, RCR, priv->ReceiveConfig);
2787
2788        /* Initialize Number of Reserved Pages in Firmware Queue */
2789        write_nic_dword(dev, RQPN1,
2790                NUM_OF_PAGE_IN_FW_QUEUE_BK << RSVD_FW_QUEUE_PAGE_BK_SHIFT |
2791                NUM_OF_PAGE_IN_FW_QUEUE_BE << RSVD_FW_QUEUE_PAGE_BE_SHIFT |
2792                NUM_OF_PAGE_IN_FW_QUEUE_VI << RSVD_FW_QUEUE_PAGE_VI_SHIFT |
2793                NUM_OF_PAGE_IN_FW_QUEUE_VO << RSVD_FW_QUEUE_PAGE_VO_SHIFT);
2794        write_nic_dword(dev, RQPN2,
2795                NUM_OF_PAGE_IN_FW_QUEUE_MGNT << RSVD_FW_QUEUE_PAGE_MGNT_SHIFT |
2796                NUM_OF_PAGE_IN_FW_QUEUE_CMD << RSVD_FW_QUEUE_PAGE_CMD_SHIFT);
2797        write_nic_dword(dev, RQPN3,
2798                APPLIED_RESERVED_QUEUE_IN_FW |
2799                NUM_OF_PAGE_IN_FW_QUEUE_BCN << RSVD_FW_QUEUE_PAGE_BCN_SHIFT);
2800        write_nic_dword(dev, RATR0 + 4 * 7, (RATE_ALL_OFDM_AG | RATE_ALL_CCK));
2801
2802        /* Set AckTimeout */
2803        /* TODO: (it value is only for FPGA version). need to be changed!! */
2804        write_nic_byte(dev, ACK_TIMEOUT, 0x30);
2805
2806        if (priv->ResetProgress == RESET_TYPE_NORESET)
2807                rtl8192_SetWirelessMode(dev, priv->ieee80211->mode);
2808        if (priv->ResetProgress == RESET_TYPE_NORESET) {
2809                CamResetAllEntry(dev);
2810                SECR_value |= SCR_TxEncEnable;
2811                SECR_value |= SCR_RxDecEnable;
2812                SECR_value |= SCR_NoSKMC;
2813                write_nic_byte(dev, SECR, SECR_value);
2814        }
2815
2816        /* Beacon related */
2817        write_nic_word(dev, ATIMWND, 2);
2818        write_nic_word(dev, BCN_INTERVAL, 100);
2819
2820#define DEFAULT_EDCA 0x005e4332
2821        {
2822                int i;
2823
2824                for (i = 0; i < QOS_QUEUE_NUM; i++)
2825                        write_nic_dword(dev, WDCAPARA_ADD[i], DEFAULT_EDCA);
2826        }
2827
2828        rtl8192_phy_configmac(dev);
2829
2830        if (priv->card_8192_version == VERSION_819XU_A) {
2831                rtl8192_phy_getTxPower(dev);
2832                rtl8192_phy_setTxPower(dev, priv->chan);
2833        }
2834
2835        /* Firmware download */
2836        init_status = init_firmware(dev);
2837        if (!init_status) {
2838                RT_TRACE(COMP_ERR, "ERR!!! %s(): Firmware download is failed\n",
2839                         __func__);
2840                return init_status;
2841        }
2842        RT_TRACE(COMP_INIT, "%s():after firmware download\n", __func__);
2843
2844#ifdef TO_DO_LIST
2845        if (Adapter->ResetProgress == RESET_TYPE_NORESET) {
2846                if (pMgntInfo->RegRfOff) { /* User disable RF via registry. */
2847                        RT_TRACE((COMP_INIT | COMP_RF), DBG_LOUD,
2848                                 ("InitializeAdapter819xUsb(): Turn off RF for RegRfOff ----------\n"));
2849                        MgntActSet_RF_State(Adapter, eRfOff, RF_CHANGE_BY_SW);
2850                        /* Those actions will be discard in MgntActSet_RF_State
2851                         * because of the same state
2852                         */
2853                        for (eRFPath = 0; eRFPath < pHalData->NumTotalRFPath; eRFPath++)
2854                                PHY_SetRFReg(Adapter,
2855                                             (enum rf90_radio_path_e)eRFPath,
2856                                             0x4, 0xC00, 0x0);
2857                } else if (pMgntInfo->RfOffReason > RF_CHANGE_BY_PS) {
2858                        /* H/W or S/W RF OFF before sleep. */
2859                        RT_TRACE((COMP_INIT | COMP_RF), DBG_LOUD,
2860                                 ("InitializeAdapter819xUsb(): Turn off RF for RfOffReason(%d) ----------\n",
2861                                  pMgntInfo->RfOffReason));
2862                        MgntActSet_RF_State(Adapter,
2863                                            eRfOff,
2864                                            pMgntInfo->RfOffReason);
2865                } else {
2866                        pHalData->eRFPowerState = eRfOn;
2867                        pMgntInfo->RfOffReason = 0;
2868                        RT_TRACE((COMP_INIT | COMP_RF), DBG_LOUD,
2869                                 ("InitializeAdapter819xUsb(): RF is on ----------\n"));
2870                }
2871        } else {
2872                if (pHalData->eRFPowerState == eRfOff) {
2873                        MgntActSet_RF_State(Adapter,
2874                                            eRfOff,
2875                                            pMgntInfo->RfOffReason);
2876                        /* Those actions will be discard in MgntActSet_RF_State
2877                         * because of the same state
2878                         */
2879                        for (eRFPath = 0; eRFPath < pHalData->NumTotalRFPath; eRFPath++)
2880                                PHY_SetRFReg(Adapter,
2881                                             (enum rf90_radio_path_e)eRFPath,
2882                                             0x4, 0xC00, 0x0);
2883                }
2884        }
2885#endif
2886        /* config RF. */
2887        if (priv->ResetProgress == RESET_TYPE_NORESET) {
2888                rtl8192_phy_RFConfig(dev);
2889                RT_TRACE(COMP_INIT, "%s():after phy RF config\n", __func__);
2890        }
2891
2892
2893        if (priv->ieee80211->FwRWRF)
2894                /* We can force firmware to do RF-R/W */
2895                priv->Rf_Mode = RF_OP_By_FW;
2896        else
2897                priv->Rf_Mode = RF_OP_By_SW_3wire;
2898
2899
2900        rtl8192_phy_updateInitGain(dev);
2901        /*--set CCK and OFDM Block "ON"--*/
2902        rtl8192_setBBreg(dev, rFPGA0_RFMOD, bCCKEn, 0x1);
2903        rtl8192_setBBreg(dev, rFPGA0_RFMOD, bOFDMEn, 0x1);
2904
2905        if (priv->ResetProgress == RESET_TYPE_NORESET) {
2906                /* if D or C cut */
2907                u8 tmpvalue;
2908
2909                read_nic_byte(dev, 0x301, &tmpvalue);
2910                if (tmpvalue == 0x03) {
2911                        priv->bDcut = true;
2912                        RT_TRACE(COMP_POWER_TRACKING, "D-cut\n");
2913                } else {
2914                        priv->bDcut = false;
2915                        RT_TRACE(COMP_POWER_TRACKING, "C-cut\n");
2916                }
2917                dm_initialize_txpower_tracking(dev);
2918
2919                if (priv->bDcut) {
2920                        u32 i, TempCCk;
2921                        u32 tmpRegA = rtl8192_QueryBBReg(dev,
2922                                                         rOFDM0_XATxIQImbalance,
2923                                                         bMaskDWord);
2924
2925                        for (i = 0; i < TxBBGainTableLength; i++) {
2926                                if (tmpRegA == priv->txbbgain_table[i].txbbgain_value) {
2927                                        priv->rfa_txpowertrackingindex = (u8)i;
2928                                        priv->rfa_txpowertrackingindex_real =
2929                                                (u8)i;
2930                                        priv->rfa_txpowertracking_default =
2931                                                priv->rfa_txpowertrackingindex;
2932                                        break;
2933                                }
2934                        }
2935
2936                        TempCCk = rtl8192_QueryBBReg(dev,
2937                                                     rCCK0_TxFilter1,
2938                                                     bMaskByte2);
2939
2940                        for (i = 0; i < CCKTxBBGainTableLength; i++) {
2941                                if (TempCCk == priv->cck_txbbgain_table[i].ccktxbb_valuearray[0]) {
2942                                        priv->cck_present_attenuation_20Mdefault = (u8)i;
2943                                        break;
2944                                }
2945                        }
2946                        priv->cck_present_attenuation_40Mdefault = 0;
2947                        priv->cck_present_attenuation_difference = 0;
2948                        priv->cck_present_attenuation =
2949                                priv->cck_present_attenuation_20Mdefault;
2950                }
2951        }
2952        write_nic_byte(dev, 0x87, 0x0);
2953
2954
2955        return init_status;
2956}
2957
2958/* this configures registers for beacon tx and enables it via
2959 * rtl8192_beacon_tx_enable(). rtl8192_beacon_tx_disable() might
2960 * be used to stop beacon transmission
2961 */
2962/***************************************************************************
2963 *   -------------------------------NET STUFF---------------------------
2964 ***************************************************************************/
2965
2966static struct net_device_stats *rtl8192_stats(struct net_device *dev)
2967{
2968        struct r8192_priv *priv = ieee80211_priv(dev);
2969
2970        return &priv->ieee80211->stats;
2971}
2972
2973static bool HalTxCheckStuck819xUsb(struct net_device *dev)
2974{
2975        struct r8192_priv *priv = ieee80211_priv(dev);
2976        u16             RegTxCounter;
2977        bool            bStuck = false;
2978
2979        read_nic_word(dev, 0x128, &RegTxCounter);
2980        RT_TRACE(COMP_RESET,
2981                 "%s():RegTxCounter is %d,TxCounter is %d\n", __func__,
2982                 RegTxCounter, priv->TxCounter);
2983        if (priv->TxCounter == RegTxCounter)
2984                bStuck = true;
2985
2986        priv->TxCounter = RegTxCounter;
2987
2988        return bStuck;
2989}
2990
2991/*
2992 *      <Assumption: RT_TX_SPINLOCK is acquired.>
2993 *      First added: 2006.11.19 by emily
2994 */
2995static RESET_TYPE TxCheckStuck(struct net_device *dev)
2996{
2997        struct r8192_priv *priv = ieee80211_priv(dev);
2998        u8                      QueueID;
2999        bool                    bCheckFwTxCnt = false;
3000
3001        /* Decide such threshold according to current power save mode */
3002
3003        for (QueueID = 0; QueueID <= BEACON_QUEUE; QueueID++) {
3004                if (QueueID == TXCMD_QUEUE)
3005                        continue;
3006                if ((skb_queue_len(&priv->ieee80211->skb_waitQ[QueueID]) == 0)  && (skb_queue_len(&priv->ieee80211->skb_aggQ[QueueID]) == 0))
3007                        continue;
3008
3009                bCheckFwTxCnt = true;
3010        }
3011        if (bCheckFwTxCnt) {
3012                if (HalTxCheckStuck819xUsb(dev)) {
3013                        RT_TRACE(COMP_RESET,
3014                                 "%s: Fw indicates no Tx condition!\n",
3015                                 __func__);
3016                        return RESET_TYPE_SILENT;
3017                }
3018        }
3019        return RESET_TYPE_NORESET;
3020}
3021
3022static bool HalRxCheckStuck819xUsb(struct net_device *dev)
3023{
3024        u16     RegRxCounter;
3025        struct r8192_priv *priv = ieee80211_priv(dev);
3026        bool bStuck = false;
3027        static u8       rx_chk_cnt;
3028
3029        read_nic_word(dev, 0x130, &RegRxCounter);
3030        RT_TRACE(COMP_RESET,
3031                 "%s(): RegRxCounter is %d,RxCounter is %d\n", __func__,
3032                 RegRxCounter, priv->RxCounter);
3033        /* If rssi is small, we should check rx for long time because of bad rx.
3034         * or maybe it will continuous silent reset every 2 seconds.
3035         */
3036        rx_chk_cnt++;
3037        if (priv->undecorated_smoothed_pwdb >= (RATE_ADAPTIVE_TH_HIGH + 5)) {
3038                rx_chk_cnt = 0; /* high rssi, check rx stuck right now. */
3039        } else if (priv->undecorated_smoothed_pwdb < (RATE_ADAPTIVE_TH_HIGH + 5) &&
3040                   ((priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20 && priv->undecorated_smoothed_pwdb >= RATE_ADAPTIVE_TH_LOW_40M) ||
3041                    (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20 && priv->undecorated_smoothed_pwdb >= RATE_ADAPTIVE_TH_LOW_20M))) {
3042                if (rx_chk_cnt < 2)
3043                        return bStuck;
3044
3045                rx_chk_cnt = 0;
3046        } else if (((priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20 && priv->undecorated_smoothed_pwdb < RATE_ADAPTIVE_TH_LOW_40M) ||
3047                    (priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20 && priv->undecorated_smoothed_pwdb < RATE_ADAPTIVE_TH_LOW_20M)) &&
3048                     priv->undecorated_smoothed_pwdb >= VERY_LOW_RSSI) {
3049                if (rx_chk_cnt < 4)
3050                        return bStuck;
3051
3052                rx_chk_cnt = 0;
3053        } else {
3054                if (rx_chk_cnt < 8)
3055                        return bStuck;
3056
3057                rx_chk_cnt = 0;
3058        }
3059
3060        if (priv->RxCounter == RegRxCounter)
3061                bStuck = true;
3062
3063        priv->RxCounter = RegRxCounter;
3064
3065        return bStuck;
3066}
3067
3068static RESET_TYPE RxCheckStuck(struct net_device *dev)
3069{
3070        struct r8192_priv *priv = ieee80211_priv(dev);
3071        bool        bRxCheck = false;
3072
3073        if (priv->IrpPendingCount > 1)
3074                bRxCheck = true;
3075
3076        if (bRxCheck) {
3077                if (HalRxCheckStuck819xUsb(dev)) {
3078                        RT_TRACE(COMP_RESET, "RxStuck Condition\n");
3079                        return RESET_TYPE_SILENT;
3080                }
3081        }
3082        return RESET_TYPE_NORESET;
3083}
3084
3085
3086/**
3087 * This function is called by Checkforhang to check whether we should
3088 * ask OS to reset driver
3089 *
3090 * \param pAdapter      The adapter context for this miniport
3091 *
3092 * Note:NIC with USB interface sholud not call this function because we
3093 * cannot scan descriptor to judge whether there is tx stuck.
3094 * Note: This function may be required to be rewrite for Vista OS.
3095 * <<<Assumption: Tx spinlock has been acquired >>>
3096 *
3097 * 8185 and 8185b does not implement this function.
3098 */
3099static RESET_TYPE rtl819x_ifcheck_resetornot(struct net_device *dev)
3100{
3101        struct r8192_priv *priv = ieee80211_priv(dev);
3102        RESET_TYPE      TxResetType = RESET_TYPE_NORESET;
3103        RESET_TYPE      RxResetType = RESET_TYPE_NORESET;
3104        RT_RF_POWER_STATE       rfState;
3105
3106        rfState = priv->ieee80211->eRFPowerState;
3107
3108        TxResetType = TxCheckStuck(dev);
3109        if (rfState != eRfOff ||
3110            (priv->ieee80211->iw_mode != IW_MODE_ADHOC)) {
3111                /* If driver is in the status of firmware download failure,
3112                 * driver skips RF initialization and RF is in turned off
3113                 * state. Driver should check whether Rx stuck and do silent
3114                 * reset. And if driver is in firmware download failure status,
3115                 * driver should initialize RF in the following silent reset
3116                 * procedure
3117                 *
3118                 * Driver should not check RX stuck in IBSS mode because it is
3119                 * required to set Check BSSID in order to send beacon,
3120                 * however, if check BSSID is set, STA cannot hear any packet
3121                 * at all.
3122                 */
3123                RxResetType = RxCheckStuck(dev);
3124        }
3125        if (TxResetType == RESET_TYPE_NORMAL ||
3126            RxResetType == RESET_TYPE_NORMAL) {
3127                return RESET_TYPE_NORMAL;
3128        } else if (TxResetType == RESET_TYPE_SILENT ||
3129                   RxResetType == RESET_TYPE_SILENT) {
3130                RT_TRACE(COMP_RESET, "%s():silent reset\n", __func__);
3131                return RESET_TYPE_SILENT;
3132        } else {
3133                return RESET_TYPE_NORESET;
3134        }
3135}
3136
3137static void rtl8192_cancel_deferred_work(struct r8192_priv *priv);
3138static int _rtl8192_up(struct net_device *dev);
3139static int rtl8192_close(struct net_device *dev);
3140
3141
3142
3143static void CamRestoreAllEntry(struct net_device *dev)
3144{
3145        u8 EntryId = 0;
3146        struct r8192_priv *priv = ieee80211_priv(dev);
3147        u8      *MacAddr = priv->ieee80211->current_network.bssid;
3148
3149        static u8       CAM_CONST_ADDR[4][6] = {
3150                {0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
3151                {0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
3152                {0x00, 0x00, 0x00, 0x00, 0x00, 0x02},
3153                {0x00, 0x00, 0x00, 0x00, 0x00, 0x03} };
3154        static u8       CAM_CONST_BROAD[] = {
3155                0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3156
3157        RT_TRACE(COMP_SEC, "%s:\n", __func__);
3158
3159
3160        if ((priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP40) ||
3161            (priv->ieee80211->pairwise_key_type == KEY_TYPE_WEP104)) {
3162                for (EntryId = 0; EntryId < 4; EntryId++) {
3163                        MacAddr = CAM_CONST_ADDR[EntryId];
3164                        setKey(dev, EntryId, EntryId,
3165                               priv->ieee80211->pairwise_key_type,
3166                               MacAddr, 0, NULL);
3167                }
3168
3169        } else if (priv->ieee80211->pairwise_key_type == KEY_TYPE_TKIP) {
3170                if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3171                        setKey(dev, 4, 0, priv->ieee80211->pairwise_key_type,
3172                               (u8 *)dev->dev_addr, 0, NULL);
3173                else
3174                        setKey(dev, 4, 0, priv->ieee80211->pairwise_key_type,
3175                               MacAddr, 0, NULL);
3176        } else if (priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP) {
3177                if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3178                        setKey(dev, 4, 0, priv->ieee80211->pairwise_key_type,
3179                               (u8 *)dev->dev_addr, 0, NULL);
3180                else
3181                        setKey(dev, 4, 0, priv->ieee80211->pairwise_key_type,
3182                               MacAddr, 0, NULL);
3183        }
3184
3185
3186
3187        if (priv->ieee80211->group_key_type == KEY_TYPE_TKIP) {
3188                MacAddr = CAM_CONST_BROAD;
3189                for (EntryId = 1; EntryId < 4; EntryId++) {
3190                        setKey(dev, EntryId, EntryId,
3191                               priv->ieee80211->group_key_type,
3192                               MacAddr, 0, NULL);
3193                }
3194                if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3195                        setKey(dev, 0, 0, priv->ieee80211->group_key_type,
3196                               CAM_CONST_ADDR[0], 0, NULL);
3197        } else if (priv->ieee80211->group_key_type == KEY_TYPE_CCMP) {
3198                MacAddr = CAM_CONST_BROAD;
3199                for (EntryId = 1; EntryId < 4; EntryId++) {
3200                        setKey(dev, EntryId, EntryId,
3201                               priv->ieee80211->group_key_type,
3202                               MacAddr, 0, NULL);
3203                }
3204
3205                if (priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3206                        setKey(dev, 0, 0, priv->ieee80211->group_key_type,
3207                               CAM_CONST_ADDR[0], 0, NULL);
3208        }
3209}
3210
3211/* This function is used to fix Tx/Rx stop bug temporarily.
3212 * This function will do "system reset" to NIC when Tx or Rx is stuck.
3213 * The method checking Tx/Rx stuck of this function is supported by FW,
3214 * which reports Tx and Rx counter to register 0x128 and 0x130.
3215 */
3216static void rtl819x_ifsilentreset(struct net_device *dev)
3217{
3218        struct r8192_priv *priv = ieee80211_priv(dev);
3219        u8      reset_times = 0;
3220        int reset_status = 0;
3221        struct ieee80211_device *ieee = priv->ieee80211;
3222
3223
3224        /* If we need to check CCK stop, please uncomment this line. */
3225        /* bStuck = Adapter->HalFunc.CheckHWStopHandler(Adapter); */
3226
3227        if (priv->ResetProgress == RESET_TYPE_NORESET) {
3228RESET_START:
3229
3230                RT_TRACE(COMP_RESET, "=========>Reset progress!!\n");
3231
3232                /* Set the variable for reset. */
3233                priv->ResetProgress = RESET_TYPE_SILENT;
3234                mutex_lock(&priv->wx_mutex);
3235                if (priv->up == 0) {
3236                        RT_TRACE(COMP_ERR,
3237                                 "%s():the driver is not up! return\n",
3238                                 __func__);
3239                        mutex_unlock(&priv->wx_mutex);
3240                        return;
3241                }
3242                priv->up = 0;
3243                RT_TRACE(COMP_RESET,
3244                         "%s():======>start to down the driver\n",
3245                         __func__);
3246
3247                rtl8192_rtx_disable(dev);
3248                rtl8192_cancel_deferred_work(priv);
3249                deinit_hal_dm(dev);
3250                del_timer_sync(&priv->watch_dog_timer);
3251
3252                ieee->sync_scan_hurryup = 1;
3253                if (ieee->state == IEEE80211_LINKED) {
3254                        mutex_lock(&ieee->wx_mutex);
3255                        netdev_dbg(dev, "ieee->state is IEEE80211_LINKED\n");
3256                        ieee80211_stop_send_beacons(priv->ieee80211);
3257                        del_timer_sync(&ieee->associate_timer);
3258                        cancel_delayed_work(&ieee->associate_retry_wq);
3259                        ieee80211_stop_scan(ieee);
3260                        netif_carrier_off(dev);
3261                        mutex_unlock(&ieee->wx_mutex);
3262                } else {
3263                        netdev_dbg(dev, "ieee->state is NOT LINKED\n");
3264                        ieee80211_softmac_stop_protocol(priv->ieee80211);
3265                }
3266                mutex_unlock(&priv->wx_mutex);
3267                RT_TRACE(COMP_RESET,
3268                         "%s():<==========down process is finished\n",
3269                         __func__);
3270                RT_TRACE(COMP_RESET,
3271                         "%s():===========>start up the driver\n",
3272                         __func__);
3273                reset_status = _rtl8192_up(dev);
3274
3275                RT_TRACE(COMP_RESET,
3276                         "%s():<===========up process is finished\n",
3277                         __func__);
3278                if (reset_status == -EAGAIN) {
3279                        if (reset_times < 3) {
3280                                reset_times++;
3281                                goto RESET_START;
3282                        } else {
3283                                RT_TRACE(COMP_ERR,
3284                                         " ERR!!! %s():  Reset Failed!!\n",
3285                                         __func__);
3286                        }
3287                }
3288                ieee->is_silent_reset = 1;
3289                EnableHWSecurityConfig8192(dev);
3290                if (ieee->state == IEEE80211_LINKED &&
3291                    ieee->iw_mode == IW_MODE_INFRA) {
3292                        ieee->set_chan(ieee->dev,
3293                                       ieee->current_network.channel);
3294
3295                        queue_work(ieee->wq, &ieee->associate_complete_wq);
3296
3297                } else if (ieee->state == IEEE80211_LINKED &&
3298                           ieee->iw_mode == IW_MODE_ADHOC) {
3299                        ieee->set_chan(ieee->dev,
3300                                       ieee->current_network.channel);
3301                        ieee->link_change(ieee->dev);
3302
3303                        ieee80211_start_send_beacons(ieee);
3304
3305                        if (ieee->data_hard_resume)
3306                                ieee->data_hard_resume(ieee->dev);
3307                        netif_carrier_on(ieee->dev);
3308                }
3309
3310                CamRestoreAllEntry(dev);
3311
3312                priv->ResetProgress = RESET_TYPE_NORESET;
3313                priv->reset_count++;
3314
3315                priv->bForcedSilentReset = false;
3316                priv->bResetInProgress = false;
3317
3318                /* For test --> force write UFWP. */
3319                write_nic_byte(dev, UFWP, 1);
3320                RT_TRACE(COMP_RESET,
3321                         "Reset finished!! ====>[%d]\n",
3322                         priv->reset_count);
3323        }
3324}
3325
3326static void rtl819x_update_rxcounts(struct r8192_priv *priv, u32 *TotalRxBcnNum,
3327                             u32 *TotalRxDataNum)
3328{
3329        u16                     SlotIndex;
3330        u8                      i;
3331
3332        *TotalRxBcnNum = 0;
3333        *TotalRxDataNum = 0;
3334
3335        SlotIndex = (priv->ieee80211->LinkDetectInfo.SlotIndex++) %
3336                    (priv->ieee80211->LinkDetectInfo.SlotNum);
3337        priv->ieee80211->LinkDetectInfo.RxBcnNum[SlotIndex] =
3338                priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod;
3339        priv->ieee80211->LinkDetectInfo.RxDataNum[SlotIndex] =
3340                priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod;
3341        for (i = 0; i < priv->ieee80211->LinkDetectInfo.SlotNum; i++) {
3342                *TotalRxBcnNum += priv->ieee80211->LinkDetectInfo.RxBcnNum[i];
3343                *TotalRxDataNum += priv->ieee80211->LinkDetectInfo.RxDataNum[i];
3344        }
3345}
3346
3347
3348static void rtl819x_watchdog_wqcallback(struct work_struct *work)
3349{
3350        struct delayed_work *dwork = to_delayed_work(work);
3351        struct r8192_priv *priv = container_of(dwork,
3352                                               struct r8192_priv, watch_dog_wq);
3353        struct net_device *dev = priv->ieee80211->dev;
3354        struct ieee80211_device *ieee = priv->ieee80211;
3355        RESET_TYPE      ResetType = RESET_TYPE_NORESET;
3356        static u8       check_reset_cnt;
3357        bool bBusyTraffic = false;
3358        u32     TotalRxBcnNum = 0;
3359        u32     TotalRxDataNum = 0;
3360
3361        if (!priv->up)
3362                return;
3363        hal_dm_watchdog(dev);
3364
3365        /* to get busy traffic condition */
3366        if (ieee->state == IEEE80211_LINKED) {
3367                if (ieee->LinkDetectInfo.NumRxOkInPeriod > 666 ||
3368                    ieee->LinkDetectInfo.NumTxOkInPeriod > 666) {
3369                        bBusyTraffic = true;
3370                }
3371                ieee->LinkDetectInfo.NumRxOkInPeriod = 0;
3372                ieee->LinkDetectInfo.NumTxOkInPeriod = 0;
3373                ieee->LinkDetectInfo.bBusyTraffic = bBusyTraffic;
3374        }
3375        /* for AP roaming */
3376        if (priv->ieee80211->state == IEEE80211_LINKED &&
3377            priv->ieee80211->iw_mode == IW_MODE_INFRA) {
3378                rtl819x_update_rxcounts(priv, &TotalRxBcnNum, &TotalRxDataNum);
3379                if ((TotalRxBcnNum + TotalRxDataNum) == 0) {
3380#ifdef TODO
3381                        if (rfState == eRfOff)
3382                                RT_TRACE(COMP_ERR, "========>%s()\n", __func__);
3383#endif
3384                        netdev_dbg(dev,
3385                                   "===>%s(): AP is power off, connect another one\n",
3386                                   __func__);
3387                        priv->ieee80211->state = IEEE80211_ASSOCIATING;
3388                        notify_wx_assoc_event(priv->ieee80211);
3389                        RemovePeerTS(priv->ieee80211,
3390                                     priv->ieee80211->current_network.bssid);
3391                        priv->ieee80211->link_change(dev);
3392                        queue_work(priv->ieee80211->wq,
3393                                   &priv->ieee80211->associate_procedure_wq);
3394                }
3395        }
3396        priv->ieee80211->LinkDetectInfo.NumRecvBcnInPeriod = 0;
3397        priv->ieee80211->LinkDetectInfo.NumRecvDataInPeriod = 0;
3398        /* check if reset the driver */
3399        if (check_reset_cnt++ >= 3) {
3400                ResetType = rtl819x_ifcheck_resetornot(dev);
3401                check_reset_cnt = 3;
3402        }
3403        /* This is control by OID set in Pomelo */
3404        if ((priv->force_reset) || (priv->ResetProgress == RESET_TYPE_NORESET &&
3405            (priv->bForcedSilentReset ||
3406            (!priv->bDisableNormalResetCheck && ResetType == RESET_TYPE_SILENT)))) {
3407                RT_TRACE(COMP_RESET,
3408                         "%s():priv->force_reset is %d,priv->ResetProgress is %d, priv->bForcedSilentReset is %d,priv->bDisableNormalResetCheck is %d,ResetType is %d\n",
3409                         __func__, priv->force_reset, priv->ResetProgress,
3410                         priv->bForcedSilentReset,
3411                         priv->bDisableNormalResetCheck, ResetType);
3412                rtl819x_ifsilentreset(dev);
3413        }
3414        priv->force_reset = false;
3415        priv->bForcedSilentReset = false;
3416        priv->bResetInProgress = false;
3417        RT_TRACE(COMP_TRACE, " <==RtUsbCheckForHangWorkItemCallback()\n");
3418}
3419
3420static void watch_dog_timer_callback(struct timer_list *t)
3421{
3422        struct r8192_priv *priv = from_timer(priv, t, watch_dog_timer);
3423
3424        schedule_delayed_work(&priv->watch_dog_wq, 0);
3425        mod_timer(&priv->watch_dog_timer,
3426                  jiffies + msecs_to_jiffies(IEEE80211_WATCH_DOG_TIME));
3427}
3428
3429static int _rtl8192_up(struct net_device *dev)
3430{
3431        struct r8192_priv *priv = ieee80211_priv(dev);
3432        int init_status = 0;
3433
3434        priv->up = 1;
3435        priv->ieee80211->ieee_up = 1;
3436        RT_TRACE(COMP_INIT, "Bringing up iface");
3437        init_status = rtl8192_adapter_start(dev);
3438        if (!init_status) {
3439                RT_TRACE(COMP_ERR, "ERR!!! %s(): initialization failed!\n",
3440                         __func__);
3441                priv->up = priv->ieee80211->ieee_up = 0;
3442                return -EAGAIN;
3443        }
3444        RT_TRACE(COMP_INIT, "start adapter finished\n");
3445        rtl8192_rx_enable(dev);
3446        if (priv->ieee80211->state != IEEE80211_LINKED)
3447                ieee80211_softmac_start_protocol(priv->ieee80211);
3448        ieee80211_reset_queue(priv->ieee80211);
3449        watch_dog_timer_callback(&priv->watch_dog_timer);
3450        if (!netif_queue_stopped(dev))
3451                netif_start_queue(dev);
3452        else
3453                netif_wake_queue(dev);
3454
3455        return 0;
3456}
3457
3458
3459static int rtl8192_open(struct net_device *dev)
3460{
3461        struct r8192_priv *priv = ieee80211_priv(dev);
3462        int ret;
3463
3464        mutex_lock(&priv->wx_mutex);
3465        ret = rtl8192_up(dev);
3466        mutex_unlock(&priv->wx_mutex);
3467        return ret;
3468}
3469
3470
3471int rtl8192_up(struct net_device *dev)
3472{
3473        struct r8192_priv *priv = ieee80211_priv(dev);
3474
3475        if (priv->up == 1)
3476                return -1;
3477
3478        return _rtl8192_up(dev);
3479}
3480
3481
3482static int rtl8192_close(struct net_device *dev)
3483{
3484        struct r8192_priv *priv = ieee80211_priv(dev);
3485        int ret;
3486
3487        mutex_lock(&priv->wx_mutex);
3488
3489        ret = rtl8192_down(dev);
3490
3491        mutex_unlock(&priv->wx_mutex);
3492
3493        return ret;
3494}
3495
3496int rtl8192_down(struct net_device *dev)
3497{
3498        struct r8192_priv *priv = ieee80211_priv(dev);
3499        int i;
3500
3501        if (priv->up == 0)
3502                return -1;
3503
3504        priv->up = 0;
3505        priv->ieee80211->ieee_up = 0;
3506        RT_TRACE(COMP_DOWN, "==========>%s()\n", __func__);
3507        /* FIXME */
3508        if (!netif_queue_stopped(dev))
3509                netif_stop_queue(dev);
3510
3511        rtl8192_rtx_disable(dev);
3512
3513        /* Tx related queue release */
3514        for (i = 0; i < MAX_QUEUE_SIZE; i++)
3515                skb_queue_purge(&priv->ieee80211->skb_waitQ[i]);
3516        for (i = 0; i < MAX_QUEUE_SIZE; i++)
3517                skb_queue_purge(&priv->ieee80211->skb_aggQ[i]);
3518
3519        for (i = 0; i < MAX_QUEUE_SIZE; i++)
3520                skb_queue_purge(&priv->ieee80211->skb_drv_aggQ[i]);
3521
3522        /* as cancel_delayed_work will del work->timer, so if work is not
3523         * defined as struct delayed_work, it will corrupt
3524         */
3525        rtl8192_cancel_deferred_work(priv);
3526        deinit_hal_dm(dev);
3527        del_timer_sync(&priv->watch_dog_timer);
3528
3529
3530        ieee80211_softmac_stop_protocol(priv->ieee80211);
3531        memset(&priv->ieee80211->current_network, 0,
3532               offsetof(struct ieee80211_network, list));
3533        RT_TRACE(COMP_DOWN, "<==========%s()\n", __func__);
3534
3535        return 0;
3536}
3537
3538
3539void rtl8192_commit(struct net_device *dev)
3540{
3541        struct r8192_priv *priv = ieee80211_priv(dev);
3542        int reset_status = 0;
3543
3544        if (priv->up == 0)
3545                return;
3546        priv->up = 0;
3547
3548        rtl8192_cancel_deferred_work(priv);
3549        del_timer_sync(&priv->watch_dog_timer);
3550
3551        ieee80211_softmac_stop_protocol(priv->ieee80211);
3552
3553        rtl8192_rtx_disable(dev);
3554        reset_status = _rtl8192_up(dev);
3555}
3556
3557static void rtl8192_restart(struct work_struct *work)
3558{
3559        struct r8192_priv *priv = container_of(work, struct r8192_priv,
3560                                               reset_wq);
3561        struct net_device *dev = priv->ieee80211->dev;
3562
3563        mutex_lock(&priv->wx_mutex);
3564
3565        rtl8192_commit(dev);
3566
3567        mutex_unlock(&priv->wx_mutex);
3568}
3569
3570static void r8192_set_multicast(struct net_device *dev)
3571{
3572        struct r8192_priv *priv = ieee80211_priv(dev);
3573        short promisc;
3574
3575        /* FIXME FIXME */
3576
3577        promisc = (dev->flags & IFF_PROMISC) ? 1 : 0;
3578
3579        if (promisc != priv->promisc)
3580
3581                priv->promisc = promisc;
3582}
3583
3584
3585static int r8192_set_mac_adr(struct net_device *dev, void *mac)
3586{
3587        struct r8192_priv *priv = ieee80211_priv(dev);
3588        struct sockaddr *addr = mac;
3589
3590        mutex_lock(&priv->wx_mutex);
3591
3592        ether_addr_copy(dev->dev_addr, addr->sa_data);
3593
3594        schedule_work(&priv->reset_wq);
3595        mutex_unlock(&priv->wx_mutex);
3596
3597        return 0;
3598}
3599
3600/* based on ipw2200 driver */
3601static int rtl8192_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
3602{
3603        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3604        struct iwreq *wrq = (struct iwreq *)rq;
3605        int ret = -1;
3606        struct ieee80211_device *ieee = priv->ieee80211;
3607        u32 key[4];
3608        u8 broadcast_addr[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
3609        struct iw_point *p = &wrq->u.data;
3610        struct ieee_param *ipw = NULL;
3611
3612        mutex_lock(&priv->wx_mutex);
3613
3614
3615        if (p->length < sizeof(struct ieee_param) || !p->pointer) {
3616                ret = -EINVAL;
3617                goto out;
3618        }
3619
3620        ipw = memdup_user(p->pointer, p->length);
3621        if (IS_ERR(ipw)) {
3622                ret = PTR_ERR(ipw);
3623                goto out;
3624        }
3625
3626        switch (cmd) {
3627        case RTL_IOCTL_WPA_SUPPLICANT:
3628                /* parse here for HW security */
3629                if (ipw->cmd == IEEE_CMD_SET_ENCRYPTION) {
3630                        if (ipw->u.crypt.set_tx) {
3631                                if (strcmp(ipw->u.crypt.alg, "CCMP") == 0) {
3632                                        ieee->pairwise_key_type = KEY_TYPE_CCMP;
3633                                } else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0) {
3634                                        ieee->pairwise_key_type = KEY_TYPE_TKIP;
3635                                } else if (strcmp(ipw->u.crypt.alg, "WEP") == 0) {
3636                                        if (ipw->u.crypt.key_len == 13)
3637                                                ieee->pairwise_key_type = KEY_TYPE_WEP104;
3638                                        else if (ipw->u.crypt.key_len == 5)
3639                                                ieee->pairwise_key_type = KEY_TYPE_WEP40;
3640                                } else {
3641                                        ieee->pairwise_key_type = KEY_TYPE_NA;
3642                                }
3643
3644                                if (ieee->pairwise_key_type) {
3645                                        memcpy((u8 *)key, ipw->u.crypt.key, 16);
3646                                        EnableHWSecurityConfig8192(dev);
3647                                        /* We fill both index entry and 4th
3648                                         * entry for pairwise key as in IPW
3649                                         * interface, adhoc will only get here,
3650                                         * so we need index entry for its
3651                                         * default key serching!
3652                                         */
3653                                        setKey(dev, 4, ipw->u.crypt.idx,
3654                                               ieee->pairwise_key_type,
3655                                               (u8 *)ieee->ap_mac_addr,
3656                                               0, key);
3657                                        if (ieee->auth_mode != 2)
3658                                                setKey(dev, ipw->u.crypt.idx,
3659                                                       ipw->u.crypt.idx,
3660                                                       ieee->pairwise_key_type,
3661                                                       (u8 *)ieee->ap_mac_addr,
3662                                                       0, key);
3663                                }
3664                        } else {
3665                                memcpy((u8 *)key, ipw->u.crypt.key, 16);
3666                                if (strcmp(ipw->u.crypt.alg, "CCMP") == 0) {
3667                                        ieee->group_key_type = KEY_TYPE_CCMP;
3668                                } else if (strcmp(ipw->u.crypt.alg, "TKIP") == 0) {
3669                                        ieee->group_key_type = KEY_TYPE_TKIP;
3670                                } else if (strcmp(ipw->u.crypt.alg, "WEP") == 0) {
3671                                        if (ipw->u.crypt.key_len == 13)
3672                                                ieee->group_key_type = KEY_TYPE_WEP104;
3673                                        else if (ipw->u.crypt.key_len == 5)
3674                                                ieee->group_key_type = KEY_TYPE_WEP40;
3675                                } else {
3676                                        ieee->group_key_type = KEY_TYPE_NA;
3677                                }
3678
3679                                if (ieee->group_key_type) {
3680                                        setKey(dev, ipw->u.crypt.idx,
3681                                               /* KeyIndex */
3682                                               ipw->u.crypt.idx,
3683                                               /* KeyType */
3684                                               ieee->group_key_type,
3685                                               /* MacAddr */
3686                                               broadcast_addr,
3687                                               /* DefaultKey */
3688                                               0,
3689                                               /* KeyContent */
3690                                               key);
3691                                }
3692                        }
3693                }
3694                ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211,
3695                                                     &wrq->u.data);
3696                break;
3697
3698        default:
3699                ret = -EOPNOTSUPP;
3700                break;
3701        }
3702        kfree(ipw);
3703        ipw = NULL;
3704out:
3705        mutex_unlock(&priv->wx_mutex);
3706        return ret;
3707}
3708
3709static u8 HwRateToMRate90(bool bIsHT, u8 rate)
3710{
3711        u8  ret_rate = 0xff;
3712
3713        if (!bIsHT) {
3714                switch (rate) {
3715                case DESC90_RATE1M:
3716                        ret_rate = MGN_1M;
3717                        break;
3718                case DESC90_RATE2M:
3719                        ret_rate = MGN_2M;
3720                        break;
3721                case DESC90_RATE5_5M:
3722                        ret_rate = MGN_5_5M;
3723                        break;
3724                case DESC90_RATE11M:
3725                        ret_rate = MGN_11M;
3726                        break;
3727                case DESC90_RATE6M:
3728                        ret_rate = MGN_6M;
3729                        break;
3730                case DESC90_RATE9M:
3731                        ret_rate = MGN_9M;
3732                        break;
3733                case DESC90_RATE12M:
3734                        ret_rate = MGN_12M;
3735                        break;
3736                case DESC90_RATE18M:
3737                        ret_rate = MGN_18M;
3738                        break;
3739                case DESC90_RATE24M:
3740                        ret_rate = MGN_24M;
3741                        break;
3742                case DESC90_RATE36M:
3743                        ret_rate = MGN_36M;
3744                        break;
3745                case DESC90_RATE48M:
3746                        ret_rate = MGN_48M;
3747                        break;
3748                case DESC90_RATE54M:
3749                        ret_rate = MGN_54M;
3750                        break;
3751
3752                default:
3753                        ret_rate = 0xff;
3754                        RT_TRACE(COMP_RECV,
3755                                 "%s: Non supported Rate [%x], bIsHT = %d!!!\n",
3756                                 __func__, rate, bIsHT);
3757                        break;
3758                }
3759
3760        } else {
3761                switch (rate) {
3762                case DESC90_RATEMCS0:
3763                        ret_rate = MGN_MCS0;
3764                        break;
3765                case DESC90_RATEMCS1:
3766                        ret_rate = MGN_MCS1;
3767                        break;
3768                case DESC90_RATEMCS2:
3769                        ret_rate = MGN_MCS2;
3770                        break;
3771                case DESC90_RATEMCS3:
3772                        ret_rate = MGN_MCS3;
3773                        break;
3774                case DESC90_RATEMCS4:
3775                        ret_rate = MGN_MCS4;
3776                        break;
3777                case DESC90_RATEMCS5:
3778                        ret_rate = MGN_MCS5;
3779                        break;
3780                case DESC90_RATEMCS6:
3781                        ret_rate = MGN_MCS6;
3782                        break;
3783                case DESC90_RATEMCS7:
3784                        ret_rate = MGN_MCS7;
3785                        break;
3786                case DESC90_RATEMCS8:
3787                        ret_rate = MGN_MCS8;
3788                        break;
3789                case DESC90_RATEMCS9:
3790                        ret_rate = MGN_MCS9;
3791                        break;
3792                case DESC90_RATEMCS10:
3793                        ret_rate = MGN_MCS10;
3794                        break;
3795                case DESC90_RATEMCS11:
3796                        ret_rate = MGN_MCS11;
3797                        break;
3798                case DESC90_RATEMCS12:
3799                        ret_rate = MGN_MCS12;
3800                        break;
3801                case DESC90_RATEMCS13:
3802                        ret_rate = MGN_MCS13;
3803                        break;
3804                case DESC90_RATEMCS14:
3805                        ret_rate = MGN_MCS14;
3806                        break;
3807                case DESC90_RATEMCS15:
3808                        ret_rate = MGN_MCS15;
3809                        break;
3810                case DESC90_RATEMCS32:
3811                        ret_rate = 0x80 | 0x20;
3812                        break;
3813
3814                default:
3815                        ret_rate = 0xff;
3816                        RT_TRACE(COMP_RECV,
3817                                 "%s: Non supported Rate [%x], bIsHT = %d!!!\n",
3818                                 __func__, rate, bIsHT);
3819                        break;
3820                }
3821        }
3822
3823        return ret_rate;
3824}
3825
3826/**
3827 * Function:     UpdateRxPktTimeStamp
3828 * Overview:     Record the TSF time stamp when receiving a packet
3829 *
3830 * Input:
3831 *       PADAPTER        Adapter
3832 *       PRT_RFD         pRfd,
3833 *
3834 * Output:
3835 *       PRT_RFD         pRfd
3836 *                               (pRfd->Status.TimeStampHigh is updated)
3837 *                               (pRfd->Status.TimeStampLow is updated)
3838 * Return:
3839 *               None
3840 */
3841static void UpdateRxPktTimeStamp8190(struct net_device *dev,
3842                                     struct ieee80211_rx_stats *stats)
3843{
3844        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
3845
3846        if (stats->bIsAMPDU && !stats->bFirstMPDU) {
3847                stats->mac_time[0] = priv->LastRxDescTSFLow;
3848                stats->mac_time[1] = priv->LastRxDescTSFHigh;
3849        } else {
3850                priv->LastRxDescTSFLow = stats->mac_time[0];
3851                priv->LastRxDescTSFHigh = stats->mac_time[1];
3852        }
3853}
3854
3855/* 0-100 index. */
3856static long rtl819x_translate_todbm(u8 signal_strength_index)
3857{
3858        long    signal_power; /* in dBm. */
3859
3860        /* Translate to dBm (x=0.5y-95). */
3861        signal_power = (long)((signal_strength_index + 1) >> 1);
3862        signal_power -= 95;
3863
3864        return signal_power;
3865}
3866
3867
3868/* We can not declare RSSI/EVM total value of sliding window to
3869 * be a local static. Otherwise, it may increase when we return from S3/S4. The
3870 * value will be kept in memory or disk. Declare the value in the adaptor
3871 * and it will be reinitialized when returned from S3/S4.
3872 */
3873static void rtl8192_process_phyinfo(struct r8192_priv *priv, u8 *buffer,
3874                                    struct ieee80211_rx_stats *pprevious_stats,
3875                                    struct ieee80211_rx_stats *pcurrent_stats)
3876{
3877        bool bcheck = false;
3878        u8      rfpath;
3879        u32     nspatial_stream, tmp_val;
3880        static u32 slide_rssi_index, slide_rssi_statistics;
3881        static u32 slide_evm_index, slide_evm_statistics;
3882        static u32 last_rssi, last_evm;
3883
3884        static u32 slide_beacon_adc_pwdb_index;
3885        static u32 slide_beacon_adc_pwdb_statistics;
3886        static u32 last_beacon_adc_pwdb;
3887
3888        struct rtl_80211_hdr_3addr *hdr;
3889        u16 sc;
3890        unsigned int seq;
3891
3892        hdr = (struct rtl_80211_hdr_3addr *)buffer;
3893        sc = le16_to_cpu(hdr->seq_ctl);
3894        seq = WLAN_GET_SEQ_SEQ(sc);
3895        /* to record the sequence number */
3896        pcurrent_stats->Seq_Num = seq;
3897
3898        /* Check whether we should take the previous packet into accounting */
3899        if (!pprevious_stats->bIsAMPDU) {
3900                /* if previous packet is not aggregated packet */
3901                bcheck = true;
3902        }
3903
3904        if (slide_rssi_statistics++ >= PHY_RSSI_SLID_WIN_MAX) {
3905                slide_rssi_statistics = PHY_RSSI_SLID_WIN_MAX;
3906                last_rssi = priv->stats.slide_signal_strength[slide_rssi_index];
3907                priv->stats.slide_rssi_total -= last_rssi;
3908        }
3909        priv->stats.slide_rssi_total += pprevious_stats->SignalStrength;
3910
3911        priv->stats.slide_signal_strength[slide_rssi_index++] =
3912                pprevious_stats->SignalStrength;
3913        if (slide_rssi_index >= PHY_RSSI_SLID_WIN_MAX)
3914                slide_rssi_index = 0;
3915
3916        /* <1> Showed on UI for user, in dbm */
3917        tmp_val = priv->stats.slide_rssi_total / slide_rssi_statistics;
3918        priv->stats.signal_strength = rtl819x_translate_todbm((u8)tmp_val);
3919        pcurrent_stats->rssi = priv->stats.signal_strength;
3920
3921        /* If the previous packet does not match the criteria, neglect it */
3922        if (!pprevious_stats->bPacketMatchBSSID) {
3923                if (!pprevious_stats->bToSelfBA)
3924                        return;
3925        }
3926
3927        if (!bcheck)
3928                return;
3929
3930
3931        /* only rtl8190 supported
3932         * rtl8190_process_cck_rxpathsel(priv,pprevious_stats);
3933         */
3934
3935        /* Check RSSI */
3936        priv->stats.num_process_phyinfo++;
3937
3938        /* record the general signal strength to the sliding window. */
3939
3940
3941        /* <2> Showed on UI for engineering
3942         * hardware does not provide rssi information for each rf path in CCK
3943         */
3944        if (!pprevious_stats->bIsCCK &&
3945            (pprevious_stats->bPacketToSelf || pprevious_stats->bToSelfBA)) {
3946                for (rfpath = RF90_PATH_A; rfpath < priv->NumTotalRFPath; rfpath++) {
3947                        if (!rtl8192_phy_CheckIsLegalRFPath(
3948                                        priv->ieee80211->dev, rfpath))
3949                                continue;
3950
3951                        if (priv->stats.rx_rssi_percentage[rfpath] == 0)
3952                                priv->stats.rx_rssi_percentage[rfpath] =
3953                                        pprevious_stats->RxMIMOSignalStrength[rfpath];
3954                        if (pprevious_stats->RxMIMOSignalStrength[rfpath]  > priv->stats.rx_rssi_percentage[rfpath]) {
3955                                priv->stats.rx_rssi_percentage[rfpath] =
3956                                        ((priv->stats.rx_rssi_percentage[rfpath] * (RX_SMOOTH_FACTOR - 1)) +
3957                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) / (RX_SMOOTH_FACTOR);
3958                                priv->stats.rx_rssi_percentage[rfpath] = priv->stats.rx_rssi_percentage[rfpath]  + 1;
3959                        } else {
3960                                priv->stats.rx_rssi_percentage[rfpath] =
3961                                        ((priv->stats.rx_rssi_percentage[rfpath] * (RX_SMOOTH_FACTOR - 1)) +
3962                                         (pprevious_stats->RxMIMOSignalStrength[rfpath])) / (RX_SMOOTH_FACTOR);
3963                        }
3964                        RT_TRACE(COMP_DBG,
3965                                 "priv->stats.rx_rssi_percentage[rfPath]  = %d\n",
3966                                 priv->stats.rx_rssi_percentage[rfpath]);
3967                }
3968        }
3969
3970
3971        /* Check PWDB. */
3972        RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
3973                 pprevious_stats->bIsCCK ? "CCK" : "OFDM",
3974                 pprevious_stats->RxPWDBAll);
3975
3976        if (pprevious_stats->bPacketBeacon) {
3977                /* record the beacon pwdb to the sliding window. */
3978                if (slide_beacon_adc_pwdb_statistics++ >= PHY_Beacon_RSSI_SLID_WIN_MAX) {
3979                        slide_beacon_adc_pwdb_statistics = PHY_Beacon_RSSI_SLID_WIN_MAX;
3980                        last_beacon_adc_pwdb = priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index];
3981                        priv->stats.Slide_Beacon_Total -= last_beacon_adc_pwdb;
3982                }
3983                priv->stats.Slide_Beacon_Total += pprevious_stats->RxPWDBAll;
3984                priv->stats.Slide_Beacon_pwdb[slide_beacon_adc_pwdb_index] = pprevious_stats->RxPWDBAll;
3985                slide_beacon_adc_pwdb_index++;
3986                if (slide_beacon_adc_pwdb_index >= PHY_Beacon_RSSI_SLID_WIN_MAX)
3987                        slide_beacon_adc_pwdb_index = 0;
3988                pprevious_stats->RxPWDBAll = priv->stats.Slide_Beacon_Total / slide_beacon_adc_pwdb_statistics;
3989                if (pprevious_stats->RxPWDBAll >= 3)
3990                        pprevious_stats->RxPWDBAll -= 3;
3991        }
3992
3993        RT_TRACE(COMP_RXDESC, "Smooth %s PWDB = %d\n",
3994                 pprevious_stats->bIsCCK ? "CCK" : "OFDM",
3995                 pprevious_stats->RxPWDBAll);
3996
3997
3998        if (pprevious_stats->bPacketToSelf ||
3999            pprevious_stats->bPacketBeacon ||
4000            pprevious_stats->bToSelfBA) {
4001                if (priv->undecorated_smoothed_pwdb < 0)
4002                        /* initialize */
4003                        priv->undecorated_smoothed_pwdb =
4004                                pprevious_stats->RxPWDBAll;
4005                if (pprevious_stats->RxPWDBAll > (u32)priv->undecorated_smoothed_pwdb) {
4006                        priv->undecorated_smoothed_pwdb =
4007                                (((priv->undecorated_smoothed_pwdb) * (RX_SMOOTH_FACTOR - 1)) +
4008                                 (pprevious_stats->RxPWDBAll)) / (RX_SMOOTH_FACTOR);
4009                        priv->undecorated_smoothed_pwdb = priv->undecorated_smoothed_pwdb + 1;
4010                } else {
4011                        priv->undecorated_smoothed_pwdb =
4012                                (((priv->undecorated_smoothed_pwdb) * (RX_SMOOTH_FACTOR - 1)) +
4013                                 (pprevious_stats->RxPWDBAll)) / (RX_SMOOTH_FACTOR);
4014                }
4015        }
4016
4017        /* Check EVM */
4018        /* record the general EVM to the sliding window. */
4019        if (pprevious_stats->SignalQuality) {
4020                if (pprevious_stats->bPacketToSelf ||
4021                    pprevious_stats->bPacketBeacon ||
4022                    pprevious_stats->bToSelfBA) {
4023                        if (slide_evm_statistics++ >= PHY_RSSI_SLID_WIN_MAX) {
4024                                slide_evm_statistics = PHY_RSSI_SLID_WIN_MAX;
4025                                last_evm = priv->stats.slide_evm[slide_evm_index];
4026                                priv->stats.slide_evm_total -= last_evm;
4027                        }
4028
4029                        priv->stats.slide_evm_total +=
4030                                pprevious_stats->SignalQuality;
4031
4032                        priv->stats.slide_evm[slide_evm_index++] =
4033                                pprevious_stats->SignalQuality;
4034                        if (slide_evm_index >= PHY_RSSI_SLID_WIN_MAX)
4035                                slide_evm_index = 0;
4036
4037                        /* <1> Showed on UI for user, in percentage. */
4038                        tmp_val = priv->stats.slide_evm_total /
4039                                  slide_evm_statistics;
4040                        priv->stats.signal_quality = tmp_val;
4041                        /* Showed on UI for user in Windows Vista,
4042                         * for Link quality.
4043                         */
4044                        priv->stats.last_signal_strength_inpercent = tmp_val;
4045                }
4046
4047                /* <2> Showed on UI for engineering */
4048                if (pprevious_stats->bPacketToSelf ||
4049                    pprevious_stats->bPacketBeacon ||
4050                    pprevious_stats->bToSelfBA) {
4051                        for (nspatial_stream = 0; nspatial_stream < 2; nspatial_stream++) { /* 2 spatial stream */
4052                                if (pprevious_stats->RxMIMOSignalQuality[nspatial_stream] != -1) {
4053                                        if (priv->stats.rx_evm_percentage[nspatial_stream] == 0) /* initialize */
4054                                                priv->stats.rx_evm_percentage[nspatial_stream] = pprevious_stats->RxMIMOSignalQuality[nspatial_stream];
4055                                        priv->stats.rx_evm_percentage[nspatial_stream] =
4056                                                ((priv->stats.rx_evm_percentage[nspatial_stream] * (RX_SMOOTH_FACTOR - 1)) +
4057                                                 (pprevious_stats->RxMIMOSignalQuality[nspatial_stream] * 1)) / (RX_SMOOTH_FACTOR);
4058                                }
4059                        }
4060                }
4061        }
4062}
4063
4064/*-----------------------------------------------------------------------------
4065 * Function:    rtl819x_query_rxpwrpercentage()
4066 *
4067 * Overview:
4068 *
4069 * Input:               char            antpower
4070 *
4071 * Output:              NONE
4072 *
4073 * Return:              0-100 percentage
4074 *---------------------------------------------------------------------------
4075 */
4076static u8 rtl819x_query_rxpwrpercentage(s8 antpower)
4077{
4078        if ((antpower <= -100) || (antpower >= 20))
4079                return  0;
4080        else if (antpower >= 0)
4081                return  100;
4082        else
4083                return  100 + antpower;
4084
4085}       /* QueryRxPwrPercentage */
4086
4087static u8 rtl819x_evm_dbtopercentage(s8 value)
4088{
4089        s8 ret_val;
4090
4091        ret_val = value;
4092
4093        if (ret_val >= 0)
4094                ret_val = 0;
4095        if (ret_val <= -33)
4096                ret_val = -33;
4097        ret_val = 0 - ret_val;
4098        ret_val *= 3;
4099        if (ret_val == 99)
4100                ret_val = 100;
4101        return ret_val;
4102}
4103
4104/* We want good-looking for signal strength/quality */
4105static long rtl819x_signal_scale_mapping(long currsig)
4106{
4107        long retsig;
4108
4109        /* Step 1. Scale mapping. */
4110        if (currsig >= 61 && currsig <= 100)
4111                retsig = 90 + ((currsig - 60) / 4);
4112        else if (currsig >= 41 && currsig <= 60)
4113                retsig = 78 + ((currsig - 40) / 2);
4114        else if (currsig >= 31 && currsig <= 40)
4115                retsig = 66 + (currsig - 30);
4116        else if (currsig >= 21 && currsig <= 30)
4117                retsig = 54 + (currsig - 20);
4118        else if (currsig >= 5 && currsig <= 20)
4119                retsig = 42 + (((currsig - 5) * 2) / 3);
4120        else if (currsig == 4)
4121                retsig = 36;
4122        else if (currsig == 3)
4123                retsig = 27;
4124        else if (currsig == 2)
4125                retsig = 18;
4126        else if (currsig == 1)
4127                retsig = 9;
4128        else
4129                retsig = currsig;
4130
4131        return retsig;
4132}
4133
4134static inline bool rx_hal_is_cck_rate(struct rx_drvinfo_819x_usb *pdrvinfo)
4135{
4136        if (pdrvinfo->RxHT)
4137                return false;
4138
4139        switch (pdrvinfo->RxRate) {
4140        case DESC90_RATE1M:
4141        case DESC90_RATE2M:
4142        case DESC90_RATE5_5M:
4143        case DESC90_RATE11M:
4144                return true;
4145        default:
4146                return false;
4147        }
4148}
4149
4150static void rtl8192_query_rxphystatus(struct r8192_priv *priv,
4151                                      struct ieee80211_rx_stats *pstats,
4152                                      struct rx_drvinfo_819x_usb  *pdrvinfo,
4153                                      struct ieee80211_rx_stats *precord_stats,
4154                                      bool bpacket_match_bssid,
4155                                      bool bpacket_toself,
4156                                      bool bPacketBeacon,
4157                                      bool bToSelfBA)
4158{
4159        phy_sts_ofdm_819xusb_t *pofdm_buf;
4160        phy_sts_cck_819xusb_t   *pcck_buf;
4161        struct phy_ofdm_rx_status_rxsc_sgien_exintfflag *prxsc;
4162        u8      *prxpkt;
4163        u8      i, max_spatial_stream, tmp_rxsnr, tmp_rxevm, rxsc_sgien_exflg;
4164        s8      rx_pwr[4], rx_pwr_all = 0;
4165        s8      rx_snrX, rx_evmX;
4166        u8      evm, pwdb_all;
4167        u32     RSSI, total_rssi = 0;
4168        u8      is_cck_rate = 0;
4169        u8      rf_rx_num = 0;
4170        u8      sq;
4171
4172
4173        priv->stats.numqry_phystatus++;
4174
4175        is_cck_rate = rx_hal_is_cck_rate(pdrvinfo);
4176
4177        /* Record it for next packet processing */
4178        memset(precord_stats, 0, sizeof(struct ieee80211_rx_stats));
4179        pstats->bPacketMatchBSSID =
4180                precord_stats->bPacketMatchBSSID = bpacket_match_bssid;
4181        pstats->bPacketToSelf = precord_stats->bPacketToSelf = bpacket_toself;
4182        pstats->bIsCCK = precord_stats->bIsCCK = is_cck_rate;
4183        pstats->bPacketBeacon = precord_stats->bPacketBeacon = bPacketBeacon;
4184        pstats->bToSelfBA = precord_stats->bToSelfBA = bToSelfBA;
4185
4186        prxpkt = (u8 *)pdrvinfo;
4187
4188        /* Move pointer to the 16th bytes. Phy status start address. */
4189        prxpkt += sizeof(struct rx_drvinfo_819x_usb);
4190
4191        /* Initial the cck and ofdm buffer pointer */
4192        pcck_buf = (phy_sts_cck_819xusb_t *)prxpkt;
4193        pofdm_buf = (phy_sts_ofdm_819xusb_t *)prxpkt;
4194
4195        pstats->RxMIMOSignalQuality[0] = -1;
4196        pstats->RxMIMOSignalQuality[1] = -1;
4197        precord_stats->RxMIMOSignalQuality[0] = -1;
4198        precord_stats->RxMIMOSignalQuality[1] = -1;
4199
4200        if (is_cck_rate) {
4201                /* (1)Hardware does not provide RSSI for CCK */
4202
4203                /* (2)PWDB, Average PWDB calculated by hardware
4204                 * (for rate adaptive)
4205                 */
4206                u8 report;
4207
4208                priv->stats.numqry_phystatusCCK++;
4209
4210                if (!priv->bCckHighPower) {
4211                        report = pcck_buf->cck_agc_rpt & 0xc0;
4212                        report >>= 6;
4213                        switch (report) {
4214                        case 0x3:
4215                                rx_pwr_all = -35 - (pcck_buf->cck_agc_rpt & 0x3e);
4216                                break;
4217                        case 0x2:
4218                                rx_pwr_all = -23 - (pcck_buf->cck_agc_rpt & 0x3e);
4219                                break;
4220                        case 0x1:
4221                                rx_pwr_all = -11 - (pcck_buf->cck_agc_rpt & 0x3e);
4222                                break;
4223                        case 0x0:
4224                                rx_pwr_all = 6 - (pcck_buf->cck_agc_rpt & 0x3e);
4225                                break;
4226                        }
4227                } else {
4228                        report = pcck_buf->cck_agc_rpt & 0x60;
4229                        report >>= 5;
4230                        switch (report) {
4231                        case 0x3:
4232                                rx_pwr_all = -35 - ((pcck_buf->cck_agc_rpt & 0x1f) << 1);
4233                                break;
4234                        case 0x2:
4235                                rx_pwr_all = -23 - ((pcck_buf->cck_agc_rpt & 0x1f) << 1);
4236                                break;
4237                        case 0x1:
4238                                rx_pwr_all = -11 - ((pcck_buf->cck_agc_rpt & 0x1f) << 1);
4239                                break;
4240                        case 0x0:
4241                                rx_pwr_all = 6 - ((pcck_buf->cck_agc_rpt & 0x1f) << 1);
4242                                break;
4243                        }
4244                }
4245
4246                pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
4247                pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
4248                pstats->RecvSignalPower = pwdb_all;
4249
4250                /* (3) Get Signal Quality (EVM) */
4251
4252                if (pstats->RxPWDBAll > 40) {
4253                        sq = 100;
4254                } else {
4255                        sq = pcck_buf->sq_rpt;
4256
4257                        if (pcck_buf->sq_rpt > 64)
4258                                sq = 0;
4259                        else if (pcck_buf->sq_rpt < 20)
4260                                sq = 100;
4261                        else
4262                                sq = ((64 - sq) * 100) / 44;
4263                }
4264                pstats->SignalQuality = precord_stats->SignalQuality = sq;
4265                pstats->RxMIMOSignalQuality[0] =
4266                        precord_stats->RxMIMOSignalQuality[0] = sq;
4267                pstats->RxMIMOSignalQuality[1] =
4268                        precord_stats->RxMIMOSignalQuality[1] = -1;
4269
4270        } else {
4271                priv->stats.numqry_phystatusHT++;
4272
4273                /* (1)Get RSSI for HT rate */
4274                for (i = RF90_PATH_A; i < priv->NumTotalRFPath; i++) {
4275                        /* We will judge RF RX path now. */
4276                        if (priv->brfpath_rxenable[i])
4277                                rf_rx_num++;
4278                        else
4279                                continue;
4280
4281                        if (!rtl8192_phy_CheckIsLegalRFPath(
4282                                        priv->ieee80211->dev, i))
4283                                continue;
4284
4285                        rx_pwr[i] =
4286                                ((pofdm_buf->trsw_gain_X[i] & 0x3F) * 2) - 106;
4287
4288                        /* Get Rx snr value in DB */
4289                        tmp_rxsnr =     pofdm_buf->rxsnr_X[i];
4290                        rx_snrX = (s8)(tmp_rxsnr);
4291                        rx_snrX /= 2;
4292                        priv->stats.rxSNRdB[i] = (long)rx_snrX;
4293
4294                        /* Translate DBM to percentage. */
4295                        RSSI = rtl819x_query_rxpwrpercentage(rx_pwr[i]);
4296                        total_rssi += RSSI;
4297
4298                        /* Record Signal Strength for next packet */
4299                        pstats->RxMIMOSignalStrength[i] = (u8)RSSI;
4300                        precord_stats->RxMIMOSignalStrength[i] = (u8)RSSI;
4301                }
4302
4303
4304                /* (2)PWDB, Average PWDB calculated by hardware
4305                 * (for rate adaptive)
4306                 */
4307                rx_pwr_all = (((pofdm_buf->pwdb_all) >> 1) & 0x7f) - 106;
4308                pwdb_all = rtl819x_query_rxpwrpercentage(rx_pwr_all);
4309
4310                pstats->RxPWDBAll = precord_stats->RxPWDBAll = pwdb_all;
4311                pstats->RxPower = precord_stats->RxPower =  rx_pwr_all;
4312
4313                /* (3)EVM of HT rate */
4314                if (pdrvinfo->RxHT && pdrvinfo->RxRate >= DESC90_RATEMCS8 &&
4315                    pdrvinfo->RxRate <= DESC90_RATEMCS15)
4316                        /* both spatial stream make sense */
4317                        max_spatial_stream = 2;
4318                else
4319                        /* only spatial stream 1 makes sense */
4320                        max_spatial_stream = 1;
4321
4322                for (i = 0; i < max_spatial_stream; i++) {
4323                        tmp_rxevm =     pofdm_buf->rxevm_X[i];
4324                        rx_evmX = (s8)(tmp_rxevm);
4325
4326                        /* Do not use shift operation like "rx_evmX >>= 1"
4327                         * because the compiler of free build environment will
4328                         * set the most significant bit to "zero" when doing
4329                         * shifting operation which may change a negative value
4330                         * to positive one, then the dbm value (which is
4331                         * supposed to be negative) is not correct anymore.
4332                         */
4333                        rx_evmX /= 2;   /* dbm */
4334
4335                        evm = rtl819x_evm_dbtopercentage(rx_evmX);
4336                        if (i == 0)
4337                                /* Fill value in RFD, Get the first spatial
4338                                 * stream only
4339                                 */
4340                                pstats->SignalQuality =
4341                                        precord_stats->SignalQuality =
4342                                        evm & 0xff;
4343                        pstats->RxMIMOSignalQuality[i] =
4344                                precord_stats->RxMIMOSignalQuality[i] =
4345                                evm & 0xff;
4346                }
4347
4348
4349                /* record rx statistics for debug */
4350                rxsc_sgien_exflg = pofdm_buf->rxsc_sgien_exflg;
4351                prxsc = (struct phy_ofdm_rx_status_rxsc_sgien_exintfflag *)
4352                        &rxsc_sgien_exflg;
4353                if (pdrvinfo->BW)       /* 40M channel */
4354                        priv->stats.received_bwtype[1 + prxsc->rxsc]++;
4355                else                    /* 20M channel */
4356                        priv->stats.received_bwtype[0]++;
4357        }
4358
4359        /* UI BSS List signal strength(in percentage), make it good looking,
4360         * from 0~100. It is assigned to the BSS List in
4361         * GetValueFromBeaconOrProbeRsp().
4362         */
4363        if (is_cck_rate) {
4364                pstats->SignalStrength =
4365                        precord_stats->SignalStrength =
4366                        (u8)(rtl819x_signal_scale_mapping((long)pwdb_all));
4367        } else {
4368                /* We can judge RX path number now. */
4369                if (rf_rx_num != 0) {
4370                        pstats->SignalStrength =
4371                                precord_stats->SignalStrength =
4372                                (u8)(rtl819x_signal_scale_mapping((long)(total_rssi /= rf_rx_num)));
4373                }
4374        }
4375}       /* QueryRxPhyStatus8190Pci */
4376
4377static void rtl8192_record_rxdesc_forlateruse(
4378                struct ieee80211_rx_stats *psrc_stats,
4379                struct ieee80211_rx_stats *ptarget_stats)
4380{
4381        ptarget_stats->bIsAMPDU = psrc_stats->bIsAMPDU;
4382        ptarget_stats->bFirstMPDU = psrc_stats->bFirstMPDU;
4383        ptarget_stats->Seq_Num = psrc_stats->Seq_Num;
4384}
4385
4386
4387static void TranslateRxSignalStuff819xUsb(struct sk_buff *skb,
4388                                          struct ieee80211_rx_stats *pstats,
4389                                          struct rx_drvinfo_819x_usb  *pdrvinfo)
4390{
4391        /* TODO: We must only check packet for current MAC address.
4392         * Not finish
4393         */
4394        struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
4395        struct net_device *dev = info->dev;
4396        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4397        bool bpacket_match_bssid, bpacket_toself;
4398        bool bPacketBeacon = false, bToSelfBA = false;
4399        static struct ieee80211_rx_stats  previous_stats;
4400        struct rtl_80211_hdr_3addr *hdr;
4401        u16 fc, type;
4402
4403        /* Get Signal Quality for only RX data queue (but not command queue) */
4404
4405        u8 *tmp_buf;
4406        u8  *praddr;
4407
4408        /* Get MAC frame start address. */
4409        tmp_buf = (u8 *)skb->data;
4410
4411        hdr = (struct rtl_80211_hdr_3addr *)tmp_buf;
4412        fc = le16_to_cpu(hdr->frame_ctl);
4413        type = WLAN_FC_GET_TYPE(fc);
4414        praddr = hdr->addr1;
4415
4416        /* Check if the received packet is acceptable. */
4417        bpacket_match_bssid = (type != IEEE80211_FTYPE_CTL) &&
4418                               (ether_addr_equal(priv->ieee80211->current_network.bssid,  (fc & IEEE80211_FCTL_TODS) ? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS) ? hdr->addr2 : hdr->addr3))
4419                               && (!pstats->bHwError) && (!pstats->bCRC) && (!pstats->bICV);
4420        bpacket_toself =  bpacket_match_bssid &
4421                          (ether_addr_equal(praddr, priv->ieee80211->dev->dev_addr));
4422
4423        if (WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BEACON)
4424                bPacketBeacon = true;
4425        if (WLAN_FC_GET_FRAMETYPE(fc) == IEEE80211_STYPE_BLOCKACK) {
4426                if ((ether_addr_equal(praddr, dev->dev_addr)))
4427                        bToSelfBA = true;
4428        }
4429
4430
4431
4432        if (bpacket_match_bssid)
4433                priv->stats.numpacket_matchbssid++;
4434        if (bpacket_toself)
4435                priv->stats.numpacket_toself++;
4436        /* Process PHY information for previous packet (RSSI/PWDB/EVM)
4437         * Because phy information is contained in the last packet of AMPDU
4438         * only, so driver should process phy information of previous packet
4439         */
4440        rtl8192_process_phyinfo(priv, tmp_buf, &previous_stats, pstats);
4441        rtl8192_query_rxphystatus(priv, pstats, pdrvinfo, &previous_stats,
4442                                  bpacket_match_bssid, bpacket_toself,
4443                                  bPacketBeacon, bToSelfBA);
4444        rtl8192_record_rxdesc_forlateruse(pstats, &previous_stats);
4445}
4446
4447/**
4448 * Function:    UpdateReceivedRateHistogramStatistics
4449 * Overview:    Record the received data rate
4450 *
4451 * Input:
4452 *      struct net_device *dev
4453 *      struct ieee80211_rx_stats *stats
4454 *
4455 * Output:
4456 *
4457 *                      (priv->stats.ReceivedRateHistogram[] is updated)
4458 * Return:
4459 *              None
4460 */
4461static void
4462UpdateReceivedRateHistogramStatistics8190(struct net_device *dev,
4463                                          struct ieee80211_rx_stats *stats)
4464{
4465        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4466        /* 0: Total, 1:OK, 2:CRC, 3:ICV */
4467        u32 rcvType = 1;
4468        u32 rateIndex;
4469        /* 1: short preamble/GI, 0: long preamble/GI */
4470        u32 preamble_guardinterval;
4471
4472
4473        if (stats->bCRC)
4474                rcvType = 2;
4475        else if (stats->bICV)
4476                rcvType = 3;
4477
4478        if (stats->bShortPreamble)
4479                preamble_guardinterval = 1; /* short */
4480        else
4481                preamble_guardinterval = 0; /* long */
4482
4483        switch (stats->rate) {
4484        /* CCK rate */
4485        case MGN_1M:
4486                rateIndex = 0;
4487                break;
4488        case MGN_2M:
4489                rateIndex = 1;
4490                break;
4491        case MGN_5_5M:
4492                rateIndex = 2;
4493                break;
4494        case MGN_11M:
4495                rateIndex = 3;
4496                break;
4497        /* Legacy OFDM rate */
4498        case MGN_6M:
4499                rateIndex = 4;
4500                break;
4501        case MGN_9M:
4502                rateIndex = 5;
4503                break;
4504        case MGN_12M:
4505                rateIndex = 6;
4506                break;
4507        case MGN_18M:
4508                rateIndex = 7;
4509                break;
4510        case MGN_24M:
4511                rateIndex = 8;
4512                break;
4513        case MGN_36M:
4514                rateIndex = 9;
4515                break;
4516        case MGN_48M:
4517                rateIndex = 10;
4518                break;
4519        case MGN_54M:
4520                rateIndex = 11;
4521                break;
4522        /* 11n High throughput rate */
4523        case MGN_MCS0:
4524                rateIndex = 12;
4525                break;
4526        case MGN_MCS1:
4527                rateIndex = 13;
4528                break;
4529        case MGN_MCS2:
4530                rateIndex = 14;
4531                break;
4532        case MGN_MCS3:
4533                rateIndex = 15;
4534                break;
4535        case MGN_MCS4:
4536                rateIndex = 16;
4537                break;
4538        case MGN_MCS5:
4539                rateIndex = 17;
4540                break;
4541        case MGN_MCS6:
4542                rateIndex = 18;
4543                break;
4544        case MGN_MCS7:
4545                rateIndex = 19;
4546                break;
4547        case MGN_MCS8:
4548                rateIndex = 20;
4549                break;
4550        case MGN_MCS9:
4551                rateIndex = 21;
4552                break;
4553        case MGN_MCS10:
4554                rateIndex = 22;
4555                break;
4556        case MGN_MCS11:
4557                rateIndex = 23;
4558                break;
4559        case MGN_MCS12:
4560                rateIndex = 24;
4561                break;
4562        case MGN_MCS13:
4563                rateIndex = 25;
4564                break;
4565        case MGN_MCS14:
4566                rateIndex = 26;
4567                break;
4568        case MGN_MCS15:
4569                rateIndex = 27;
4570                break;
4571        default:
4572                rateIndex = 28;
4573                break;
4574        }
4575        priv->stats.received_preamble_GI[preamble_guardinterval][rateIndex]++;
4576        priv->stats.received_rate_histogram[0][rateIndex]++; /* total */
4577        priv->stats.received_rate_histogram[rcvType][rateIndex]++;
4578}
4579
4580
4581static void query_rxdesc_status(struct sk_buff *skb,
4582                                struct ieee80211_rx_stats *stats,
4583                                bool bIsRxAggrSubframe)
4584{
4585        struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
4586        struct net_device *dev = info->dev;
4587        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4588        struct rx_drvinfo_819x_usb  *driver_info = NULL;
4589
4590        /* Get Rx Descriptor Information */
4591        struct rx_desc_819x_usb *desc = (struct rx_desc_819x_usb *)skb->data;
4592
4593        stats->Length = desc->Length;
4594        stats->RxDrvInfoSize = desc->RxDrvInfoSize;
4595        stats->RxBufShift = 0;
4596        stats->bICV = desc->ICV;
4597        stats->bCRC = desc->CRC32;
4598        stats->bHwError = stats->bCRC | stats->bICV;
4599        /* RTL8190 set this bit to indicate that Hw does not decrypt packet */
4600        stats->Decrypted = !desc->SWDec;
4601
4602        if ((priv->ieee80211->pHTInfo->bCurrentHTSupport) &&
4603            (priv->ieee80211->pairwise_key_type == KEY_TYPE_CCMP))
4604                stats->bHwError = false;
4605        else
4606                stats->bHwError = stats->bCRC | stats->bICV;
4607
4608        if (stats->Length < 24 || stats->Length > MAX_8192U_RX_SIZE)
4609                stats->bHwError |= 1;
4610        /* Get Driver Info */
4611        /* TODO: Need to verify it on FGPA platform
4612         * Driver info are written to the RxBuffer following rx desc
4613         */
4614        if (stats->RxDrvInfoSize != 0) {
4615                driver_info = (struct rx_drvinfo_819x_usb *)(
4616                                skb->data
4617                                + sizeof(struct rx_desc_819x_usb)
4618                                + stats->RxBufShift
4619                              );
4620                /* unit: 0.5M */
4621                /* TODO */
4622                if (!stats->bHwError) {
4623                        u8      ret_rate;
4624
4625                        ret_rate = HwRateToMRate90(driver_info->RxHT,
4626                                                   driver_info->RxRate);
4627                        if (ret_rate == 0xff) {
4628                                /* Abnormal Case: Receive CRC OK packet with Rx
4629                                 * descriptor indicating non supported rate.
4630                                 * Special Error Handling here
4631                                 */
4632
4633                                stats->bHwError = 1;
4634                                /* Set 1M rate by default */
4635                                stats->rate = MGN_1M;
4636                        } else {
4637                                stats->rate = ret_rate;
4638                        }
4639                } else {
4640                        stats->rate = 0x02;
4641                }
4642
4643                stats->bShortPreamble = driver_info->SPLCP;
4644
4645
4646                UpdateReceivedRateHistogramStatistics8190(dev, stats);
4647
4648                stats->bIsAMPDU = (driver_info->PartAggr == 1);
4649                stats->bFirstMPDU = (driver_info->PartAggr == 1) &&
4650                                    (driver_info->FirstAGGR == 1);
4651                stats->TimeStampLow = driver_info->TSFL;
4652
4653                UpdateRxPktTimeStamp8190(dev, stats);
4654
4655                /* Rx A-MPDU */
4656                if (driver_info->FirstAGGR == 1 || driver_info->PartAggr == 1)
4657                        RT_TRACE(COMP_RXDESC,
4658                                "driver_info->FirstAGGR = %d, driver_info->PartAggr = %d\n",
4659                                 driver_info->FirstAGGR, driver_info->PartAggr);
4660        }
4661
4662        skb_pull(skb, sizeof(struct rx_desc_819x_usb));
4663        /* Get Total offset of MPDU Frame Body */
4664        if ((stats->RxBufShift + stats->RxDrvInfoSize) > 0) {
4665                stats->bShift = 1;
4666                skb_pull(skb, stats->RxBufShift + stats->RxDrvInfoSize);
4667        }
4668
4669        if (driver_info) {
4670                stats->RxIs40MHzPacket = driver_info->BW;
4671                TranslateRxSignalStuff819xUsb(skb, stats, driver_info);
4672        }
4673}
4674
4675static void rtl8192_rx_nomal(struct sk_buff *skb)
4676{
4677        struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
4678        struct net_device *dev = info->dev;
4679        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
4680        struct ieee80211_rx_stats stats = {
4681                .signal = 0,
4682                .noise = 0x100 - 98,
4683                .rate = 0,
4684                .freq = IEEE80211_24GHZ_BAND,
4685        };
4686        u32 rx_pkt_len = 0;
4687        struct rtl_80211_hdr_1addr *ieee80211_hdr = NULL;
4688        bool unicast_packet = false;
4689
4690        /* 20 is for ps-poll */
4691        if ((skb->len >= (20 + sizeof(struct rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
4692                /* first packet should not contain Rx aggregation header */
4693                query_rxdesc_status(skb, &stats, false);
4694                /* TODO */
4695                /* hardware related info */
4696                /* Process the MPDU received */
4697                skb_trim(skb, skb->len - 4/*sCrcLng*/);
4698
4699                rx_pkt_len = skb->len;
4700                ieee80211_hdr = (struct rtl_80211_hdr_1addr *)skb->data;
4701                unicast_packet = false;
4702                if (is_broadcast_ether_addr(ieee80211_hdr->addr1)) {
4703                        /* TODO */
4704                } else if (is_multicast_ether_addr(ieee80211_hdr->addr1)) {
4705                        /* TODO */
4706                } else {
4707                        /* unicast packet */
4708                        unicast_packet = true;
4709                }
4710
4711                if (!ieee80211_rx(priv->ieee80211, skb, &stats)) {
4712                        dev_kfree_skb_any(skb);
4713                } else {
4714                        priv->stats.rxoktotal++;
4715                        if (unicast_packet)
4716                                priv->stats.rxbytesunicast += rx_pkt_len;
4717                }
4718        } else {
4719                priv->stats.rxurberr++;
4720                netdev_dbg(dev, "actual_length: %d\n", skb->len);
4721                dev_kfree_skb_any(skb);
4722        }
4723}
4724
4725static void rtl819xusb_process_received_packet(
4726                struct net_device *dev,
4727                struct ieee80211_rx_stats *pstats)
4728{
4729        struct r8192_priv *priv = ieee80211_priv(dev);
4730
4731        /* Get shifted bytes of Starting address of 802.11 header. */
4732        pstats->virtual_address += get_rxpacket_shiftbytes_819xusb(pstats);
4733#ifdef TODO     /* about HCT */
4734        if (!Adapter->bInHctTest)
4735                CountRxErrStatistics(Adapter, pRfd);
4736#endif
4737#ifdef ENABLE_PS  /* for adding ps function in future */
4738        RT_RF_POWER_STATE rtState;
4739        /* When RF is off, we should not count the packet for hw/sw synchronize
4740         * reason, ie. there may be a duration while sw switch is changed and
4741         * hw switch is being changed.
4742         */
4743        Adapter->HalFunc.GetHwRegHandler(Adapter, HW_VAR_RF_STATE,
4744                                         (u8 *)(&rtState));
4745        if (rtState == eRfOff)
4746                return;
4747#endif
4748        priv->stats.rxframgment++;
4749
4750#ifdef TODO
4751        RmMonitorSignalStrength(Adapter, pRfd);
4752#endif
4753        /* We have to release RFD and return if rx pkt is cmd pkt. */
4754        if (rtl819xusb_rx_command_packet(dev, pstats))
4755                return;
4756
4757#ifdef SW_CRC_CHECK
4758        SwCrcCheck();
4759#endif
4760
4761
4762}
4763
4764static void query_rx_cmdpkt_desc_status(struct sk_buff *skb,
4765                                        struct ieee80211_rx_stats *stats)
4766{
4767        struct rx_desc_819x_usb *desc = (struct rx_desc_819x_usb *)skb->data;
4768
4769        /* Get Rx Descriptor Information */
4770        stats->virtual_address = (u8 *)skb->data;
4771        stats->Length = desc->Length;
4772        stats->RxDrvInfoSize = 0;
4773        stats->RxBufShift = 0;
4774        stats->packetlength = stats->Length - scrclng;
4775        stats->fraglength = stats->packetlength;
4776        stats->fragoffset = 0;
4777        stats->ntotalfrag = 1;
4778}
4779
4780
4781static void rtl8192_rx_cmd(struct sk_buff *skb)
4782{
4783        struct rtl8192_rx_info *info = (struct rtl8192_rx_info *)skb->cb;
4784        struct net_device *dev = info->dev;
4785        /* TODO */
4786        struct ieee80211_rx_stats stats = {
4787                .signal = 0,
4788                .noise = 0x100 - 98,
4789                .rate = 0,
4790                .freq = IEEE80211_24GHZ_BAND,
4791        };
4792
4793        if ((skb->len >= (20 + sizeof(struct rx_desc_819x_usb))) && (skb->len < RX_URB_SIZE)) {
4794                query_rx_cmdpkt_desc_status(skb, &stats);
4795                /* prfd->queue_id = 1; */
4796
4797                /* Process the command packet received. */
4798
4799                rtl819xusb_process_received_packet(dev, &stats);
4800
4801                dev_kfree_skb_any(skb);
4802        }
4803}
4804
4805static void rtl8192_irq_rx_tasklet(struct r8192_priv *priv)
4806{
4807        struct sk_buff *skb;
4808        struct rtl8192_rx_info *info;
4809
4810        while (NULL != (skb = skb_dequeue(&priv->skb_queue))) {
4811                info = (struct rtl8192_rx_info *)skb->cb;
4812                switch (info->out_pipe) {
4813                /* Nomal packet pipe */
4814                case 3:
4815                        priv->IrpPendingCount--;
4816                        rtl8192_rx_nomal(skb);
4817                        break;
4818
4819                /* Command packet pipe */
4820                case 9:
4821                        RT_TRACE(COMP_RECV, "command in-pipe index(%d)\n",
4822                                 info->out_pipe);
4823
4824                        rtl8192_rx_cmd(skb);
4825                        break;
4826
4827                default: /* should never get here! */
4828                        RT_TRACE(COMP_ERR, "Unknown in-pipe index(%d)\n",
4829                                 info->out_pipe);
4830                        dev_kfree_skb(skb);
4831                        break;
4832                }
4833        }
4834}
4835
4836static const struct net_device_ops rtl8192_netdev_ops = {
4837        .ndo_open               = rtl8192_open,
4838        .ndo_stop               = rtl8192_close,
4839        .ndo_get_stats          = rtl8192_stats,
4840        .ndo_tx_timeout         = tx_timeout,
4841        .ndo_do_ioctl           = rtl8192_ioctl,
4842        .ndo_set_rx_mode        = r8192_set_multicast,
4843        .ndo_set_mac_address    = r8192_set_mac_adr,
4844        .ndo_validate_addr      = eth_validate_addr,
4845        .ndo_start_xmit         = ieee80211_xmit,
4846};
4847
4848
4849/****************************************************************************
4850 *    ---------------------------- USB_STUFF---------------------------
4851 *****************************************************************************/
4852
4853static int rtl8192_usb_probe(struct usb_interface *intf,
4854                             const struct usb_device_id *id)
4855{
4856        struct net_device *dev = NULL;
4857        struct r8192_priv *priv = NULL;
4858        struct usb_device *udev = interface_to_usbdev(intf);
4859        int ret;
4860
4861        RT_TRACE(COMP_INIT, "Oops: i'm coming\n");
4862
4863        dev = alloc_ieee80211(sizeof(struct r8192_priv));
4864        if (!dev)
4865                return -ENOMEM;
4866
4867        usb_set_intfdata(intf, dev);
4868        SET_NETDEV_DEV(dev, &intf->dev);
4869        priv = ieee80211_priv(dev);
4870        priv->ieee80211 = netdev_priv(dev);
4871        priv->udev = udev;
4872
4873        dev->netdev_ops = &rtl8192_netdev_ops;
4874
4875        dev->wireless_handlers = &r8192_wx_handlers_def;
4876
4877        dev->type = ARPHRD_ETHER;
4878
4879        dev->watchdog_timeo = HZ * 3;
4880
4881        if (dev_alloc_name(dev, ifname) < 0) {
4882                RT_TRACE(COMP_INIT,
4883                         "Oops: devname already taken! Trying wlan%%d...\n");
4884                ifname = "wlan%d";
4885                dev_alloc_name(dev, ifname);
4886        }
4887
4888        RT_TRACE(COMP_INIT, "Driver probe completed1\n");
4889        if (rtl8192_init(dev) != 0) {
4890                RT_TRACE(COMP_ERR, "Initialization failed");
4891                ret = -ENODEV;
4892                goto fail;
4893        }
4894        netif_carrier_off(dev);
4895        netif_stop_queue(dev);
4896
4897        ret = register_netdev(dev);
4898        if (ret)
4899                goto fail2;
4900
4901        RT_TRACE(COMP_INIT, "dev name=======> %s\n", dev->name);
4902        rtl8192_proc_init_one(dev);
4903
4904
4905        RT_TRACE(COMP_INIT, "Driver probe completed\n");
4906        return 0;
4907
4908fail2:
4909        rtl8192_down(dev);
4910fail:
4911        kfree(priv->pFirmware);
4912        priv->pFirmware = NULL;
4913        rtl8192_usb_deleteendpoints(dev);
4914        msleep(10);
4915        free_ieee80211(dev);
4916
4917        RT_TRACE(COMP_ERR, "wlan driver load failed\n");
4918        return ret;
4919}
4920
4921/* detach all the work and timer structure declared or inititialize
4922 * in r8192U_init function.
4923 */
4924static void rtl8192_cancel_deferred_work(struct r8192_priv *priv)
4925{
4926        cancel_work_sync(&priv->reset_wq);
4927        cancel_delayed_work(&priv->watch_dog_wq);
4928        cancel_delayed_work(&priv->update_beacon_wq);
4929        cancel_work_sync(&priv->qos_activate);
4930}
4931
4932
4933static void rtl8192_usb_disconnect(struct usb_interface *intf)
4934{
4935        struct net_device *dev = usb_get_intfdata(intf);
4936        struct r8192_priv *priv = ieee80211_priv(dev);
4937
4938        unregister_netdev(dev);
4939
4940        RT_TRACE(COMP_DOWN, "=============>wlan driver to be removed\n");
4941        rtl8192_proc_remove_one(dev);
4942
4943        rtl8192_down(dev);
4944        kfree(priv->pFirmware);
4945        priv->pFirmware = NULL;
4946        rtl8192_usb_deleteendpoints(dev);
4947        usleep_range(10000, 11000);
4948        free_ieee80211(dev);
4949
4950        RT_TRACE(COMP_DOWN, "wlan driver removed\n");
4951}
4952
4953static int __init rtl8192_usb_module_init(void)
4954{
4955        int ret;
4956
4957#ifdef CONFIG_IEEE80211_DEBUG
4958        ret = ieee80211_debug_init();
4959        if (ret) {
4960                pr_err("ieee80211_debug_init() failed %d\n", ret);
4961                return ret;
4962        }
4963#endif
4964        ret = ieee80211_crypto_init();
4965        if (ret) {
4966                pr_err("ieee80211_crypto_init() failed %d\n", ret);
4967                return ret;
4968        }
4969
4970        ret = ieee80211_crypto_tkip_init();
4971        if (ret) {
4972                pr_err("ieee80211_crypto_tkip_init() failed %d\n", ret);
4973                return ret;
4974        }
4975
4976        ret = ieee80211_crypto_ccmp_init();
4977        if (ret) {
4978                pr_err("ieee80211_crypto_ccmp_init() failed %d\n", ret);
4979                return ret;
4980        }
4981
4982        ret = ieee80211_crypto_wep_init();
4983        if (ret) {
4984                pr_err("ieee80211_crypto_wep_init() failed %d\n", ret);
4985                return ret;
4986        }
4987
4988        pr_info("\nLinux kernel driver for RTL8192 based WLAN cards\n");
4989        pr_info("Copyright (c) 2007-2008, Realsil Wlan\n");
4990        RT_TRACE(COMP_INIT, "Initializing module");
4991        RT_TRACE(COMP_INIT, "Wireless extensions version %d", WIRELESS_EXT);
4992        rtl8192_proc_module_init();
4993        return usb_register(&rtl8192_usb_driver);
4994}
4995
4996
4997static void __exit rtl8192_usb_module_exit(void)
4998{
4999        usb_deregister(&rtl8192_usb_driver);
5000
5001        RT_TRACE(COMP_DOWN, "Exiting");
5002}
5003
5004void EnableHWSecurityConfig8192(struct net_device *dev)
5005{
5006        u8 SECR_value = 0x0;
5007        struct r8192_priv *priv = (struct r8192_priv *)ieee80211_priv(dev);
5008        struct ieee80211_device *ieee = priv->ieee80211;
5009
5010        SECR_value = SCR_TxEncEnable | SCR_RxDecEnable;
5011        if (((ieee->pairwise_key_type == KEY_TYPE_WEP40) || (ieee->pairwise_key_type == KEY_TYPE_WEP104)) && (priv->ieee80211->auth_mode != 2)) {
5012                SECR_value |= SCR_RxUseDK;
5013                SECR_value |= SCR_TxUseDK;
5014        } else if ((ieee->iw_mode == IW_MODE_ADHOC) && (ieee->pairwise_key_type & (KEY_TYPE_CCMP | KEY_TYPE_TKIP))) {
5015                SECR_value |= SCR_RxUseDK;
5016                SECR_value |= SCR_TxUseDK;
5017        }
5018        /* add HWSec active enable here.
5019         * default using hwsec. when peer AP is in N mode only and
5020         * pairwise_key_type is none_aes(which HT_IOT_ACT_PURE_N_MODE indicates
5021         * it), use software security. when peer AP is in b,g,n mode mixed and
5022         * pairwise_key_type is none_aes, use g mode hw security.
5023         */
5024
5025        ieee->hwsec_active = 1;
5026
5027        /* add hwsec_support flag to totol control hw_sec on/off */
5028        if ((ieee->pHTInfo->IOTAction & HT_IOT_ACT_PURE_N_MODE) || !hwwep) {
5029                ieee->hwsec_active = 0;
5030                SECR_value &= ~SCR_RxDecEnable;
5031        }
5032        RT_TRACE(COMP_SEC, "%s:, hwsec:%d, pairwise_key:%d, SECR_value:%x\n",
5033                 __func__, ieee->hwsec_active, ieee->pairwise_key_type,
5034                 SECR_value);
5035        write_nic_byte(dev, SECR,  SECR_value);
5036}
5037
5038
5039void setKey(struct net_device *dev, u8 EntryNo, u8 KeyIndex, u16 KeyType,
5040            u8 *MacAddr, u8 DefaultKey, u32 *KeyContent)
5041{
5042        u32 TargetCommand = 0;
5043        u32 TargetContent = 0;
5044        u16 usConfig = 0;
5045        u8 i;
5046
5047        if (EntryNo >= TOTAL_CAM_ENTRY)
5048                RT_TRACE(COMP_ERR, "cam entry exceeds in setKey()\n");
5049
5050        RT_TRACE(COMP_SEC,
5051                 "====>to setKey(), dev:%p, EntryNo:%d, KeyIndex:%d, KeyType:%d, MacAddr%pM\n",
5052                 dev, EntryNo, KeyIndex, KeyType, MacAddr);
5053
5054        if (DefaultKey)
5055                usConfig |= BIT(15) | (KeyType << 2);
5056        else
5057                usConfig |= BIT(15) | (KeyType << 2) | KeyIndex;
5058
5059
5060        for (i = 0; i < CAM_CONTENT_COUNT; i++) {
5061                TargetCommand  = i + CAM_CONTENT_COUNT * EntryNo;
5062                TargetCommand |= BIT(31) | BIT(16);
5063
5064                if (i == 0) { /* MAC|Config */
5065                        TargetContent = (u32)(*(MacAddr + 0)) << 16 |
5066                                        (u32)(*(MacAddr + 1)) << 24 |
5067                                        (u32)usConfig;
5068
5069                        write_nic_dword(dev, WCAMI, TargetContent);
5070                        write_nic_dword(dev, RWCAM, TargetCommand);
5071                } else if (i == 1) { /* MAC */
5072                        TargetContent = (u32)(*(MacAddr + 2))    |
5073                                        (u32)(*(MacAddr + 3)) <<  8 |
5074                                        (u32)(*(MacAddr + 4)) << 16 |
5075                                        (u32)(*(MacAddr + 5)) << 24;
5076                        write_nic_dword(dev, WCAMI, TargetContent);
5077                        write_nic_dword(dev, RWCAM, TargetCommand);
5078                } else {
5079                        /* Key Material */
5080                        if (KeyContent) {
5081                                write_nic_dword(dev, WCAMI,
5082                                                *(KeyContent + i - 2));
5083                                write_nic_dword(dev, RWCAM, TargetCommand);
5084                        }
5085                }
5086        }
5087}
5088
5089/***************************************************************************
5090 *    ------------------- module init / exit stubs ----------------
5091 ****************************************************************************/
5092module_init(rtl8192_usb_module_init);
5093module_exit(rtl8192_usb_module_exit);
5094