/*************************************************************************** 
 * RT2x00 SourceForge Project - http://rt2x00.sourceforge.net              * 
 *                                                                         * 
 *   This program is free software; you can redistribute it and/or modify  * 
 *   it under the terms of the GNU General Public License as published by  * 
 *   the Free Software Foundation; either version 2 of the License, or     * 
 *   (at your option) any later version.                                   * 
 *                                                                         * 
 *   This program is distributed in the hope that it will be useful,       * 
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        * 
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         * 
 *   GNU General Public License for more details.                          * 
 *                                                                         * 
 *   You should have received a copy of the GNU General Public License     * 
 *   along with this program; if not, write to the                         * 
 *   Free Software Foundation, Inc.,                                       * 
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             * 
 *                                                                         * 
 *   Licensed under the GNU GPL                                            * 
 *   Original code supplied under license from RaLink Inc, 2004.           * 
 ***************************************************************************/

/*************************************************************************** 
 *	Module Name:	rt2570sw.h
 *
 *	Abstract:
 *
 *	Revision History:
 *	Who		When		What
 *	--------	----------	------------------------------------
 *	Name		Date		Modification logs
 *	Jan Lee		2005-06-01	Release
 *	Ivo		02-06-2005	Debug flag fix
 *	FelipeaA	02-06-2005	Added Conceptronic C54RU
 *	MathiasK	02-06-2005	Added F5D7050,UB801R
 *	MarkW		02-08-2005	Added MSI 6861
 *	PeterF		27-06-2005	Added GN-WBKG
 *	zak		03-07-2005	Added second GN-WBKG
 *	PedroP          04-07-2005      Added EMINENT 3035
 *      MarkW		06-12-2005	Added Linksys@Home  
 ***************************************************************************/


#ifndef __vnetsw_h_OK__
#define __vnetsw_h_OK__

#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0)
#include <linux/kthread.h>
#endif

//red,extern	unsigned long	NIC_VENDOR_DRIVER_VERSION;//blue
////////////////////////////////////////////////////////////////////////////
// Frame Sizes
////////////////////////////////////////////////////////////////////////////

#define MAC_ADDRESS_LENGTH                  6

#define HEADER_SIZE                     14
#define MAXIMUM_PACKET_SIZE             1500

#define MAX_QUEUE_SIZE                  100

#define USB_TX_HEADER_SIZE              8//WLength+TxRate+PaddingBytes+Reserved
#define USB_RX_HEADER_SIZE              12

#define WIRELESS_HEADER_OVERHEAD        18
#define MAX_TX_PADDING_BYTES            50
#define MAX_RX_PADDING_BYTES            66
#define CRC32_BYTES                     4

#define MAX_WIRELESS_SIZE               WIRELESS_HEADER_OVERHEAD + HEADER_SIZE + MAXIMUM_PACKET_SIZE + CRC32_BYTES
extern unsigned long flagg;


typedef UCHAR ADDRESS[MAC_ADDRESS_LENGTH];

////////////////////////////////////////////////////////////////////////////
// NDIS related definitions
////////////////////////////////////////////////////////////////////////////
#define MAX_MULTICAST_ADDRESSES         32
#define MAX_LOOKAHEAD_SIZE              MAXIMUM_PACKET_SIZE + HEADER_SIZE
#define TRANSMIT_BUFFER_SPACE           0x3000
#define RECEIVE_BUFFER_SPACE            0x4000
#define MAXIMUM_SEND_PACKETS            8

#define OPER_RATE_SIZE                  4

#define SUPPORTED_RATES_SET_1           0
#define SUPPORTED_RATES_SET_2           1


////////////////////////////////////////////////////////////////////////////
// Memory Macros
////////////////////////////////////////////////////////////////////////////
#define FreeMemory(_buffer) kfree(_buffer)

////////////////////////////////////////////////////////////////////////////
// 802,11 related definitions
////////////////////////////////////////////////////////////////////////////
#define ESS_ID_SIZE                             32
#define AD_HOC_MODE                             1
#define INFRASTRUCTURE_MODE                     2
#define WEP_KEY_SIZE                            13 //128-bit encryption
#define PREAMBLE_TYPE_LONG                      0
#define PREAMBLE_TYPE_SHORT                     1

////////////////////////////////////////////////////////////////////////////
// used to track information on usb pipes in use
////////////////////////////////////////////////////////////////////////////
typedef struct __BULKUSB_PIPEINFO {
    BOOLEAN fPipeOpened;
} BULKUSB_PIPEINFO, *PBULKUSB_PIPEINFO;


//#pragma pack (push, 1)


#define RTUSB_DEVICES { \
	{ USB_DEVICE(0x0411, 0x0066)},	/* Melco */		\
	{ USB_DEVICE(0x0411, 0x0067)},	/* Melco */		\
	{ USB_DEVICE(0x050d, 0x7050)},	/* Belkin */		\
	{ USB_DEVICE(0x050d, 0x705a)},  /* Belkin */		\
	{ USB_DEVICE(0x06f8, 0xe000)}, /* GUILLEMOT */		\
	{ USB_DEVICE(0x0707, 0xee13)},	/* SMC */		\
	{ USB_DEVICE(0x0b05, 0x1706)},	/* ASUS */		\
	{ USB_DEVICE(0x0b05, 0x1707)},	/* ASUS */		\
	{ USB_DEVICE(0x0db0, 0x6861)},	/* MSI */		\
	{ USB_DEVICE(0x0db0, 0x6865)},	/* MSI */		\
	{ USB_DEVICE(0x0db0, 0x6869)},	/* MSI */		\
	{ USB_DEVICE(0x1044, 0x8001)},	/* Gigabyte */		\
	{ USB_DEVICE(0x1044, 0x8007)},	/* Gigabyte */		\
	{ USB_DEVICE(0x114b, 0x0110)},	/* Spairon */		\
	{ USB_DEVICE(0x13b1, 0x000d)},	/* Cisco Systems */	\
	{ USB_DEVICE(0x13b1, 0x0011)},	/* Cisco Systems */	\
	{ USB_DEVICE(0x13b1, 0x001a)},  /* Cisco Systems */	\
	{ USB_DEVICE(0x148f, 0x1706)},	/* Ralink */		\
	{ USB_DEVICE(0x148f, 0x2570)},	/* Ralink */		\
	{ USB_DEVICE(0x148f, 0x2573)},	/* CNET CWD-854 */	\
	{ USB_DEVICE(0x148f, 0x9020)},	/* Ralink */		\
	{ USB_DEVICE(0x14b2, 0x3c02)},	/* Conceptronic */	\
	{ USB_DEVICE(0x14f8, 0x2570)},	/* Eminent */		\
	{ USB_DEVICE(0x2001, 0x3c00)},	/* D-LINK */		\
	{ USB_DEVICE(0x0411, 0x008b)},	/* Nintendo */		\
	{0,}							\
}


typedef struct urb *purbb_t;
typedef struct usb_ctrlrequest devctrlrequest;
// for vendor-specific control operations
#define CONTROL_TIMEOUT_MS	(500)			/* msec */
#define CONTROL_TIMEOUT_JIFFIES ((CONTROL_TIMEOUT_MS * HZ)/1000)
/* map devrequest fields onto usb_ctrlrequest's */
#define DEVREQ_REQUEST(x) ((x)->bRequest)
#define DEVREQ_REQUESTTYPE(x) ((x)->bRequestType)
#define DEVREQ_VALUE(x) ((x)->wValue)
#define DEVREQ_INDEX(x) ((x)->wIndex)
#define DEVREQ_LENGTH(x) ((x)->wLength)
#define PURB	purbb_t
#define PIRP	PVOID
#define PMDL PVOID

#define NDIS_OID UINT       

//
//  MACRO for debugging information
//
#ifdef RT2500_DBG
extern ULONG    debug;

