device_main.c revision 96fe9ee2c2dfe3268961f3873ea6098b9b9f27c2
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: device_main.c
20 *
21 * Purpose: driver entry for initial, open, close, tx and rx.
22 *
23 * Author: Lyndon Chen
24 *
25 * Date: Jan 8, 2003
26 *
27 * Functions:
28 *
29 *   device_found1 - module initial (insmod) driver entry
30 *   device_remove1 - module remove entry
31 *   device_init_info - device structure resource allocation function
32 *   device_free_info - device structure resource free function
33 *   device_get_pci_info - get allocated pci io/mem resource
34 *   device_print_info - print out resource
35 *   device_open - allocate dma/descripter resource & initial mac/bbp function
36 *   device_xmit - asynchrous data tx function
37 *   device_intr - interrupt handle function
38 *   device_set_multi - set mac filter
39 *   device_ioctl - ioctl entry
40 *   device_close - shutdown mac/bbp & free dma/descripter resource
41 *   device_rx_srv - rx service function
42 *   device_receive_frame - rx data function
43 *   device_alloc_rx_buf - rx buffer pre-allocated function
44 *   device_alloc_frag_buf - rx fragement pre-allocated function
45 *   device_free_tx_buf - free tx buffer function
46 *   device_free_frag_buf- free de-fragement buffer
47 *   device_dma0_tx_80211- tx 802.11 frame via dma0
48 *   device_dma0_xmit- tx PS bufferred frame via dma0
49 *   device_init_rd0_ring- initial rd dma0 ring
50 *   device_init_rd1_ring- initial rd dma1 ring
51 *   device_init_td0_ring- initial tx dma0 ring buffer
52 *   device_init_td1_ring- initial tx dma1 ring buffer
53 *   device_init_registers- initial MAC & BBP & RF internal registers.
54 *   device_init_rings- initial tx/rx ring buffer
55 *   device_init_defrag_cb- initial & allocate de-fragement buffer.
56 *   device_free_rings- free all allocated ring buffer
57 *   device_tx_srv- tx interrupt service function
58 *
59 * Revision History:
60 */
61#undef __NO_VERSION__
62
63#include "device.h"
64#include "card.h"
65#include "baseband.h"
66#include "mac.h"
67#include "tether.h"
68#include "wmgr.h"
69#include "wctl.h"
70#include "power.h"
71#include "wcmd.h"
72#include "iocmd.h"
73#include "tcrc.h"
74#include "rxtx.h"
75#include "wroute.h"
76#include "bssdb.h"
77#include "hostap.h"
78#include "wpactl.h"
79#include "ioctl.h"
80#include "iwctl.h"
81#include "dpc.h"
82#include "datarate.h"
83#include "rf.h"
84#include "iowpa.h"
85#include <linux/delay.h>
86#include <linux/kthread.h>
87#include <linux/slab.h>
88
89//#define	DEBUG
90/*---------------------  Static Definitions -------------------------*/
91//static int          msglevel                =MSG_LEVEL_DEBUG;
92static int          msglevel                =   MSG_LEVEL_INFO;
93
94//#define	PLICE_DEBUG
95//
96// Define module options
97//
98MODULE_AUTHOR("VIA Networking Technologies, Inc., <lyndonchen@vntek.com.tw>");
99MODULE_LICENSE("GPL");
100MODULE_DESCRIPTION("VIA Networking Solomon-A/B/G Wireless LAN Adapter Driver");
101
102//PLICE_DEBUG ->
103	static int mlme_kill;
104	//static  struct task_struct * mlme_task;
105//PLICE_DEBUG <-
106
107#define DEVICE_PARAM(N,D)
108/*
109        static const int N[MAX_UINTS]=OPTION_DEFAULT;\
110        MODULE_PARM(N, "1-" __MODULE_STRING(MAX_UINTS) "i");\
111        MODULE_PARM_DESC(N, D);
112*/
113
114#define RX_DESC_MIN0     16
115#define RX_DESC_MAX0     128
116#define RX_DESC_DEF0     32
117DEVICE_PARAM(RxDescriptors0,"Number of receive descriptors0");
118
119#define RX_DESC_MIN1     16
120#define RX_DESC_MAX1     128
121#define RX_DESC_DEF1     32
122DEVICE_PARAM(RxDescriptors1,"Number of receive descriptors1");
123
124#define TX_DESC_MIN0     16
125#define TX_DESC_MAX0     128
126#define TX_DESC_DEF0     32
127DEVICE_PARAM(TxDescriptors0,"Number of transmit descriptors0");
128
129#define TX_DESC_MIN1     16
130#define TX_DESC_MAX1     128
131#define TX_DESC_DEF1     64
132DEVICE_PARAM(TxDescriptors1,"Number of transmit descriptors1");
133
134
135#define IP_ALIG_DEF     0
136/* IP_byte_align[] is used for IP header DWORD byte aligned
137   0: indicate the IP header won't be DWORD byte aligned.(Default) .
138   1: indicate the IP header will be DWORD byte aligned.
139      In some enviroment, the IP header should be DWORD byte aligned,
140      or the packet will be droped when we receive it. (eg: IPVS)
141*/
142DEVICE_PARAM(IP_byte_align,"Enable IP header dword aligned");
143
144
145#define INT_WORKS_DEF   20
146#define INT_WORKS_MIN   10
147#define INT_WORKS_MAX   64
148
149DEVICE_PARAM(int_works,"Number of packets per interrupt services");
150
151#define CHANNEL_MIN     1
152#define CHANNEL_MAX     14
153#define CHANNEL_DEF     6
154
155DEVICE_PARAM(Channel, "Channel number");
156
157
158/* PreambleType[] is the preamble length used for transmit.
159   0: indicate allows long preamble type
160   1: indicate allows short preamble type
161*/
162
163#define PREAMBLE_TYPE_DEF     1
164
165DEVICE_PARAM(PreambleType, "Preamble Type");
166
167
168#define RTS_THRESH_MIN     512
169#define RTS_THRESH_MAX     2347
170#define RTS_THRESH_DEF     2347
171
172DEVICE_PARAM(RTSThreshold, "RTS threshold");
173
174
175#define FRAG_THRESH_MIN     256
176#define FRAG_THRESH_MAX     2346
177#define FRAG_THRESH_DEF     2346
178
179DEVICE_PARAM(FragThreshold, "Fragmentation threshold");
180
181
182#define DATA_RATE_MIN     0
183#define DATA_RATE_MAX     13
184#define DATA_RATE_DEF     13
185/* datarate[] index
186   0: indicate 1 Mbps   0x02
187   1: indicate 2 Mbps   0x04
188   2: indicate 5.5 Mbps 0x0B
189   3: indicate 11 Mbps  0x16
190   4: indicate 6 Mbps   0x0c
191   5: indicate 9 Mbps   0x12
192   6: indicate 12 Mbps  0x18
193   7: indicate 18 Mbps  0x24
194   8: indicate 24 Mbps  0x30
195   9: indicate 36 Mbps  0x48
196  10: indicate 48 Mbps  0x60
197  11: indicate 54 Mbps  0x6c
198  12: indicate 72 Mbps  0x90
199  13: indicate auto rate
200*/
201
202DEVICE_PARAM(ConnectionRate, "Connection data rate");
203
204#define OP_MODE_DEF     0
205
206DEVICE_PARAM(OPMode, "Infrastruct, adhoc, AP mode ");
207
208/* OpMode[] is used for transmit.
209   0: indicate infrastruct mode used
210   1: indicate adhoc mode used
211   2: indicate AP mode used
212*/
213
214
215/* PSMode[]
216   0: indicate disable power saving mode
217   1: indicate enable power saving mode
218*/
219
220#define PS_MODE_DEF     0
221
222DEVICE_PARAM(PSMode, "Power saving mode");
223
224
225#define SHORT_RETRY_MIN     0
226#define SHORT_RETRY_MAX     31
227#define SHORT_RETRY_DEF     8
228
229
230DEVICE_PARAM(ShortRetryLimit, "Short frame retry limits");
231
232#define LONG_RETRY_MIN     0
233#define LONG_RETRY_MAX     15
234#define LONG_RETRY_DEF     4
235
236
237DEVICE_PARAM(LongRetryLimit, "long frame retry limits");
238
239
240/* BasebandType[] baseband type selected
241   0: indicate 802.11a type
242   1: indicate 802.11b type
243   2: indicate 802.11g type
244*/
245#define BBP_TYPE_MIN     0
246#define BBP_TYPE_MAX     2
247#define BBP_TYPE_DEF     2
248
249DEVICE_PARAM(BasebandType, "baseband type");
250
251
252
253/* 80211hEnable[]
254   0: indicate disable 802.11h
255   1: indicate enable 802.11h
256*/
257
258#define X80211h_MODE_DEF     0
259
260DEVICE_PARAM(b80211hEnable, "802.11h mode");
261
262/* 80211hEnable[]
263   0: indicate disable 802.11h
264   1: indicate enable 802.11h
265*/
266
267#define DIVERSITY_ANT_DEF     0
268
269DEVICE_PARAM(bDiversityANTEnable, "ANT diversity mode");
270
271
272//
273// Static vars definitions
274//
275
276
277static int          device_nics             =0;
278static PSDevice     pDevice_Infos           =NULL;
279static struct net_device *root_device_dev = NULL;
280
281static CHIP_INFO chip_info_table[]= {
282    { VT3253,       "VIA Networking Solomon-A/B/G Wireless LAN Adapter ",
283        256, 1,     DEVICE_FLAGS_IP_ALIGN|DEVICE_FLAGS_TX_ALIGN },
284    {0,NULL}
285};
286
287DEFINE_PCI_DEVICE_TABLE(device_id_table) = {
288	{ PCI_VDEVICE(VIA, 0x3253), (kernel_ulong_t)chip_info_table},
289	{ 0, }
290};
291
292/*---------------------  Static Functions  --------------------------*/
293
294
295static int  device_found1(struct pci_dev *pcid, const struct pci_device_id *ent);
296static BOOL device_init_info(struct pci_dev* pcid, PSDevice* ppDevice, PCHIP_INFO);
297static void device_free_info(PSDevice pDevice);
298static BOOL device_get_pci_info(PSDevice, struct pci_dev* pcid);
299static void device_print_info(PSDevice pDevice);
300static struct net_device_stats *device_get_stats(struct net_device *dev);
301static void device_init_diversity_timer(PSDevice pDevice);
302static int  device_open(struct net_device *dev);
303static int  device_xmit(struct sk_buff *skb, struct net_device *dev);
304static  irqreturn_t  device_intr(int irq,  void*dev_instance);
305static void device_set_multi(struct net_device *dev);
306static int  device_close(struct net_device *dev);
307static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
308
309#ifdef CONFIG_PM
310static int device_notify_reboot(struct notifier_block *, unsigned long event, void *ptr);
311static int viawget_suspend(struct pci_dev *pcid, pm_message_t state);
312static int viawget_resume(struct pci_dev *pcid);
313struct notifier_block device_notifier = {
314        notifier_call:  device_notify_reboot,
315        next:           NULL,
316        priority:       0
317};
318#endif
319
320
321static void device_init_rd0_ring(PSDevice pDevice);
322static void device_init_rd1_ring(PSDevice pDevice);
323static void device_init_defrag_cb(PSDevice pDevice);
324static void device_init_td0_ring(PSDevice pDevice);
325static void device_init_td1_ring(PSDevice pDevice);
326
327static int  device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev);
328//2008-0714<Add>by Mike Liu
329static BOOL device_release_WPADEV(PSDevice pDevice);
330
331static int  ethtool_ioctl(struct net_device *dev, void *useraddr);
332static int  device_rx_srv(PSDevice pDevice, UINT uIdx);
333static int  device_tx_srv(PSDevice pDevice, UINT uIdx);
334static BOOL device_alloc_rx_buf(PSDevice pDevice, PSRxDesc pDesc);
335static void device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType);
336static void device_free_tx_buf(PSDevice pDevice, PSTxDesc pDesc);
337static void device_free_td0_ring(PSDevice pDevice);
338static void device_free_td1_ring(PSDevice pDevice);
339static void device_free_rd0_ring(PSDevice pDevice);
340static void device_free_rd1_ring(PSDevice pDevice);
341static void device_free_rings(PSDevice pDevice);
342static void device_free_frag_buf(PSDevice pDevice);
343static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source);
344
345
346/*---------------------  Export Variables  --------------------------*/
347
348/*---------------------  Export Functions  --------------------------*/
349
350
351
352static char* get_chip_name(int chip_id) {
353    int i;
354    for (i=0;chip_info_table[i].name!=NULL;i++)
355        if (chip_info_table[i].chip_id==chip_id)
356            break;
357    return chip_info_table[i].name;
358}
359
360static void device_remove1(struct pci_dev *pcid)
361{
362    PSDevice pDevice=pci_get_drvdata(pcid);
363
364    if (pDevice==NULL)
365        return;
366    device_free_info(pDevice);
367
368}
369
370/*
371static void
372device_set_int_opt(int *opt, int val, int min, int max, int def,char* name,char* devname) {
373    if (val==-1)
374        *opt=def;
375    else if (val<min || val>max) {
376        DBG_PRT(MSG_LEVEL_INFO, KERN_NOTICE "%s: the value of parameter %s is invalid, the valid range is (%d-%d)\n" ,
377            devname,name, min,max);
378        *opt=def;
379    } else {
380        DBG_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: set value of parameter %s to %d\n",
381            devname, name, val);
382        *opt=val;
383    }
384}
385
386static void
387device_set_bool_opt(unsigned int *opt, int val,BOOL def,U32 flag, char* name,char* devname) {
388    (*opt)&=(~flag);
389    if (val==-1)
390        *opt|=(def ? flag : 0);
391    else if (val<0 || val>1) {
392        DBG_PRT(MSG_LEVEL_INFO, KERN_NOTICE
393            "%s: the value of parameter %s is invalid, the valid range is (0-1)\n",devname,name);
394        *opt|=(def ? flag : 0);
395    } else {
396        DBG_PRT(MSG_LEVEL_INFO, KERN_NOTICE "%s: set parameter %s to %s\n",
397            devname,name , val ? "TRUE" : "FALSE");
398        *opt|=(val ? flag : 0);
399    }
400}
401*/
402static void
403device_get_options(PSDevice pDevice, int index, char* devname) {
404
405    POPTIONS pOpts = &(pDevice->sOpts);
406  pOpts->nRxDescs0=RX_DESC_DEF0;
407  pOpts->nRxDescs1=RX_DESC_DEF1;
408  pOpts->nTxDescs[0]=TX_DESC_DEF0;
409  pOpts->nTxDescs[1]=TX_DESC_DEF1;
410pOpts->flags|=DEVICE_FLAGS_IP_ALIGN;
411  pOpts->int_works=INT_WORKS_DEF;
412  pOpts->rts_thresh=RTS_THRESH_DEF;
413  pOpts->frag_thresh=FRAG_THRESH_DEF;
414  pOpts->data_rate=DATA_RATE_DEF;
415  pOpts->channel_num=CHANNEL_DEF;
416
417pOpts->flags|=DEVICE_FLAGS_PREAMBLE_TYPE;
418pOpts->flags|=DEVICE_FLAGS_OP_MODE;
419//pOpts->flags|=DEVICE_FLAGS_PS_MODE;
420  pOpts->short_retry=SHORT_RETRY_DEF;
421  pOpts->long_retry=LONG_RETRY_DEF;
422  pOpts->bbp_type=BBP_TYPE_DEF;
423pOpts->flags|=DEVICE_FLAGS_80211h_MODE;
424pOpts->flags|=DEVICE_FLAGS_DiversityANT;
425
426
427}
428
429static void
430device_set_options(PSDevice pDevice) {
431
432    BYTE    abyBroadcastAddr[ETH_ALEN] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
433    BYTE    abySNAP_RFC1042[ETH_ALEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0x00};
434    BYTE    abySNAP_Bridgetunnel[ETH_ALEN] = {0xAA, 0xAA, 0x03, 0x00, 0x00, 0xF8};
435
436
437    memcpy(pDevice->abyBroadcastAddr, abyBroadcastAddr, ETH_ALEN);
438    memcpy(pDevice->abySNAP_RFC1042, abySNAP_RFC1042, ETH_ALEN);
439    memcpy(pDevice->abySNAP_Bridgetunnel, abySNAP_Bridgetunnel, ETH_ALEN);
440
441    pDevice->uChannel = pDevice->sOpts.channel_num;
442    pDevice->wRTSThreshold = pDevice->sOpts.rts_thresh;
443    pDevice->wFragmentationThreshold = pDevice->sOpts.frag_thresh;
444    pDevice->byShortRetryLimit = pDevice->sOpts.short_retry;
445    pDevice->byLongRetryLimit = pDevice->sOpts.long_retry;
446    pDevice->wMaxTransmitMSDULifetime = DEFAULT_MSDU_LIFETIME;
447    pDevice->byShortPreamble = (pDevice->sOpts.flags & DEVICE_FLAGS_PREAMBLE_TYPE) ? 1 : 0;
448    pDevice->byOpMode = (pDevice->sOpts.flags & DEVICE_FLAGS_OP_MODE) ? 1 : 0;
449    pDevice->ePSMode = (pDevice->sOpts.flags & DEVICE_FLAGS_PS_MODE) ? 1 : 0;
450    pDevice->b11hEnable = (pDevice->sOpts.flags & DEVICE_FLAGS_80211h_MODE) ? 1 : 0;
451    pDevice->bDiversityRegCtlON = (pDevice->sOpts.flags & DEVICE_FLAGS_DiversityANT) ? 1 : 0;
452    pDevice->uConnectionRate = pDevice->sOpts.data_rate;
453    if (pDevice->uConnectionRate < RATE_AUTO) pDevice->bFixRate = TRUE;
454    pDevice->byBBType = pDevice->sOpts.bbp_type;
455    pDevice->byPacketType = pDevice->byBBType;
456
457//PLICE_DEBUG->
458	pDevice->byAutoFBCtrl = AUTO_FB_0;
459	//pDevice->byAutoFBCtrl = AUTO_FB_1;
460//PLICE_DEBUG<-
461pDevice->bUpdateBBVGA = TRUE;
462    pDevice->byFOETuning = 0;
463    pDevice->wCTSDuration = 0;
464    pDevice->byPreambleType = 0;
465
466
467    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" uChannel= %d\n",(INT)pDevice->uChannel);
468    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byOpMode= %d\n",(INT)pDevice->byOpMode);
469    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" ePSMode= %d\n",(INT)pDevice->ePSMode);
470    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" wRTSThreshold= %d\n",(INT)pDevice->wRTSThreshold);
471    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byShortRetryLimit= %d\n",(INT)pDevice->byShortRetryLimit);
472    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byLongRetryLimit= %d\n",(INT)pDevice->byLongRetryLimit);
473    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byPreambleType= %d\n",(INT)pDevice->byPreambleType);
474    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byShortPreamble= %d\n",(INT)pDevice->byShortPreamble);
475    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" uConnectionRate= %d\n",(INT)pDevice->uConnectionRate);
476    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" byBBType= %d\n",(INT)pDevice->byBBType);
477    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->b11hEnable= %d\n",(INT)pDevice->b11hEnable);
478    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->bDiversityRegCtlON= %d\n",(INT)pDevice->bDiversityRegCtlON);
479}
480
481static void s_vCompleteCurrentMeasure (PSDevice pDevice, BYTE byResult)
482{
483    UINT    ii;
484    DWORD   dwDuration = 0;
485    BYTE    byRPI0 = 0;
486
487    for(ii=1;ii<8;ii++) {
488        pDevice->dwRPIs[ii] *= 255;
489        dwDuration |= *((PWORD) (pDevice->pCurrMeasureEID->sReq.abyDuration));
490        dwDuration <<= 10;
491        pDevice->dwRPIs[ii] /= dwDuration;
492        pDevice->abyRPIs[ii] = (BYTE) pDevice->dwRPIs[ii];
493        byRPI0 += pDevice->abyRPIs[ii];
494    }
495    pDevice->abyRPIs[0] = (0xFF - byRPI0);
496
497     if (pDevice->uNumOfMeasureEIDs == 0) {
498        VNTWIFIbMeasureReport(  pDevice->pMgmt,
499                                TRUE,
500                                pDevice->pCurrMeasureEID,
501                                byResult,
502                                pDevice->byBasicMap,
503                                pDevice->byCCAFraction,
504                                pDevice->abyRPIs
505                                );
506    } else {
507        VNTWIFIbMeasureReport(  pDevice->pMgmt,
508                                FALSE,
509                                pDevice->pCurrMeasureEID,
510                                byResult,
511                                pDevice->byBasicMap,
512                                pDevice->byCCAFraction,
513                                pDevice->abyRPIs
514                                );
515        CARDbStartMeasure (pDevice, pDevice->pCurrMeasureEID++, pDevice->uNumOfMeasureEIDs);
516    }
517
518}
519
520
521
522//
523// Initialiation of MAC & BBP registers
524//
525
526static void device_init_registers(PSDevice pDevice, DEVICE_INIT_TYPE InitType)
527{
528    UINT    ii;
529    BYTE    byValue;
530	BYTE    byValue1;
531    BYTE    byCCKPwrdBm = 0;
532    BYTE    byOFDMPwrdBm = 0;
533    INT zonetype=0;
534     PSMgmtObject    pMgmt = &(pDevice->sMgmtObj);
535    MACbShutdown(pDevice->PortOffset);
536    BBvSoftwareReset(pDevice->PortOffset);
537
538    if ((InitType == DEVICE_INIT_COLD) ||
539        (InitType == DEVICE_INIT_DXPL)) {
540        // Do MACbSoftwareReset in MACvInitialize
541        MACbSoftwareReset(pDevice->PortOffset);
542        // force CCK
543        pDevice->bCCK = TRUE;
544        pDevice->bAES = FALSE;
545        pDevice->bProtectMode = FALSE;      //Only used in 11g type, sync with ERP IE
546        pDevice->bNonERPPresent = FALSE;
547        pDevice->bBarkerPreambleMd = FALSE;
548        pDevice->wCurrentRate = RATE_1M;
549        pDevice->byTopOFDMBasicRate = RATE_24M;
550        pDevice->byTopCCKBasicRate = RATE_1M;
551
552        pDevice->byRevId = 0;                   //Target to IF pin while programming to RF chip.
553
554        // init MAC
555        MACvInitialize(pDevice->PortOffset);
556
557        // Get Local ID
558        VNSvInPortB(pDevice->PortOffset + MAC_REG_LOCALID, &(pDevice->byLocalID));
559
560           spin_lock_irq(&pDevice->lock);
561	 SROMvReadAllContents(pDevice->PortOffset,pDevice->abyEEPROM);
562
563           spin_unlock_irq(&pDevice->lock);
564
565        // Get Channel range
566
567        pDevice->byMinChannel = 1;
568        pDevice->byMaxChannel = CB_MAX_CHANNEL;
569
570        // Get Antena
571        byValue = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ANTENNA);
572        if (byValue & EEP_ANTINV)
573            pDevice->bTxRxAntInv = TRUE;
574        else
575            pDevice->bTxRxAntInv = FALSE;
576#ifdef	PLICE_DEBUG
577	//printk("init_register:TxRxAntInv is %d,byValue is %d\n",pDevice->bTxRxAntInv,byValue);
578#endif
579
580        byValue &= (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
581        if (byValue == 0) // if not set default is All
582            byValue = (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN);
583#ifdef	PLICE_DEBUG
584	//printk("init_register:byValue is %d\n",byValue);
585#endif
586        pDevice->ulDiversityNValue = 100*260;//100*SROMbyReadEmbedded(pDevice->PortOffset, 0x51);
587        pDevice->ulDiversityMValue = 100*16;//SROMbyReadEmbedded(pDevice->PortOffset, 0x52);
588        pDevice->byTMax = 1;//SROMbyReadEmbedded(pDevice->PortOffset, 0x53);
589        pDevice->byTMax2 = 4;//SROMbyReadEmbedded(pDevice->PortOffset, 0x54);
590        pDevice->ulSQ3TH = 0;//(ULONG) SROMbyReadEmbedded(pDevice->PortOffset, 0x55);
591        pDevice->byTMax3 = 64;//SROMbyReadEmbedded(pDevice->PortOffset, 0x56);
592
593        if (byValue == (EEP_ANTENNA_AUX | EEP_ANTENNA_MAIN)) {
594            pDevice->byAntennaCount = 2;
595            pDevice->byTxAntennaMode = ANT_B;
596            pDevice->dwTxAntennaSel = 1;
597            pDevice->dwRxAntennaSel = 1;
598            if (pDevice->bTxRxAntInv == TRUE)
599                pDevice->byRxAntennaMode = ANT_A;
600            else
601                pDevice->byRxAntennaMode = ANT_B;
602                // chester for antenna
603byValue1 = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ANTENNA);
604          //  if (pDevice->bDiversityRegCtlON)
605          if((byValue1&0x08)==0)
606                pDevice->bDiversityEnable = FALSE;//SROMbyReadEmbedded(pDevice->PortOffset, 0x50);
607            else
608                pDevice->bDiversityEnable = TRUE;
609#ifdef	PLICE_DEBUG
610		//printk("aux |main antenna: RxAntennaMode is %d\n",pDevice->byRxAntennaMode);
611#endif
612	} else  {
613            pDevice->bDiversityEnable = FALSE;
614            pDevice->byAntennaCount = 1;
615            pDevice->dwTxAntennaSel = 0;
616            pDevice->dwRxAntennaSel = 0;
617            if (byValue & EEP_ANTENNA_AUX) {
618                pDevice->byTxAntennaMode = ANT_A;
619                if (pDevice->bTxRxAntInv == TRUE)
620                    pDevice->byRxAntennaMode = ANT_B;
621                else
622                    pDevice->byRxAntennaMode = ANT_A;
623            } else {
624                pDevice->byTxAntennaMode = ANT_B;
625                if (pDevice->bTxRxAntInv == TRUE)
626                    pDevice->byRxAntennaMode = ANT_A;
627                else
628                    pDevice->byRxAntennaMode = ANT_B;
629            }
630        }
631#ifdef	PLICE_DEBUG
632	//printk("init registers: TxAntennaMode is %d\n",pDevice->byTxAntennaMode);
633#endif
634        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "bDiversityEnable=[%d],NValue=[%d],MValue=[%d],TMax=[%d],TMax2=[%d]\n",
635            pDevice->bDiversityEnable,(int)pDevice->ulDiversityNValue,(int)pDevice->ulDiversityMValue,pDevice->byTMax,pDevice->byTMax2);
636
637//#ifdef ZoneType_DefaultSetting
638//2008-8-4 <add> by chester
639//zonetype initial
640 pDevice->byOriginalZonetype = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
641 zonetype = Config_FileOperation(pDevice,FALSE,NULL);
642 if (zonetype >= 0) {         //read zonetype file ok!
643  if ((zonetype == 0)&&
644        (pDevice->abyEEPROM[EEP_OFS_ZONETYPE] !=0x00)){          //for USA
645    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0;
646    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0B;
647    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :USA\n");
648  }
649 else if((zonetype == 1)&&
650 	     (pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x01)){   //for Japan
651    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x01;
652    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
653  }
654 else if((zonetype == 2)&&
655 	     (pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x02)){   //for Europe
656    pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x02;
657    pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
658    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :Europe\n");
659  }
660
661else
662{
663   if(zonetype!=pDevice->abyEEPROM[EEP_OFS_ZONETYPE])
664      printk("zonetype in file[%02x] mismatch with in EEPROM[%02x]\n",zonetype,pDevice->abyEEPROM[EEP_OFS_ZONETYPE]);
665   else
666      printk("Read Zonetype file success,use default zonetype setting[%02x]\n",zonetype);
667 }
668 	}
669  else
670    printk("Read Zonetype file fail,use default zonetype setting[%02x]\n",SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_ZONETYPE));
671
672        // Get RFType
673        pDevice->byRFType = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RFTYPE);
674
675        if ((pDevice->byRFType & RF_EMU) != 0) {
676            // force change RevID for VT3253 emu
677            pDevice->byRevId = 0x80;
678        }
679
680        pDevice->byRFType &= RF_MASK;
681        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRFType = %x\n", pDevice->byRFType);
682
683        if (pDevice->bZoneRegExist == FALSE) {
684            pDevice->byZoneType = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
685        }
686        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byZoneType = %x\n", pDevice->byZoneType);
687
688        //Init RF module
689        RFbInit(pDevice);
690
691        //Get Desire Power Value
692        pDevice->byCurPwr = 0xFF;
693        pDevice->byCCKPwr = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_PWR_CCK);
694        pDevice->byOFDMPwrG = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_PWR_OFDMG);
695        //byCCKPwrdBm = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_CCK_PWR_dBm);
696
697	//byOFDMPwrdBm = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_OFDM_PWR_dBm);
698//printk("CCKPwrdBm is 0x%x,byOFDMPwrdBm is 0x%x\n",byCCKPwrdBm,byOFDMPwrdBm);
699		// Load power Table
700
701
702        for (ii=0;ii<CB_MAX_CHANNEL_24G;ii++) {
703            pDevice->abyCCKPwrTbl[ii+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_CCK_PWR_TBL));
704            if (pDevice->abyCCKPwrTbl[ii+1] == 0) {
705                pDevice->abyCCKPwrTbl[ii+1] = pDevice->byCCKPwr;
706            }
707            pDevice->abyOFDMPwrTbl[ii+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDM_PWR_TBL));
708            if (pDevice->abyOFDMPwrTbl[ii+1] == 0) {
709                pDevice->abyOFDMPwrTbl[ii+1] = pDevice->byOFDMPwrG;
710            }
711            pDevice->abyCCKDefaultPwr[ii+1] = byCCKPwrdBm;
712            pDevice->abyOFDMDefaultPwr[ii+1] = byOFDMPwrdBm;
713        }
714		//2008-8-4 <add> by chester
715	  //recover 12,13 ,14channel for EUROPE by 11 channel
716          if(((pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Japan) ||
717	        (pDevice->abyEEPROM[EEP_OFS_ZONETYPE] == ZoneType_Europe))&&
718	     (pDevice->byOriginalZonetype == ZoneType_USA)) {
719	    for(ii=11;ii<14;ii++) {
720                pDevice->abyCCKPwrTbl[ii] = pDevice->abyCCKPwrTbl[10];
721	       pDevice->abyOFDMPwrTbl[ii] = pDevice->abyOFDMPwrTbl[10];
722
723	    }
724	  }
725
726
727        // Load OFDM A Power Table
728        for (ii=0;ii<CB_MAX_CHANNEL_5G;ii++) { //RobertYu:20041224, bug using CB_MAX_CHANNEL
729            pDevice->abyOFDMPwrTbl[ii+CB_MAX_CHANNEL_24G+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDMA_PWR_TBL));
730            pDevice->abyOFDMDefaultPwr[ii+CB_MAX_CHANNEL_24G+1] = SROMbyReadEmbedded(pDevice->PortOffset, (BYTE)(ii + EEP_OFS_OFDMA_PWR_dBm));
731        }
732        CARDvInitChannelTable((void *)pDevice);
733
734
735        if (pDevice->byLocalID > REV_ID_VT3253_B1) {
736            MACvSelectPage1(pDevice->PortOffset);
737            VNSvOutPortB(pDevice->PortOffset + MAC_REG_MSRCTL + 1, (MSRCTL1_TXPWR | MSRCTL1_CSAPAREN));
738            MACvSelectPage0(pDevice->PortOffset);
739        }
740
741
742         // use relative tx timeout and 802.11i D4
743        MACvWordRegBitsOn(pDevice->PortOffset, MAC_REG_CFG, (CFG_TKIPOPT | CFG_NOTXTIMEOUT));
744
745        // set performance parameter by registry
746        MACvSetShortRetryLimit(pDevice->PortOffset, pDevice->byShortRetryLimit);
747        MACvSetLongRetryLimit(pDevice->PortOffset, pDevice->byLongRetryLimit);
748
749        // reset TSF counter
750        VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
751        // enable TSF counter
752        VNSvOutPortB(pDevice->PortOffset + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
753
754        // initialize BBP registers
755        BBbVT3253Init(pDevice);
756
757        if (pDevice->bUpdateBBVGA) {
758            pDevice->byBBVGACurrent = pDevice->abyBBVGA[0];
759            pDevice->byBBVGANew = pDevice->byBBVGACurrent;
760            BBvSetVGAGainOffset(pDevice, pDevice->abyBBVGA[0]);
761        }
762#ifdef	PLICE_DEBUG
763	//printk("init registers:RxAntennaMode is %x,TxAntennaMode is %x\n",pDevice->byRxAntennaMode,pDevice->byTxAntennaMode);
764#endif
765        BBvSetRxAntennaMode(pDevice->PortOffset, pDevice->byRxAntennaMode);
766        BBvSetTxAntennaMode(pDevice->PortOffset, pDevice->byTxAntennaMode);
767
768        pDevice->byCurrentCh = 0;
769
770        //pDevice->NetworkType = Ndis802_11Automode;
771        // Set BB and packet type at the same time.
772        // Set Short Slot Time, xIFS, and RSPINF.
773        if (pDevice->uConnectionRate == RATE_AUTO) {
774            pDevice->wCurrentRate = RATE_54M;
775        } else {
776            pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
777        }
778
779        // default G Mode
780        VNTWIFIbConfigPhyMode(pDevice->pMgmt, PHY_TYPE_11G);
781        VNTWIFIbConfigPhyMode(pDevice->pMgmt, PHY_TYPE_AUTO);
782
783        pDevice->bRadioOff = FALSE;
784
785        pDevice->byRadioCtl = SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RADIOCTL);
786        pDevice->bHWRadioOff = FALSE;
787
788        if (pDevice->byRadioCtl & EEP_RADIOCTL_ENABLE) {
789            // Get GPIO
790            MACvGPIOIn(pDevice->PortOffset, &pDevice->byGPIO);
791//2008-4-14 <add> by chester for led issue
792 #ifdef FOR_LED_ON_NOTEBOOK
793if (pDevice->byGPIO & GPIO0_DATA){pDevice->bHWRadioOff = TRUE;}
794if ( !(pDevice->byGPIO & GPIO0_DATA)){pDevice->bHWRadioOff = FALSE;}
795
796            }
797        if ( (pDevice->bRadioControlOff == TRUE)) {
798            CARDbRadioPowerOff(pDevice);
799        }
800else  CARDbRadioPowerOn(pDevice);
801#else
802            if (((pDevice->byGPIO & GPIO0_DATA) && !(pDevice->byRadioCtl & EEP_RADIOCTL_INV)) ||
803                ( !(pDevice->byGPIO & GPIO0_DATA) && (pDevice->byRadioCtl & EEP_RADIOCTL_INV))) {
804                pDevice->bHWRadioOff = TRUE;
805            }
806        }
807        if ((pDevice->bHWRadioOff == TRUE) || (pDevice->bRadioControlOff == TRUE)) {
808            CARDbRadioPowerOff(pDevice);
809        }
810
811#endif
812    }
813            pMgmt->eScanType = WMAC_SCAN_PASSIVE;
814    // get Permanent network address
815    SROMvReadEtherAddress(pDevice->PortOffset, pDevice->abyCurrentNetAddr);
816    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Network address = %02x-%02x-%02x=%02x-%02x-%02x\n",
817        pDevice->abyCurrentNetAddr[0],
818        pDevice->abyCurrentNetAddr[1],
819        pDevice->abyCurrentNetAddr[2],
820        pDevice->abyCurrentNetAddr[3],
821        pDevice->abyCurrentNetAddr[4],
822        pDevice->abyCurrentNetAddr[5]);
823
824
825    // reset Tx pointer
826    CARDvSafeResetRx(pDevice);
827    // reset Rx pointer
828    CARDvSafeResetTx(pDevice);
829
830    if (pDevice->byLocalID <= REV_ID_VT3253_A1) {
831        MACvRegBitsOn(pDevice->PortOffset, MAC_REG_RCR, RCR_WPAERR);
832    }
833
834    pDevice->eEncryptionStatus = Ndis802_11EncryptionDisabled;
835
836    // Turn On Rx DMA
837    MACvReceive0(pDevice->PortOffset);
838    MACvReceive1(pDevice->PortOffset);
839
840    // start the adapter
841    MACvStart(pDevice->PortOffset);
842
843    netif_stop_queue(pDevice->dev);
844
845
846}
847
848
849
850static void device_init_diversity_timer(PSDevice pDevice) {
851
852    init_timer(&pDevice->TimerSQ3Tmax1);
853    pDevice->TimerSQ3Tmax1.data = (ULONG)pDevice;
854    pDevice->TimerSQ3Tmax1.function = (TimerFunction)TimerSQ3CallBack;
855    pDevice->TimerSQ3Tmax1.expires = RUN_AT(HZ);
856
857    init_timer(&pDevice->TimerSQ3Tmax2);
858    pDevice->TimerSQ3Tmax2.data = (ULONG)pDevice;
859    pDevice->TimerSQ3Tmax2.function = (TimerFunction)TimerSQ3CallBack;
860    pDevice->TimerSQ3Tmax2.expires = RUN_AT(HZ);
861
862    init_timer(&pDevice->TimerSQ3Tmax3);
863    pDevice->TimerSQ3Tmax3.data = (ULONG)pDevice;
864    pDevice->TimerSQ3Tmax3.function = (TimerFunction)TimerState1CallBack;
865    pDevice->TimerSQ3Tmax3.expires = RUN_AT(HZ);
866
867    return;
868}
869
870
871static BOOL device_release_WPADEV(PSDevice pDevice)
872{
873  viawget_wpa_header *wpahdr;
874  int ii=0;
875 // wait_queue_head_t	Set_wait;
876  //send device close to wpa_supplicnat layer
877    if (pDevice->bWPADEVUp==TRUE) {
878                 wpahdr = (viawget_wpa_header *)pDevice->skb->data;
879                 wpahdr->type = VIAWGET_DEVICECLOSE_MSG;
880                 wpahdr->resp_ie_len = 0;
881                 wpahdr->req_ie_len = 0;
882                 skb_put(pDevice->skb, sizeof(viawget_wpa_header));
883                 pDevice->skb->dev = pDevice->wpadev;
884		 skb_reset_mac_header(pDevice->skb);
885                 pDevice->skb->pkt_type = PACKET_HOST;
886                 pDevice->skb->protocol = htons(ETH_P_802_2);
887                 memset(pDevice->skb->cb, 0, sizeof(pDevice->skb->cb));
888                 netif_rx(pDevice->skb);
889                 pDevice->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
890
891 //wait release WPADEV
892              //    init_waitqueue_head(&Set_wait);
893              //    wait_event_timeout(Set_wait, ((pDevice->wpadev==NULL)&&(pDevice->skb == NULL)),5*HZ);    //1s wait
894              while((pDevice->bWPADEVUp==TRUE)) {
895	        set_current_state(TASK_UNINTERRUPTIBLE);
896                 schedule_timeout (HZ/20);          //wait 50ms
897                 ii++;
898	        if(ii>20)
899		  break;
900              }
901           };
902    return TRUE;
903}
904
905
906static const struct net_device_ops device_netdev_ops = {
907    .ndo_open               = device_open,
908    .ndo_stop               = device_close,
909    .ndo_do_ioctl           = device_ioctl,
910    .ndo_get_stats          = device_get_stats,
911    .ndo_start_xmit         = device_xmit,
912    .ndo_set_multicast_list = device_set_multi,
913};
914
915
916
917static int
918device_found1(struct pci_dev *pcid, const struct pci_device_id *ent)
919{
920    static BOOL bFirst = TRUE;
921    struct net_device*  dev = NULL;
922    PCHIP_INFO  pChip_info = (PCHIP_INFO)ent->driver_data;
923    PSDevice    pDevice;
924    int         rc;
925    if (device_nics ++>= MAX_UINTS) {
926        printk(KERN_NOTICE DEVICE_NAME ": already found %d NICs\n", device_nics);
927        return -ENODEV;
928    }
929
930
931    dev = alloc_etherdev(sizeof(DEVICE_INFO));
932
933    pDevice = (PSDevice) netdev_priv(dev);
934
935    if (dev == NULL) {
936        printk(KERN_ERR DEVICE_NAME ": allocate net device failed \n");
937        return -ENODEV;
938    }
939
940    // Chain it all together
941   // SET_MODULE_OWNER(dev);
942    SET_NETDEV_DEV(dev, &pcid->dev);
943
944    if (bFirst) {
945        printk(KERN_NOTICE "%s Ver. %s\n",DEVICE_FULL_DRV_NAM, DEVICE_VERSION);
946        printk(KERN_NOTICE "Copyright (c) 2003 VIA Networking Technologies, Inc.\n");
947        bFirst=FALSE;
948    }
949
950    if (!device_init_info(pcid, &pDevice, pChip_info)) {
951        return -ENOMEM;
952    }
953    pDevice->dev = dev;
954    pDevice->next_module = root_device_dev;
955    root_device_dev = dev;
956    dev->irq = pcid->irq;
957
958    if (pci_enable_device(pcid)) {
959        device_free_info(pDevice);
960        return -ENODEV;
961    }
962#ifdef	DEBUG
963	printk("Before get pci_info memaddr is %x\n",pDevice->memaddr);
964#endif
965    if (device_get_pci_info(pDevice,pcid) == FALSE) {
966        printk(KERN_ERR DEVICE_NAME ": Failed to find PCI device.\n");
967        device_free_info(pDevice);
968        return -ENODEV;
969    }
970
971#if 1
972
973#ifdef	DEBUG
974
975	//pci_read_config_byte(pcid, PCI_BASE_ADDRESS_0, &pDevice->byRevId);
976	printk("after get pci_info memaddr is %x, io addr is %x,io_size is %d\n",pDevice->memaddr,pDevice->ioaddr,pDevice->io_size);
977	{
978		int i;
979		U32			bar,len;
980		u32 address[] = {
981		PCI_BASE_ADDRESS_0,
982		PCI_BASE_ADDRESS_1,
983		PCI_BASE_ADDRESS_2,
984		PCI_BASE_ADDRESS_3,
985		PCI_BASE_ADDRESS_4,
986		PCI_BASE_ADDRESS_5,
987		0};
988		for (i=0;address[i];i++)
989		{
990			//pci_write_config_dword(pcid,address[i], 0xFFFFFFFF);
991			pci_read_config_dword(pcid, address[i], &bar);
992			printk("bar %d is %x\n",i,bar);
993			if (!bar)
994			{
995				printk("bar %d not implemented\n",i);
996				continue;
997			}
998			if (bar & PCI_BASE_ADDRESS_SPACE_IO) {
999			/* This is IO */
1000
1001			len = bar & (PCI_BASE_ADDRESS_IO_MASK & 0xFFFF);
1002			len = len & ~(len - 1);
1003
1004			printk("IO space:  len in IO %x, BAR %d\n", len, i);
1005			}
1006			else
1007			{
1008				len = bar & 0xFFFFFFF0;
1009				len = ~len + 1;
1010
1011				printk("len in MEM %x, BAR %d\n", len, i);
1012			}
1013		}
1014	}
1015#endif
1016
1017
1018#endif
1019
1020#ifdef	DEBUG
1021	//return  0  ;
1022#endif
1023    pDevice->PortOffset = (DWORD)ioremap(pDevice->memaddr & PCI_BASE_ADDRESS_MEM_MASK, pDevice->io_size);
1024	//pDevice->PortOffset = (DWORD)ioremap(pDevice->ioaddr & PCI_BASE_ADDRESS_IO_MASK, pDevice->io_size);
1025
1026	if(pDevice->PortOffset == 0) {
1027       printk(KERN_ERR DEVICE_NAME ": Failed to IO remapping ..\n");
1028       device_free_info(pDevice);
1029        return -ENODEV;
1030    }
1031
1032
1033
1034
1035    rc = pci_request_regions(pcid, DEVICE_NAME);
1036    if (rc) {
1037        printk(KERN_ERR DEVICE_NAME ": Failed to find PCI device\n");
1038        device_free_info(pDevice);
1039        return -ENODEV;
1040    }
1041
1042    dev->base_addr = pDevice->ioaddr;
1043#ifdef	PLICE_DEBUG
1044	BYTE	value;
1045
1046	VNSvInPortB(pDevice->PortOffset+0x4F, &value);
1047	printk("Before write: value is %x\n",value);
1048	//VNSvInPortB(pDevice->PortOffset+0x3F, 0x00);
1049	VNSvOutPortB(pDevice->PortOffset,value);
1050	VNSvInPortB(pDevice->PortOffset+0x4F, &value);
1051	printk("After write: value is %x\n",value);
1052#endif
1053
1054
1055
1056#ifdef IO_MAP
1057    pDevice->PortOffset = pDevice->ioaddr;
1058#endif
1059    // do reset
1060    if (!MACbSoftwareReset(pDevice->PortOffset)) {
1061        printk(KERN_ERR DEVICE_NAME ": Failed to access MAC hardware..\n");
1062        device_free_info(pDevice);
1063        return -ENODEV;
1064    }
1065    // initial to reload eeprom
1066    MACvInitialize(pDevice->PortOffset);
1067    MACvReadEtherAddress(pDevice->PortOffset, dev->dev_addr);
1068
1069    device_get_options(pDevice, device_nics-1, dev->name);
1070    device_set_options(pDevice);
1071    //Mask out the options cannot be set to the chip
1072    pDevice->sOpts.flags &= pChip_info->flags;
1073
1074    //Enable the chip specified capbilities
1075    pDevice->flags = pDevice->sOpts.flags | (pChip_info->flags & 0xFF000000UL);
1076    pDevice->tx_80211 = device_dma0_tx_80211;
1077    pDevice->sMgmtObj.pAdapter = (void *)pDevice;
1078    pDevice->pMgmt = &(pDevice->sMgmtObj);
1079
1080    dev->irq                = pcid->irq;
1081    dev->netdev_ops         = &device_netdev_ops;
1082
1083	dev->wireless_handlers = (struct iw_handler_def *)&iwctl_handler_def;
1084
1085    rc = register_netdev(dev);
1086    if (rc)
1087    {
1088        printk(KERN_ERR DEVICE_NAME " Failed to register netdev\n");
1089        device_free_info(pDevice);
1090        return -ENODEV;
1091    }
1092//2008-07-21-01<Add>by MikeLiu
1093//register wpadev
1094#if 0
1095   if(wpa_set_wpadev(pDevice, 1)!=0) {
1096     printk("Fail to Register WPADEV?\n");
1097        unregister_netdev(pDevice->dev);
1098        free_netdev(dev);
1099   }
1100#endif
1101    device_print_info(pDevice);
1102    pci_set_drvdata(pcid, pDevice);
1103    return 0;
1104
1105}
1106
1107static void device_print_info(PSDevice pDevice)
1108{
1109    struct net_device* dev=pDevice->dev;
1110
1111    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: %s\n",dev->name, get_chip_name(pDevice->chip_id));
1112    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO "%s: MAC=%pM", dev->name, dev->dev_addr);
1113#ifdef IO_MAP
1114    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO" IO=0x%lx  ",(ULONG) pDevice->ioaddr);
1115    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO" IRQ=%d \n", pDevice->dev->irq);
1116#else
1117    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO" IO=0x%lx Mem=0x%lx ",(ULONG) pDevice->ioaddr,(ULONG) pDevice->PortOffset);
1118    DBG_PRT(MSG_LEVEL_INFO, KERN_INFO" IRQ=%d \n", pDevice->dev->irq);
1119#endif
1120
1121}
1122
1123static BOOL device_init_info(struct pci_dev* pcid, PSDevice* ppDevice,
1124    PCHIP_INFO pChip_info) {
1125
1126    PSDevice p;
1127
1128    memset(*ppDevice,0,sizeof(DEVICE_INFO));
1129
1130    if (pDevice_Infos == NULL) {
1131        pDevice_Infos =*ppDevice;
1132    }
1133    else {
1134        for (p=pDevice_Infos;p->next!=NULL;p=p->next)
1135            do {} while (0);
1136        p->next = *ppDevice;
1137        (*ppDevice)->prev = p;
1138    }
1139
1140    (*ppDevice)->pcid = pcid;
1141    (*ppDevice)->chip_id = pChip_info->chip_id;
1142    (*ppDevice)->io_size = pChip_info->io_size;
1143    (*ppDevice)->nTxQueues = pChip_info->nTxQueue;
1144    (*ppDevice)->multicast_limit =32;
1145
1146    spin_lock_init(&((*ppDevice)->lock));
1147
1148    return TRUE;
1149}
1150
1151static BOOL device_get_pci_info(PSDevice pDevice, struct pci_dev* pcid) {
1152
1153    U16 pci_cmd;
1154    U8  b;
1155    UINT cis_addr;
1156#ifdef	PLICE_DEBUG
1157	BYTE       pci_config[256];
1158	BYTE	value =0x00;
1159	int		ii,j;
1160	U16	max_lat=0x0000;
1161	memset(pci_config,0x00,256);
1162#endif
1163
1164    pci_read_config_byte(pcid, PCI_REVISION_ID, &pDevice->byRevId);
1165    pci_read_config_word(pcid, PCI_SUBSYSTEM_ID,&pDevice->SubSystemID);
1166    pci_read_config_word(pcid, PCI_SUBSYSTEM_VENDOR_ID, &pDevice->SubVendorID);
1167    pci_read_config_word(pcid, PCI_COMMAND, (u16 *) & (pci_cmd));
1168
1169    pci_set_master(pcid);
1170
1171    pDevice->memaddr = pci_resource_start(pcid,0);
1172    pDevice->ioaddr = pci_resource_start(pcid,1);
1173
1174#ifdef	DEBUG
1175//	pDevice->ioaddr = pci_resource_start(pcid, 0);
1176//	pDevice->memaddr = pci_resource_start(pcid,1);
1177#endif
1178
1179    cis_addr = pci_resource_start(pcid,2);
1180
1181    pDevice->pcid = pcid;
1182
1183    pci_read_config_byte(pcid, PCI_COMMAND, &b);
1184    pci_write_config_byte(pcid, PCI_COMMAND, (b|PCI_COMMAND_MASTER));
1185
1186#ifdef	PLICE_DEBUG
1187   	//pci_read_config_word(pcid,PCI_MAX_LAT,&max_lat);
1188	//printk("max lat is %x,SubSystemID is %x\n",max_lat,pDevice->SubSystemID);
1189	//for (ii=0;ii<0xFF;ii++)
1190	//pci_read_config_word(pcid,PCI_MAX_LAT,&max_lat);
1191	//max_lat  = 0x20;
1192	//pci_write_config_word(pcid,PCI_MAX_LAT,max_lat);
1193	//pci_read_config_word(pcid,PCI_MAX_LAT,&max_lat);
1194	//printk("max lat is %x\n",max_lat);
1195
1196	for (ii=0;ii<0xFF;ii++)
1197	{
1198		pci_read_config_byte(pcid,ii,&value);
1199		pci_config[ii] = value;
1200	}
1201	for (ii=0,j=1;ii<0x100;ii++,j++)
1202	{
1203		if (j %16 == 0)
1204		{
1205			printk("%x:",pci_config[ii]);
1206			printk("\n");
1207		}
1208		else
1209		{
1210			printk("%x:",pci_config[ii]);
1211		}
1212	}
1213#endif
1214    return TRUE;
1215}
1216
1217static void device_free_info(PSDevice pDevice) {
1218    PSDevice         ptr;
1219    struct net_device*  dev=pDevice->dev;
1220
1221    ASSERT(pDevice);
1222//2008-0714-01<Add>by chester
1223device_release_WPADEV(pDevice);
1224
1225//2008-07-21-01<Add>by MikeLiu
1226//unregister wpadev
1227   if(wpa_set_wpadev(pDevice, 0)!=0)
1228     printk("unregister wpadev fail?\n");
1229
1230    if (pDevice_Infos==NULL)
1231        return;
1232
1233    for (ptr=pDevice_Infos;ptr && (ptr!=pDevice);ptr=ptr->next)
1234            do {} while (0);
1235
1236    if (ptr==pDevice) {
1237        if (ptr==pDevice_Infos)
1238            pDevice_Infos=ptr->next;
1239        else
1240            ptr->prev->next=ptr->next;
1241    }
1242    else {
1243        DBG_PRT(MSG_LEVEL_ERR, KERN_ERR "info struct not found\n");
1244        return;
1245    }
1246#ifdef HOSTAP
1247    if (dev)
1248        vt6655_hostap_set_hostapd(pDevice, 0, 0);
1249#endif
1250    if (dev)
1251        unregister_netdev(dev);
1252
1253    if (pDevice->PortOffset)
1254        iounmap((void *)pDevice->PortOffset);
1255
1256    if (pDevice->pcid)
1257        pci_release_regions(pDevice->pcid);
1258    if (dev)
1259        free_netdev(dev);
1260
1261    if (pDevice->pcid) {
1262        pci_set_drvdata(pDevice->pcid,NULL);
1263    }
1264}
1265
1266static BOOL device_init_rings(PSDevice pDevice) {
1267    void*   vir_pool;
1268
1269
1270    /*allocate all RD/TD rings a single pool*/
1271    vir_pool = pci_alloc_consistent(pDevice->pcid,
1272                    pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
1273                    pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
1274                    pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
1275                    pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc),
1276                    &pDevice->pool_dma);
1277
1278    if (vir_pool == NULL) {
1279        DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s : allocate desc dma memory failed\n", pDevice->dev->name);
1280        return FALSE;
1281    }
1282
1283    memset(vir_pool, 0,
1284            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
1285            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
1286            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
1287            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc)
1288          );
1289
1290    pDevice->aRD0Ring = vir_pool;
1291    pDevice->aRD1Ring = vir_pool +
1292                        pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc);
1293
1294
1295    pDevice->rd0_pool_dma = pDevice->pool_dma;
1296    pDevice->rd1_pool_dma = pDevice->rd0_pool_dma +
1297                            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc);
1298
1299    pDevice->tx0_bufs = pci_alloc_consistent(pDevice->pcid,
1300                    pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
1301                    pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
1302                    CB_BEACON_BUF_SIZE +
1303                    CB_MAX_BUF_SIZE,
1304                    &pDevice->tx_bufs_dma0);
1305
1306    if (pDevice->tx0_bufs == NULL) {
1307        DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: allocate buf dma memory failed\n", pDevice->dev->name);
1308        pci_free_consistent(pDevice->pcid,
1309            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
1310            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
1311            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
1312            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc),
1313            vir_pool, pDevice->pool_dma
1314            );
1315        return FALSE;
1316    }
1317
1318    memset(pDevice->tx0_bufs, 0,
1319           pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
1320           pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
1321           CB_BEACON_BUF_SIZE +
1322           CB_MAX_BUF_SIZE
1323          );
1324
1325    pDevice->td0_pool_dma = pDevice->rd1_pool_dma +
1326            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc);
1327
1328    pDevice->td1_pool_dma = pDevice->td0_pool_dma +
1329            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc);
1330
1331
1332    // vir_pool: pvoid type
1333    pDevice->apTD0Rings = vir_pool
1334                          + pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc)
1335                          + pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc);
1336
1337    pDevice->apTD1Rings = vir_pool
1338            + pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc)
1339            + pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc)
1340            + pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc);
1341
1342
1343    pDevice->tx1_bufs = pDevice->tx0_bufs +
1344            pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ;
1345
1346
1347    pDevice->tx_beacon_bufs = pDevice->tx1_bufs +
1348            pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ;
1349
1350    pDevice->pbyTmpBuff = pDevice->tx_beacon_bufs +
1351            CB_BEACON_BUF_SIZE;
1352
1353    pDevice->tx_bufs_dma1 = pDevice->tx_bufs_dma0 +
1354            pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ;
1355
1356
1357    pDevice->tx_beacon_dma = pDevice->tx_bufs_dma1 +
1358            pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ;
1359
1360
1361    return TRUE;
1362}
1363
1364static void device_free_rings(PSDevice pDevice) {
1365
1366    pci_free_consistent(pDevice->pcid,
1367            pDevice->sOpts.nRxDescs0 * sizeof(SRxDesc) +
1368            pDevice->sOpts.nRxDescs1 * sizeof(SRxDesc) +
1369            pDevice->sOpts.nTxDescs[0] * sizeof(STxDesc) +
1370            pDevice->sOpts.nTxDescs[1] * sizeof(STxDesc)
1371            ,
1372            pDevice->aRD0Ring, pDevice->pool_dma
1373        );
1374
1375    if (pDevice->tx0_bufs)
1376        pci_free_consistent(pDevice->pcid,
1377           pDevice->sOpts.nTxDescs[0] * PKT_BUF_SZ +
1378           pDevice->sOpts.nTxDescs[1] * PKT_BUF_SZ +
1379           CB_BEACON_BUF_SIZE +
1380           CB_MAX_BUF_SIZE,
1381           pDevice->tx0_bufs, pDevice->tx_bufs_dma0
1382        );
1383}
1384
1385static void device_init_rd0_ring(PSDevice pDevice) {
1386    int i;
1387    dma_addr_t      curr = pDevice->rd0_pool_dma;
1388    PSRxDesc        pDesc;
1389
1390    /* Init the RD0 ring entries */
1391    for (i = 0; i < pDevice->sOpts.nRxDescs0; i ++, curr += sizeof(SRxDesc)) {
1392        pDesc = &(pDevice->aRD0Ring[i]);
1393        pDesc->pRDInfo = alloc_rd_info();
1394        ASSERT(pDesc->pRDInfo);
1395        if (!device_alloc_rx_buf(pDevice, pDesc)) {
1396            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc rx bufs\n",
1397            pDevice->dev->name);
1398        }
1399        pDesc->next = &(pDevice->aRD0Ring[(i+1) % pDevice->sOpts.nRxDescs0]);
1400        pDesc->pRDInfo->curr_desc = cpu_to_le32(curr);
1401        pDesc->next_desc = cpu_to_le32(curr + sizeof(SRxDesc));
1402    }
1403
1404    if (i > 0)
1405        pDevice->aRD0Ring[i-1].next_desc = cpu_to_le32(pDevice->rd0_pool_dma);
1406    pDevice->pCurrRD[0] = &(pDevice->aRD0Ring[0]);
1407}
1408
1409
1410static void device_init_rd1_ring(PSDevice pDevice) {
1411    int i;
1412    dma_addr_t      curr = pDevice->rd1_pool_dma;
1413    PSRxDesc        pDesc;
1414
1415    /* Init the RD1 ring entries */
1416    for (i = 0; i < pDevice->sOpts.nRxDescs1; i ++, curr += sizeof(SRxDesc)) {
1417        pDesc = &(pDevice->aRD1Ring[i]);
1418        pDesc->pRDInfo = alloc_rd_info();
1419        ASSERT(pDesc->pRDInfo);
1420        if (!device_alloc_rx_buf(pDevice, pDesc)) {
1421            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc rx bufs\n",
1422            pDevice->dev->name);
1423        }
1424        pDesc->next = &(pDevice->aRD1Ring[(i+1) % pDevice->sOpts.nRxDescs1]);
1425        pDesc->pRDInfo->curr_desc = cpu_to_le32(curr);
1426        pDesc->next_desc = cpu_to_le32(curr + sizeof(SRxDesc));
1427    }
1428
1429    if (i > 0)
1430        pDevice->aRD1Ring[i-1].next_desc = cpu_to_le32(pDevice->rd1_pool_dma);
1431    pDevice->pCurrRD[1] = &(pDevice->aRD1Ring[0]);
1432}
1433
1434
1435static void device_init_defrag_cb(PSDevice pDevice) {
1436    int i;
1437    PSDeFragControlBlock pDeF;
1438
1439    /* Init the fragment ctl entries */
1440    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
1441        pDeF = &(pDevice->sRxDFCB[i]);
1442        if (!device_alloc_frag_buf(pDevice, pDeF)) {
1443            DBG_PRT(MSG_LEVEL_ERR,KERN_ERR "%s: can not alloc frag bufs\n",
1444                pDevice->dev->name);
1445        };
1446    }
1447    pDevice->cbDFCB = CB_MAX_RX_FRAG;
1448    pDevice->cbFreeDFCB = pDevice->cbDFCB;
1449}
1450
1451
1452
1453
1454static void device_free_rd0_ring(PSDevice pDevice) {
1455    int i;
1456
1457    for (i = 0; i < pDevice->sOpts.nRxDescs0; i++) {
1458        PSRxDesc        pDesc =&(pDevice->aRD0Ring[i]);
1459        PDEVICE_RD_INFO  pRDInfo =pDesc->pRDInfo;
1460
1461        pci_unmap_single(pDevice->pcid,pRDInfo->skb_dma,
1462           pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
1463
1464        dev_kfree_skb(pRDInfo->skb);
1465
1466        kfree((void *)pDesc->pRDInfo);
1467    }
1468
1469}
1470
1471static void device_free_rd1_ring(PSDevice pDevice) {
1472    int i;
1473
1474
1475    for (i = 0; i < pDevice->sOpts.nRxDescs1; i++) {
1476        PSRxDesc        pDesc=&(pDevice->aRD1Ring[i]);
1477        PDEVICE_RD_INFO  pRDInfo=pDesc->pRDInfo;
1478
1479        pci_unmap_single(pDevice->pcid,pRDInfo->skb_dma,
1480           pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
1481
1482        dev_kfree_skb(pRDInfo->skb);
1483
1484        kfree((void *)pDesc->pRDInfo);
1485    }
1486
1487}
1488
1489static void device_free_frag_buf(PSDevice pDevice) {
1490    PSDeFragControlBlock pDeF;
1491    int i;
1492
1493    for (i = 0; i < CB_MAX_RX_FRAG; i++) {
1494
1495        pDeF = &(pDevice->sRxDFCB[i]);
1496
1497        if (pDeF->skb)
1498            dev_kfree_skb(pDeF->skb);
1499
1500    }
1501
1502}
1503
1504static void device_init_td0_ring(PSDevice pDevice) {
1505    int i;
1506    dma_addr_t  curr;
1507    PSTxDesc        pDesc;
1508
1509    curr = pDevice->td0_pool_dma;
1510    for (i = 0; i < pDevice->sOpts.nTxDescs[0]; i++, curr += sizeof(STxDesc)) {
1511        pDesc = &(pDevice->apTD0Rings[i]);
1512        pDesc->pTDInfo = alloc_td_info();
1513        ASSERT(pDesc->pTDInfo);
1514        if (pDevice->flags & DEVICE_FLAGS_TX_ALIGN) {
1515            pDesc->pTDInfo->buf = pDevice->tx0_bufs + (i)*PKT_BUF_SZ;
1516            pDesc->pTDInfo->buf_dma = pDevice->tx_bufs_dma0 + (i)*PKT_BUF_SZ;
1517        }
1518        pDesc->next =&(pDevice->apTD0Rings[(i+1) % pDevice->sOpts.nTxDescs[0]]);
1519        pDesc->pTDInfo->curr_desc = cpu_to_le32(curr);
1520        pDesc->next_desc = cpu_to_le32(curr+sizeof(STxDesc));
1521    }
1522
1523    if (i > 0)
1524        pDevice->apTD0Rings[i-1].next_desc = cpu_to_le32(pDevice->td0_pool_dma);
1525    pDevice->apTailTD[0] = pDevice->apCurrTD[0] =&(pDevice->apTD0Rings[0]);
1526
1527}
1528
1529static void device_init_td1_ring(PSDevice pDevice) {
1530    int i;
1531    dma_addr_t  curr;
1532    PSTxDesc    pDesc;
1533
1534    /* Init the TD ring entries */
1535    curr=pDevice->td1_pool_dma;
1536    for (i = 0; i < pDevice->sOpts.nTxDescs[1]; i++, curr+=sizeof(STxDesc)) {
1537        pDesc=&(pDevice->apTD1Rings[i]);
1538        pDesc->pTDInfo = alloc_td_info();
1539        ASSERT(pDesc->pTDInfo);
1540        if (pDevice->flags & DEVICE_FLAGS_TX_ALIGN) {
1541            pDesc->pTDInfo->buf=pDevice->tx1_bufs+(i)*PKT_BUF_SZ;
1542            pDesc->pTDInfo->buf_dma=pDevice->tx_bufs_dma1+(i)*PKT_BUF_SZ;
1543        }
1544        pDesc->next=&(pDevice->apTD1Rings[(i+1) % pDevice->sOpts.nTxDescs[1]]);
1545        pDesc->pTDInfo->curr_desc = cpu_to_le32(curr);
1546        pDesc->next_desc = cpu_to_le32(curr+sizeof(STxDesc));
1547    }
1548
1549    if (i > 0)
1550        pDevice->apTD1Rings[i-1].next_desc = cpu_to_le32(pDevice->td1_pool_dma);
1551    pDevice->apTailTD[1] = pDevice->apCurrTD[1] = &(pDevice->apTD1Rings[0]);
1552}
1553
1554
1555
1556static void device_free_td0_ring(PSDevice pDevice) {
1557    int i;
1558    for (i = 0; i < pDevice->sOpts.nTxDescs[0]; i++) {
1559        PSTxDesc        pDesc=&(pDevice->apTD0Rings[i]);
1560        PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
1561
1562        if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma))
1563            pci_unmap_single(pDevice->pcid,pTDInfo->skb_dma,
1564               pTDInfo->skb->len, PCI_DMA_TODEVICE);
1565
1566        if (pTDInfo->skb)
1567            dev_kfree_skb(pTDInfo->skb);
1568
1569        kfree((void *)pDesc->pTDInfo);
1570    }
1571}
1572
1573static void device_free_td1_ring(PSDevice pDevice) {
1574    int i;
1575
1576    for (i = 0; i < pDevice->sOpts.nTxDescs[1]; i++) {
1577        PSTxDesc        pDesc=&(pDevice->apTD1Rings[i]);
1578        PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
1579
1580        if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma))
1581            pci_unmap_single(pDevice->pcid, pTDInfo->skb_dma,
1582               pTDInfo->skb->len, PCI_DMA_TODEVICE);
1583
1584        if (pTDInfo->skb)
1585            dev_kfree_skb(pTDInfo->skb);
1586
1587        kfree((void *)pDesc->pTDInfo);
1588    }
1589
1590}
1591
1592
1593
1594/*-----------------------------------------------------------------*/
1595
1596static int device_rx_srv(PSDevice pDevice, UINT uIdx) {
1597    PSRxDesc    pRD;
1598    int works = 0;
1599
1600
1601    for (pRD = pDevice->pCurrRD[uIdx];
1602         pRD->m_rd0RD0.f1Owner == OWNED_BY_HOST;
1603         pRD = pRD->next) {
1604//        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->pCurrRD = %x, works = %d\n", pRD, works);
1605        if (works++>15)
1606            break;
1607        if (device_receive_frame(pDevice, pRD)) {
1608            if (!device_alloc_rx_buf(pDevice,pRD)) {
1609                    DBG_PRT(MSG_LEVEL_ERR, KERN_ERR
1610                    "%s: can not allocate rx buf\n", pDevice->dev->name);
1611                    break;
1612            }
1613        }
1614        pRD->m_rd0RD0.f1Owner = OWNED_BY_NIC;
1615        pDevice->dev->last_rx = jiffies;
1616    }
1617
1618    pDevice->pCurrRD[uIdx]=pRD;
1619
1620    return works;
1621}
1622
1623
1624static BOOL device_alloc_rx_buf(PSDevice pDevice, PSRxDesc pRD) {
1625
1626    PDEVICE_RD_INFO pRDInfo=pRD->pRDInfo;
1627
1628
1629    pRDInfo->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
1630#ifdef	PLICE_DEBUG
1631	//printk("device_alloc_rx_buf:skb is %x\n",pRDInfo->skb);
1632#endif
1633    if (pRDInfo->skb==NULL)
1634        return FALSE;
1635    ASSERT(pRDInfo->skb);
1636    pRDInfo->skb->dev = pDevice->dev;
1637    pRDInfo->skb_dma = pci_map_single(pDevice->pcid, skb_tail_pointer(pRDInfo->skb),
1638				      pDevice->rx_buf_sz, PCI_DMA_FROMDEVICE);
1639    *((unsigned int *) &(pRD->m_rd0RD0)) = 0; /* FIX cast */
1640
1641    pRD->m_rd0RD0.wResCount = cpu_to_le16(pDevice->rx_buf_sz);
1642    pRD->m_rd0RD0.f1Owner = OWNED_BY_NIC;
1643    pRD->m_rd1RD1.wReqCount = cpu_to_le16(pDevice->rx_buf_sz);
1644    pRD->buff_addr = cpu_to_le32(pRDInfo->skb_dma);
1645
1646    return TRUE;
1647}
1648
1649
1650
1651BOOL device_alloc_frag_buf(PSDevice pDevice, PSDeFragControlBlock pDeF) {
1652
1653    pDeF->skb = dev_alloc_skb((int)pDevice->rx_buf_sz);
1654    if (pDeF->skb == NULL)
1655        return FALSE;
1656    ASSERT(pDeF->skb);
1657    pDeF->skb->dev = pDevice->dev;
1658
1659    return TRUE;
1660}
1661
1662
1663
1664static int device_tx_srv(PSDevice pDevice, UINT uIdx) {
1665    PSTxDesc                 pTD;
1666    BOOL                     bFull=FALSE;
1667    int                      works = 0;
1668    BYTE                     byTsr0;
1669    BYTE                     byTsr1;
1670    UINT                     uFrameSize, uFIFOHeaderSize;
1671    PSTxBufHead              pTxBufHead;
1672    struct net_device_stats* pStats = &pDevice->stats;
1673    struct sk_buff*          skb;
1674    UINT                     uNodeIndex;
1675    PSMgmtObject             pMgmt = pDevice->pMgmt;
1676
1677
1678    for (pTD = pDevice->apTailTD[uIdx]; pDevice->iTDUsed[uIdx] >0; pTD = pTD->next) {
1679
1680        if (pTD->m_td0TD0.f1Owner == OWNED_BY_NIC)
1681            break;
1682        if (works++>15)
1683            break;
1684
1685        byTsr0 = pTD->m_td0TD0.byTSR0;
1686        byTsr1 = pTD->m_td0TD0.byTSR1;
1687
1688        //Only the status of first TD in the chain is correct
1689        if (pTD->m_td1TD1.byTCR & TCR_STP) {
1690
1691            if ((pTD->pTDInfo->byFlags & TD_FLAGS_NETIF_SKB) != 0) {
1692                uFIFOHeaderSize = pTD->pTDInfo->dwHeaderLength;
1693                uFrameSize = pTD->pTDInfo->dwReqCount - uFIFOHeaderSize;
1694                pTxBufHead = (PSTxBufHead) (pTD->pTDInfo->buf);
1695                // Update the statistics based on the Transmit status
1696                // now, we DO'NT check TSR0_CDH
1697
1698                STAvUpdateTDStatCounter(&pDevice->scStatistic,
1699                        byTsr0, byTsr1,
1700                        (PBYTE)(pTD->pTDInfo->buf + uFIFOHeaderSize),
1701                        uFrameSize, uIdx);
1702
1703
1704                BSSvUpdateNodeTxCounter(pDevice,
1705                         byTsr0, byTsr1,
1706                         (PBYTE)(pTD->pTDInfo->buf),
1707                         uFIFOHeaderSize
1708                         );
1709
1710                if ( !(byTsr1 & TSR1_TERR)) {
1711                    if (byTsr0 != 0) {
1712                        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] OK but has error. tsr1[%02X] tsr0[%02X].\n",
1713                           (INT)uIdx, byTsr1, byTsr0);
1714                    }
1715                    if ((pTxBufHead->wFragCtl & FRAGCTL_ENDFRAG) != FRAGCTL_NONFRAG) {
1716                        pDevice->s802_11Counter.TransmittedFragmentCount ++;
1717                    }
1718                    pStats->tx_packets++;
1719                    pStats->tx_bytes += pTD->pTDInfo->skb->len;
1720                }
1721                else {
1722                     DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] dropped & tsr1[%02X] tsr0[%02X].\n",
1723                           (INT)uIdx, byTsr1, byTsr0);
1724                    pStats->tx_errors++;
1725                    pStats->tx_dropped++;
1726                }
1727            }
1728
1729            if ((pTD->pTDInfo->byFlags & TD_FLAGS_PRIV_SKB) != 0) {
1730                if (pDevice->bEnableHostapd) {
1731                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "tx call back netif.. \n");
1732                    skb = pTD->pTDInfo->skb;
1733	                skb->dev = pDevice->apdev;
1734			skb_reset_mac_header(skb);
1735	                skb->pkt_type = PACKET_OTHERHOST;
1736    	            //skb->protocol = htons(ETH_P_802_2);
1737	                memset(skb->cb, 0, sizeof(skb->cb));
1738	                netif_rx(skb);
1739	            }
1740            }
1741
1742            if (byTsr1 & TSR1_TERR) {
1743            if ((pTD->pTDInfo->byFlags & TD_FLAGS_PRIV_SKB) != 0) {
1744                DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] fail has error. tsr1[%02X] tsr0[%02X].\n",
1745                          (INT)uIdx, byTsr1, byTsr0);
1746            }
1747
1748//                DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" Tx[%d] fail has error. tsr1[%02X] tsr0[%02X].\n",
1749//                          (INT)uIdx, byTsr1, byTsr0);
1750
1751                if ((pMgmt->eCurrMode == WMAC_MODE_ESS_AP) &&
1752                    (pTD->pTDInfo->byFlags & TD_FLAGS_NETIF_SKB)) {
1753                    WORD    wAID;
1754                    BYTE    byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
1755
1756                    skb = pTD->pTDInfo->skb;
1757                    if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(skb->data), &uNodeIndex)) {
1758                        if (pMgmt->sNodeDBTable[uNodeIndex].bPSEnable) {
1759                            skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, skb);
1760                            pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt++;
1761                            // set tx map
1762                            wAID = pMgmt->sNodeDBTable[uNodeIndex].wAID;
1763                            pMgmt->abyPSTxMap[wAID >> 3] |=  byMask[wAID & 7];
1764                            pTD->pTDInfo->byFlags &= ~(TD_FLAGS_NETIF_SKB);
1765                            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "tx_srv:tx fail re-queue sta index= %d, QueCnt= %d\n"
1766                                    ,(INT)uNodeIndex, pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt);
1767                            pStats->tx_errors--;
1768                            pStats->tx_dropped--;
1769                        }
1770                    }
1771                }
1772            }
1773            device_free_tx_buf(pDevice,pTD);
1774            pDevice->iTDUsed[uIdx]--;
1775        }
1776    }
1777
1778
1779    if (uIdx == TYPE_AC0DMA) {
1780        // RESERV_AC0DMA reserved for relay
1781
1782        if (AVAIL_TD(pDevice, uIdx) < RESERV_AC0DMA) {
1783            bFull = TRUE;
1784            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " AC0DMA is Full = %d\n", pDevice->iTDUsed[uIdx]);
1785        }
1786        if (netif_queue_stopped(pDevice->dev) && (bFull==FALSE)){
1787            netif_wake_queue(pDevice->dev);
1788        }
1789    }
1790
1791
1792    pDevice->apTailTD[uIdx] = pTD;
1793
1794    return works;
1795}
1796
1797
1798static void device_error(PSDevice pDevice, WORD status) {
1799
1800    if (status & ISR_FETALERR) {
1801        DBG_PRT(MSG_LEVEL_ERR, KERN_ERR
1802            "%s: Hardware fatal error.\n",
1803            pDevice->dev->name);
1804        netif_stop_queue(pDevice->dev);
1805        del_timer(&pDevice->sTimerCommand);
1806        del_timer(&(pDevice->pMgmt->sTimerSecondCallback));
1807        pDevice->bCmdRunning = FALSE;
1808        MACbShutdown(pDevice->PortOffset);
1809        return;
1810    }
1811
1812}
1813
1814static void device_free_tx_buf(PSDevice pDevice, PSTxDesc pDesc) {
1815    PDEVICE_TD_INFO  pTDInfo=pDesc->pTDInfo;
1816    struct sk_buff* skb=pTDInfo->skb;
1817
1818    // pre-allocated buf_dma can't be unmapped.
1819    if (pTDInfo->skb_dma && (pTDInfo->skb_dma != pTDInfo->buf_dma)) {
1820        pci_unmap_single(pDevice->pcid,pTDInfo->skb_dma,skb->len,
1821              PCI_DMA_TODEVICE);
1822    }
1823
1824    if ((pTDInfo->byFlags & TD_FLAGS_NETIF_SKB) != 0)
1825        dev_kfree_skb_irq(skb);
1826
1827    pTDInfo->skb_dma = 0;
1828    pTDInfo->skb = 0;
1829    pTDInfo->byFlags = 0;
1830}
1831
1832
1833
1834//PLICE_DEBUG ->
1835void	InitRxManagementQueue(PSDevice  pDevice)
1836{
1837	pDevice->rxManeQueue.packet_num = 0;
1838	pDevice->rxManeQueue.head = pDevice->rxManeQueue.tail = 0;
1839}
1840//PLICE_DEBUG<-
1841
1842
1843
1844
1845
1846//PLICE_DEBUG ->
1847INT MlmeThread(
1848     void * Context)
1849{
1850	PSDevice	pDevice =  (PSDevice) Context;
1851	PSRxMgmtPacket			pRxMgmtPacket;
1852	// int i ;
1853	//complete(&pDevice->notify);
1854//printk("Enter MngWorkItem,Queue packet num is %d\n",pDevice->rxManeQueue.packet_num);
1855
1856	//printk("Enter MlmeThread,packet _num is %d\n",pDevice->rxManeQueue.packet_num);
1857	//i = 0;
1858#if 1
1859	while (1)
1860	{
1861
1862	//printk("DDDD\n");
1863	//down(&pDevice->mlme_semaphore);
1864        // pRxMgmtPacket =  DeQueue(pDevice);
1865#if 1
1866		spin_lock_irq(&pDevice->lock);
1867		 while(pDevice->rxManeQueue.packet_num != 0)
1868	 	{
1869			 pRxMgmtPacket =  DeQueue(pDevice);
1870        			//pDevice;
1871        			//DequeueManageObject(pDevice->FirstRecvMngList, pDevice->LastRecvMngList);
1872			vMgrRxManagePacket(pDevice, pDevice->pMgmt, pRxMgmtPacket);
1873			//printk("packet_num is %d\n",pDevice->rxManeQueue.packet_num);
1874
1875		 }
1876		spin_unlock_irq(&pDevice->lock);
1877		if (mlme_kill == 0)
1878		break;
1879		//udelay(200);
1880#endif
1881	//printk("Before schedule thread jiffies is %x\n",jiffies);
1882	schedule();
1883	//printk("after schedule thread jiffies is %x\n",jiffies);
1884	if (mlme_kill == 0)
1885		break;
1886	//printk("i is %d\n",i);
1887	}
1888
1889#endif
1890	return 0;
1891
1892}
1893
1894
1895
1896static int  device_open(struct net_device *dev) {
1897    PSDevice    pDevice=(PSDevice) netdev_priv(dev);
1898    int i;
1899#ifdef WPA_SM_Transtatus
1900    extern SWPAResult wpa_Result;
1901#endif
1902
1903    pDevice->rx_buf_sz = PKT_BUF_SZ;
1904    if (!device_init_rings(pDevice)) {
1905        return -ENOMEM;
1906    }
1907//2008-5-13 <add> by chester
1908    i=request_irq(pDevice->pcid->irq, &device_intr, IRQF_SHARED, dev->name, dev);
1909    if (i)
1910        return i;
1911	//printk("DEBUG1\n");
1912#ifdef WPA_SM_Transtatus
1913     memset(wpa_Result.ifname,0,sizeof(wpa_Result.ifname));
1914     wpa_Result.proto = 0;
1915     wpa_Result.key_mgmt = 0;
1916     wpa_Result.eap_type = 0;
1917     wpa_Result.authenticated = FALSE;
1918     pDevice->fWPA_Authened = FALSE;
1919#endif
1920DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call device init rd0 ring\n");
1921device_init_rd0_ring(pDevice);
1922    device_init_rd1_ring(pDevice);
1923    device_init_defrag_cb(pDevice);
1924    device_init_td0_ring(pDevice);
1925    device_init_td1_ring(pDevice);
1926//    VNTWIFIvSet11h(pDevice->pMgmt, pDevice->b11hEnable);
1927
1928
1929    if (pDevice->bDiversityRegCtlON) {
1930        device_init_diversity_timer(pDevice);
1931    }
1932    vMgrObjectInit(pDevice);
1933    vMgrTimerInit(pDevice);
1934
1935//PLICE_DEBUG->
1936#ifdef	TASK_LET
1937	tasklet_init (&pDevice->RxMngWorkItem,(void *)MngWorkItem,(unsigned long )pDevice);
1938#endif
1939#ifdef	THREAD
1940	InitRxManagementQueue(pDevice);
1941	mlme_kill = 0;
1942	mlme_task = kthread_run(MlmeThread,(void *) pDevice, "MLME");
1943	if (IS_ERR(mlme_task)) {
1944		printk("thread create fail\n");
1945		return -1;
1946	}
1947
1948	mlme_kill = 1;
1949#endif
1950
1951
1952
1953#if 0
1954	pDevice->MLMEThr_pid = kernel_thread(MlmeThread, pDevice, CLONE_VM);
1955	if (pDevice->MLMEThr_pid <0 )
1956	{
1957		printk("unable start thread MlmeThread\n");
1958		return -1;
1959	}
1960#endif
1961
1962	//printk("thread id is %d\n",pDevice->MLMEThr_pid);
1963	//printk("Create thread time is %x\n",jiffies);
1964	//wait_for_completion(&pDevice->notify);
1965
1966
1967
1968
1969  // if (( SROMbyReadEmbedded(pDevice->PortOffset, EEP_OFS_RADIOCTL)&0x06)==0x04)
1970    //    return -ENOMEM;
1971DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call device_init_registers\n");
1972	device_init_registers(pDevice, DEVICE_INIT_COLD);
1973    MACvReadEtherAddress(pDevice->PortOffset, pDevice->abyCurrentNetAddr);
1974    memcpy(pDevice->pMgmt->abyMACAddr, pDevice->abyCurrentNetAddr, ETH_ALEN);
1975    device_set_multi(pDevice->dev);
1976
1977    // Init for Key Management
1978    KeyvInitTable(&pDevice->sKey, pDevice->PortOffset);
1979    add_timer(&(pDevice->pMgmt->sTimerSecondCallback));
1980
1981	#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
1982	/*
1983     pDevice->bwextstep0 = FALSE;
1984     pDevice->bwextstep1 = FALSE;
1985     pDevice->bwextstep2 = FALSE;
1986     pDevice->bwextstep3 = FALSE;
1987     */
1988       pDevice->bwextcount=0;
1989     pDevice->bWPASuppWextEnabled = FALSE;
1990#endif
1991    pDevice->byReAssocCount = 0;
1992   pDevice->bWPADEVUp = FALSE;
1993    // Patch: if WEP key already set by iwconfig but device not yet open
1994    if ((pDevice->bEncryptionEnable == TRUE) && (pDevice->bTransmitKey == TRUE)) {
1995        KeybSetDefaultKey(&(pDevice->sKey),
1996                            (DWORD)(pDevice->byKeyIndex | (1 << 31)),
1997                            pDevice->uKeyLength,
1998                            NULL,
1999                            pDevice->abyKey,
2000                            KEY_CTL_WEP,
2001                            pDevice->PortOffset,
2002                            pDevice->byLocalID
2003                          );
2004         pDevice->eEncryptionStatus = Ndis802_11Encryption1Enabled;
2005    }
2006
2007//printk("DEBUG2\n");
2008
2009
2010DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "call MACvIntEnable\n");
2011	MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
2012
2013    if (pDevice->pMgmt->eConfigMode == WMAC_CONFIG_AP) {
2014        bScheduleCommand((void *)pDevice, WLAN_CMD_RUN_AP, NULL);
2015	}
2016	else {
2017        bScheduleCommand((void *)pDevice, WLAN_CMD_BSSID_SCAN, NULL);
2018        bScheduleCommand((void *)pDevice, WLAN_CMD_SSID, NULL);
2019    }
2020    pDevice->flags |=DEVICE_FLAGS_OPENED;
2021
2022    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_open success.. \n");
2023    return 0;
2024}
2025
2026
2027static int  device_close(struct net_device *dev) {
2028    PSDevice  pDevice=(PSDevice) netdev_priv(dev);
2029    PSMgmtObject     pMgmt = pDevice->pMgmt;
2030 //PLICE_DEBUG->
2031#ifdef	THREAD
2032	mlme_kill = 0;
2033#endif
2034//PLICE_DEBUG<-
2035//2007-1121-02<Add>by EinsnLiu
2036    if (pDevice->bLinkPass) {
2037	bScheduleCommand((void *)pDevice, WLAN_CMD_DISASSOCIATE, NULL);
2038        mdelay(30);
2039    }
2040#ifdef TxInSleep
2041    del_timer(&pDevice->sTimerTxData);
2042#endif
2043    del_timer(&pDevice->sTimerCommand);
2044    del_timer(&pMgmt->sTimerSecondCallback);
2045    if (pDevice->bDiversityRegCtlON) {
2046        del_timer(&pDevice->TimerSQ3Tmax1);
2047        del_timer(&pDevice->TimerSQ3Tmax2);
2048        del_timer(&pDevice->TimerSQ3Tmax3);
2049    }
2050
2051#ifdef	TASK_LET
2052	tasklet_kill(&pDevice->RxMngWorkItem);
2053#endif
2054     netif_stop_queue(dev);
2055    pDevice->bCmdRunning = FALSE;
2056    MACbShutdown(pDevice->PortOffset);
2057    MACbSoftwareReset(pDevice->PortOffset);
2058    CARDbRadioPowerOff(pDevice);
2059
2060    pDevice->bLinkPass = FALSE;
2061    memset(pMgmt->abyCurrBSSID, 0, 6);
2062    pMgmt->eCurrState = WMAC_STATE_IDLE;
2063    device_free_td0_ring(pDevice);
2064    device_free_td1_ring(pDevice);
2065    device_free_rd0_ring(pDevice);
2066    device_free_rd1_ring(pDevice);
2067    device_free_frag_buf(pDevice);
2068    device_free_rings(pDevice);
2069    BSSvClearNodeDBTable(pDevice, 0);
2070    free_irq(dev->irq, dev);
2071    pDevice->flags &=(~DEVICE_FLAGS_OPENED);
2072	//2008-0714-01<Add>by chester
2073device_release_WPADEV(pDevice);
2074//PLICE_DEBUG->
2075	//tasklet_kill(&pDevice->RxMngWorkItem);
2076//PLICE_DEBUG<-
2077    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_close.. \n");
2078    return 0;
2079}
2080
2081
2082
2083static int device_dma0_tx_80211(struct sk_buff *skb, struct net_device *dev) {
2084    PSDevice        pDevice=netdev_priv(dev);
2085    PBYTE           pbMPDU;
2086    UINT            cbMPDULen = 0;
2087
2088
2089    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_tx_80211\n");
2090    spin_lock_irq(&pDevice->lock);
2091
2092    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 0) {
2093        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_tx_80211, td0 <=0\n");
2094        dev_kfree_skb_irq(skb);
2095        spin_unlock_irq(&pDevice->lock);
2096        return 0;
2097    }
2098
2099    if (pDevice->bStopTx0Pkt == TRUE) {
2100        dev_kfree_skb_irq(skb);
2101        spin_unlock_irq(&pDevice->lock);
2102        return 0;
2103    };
2104
2105    cbMPDULen = skb->len;
2106    pbMPDU = skb->data;
2107
2108    vDMA0_tx_80211(pDevice, skb, pbMPDU, cbMPDULen);
2109
2110    spin_unlock_irq(&pDevice->lock);
2111
2112    return 0;
2113
2114}
2115
2116
2117
2118BOOL device_dma0_xmit(PSDevice pDevice, struct sk_buff *skb, UINT uNodeIndex) {
2119    PSMgmtObject    pMgmt = pDevice->pMgmt;
2120    PSTxDesc        pHeadTD, pLastTD;
2121    UINT            cbFrameBodySize;
2122    UINT            uMACfragNum;
2123    BYTE            byPktType;
2124    BOOL            bNeedEncryption = FALSE;
2125    PSKeyItem       pTransmitKey = NULL;
2126    UINT            cbHeaderSize;
2127    UINT            ii;
2128    SKeyItem        STempKey;
2129//    BYTE            byKeyIndex = 0;
2130
2131
2132    if (pDevice->bStopTx0Pkt == TRUE) {
2133        dev_kfree_skb_irq(skb);
2134        return FALSE;
2135    };
2136
2137    if (AVAIL_TD(pDevice, TYPE_TXDMA0) <= 0) {
2138        dev_kfree_skb_irq(skb);
2139        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_xmit, td0 <=0\n");
2140        return FALSE;
2141    }
2142
2143    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
2144        if (pDevice->uAssocCount == 0) {
2145            dev_kfree_skb_irq(skb);
2146            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "device_dma0_xmit, assocCount = 0\n");
2147            return FALSE;
2148        }
2149    }
2150
2151    pHeadTD = pDevice->apCurrTD[TYPE_TXDMA0];
2152
2153    pHeadTD->m_td1TD1.byTCR = (TCR_EDP|TCR_STP);
2154
2155    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(skb->data), ETH_HLEN);
2156    cbFrameBodySize = skb->len - ETH_HLEN;
2157
2158    // 802.1H
2159    if (ntohs(pDevice->sTxEthHeader.wType) > MAX_DATA_LEN) {
2160        cbFrameBodySize += 8;
2161    }
2162    uMACfragNum = cbGetFragCount(pDevice, pTransmitKey, cbFrameBodySize, &pDevice->sTxEthHeader);
2163
2164    if ( uMACfragNum > AVAIL_TD(pDevice, TYPE_TXDMA0)) {
2165        dev_kfree_skb_irq(skb);
2166        return FALSE;
2167    }
2168    byPktType = (BYTE)pDevice->byPacketType;
2169
2170
2171    if (pDevice->bFixRate) {
2172        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
2173            if (pDevice->uConnectionRate >= RATE_11M) {
2174                pDevice->wCurrentRate = RATE_11M;
2175            } else {
2176                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
2177            }
2178        } else {
2179            if (pDevice->uConnectionRate >= RATE_54M)
2180                pDevice->wCurrentRate = RATE_54M;
2181            else
2182                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
2183        }
2184    }
2185    else {
2186        pDevice->wCurrentRate = pDevice->pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
2187    }
2188
2189    //preamble type
2190    if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
2191        pDevice->byPreambleType = pDevice->byShortPreamble;
2192    }
2193    else {
2194        pDevice->byPreambleType = PREAMBLE_LONG;
2195    }
2196
2197    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dma0: pDevice->wCurrentRate = %d \n", pDevice->wCurrentRate);
2198
2199
2200    if (pDevice->wCurrentRate <= RATE_11M) {
2201        byPktType = PK_TYPE_11B;
2202    } else if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
2203        byPktType = PK_TYPE_11A;
2204    } else {
2205        if (pDevice->bProtectMode == TRUE) {
2206            byPktType = PK_TYPE_11GB;
2207        } else {
2208            byPktType = PK_TYPE_11GA;
2209        }
2210    }
2211
2212    if (pDevice->bEncryptionEnable == TRUE)
2213        bNeedEncryption = TRUE;
2214
2215    if (pDevice->bEnableHostWEP) {
2216        pTransmitKey = &STempKey;
2217        pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
2218        pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
2219        pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
2220        pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
2221        pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
2222        memcpy(pTransmitKey->abyKey,
2223            &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
2224            pTransmitKey->uKeyLength
2225            );
2226    }
2227    vGenerateFIFOHeader(pDevice, byPktType, pDevice->pbyTmpBuff, bNeedEncryption,
2228                        cbFrameBodySize, TYPE_TXDMA0, pHeadTD,
2229                        &pDevice->sTxEthHeader, (PBYTE)skb->data, pTransmitKey, uNodeIndex,
2230                        &uMACfragNum,
2231                        &cbHeaderSize
2232                        );
2233
2234    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
2235        // Disable PS
2236        MACbPSWakeup(pDevice->PortOffset);
2237    }
2238
2239    pDevice->bPWBitOn = FALSE;
2240
2241    pLastTD = pHeadTD;
2242    for (ii = 0; ii < uMACfragNum; ii++) {
2243        // Poll Transmit the adapter
2244        wmb();
2245        pHeadTD->m_td0TD0.f1Owner=OWNED_BY_NIC;
2246        wmb();
2247        if (ii == (uMACfragNum - 1))
2248            pLastTD = pHeadTD;
2249        pHeadTD = pHeadTD->next;
2250    }
2251
2252    // Save the information needed by the tx interrupt handler
2253    // to complete the Send request
2254    pLastTD->pTDInfo->skb = skb;
2255    pLastTD->pTDInfo->byFlags = 0;
2256    pLastTD->pTDInfo->byFlags |= TD_FLAGS_NETIF_SKB;
2257
2258    pDevice->apCurrTD[TYPE_TXDMA0] = pHeadTD;
2259
2260    MACvTransmit0(pDevice->PortOffset);
2261
2262
2263    return TRUE;
2264}
2265
2266//TYPE_AC0DMA data tx
2267static int  device_xmit(struct sk_buff *skb, struct net_device *dev) {
2268    PSDevice pDevice=netdev_priv(dev);
2269
2270    PSMgmtObject    pMgmt = pDevice->pMgmt;
2271    PSTxDesc        pHeadTD, pLastTD;
2272    UINT            uNodeIndex = 0;
2273    BYTE            byMask[8] = {1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80};
2274    WORD            wAID;
2275    UINT            uMACfragNum = 1;
2276    UINT            cbFrameBodySize;
2277    BYTE            byPktType;
2278    UINT            cbHeaderSize;
2279    BOOL            bNeedEncryption = FALSE;
2280    PSKeyItem       pTransmitKey = NULL;
2281    SKeyItem        STempKey;
2282    UINT            ii;
2283    BOOL            bTKIP_UseGTK = FALSE;
2284    BOOL            bNeedDeAuth = FALSE;
2285    PBYTE           pbyBSSID;
2286    BOOL            bNodeExist = FALSE;
2287
2288
2289
2290    spin_lock_irq(&pDevice->lock);
2291    if (pDevice->bLinkPass == FALSE) {
2292        dev_kfree_skb_irq(skb);
2293        spin_unlock_irq(&pDevice->lock);
2294        return 0;
2295    }
2296
2297    if (pDevice->bStopDataPkt) {
2298        dev_kfree_skb_irq(skb);
2299        spin_unlock_irq(&pDevice->lock);
2300        return 0;
2301    }
2302
2303
2304    if (pMgmt->eCurrMode == WMAC_MODE_ESS_AP) {
2305        if (pDevice->uAssocCount == 0) {
2306            dev_kfree_skb_irq(skb);
2307            spin_unlock_irq(&pDevice->lock);
2308            return 0;
2309        }
2310        if (IS_MULTICAST_ADDRESS((PBYTE)(skb->data))) {
2311            uNodeIndex = 0;
2312            bNodeExist = TRUE;
2313            if (pMgmt->sNodeDBTable[0].bPSEnable) {
2314                skb_queue_tail(&(pMgmt->sNodeDBTable[0].sTxPSQueue), skb);
2315                pMgmt->sNodeDBTable[0].wEnQueueCnt++;
2316                // set tx map
2317                pMgmt->abyPSTxMap[0] |= byMask[0];
2318                spin_unlock_irq(&pDevice->lock);
2319                return 0;
2320            }
2321}else {
2322            if (BSSDBbIsSTAInNodeDB(pMgmt, (PBYTE)(skb->data), &uNodeIndex)) {
2323                if (pMgmt->sNodeDBTable[uNodeIndex].bPSEnable) {
2324                    skb_queue_tail(&pMgmt->sNodeDBTable[uNodeIndex].sTxPSQueue, skb);
2325                    pMgmt->sNodeDBTable[uNodeIndex].wEnQueueCnt++;
2326                    // set tx map
2327                    wAID = pMgmt->sNodeDBTable[uNodeIndex].wAID;
2328                    pMgmt->abyPSTxMap[wAID >> 3] |=  byMask[wAID & 7];
2329                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Set:pMgmt->abyPSTxMap[%d]= %d\n",
2330                             (wAID >> 3), pMgmt->abyPSTxMap[wAID >> 3]);
2331                    spin_unlock_irq(&pDevice->lock);
2332                    return 0;
2333                }
2334
2335                if (pMgmt->sNodeDBTable[uNodeIndex].bShortPreamble) {
2336                    pDevice->byPreambleType = pDevice->byShortPreamble;
2337
2338                }else {
2339                    pDevice->byPreambleType = PREAMBLE_LONG;
2340                }
2341                bNodeExist = TRUE;
2342
2343            }
2344        }
2345
2346        if (bNodeExist == FALSE) {
2347            DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Unknown STA not found in node DB \n");
2348            dev_kfree_skb_irq(skb);
2349            spin_unlock_irq(&pDevice->lock);
2350            return 0;
2351        }
2352    }
2353
2354    pHeadTD = pDevice->apCurrTD[TYPE_AC0DMA];
2355
2356    pHeadTD->m_td1TD1.byTCR = (TCR_EDP|TCR_STP);
2357
2358
2359    memcpy(pDevice->sTxEthHeader.abyDstAddr, (PBYTE)(skb->data), ETH_HLEN);
2360    cbFrameBodySize = skb->len - ETH_HLEN;
2361    // 802.1H
2362    if (ntohs(pDevice->sTxEthHeader.wType) > MAX_DATA_LEN) {
2363        cbFrameBodySize += 8;
2364    }
2365
2366
2367    if (pDevice->bEncryptionEnable == TRUE) {
2368        bNeedEncryption = TRUE;
2369        // get Transmit key
2370        do {
2371            if ((pDevice->pMgmt->eCurrMode == WMAC_MODE_ESS_STA) &&
2372                (pDevice->pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
2373                pbyBSSID = pDevice->abyBSSID;
2374                // get pairwise key
2375                if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == FALSE) {
2376                    // get group key
2377                    if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == TRUE) {
2378                        bTKIP_UseGTK = TRUE;
2379                        DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
2380                        break;
2381                    }
2382                } else {
2383                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get PTK.\n");
2384                    break;
2385                }
2386            }else if (pDevice->pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
2387
2388                pbyBSSID = pDevice->sTxEthHeader.abyDstAddr;  //TO_DS = 0 and FROM_DS = 0 --> 802.11 MAC Address1
2389                DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS Serach Key: \n");
2390                for (ii = 0; ii< 6; ii++)
2391                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"%x \n", *(pbyBSSID+ii));
2392                DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"\n");
2393
2394                // get pairwise key
2395                if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, PAIRWISE_KEY, &pTransmitKey) == TRUE)
2396                    break;
2397            }
2398            // get group key
2399            pbyBSSID = pDevice->abyBroadcastAddr;
2400            if(KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID, GROUP_KEY, &pTransmitKey) == FALSE) {
2401                pTransmitKey = NULL;
2402                if (pDevice->pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
2403                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"IBSS and KEY is NULL. [%d]\n", pDevice->pMgmt->eCurrMode);
2404                }
2405                else
2406                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"NOT IBSS and KEY is NULL. [%d]\n", pDevice->pMgmt->eCurrMode);
2407            } else {
2408                bTKIP_UseGTK = TRUE;
2409                DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"Get GTK.\n");
2410            }
2411        } while(FALSE);
2412    }
2413
2414    if (pDevice->bEnableHostWEP) {
2415        DBG_PRT(MSG_LEVEL_DEBUG, KERN_DEBUG"acdma0: STA index %d\n", uNodeIndex);
2416        if (pDevice->bEncryptionEnable == TRUE) {
2417            pTransmitKey = &STempKey;
2418            pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
2419            pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
2420            pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
2421            pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
2422            pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
2423            memcpy(pTransmitKey->abyKey,
2424                &pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
2425                pTransmitKey->uKeyLength
2426                );
2427         }
2428    }
2429
2430    uMACfragNum = cbGetFragCount(pDevice, pTransmitKey, cbFrameBodySize, &pDevice->sTxEthHeader);
2431
2432    if (uMACfragNum > AVAIL_TD(pDevice, TYPE_AC0DMA)) {
2433        DBG_PRT(MSG_LEVEL_ERR, KERN_DEBUG "uMACfragNum > AVAIL_TD(TYPE_AC0DMA) = %d\n", uMACfragNum);
2434        dev_kfree_skb_irq(skb);
2435        spin_unlock_irq(&pDevice->lock);
2436        return 0;
2437    }
2438
2439    if (pTransmitKey != NULL) {
2440        if ((pTransmitKey->byCipherSuite == KEY_CTL_WEP) &&
2441            (pTransmitKey->uKeyLength == WLAN_WEP232_KEYLEN)) {
2442            uMACfragNum = 1; //WEP256 doesn't support fragment
2443        }
2444    }
2445
2446    byPktType = (BYTE)pDevice->byPacketType;
2447
2448    if (pDevice->bFixRate) {
2449#ifdef	PLICE_DEBUG
2450	printk("Fix Rate: PhyType is %d,ConnectionRate is %d\n",pDevice->eCurrentPHYType,pDevice->uConnectionRate);
2451#endif
2452
2453        if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
2454            if (pDevice->uConnectionRate >= RATE_11M) {
2455                pDevice->wCurrentRate = RATE_11M;
2456            } else {
2457                pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
2458            }
2459        } else {
2460            if ((pDevice->eCurrentPHYType == PHY_TYPE_11A) &&
2461                (pDevice->uConnectionRate <= RATE_6M)) {
2462                pDevice->wCurrentRate = RATE_6M;
2463            } else {
2464                if (pDevice->uConnectionRate >= RATE_54M)
2465                    pDevice->wCurrentRate = RATE_54M;
2466                else
2467                    pDevice->wCurrentRate = (WORD)pDevice->uConnectionRate;
2468
2469            }
2470        }
2471        pDevice->byACKRate = (BYTE) pDevice->wCurrentRate;
2472        pDevice->byTopCCKBasicRate = RATE_1M;
2473        pDevice->byTopOFDMBasicRate = RATE_6M;
2474    }
2475    else {
2476        //auto rate
2477    if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
2478            if (pDevice->eCurrentPHYType != PHY_TYPE_11A) {
2479                pDevice->wCurrentRate = RATE_1M;
2480                pDevice->byACKRate = RATE_1M;
2481                pDevice->byTopCCKBasicRate = RATE_1M;
2482                pDevice->byTopOFDMBasicRate = RATE_6M;
2483            } else {
2484                pDevice->wCurrentRate = RATE_6M;
2485                pDevice->byACKRate = RATE_6M;
2486                pDevice->byTopCCKBasicRate = RATE_1M;
2487                pDevice->byTopOFDMBasicRate = RATE_6M;
2488            }
2489        }
2490        else {
2491		VNTWIFIvGetTxRate(  pDevice->pMgmt,
2492                                pDevice->sTxEthHeader.abyDstAddr,
2493                                &(pDevice->wCurrentRate),
2494                                &(pDevice->byACKRate),
2495                                &(pDevice->byTopCCKBasicRate),
2496                                &(pDevice->byTopOFDMBasicRate));
2497
2498#if 0
2499printk("auto rate:Rate : %d,AckRate:%d,TopCCKRate:%d,TopOFDMRate:%d\n",
2500pDevice->wCurrentRate,pDevice->byACKRate,
2501pDevice->byTopCCKBasicRate,pDevice->byTopOFDMBasicRate);
2502
2503#endif
2504
2505#if 0
2506
2507	pDevice->wCurrentRate = 11;
2508	pDevice->byACKRate = 8;
2509	pDevice->byTopCCKBasicRate = 3;
2510	pDevice->byTopOFDMBasicRate = 8;
2511#endif
2512
2513
2514		}
2515    }
2516
2517//    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "acdma0: pDevice->wCurrentRate = %d \n", pDevice->wCurrentRate);
2518
2519    if (pDevice->wCurrentRate <= RATE_11M) {
2520        byPktType = PK_TYPE_11B;
2521    } else if (pDevice->eCurrentPHYType == PHY_TYPE_11A) {
2522        byPktType = PK_TYPE_11A;
2523    } else {
2524        if (pDevice->bProtectMode == TRUE) {
2525            byPktType = PK_TYPE_11GB;
2526        } else {
2527            byPktType = PK_TYPE_11GA;
2528        }
2529    }
2530
2531//#ifdef	PLICE_DEBUG
2532//	printk("FIX RATE:CurrentRate is %d");
2533//#endif
2534
2535    if (bNeedEncryption == TRUE) {
2536        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ntohs Pkt Type=%04x\n", ntohs(pDevice->sTxEthHeader.wType));
2537        if ((pDevice->sTxEthHeader.wType) == TYPE_PKT_802_1x) {
2538            bNeedEncryption = FALSE;
2539            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Pkt Type=%04x\n", (pDevice->sTxEthHeader.wType));
2540            if ((pDevice->pMgmt->eCurrMode == WMAC_MODE_ESS_STA) && (pDevice->pMgmt->eCurrState == WMAC_STATE_ASSOC)) {
2541                if (pTransmitKey == NULL) {
2542                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Don't Find TX KEY\n");
2543                }
2544                else {
2545                    if (bTKIP_UseGTK == TRUE) {
2546                        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"error: KEY is GTK!!~~\n");
2547                    }
2548                    else {
2549                        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
2550                        bNeedEncryption = TRUE;
2551                    }
2552                }
2553            }
2554
2555            if (pDevice->byCntMeasure == 2) {
2556                bNeedDeAuth = TRUE;
2557                pDevice->s802_11Counter.TKIPCounterMeasuresInvoked++;
2558            }
2559
2560            if (pDevice->bEnableHostWEP) {
2561                if ((uNodeIndex != 0) &&
2562                    (pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex & PAIRWISE_KEY)) {
2563                    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Find PTK [%lX]\n", pTransmitKey->dwKeyIndex);
2564                    bNeedEncryption = TRUE;
2565                 }
2566             }
2567        }
2568        else {
2569            if (pTransmitKey == NULL) {
2570                DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"return no tx key\n");
2571                dev_kfree_skb_irq(skb);
2572                spin_unlock_irq(&pDevice->lock);
2573                return 0;
2574            }
2575        }
2576    }
2577
2578
2579#ifdef	PLICE_DEBUG
2580	//if (skb->len == 98)
2581	//{
2582	//	printk("ping:len is %d\n");
2583	//}
2584#endif
2585    vGenerateFIFOHeader(pDevice, byPktType, pDevice->pbyTmpBuff, bNeedEncryption,
2586                        cbFrameBodySize, TYPE_AC0DMA, pHeadTD,
2587                        &pDevice->sTxEthHeader, (PBYTE)skb->data, pTransmitKey, uNodeIndex,
2588                        &uMACfragNum,
2589                        &cbHeaderSize
2590                        );
2591
2592    if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
2593        // Disable PS
2594        MACbPSWakeup(pDevice->PortOffset);
2595    }
2596    pDevice->bPWBitOn = FALSE;
2597
2598    pLastTD = pHeadTD;
2599    for (ii = 0; ii < uMACfragNum; ii++) {
2600        // Poll Transmit the adapter
2601        wmb();
2602        pHeadTD->m_td0TD0.f1Owner=OWNED_BY_NIC;
2603        wmb();
2604        if (ii == uMACfragNum - 1)
2605            pLastTD = pHeadTD;
2606        pHeadTD = pHeadTD->next;
2607    }
2608
2609    // Save the information needed by the tx interrupt handler
2610    // to complete the Send request
2611    pLastTD->pTDInfo->skb = skb;
2612    pLastTD->pTDInfo->byFlags = 0;
2613    pLastTD->pTDInfo->byFlags |= TD_FLAGS_NETIF_SKB;
2614#ifdef TxInSleep
2615  pDevice->nTxDataTimeCout=0; //2008-8-21 chester <add> for send null packet
2616  #endif
2617    if (AVAIL_TD(pDevice, TYPE_AC0DMA) <= 1) {
2618        netif_stop_queue(dev);
2619    }
2620
2621    pDevice->apCurrTD[TYPE_AC0DMA] = pHeadTD;
2622//#ifdef	PLICE_DEBUG
2623	if (pDevice->bFixRate)
2624	{
2625		printk("FixRate:Rate is %d,TxPower is %d\n",pDevice->wCurrentRate,pDevice->byCurPwr);
2626	}
2627	else
2628	{
2629		//printk("Auto Rate:Rate is %d,TxPower is %d\n",pDevice->wCurrentRate,pDevice->byCurPwr);
2630	}
2631//#endif
2632
2633{
2634    BYTE  Protocol_Version;    //802.1x Authentication
2635    BYTE  Packet_Type;           //802.1x Authentication
2636    BYTE  Descriptor_type;
2637    WORD Key_info;
2638BOOL            bTxeapol_key = FALSE;
2639    Protocol_Version = skb->data[ETH_HLEN];
2640    Packet_Type = skb->data[ETH_HLEN+1];
2641    Descriptor_type = skb->data[ETH_HLEN+1+1+2];
2642    Key_info = (skb->data[ETH_HLEN+1+1+2+1] << 8)|(skb->data[ETH_HLEN+1+1+2+2]);
2643   if (pDevice->sTxEthHeader.wType == TYPE_PKT_802_1x) {
2644           if(((Protocol_Version==1) ||(Protocol_Version==2)) &&
2645	        (Packet_Type==3)) {  //802.1x OR eapol-key challenge frame transfer
2646                        bTxeapol_key = TRUE;
2647		if((Descriptor_type==254)||(Descriptor_type==2)) {       //WPA or RSN
2648                       if(!(Key_info & BIT3) &&   //group-key challenge
2649			   (Key_info & BIT8) && (Key_info & BIT9)) {    //send 2/2 key
2650			  pDevice->fWPA_Authened = TRUE;
2651			  if(Descriptor_type==254)
2652			      printk("WPA ");
2653			  else
2654			      printk("WPA2 ");
2655			  printk("Authentication completed!!\n");
2656                        }
2657		 }
2658             }
2659   }
2660}
2661
2662    MACvTransmitAC0(pDevice->PortOffset);
2663//    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "acdma0:pDevice->apCurrTD= %p\n", pHeadTD);
2664
2665    dev->trans_start = jiffies;
2666
2667    spin_unlock_irq(&pDevice->lock);
2668    return 0;
2669
2670}
2671
2672static  irqreturn_t  device_intr(int irq,  void *dev_instance) {
2673    struct net_device* dev=dev_instance;
2674    PSDevice     pDevice=(PSDevice) netdev_priv(dev);
2675
2676    int             max_count=0;
2677    DWORD           dwMIBCounter=0;
2678    PSMgmtObject    pMgmt = pDevice->pMgmt;
2679    BYTE            byOrgPageSel=0;
2680    int             handled = 0;
2681    BYTE            byData = 0;
2682    int             ii= 0;
2683//    BYTE            byRSSI;
2684
2685
2686    MACvReadISR(pDevice->PortOffset, &pDevice->dwIsr);
2687
2688    if (pDevice->dwIsr == 0)
2689        return IRQ_RETVAL(handled);
2690
2691    if (pDevice->dwIsr == 0xffffffff) {
2692        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "dwIsr = 0xffff\n");
2693        return IRQ_RETVAL(handled);
2694    }
2695    /*
2696      // 2008-05-21 <mark> by Richardtai, we can't read RSSI here, because no packet bound with RSSI
2697
2698    	if ((pDevice->dwIsr & ISR_RXDMA0) &&
2699        (pDevice->byLocalID != REV_ID_VT3253_B0) &&
2700        (pDevice->bBSSIDFilter == TRUE)) {
2701        // update RSSI
2702        //BBbReadEmbeded(pDevice->PortOffset, 0x3E, &byRSSI);
2703        //pDevice->uCurrRSSI = byRSSI;
2704    }
2705    */
2706
2707    handled = 1;
2708    MACvIntDisable(pDevice->PortOffset);
2709    spin_lock_irq(&pDevice->lock);
2710
2711    //Make sure current page is 0
2712    VNSvInPortB(pDevice->PortOffset + MAC_REG_PAGE1SEL, &byOrgPageSel);
2713    if (byOrgPageSel == 1) {
2714        MACvSelectPage0(pDevice->PortOffset);
2715    }
2716    else
2717        byOrgPageSel = 0;
2718
2719    MACvReadMIBCounter(pDevice->PortOffset, &dwMIBCounter);
2720    // TBD....
2721    // Must do this after doing rx/tx, cause ISR bit is slow
2722    // than RD/TD write back
2723    // update ISR counter
2724    STAvUpdate802_11Counter(&pDevice->s802_11Counter, &pDevice->scStatistic , dwMIBCounter);
2725    while (pDevice->dwIsr != 0) {
2726
2727        STAvUpdateIsrStatCounter(&pDevice->scStatistic, pDevice->dwIsr);
2728        MACvWriteISR(pDevice->PortOffset, pDevice->dwIsr);
2729
2730        if (pDevice->dwIsr & ISR_FETALERR){
2731            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " ISR_FETALERR \n");
2732            VNSvOutPortB(pDevice->PortOffset + MAC_REG_SOFTPWRCTL, 0);
2733            VNSvOutPortW(pDevice->PortOffset + MAC_REG_SOFTPWRCTL, SOFTPWRCTL_SWPECTI);
2734            device_error(pDevice, pDevice->dwIsr);
2735        }
2736
2737        if (pDevice->byLocalID > REV_ID_VT3253_B1) {
2738
2739            if (pDevice->dwIsr & ISR_MEASURESTART) {
2740                // 802.11h measure start
2741                pDevice->byOrgChannel = pDevice->byCurrentCh;
2742                VNSvInPortB(pDevice->PortOffset + MAC_REG_RCR, &(pDevice->byOrgRCR));
2743                VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, (RCR_RXALLTYPE | RCR_UNICAST | RCR_BROADCAST | RCR_MULTICAST | RCR_WPAERR));
2744                MACvSelectPage1(pDevice->PortOffset);
2745                VNSvInPortD(pDevice->PortOffset + MAC_REG_MAR0, &(pDevice->dwOrgMAR0));
2746                VNSvInPortD(pDevice->PortOffset + MAC_REG_MAR4, &(pDevice->dwOrgMAR4));
2747                MACvSelectPage0(pDevice->PortOffset);
2748               //xxxx
2749               // WCMDbFlushCommandQueue(pDevice->pMgmt, TRUE);
2750                if (CARDbSetChannel(pDevice, pDevice->pCurrMeasureEID->sReq.byChannel) == TRUE) {
2751                    pDevice->bMeasureInProgress = TRUE;
2752                    MACvSelectPage1(pDevice->PortOffset);
2753                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_READY);
2754                    MACvSelectPage0(pDevice->PortOffset);
2755                    pDevice->byBasicMap = 0;
2756                    pDevice->byCCAFraction = 0;
2757                    for(ii=0;ii<8;ii++) {
2758                        pDevice->dwRPIs[ii] = 0;
2759                    }
2760                } else {
2761                    // can not measure because set channel fail
2762                   // WCMDbResetCommandQueue(pDevice->pMgmt);
2763                    // clear measure control
2764                    MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
2765                    s_vCompleteCurrentMeasure(pDevice, MEASURE_MODE_INCAPABLE);
2766                    MACvSelectPage1(pDevice->PortOffset);
2767                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
2768                    MACvSelectPage0(pDevice->PortOffset);
2769                }
2770            }
2771            if (pDevice->dwIsr & ISR_MEASUREEND) {
2772                // 802.11h measure end
2773                pDevice->bMeasureInProgress = FALSE;
2774                VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, pDevice->byOrgRCR);
2775                MACvSelectPage1(pDevice->PortOffset);
2776                VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, pDevice->dwOrgMAR0);
2777                VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR4, pDevice->dwOrgMAR4);
2778                VNSvInPortB(pDevice->PortOffset + MAC_REG_MSRBBSTS, &byData);
2779                pDevice->byBasicMap |= (byData >> 4);
2780                VNSvInPortB(pDevice->PortOffset + MAC_REG_CCAFRACTION, &pDevice->byCCAFraction);
2781                VNSvInPortB(pDevice->PortOffset + MAC_REG_MSRCTL, &byData);
2782                // clear measure control
2783                MACvRegBitsOff(pDevice->PortOffset, MAC_REG_MSRCTL, MSRCTL_EN);
2784                MACvSelectPage0(pDevice->PortOffset);
2785                CARDbSetChannel(pDevice, pDevice->byOrgChannel);
2786                // WCMDbResetCommandQueue(pDevice->pMgmt);
2787                MACvSelectPage1(pDevice->PortOffset);
2788                MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
2789                MACvSelectPage0(pDevice->PortOffset);
2790                if (byData & MSRCTL_FINISH) {
2791                    // measure success
2792                    s_vCompleteCurrentMeasure(pDevice, 0);
2793                } else {
2794                    // can not measure because not ready before end of measure time
2795                    s_vCompleteCurrentMeasure(pDevice, MEASURE_MODE_LATE);
2796                }
2797            }
2798            if (pDevice->dwIsr & ISR_QUIETSTART) {
2799                do {
2800                    ;
2801                } while (CARDbStartQuiet(pDevice) == FALSE);
2802            }
2803        }
2804
2805        if (pDevice->dwIsr & ISR_TBTT) {
2806            if (pDevice->bEnableFirstQuiet == TRUE) {
2807                pDevice->byQuietStartCount--;
2808                if (pDevice->byQuietStartCount == 0) {
2809                    pDevice->bEnableFirstQuiet = FALSE;
2810                    MACvSelectPage1(pDevice->PortOffset);
2811                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL, (MSRCTL_QUIETTXCHK | MSRCTL_QUIETEN));
2812                    MACvSelectPage0(pDevice->PortOffset);
2813                }
2814            }
2815            if ((pDevice->bChannelSwitch == TRUE) &&
2816                (pDevice->eOPMode == OP_MODE_INFRASTRUCTURE)) {
2817                pDevice->byChannelSwitchCount--;
2818                if (pDevice->byChannelSwitchCount == 0) {
2819                    pDevice->bChannelSwitch = FALSE;
2820                    CARDbSetChannel(pDevice, pDevice->byNewChannel);
2821                    VNTWIFIbChannelSwitch(pDevice->pMgmt, pDevice->byNewChannel);
2822                    MACvSelectPage1(pDevice->PortOffset);
2823                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
2824                    MACvSelectPage0(pDevice->PortOffset);
2825                    CARDbStartTxPacket(pDevice, PKT_TYPE_802_11_ALL);
2826
2827                }
2828            }
2829            if (pDevice->eOPMode == OP_MODE_ADHOC) {
2830                //pDevice->bBeaconSent = FALSE;
2831            } else {
2832                if ((pDevice->bUpdateBBVGA) && (pDevice->bLinkPass == TRUE) && (pDevice->uCurrRSSI != 0)) {
2833                    LONG            ldBm;
2834
2835                    RFvRSSITodBm(pDevice, (BYTE) pDevice->uCurrRSSI, &ldBm);
2836                    for (ii=0;ii<BB_VGA_LEVEL;ii++) {
2837                        if (ldBm < pDevice->ldBmThreshold[ii]) {
2838                            pDevice->byBBVGANew = pDevice->abyBBVGA[ii];
2839                            break;
2840                        }
2841                    }
2842                    if (pDevice->byBBVGANew != pDevice->byBBVGACurrent) {
2843                        pDevice->uBBVGADiffCount++;
2844                        if (pDevice->uBBVGADiffCount == 1) {
2845                            // first VGA diff gain
2846                            BBvSetVGAGainOffset(pDevice, pDevice->byBBVGANew);
2847                            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"First RSSI[%d] NewGain[%d] OldGain[%d] Count[%d]\n",
2848                                            (int)ldBm, pDevice->byBBVGANew, pDevice->byBBVGACurrent, (int)pDevice->uBBVGADiffCount);
2849                        }
2850                        if (pDevice->uBBVGADiffCount >= BB_VGA_CHANGE_THRESHOLD) {
2851                            DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RSSI[%d] NewGain[%d] OldGain[%d] Count[%d]\n",
2852                                            (int)ldBm, pDevice->byBBVGANew, pDevice->byBBVGACurrent, (int)pDevice->uBBVGADiffCount);
2853                            BBvSetVGAGainOffset(pDevice, pDevice->byBBVGANew);
2854                        }
2855                    } else {
2856                        pDevice->uBBVGADiffCount = 1;
2857                    }
2858                }
2859            }
2860
2861            pDevice->bBeaconSent = FALSE;
2862            if (pDevice->bEnablePSMode) {
2863                PSbIsNextTBTTWakeUp((void *)pDevice);
2864            };
2865
2866            if ((pDevice->eOPMode == OP_MODE_AP) ||
2867                (pDevice->eOPMode == OP_MODE_ADHOC)) {
2868
2869                MACvOneShotTimer1MicroSec(pDevice->PortOffset,
2870                        (pMgmt->wIBSSBeaconPeriod - MAKE_BEACON_RESERVED) << 10);
2871            }
2872
2873            if (pDevice->eOPMode == OP_MODE_ADHOC && pDevice->pMgmt->wCurrATIMWindow > 0) {
2874                // todo adhoc PS mode
2875            };
2876
2877        }
2878
2879        if (pDevice->dwIsr & ISR_BNTX) {
2880
2881            if (pDevice->eOPMode == OP_MODE_ADHOC) {
2882                pDevice->bIsBeaconBufReadySet = FALSE;
2883                pDevice->cbBeaconBufReadySetCnt = 0;
2884            };
2885
2886            if (pDevice->eOPMode == OP_MODE_AP) {
2887                if(pMgmt->byDTIMCount > 0) {
2888                   pMgmt->byDTIMCount --;
2889                   pMgmt->sNodeDBTable[0].bRxPSPoll = FALSE;
2890                }
2891                else {
2892                    if(pMgmt->byDTIMCount == 0) {
2893                        // check if mutltcast tx bufferring
2894                        pMgmt->byDTIMCount = pMgmt->byDTIMPeriod - 1;
2895                        pMgmt->sNodeDBTable[0].bRxPSPoll = TRUE;
2896                        bScheduleCommand((void *)pDevice, WLAN_CMD_RX_PSPOLL, NULL);
2897                    }
2898                }
2899            }
2900            pDevice->bBeaconSent = TRUE;
2901
2902            if (pDevice->bChannelSwitch == TRUE) {
2903                pDevice->byChannelSwitchCount--;
2904                if (pDevice->byChannelSwitchCount == 0) {
2905                    pDevice->bChannelSwitch = FALSE;
2906                    CARDbSetChannel(pDevice, pDevice->byNewChannel);
2907                    VNTWIFIbChannelSwitch(pDevice->pMgmt, pDevice->byNewChannel);
2908                    MACvSelectPage1(pDevice->PortOffset);
2909                    MACvRegBitsOn(pDevice->PortOffset, MAC_REG_MSRCTL+1, MSRCTL1_TXPAUSE);
2910                    MACvSelectPage0(pDevice->PortOffset);
2911                    //VNTWIFIbSendBeacon(pDevice->pMgmt);
2912                    CARDbStartTxPacket(pDevice, PKT_TYPE_802_11_ALL);
2913                }
2914            }
2915
2916        }
2917
2918        if (pDevice->dwIsr & ISR_RXDMA0) {
2919            max_count += device_rx_srv(pDevice, TYPE_RXDMA0);
2920        }
2921        if (pDevice->dwIsr & ISR_RXDMA1) {
2922            max_count += device_rx_srv(pDevice, TYPE_RXDMA1);
2923        }
2924        if (pDevice->dwIsr & ISR_TXDMA0){
2925            max_count += device_tx_srv(pDevice, TYPE_TXDMA0);
2926        }
2927        if (pDevice->dwIsr & ISR_AC0DMA){
2928            max_count += device_tx_srv(pDevice, TYPE_AC0DMA);
2929        }
2930        if (pDevice->dwIsr & ISR_SOFTTIMER) {
2931
2932        }
2933        if (pDevice->dwIsr & ISR_SOFTTIMER1) {
2934            if (pDevice->eOPMode == OP_MODE_AP) {
2935               if (pDevice->bShortSlotTime)
2936                   pMgmt->wCurrCapInfo |= WLAN_SET_CAP_INFO_SHORTSLOTTIME(1);
2937               else
2938                   pMgmt->wCurrCapInfo &= ~(WLAN_SET_CAP_INFO_SHORTSLOTTIME(1));
2939            }
2940            bMgrPrepareBeaconToSend(pDevice, pMgmt);
2941            pDevice->byCntMeasure = 0;
2942        }
2943
2944        MACvReadISR(pDevice->PortOffset, &pDevice->dwIsr);
2945
2946        MACvReceive0(pDevice->PortOffset);
2947        MACvReceive1(pDevice->PortOffset);
2948
2949        if (max_count>pDevice->sOpts.int_works)
2950            break;
2951    }
2952
2953    if (byOrgPageSel == 1) {
2954        MACvSelectPage1(pDevice->PortOffset);
2955    }
2956
2957    spin_unlock_irq(&pDevice->lock);
2958    MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
2959
2960    return IRQ_RETVAL(handled);
2961}
2962
2963
2964static unsigned const ethernet_polynomial = 0x04c11db7U;
2965static inline u32 ether_crc(int length, unsigned char *data)
2966{
2967    int crc = -1;
2968
2969    while(--length >= 0) {
2970        unsigned char current_octet = *data++;
2971        int bit;
2972        for (bit = 0; bit < 8; bit++, current_octet >>= 1) {
2973            crc = (crc << 1) ^
2974                ((crc < 0) ^ (current_octet & 1) ? ethernet_polynomial : 0);
2975        }
2976    }
2977    return crc;
2978}
2979
2980//2008-8-4 <add> by chester
2981static int Config_FileGetParameter(UCHAR *string, UCHAR *dest,UCHAR *source)
2982{
2983  UCHAR buf1[100];
2984  int source_len = strlen(source);
2985
2986    memset(buf1,0,100);
2987    strcat(buf1, string);
2988    strcat(buf1, "=");
2989    source+=strlen(buf1);
2990
2991   memcpy(dest,source,source_len-strlen(buf1));
2992 return TRUE;
2993}
2994
2995int Config_FileOperation(PSDevice pDevice,BOOL fwrite,unsigned char *Parameter) {
2996    UCHAR    *config_path=CONFIG_PATH;
2997    UCHAR    *buffer=NULL;
2998    UCHAR      tmpbuffer[20];
2999    struct file   *filp=NULL;
3000    mm_segment_t old_fs = get_fs();
3001    //int oldfsuid=0,oldfsgid=0;
3002    int result=0;
3003
3004    set_fs (KERNEL_DS);
3005
3006    /* Can't do this anymore, so we rely on correct filesystem permissions:
3007    //Make sure a caller can read or write power as root
3008    oldfsuid=current->cred->fsuid;
3009    oldfsgid=current->cred->fsgid;
3010    current->cred->fsuid = 0;
3011    current->cred->fsgid = 0;
3012    */
3013
3014    //open file
3015      filp = filp_open(config_path, O_RDWR, 0);
3016        if (IS_ERR(filp)) {
3017	     printk("Config_FileOperation:open file fail?\n");
3018	     result=-1;
3019             goto error2;
3020	  }
3021
3022     if(!(filp->f_op) || !(filp->f_op->read) ||!(filp->f_op->write)) {
3023           printk("file %s cann't readable or writable?\n",config_path);
3024	  result = -1;
3025	  goto error1;
3026     	}
3027
3028buffer = kmalloc(1024, GFP_KERNEL);
3029if(buffer==NULL) {
3030  printk("alllocate mem for file fail?\n");
3031  result = -1;
3032  goto error1;
3033}
3034
3035if(filp->f_op->read(filp, buffer, 1024, &filp->f_pos)<0) {
3036 printk("read file error?\n");
3037 result = -1;
3038 goto error1;
3039}
3040
3041if(Config_FileGetParameter("ZONETYPE",tmpbuffer,buffer)!=TRUE) {
3042  printk("get parameter error?\n");
3043  result = -1;
3044  goto error1;
3045}
3046
3047if(memcmp(tmpbuffer,"USA",3)==0) {
3048  result=ZoneType_USA;
3049}
3050else if(memcmp(tmpbuffer,"JAPAN",5)==0) {
3051  result=ZoneType_Japan;
3052}
3053else if(memcmp(tmpbuffer,"EUROPE",5)==0) {
3054 result=ZoneType_Europe;
3055}
3056else {
3057  result = -1;
3058  printk("Unknown Zonetype[%s]?\n",tmpbuffer);
3059}
3060
3061error1:
3062  if(buffer)
3063  	 kfree(buffer);
3064
3065  if(filp_close(filp,NULL))
3066       printk("Config_FileOperation:close file fail\n");
3067
3068error2:
3069  set_fs (old_fs);
3070
3071  /*
3072  current->cred->fsuid=oldfsuid;
3073  current->cred->fsgid=oldfsgid;
3074  */
3075
3076  return result;
3077}
3078
3079
3080
3081static void device_set_multi(struct net_device *dev) {
3082    PSDevice         pDevice = (PSDevice) netdev_priv(dev);
3083
3084    PSMgmtObject     pMgmt = pDevice->pMgmt;
3085    u32              mc_filter[2];
3086    struct dev_mc_list *mclist;
3087
3088
3089    VNSvInPortB(pDevice->PortOffset + MAC_REG_RCR, &(pDevice->byRxMode));
3090
3091    if (dev->flags & IFF_PROMISC) {         /* Set promiscuous. */
3092        DBG_PRT(MSG_LEVEL_ERR,KERN_NOTICE "%s: Promiscuous mode enabled.\n", dev->name);
3093        /* Unconditionally log net taps. */
3094        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST|RCR_UNICAST);
3095    }
3096    else if ((netdev_mc_count(dev) > pDevice->multicast_limit)
3097        ||  (dev->flags & IFF_ALLMULTI)) {
3098        MACvSelectPage1(pDevice->PortOffset);
3099        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, 0xffffffff);
3100        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0 + 4, 0xffffffff);
3101        MACvSelectPage0(pDevice->PortOffset);
3102        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
3103    }
3104    else {
3105        memset(mc_filter, 0, sizeof(mc_filter));
3106	netdev_for_each_mc_addr(mclist, dev) {
3107            int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
3108            mc_filter[bit_nr >> 5] |= cpu_to_le32(1 << (bit_nr & 31));
3109        }
3110        MACvSelectPage1(pDevice->PortOffset);
3111        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0, mc_filter[0]);
3112        VNSvOutPortD(pDevice->PortOffset + MAC_REG_MAR0 + 4, mc_filter[1]);
3113        MACvSelectPage0(pDevice->PortOffset);
3114        pDevice->byRxMode &= ~(RCR_UNICAST);
3115        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
3116    }
3117
3118    if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
3119        // If AP mode, don't enable RCR_UNICAST. Since hw only compare addr1 with local mac.
3120        pDevice->byRxMode |= (RCR_MULTICAST|RCR_BROADCAST);
3121        pDevice->byRxMode &= ~(RCR_UNICAST);
3122    }
3123
3124    VNSvOutPortB(pDevice->PortOffset + MAC_REG_RCR, pDevice->byRxMode);
3125    DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "pDevice->byRxMode = %x\n", pDevice->byRxMode );
3126}
3127
3128
3129static struct net_device_stats *device_get_stats(struct net_device *dev) {
3130    PSDevice pDevice=(PSDevice) netdev_priv(dev);
3131
3132    return &pDevice->stats;
3133}
3134
3135
3136
3137static int  device_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) {
3138	PSDevice	        pDevice = (PSDevice)netdev_priv(dev);
3139
3140	struct iwreq *wrq = (struct iwreq *) rq;
3141	int                 rc =0;
3142    PSMgmtObject        pMgmt = pDevice->pMgmt;
3143    PSCmdRequest        pReq;
3144
3145
3146    if (pMgmt == NULL) {
3147        rc = -EFAULT;
3148        return rc;
3149    }
3150
3151    switch(cmd) {
3152
3153	case SIOCGIWNAME:
3154		rc = iwctl_giwname(dev, NULL, (char *)&(wrq->u.name), NULL);
3155		break;
3156
3157	case SIOCGIWNWID:     //0x8b03  support
3158	#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
3159          rc = iwctl_giwnwid(dev, NULL, &(wrq->u.nwid), NULL);
3160	#else
3161        rc = -EOPNOTSUPP;
3162	#endif
3163		break;
3164
3165		// Set frequency/channel
3166	case SIOCSIWFREQ:
3167	    rc = iwctl_siwfreq(dev, NULL, &(wrq->u.freq), NULL);
3168		break;
3169
3170		// Get frequency/channel
3171	case SIOCGIWFREQ:
3172		rc = iwctl_giwfreq(dev, NULL, &(wrq->u.freq), NULL);
3173		break;
3174
3175		// Set desired network name (ESSID)
3176	case SIOCSIWESSID:
3177
3178		{
3179			char essid[IW_ESSID_MAX_SIZE+1];
3180			if (wrq->u.essid.length > IW_ESSID_MAX_SIZE) {
3181				rc = -E2BIG;
3182				break;
3183			}
3184			if (copy_from_user(essid, wrq->u.essid.pointer,
3185					   wrq->u.essid.length)) {
3186				rc = -EFAULT;
3187				break;
3188			}
3189			rc = iwctl_siwessid(dev, NULL,
3190					    &(wrq->u.essid), essid);
3191		}
3192		break;
3193
3194
3195		// Get current network name (ESSID)
3196	case SIOCGIWESSID:
3197
3198		{
3199			char essid[IW_ESSID_MAX_SIZE+1];
3200			if (wrq->u.essid.pointer)
3201				rc = iwctl_giwessid(dev, NULL,
3202						    &(wrq->u.essid), essid);
3203				if (copy_to_user(wrq->u.essid.pointer,
3204						         essid,
3205						         wrq->u.essid.length) )
3206					rc = -EFAULT;
3207		}
3208		break;
3209
3210	case SIOCSIWAP:
3211
3212		rc = iwctl_siwap(dev, NULL, &(wrq->u.ap_addr), NULL);
3213		break;
3214
3215
3216		// Get current Access Point (BSSID)
3217	case SIOCGIWAP:
3218		rc = iwctl_giwap(dev, NULL, &(wrq->u.ap_addr), NULL);
3219		break;
3220
3221
3222		// Set desired station name
3223	case SIOCSIWNICKN:
3224        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWNICKN \n");
3225        rc = -EOPNOTSUPP;
3226		break;
3227
3228		// Get current station name
3229	case SIOCGIWNICKN:
3230        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWNICKN \n");
3231        rc = -EOPNOTSUPP;
3232		break;
3233
3234		// Set the desired bit-rate
3235	case SIOCSIWRATE:
3236		rc = iwctl_siwrate(dev, NULL, &(wrq->u.bitrate), NULL);
3237		break;
3238
3239	// Get the current bit-rate
3240	case SIOCGIWRATE:
3241
3242		rc = iwctl_giwrate(dev, NULL, &(wrq->u.bitrate), NULL);
3243		break;
3244
3245	// Set the desired RTS threshold
3246	case SIOCSIWRTS:
3247
3248		rc = iwctl_siwrts(dev, NULL, &(wrq->u.rts), NULL);
3249		break;
3250
3251	// Get the current RTS threshold
3252	case SIOCGIWRTS:
3253
3254		rc = iwctl_giwrts(dev, NULL, &(wrq->u.rts), NULL);
3255		break;
3256
3257		// Set the desired fragmentation threshold
3258	case SIOCSIWFRAG:
3259
3260		rc = iwctl_siwfrag(dev, NULL, &(wrq->u.frag), NULL);
3261	    break;
3262
3263	// Get the current fragmentation threshold
3264	case SIOCGIWFRAG:
3265
3266		rc = iwctl_giwfrag(dev, NULL, &(wrq->u.frag), NULL);
3267		break;
3268
3269		// Set mode of operation
3270	case SIOCSIWMODE:
3271    	rc = iwctl_siwmode(dev, NULL, &(wrq->u.mode), NULL);
3272		break;
3273
3274		// Get mode of operation
3275	case SIOCGIWMODE:
3276		rc = iwctl_giwmode(dev, NULL, &(wrq->u.mode), NULL);
3277		break;
3278
3279		// Set WEP keys and mode
3280	case SIOCSIWENCODE:
3281		{
3282            char abyKey[WLAN_WEP232_KEYLEN];
3283
3284			if (wrq->u.encoding.pointer) {
3285
3286
3287				if (wrq->u.encoding.length > WLAN_WEP232_KEYLEN) {
3288					rc = -E2BIG;
3289					break;
3290				}
3291				memset(abyKey, 0, WLAN_WEP232_KEYLEN);
3292				if (copy_from_user(abyKey,
3293				                  wrq->u.encoding.pointer,
3294				                  wrq->u.encoding.length)) {
3295					rc = -EFAULT;
3296					break;
3297				}
3298			} else if (wrq->u.encoding.length != 0) {
3299				rc = -EINVAL;
3300				break;
3301			}
3302			rc = iwctl_siwencode(dev, NULL, &(wrq->u.encoding), abyKey);
3303		}
3304		break;
3305
3306		// Get the WEP keys and mode
3307	case SIOCGIWENCODE:
3308
3309		if (!capable(CAP_NET_ADMIN)) {
3310			rc = -EPERM;
3311			break;
3312		}
3313		{
3314		    char abyKey[WLAN_WEP232_KEYLEN];
3315
3316		    rc = iwctl_giwencode(dev, NULL, &(wrq->u.encoding), abyKey);
3317		    if (rc != 0) break;
3318			if (wrq->u.encoding.pointer) {
3319				if (copy_to_user(wrq->u.encoding.pointer,
3320						        abyKey,
3321						        wrq->u.encoding.length))
3322					rc = -EFAULT;
3323			}
3324		}
3325		break;
3326
3327		// Get the current Tx-Power
3328	case SIOCGIWTXPOW:
3329        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWTXPOW \n");
3330        rc = -EOPNOTSUPP;
3331		break;
3332
3333	case SIOCSIWTXPOW:
3334        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWTXPOW \n");
3335        rc = -EOPNOTSUPP;
3336		break;
3337
3338	case SIOCSIWRETRY:
3339
3340		rc = iwctl_siwretry(dev, NULL, &(wrq->u.retry), NULL);
3341		break;
3342
3343	case SIOCGIWRETRY:
3344
3345		rc = iwctl_giwretry(dev, NULL, &(wrq->u.retry), NULL);
3346		break;
3347
3348		// Get range of parameters
3349	case SIOCGIWRANGE:
3350
3351		{
3352			struct iw_range range;
3353
3354			rc = iwctl_giwrange(dev, NULL, &(wrq->u.data), (char *) &range);
3355			if (copy_to_user(wrq->u.data.pointer, &range, sizeof(struct iw_range)))
3356				rc = -EFAULT;
3357		}
3358
3359		break;
3360
3361	case SIOCGIWPOWER:
3362
3363		rc = iwctl_giwpower(dev, NULL, &(wrq->u.power), NULL);
3364		break;
3365
3366
3367	case SIOCSIWPOWER:
3368
3369		rc = iwctl_siwpower(dev, NULL, &(wrq->u.power), NULL);
3370		break;
3371
3372
3373	case SIOCGIWSENS:
3374
3375	    rc = iwctl_giwsens(dev, NULL, &(wrq->u.sens), NULL);
3376		break;
3377
3378	case SIOCSIWSENS:
3379        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSENS \n");
3380		rc = -EOPNOTSUPP;
3381		break;
3382
3383	case SIOCGIWAPLIST:
3384	    {
3385            char buffer[IW_MAX_AP * (sizeof(struct sockaddr) + sizeof(struct iw_quality))];
3386
3387		    if (wrq->u.data.pointer) {
3388		        rc = iwctl_giwaplist(dev, NULL, &(wrq->u.data), buffer);
3389		        if (rc == 0) {
3390                    if (copy_to_user(wrq->u.data.pointer,
3391					                buffer,
3392					               (wrq->u.data.length * (sizeof(struct sockaddr) +  sizeof(struct iw_quality)))
3393				        ))
3394				    rc = -EFAULT;
3395		        }
3396            }
3397        }
3398		break;
3399
3400
3401#ifdef WIRELESS_SPY
3402		// Set the spy list
3403	case SIOCSIWSPY:
3404
3405        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWSPY \n");
3406		rc = -EOPNOTSUPP;
3407		break;
3408
3409		// Get the spy list
3410	case SIOCGIWSPY:
3411
3412        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWSPY \n");
3413		rc = -EOPNOTSUPP;
3414		break;
3415
3416#endif // WIRELESS_SPY
3417
3418	case SIOCGIWPRIV:
3419        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWPRIV \n");
3420		rc = -EOPNOTSUPP;
3421/*
3422		if(wrq->u.data.pointer) {
3423			wrq->u.data.length = sizeof(iwctl_private_args) / sizeof( iwctl_private_args[0]);
3424
3425			if(copy_to_user(wrq->u.data.pointer,
3426					(u_char *) iwctl_private_args,
3427					sizeof(iwctl_private_args)))
3428				rc = -EFAULT;
3429		}
3430*/
3431		break;
3432
3433
3434//2008-0409-07, <Add> by Einsn Liu
3435#ifdef  WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
3436	case SIOCSIWAUTH:
3437		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWAUTH \n");
3438		rc = iwctl_siwauth(dev, NULL, &(wrq->u.param), NULL);
3439		break;
3440
3441	case SIOCGIWAUTH:
3442		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWAUTH \n");
3443		rc = iwctl_giwauth(dev, NULL, &(wrq->u.param), NULL);
3444		break;
3445
3446	case SIOCSIWGENIE:
3447		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWGENIE \n");
3448		rc = iwctl_siwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
3449		break;
3450
3451	case SIOCGIWGENIE:
3452		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWGENIE \n");
3453		rc = iwctl_giwgenie(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
3454		break;
3455
3456	case SIOCSIWENCODEEXT:
3457		{
3458			char extra[sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1];
3459			DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWENCODEEXT \n");
3460			if(wrq->u.encoding.pointer){
3461				memset(extra, 0, sizeof(struct iw_encode_ext)+MAX_KEY_LEN+1);
3462				if(wrq->u.encoding.length > (sizeof(struct iw_encode_ext)+ MAX_KEY_LEN)){
3463					rc = -E2BIG;
3464					break;
3465				}
3466				if(copy_from_user(extra, wrq->u.encoding.pointer,wrq->u.encoding.length)){
3467					rc = -EFAULT;
3468					break;
3469				}
3470			}else if(wrq->u.encoding.length != 0){
3471				rc = -EINVAL;
3472				break;
3473			}
3474			rc = iwctl_siwencodeext(dev, NULL, &(wrq->u.encoding), extra);
3475		}
3476		break;
3477
3478	case SIOCGIWENCODEEXT:
3479		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCGIWENCODEEXT \n");
3480		rc = iwctl_giwencodeext(dev, NULL, &(wrq->u.encoding), NULL);
3481		break;
3482
3483	case SIOCSIWMLME:
3484		DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO " SIOCSIWMLME \n");
3485		rc = iwctl_siwmlme(dev, NULL, &(wrq->u.data), wrq->u.data.pointer);
3486		break;
3487
3488#endif // #ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
3489//End Add -- //2008-0409-07, <Add> by Einsn Liu
3490
3491    case IOCTL_CMD_TEST:
3492
3493		if (!(pDevice->flags & DEVICE_FLAGS_OPENED)) {
3494		    rc = -EFAULT;
3495		    break;
3496		} else {
3497		    rc = 0;
3498		}
3499        pReq = (PSCmdRequest)rq;
3500        pReq->wResult = MAGIC_CODE;
3501        break;
3502
3503    case IOCTL_CMD_SET:
3504
3505               #ifdef SndEvt_ToAPI
3506                  if((((PSCmdRequest)rq)->wCmdCode !=WLAN_CMD_SET_EVT) &&
3507		       !(pDevice->flags & DEVICE_FLAGS_OPENED))
3508	      #else
3509		if (!(pDevice->flags & DEVICE_FLAGS_OPENED) &&
3510		       (((PSCmdRequest)rq)->wCmdCode !=WLAN_CMD_SET_WPA))
3511	      #endif
3512		{
3513		    rc = -EFAULT;
3514		    break;
3515		} else {
3516		    rc = 0;
3517		}
3518
3519	    if (test_and_set_bit( 0, (void*)&(pMgmt->uCmdBusy))) {
3520		    return -EBUSY;
3521	    }
3522        rc = private_ioctl(pDevice, rq);
3523        clear_bit( 0, (void*)&(pMgmt->uCmdBusy));
3524        break;
3525
3526    case IOCTL_CMD_HOSTAPD:
3527
3528
3529	rc = vt6655_hostap_ioctl(pDevice, &wrq->u.data);
3530        break;
3531
3532    case IOCTL_CMD_WPA:
3533
3534	rc = wpa_ioctl(pDevice, &wrq->u.data);
3535        break;
3536
3537	case SIOCETHTOOL:
3538        return ethtool_ioctl(dev, (void *) rq->ifr_data);
3539	// All other calls are currently unsupported
3540
3541	default:
3542		rc = -EOPNOTSUPP;
3543        DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Ioctl command not support..%x\n", cmd);
3544
3545
3546    }
3547
3548    if (pDevice->bCommit) {
3549       if (pMgmt->eConfigMode == WMAC_CONFIG_AP) {
3550           netif_stop_queue(pDevice->dev);
3551           spin_lock_irq(&pDevice->lock);
3552           bScheduleCommand((void *)pDevice, WLAN_CMD_RUN_AP, NULL);
3553           spin_unlock_irq(&pDevice->lock);
3554       }
3555       else {
3556           DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO "Commit the settings\n");
3557           spin_lock_irq(&pDevice->lock);
3558           pDevice->bLinkPass = FALSE;
3559           memset(pMgmt->abyCurrBSSID, 0, 6);
3560           pMgmt->eCurrState = WMAC_STATE_IDLE;
3561           netif_stop_queue(pDevice->dev);
3562	#ifdef WPA_SUPPLICANT_DRIVER_WEXT_SUPPORT
3563	      pMgmt->eScanType = WMAC_SCAN_ACTIVE;
3564	 if(pDevice->bWPASuppWextEnabled !=TRUE)
3565	 #endif
3566           bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, pMgmt->abyDesireSSID);
3567           bScheduleCommand((void *) pDevice, WLAN_CMD_SSID, NULL);
3568           spin_unlock_irq(&pDevice->lock);
3569      }
3570      pDevice->bCommit = FALSE;
3571    }
3572
3573    return rc;
3574}
3575
3576
3577static int ethtool_ioctl(struct net_device *dev, void *useraddr)
3578{
3579	u32 ethcmd;
3580
3581	if (copy_from_user(&ethcmd, useraddr, sizeof(ethcmd)))
3582		return -EFAULT;
3583
3584        switch (ethcmd) {
3585	case ETHTOOL_GDRVINFO: {
3586		struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
3587		strncpy(info.driver, DEVICE_NAME, sizeof(info.driver)-1);
3588		strncpy(info.version, DEVICE_VERSION, sizeof(info.version)-1);
3589		if (copy_to_user(useraddr, &info, sizeof(info)))
3590			return -EFAULT;
3591		return 0;
3592	}
3593
3594        }
3595
3596	return -EOPNOTSUPP;
3597}
3598
3599/*------------------------------------------------------------------*/
3600
3601MODULE_DEVICE_TABLE(pci, device_id_table);
3602
3603static struct pci_driver device_driver = {
3604        name:       DEVICE_NAME,
3605        id_table:   device_id_table,
3606        probe:      device_found1,
3607        remove:     device_remove1,
3608#ifdef CONFIG_PM
3609        suspend:    viawget_suspend,
3610        resume:     viawget_resume,
3611#endif
3612};
3613
3614static int __init device_init_module(void)
3615{
3616    int ret;
3617
3618
3619//    ret=pci_module_init(&device_driver);
3620	//ret = pcie_port_service_register(&device_driver);
3621	ret = pci_register_driver(&device_driver);
3622#ifdef CONFIG_PM
3623    if(ret >= 0)
3624        register_reboot_notifier(&device_notifier);
3625#endif
3626
3627    return ret;
3628}
3629
3630static void __exit device_cleanup_module(void)
3631{
3632
3633
3634#ifdef CONFIG_PM
3635    unregister_reboot_notifier(&device_notifier);
3636#endif
3637    pci_unregister_driver(&device_driver);
3638
3639}
3640
3641module_init(device_init_module);
3642module_exit(device_cleanup_module);
3643
3644
3645#ifdef CONFIG_PM
3646static int
3647device_notify_reboot(struct notifier_block *nb, unsigned long event, void *p)
3648{
3649    struct pci_dev *pdev = NULL;
3650    switch(event) {
3651    case SYS_DOWN:
3652    case SYS_HALT:
3653    case SYS_POWER_OFF:
3654        while ((pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev)) != NULL) {
3655            if(pci_dev_driver(pdev) == &device_driver) {
3656                if (pci_get_drvdata(pdev))
3657                    viawget_suspend(pdev, PMSG_HIBERNATE);
3658            }
3659        }
3660    }
3661    return NOTIFY_DONE;
3662}
3663
3664static int
3665viawget_suspend(struct pci_dev *pcid, pm_message_t state)
3666{
3667    int power_status;   // to silence the compiler
3668
3669    PSDevice pDevice=pci_get_drvdata(pcid);
3670    PSMgmtObject  pMgmt = pDevice->pMgmt;
3671
3672    netif_stop_queue(pDevice->dev);
3673    spin_lock_irq(&pDevice->lock);
3674    pci_save_state(pcid);
3675    del_timer(&pDevice->sTimerCommand);
3676    del_timer(&pMgmt->sTimerSecondCallback);
3677    pDevice->cbFreeCmdQueue = CMD_Q_SIZE;
3678    pDevice->uCmdDequeueIdx = 0;
3679    pDevice->uCmdEnqueueIdx = 0;
3680    pDevice->bCmdRunning = FALSE;
3681    MACbShutdown(pDevice->PortOffset);
3682    MACvSaveContext(pDevice->PortOffset, pDevice->abyMacContext);
3683    pDevice->bLinkPass = FALSE;
3684    memset(pMgmt->abyCurrBSSID, 0, 6);
3685    pMgmt->eCurrState = WMAC_STATE_IDLE;
3686    pci_disable_device(pcid);
3687    power_status = pci_set_power_state(pcid, pci_choose_state(pcid, state));
3688    spin_unlock_irq(&pDevice->lock);
3689    return 0;
3690}
3691
3692static int
3693viawget_resume(struct pci_dev *pcid)
3694{
3695    PSDevice  pDevice=pci_get_drvdata(pcid);
3696    PSMgmtObject  pMgmt = pDevice->pMgmt;
3697    int power_status;   // to silence the compiler
3698
3699
3700    power_status = pci_set_power_state(pcid, 0);
3701    power_status = pci_enable_wake(pcid, 0, 0);
3702    pci_restore_state(pcid);
3703    if (netif_running(pDevice->dev)) {
3704        spin_lock_irq(&pDevice->lock);
3705        MACvRestoreContext(pDevice->PortOffset, pDevice->abyMacContext);
3706        device_init_registers(pDevice, DEVICE_INIT_DXPL);
3707        if (pMgmt->sNodeDBTable[0].bActive == TRUE) { // Assoc with BSS
3708            pMgmt->sNodeDBTable[0].bActive = FALSE;
3709            pDevice->bLinkPass = FALSE;
3710            if(pMgmt->eCurrMode == WMAC_MODE_IBSS_STA) {
3711                // In Adhoc, BSS state set back to started.
3712                pMgmt->eCurrState = WMAC_STATE_STARTED;
3713           }
3714            else {
3715                pMgmt->eCurrMode = WMAC_MODE_STANDBY;
3716                pMgmt->eCurrState = WMAC_STATE_IDLE;
3717            }
3718        }
3719        init_timer(&pMgmt->sTimerSecondCallback);
3720        init_timer(&pDevice->sTimerCommand);
3721        MACvIntEnable(pDevice->PortOffset, IMR_MASK_VALUE);
3722        BSSvClearBSSList((void *)pDevice, pDevice->bLinkPass);
3723        bScheduleCommand((void *) pDevice, WLAN_CMD_BSSID_SCAN, NULL);
3724        bScheduleCommand((void *) pDevice, WLAN_CMD_SSID, NULL);
3725        spin_unlock_irq(&pDevice->lock);
3726    }
3727    return 0;
3728}
3729
3730#endif
3731
3732
3733
3734
3735