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