#define DBGPRINT(Level, fmt, args...) 					\
{									\
	if (Level <= debug)						\
	{								\
		printk(KERN_DEBUG NIC_DBG_STRING fmt, ## args);		\
	}								\
}

#define DBGPRINT_RAW(Level, fmt, args...)				\
  {									\
	if (Level <= debug)						\
	{								\
		printk(fmt, ## args);					\
	}								\
}

#else /* RT2500_DBG */
#define DBGPRINT(Level, fmt, args...)
#define DBGPRINT_RAW(Level, fmt, args...)
#endif /* RT2500_DBG */


#  define assert(expr) \
        if(unlikely(!(expr))) {				        \
        printk(KERN_ERR "Assertion failed! %s,%s,%s,line=%d\n",	\
        #expr,__FILE__,__FUNCTION__,__LINE__);		        \
        }


//
// Defines the state of the LAN media
//
typedef enum _NDIS_MEDIA_STATE
{
    NdisMediaStateConnected,
    NdisMediaStateDisconnected
} NDIS_MEDIA_STATE, *PNDIS_MEDIA_STATE;


#define NdisMSetInformationComplete(handle, status)		\
{					\
}

#define NdisMIndicateStatusComplete(handle)		\
{					\
}

#define NdisMIndicateStatus(_M, _G, _SB, _BS)		\
{						\
}



//
//	The following structure defines the device power states.
//
typedef enum _NDIS_DEVICE_POWER_STATE
{
	NdisDeviceStateUnspecified = 0,
	NdisDeviceStateD0,
	NdisDeviceStateD1,
	NdisDeviceStateD2,
	NdisDeviceStateD3,
	NdisDeviceStateMaximum
} NDIS_DEVICE_POWER_STATE, *PNDIS_DEVICE_POWER_STATE;


#define ETH_LENGTH_OF_ADDRESS	6


#define STATUS_SUCCESS	0x00
#define STATUS_UNSUCCESSFUL 0x01

typedef LONG NTSTATUS;
typedef NTSTATUS *PNTSTATUS;

//
//	spin_lock enhanced for Nested spin lock
//
#define	NdisAllocateSpinLock(lock)		\
{									\
	spin_lock_init(lock);				\
}

#define NdisReleaseSpinLock(lock)						\
{										\
	if (in_interrupt())				\
{										\
		spin_unlock_irqrestore(lock, flagg);			\
}	\
	else						\
{										\
		spin_unlock(lock);			\
}	\
}

#define NdisAcquireSpinLock(lock)			\
{							\
	if (in_interrupt())				\
		spin_lock_irqsave(lock, flagg);			\
	else						\
		spin_lock(lock);			\
}


#define RTUSBFreeSkbBuffer(skb)				\
{											\
	dev_kfree_skb_any(skb);					\
}

#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
#define RTUSBUp(pAd, semaphore)	\
{				\
	if(pAd->MLMEThr_pid>0)	\
	up(semaphore);		\
}

#define RTUSBCMDUp(pAd, semaphore)	\
{	\
	if(pAd->RTUSBCmdThr_pid>0)	\
	up(semaphore);	\
}
#else
#define RTUSBUp(pAd, semaphore)	\
{				\
	if(pAd->MLMEThr_active)	\
	up(semaphore);		\
}

#define RTUSBCMDUp(pAd, semaphore)	\
{	\
	if(pAd->RTUSBCmdThr_active)	\
	up(semaphore);	\
}
#endif

//Setup Packet used in Ctrl urb's filler....

#define FILL_REQUEST(a,aa,ab,ac,ad,ae)\
  do {\
      (a)->devreq->request = aa;\
      (a)->devreq->requesttype = ab;\
      (a)->devreq->value = cpu_to_le16(ac);\
      (a)->devreq->index = cpu_to_le16(ad);\
      (a)->devreq->length = cpu_to_le16(ae);\
  }while(0);



// direction is specified in TransferFlags

#define URB_FUNCTION_RESERVED0                      0x0016

//
// These are for sending vendor and class commands
// on the default pipe
//
// direction is specified in TransferFlags
//

#define URB_FUNCTION_VENDOR_DEVICE                   0x0017
#define URB_FUNCTION_VENDOR_INTERFACE                0x0018
#define URB_FUNCTION_VENDOR_ENDPOINT                 0x0019
#define URB_FUNCTION_VENDOR_OTHER                    0x0020

#define URB_FUNCTION_CLASS_DEVICE                    0x001A
#define URB_FUNCTION_CLASS_INTERFACE                 0x001B
#define URB_FUNCTION_CLASS_ENDPOINT                  0x001C
#define URB_FUNCTION_CLASS_OTHER                     0x001F

//
// Reserved function codes
//                                                                                                        
#define URB_FUNCTION_RESERVED                        0x001D

#define URB_FUNCTION_GET_CONFIGURATION               0x0026
#define URB_FUNCTION_GET_INTERFACE                   0x0027
                    
#define URB_FUNCTION_LAST                            0x0029


//define Vendor Command Constant
#define CMD_VendorReset	0x01
#define CMD_Disconnect	0x02
#define CMD_FunctionSwitch 0x03
#define CMD_SetTestMode	0x04
#define CMD_ClearTestMode 0x05
#define CMD_WriteMacRegister 0x06
#define CMD_ReadMacRegister 0x07
#define CMD_EEPROMWrite 0x08
#define CMD_EEPROMRead 0x09
#define CMD_MultipleRead 0x0A
#define CMD_MultipleWrite 0x0B
#define CMD_SingleRead 0x0C
#define CMD_SingleWrite 0x0D

#define NdisMSleep	mdelay


//  Assert MACRO to make sure program running
//
#undef  ASSERT
#define ASSERT(x)                                                                       \
{                                                                                       \
    if (!(x))                                                                           \
    {                                                                                   \
        printk(KERN_WARNING __FILE__ ":%d assert " #x "failed\n", __LINE__);		\
    }                                                                                   \
}

#if 0
#undef MOD_INC_USE_COUNT
#define MOD_INC_USE_COUNT	do { } while (0)

#undef MOD_DEC_USE_COUNT
#define MOD_DEC_USE_COUNT	do { } while (0)
#endif


//add by james

////////////////////////////////////////////////////////////////////////////
// VERSION_INFO exchanged between driver/application
////////////////////////////////////////////////////////////////////////////
typedef struct __VERSION_INFO{
    UCHAR   DriverMajorVersion;
    UCHAR   DriverMinorVersion;
    UCHAR   DriverSubVersion;
    USHORT  DriverBuild;

    USHORT  FwMajorVersion;
    USHORT  FwMinorVersion;
    USHORT  FwSubVersion;
    USHORT  FwBuild;
}VERSION_INFO, *PVERSION_INFO;

#if 0
////////////////////////////////////////////////////////////////////////////
// The RX_BUFFER structure forms the Received USB packet from the device
////////////////////////////////////////////////////////////////////////////
typedef struct __RX_BUFFER{
    USHORT      WLength;
    UCHAR       RxRate;       //This field is not used in this version of Drv/FW
    UCHAR       ChangeBSSID;
    UCHAR       Fragmentation;//This field is not used in this version of Drv/FW
    UCHAR       RSSI;
    UCHAR       LinkQuality;
    UCHAR       NoiseLevel;   //This field is not used in this version of Drv/FW
    UCHAR       RxTime[4];    //This field is not used in this version of Drv/FW
    UCHAR       WirelessPacket[MAX_WIRELESS_SIZE];
} RX_BUFFER, *PRX_BUFFER;
#endif


////////////////////////////////////////////////////////////////////////////
// The TX_BUFFER structure forms the transmitted USB packet to the device
////////////////////////////////////////////////////////////////////////////
typedef struct _TX_BUFFER{
//	UINT			BulkOutSize;
    TXD_STRUC		TxDesc;
    UCHAR			WirelessPacket[2342];
} TX_BUFFER, *PTX_BUFFER;


////////////////////////////////////////////////////////////////////////////
// The RTS_BUFFER structure forms the transmitted USB packet to the device
////////////////////////////////////////////////////////////////////////////
typedef struct __RTS_BUFFER{
    TXD_STRUC      TxDesc;
    UCHAR	       RTSPacket[16];
} RTS_BUFFER, *PRTS_BUFFER;

////////////////////////////////////////////////////////////////////////////
// The USB_CARD_CONFIG structure is used only during device initialization
// to pass the initial operationg parameters to device
////////////////////////////////////////////////////////////////////////////
typedef struct __USB_CARD_CONFIG{
    UCHAR       ExcludeUnencrypted;
    UCHAR       PromiscuousMode;
    UCHAR       ShortRetryLimit;
    UCHAR       EncryptionType;
    USHORT      RtsThreshold;
    USHORT      FragmentationThreshold;     // 256..2346
    UCHAR       BasicRateSet[4];
    BOOLEAN     AutoRateFallBack;           //0,1
    UCHAR       Channel;
    BOOLEAN     PrivacyInvoked;
    UCHAR       WEPDefaultKeyID;            // 0..3
    UCHAR       CurrentSSID[32];
    UCHAR       WEPDefaultKeyValue[4][WEP_KEY_SIZE];
    UCHAR       SSIDLen;
    UCHAR       ShortPreamble;
    USHORT      BeaconPeriod;
} USB_CARD_CONFIG, *PUSB_CARD_CONFIG;


////////////////////////////////////////////////////////////////////////////
// In WEP_INFO are kept all the WEP related parameters. This structure is
// also exchanged between driver and application.
////////////////////////////////////////////////////////////////////////////
typedef struct __WEP_INFO{
    UCHAR                       WepKeyToUse;
    UCHAR                       WepMode;
    USHORT                      AuthenticationType;
    UCHAR                       EncryptionLevel;
    UCHAR                       WepKey1[WEP_KEY_SIZE];
    UCHAR                       WepKey2[WEP_KEY_SIZE];
    UCHAR                       WepKey3[WEP_KEY_SIZE];
    UCHAR                       WepKey4[WEP_KEY_SIZE];
} WEP_INFO, *PWEP_INFO;


////////////////////////////////////////////////////////////////////////////
// In the STATISTICS structure are kept all the device's statitrics.
// This structure is also exchanged between driver and application.
////////////////////////////////////////////////////////////////////////////
typedef struct __STATISTICS{
    ULONG   TxDataPacketsOk;
    ULONG   TxDataPacketsError;
    ULONG   TxMgmtPacketsOk;
    ULONG   TxMgmtPacketsError;

    ULONG   RxDataPacketsOk;
    ULONG   RxDataPacketsError;
    ULONG   RxMgmtPacketsOk;
    ULONG   RxMgmtPacketsError;

    ULONG   RxLost;
    ULONG   TxPacketsRejectedNotReady;
    ULONG   TxPacketsRejectedResources;
    ULONG   MatchingBeacons;
}STATISTICS, *PSTATISTICS;

////////////////////////////////////////////////////////////////////////////
// The BSS_INFO and SITE_SURVEY_INFO structures are used to form a custom
// list of 12 maximum BSSs and keet there characteristics.
// This list is the one that application displays in Site Survey Tab.
////////////////////////////////////////////////////////////////////////////
typedef struct __BSS_INFO{
    UCHAR   Channel;
    UCHAR   SSID[ESS_ID_SIZE];
    UCHAR   SSIDsize;
    UCHAR   BSSID[6];
    UCHAR   RSSI;
    UCHAR   UsingWEP;
    UCHAR   PreambleType;
    USHORT  BeaconPeriod;
    UCHAR   BSSType;  //11->Ad-Hoc, 2->Infrastructure
}BSS_INFO, *PBSS_INFO;

#define MAX_AP_ENTRIES  30

typedef struct __SITE_SURVEY_INFO{
    BSS_INFO        BSSinfo[MAX_AP_ENTRIES];
    UCHAR           BSSsInList;
    UCHAR           UserSelectedIndex;
    UCHAR           SiteSurveyState;
}SITE_SURVEY_INFO, *PSITE_SURVEY_INFO;

#ifdef WINXP
typedef struct __XP_BSSID_LIST{
    ULONG                   NumberOfEntries;
    NDIS_WLAN_BSSID         NdisBSSIDEntry[MAX_AP_ENTRIES];
}XP_BSSID_LIST;
#endif

//#pragma pack(pop)



////////////////////////////////////////////////////////////////////////////
// The FRAGMENTED_PACKET structure is used for the reassembly of the
// fragmented 802.11 packets in the driver
////////////////////////////////////////////////////////////////////////////
typedef struct __FRAGMENTED_PACKET{
    USHORT  Sequence;
    USHORT  CurrentLen;
    UCHAR   SourceAddress[6];
    UCHAR   FragmentNumber;//next fragment expected
    UCHAR   WirelessPacket[MAX_WIRELESS_SIZE];
}FRAGMENTED_PACKET, *PFRAGMENTED_PACKET;

////////////////////////////////////////////////////////////////////////////
// The ASYNC_OID structure is used for holding the context of an OID call
// that the driver will complete asynchronously
////////////////////////////////////////////////////////////////////////////
typedef struct __ASYNC_OID{
    PVOID   InformationBuffer;
    ULONG   InformationBufferLength;
    PULONG  Bytes;
    PULONG  BytesNeeded;
}ASYNC_OID, *PASYNC_OID;

#if 1//RT2460
//
//  Some utility macros
//
#ifndef min
#define min(_a, _b)     (((_a) < (_b)) ? (_a) : (_b))
#endif

#ifndef max
#define max(_a, _b)     (((_a) > (_b)) ? (_a) : (_b))
#endif

#define INC_COUNTER(Val)    (Val.QuadPart++)

#define	INFRA_ON(_p)		        (((_p)->PortCfg.Massoc) == TRUE)	// Check Massoc
#define ADHOC_ON(_p)                (((_p)->PortCfg.Mibss) == TRUE)    // check Mibss

#define	RTMP_SET_PACKET_FRAGMENTS(_p, number)	((_p)->cb[10] = number)
#define RTMP_GET_PACKET_FRAGMENTS(_p)			((_p)->cb[10])
#define	RTMP_SET_PACKET_RTS(_p, number)			((_p)->cb[11] = number)
#define RTMP_GET_PACKET_RTS(_p)					((_p)->cb[11])
#define	RTMP_SET_PACKET_FIRST_CONTEXT(_p, number)	((_p)->cb[12] = number)
#define RTMP_GET_PACKET_FIRST_CONTEXT(_p)			((_p)->cb[12])
//blue,#define	RTMP_SET_PACKET_CONTEXTS_REQUIRED(_p, number)	((_p)->cb[13] = number)
//blue,#define RTMP_GET_PACKET_CONTEXTS_REQUIRED(_p)			((_p)->cb[13])
#define GET_NEXT_PACKET_IN_BULKOUT_QUEUE(_p)			((struct sk_buff **)&((_p)->cb[14]))


#define	MAKE_802_3_HEADER(_p, _pMac1, _pMac2, _pType)								\
{																					\
	memcpy(_p, _pMac1, ETH_LENGTH_OF_ADDRESS);								\
	memcpy((_p + ETH_LENGTH_OF_ADDRESS), _pMac2, ETH_LENGTH_OF_ADDRESS);	\
	memcpy((_p + ETH_LENGTH_OF_ADDRESS * 2), _pType, LENGTH_802_3_TYPE);	\
}

//
// Register set pair for initialzation register set definition
//
typedef	struct	_RTMP_REG_PAIR
{
	ULONG	Register;
	ULONG	Value;
}	RTMP_REG_PAIR, *PRTMP_REG_PAIR;

//
// Register set pair for initialzation register set definition
//
typedef	struct	_RTMP_RF_REGS
{
	UCHAR   Channel;
	ULONG	R1;
	ULONG   R2;
	ULONG   R3;
	ULONG   R4;
}	RTMP_RF_REGS, *PRTMP_RF_REGS;

typedef	struct	_RTMP_RF_REGS_1
{
	UCHAR   Channel;
	ULONG	TempR2;
	ULONG	R1;
	ULONG   R2;
	ULONG   R3;
	ULONG   R4;
}	RTMP_RF_REGS_1, *PRTMP_RF_REGS_1;

//
//  Macros for flag and ref count operations
//
#define RTMP_SET_FLAG(_M, _F)       ((_M)->Flags |= (_F))
#define RTMP_CLEAR_FLAG(_M, _F)     ((_M)->Flags &= ~(_F))
#define RTMP_CLEAR_FLAGS(_M)        ((_M)->Flags = 0)
#define RTMP_TEST_FLAG(_M, _F)      (((_M)->Flags & (_F)) != 0)
#define RTMP_TEST_FLAGS(_M, _F)     (((_M)->Flags & (_F)) == (_F))

#define RTMP_INC_REF(_A)            NdisInterlockedIncrement(&(_A)->RefCount)
#define RTMP_DEC_REF(_A)            NdisInterlockedDecrement(&(_A)->RefCount); ASSERT(_A->RefCount >= 0)
#define RTMP_GET_REF(_A)            ((_A)->RefCount)

#define RTMP_INC_RCV_REF(_A)        ((_A)->RcvRefCount++)
#define RTMP_DEC_RCV_REF(_A)        ((_A)->RcvRefCount--)
#define RTMP_GET_RCV_REF(_A)        ((_A)->RcvRefCount)

#define RTMP_INC_SEND_REF(_A)       ((_A)->SendRefCount++)
#define RTMP_DEC_SEND_REF(_A)       ((_A)->SendRefCount--)
#define RTMP_GET_SEND_REF(_A)       ((_A)->SendRefCount)

#define RTMP_OFFSET(field)          ((UINT)FIELD_OFFSET(RTMP_ADAPTER, field))
#define RTMP_SIZE(field)            sizeof(((PRT2570ADAPTER)0)->field)
#define PORT_OFFSET(field)          ((UINT)FIELD_OFFSET(PORT_CONFIG, field))
#define PORT_SIZE(field)            sizeof(((PPORT_CONFIG)0)->field)

//blue,#define RTMP_IO_READ32(_A, _R, _pV) RTUSBReadMACRegister((_A), (_R), (_pV))
//blue,#define RTMP_IO_WRITE32(_A, _R, _V) RTUSBReadMACRegister((_A), (_R), (_V))
//
//  Statistic counter structure
//
//mandatory counters from general and Ethernet statistics objects
typedef struct _COUNTER_802_3
{
    // General Stats
	ULONG		GoodTransmits;
	ULONG		GoodReceives;
	ULONG		TxErrors;
	ULONG		RxErrors;
	ULONG		RxNoBuffer;

    // Ethernet Stats
	ULONG		RcvAlignmentErrors;
	ULONG		OneCollision;
	ULONG		MoreCollisions;

}   COUNTER_802_3, *PCOUNTER_802_3;
//OID_802_11_STATISTICS
typedef struct _COUNTER_802_11 {
    ULONG           Length;
    LARGE_INTEGER   TransmittedFragmentCount;
    LARGE_INTEGER   MulticastTransmittedFrameCount;
    LARGE_INTEGER   FailedCount;
    LARGE_INTEGER   NoRetryCount;
    LARGE_INTEGER   RetryCount;
    LARGE_INTEGER   MultipleRetryCount;
    LARGE_INTEGER   RTSSuccessCount;
    LARGE_INTEGER   RTSFailureCount;
    LARGE_INTEGER   ACKFailureCount;
    LARGE_INTEGER   FrameDuplicateCount;
    LARGE_INTEGER   ReceivedFragmentCount;
    LARGE_INTEGER   MulticastReceivedFrameCount;
    LARGE_INTEGER   FCSErrorCount;
} COUNTER_802_11, *PCOUNTER_802_11;
//proprietary counters
typedef struct _COUNTER_RALINK {
    ULONG           TransmittedByteCount;   // both successful and failure, used to calculate TX throughput
    ULONG           ReceivedByteCount;      // both CRC okay and CRC error, used to calculate RX throughput
    ULONG           BeenDisassociatedCount;
    ULONG           BadCQIAutoRecoveryCount;
    ULONG           PoorCQIRoamingCount;
    ULONG           MgmtRingFullCount;
    ULONG           RxCount;
    ULONG           DecryptCount;
    ULONG           RxRingErrCount;
    ULONG           EncryptCount;
    ULONG           KickTxCount;
    ULONG           TxRingErrCount;	
} COUNTER_RALINK, *PCOUNTER_RALINK;

typedef struct _COUNTER_DRS {
    USHORT          TxQuality[MAX_LEN_OF_SUPPORTED_RATES];
    UCHAR           PER[MAX_LEN_OF_SUPPORTED_RATES];
    UCHAR           TxRateUpPenalty;      // extra # of second penalty due to last unstable condition
    ULONG           CurrTxRateStableTime; // # of second in current TX rate
    BOOLEAN         fNoisyEnvironment;
    UCHAR           LastSecTxRateChangeAction; // 0: no change, 1:rate UP, 2:rate down
} COUNTER_DRS, *PCOUNTER_DRS;

typedef struct _COUNTER_QA {
	LARGE_INTEGER   CRCErrorCount;
	LARGE_INTEGER   RXOverFlowCount;
	LARGE_INTEGER   PHYErrorCount;
	LARGE_INTEGER   FalseCCACount;
	LARGE_INTEGER   U2MDataCount;
	LARGE_INTEGER   OtherDataCount;
	LARGE_INTEGER   BeaconCount;
	LARGE_INTEGER   othersCount;	
} COUNTER_QA, *PCOUNTER_QA;


//
//  Arcfour Structure Added by PaulWu
//
typedef struct  _ARCFOUR
{
	UINT			X;
	UINT			Y;
	UCHAR			STATE[256];
}   ARCFOURCONTEXT, *PARCFOURCONTEXT;

// Shared key data structure
typedef	struct	_WEP_KEY {
	UCHAR	KeyLen;						// Key length for each key, 0: entry is invalid
	UCHAR	Key[MAX_LEN_OF_KEY];		// right now we implement 4 keys, 128 bits max
}	WEP_KEY, *PWEP_KEY;

// Shared key data structure
typedef	struct	_WPA_KEY {
	UCHAR	KeyLen;				// Key length for each key, 0: entry is invalid
	UCHAR	Key[16];			// right now we implement 4 keys, 128 bits max
	UCHAR	RxMic[8];
	UCHAR	TxMic[8];
	NDIS_802_11_MAC_ADDRESS	BssId;	// For pairwise key only
	UCHAR	TxTsc[6];			// 48bit TSC value
	UCHAR	RxTsc[6];			// 48bit TSC value
	UCHAR	Type;				// Indicate Pairwise / Group
}	WPA_KEY, *PWPA_KEY;

// configuration to be used when this STA starts a new ADHOC network
typedef struct _IBSS_CONFIG {
    USHORT    BeaconPeriod;
    USHORT    AtimWin;
    UCHAR     Channel;
    UCHAR     SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];    // Supported rates
    UCHAR     SupportedRatesLen;
}   IBSS_CONFIG, *PIBSS_CONFIG;

typedef struct _LED_CONTROL {
    BOOLEAN     fOdd;
    BOOLEAN     fRxActivity;
    BOOLEAN     fSiteSurvey;
    BOOLEAN     fLinkUp;
     RALINK_TIMER_STRUCT BlinkTimer; // 50 ms periodic timer
//    ULONG       LastLedCsr;
    USHORT       LastLedCsr;
} LED_CONTROL;


typedef struct _BBP_TUNING_STRUCT {
    BOOLEAN     Enable;
    UCHAR       FalseCcaCountUpperBound;  // 100 per sec
    UCHAR       FalseCcaCountLowerBound;  // 10 per sec
    UCHAR       R17LowerBound;            // specified in E2PROM
    UCHAR       R17UpperBound;            // 0x68 according to David Tung
    UCHAR       CurrentR17Value;
} BBP_TUNING, *PBBP_TUNING;

typedef struct _SOFT_RX_ANT_DIVERSITY_STRUCT {
    BOOLEAN   PrimaryInUsed;
    UCHAR     PrimaryRxAnt;     // 0:Ant-A, 1:Ant-B
    UCHAR     SecondaryRxAnt;   // 0:Ant-A, 1:Ant-B
    USHORT    AvgRssi[2];       // AvgRssi[0]:Ant-A, AvgRssi[1]:Ant-B
     RALINK_TIMER_STRUCT    RxAntDiversityTimer;
} SOFT_RX_ANT_DIVERSITY, *PSOFT_RX_ANT_DIVERSITY;



// PortConfig
typedef struct _PORT_CONFIG {

    // MIB:ieee802dot11.dot11smt(1).dot11StationConfigTable(1)
    USHORT    CapabilityInfo;
    USHORT    Psm;                  // power management mode   (PWR_ACTIVE|PWR_SAVE)
    USHORT    BeaconPeriod;         // in units of TU

    USHORT    CfpMaxDuration;
    USHORT    CfpDurRemain;
    USHORT    CfpCount;
    USHORT    CfpPeriod;

    USHORT    DisassocReason;
    MACADDR   DisassocSta;
    USHORT    DeauthReason;
    MACADDR   DeauthSta;
    USHORT    AuthFailReason;
    MACADDR   AuthFailSta;

	NDIS_802_11_AUTHENTICATION_MODE		AuthMode;//set by OID_802_11_AUTHENTICATION_MODE. This should match to whatever microsoft defined
	NDIS_802_11_WEP_STATUS				WepStatus;//set by OID_802_11_WEP_STATUS
	NDIS_802_11_WEP_STATUS				OrigWepStatus;	// Original wep status set from OID

	// Add to support different cipher suite for WPA2/WPA mode
	NDIS_802_11_ENCRYPTION_STATUS		GroupCipher;		// Multicast cipher suite
	NDIS_802_11_ENCRYPTION_STATUS		PairCipher;			// Unicast cipher suite
    BOOLEAN								bMixCipher;			// Indicate current Pair & Group use different cipher suites
    USHORT								RsnCapability;
    
#if 1  
    // MIB:ieee802dot11.dot11smt(1).dot11WEPDefaultKeysTable(3)
    WEP_KEY	  SharedKey[SHARE_KEY_NO];//set by OID_802_11_ADD_KEY or OID_802_11_ADD_WEP. Keep for backward compatiable
	WPA_KEY   PairwiseKey[PAIRWISE_KEY_NO];//set by OID_802_11_ADD_KEY
	WPA_KEY   GroupKey[GROUP_KEY_NO];//set by OID_802_11_ADD_KEY
	WPA_KEY   PskKey;                   // WPA PSK mode PMK
	BSSID_INFO	SavedPMK[PMKID_NO];
	ULONG		SavedPMKNum;			// Saved PMKID number
    UCHAR     PTK[64];
#endif
	// WPA 802.1x port control, WPA_802_1X_PORT_SECURED, WPA_802_1X_PORT_NOT_SECURED
	UCHAR     PortSecured;

	// For WPA countermeasures
	ULONG		LastMicErrorTime;	// record last MIC error time
	ULONG		MicErrCnt;			// Should be 0, 1, 2, then reset to zero (after disassoiciation).
	BOOLEAN		bBlockAssoc;		// Block associate attempt for 60 seconds after counter measure occurred.

	// For WPA-PSK supplicant state,red, add for WPA-PSK
      WPA_STATE   WpaState;           // Default is SS_NOTUSE and handled by microsoft 802.1x
      UCHAR       ReplayCounter[8];
      UCHAR       ANonce[32];         // ANonce for WPA-PSK from aurhenticator
      UCHAR       SNonce[32];         // SNonce for WPA-PSK

    // MIB:ieee802dot11.dot11smt(1).dot11WEPKeyMappingsTable(4)
    // not implemented yet

    // MIB:ieee802dot11.dot11smt(1).dot11PrivacyTable(5)
    UCHAR     DefaultKeyId;//set by OID_802_11_ADD_KEY or OID_802_11_ADD_WEP
	NDIS_802_11_PRIVACY_FILTER	PrivacyFilter;		// PrivacyFilter enum for 802.1X

    // MIB:ieee802dot11.dot11mac(2).dot11OperationTable(1)
    USHORT    RtsThreshold;       // in units of BYTE
    USHORT    FragmentThreshold;
    BOOLEAN   bFragmentZeroDisable;		// Microsoft use 0 as disable 
    
    // MIB:ieee802dot11.dot11phy(4).dot11PhyAntennaTable(2)
    UCHAR     CurrentTxAntenna;
    UCHAR     CurrentRxAntenna;
    UCHAR     NumberOfAntenna;

    // MIB:ieee802dot11.dot11phy(4).dot11PhyTxPowerTable(3)
    UCHAR     CurrentTxPowerLevelIndex; //default&other value=MaxPower,1=MinPower,2=1*MaxPower/4,3=2*MaxPower/4,4=3*MaxPower/4,
    UCHAR     TxPower;
    UCHAR     TxRate;       // RATE_1, RATE_2, RATE_5_5, RATE_11, ...
    BOOLEAN   EnableAutoRateSwitching;  // 1 - enable auto rate switching; 0 - disable
    ULONG     TxPowerPercentage;        // 0~100 %,blue
    
    // MIB:ieee802dot11.dot11phy(4).dot11PhyDSSSTable(5)
    UCHAR     Channel;        // current (I)BSS channel used in the station
    UCHAR     CountryRegion;	// Enum of country region, 0:FCC, 1:IC, 2:ETSI, 3:SPAIN, 4:France, 5:MKK, 6:MKK1, 7:Israel
    
    // MIB:ieee802dot11.dot11phy(4).dot11AntennasListTable(8)
    BOOLEAN AntennaSupportTx;
    BOOLEAN AntennaSupportRx;
    BOOLEAN AntennaSupportDiversityRx;

	// Use user changed MAC
    BOOLEAN bLocalAdminMAC;                           
    
    // MIB:ieee802dot11.dot11phy(4).dot11SupportedDataRatesTxTable(9)
    // MIB:ieee802dot11.dot11phy(4).dot11SupportedDataRatesRxTable(10)
    UCHAR     SupportedRates[MAX_LEN_OF_SUPPORTED_RATES];    // Supported rates
    UCHAR     SupportedRatesLen;
    UCHAR     ExpectedACKRate[MAX_LEN_OF_SUPPORTED_RATES];

    //blue
    // Copy supported rate from desired AP's beacon. We are trying to match
	// AP's supported and extended rate settings.
	UCHAR		SupRate[MAX_LEN_OF_SUPPORTED_RATES];
	UCHAR		ExtRate[MAX_LEN_OF_SUPPORTED_RATES];
	UCHAR		SupRateLen;
	UCHAR		ExtRateLen;

    //
    // other parameters not defined in standard MIB
    //
    UCHAR     DesiredRates[MAX_LEN_OF_SUPPORTED_RATES];      // OID_802_11_DESIRED_RATES
    UCHAR     MaxDesiredRate;
    USHORT    RecvDtim;
    MACADDR   Bssid;
    MACADDR   Broadcast;            // FF:FF:FF:FF:FF:FF
    USHORT    Pss;                  // current power saving status (PWR_SAVE|PWR_ACTIVE)
    UCHAR     RssiTrigger;
    UCHAR     RssiTriggerMode;      // RSSI_TRIGGERED_UPON_BELOW_THRESHOLD or RSSI_TRIGGERED_UPON_EXCCEED_THRESHOLD
    UCHAR     LastRssi;             // last received BEACON's RSSI
    USHORT    AvgRssi;              // last 8 BEACON's average RSSI,blue
    USHORT    AtimWin;              // in kusec; IBSS parameter set element
    USHORT    Aid;                  // association ID
    UCHAR     RtsRate;              // RATE_xxx
    UCHAR     MlmeRate;               // RATE_xxx, used to send MLME frames
    UCHAR     MaxTxRate;            // RATE_xxx
    USHORT    DefaultListenCount;   // default listen count;
    UCHAR     BssType;              // BSS_INFRA or BSS_INDEP

    UCHAR     SsidLen;               // the actual ssid length in used
    CHAR      Ssid[MAX_LEN_OF_SSID]; // NOT NULL-terminated

    BSS_TABLE BssTab;     // BSS Table

    // global variables mXXXX used in MAC protocol state machines
    BOOLEAN   Mibss;
    BOOLEAN   Massoc;
    BOOLEAN   Mauth;

    // RFMON logic flags
    BOOLEAN   MallowRFMONTx;

    // PHY specification
    UCHAR     PhyMode;    // PHY_11A, PHY_11B, PHY_11BG_MIXED, PHY_ABG_MIXED
    USHORT    Dsifs;      // in units of usec

    ULONG     WindowsPowerMode;			// Power mode for AC power
    //ULONG     WindowsBatteryPowerMode;	// Power mode for battery if exists
    //BOOLEAN   WindowsACCAMEnable;		// Enable CAM power mode when AC on
    ULONG     PacketFilter;				// Packet filter for receiving
    BOOLEAN   AutoReconnect;			// Set to TRUE when setting OID_802_11_SSID with no matching BSSID
#ifdef NDIS51_MINIPORT   
    ULONG     WindowsPowerProfile;	// Windows power profile, for NDIS5.1 PnP
#endif
    ULONG     WindowsTxPreamble; // Rt802_11PreambleLong, Rt802_11PreambleShort, Rt802_11PreambleAuto

	UCHAR	  ChannelTxPower[MAX_LEN_OF_CHANNELS];		// Store Tx power value for all channels.

	//blue
	UCHAR	  ChannelTssiRef[MAX_LEN_OF_CHANNELS];		// Store Tssi Reference value for all channels.
	UCHAR	  ChannelTssiDelta;							// Store Tx TSSI delta increment / decrement value
	BOOLEAN   bAutoTxAgc;
	
	UCHAR     ChannelList[MAX_LEN_OF_CHANNELS];         // list all supported channels for site survey
	UCHAR     ChannelListNum;                           // number of channel in ChannelList[]
	BOOLEAN   bShowHiddenSSID;//blue
	
    // configuration to be used when this STA starts a new ADHOC network
    IBSS_CONFIG IbssConfig;

    ULONG     LastBeaconRxTime;     // OS's timestamp of the last BEACON RX time
    atomic_t     DataPacketsFromAP;     // # of data packets received from AP since we receive last Beacon from AP
    ULONG     Last11bBeaconRxTime;  // OS's timestamp of the last 11B BEACON RX time
    ULONG     LastScanTime;		// Record last scan time for issue BSSID_SCAN_LIST
    ULONG     IgnoredScanNumber;	// Ignored BSSID_SCAN_LIST requests
    BOOLEAN	  bSwRadio;			// Software controlled Radio On/Off, TRUE: On
    BOOLEAN	  bHwRadio;			// Hardware controlled Radio On/Off, TRUE: On
    BOOLEAN	  bRadio;			// Radio state, And of Sw & Hw radio state
    BOOLEAN   bHardwareRadio;	// Hardware-controlled Radio enabled

    LED_CONTROL             LedCntl;
    UCHAR                   RfType;
    UCHAR                   LedMode;
    
	// New for WPA, windows want us to to keep association information and
	// Fixed IEs from last association response
	NDIS_802_11_ASSOCIATION_INFORMATION		AssocInfo;
//	NDIS_802_11_FIXED_IEs					FixIEs;
	UCHAR					ReqVarIELen;				// Length of next VIE include EID & Length
	UCHAR					ReqVarIEs[MAX_VIE_LEN];
	UCHAR					ResVarIELen;				// Length of next VIE include EID & Length
	UCHAR					ResVarIEs[MAX_VIE_LEN];

    // the following fields are user setting from UI
    ULONG     EnableTurboRate;      // 0: disable, 1: enable 72/100 Mbps whenever applicable
    ULONG     EnableTxBurst;        // 0: disable, 1: enable TX PACKET BURST
    ULONG     UseBGProtection;      // 0: auto, 1: always use, 2: always not use
    ULONG     UseShortSlotTime;     // 0: disable, 1: enable 9us short slot time if AP supports
    //blue,ULONG     UseOfdmRatesIn11gAdhoc; // 0:WIFI mode (11b rates only), 1:allow OFDM rates
    ULONG     AdhocMode; 			// 0:WIFI mode (11b rates only), 1: b/g mixed, 2: 11g only,blue

    // this flag is the result calculated from UI settings and AP's ERP/Capability
    ULONG     BGProtectionInUsed;   // 0: not in-used, 1: in-used
    ULONG     ShortSlotInUsed;      // 0: not in-used, 1: in-used
    USHORT    TxPreambleInUsed;     // Rt802_11PreambleLong, Rt802_11PreambleShort
	UCHAR		CipherAlg;

    // latch th latest RF programming value here since RF IC doesn't support READ operation
    RTMP_RF_REGS    LatchRfRegs;

    //blue
    BOOLEAN                       BbpTuningEnable;
    UCHAR                         VgcLowerBound;
    RT_802_11_RX_AGC_VGC_TUNING   BbpTuning;
    UCHAR                         LastR17Value;

    ULONG                         SystemErrorBitmap;  // b0: E2PROM version error

    //blue
    UCHAR                   BbpWriteLatch[100];   // record last BBP register value written via BBP_IO_WRITE
    ULONG                   CurrTxRateStableTime; // # of second in current TX rate
    UCHAR                   TxRateUpPenalty;      // extra # of second penalty due to last unstable condition

    // For WPA-PSK supplicant state
    //red,WPA_STATE   WpaState;           // Default is SS_NOTUSE and handled by microsoft 802.1x
	
    
} PORT_CONFIG, *PPORT_CONFIG;

typedef struct _MLME_MEMORY_STRUCT {
    PVOID                           AllocVa;    //Pointer to the base virtual address of the allocated memory
    struct _MLME_MEMORY_STRUCT      *Next;      //Pointer to the next virtual address of the allocated memory
} MLME_MEMORY_STRUCT, *PMLME_MEMORY_STRUCT;

typedef struct  _MLME_MEMORY_HANDLER {
    BOOLEAN                 MemRunning;         //The flag of the Mlme memory handler's status
    UINT                    MemoryCount;        //Total nonpaged system-space memory not size
    UINT                    InUseCount;         //Nonpaged system-space memory in used counts
    UINT                    UnUseCount;         //Nonpaged system-space memory available counts
    UINT                    PendingCount;       //Nonpaged system-space memory for free counts
    PMLME_MEMORY_STRUCT     pInUseHead;         //Pointer to the first nonpaed memory not used
    PMLME_MEMORY_STRUCT     pInUseTail;         //Pointer to the last nonpaged memory not used
    PMLME_MEMORY_STRUCT     pUnUseHead;         //Pointer to the first nonpaged memory in used
    PMLME_MEMORY_STRUCT     pUnUseTail;         //Pointer to the last nonpaged memory in used
    PULONG                  MemFreePending[MAX_MLME_HANDLER_MEMORY];   //an array to keep pending free-memory's pointer (32bits)
} MLME_MEMORY_HANDLER, *PMLME_MEMORY_HANDLER;

typedef struct _MLME_STRUCT {
    STATE_MACHINE           CntlMachine, AssocMachine, AuthMachine, AuthRspMachine, SyncMachine,WpaPskMachine;
    STATE_MACHINE_FUNC      CntlFunc[CNTL_FUNC_SIZE], AssocFunc[ASSOC_FUNC_SIZE];
    STATE_MACHINE_FUNC      AuthFunc[AUTH_FUNC_SIZE], AuthRspFunc[AUTH_RSP_FUNC_SIZE];
    STATE_MACHINE_FUNC      SyncFunc[SYNC_FUNC_SIZE],WpaPskFunc[WPA_PSK_FUNC_SIZE];
    
    ASSOC_AUX               AssocAux;
    AUTH_AUX                AuthAux;
    AUTH_RSP_AUX            AuthRspAux;
    SYNC_AUX                SyncAux;
    CNTL_AUX                CntlAux;
    
    COUNTER_802_11          PrevWlanCounters;
    ULONG                   ChannelQuality;  // 0..100, Channel Quality Indication for Roaming

    BOOLEAN                 Running;
    spinlock_t          TaskLock;
    MLME_QUEUE              Queue;

    UINT                    ShiftReg;
//    PSPOLL_FRAME            PsFr;
//    MACHDR                  NullFr;
    
    RALINK_TIMER_STRUCT	PeriodicTimer;
    ULONG                   PeriodicRound;
    ULONG                   PrevTxCnt;

    MLME_MEMORY_HANDLER     MemHandler;         //The handler of the nonpaged memory inside MLME

} MLME_STRUCT, *PMLME_STRUCT;

//
// Management ring buffer format
//
typedef	struct	_MGMT_STRUC	{
	BOOLEAN		Valid;
	PUCHAR		pBuffer;
	ULONG		Length;
	UCHAR		FirstIndex;
	UCHAR		ContextsRequired;
	struct	_MGMT_STRUC *next;//blue
}	MGMT_STRUC, *PMGMT_STRUC;

//
// P802.11 Frame control field, 16 bit
//
typedef	struct	_FRAME_CONTROL	{
	USHORT		Ver:2;				// Protocol version
	USHORT		Type:2;				// MSDU type
	USHORT		Subtype:4;			// MSDU subtype
	USHORT		ToDs:1;				// To DS indication
	USHORT		FrDs:1;				// From DS indication
	USHORT		MoreFrag:1;			// More fragment bit
	USHORT		Retry:1;			// Retry status bit
	USHORT		PwrMgt:1;			// Power management bit
	USHORT		MoreData:1;			// More data bit
	USHORT		Wep:1;				// Wep data
	USHORT		Order:1;			// Strict order expected
}	FRAME_CONTROL, *PFRAME_CONTROL;

//
// P802.11 intermediate header format
//
typedef	struct	_CONTROL_HEADER	{
	FRAME_CONTROL	Frame;				// Frame control structure
	USHORT			Duration;			// Duration value
	MACADDR			Addr1;				// Address 1 field
	MACADDR			Addr2;				// Address 2 field
}	CONTROL_HEADER, *PCONTROL_HEADER;

typedef	struct	_PS_POLL_BUFFER	{
    TXD_STRUC		TxDesc;
	PSPOLL_FRAME	PsPollPacket;
}	PS_POLL_BUFFER, *PPS_POLL_BUFFER;

//
// P802.11 header format
//
typedef	struct	_HEADER_802_11	{
	CONTROL_HEADER	Controlhead;
	MACADDR			Addr3;				// Address 3 field
	USHORT			Frag:4;				// Fragment number
	USHORT			Sequence:12;		// Sequence number
}	HEADER_802_11, *PHEADER_802_11;

typedef	struct	_NULL_FRAME_BUFFER	{
    TXD_STRUC		TxDesc;
	HEADER_802_11	NullFrame;
}	NULL_FRAME_BUFFER, *PNULL_FRAME_BUFFER;

typedef	struct	_WPAPSK_BUFFER	{
    TXD_STRUC		TxDesc;
	UCHAR	WpaPskFrame[512];
}	WPAPSK_BUFFER, *PWPAPSK_BUFFER;



typedef	struct	_STUFF_BUFFER	{
	NULL_FRAME_BUFFER	NullFrameBuffer;
    UCHAR	StuffBuffer[512];
}	STUFF_BUFFER, *PSTUFF_BUFFER;

//
// Receive Tuple Cache Format
//
typedef	struct	_TUPLE_CACHE	{
	BOOLEAN			Valid;
	MACADDR			MAC;
	USHORT			Sequence; 
	USHORT			Frag;
}	TUPLE_CACHE, *PTUPLE_CACHE;

//
// Fragment Frame structure
//
typedef	struct	_FRAGMENT_FRAME	{
	UCHAR		Header802_3[14];
	UCHAR		Header_LLC[8];
	UCHAR		Buffer[MAX_FRAME_SIZE];
	ULONG		RxSize;
	USHORT		Sequence;
	USHORT		LastFrag;
	ULONG		Flags;			// Some extra frame information. bit 0: LLC presented
}	FRAGMENT_FRAME, *PFRAGMENT_FRAME;

//
// Packet information for NdisQueryPacket
//
typedef	struct	_PACKET_INFO	{
	UINT			PhysicalBufferCount;	// Physical breaks of buffer descripor chained
	UINT			BufferCount ;			// Number of Buffer descriptor chained
	UINT			TotalPacketLength ;  	// Self explained
	//PNDIS_BUFFER	pFirstBuffer;			// Pointer to first buffer descriptor
}	PACKET_INFO, *PPACKET_INFO;

//
// Tkip Key structure which RC4 key & MIC calculation
//
typedef	struct	_TKIP_KEY_INFO	{
	UINT		nBytesInM;	// # bytes in M for MICKEY
	ULONG		IV16;
	ULONG		IV32;	
	ULONG		K0;			// for MICKEY Low
	ULONG		K1;			// for MICKEY Hig
	ULONG		L;			// Current state for MICKEY
	ULONG		R;			// Current state for MICKEY
	ULONG		M;			// Message accumulator for MICKEY
	UCHAR		RC4KEY[16];
	UCHAR		MIC[8];
}	TKIP_KEY_INFO, *PTKIP_KEY_INFO;

//
// Private / Misc data, counters for driver internal use
//
typedef	struct	__PRIVATE_STRUC	{
	ULONG		SystemResetCnt;			// System reset counter
	ULONG		ResetCountDown;			// Count down before issue reset, patch for RT2430
//	ULONG		CCAErrCnt;				// CCA error count, for debug purpose, might move to global counter
	ULONG		PhyRxErrCnt;			// PHY Rx error count, for debug purpose, might move to global counter
	ULONG		PhyTxErrCnt;			// PHY Tx error count, for debug purpose, might move to global counter
	// Variables for WEP encryption / decryption in rtmp_wep.c
	ULONG			FCSCRC32;
	ULONG			RxSetCnt;
	ULONG			DecryptCnt;
	ARCFOURCONTEXT	WEPCONTEXT;
	// Tkip stuff
	TKIP_KEY_INFO	Tx;
	TKIP_KEY_INFO	Rx;
}	PRIVATE_STRUC, *PPRIVATE_STRUC;



/////////////////
//Vendor Commands
/////////////////
#define COMMAND_QUEUE_SIZE  11

typedef	struct _CmdQElmt	{
	UINT				command;
	PVOID				buffer;
	ULONG				bufferlength;
	BOOLEAN				CmdFromNdis;
	BOOLEAN				SetOperation;
	BOOLEAN				InUse;//blue
	struct _CmdQElmt	*next;
}	CmdQElmt, *PCmdQElmt;

typedef	struct	_CmdQ	{
	UINT		size;
	CmdQElmt	*head;
	CmdQElmt	*tail;
}	CmdQ, *PCmdQ;

typedef enum _BULK_OUT_TYPE {
    DATA,
    MLME,
	BEACON,
	PS_POLL,
    ALL
} BULK_OUT_TYPE;

#if 0
typedef	struct _BULK_OUT_QUEUE_ELEMENT	{
	BULK_OUT_TYPE			BulkOutType;
	PVOID				buffer;
	struct _BULK_OUT_QUEUE_ELEMENT	*next;
}	BULK_OUT_QUEUE_ELEMENT, *PBULK_OUT_QUEUE_ELEMENT;

typedef	struct	_BULK_OUT_QUEUE	{
	UINT		size;
	BULK_OUT_QUEUE_ELEMENT	*head;
	BULK_OUT_QUEUE_ELEMENT	*tail;
}	BULK_OUT_QUEUE, *PBULK_OUT_QUEUE;

typedef	struct _BULK_OUT_QUEUE_ELEMENT	{
	PVOID				buffer;
	struct _BULK_OUT_QUEUE_ELEMENT	*next;
}	BULK_OUT_QUEUE_ELEMENT, *PBULK_OUT_QUEUE_ELEMENT;

typedef	struct	_BULK_OUT_QUEUE	{
	UINT		size;
	BULK_OUT_QUEUE_ELEMENT	*head;
	BULK_OUT_QUEUE_ELEMENT	*tail;
}	BULK_OUT_QUEUE, *PBULK_OUT_QUEUE;
#endif

//blue
typedef	struct	_DATA_BULKOUT_QUEUE	{
	UINT		size;
	struct sk_buff 	*head;
	struct sk_buff	*tail;
}	DATA_BULKOUT_QUEUE, *PDATA_BULKOUT_QUEUE;

typedef	struct	_MLME_BULKOUT_QUEUE	{
	UINT		size;
	PMGMT_STRUC	head;
	PMGMT_STRUC	tail;
}	MLME_BULKOUT_QUEUE, *PMLME_BULKOUT_QUEUE;

#if 0
typedef enum bufferStates {
    FREE,
    USED,
	COMPLETED,
    PENDING
} BufferState;
#endif

// used to track driver-generated write irps 
typedef struct _TX_CONTEXT
{

	PVOID				pAdapter;//Initialized in MiniportInitialize
	//    struct sk_buff *skb;
	PURB				pUrb;//Initialized in MiniportInitialize
	PIRP	            pIrp;//used to cancel pending bulk out.//Initialized in MiniportInitialize
	PTX_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
	ULONG			BulkOutSize;
	BOOLEAN				InUse;
	BOOLEAN				IRPPending;
	BOOLEAN				LastOne;
}
TX_CONTEXT, *PTX_CONTEXT, **PPTX_CONTEXT;

// used to track driver-generated write irps 
typedef struct _MLME_CONTEXT
{
    PVOID				pAdapter;//Initialized in MiniportInitialize
    PMGMT_STRUC			pMgmt;
    PURB				pUrb;//Initialized in MiniportInitialize
    PIRP	            pIrp;//used to cancel pending bulk out.//Initialized in MiniportInitialize
    PTX_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
//    UINT	            TransferBufferLength;//TransferBufferLength
//    CONTEXT_TYPE    Type;
//    BufferState	            fInUse; // Declared as ULONG so can use with InterlockedExchange()
	BOOLEAN				InUse;
	BOOLEAN				IRPPending;
	BOOLEAN				LastOne;
	UCHAR				Index;
}
MLME_CONTEXT, *PMLME_CONTEXT, **PPMLME_CONTEXT;


typedef struct _NULL_CONTEXT
{
    PVOID				pAdapter;//Initialized in MiniportInitialize
    PURB				pUrb;//Initialized in MiniportInitialize
    PIRP	            pIrp;//used to cancel pending bulk out.
    PNULL_FRAME_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
//    UINT	            TransferBufferLength;//TransferBufferLength
//    BufferState	            fInUse; // Declared as ULONG so can use with InterlockedExchange()
	BOOLEAN				InUse;
	BOOLEAN				IRPPending;
}
NULL_CONTEXT, *PNULL_CONTEXT;


typedef struct _WPAPSK_CONTEXT
{
    PVOID				pAdapter;//Initialized in MiniportInitialize
    PURB				pUrb;//Initialized in MiniportInitialize
    PIRP	            pIrp;//used to cancel pending bulk out.
    PWPAPSK_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
//    UINT	            TransferBufferLength;//TransferBufferLength
//    BufferState	            fInUse; // Declared as ULONG so can use with InterlockedExchange()
	BOOLEAN				InUse;
	BOOLEAN				Ready;
	BOOLEAN				IRPPending;
}
WPAPSK_CONTEXT, *PWPAPSK_CONTEXT;

typedef struct _PS_POLL_CONTEXT
{
    PVOID				pAdapter;//Initialized in MiniportInitialize
    PURB				pUrb;//Initialized in MiniportInitialize
    PIRP	            pIrp;//used to cancel pending bulk out.
    PPS_POLL_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
//    UINT	            TransferBufferLength;//TransferBufferLength
//    BufferState	            fInUse; // Declared as ULONG so can use with InterlockedExchange()
	BOOLEAN				InUse;
	BOOLEAN				Ready;
	BOOLEAN				IRPPending;
}
PS_POLL_CONTEXT, *PPS_POLL_CONTEXT;

typedef struct _STUFF_CONTEXT
{
    PVOID				pAdapter;//Initialized in MiniportInitialize
    PURB				pUrb;//Initialized in MiniportInitialize
    PIRP	            pIrp;//used to cancel pending bulk out.
    PSTUFF_BUFFER          TransferBuffer;//Initialized in MiniportInitialize
//    UINT	            TransferBufferLength;//TransferBufferLength
//    BufferState	            fInUse; // Declared as ULONG so can use with InterlockedExchange()
	BOOLEAN				InUse;
	BOOLEAN				Ready;
	BOOLEAN				IRPPending;
}
STUFF_CONTEXT, *PSTUFF_CONTEXT;

//
// Structure to keep track of receive packets and buffers to indicate
// receive data to the protocol.
//
#define   IRPLOCK_COMPLETED     0
#define   IRPLOCK_CANCELABLE    1
#define   IRPLOCK_CANCE_START   2
#define   IRPLOCK_CANCE_COMPLETE    3

typedef struct _RX_CONTEXT
{
	PVOID				pAdapter;
	PIRP					pIrp; //used to cancel pending bulk in.
	PURB				pUrb;
	BOOLEAN				InUse;
	atomic_t				IrpLock;
	PUCHAR				TransferBuffer; 
}
RX_CONTEXT, *PRX_CONTEXT;
#if 0
// NDIS
typedef struct _RX_CONTEXT
{
    PUCHAR				TransferBuffer; 
    PVOID				pAdapter;
    PIRP				pIrp;//used to cancel pending bulk in.
    PURB				pUrb;
	BOOLEAN				InUse;
	IRPLOCK				IrpLock;
}	RX_CONTEXT, *PRX_CONTEXT;
#endif
typedef struct _VENDOR_REQUEST_URB
{
    PURB				pUrb;
//    BOOLEAN	            InUse;
    PIRP				pIrp;//used to cancel pending IRP
	BOOLEAN				IRPPending;
}
VENDOR_REQUEST_URB;


typedef struct _TX_RATE_SWITCHING_STRUC
{
	ULONG			LastStableTime;
	UCHAR			DownRate1Ratio;
	UCHAR			DownRate2Ratio;
	UCHAR			UpRateRatio;
	UCHAR			StableTimeRequired;
	UCHAR			PenaltyPeriod;
	UCHAR			DownWaitingTime;
}
TX_RATE_SWITCHING_STRUC, *PTX_RATE_SWITCHING_STRUC;

typedef struct _TX_RATE_SWITCHING_COUNTERS
{
	USHORT			NoRetryOKCnt;
	USHORT			OneRetryOKCnt;
	USHORT			MRetryOKCnt;
	USHORT			FailCnt;
}
TX_RATE_SWITCHING_COUNTERS, *PTX_RATE_SWITCHING_COUNTERS;

typedef struct _BBP_TUNING_PARAMETERS_STRUC
{
	UCHAR			BBPTuningThreshold;
	UCHAR			R24LowerValue;
	UCHAR			R24HigherValue;
	UCHAR			R25LowerValue;
	UCHAR			R25HigherValue;
	UCHAR			R61LowerValue;
	UCHAR			R61HigherValue;
	UCHAR			BBPR17LowSensitivity;
	UCHAR			BBPR17MidSensitivity;
	UCHAR			RSSIToDbmOffset;
	BOOLEAN			LargeCurrentRSSI;
}
BBP_TUNING_PARAMETERS_STRUC, *PBBP_TUNING_PARAMETERS_STRUC;

#define	IEEE80211_NWID_LEN			32


#define UNLINK_TIMEOUT_MS		3
//
//  The miniport adapter structure
//
typedef struct _RT2570_ADAPTER
{
	int			nicknamelen;
	char nickn[IEEE80211_NWID_LEN+1]; // nickname, only used in the iwconfig i/f 
	struct tasklet_struct	rx_bh;		
	struct usb_device *usb;
	//KERNEL266
	struct usb_config_descriptor *config;
	//struct usb_host_config *config;
	devctrlrequest *devreq;
	/* The device we're working with
	 * It's important to note:
	 *    (o) you must hold dev_semaphore to change pusb_dev
	 */
	struct semaphore	usbdev_semaphore;	 /* protect  usb */
	// Thread
	struct semaphore	mlme_semaphore;	 /* to sleep thread on   */
	struct semaphore	RTUSBCmd_semaphore;	 /* to sleep thread on   */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0)
		struct completion	notify;		/* thread begin/end */
		pid_t			MLMEThr_pid;
		pid_t			RTUSBCmdThr_pid;
#else
	struct task_struct *	MLMEThr;
	volatile int MLMEThr_active;
	struct task_struct *	RTUSBCmdThr;
	volatile int RTUSBCmdThr_active;
#endif
	wait_queue_head_t	*wait;
	
	spinlock_t *lock;
#if 1
	UINT					SET_R17_FLAG;
	UCHAR					BBPR17InitValue;
	UCHAR					ResetRequest;
	UCHAR					BulkAction;
#endif

	struct net_device *net;
	BOOLEAN                 bNetDeviceStopQueue;

#if WIRELESS_EXT >= 12
    struct iw_statistics iw_stats;
#endif
	
	struct net_device_stats netstats;

	// configuration
	UCHAR                   PermanentAddress[ETH_LENGTH_OF_ADDRESS];    // Factory default MAC address
	UCHAR                   CurrentAddress[ETH_LENGTH_OF_ADDRESS];      // User changed MAC address

	USHORT			EEPROMDefaultValue[NUM_EEPROM_BBP_PARMS];
	USHORT			EEPROMBBPTuningParameters[NUM_EEPROM_BBP_TUNING_PARMS];

    //
    // Handle given by NDIS when the Adapter registered itself.
    // Various NDIS handle function
    //

	MGMT_STRUC				MgmtRing[MGMT_RING_SIZE];	// management ring size
	
	UCHAR					NextTxIndex;					// Next TxD write pointer
	UCHAR					NextMLMEIndex;				// Next PrioD write pointer
	UCHAR					PushMgmtIndex;				// Next SW management ring index
	UCHAR					PopMgmtIndex;				// Next SW management ring index
	atomic_t					MgmtQueueSize;				// Number of Mgmt request stored in MgmtRing
	UCHAR					NextRxBulkInIndex;
	UCHAR					NextBulkOutIndex;
	BOOLEAN					BulkOutPending;
	BOOLEAN					ControlPending;
	ULONG					PrioRingTxCnt;
	UCHAR					PrioRingFirstIndex;

 	// 802.3 multicast support
	ULONG					NumberOfMcAddresses;		// Number of mcast entry exists
	UCHAR					McastTable[MAX_MCAST_LIST_SIZE][ETH_LENGTH_OF_ADDRESS];		// Mcast list
	ULONG                   Flags;                      // Represent current device status

	// Flags for bulk out data priority
	ULONG					BulkFlags;
	/////////////////////
	// Transmit Path
	/////////////////////
	atomic_t								TxCount;		// Number of Bulkout waiting to be send.
	TX_CONTEXT							TxContext[TX_RING_SIZE];
	TX_CONTEXT							MLMEContext[PRIO_RING_SIZE];
	TX_CONTEXT							BeaconContext[BEACON_RING_SIZE];
	TX_CONTEXT							NullContext;
	TX_CONTEXT							PsPollContext;
	RTS_BUFFER							RTSBuffer;

	WPAPSK_CONTEXT					       WpaPskContext;
	PUCHAR								TxBuffer;
	TX_BUFFER                           TxMgmtBuf;

	/////////////////////
	// Receive Path
	/////////////////////
	RX_CONTEXT							RxContext[RX_RING_SIZE];
	PURB                                pRxUrb;//red: test mode only
	PIRP                                pRxIrp;
	PUCHAR								RxBuffer;
    // SEND queue list
	struct sk_buff_head            SendTxWaitQueue;

	USHORT					Sequence;					// Current sequence number

	TUPLE_CACHE				TupleCache[MAX_CLIENT];		// Maximum number of tuple caches, only useful in Ad-Hoc
	UCHAR                   TupleCacheLastUpdateIndex;  // 0..MAX_CLIENT-1
	FRAGMENT_FRAME			FragFrame;					// Frame storage for fragment frame
	
	// For MiniportTransferData
	PUCHAR					pRxData;					// Pointer to current RxRing offset / fragment frame offset
	
	// Counters for 802.3 & generic.
	// Add 802.11 specific counters later
	COUNTER_802_3           Counters;                   // 802.3 counters
	COUNTER_802_11          WlanCounters;				// 802.11 MIB counters
	COUNTER_RALINK          RalinkCounters;				// Ralink propriety counters
	COUNTER_DRS             DrsCounters;                // counters for Dynamic Rate Switching
	COUNTER_QA				QACounters;				// Ralink propriety counters

	NDIS_MEDIA_STATE        MediaState;
	UCHAR                               StationState;

	NDIS_DEVICE_POWER_STATE CurrentPowerState;          // Current device power state
	NDIS_DEVICE_POWER_STATE NextPowerState;             // Next device power state

	PRIVATE_STRUC			PrivateInfo;				// Private information & counters

	// SpinLocks
	spinlock_t			SendTxWaitQueueLock;		// SendTxWaitQueue spinlock
	spinlock_t			MLMEWaitQueueLock;		// SendTxWaitQueue spinlock
	spinlock_t			CmdQLock;		// SendTxWaitQueue spinlock
	spinlock_t			BulkOutLock;		// SendTxWaitQueue spinlock
	spinlock_t			ControlLock;		// SendTxWaitQueue spinlock
	spinlock_t			MLMEQLock;		// SendTxWaitQueue spinlock
	spinlock_t			GenericLock;		// SendTxWaitQueue spinlock
	spinlock_t                  MemLock;            // need to check

	// Reference count
	LONG                    RefCount;           // Keep adapter refer count for checkforhang & halt
	ULONG                   SendRefCount;       // number of packet that have not been confirmed
	ULONG                   RcvRefCount;        // number of packets that have not been returned back

	// Various NDIS Event
	int              ExitEvent;
	

	NDIS_MEDIA_STATE                    LinkIsActive;
	ULONG                               CurrentLookAhead;
	CmdQ								CmdQ;
	DATA_BULKOUT_QUEUE								DataQ;
	MLME_BULKOUT_QUEUE								MLMEQ;

	// Boolean control for packet filter
	BOOLEAN					bAcceptDirect;
	BOOLEAN					bAcceptMulticast;
	BOOLEAN					bAcceptBroadcast;
	BOOLEAN					bAcceptAllMulticast;

	// Control to check Tx hang
	BOOLEAN					bTxBusy;
	
	// Control disconnect / connect event generation
	ULONG					LinkDownTime;
	UCHAR					LastSsidLen;               // the actual ssid length in used
	CHAR					LastSsid[MAX_LEN_OF_SSID]; // NOT NULL-terminated
	MACADDR					LastBssid;
	BOOLEAN					bConfigChanged;				// Config Change flag for the same SSID setting
	
	PORT_CONFIG             PortCfg;
	MLME_STRUCT             Mlme;
	/////////////////////
	// USB
	/////////////////////
	USHORT                              BulkOutMaxPacketSize;   // 64 in XP
	USHORT                              BulkInMaxPacketSize;

	/////////////////////
	//  Control Flags
	/////////////////////
	LONG                                PendingTx;
	atomic_t                                PendingRx;
	LONG                                PendingReset;
	LONG                                BulkOutFailed;
	LONG                                BulkInFailed;
	LONG                                DeviceFailed;
	UCHAR                               DeviceMode;
	BOOLEAN                             UnplugDevice;
	atomic_t                                TerminateThreads;
	atomic_t                                PendingIoCount;
	BOOLEAN                             BSSSelected;
	BOOLEAN                             StationWasAssociated;
	BOOLEAN                             StationIsAssociated;
	BOOLEAN                             StationIsAuthenticated;
	UCHAR                               WepLevel;
	BOOLEAN                             OutOfRangeDetected;
	BOOLEAN                             AddressOverrided;
	BOOLEAN                             AutoAuthentication;
	BOOLEAN                             AutoPreamble;
	BOOLEAN                             AutoJoin;
	BOOLEAN                             UseInternalFWImage;
	BOOLEAN                             AnyAP;
	
	PVOID								pInformationBuffer;
	ULONG								InformationBufferLength;
	PULONG								pBytesWritten;
	PULONG								pBytesNeeded;
	BOOLEAN								SendDelimitingPacket;
	ULONG								DelimitingPacketSent;
	UINT								FragmentsSent;
	USHORT								BulkOutLength;
	USHORT								BulkOutRemained;
	BOOLEAN								ContinBulkOut;
	USHORT								BulkInRemained;
	BOOLEAN								ContinBulkIn;
	BOOLEAN								BeaconIntervalChangeAllowed;
	USHORT								SentBeaconsCount;
	USHORT								ReceivedBeaconsCount;
	LARGE_INTEGER						TransmittedFragmentCount;
#ifdef TEST_MODE_SUPPORT
	CmdQElmt							CmdQElements[12];
#else
	CmdQElmt							CmdQElements[COMMAND_QUEUE_SIZE];
#endif

	USHORT								MACCounters[11];
	TX_RATE_SWITCHING_STRUC			TxRateSwitchingStruc[12];
	ULONG			CurrRateGoodTime;
	UCHAR			CurrRateBadTime;
	UCHAR			TxQuality;
	BBP_TUNING_PARAMETERS_STRUC			BBPTuningParameters;
	ULONG					LastRxRate;
	ULONG					PacketsSentBetweenTBTTs;
	BOOLEAN					ScanAllowed;
	// Alpha can't link up problem
	ULONG					ExtraInfo;				// Extra information for displaying status
	struct net_device_stats	net_device_stats;	/* interface statistics */
	
}   RT2570ADAPTER, *PRT2570ADAPTER;



#endif






////////////////////////////////////////////////////////////////////////////
//
//  inline FUNCTIONS
//
//   IncrementIoCount and DecrementIoCount
//
//  DESCRIPTION
//
//   We keep a pending IO count. This count is initialized to one.
//   Subsequently, the count is incremented for each new IRP received or
//   created and is decremented when each IRP is completed.
//   Transition to 'one' therefore indicates no IO is pending and signals
//   Adapter->RemoveEvent. Transition to 'zero' signals an event
//   (Adapter->RemoveEvent) to enable device removal.
//
//  INPUT
//
//    Adapter                       Ptr to the adapter object
//
//  OUTPUT
//
//    -
//
////////////////////////////////////////////////////////////////////////////
inline VOID IncrementIoCount(PRT2570ADAPTER Adapter);
inline VOID DecrementIoCount(IN PRT2570ADAPTER pAdapter);



////////////////////////////////////////////////////////////////////////////
// __inline VOID EnQTxPacket(PRT2570ADAPTER Adapter, PNDIS_PACKET Packet)
// {
//     PTX_QUEUE tempTxQnode;
//
//
//     if (AllocateMemory(&tempTxQnode, sizeof(TX_QUEUE))!=NDIS_STATUS_SUCCESS)
//     {
//         NdisMSendComplete(Adapter->AdapterHandle, Packet, NDIS_STATUS_SUCCESS);
//         return;
//     }
//
//     tempTxQnode->pNdisPacket = Packet;
//     tempTxQnode->next = NULL;
//
//     if (Adapter->TxQHead==NULL)
//     {
//         Adapter->TxQHead = tempTxQnode;
//     }
//
//     if (Adapter->TxQTail!=NULL)
//     {
//         Adapter->TxQTail->next = tempTxQnode;
//     }
//
//     Adapter->TxQTail = tempTxQnode;
// }



////////////////////////////////////////////////////////////////////////////
// __inline VOID DeQTxPacket(PRT2570ADAPTER Adapter)
// {
//     PTX_QUEUE tempTxQnode;
//
//     tempTxQnode = Adapter->TxQHead;
//     Adapter->TxQHead = tempTxQnode->next;
//
//     if (Adapter->TxQHead==NULL)
//     {
//         Adapter->TxQTail=NULL;
//     }
//
//     FreeMemory(tempTxQnode, sizeof(TX_QUEUE));
// }



#define DEVICE_VENDOR_REQUEST_OUT       (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE) // 0x40
#define DEVICE_VENDOR_REQUEST_IN        (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE )  //0xc0
#define INTERFACE_VENDOR_REQUEST_OUT    0x41
#define INTERFACE_VENDOR_REQUEST_IN     0xc1
#define	PL_RESET_IN	(1<<3)		/* reset input pipe */

////////////////////////////////////////////////////////////////////////////
// Misc definitions
////////////////////////////////////////////////////////////////////////////
#define OS_IS_WIN_2000              0   
#define OS_IS_WIN_ME                1
#define OS_IS_WIN_98                2
#define OS_IS_WIN_XP                3


////////////////////////////////////////////////////////////////////////////
// Station States definitions
////////////////////////////////////////////////////////////////////////////
#define STATION_STATE_INITIALIZING          0x00
#define STATION_STATE_SCANNING              0x01
#define STATION_STATE_JOINNING              0x02
#define STATION_STATE_AUTHENTICATING        0x03
#define STATION_STATE_ASSOCIATING           0x04
#define STATION_STATE_READY                 0x05
#define STATION_STATE_OUT_OF_RANGE          0x06
#define STATION_STATE_DISASSOCIATING        0x07
#define STATION_STATE_DIAUTHENTICATING      0x08
#define STATION_STATE_REASSOCIATING         0x09
#define STATION_STATE_FORCED_JOINNING       0x0a
#define STATION_STATE_RECONFIGURING         0x0b
#define STATION_STATE_FW_UPGRADE            0x0c
#define STATION_STATE_FORCED_JOIN_FAILURE   0x0d 
#define STATION_STATE_RESETTING             0x0e 
#define STATION_STATE_RESET_PENDING         0x0f 
#define STATION_STATE_NOT_NET_MODE          0x10
#define STATION_STATE_WAIT_ACTION           0x11 //under XP we need this state to allow XP to take control
#define STATION_STATE_REJECTING_PACKETS     0x99 
#define STATION_STATE_NO_CARD               0xf0 
#define STATION_STATE_MGMT_ERROR            0xf1 
#define STATION_STATE_GENERAL_ERROR         0xf2 
#define STATION_STATE_POWER_DOWN            0xff


////////////////////////////////////////////////////////////////////////////
// SCAN Type Definitions
////////////////////////////////////////////////////////////////////////////
#define SCAN_TYPE_ACTIVE                    0
#define SCAN_TYPE_PASSIVE                   1


////////////////////////////////////////////////////////////////////////////
// Operating Modes definitions
////////////////////////////////////////////////////////////////////////////
#define BSS_TYPE_AD_HOC                     1
#define BSS_TYPE_INFRASTRUCTURE             2

//
//  Miniport routines in rtmp_main.c
//


VOID	RTUSBHalt(	IN	PRT2570ADAPTER	pAdapter, BOOLEAN IsFree);


//
//  Private routines in rtmp_init.c
//

PUCHAR  RTMPFindSection(
    IN  PCHAR   buffer,
    IN  PCHAR   section);

INT RTMPIsFindSection(
    IN  PUCHAR  ptr,
    IN  PUCHAR  buffer);


INT RTMPGetKeyParameter(
    IN  PUCHAR  section,
    IN  PCHAR   key,
    OUT PCHAR   dest,   
    IN  INT     destsize,
    IN  PCHAR   buffer);
VOID RTMPReadParametersFromFile(
	IN	PRT2570ADAPTER pAdapter);



VOID	NICReadEEPROMParameters(
    IN  PRT2570ADAPTER       pAdapter);

VOID	NICInitAsicFromEEPROM(
	IN  PRT2570ADAPTER       pAdapter);


NDIS_STATUS NICInitRecv(
    IN  PRT2570ADAPTER   pAdapter);

#if 0
NDIS_STATUS	NICReadAdapterInfo(
	IN	PRT2570ADAPTER		pAdapter);


VOID	NICInitializeAdapter(
    IN  PRT2570ADAPTER   pAdapter);
#endif//blue

VOID	RT2570InitializeAsic(
	IN	PRT2570ADAPTER	pAdapter);

VOID	NICIssueReset(
	IN	PRT2570ADAPTER	pAdapter);

#if 0
VOID	RTMPRingCleanUp(
	IN	PRT2570ADAPTER	pAdapter,
	IN	UCHAR			RingType);
#endif

VOID	RxTest(
	IN	PRT2570ADAPTER	pAdapter);

//
#if 0
NDIS_STATUS	DbgSendPacket(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PNDIS_PACKET	pPacket);
#endif

VOID	PortCfgInit(
	IN	PRT2570ADAPTER	pAdapter);

VOID	NICResetFromError(
	IN	PRT2570ADAPTER	pAdapter);

BOOLEAN	NICCheckForHang(
	IN	PRT2570ADAPTER	pAdapter);

VOID CreateThreads( struct net_device *net_dev);

#if 0
NDIS_STATUS	RT2570ReadHWMACAddress(
	IN	PRT2570ADAPTER		pAdapter);
#endif
NDIS_STATUS	RTUSBWriteHWMACAddress(
	IN	PRT2570ADAPTER		pAdapter);

void AtoH(char * src, UCHAR * dest, int destlen);
UCHAR BtoH(char ch);

VOID	RTMPInitTimer(
	IN	PRT2570ADAPTER			pAdapter,
	IN	PRALINK_TIMER_STRUCT	pTimer,
	IN	PVOID					pTimerFunc);

VOID	RTMPSetTimer(
	IN	PRT2570ADAPTER			pAdapter,	
	IN	PRALINK_TIMER_STRUCT	pTimer,
	IN	ULONG					Value);

VOID	RTMPCancelTimer(
	IN	PRALINK_TIMER_STRUCT	pTimer);


//
// Private routines in rtmp_data.c
//
#if 0
VOID	RTMPHandleRxDoneInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHandleTxRingTxDoneInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHandlePrioRingTxDoneInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHandleAtimRingTxDoneInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHandleTbcnInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHandleTwakeupInterrupt(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPHardTransmitDone(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PTXD_STRUC		pTxD,
	IN	UCHAR			FrameType);

NDIS_STATUS	RTMPSendPacket(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PNDIS_PACKET	pPacket);
	
VOID	RTMPDeQueuePacket(
    IN	PRT2570ADAPTER	pAdapter,
    IN	PQUEUE_HEADER	pQueue);

NDIS_STATUS	RTMPHardTransmit(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PNDIS_PACKET	pPacket,
	IN	UCHAR			NumberRequired);

NDIS_STATUS	RTMPFreeDescriptorRequest(
	IN		PRT2570ADAPTER	pAdapter,
	IN		UCHAR			RingType,
	IN		UCHAR			NumberRequired);
#endif//red


VOID	MlmeHardTransmit(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PMGMT_STRUC		pMgmt);

VOID
BulkOutMLMEPacket
(
 PRT2570ADAPTER	pAdapter,
 UCHAR	Index);


void BulkOutMLMEPacketComplete(purbb_t purb,struct pt_regs *pt_regs);

USHORT	RTMPCalcDuration(
	IN	PRT2570ADAPTER	pAdapter,
	IN	UCHAR			Rate,
	IN	ULONG			Size);


VOID	RTMPWriteBeaconDescriptor(
	IN	PTXD_STRUC	pTxD,
	IN	UINT		Length,
	IN	UINT		PLCPLength,
	IN	UINT		Rate,
	IN	UCHAR		Service,
	IN  USHORT      TxPreamble);


VOID    RTUSBSuspendMsduTransmission(
   	IN	PRT2570ADAPTER	pAdapter);

VOID    RTUSBResumeMsduTransmission(
   	IN	PRT2570ADAPTER	pAdapter);

VOID
DequeueMLMEPacket(
	IN	PRT2570ADAPTER	pAdapter);


VOID
MiniportMMRequest(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PVOID			pBuffer,
	IN	ULONG			Length);

BOOLEAN	RTMPSearchTupleCache(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PHEADER_802_11	pHeader);

VOID	RTMPUpdateTupleCache(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PHEADER_802_11	pHeader);

NDIS_STATUS	RTMPApplyPacketFilter(
	IN	PRT2570ADAPTER	pAdapter, 
	IN	PRXD_STRUC		pRxD, 
	IN	PHEADER_802_11	pHeader);

NDIS_STATUS	RTMPCheckRxDescriptor(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PRXD_STRUC	pRxD);

VOID	RTMPReportMicError(
	IN	PRT2570ADAPTER	pAdapter, 
	IN	PWPA_KEY		pWpaKey);

VOID	RTUSBMlmeHardTransmit(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PMGMT_STRUC		pMgmt);


//
// Private routines in rtmp_wep.c
//
VOID	RTMPInitWepEngine(
	IN	PRT2570ADAPTER	pAdapter,	
	IN	PUCHAR			pKey,
	IN	UCHAR			KeyId,
	IN	UCHAR			KeyLen, 
	IN	PUCHAR			pDest);

VOID	RTMPEncryptData(
	IN	PRT2570ADAPTER	pAdapter,	
	IN	PUCHAR			pSrc,
	IN	PUCHAR			pDest,
	IN	UINT			Len);

BOOLEAN	RTMPDecryptData(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PUCHAR	pSrc,
	IN	UINT	Len);

VOID	RTMPSetICV(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PUCHAR			pDest);

VOID	ARCFOUR_INIT(
	IN	PARCFOURCONTEXT	Ctx,
	IN	PUCHAR			pKey,
	IN	UINT			KeyLen);

UCHAR	ARCFOUR_BYTE(
	IN	PARCFOURCONTEXT		Ctx);

VOID	ARCFOUR_DECRYPT(
	IN	PARCFOURCONTEXT	Ctx,
	IN	PUCHAR			pDest, 
	IN	PUCHAR			pSrc,
	IN	UINT			Len);

VOID	ARCFOUR_ENCRYPT(
	IN	PARCFOURCONTEXT	Ctx,
	IN	PUCHAR			pDest,
	IN	PUCHAR			pSrc,
	IN	UINT			Len);

ULONG	RTMP_CALC_FCS32(
	IN	ULONG	Fcs,
	IN	PUCHAR	Cp,
	IN	INT		Len);

//
// MLME routines
//
//VOID    Arc4Init(ARC4_CONTEXT *Ctx, UCHAR *Key, ULONG KeyLen);
//UCHAR   Arc4Byte(ARC4_CONTEXT *Ctx);
//VOID    Arc4Cipher(ARC4_CONTEXT *Ctx, UCHAR *Dest, UCHAR *Src, ULONG Len);

// Asic/RF/BBP related functions

VOID AsicAdjustTxPower(
    IN PRT2570ADAPTER pAd);
    
VOID    AsicSwitchChannel(
    IN	PRT2570ADAPTER	pAdapter, 
    UCHAR Channel);

VOID    AsicLockChannel(
    IN PRT2570ADAPTER pAd, 
    IN ULONG Channel) ;

#if 0
VOID AsicRfTuningExec(
    IN PVOID SystemSpecific1, 
    IN PVOID FunctionContext, 
    IN PVOID SystemSpecific2, 
    IN PVOID SystemSpecific3);
#endif

#ifdef RALINK_ATE
VOID    AsicSwitchChannel_ATE(
    IN	PRT2570ADAPTER	pAdapter, 
    ULONG Channel);
#endif

VOID    AsicSleepThenAutoWakeup(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  USHORT TbttNumToNextWakeUp);

VOID    AsicForceSleep(
    IN PRT2570ADAPTER pAdapter);

VOID    AsicForceWakeup(
    IN PRT2570ADAPTER pAdapter);

VOID    AsicSetBssid(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MACADDR *Bssid);

VOID    AsicDisableSync(
    IN	PRT2570ADAPTER	pAdapter);

VOID    AsicEnableBssSync(
    IN	PRT2570ADAPTER	pAdapter);

VOID    AsicEnableIbssSync(
    IN	PRT2570ADAPTER	pAdapter);

VOID    AsicLedPeriodicExec(
    IN unsigned long data);

VOID AsicSetSlotTime(
    IN PRT2570ADAPTER pAd,
    IN BOOLEAN UseShortSlotTime);

//blue
VOID AsicBbpTuning(
    IN PRT2570ADAPTER pAd);

VOID AsicRestoreBbpSensibility(
    IN PRT2570ADAPTER pAd);


VOID    MacAddrRandomBssid(
    IN	PRT2570ADAPTER	pAdapter, 
    OUT PMACADDR Addr);

VOID    MgtMacHeaderInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN OUT PMACHDR Hdr, 
    IN UCHAR Subtype, 
    IN UCHAR ToDs, 
//  IN UCHAR AddrType, 
    IN PMACADDR Ds, 
    IN PMACADDR Bssid);

VOID MlmeRadioOff(
    IN PRT2570ADAPTER pAd);

VOID MlmeRadioOn(
    IN PRT2570ADAPTER pAd);

VOID  BssTableInit(
    IN BSS_TABLE *Tab);

ULONG BssTableSearch(
    IN BSS_TABLE *Tab, 
    IN PMACADDR Bssid);

VOID BssTableDeleteEntry(
    IN OUT	BSS_TABLE *Tab, 
    IN		PMACADDR Bssid);

VOID  BssEntrySet(
    IN	PRT2570ADAPTER	pAdapter, 
    OUT BSS_ENTRY *Bss, 
    IN MACADDR *Bssid, 
    IN CHAR Ssid[], 
    IN UCHAR SsidLen, 
    IN UCHAR BssType, 
    IN USHORT BeaconPeriod,
    IN BOOLEAN CfExist, 
    IN CF_PARM *CfParm, 
    IN USHORT AtimWin, 
    IN USHORT CapabilityInfo, 
    IN UCHAR Rates[], 
    IN UCHAR RatesLen,
    IN BOOLEAN ExtendedRateIeExist,
    IN UCHAR Channel,
    IN UCHAR Rssi,
    IN LARGE_INTEGER TimeStamp,
    IN UCHAR LengthVIE,
    IN PNDIS_802_11_VARIABLE_IEs pVIE);

ULONG  BssTableSetEntry(
    IN	PRT2570ADAPTER	pAdapter, 
    OUT BSS_TABLE *Tab, 
    IN MACADDR *Bssid, 
    IN CHAR Ssid[], 
    IN UCHAR SsidLen, 
    IN UCHAR BssType, 
    IN USHORT BeaconPeriod, 
    IN BOOLEAN CfExist, 
    IN CF_PARM *CfParm, 
    IN USHORT AtimWin, 
    IN USHORT CapabilityInfo, 
    IN UCHAR Rates[], 
    IN UCHAR RatesLen,
    IN BOOLEAN ExtendedRateIeExist,
    IN UCHAR Channel,
    IN UCHAR Rssi,
    IN LARGE_INTEGER TimeStamp,
    IN UCHAR LengthVIE,
    IN PNDIS_802_11_VARIABLE_IEs pVIE);

VOID  BssTableSsidSort(
    IN	PRT2570ADAPTER	pAd, 
    OUT BSS_TABLE *OutTab, 
    IN  CHAR Ssid[], 
    IN  UCHAR SsidLen);

VOID  BssTableSortByRssi(
    IN OUT BSS_TABLE *OutTab);

VOID	BssCipherParse(
	IN OUT	PBSS_ENTRY	pBss);

NDIS_STATUS  MlmeQueueInit(
    IN MLME_QUEUE *Queue);

VOID  MlmeQueueDestroy(
    IN MLME_QUEUE *Queue);

BOOLEAN MlmeEnqueue(
    IN PRT2570ADAPTER pAd, 
	IN ULONG Machine, 
    IN ULONG MsgType, 
    IN ULONG MsgLen, 
    IN VOID *Msg);

BOOLEAN MlmeEnqueueForRecv(
    IN	PRT2570ADAPTER	pAdapter, 
    OUT MLME_QUEUE *Queue, 
    IN UCHAR Rssi, 
    IN ULONG MsgLen, 
    IN PVOID Msg);

BOOLEAN MlmeDequeue(
    IN MLME_QUEUE *Queue, 
    OUT MLME_QUEUE_ELEM **Elem);

#if 1
VOID	MlmeRestartStateMachine(
    IN	PRT2570ADAPTER	pAd);
#endif

//blue
VOID	MlmePostRestartStateMachine(
    IN	PRT2570ADAPTER	pAd);

BOOLEAN  MlmeQueueEmpty(
    IN MLME_QUEUE *Queue);

BOOLEAN  MlmeQueueFull(
    IN MLME_QUEUE *Queue);

BOOLEAN  MsgTypeSubst(
	IN PRT2570ADAPTER pAd,
    IN MACFRAME *Fr, 
    OUT INT *Machine, 
    OUT INT *MsgType);

VOID StateMachineInit(
    IN STATE_MACHINE *Sm, 
    IN STATE_MACHINE_FUNC Trans[], 
    IN ULONG StNr, 
    IN ULONG MsgNr, 
    IN STATE_MACHINE_FUNC DefFunc, 
    IN ULONG InitState, 
    IN ULONG Base);

VOID StateMachineSetAction(
    IN STATE_MACHINE *S, 
    IN ULONG St, 
    ULONG Msg, 
    IN STATE_MACHINE_FUNC F);

VOID StateMachinePerformAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN STATE_MACHINE *S, 
    IN MLME_QUEUE_ELEM *Elem);

VOID Drop(
    IN	PRT2570ADAPTER	pAdapter, 
    IN MLME_QUEUE_ELEM *Elem);

VOID StateMachineDestroy(
    IN STATE_MACHINE *Sm);

VOID  AssocStateMachineInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  STATE_MACHINE *Sm, 
    OUT STATE_MACHINE_FUNC Trans[]);

