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