main_usb.c revision 9d26d60f99855056a20ac7c0b68eb5ed04619831
1/*
2 * Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
3 * All rights reserved.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * File: main_usb.c
20 *
21 * Purpose: driver entry for initial, open, close, tx and rx.
22 *
23 * Author: Lyndon Chen
24 *
25 * Date: Dec 8, 2005
26 *
27 * Functions:
28 *
29 *   vntwusb_found1 - module initial (insmod) driver entry
30 *   device_remove1 - module remove entry
31 *   device_open - allocate dma/descripter resource & initial mac/bbp function
32 *   device_xmit - asynchrous data tx function
33 *   device_set_multi - set mac filter
34 *   device_ioctl - ioctl entry
35 *   device_close - shutdown mac/bbp & free dma/descripter resource
36 *   device_alloc_frag_buf - rx fragement pre-allocated function
37 *   device_free_tx_bufs - free tx buffer function
38 *   device_dma0_tx_80211- tx 802.11 frame via dma0
39 *   device_dma0_xmit- tx PS bufferred frame via dma0
40 *   device_init_registers- initial MAC & BBP & RF internal registers.
41 *   device_init_rings- initial tx/rx ring buffer
42 *   device_init_defrag_cb- initial & allocate de-fragement buffer.
43 *   device_tx_srv- tx interrupt service function
44 *
45 * Revision History:
46 */
47#undef __NO_VERSION__
48
49#include "device.h"
50#include "card.h"
51#include "tbit.h"
52#include "baseband.h"
53#include "mac.h"
54#include "tether.h"
55#include "wmgr.h"
56#include "wctl.h"
57#include "power.h"
58#include "wcmd.h"
59#include "iocmd.h"
60#include "tcrc.h"
61#include "rxtx.h"
62#include "bssdb.h"
63#include "hostap.h"
64#include "wpactl.h"
65#include "ioctl.h"
66#include "iwctl.h"
67#include "dpc.h"
68#include "iocmd.h"
69#include "datarate.h"
70#include "rf.h"
71#include "firmware.h"
72#include "mac.h"
73#include "rndis.h"
74#include "control.h"
75#include "channel.h"
76#include "int.h"
77#include "iowpa.h"
78
79/*---------------------  Static Definitions -------------------------*/
80//static int          msglevel                =MSG_LEVEL_DEBUG;
81static int          msglevel                =MSG_LEVEL_INFO;
82
83//
84// Define module options
85//
86
87// Version Information
88#define DRIVER_AUTHOR "VIA Networking Technologies, Inc., <lyndonchen@vntek.com.tw>"
89MODULE_AUTHOR(DRIVER_AUTHOR);
90MODULE_LICENSE("GPL");
91MODULE_DESCRIPTION(DEVICE_FULL_DRV_NAM);
92
93#define DEVICE_PARAM(N,D) \
94        static int N[MAX_UINTS]=OPTION_DEFAULT;\
95        module_param_array(N, int, NULL, 0);\
96        MODULE_PARM_DESC(N, D);
97
98#define RX_DESC_MIN0     16
99#define RX_DESC_MAX0     128
100#define RX_DESC_DEF0     64
101DEVICE_PARAM(RxDescriptors0,"Number of receive usb desc buffer");
102
103
104#define TX_DESC_MIN0     16
105#define TX_DESC_MAX0     128
106#define TX_DESC_DEF0     64
107DEVICE_PARAM(TxDescriptors0,"Number of transmit usb desc buffer");
108
109
110#define CHANNEL_MIN     1
111#define CHANNEL_MAX     14
112#define CHANNEL_DEF     6
113
114DEVICE_PARAM(Channel, "Channel number");
115
116
117/* PreambleType[] is the preamble length used for transmit.
118   0: indicate allows long preamble type
119   1: indicate allows short preamble type
120*/
121
122#define PREAMBLE_TYPE_DEF     1
123
124DEVICE_PARAM(PreambleType, "Preamble Type");
125
126
127#define RTS_THRESH_MIN     512
128#define RTS_THRESH_MAX     2347
129#define RTS_THRESH_DEF     2347
130
131DEVICE_PARAM(RTSThreshold, "RTS threshold");
132
133
134#define FRAG_THRESH_MIN     256
135#define FRAG_THRESH_MAX     2346
136#define FRAG_THRESH_DEF     2346
137
138DEVICE_PARAM(FragThreshold, "Fragmentation threshold");
139
140
141#define DATA_RATE_MIN     0
142#define DATA_RATE_MAX     13
143#define DATA_RATE_DEF     13
144/* datarate[] index
145   0: indicate 1 Mbps   0x02
146   1: indicate 2 Mbps   0x04
147   2: indicate 5.5 Mbps 0x0B
148   3: indicate 11 Mbps  0x16
149   4: indicate 6 Mbps   0x0c
150   5: indicate 9 Mbps   0x12
151   6: indicate 12 Mbps  0x18
152   7: indicate 18 Mbps  0x24
153   8: indicate 24 Mbps  0x30
154   9: indicate 36 Mbps  0x48
155  10: indicate 48 Mbps  0x60
156  11: indicate 54 Mbps  0x6c
157  12: indicate 72 Mbps  0x90
158  13: indicate auto rate
159*/
160
161DEVICE_PARAM(ConnectionRate, "Connection data rate");
162
163#define OP_MODE_MAX     2
164#define OP_MODE_DEF     0
165#define OP_MODE_MIN     0
166
167DEVICE_PARAM(OPMode, "Infrastruct, adhoc, AP mode ");
168
169/* OpMode[] is used for transmit.
170   0: indicate infrastruct mode used
171   1: indicate adhoc mode used
172   2: indicate AP mode used
173*/
174
175
176/* PSMode[]
177   0: indicate disable power saving mode
178   1: indicate enable power saving mode
179*/
180
181#define PS_MODE_DEF     0
182
183DEVICE_PARAM(PSMode, "Power saving mode");
184
185
186#define SHORT_RETRY_MIN     0
187#define SHORT_RETRY_MAX     31
188#define SHORT_RETRY_DEF     8
189
190
191DEVICE_PARAM(ShortRetryLimit, "Short frame retry limits");
192
193#define LONG_RETRY_MIN     0
194#define LONG_RETRY_MAX     15
195#define LONG_RETRY_DEF     4
196
197
198DEVICE_PARAM(LongRetryLimit, "long frame retry limits");
199
200
201/* BasebandType[] baseband type selected
202   0: indicate 802.11a type
203   1: indicate 802.11b type
204   2: indicate 802.11g type
205*/
206#define BBP_TYPE_MIN     0
207#define BBP_TYPE_MAX     2
208#define BBP_TYPE_DEF     2
209
210DEVICE_PARAM(BasebandType, "baseband type");
211
212
213
214/* 80211hEnable[]
215   0: indicate disable 802.11h
216   1: indicate enable 802.11h
217*/
218
219#define X80211h_MODE_DEF     0
220
221DEVICE_PARAM(b80211hEnable, "802.11h mode");
222
223
224//
225// Static vars definitions
226//
227
228
229
230static struct usb_device_id vntwusb_table[] = {
231	{USB_DEVICE(VNT_USB_VENDOR_ID, VNT_USB_PRODUCT_ID)},
232	{}
233};
234
235
236
237// Frequency list (map channels to frequencies)
238/*
239static const long frequency_list[] = {
240    2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462, 2467, 2472, 2484,
241    4915, 4920, 4925, 4935, 4940, 4945, 4960, 4980,
242    5035, 5040, 5045, 5055, 5060, 5080, 5170, 5180, 5190, 5200, 5210, 5220, 5230, 5240,
243    5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680,
244    5700, 5745, 5765, 5785, 5805, 5825
245	};
246
247
248#ifndef IW_ENCODE_NOKEY
249#define IW_ENCODE_NOKEY         0x0800
250#define IW_ENCODE_MODE  (IW_ENCODE_DISABLED | IW_ENCODE_RESTRICTED | IW_ENCODE_OPEN)
251#endif
252
253static const struct iw_handler_def	iwctl_handler_def;
254*/
255
256
257
258/*---------------------  Static Functions  --------------------------*/
259static int vntwusb_found1(struct usb_interface *intf, const struct usb_device_id *id);
260static void vntwusb_disconnect(struct usb_interface *intf);
261#ifdef CONFIG_PM	/* Minimal support for suspend and resume */
262static int vntwusb_suspend(struct usb_interface *intf, pm_message_t message);
263static int vntwusb_resume(struct usb_interface *intf);
264#endif
265static struct net_device_stats *device_get_stats(struct net_device *dev);
266static int  device_open(struct net_device *dev);
267static int  device_xmit(struct sk_buff *skb, struct net_device *dev);
268static void device_set_multi(struct net_device *dev);
269static int  device_close(struct net_device *dev);
270static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
271
272static BOOL device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType);
273static BOOL device_init_defrag_cb(PSDevice pDevice);
274static void device_init_diversity_timer(PSDevice pDevice);
275static int  device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev);
276
277static int  ethtool_ioctl(struct net_device *dev, void *useraddr);
278static void device_free_tx_bufs(PSDevice pDevice);
279static void device_free_rx_bufs(PSDevice pDevice);
280static void device_free_int_bufs(PSDevice pDevice);
281static void device_free_frag_bufs(PSDevice pDevice);
282static BOOL device_alloc_bufs(PSDevice pDevice);
283
284static int Read_config_file(PSDevice pDevice);
285static UCHAR *Config_FileOperation(PSDevice pDevice);
286static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source);
287
288//2008-0714<Add>by Mike Liu
289static BOOL device_release_WPADEV(PSDevice pDevice);
290
291static void usb_device_reset(PSDevice pDevice);
292
293
294
295/*---------------------  Export Variables  --------------------------*/
296
297/*---------------------  Export Functions  --------------------------*/
298
299
300static void
301device_set_options(PSDevice pDevice) {
302
303    BYTE    abyBroadcastAddr[U_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
304    BYTE    abySNAP_RFC1042[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
305    BYTE    abySNAP_Bridgetunnel[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0xF8};
306
307
308    memcpy(pDevice->abyBroadcastAddr, abyBroadcastAddr, U_ETHER_ADDR_LEN);
309    memcpy(pDevice->abySNAP_RFC1042, abySNAP_RFC1042, U_ETHER_ADDR_LEN);
310    memcpy(pDevice->abySNAP_Bridgetunnel, abySNAP_Bridgetunnel, U_ETHER_ADDR_LEN);
311
312    pDevice->cbTD = TX_DESC_DEF0;
313    pDevice->cbRD = RX_DESC_DEF0;
314    pDevice->uChannel = CHANNEL_DEF;
315    pDevice->wRTSThreshold = RTS_THRESH_DEF;
316    pDevice->wFragmentationThreshold = FRAG_THRESH_DEF;
317    pDevice->byShortRetryLimit = SHORT_RETRY_DEF;
318    pDevice->byLongRetryLimit = LONG_RETRY_DEF;
319    pDevice->wMaxTransmitMSDULifetime = DEFAULT_MSDU_LIFETIME;
320    pDevice->byShortPreamble = PREAMBLE_TYPE_DEF;
321    pDevice->ePSMode = PS_MODE_DEF;
322    pDevice->b11hEnable = X80211h_MODE_DEF;
323    pDevice->eOPMode = OP_MODE_DEF;
324    pDevice->uConnectionRate = DATA_RATE_DEF;
325    if (pDevice->uConnectionRate < RATE_AUTO) pDevice->bFixRate = TRUE;
326    pDevice->byBBType = BBP_TYPE_DEF;
327    pDevice->byPacketType = pDevice->byBBType;
328    pDevice->byAutoFBCtrl = AUTO_FB_0;
329    pDevice->bUpdateBBVGA = TRUE;
330    pDevice->byFOETuning = 0;
331    pDevice->byAutoPwrTunning = 0;
332    pDevice->wCTSDuration = 0;
333    pDevice->byPreambleType = 0;
334    pDevice->bExistSWNetAddr = FALSE;
335//    pDevice->bDiversityRegCtlON = TRUE;
336    pDevice->bDiversityRegCtlON = FALSE;
337}
338
339
340static VOID device_init_diversity_timer(PSDevice pDevice) {
341
342    init_timer(&pDevice->TimerSQ3Tmax1);
343    pDevice->TimerSQ3Tmax1.data = (ULONG)pDevice;
344    pDevice->TimerSQ3Tmax1.function = (TimerFunction)TimerSQ3CallBack;
345    pDevice->TimerSQ3Tmax1.expires = RUN_AT(HZ);
346
347    init_timer(&pDevice->TimerSQ3Tmax2);
348    pDevice->TimerSQ3Tmax2.data = (ULONG)pDevice;
349    pDevice->TimerSQ3Tmax2.function = (TimerFunction)TimerSQ3CallBack;
350    pDevice->TimerSQ3Tmax2.expires = RUN_AT(HZ);
351
352    init_timer(&pDevice->TimerSQ3Tmax3);
353    pDevice->TimerSQ3Tmax3.data = (ULONG)pDevice;
354    pDevice->TimerSQ3Tmax3.function = (TimerFunction)TimerSQ3Tmax3CallBack;
355    pDevice->TimerSQ3Tmax3.expires = RUN_AT(HZ);
356
357    return;
358}
359
360
361//
362// Initialiation of MAC & BBP registers
363//
364
365static BOOL device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType)
366{
367    BYTE            abyBroadcastAddr[U_ETHER_ADDR_LEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
368    BYTE            abySNAP_RFC1042[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
369    BYTE            abySNAP_Bridgetunnel[U_ETHER_ADDR_LEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0xF8};
370    BYTE            byAntenna;
371    UINT            ii;
372    CMD_CARD_INIT   sInitCmd;
373    NTSTATUS        ntStatus = STATUS_SUCCESS;
374    RSP_CARD_INIT   sInitRsp;
375    PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
376    BYTE            byTmp;
377    BYTE            byCalibTXIQ = 0;
378    BYTE            byCalibTXDC = 0;
379    BYTE            byCalibRXIQ = 0;
380
381    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "---->INIbInitAdapter. [%d][%d]\n", InitType, pDevice->byPacketType);
382	spin_lock_irq(&pDevice->lock);
383    if (InitType == DEVICE_INIT_COLD) {
384        memcpy(pDevice->abyBroadcastAddr, abyBroadcastAddr, U_ETHER_ADDR_LEN);
385        memcpy(pDevice->abySNAP_RFC1042, abySNAP_RFC1042, U_ETHER_ADDR_LEN);
386        memcpy(pDevice->abySNAP_Bridgetunnel, abySNAP_Bridgetunnel, U_ETHER_ADDR_LEN);
387
388        if ( !FIRMWAREbCheckVersion(pDevice) ) {
389            if (FIRMWAREbDownload(pDevice) == TRUE) {
390                if (FIRMWAREbBrach2Sram(pDevice) == FALSE) {
391                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" FIRMWAREbBrach2Sram fail \n");
392                  	spin_unlock_irq(&pDevice->lock);
393                    return FALSE;
394                }
395            } else {
396
397                DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" FIRMWAREbDownload fail \n");
398                spin_unlock_irq(&pDevice->lock);
399                return FALSE;
400            }
401        }
402
403        if ( !BBbVT3184Init(pDevice) ) {
404            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" BBbVT3184Init fail \n");
405            spin_unlock_irq(&pDevice->lock);
406            return FALSE;
407        }
408    }
409
410    sInitCmd.byInitClass = (BYTE)InitType;
411    sInitCmd.bExistSWNetAddr = (BYTE) pDevice->bExistSWNetAddr;
412    for(ii=0;ii<6;ii++)
413        sInitCmd.bySWNetAddr[ii] = pDevice->abyCurrentNetAddr[ii];
414    sInitCmd.byShortRetryLimit = pDevice->byShortRetryLimit;
415    sInitCmd.byLongRetryLimit = pDevice->byLongRetryLimit;
416
417    //issue Card_init command to device
418    ntStatus = CONTROLnsRequestOut(pDevice,
419                                    MESSAGE_TYPE_CARDINIT,
420                                    0,
421                                    0,
422                                    sizeof(CMD_CARD_INIT),
423                                    (PBYTE) &(sInitCmd));
424
425    if ( ntStatus != STATUS_SUCCESS ) {
426        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Issue Card init fail \n");
427        spin_unlock_irq(&pDevice->lock);
428        return FALSE;
429    }
430    if (InitType == DEVICE_INIT_COLD) {
431
432        ntStatus = CONTROLnsRequestIn(pDevice,MESSAGE_TYPE_INIT_RSP,0,0,sizeof(RSP_CARD_INIT), (PBYTE) &(sInitRsp));
433
434        if (ntStatus != STATUS_SUCCESS) {
435            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Cardinit request in status fail!\n");
436            spin_unlock_irq(&pDevice->lock);
437            return FALSE;
438        }
439
440        //Local ID for AES functions
441        ntStatus = CONTROLnsRequestIn(pDevice,
442                                    MESSAGE_TYPE_READ,
443                                    MAC_REG_LOCALID,
444                                    MESSAGE_REQUEST_MACREG,
445                                    1,
446                                    &pDevice->byLocalID);
447
448        if ( ntStatus != STATUS_SUCCESS ) {
449            spin_unlock_irq(&pDevice->lock);
450            return FALSE;
451        }
452
453        // Do MACbSoftwareReset in MACvInitialize
454        // force CCK
455        pDevice->bCCK = TRUE;
456        pDevice->bProtectMode = FALSE;          //Only used in 11g type, sync with ERP IE
457        pDevice->bNonERPPresent = FALSE;
458        pDevice->bBarkerPreambleMd = FALSE;
459        if ( pDevice->bFixRate ) {
460            pDevice->wCurrentRate = (WORD) pDevice->uConnectionRate;
461        } else {
462            if ( pDevice->byBBType == BB_TYPE_11B )
463                pDevice->wCurrentRate = RATE_11M;
464            else
465                pDevice->wCurrentRate = RATE_54M;
466        }
467
468        CHvInitChannelTable(pDevice);
469
470        pDevice->byTopOFDMBasicRate = RATE_24M;
471        pDevice->byTopCCKBasicRate = RATE_1M;
472        pDevice->byRevId = 0;                   //Target to IF pin while programming to RF chip.
473        pDevice->byCurPwr = 0xFF;
474
475        pDevice->byCCKPwr = pDevice->abyEEPROM[EEP_OFS_PWR_CCK];
476        pDevice->byOFDMPwrG = pDevice->abyEEPROM[EEP_OFS_PWR_OFDMG];
477        // Load power Table
478        for (ii=0;ii<14;ii++) {
479            pDevice->abyCCKPwrTbl[ii] = pDevice->abyEEPROM[ii + EEP_OFS_CCK_PWR_TBL];
480            if (pDevice->abyCCKPwrTbl[ii] == 0)
481                pDevice->abyCCKPwrTbl[ii] = pDevice->byCCKPwr;
482            pDevice->abyOFDMPwrTbl[ii] = pDevice->abyEEPROM[ii + EEP_OFS_OFDM_PWR_TBL];
483            if (pDevice->abyOFDMPwrTbl[ii] == 0)
484                pDevice->abyOFDMPwrTbl[ii] = pDevice->byOFDMPwrG;
485        }
486
487	  //original zonetype is USA,but customize zonetype is europe,
488	  // then need recover 12,13 ,14 channel  with 11 channel
489          if(((pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Japan) ||
490	        (pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Europe))&&
491	     (pDevice->byOriginalZonetype == ZoneType_USA)) {
492	    for(ii=11;ii<14;ii++) {
493                pDevice->abyCCKPwrTbl[ii] = pDevice->abyCCKPwrTbl[10];
494	       pDevice->abyOFDMPwrTbl[ii] = pDevice->abyOFDMPwrTbl[10];
495	    }
496	  }
497
498        //{{ RobertYu: 20041124
499        pDevice->byOFDMPwrA = 0x34; // same as RFbMA2829SelectChannel
500        // Load OFDM A Power Table
501        for (ii=0;ii<CB_MAX_CHANNEL_5G;ii++) { //RobertYu:20041224, bug using CB_MAX_CHANNEL
502            pDevice->abyOFDMAPwrTbl[ii] = pDevice->abyEEPROM[ii + EEP_OFS_OFDMA_PWR_TBL];
503            if (pDevice->abyOFDMAPwrTbl[ii] == 0)
504                pDevice->abyOFDMAPwrTbl[ii] = pDevice->byOFDMPwrA;
505        }
506        //}} RobertYu
507
508        byAntenna = pDevice->abyEEPROM[EEP_OFS_ANTENNA];
509        if (byAntenna & EEP_ANTINV)
510            pDevice->bTxRxAntInv = TRUE;
511        else
512            pDevice->bTxRxAntInv = FALSE;
513
514        byAntenna &= (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
515
516        if (byAntenna == 0) // if not set default is All
517            byAntenna = (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
518
519        if (byAntenna == (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN)) {
520            pDevice->byAntennaCount = 2;
521            pDevice->byTxAntennaMode = ANT_B;
522            pDevice->dwTxAntennaSel = 1;
523            pDevice->dwRxAntennaSel = 1;
524            if (pDevice->bTxRxAntInv == TRUE)
525                pDevice->byRxAntennaMode = ANT_A;
526            else
527                pDevice->byRxAntennaMode = ANT_B;
528
529            if (pDevice->bDiversityRegCtlON)
530                pDevice->bDiversityEnable = TRUE;
531            else
532                pDevice->bDiversityEnable = FALSE;
533        } else  {
534            pDevice->bDiversityEnable = FALSE;
535            pDevice->byAntennaCount = 1;
536            pDevice->dwTxAntennaSel = 0;
537            pDevice->dwRxAntennaSel = 0;
538            if (byAntenna & EEP_ANTENNA_AUX) {
539                pDevice->byTxAntennaMode = ANT_A;
540                if (pDevice->bTxRxAntInv == TRUE)
541                    pDevice->byRxAntennaMode = ANT_B;
542                else
543                    pDevice->byRxAntennaMode = ANT_A;
544            } else {
545                pDevice->byTxAntennaMode = ANT_B;
546                if (pDevice->bTxRxAntInv == TRUE)
547                    pDevice->byRxAntennaMode = ANT_A;
548                else
549                    pDevice->byRxAntennaMode = ANT_B;
550            }
551        }
552        pDevice->ulDiversityNValue = 100*255;
553        pDevice->ulDiversityMValue = 100*16;
554        pDevice->byTMax = 1;
555        pDevice->byTMax2 = 4;
556        pDevice->ulSQ3TH = 0;
557        pDevice->byTMax3 = 64;
558        // -----------------------------------------------------------------
559
560        //Get Auto Fall Back Type
561        pDevice->byAutoFBCtrl = AUTO_FB_0;
562
563        // Set SCAN Time
564        pDevice->uScanTime = WLAN_SCAN_MINITIME;
565
566        // default Auto Mode
567        //pDevice->NetworkType = Ndis802_11Automode;
568        pDevice->eConfigPHYMode = PHY_TYPE_AUTO;
569        pDevice->byBBType = BB_TYPE_11G;
570
571        // initialize BBP registers
572        pDevice->ulTxPower = 25;
573
574        // Get Channel range
575        pDevice->byMinChannel = 1;
576        pDevice->byMaxChannel = CB_MAX_CHANNEL;
577
578        // Get RFType
579        pDevice->byRFType = sInitRsp.byRFType;
580
581        if ((pDevice->byRFType & RF_EMU) != 0) {
582            // force change RevID for VT3253 emu
583            pDevice->byRevId = 0x80;
584        }
585
586        // Load EEPROM calibrated vt3266 parameters
587        if (pDevice->byRFType == RF_VT3226D0) {
588            if((pDevice->abyEEPROM[EEP_OFS_MAJOR_VER] == 0x1) &&
589                (pDevice->abyEEPROM[EEP_OFS_MINOR_VER] >= 0x4)) {
590                byCalibTXIQ = pDevice->abyEEPROM[EEP_OFS_CALIB_TX_IQ];
591                byCalibTXDC = pDevice->abyEEPROM[EEP_OFS_CALIB_TX_DC];
592                byCalibRXIQ = pDevice->abyEEPROM[EEP_OFS_CALIB_RX_IQ];
593                if( (byCalibTXIQ || byCalibTXDC || byCalibRXIQ) ) {
594                    ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xFF, 0x03); // CR255, Set BB to support TX/RX IQ and DC compensation Mode
595                    ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xFB, byCalibTXIQ); // CR251, TX I/Q Imbalance Calibration
596                    ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xFC, byCalibTXDC); // CR252, TX DC-Offset Calibration
597                    ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xFD, byCalibRXIQ); // CR253, RX I/Q Imbalance Calibration
598                } else {
599                // turn off BB Calibration compensation
600                    ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xFF, 0x0); // CR255
601                }
602            }
603        }
604        pMgmt->eScanType = WMAC_SCAN_PASSIVE;
605        pMgmt->uCurrChannel = pDevice->uChannel;
606        pMgmt->uIBSSChannel = pDevice->uChannel;
607        CARDbSetMediaChannel(pDevice, pMgmt->uCurrChannel);
608
609        // get Permanent network address
610        MEMvCopy(pDevice->abyPermanentNetAddr,&(sInitRsp.byNetAddr[0]),6)
611        MEMvCopy(pDevice->abyCurrentNetAddr, pDevice->abyPermanentNetAddr, U_ETHER_ADDR_LEN);
612
613        // if exist SW network address, use SW network address.
614
615        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Network address = %02x-%02x-%02x=%02x-%02x-%02x\n",
616            pDevice->abyCurrentNetAddr[0],
617            pDevice->abyCurrentNetAddr[1],
618            pDevice->abyCurrentNetAddr[2],
619            pDevice->abyCurrentNetAddr[3],
620            pDevice->abyCurrentNetAddr[4],
621            pDevice->abyCurrentNetAddr[5]);
622    }
623
624
625
626    // Set BB and packet type at the same time.
627    // Set Short Slot Time, xIFS, and RSPINF.
628    if (pDevice->byBBType == BB_TYPE_11A) {
629        CARDbAddBasicRate(pDevice, RATE_6M);
630        pDevice->bShortSlotTime = TRUE;
631    } else {
632        CARDbAddBasicRate(pDevice, RATE_1M);
633        pDevice->bShortSlotTime = FALSE;
634    }
635    BBvSetShortSlotTime(pDevice);
636    CARDvSetBSSMode(pDevice);
637
638    if (pDevice->bUpdateBBVGA) {
639        pDevice->byBBVGACurrent = pDevice->abyBBVGA[0];
640        pDevice->byBBVGANew = pDevice->byBBVGACurrent;
641        BBvSetVGAGainOffset(pDevice, pDevice->abyBBVGA[0]);
642    }
643
644    pDevice->byRadioCtl = pDevice->abyEEPROM[EEP_OFS_RADIOCTL];
645    pDevice->bHWRadioOff = FALSE;
646    if ( (pDevice->byRadioCtl & EEP_RADIOCTL_ENABLE) != 0 ) {
647        ntStatus = CONTROLnsRequestIn(pDevice,
648                                    MESSAGE_TYPE_READ,
649                                    MAC_REG_GPIOCTL1,
650                                    MESSAGE_REQUEST_MACREG,
651                                    1,
652                                    &byTmp);
653
654        if ( ntStatus != STATUS_SUCCESS ) {
655            spin_unlock_irq(&pDevice->lock);
656            return FALSE;
657        }
658        if ( (byTmp & GPIO3_DATA) == 0 ) {
659            pDevice->bHWRadioOff = TRUE;
660            MACvRegBitsOn(pDevice,MAC_REG_GPIOCTL1,GPIO3_INTMD);
661        } else {
662            MACvRegBitsOff(pDevice,MAC_REG_GPIOCTL1,GPIO3_INTMD);
663            pDevice->bHWRadioOff = FALSE;
664        }
665
666    } //EEP_RADIOCTL_ENABLE
667
668    ControlvMaskByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_PAPEDELAY,LEDSTS_TMLEN,0x38);
669    ControlvMaskByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_PAPEDELAY,LEDSTS_STS,LEDSTS_SLOW);
670    MACvRegBitsOn(pDevice,MAC_REG_GPIOCTL0,0x01);
671
672    if ((pDevice->bHWRadioOff == TRUE) || (pDevice->bRadioControlOff == TRUE)) {
673        CARDbRadioPowerOff(pDevice);
674    } else {
675        CARDbRadioPowerOn(pDevice);
676    }
677
678    spin_unlock_irq(&pDevice->lock);
679    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"<----INIbInitAdapter Exit\n");
680    return TRUE;
681}
682
683static BOOL device_release_WPADEV(PSDevice pDevice)
684{
685  viawget_wpa_header *wpahdr;
686  int ii=0;
687 // wait_queue_head_t	Set_wait;
688  //send device close to wpa_supplicnat layer
689    if (pDevice->bWPADEVUp==TRUE) {
690                 wpahdr = (viawget_wpa_header *)pDevice->skb->data;
691                 wpahdr->type = VIAWGET_DEVICECLOSE_MSG;
692                 wpahdr->resp_ie_len = 0;
693                 wpahdr->req_ie_len = 0;
694                 skb_put(pDevice->skb, sizeof(viawget_wpa_header));
695                 pDevice->skb->dev = pDevice->wpadev;
696		 skb_reset_mac_header(pDevice->skb);
697                 pDevice->skb->pkt_type = PACKET_HOST;
698                 pDevice->skb->protocol = htons(ETH_P_802_2);
699                 memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
700                 netif_rx(pDevice->skb);
701                 pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
702
703 //wait release WPADEV
704              //    init_waitqueue_head(&Set_wait);
705              //    wait_event_timeout(Set_wait, ((pDevice->wpadev==NULL)&&(pDevice->skb == NULL)),5*HZ);    //1s wait
706              while(pDevice->bWPADEVUp==TRUE) {
707	        set_current_state(TASK_UNINTERRUPTIBLE);
708                 schedule_timeout (HZ/20);          //wait 50ms
709                 ii++;
710	        if(ii>20)
711		  break;
712              }
713           };
714    return TRUE;
715}
716
717#ifdef CONFIG_PM	/* Minimal support for suspend and resume */
718static int vntwusb_suspend(struct usb_interface *intf, pm_message_t message)
719{
720 PSDevice  pDevice = usb_get_intfdata(intf);
721 struct net_device *dev = pDevice->dev;
722
723 printk("VNTWUSB Suspend Start======>\n");
724if(dev != NULL) {
725  if(pDevice->flags & DEVICE_FLAGS_OPENED)
726     device_close(dev);
727}
728
729 usb_put_dev(interface_to_usbdev(intf));
730 return 0;
731}
732
733static int vntwusb_resume(struct usb_interface *intf)
734{
735 PSDevice  pDevice = usb_get_intfdata(intf);
736 struct net_device *dev = pDevice->dev;
737
738 printk("VNTWUSB Resume Start======>\n");
739 if(dev != NULL) {
740  usb_get_dev(interface_to_usbdev(intf));
741  if(!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
742    if(device_open(dev)!=0)
743        printk("VNTWUSB Resume Start======>open fail\n");
744   }
745 }
746 return 0;
747}
748#endif
749
750
751static const struct net_device_ops device_netdev_ops = {
752    .ndo_open               = device_open,
753    .ndo_stop               = device_close,
754    .ndo_do_ioctl           = device_ioctl,
755    .ndo_get_stats          = device_get_stats,
756    .ndo_start_xmit         = device_xmit,
757    .ndo_set_multicast_list = device_set_multi,
758};
759
760
761static int
762vntwusb_found1(struct usb_interface *intf, const struct usb_device_id *id)
763{
764   BYTE            fake_mac[U_ETHER_ADDR_LEN] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x01};//fake MAC address
765	struct usb_device *udev = interface_to_usbdev(intf);
766    int         rc = 0;
767    struct net_device *netdev = NULL;
768    PSDevice    pDevice = NULL;
769
770
771    printk(KERN_NOTICE "%s Ver. %s\n",DEVICE_FULL_DRV_NAM, DEVICE_VERSION);
772    printk(KERN_NOTICE "Copyright (c) 2004 VIA Networking Technologies, Inc.\n");
773
774  udev = usb_get_dev(udev);
775
776    netdev = alloc_etherdev(sizeof(DEVICE_INFO));
777
778    if (netdev == NULL) {
779        printk(KERN_ERR DEVICE_NAME ": allocate net device failed \n");
780        kfree(pDevice);
781	    goto err_nomem;
782    }
783
784    pDevice = netdev_priv(netdev);
785    memset(pDevice, 0, sizeof(DEVICE_INFO));
786
787    pDevice->dev = netdev;
788    pDevice->usb = udev;
789
790    // Set initial settings
791    device_set_options(pDevice);
792    spin_lock_init(&pDevice->lock);
793
794    pDevice->tx_80211 = device_dma0_tx_80211;
795    pDevice->sMgmtObj.pAdapter = (PVOID)pDevice;
796
797    netdev->netdev_ops         = &device_netdev_ops;
798
799	netdev->wireless_handlers = (struct iw_handler_def *)&iwctl_handler_def;
800
801   //2008-0623-01<Remark>by MikeLiu
802  //2007-0821-01<Add>by MikeLiu
803         usb_set_intfdata(intf, pDevice);
804	SET_NETDEV_DEV(netdev, &intf->dev);
805    memcpy(pDevice->dev->dev_addr, fake_mac, U_ETHER_ADDR_LEN); //use fake mac address
806    rc = register_netdev(netdev);
807    if (rc != 0) {
808        printk(KERN_ERR DEVICE_NAME " Failed to register netdev\n");
809		free_netdev(netdev);
810        kfree(pDevice);
811        return -ENODEV;
812    }
813	//2008-0623-02<Remark>by MikeLiu
814        //2007-0821-01<Add>by MikeLiu
815       //#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,21)
816  	//usb_set_intfdata(intf, pDevice);
817	//SET_NETDEV_DEV(netdev, &intf->dev);
818       //#endif
819
820//2008-07-21-01<Add>by MikeLiu
821//register wpadev
822#if 0
823   if(wpa_set_wpadev(pDevice, 1)!=0) {
824     printk("Fail to Register WPADEV?\n");
825        unregister_netdev(pDevice->dev);
826        free_netdev(netdev);
827        kfree(pDevice);
828   }
829#endif
830         usb_device_reset(pDevice);
831
832#ifdef SndEvt_ToAPI
833{
834  union iwreq_data      wrqu;
835  memset(&wrqu, 0, sizeof(wrqu));
836  wrqu.data.flags = RT_INSMOD_EVENT_FLAG;
837  wrqu.data.length =IFNAMSIZ;
838  wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, pDevice->dev->name);
839}
840#endif
841
842	return 0;
843
844
845err_nomem:
846 //2008-0922-01<Add>by MikeLiu, decrease usb counter.
847    usb_put_dev(udev);
848
849    return -ENOMEM;
850}
851
852
853static VOID device_free_tx_bufs(PSDevice pDevice) {
854    PUSB_SEND_CONTEXT pTxContext;
855    int ii;
856
857    for (ii = 0; ii < pDevice->cbTD; ii++) {
858
859        pTxContext = pDevice->apTD[ii];
860        //de-allocate URBs
861        if (pTxContext->pUrb) {
862            vntwusb_unlink_urb(pTxContext->pUrb);
863            usb_free_urb(pTxContext->pUrb);
864        }
865        if (pTxContext)
866            kfree(pTxContext);
867    }
868    return;
869}
870
871
872static VOID device_free_rx_bufs(PSDevice pDevice) {
873    PRCB pRCB;
874    int ii;
875
876    for (ii = 0; ii < pDevice->cbRD; ii++) {
877
878        pRCB = pDevice->apRCB[ii];
879        //de-allocate URBs
880        if (pRCB->pUrb) {
881            vntwusb_unlink_urb(pRCB->pUrb);
882            usb_free_urb(pRCB->pUrb);
883        }
884        //de-allocate skb
885        if (pRCB->skb)
886            dev_kfree_skb(pRCB->skb);
887    }
888    if (pDevice->pRCBMem)
889        kfree(pDevice->pRCBMem);
890
891    return;
892}
893
894//2007-1107-02<Add>by MikeLiu
895static void usb_device_reset(PSDevice pDevice)
896{
897 int status;
898 status = usb_reset_device(pDevice->usb);
899	if (status)
900            printk("usb_device_reset fail status=%d\n",status);
901	return ;
902}
903
904static VOID device_free_int_bufs(PSDevice pDevice) {
905
906    if (pDevice->intBuf.pDataBuf != NULL)
907        kfree(pDevice->intBuf.pDataBuf);
908    return;
909}
910
911
912static BOOL device_alloc_bufs(PSDevice pDevice) {
913
914    PUSB_SEND_CONTEXT pTxContext;
915    PRCB pRCB;
916    int ii;
917
918
919    for (ii = 0; ii < pDevice->cbTD; ii++) {
920
921        pTxContext = kmalloc(sizeof(USB_SEND_CONTEXT), GFP_KERNEL);
922        if (pTxContext == NULL) {
923            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s : allocate tx usb context failed\n", pDevice->dev->name);
924            goto free_tx;
925        }
926        pDevice->apTD[ii] = pTxContext;
927        pTxContext->pDevice = (PVOID) pDevice;
928        //allocate URBs
929        pTxContext->pUrb = vntwusb_alloc_urb(0);;
930        if (pTxContext->pUrb == NULL) {
931            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "alloc tx urb failed\n");
932            goto free_tx;
933        }
934        pTxContext->bBoolInUse = FALSE;
935    }
936
937    // allocate rcb mem
938    pDevice->pRCBMem = kmalloc((sizeof(RCB) * pDevice->cbRD), GFP_KERNEL);
939    if (pDevice->pRCBMem == NULL) {
940        DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s : alloc rx usb context failed\n", pDevice->dev->name);
941        goto free_tx;
942    }
943
944
945    pDevice->FirstRecvFreeList = NULL;
946    pDevice->LastRecvFreeList = NULL;
947    pDevice->FirstRecvMngList = NULL;
948    pDevice->LastRecvMngList = NULL;
949    pDevice->NumRecvFreeList = 0;
950    memset(pDevice->pRCBMem, 0, (sizeof(RCB) * pDevice->cbRD));
951    pRCB = (PRCB) pDevice->pRCBMem;
952
953    for (ii = 0; ii < pDevice->cbRD; ii++) {
954
955        pDevice->apRCB[ii] = pRCB;
956        pRCB->pDevice = (PVOID) pDevice;
957        //allocate URBs
958        pRCB->pUrb = vntwusb_alloc_urb(0);
959
960        if (pRCB->pUrb == NULL) {
961            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR" Failed to alloc rx urb\n");
962            goto free_rx_tx;
963        }
964        pRCB->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
965        if (pRCB->skb == NULL) {
966            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR" Failed to alloc rx skb\n");
967            goto free_rx_tx;
968        }
969        pRCB->skb->dev = pDevice->dev;
970        pRCB->bBoolInUse = FALSE;
971        EnqueueRCB(pDevice->FirstRecvFreeList, pDevice->LastRecvFreeList, pRCB);
972        pDevice->NumRecvFreeList++;
973        pRCB++;
974    }
975
976
977	pDevice->pControlURB = vntwusb_alloc_urb(0);
978	if (pDevice->pControlURB == NULL) {
979	    DBG_PRT(MSG_LEVEL_ERR,KERN_ERR"Failed to alloc control urb\n");
980	    goto free_rx_tx;
981	}
982
983	pDevice->pInterruptURB = vntwusb_alloc_urb(0);
984	if (pDevice->pInterruptURB == NULL) {
985	    DBG_PRT(MSG_LEVEL_ERR,KERN_ERR"Failed to alloc int urb\n");
986   	    vntwusb_unlink_urb(pDevice->pControlURB);
987	    usb_free_urb(pDevice->pControlURB);
988	    goto free_rx_tx;
989	}
990
991    pDevice->intBuf.pDataBuf = kmalloc(MAX_INTERRUPT_SIZE, GFP_KERNEL);
992	if (pDevice->intBuf.pDataBuf == NULL) {
993	    DBG_PRT(MSG_LEVEL_ERR,KERN_ERR"Failed to alloc int buf\n");
994   	    vntwusb_unlink_urb(pDevice->pControlURB);
995   	    vntwusb_unlink_urb(pDevice->pInterruptURB);
996	    usb_free_urb(pDevice->pControlURB);
997	    usb_free_urb(pDevice->pInterruptURB);
998	    goto free_rx_tx;
999	}
1000
1001    return TRUE;
1002
1003free_rx_tx:
1004    device_free_rx_bufs(pDevice);
1005
1006free_tx:
1007    device_free_tx_bufs(pDevice);
1008
1009	return FALSE;
1010}
1011
1012
1013
1014
1015static BOOL device_init_defrag_cb(PSDevice pDevice) {
1016    int i;
1017    PSDeFragControlBlock pDeF;
1018
1019    /* Init the fragment ctl entries */
1020    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
1021        pDeF = &(pDevice->sRxDFCB[i]);
1022        if (!device_alloc_frag_buf(pDevice, pDeF)) {
1023            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc frag bufs\n",
1024                pDevice->dev->name);
1025            goto free_frag;
1026        };
1027    }
1028    pDevice->cbDFCB = CB_MAX_RX_FRAG;
1029    pDevice->cbFreeDFCB = pDevice->cbDFCB;
1030    return TRUE;
1031
1032free_frag:
1033    device_free_frag_bufs(pDevice);
1034    return FALSE;
1035}
1036
1037
1038
1039static void device_free_frag_bufs(PSDevice pDevice) {
1040    PSDeFragControlBlock pDeF;
1041    int i;
1042
1043    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
1044
1045        pDeF = &(pDevice->sRxDFCB[i]);
1046
1047        if (pDeF->skb)
1048            dev_kfree_skb(pDeF->skb);
1049    }
1050}
1051
1052
1053
1054BOOL device_alloc_frag_buf(PSDevice pDevice, PSDeFragControlBlock pDeF) {
1055
1056    pDeF->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
1057    if (pDeF->skb == NULL)
1058        return FALSE;
1059    ASSERT(pDeF->skb);
1060    pDeF->skb->dev = pDevice->dev;
1061
1062    return TRUE;
1063}
1064
1065
1066/*-----------------------------------------------------------------*/
1067
1068static int  device_open(struct net_device *dev) {
1069    PSDevice    pDevice=(PSDevice) netdev_priv(dev);
1070
1071#ifdef WPA_SM_Transtatus
1072     extern SWPAResult wpa_Result;
1073     memset(wpa_Result.ifname,0,sizeof(wpa_Result.ifname));
1074     wpa_Result.proto = 0;
1075     wpa_Result.key_mgmt = 0;
1076     wpa_Result.eap_type = 0;
1077     wpa_Result.authenticated = FALSE;
1078     pDevice->fWPA_Authened = FALSE;
1079#endif
1080
1081    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " device_open...\n");
1082
1083
1084    pDevice->rx_buf_sz = MAX_TOTAL_SIZE_WITH_ALL_HEADERS;
1085
1086    if (device_alloc_bufs(pDevice) == FALSE) {
1087        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " device_alloc_bufs fail... \n");
1088        return -ENOMEM;
1089    }
1090
1091    if (device_init_defrag_cb(pDevice)== FALSE) {
1092        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " Initial defragement cb fail \n");
1093        goto free_rx_tx;
1094    }
1095
1096    MP_CLEAR_FLAG(pDevice, fMP_DISCONNECTED);
1097    MP_CLEAR_FLAG(pDevice, fMP_CONTROL_READS);
1098    MP_CLEAR_FLAG(pDevice, fMP_CONTROL_WRITES);
1099    MP_SET_FLAG(pDevice, fMP_POST_READS);
1100    MP_SET_FLAG(pDevice, fMP_POST_WRITES);
1101
1102   //read config file
1103    Read_config_file(pDevice);
1104
1105    if (device_init_registers(pDevice, DEVICE_INIT_COLD) == FALSE) {
1106        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " init register fail\n");
1107        goto free_all;
1108    }
1109
1110    device_set_multi(pDevice->dev);
1111    // Init for Key Management
1112
1113    KeyvInitTable(pDevice,&pDevice->sKey);
1114    memcpy(pDevice->sMgmtObj.abyMACAddr, pDevice->abyCurrentNetAddr, U_ETHER_ADDR_LEN);
1115    memcpy(pDevice->dev->dev_addr, pDevice->abyCurrentNetAddr, U_ETHER_ADDR_LEN);
1116    pDevice->bStopTx0Pkt = FALSE;
1117    pDevice->bStopDataPkt = FALSE;
1118    pDevice->bRoaming = FALSE;  //DavidWang
1119    pDevice->bIsRoaming = FALSE;//DavidWang
1120    pDevice->bEnableRoaming = FALSE;
1121    if (pDevice->bDiversityRegCtlON) {
1122        device_init_diversity_timer(pDevice);
1123    }
1124
1125    vMgrObjectInit(pDevice);
1126    tasklet_init(&pDevice->RxMngWorkItem, (void *)RXvMngWorkItem, (unsigned long)pDevice);
1127    tasklet_init(&pDevice->ReadWorkItem, (void *)RXvWorkItem, (unsigned long)pDevice);
1128    tasklet_init(&pDevice->EventWorkItem, (void *)INTvWorkItem, (unsigned long)pDevice);
1129    add_timer(&(pDevice->sMgmtObj.sTimerSecondCallback));
1130    pDevice->int_interval = 100;  //Max 100 microframes.
1131    pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
1132
1133    pDevice->bIsRxWorkItemQueued = TRUE;
1134    pDevice->fKillEventPollingThread = FALSE;
1135    pDevice->bEventAvailable = FALSE;
1136
1137   pDevice->bWPADEVUp = FALSE;
1138#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
1139     pDevice->bwextstep0 = FALSE;
1140     pDevice->bwextstep1 = FALSE;
1141     pDevice->bwextstep2 = FALSE;
1142     pDevice->bwextstep3 = FALSE;
1143     pDevice->bWPASuppWextEnabled = FALSE;
1144#endif
1145    pDevice->byReAssocCount = 0;
1146
1147    RXvWorkItem(pDevice);
1148    INTvWorkItem(pDevice);
1149
1150    // Patch: if WEP key already set by iwconfig but device not yet open
1151    if ((pDevice->bEncryptionEnable == TRUE) && (pDevice->bTransmitKey == TRUE)) {
1152         spin_lock_irq(&pDevice->lock);
1153         KeybSetDefaultKey( pDevice,
1154                            &(pDevice->sKey),
1155                            pDevice->byKeyIndex | (1 << 31),
1156                            pDevice->uKeyLength,
1157                            NULL,
1158                            pDevice->abyKey,
1159                            KEY_CTL_WEP
1160                          );
1161         spin_unlock_irq(&pDevice->lock);
1162         pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
1163    }
1164
1165    if (pDevice->sMgmtObj.eConfigMode == WMAC_CONFIG_AP) {
1166        bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RUN_AP, NULL);
1167	}
1168	else {
1169	//mike:mark@2008-11-10
1170            bScheduleCommand((HANDLE)pDevice, WLAN_CMD_BSSID_SCAN, NULL);
1171        //bScheduleCommand((HANDLE)pDevice, WLAN_CMD_SSID, NULL);
1172    }
1173
1174
1175    netif_stop_queue(pDevice->dev);
1176    pDevice->flags |= DEVICE_FLAGS_OPENED;
1177
1178#ifdef SndEvt_ToAPI
1179{
1180  union iwreq_data      wrqu;
1181  memset(&wrqu, 0, sizeof(wrqu));
1182  wrqu.data.flags = RT_UPDEV_EVENT_FLAG;
1183  wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, NULL);
1184}
1185#endif
1186
1187    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_open success.. \n");
1188    return 0;
1189
1190free_all:
1191    device_free_frag_bufs(pDevice);
1192free_rx_tx:
1193    device_free_rx_bufs(pDevice);
1194    device_free_tx_bufs(pDevice);
1195    device_free_int_bufs(pDevice);
1196	vntwusb_unlink_urb(pDevice->pControlURB);
1197	vntwusb_unlink_urb(pDevice->pInterruptURB);
1198    usb_free_urb(pDevice->pControlURB);
1199    usb_free_urb(pDevice->pInterruptURB);
1200
1201    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_open fail.. \n");
1202    return -ENOMEM;
1203}
1204
1205
1206
1207static int  device_close(struct net_device *dev) {
1208    PSDevice    pDevice=(PSDevice) netdev_priv(dev);
1209    PSMgmtObject     pMgmt = &(pDevice->sMgmtObj);
1210
1211        int uu;
1212
1213    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_close1 \n");
1214    if (pDevice == NULL)
1215        return -ENODEV;
1216
1217#ifdef SndEvt_ToAPI
1218{
1219  union iwreq_data      wrqu;
1220  memset(&wrqu, 0, sizeof(wrqu));
1221  wrqu.data.flags = RT_DOWNDEV_EVENT_FLAG;
1222  wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, NULL);
1223}
1224#endif
1225
1226//2007-1121-02<Add>by EinsnLiu
1227    if (pDevice->bLinkPass) {
1228	bScheduleCommand((HANDLE)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
1229        mdelay(30);
1230    }
1231//End Add
1232
1233//2008-0714-01<Add>by MikeLiu
1234device_release_WPADEV(pDevice);
1235
1236        memset(pMgmt->abyDesireSSID, 0, WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN + 1);
1237        pMgmt->bShareKeyAlgorithm = FALSE;
1238        pDevice->bEncryptionEnable = FALSE;
1239        pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
1240            spin_lock_irq(&pDevice->lock);
1241            for(uu=0;uu<MAX_KEY_TABLE;uu++)
1242                MACvDisableKeyEntry(pDevice,uu);
1243            spin_unlock_irq(&pDevice->lock);
1244
1245    if ((pDevice->flags & DEVICE_FLAGS_UNPLUG) == FALSE) {
1246        MACbShutdown(pDevice);
1247    }
1248    netif_stop_queue(pDevice->dev);
1249    MP_SET_FLAG(pDevice, fMP_DISCONNECTED);
1250    MP_CLEAR_FLAG(pDevice, fMP_POST_WRITES);
1251    MP_CLEAR_FLAG(pDevice, fMP_POST_READS);
1252    pDevice->fKillEventPollingThread = TRUE;
1253    del_timer(&pDevice->sTimerCommand);
1254    del_timer(&pMgmt->sTimerSecondCallback);
1255
1256//2007-0115-02<Add>by MikeLiu
1257#ifdef TxInSleep
1258    del_timer(&pDevice->sTimerTxData);
1259#endif
1260
1261    if (pDevice->bDiversityRegCtlON) {
1262        del_timer(&pDevice->TimerSQ3Tmax1);
1263        del_timer(&pDevice->TimerSQ3Tmax2);
1264        del_timer(&pDevice->TimerSQ3Tmax3);
1265    }
1266    tasklet_kill(&pDevice->RxMngWorkItem);
1267    tasklet_kill(&pDevice->ReadWorkItem);
1268    tasklet_kill(&pDevice->EventWorkItem);
1269
1270   pDevice->bRoaming = FALSE;  //DavidWang
1271   pDevice->bIsRoaming = FALSE;//DavidWang
1272   pDevice->bEnableRoaming = FALSE;
1273    pDevice->bCmdRunning = FALSE;
1274    pDevice->bLinkPass = FALSE;
1275    memset(pMgmt->abyCurrBSSID, 0, 6);
1276    pMgmt->eCurrState = WMAC_STATE_IDLE;
1277
1278    device_free_tx_bufs(pDevice);
1279    device_free_rx_bufs(pDevice);
1280    device_free_int_bufs(pDevice);
1281    device_free_frag_bufs(pDevice);
1282
1283	vntwusb_unlink_urb(pDevice->pControlURB);
1284	vntwusb_unlink_urb(pDevice->pInterruptURB);
1285    usb_free_urb(pDevice->pControlURB);
1286    usb_free_urb(pDevice->pInterruptURB);
1287
1288    BSSvClearNodeDBTable(pDevice, 0);
1289    pDevice->flags &=(~DEVICE_FLAGS_OPENED);
1290
1291    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_close2 \n");
1292
1293    return 0;
1294}
1295
1296
1297static void vntwusb_disconnect(struct usb_interface *intf)
1298
1299{
1300
1301	PSDevice  pDevice = usb_get_intfdata(intf);
1302
1303    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_disconnect1.. \n");
1304    if (pDevice == NULL)
1305        return;
1306
1307#ifdef SndEvt_ToAPI
1308{
1309  union iwreq_data      wrqu;
1310  memset(&wrqu, 0, sizeof(wrqu));
1311  wrqu.data.flags = RT_RMMOD_EVENT_FLAG;
1312  wireless_send_event(pDevice->dev, IWEVCUSTOM, &wrqu, NULL);
1313}
1314#endif
1315
1316//2008-0714-01<Add>by MikeLiu
1317device_release_WPADEV(pDevice);
1318
1319	usb_set_intfdata(intf, NULL);
1320//2008-0922-01<Add>by MikeLiu, decrease usb counter.
1321     usb_put_dev(interface_to_usbdev(intf));
1322
1323    pDevice->flags |= DEVICE_FLAGS_UNPLUG;
1324    if (pDevice->dev != NULL) {
1325        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "unregister_netdev..\n");
1326        unregister_netdev(pDevice->dev);
1327
1328//2008-07-21-01<Add>by MikeLiu
1329//unregister wpadev
1330   if(wpa_set_wpadev(pDevice, 0)!=0)
1331     printk("unregister wpadev fail?\n");
1332
1333        free_netdev(pDevice->dev);
1334    }
1335
1336	kfree(pDevice);
1337    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_disconnect3.. \n");
1338}
1339
1340
1341
1342
1343static int device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev) {
1344    PSDevice        pDevice=netdev_priv(dev);
1345    PBYTE           pbMPDU;
1346    UINT            cbMPDULen = 0;
1347
1348
1349    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_tx_80211\n");
1350    spin_lock_irq(&pDevice->lock);
1351
1352    if (pDevice->bStopTx0Pkt == TRUE) {
1353        dev_kfree_skb_irq(skb);
1354        spin_unlock_irq(&pDevice->lock);
1355        return 0;
1356    };
1357
1358
1359    cbMPDULen = skb->len;
1360    pbMPDU = skb->data;
1361
1362    vDMA0_tx_80211(pDevice, skb);
1363
1364    spin_unlock_irq(&pDevice->lock);
1365
1366    return 0;
1367
1368}
1369
1370
1371static int  device_xmit(struct sk_buff *skb, struct net_device *dev) {
1372    PSDevice    pDevice=netdev_priv(dev);
1373    struct net_device_stats* pStats = &pDevice->stats;
1374
1375
1376    spin_lock_irq(&pDevice->lock);
1377
1378    netif_stop_queue(pDevice->dev);
1379
1380    if (pDevice->bLinkPass == FALSE) {
1381        dev_kfree_skb_irq(skb);
1382        spin_unlock_irq(&pDevice->lock);
1383        return 0;
1384    }
1385    if (pDevice->bStopDataPkt == TRUE) {
1386        dev_kfree_skb_irq(skb);
1387        pStats->tx_dropped++;
1388        spin_unlock_irq(&pDevice->lock);
1389        return 0;
1390    }
1391
1392    if(nsDMA_tx_packet(pDevice, TYPE_AC0DMA, skb) !=0) {  //mike add:xmit fail!
1393         if (netif_queue_stopped(pDevice->dev))
1394              netif_wake_queue(pDevice->dev);
1395    }
1396
1397    spin_unlock_irq(&pDevice->lock);
1398
1399    return 0;
1400}
1401
1402
1403
1404static unsigned const ethernet_polynomial = 0x04c11db7U;
1405static inline u32 ether_crc(int length, unsigned char *data)
1406{
1407    int crc = -1;
1408
1409    while(--length >= 0) {
1410        unsigned char current_octet = *data++;
1411        int bit;
1412        for (bit = 0; bit < 8; bit++, current_octet >>= 1) {
1413            crc = (crc << 1) ^
1414                ((crc < 0) ^ (current_octet & 1) ? ethernet_polynomial : 0);
1415        }
1416    }
1417    return crc;
1418}
1419
1420//find out  the start  position of str2 from str1
1421static UCHAR *kstrstr(const UCHAR *str1,const UCHAR *str2) {
1422  int str1_len=strlen(str1);
1423  int str2_len=strlen(str2);
1424
1425  while (str1_len >= str2_len) {
1426       str1_len--;
1427      if(memcmp(str1,str2,str2_len)==0)
1428         return (UCHAR *)str1;
1429        str1++;
1430  }
1431  return NULL;
1432}
1433
1434static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source)
1435{
1436  UCHAR buf1[100];
1437  UCHAR buf2[100];
1438  UCHAR *start_p=NULL,*end_p=NULL,*tmp_p=NULL;
1439  int ii;
1440
1441    memset(buf1,0,100);
1442    strcat(buf1, string);
1443    strcat(buf1, "=");
1444    source+=strlen(buf1);
1445
1446//find target string start point
1447    if((start_p = kstrstr(source,buf1))==NULL)
1448	return FALSE;
1449
1450//check if current config line is marked by "#" ??
1451for(ii=1;;ii++) {
1452  if(memcmp(start_p-ii,"\n",1)==0)
1453      break;
1454  if(memcmp(start_p-ii,"#",1)==0)
1455      return FALSE;
1456}
1457
1458//find target string end point
1459     if((end_p = kstrstr(start_p,"\n"))==NULL) {       //cann't find "\n",but don't care
1460          end_p=start_p+strlen(start_p);   //no include "\n"
1461       }
1462
1463   memset(buf2,0,100);
1464   memcpy(buf2,start_p,end_p-start_p);    //get the tartget line
1465   buf2[end_p-start_p]='\0';
1466
1467   //find value
1468   if((start_p = kstrstr(buf2,"="))==NULL)
1469      return FALSE;
1470   memset(buf1,0,100);
1471   strcpy(buf1,start_p+1);
1472
1473  //except space
1474  tmp_p = buf1;
1475  while(*tmp_p != 0x00) {
1476  	if(*tmp_p==' ')
1477	    tmp_p++;
1478         else
1479	  break;
1480  }
1481
1482   memcpy(dest,tmp_p,strlen(tmp_p));
1483 return TRUE;
1484}
1485
1486//if read fail,return NULL,or return data pointer;
1487static UCHAR *Config_FileOperation(PSDevice pDevice) {
1488    UCHAR    *config_path=CONFIG_PATH;
1489    UCHAR    *buffer=NULL;
1490    struct file   *filp=NULL;
1491    mm_segment_t old_fs = get_fs();
1492    //int oldfsuid=0,oldfsgid=0;
1493    int result=0;
1494
1495    set_fs (KERNEL_DS);
1496    /* Can't do this anymore, so we rely on correct filesystem permissions:
1497    //Make sure a caller can read or write power as root
1498    oldfsuid=current->fsuid;
1499    oldfsgid=current->fsgid;
1500    current->fsuid = 0;
1501    current->fsgid = 0;
1502    */
1503
1504    //open file
1505      filp = filp_open(config_path, O_RDWR, 0);
1506        if (IS_ERR(filp)) {
1507	     printk("Config_FileOperation file Not exist\n");
1508	     result=-1;
1509             goto error2;
1510	  }
1511
1512     if(!(filp->f_op) || !(filp->f_op->read) ||!(filp->f_op->write)) {
1513           printk("file %s cann't readable or writable?\n",config_path);
1514	  result = -1;
1515	  goto error1;
1516     	}
1517
1518    buffer = (UCHAR *)kmalloc(1024, GFP_KERNEL);
1519    if(buffer==NULL) {
1520      printk("alllocate mem for file fail?\n");
1521      result = -1;
1522      goto error1;
1523    }
1524
1525    if(filp->f_op->read(filp, buffer, 1024, &filp->f_pos)<0) {
1526     printk("read file error?\n");
1527     result = -1;
1528    }
1529
1530error1:
1531  if(filp_close(filp,NULL))
1532       printk("Config_FileOperation:close file fail\n");
1533
1534error2:
1535  set_fs (old_fs);
1536
1537  /*
1538  current->fsuid=oldfsuid;
1539  current->fsgid=oldfsgid;
1540  */
1541
1542if(result!=0) {
1543    if(buffer)
1544  	 kfree(buffer);
1545    buffer=NULL;
1546}
1547  return buffer;
1548}
1549
1550//return --->-1:fail;  >=0:sucessful
1551static int Read_config_file(PSDevice pDevice) {
1552  int result=0;
1553  UCHAR      tmpbuffer[100];
1554  UCHAR *buffer=NULL;
1555
1556  //init config setting
1557 pDevice->config_file.ZoneType = -1;
1558 pDevice->config_file.eAuthenMode = -1;
1559 pDevice->config_file.eEncryptionStatus = -1;
1560
1561  if((buffer=Config_FileOperation(pDevice)) ==NULL) {
1562     result =-1;
1563     return result;
1564  }
1565
1566//get zonetype
1567{
1568    memset(tmpbuffer,0,sizeof(tmpbuffer));
1569    if(Config_FileGetParameter("ZONETYPE",tmpbuffer,buffer) ==TRUE) {
1570    if(memcmp(tmpbuffer,"USA",3)==0) {
1571      pDevice->config_file.ZoneType=ZoneType_USA;
1572    }
1573    else if(memcmp(tmpbuffer,"JAPAN",5)==0) {
1574      pDevice->config_file.ZoneType=ZoneType_Japan;
1575    }
1576    else if(memcmp(tmpbuffer,"EUROPE",6)==0) {
1577     pDevice->config_file.ZoneType=ZoneType_Europe;
1578    }
1579    else {
1580      printk("Unknown Zonetype[%s]?\n",tmpbuffer);
1581   }
1582 }
1583}
1584
1585#if 1
1586//get other parameter
1587  {
1588	memset(tmpbuffer,0,sizeof(tmpbuffer));
1589       if(Config_FileGetParameter("AUTHENMODE",tmpbuffer,buffer)==TRUE) {
1590	 pDevice->config_file.eAuthenMode = (int) simple_strtol(tmpbuffer, NULL, 10);
1591       }
1592
1593	memset(tmpbuffer,0,sizeof(tmpbuffer));
1594       if(Config_FileGetParameter("ENCRYPTIONMODE",tmpbuffer,buffer)==TRUE) {
1595	 pDevice->config_file.eEncryptionStatus= (int) simple_strtol(tmpbuffer, NULL, 10);
1596       }
1597  }
1598#endif
1599
1600  kfree(buffer);
1601  return result;
1602}
1603
1604static void device_set_multi(struct net_device *dev) {
1605    PSDevice         pDevice = (PSDevice) netdev_priv(dev);
1606    PSMgmtObject     pMgmt = &(pDevice->sMgmtObj);
1607    u32              mc_filter[2];
1608    int              ii;
1609    struct dev_mc_list  *mclist;
1610    BYTE             pbyData[8] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
1611    BYTE             byTmpMode = 0;
1612    int              rc;
1613
1614
1615	spin_lock_irq(&pDevice->lock);
1616    rc = CONTROLnsRequestIn(pDevice,
1617                            MESSAGE_TYPE_READ,
1618                            MAC_REG_RCR,
1619                            MESSAGE_REQUEST_MACREG,
1620                            1,
1621                            &byTmpMode
1622                            );
1623    if (rc == 0) pDevice->byRxMode = byTmpMode;
1624
1625    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRxMode in= %x\n", pDevice->byRxMode);
1626
1627    if (dev->flags & IFF_PROMISC) {         // Set promiscuous.
1628        DBG_PRT(MSG_LEVEL_ERR,KERN_NOTICE "%s: Promiscuous mode enabled.\n", dev->name);
1629        // Unconditionally log net taps.
1630        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST|RCR_UNICAST);
1631    }
1632    else if ((dev->mc_count > pDevice->multicast_limit) || (dev->flags & IFF_ALLMULTI)) {
1633        CONTROLnsRequestOut(pDevice,
1634                            MESSAGE_TYPE_WRITE,
1635                            MAC_REG_MAR0,
1636                            MESSAGE_REQUEST_MACREG,
1637                            8,
1638                            pbyData
1639                            );
1640        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
1641    }
1642    else {
1643        memset(mc_filter, 0, sizeof(mc_filter));
1644        for (ii = 0, mclist = dev->mc_list; mclist && ii < dev->mc_count;
1645             ii++, mclist = mclist->next) {
1646            int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
1647            mc_filter[bit_nr >> 5] |= cpu_to_le32(1 << (bit_nr & 31));
1648        }
1649        for (ii = 0; ii < 4; ii++) {
1650             MACvWriteMultiAddr(pDevice, ii, *((PBYTE)&mc_filter[0] + ii));
1651             MACvWriteMultiAddr(pDevice, ii+ 4, *((PBYTE)&mc_filter[1] + ii));
1652        }
1653        pDevice->byRxMode &= ~(RCR_UNICAST);
1654        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
1655    }
1656
1657    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
1658        // If AP mode, don't enable RCR_UNICAST. Since hw only compare addr1 with local mac.
1659        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
1660        pDevice->byRxMode &= ~(RCR_UNICAST);
1661    }
1662    ControlvWriteByte(pDevice, MESSAGE_REQUEST_MACREG, MAC_REG_RCR, pDevice->byRxMode);
1663    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRxMode out= %x\n", pDevice->byRxMode);
1664	spin_unlock_irq(&pDevice->lock);
1665
1666}
1667
1668
1669static struct net_device_stats *device_get_stats(struct net_device *dev) {
1670    PSDevice pDevice=(PSDevice) netdev_priv(dev);
1671
1672    return &pDevice->stats;
1673}
1674
1675
1676static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) {
1677	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
1678    PSMgmtObject        pMgmt = &(pDevice->sMgmtObj);
1679    PSCmdRequest        pReq;
1680    //BOOL                bCommit = FALSE;
1681	struct iwreq *wrq = (struct iwreq *) rq;
1682	int                 rc =0;
1683
1684    if (pMgmt == NULL) {
1685        rc = -EFAULT;
1686        return rc;
1687    }
1688
1689    switch(cmd) {
1690
1691	case SIOCGIWNAME:
1692		rc = iwctl_giwname(dev, NULL, (char *)&(wrq->u.name), NULL);
1693		break;
1694
1695	case SIOCSIWNWID:
1696        rc = -EOPNOTSUPP;
1697		break;
1698
1699	case SIOCGIWNWID:     //0x8b03  support
1700	#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
1701          rc = iwctl_giwnwid(dev, NULL, &(wrq->u.nwid), NULL);
1702	#else
1703        rc = -EOPNOTSUPP;
1704	#endif
1705		break;
1706
1707		// Set frequency/channel
1708	case SIOCSIWFREQ:
1709	    rc = iwctl_siwfreq(dev, NULL, &(wrq->u.freq), NULL);
1710		break;
1711
1712		// Get frequency/channel
1713	case SIOCGIWFREQ:
1714		rc = iwctl_giwfreq(dev, NULL, &(wrq->u.freq), NULL);
1715		break;
1716
1717		// Set desired network name (ESSID)
1718	case SIOCSIWESSID:
1719
1720		{
1721			char essid[IW_ESSID_MAX_SIZE+1];
1722			if (wrq->u.essid.length > IW_ESSID_MAX_SIZE) {
1723				rc = -E2BIG;
1724				break;
1725			}
1726			if (copy_from_user(essid, wrq->u.essid.pointer,
1727					   wrq->u.essid.length)) {
1728				rc = -EFAULT;
1729				break;
1730			}
1731			rc = iwctl_siwessid(dev, NULL,
1732					    &(wrq->u.essid), essid);
1733		}
1734		break;
1735
1736
1737		// Get current network name (ESSID)
1738	case SIOCGIWESSID:
1739
1740		{
1741			char essid[IW_ESSID_MAX_SIZE+1];
1742			if (wrq->u.essid.pointer)
1743				rc = iwctl_giwessid(dev, NULL,
1744						    &(wrq->u.essid), essid);
1745				if (copy_to_user(wrq->u.essid.pointer,
1746						         essid,
1747						         wrq->u.essid.length) )
1748					rc = -EFAULT;
1749		}
1750		break;
1751
1752	case SIOCSIWAP:
1753
1754		rc = iwctl_siwap(dev, NULL, &(wrq->u.ap_addr), NULL);
1755		break;
1756
1757
1758		// Get current Access Point (BSSID)
1759	case SIOCGIWAP:
1760		rc = iwctl_giwap(dev, NULL, &(wrq->u.ap_addr), NULL);
1761		break;
1762
1763
1764		// Set desired station name
1765	case SIOCSIWNICKN:
1766        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWNICKN \n");
1767        rc = -EOPNOTSUPP;
1768		break;
1769
1770		// Get current station name
1771	case SIOCGIWNICKN:
1772        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWNICKN \n");
1773        rc = -EOPNOTSUPP;
1774		break;
1775
1776		// Set the desired bit-rate
1777	case SIOCSIWRATE:
1778		rc = iwctl_siwrate(dev, NULL, &(wrq->u.bitrate), NULL);
1779		break;
1780
1781	// Get the current bit-rate
1782	case SIOCGIWRATE:
1783
1784		rc = iwctl_giwrate(dev, NULL, &(wrq->u.bitrate), NULL);
1785		break;
1786
1787	// Set the desired RTS threshold
1788	case SIOCSIWRTS:
1789
1790		rc = iwctl_siwrts(dev, NULL, &(wrq->u.rts), NULL);
1791		break;
1792
1793	// Get the current RTS threshold
1794	case SIOCGIWRTS:
1795
1796		rc = iwctl_giwrts(dev, NULL, &(wrq->u.rts), NULL);
1797		break;
1798
1799		// Set the desired fragmentation threshold
1800	case SIOCSIWFRAG:
1801
1802		rc = iwctl_siwfrag(dev, NULL, &(wrq->u.frag), NULL);
1803	    break;
1804
1805	// Get the current fragmentation threshold
1806	case SIOCGIWFRAG:
1807
1808		rc = iwctl_giwfrag(dev, NULL, &(wrq->u.frag), NULL);
1809		break;
1810
1811		// Set mode of operation
1812	case SIOCSIWMODE:
1813    	rc = iwctl_siwmode(dev, NULL, &(wrq->u.mode), NULL);
1814		break;
1815
1816		// Get mode of operation
1817	case SIOCGIWMODE:
1818		rc = iwctl_giwmode(dev, NULL, &(wrq->u.mode), NULL);
1819		break;
1820
1821		// Set WEP keys and mode
1822	case SIOCSIWENCODE:
1823		{
1824            char abyKey[WLAN_WEP232_KEYLEN];
1825
1826			if (wrq->u.encoding.pointer) {
1827
1828
1829				if (wrq->u.encoding.length > WLAN_WEP232_KEYLEN) {
1830					rc = -E2BIG;
1831					break;
1832				}
1833				memset(abyKey, 0, WLAN_WEP232_KEYLEN);
1834				if (copy_from_user(abyKey,
1835				                  wrq->u.encoding.pointer,
1836				                  wrq->u.encoding.length)) {
1837					rc = -EFAULT;
1838					break;
1839				}
1840			} else if (wrq->u.encoding.length != 0) {
1841				rc = -EINVAL;
1842				break;
1843			}
1844			rc = iwctl_siwencode(dev, NULL, &(wrq->u.encoding), abyKey);
1845		}
1846		break;
1847
1848		// Get the WEP keys and mode
1849	case SIOCGIWENCODE:
1850
1851		if (!capable(CAP_NET_ADMIN)) {
1852			rc = -EPERM;
1853			break;
1854		}
1855		{
1856		    char abyKey[WLAN_WEP232_KEYLEN];
1857
1858		    rc = iwctl_giwencode(dev, NULL, &(wrq->u.encoding), abyKey);
1859		    if (rc != 0) break;
1860			if (wrq->u.encoding.pointer) {
1861				if (copy_to_user(wrq->u.encoding.pointer,
1862						        abyKey,
1863						        wrq->u.encoding.length))
1864					rc = -EFAULT;
1865			}
1866		}
1867		break;
1868
1869		// Get the current Tx-Power
1870	case SIOCGIWTXPOW:
1871        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWTXPOW \n");
1872        rc = -EOPNOTSUPP;
1873		break;
1874
1875	case SIOCSIWTXPOW:
1876        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWTXPOW \n");
1877        rc = -EOPNOTSUPP;
1878		break;
1879
1880	case SIOCSIWRETRY:
1881
1882		rc = iwctl_siwretry(dev, NULL, &(wrq->u.retry), NULL);
1883		break;
1884
1885	case SIOCGIWRETRY:
1886
1887		rc = iwctl_giwretry(dev, NULL, &(wrq->u.retry), NULL);
1888		break;
1889
1890		// Get range of parameters
1891	case SIOCGIWRANGE:
1892
1893		{
1894			struct iw_range range;
1895
1896			rc = iwctl_giwrange(dev, NULL, &(wrq->u.data), (char *) &range);
1897			if (copy_to_user(wrq->u.data.pointer, &range, sizeof(struct iw_range)))
1898				rc = -EFAULT;
1899		}
1900
1901		break;
1902
1903	case SIOCGIWPOWER:
1904
1905		rc = iwctl_giwpower(dev, NULL, &(wrq->u.power), NULL);
1906		break;
1907
1908
1909	case SIOCSIWPOWER:
1910
1911		rc = iwctl_siwpower(dev, NULL, &(wrq->u.power), NULL);
1912		break;
1913
1914
1915	case SIOCGIWSENS:
1916
1917	    rc = iwctl_giwsens(dev, NULL, &(wrq->u.sens), NULL);
1918		break;
1919
1920	case SIOCSIWSENS:
1921        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSENS \n");
1922		rc = -EOPNOTSUPP;
1923		break;
1924
1925	case SIOCGIWAPLIST:
1926	    {
1927            char buffer[IW_MAX_AP * (sizeof(struct sockaddr) + sizeof(struct iw_quality))];
1928
1929		    if (wrq->u.data.pointer) {
1930		        rc = iwctl_giwaplist(dev, NULL, &(wrq->u.data), buffer);
1931		        if (rc == 0) {
1932                    if (copy_to_user(wrq->u.data.pointer,
1933					                buffer,
1934					               (wrq->u.data.length * (sizeof(struct sockaddr) +  sizeof(struct iw_quality)))
1935				        ))
1936				    rc = -EFAULT;
1937		        }
1938            }
1939        }
1940		break;
1941
1942
1943#ifdef WIRELESS_SPY
1944		// Set the spy list
1945	case SIOCSIWSPY:
1946
1947        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSPY \n");
1948		rc = -EOPNOTSUPP;
1949		break;
1950
1951		// Get the spy list
1952	case SIOCGIWSPY:
1953
1954        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSPY \n");
1955		rc = -EOPNOTSUPP;
1956		break;
1957
1958#endif // WIRELESS_SPY
1959
1960	case SIOCGIWPRIV:
1961        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWPRIV \n");
1962		rc = -EOPNOTSUPP;
1963/*
1964		if(wrq->u.data.pointer) {
1965			wrq->u.data.length = sizeof(iwctl_private_args) / sizeof( iwctl_private_args[0]);
1966
1967			if(copy_to_user(wrq->u.data.pointer,
1968					(u_char *) iwctl_private_args,
1969					sizeof(iwctl_private_args)))
1970				rc = -EFAULT;
1971		}
1972*/
1973		break;
1974
1975
1976//2008-0409-07, <Add> by Einsn Liu
1977#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
1978	case SIOCSIWAUTH:
1979		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWAUTH \n");
1980		rc = iwctl_siwauth(dev, NULL, &(wrq->u.param), NULL);
1981		break;
1982
1983	case SIOCGIWAUTH:
1984		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWAUTH \n");
1985		rc = iwctl_giwauth(dev, NULL, &(wrq->u.param), NULL);
1986		break;
1987
1988	case SIOCSIWGENIE:
1989		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWGENIE \n");
1990		rc = iwctl_siwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
1991		break;
1992
1993	case SIOCGIWGENIE:
1994		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWGENIE \n");
1995		rc = iwctl_giwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
1996		break;
1997
1998	case SIOCSIWENCODEEXT:
1999		{
2000			char extra[sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1];
2001			DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWENCODEEXT \n");
2002			if(wrq->u.encoding.pointer){
2003				memset(extra, 0, sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1);
2004				if(wrq->u.encoding.length > (sizeof(struct iw_encode_ext)+ MAX_KEY_LEN)){
2005					rc = -E2BIG;
2006					break;
2007				}
2008				if(copy_from_user(extra, wrq->u.encoding.pointer,wrq->u.encoding.length)){
2009					rc = -EFAULT;
2010					break;
2011				}
2012			}else if(wrq->u.encoding.length != 0){
2013				rc = -EINVAL;
2014				break;
2015			}
2016			rc = iwctl_siwencodeext(dev, NULL, &(wrq->u.encoding), extra);
2017		}
2018		break;
2019
2020	case SIOCGIWENCODEEXT:
2021		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWENCODEEXT \n");
2022		rc = iwctl_giwencodeext(dev, NULL, &(wrq->u.encoding), NULL);
2023		break;
2024
2025	case SIOCSIWMLME:
2026		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWMLME \n");
2027		rc = iwctl_siwmlme(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
2028		break;
2029
2030#endif // #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
2031//End Add -- //2008-0409-07, <Add> by Einsn Liu
2032
2033    case IOCTL_CMD_TEST:
2034
2035		if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
2036		    rc = -EFAULT;
2037		    break;
2038		} else {
2039		    rc = 0;
2040		}
2041        pReq = (PSCmdRequest)rq;
2042
2043   //20080130-01,<Remark> by Mike Liu
2044      // if(pDevice->bLinkPass==TRUE)
2045          pReq->wResult = MAGIC_CODE;         //Linking status:0x3142
2046   //20080130-02,<Remark> by Mike Liu
2047      //  else
2048      //	 pReq->wResult = MAGIC_CODE+1;    //disconnect status:0x3143
2049        break;
2050
2051    case IOCTL_CMD_SET:
2052		if (!(pDevice->flags & DEVICE_FLAGS_OPENED) &&
2053		       (((PSCmdRequest)rq)->wCmdCode !=WLAN_CMD_SET_WPA))
2054		{
2055		    rc = -EFAULT;
2056		    break;
2057		} else {
2058		    rc = 0;
2059		}
2060
2061	    if (test_and_set_bit( 0, (void*)&(pMgmt->uCmdBusy))) {
2062		    return -EBUSY;
2063	    }
2064        rc = private_ioctl(pDevice, rq);
2065        clear_bit( 0, (void*)&(pMgmt->uCmdBusy));
2066        break;
2067
2068    case IOCTL_CMD_HOSTAPD:
2069
2070		if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
2071		    rc = -EFAULT;
2072		    break;
2073		} else {
2074		    rc = 0;
2075		}
2076
2077		rc = hostap_ioctl(pDevice, &wrq->u.data);
2078        break;
2079
2080    case IOCTL_CMD_WPA:
2081
2082		if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
2083		    rc = -EFAULT;
2084		    break;
2085		} else {
2086		    rc = 0;
2087		}
2088
2089		rc = wpa_ioctl(pDevice, &wrq->u.data);
2090        break;
2091
2092	case SIOCETHTOOL:
2093        return ethtool_ioctl(dev, (void *) rq->ifr_data);
2094	// All other calls are currently unsupported
2095
2096	default:
2097		rc = -EOPNOTSUPP;
2098        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Ioctl command not support..%x\n", cmd);
2099
2100
2101    }
2102
2103    if (pDevice->bCommit) {
2104       if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
2105           netif_stop_queue(pDevice->dev);
2106           spin_lock_irq(&pDevice->lock);
2107           bScheduleCommand((HANDLE)pDevice, WLAN_CMD_RUN_AP, NULL);
2108           spin_unlock_irq(&pDevice->lock);
2109       }
2110       else {
2111           DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Commit the settings\n");
2112           spin_lock_irq(&pDevice->lock);
2113//2007-1121-01<Modify>by EinsnLiu
2114	    if (pDevice->bLinkPass&&
2115		  memcmp(pMgmt->abyCurrSSID,pMgmt->abyDesireSSID,WLAN_IEHDR_LEN + WLAN_SSID_MAXLEN)) {
2116      		  bScheduleCommand((HANDLE)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
2117	     } else {
2118           pDevice->bLinkPass = FALSE;
2119	   pMgmt->eCurrState = WMAC_STATE_IDLE;
2120	   memset(pMgmt->abyCurrBSSID, 0, 6);
2121		 }
2122           ControlvMaskByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_PAPEDELAY,LEDSTS_STS,LEDSTS_SLOW);
2123//End Modify
2124           netif_stop_queue(pDevice->dev);
2125#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
2126           pMgmt->eScanType = WMAC_SCAN_ACTIVE;
2127           if(pDevice->bWPASuppWextEnabled !=TRUE)
2128#endif
2129           bScheduleCommand((HANDLE) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
2130           bScheduleCommand((HANDLE) pDevice, WLAN_CMD_SSID, NULL);
2131           spin_unlock_irq(&pDevice->lock);
2132      }
2133      pDevice->bCommit = FALSE;
2134    }
2135
2136
2137    return rc;
2138}
2139
2140
2141static int ethtool_ioctl(struct net_device *dev, void *useraddr)
2142{
2143	u32 ethcmd;
2144
2145	if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd)))
2146		return -EFAULT;
2147
2148        switch (ethcmd) {
2149	case ETHTOOL_GDRVINFO: {
2150		struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
2151		strncpy(info.driver, DEVICE_NAME, sizeof(info.driver)-1);
2152		strncpy(info.version, DEVICE_VERSION, sizeof(info.version)-1);
2153		if (copy_to_user(useraddr, &info, sizeof(info)))
2154			return -EFAULT;
2155		return 0;
2156	}
2157
2158        }
2159
2160	return -EOPNOTSUPP;
2161}
2162
2163
2164/*------------------------------------------------------------------*/
2165
2166
2167MODULE_DEVICE_TABLE(usb, vntwusb_table);
2168
2169
2170static struct usb_driver vntwusb_driver = {
2171	    .name =		DEVICE_NAME,
2172	    .probe =	vntwusb_found1,
2173	    .disconnect =	vntwusb_disconnect,
2174	    .id_table =	vntwusb_table,
2175
2176//2008-0920-01<Add>by MikeLiu
2177//for supporting S3 & S4 function
2178#ifdef CONFIG_PM
2179	   .suspend = vntwusb_suspend,
2180	   .resume = vntwusb_resume,
2181#endif
2182};
2183
2184static int __init vntwusb_init_module(void)
2185{
2186    printk(KERN_NOTICE DEVICE_FULL_DRV_NAM " " DEVICE_VERSION);
2187    return usb_register(&vntwusb_driver);
2188}
2189
2190static void __exit vntwusb_cleanup_module(void)
2191{
2192	usb_deregister(&vntwusb_driver);
2193}
2194
2195module_init(vntwusb_init_module);
2196module_exit(vntwusb_cleanup_module);
2197
2198