VOID  ReassocTimeout(
    IN	unsigned long data);

VOID  AssocTimeout(
    IN	unsigned long data);

VOID  DisassocTimeout(
    IN	unsigned long data);

//----------------------------------------------
VOID  MlmeDisassocReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  MlmeAssocReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  MlmeReassocReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  MlmeDisassocReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  PeerAssocRspAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  PeerReassocRspAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  PeerDisassocAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  DisassocTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  AssocTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  ReassocTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  Cls3errAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  PMACADDR pAddr);

VOID  InvalidStateWhenAssoc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  InvalidStateWhenReassoc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID InvalidStateWhenDisassociate(
    IN  PRT2570ADAPTER pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID  ComposePsPoll(
    IN	PRT2570ADAPTER	pAdapter);

VOID  ComposeNullFrame(
    IN  PRT2570ADAPTER pAdapter);

VOID  ComposeStuffFrame(
    IN  PRT2570ADAPTER pAdapter);

VOID  AssocPostProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MACADDR *Addr2, 
    IN  USHORT CapabilityInfo, 
    IN  USHORT Aid, 
    IN  UCHAR Rates[], 
    IN  UCHAR RatesLen,
    IN  BOOLEAN ExtendedRateIeExist);

VOID AuthStateMachineInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN PSTATE_MACHINE sm, 
    OUT STATE_MACHINE_FUNC Trans[]);

