linux/drivers/staging/rtl8187se/r8180_core.c
<<
>>
Prefs
   1/*
   2   This is part of rtl818x pci OpenSource driver - v 0.1
   3   Copyright (C) Andrea Merello 2004-2005  <andreamrl@tiscali.it>
   4   Released under the terms of GPL (General Public License)
   5
   6   Parts of this driver are based on the GPL part of the official
   7   Realtek driver.
   8
   9   Parts of this driver are based on the rtl8180 driver skeleton
  10   from Patric Schenke & Andres Salomon.
  11
  12   Parts of this driver are based on the Intel Pro Wireless 2100 GPL driver.
  13
  14   Parts of BB/RF code are derived from David Young rtl8180 netbsd driver.
  15
  16   RSSI calc function from 'The Deuce'
  17
  18   Some ideas borrowed from the 8139too.c driver included in linux kernel.
  19
  20   We (I?) want to thanks the Authors of those projecs and also the
  21   Ndiswrapper's project Authors.
  22
  23   A big big thanks goes also to Realtek corp. for their help in my attempt to
  24   add RTL8185 and RTL8225 support, and to David Young also.
  25
  26   Power management interface routines.
  27   Written by Mariusz Matuszek.
  28*/
  29
  30#undef RX_DONT_PASS_UL
  31#undef DUMMY_RX
  32
  33#include <linux/syscalls.h>
  34
  35#include "r8180_hw.h"
  36#include "r8180.h"
  37#include "r8180_rtl8225.h" /* RTL8225 Radio frontend */
  38#include "r8180_93cx6.h"   /* Card EEPROM */
  39#include "r8180_wx.h"
  40#include "r8180_dm.h"
  41
  42#include "ieee80211/dot11d.h"
  43
  44#ifndef PCI_VENDOR_ID_BELKIN
  45        #define PCI_VENDOR_ID_BELKIN 0x1799
  46#endif
  47#ifndef PCI_VENDOR_ID_DLINK
  48        #define PCI_VENDOR_ID_DLINK 0x1186
  49#endif
  50
  51static struct pci_device_id rtl8180_pci_id_tbl[] __devinitdata = {
  52        {
  53                .vendor = PCI_VENDOR_ID_REALTEK,
  54                .device = 0x8199,
  55                .subvendor = PCI_ANY_ID,
  56                .subdevice = PCI_ANY_ID,
  57                .driver_data = 0,
  58        },
  59        {
  60                .vendor = 0,
  61                .device = 0,
  62                .subvendor = 0,
  63                .subdevice = 0,
  64                .driver_data = 0,
  65        }
  66};
  67
  68
  69static char* ifname = "wlan%d";
  70static int hwseqnum = 0;
  71static int hwwep = 0;
  72static int channels = 0x3fff;
  73
  74#define eqMacAddr(a,b)          ( ((a)[0]==(b)[0] && (a)[1]==(b)[1] && (a)[2]==(b)[2] && (a)[3]==(b)[3] && (a)[4]==(b)[4] && (a)[5]==(b)[5]) ? 1:0 )
  75#define cpMacAddr(des,src)            ((des)[0]=(src)[0],(des)[1]=(src)[1],(des)[2]=(src)[2],(des)[3]=(src)[3],(des)[4]=(src)[4],(des)[5]=(src)[5])
  76MODULE_LICENSE("GPL");
  77MODULE_DEVICE_TABLE(pci, rtl8180_pci_id_tbl);
  78MODULE_AUTHOR("Andrea Merello <andreamrl@tiscali.it>");
  79MODULE_DESCRIPTION("Linux driver for Realtek RTL8180 / RTL8185 WiFi cards");
  80
  81
  82module_param(ifname, charp, S_IRUGO|S_IWUSR );
  83module_param(hwseqnum,int, S_IRUGO|S_IWUSR);
  84module_param(hwwep,int, S_IRUGO|S_IWUSR);
  85module_param(channels,int, S_IRUGO|S_IWUSR);
  86
  87MODULE_PARM_DESC(devname," Net interface name, wlan%d=default");
  88MODULE_PARM_DESC(hwseqnum," Try to use hardware 802.11 header sequence numbers. Zero=default");
  89MODULE_PARM_DESC(hwwep," Try to use hardware WEP support. Still broken and not available on all cards");
  90MODULE_PARM_DESC(channels," Channel bitmask for specific locales. NYI");
  91
  92
  93static int __devinit rtl8180_pci_probe(struct pci_dev *pdev,
  94                                       const struct pci_device_id *id);
  95
  96static void __devexit rtl8180_pci_remove(struct pci_dev *pdev);
  97
  98static void rtl8180_shutdown (struct pci_dev *pdev)
  99{
 100        struct net_device *dev = pci_get_drvdata(pdev);
 101        if (dev->netdev_ops->ndo_stop)
 102                dev->netdev_ops->ndo_stop(dev);
 103        pci_disable_device(pdev);
 104}
 105
 106static int rtl8180_suspend(struct pci_dev *pdev, pm_message_t state)
 107{
 108        struct net_device *dev = pci_get_drvdata(pdev);
 109
 110        if (!netif_running(dev))
 111                goto out_pci_suspend;
 112
 113        if (dev->netdev_ops->ndo_stop)
 114                dev->netdev_ops->ndo_stop(dev);
 115
 116        netif_device_detach(dev);
 117
 118out_pci_suspend:
 119        pci_save_state(pdev);
 120        pci_disable_device(pdev);
 121        pci_set_power_state(pdev, pci_choose_state(pdev, state));
 122        return 0;
 123}
 124
 125static int rtl8180_resume(struct pci_dev *pdev)
 126{
 127        struct net_device *dev = pci_get_drvdata(pdev);
 128        int err;
 129        u32 val;
 130
 131        pci_set_power_state(pdev, PCI_D0);
 132
 133        err = pci_enable_device(pdev);
 134        if (err) {
 135                printk(KERN_ERR "%s: pci_enable_device failed on resume\n",
 136                                dev->name);
 137
 138                return err;
 139        }
 140
 141        pci_restore_state(pdev);
 142
 143        /*
 144         * Suspend/Resume resets the PCI configuration space, so we have to
 145         * re-disable the RETRY_TIMEOUT register (0x41) to keep PCI Tx retries
 146         * from interfering with C3 CPU state. pci_restore_state won't help
 147         * here since it only restores the first 64 bytes pci config header.
 148         */
 149        pci_read_config_dword(pdev, 0x40, &val);
 150        if ((val & 0x0000ff00) != 0)
 151                pci_write_config_dword(pdev, 0x40, val & 0xffff00ff);
 152
 153        if (!netif_running(dev))
 154                goto out;
 155
 156        if (dev->netdev_ops->ndo_open)
 157                dev->netdev_ops->ndo_open(dev);
 158
 159        netif_device_attach(dev);
 160out:
 161        return 0;
 162}
 163
 164static struct pci_driver rtl8180_pci_driver = {
 165        .name           = RTL8180_MODULE_NAME,
 166        .id_table       = rtl8180_pci_id_tbl,
 167        .probe          = rtl8180_pci_probe,
 168        .remove         = __devexit_p(rtl8180_pci_remove),
 169        .suspend        = rtl8180_suspend,
 170        .resume         = rtl8180_resume,
 171        .shutdown       = rtl8180_shutdown,
 172};
 173
 174u8 read_nic_byte(struct net_device *dev, int x)
 175{
 176        return 0xff&readb((u8*)dev->mem_start +x);
 177}
 178
 179u32 read_nic_dword(struct net_device *dev, int x)
 180{
 181        return readl((u8*)dev->mem_start +x);
 182}
 183
 184u16 read_nic_word(struct net_device *dev, int x)
 185{
 186        return readw((u8*)dev->mem_start +x);
 187}
 188
 189void write_nic_byte(struct net_device *dev, int x,u8 y)
 190{
 191        writeb(y,(u8*)dev->mem_start +x);
 192        udelay(20);
 193}
 194
 195void write_nic_dword(struct net_device *dev, int x,u32 y)
 196{
 197        writel(y,(u8*)dev->mem_start +x);
 198        udelay(20);
 199}
 200
 201void write_nic_word(struct net_device *dev, int x,u16 y)
 202{
 203        writew(y,(u8*)dev->mem_start +x);
 204        udelay(20);
 205}
 206
 207inline void force_pci_posting(struct net_device *dev)
 208{
 209        read_nic_byte(dev,EPROM_CMD);
 210        mb();
 211}
 212
 213irqreturn_t rtl8180_interrupt(int irq, void *netdev, struct pt_regs *regs);
 214void set_nic_rxring(struct net_device *dev);
 215void set_nic_txring(struct net_device *dev);
 216static struct net_device_stats *rtl8180_stats(struct net_device *dev);
 217void rtl8180_commit(struct net_device *dev);
 218void rtl8180_start_tx_beacon(struct net_device *dev);
 219
 220static struct proc_dir_entry *rtl8180_proc = NULL;
 221
 222static int proc_get_registers(char *page, char **start,
 223                          off_t offset, int count,
 224                          int *eof, void *data)
 225{
 226        struct net_device *dev = data;
 227        int len = 0;
 228        int i,n;
 229        int max = 0xff;
 230
 231        /* This dump the current register page */
 232        for (n = 0; n <= max;) {
 233                len += snprintf(page + len, count - len, "\nD:  %2x > ", n);
 234
 235                for (i = 0; i < 16 && n <= max; i++, n++)
 236                        len += snprintf(page + len, count - len, "%2x ",
 237                                        read_nic_byte(dev, n));
 238        }
 239        len += snprintf(page + len, count - len,"\n");
 240
 241        *eof = 1;
 242        return len;
 243}
 244
 245int get_curr_tx_free_desc(struct net_device *dev, int priority);
 246
 247static int proc_get_stats_hw(char *page, char **start,
 248                          off_t offset, int count,
 249                          int *eof, void *data)
 250{
 251        int len = 0;
 252
 253        *eof = 1;
 254        return len;
 255}
 256
 257static int proc_get_stats_rx(char *page, char **start,
 258                          off_t offset, int count,
 259                          int *eof, void *data)
 260{
 261        struct net_device *dev = data;
 262        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 263
 264        int len = 0;
 265
 266        len += snprintf(page + len, count - len,
 267                "RX OK: %lu\n"
 268                "RX Retry: %lu\n"
 269                "RX CRC Error(0-500): %lu\n"
 270                "RX CRC Error(500-1000): %lu\n"
 271                "RX CRC Error(>1000): %lu\n"
 272                "RX ICV Error: %lu\n",
 273                priv->stats.rxint,
 274                priv->stats.rxerr,
 275                priv->stats.rxcrcerrmin,
 276                priv->stats.rxcrcerrmid,
 277                priv->stats.rxcrcerrmax,
 278                priv->stats.rxicverr
 279                );
 280
 281        *eof = 1;
 282        return len;
 283}
 284
 285static int proc_get_stats_tx(char *page, char **start,
 286                          off_t offset, int count,
 287                          int *eof, void *data)
 288{
 289        struct net_device *dev = data;
 290        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 291
 292        int len = 0;
 293        unsigned long totalOK;
 294
 295        totalOK=priv->stats.txnpokint+priv->stats.txhpokint+priv->stats.txlpokint;
 296        len += snprintf(page + len, count - len,
 297                "TX OK: %lu\n"
 298                "TX Error: %lu\n"
 299                "TX Retry: %lu\n"
 300                "TX beacon OK: %lu\n"
 301                "TX beacon error: %lu\n",
 302                totalOK,
 303                priv->stats.txnperr+priv->stats.txhperr+priv->stats.txlperr,
 304                priv->stats.txretry,
 305                priv->stats.txbeacon,
 306                priv->stats.txbeaconerr
 307        );
 308
 309        *eof = 1;
 310        return len;
 311}
 312
 313void rtl8180_proc_module_init(void)
 314{
 315        DMESG("Initializing proc filesystem");
 316        rtl8180_proc=create_proc_entry(RTL8180_MODULE_NAME, S_IFDIR, init_net.proc_net);
 317}
 318
 319void rtl8180_proc_module_remove(void)
 320{
 321        remove_proc_entry(RTL8180_MODULE_NAME, init_net.proc_net);
 322}
 323
 324void rtl8180_proc_remove_one(struct net_device *dev)
 325{
 326        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 327        if (priv->dir_dev) {
 328                remove_proc_entry("stats-hw", priv->dir_dev);
 329                remove_proc_entry("stats-tx", priv->dir_dev);
 330                remove_proc_entry("stats-rx", priv->dir_dev);
 331                remove_proc_entry("registers", priv->dir_dev);
 332                remove_proc_entry(dev->name, rtl8180_proc);
 333                priv->dir_dev = NULL;
 334        }
 335}
 336
 337void rtl8180_proc_init_one(struct net_device *dev)
 338{
 339        struct proc_dir_entry *e;
 340        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 341
 342        priv->dir_dev = rtl8180_proc;
 343        if (!priv->dir_dev) {
 344                DMESGE("Unable to initialize /proc/net/r8180/%s\n",
 345                      dev->name);
 346                return;
 347        }
 348
 349        e = create_proc_read_entry("stats-hw", S_IFREG | S_IRUGO,
 350                                   priv->dir_dev, proc_get_stats_hw, dev);
 351        if (!e) {
 352                DMESGE("Unable to initialize "
 353                      "/proc/net/r8180/%s/stats-hw\n",
 354                      dev->name);
 355        }
 356
 357        e = create_proc_read_entry("stats-rx", S_IFREG | S_IRUGO,
 358                                   priv->dir_dev, proc_get_stats_rx, dev);
 359        if (!e) {
 360                DMESGE("Unable to initialize "
 361                      "/proc/net/r8180/%s/stats-rx\n",
 362                      dev->name);
 363        }
 364
 365
 366        e = create_proc_read_entry("stats-tx", S_IFREG | S_IRUGO,
 367                                   priv->dir_dev, proc_get_stats_tx, dev);
 368        if (!e) {
 369                DMESGE("Unable to initialize "
 370                      "/proc/net/r8180/%s/stats-tx\n",
 371                      dev->name);
 372        }
 373
 374        e = create_proc_read_entry("registers", S_IFREG | S_IRUGO,
 375                                   priv->dir_dev, proc_get_registers, dev);
 376        if (!e) {
 377                DMESGE("Unable to initialize "
 378                      "/proc/net/r8180/%s/registers\n",
 379                      dev->name);
 380        }
 381}
 382
 383/*
 384  FIXME: check if we can use some standard already-existent
 385  data type+functions in kernel
 386*/
 387
 388short buffer_add(struct buffer **buffer, u32 *buf, dma_addr_t dma,
 389                struct buffer **bufferhead)
 390{
 391        struct buffer *tmp;
 392
 393        if(! *buffer){
 394
 395                *buffer = kmalloc(sizeof(struct buffer),GFP_KERNEL);
 396
 397                if (*buffer == NULL) {
 398                        DMESGE("Failed to kmalloc head of TX/RX struct");
 399                        return -1;
 400                }
 401                (*buffer)->next=*buffer;
 402                (*buffer)->buf=buf;
 403                (*buffer)->dma=dma;
 404                if(bufferhead !=NULL)
 405                        (*bufferhead) = (*buffer);
 406                return 0;
 407        }
 408        tmp=*buffer;
 409
 410        while(tmp->next!=(*buffer)) tmp=tmp->next;
 411        if ((tmp->next= kmalloc(sizeof(struct buffer),GFP_KERNEL)) == NULL){
 412                DMESGE("Failed to kmalloc TX/RX struct");
 413                return -1;
 414        }
 415        tmp->next->buf=buf;
 416        tmp->next->dma=dma;
 417        tmp->next->next=*buffer;
 418
 419        return 0;
 420}
 421
 422void buffer_free(struct net_device *dev,struct buffer **buffer,int len,short
 423consistent)
 424{
 425
 426        struct buffer *tmp,*next;
 427        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 428        struct pci_dev *pdev=priv->pdev;
 429
 430        if (!*buffer)
 431                return;
 432
 433        tmp = *buffer;
 434
 435        do{
 436                next=tmp->next;
 437                if(consistent){
 438                        pci_free_consistent(pdev,len,
 439                                    tmp->buf,tmp->dma);
 440                }else{
 441                        pci_unmap_single(pdev, tmp->dma,
 442                        len,PCI_DMA_FROMDEVICE);
 443                        kfree(tmp->buf);
 444                }
 445                kfree(tmp);
 446                tmp = next;
 447        }
 448        while(next != *buffer);
 449
 450        *buffer=NULL;
 451}
 452
 453void print_buffer(u32 *buffer, int len)
 454{
 455        int i;
 456        u8 *buf =(u8*)buffer;
 457
 458        printk("ASCII BUFFER DUMP (len: %x):\n",len);
 459
 460        for(i=0;i<len;i++)
 461                printk("%c",buf[i]);
 462
 463        printk("\nBINARY BUFFER DUMP (len: %x):\n",len);
 464
 465        for(i=0;i<len;i++)
 466                printk("%02x",buf[i]);
 467
 468        printk("\n");
 469}
 470
 471int get_curr_tx_free_desc(struct net_device *dev, int priority)
 472{
 473        struct r8180_priv *priv = ieee80211_priv(dev);
 474        u32* tail;
 475        u32* head;
 476        int ret;
 477
 478        switch (priority){
 479                case MANAGE_PRIORITY:
 480                        head = priv->txmapringhead;
 481                        tail = priv->txmapringtail;
 482                        break;
 483                case BK_PRIORITY:
 484                        head = priv->txbkpringhead;
 485                        tail = priv->txbkpringtail;
 486                        break;
 487                case BE_PRIORITY:
 488                        head = priv->txbepringhead;
 489                        tail = priv->txbepringtail;
 490                        break;
 491                case VI_PRIORITY:
 492                        head = priv->txvipringhead;
 493                        tail = priv->txvipringtail;
 494                        break;
 495                case VO_PRIORITY:
 496                        head = priv->txvopringhead;
 497                        tail = priv->txvopringtail;
 498                        break;
 499                case HI_PRIORITY:
 500                        head = priv->txhpringhead;
 501                        tail = priv->txhpringtail;
 502                        break;
 503                default:
 504                        return -1;
 505        }
 506
 507        if (head <= tail)
 508                ret = priv->txringcount - (tail - head)/8;
 509        else
 510                ret = (head - tail)/8;
 511
 512        if (ret > priv->txringcount)
 513                DMESG("BUG");
 514
 515        return ret;
 516}
 517
 518short check_nic_enought_desc(struct net_device *dev, int priority)
 519{
 520        struct r8180_priv *priv = ieee80211_priv(dev);
 521        struct ieee80211_device *ieee = netdev_priv(dev);
 522        int requiredbyte, required;
 523
 524        requiredbyte = priv->ieee80211->fts + sizeof(struct ieee80211_header_data);
 525
 526        if (ieee->current_network.QoS_Enable)
 527                requiredbyte += 2;
 528
 529        required = requiredbyte / (priv->txbuffsize-4);
 530
 531        if (requiredbyte % priv->txbuffsize)
 532                required++;
 533
 534        /* for now we keep two free descriptor as a safety boundary
 535         * between the tail and the head
 536         */
 537
 538        return (required+2 < get_curr_tx_free_desc(dev,priority));
 539}
 540
 541void fix_tx_fifo(struct net_device *dev)
 542{
 543        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 544        u32 *tmp;
 545        int i;
 546
 547        for (tmp=priv->txmapring, i=0;
 548             i < priv->txringcount;
 549             tmp+=8, i++){
 550                *tmp = *tmp &~ (1<<31);
 551        }
 552
 553        for (tmp=priv->txbkpring, i=0;
 554             i < priv->txringcount;
 555             tmp+=8, i++) {
 556                *tmp = *tmp &~ (1<<31);
 557        }
 558
 559        for (tmp=priv->txbepring, i=0;
 560             i < priv->txringcount;
 561             tmp+=8, i++){
 562                *tmp = *tmp &~ (1<<31);
 563        }
 564        for (tmp=priv->txvipring, i=0;
 565             i < priv->txringcount;
 566             tmp+=8, i++) {
 567                *tmp = *tmp &~ (1<<31);
 568        }
 569
 570        for (tmp=priv->txvopring, i=0;
 571             i < priv->txringcount;
 572             tmp+=8, i++){
 573                *tmp = *tmp &~ (1<<31);
 574        }
 575
 576        for (tmp=priv->txhpring, i=0;
 577             i < priv->txringcount;
 578             tmp+=8,i++){
 579                *tmp = *tmp &~ (1<<31);
 580        }
 581
 582        for (tmp=priv->txbeaconring, i=0;
 583             i < priv->txbeaconcount;
 584             tmp+=8, i++){
 585                *tmp = *tmp &~ (1<<31);
 586        }
 587
 588        priv->txmapringtail = priv->txmapring;
 589        priv->txmapringhead = priv->txmapring;
 590        priv->txmapbufstail = priv->txmapbufs;
 591
 592        priv->txbkpringtail = priv->txbkpring;
 593        priv->txbkpringhead = priv->txbkpring;
 594        priv->txbkpbufstail = priv->txbkpbufs;
 595
 596        priv->txbepringtail = priv->txbepring;
 597        priv->txbepringhead = priv->txbepring;
 598        priv->txbepbufstail = priv->txbepbufs;
 599
 600        priv->txvipringtail = priv->txvipring;
 601        priv->txvipringhead = priv->txvipring;
 602        priv->txvipbufstail = priv->txvipbufs;
 603
 604        priv->txvopringtail = priv->txvopring;
 605        priv->txvopringhead = priv->txvopring;
 606        priv->txvopbufstail = priv->txvopbufs;
 607
 608        priv->txhpringtail = priv->txhpring;
 609        priv->txhpringhead = priv->txhpring;
 610        priv->txhpbufstail = priv->txhpbufs;
 611
 612        priv->txbeaconringtail = priv->txbeaconring;
 613        priv->txbeaconbufstail = priv->txbeaconbufs;
 614        set_nic_txring(dev);
 615
 616        ieee80211_reset_queue(priv->ieee80211);
 617        priv->ack_tx_to_ieee = 0;
 618}
 619
 620void fix_rx_fifo(struct net_device *dev)
 621{
 622        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 623        u32 *tmp;
 624        struct buffer *rxbuf;
 625        u8 rx_desc_size;
 626
 627        rx_desc_size = 8; // 4*8 = 32 bytes
 628
 629        for (tmp=priv->rxring, rxbuf=priv->rxbufferhead;
 630             (tmp < (priv->rxring)+(priv->rxringcount)*rx_desc_size);
 631             tmp+=rx_desc_size,rxbuf=rxbuf->next){
 632                *(tmp+2) = rxbuf->dma;
 633                *tmp=*tmp &~ 0xfff;
 634                *tmp=*tmp | priv->rxbuffersize;
 635                *tmp |= (1<<31);
 636        }
 637
 638        priv->rxringtail=priv->rxring;
 639        priv->rxbuffer=priv->rxbufferhead;
 640        priv->rx_skb_complete=1;
 641        set_nic_rxring(dev);
 642}
 643
 644unsigned char QUALITY_MAP[] = {
 645        0x64, 0x64, 0x64, 0x63, 0x63, 0x62, 0x62, 0x61,
 646        0x61, 0x60, 0x60, 0x5f, 0x5f, 0x5e, 0x5d, 0x5c,
 647        0x5b, 0x5a, 0x59, 0x57, 0x56, 0x54, 0x52, 0x4f,
 648        0x4c, 0x49, 0x45, 0x41, 0x3c, 0x37, 0x31, 0x29,
 649        0x24, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
 650        0x22, 0x22, 0x21, 0x21, 0x21, 0x21, 0x21, 0x20,
 651        0x20, 0x20, 0x20, 0x1f, 0x1f, 0x1e, 0x1e, 0x1e,
 652        0x1d, 0x1d, 0x1c, 0x1c, 0x1b, 0x1a, 0x19, 0x19,
 653        0x18, 0x17, 0x16, 0x15, 0x14, 0x12, 0x11, 0x0f,
 654        0x0e, 0x0c, 0x0a, 0x08, 0x06, 0x04, 0x01, 0x00
 655};
 656
 657unsigned char STRENGTH_MAP[] = {
 658        0x64, 0x64, 0x63, 0x62, 0x61, 0x60, 0x5f, 0x5e,
 659        0x5d, 0x5c, 0x5b, 0x5a, 0x57, 0x54, 0x52, 0x50,
 660        0x4e, 0x4c, 0x4a, 0x48, 0x46, 0x44, 0x41, 0x3f,
 661        0x3c, 0x3a, 0x37, 0x36, 0x36, 0x1c, 0x1c, 0x1b,
 662        0x1b, 0x1a, 0x1a, 0x19, 0x19, 0x18, 0x18, 0x17,
 663        0x17, 0x16, 0x16, 0x15, 0x15, 0x14, 0x14, 0x13,
 664        0x13, 0x12, 0x12, 0x11, 0x11, 0x10, 0x10, 0x0f,
 665        0x0f, 0x0e, 0x0e, 0x0d, 0x0d, 0x0c, 0x0c, 0x0b,
 666        0x0b, 0x0a, 0x0a, 0x09, 0x09, 0x08, 0x08, 0x07,
 667        0x07, 0x06, 0x06, 0x05, 0x04, 0x03, 0x02, 0x00
 668};
 669
 670void rtl8180_RSSI_calc(struct net_device *dev, u8 *rssi, u8 *qual)
 671{
 672        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 673        u32 temp;
 674        u32 temp2;
 675        u32 temp3;
 676        u32 lsb;
 677        u32 q;
 678        u32 orig_qual;
 679        u8  _rssi;
 680
 681        q = *qual;
 682        orig_qual = *qual;
 683        _rssi = 0; // avoid gcc complains..
 684
 685        if (q <= 0x4e) {
 686                temp = QUALITY_MAP[q];
 687        } else {
 688                if( q & 0x80 ) {
 689                        temp = 0x32;
 690                } else {
 691                        temp = 1;
 692                }
 693        }
 694
 695        *qual = temp;
 696        temp2 = *rssi;
 697
 698        switch(priv->rf_chip){
 699        case RFCHIPID_RFMD:
 700                lsb = temp2 & 1;
 701                temp2 &= 0x7e;
 702                if ( !lsb || !(temp2 <= 0x3c) ) {
 703                        temp2 = 0x64;
 704                } else {
 705                        temp2 = 100 * temp2 / 0x3c;
 706                }
 707                *rssi = temp2 & 0xff;
 708                _rssi = temp2 & 0xff;
 709                break;
 710        case RFCHIPID_INTERSIL:
 711                lsb = temp2;
 712                temp2 &= 0xfffffffe;
 713                temp2 *= 251;
 714                temp3 = temp2;
 715                temp2 <<= 6;
 716                temp3 += temp2;
 717                temp3 <<= 1;
 718                temp2 = 0x4950df;
 719                temp2 -= temp3;
 720                lsb &= 1;
 721                if ( temp2 <= 0x3e0000 ) {
 722                        if ( temp2 < 0xffef0000 )
 723                                temp2 = 0xffef0000;
 724                } else {
 725                        temp2 = 0x3e0000;
 726                }
 727                if ( !lsb ) {
 728                        temp2 -= 0xf0000;
 729                } else {
 730                        temp2 += 0xf0000;
 731                }
 732
 733                temp3 = 0x4d0000;
 734                temp3 -= temp2;
 735                temp3 *= 100;
 736                temp3 = temp3 / 0x6d;
 737                temp3 >>= 0x10;
 738                _rssi = temp3 & 0xff;
 739                *rssi = temp3 & 0xff;
 740                break;
 741        case RFCHIPID_GCT:
 742                lsb = temp2 & 1;
 743                temp2 &= 0x7e;
 744                if ( ! lsb || !(temp2 <= 0x3c) ){
 745                        temp2 = 0x64;
 746                } else {
 747                        temp2 = (100 * temp2) / 0x3c;
 748                }
 749                *rssi = temp2 & 0xff;
 750                _rssi = temp2 & 0xff;
 751                break;
 752        case RFCHIPID_PHILIPS:
 753                if( orig_qual <= 0x4e ){
 754                        _rssi = STRENGTH_MAP[orig_qual];
 755                        *rssi = _rssi;
 756                } else {
 757                        orig_qual -= 0x80;
 758                        if ( !orig_qual ){
 759                                _rssi = 1;
 760                                *rssi = 1;
 761                        } else {
 762                                _rssi = 0x32;
 763                                *rssi = 0x32;
 764                        }
 765                }
 766                break;
 767        case RFCHIPID_MAXIM:
 768                lsb = temp2 & 1;
 769                temp2 &= 0x7e;
 770                temp2 >>= 1;
 771                temp2 += 0x42;
 772                if( lsb != 0 ){
 773                        temp2 += 0xa;
 774                }
 775                *rssi = temp2 & 0xff;
 776                _rssi = temp2 & 0xff;
 777                break;
 778        }
 779
 780        if ( _rssi < 0x64 ){
 781                if ( _rssi == 0 ) {
 782                        *rssi = 1;
 783                }
 784        } else {
 785                *rssi = 0x64;
 786        }
 787
 788        return;
 789}
 790
 791void rtl8180_irq_enable(struct net_device *dev)
 792{
 793        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 794
 795        priv->irq_enabled = 1;
 796        write_nic_word(dev,INTA_MASK, priv->irq_mask);
 797}
 798
 799void rtl8180_irq_disable(struct net_device *dev)
 800{
 801        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 802
 803        write_nic_dword(dev,IMR,0);
 804        force_pci_posting(dev);
 805        priv->irq_enabled = 0;
 806}
 807
 808void rtl8180_set_mode(struct net_device *dev,int mode)
 809{
 810        u8 ecmd;
 811
 812        ecmd=read_nic_byte(dev, EPROM_CMD);
 813        ecmd=ecmd &~ EPROM_CMD_OPERATING_MODE_MASK;
 814        ecmd=ecmd | (mode<<EPROM_CMD_OPERATING_MODE_SHIFT);
 815        ecmd=ecmd &~ (1<<EPROM_CS_SHIFT);
 816        ecmd=ecmd &~ (1<<EPROM_CK_SHIFT);
 817        write_nic_byte(dev, EPROM_CMD, ecmd);
 818}
 819
 820void rtl8180_adapter_start(struct net_device *dev);
 821void rtl8180_beacon_tx_enable(struct net_device *dev);
 822
 823void rtl8180_update_msr(struct net_device *dev)
 824{
 825        struct r8180_priv *priv = ieee80211_priv(dev);
 826        u8 msr;
 827        u32 rxconf;
 828
 829        msr  = read_nic_byte(dev, MSR);
 830        msr &= ~ MSR_LINK_MASK;
 831
 832        rxconf=read_nic_dword(dev,RX_CONF);
 833
 834        if(priv->ieee80211->state == IEEE80211_LINKED)
 835        {
 836                if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
 837                        msr |= (MSR_LINK_ADHOC<<MSR_LINK_SHIFT);
 838                else if (priv->ieee80211->iw_mode == IW_MODE_MASTER)
 839                        msr |= (MSR_LINK_MASTER<<MSR_LINK_SHIFT);
 840                else if (priv->ieee80211->iw_mode == IW_MODE_INFRA)
 841                        msr |= (MSR_LINK_MANAGED<<MSR_LINK_SHIFT);
 842                else
 843                        msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
 844                rxconf |= (1<<RX_CHECK_BSSID_SHIFT);
 845
 846        }else {
 847                msr |= (MSR_LINK_NONE<<MSR_LINK_SHIFT);
 848                rxconf &= ~(1<<RX_CHECK_BSSID_SHIFT);
 849        }
 850
 851        write_nic_byte(dev, MSR, msr);
 852        write_nic_dword(dev, RX_CONF, rxconf);
 853}
 854
 855void rtl8180_set_chan(struct net_device *dev,short ch)
 856{
 857        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 858
 859        if ((ch > 14) || (ch < 1)) {
 860                printk("In %s: Invalid chnanel %d\n", __func__, ch);
 861                return;
 862        }
 863
 864        priv->chan=ch;
 865        priv->rf_set_chan(dev,priv->chan);
 866}
 867
 868void rtl8180_rx_enable(struct net_device *dev)
 869{
 870        u8 cmd;
 871        u32 rxconf;
 872        /* for now we accept data, management & ctl frame*/
 873        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 874
 875        rxconf=read_nic_dword(dev,RX_CONF);
 876        rxconf = rxconf &~ MAC_FILTER_MASK;
 877        rxconf = rxconf | (1<<ACCEPT_MNG_FRAME_SHIFT);
 878        rxconf = rxconf | (1<<ACCEPT_DATA_FRAME_SHIFT);
 879        rxconf = rxconf | (1<<ACCEPT_BCAST_FRAME_SHIFT);
 880        rxconf = rxconf | (1<<ACCEPT_MCAST_FRAME_SHIFT);
 881        if (dev->flags & IFF_PROMISC)
 882                DMESG("NIC in promisc mode");
 883
 884        if(priv->ieee80211->iw_mode == IW_MODE_MONITOR || \
 885           dev->flags & IFF_PROMISC){
 886                rxconf = rxconf | (1<<ACCEPT_ALLMAC_FRAME_SHIFT);
 887        }else{
 888                rxconf = rxconf | (1<<ACCEPT_NICMAC_FRAME_SHIFT);
 889                if(priv->card_8185 == 0)
 890                        rxconf = rxconf | (1<<RX_CHECK_BSSID_SHIFT);
 891        }
 892
 893        if(priv->ieee80211->iw_mode == IW_MODE_MONITOR){
 894                rxconf = rxconf | (1<<ACCEPT_CTL_FRAME_SHIFT);
 895                rxconf = rxconf | (1<<ACCEPT_ICVERR_FRAME_SHIFT);
 896                rxconf = rxconf | (1<<ACCEPT_PWR_FRAME_SHIFT);
 897        }
 898
 899        if( priv->crcmon == 1 && priv->ieee80211->iw_mode == IW_MODE_MONITOR)
 900                rxconf = rxconf | (1<<ACCEPT_CRCERR_FRAME_SHIFT);
 901
 902        rxconf = rxconf & ~RX_FIFO_THRESHOLD_MASK;
 903        rxconf = rxconf | (RX_FIFO_THRESHOLD_NONE << RX_FIFO_THRESHOLD_SHIFT);
 904
 905        rxconf = rxconf | (1<<RX_AUTORESETPHY_SHIFT);
 906        rxconf = rxconf &~ MAX_RX_DMA_MASK;
 907        rxconf = rxconf | (MAX_RX_DMA_2048<<MAX_RX_DMA_SHIFT);
 908
 909        rxconf = rxconf | RCR_ONLYERLPKT;
 910
 911        rxconf = rxconf &~ RCR_CS_MASK;
 912
 913        if (!priv->card_8185)
 914                rxconf |= (priv->rcr_csense<<RCR_CS_SHIFT);
 915
 916        write_nic_dword(dev, RX_CONF, rxconf);
 917
 918        fix_rx_fifo(dev);
 919
 920        cmd=read_nic_byte(dev,CMD);
 921        write_nic_byte(dev,CMD,cmd | (1<<CMD_RX_ENABLE_SHIFT));
 922}
 923
 924void set_nic_txring(struct net_device *dev)
 925{
 926        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 927
 928        write_nic_dword(dev, TX_MANAGEPRIORITY_RING_ADDR, priv->txmapringdma);
 929        write_nic_dword(dev, TX_BKPRIORITY_RING_ADDR, priv->txbkpringdma);
 930        write_nic_dword(dev, TX_BEPRIORITY_RING_ADDR, priv->txbepringdma);
 931        write_nic_dword(dev, TX_VIPRIORITY_RING_ADDR, priv->txvipringdma);
 932        write_nic_dword(dev, TX_VOPRIORITY_RING_ADDR, priv->txvopringdma);
 933        write_nic_dword(dev, TX_HIGHPRIORITY_RING_ADDR, priv->txhpringdma);
 934        write_nic_dword(dev, TX_BEACON_RING_ADDR, priv->txbeaconringdma);
 935}
 936
 937void rtl8180_conttx_enable(struct net_device *dev)
 938{
 939        u32 txconf;
 940
 941        txconf = read_nic_dword(dev,TX_CONF);
 942        txconf = txconf &~ TX_LOOPBACK_MASK;
 943        txconf = txconf | (TX_LOOPBACK_CONTINUE <<TX_LOOPBACK_SHIFT);
 944        write_nic_dword(dev,TX_CONF,txconf);
 945}
 946
 947void rtl8180_conttx_disable(struct net_device *dev)
 948{
 949        u32 txconf;
 950
 951        txconf = read_nic_dword(dev,TX_CONF);
 952        txconf = txconf &~ TX_LOOPBACK_MASK;
 953        txconf = txconf | (TX_LOOPBACK_NONE <<TX_LOOPBACK_SHIFT);
 954        write_nic_dword(dev,TX_CONF,txconf);
 955}
 956
 957void rtl8180_tx_enable(struct net_device *dev)
 958{
 959        u8 cmd;
 960        u8 tx_agc_ctl;
 961        u8 byte;
 962        u32 txconf;
 963        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
 964
 965        txconf = read_nic_dword(dev, TX_CONF);
 966
 967        if (priv->card_8185) {
 968                byte = read_nic_byte(dev,CW_CONF);
 969                byte &= ~(1<<CW_CONF_PERPACKET_CW_SHIFT);
 970                byte &= ~(1<<CW_CONF_PERPACKET_RETRY_SHIFT);
 971                write_nic_byte(dev, CW_CONF, byte);
 972
 973                tx_agc_ctl = read_nic_byte(dev, TX_AGC_CTL);
 974                tx_agc_ctl &= ~(1<<TX_AGC_CTL_PERPACKET_GAIN_SHIFT);
 975                tx_agc_ctl &= ~(1<<TX_AGC_CTL_PERPACKET_ANTSEL_SHIFT);
 976                tx_agc_ctl |=(1<<TX_AGC_CTL_FEEDBACK_ANT);
 977                write_nic_byte(dev, TX_AGC_CTL, tx_agc_ctl);
 978                write_nic_byte(dev, 0xec, 0x3f); /* Disable early TX */
 979        }
 980
 981        if (priv->card_8185)
 982                txconf = txconf &~ (1<<TCR_PROBE_NOTIMESTAMP_SHIFT);
 983        else {
 984                if(hwseqnum)
 985                        txconf= txconf &~ (1<<TX_CONF_HEADER_AUTOICREMENT_SHIFT);
 986                else
 987                        txconf= txconf | (1<<TX_CONF_HEADER_AUTOICREMENT_SHIFT);
 988        }
 989
 990        txconf = txconf &~ TX_LOOPBACK_MASK;
 991        txconf = txconf | (TX_LOOPBACK_NONE <<TX_LOOPBACK_SHIFT);
 992        txconf = txconf &~ TCR_DPRETRY_MASK;
 993        txconf = txconf &~ TCR_RTSRETRY_MASK;
 994        txconf = txconf | (priv->retry_data<<TX_DPRETRY_SHIFT);
 995        txconf = txconf | (priv->retry_rts<<TX_RTSRETRY_SHIFT);
 996        txconf = txconf &~ (1<<TX_NOCRC_SHIFT);
 997
 998        if (priv->card_8185) {
 999                if (priv->hw_plcp_len)
1000                        txconf = txconf &~ TCR_PLCP_LEN;
1001                else
1002                        txconf = txconf | TCR_PLCP_LEN;
1003        } else
1004                txconf = txconf &~ TCR_SAT;
1005
1006        txconf = txconf &~ TCR_MXDMA_MASK;
1007        txconf = txconf | (TCR_MXDMA_2048<<TCR_MXDMA_SHIFT);
1008        txconf = txconf | TCR_CWMIN;
1009        txconf = txconf | TCR_DISCW;
1010
1011        txconf = txconf | (1 << TX_NOICV_SHIFT);
1012
1013        write_nic_dword(dev,TX_CONF,txconf);
1014
1015        fix_tx_fifo(dev);
1016
1017        cmd=read_nic_byte(dev,CMD);
1018        write_nic_byte(dev,CMD,cmd | (1<<CMD_TX_ENABLE_SHIFT));
1019
1020        write_nic_dword(dev,TX_CONF,txconf);
1021}
1022
1023void rtl8180_beacon_tx_enable(struct net_device *dev)
1024{
1025        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1026
1027        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
1028        priv->dma_poll_stop_mask &= ~(TPPOLLSTOP_BQ);
1029        write_nic_byte(dev,TPPollStop, priv->dma_poll_mask);
1030        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
1031}
1032
1033void rtl8180_beacon_tx_disable(struct net_device *dev)
1034{
1035        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1036
1037        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
1038        priv->dma_poll_stop_mask |= TPPOLLSTOP_BQ;
1039        write_nic_byte(dev,TPPollStop, priv->dma_poll_stop_mask);
1040        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
1041
1042}
1043
1044void rtl8180_rtx_disable(struct net_device *dev)
1045{
1046        u8 cmd;
1047        struct r8180_priv *priv = ieee80211_priv(dev);
1048
1049        cmd=read_nic_byte(dev,CMD);
1050        write_nic_byte(dev, CMD, cmd &~ \
1051                       ((1<<CMD_RX_ENABLE_SHIFT)|(1<<CMD_TX_ENABLE_SHIFT)));
1052        force_pci_posting(dev);
1053        mdelay(10);
1054
1055        if(!priv->rx_skb_complete)
1056                dev_kfree_skb_any(priv->rx_skb);
1057}
1058
1059short alloc_tx_desc_ring(struct net_device *dev, int bufsize, int count,
1060                         int addr)
1061{
1062        int i;
1063        u32 *desc;
1064        u32 *tmp;
1065        dma_addr_t dma_desc, dma_tmp;
1066        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1067        struct pci_dev *pdev = priv->pdev;
1068        void *buf;
1069
1070        if((bufsize & 0xfff) != bufsize) {
1071                DMESGE ("TX buffer allocation too large");
1072                return 0;
1073        }
1074        desc = (u32*)pci_alloc_consistent(pdev,
1075                                          sizeof(u32)*8*count+256, &dma_desc);
1076        if (desc == NULL)
1077                return -1;
1078
1079        if (dma_desc & 0xff)
1080                /*
1081                 * descriptor's buffer must be 256 byte aligned
1082                 * we shouldn't be here, since we set DMA mask !
1083                 */
1084                WARN(1, "DMA buffer is not aligned\n");
1085
1086        tmp = desc;
1087
1088        for (i = 0; i < count; i++) {
1089                buf = (void *)pci_alloc_consistent(pdev, bufsize, &dma_tmp);
1090                if (buf == NULL)
1091                        return -ENOMEM;
1092
1093                switch(addr) {
1094                case TX_MANAGEPRIORITY_RING_ADDR:
1095                        if(-1 == buffer_add(&(priv->txmapbufs),buf,dma_tmp,NULL)){
1096                                DMESGE("Unable to allocate mem for buffer NP");
1097                                return -ENOMEM;
1098                        }
1099                        break;
1100                case TX_BKPRIORITY_RING_ADDR:
1101                        if(-1 == buffer_add(&(priv->txbkpbufs),buf,dma_tmp,NULL)){
1102                                DMESGE("Unable to allocate mem for buffer LP");
1103                                return -ENOMEM;
1104                        }
1105                        break;
1106                case TX_BEPRIORITY_RING_ADDR:
1107                        if(-1 == buffer_add(&(priv->txbepbufs),buf,dma_tmp,NULL)){
1108                                DMESGE("Unable to allocate mem for buffer NP");
1109                                return -ENOMEM;
1110                        }
1111                        break;
1112                case TX_VIPRIORITY_RING_ADDR:
1113                        if(-1 == buffer_add(&(priv->txvipbufs),buf,dma_tmp,NULL)){
1114                                DMESGE("Unable to allocate mem for buffer LP");
1115                                return -ENOMEM;
1116                        }
1117                        break;
1118                case TX_VOPRIORITY_RING_ADDR:
1119                        if(-1 == buffer_add(&(priv->txvopbufs),buf,dma_tmp,NULL)){
1120                                DMESGE("Unable to allocate mem for buffer NP");
1121                                return -ENOMEM;
1122                        }
1123                        break;
1124                case TX_HIGHPRIORITY_RING_ADDR:
1125                        if(-1 == buffer_add(&(priv->txhpbufs),buf,dma_tmp,NULL)){
1126                                DMESGE("Unable to allocate mem for buffer HP");
1127                                return -ENOMEM;
1128                        }
1129                        break;
1130                case TX_BEACON_RING_ADDR:
1131                        if(-1 == buffer_add(&(priv->txbeaconbufs),buf,dma_tmp,NULL)){
1132                        DMESGE("Unable to allocate mem for buffer BP");
1133                                return -ENOMEM;
1134                        }
1135                        break;
1136                }
1137                *tmp = *tmp &~ (1<<31); // descriptor empty, owned by the drv
1138                *(tmp+2) = (u32)dma_tmp;
1139                *(tmp+3) = bufsize;
1140
1141                if(i+1<count)
1142                        *(tmp+4) = (u32)dma_desc+((i+1)*8*4);
1143                else
1144                        *(tmp+4) = (u32)dma_desc;
1145
1146                tmp=tmp+8;
1147        }
1148
1149        switch(addr) {
1150        case TX_MANAGEPRIORITY_RING_ADDR:
1151                priv->txmapringdma=dma_desc;
1152                priv->txmapring=desc;
1153                break;
1154        case TX_BKPRIORITY_RING_ADDR:
1155                priv->txbkpringdma=dma_desc;
1156                priv->txbkpring=desc;
1157                break;
1158        case TX_BEPRIORITY_RING_ADDR:
1159                priv->txbepringdma=dma_desc;
1160                priv->txbepring=desc;
1161                break;
1162        case TX_VIPRIORITY_RING_ADDR:
1163                priv->txvipringdma=dma_desc;
1164                priv->txvipring=desc;
1165                break;
1166        case TX_VOPRIORITY_RING_ADDR:
1167                priv->txvopringdma=dma_desc;
1168                priv->txvopring=desc;
1169                break;
1170        case TX_HIGHPRIORITY_RING_ADDR:
1171                priv->txhpringdma=dma_desc;
1172                priv->txhpring=desc;
1173                break;
1174        case TX_BEACON_RING_ADDR:
1175                priv->txbeaconringdma=dma_desc;
1176                priv->txbeaconring=desc;
1177                break;
1178
1179        }
1180
1181        return 0;
1182}
1183
1184void free_tx_desc_rings(struct net_device *dev)
1185{
1186        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1187        struct pci_dev *pdev=priv->pdev;
1188        int count = priv->txringcount;
1189
1190        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1191                            priv->txmapring, priv->txmapringdma);
1192        buffer_free(dev,&(priv->txmapbufs),priv->txbuffsize,1);
1193
1194        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1195                            priv->txbkpring, priv->txbkpringdma);
1196        buffer_free(dev,&(priv->txbkpbufs),priv->txbuffsize,1);
1197
1198        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1199                            priv->txbepring, priv->txbepringdma);
1200        buffer_free(dev,&(priv->txbepbufs),priv->txbuffsize,1);
1201
1202        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1203                            priv->txvipring, priv->txvipringdma);
1204        buffer_free(dev,&(priv->txvipbufs),priv->txbuffsize,1);
1205
1206        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1207                            priv->txvopring, priv->txvopringdma);
1208        buffer_free(dev,&(priv->txvopbufs),priv->txbuffsize,1);
1209
1210        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1211                            priv->txhpring, priv->txhpringdma);
1212        buffer_free(dev,&(priv->txhpbufs),priv->txbuffsize,1);
1213
1214        count = priv->txbeaconcount;
1215        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1216                            priv->txbeaconring, priv->txbeaconringdma);
1217        buffer_free(dev,&(priv->txbeaconbufs),priv->txbuffsize,1);
1218}
1219
1220void free_rx_desc_ring(struct net_device *dev)
1221{
1222        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1223        struct pci_dev *pdev = priv->pdev;
1224        int count = priv->rxringcount;
1225
1226        pci_free_consistent(pdev, sizeof(u32)*8*count+256,
1227                            priv->rxring, priv->rxringdma);
1228
1229        buffer_free(dev,&(priv->rxbuffer),priv->rxbuffersize,0);
1230}
1231
1232short alloc_rx_desc_ring(struct net_device *dev, u16 bufsize, int count)
1233{
1234        int i;
1235        u32 *desc;
1236        u32 *tmp;
1237        dma_addr_t dma_desc,dma_tmp;
1238        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1239        struct pci_dev *pdev=priv->pdev;
1240        void *buf;
1241        u8 rx_desc_size;
1242
1243        rx_desc_size = 8; // 4*8 = 32 bytes
1244
1245        if((bufsize & 0xfff) != bufsize){
1246                DMESGE ("RX buffer allocation too large");
1247                return -1;
1248        }
1249
1250        desc = (u32*)pci_alloc_consistent(pdev,sizeof(u32)*rx_desc_size*count+256,
1251                                          &dma_desc);
1252
1253        if (dma_desc & 0xff)
1254                /*
1255                 * descriptor's buffer must be 256 byte aligned
1256                 * should never happen since we specify the DMA mask
1257                 */
1258                WARN(1, "DMA buffer is not aligned\n");
1259
1260        priv->rxring=desc;
1261        priv->rxringdma=dma_desc;
1262        tmp=desc;
1263
1264        for (i = 0; i < count; i++) {
1265                if ((buf= kmalloc(bufsize * sizeof(u8),GFP_ATOMIC)) == NULL){
1266                        DMESGE("Failed to kmalloc RX buffer");
1267                        return -1;
1268                }
1269
1270                dma_tmp = pci_map_single(pdev,buf,bufsize * sizeof(u8),
1271                                         PCI_DMA_FROMDEVICE);
1272
1273                if(-1 == buffer_add(&(priv->rxbuffer), buf,dma_tmp,
1274                           &(priv->rxbufferhead))){
1275                           DMESGE("Unable to allocate mem RX buf");
1276                           return -1;
1277                }
1278                *tmp = 0; //zero pads the header of the descriptor
1279                *tmp = *tmp |( bufsize&0xfff);
1280                *(tmp+2) = (u32)dma_tmp;
1281                *tmp = *tmp |(1<<31); // descriptor void, owned by the NIC
1282
1283                tmp=tmp+rx_desc_size;
1284        }
1285
1286        *(tmp-rx_desc_size) = *(tmp-rx_desc_size) | (1<<30); // this is the last descriptor
1287
1288        return 0;
1289}
1290
1291
1292void set_nic_rxring(struct net_device *dev)
1293{
1294        u8 pgreg;
1295        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1296
1297        pgreg=read_nic_byte(dev, PGSELECT);
1298        write_nic_byte(dev, PGSELECT, pgreg &~ (1<<PGSELECT_PG_SHIFT));
1299
1300        write_nic_dword(dev, RXRING_ADDR,priv->rxringdma);
1301}
1302
1303void rtl8180_reset(struct net_device *dev)
1304{
1305        u8 cr;
1306
1307        rtl8180_irq_disable(dev);
1308
1309        cr=read_nic_byte(dev,CMD);
1310        cr = cr & 2;
1311        cr = cr | (1<<CMD_RST_SHIFT);
1312        write_nic_byte(dev,CMD,cr);
1313
1314        force_pci_posting(dev);
1315
1316        mdelay(200);
1317
1318        if(read_nic_byte(dev,CMD) & (1<<CMD_RST_SHIFT))
1319                DMESGW("Card reset timeout!");
1320        else
1321                DMESG("Card successfully reset");
1322
1323        rtl8180_set_mode(dev,EPROM_CMD_LOAD);
1324        force_pci_posting(dev);
1325        mdelay(200);
1326}
1327
1328inline u16 ieeerate2rtlrate(int rate)
1329{
1330        switch(rate){
1331        case 10:
1332                return 0;
1333        case 20:
1334                return 1;
1335        case 55:
1336                return 2;
1337        case 110:
1338                return 3;
1339        case 60:
1340                return 4;
1341        case 90:
1342                return 5;
1343        case 120:
1344                return 6;
1345        case 180:
1346                return 7;
1347        case 240:
1348                return 8;
1349        case 360:
1350                return 9;
1351        case 480:
1352                return 10;
1353        case 540:
1354                return 11;
1355        default:
1356                return 3;
1357        }
1358}
1359
1360static u16 rtl_rate[] = {10,20,55,110,60,90,120,180,240,360,480,540,720};
1361
1362inline u16 rtl8180_rate2rate(short rate)
1363{
1364        if (rate > 12)
1365                return 10;
1366        return rtl_rate[rate];
1367}
1368
1369inline u8 rtl8180_IsWirelessBMode(u16 rate)
1370{
1371        if( ((rate <= 110) && (rate != 60) && (rate != 90)) || (rate == 220) )
1372                return 1;
1373        else
1374                return 0;
1375}
1376
1377u16 N_DBPSOfRate(u16 DataRate);
1378
1379u16 ComputeTxTime(u16 FrameLength, u16 DataRate, u8 bManagementFrame,
1380                  u8 bShortPreamble)
1381{
1382        u16     FrameTime;
1383        u16     N_DBPS;
1384        u16     Ceiling;
1385
1386        if (rtl8180_IsWirelessBMode(DataRate)) {
1387                if (bManagementFrame || !bShortPreamble || DataRate == 10)
1388                        /* long preamble */
1389                        FrameTime = (u16)(144+48+(FrameLength*8/(DataRate/10)));
1390                else
1391                        /* short preamble */
1392                        FrameTime = (u16)(72+24+(FrameLength*8/(DataRate/10)));
1393
1394                if ((FrameLength*8 % (DataRate/10)) != 0) /* get the ceilling */
1395                        FrameTime++;
1396        } else {        /* 802.11g DSSS-OFDM PLCP length field calculation. */
1397                N_DBPS = N_DBPSOfRate(DataRate);
1398                Ceiling = (16 + 8*FrameLength + 6) / N_DBPS
1399                                + (((16 + 8*FrameLength + 6) % N_DBPS) ? 1 : 0);
1400                FrameTime = (u16)(16 + 4 + 4*Ceiling + 6);
1401        }
1402        return FrameTime;
1403}
1404
1405u16 N_DBPSOfRate(u16 DataRate)
1406{
1407         u16 N_DBPS = 24;
1408
1409        switch (DataRate) {
1410        case 60:
1411                N_DBPS = 24;
1412                break;
1413        case 90:
1414                N_DBPS = 36;
1415                break;
1416        case 120:
1417                N_DBPS = 48;
1418                break;
1419        case 180:
1420                N_DBPS = 72;
1421                break;
1422        case 240:
1423                N_DBPS = 96;
1424                break;
1425        case 360:
1426                N_DBPS = 144;
1427                break;
1428        case 480:
1429                N_DBPS = 192;
1430                break;
1431        case 540:
1432                N_DBPS = 216;
1433                break;
1434        default:
1435                break;
1436        }
1437
1438        return N_DBPS;
1439}
1440
1441//{by amy 080312
1442//
1443//      Description:
1444//      For Netgear case, they want good-looking singal strength.
1445//              2004.12.05, by rcnjko.
1446//
1447long NetgearSignalStrengthTranslate(long LastSS, long CurrSS)
1448{
1449        long RetSS;
1450
1451        // Step 1. Scale mapping.
1452        if (CurrSS >= 71 && CurrSS <= 100)
1453                RetSS = 90 + ((CurrSS - 70) / 3);
1454        else if (CurrSS >= 41 && CurrSS <= 70)
1455                RetSS = 78 + ((CurrSS - 40) / 3);
1456        else if (CurrSS >= 31 && CurrSS <= 40)
1457                RetSS = 66 + (CurrSS - 30);
1458        else if (CurrSS >= 21 && CurrSS <= 30)
1459                RetSS = 54 + (CurrSS - 20);
1460        else if (CurrSS >= 5 && CurrSS <= 20)
1461                RetSS = 42 + (((CurrSS - 5) * 2) / 3);
1462        else if (CurrSS == 4)
1463                RetSS = 36;
1464        else if (CurrSS == 3)
1465                RetSS = 27;
1466        else if (CurrSS == 2)
1467                RetSS = 18;
1468        else if (CurrSS == 1)
1469                RetSS = 9;
1470        else
1471                RetSS = CurrSS;
1472
1473        // Step 2. Smoothing.
1474        if(LastSS > 0)
1475                RetSS = ((LastSS * 5) + (RetSS)+ 5) / 6;
1476
1477        return RetSS;
1478}
1479
1480//
1481//      Description:
1482//              Translate 0-100 signal strength index into dBm.
1483//
1484long TranslateToDbm8185(u8 SignalStrengthIndex)
1485{
1486        long SignalPower;
1487
1488        // Translate to dBm (x=0.5y-95).
1489        SignalPower = (long)((SignalStrengthIndex + 1) >> 1);
1490        SignalPower -= 95;
1491
1492        return SignalPower;
1493}
1494
1495//
1496//      Description:
1497//              Perform signal smoothing for dynamic mechanism.
1498//              This is different with PerformSignalSmoothing8185 in smoothing fomula.
1499//              No dramatic adjustion is apply because dynamic mechanism need some degree
1500//              of correctness. Ported from 8187B.
1501//      2007-02-26, by Bruce.
1502//
1503void PerformUndecoratedSignalSmoothing8185(struct r8180_priv *priv,
1504                                           bool bCckRate)
1505{
1506        // Determin the current packet is CCK rate.
1507        priv->bCurCCKPkt = bCckRate;
1508
1509        if (priv->UndecoratedSmoothedSS >= 0)
1510                priv->UndecoratedSmoothedSS = ( (priv->UndecoratedSmoothedSS * 5) + (priv->SignalStrength * 10) ) / 6;
1511        else
1512                priv->UndecoratedSmoothedSS = priv->SignalStrength * 10;
1513
1514        priv->UndercorateSmoothedRxPower = ( (priv->UndercorateSmoothedRxPower * 50) + (priv->RxPower* 11)) / 60;
1515
1516        if (bCckRate)
1517                priv->CurCCKRSSI = priv->RSSI;
1518        else
1519                priv->CurCCKRSSI = 0;
1520}
1521
1522//by amy 080312}
1523
1524/* This is rough RX isr handling routine*/
1525void rtl8180_rx(struct net_device *dev)
1526{
1527        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1528        struct sk_buff *tmp_skb;
1529        short first,last;
1530        u32 len;
1531        int lastlen;
1532        unsigned char quality, signal;
1533        u8 rate;
1534        u32 *tmp,*tmp2;
1535        u8 rx_desc_size;
1536        u8 padding;
1537        char rxpower = 0;
1538        u32 RXAGC = 0;
1539        long RxAGC_dBm = 0;
1540        u8      LNA=0, BB=0;
1541        u8      LNA_gain[4]={02, 17, 29, 39};
1542        u8  Antenna = 0;
1543        struct ieee80211_hdr_4addr *hdr;
1544        u16 fc,type;
1545        u8 bHwError = 0,bCRC = 0,bICV = 0;
1546        bool    bCckRate = false;
1547        u8     RSSI = 0;
1548        long    SignalStrengthIndex = 0;
1549        struct ieee80211_rx_stats stats = {
1550                .signal = 0,
1551                .noise = -98,
1552                .rate = 0,
1553                .freq = IEEE80211_24GHZ_BAND,
1554        };
1555
1556        stats.nic_type = NIC_8185B;
1557        rx_desc_size = 8;
1558
1559        if ((*(priv->rxringtail)) & (1<<31)) {
1560                /* we have got an RX int, but the descriptor
1561                 * we are pointing is empty*/
1562
1563                priv->stats.rxnodata++;
1564                priv->ieee80211->stats.rx_errors++;
1565
1566                tmp2 = NULL;
1567                tmp = priv->rxringtail;
1568                do{
1569                        if(tmp == priv->rxring)
1570                                tmp  = priv->rxring + (priv->rxringcount - 1)*rx_desc_size;
1571                        else
1572                                tmp -= rx_desc_size;
1573
1574                        if(! (*tmp & (1<<31)))
1575                                tmp2 = tmp;
1576                }while(tmp != priv->rxring);
1577
1578                if(tmp2) priv->rxringtail = tmp2;
1579        }
1580
1581        /* while there are filled descriptors */
1582        while(!(*(priv->rxringtail) & (1<<31))){
1583                if(*(priv->rxringtail) & (1<<26))
1584                        DMESGW("RX buffer overflow");
1585                if(*(priv->rxringtail) & (1<<12))
1586                        priv->stats.rxicverr++;
1587
1588                if(*(priv->rxringtail) & (1<<27)){
1589                        priv->stats.rxdmafail++;
1590                        //DMESG("EE: RX DMA FAILED at buffer pointed by descriptor %x",(u32)priv->rxringtail);
1591                        goto drop;
1592                }
1593
1594                pci_dma_sync_single_for_cpu(priv->pdev,
1595                                    priv->rxbuffer->dma,
1596                                    priv->rxbuffersize * \
1597                                    sizeof(u8),
1598                                    PCI_DMA_FROMDEVICE);
1599
1600                first = *(priv->rxringtail) & (1<<29) ? 1:0;
1601                if(first) priv->rx_prevlen=0;
1602
1603                last = *(priv->rxringtail) & (1<<28) ? 1:0;
1604                if(last){
1605                        lastlen=((*priv->rxringtail) &0xfff);
1606
1607                        /* if the last descriptor (that should
1608                         * tell us the total packet len) tell
1609                         * us something less than the descriptors
1610                         * len we had until now, then there is some
1611                         * problem..
1612                         * workaround to prevent kernel panic
1613                         */
1614                        if(lastlen < priv->rx_prevlen)
1615                                len=0;
1616                        else
1617                                len=lastlen-priv->rx_prevlen;
1618
1619                        if(*(priv->rxringtail) & (1<<13)) {
1620                                if ((*(priv->rxringtail) & 0xfff) <500)
1621                                        priv->stats.rxcrcerrmin++;
1622                                else if ((*(priv->rxringtail) & 0x0fff) >1000)
1623                                        priv->stats.rxcrcerrmax++;
1624                                else
1625                                        priv->stats.rxcrcerrmid++;
1626
1627                        }
1628
1629                }else{
1630                        len = priv->rxbuffersize;
1631                }
1632
1633                if(first && last) {
1634                        padding = ((*(priv->rxringtail+3))&(0x04000000))>>26;
1635                }else if(first) {
1636                        padding = ((*(priv->rxringtail+3))&(0x04000000))>>26;
1637                        if(padding) {
1638                                len -= 2;
1639                        }
1640                }else {
1641                        padding = 0;
1642                }
1643               padding = 0;
1644                priv->rx_prevlen+=len;
1645
1646                if(priv->rx_prevlen > MAX_FRAG_THRESHOLD + 100){
1647                        /* HW is probably passing several buggy frames
1648                        * without FD or LD flag set.
1649                        * Throw this garbage away to prevent skb
1650                        * memory exausting
1651                        */
1652                        if(!priv->rx_skb_complete)
1653                                dev_kfree_skb_any(priv->rx_skb);
1654                        priv->rx_skb_complete = 1;
1655                }
1656
1657                signal=(unsigned char)(((*(priv->rxringtail+3))& (0x00ff0000))>>16);
1658                signal=(signal&0xfe)>>1;        // Modify by hikaru 6.6
1659
1660                quality=(unsigned char)((*(priv->rxringtail+3)) & (0xff));
1661
1662                stats.mac_time[0] = *(priv->rxringtail+1);
1663                stats.mac_time[1] = *(priv->rxringtail+2);
1664                rxpower =((char)(((*(priv->rxringtail+4))& (0x00ff0000))>>16))/2 - 42;
1665                RSSI = ((u8)(((*(priv->rxringtail+3)) & (0x0000ff00))>> 8)) & (0x7f);
1666
1667                rate=((*(priv->rxringtail)) &
1668                        ((1<<23)|(1<<22)|(1<<21)|(1<<20)))>>20;
1669
1670                stats.rate = rtl8180_rate2rate(rate);
1671                Antenna = (((*(priv->rxringtail +3))& (0x00008000)) == 0 )? 0:1 ;
1672//by amy for antenna
1673                if(!rtl8180_IsWirelessBMode(stats.rate))
1674                { // OFDM rate.
1675
1676                        RxAGC_dBm = rxpower+1;  //bias
1677                }
1678                else
1679                { // CCK rate.
1680                        RxAGC_dBm = signal;//bit 0 discard
1681
1682                        LNA = (u8) (RxAGC_dBm & 0x60 ) >> 5 ; //bit 6~ bit 5
1683                        BB  = (u8) (RxAGC_dBm & 0x1F);  // bit 4 ~ bit 0
1684
1685                        RxAGC_dBm = -( LNA_gain[LNA] + (BB *2) ); //Pin_11b=-(LNA_gain+BB_gain) (dBm)
1686
1687                        RxAGC_dBm +=4; //bias
1688                }
1689
1690                if(RxAGC_dBm & 0x80) //absolute value
1691                        RXAGC= ~(RxAGC_dBm)+1;
1692                bCckRate = rtl8180_IsWirelessBMode(stats.rate);
1693                // Translate RXAGC into 1-100.
1694                if(!rtl8180_IsWirelessBMode(stats.rate))
1695                { // OFDM rate.
1696                        if(RXAGC>90)
1697                                RXAGC=90;
1698                        else if(RXAGC<25)
1699                                RXAGC=25;
1700                        RXAGC=(90-RXAGC)*100/65;
1701                }
1702                else
1703                { // CCK rate.
1704                        if(RXAGC>95)
1705                                RXAGC=95;
1706                        else if(RXAGC<30)
1707                                RXAGC=30;
1708                        RXAGC=(95-RXAGC)*100/65;
1709                }
1710                priv->SignalStrength = (u8)RXAGC;
1711                priv->RecvSignalPower = RxAGC_dBm ;  // It can use directly by SD3 CMLin
1712                priv->RxPower = rxpower;
1713                priv->RSSI = RSSI;
1714//{by amy 080312
1715                // SQ translation formular is provided by SD3 DZ. 2006.06.27, by rcnjko.
1716                if(quality >= 127)
1717                        quality = 1;//0; //0 will cause epc to show signal zero , walk aroud now;
1718                else if(quality < 27)
1719                        quality = 100;
1720                else
1721                        quality = 127 - quality;
1722                priv->SignalQuality = quality;
1723                if(!priv->card_8185)
1724                        printk("check your card type\n");
1725
1726                stats.signal = (u8)quality;//priv->wstats.qual.level = priv->SignalStrength;
1727                stats.signalstrength = RXAGC;
1728                if(stats.signalstrength > 100)
1729                        stats.signalstrength = 100;
1730                stats.signalstrength = (stats.signalstrength * 70)/100 + 30;
1731        //      printk("==========================>rx : RXAGC is %d,signalstrength is %d\n",RXAGC,stats.signalstrength);
1732                stats.rssi = priv->wstats.qual.qual = priv->SignalQuality;
1733                stats.noise = priv->wstats.qual.noise = 100 - priv ->wstats.qual.qual;
1734//by amy 080312}
1735                bHwError = (((*(priv->rxringtail))& (0x00000fff)) == 4080)| (((*(priv->rxringtail))& (0x04000000)) != 0 )
1736                        | (((*(priv->rxringtail))& (0x08000000)) != 0 )| (((~(*(priv->rxringtail)))& (0x10000000)) != 0 )| (((~(*(priv->rxringtail)))& (0x20000000)) != 0 );
1737                bCRC = ((*(priv->rxringtail)) & (0x00002000)) >> 13;
1738                bICV = ((*(priv->rxringtail)) & (0x00001000)) >> 12;
1739                hdr = (struct ieee80211_hdr_4addr *)priv->rxbuffer->buf;
1740                    fc = le16_to_cpu(hdr->frame_ctl);
1741                type = WLAN_FC_GET_TYPE(fc);
1742
1743                        if((IEEE80211_FTYPE_CTL != type) &&
1744                                (eqMacAddr(priv->ieee80211->current_network.bssid, (fc & IEEE80211_FCTL_TODS)? hdr->addr1 : (fc & IEEE80211_FCTL_FROMDS )? hdr->addr2 : hdr->addr3))
1745                                 && (!bHwError) && (!bCRC)&& (!bICV))
1746                        {
1747//by amy 080312
1748                                // Perform signal smoothing for dynamic mechanism on demand.
1749                                // This is different with PerformSignalSmoothing8185 in smoothing fomula.
1750                                // No dramatic adjustion is apply because dynamic mechanism need some degree
1751                                // of correctness. 2007.01.23, by shien chang.
1752                                PerformUndecoratedSignalSmoothing8185(priv,bCckRate);
1753                                //
1754                                // For good-looking singal strength.
1755                                //
1756                                SignalStrengthIndex = NetgearSignalStrengthTranslate(
1757                                                                priv->LastSignalStrengthInPercent,
1758                                                                priv->SignalStrength);
1759
1760                                priv->LastSignalStrengthInPercent = SignalStrengthIndex;
1761                                priv->Stats_SignalStrength = TranslateToDbm8185((u8)SignalStrengthIndex);
1762                //
1763                // We need more correct power of received packets and the  "SignalStrength" of RxStats is beautified,
1764                // so we record the correct power here.
1765                //
1766                                priv->Stats_SignalQuality =(long) (priv->Stats_SignalQuality * 5 + (long)priv->SignalQuality + 5) / 6;
1767                                priv->Stats_RecvSignalPower = (long)(priv->Stats_RecvSignalPower * 5 + priv->RecvSignalPower -1) / 6;
1768
1769                // Figure out which antenna that received the lasted packet.
1770                                priv->LastRxPktAntenna = Antenna ? 1 : 0; // 0: aux, 1: main.
1771//by amy 080312
1772                            SwAntennaDiversityRxOk8185(dev, priv->SignalStrength);
1773                        }
1774
1775//by amy for antenna
1776#ifndef DUMMY_RX
1777                if(first){
1778                        if(!priv->rx_skb_complete){
1779                                /* seems that HW sometimes fails to reiceve and
1780                                   doesn't provide the last descriptor */
1781                                dev_kfree_skb_any(priv->rx_skb);
1782                                priv->stats.rxnolast++;
1783                        }
1784                        /* support for prism header has been originally added by Christian */
1785                        if(priv->prism_hdr && priv->ieee80211->iw_mode == IW_MODE_MONITOR){
1786
1787                        }else{
1788                                priv->rx_skb = dev_alloc_skb(len+2);
1789                                if( !priv->rx_skb) goto drop;
1790                        }
1791
1792                        priv->rx_skb_complete=0;
1793                        priv->rx_skb->dev=dev;
1794                }else{
1795                        /* if we are here we should  have already RXed
1796                        * the first frame.
1797                        * If we get here and the skb is not allocated then
1798                        * we have just throw out garbage (skb not allocated)
1799                        * and we are still rxing garbage....
1800                        */
1801                        if(!priv->rx_skb_complete){
1802
1803                                tmp_skb= dev_alloc_skb(priv->rx_skb->len +len+2);
1804
1805                                if(!tmp_skb) goto drop;
1806
1807                                tmp_skb->dev=dev;
1808
1809                                memcpy(skb_put(tmp_skb,priv->rx_skb->len),
1810                                        priv->rx_skb->data,
1811                                        priv->rx_skb->len);
1812
1813                                dev_kfree_skb_any(priv->rx_skb);
1814
1815                                priv->rx_skb=tmp_skb;
1816                        }
1817                }
1818
1819                if(!priv->rx_skb_complete) {
1820                        if(padding) {
1821                                memcpy(skb_put(priv->rx_skb,len),
1822                                        (((unsigned char *)priv->rxbuffer->buf) + 2),len);
1823                        } else {
1824                                memcpy(skb_put(priv->rx_skb,len),
1825                                        priv->rxbuffer->buf,len);
1826                        }
1827                }
1828
1829                if(last && !priv->rx_skb_complete){
1830                        if(priv->rx_skb->len > 4)
1831                                skb_trim(priv->rx_skb,priv->rx_skb->len-4);
1832#ifndef RX_DONT_PASS_UL
1833                        if(!ieee80211_rx(priv->ieee80211,
1834                                         priv->rx_skb, &stats)){
1835#endif // RX_DONT_PASS_UL
1836
1837                                dev_kfree_skb_any(priv->rx_skb);
1838#ifndef RX_DONT_PASS_UL
1839                        }
1840#endif
1841                        priv->rx_skb_complete=1;
1842                }
1843
1844#endif //DUMMY_RX
1845                pci_dma_sync_single_for_device(priv->pdev,
1846                                    priv->rxbuffer->dma,
1847                                    priv->rxbuffersize * \
1848                                    sizeof(u8),
1849                                    PCI_DMA_FROMDEVICE);
1850
1851drop: // this is used when we have not enought mem
1852                /* restore the descriptor */
1853                *(priv->rxringtail+2)=priv->rxbuffer->dma;
1854                *(priv->rxringtail)=*(priv->rxringtail) &~ 0xfff;
1855                *(priv->rxringtail)=
1856                        *(priv->rxringtail) | priv->rxbuffersize;
1857
1858                *(priv->rxringtail)=
1859                        *(priv->rxringtail) | (1<<31);
1860
1861                priv->rxringtail+=rx_desc_size;
1862                if(priv->rxringtail >=
1863                   (priv->rxring)+(priv->rxringcount )*rx_desc_size)
1864                        priv->rxringtail=priv->rxring;
1865
1866                priv->rxbuffer=(priv->rxbuffer->next);
1867        }
1868}
1869
1870
1871void rtl8180_dma_kick(struct net_device *dev, int priority)
1872{
1873        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1874
1875        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
1876        write_nic_byte(dev, TX_DMA_POLLING,
1877                        (1 << (priority + 1)) | priv->dma_poll_mask);
1878        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
1879
1880        force_pci_posting(dev);
1881}
1882
1883void rtl8180_data_hard_stop(struct net_device *dev)
1884{
1885        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1886
1887        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
1888        priv->dma_poll_stop_mask |= TPPOLLSTOP_AC_VIQ;
1889        write_nic_byte(dev,TPPollStop, priv->dma_poll_stop_mask);
1890        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
1891}
1892
1893void rtl8180_data_hard_resume(struct net_device *dev)
1894{
1895        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1896
1897        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
1898        priv->dma_poll_stop_mask &= ~(TPPOLLSTOP_AC_VIQ);
1899        write_nic_byte(dev,TPPollStop, priv->dma_poll_stop_mask);
1900        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
1901}
1902
1903/* this function TX data frames when the ieee80211 stack requires this.
1904 * It checks also if we need to stop the ieee tx queue, eventually do it
1905 */
1906void rtl8180_hard_data_xmit(struct sk_buff *skb,struct net_device *dev, int
1907rate)
1908{
1909        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1910        int mode;
1911        struct ieee80211_hdr_3addr  *h = (struct ieee80211_hdr_3addr  *) skb->data;
1912        short morefrag = (h->frame_ctl) & IEEE80211_FCTL_MOREFRAGS;
1913        unsigned long flags;
1914        int priority;
1915
1916        mode = priv->ieee80211->iw_mode;
1917
1918        rate = ieeerate2rtlrate(rate);
1919        /*
1920        * This function doesn't require lock because we make
1921        * sure it's called with the tx_lock already acquired.
1922        * this come from the kernel's hard_xmit callback (trought
1923        * the ieee stack, or from the try_wake_queue (again trought
1924        * the ieee stack.
1925        */
1926        priority = AC2Q(skb->priority);
1927        spin_lock_irqsave(&priv->tx_lock,flags);
1928
1929        if(priv->ieee80211->bHwRadioOff)
1930        {
1931                spin_unlock_irqrestore(&priv->tx_lock,flags);
1932
1933                return;
1934        }
1935
1936        if (!check_nic_enought_desc(dev, priority)){
1937                DMESGW("Error: no descriptor left by previous TX (avail %d) ",
1938                        get_curr_tx_free_desc(dev, priority));
1939                ieee80211_stop_queue(priv->ieee80211);
1940        }
1941        rtl8180_tx(dev, skb->data, skb->len, priority, morefrag,0,rate);
1942        if (!check_nic_enought_desc(dev, priority))
1943                ieee80211_stop_queue(priv->ieee80211);
1944
1945        spin_unlock_irqrestore(&priv->tx_lock,flags);
1946}
1947
1948/* This is a rough attempt to TX a frame
1949 * This is called by the ieee 80211 stack to TX management frames.
1950 * If the ring is full packet are dropped (for data frame the queue
1951 * is stopped before this can happen). For this reason it is better
1952 * if the descriptors are larger than the largest management frame
1953 * we intend to TX: i'm unsure what the HW does if it will not found
1954 * the last fragment of a frame because it has been dropped...
1955 * Since queues for Management and Data frames are different we
1956 * might use a different lock than tx_lock (for example mgmt_tx_lock)
1957 */
1958/* these function may loops if invoked with 0 descriptors or 0 len buffer*/
1959int rtl8180_hard_start_xmit(struct sk_buff *skb,struct net_device *dev)
1960{
1961        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
1962        unsigned long flags;
1963        int priority;
1964
1965        priority = MANAGE_PRIORITY;
1966
1967        spin_lock_irqsave(&priv->tx_lock,flags);
1968
1969        if (priv->ieee80211->bHwRadioOff) {
1970                spin_unlock_irqrestore(&priv->tx_lock,flags);
1971                dev_kfree_skb_any(skb);
1972                return NETDEV_TX_OK;
1973        }
1974
1975        rtl8180_tx(dev, skb->data, skb->len, priority,
1976                0, 0,ieeerate2rtlrate(priv->ieee80211->basic_rate));
1977
1978        priv->ieee80211->stats.tx_bytes+=skb->len;
1979        priv->ieee80211->stats.tx_packets++;
1980        spin_unlock_irqrestore(&priv->tx_lock,flags);
1981
1982        dev_kfree_skb_any(skb);
1983        return NETDEV_TX_OK;
1984}
1985
1986// longpre 144+48 shortpre 72+24
1987u16 rtl8180_len2duration(u32 len, short rate,short* ext)
1988{
1989        u16 duration;
1990        u16 drift;
1991        *ext=0;
1992
1993        switch(rate){
1994        case 0://1mbps
1995                *ext=0;
1996                duration = ((len+4)<<4) /0x2;
1997                drift = ((len+4)<<4) % 0x2;
1998                if(drift ==0 ) break;
1999                duration++;
2000                break;
2001        case 1://2mbps
2002                *ext=0;
2003                duration = ((len+4)<<4) /0x4;
2004                drift = ((len+4)<<4) % 0x4;
2005                if(drift ==0 ) break;
2006                duration++;
2007                break;
2008        case 2: //5.5mbps
2009                *ext=0;
2010                duration = ((len+4)<<4) /0xb;
2011                drift = ((len+4)<<4) % 0xb;
2012                if(drift ==0 )
2013                        break;
2014                duration++;
2015                break;
2016        default:
2017        case 3://11mbps
2018                *ext=0;
2019                duration = ((len+4)<<4) /0x16;
2020                drift = ((len+4)<<4) % 0x16;
2021                if(drift ==0 )
2022                        break;
2023                duration++;
2024                if(drift > 6)
2025                        break;
2026                *ext=1;
2027                break;
2028        }
2029
2030        return duration;
2031}
2032
2033void rtl8180_prepare_beacon(struct net_device *dev)
2034{
2035        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
2036        struct sk_buff *skb;
2037
2038        u16 word  = read_nic_word(dev, BcnItv);
2039        word &= ~BcnItv_BcnItv; // clear Bcn_Itv
2040        word |= cpu_to_le16(priv->ieee80211->current_network.beacon_interval);//0x64;
2041        write_nic_word(dev, BcnItv, word);
2042
2043        skb = ieee80211_get_beacon(priv->ieee80211);
2044        if(skb){
2045                rtl8180_tx(dev,skb->data,skb->len,BEACON_PRIORITY,
2046                        0,0,ieeerate2rtlrate(priv->ieee80211->basic_rate));
2047                dev_kfree_skb_any(skb);
2048        }
2049}
2050
2051/* This function do the real dirty work: it enqueues a TX command
2052 * descriptor in the ring buffer, copyes the frame in a TX buffer
2053 * and kicks the NIC to ensure it does the DMA transfer.
2054 */
2055short rtl8180_tx(struct net_device *dev, u8* txbuf, int len, int priority,
2056                 short morefrag, short descfrag, int rate)
2057{
2058        struct r8180_priv *priv = ieee80211_priv(dev);
2059        u32 *tail,*temp_tail;
2060        u32 *begin;
2061        u32 *buf;
2062        int i;
2063        int remain;
2064        int buflen;
2065        int count;
2066        u16 duration;
2067        short ext;
2068        struct buffer* buflist;
2069        struct ieee80211_hdr_3addr *frag_hdr = (struct ieee80211_hdr_3addr *)txbuf;
2070        u8 dest[ETH_ALEN];
2071        u8                      bUseShortPreamble = 0;
2072        u8                      bCTSEnable = 0;
2073        u8                      bRTSEnable = 0;
2074        u16                     Duration = 0;
2075        u16                     RtsDur = 0;
2076        u16                     ThisFrameTime = 0;
2077        u16                     TxDescDuration = 0;
2078        u8                      ownbit_flag = false; //added by david woo for sync Tx, 2007.12.14
2079
2080        switch(priority) {
2081        case MANAGE_PRIORITY:
2082                tail=priv->txmapringtail;
2083                begin=priv->txmapring;
2084                buflist = priv->txmapbufstail;
2085                count = priv->txringcount;
2086                break;
2087        case BK_PRIORITY:
2088                tail=priv->txbkpringtail;
2089                begin=priv->txbkpring;
2090                buflist = priv->txbkpbufstail;
2091                count = priv->txringcount;
2092                break;
2093        case BE_PRIORITY:
2094                tail=priv->txbepringtail;
2095                begin=priv->txbepring;
2096                buflist = priv->txbepbufstail;
2097                count = priv->txringcount;
2098                break;
2099        case VI_PRIORITY:
2100                tail=priv->txvipringtail;
2101                begin=priv->txvipring;
2102                buflist = priv->txvipbufstail;
2103                count = priv->txringcount;
2104                break;
2105        case VO_PRIORITY:
2106                tail=priv->txvopringtail;
2107                begin=priv->txvopring;
2108                buflist = priv->txvopbufstail;
2109                count = priv->txringcount;
2110                break;
2111        case HI_PRIORITY:
2112                tail=priv->txhpringtail;
2113                begin=priv->txhpring;
2114                buflist = priv->txhpbufstail;
2115                count = priv->txringcount;
2116                break;
2117        case BEACON_PRIORITY:
2118                tail=priv->txbeaconringtail;
2119                begin=priv->txbeaconring;
2120                buflist = priv->txbeaconbufstail;
2121                count = priv->txbeaconcount;
2122                break;
2123        default:
2124                return -1;
2125                break;
2126        }
2127
2128                memcpy(&dest, frag_hdr->addr1, ETH_ALEN);
2129                if (is_multicast_ether_addr(dest) ||
2130                                is_broadcast_ether_addr(dest))
2131                {
2132                        Duration = 0;
2133                        RtsDur = 0;
2134                        bRTSEnable = 0;
2135                        bCTSEnable = 0;
2136
2137                        ThisFrameTime = ComputeTxTime(len + sCrcLng, rtl8180_rate2rate(rate), 0, bUseShortPreamble);
2138                        TxDescDuration = ThisFrameTime;
2139                } else {// Unicast packet
2140                        u16 AckTime;
2141
2142                        //YJ,add,080828,for Keep alive
2143                        priv->NumTxUnicast++;
2144
2145                        // Figure out ACK rate according to BSS basic rate and Tx rate, 2006.03.08 by rcnjko.
2146                        AckTime = ComputeTxTime(14, 10,0, 0);   // AckCTSLng = 14 use 1M bps send
2147
2148                        if ( ((len + sCrcLng) > priv->rts) && priv->rts )
2149                        { // RTS/CTS.
2150                                u16 RtsTime, CtsTime;
2151                                //u16 CtsRate;
2152                                bRTSEnable = 1;
2153                                bCTSEnable = 0;
2154
2155                                // Rate and time required for RTS.
2156                                RtsTime = ComputeTxTime( sAckCtsLng/8,priv->ieee80211->basic_rate, 0, 0);
2157                                // Rate and time required for CTS.
2158                                CtsTime = ComputeTxTime(14, 10,0, 0);   // AckCTSLng = 14 use 1M bps send
2159
2160                                // Figure out time required to transmit this frame.
2161                                ThisFrameTime = ComputeTxTime(len + sCrcLng,
2162                                                rtl8180_rate2rate(rate),
2163                                                0,
2164                                                bUseShortPreamble);
2165
2166                                // RTS-CTS-ThisFrame-ACK.
2167                                RtsDur = CtsTime + ThisFrameTime + AckTime + 3*aSifsTime;
2168
2169                                TxDescDuration = RtsTime + RtsDur;
2170                        }
2171                        else {// Normal case.
2172                                bCTSEnable = 0;
2173                                bRTSEnable = 0;
2174                                RtsDur = 0;
2175
2176                                ThisFrameTime = ComputeTxTime(len + sCrcLng, rtl8180_rate2rate(rate), 0, bUseShortPreamble);
2177                                TxDescDuration = ThisFrameTime + aSifsTime + AckTime;
2178                        }
2179
2180                        if(!(frag_hdr->frame_ctl & IEEE80211_FCTL_MOREFRAGS)) { //no more fragment
2181                                // ThisFrame-ACK.
2182                                Duration = aSifsTime + AckTime;
2183                        } else { // One or more fragments remained.
2184                                u16 NextFragTime;
2185                                NextFragTime = ComputeTxTime( len + sCrcLng, //pretend following packet length equal current packet
2186                                                rtl8180_rate2rate(rate),
2187                                                0,
2188                                                bUseShortPreamble );
2189
2190                                //ThisFrag-ACk-NextFrag-ACK.
2191                                Duration = NextFragTime + 3*aSifsTime + 2*AckTime;
2192                        }
2193
2194                } // End of Unicast packet
2195
2196                frag_hdr->duration_id = Duration;
2197
2198        buflen=priv->txbuffsize;
2199        remain=len;
2200        temp_tail = tail;
2201
2202        while(remain!=0){
2203                mb();
2204                if(!buflist){
2205                        DMESGE("TX buffer error, cannot TX frames. pri %d.", priority);
2206                        return -1;
2207                }
2208                buf=buflist->buf;
2209
2210                if ((*tail & (1 << 31)) && (priority != BEACON_PRIORITY)) {
2211                        DMESGW("No more TX desc, returning %x of %x",
2212                               remain, len);
2213                        priv->stats.txrdu++;
2214                        return remain;
2215                }
2216
2217                *tail= 0; // zeroes header
2218                *(tail+1) = 0;
2219                *(tail+3) = 0;
2220                *(tail+5) = 0;
2221                *(tail+6) = 0;
2222                *(tail+7) = 0;
2223
2224                if(priv->card_8185){
2225                        //FIXME: this should be triggered by HW encryption parameters.
2226                        *tail |= (1<<15); //no encrypt
2227                }
2228
2229                if(remain==len && !descfrag) {
2230                        ownbit_flag = false;    //added by david woo,2007.12.14
2231                        *tail = *tail| (1<<29) ; //fist segment of the packet
2232                        *tail = *tail |(len);
2233                } else {
2234                        ownbit_flag = true;
2235                }
2236
2237                for(i=0;i<buflen&& remain >0;i++,remain--){
2238                        ((u8*)buf)[i]=txbuf[i]; //copy data into descriptor pointed DMAble buffer
2239                        if(remain == 4 && i+4 >= buflen) break;
2240                        /* ensure the last desc has at least 4 bytes payload */
2241
2242                }
2243                txbuf = txbuf + i;
2244                *(tail+3)=*(tail+3) &~ 0xfff;
2245                *(tail+3)=*(tail+3) | i; // buffer lenght
2246                // Use short preamble or not
2247                if (priv->ieee80211->current_network.capability&WLAN_CAPABILITY_SHORT_PREAMBLE)
2248                        if (priv->plcp_preamble_mode==1 && rate!=0)     //  short mode now, not long!
2249                        ;//     *tail |= (1<<16);                               // enable short preamble mode.
2250
2251                if(bCTSEnable) {
2252                        *tail |= (1<<18);
2253                }
2254
2255                if(bRTSEnable) //rts enable
2256                {
2257                        *tail |= ((ieeerate2rtlrate(priv->ieee80211->basic_rate))<<19);//RTS RATE
2258                        *tail |= (1<<23);//rts enable
2259                        *(tail+1) |=(RtsDur&0xffff);//RTS Duration
2260                }
2261                *(tail+3) |= ((TxDescDuration&0xffff)<<16); //DURATION
2262//              *(tail+3) |= (0xe6<<16);
2263                *(tail+5) |= (11<<8);//(priv->retry_data<<8); //retry lim ;
2264
2265                *tail = *tail | ((rate&0xf) << 24);
2266
2267                /* hw_plcp_len is not used for rtl8180 chip */
2268                /* FIXME */
2269                if(priv->card_8185 == 0 || !priv->hw_plcp_len){
2270                        duration = rtl8180_len2duration(len, rate, &ext);
2271                        *(tail+1) = *(tail+1) | ((duration & 0x7fff)<<16);
2272                        if(ext) *(tail+1) = *(tail+1) |(1<<31); //plcp length extension
2273                }
2274
2275                if(morefrag) *tail = (*tail) | (1<<17); // more fragment
2276                if(!remain) *tail = (*tail) | (1<<28); // last segment of frame
2277
2278               *(tail+5) = *(tail+5)|(2<<27);
2279                *(tail+7) = *(tail+7)|(1<<4);
2280
2281                wmb();
2282                if(ownbit_flag)
2283                {
2284                        *tail = *tail | (1<<31); // descriptor ready to be txed
2285                }
2286
2287                if((tail - begin)/8 == count-1)
2288                        tail=begin;
2289                else
2290                        tail=tail+8;
2291
2292                buflist=buflist->next;
2293
2294                mb();
2295
2296                switch(priority) {
2297                        case MANAGE_PRIORITY:
2298                                priv->txmapringtail=tail;
2299                                priv->txmapbufstail=buflist;
2300                                break;
2301                        case BK_PRIORITY:
2302                                priv->txbkpringtail=tail;
2303                                priv->txbkpbufstail=buflist;
2304                                break;
2305                        case BE_PRIORITY:
2306                                priv->txbepringtail=tail;
2307                                priv->txbepbufstail=buflist;
2308                                break;
2309                        case VI_PRIORITY:
2310                                priv->txvipringtail=tail;
2311                                priv->txvipbufstail=buflist;
2312                                break;
2313                        case VO_PRIORITY:
2314                                priv->txvopringtail=tail;
2315                                priv->txvopbufstail=buflist;
2316                                break;
2317                        case HI_PRIORITY:
2318                                priv->txhpringtail=tail;
2319                                priv->txhpbufstail = buflist;
2320                                break;
2321                        case BEACON_PRIORITY:
2322                                /* the HW seems to be happy with the 1st
2323                                 * descriptor filled and the 2nd empty...
2324                                 * So always update descriptor 1 and never
2325                                 * touch 2nd
2326                                 */
2327                                break;
2328                }
2329        }
2330        *temp_tail = *temp_tail | (1<<31); // descriptor ready to be txed
2331        rtl8180_dma_kick(dev,priority);
2332
2333        return 0;
2334}
2335
2336void rtl8180_irq_rx_tasklet(struct r8180_priv * priv);
2337
2338void rtl8180_link_change(struct net_device *dev)
2339{
2340        struct r8180_priv *priv = ieee80211_priv(dev);
2341        u16 beacon_interval;
2342        struct ieee80211_network *net = &priv->ieee80211->current_network;
2343
2344        rtl8180_update_msr(dev);
2345
2346        rtl8180_set_mode(dev,EPROM_CMD_CONFIG);
2347
2348        write_nic_dword(dev,BSSID,((u32*)net->bssid)[0]);
2349        write_nic_word(dev,BSSID+4,((u16*)net->bssid)[2]);
2350
2351        beacon_interval  = read_nic_dword(dev,BEACON_INTERVAL);
2352        beacon_interval &= ~ BEACON_INTERVAL_MASK;
2353        beacon_interval |= net->beacon_interval;
2354        write_nic_dword(dev, BEACON_INTERVAL, beacon_interval);
2355
2356        rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
2357
2358        if(priv->card_8185)
2359                rtl8180_set_chan(dev, priv->chan);
2360}
2361
2362void rtl8180_rq_tx_ack(struct net_device *dev){
2363
2364        struct r8180_priv *priv = ieee80211_priv(dev);
2365
2366        write_nic_byte(dev,CONFIG4,read_nic_byte(dev,CONFIG4)|CONFIG4_PWRMGT);
2367        priv->ack_tx_to_ieee = 1;
2368}
2369
2370short rtl8180_is_tx_queue_empty(struct net_device *dev){
2371
2372        struct r8180_priv *priv = ieee80211_priv(dev);
2373        u32* d;
2374
2375        for (d = priv->txmapring;
2376                d < priv->txmapring + priv->txringcount;d+=8)
2377                        if(*d & (1<<31)) return 0;
2378
2379        for (d = priv->txbkpring;
2380                d < priv->txbkpring + priv->txringcount;d+=8)
2381                        if(*d & (1<<31)) return 0;
2382
2383        for (d = priv->txbepring;
2384                d < priv->txbepring + priv->txringcount;d+=8)
2385                        if(*d & (1<<31)) return 0;
2386
2387        for (d = priv->txvipring;
2388                d < priv->txvipring + priv->txringcount;d+=8)
2389                        if(*d & (1<<31)) return 0;
2390
2391        for (d = priv->txvopring;
2392                d < priv->txvopring + priv->txringcount;d+=8)
2393                        if(*d & (1<<31)) return 0;
2394
2395        for (d = priv->txhpring;
2396                d < priv->txhpring + priv->txringcount;d+=8)
2397                        if(*d & (1<<31)) return 0;
2398        return 1;
2399}
2400/* FIXME FIXME 5msecs is random */
2401#define HW_WAKE_DELAY 5
2402
2403void rtl8180_hw_wakeup(struct net_device *dev)
2404{
2405        unsigned long flags;
2406        struct r8180_priv *priv = ieee80211_priv(dev);
2407
2408        spin_lock_irqsave(&priv->ps_lock,flags);
2409        write_nic_byte(dev,CONFIG4,read_nic_byte(dev,CONFIG4)&~CONFIG4_PWRMGT);
2410        if (priv->rf_wakeup)
2411                priv->rf_wakeup(dev);
2412        spin_unlock_irqrestore(&priv->ps_lock,flags);
2413}
2414
2415void rtl8180_hw_sleep_down(struct net_device *dev)
2416{
2417        unsigned long flags;
2418        struct r8180_priv *priv = ieee80211_priv(dev);
2419
2420        spin_lock_irqsave(&priv->ps_lock,flags);
2421        if(priv->rf_sleep)
2422                priv->rf_sleep(dev);
2423        spin_unlock_irqrestore(&priv->ps_lock,flags);
2424}
2425
2426void rtl8180_hw_sleep(struct net_device *dev, u32 th, u32 tl)
2427{
2428        struct r8180_priv *priv = ieee80211_priv(dev);
2429        u32 rb = jiffies;
2430        unsigned long flags;
2431
2432        spin_lock_irqsave(&priv->ps_lock,flags);
2433
2434        /* Writing HW register with 0 equals to disable
2435         * the timer, that is not really what we want
2436         */
2437        tl -= MSECS(4+16+7);
2438
2439        /* If the interval in witch we are requested to sleep is too
2440         * short then give up and remain awake
2441         */
2442        if(((tl>=rb)&& (tl-rb) <= MSECS(MIN_SLEEP_TIME))
2443                ||((rb>tl)&& (rb-tl) < MSECS(MIN_SLEEP_TIME))) {
2444                spin_unlock_irqrestore(&priv->ps_lock,flags);
2445                printk("too short to sleep\n");
2446                return;
2447        }
2448
2449        {
2450                u32 tmp = (tl>rb)?(tl-rb):(rb-tl);
2451
2452                priv->DozePeriodInPast2Sec += jiffies_to_msecs(tmp);
2453
2454                queue_delayed_work(priv->ieee80211->wq, &priv->ieee80211->hw_wakeup_wq, tmp); //as tl may be less than rb
2455        }
2456        /* if we suspect the TimerInt is gone beyond tl
2457         * while setting it, then give up
2458         */
2459
2460        if(((tl > rb) && ((tl-rb) > MSECS(MAX_SLEEP_TIME)))||
2461                ((tl < rb) && ((rb-tl) > MSECS(MAX_SLEEP_TIME)))) {
2462                spin_unlock_irqrestore(&priv->ps_lock,flags);
2463                return;
2464        }
2465
2466        queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_sleep_wq);
2467        spin_unlock_irqrestore(&priv->ps_lock,flags);
2468}
2469
2470void rtl8180_wmm_param_update(struct work_struct * work)
2471{
2472        struct ieee80211_device * ieee = container_of(work, struct ieee80211_device,wmm_param_update_wq);
2473        struct net_device *dev = ieee->dev;
2474        u8 *ac_param = (u8 *)(ieee->current_network.wmm_param);
2475        u8 mode = ieee->current_network.mode;
2476        AC_CODING       eACI;
2477        AC_PARAM        AcParam;
2478        PAC_PARAM       pAcParam;
2479        u8 i;
2480
2481        if(!ieee->current_network.QoS_Enable){
2482                //legacy ac_xx_param update
2483                AcParam.longData = 0;
2484                AcParam.f.AciAifsn.f.AIFSN = 2; // Follow 802.11 DIFS.
2485                AcParam.f.AciAifsn.f.ACM = 0;
2486                AcParam.f.Ecw.f.ECWmin = 3; // Follow 802.11 CWmin.
2487                AcParam.f.Ecw.f.ECWmax = 7; // Follow 802.11 CWmax.
2488                AcParam.f.TXOPLimit = 0;
2489                for(eACI = 0; eACI < AC_MAX; eACI++){
2490                        AcParam.f.AciAifsn.f.ACI = (u8)eACI;
2491                        {
2492                                u8              u1bAIFS;
2493                                u32             u4bAcParam;
2494                                pAcParam = (PAC_PARAM)(&AcParam);
2495                                // Retrive paramters to udpate.
2496                                u1bAIFS = pAcParam->f.AciAifsn.f.AIFSN *(((mode&IEEE_G) == IEEE_G)?9:20) + aSifsTime;
2497                                u4bAcParam = ((((u32)(pAcParam->f.TXOPLimit))<<AC_PARAM_TXOP_LIMIT_OFFSET)|
2498                                              (((u32)(pAcParam->f.Ecw.f.ECWmax))<<AC_PARAM_ECW_MAX_OFFSET)|
2499                                              (((u32)(pAcParam->f.Ecw.f.ECWmin))<<AC_PARAM_ECW_MIN_OFFSET)|
2500                                               (((u32)u1bAIFS) << AC_PARAM_AIFS_OFFSET));
2501                                switch(eACI){
2502                                        case AC1_BK:
2503                                                write_nic_dword(dev, AC_BK_PARAM, u4bAcParam);
2504                                                break;
2505                                        case AC0_BE:
2506                                                write_nic_dword(dev, AC_BE_PARAM, u4bAcParam);
2507                                                break;
2508                                        case AC2_VI:
2509                                                write_nic_dword(dev, AC_VI_PARAM, u4bAcParam);
2510                                                break;
2511                                        case AC3_VO:
2512                                                write_nic_dword(dev, AC_VO_PARAM, u4bAcParam);
2513                                                break;
2514                                        default:
2515                                                printk(KERN_WARNING "SetHwReg8185():invalid ACI: %d!\n", eACI);
2516                                                break;
2517                                }
2518                        }
2519                }
2520                return;
2521        }
2522
2523        for(i = 0; i < AC_MAX; i++){
2524                //AcParam.longData = 0;
2525                pAcParam = (AC_PARAM * )ac_param;
2526                {
2527                        AC_CODING       eACI;
2528                        u8              u1bAIFS;
2529                        u32             u4bAcParam;
2530
2531                        // Retrive paramters to udpate.
2532                        eACI = pAcParam->f.AciAifsn.f.ACI;
2533                        //Mode G/A: slotTimeTimer = 9; Mode B: 20
2534                        u1bAIFS = pAcParam->f.AciAifsn.f.AIFSN * (((mode&IEEE_G) == IEEE_G)?9:20) + aSifsTime;
2535                        u4bAcParam = (  (((u32)(pAcParam->f.TXOPLimit)) << AC_PARAM_TXOP_LIMIT_OFFSET)  |
2536                                        (((u32)(pAcParam->f.Ecw.f.ECWmax)) << AC_PARAM_ECW_MAX_OFFSET)  |
2537                                        (((u32)(pAcParam->f.Ecw.f.ECWmin)) << AC_PARAM_ECW_MIN_OFFSET)  |
2538                                        (((u32)u1bAIFS) << AC_PARAM_AIFS_OFFSET));
2539
2540                        switch(eACI){
2541                                case AC1_BK:
2542                                        write_nic_dword(dev, AC_BK_PARAM, u4bAcParam);
2543                                        break;
2544                                case AC0_BE:
2545                                        write_nic_dword(dev, AC_BE_PARAM, u4bAcParam);
2546                                        break;
2547                                case AC2_VI:
2548                                        write_nic_dword(dev, AC_VI_PARAM, u4bAcParam);
2549                                        break;
2550                                case AC3_VO:
2551                                        write_nic_dword(dev, AC_VO_PARAM, u4bAcParam);
2552                                        break;
2553                                default:
2554                                        printk(KERN_WARNING "SetHwReg8185(): invalid ACI: %d !\n", eACI);
2555                                        break;
2556                        }
2557                }
2558                ac_param += (sizeof(AC_PARAM));
2559        }
2560}
2561
2562void rtl8180_tx_irq_wq(struct work_struct *work);
2563void rtl8180_restart_wq(struct work_struct *work);
2564//void rtl8180_rq_tx_ack(struct work_struct *work);
2565void rtl8180_watch_dog_wq(struct work_struct *work);
2566void rtl8180_hw_wakeup_wq(struct work_struct *work);
2567void rtl8180_hw_sleep_wq(struct work_struct *work);
2568void rtl8180_sw_antenna_wq(struct work_struct *work);
2569void rtl8180_watch_dog(struct net_device *dev);
2570
2571void watch_dog_adaptive(unsigned long data)
2572{
2573        struct r8180_priv* priv = ieee80211_priv((struct net_device *)data);
2574
2575        if (!priv->up) {
2576                DMESG("<----watch_dog_adaptive():driver is not up!\n");
2577                return;
2578        }
2579
2580        // Tx High Power Mechanism.
2581#ifdef HIGH_POWER
2582        if(CheckHighPower((struct net_device *)data))
2583        {
2584                queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->tx_pw_wq);
2585        }
2586#endif
2587
2588        // Tx Power Tracking on 87SE.
2589#ifdef TX_TRACK
2590        //if( priv->bTxPowerTrack )     //lzm mod 080826
2591        if( CheckTxPwrTracking((struct net_device *)data));
2592                TxPwrTracking87SE((struct net_device *)data);
2593#endif
2594
2595        // Perform DIG immediately.
2596#ifdef SW_DIG
2597        if(CheckDig((struct net_device *)data) == true)
2598        {
2599                queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->hw_dig_wq);
2600        }
2601#endif
2602        rtl8180_watch_dog((struct net_device *)data);
2603
2604        queue_work(priv->ieee80211->wq, (void *)&priv->ieee80211->GPIOChangeRFWorkItem);
2605
2606        priv->watch_dog_timer.expires = jiffies + MSECS(IEEE80211_WATCH_DOG_TIME);
2607        add_timer(&priv->watch_dog_timer);
2608}
2609
2610static CHANNEL_LIST ChannelPlan[] = {
2611        {{1,2,3,4,5,6,7,8,9,10,11,36,40,44,48,52,56,60,64},19},                 //FCC
2612        {{1,2,3,4,5,6,7,8,9,10,11},11},                                                 //IC
2613        {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //ETSI
2614        {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},    //Spain. Change to ETSI.
2615        {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //France. Change to ETSI.
2616        {{14,36,40,44,48,52,56,60,64},9},                                               //MKK
2617        {{1,2,3,4,5,6,7,8,9,10,11,12,13,14, 36,40,44,48,52,56,60,64},22},//MKK1
2618        {{1,2,3,4,5,6,7,8,9,10,11,12,13,36,40,44,48,52,56,60,64},21},   //Israel.
2619        {{1,2,3,4,5,6,7,8,9,10,11,12,13,34,38,42,46},17},                       // For 11a , TELEC
2620        {{1,2,3,4,5,6,7,8,9,10,11,12,13,14},14},  //For Global Domain. 1-11:active scan, 12-14 passive scan. //+YJ, 080626
2621        {{1,2,3,4,5,6,7,8,9,10,11,12,13},13} //world wide 13: ch1~ch11 active scan, ch12~13 passive //lzm add 080826
2622};
2623
2624static void rtl8180_set_channel_map(u8 channel_plan, struct ieee80211_device *ieee)
2625{
2626        int i;
2627
2628        //lzm add 080826
2629        ieee->MinPassiveChnlNum=MAX_CHANNEL_NUMBER+1;
2630        ieee->IbssStartChnl=0;
2631
2632        switch (channel_plan)
2633        {
2634                case COUNTRY_CODE_FCC:
2635                case COUNTRY_CODE_IC:
2636                case COUNTRY_CODE_ETSI:
2637                case COUNTRY_CODE_SPAIN:
2638                case COUNTRY_CODE_FRANCE:
2639                case COUNTRY_CODE_MKK:
2640                case COUNTRY_CODE_MKK1:
2641                case COUNTRY_CODE_ISRAEL:
2642                case COUNTRY_CODE_TELEC:
2643                {
2644                        Dot11d_Init(ieee);
2645                        ieee->bGlobalDomain = false;
2646                        if (ChannelPlan[channel_plan].Len != 0){
2647                                // Clear old channel map
2648                                memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
2649                                // Set new channel map
2650                                for (i=0;i<ChannelPlan[channel_plan].Len;i++)
2651                                {
2652                                        if(ChannelPlan[channel_plan].Channel[i] <= 14)
2653                                                GET_DOT11D_INFO(ieee)->channel_map[ChannelPlan[channel_plan].Channel[i]] = 1;
2654                                }
2655                        }
2656                        break;
2657                }
2658                case COUNTRY_CODE_GLOBAL_DOMAIN:
2659                {
2660                        GET_DOT11D_INFO(ieee)->bEnabled = 0;
2661                        Dot11d_Reset(ieee);
2662                        ieee->bGlobalDomain = true;
2663                        break;
2664                }
2665                case COUNTRY_CODE_WORLD_WIDE_13_INDEX://lzm add 080826
2666                {
2667                ieee->MinPassiveChnlNum=12;
2668                ieee->IbssStartChnl= 10;
2669                break;
2670                }
2671                default:
2672                {
2673                        Dot11d_Init(ieee);
2674                        ieee->bGlobalDomain = false;
2675                        memset(GET_DOT11D_INFO(ieee)->channel_map, 0, sizeof(GET_DOT11D_INFO(ieee)->channel_map));
2676                        for (i=1;i<=14;i++)
2677                        {
2678                                GET_DOT11D_INFO(ieee)->channel_map[i] = 1;
2679                        }
2680                        break;
2681                }
2682        }
2683}
2684
2685void GPIOChangeRFWorkItemCallBack(struct work_struct *work);
2686
2687//YJ,add,080828
2688static void rtl8180_statistics_init(struct Stats *pstats)
2689{
2690        memset(pstats, 0, sizeof(struct Stats));
2691}
2692
2693static void rtl8180_link_detect_init(plink_detect_t plink_detect)
2694{
2695        memset(plink_detect, 0, sizeof(link_detect_t));
2696        plink_detect->SlotNum = DEFAULT_SLOT_NUM;
2697}
2698//YJ,add,080828,end
2699
2700short rtl8180_init(struct net_device *dev)
2701{
2702        struct r8180_priv *priv = ieee80211_priv(dev);
2703        u16 word;
2704        u16 version;
2705        u8 hw_version;
2706        //u8 config3;
2707        u32 usValue;
2708        u16 tmpu16;
2709        int i, j;
2710
2711        priv->channel_plan = eprom_read(dev, EEPROM_COUNTRY_CODE>>1) & 0xFF;
2712        if(priv->channel_plan > COUNTRY_CODE_GLOBAL_DOMAIN){
2713                printk("rtl8180_init:Error channel plan! Set to default.\n");
2714                priv->channel_plan = 0;
2715        }
2716
2717        DMESG("Channel plan is %d\n",priv->channel_plan);
2718        rtl8180_set_channel_map(priv->channel_plan, priv->ieee80211);
2719
2720        //FIXME: these constants are placed in a bad pleace.
2721        priv->txbuffsize = 2048;//1024;
2722        priv->txringcount = 32;//32;
2723        priv->rxbuffersize = 2048;//1024;
2724        priv->rxringcount = 64;//32;
2725        priv->txbeaconcount = 2;
2726        priv->rx_skb_complete = 1;
2727
2728        priv->RegThreeWireMode = HW_THREE_WIRE_SI;
2729
2730        priv->RFChangeInProgress = false;
2731        priv->SetRFPowerStateInProgress = false;
2732        priv->RFProgType = 0;
2733        priv->bInHctTest = false;
2734
2735        priv->irq_enabled=0;
2736
2737        rtl8180_statistics_init(&priv->stats);
2738        rtl8180_link_detect_init(&priv->link_detect);
2739
2740        priv->ack_tx_to_ieee = 0;
2741        priv->ieee80211->current_network.beacon_interval = DEFAULT_BEACONINTERVAL;
2742        priv->ieee80211->iw_mode = IW_MODE_INFRA;
2743        priv->ieee80211->softmac_features  = IEEE_SOFTMAC_SCAN |
2744                IEEE_SOFTMAC_ASSOCIATE | IEEE_SOFTMAC_PROBERQ |
2745                IEEE_SOFTMAC_PROBERS | IEEE_SOFTMAC_TX_QUEUE;
2746        priv->ieee80211->active_scan = 1;
2747        priv->ieee80211->rate = 110; //11 mbps
2748        priv->ieee80211->modulation = IEEE80211_CCK_MODULATION;
2749        priv->ieee80211->host_encrypt = 1;
2750        priv->ieee80211->host_decrypt = 1;
2751        priv->ieee80211->sta_wake_up = rtl8180_hw_wakeup;
2752        priv->ieee80211->ps_request_tx_ack = rtl8180_rq_tx_ack;
2753        priv->ieee80211->enter_sleep_state = rtl8180_hw_sleep;
2754        priv->ieee80211->ps_is_queue_empty = rtl8180_is_tx_queue_empty;
2755
2756        priv->hw_wep = hwwep;
2757        priv->prism_hdr=0;
2758        priv->dev=dev;
2759        priv->retry_rts = DEFAULT_RETRY_RTS;
2760        priv->retry_data = DEFAULT_RETRY_DATA;
2761        priv->RFChangeInProgress = false;
2762        priv->SetRFPowerStateInProgress = false;
2763        priv->RFProgType = 0;
2764        priv->bInHctTest = false;
2765        priv->bInactivePs = true;//false;
2766        priv->ieee80211->bInactivePs = priv->bInactivePs;
2767        priv->bSwRfProcessing = false;
2768        priv->eRFPowerState = eRfOff;
2769        priv->RfOffReason = 0;
2770        priv->LedStrategy = SW_LED_MODE0;
2771        priv->TxPollingTimes = 0;//lzm add 080826
2772        priv->bLeisurePs = true;
2773        priv->dot11PowerSaveMode = eActive;
2774//by amy for antenna
2775        priv->AdMinCheckPeriod = 5;
2776        priv->AdMaxCheckPeriod = 10;
2777// Lower signal strength threshold to fit the HW participation in antenna diversity. +by amy 080312
2778        priv->AdMaxRxSsThreshold = 30;//60->30
2779        priv->AdRxSsThreshold = 20;//50->20
2780        priv->AdCheckPeriod = priv->AdMinCheckPeriod;
2781        priv->AdTickCount = 0;
2782        priv->AdRxSignalStrength = -1;
2783        priv->RegSwAntennaDiversityMechanism = 0;
2784        priv->RegDefaultAntenna = 0;
2785        priv->SignalStrength = 0;
2786        priv->AdRxOkCnt = 0;
2787        priv->CurrAntennaIndex = 0;
2788        priv->AdRxSsBeforeSwitched = 0;
2789        init_timer(&priv->SwAntennaDiversityTimer);
2790        priv->SwAntennaDiversityTimer.data = (unsigned long)dev;
2791        priv->SwAntennaDiversityTimer.function = (void *)SwAntennaDiversityTimerCallback;
2792//by amy for antenna
2793//{by amy 080312
2794        priv->bDigMechanism = 1;
2795        priv->InitialGain = 6;
2796        priv->bXtalCalibration = false;
2797        priv->XtalCal_Xin = 0;
2798        priv->XtalCal_Xout = 0;
2799        priv->bTxPowerTrack = false;
2800        priv->ThermalMeter = 0;
2801        priv->FalseAlarmRegValue = 0;
2802        priv->RegDigOfdmFaUpTh = 0xc; // Upper threhold of OFDM false alarm, which is used in DIG.
2803        priv->DIG_NumberFallbackVote = 0;
2804        priv->DIG_NumberUpgradeVote = 0;
2805        priv->LastSignalStrengthInPercent = 0;
2806        priv->Stats_SignalStrength = 0;
2807        priv->LastRxPktAntenna = 0;
2808        priv->SignalQuality = 0; // in 0-100 index.
2809        priv->Stats_SignalQuality = 0;
2810        priv->RecvSignalPower = 0; // in dBm.
2811        priv->Stats_RecvSignalPower = 0;
2812        priv->AdMainAntennaRxOkCnt = 0;
2813        priv->AdAuxAntennaRxOkCnt = 0;
2814        priv->bHWAdSwitched = false;
2815        priv->bRegHighPowerMechanism = true;
2816        priv->RegHiPwrUpperTh = 77;
2817        priv->RegHiPwrLowerTh = 75;
2818        priv->RegRSSIHiPwrUpperTh = 70;
2819        priv->RegRSSIHiPwrLowerTh = 20;
2820        priv->bCurCCKPkt = false;
2821        priv->UndecoratedSmoothedSS = -1;
2822        priv->bToUpdateTxPwr = false;
2823        priv->CurCCKRSSI = 0;
2824        priv->RxPower = 0;
2825        priv->RSSI = 0;
2826        priv->NumTxOkTotal = 0;
2827        priv->NumTxUnicast = 0;
2828        priv->keepAliveLevel = DEFAULT_KEEP_ALIVE_LEVEL;
2829        priv->PowerProfile = POWER_PROFILE_AC;
2830    priv->CurrRetryCnt=0;
2831    priv->LastRetryCnt=0;
2832    priv->LastTxokCnt=0;
2833    priv->LastRxokCnt=0;
2834    priv->LastRetryRate=0;
2835    priv->bTryuping=0;
2836    priv->CurrTxRate=0;
2837    priv->CurrRetryRate=0;
2838    priv->TryupingCount=0;
2839    priv->TryupingCountNoData=0;
2840    priv->TryDownCountLowData=0;
2841    priv->LastTxOKBytes=0;
2842    priv->LastFailTxRate=0;
2843    priv->LastFailTxRateSS=0;
2844    priv->FailTxRateCount=0;
2845    priv->LastTxThroughput=0;
2846    priv->NumTxOkBytesTotal=0;
2847        priv->ForcedDataRate = 0;
2848        priv->RegBModeGainStage = 1;
2849
2850        priv->promisc = (dev->flags & IFF_PROMISC) ? 1:0;
2851        spin_lock_init(&priv->irq_lock);
2852        spin_lock_init(&priv->irq_th_lock);
2853        spin_lock_init(&priv->tx_lock);
2854        spin_lock_init(&priv->ps_lock);
2855        spin_lock_init(&priv->rf_ps_lock);
2856        sema_init(&priv->wx_sem,1);
2857        sema_init(&priv->rf_state,1);
2858        INIT_WORK(&priv->reset_wq,(void*) rtl8180_restart_wq);
2859        INIT_WORK(&priv->tx_irq_wq,(void*) rtl8180_tx_irq_wq);
2860        INIT_DELAYED_WORK(&priv->ieee80211->hw_wakeup_wq,(void*) rtl8180_hw_wakeup_wq);
2861        INIT_DELAYED_WORK(&priv->ieee80211->hw_sleep_wq,(void*) rtl8180_hw_sleep_wq);
2862        INIT_WORK(&priv->ieee80211->wmm_param_update_wq,(void*) rtl8180_wmm_param_update);
2863        INIT_DELAYED_WORK(&priv->ieee80211->rate_adapter_wq,(void*)rtl8180_rate_adapter);//+by amy 080312
2864        INIT_DELAYED_WORK(&priv->ieee80211->hw_dig_wq,(void*)rtl8180_hw_dig_wq);//+by amy 080312
2865        INIT_DELAYED_WORK(&priv->ieee80211->tx_pw_wq,(void*)rtl8180_tx_pw_wq);//+by amy 080312
2866
2867        INIT_DELAYED_WORK(&priv->ieee80211->GPIOChangeRFWorkItem,(void*) GPIOChangeRFWorkItemCallBack);
2868
2869        tasklet_init(&priv->irq_rx_tasklet,
2870                     (void(*)(unsigned long)) rtl8180_irq_rx_tasklet,
2871                     (unsigned long)priv);
2872
2873    init_timer(&priv->watch_dog_timer);
2874        priv->watch_dog_timer.data = (unsigned long)dev;
2875        priv->watch_dog_timer.function = watch_dog_adaptive;
2876
2877    init_timer(&priv->rateadapter_timer);
2878        priv->rateadapter_timer.data = (unsigned long)dev;
2879        priv->rateadapter_timer.function = timer_rate_adaptive;
2880                priv->RateAdaptivePeriod= RATE_ADAPTIVE_TIMER_PERIOD;
2881                priv->bEnhanceTxPwr=false;
2882
2883        priv->ieee80211->softmac_hard_start_xmit = rtl8180_hard_start_xmit;
2884        priv->ieee80211->set_chan = rtl8180_set_chan;
2885        priv->ieee80211->link_change = rtl8180_link_change;
2886        priv->ieee80211->softmac_data_hard_start_xmit = rtl8180_hard_data_xmit;
2887        priv->ieee80211->data_hard_stop = rtl8180_data_hard_stop;
2888        priv->ieee80211->data_hard_resume = rtl8180_data_hard_resume;
2889
2890        priv->ieee80211->init_wmmparam_flag = 0;
2891
2892        priv->ieee80211->start_send_beacons = rtl8180_start_tx_beacon;
2893        priv->ieee80211->stop_send_beacons = rtl8180_beacon_tx_disable;
2894        priv->ieee80211->fts = DEFAULT_FRAG_THRESHOLD;
2895
2896        priv->MWIEnable = 0;
2897
2898        priv->ShortRetryLimit = 7;
2899        priv->LongRetryLimit = 7;
2900        priv->EarlyRxThreshold = 7;
2901
2902        priv->CSMethod = (0x01 << 29);
2903
2904        priv->TransmitConfig    =
2905                                                                        1<<TCR_DurProcMode_OFFSET |             //for RTL8185B, duration setting by HW
2906                                                                        (7<<TCR_MXDMA_OFFSET) | // Max DMA Burst Size per Tx DMA Burst, 7: reservied.
2907                                                                        (priv->ShortRetryLimit<<TCR_SRL_OFFSET) |       // Short retry limit
2908                                                                        (priv->LongRetryLimit<<TCR_LRL_OFFSET) |        // Long retry limit
2909                                                                        (0 ? TCR_SAT : 0);      // FALSE: HW provies PLCP length and LENGEXT, TURE: SW proiveds them
2910
2911        priv->ReceiveConfig     =
2912                                                                RCR_AMF | RCR_ADF |                             //accept management/data
2913                                                                RCR_ACF |                                               //accept control frame for SW AP needs PS-poll, 2005.07.07, by rcnjko.
2914                                                                RCR_AB | RCR_AM | RCR_APM |             //accept BC/MC/UC
2915                                                                (7<<RCR_MXDMA_OFFSET) | // Max DMA Burst Size per Rx DMA Burst, 7: unlimited.
2916                                                                (priv->EarlyRxThreshold<<RCR_FIFO_OFFSET) | // Rx FIFO Threshold, 7: No Rx threshold.
2917                                                                (priv->EarlyRxThreshold == 7 ? RCR_ONLYERLPKT:0);
2918
2919        priv->IntrMask          = IMR_TMGDOK | IMR_TBDER | IMR_THPDER |
2920                                                                IMR_THPDER | IMR_THPDOK |
2921                                                                IMR_TVODER | IMR_TVODOK |
2922                                                                IMR_TVIDER | IMR_TVIDOK |
2923                                                                IMR_TBEDER | IMR_TBEDOK |
2924                                                                IMR_TBKDER | IMR_TBKDOK |
2925                                                                IMR_RDU |                                               // To handle the defragmentation not enough Rx descriptors case. Annie, 2006-03-27.
2926                                                                IMR_RER | IMR_ROK |
2927                                                                IMR_RQoSOK; // <NOTE> ROK and RQoSOK are mutually exclusive, so, we must handle RQoSOK interrupt to receive QoS frames, 2005.12.09, by rcnjko.
2928
2929        priv->InitialGain = 6;
2930
2931        hw_version =( read_nic_dword(dev, TCR) & TCR_HWVERID_MASK)>>TCR_HWVERID_SHIFT;
2932
2933        switch (hw_version){
2934                case HW_VERID_R8185B_B:
2935                        priv->card_8185 = VERSION_8187S_C;
2936                        DMESG("MAC controller is a RTL8187SE b/g");
2937                        priv->phy_ver = 2;
2938                        break;
2939                case HW_VERID_R8185_ABC:
2940                        DMESG("MAC controller is a RTL8185 b/g");
2941                        priv->card_8185 = 1;
2942                        /* you should not find a card with 8225 PHY ver < C*/
2943                        priv->phy_ver = 2;
2944                        break;
2945                case HW_VERID_R8185_D:
2946                        DMESG("MAC controller is a RTL8185 b/g (V. D)");
2947                        priv->card_8185 = 2;
2948                        /* you should not find a card with 8225 PHY ver < C*/
2949                        priv->phy_ver = 2;
2950                        break;
2951                case HW_VERID_R8180_ABCD:
2952                        DMESG("MAC controller is a RTL8180");
2953                        priv->card_8185 = 0;
2954                        break;
2955                case HW_VERID_R8180_F:
2956                        DMESG("MAC controller is a RTL8180 (v. F)");
2957                        priv->card_8185 = 0;
2958                        break;
2959                default:
2960                        DMESGW("MAC chip not recognized: version %x. Assuming RTL8180",hw_version);
2961                        priv->card_8185 = 0;
2962                        break;
2963        }
2964
2965        if(priv->card_8185){
2966                priv->ieee80211->modulation |= IEEE80211_OFDM_MODULATION;
2967                priv->ieee80211->short_slot = 1;
2968        }
2969        /* you should not found any 8185 Ver B Card */
2970        priv->card_8185_Bversion = 0;
2971
2972        // just for sync 85
2973        priv->card_type = PCI;
2974        DMESG("This is a PCI NIC");
2975        priv->enable_gpio0 = 0;
2976
2977        usValue = eprom_read(dev, EEPROM_SW_REVD_OFFSET);
2978        DMESG("usValue is 0x%x\n",usValue);
2979        //3Read AntennaDiversity
2980
2981        // SW Antenna Diversity.
2982        if ((usValue & EEPROM_SW_AD_MASK) != EEPROM_SW_AD_ENABLE)
2983                priv->EEPROMSwAntennaDiversity = false;
2984        else
2985                priv->EEPROMSwAntennaDiversity = true;
2986
2987        // Default Antenna to use.
2988        if ((usValue & EEPROM_DEF_ANT_MASK) != EEPROM_DEF_ANT_1)
2989                priv->EEPROMDefaultAntenna1 = false;
2990        else
2991                priv->EEPROMDefaultAntenna1 = true;
2992
2993        if( priv->RegSwAntennaDiversityMechanism == 0 ) // Auto
2994                /* 0: default from EEPROM. */
2995                priv->bSwAntennaDiverity = priv->EEPROMSwAntennaDiversity;
2996        else
2997                /* 1:disable antenna diversity, 2: enable antenna diversity. */
2998                priv->bSwAntennaDiverity = ((priv->RegSwAntennaDiversityMechanism == 1)? false : true);
2999
3000        if (priv->RegDefaultAntenna == 0)
3001                /* 0: default from EEPROM. */
3002                priv->bDefaultAntenna1 = priv->EEPROMDefaultAntenna1;
3003        else
3004                /* 1: main, 2: aux. */
3005                priv->bDefaultAntenna1 = ((priv->RegDefaultAntenna== 2) ? true : false);
3006
3007        /* rtl8185 can calc plcp len in HW.*/
3008        priv->hw_plcp_len = 1;
3009
3010        priv->plcp_preamble_mode = 2;
3011        /*the eeprom type is stored in RCR register bit #6 */
3012        if (RCR_9356SEL & read_nic_dword(dev, RCR))
3013                priv->epromtype=EPROM_93c56;
3014        else
3015                priv->epromtype=EPROM_93c46;
3016
3017        dev->dev_addr[0]=eprom_read(dev,MAC_ADR) & 0xff;
3018        dev->dev_addr[1]=(eprom_read(dev,MAC_ADR) & 0xff00)>>8;
3019        dev->dev_addr[2]=eprom_read(dev,MAC_ADR+1) & 0xff;
3020        dev->dev_addr[3]=(eprom_read(dev,MAC_ADR+1) & 0xff00)>>8;
3021        dev->dev_addr[4]=eprom_read(dev,MAC_ADR+2) & 0xff;
3022        dev->dev_addr[5]=(eprom_read(dev,MAC_ADR+2) & 0xff00)>>8;
3023
3024        for(i=1,j=0; i<14; i+=2,j++){
3025                word = eprom_read(dev,EPROM_TXPW_CH1_2 + j);
3026                priv->chtxpwr[i]=word & 0xff;
3027                priv->chtxpwr[i+1]=(word & 0xff00)>>8;
3028        }
3029        if(priv->card_8185){
3030                for(i=1,j=0; i<14; i+=2,j++){
3031                        word = eprom_read(dev,EPROM_TXPW_OFDM_CH1_2 + j);
3032                        priv->chtxpwr_ofdm[i]=word & 0xff;
3033                        priv->chtxpwr_ofdm[i+1]=(word & 0xff00)>>8;
3034                }
3035        }
3036
3037        //3Read crystal calibtration and thermal meter indication on 87SE.
3038
3039        // By SD3 SY's request. Added by Roger, 2007.12.11.
3040
3041        tmpu16 = eprom_read(dev, EEPROM_RSV>>1);
3042
3043                // Crystal calibration for Xin and Xout resp.
3044                priv->XtalCal_Xout = tmpu16 & EEPROM_XTAL_CAL_XOUT_MASK; // 0~7.5pF
3045                priv->XtalCal_Xin = (tmpu16 & EEPROM_XTAL_CAL_XIN_MASK)>>4; // 0~7.5pF
3046                if((tmpu16 & EEPROM_XTAL_CAL_ENABLE)>>12)
3047                        priv->bXtalCalibration = true;
3048
3049                // Thermal meter reference indication.
3050                priv->ThermalMeter =  (u8)((tmpu16 & EEPROM_THERMAL_METER_MASK)>>8);
3051                if((tmpu16 & EEPROM_THERMAL_METER_ENABLE)>>13)
3052                        priv->bTxPowerTrack = true;
3053
3054        word = eprom_read(dev,EPROM_TXPW_BASE);
3055        priv->cck_txpwr_base = word & 0xf;
3056        priv->ofdm_txpwr_base = (word>>4) & 0xf;
3057
3058        version = eprom_read(dev,EPROM_VERSION);
3059        DMESG("EEPROM version %x",version);
3060        if( (!priv->card_8185) && version < 0x0101){
3061                DMESG ("EEPROM version too old, assuming defaults");
3062                DMESG ("If you see this message *plase* send your \
3063DMESG output to andreamrl@tiscali.it THANKS");
3064                priv->digphy=1;
3065                priv->antb=0;
3066                priv->diversity=1;
3067                priv->cs_treshold=0xc;
3068                priv->rcr_csense=1;
3069                priv->rf_chip=RFCHIPID_PHILIPS;
3070        }else{
3071                if(!priv->card_8185){
3072                        u8 rfparam = eprom_read(dev,RF_PARAM);
3073                        DMESG("RfParam: %x",rfparam);
3074
3075                        priv->digphy = rfparam & (1<<RF_PARAM_DIGPHY_SHIFT) ? 0:1;
3076                        priv->antb =  rfparam & (1<<RF_PARAM_ANTBDEFAULT_SHIFT) ? 1:0;
3077
3078                        priv->rcr_csense = (rfparam & RF_PARAM_CARRIERSENSE_MASK) >>
3079                                        RF_PARAM_CARRIERSENSE_SHIFT;
3080
3081                        priv->diversity =
3082                                (read_nic_byte(dev,CONFIG2)&(1<<CONFIG2_ANTENNA_SHIFT)) ? 1:0;
3083                }else{
3084                        priv->rcr_csense = 3;
3085                }
3086
3087                priv->cs_treshold = (eprom_read(dev,ENERGY_TRESHOLD)&0xff00) >>8;
3088
3089                priv->rf_chip = 0xff & eprom_read(dev,RFCHIPID);
3090        }
3091
3092        priv->rf_chip = RF_ZEBRA4;
3093        priv->rf_sleep = rtl8225z4_rf_sleep;
3094        priv->rf_wakeup = rtl8225z4_rf_wakeup;
3095        DMESGW("**PLEASE** REPORT SUCCESSFUL/UNSUCCESSFUL TO Realtek!");
3096
3097        priv->rf_close = rtl8225z2_rf_close;
3098        priv->rf_init = rtl8225z2_rf_init;
3099        priv->rf_set_chan = rtl8225z2_rf_set_chan;
3100        priv->rf_set_sens = NULL;
3101
3102        if(!priv->card_8185){
3103                if(priv->antb)
3104                        DMESG ("Antenna B is default antenna");
3105                else
3106                        DMESG ("Antenna A is default antenna");
3107
3108                if(priv->diversity)
3109                        DMESG ("Antenna diversity is enabled");
3110                else
3111                        DMESG("Antenna diversity is disabled");
3112
3113                DMESG("Carrier sense %d",priv->rcr_csense);
3114        }
3115
3116        if (0!=alloc_rx_desc_ring(dev, priv->rxbuffersize, priv->rxringcount))
3117                return -ENOMEM;
3118
3119        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3120                                  TX_MANAGEPRIORITY_RING_ADDR))
3121                return -ENOMEM;
3122
3123        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3124                                 TX_BKPRIORITY_RING_ADDR))
3125                return -ENOMEM;
3126
3127        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3128                                 TX_BEPRIORITY_RING_ADDR))
3129                return -ENOMEM;
3130
3131        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3132                                  TX_VIPRIORITY_RING_ADDR))
3133                return -ENOMEM;
3134
3135        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3136                                  TX_VOPRIORITY_RING_ADDR))
3137                return -ENOMEM;
3138
3139        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txringcount,
3140                                  TX_HIGHPRIORITY_RING_ADDR))
3141                return -ENOMEM;
3142
3143        if (0!=alloc_tx_desc_ring(dev, priv->txbuffsize, priv->txbeaconcount,
3144                                  TX_BEACON_RING_ADDR))
3145                return -ENOMEM;
3146
3147        if(!priv->card_8185){
3148                if(read_nic_byte(dev, CONFIG0) & (1<<CONFIG0_WEP40_SHIFT))
3149                        DMESG ("40-bit WEP is supported in hardware");
3150                else
3151                        DMESG ("40-bit WEP is NOT supported in hardware");
3152
3153                if(read_nic_byte(dev,CONFIG0) & (1<<CONFIG0_WEP104_SHIFT))
3154                        DMESG ("104-bit WEP is supported in hardware");
3155                else
3156                        DMESG ("104-bit WEP is NOT supported in hardware");
3157        }
3158#if !defined(SA_SHIRQ)
3159        if(request_irq(dev->irq, (void *)rtl8180_interrupt, IRQF_SHARED, dev->name, dev)){
3160#else
3161        if(request_irq(dev->irq, (void *)rtl8180_interrupt, SA_SHIRQ, dev->name, dev)){
3162#endif
3163                DMESGE("Error allocating IRQ %d",dev->irq);
3164                return -1;
3165        }else{
3166                priv->irq=dev->irq;
3167                DMESG("IRQ %d",dev->irq);
3168        }
3169
3170        return 0;
3171}
3172
3173void rtl8180_no_hw_wep(struct net_device *dev)
3174{
3175        struct r8180_priv *priv = ieee80211_priv(dev);
3176
3177        if (!priv->card_8185) {
3178                u8 security;
3179
3180                security  = read_nic_byte(dev, SECURITY);
3181                security &=~(1<<SECURITY_WEP_TX_ENABLE_SHIFT);
3182                security &=~(1<<SECURITY_WEP_RX_ENABLE_SHIFT);
3183
3184                write_nic_byte(dev, SECURITY, security);
3185        }
3186}
3187
3188void rtl8180_set_hw_wep(struct net_device *dev)
3189{
3190        struct r8180_priv *priv = ieee80211_priv(dev);
3191        u8 pgreg;
3192        u8 security;
3193        u32 key0_word4;
3194
3195        pgreg=read_nic_byte(dev, PGSELECT);
3196        write_nic_byte(dev, PGSELECT, pgreg &~ (1<<PGSELECT_PG_SHIFT));
3197
3198        key0_word4 = read_nic_dword(dev, KEY0+4+4+4);
3199        key0_word4 &= ~ 0xff;
3200        key0_word4 |= priv->key0[3]& 0xff;
3201        write_nic_dword(dev,KEY0,(priv->key0[0]));
3202        write_nic_dword(dev,KEY0+4,(priv->key0[1]));
3203        write_nic_dword(dev,KEY0+4+4,(priv->key0[2]));
3204        write_nic_dword(dev,KEY0+4+4+4,(key0_word4));
3205
3206        security  = read_nic_byte(dev,SECURITY);
3207        security |= (1<<SECURITY_WEP_TX_ENABLE_SHIFT);
3208        security |= (1<<SECURITY_WEP_RX_ENABLE_SHIFT);
3209        security &= ~ SECURITY_ENCRYP_MASK;
3210        security |= (SECURITY_ENCRYP_104<<SECURITY_ENCRYP_SHIFT);
3211
3212        write_nic_byte(dev, SECURITY, security);
3213
3214        DMESG("key %x %x %x %x",read_nic_dword(dev,KEY0+4+4+4),
3215              read_nic_dword(dev,KEY0+4+4),read_nic_dword(dev,KEY0+4),
3216              read_nic_dword(dev,KEY0));
3217}
3218
3219
3220void rtl8185_rf_pins_enable(struct net_device *dev)
3221{
3222//      u16 tmp;
3223//      tmp = read_nic_word(dev, RFPinsEnable);
3224        write_nic_word(dev, RFPinsEnable, 0x1fff);// | tmp);
3225}
3226
3227void rtl8185_set_anaparam2(struct net_device *dev, u32 a)
3228{
3229        u8 conf3;
3230
3231        rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
3232
3233        conf3 = read_nic_byte(dev, CONFIG3);
3234        write_nic_byte(dev, CONFIG3, conf3 | (1<<CONFIG3_ANAPARAM_W_SHIFT));
3235        write_nic_dword(dev, ANAPARAM2, a);
3236
3237        conf3 = read_nic_byte(dev, CONFIG3);
3238        write_nic_byte(dev, CONFIG3, conf3 &~(1<<CONFIG3_ANAPARAM_W_SHIFT));
3239        rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
3240}
3241
3242void rtl8180_set_anaparam(struct net_device *dev, u32 a)
3243{
3244        u8 conf3;
3245
3246        rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
3247
3248        conf3 = read_nic_byte(dev, CONFIG3);
3249        write_nic_byte(dev, CONFIG3, conf3 | (1<<CONFIG3_ANAPARAM_W_SHIFT));
3250        write_nic_dword(dev, ANAPARAM, a);
3251
3252        conf3 = read_nic_byte(dev, CONFIG3);
3253        write_nic_byte(dev, CONFIG3, conf3 &~(1<<CONFIG3_ANAPARAM_W_SHIFT));
3254        rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
3255}
3256
3257void rtl8185_tx_antenna(struct net_device *dev, u8 ant)
3258{
3259        write_nic_byte(dev, TX_ANTENNA, ant);
3260        force_pci_posting(dev);
3261        mdelay(1);
3262}
3263
3264void rtl8185_write_phy(struct net_device *dev, u8 adr, u32 data)
3265{
3266        u32 phyw;
3267
3268        adr |= 0x80;
3269
3270        phyw= ((data<<8) | adr);
3271
3272        // Note that, we must write 0xff7c after 0x7d-0x7f to write BB register.
3273        write_nic_byte(dev, 0x7f, ((phyw & 0xff000000) >> 24));
3274        write_nic_byte(dev, 0x7e, ((phyw & 0x00ff0000) >> 16));
3275        write_nic_byte(dev, 0x7d, ((phyw & 0x0000ff00) >> 8));
3276        write_nic_byte(dev, 0x7c, ((phyw & 0x000000ff) ));
3277
3278        /* this is ok to fail when we write AGC table. check for AGC table might be
3279         * done by masking with 0x7f instead of 0xff
3280         */
3281        //if(phyr != (data&0xff)) DMESGW("Phy write timeout %x %x %x", phyr, data,adr);
3282}
3283
3284inline void write_phy_ofdm (struct net_device *dev, u8 adr, u32 data)
3285{
3286        data = data & 0xff;
3287        rtl8185_write_phy(dev, adr, data);
3288}
3289
3290void write_phy_cck (struct net_device *dev, u8 adr, u32 data)
3291{
3292        data = data & 0xff;
3293        rtl8185_write_phy(dev, adr, data | 0x10000);
3294}
3295
3296/* 70*3 = 210 ms
3297 * I hope this is enougth
3298 */
3299#define MAX_PHY 70
3300void write_phy(struct net_device *dev, u8 adr, u8 data)
3301{
3302        u32 phy;
3303        int i;
3304
3305        phy = 0xff0000;
3306        phy |= adr;
3307        phy |= 0x80; /* this should enable writing */
3308        phy |= (data<<8);
3309
3310        //PHY_ADR, PHY_R and PHY_W  are contig and treated as one dword
3311        write_nic_dword(dev,PHY_ADR, phy);
3312
3313        phy= 0xffff00;
3314        phy |= adr;
3315
3316        write_nic_dword(dev,PHY_ADR, phy);
3317        for(i=0;i<MAX_PHY;i++){
3318                phy=read_nic_dword(dev,PHY_ADR);
3319                phy= phy & 0xff0000;
3320                phy= phy >> 16;
3321                if(phy == data){ //SUCCESS!
3322                        force_pci_posting(dev);
3323                        mdelay(3); //random value
3324                        return;
3325                }else{
3326                        force_pci_posting(dev);
3327                        mdelay(3); //random value
3328                }
3329        }
3330        DMESGW ("Phy writing %x %x failed!", adr,data);
3331}
3332
3333void rtl8185_set_rate(struct net_device *dev)
3334{
3335        int i;
3336        u16 word;
3337        int basic_rate,min_rr_rate,max_rr_rate;
3338
3339        basic_rate = ieeerate2rtlrate(240);
3340        min_rr_rate = ieeerate2rtlrate(60);
3341        max_rr_rate = ieeerate2rtlrate(240);
3342
3343        write_nic_byte(dev, RESP_RATE,
3344                        max_rr_rate<<MAX_RESP_RATE_SHIFT| min_rr_rate<<MIN_RESP_RATE_SHIFT);
3345
3346        word  = read_nic_word(dev, BRSR);
3347        word &= ~BRSR_MBR_8185;
3348
3349        for(i=0;i<=basic_rate;i++)
3350                word |= (1<<i);
3351
3352        write_nic_word(dev, BRSR, word);
3353}
3354
3355void rtl8180_adapter_start(struct net_device *dev)
3356{
3357        struct r8180_priv *priv = ieee80211_priv(dev);
3358        u32 anaparam;
3359        u16 word;
3360        u8 config3;
3361
3362        rtl8180_rtx_disable(dev);
3363        rtl8180_reset(dev);
3364
3365        /* enable beacon timeout, beacon TX ok and err
3366         * LP tx ok and err, HP TX ok and err, NP TX ok and err,
3367         * RX ok and ERR, and GP timer */
3368        priv->irq_mask = 0x6fcf;
3369
3370        priv->dma_poll_mask = 0;
3371
3372        rtl8180_beacon_tx_disable(dev);
3373
3374        if(priv->card_type == CARDBUS ){
3375                config3=read_nic_byte(dev, CONFIG3);
3376                write_nic_byte(dev,CONFIG3,config3 | CONFIG3_FuncRegEn);
3377                write_nic_word(dev,FEMR, FEMR_INTR | FEMR_WKUP | FEMR_GWAKE |
3378                        read_nic_word(dev, FEMR));
3379        }
3380        rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
3381        write_nic_dword(dev, MAC0, ((u32*)dev->dev_addr)[0]);
3382        write_nic_word(dev, MAC4, ((u32*)dev->dev_addr)[1] & 0xffff );
3383        rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
3384
3385        rtl8180_update_msr(dev);
3386
3387        if(!priv->card_8185){
3388                anaparam  = eprom_read(dev,EPROM_ANAPARAM_ADDRLWORD);
3389                anaparam |= eprom_read(dev,EPROM_ANAPARAM_ADDRHWORD)<<16;
3390
3391                rtl8180_set_anaparam(dev,anaparam);
3392        }
3393        /* These might be unnecessary since we do in rx_enable / tx_enable */
3394        fix_rx_fifo(dev);
3395        fix_tx_fifo(dev);
3396
3397        rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
3398
3399        /*
3400           The following is very strange. seems to be that 1 means test mode,
3401           but we need to acknolwledges the nic when a packet is ready
3402           altought we set it to 0
3403        */
3404
3405        write_nic_byte(dev,
3406                       CONFIG2, read_nic_byte(dev,CONFIG2) &~\
3407                       (1<<CONFIG2_DMA_POLLING_MODE_SHIFT));
3408        //^the nic isn't in test mode
3409        if(priv->card_8185)
3410                        write_nic_byte(dev,
3411                       CONFIG2, read_nic_byte(dev,CONFIG2)|(1<<4));
3412
3413        rtl8180_set_mode(dev,EPROM_CMD_NORMAL);
3414
3415        write_nic_dword(dev,INT_TIMEOUT,0);
3416
3417        if(!priv->card_8185)
3418        {
3419                /*
3420                experimental - this might be needed to calibrate AGC,
3421                anyway it shouldn't hurt
3422                */
3423                write_nic_byte(dev, CONFIG5,
3424                        read_nic_byte(dev, CONFIG5) | (1<<AGCRESET_SHIFT));
3425                read_nic_byte(dev, CONFIG5);
3426                udelay(15);
3427                write_nic_byte(dev, CONFIG5,
3428                        read_nic_byte(dev, CONFIG5) &~ (1<<AGCRESET_SHIFT));
3429        }else{
3430                write_nic_byte(dev, WPA_CONFIG, 0);
3431                //write_nic_byte(dev, TESTR, 0xd);
3432        }
3433
3434        rtl8180_no_hw_wep(dev);
3435
3436        if(priv->card_8185){
3437                rtl8185_set_rate(dev);
3438                write_nic_byte(dev, RATE_FALLBACK, 0x81);
3439        }else{
3440                word  = read_nic_word(dev, BRSR);
3441                word &= ~BRSR_MBR;
3442                word &= ~BRSR_BPLCP;
3443                word |= ieeerate2rtlrate(priv->ieee80211->basic_rate);
3444                word |= 0x0f;
3445                write_nic_word(dev, BRSR, word);
3446        }
3447
3448        if(priv->card_8185){
3449                write_nic_byte(dev, GP_ENABLE,read_nic_byte(dev, GP_ENABLE) & ~(1<<6));
3450
3451                //FIXME cfg 3 ClkRun enable - isn't it ReadOnly ?
3452                rtl8180_set_mode(dev, EPROM_CMD_CONFIG);
3453                write_nic_byte(dev,CONFIG3, read_nic_byte(dev, CONFIG3)
3454                               | (1 << CONFIG3_CLKRUN_SHIFT));
3455                rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
3456        }
3457
3458        priv->rf_init(dev);
3459
3460        if(priv->rf_set_sens != NULL)
3461                priv->rf_set_sens(dev,priv->sens);
3462        rtl8180_irq_enable(dev);
3463
3464        netif_start_queue(dev);
3465}
3466
3467/* this configures registers for beacon tx and enables it via
3468 * rtl8180_beacon_tx_enable(). rtl8180_beacon_tx_disable() might
3469 * be used to stop beacon transmission
3470 */
3471void rtl8180_start_tx_beacon(struct net_device *dev)
3472{
3473        u16 word;
3474
3475        DMESG("Enabling beacon TX");
3476        rtl8180_prepare_beacon(dev);
3477        rtl8180_irq_disable(dev);
3478        rtl8180_beacon_tx_enable(dev);
3479
3480        word = read_nic_word(dev, AtimWnd) &~ AtimWnd_AtimWnd;
3481        write_nic_word(dev, AtimWnd,word);// word |=
3482
3483        word  = read_nic_word(dev, BintrItv);
3484        word &= ~BintrItv_BintrItv;
3485        word |= 1000;/*priv->ieee80211->current_network.beacon_interval *
3486                ((priv->txbeaconcount > 1)?(priv->txbeaconcount-1):1);
3487        // FIXME: check if correct ^^ worked with 0x3e8;
3488        */
3489        write_nic_word(dev, BintrItv, word);
3490
3491        rtl8180_set_mode(dev, EPROM_CMD_NORMAL);
3492
3493        rtl8185b_irq_enable(dev);
3494}
3495
3496static struct net_device_stats *rtl8180_stats(struct net_device *dev)
3497{
3498        struct r8180_priv *priv = ieee80211_priv(dev);
3499
3500        return &priv->ieee80211->stats;
3501}
3502//
3503// Change current and default preamble mode.
3504// 2005.01.06, by rcnjko.
3505//
3506bool
3507MgntActSet_802_11_PowerSaveMode(
3508        struct r8180_priv *priv,
3509        RT_PS_MODE              rtPsMode
3510)
3511{
3512        // Currently, we do not change power save mode on IBSS mode.
3513        if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3514                return false;
3515
3516        priv->ieee80211->ps = rtPsMode;
3517
3518        return true;
3519}
3520
3521void LeisurePSEnter(struct r8180_priv *priv)
3522{
3523        if (priv->bLeisurePs) {
3524                if (priv->ieee80211->ps == IEEE80211_PS_DISABLED)
3525                        MgntActSet_802_11_PowerSaveMode(priv, IEEE80211_PS_MBCAST|IEEE80211_PS_UNICAST);//IEEE80211_PS_ENABLE
3526        }
3527}
3528
3529void LeisurePSLeave(struct r8180_priv *priv)
3530{
3531        if (priv->bLeisurePs) {
3532                if (priv->ieee80211->ps != IEEE80211_PS_DISABLED)
3533                        MgntActSet_802_11_PowerSaveMode(priv, IEEE80211_PS_DISABLED);
3534        }
3535}
3536
3537void rtl8180_hw_wakeup_wq (struct work_struct *work)
3538{
3539        struct delayed_work *dwork = to_delayed_work(work);
3540        struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_wakeup_wq);
3541        struct net_device *dev = ieee->dev;
3542
3543        rtl8180_hw_wakeup(dev);
3544}
3545
3546void rtl8180_hw_sleep_wq (struct work_struct *work)
3547{
3548        struct delayed_work *dwork = to_delayed_work(work);
3549        struct ieee80211_device *ieee = container_of(dwork,struct ieee80211_device,hw_sleep_wq);
3550        struct net_device *dev = ieee->dev;
3551
3552        rtl8180_hw_sleep_down(dev);
3553}
3554
3555static void MgntLinkKeepAlive(struct r8180_priv *priv )
3556{
3557        if (priv->keepAliveLevel == 0)
3558                return;
3559
3560        if(priv->ieee80211->state == IEEE80211_LINKED)
3561        {
3562                //
3563                // Keep-Alive.
3564                //
3565
3566                if ( (priv->keepAliveLevel== 2) ||
3567                        (priv->link_detect.LastNumTxUnicast == priv->NumTxUnicast &&
3568                        priv->link_detect.LastNumRxUnicast == priv->ieee80211->NumRxUnicast )
3569                        )
3570                {
3571                        priv->link_detect.IdleCount++;
3572
3573                        //
3574                        // Send a Keep-Alive packet packet to AP if we had been idle for a while.
3575                        //
3576                        if(priv->link_detect.IdleCount >= ((KEEP_ALIVE_INTERVAL / CHECK_FOR_HANG_PERIOD)-1) )
3577                        {
3578                                priv->link_detect.IdleCount = 0;
3579                                ieee80211_sta_ps_send_null_frame(priv->ieee80211, false);
3580                        }
3581                }
3582                else
3583                {
3584                        priv->link_detect.IdleCount = 0;
3585                }
3586                priv->link_detect.LastNumTxUnicast = priv->NumTxUnicast;
3587                priv->link_detect.LastNumRxUnicast = priv->ieee80211->NumRxUnicast;
3588        }
3589}
3590
3591static u8 read_acadapter_file(char *filename);
3592
3593void rtl8180_watch_dog(struct net_device *dev)
3594{
3595        struct r8180_priv *priv = ieee80211_priv(dev);
3596        bool bEnterPS = false;
3597        bool bBusyTraffic = false;
3598        u32 TotalRxNum = 0;
3599        u16 SlotIndex = 0;
3600        u16 i = 0;
3601        if(priv->ieee80211->actscanning == false){
3602                if((priv->ieee80211->iw_mode != IW_MODE_ADHOC) && (priv->ieee80211->state == IEEE80211_NOLINK) && (priv->ieee80211->beinretry == false) && (priv->eRFPowerState == eRfOn)){
3603                        IPSEnter(dev);
3604                }
3605        }
3606        //YJ,add,080828,for link state check
3607        if((priv->ieee80211->state == IEEE80211_LINKED) && (priv->ieee80211->iw_mode == IW_MODE_INFRA)){
3608                SlotIndex = (priv->link_detect.SlotIndex++) % priv->link_detect.SlotNum;
3609                priv->link_detect.RxFrameNum[SlotIndex] = priv->ieee80211->NumRxDataInPeriod + priv->ieee80211->NumRxBcnInPeriod;
3610                for( i=0; i<priv->link_detect.SlotNum; i++ )
3611                        TotalRxNum+= priv->link_detect.RxFrameNum[i];
3612
3613                if(TotalRxNum == 0){
3614                        priv->ieee80211->state = IEEE80211_ASSOCIATING;
3615                        queue_work(priv->ieee80211->wq, &priv->ieee80211->associate_procedure_wq);
3616                }
3617        }
3618
3619        //YJ,add,080828,for KeepAlive
3620        MgntLinkKeepAlive(priv);
3621
3622        //YJ,add,080828,for LPS
3623#ifdef ENABLE_LPS
3624        if (priv->PowerProfile == POWER_PROFILE_BATTERY)
3625                priv->bLeisurePs = true;
3626        else if (priv->PowerProfile == POWER_PROFILE_AC) {
3627                LeisurePSLeave(priv);
3628                priv->bLeisurePs= false;
3629        }
3630
3631        if(priv->ieee80211->state == IEEE80211_LINKED){
3632                priv->link_detect.NumRxOkInPeriod = priv->ieee80211->NumRxDataInPeriod;
3633                //printk("TxOk=%d RxOk=%d\n", priv->link_detect.NumTxOkInPeriod, priv->link_detect.NumRxOkInPeriod);
3634                if(     priv->link_detect.NumRxOkInPeriod> 666 ||
3635                        priv->link_detect.NumTxOkInPeriod> 666 ) {
3636                        bBusyTraffic = true;
3637                }
3638                if(((priv->link_detect.NumRxOkInPeriod + priv->link_detect.NumTxOkInPeriod) > 8)
3639                        || (priv->link_detect.NumRxOkInPeriod > 2)) {
3640                        bEnterPS= false;
3641                } else
3642                        bEnterPS= true;
3643
3644                if (bEnterPS)
3645                        LeisurePSEnter(priv);
3646                else
3647                        LeisurePSLeave(priv);
3648        } else
3649                LeisurePSLeave(priv);
3650#endif
3651        priv->link_detect.bBusyTraffic = bBusyTraffic;
3652        priv->link_detect.NumRxOkInPeriod = 0;
3653        priv->link_detect.NumTxOkInPeriod = 0;
3654        priv->ieee80211->NumRxDataInPeriod = 0;
3655        priv->ieee80211->NumRxBcnInPeriod = 0;
3656}
3657
3658int _rtl8180_up(struct net_device *dev)
3659{
3660        struct r8180_priv *priv = ieee80211_priv(dev);
3661
3662        priv->up=1;
3663
3664        DMESG("Bringing up iface");
3665        rtl8185b_adapter_start(dev);
3666        rtl8185b_rx_enable(dev);
3667        rtl8185b_tx_enable(dev);
3668        if(priv->bInactivePs){
3669                if(priv->ieee80211->iw_mode == IW_MODE_ADHOC)
3670                        IPSLeave(dev);
3671        }
3672#ifdef RATE_ADAPT
3673       timer_rate_adaptive((unsigned long)dev);
3674#endif
3675        watch_dog_adaptive((unsigned long)dev);
3676#ifdef SW_ANTE
3677        if(priv->bSwAntennaDiverity)
3678                        SwAntennaDiversityTimerCallback(dev);
3679#endif
3680        ieee80211_softmac_start_protocol(priv->ieee80211);
3681
3682        return 0;
3683}
3684
3685int rtl8180_open(struct net_device *dev)
3686{
3687        struct r8180_priv *priv = ieee80211_priv(dev);
3688        int ret;
3689
3690        down(&priv->wx_sem);
3691        ret = rtl8180_up(dev);
3692        up(&priv->wx_sem);
3693        return ret;
3694}
3695
3696int rtl8180_up(struct net_device *dev)
3697{
3698        struct r8180_priv *priv = ieee80211_priv(dev);
3699
3700        if (priv->up == 1) return -1;
3701
3702        return _rtl8180_up(dev);
3703}
3704
3705int rtl8180_close(struct net_device *dev)
3706{
3707        struct r8180_priv *priv = ieee80211_priv(dev);
3708        int ret;
3709
3710        down(&priv->wx_sem);
3711        ret = rtl8180_down(dev);
3712        up(&priv->wx_sem);
3713
3714        return ret;
3715}
3716
3717int rtl8180_down(struct net_device *dev)
3718{
3719        struct r8180_priv *priv = ieee80211_priv(dev);
3720
3721        if (priv->up == 0)
3722                return -1;
3723
3724        priv->up=0;
3725
3726        ieee80211_softmac_stop_protocol(priv->ieee80211);
3727        /* FIXME */
3728        if (!netif_queue_stopped(dev))
3729                netif_stop_queue(dev);
3730        rtl8180_rtx_disable(dev);
3731        rtl8180_irq_disable(dev);
3732        del_timer_sync(&priv->watch_dog_timer);
3733        del_timer_sync(&priv->rateadapter_timer);
3734        cancel_delayed_work(&priv->ieee80211->rate_adapter_wq);
3735        cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
3736        cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
3737        cancel_delayed_work(&priv->ieee80211->hw_dig_wq);
3738        cancel_delayed_work(&priv->ieee80211->tx_pw_wq);
3739        del_timer_sync(&priv->SwAntennaDiversityTimer);
3740        SetZebraRFPowerState8185(dev,eRfOff);
3741        memset(&(priv->ieee80211->current_network),0,sizeof(struct ieee80211_network));
3742        priv->ieee80211->state = IEEE80211_NOLINK;
3743        return 0;
3744}
3745
3746void rtl8180_restart_wq(struct work_struct *work)
3747{
3748        struct r8180_priv *priv = container_of(work, struct r8180_priv, reset_wq);
3749        struct net_device *dev = priv->dev;
3750
3751        down(&priv->wx_sem);
3752
3753        rtl8180_commit(dev);
3754
3755        up(&priv->wx_sem);
3756}
3757
3758void rtl8180_restart(struct net_device *dev)
3759{
3760        struct r8180_priv *priv = ieee80211_priv(dev);
3761
3762        schedule_work(&priv->reset_wq);
3763}
3764
3765void rtl8180_commit(struct net_device *dev)
3766{
3767        struct r8180_priv *priv = ieee80211_priv(dev);
3768
3769        if (priv->up == 0)
3770                return ;
3771
3772        del_timer_sync(&priv->watch_dog_timer);
3773        del_timer_sync(&priv->rateadapter_timer);
3774        cancel_delayed_work(&priv->ieee80211->rate_adapter_wq);
3775        cancel_delayed_work(&priv->ieee80211->hw_wakeup_wq);
3776        cancel_delayed_work(&priv->ieee80211->hw_sleep_wq);
3777        cancel_delayed_work(&priv->ieee80211->hw_dig_wq);
3778        cancel_delayed_work(&priv->ieee80211->tx_pw_wq);
3779        del_timer_sync(&priv->SwAntennaDiversityTimer);
3780        ieee80211_softmac_stop_protocol(priv->ieee80211);
3781        rtl8180_irq_disable(dev);
3782        rtl8180_rtx_disable(dev);
3783        _rtl8180_up(dev);
3784}
3785
3786static void r8180_set_multicast(struct net_device *dev)
3787{
3788        struct r8180_priv *priv = ieee80211_priv(dev);
3789        short promisc;
3790
3791        promisc = (dev->flags & IFF_PROMISC) ? 1:0;
3792
3793        if (promisc != priv->promisc)
3794                rtl8180_restart(dev);
3795
3796        priv->promisc = promisc;
3797}
3798
3799int r8180_set_mac_adr(struct net_device *dev, void *mac)
3800{
3801        struct r8180_priv *priv = ieee80211_priv(dev);
3802        struct sockaddr *addr = mac;
3803
3804        down(&priv->wx_sem);
3805
3806        memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
3807
3808        if(priv->ieee80211->iw_mode == IW_MODE_MASTER)
3809                memcpy(priv->ieee80211->current_network.bssid, dev->dev_addr, ETH_ALEN);
3810
3811        if (priv->up) {
3812                rtl8180_down(dev);
3813                rtl8180_up(dev);
3814        }
3815
3816        up(&priv->wx_sem);
3817
3818        return 0;
3819}
3820
3821/* based on ipw2200 driver */
3822int rtl8180_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
3823{
3824        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
3825        struct iwreq *wrq = (struct iwreq *) rq;
3826        int ret=-1;
3827
3828        switch (cmd) {
3829        case RTL_IOCTL_WPA_SUPPLICANT:
3830                ret = ieee80211_wpa_supplicant_ioctl(priv->ieee80211, &wrq->u.data);
3831                return ret;
3832        default:
3833                return -EOPNOTSUPP;
3834        }
3835
3836        return -EOPNOTSUPP;
3837}
3838
3839static const struct net_device_ops rtl8180_netdev_ops = {
3840        .ndo_open               = rtl8180_open,
3841        .ndo_stop               = rtl8180_close,
3842        .ndo_get_stats          = rtl8180_stats,
3843        .ndo_tx_timeout         = rtl8180_restart,
3844        .ndo_do_ioctl           = rtl8180_ioctl,
3845        .ndo_set_multicast_list = r8180_set_multicast,
3846        .ndo_set_mac_address    = r8180_set_mac_adr,
3847        .ndo_validate_addr      = eth_validate_addr,
3848        .ndo_change_mtu         = eth_change_mtu,
3849        .ndo_start_xmit         = ieee80211_xmit,
3850};
3851
3852static int __devinit rtl8180_pci_probe(struct pci_dev *pdev,
3853                                       const struct pci_device_id *id)
3854{
3855        unsigned long ioaddr = 0;
3856        struct net_device *dev = NULL;
3857        struct r8180_priv *priv= NULL;
3858        u8 unit = 0;
3859
3860        unsigned long pmem_start, pmem_len, pmem_flags;
3861
3862        DMESG("Configuring chip resources");
3863
3864        if( pci_enable_device (pdev) ){
3865                DMESG("Failed to enable PCI device");
3866                return -EIO;
3867        }
3868
3869        pci_set_master(pdev);
3870        pci_set_dma_mask(pdev, 0xffffff00ULL);
3871        pci_set_consistent_dma_mask(pdev,0xffffff00ULL);
3872        dev = alloc_ieee80211(sizeof(struct r8180_priv));
3873        if (!dev)
3874                return -ENOMEM;
3875        priv = ieee80211_priv(dev);
3876        priv->ieee80211 = netdev_priv(dev);
3877
3878        pci_set_drvdata(pdev, dev);
3879        SET_NETDEV_DEV(dev, &pdev->dev);
3880
3881        priv = ieee80211_priv(dev);
3882        priv->pdev = pdev;
3883
3884        pmem_start = pci_resource_start(pdev, 1);
3885        pmem_len = pci_resource_len(pdev, 1);
3886        pmem_flags = pci_resource_flags (pdev, 1);
3887
3888        if (!(pmem_flags & IORESOURCE_MEM)) {
3889                DMESG("region #1 not a MMIO resource, aborting");
3890                goto fail;
3891        }
3892
3893        if( ! request_mem_region(pmem_start, pmem_len, RTL8180_MODULE_NAME)) {
3894                DMESG("request_mem_region failed!");
3895                goto fail;
3896        }
3897
3898        ioaddr = (unsigned long)ioremap_nocache( pmem_start, pmem_len);
3899        if( ioaddr == (unsigned long)NULL ){
3900                DMESG("ioremap failed!");
3901                goto fail1;
3902        }
3903
3904        dev->mem_start = ioaddr; // shared mem start
3905        dev->mem_end = ioaddr + pci_resource_len(pdev, 0); // shared mem end
3906
3907        pci_read_config_byte(pdev, 0x05, &unit);
3908        pci_write_config_byte(pdev, 0x05, unit & (~0x04));
3909
3910        dev->irq = pdev->irq;
3911        priv->irq = 0;
3912
3913        dev->netdev_ops = &rtl8180_netdev_ops;
3914        dev->wireless_handlers = &r8180_wx_handlers_def;
3915
3916        dev->type=ARPHRD_ETHER;
3917        dev->watchdog_timeo = HZ*3; //added by david woo, 2007.12.13
3918
3919        if (dev_alloc_name(dev, ifname) < 0){
3920                DMESG("Oops: devname already taken! Trying wlan%%d...\n");
3921                ifname = "wlan%d";
3922                dev_alloc_name(dev, ifname);
3923        }
3924
3925        if(rtl8180_init(dev)!=0){
3926                DMESG("Initialization failed");
3927                goto fail1;
3928        }
3929
3930        netif_carrier_off(dev);
3931
3932        register_netdev(dev);
3933
3934        rtl8180_proc_init_one(dev);
3935
3936        DMESG("Driver probe completed\n");
3937        return 0;
3938fail1:
3939        if( dev->mem_start != (unsigned long)NULL ){
3940                iounmap( (void *)dev->mem_start );
3941                release_mem_region( pci_resource_start(pdev, 1),
3942                                    pci_resource_len(pdev, 1) );
3943        }
3944fail:
3945        if(dev){
3946                if (priv->irq) {
3947                        free_irq(dev->irq, dev);
3948                        dev->irq=0;
3949                }
3950                free_ieee80211(dev);
3951        }
3952
3953        pci_disable_device(pdev);
3954
3955        DMESG("wlan driver load failed\n");
3956        pci_set_drvdata(pdev, NULL);
3957        return -ENODEV;
3958}
3959
3960static void __devexit rtl8180_pci_remove(struct pci_dev *pdev)
3961{
3962        struct r8180_priv *priv;
3963        struct net_device *dev = pci_get_drvdata(pdev);
3964
3965        if (dev) {
3966                unregister_netdev(dev);
3967
3968                priv = ieee80211_priv(dev);
3969
3970                rtl8180_proc_remove_one(dev);
3971                rtl8180_down(dev);
3972                priv->rf_close(dev);
3973                rtl8180_reset(dev);
3974                mdelay(10);
3975
3976                if(priv->irq){
3977                        DMESG("Freeing irq %d",dev->irq);
3978                        free_irq(dev->irq, dev);
3979                        priv->irq=0;
3980                }
3981
3982                free_rx_desc_ring(dev);
3983                free_tx_desc_rings(dev);
3984
3985                if( dev->mem_start != (unsigned long)NULL ){
3986                        iounmap( (void *)dev->mem_start );
3987                        release_mem_region( pci_resource_start(pdev, 1),
3988                                            pci_resource_len(pdev, 1) );
3989                }
3990
3991                free_ieee80211(dev);
3992        }
3993        pci_disable_device(pdev);
3994
3995        DMESG("wlan driver removed\n");
3996}
3997
3998/* fun with the built-in ieee80211 stack... */
3999extern int ieee80211_crypto_init(void);
4000extern void ieee80211_crypto_deinit(void);
4001extern int ieee80211_crypto_tkip_init(void);
4002extern void ieee80211_crypto_tkip_exit(void);
4003extern int ieee80211_crypto_ccmp_init(void);
4004extern void ieee80211_crypto_ccmp_exit(void);
4005extern int ieee80211_crypto_wep_init(void);
4006extern void ieee80211_crypto_wep_exit(void);
4007
4008static int __init rtl8180_pci_module_init(void)
4009{
4010        int ret;
4011
4012        ret = ieee80211_crypto_init();
4013        if (ret) {
4014                printk(KERN_ERR "ieee80211_crypto_init() failed %d\n", ret);
4015                return ret;
4016        }
4017        ret = ieee80211_crypto_tkip_init();
4018        if (ret) {
4019                printk(KERN_ERR "ieee80211_crypto_tkip_init() failed %d\n", ret);
4020                return ret;
4021        }
4022        ret = ieee80211_crypto_ccmp_init();
4023        if (ret) {
4024                printk(KERN_ERR "ieee80211_crypto_ccmp_init() failed %d\n", ret);
4025                return ret;
4026        }
4027        ret = ieee80211_crypto_wep_init();
4028        if (ret) {
4029                printk(KERN_ERR "ieee80211_crypto_wep_init() failed %d\n", ret);
4030                return ret;
4031        }
4032
4033        printk(KERN_INFO "\nLinux kernel driver for RTL8180 \
4034/ RTL8185 based WLAN cards\n");
4035        printk(KERN_INFO "Copyright (c) 2004-2005, Andrea Merello\n");
4036        DMESG("Initializing module");
4037        DMESG("Wireless extensions version %d", WIRELESS_EXT);
4038        rtl8180_proc_module_init();
4039
4040      if (pci_register_driver(&rtl8180_pci_driver)) {
4041                DMESG("No device found");
4042                return -ENODEV;
4043        }
4044        return 0;
4045}
4046
4047static void __exit rtl8180_pci_module_exit(void)
4048{
4049        pci_unregister_driver (&rtl8180_pci_driver);
4050        rtl8180_proc_module_remove();
4051        ieee80211_crypto_tkip_exit();
4052        ieee80211_crypto_ccmp_exit();
4053        ieee80211_crypto_wep_exit();
4054        ieee80211_crypto_deinit();
4055        DMESG("Exiting");
4056}
4057
4058void rtl8180_try_wake_queue(struct net_device *dev, int pri)
4059{
4060        unsigned long flags;
4061        short enough_desc;
4062        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
4063
4064        spin_lock_irqsave(&priv->tx_lock,flags);
4065        enough_desc = check_nic_enought_desc(dev,pri);
4066        spin_unlock_irqrestore(&priv->tx_lock,flags);
4067
4068        if(enough_desc)
4069                ieee80211_wake_queue(priv->ieee80211);
4070}
4071
4072void rtl8180_tx_isr(struct net_device *dev, int pri,short error)
4073{
4074        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
4075        u32 *tail; //tail virtual addr
4076        u32 *head; //head virtual addr
4077        u32 *begin;//start of ring virtual addr
4078        u32 *nicv; //nic pointer virtual addr
4079        u32 nic; //nic pointer physical addr
4080        u32 nicbegin;// start of ring physical addr
4081        unsigned long flag;
4082        /* physical addr are ok on 32 bits since we set DMA mask*/
4083        int offs;
4084        int j,i;
4085        int hd;
4086        if (error) priv->stats.txretry++; //tony 20060601
4087        spin_lock_irqsave(&priv->tx_lock,flag);
4088        switch(pri) {
4089        case MANAGE_PRIORITY:
4090                tail = priv->txmapringtail;
4091                begin = priv->txmapring;
4092                head = priv->txmapringhead;
4093                nic = read_nic_dword(dev,TX_MANAGEPRIORITY_RING_ADDR);
4094                nicbegin = priv->txmapringdma;
4095                break;
4096        case BK_PRIORITY:
4097                tail = priv->txbkpringtail;
4098                begin = priv->txbkpring;
4099                head = priv->txbkpringhead;
4100                nic = read_nic_dword(dev,TX_BKPRIORITY_RING_ADDR);
4101                nicbegin = priv->txbkpringdma;
4102                break;
4103        case BE_PRIORITY:
4104                tail = priv->txbepringtail;
4105                begin = priv->txbepring;
4106                head = priv->txbepringhead;
4107                nic = read_nic_dword(dev,TX_BEPRIORITY_RING_ADDR);
4108                nicbegin = priv->txbepringdma;
4109                break;
4110        case VI_PRIORITY:
4111                tail = priv->txvipringtail;
4112                begin = priv->txvipring;
4113                head = priv->txvipringhead;
4114                nic = read_nic_dword(dev,TX_VIPRIORITY_RING_ADDR);
4115                nicbegin = priv->txvipringdma;
4116                break;
4117        case VO_PRIORITY:
4118                tail = priv->txvopringtail;
4119                begin = priv->txvopring;
4120                head = priv->txvopringhead;
4121                nic = read_nic_dword(dev,TX_VOPRIORITY_RING_ADDR);
4122                nicbegin = priv->txvopringdma;
4123                break;
4124        case HI_PRIORITY:
4125                tail = priv->txhpringtail;
4126                begin = priv->txhpring;
4127                head = priv->txhpringhead;
4128                nic = read_nic_dword(dev,TX_HIGHPRIORITY_RING_ADDR);
4129                nicbegin = priv->txhpringdma;
4130                break;
4131
4132        default:
4133                spin_unlock_irqrestore(&priv->tx_lock,flag);
4134                return ;
4135        }
4136
4137        nicv = (u32*) ((nic - nicbegin) + (u8*)begin);
4138        if((head <= tail && (nicv > tail || nicv < head)) ||
4139                (head > tail && (nicv > tail && nicv < head))){
4140                        DMESGW("nic has lost pointer");
4141                        spin_unlock_irqrestore(&priv->tx_lock,flag);
4142                        rtl8180_restart(dev);
4143                        return;
4144                }
4145
4146        /* we check all the descriptors between the head and the nic,
4147         * but not the currenly pointed by the nic (the next to be txed)
4148         * and the previous of the pointed (might be in process ??)
4149        */
4150        offs = (nic - nicbegin);
4151        offs = offs / 8 /4;
4152        hd = (head - begin) /8;
4153
4154        if(offs >= hd)
4155                j = offs - hd;
4156        else
4157                j = offs + (priv->txringcount -1 -hd);
4158
4159        j-=2;
4160        if(j<0) j=0;
4161
4162        for(i=0;i<j;i++)
4163        {
4164                if((*head) & (1<<31))
4165                        break;
4166                if(((*head)&(0x10000000)) != 0){
4167                        priv->CurrRetryCnt += (u16)((*head) & (0x000000ff));
4168                        if (!error)
4169                                priv->NumTxOkTotal++;
4170                }
4171
4172                if (!error)
4173                        priv->NumTxOkBytesTotal += (*(head+3)) & (0x00000fff);
4174
4175                *head = *head &~ (1<<31);
4176
4177                if((head - begin)/8 == priv->txringcount-1)
4178                        head=begin;
4179                else
4180                        head+=8;
4181        }
4182
4183        /* the head has been moved to the last certainly TXed
4184         * (or at least processed by the nic) packet.
4185         * The driver take forcefully owning of all these packets
4186         * If the packet previous of the nic pointer has been
4187         * processed this doesn't matter: it will be checked
4188         * here at the next round. Anyway if no more packet are
4189         * TXed no memory leak occour at all.
4190         */
4191
4192        switch(pri) {
4193        case MANAGE_PRIORITY:
4194                priv->txmapringhead = head;
4195
4196                if(priv->ack_tx_to_ieee){
4197                        if(rtl8180_is_tx_queue_empty(dev)){
4198                                priv->ack_tx_to_ieee = 0;
4199                                ieee80211_ps_tx_ack(priv->ieee80211,!error);
4200                        }
4201                }
4202                break;
4203        case BK_PRIORITY:
4204                priv->txbkpringhead = head;
4205                break;
4206        case BE_PRIORITY:
4207                priv->txbepringhead = head;
4208                break;
4209        case VI_PRIORITY:
4210                priv->txvipringhead = head;
4211                break;
4212        case VO_PRIORITY:
4213                priv->txvopringhead = head;
4214                break;
4215        case HI_PRIORITY:
4216                priv->txhpringhead = head;
4217                break;
4218        }
4219
4220        spin_unlock_irqrestore(&priv->tx_lock,flag);
4221}
4222
4223void rtl8180_tx_irq_wq(struct work_struct *work)
4224{
4225        struct delayed_work *dwork = to_delayed_work(work);
4226        struct ieee80211_device * ieee = (struct ieee80211_device*)
4227                                               container_of(dwork, struct ieee80211_device, watch_dog_wq);
4228        struct net_device *dev = ieee->dev;
4229
4230        rtl8180_tx_isr(dev,MANAGE_PRIORITY,0);
4231}
4232irqreturn_t rtl8180_interrupt(int irq, void *netdev, struct pt_regs *regs)
4233{
4234        struct net_device *dev = (struct net_device *) netdev;
4235        struct r8180_priv *priv = (struct r8180_priv *)ieee80211_priv(dev);
4236        unsigned long flags;
4237        u32 inta;
4238
4239        /* We should return IRQ_NONE, but for now let me keep this */
4240        if(priv->irq_enabled == 0) return IRQ_HANDLED;
4241
4242        spin_lock_irqsave(&priv->irq_th_lock,flags);
4243
4244        //ISR: 4bytes
4245        inta = read_nic_dword(dev, ISR);// & priv->IntrMask;
4246        write_nic_dword(dev,ISR,inta); // reset int situation
4247
4248        priv->stats.shints++;
4249
4250        if(!inta){
4251                spin_unlock_irqrestore(&priv->irq_th_lock,flags);
4252                return IRQ_HANDLED;
4253        /*
4254           most probably we can safely return IRQ_NONE,
4255           but for now is better to avoid problems
4256        */
4257        }
4258
4259        if (inta == 0xffff) {
4260                /* HW disappared */
4261                spin_unlock_irqrestore(&priv->irq_th_lock, flags);
4262                return IRQ_HANDLED;
4263        }
4264
4265        priv->stats.ints++;
4266
4267        if(!netif_running(dev)) {
4268                spin_unlock_irqrestore(&priv->irq_th_lock,flags);
4269                return IRQ_HANDLED;
4270        }
4271
4272        if (inta & ISR_TimeOut)
4273                write_nic_dword(dev, TimerInt, 0);
4274
4275        if (inta & ISR_TBDOK)
4276                priv->stats.txbeacon++;
4277
4278        if (inta & ISR_TBDER)
4279                priv->stats.txbeaconerr++;
4280
4281        if (inta & IMR_TMGDOK)
4282                rtl8180_tx_isr(dev,MANAGE_PRIORITY,0);
4283
4284        if(inta & ISR_THPDER){
4285                priv->stats.txhperr++;
4286                rtl8180_tx_isr(dev,HI_PRIORITY,1);
4287                priv->ieee80211->stats.tx_errors++;
4288        }
4289
4290        if(inta & ISR_THPDOK){ //High priority tx ok
4291                priv->link_detect.NumTxOkInPeriod++; //YJ,add,080828
4292                priv->stats.txhpokint++;
4293                rtl8180_tx_isr(dev,HI_PRIORITY,0);
4294        }
4295
4296        if(inta & ISR_RER) {
4297                priv->stats.rxerr++;
4298        }
4299        if(inta & ISR_TBKDER){ //corresponding to BK_PRIORITY
4300                priv->stats.txbkperr++;
4301                priv->ieee80211->stats.tx_errors++;
4302                rtl8180_tx_isr(dev,BK_PRIORITY,1);
4303                rtl8180_try_wake_queue(dev, BE_PRIORITY);
4304        }
4305
4306        if(inta & ISR_TBEDER){ //corresponding to BE_PRIORITY
4307                priv->stats.txbeperr++;
4308                priv->ieee80211->stats.tx_errors++;
4309                rtl8180_tx_isr(dev,BE_PRIORITY,1);
4310                rtl8180_try_wake_queue(dev, BE_PRIORITY);
4311        }
4312        if(inta & ISR_TNPDER){ //corresponding to VO_PRIORITY
4313                priv->stats.txnperr++;
4314                priv->ieee80211->stats.tx_errors++;
4315                rtl8180_tx_isr(dev,NORM_PRIORITY,1);
4316                rtl8180_try_wake_queue(dev, NORM_PRIORITY);
4317        }
4318
4319        if(inta & ISR_TLPDER){ //corresponding to VI_PRIORITY
4320                priv->stats.txlperr++;
4321                priv->ieee80211->stats.tx_errors++;
4322                rtl8180_tx_isr(dev,LOW_PRIORITY,1);
4323                rtl8180_try_wake_queue(dev, LOW_PRIORITY);
4324        }
4325
4326        if(inta & ISR_ROK){
4327                priv->stats.rxint++;
4328                tasklet_schedule(&priv->irq_rx_tasklet);
4329        }
4330
4331        if(inta & ISR_RQoSOK ){
4332                priv->stats.rxint++;
4333                tasklet_schedule(&priv->irq_rx_tasklet);
4334        }
4335        if(inta & ISR_BcnInt) {
4336                rtl8180_prepare_beacon(dev);
4337        }
4338
4339        if(inta & ISR_RDU){
4340                DMESGW("No RX descriptor available");
4341                priv->stats.rxrdu++;
4342                tasklet_schedule(&priv->irq_rx_tasklet);
4343        }
4344
4345        if(inta & ISR_RXFOVW){
4346                priv->stats.rxoverflow++;
4347                tasklet_schedule(&priv->irq_rx_tasklet);
4348        }
4349
4350        if (inta & ISR_TXFOVW)
4351                priv->stats.txoverflow++;
4352
4353        if(inta & ISR_TNPDOK){ //Normal priority tx ok
4354                priv->link_detect.NumTxOkInPeriod++; //YJ,add,080828
4355                priv->stats.txnpokint++;
4356                rtl8180_tx_isr(dev,NORM_PRIORITY,0);
4357        }
4358
4359        if(inta & ISR_TLPDOK){ //Low priority tx ok
4360                priv->link_detect.NumTxOkInPeriod++; //YJ,add,080828
4361                priv->stats.txlpokint++;
4362                rtl8180_tx_isr(dev,LOW_PRIORITY,0);
4363                rtl8180_try_wake_queue(dev, LOW_PRIORITY);
4364        }
4365
4366        if(inta & ISR_TBKDOK){ //corresponding to BK_PRIORITY
4367                priv->stats.txbkpokint++;
4368                priv->link_detect.NumTxOkInPeriod++; //YJ,add,080828
4369                rtl8180_tx_isr(dev,BK_PRIORITY,0);
4370                rtl8180_try_wake_queue(dev, BE_PRIORITY);
4371        }
4372
4373        if(inta & ISR_TBEDOK){ //corresponding to BE_PRIORITY
4374                priv->stats.txbeperr++;
4375                priv->link_detect.NumTxOkInPeriod++; //YJ,add,080828
4376                rtl8180_tx_isr(dev,BE_PRIORITY,0);
4377                rtl8180_try_wake_queue(dev, BE_PRIORITY);
4378        }
4379        force_pci_posting(dev);
4380        spin_unlock_irqrestore(&priv->irq_th_lock,flags);
4381
4382        return IRQ_HANDLED;
4383}
4384
4385void rtl8180_irq_rx_tasklet(struct r8180_priv* priv)
4386{
4387        rtl8180_rx(priv->dev);
4388}
4389
4390void GPIOChangeRFWorkItemCallBack(struct work_struct *work)
4391{
4392        struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, GPIOChangeRFWorkItem.work);
4393        struct net_device *dev = ieee->dev;
4394        struct r8180_priv *priv = ieee80211_priv(dev);
4395        u8 btPSR;
4396        u8 btConfig0;
4397        RT_RF_POWER_STATE       eRfPowerStateToSet;
4398        bool    bActuallySet=false;
4399
4400        char *argv[3];
4401        static char *RadioPowerPath = "/etc/acpi/events/RadioPower.sh";
4402        static char *envp[] = {"HOME=/", "TERM=linux", "PATH=/usr/bin:/bin", NULL};
4403        static int readf_count = 0;
4404
4405#ifdef ENABLE_LPS
4406        if(readf_count % 10 == 0)
4407                priv->PowerProfile = read_acadapter_file("/proc/acpi/ac_adapter/AC0/state");
4408
4409        readf_count = (readf_count+1)%0xffff;
4410#endif
4411                {
4412                        // We should turn off LED before polling FF51[4].
4413
4414                        //Turn off LED.
4415                        btPSR = read_nic_byte(dev, PSR);
4416                        write_nic_byte(dev, PSR, (btPSR & ~BIT3));
4417
4418                        //It need to delay 4us suggested by Jong, 2008-01-16
4419                        udelay(4);
4420
4421                        //HW radio On/Off according to the value of FF51[4](config0)
4422                        btConfig0 = btPSR = read_nic_byte(dev, CONFIG0);
4423
4424                        //Turn on LED.
4425                        write_nic_byte(dev, PSR, btPSR| BIT3);
4426
4427                        eRfPowerStateToSet = (btConfig0 & BIT4) ?  eRfOn : eRfOff;
4428
4429                        if((priv->ieee80211->bHwRadioOff == true) && (eRfPowerStateToSet == eRfOn))
4430                        {
4431                                priv->ieee80211->bHwRadioOff = false;
4432                                bActuallySet = true;
4433                        }
4434                        else if((priv->ieee80211->bHwRadioOff == false) && (eRfPowerStateToSet == eRfOff))
4435                        {
4436                                priv->ieee80211->bHwRadioOff = true;
4437                                bActuallySet = true;
4438                        }
4439
4440                        if(bActuallySet)
4441                        {
4442                                MgntActSet_RF_State(dev, eRfPowerStateToSet, RF_CHANGE_BY_HW);
4443
4444                                /* To update the UI status for Power status changed */
4445                                if(priv->ieee80211->bHwRadioOff == true)
4446                                        argv[1] = "RFOFF";
4447                                else{
4448                                        //if(!priv->RfOffReason)
4449                                                argv[1] = "RFON";
4450                                        //else
4451                                        //      argv[1] = "RFOFF";
4452                                }
4453                                argv[0] = RadioPowerPath;
4454                                argv[2] = NULL;
4455
4456                                call_usermodehelper(RadioPowerPath,argv,envp,1);
4457                        }
4458                }
4459}
4460
4461static u8 read_acadapter_file(char *filename)
4462{
4463        return 0;
4464}
4465
4466module_init(rtl8180_pci_module_init);
4467module_exit(rtl8180_pci_module_exit);
4468