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