VOID AuthTimeout(
    IN	unsigned long data);


VOID MlmeAuthReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerAuthRspAtSeq2Action(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerAuthRspAtSeq4Action(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID AuthTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID Cls2errAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  PMACADDR pAddr);

VOID MlmeDeauthReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID InvalidStateWhenAuth(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

//VOID MlmeDeauthReqProc(
//    IN	PRT2570ADAPTER	pAdapter, 
//    IN  MACADDR *Addr, 
//    IN  USHORT Reason);

//=============================================

VOID AuthRspStateMachineInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  PSTATE_MACHINE Sm, 
    IN  STATE_MACHINE_FUNC Trans[]);


VOID AuthRspChallengeTimeout(
    IN	unsigned long data);

VOID AuthRspChallengeTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerAuthAtAuthRspIdleAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerAuthAtAuthRspWaitAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerDeauthAction(
    IN PRT2570ADAPTER pAdaptor, 
    IN MLME_QUEUE_ELEM *Elem);

VOID PeerAuthSimpleRspGenAndSend(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  PMACHDR Hdr, 
    IN  USHORT Alg, 
    IN  USHORT Seq, 
    IN  USHORT Reason, 
    IN  USHORT Status);

//========================================

VOID SyncStateMachineInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  STATE_MACHINE *Sm, 
    OUT STATE_MACHINE_FUNC Trans[]);

VOID BeaconTimeout(
    IN	unsigned long data);

VOID AtimTimeout(
    IN	unsigned long data); 

VOID ScanTimeout(
    IN	unsigned long data);

VOID MlmeScanReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID InvalidStateWhenScan(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID InvalidStateWhenJoin(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID InvalidStateWhenStart(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerBeacon(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

//=========================================

VOID MlmeCntlInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  STATE_MACHINE *S, 
    OUT STATE_MACHINE_FUNC Trans[]);

VOID MlmeCntlMachinePerformAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  STATE_MACHINE *S, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlIdleProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlOidScanProc(
    IN  PRT2570ADAPTER pAdapter,
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlOidSsidProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM * Elem);

VOID CntlOidRTBssidProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM * Elem);

VOID CntlMlmeRoamingProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM * Elem);

VOID CntlWaitDisassocProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitJoinProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitReassocProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitStartProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitAuthProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitAuthProc2(
    IN  PRT2570ADAPTER pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID CntlWaitAssocProc(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID LinkUp(
    IN	PRT2570ADAPTER	pAdapter,
    IN  UCHAR BssType);

VOID LinkDown(
    IN	PRT2570ADAPTER	pAdapter);

VOID MlmeCntlConfirm(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  ULONG MsgType, 
    IN  USHORT Msg);

VOID IterateOnBssTab(
    IN	PRT2570ADAPTER	pAdapter);

VOID IterateOnBssTab2(
    IN  PRT2570ADAPTER   pAdapter);;

VOID JoinParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  OUT MLME_JOIN_REQ_STRUCT *JoinReq, 
    IN  ULONG BssIdx);

VOID AssocParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN OUT MLME_ASSOC_REQ_STRUCT *AssocReq, 
    IN  MACADDR *Addr, 
    IN  USHORT CapabilityInfo, 
    IN  ULONG Timeout, 
    IN  USHORT ListenIntv);

VOID ScanParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  OUT MLME_SCAN_REQ_STRUCT *ScanReq, 
    IN  CHAR Ssid[], 
    IN  UCHAR SsidLen, 
    IN  UCHAR BssType, 
    IN  UCHAR ScanType); 

VOID DisassocParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  OUT MLME_DISASSOC_REQ_STRUCT *DisassocReq, 
    IN  MACADDR *Addr, 
    IN  USHORT Reason);

VOID StartParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  OUT MLME_START_REQ_STRUCT *StartReq, 
    IN  CHAR Ssid[], 
    IN  UCHAR SsidLen);

VOID AuthParmFill(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  OUT MLME_AUTH_REQ_STRUCT *AuthReq, 
    IN  MACADDR *Addr, 
    IN  USHORT Alg);

VOID EnqueuePsPoll(
    IN	PRT2570ADAPTER	pAdapter);

VOID EnqueueBeaconFrame(
    IN  PRT2570ADAPTER   pAdapter); 

void USB_SendNullFrameComplete(purbb_t purb,struct pt_regs *pt_regs);

VOID EnqueueNullFrame(
    IN  PRT2570ADAPTER pAdapter,
    IN  UCHAR         TxRate);

VOID MlmeJoinReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);



VOID MlmeStartReqAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID ScanTimeoutAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID BeaconTimeoutAtJoinAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerBeaconAtScanAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerBeaconAtJoinAction(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerBeacon(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID PeerProbeReqAction(
    IN  PRT2570ADAPTER pAd, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID ScanNextChannel(
    IN	PRT2570ADAPTER	pAdapter);

VOID MakeIbssBeacon(
    IN	PRT2570ADAPTER	pAdapter);

BOOLEAN MlmeScanReqSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT UCHAR *BssType, 
    OUT CHAR ssid[], 
    OUT UCHAR *SsidLen, 
    OUT UCHAR *ScanType);

BOOLEAN PeerBeaconAndProbeRspSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr2, 
    OUT MACADDR *Bssid, 
    OUT CHAR Ssid[], 
    OUT UCHAR *SsidLen, 
    OUT UCHAR *BssType, 
    OUT USHORT *BeaconPeriod, 
    OUT UCHAR *Channel, 
    OUT LARGE_INTEGER *Timestamp, 
    OUT BOOLEAN *CfExist, 
    OUT CF_PARM *Cf, 
    OUT USHORT *AtimWin, 
    OUT USHORT *CapabilityInfo, 
    OUT UCHAR Rate[], 
    OUT UCHAR *RateLen,
    OUT BOOLEAN *ExtendedRateIeExist,
    OUT UCHAR *Erp,
    OUT UCHAR *DtimCount, 
    OUT UCHAR *DtimPeriod, 
    OUT UCHAR *BcastFlag, 
    OUT UCHAR *MessageToMe, 
    OUT UCHAR *Legacy,
    OUT UCHAR SupRate[],
    OUT UCHAR *SupRateLen,
    OUT UCHAR ExtRate[],
    OUT UCHAR *ExtRateLen,
    OUT UCHAR *LengthVIE,
    OUT	PNDIS_802_11_VARIABLE_IEs pVIE);

//BOOLEAN JoinParmSanity(
//    IN	PRT2570ADAPTER	pAdapter, 
//    IN  VOID *Msg, 
//    IN  ULONG MsgLen, 
//    OUT ULONG *BssIdx,
//    OUT UCHAR SupportedRates[], 
//    OUT UCHAR *SupportedRatesLen);

BOOLEAN MlmeAssocReqSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *ApAddr, 
    OUT USHORT *CapabilityInfo, 
    OUT ULONG *Timeout, 
    OUT USHORT *ListenIntv);

BOOLEAN MlmeAuthReqSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr, 
    OUT ULONG *Timeout, 
    OUT USHORT *Alg);

BOOLEAN MlmeStartReqSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT CHAR Ssid[], 
    OUT UCHAR *Ssidlen);

BOOLEAN PeerAuthSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr, 
    OUT USHORT *Alg, 
    OUT USHORT *Seq, 
    OUT USHORT *Status, 
    OUT CHAR ChlgText[]);

BOOLEAN PeerAssocRspSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr2, 
    OUT USHORT *CapabilityInfo, 
    OUT USHORT *Status, 
    OUT USHORT *Aid, 
    OUT UCHAR Rates[], 
    OUT UCHAR *RatesLen,
    OUT BOOLEAN *ExtendedRateIeExist);

BOOLEAN PeerDisassocSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr2, 
    OUT USHORT *Reason);

BOOLEAN PeerDeauthSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr2, 
    OUT USHORT *Reason);

BOOLEAN PeerProbeReqSanity(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  VOID *Msg, 
    IN  ULONG MsgLen, 
    OUT MACADDR *Addr2,
    OUT CHAR Ssid[], 
    OUT UCHAR *SsidLen); 
//    OUT UCHAR Rates[], 
//    OUT UCHAR *RatesLen);
NDIS_STATUS	RTMPWPAWepKeySanity(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PVOID			pBuf);

BOOLEAN GetTimBit(
    IN  CHAR *Ptr, 
    IN  USHORT Aid, 
    OUT UCHAR *TimLen, 
    OUT UCHAR *BcastFlag, 
    OUT UCHAR *DtimCount, 
    OUT UCHAR *DtimPeriod, 
    OUT UCHAR *MessageToMe);

BOOLEAN GetLegacy(
    IN  CHAR *Ptr, 
    OUT UCHAR *Legacy);

ULONG MakeOutgoingFrame(
    OUT CHAR *Buffer, 
    OUT ULONG *Length, ...);

VOID  LfsrInit(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  ULONG Seed);

UCHAR RandomByte(
    IN	PRT2570ADAPTER	pAdapter);

VOID  MlmePeriodicExec(
    IN	unsigned long data);

#if 1
VOID  RxPeriodicExec(
    IN PVOID SystemSpecific1, 
    IN PVOID FunctionContext, 
    IN PVOID SystemSpecific2, 
    IN PVOID SystemSpecific3);

#endif

VOID MlmeAutoScan(
    IN PRT2570ADAPTER pAdapter);

VOID MlmeAutoRecoverNetwork(
    IN PRT2570ADAPTER pAdapter);

VOID MlmeAutoReconnectLastSSID(
    IN PRT2570ADAPTER pAdapter);

BOOLEAN	MlmeValidateSSID(
    IN PRT2570ADAPTER pAd);

VOID MlmeCheckForRoaming(
    IN PRT2570ADAPTER pAdapter,
    IN ULONG    Now32);

//blue,VOID MlmeCheckChannelQuality(
VOID PeriodicExec(
    IN PRT2570ADAPTER pAdapter);

VOID MlmeCheckForPsmChange(
    IN PRT2570ADAPTER pAd);

VOID MlmeSetPsmBit(
    IN PRT2570ADAPTER pAdapter, 
    IN USHORT psm);

VOID MlmeSetTxPreamble(
    IN PRT2570ADAPTER pAdapter, 
    IN USHORT TxPreamble);

VOID MlmeUpdateTxRates(
    IN PRT2570ADAPTER pAd,
    IN BOOLEAN		 bLinkUp);

VOID	RTMPCheckRates(
	IN		PRT2570ADAPTER	pAd,
	IN OUT	UCHAR			SupRate[],
	IN OUT	UCHAR			*SupRateLen);

NDIS_STATUS MlmeInit(
    IN	PRT2570ADAPTER	pAdapter);

struct net_device_stats *
rt_getstats(struct net_device *dev);

struct iw_statistics *RTUSB_get_wireless_stats(
    IN  struct net_device *net_dev);

VOID MlmeHalt(
    IN	PRT2570ADAPTER	pAdapter);

VOID MlmeHandler(
    IN PRT2570ADAPTER pAd);

VOID MlmeSuspend(
    IN PRT2570ADAPTER pAd);

int MlmeThread(void * Context);
VOID CMDHandler(
    IN PRT2570ADAPTER pAdapter);

int RTUSBCmdThread(void * Context);
NDIS_STATUS MlmeInitMemoryHandler(
    IN PRT2570ADAPTER    pAd,
    IN UINT             Number,
    IN UINT             Size);

NDIS_STATUS MlmeAllocateMemory(
    IN PRT2570ADAPTER    pAd,
    OUT PVOID           *AllocVa);

VOID MlmeFreeMemory(
    IN PRT2570ADAPTER    pAd,
    IN PVOID            AllocVa);

VOID MlmeFreeMemoryHandler(
    IN PRT2570ADAPTER    pAd);


VOID DeleteTimer(
    IN PRT2570ADAPTER    pAd);

NTSTATUS
RTUSBSingleRead
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUSHORT			pValue
 );

NTSTATUS
RTUSBSingleWrite
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 USHORT				Value
 );

NTSTATUS
RTUSBReadMACRegister
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUSHORT			pValue
 );

NTSTATUS
RTUSBWriteMACRegister
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 USHORT				Value
 );

NTSTATUS
RTUSBMultiRead
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUCHAR				pData,
 USHORT				length
 );

NTSTATUS
RTUSBMultiWrite
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUCHAR				pData,
 USHORT				length
 );

#define	RETRY_LIMIT	3
NTSTATUS
RTUSBReadBBPRegister
(
 IN	PRT2570ADAPTER	pAdapter,
 IN	UCHAR			Id,
 IN	PUCHAR			pValue
 );


NTSTATUS
RTUSBWriteBBPRegister
(
 IN	PRT2570ADAPTER	pAdapter,
 IN	UCHAR			Id,
 IN	UCHAR			Value
 );

NTSTATUS
RTUSBWriteRFRegister
(
 IN	PRT2570ADAPTER	pAdapter,
 IN	ULONG			Value
 );

NTSTATUS
RTUSBReadEEPROM
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUCHAR				pData,
 USHORT				length
 );

NTSTATUS
RT2570WriteEEPROM
(
 IN	PRT2570ADAPTER	pAdapter,
 USHORT				Offset,
 PUCHAR				pData,
 USHORT				length
 );


VOID
  UsbBuildVendorRequest(
    IN PRT2570ADAPTER	pAdapter,
    IN PURB	Urb,
    IN USHORT  Function,
    IN USHORT  Length,
    IN ULONG  TransferFlags,
    IN UCHAR  ReservedBits,
    IN UCHAR  Request,
    IN USHORT  Value,
    IN USHORT  Index,
    IN PVOID  TransferBuffer ,
    IN PMDL  TransferBufferMDL ,
    IN ULONG  TransferBufferLength,
    IN PURB  Link
    );


void mod_use(UCHAR a, PRT2570ADAPTER pAdapter);




#if 0
VOID
EnqueueCmd
(
 PCmdQ	cmdq,
 PCmdQElmt	cmdelmt
 );
#else
#define EnqueueCmd(cmdq, cmdqelmt) \
{ \
	if (cmdq->size == 0) \
		cmdq->head = cmdqelmt; \
	else \
		cmdq->tail->next = cmdqelmt; \
	cmdq->tail = cmdqelmt; \
	cmdqelmt->next = NULL; \
	cmdq->size++; \
}
#endif


VOID
EnqueueInternalCmd
(
 PRT2570ADAPTER	pAdapter,
 NDIS_OID		Oid
 );

VOID
DequeueCmd
(
 PCmdQ	cmdq,
 PCmdQElmt	*pcmdelmt
 );


//blue
#if 0
VOID
InitializeBulkOutQueue
(
 PBULK_OUT_QUEUE	cmdq
 );


VOID
EnqueueBulkOut
(
 PBULK_OUT_QUEUE	cmdq,
 PBULK_OUT_QUEUE_ELEMENT	cmdelmt
 );

VOID
DequeueBulkOut
(
 PBULK_OUT_QUEUE	cmdq,
 PBULK_OUT_QUEUE_ELEMENT	*pcmdelmt
 );
#endif

VOID
InitializeDataBulkOutQueue
(
 PRT2570ADAPTER	pAdapter
 );

#if 0
VOID
EnqueueDataBulkOut
(
 PRT2570ADAPTER	pAdapter,
 PNDIS_PACKET	cmdelmt
 );

VOID
DequeueDataBulkOut
(
 PRT2570ADAPTER	pAdapter,
 PNDIS_PACKET	*pcmdelmt
 );
#else

#define EnqueueDataBulkOut(pAdapter, cmdqelmt) \
{ \
	PDATA_BULKOUT_QUEUE	cmdq = &(pAdapter->DataQ); \
	if (cmdq->size == 0) \
		cmdq->head = cmdqelmt; \
	else \
		*(GET_NEXT_PACKET_IN_BULKOUT_QUEUE(cmdq->tail)) = cmdqelmt; \
	cmdq->tail = cmdqelmt; \
	cmdq->size++; \
	*(GET_NEXT_PACKET_IN_BULKOUT_QUEUE(cmdqelmt)) = NULL; \
}

#define DequeueDataBulkOut(pAdapter, pcmdqelmt) \
{ \
	PDATA_BULKOUT_QUEUE	cmdq = &(pAdapter->DataQ); \
	*pcmdqelmt = cmdq->head; \
	cmdq->head = *(GET_NEXT_PACKET_IN_BULKOUT_QUEUE(*pcmdqelmt)); \
	cmdq->size--; \
	if (cmdq->size == 0) \
		cmdq->tail = NULL; \
}


#endif

VOID
InitializeMLMEBulkOutQueue
(
 PRT2570ADAPTER	pAdapter
 );

#if 0
VOID
EnqueueMLMEBulkOut
(
 PRT2570ADAPTER	pAdapter,
 PMGMT_STRUC	cmdelmt
 );

VOID
DequeueMLMEBulkOut
(
 PRT2570ADAPTER	pAdapter,
 PMGMT_STRUC	*pcmdelmt
 );
#else
#define EnqueueMLMEBulkOut(pAdapter, cmdqelmt) \
{ \
	PMLME_BULKOUT_QUEUE	cmdq = &(pAdapter->MLMEQ); \
	if (cmdq->size == 0) \
		cmdq->head = cmdqelmt; \
	else \
 		cmdq->tail->next = cmdqelmt; \
 	cmdq->tail = cmdqelmt; \
	cmdq->size++; \
	cmdqelmt->next = NULL; \
}

#define DequeueMLMEBulkOut(pAdapter, pcmdqelmt) \
{ \
	PMLME_BULKOUT_QUEUE	cmdq = &(pAdapter->MLMEQ); \
	*pcmdqelmt = cmdq->head; \
	cmdq->head = (*pcmdqelmt)->next; \
	cmdq->size--; \
	if (cmdq->size == 0) \
		cmdq->tail = NULL; \
}
#endif

NDIS_STATUS RTMPFreeDescriptorRequest(
	IN		PRT2570ADAPTER	pAdapter,
	IN		UCHAR			RingType,
	IN		UCHAR			NumberRequired);


VOID MlmeSuspend(
    IN	PRT2570ADAPTER	pAdapter);

VOID MlmeResume(
    IN	PRT2570ADAPTER	pAdapter);

#ifdef TEST_MODE_SUPPORT
NTSTATUS
USB_BulkOut
(
 PRT2570ADAPTER pAdapter,
 USHORT	length,
 PVOID buffer
 );

//blue
#if 0
VOID
BulkInOnePacket
(
 PRT2570ADAPTER Adapter
 );
#endif

VOID
BulkInPackets
(
 PRT2570ADAPTER Adapter
 );

VOID
BulkOutPackets
(
 PRT2570ADAPTER pAdapter,
 USHORT length, PVOID buffer
 );
#endif

#ifdef RALINK_ATE
VOID DisableMlme(
    IN PRT2570ADAPTER pAd); 

VOID ReenableMlme(
    IN PRT2570ADAPTER pAd); 
#endif

VOID BuildChannelList(
    IN PRT2570ADAPTER pAdapter);

UCHAR FirstChannel(
    IN	PRT2570ADAPTER	pAdapter);

UCHAR NextChannel(
    IN	PRT2570ADAPTER	pAdapter, 
    IN  UCHAR channel);

VOID RaiseClock(
    IN	PRT2570ADAPTER	pAd,
    IN  ULONG *x);

VOID LowerClock(
    IN	PRT2570ADAPTER	pAd,
    IN  ULONG *x);

USHORT ShiftInBits(
    IN	PRT2570ADAPTER	pAd);

VOID ShiftOutBits(
    IN	PRT2570ADAPTER	pAd,
    IN  USHORT data,
    IN  USHORT count);

VOID EEpromCleanup(
    IN	PRT2570ADAPTER	pAd);

VOID EWDS(
	IN	PRT2570ADAPTER	pAd);

VOID EWEN(
	IN	PRT2570ADAPTER	pAd);
    
USHORT RTMP_EEPROM_READ16(
    IN	PRT2570ADAPTER	pAd,
    IN  USHORT Offset);

VOID RTMP_EEPROM_WRITE16(
    IN	PRT2570ADAPTER	pAd,
    IN  USHORT Offset,
    IN  USHORT Data);

UCHAR ChannelSanity(
    IN PRT2570ADAPTER pAd, 
    IN UCHAR channel);
    
//
// Prototypes of function definition in rtmp_tkip.c
//
VOID	RTMPInitTkipEngine(
	IN	PRT2570ADAPTER	pAdapter,	
	IN	PUCHAR			pTKey,
	IN	UCHAR			KeyId,
	IN	PUCHAR			pTA,
	IN	PUCHAR			pMICKey,
	IN	PUCHAR			pTSC,
	IN	INT				DoEncrypt,
	OUT PULONG			pIV16,
	OUT PULONG			pIV32,
	IN	PUCHAR			pDest);

BOOLEAN	RTMPTkipCompareMICValue(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PUCHAR			pSrc,
	IN	PUCHAR			pDA,
	IN	PUCHAR			pSA,
	IN	PUCHAR			pMICKey,
	IN	UINT			Len);

VOID	RTMPCalculateMICValue(
	IN	PRT2570ADAPTER	pAdapter,
	IN	struct sk_buff 	*pPacket,
	IN	PUCHAR			pEncap,
	IN	INT				LenEncap,
	IN	PWPA_KEY		pWpaKey);

VOID RTMPTkipMixTKey(
	IN	PTKIP_KEY_INFO	pTkip,
	IN	PUCHAR			pTKey,
	IN	PUCHAR			pTA	);

BOOLEAN	RTMPTkipCompareMICValueWithLLC(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PUCHAR			pLLC,
	IN	PUCHAR			pSrc,
	IN	PUCHAR			pDA,
	IN	PUCHAR			pSA,
	IN	PUCHAR			pMICKey,
	IN	UINT			Len);

BOOLEAN RTMPSoftDecryptTKIP(
	IN PRT2570ADAPTER pAdapter,
	IN PUCHAR	pData,
	IN ULONG	DataByteCnt, 
	IN PWPA_KEY	pWpaKey);

NDIS_STATUS	RTMPWPAAddKeyProc(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PVOID			pBuf);

NDIS_STATUS	RTMPWPARemoveKeyProc(
	IN	PRT2570ADAPTER	pAdapter,
	IN	PVOID			pBuf);

VOID	RTMPWPARemoveAllKeys(
	IN	PRT2570ADAPTER	pAdapter);

VOID	RTMPSetPhyMode(
	IN	PRT2570ADAPTER	pAdapter,
	IN  ULONG phymode);

VOID    RT2570SetDesiredRates(
    IN  PRT2570ADAPTER	pAdapter,
    IN  LONG            Rates);
INT Set_R17_Proc(
	IN	PRT2570ADAPTER	 pAdapter, 
	IN	PUCHAR			arg);

INT Read_R17_Proc(
	IN	PRT2570ADAPTER	 pAdapter, 
	IN	PUCHAR			arg);

int usb_rt2570_ioctl(struct net_device *net_dev, struct ifreq *rq, int cmd);

VOID
KickBulkOut
(
 PRT2570ADAPTER pAdapter,
 BOOLEAN	InBurst
 );

VOID
BulkOutBeacon0
(
 PRT2570ADAPTER	pAdapter
 );

VOID
RejectPendingPackets
(
 PRT2570ADAPTER pAdapter
 );

VOID
CleanUpMLMEWaitQueue
(
 IN	PRT2570ADAPTER	pAdapter
 );

#if 0
VOID
CleanUpBulkOutQueues
(
 PRT2570ADAPTER pAdapter,
 BULK_OUT_TYPE	type
 );
#endif

VOID
CleanUpDataBulkOutQueue
(
 PRT2570ADAPTER pAdapter
 );

VOID
CleanUpMLMEBulkOutQueue
(
 PRT2570ADAPTER pAdapter
 );

VOID
CancelPendingIRPs
(
 IN PRT2570ADAPTER pAdapter
 );

VOID
CancelPendingBulkOutIRP
(
 PRT2570ADAPTER pAdapter
 );

VOID
CancelPendingBulkInIRP_bh
(
 PRT2570ADAPTER pAdapter
 );



//
// Prototypes of function definition for *iwpriv* in rtmp_info.c
//
INT Set_CountryRegion_Proc(
    IN  PRT2570ADAPTER	pAdapter, 
    IN  PUCHAR          arg);

INT Set_SSID_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_WirelessMode_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_TxRate_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_Channel_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR  
    arg);

INT Set_BGProtection_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_TxPreamble_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_RTSThreshold_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_FragThreshold_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_TxBurst_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_TurboRate_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_AuthMode_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_EncrypType_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_DefaultKeyID_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_Key1_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_Key2_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_Key3_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_Key4_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

INT Set_WPAPSK_Proc(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  PUCHAR          arg);

#ifdef RT2500_DBG
VOID RTMPIoctlBBP(
    IN  PRT2570ADAPTER   pAdapter,
    IN  struct iwreq    *wrq);

VOID RTMPIoctlMAC(
    IN  PRT2570ADAPTER   pAdapter,
    IN  struct iwreq    *wrq);
#endif



//
// prototype in wpa.c
//
BOOLEAN WpaMsgTypeSubst(
    IN  UCHAR   EAPType,
    OUT ULONG   *MsgType);

VOID WpaPskStateMachineInit(
    IN  PRT2570ADAPTER       pAd, 
    IN  STATE_MACHINE       *S, 
    OUT STATE_MACHINE_FUNC Trans[]);

VOID WpaEAPOLKeyAction(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID    WpaPairMsg1Action(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID    WpaPairMsg3Action(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem); 

VOID    WpaGroupMsg1Action(
    IN  PRT2570ADAPTER   pAdapter, 
    IN  MLME_QUEUE_ELEM *Elem);

VOID    WpaMacHeaderInit(
    IN      PRT2570ADAPTER   pAd, 
    IN OUT  PHEADER_802_11  Hdr, 
    IN      UCHAR           wep, 
    IN      PMACADDR        pAddr1); 

VOID    WpaHardEncrypt(
    IN  PRT2570ADAPTER   pAdapter,
    IN  PUCHAR          pPacket,
    IN  ULONG           Len);

VOID    HMAC_SHA1(
    IN  UCHAR   *text,
    IN  UINT    text_len,
    IN  UCHAR   *key,
    IN  UINT    key_len,
    IN  UCHAR   *digest);
 void hmac_sha1(unsigned char *text, int text_len, unsigned char *key, int key_len, unsigned char *digest);

VOID    PRF(
    IN  UCHAR   *key,
    IN  INT     key_len,
    IN  UCHAR   *prefix,
    IN  INT     prefix_len,
    IN  UCHAR   *data,
    IN  INT     data_len,
    OUT UCHAR   *output,
    IN  INT     len);

VOID WpaCountPTK(
    IN  UCHAR   *PMK,
    IN  UCHAR   *ANonce,
    IN  UCHAR   *AA,
    IN  UCHAR   *SNonce,
    IN  UCHAR   *SA,
    OUT UCHAR   *output,
    IN  UINT    len);

VOID    GenRandom(
    IN  PRT2570ADAPTER   pAd, 
    OUT UCHAR           *random);

VOID    AES_GTK_KEY_UNWRAP( 
    IN  UCHAR   *key,
    OUT UCHAR   *plaintext,
    IN  UCHAR   *ciphertext);


//
// SHA context
//
typedef	struct _SHA_CTX
{
    ULONG   Buf[5];             // buffers of five states
	UCHAR   Input[80];          // input message
	ULONG   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
	
}	SHA_CTX;
    
    
VOID BulkOutWpaPskFrame( PRT2570ADAPTER	pAd);

VOID	RTMPTkipEncryptData(
	IN	PRT2570ADAPTER	pAdapter,	
	IN	PUCHAR			pSrc,
	IN	PUCHAR			pDest,
	IN	UINT			Len);

VOID    RTMPInitMICEngine(
    IN  PRT2570ADAPTER pAdapter,   
    IN  PUCHAR          pKey,
    IN  PUCHAR          pDA,
    IN  PUCHAR          pSA,
    IN  PUCHAR          pMICKey);


VOID    RTMPTkipAppend( 
    IN  PTKIP_KEY_INFO  pTkip,  
    IN  PUCHAR          pSrc,
    IN  UINT            nBytes);

VOID    RTMPTkipGetMIC( 
    IN  PTKIP_KEY_INFO  pTkip);

void USB_SendWpaPskComplete(purbb_t pUrb,struct pt_regs *pt_regs);
//void USB_SendWpaPskComplete(purbb_t pUrb);

//
// extra prototype in md5.c
//
VOID    SHAInit(SHA_CTX *ctx);

  VOID    SHAHashBlock(SHA_CTX *ctx);

UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, ULONG LenInBytes);

VOID    SHAFinal(SHA_CTX *ctx, unsigned char hashout[20]);
#endif 
#ifndef _stdincl_h_OK__
#define _stdincl_h_OK__




//=============================================
// functions in usbrx.c
//=============================================

int USB_RxPacket(PRT2570ADAPTER Adapter);

//=============================================
// functions in rt2570_main.c
//=============================================

VOID ReleaseAdapter(PRT2570ADAPTER   Adapter, BOOLEAN IsFree);


VOID RejectPendingPackets(PRT2570ADAPTER Adapter);

int ControlThread(IN OUT PVOID Context);


int TXThread(IN OUT PVOID  Context);


BOOLEAN RT2570UsbReset(PRT2570ADAPTER    Adapter);

NTSTATUS USB_ResetPipe(PRT2570ADAPTER    Adapter, 
                       UINT BulkPipe);

int USB_CallUSBD(PRT2570ADAPTER Adapter, 
                      IN PURB       Urb);

#endif

#ifndef _PRISMHEADER
#define _PRISMHEADER

enum {
	DIDmsg_lnxind_wlansniffrm		= 0x00000044,
	DIDmsg_lnxind_wlansniffrm_hosttime	= 0x00010044,
	DIDmsg_lnxind_wlansniffrm_mactime	= 0x00020044,
	DIDmsg_lnxind_wlansniffrm_channel	= 0x00030044,
	DIDmsg_lnxind_wlansniffrm_rssi		= 0x00040044,
	DIDmsg_lnxind_wlansniffrm_sq		= 0x00050044,
	DIDmsg_lnxind_wlansniffrm_signal	= 0x00060044,
	DIDmsg_lnxind_wlansniffrm_noise		= 0x00070044,
	DIDmsg_lnxind_wlansniffrm_rate		= 0x00080044,
	DIDmsg_lnxind_wlansniffrm_istx		= 0x00090044,
	DIDmsg_lnxind_wlansniffrm_frmlen	= 0x000A0044
};
enum {
	P80211ENUM_msgitem_status_no_value	= 0x00
};
enum {
	P80211ENUM_truth_false			= 0x00,
	P80211ENUM_truth_true			= 0x01
};

typedef struct {
	u_int32_t did;
	u_int16_t status;
	u_int16_t len;
	u_int32_t data;
} p80211item_uint32_t;

typedef struct {
	u_int32_t msgcode;
	u_int32_t msglen;
#define WLAN_DEVNAMELEN_MAX 16
	u_int8_t devname[WLAN_DEVNAMELEN_MAX];
	p80211item_uint32_t hosttime;
	p80211item_uint32_t mactime;
	p80211item_uint32_t channel;
	p80211item_uint32_t rssi;
	p80211item_uint32_t sq;
	p80211item_uint32_t signal;
	p80211item_uint32_t noise;
	p80211item_uint32_t rate;
	p80211item_uint32_t istx;
	p80211item_uint32_t frmlen;
} wlan_ng_prism2_header;

#endif
