// Embedded 802.11a/g wireless network interface
// MAC layer hardware interface for ConnectCore Wi-9C
// Copyright 2006 Digi International
//
// #include "bsp.h"
#include "mac.h"
#include "assert.h"
#include "mcsys_reg.h"
#include "WiFi_USB.h"
#include "mac_hw_wiwave.h"

#ifdef NET_OS_SPECIFIC
#include <bsp_api.h>
#include "bsp_net.h"
#if (BSP_WPS_ENABLED == TRUE)
#include "mac_wps.h"
#endif

#else
#include <libutils.h>
#include "digi_products.h"
#include "hwtypes.h"
#include "gpio.h"
#include "cellbar.h"
#include "p_registry.h"
#endif

#if (USB_WIFI_ENABLED == 1)

#ifdef NET_OS_SPECIFIC
#define MAC_PRINTF(y,...) printf(__VA_ARGS__)
#else
#define MAC_PRINTF(y,...) trace(WIRELESS_TRACE,y, __VA_ARGS__)
#endif

#ifdef NET_OS_SPECIFIC
#define MAC_USB_EEPROM_ACCESS_MS    21
#else
#define MAC_USB_EEPROM_ACCESS_MS    6
#endif

// Register read timeout
#define MAC_USB_READ_TIMEOUT_MS     1000

// Number of bytes in a USB 'Write Packet'
#define USB_REG_WRITE_LEN 8

// Size of the initialization vector (4*12)
// This is in four byte words
#define AES_INIT_DATA_LEN 48 

// Memory pools used to store data for mult-part USB meaages.
// One pool for the message header and the other for the body
static TX_BLOCK_POOL usb_message_hdr_pool;
static TX_BLOCK_POOL usb_message_pool;

// This is the number of USB messages
#define MAX_MULTI_MSG 16

// This is the size of a USB message
#define MAX_MULTI_MSG_SIZE 512

// Size of memory pools. threadX requires an extra sizeof(void *)
#define USB_MESSAGE_HDR_POOL_BLOCK_SIZE  (sizeof(MacUsbMsg)+sizeof(void *))
#define USB_MESSAGE_HDR_POOL_SIZE        (USB_MESSAGE_HDR_POOL_BLOCK_SIZE*MAX_MULTI_MSG)

#define USB_MESSAGE_POOL_BLOCK_SIZE (MAX_MULTI_MSG_SIZE+sizeof(void *))
#define USB_MESSAGE_POOL_SIZE       (USB_MESSAGE_POOL_BLOCK_SIZE*MAX_MULTI_MSG)

static void WriteRF (uint8 addr, uint32 data);
static int mac_usb_read_req_init(void);
static MacUsbMsg *MacUsbInitMsg(void);

static int MacUsbWriteData(uint8 reg, uint16 len, void *data);
static int MacUsbWriteFifoData(uint8 reg, uint16 len, void *data, int block);

//
// Hardware register defines
//
#define MAC_BASE        0x60000000      // Register base address
#define MAC_PROG        0x70000000      // FPGA program address
#define MAC_MASK        0xffffc001      // Size mask and enable bit

#define REG32(offset)   (* (volatile uint32 *) (MAC_BASE + (offset)))
#define	REG16(offset)	(* (volatile uint16 *) (MAC_BASE + (offset)))
#define REG8(offset)	(* (volatile uint8  *) (MAC_BASE + (offset) + 1))


// Baseband control registers
#define HW_VERSION      0x00     // Version
#define HW_GEN_CONTROL  0x04     // General control
#define HW_GEN_STATUS   0x08     // General status
#define HW_RSSI_AES     0x0c     // RSSI and AES status
#define HW_INTR_MASK    0x10     // Interrupt mask
#define HW_INTR_STATUS  0x14     // Interrupt status
#define HW_SPI          0x18     // RF SPI interface
#define HW_DATA_FIFO_END  0x20   // Data FIFO
#define HW_DATA_FIFO      0x21   // Data FIFO addr to prevent under-run condition
#define HW_AES_FIFO_END   0x30   // AES FIFO
#define HW_AES_FIFO       0x31	 // AES FIFO addr to prevent under-run condition
#define HW_AES_CONTROL    0x38   // AES Control  
// MAC control registers.
#define HW_STAID0       0x40     // Station ID (6 bytes)
#define HW_STAID1       0x44
#define HW_BSSID0       0x48     // BSS ID (6 bytes)
#define HW_BSSID1       0x4c
#define HW_SSID_LEN     0x50     // Basic rates (high 16 bits), SSID length (low 8 bits)
#define HW_BACKOFF      0x54     // Backoff period (16 bits)
#define HW_LISTEN       0x58     // Listen interval (16 bits), CFP (8 bits), DTIM (8 bits)
#define HW_CFP_ATIM     0x5c     // CFP max duration/ATIM period (16 bits), beacon interval (16 bits)
#define HW_MAC_STATUS   0x60     // FW version (high 16 bits), MAC status (low 8 bits)
#define HW_MAC_CONTROL  0x64     // AES key disable (8 bits), MAC control (8 bits)
#define HW_REMAIN_BO    0x68     // Remaining backoff (16 bits)
#define HW_BEACON_BO    0x6c     // Beacon backoff (16 bits), beacon mask (8 bits)
#define HW_SSID         0x80     // Service set ID (32 bytes)

#define HW_EEPROM_CONTROL 0xF0 // EEPROM Control register addr
#define HW_EEPROM_DATA    0xF8 // EEPROM Data register addr
// FIFO sizes in bytes
#define HW_TX_FIFO_SIZE 1792
#define HW_RX_FIFO_SIZE 2048

// AES_CONTROL_REGISTER
#define AES_MODE_BIT         0x10
#define AES_KEY_LOAD_BIT     0x04

// Min fragment size to allow interrupt latency between frames
#define MIN_FRAG_SIZE   400

// Size of CTS frame in FIFO
#define CTS_OVERHEAD    20
// Max overhead per fragment (CCMP is worst case)
#define FRAG_OVERHEAD   (8+DATA_SIZE+CCMP_SIZE-FCS_SIZE)
// Max fragment size to fit CTS and 2 fragments in transmit FIFO
#define MAX_FRAG_SIZE   (DATA_SIZE + (HW_TX_FIFO_SIZE-CTS_OVERHEAD-2*FRAG_OVERHEAD)/2)

// General control register bits
#define GEN_RXEN        0x00000001      // Receive enable
#define GEN_ANTDIV      0x00000002      // Antenna diversity
#define GEN_ANTSEL      0x00000004      // Antenna select
#define GEN_5GEN        0x00000008      // 5 GHz band enable
#define GEN_SHPRE       0x00000010      // Transmit short preamble
#define GEN_RXFIFORST   0x00000020      // Receive FIFO reset
#define GEN_TXFIFORST   0x00000040      // Transmit FIFO reset
#define GEN_TXHOLD      0x00000080      // Transmit FIFO hold
#define GEN_BEACEN      0x00000100      // Beacon enable
#define GEN_TXFIFOEMPTY 0x00004000      // Transmit FIFO empty
#define GEN_TXFIFOFULL  0x00008000      // Transmit FIFO full
#define	GEN_TESTMODE	0x80000000	// Mode of operation: test/normal

#define GEN_RESET       0x527f0000      // Reset state
#define GEN_INIT        0x337a0000      // Initial state

// General status register bits
#define STAT_RXFE       0x00000010      // Receive FIFO empty
#define STAT_SFTRST     0x40000000      // Soft reset

// AES status register bits
#define AES_LED         0x00000100      // PCIe association LED
#define AES_EMPTY       0x00010000      // AES receive FIFO empty
#define AES_FULL        0x00020000      // AES transmit FIFO full
#define AES_BUSY        0x00040000      // AES engine busy
#define AES_MIC         0x00080000      // AES MIC correct

// Interrupt mask and status register bits
#define INTR_RXFIFO     0x00000001      // Receive FIFO not empty
#define INTR_TXEND      0x00000002      // Transmit complete
#define INTR_TIMEOUT    0x00000004      // CTS/ACK receive timeout
#define INTR_ABORT      0x00000008      // CTS transmit abort
#define INTR_TBTT       0x00000010      // Beacon transmission time
#define INTR_ATIM       0x00000020      // ATIM interval end
#define INTR_RXOVERRUN  0x00000040      // Receive FIFO overrun

// MAC control register bits
#define CTRL_TXREQ      0x00000001      // Transmit request
#define CTRL_AUTOTXDIS  0x00000002      // Auto-transmit disable
#define CTRL_BEACONTX   0x00000004      // Beacon transmit enable
#define CTRL_PROMISC    0x00000008      // Promiscuous mode
#define CTRL_IBSS       0x00000010      // IBBS mode
#define CTRL_AES_DISABLE 0x00000020     // AES decryption disable
#define CTRL_KEY0_DIS   0x00000100      // AES key 0 disable
#define CTRL_KEY1_DIS   0x00000200      // AES key 1 disable
#define CTRL_KEY2_DIS   0x00000400      // AES key 2 disable
#define CTRL_KEY3_DIS   0x00000800      // AES key 3 disable
#define CTRL_AES_DIS_ALL 0x00000f20     // All AES key disable bits

// GPIO output values for LEDs
#define LED_OFF         1
#define LED_ON          0

// RF transceiver transmitter gain for each power level.
// This is the 0-15 power level, bit reversed.
static uint8 powerTable[] = {
    0x0, 0x8, 0x4, 0xc, 0x2, 0xa, 0x6, 0xe, 
    0x1, 0x9, 0x5, 0xd, 0x3, 0xb, 0x7, 0xf
};

// RF transceiver frequency divider for each channel
static const struct {
    uint16 integer;
    uint16 fraction;
} freqTable[] = {
    { 0, 0 },
    { 0x6847, 0x0999 }, // 1 (2412 MHz)
    { 0x6847, 0x099b }, // 2 (2417 MHz)
    { 0x6867, 0x0998 }, // 3
    { 0x6867, 0x099a }, // 4
    { 0x6867, 0x0999 }, // 5
    { 0x6867, 0x099b }, // 6
    { 0x6857, 0x0998 }, // 7
    { 0x6857, 0x099a }, // 8
    { 0x6857, 0x0999 }, // 9
    { 0x6857, 0x099b }, // 10
    { 0x6877, 0x0998 }, // 11
    { 0x6877, 0x099a }, // 12
    { 0x6877, 0x0999 }, // 13 (2472 MHz)
    { 0x684f, 0x0ccc }, // 14 (2484 MHz)
};

// Map LNA value to gain value
static const uint8 lnaTable[] = 
{
    0, 0, 23, 39
};

// Map high gain values to dbm
static const int8_t gainTable[] = 
{
    -82, -84, -85, -86, -87, -89, -90, -92, -94, -98
};


//static MacBuffer rxFrame;   // Frame being received
static uint32 intrMask;     // Interrupt mask register
static uint32 timerLoops;   // Loops for 10 usec delay

unsigned char *current_rx_frame_ptr;    // Pointer to the current frame
int            current_rx_frame_len=0;  // Number of bytes left in the frame

uint8 wless_mac_addr[6] = {0x0, 0xA, 0x0, 0xA, 0x0, 0xA};

uint8 naWifiStartHWGetBasicMeasureMap(void)
{
    return 0;           /* only implemented on Piper */
}

void naWifiStartHWBasicMeasure(void)
{
    /* This function is only implemented on Piper based platforms.*/
}

//
// Delay for usec microseconds
//
void naWifiWaitUS (uint32 usec)
{
    volatile int n = usec*timerLoops/10;
    
    while (n-- > 0)
        ;
}

//
// Calibrate the spin loop in naWifiWaitUS()
//
// We need 10us resolution, but the threadx timer is only accurate to 10ms.
// Use it to calibrate a large number of iterations of the spin loop in naWifiWaitUS().
//
static void InitTimer (void)
{
    uint32 ntime;
    
    // Initial guess
    timerLoops = 500;
    
    // Time 100ms delay using hardware timer
    ntime = getTimeMS();
    naWifiWaitUS (100000);
    ntime = getTimeMS() - ntime;
    
    // Calculate loops for 100ms delay:
    // (initial guess)*(expected time)/(actual time)
    if (ntime != 0)
        timerLoops = 500*100/ntime;
    
#ifdef DEBUG
//    MAC_PRINTF(TRACE_INFO, "time=%ld ms, loops=%ld\n", ntime, timerLoops);

    ntime = getTimeMS();
    naWifiWaitUS (100000);
    ntime = getTimeMS() - ntime;
    
//    MAC_PRINTF(TRACE_INFO, "time=%ld ms (should be 100)\n", ntime);
#endif
}

//
// Write data to an RF tranceiver register
// @param addr Register address (4 bits)
// @param data Data to write (20 bits, bit reversed)
//
static void WriteRF (uint8 addr, uint32 data)
{
    // HW_SPI = (addr << 20) | data;
    
    MacUsbWriteReg(HW_SPI,  (addr << 20) | data, MAC_COMPLETE_MSG, MAC_OP_WRITE,
                  (MacUsbMsg *)NULL);

    naWifiWaitUS (10);
}

// Write to transmit FIFO 0x20 or 0x21
static void HWWriteFifo(void *src_, int len, BOOL last)
{
   if (last)
       MacUsbWriteFifoData(HW_DATA_FIFO_END, len, src_, 0);
   else
       MacUsbWriteFifoData(HW_DATA_FIFO, len, src_, 0);
}


// Write AES frame headers to 0x21
static void HWWriteAESHeaderFifo (void *src_, int len)
{
   MacUsbWriteFifoData(HW_DATA_FIFO, len, src_, 1);
}

// Write plaintext key, IV and data to 0x30 or 0x31 
static void HWWriteAESFifo (void *src_, int len, BOOL last)
{
    if (last)
        MacUsbWriteFifoData(HW_AES_FIFO_END, len, src_, 1);
    else
        MacUsbWriteFifoData(HW_AES_FIFO, len, src_, 1);
}

//
// Load the baseband controller firmware
//
#ifdef NET_OS_SPECIFIC
static MacReturn LoadHW (void)
{
    // Baseband firmware image
    // extern const char bbfw_bin_data[];
    // extern const int bbfw_bin_data_len;

    static BOOL loaded = FALSE;
    
    // Load only once after reset
    if (loaded)
        return ERR_OK;

    MAC_PRINTF(TRACE_INFO, "HW load\n");

    loaded = TRUE;
    return ERR_OK;
}
#endif

extern int usb_wifi_read(unsigned char *, int , int* , int*, MacBuffer*);
extern void reset_system(int);

static MacReturn InitPolling(void)
{
    MacBuffer     *mac_buffer = NULL;
    MacReturn     outcome = ERR_OK;
    unsigned int  len = BUF_SIZE; /* Size of the MacBuffer portion that is filled in by USB: 512*3+24 */
    int           bytesTransferred = 0;
    int           errorCode=0;
    extern int wifi_not_polling;

    /*Allocate a MacBuffer Start polling the WiFi device */ 
    mac_buffer = MacGetBuffer();
    if (mac_buffer == (MacBuffer *)NULL)
    {
      outcome = ERR_MEMORY;
    }
    else
    {
        wifi_not_polling = 0;

        /* Start polling the WiWave device */
        usb_wifi_read((unsigned char *)&mac_buffer->usb_encoded_length, len,
                               &bytesTransferred, &errorCode, mac_buffer);

        if (errorCode)
        {     
            outcome = ERR_MEMORY; 
        }
    }

    return outcome;
}

//
// Initialize the wireless hardware
//

static void *msg_hdr_pool_ptr=0, *msg_pool_ptr=0;

MacReturn InitHW (void)
{
    unsigned int ret;
	epStatus *pSta = rootEndPoint[0];

    // Wait for the Wi-Wave card to be connected. 
    if (usb_wifi_wait(USB_WIFI_DEVICE_CONNECTED) != 0) 
    {
        MAC_PRINTF(TRACE_CRITICAL, "Wi-Wave not connected\n");
        return ERR_MEMORY;
    }
    
    // Create the block pools used for multi-part USB messages.
    msg_hdr_pool_ptr = malloc(USB_MESSAGE_HDR_POOL_SIZE);
   
    ret = tx_block_pool_create(&usb_message_hdr_pool,
                               "USB message hdr pool",
                                USB_MESSAGE_HDR_POOL_BLOCK_SIZE,
                                msg_hdr_pool_ptr,
                                USB_MESSAGE_HDR_POOL_SIZE);

    if (ret != TX_SUCCESS) 
             return ERR_MEMORY;

    msg_pool_ptr = malloc(USB_MESSAGE_POOL_SIZE);
 
    ret = tx_block_pool_create(&usb_message_pool,
                               "USB message pool",
                               USB_MESSAGE_POOL_BLOCK_SIZE,
                               msg_pool_ptr,
                               USB_MESSAGE_POOL_SIZE);

    if (ret != TX_SUCCESS) 
             return ERR_MEMORY;
   
    // Initalize read request packet
    if (mac_usb_read_req_init() != 0) 
            return ERR_MEMORY;

    // Start USB IN tokens  
    ret = InitPolling();
    if (ret != ERR_OK)
        return ret;
    
    // Hardware supports 802.11b/g, channels 1-14, AES acceleration
    hwAES = TRUE;
    macParams.chan_mask[0] &= 0x3fff;
	macParams.chan_mask[1] = 0;
    
    if (macParams.frag_thresh < MIN_FRAG_SIZE)
        macParams.frag_thresh = MIN_FRAG_SIZE;
    if (maxFragSize > MAX_FRAG_SIZE)
        maxFragSize = MAX_FRAG_SIZE;

    // Set RSSI average to a middle value so it 
    // converges to its initial value faster
    pSta->macStatus.rx_signal = -50*RSSI_SCALE;
    
#if (BSP_WPS_ENABLED == TRUE)
    naWpsParamsInit(&macParams);
#endif

    InitTimer();
    
    // Init baseband processor and MAC assist
    
    // Reset baseband processor in case it was already running
    MacUsbWriteReg(HW_GEN_STATUS, STAT_SFTRST, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

    // HW_GEN_CONTROL = GEN_INIT;
    MacUsbWriteReg(HW_GEN_CONTROL, GEN_INIT, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
                   
    // ***Phillips USB peripheral workaround***
    // In full speed mode, after a soft reset, the USB controller on the 
    // Wi-Wave sends the first two USB data packets as length 64 bytes,
    // regardless of actual size.  The host controller combines these and
    // the next packet into a single transfer.  This causes the first
    // register read (MAC address) to fail.  Work around this by sending
    // 3 small read requests. MacUsbReadReqHandleResponse() will ignore the 
    // response because no request buffer has been set up.
    MacUsbWriteReg (0xFD, 1 << 16, MAC_COMPLETE_MSG, 0, NULL);
    MacUsbWriteReg (0xFD, 1 << 16, MAC_COMPLETE_MSG, 0, NULL);
    MacUsbWriteReg (0xFD, 1 << 16, MAC_COMPLETE_MSG, 0, NULL);
    
#ifndef NET_OS_SPECIFIC
    // get module mac address from perm storage
    MacUsbReadEEPROM((unsigned int)VPD_WIWAVE_MAC_OFFSET, (char* )&wless_mac_addr, WLN_ADDR_SIZE);
    memcpy (macParams.sta_addr, (uint8 *)&wless_mac_addr, WLN_ADDR_SIZE);
#endif

    // HWMemcpy (&HW_STAID0, macParams.sta_addr, WLN_ADDR_SIZE);
    MacUsbWriteData(HW_STAID0, WLN_ADDR_SIZE, macParams.sta_addr);

    // Transmit on primary antenna
    MacUsbWriteReg(HW_RSSI_AES, 0x88000000, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

    // Set anternna diversity if enabled
    if (macParams.options & WLN_OPT_ANTDIV)
    {
        // HW_GEN_CONTROL |= GEN_ANTDIV;
        MacUsbWriteReg(HW_GEN_CONTROL, GEN_ANTDIV, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
    }

    // Enable HW AES mode=1 
    MacUsbWriteReg(HW_AES_CONTROL, AES_MODE_BIT, 
                  MAC_COMPLETE_MSG, MAC_OP_WRITE,
                  (MacUsbMsg *)NULL);

    // Initialize RF tranceiver 
    WriteRF (7, 0x27ffe); // test
    WriteRF (6, 0xf81ac); // filter register
    WriteRF (5, 0x19e4f); // transmitter gain
    WriteRF (4, 0x0002b); // receiver gain
    WriteRF (3, 0x46662); // vco control
    WriteRF (0, 0x25f9c); // mode control
    naWifiWaitUS (10);
    
    MacSetTxPower(macParams.tx_power);

    // Enable interrupts
    intrMask = INTR_RXFIFO|INTR_TXEND|INTR_TIMEOUT|INTR_RXOVERRUN;
    // HW_INTR_MASK = intrMask;
    MacUsbWriteReg(HW_INTR_MASK, intrMask, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

    return ERR_OK;
}

//
// Shutdown the wireless hardware
//
void ShutdownHW (void)
{
    int ret;
    
    // This function may be called more than once. 
    if (msg_hdr_pool_ptr)
    {
    
        MAC_PRINTF(TRACE_INFO, "HW shutdown\n");

        // HW_GEN_CONTROL = GEN_RESET;
        MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_RESET, 
                   MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);

         // HW_MAC_CONTROL = 0;
        MacUsbWriteReg(HW_MAC_CONTROL, 0, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
                   
        // HW_INTR_MASK = 0;
        MacUsbWriteReg(HW_INTR_MASK, 0, 
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

        // This function may be called more than once. 
        ret = tx_block_pool_delete(&usb_message_hdr_pool);
        if (ret != TX_SUCCESS) 
            panic("tx_block_delete failed1");
    
        free(msg_hdr_pool_ptr);

        ret = tx_block_pool_delete(&usb_message_pool);
        if (ret != TX_SUCCESS)
            panic("tx_block_delete failed2");
    
        free(msg_pool_ptr);
        msg_hdr_pool_ptr = 0;
     }

}

//
// Select a channel
// @param channel Channel number: 1-14
//
void SetChannel (int channel)
{
    MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_RXEN,
                   MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);


    // Set frequency divider for channel
    WriteRF (1, freqTable[channel].integer);
    WriteRF (2, freqTable[channel].fraction);

    WriteRF (0, 0x25f9c); 
    naWifiWaitUS (10);
    WriteRF (0, 0x25f9a);
    naWifiWaitUS (80);
    WriteRF (0, 0x25f94);
    naWifiWaitUS (10);
 
    // HW_GEN_CONTROL |= GEN_RXEN;
    MacUsbWriteReg(HW_GEN_CONTROL, GEN_RXEN,
                   MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

	global_chan = channel;
}

int HWSetFilterAddress(MacAddr staAddr)
{
    /*
     * Multiple MACs are only supported on Piper and recent versions of the 
     * FPGA.
     */
    NA_UNUSED_PARAM(staAddr);
    panic("HWSetFilterAddress called on platform which only supports 1 MAC address.");
    return -1;
}



int wifi_num_set_bss=0;

//
// Set BSS mode and IDs
// @param bssCaps BSS capabilities, OR of CAP_xxx
// @param bssid ID of BSS to join or start
// @param ssid Service set ID
// @param ssid_len Service set ID length
// @param atim IBSS ATIM window size in TU
//
void SetBSS (int bssCaps, MacAddr bssid, uint8 *ssid, int ssid_len, uint16 basic, int atim)
{
        //__FIX_NULL_SSID_MEMORY_ACCESS == TRUE)
        unsigned char ssid_tmp[WLN_SSID_SIZE];
        int nr_ssid_bytes_to_output;
        
        if (ssid && ssid_len)
        {
                nr_ssid_bytes_to_output = ssid_len;
        }
        else
        {
                nr_ssid_bytes_to_output = 32;
                ssid_len = 0;
                memset( ssid_tmp, 0, sizeof(ssid_tmp) );
                ssid = &ssid_tmp[0];
        }
        
    wifi_num_set_bss++;

    // Set BSSID in hardware
    // HWMemcpy (&HW_BSSID0, bssid, WLN_ADDR_SIZE);
    MacUsbWriteData(HW_BSSID0, WLN_ADDR_SIZE, bssid);


    // HWMemcpy (&HW_SSID, ssid, ssid_len);
    //MacUsbWriteData(HW_SSID, ssid_len, ssid);
    //__FIX_NULL_SSID_MEMORY_ACCESS
    MacUsbWriteData(HW_SSID, nr_ssid_bytes_to_output, ssid);

    // Set SSID in hardware
    // HW_SSID_LEN = ssid_len;
    MacUsbWriteReg(HW_SSID_LEN, 
    ssid_len |
    ((basic & RATE_MASK_OFDM) << 20) |
    ((basic & (RATE_MASK_PSK|RATE_MASK_CCK)) << 16), 
     MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

    // IBSS mode
    if (bssCaps & CAP_IBSS)
    {
        // If starting IBSS, set beacon and ATIM intervals
        // HW_CFP_ATIM = atim | (BEACON_INT << 16);
        MacUsbWriteReg(HW_CFP_ATIM, atim | (BEACON_INT << 16), 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
 
        // Write beacon frame to beacon buffer
        if (bcnFrame)
        {
            // HW_GEN_CONTROL |= GEN_BEACEN;
            MacUsbWriteReg(HW_GEN_CONTROL, GEN_BEACEN, 
                           MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
                           
            HWWriteFifo (&bcnFrame->usb_status[2], 
                sizeof(FrameHeader) + sizeof(PlcpHeader) + bcnFrame->length - FCS_SIZE + 4, 1);

            // HW_GEN_CONTROL &= ~GEN_BEACEN;
            MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_BEACEN, 
                           MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);
        }

        // Set interrupt mask to enable TBTT and ATIM interrupts
        // HW_INTR_STATUS = INTR_TBTT|INTR_ATIM; // clear
        MacUsbWriteReg(HW_INTR_STATUS, INTR_TBTT|INTR_ATIM, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
 
        
        intrMask |= INTR_TBTT|INTR_ATIM;      // enable
        // HW_INTR_MASK = intrMask;
        MacUsbWriteReg(HW_INTR_MASK, intrMask, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

        
        // Enable IBSS mode, turn off HW AES decryption
        // HW_MAC_CONTROL |= CTRL_IBSS|CTRL_BEACONTX|CTRL_AES_DIS_ALL;
        MacUsbWriteReg(HW_MAC_CONTROL,   
                       CTRL_IBSS|CTRL_BEACONTX|CTRL_AES_DIS_ALL,
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

    }
    else // ESS mode
    {
        // Set interrupt mask to disable TBTT and ATIM interrupts
        intrMask &= ~(INTR_TBTT|INTR_ATIM); // disable
        // HW_INTR_MASK = intrMask;
        MacUsbWriteReg(HW_INTR_MASK, intrMask, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);


        // Disable IBSS mode
        // HW_MAC_CONTROL &= ~(CTRL_IBSS|CTRL_BEACONTX);
        MacUsbWriteReg(HW_MAC_CONTROL, ~(CTRL_IBSS|CTRL_BEACONTX), 
                           MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);
                           
        // Turn off HW AES decryption until a key is set
        // HW_MAC_CONTROL |= CTRL_AES_DIS_ALL;
        MacUsbWriteReg(HW_MAC_CONTROL, CTRL_AES_DIS_ALL,
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
    }
}


void SetPromiscuousMode(BOOLEAN enable)
{
    if (enable == TRUE)    // Enable PROMISC mode
    {
//	HW_MAC_CONTROL |= CTRL_PROMISC;
        MacUsbWriteReg(HW_MAC_CONTROL, CTRL_PROMISC, MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
    }
		
    else    //disable
    {
//	HW_MAC_CONTROL &= ~CTRL_PROMISC;
        MacUsbWriteReg(HW_MAC_CONTROL, ~CTRL_PROMISC, MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);
	}
}

//
// Set the link status LED
// @param on TRUE to turn LED on
//
void SetLED (BOOL on)
{
#ifndef NET_OS_SPECIFIC
    static BOOL lastLED = FALSE;
    BOOL led;

    // Set the link status LED
    GpioSetOutputValue (GPIO_WIFI_LINK_GREEN, on ? LED_ON : LED_OFF);
    
    // Turn on PCIe association LED if authenticated with WPA
    // or associated and not WPA
    led = (pSta->macStatus.state == WLN_ST_AUTH_ESS || 
           (pSta->macStatus.state >= WLN_ST_ASSOC_ESS && pSta->macStatus.wpa_info_len == 0));
    if (led != lastLED)
    {
        if (led)
            MacUsbWriteReg(HW_RSSI_AES, AES_LED, MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
        else
            MacUsbWriteReg(HW_RSSI_AES, ~AES_LED, MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);
        
        lastLED = led;
    }
        
    // Set signal strength LEDs if not used by cellular
#ifdef CELLULAR_ENABLED        
    if (RUNTIME_DISABLED(CELLULAR))
#endif
    {
#define NUM_LEDS    5

        // Scale signal strength average by number of samples
        int n = (pSta->macStatus.rx_signal + RSSI_SCALE/2) / RSSI_SCALE;
        
        // Get signal quality (0-100) and scale to 0 to NUM_LEDS.
        // 0 maps to no LEDs, 1 maps to 1 LED, 100 maps to NUM_LEDS.
        n = (NUM_LEDS*MacGetSignalQuality (n) + 99) / 100;
        NAIndicateSignalStrength (n);
    }
    
#else
    NA_UNUSED_PARAM(on);
#endif
}

//
// Set the link activity LED
// @param on TRUE to turn LED on
//
void SetActivityLED (BOOL on)
{
#ifndef NET_OS_SPECIFIC
    GpioSetOutputValue (GPIO_WIFI_ACT, on ? LED_ON : LED_OFF);
#else
    NA_UNUSED_PARAM(on);
#endif
}

//
// Transmit a frame
// This cannot be called from an ISR context
// @param buf Frame to transmit
// @param cw Contention window size, 0 if no backoff
// @param next Next expected event, one of SF_xxx
//
void MacSendFrame (MacBuffer *buf, int cw, int next)
{
    CcmpData  data;
    MacUsbMsg *msg_ptr;
    BOOL      last=1;
    BOOL      useAES;

    msg_ptr = MacUsbInitMsg();
    if (msg_ptr == (MacUsbMsg *)NULL) 
        return;
    

    if ((buf->macHdr.fc.type == TYPE_CTS) ||
        (buf->macHdr.fc.type == TYPE_RTS))
    {
        // For a MultiFrame transmission we write to 0x21/0x30
        // Instead of 0x20/0x30 for all but the last frame 
        last = 0;  
    }

    // Set backoff timer
    if (cw)
    {
        // Pick a random time up to cw, convert to usecs
        cw = 10*((int)wln_rand() & cw);
        if (buf->macHdr.fc.type == TYPE_BEACON)
        {
            // Beacon frame is already in beacon buffer.
            // Only set backoff timer here.
            //HW_BEACON_BO = cw;
            MacUsbWriteReg(HW_BEACON_BO, cw, 
                           MAC_COMPLETE_MSG, MAC_OP_WRITE, msg_ptr);

            // Simulate TxEnd
            HandleTxEnd();
            return;
        }
        else
        {
             // HW_BACKOFF = cw;
             MacUsbWriteReg(HW_BACKOFF, cw, 
                            MAC_CONTINUE_MSG, MAC_OP_WRITE, msg_ptr);

        }
    }
    
    // Use short preamble?
    if (USE_SHORTPRE (buf->tx_rate))
    {
        // HW_GEN_CONTROL |= GEN_SHPRE;
        MacUsbWriteReg(HW_GEN_CONTROL, GEN_SHPRE, 
                       MAC_CONTINUE_MSG, MAC_OP_OR, msg_ptr);


    }
    else
    {
        // HW_GEN_CONTROL &= ~GEN_SHPRE;
        MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_SHPRE, 
                       MAC_CONTINUE_MSG, MAC_OP_AND, msg_ptr);

    }
    
    // Use hardware AES if encrypted with AES 
    useAES = (hwAES && buf->macHdr.fc.protected && CcmpGetData (buf->macHdr.addr2, buf, &data));
    
    if (useAES)
    {
        if (next == SF_TXEND)
        {
            // HW_INTR_MASK |= INTR_TXEND; // enable
            MacUsbWriteReg(HW_INTR_MASK, INTR_TXEND, 
                           MAC_CONTINUE_MSG, MAC_OP_OR, msg_ptr);
        } 
        else
        {
            // HW_INTR_MASK &= ~INTR_TXEND; // disable
            MacUsbWriteReg(HW_INTR_MASK, ~INTR_TXEND, 
                           MAC_CONTINUE_MSG, MAC_OP_AND, msg_ptr);
        }
    }
    else
    {
        if (next == SF_TXEND)
        {
            // HW_INTR_MASK |= INTR_TXEND; // enable
            MacUsbWriteReg(HW_INTR_MASK, INTR_TXEND, 
                           MAC_COMPLETE_MSG, MAC_OP_OR, msg_ptr);
        } 
        else
        {
            // HW_INTR_MASK &= ~INTR_TXEND; // disable
            MacUsbWriteReg(HW_INTR_MASK, ~INTR_TXEND, 
                          MAC_COMPLETE_MSG, MAC_OP_AND, msg_ptr);
        }
    }

    if (useAES)
    {
        char *ptr;
        unsigned long aes_mode;
#ifdef NETOS_GNU_TOOLS
        static unsigned char buffer[2000] __attribute__ ((aligned(32)));
#else
#pragma alignvar (32)
        static unsigned char buffer[2000];
#endif
        aes_mode = (AES_MODE_BIT | (buf->body[3] >> 6));

        MacUsbWriteReg(HW_AES_CONTROL, aes_mode, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, msg_ptr);

        // Write frame headers to transmit FIFO (0x21)
        HWWriteAESHeaderFifo(&buf->usb_status[2], 40 + 4);

        ptr = (char *)(buffer+64);
        
        // We currently copy the plain text data because the IV and Key
        // MUST go before the body to be sent over USB, we can fix this
        // by allocating enough space before the body in the mac_buff
        // structure.
        memcpy(ptr, data.init, AES_INIT_DATA_LEN);
        ptr += AES_INIT_DATA_LEN;
       
        memcpy(ptr, buf->body+EXTIV_SIZE, buf->length-DATA_SIZE-CCMP_SIZE);

        // Write IV and data to HW_DATA_FIFO (0x20) 
        // or 0x21 if it's not the last frame.
        HWWriteAESFifo(buffer+60, 
                       AES_INIT_DATA_LEN +
                       buf->length - DATA_SIZE-CCMP_SIZE + 4, 1); 
    }
        
    else
    {
        // Write frame to transmit FIFO, excluding FCS
        // This has register writes pre-pended
        HWWriteFifo(&buf->usb_status[2],
        sizeof(FrameHeader) + sizeof(PlcpHeader) + buf->length - FCS_SIZE + 4, last);
    }


}

// Offset into Interrupt Packet (In 32 bit words)
#define  RX_FRAME_OFFSET 3 

// Interrupt Status - Gen Status 1 
#define IRQ_GEN_STATUS1_START_BIT    16


//
// Handle an interrupt request
//
// data contains the address of Status0 of the interrupt packet
//
int MacHandleIR (MacBuffer *buf, int len)
{
    uint32    intrStatus;
    MacUsbMsg *msg_ptr=(MacUsbMsg *)NULL; 
	epStatus *pSta = rootEndPoint[0];

    buf->length = len*4 - RX_FRAME_OFFSET*4;

    // Get the interrupt status (Gen Status 1)
    intrStatus = (buf->usb_status[0] >> IRQ_GEN_STATUS1_START_BIT);

    if (intrStatus == 0)
    {
        MacFreeBufferIR(buf);
        return 0;
    }

    // Handle errors
    if (intrStatus & (INTR_TIMEOUT|INTR_ABORT))
    {
        HandleMacError (intrStatus);

        if (msg_ptr != (MacUsbMsg *)NULL)
         intrStatus &= ~INTR_TXEND;
    }

    if (intrStatus & INTR_RXOVERRUN)
        macStats.rxDropOverrun++;

    // Handle beacon/ATIM timer
    if (intrStatus & (INTR_TBTT|INTR_ATIM))
        HandleBeacon (intrStatus & INTR_TBTT);

    // Transmit complete
    if (intrStatus & INTR_TXEND)
        HandleTxEnd();
            
    // Received a frame
    if (intrStatus & INTR_RXFIFO)
    {
        // Convert received signal strength to dbm
        int gain = lnaTable[buf->frameHdr.rx.rssiLNA] + 2*buf->frameHdr.rx.rssiVGA;
        if (gain > 96)
            buf->rx_signal = -98;
        else if (gain > 86)
            buf->rx_signal = gainTable[gain-87];
        else
            buf->rx_signal = 5-gain;
                
        // Add into average RSSI
        pSta->macStatus.rx_signal += buf->rx_signal - pSta->macStatus.rx_signal/RSSI_SCALE;

        // Process the frame
        HandleRxEnd (buf);
    }
    else
    {
        // Not a frame so free the macBuffer
        MacFreeBufferIR(buf);
    }

    return 0;
}

void MacClearTxEnd(void)
{
    //HW_INTR_STATUS = INTR_TXEND;
    MacUsbWriteReg(HW_INTR_STATUS, INTR_TXEND,
                   MAC_COMPLETE_MSG, MAC_OP_WRITE, 
                   (MacUsbMsg *)NULL);
}

//
// Get the complete frame that is being received
// @param buf Buffer to copy frame into, length field contains frame size
//
BOOL GetFrame (MacBuffer *buf)
{
    // All frames are alread in memory
    NA_UNUSED_PARAM(buf);

    return TRUE;
}

//
// Received frame is not needed, remove from FIFO
// @param length MAC frame size
// This can be called from an ISR
//
void DropFrame (int length)
{
    NA_UNUSED_PARAM(length);
}

void MacResetRxFifo(void)
{
    MacUsbMsg *msg_ptr=(MacUsbMsg *)NULL;

    msg_ptr = MacUsbInitMsg();
    if (msg_ptr != (MacUsbMsg *)NULL) 
    {
        MacUsbWriteReg(HW_GEN_CONTROL, GEN_RXFIFORST, 
                       MAC_CONTINUE_MSG, MAC_OP_OR, msg_ptr);
                       
        // HW_GEN_CONTROL &= ~GEN_RXFIFORST;
        MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_RXFIFORST, 
                       MAC_COMPLETE_MSG, MAC_OP_AND, msg_ptr);
    }
}

#ifdef NET_OS_SPECIFIC
//
// Public function to load the FPGA image
//
int InitWirelessHw(void)
{
	if (LoadHW() != ERR_OK)
		return 1;
	else
		return 0;
}

int getHardwareStrapping(void)
{
    return 0;
}

#endif

//
// Convert a received signal strength value in dbm
// to a percentage value (0-100).
//
int MacGetSignalQuality (int dbm)
{
    int n;
    
    if (dbm == 0)
        return 0;
        
// Useful RSSI range in dbm
#define RSSI_LOW    (-90)
#define RSSI_HIGH   (-30)

    n = 100*(dbm-RSSI_LOW)/(RSSI_HIGH-RSSI_LOW);
    if (n < 0)
        n = 0;
    else if (n > 100)
        n = 100;
       
    return n;
}

//
// This is used to set the transmit power.  
// Value is in dbm and will be limited to 0-15 dbm.
//
void MacSetTxPower (int value)
{
    epStatus *pSta = rootEndPoint[0];
    
    if (value < 0)
        value = 0;
    else if ((value > 10) && (macParams.band == WLN_BAND_B))
    	value = 10;
    else if (value > 15)
        value = 15;

    WriteRF (5, 0x19e40 | powerTable[value]);
    naDot11.currentTxPower = value;
    
    //update the status
    pSta->macStatus.tx_power = value;
}

//
// Get the FPGA hardware and firmware (MAC assist/DSP) version numbers
//
int MacGetVersion (uint16 *hw, uint16 *fw)
{
    *hw = MacReadReg32 (HW_VERSION);
    *fw = MacReadReg32 (HW_MAC_STATUS) >> 16;
    return 0;
}

//
// This function is used to put the mac driver in a quiet mode where
// no transmitting is done, but the FPGA is still running.  It is my
// hope that by disabling interrupts the FPGA will not do any automatic
// acking of received data.
//
void MacSetQuiet(int enable_quiet)
{
    int level;
	epStatus *pSta = rootEndPoint[0];

    /* disable interrupts */
    level = DISABLE();

    if (enable_quiet)
    {
        /* disable the mac driver */
        pSta->macStatus.state = WLN_ST_STOPPED;

        /* disable continuous transmit mode */ 
        MacUsbWriteReg(HW_GEN_STATUS, 0x30000000, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

        /* disable mac interrupts except for rx interrupts */
        MacUsbWriteReg(HW_INTR_MASK, INTR_RXFIFO, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
    }
    else
    {

        /* enable common mac interrupts */
        MacUsbWriteReg(HW_INTR_MASK,  
                       INTR_RXFIFO|INTR_TXEND|INTR_TIMEOUT|INTR_ABORT, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

        /* enable the mac driver */
        pSta->macStatus.state = WLN_ST_SCANNING;
        pSta->staState = SS_WAIT;
    }

    /* enable interrupts */
    ENABLE(level);
}

// This buffer is used as the transmit buffer for testing the
// continuous transmit FCC test.
static unsigned char fcc_txbuffer[64];
static unsigned char radio_txbuffer[1024];
static wln_bss bss_save = WLN_BSS_NONE;

//
// This function is used to fill the fcc_txbuffer with random data
// for the transmit test.
//
void MacUpdateFccBuffer(unsigned int transmit_mode, unsigned int transmit_rate)
{
    int i;

    switch (transmit_rate)
    {
    case 0:
        /* 1mpbs */
        fcc_txbuffer[4] = 0x00;
        fcc_txbuffer[5] = 0x10;                
        fcc_txbuffer[8] = 0x0a;
        break;

    case 1:
        /* 2mpbs */
        fcc_txbuffer[4] = 0x00;
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x14;
        break;

    case 2:
        /* 5.5mpbs */
        fcc_txbuffer[4] = 0x00;        
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x37;
        break;

    case 3:
        /* 11mpbs */
        fcc_txbuffer[4] = 0x00;
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x6e;
        break;

    /*OFDM */

    case 4:
        /* 6mpbs */
        fcc_txbuffer[4] = 0xEE;        
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0B;
        break;

    case 5:
        /* 9mpbs */
        fcc_txbuffer[4] = 0xEE;        
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0F;
        break;

    case 6:
        /* 12mpbs */
        fcc_txbuffer[4] = 0xEE;
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0A;
        break;
        
    case 7:
        /* 18mpbs */
        fcc_txbuffer[4] = 0xEE;
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0E;
        break;
        
    case 8:
        /* 24mpbs */
        fcc_txbuffer[4] = 0xEE;         
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x09;
        break;                

    case 9:
        /* 36mpbs */
        fcc_txbuffer[4] = 0xEE;        
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0D;
        break;
        
    case 10:
        /* 48mpbs */
        fcc_txbuffer[4] = 0xEE;        
        fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x08;
        break;
        
    case 11:
        /* 54mpbs */
        fcc_txbuffer[4] = 0xEE;
        fcc_txbuffer[5] = 0x10;         
        fcc_txbuffer[8] = 0x0C;
        break;                

    default:
        fcc_txbuffer[4] = 0x00; 
    	fcc_txbuffer[5] = 0x10; 
        fcc_txbuffer[8] = 0x0a;
        break;
    }

    if (transmit_mode == 4)
    {
        /* for fcc transmit 01 pattern */
        for (i=9; i < 64; i++)
        {
            fcc_txbuffer[i] = 0xaa;
        }
    }
    else
    {
        for (i=9; i < 64; i++)
        {
            fcc_txbuffer[i] = (unsigned char )rand();
        }
    }

    /* copy to transmit buffer */
    HWWriteFifo (&fcc_txbuffer, 16, TRUE);
}

//
// This function puts the driver into continuous transfer mode.  When doing
// so it attempts to shutdown normal driver functionality so the driver
// will not interfere with the continuous transfer.  However I do not think
// the process of shutting down the driver while enabling continous transfer
// mode is completely void of interference, but I think it will work well
// enough for FCC testing.
//
void MacContinuousTransmit(int enable, unsigned int transmit_mode, unsigned int transmit_rate)
{
    int level;
    uint32 data;
	epStatus *pSta = rootEndPoint[0];

      switch (transmit_mode)
    {
    case 0:
        /* random */
        data = 0x30100000;
        break;

    case 1:
        /* zeros */
        data = 0x30300000;
        //data = 0x30330000;  /*with scrambling and spreading disabled */   
        break;

    case 2:
        /* ones */
        data = 0x30500000;
        break;

    case 3:
        /* Unmodulated signal, carrier only, continuous
           transmit.  Used for Japan emmissions testing. */
        data = 0x30700000;
        //data = 0x30730000; /*with scrambling and spreading disabled */
        break;

    case 4:
        /* FCC - continuous transmit, scramble disable, 010101...*/
        data = 0x30100000;
        break;

    default:
        data = 0x30100000;
        break;
    }

    /* disable interrupts */
    level = DISABLE();

    if (enable)
    {
        /* disable the mac driver */
        pSta->macStatus.state = WLN_ST_STOPPED;
        bss_save = macParams.bss_type;
        macParams.bss_type = WLN_BSS_NONE;
	    pSta->staState = SS_WAIT;

        MacUpdateFccBuffer(transmit_mode, transmit_rate);

        /* disable mac interrupts */
        MacUsbWriteReg(HW_INTR_MASK, 0,
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

       // Disable IBSS mode
        MacUsbWriteReg(HW_MAC_CONTROL, ~(CTRL_IBSS|CTRL_BEACONTX), 
                           MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);

 
        if(3 == transmit_mode)
	  //enable test mode of operation
        MacUsbWriteReg(HW_GEN_CONTROL, GEN_TESTMODE, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

        /* set to continuous transmit */
        MacUsbWriteReg(HW_GEN_STATUS, data, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

        /* start transmiting */
        MacUsbWriteReg(HW_MAC_CONTROL, CTRL_TXREQ, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

    }
    else
    {
         /* disable continuous transmit */
        switch(transmit_mode)
        {
        	case 0:
                        MacUsbWriteReg(HW_GEN_STATUS, 0x30000000, 
                                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
        		break;

        	case 1:
                        MacUsbWriteReg(HW_GEN_STATUS, 0x30200000, 
                                     MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
        		break;

        	case 2:
                        MacUsbWriteReg(HW_GEN_STATUS, 0x30400000, 
                                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
        		break;
        		
        	case 3:
                        MacUsbWriteReg(HW_GEN_STATUS, 0x30000000, 
                                   MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);

                        MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_TESTMODE, 
                                  MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);
         		break;        		

        	case 4:
                         MacUsbWriteReg(HW_GEN_STATUS, 0x30000000, 
                                  MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
        		break;
        		        		
        	default:
                         MacUsbWriteReg(HW_GEN_STATUS, 0x30000000, 
                                  MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
        		break;	
        }
        
        macParams.bss_type = bss_save;
        pSta->staState = SS_WAIT;
        pSta->macStatus.state = WLN_ST_SCANNING;
      
        /* enable common mac interrupts */
        MacUsbWriteReg(HW_INTR_MASK,  
                       INTR_RXFIFO|INTR_TXEND|INTR_TIMEOUT|INTR_ABORT, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
     }

    /* enable interrupts */
    ENABLE (level);
}

void MacRadioPrepareTXBeacon(unsigned int tx_frame_period)
{
    if(tx_frame_period)
         /* 1-100 milliseconds */
        MacUsbWriteReg(HW_CFP_ATIM, (tx_frame_period << 16), 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
    else
        /* 0 = 20 msecs default tx frame period */
        MacUsbWriteReg(HW_CFP_ATIM, (20 << 16), 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
    
    /* enable beacon transmission */
    MacUsbWriteReg(HW_GEN_CONTROL, GEN_BEACEN, 
                           MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

}

/* Build a 1024/128 bytes frame. For WiWave, first word in the buffer is used for 
   a 4 bytes USB specific header. Shift everything by 4 bytes and adjust the 
   length upward */
void MacRadioTXRandomBuffer( unsigned int transmit_rate, unsigned int tx_frame_length)
{
    int i;

    /* TBD frame length of 128 bytes */
    //(void) tx_frame_length;

    switch (transmit_rate)
    {
    case 0:
        /* 1mpbs */
        
        /* modulation type = 0x00; no of ensuing 32bits words = 0x01 */
        radio_txbuffer[4] = 0x00;
        radio_txbuffer[5] = 0x01;        
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
        
        /*data rate identifier = 0x0a; length of 1,024 bytes frame in usecs = 0x2000 */
        radio_txbuffer[8] = 0x0a;        
        radio_txbuffer[9] = 0x04;

        if(!tx_frame_length)
	{
           radio_txbuffer[10] = 0x00;
           radio_txbuffer[11] = 0x20;
	}
	else
	{
           radio_txbuffer[10] = 0x00;
           radio_txbuffer[11] = 0x04;
        }
    
        break;

     case 1:
        /* 2mpbs */
        
        /* modulation type = 0x00; no of ensuing 32bits words = 0x01 */        
        radio_txbuffer[4] = 0x00;
        radio_txbuffer[5] = 0x01;        
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        
        
        /*data rate identifier = 0x14; length of 1,024 bytes frame in usecs = 0x1000 */        
        radio_txbuffer[8] = 0x14;
        radio_txbuffer[9] = 0x04;

        if(!tx_frame_length)
	{
          radio_txbuffer[10] = 0x00;
          radio_txbuffer[11] = 0x10;
	}
	else
	{
          radio_txbuffer[10] = 0x00;
          radio_txbuffer[11] = 0x02;
        }

        break;

    case 2:
        /* 5.5mpbs */
        
        /* modulation type = 0x00; no of ensuing 32bits words = 0x01 */
        radio_txbuffer[4] = 0x00;
        radio_txbuffer[5] = 0x01;        
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
        
        /*data rate identifier = 0x37; length of 1,024 bytes frame in usecs = 0x0661 */
        radio_txbuffer[8] = 0x37;
        radio_txbuffer[9] = 0x04;

        if(!tx_frame_length)
	{
          radio_txbuffer[10] = 0x61;
          radio_txbuffer[11] = 0x06;
	}
	else
	{
          radio_txbuffer[10] = 0xcc;
          radio_txbuffer[11] = 0x00;
	}

        break;

    case 3:
        /* 11mpbs */
        
        /* modulation type = 0x00; no of ensuing 32bits words = 0x01 */
        radio_txbuffer[4] = 0x00;
        radio_txbuffer[5] = 0x01;        
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
        
        /*data rate identifier = 0x6e; length of 1,024 bytes frame in usecs = 0x02e8 */        
        radio_txbuffer[8] = 0x6e;
        radio_txbuffer[9] = 0x04;

        if(!tx_frame_length)
	{
          radio_txbuffer[10] = 0xe8;
          radio_txbuffer[11] = 0x02;
	}
	else
	{
          radio_txbuffer[10] = 0x5d;
          radio_txbuffer[11] = 0x00;
	}

        break;

    /*OFDM */

    case 4:
        /* 6mpbs */
 
        /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;         
 
        /*data rate identifier = 0x0B; length of 1,024 bytes frame in bytes = 0x80 */       
        radio_txbuffer[8] = 0x0B;

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        

        break;

    case 5:
        /* 9mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        
        
        /*data rate identifier = 0x0F; length of 1,024 bytes frame in bytes = 0x80 */        
        radio_txbuffer[8] = 0x0F;
        
        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;

    case 6:
        /* 12mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        
        
        /*data rate identifier = 0x0A; length of 1,024 bytes frame in bytes = 0x80 */
        radio_txbuffer[8] = 0x0A;

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;
        
    case 7:
        /* 18mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
        
        /*data rate identifier = 0x0E; length of 1,024 bytes frame in bytes = 0x80 */
        radio_txbuffer[8] = 0x0E;

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;
        
    case 8:
        /* 24mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        

        /*data rate identifier = 0x09; length of 1,024 bytes frame in bytes = 0x80 */        
        radio_txbuffer[8] = 0x09;         

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;                

    case 9:
        /* 36mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        
        
        /*data rate identifier = 0x0D; length of 1,024 bytes frame in bytes = 0x80 */        
        radio_txbuffer[8] = 0x0d;        

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;
        
    case 10:
        /* 48mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;        
        
        /*data rate identifier = 0x08; length of 1,024 bytes frame in bytes = 0x80 */
        radio_txbuffer[8] = 0x08;        

        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;
        
    case 11:
        /* 54mpbs */
        
       /* modulation type = 0xEE; no of ensuing 32bits words = 0x01 */       
        radio_txbuffer[4] = 0xEE;        
        radio_txbuffer[5] = 0x01;
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
        
        /*data rate identifier = 0x0C; length of 1,024 bytes frame in bytes = 0x80 */
        radio_txbuffer[8] = 0x0c;
       
        if(!tx_frame_length)
          radio_txbuffer[9] = 0x80;   
	else
          radio_txbuffer[9] = 0x20;

        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x00;        
        break;


    default:
    	
    	  /* modulation type = 0x00; no of ensuing 32bits words = 0x01 */        
        radio_txbuffer[4] = 0x00;
        radio_txbuffer[5] = 0x01;        
        radio_txbuffer[6] = 0x00;
        radio_txbuffer[7] = 0x00;
    	
       /*data rate identifier = 0x0a; length of 1,024 bytes frame in usecs = 0x2000 */    	
        radio_txbuffer[8] = 0x0a;
        radio_txbuffer[9] = 0x04;
        radio_txbuffer[10] = 0x00;
        radio_txbuffer[11] = 0x20;
       break;
    }

    /* fill the rest of the frame with random data */
    for (i=12; i < 1023; i++)
    {
        radio_txbuffer[i] = (unsigned char )wln_rand();
    }

    /* copy 3 words of data to the transmit buffer, length in bytes! */
    HWWriteFifo (&radio_txbuffer, 8+4,TRUE);
}


void MacRadioTXBeacon(int enable, unsigned int transmit_rate, unsigned int tx_frame_period, unsigned int tx_frame_length)
{
    int level;
	epStatus *pSta = rootEndPoint[0];


    /* disable interrupts */
    level = DISABLE();

    if (enable)
    {
        /* disable the mac driver */
        bss_save = macParams.bss_type;
        macParams.bss_type = WLN_BSS_NONE;
		    pSta->staState = SS_WAIT;

	    MacRadioPrepareTXBeacon(tx_frame_period);

        MacRadioTXRandomBuffer(transmit_rate, tx_frame_length);


         /* disable mac interrupts */
        MacUsbWriteReg(HW_INTR_MASK, 0, 
                       MAC_COMPLETE_MSG, MAC_OP_WRITE, (MacUsbMsg *)NULL);
			  
        /* set ad-hoc mode of operation */
        MacUsbWriteReg(HW_MAC_CONTROL, CTRL_IBSS|CTRL_BEACONTX, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);
		  
    }
    else
    {
        MacUsbWriteReg(HW_MAC_CONTROL, ~(CTRL_IBSS|CTRL_BEACONTX), 
                       MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);


        MacUsbWriteReg(HW_GEN_CONTROL, ~GEN_BEACEN, 
                           MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);

        /* enable common mac interrupts */
        MacUsbWriteReg(HW_INTR_MASK,  
                       INTR_RXFIFO|INTR_TXEND|INTR_TIMEOUT|INTR_ABORT, 
                       MAC_COMPLETE_MSG, MAC_OP_OR, (MacUsbMsg *)NULL);

        macParams.bss_type = bss_save;
        pSta->staState = SS_WAIT;
    }

    /* enable interrupts */
    ENABLE (level);
}


// This function is used to put the mac driver in a quiet mode where
// no transmitting is done, but the FPGA is still running.  It is my
// hope that by disabling interrupts the FPGA will not do any automatic
// acking of received data.
//
void MacRadioRXTest(int enable, uint32* rx_frames)
{
    int level;
	epStatus *pSta = rootEndPoint[0];

    /* disable interrupts */
    level = DISABLE();

    if (enable)
    {

         /* disable the mac driver */
         bss_save = macParams.bss_type;
         macParams.bss_type = WLN_BSS_NONE;
		 pSta->staState = SS_WAIT;

         memset (&macStats, 0, sizeof macStats); 
                 
         SetPromiscuousMode(TRUE);   
         MacSetQuiet(1); 
     }
    else
    {
         SetPromiscuousMode(FALSE);
         *rx_frames = (uint32) macStats.rxFrames;
         
         MacSetQuiet(0);

        macParams.bss_type = bss_save;
        pSta->staState = SS_WAIT;
    }

    /* enable interrupts */
    ENABLE(level);
}

void MacWriteRF(uint8 addr, uint32 data)
{
   WriteRF (addr, data);
}

void MacReadRF(uint8 addr, uint32 *data)
{
  /* TBD */
   addr = addr;
  *data = *data;

#if 0
    uint8 data0;
    uint8 data1;
    uint8 data2;
    uint16 len = sizeof(uint8);

    addr &= ~SSI_ADDR_WR;

    HW_SSI_ADDR  = addr;
    naWifiWaitUS(50);
      
    data0 = HW_SSI_DATA0;
    data1 = HW_SSI_DATA1;
    data2 = HW_SSI_DATA2;

    *data = ((uint32)data0) | (((uint32)data1) << 8) | (((uint32)data2) << 16);
#endif

}

void MacWriteReg8(unsigned int offset, uint8 data)
{
    /* Not supported */
   //    REG8(offset) = data;

   (void) offset;
   (void) data;

}

uint8 MacReadReg8(unsigned int offset)
{
    /* Not supported */
   (void) offset;

#if 0
    uint8 data;

    data = REG8(offset);
    return data;
#endif
 
    return 0xFF;


}

void MacWriteReg16(unsigned int offset, uint16 data)
{
    REG16(offset) = data;
}


uint16 MacReadReg16(unsigned int offset)
{
    uint16 data;

    data = REG16(offset);
    return data;
}

void MacWriteReg32(unsigned int offset, uint32 data)
{

  MacUsbWriteReg((uint32)offset, (unsigned int)data, 
                   MAC_COMPLETE_MSG, 0, (MacUsbMsg *)NULL);
}


uint32 MacReadReg32(unsigned int offset)
{
    uint32 data = 0;
    
    if (MacUsbReadReg(offset, &data, sizeof data) != 0)
    {
        MAC_PRINTF(TRACE_CRITICAL, "MacUsbReadReg fails to read offset 0x%x\n", offset);
        return -1;
    }

    return data;
}



/*
 * Initialize a block of memory for a packet used to
 * send multiple messages in a single USB packet, in order to do this we need
 * to allocate a continous piece of memory.  This routine can not block and
 * may be called from an ISR context.
 *
 * Return NULL if no blocks are available.
 */
static MacUsbMsg *MacUsbInitMsg(void)
{
    MacUsbMsg    *msg_ptr;
    unsigned int ret;    

    /* 
     * Allocate a structure to keep track of the message ,this 
     * memory is freed when the message is sent
     */
    ret = tx_block_allocate(&usb_message_hdr_pool, (void **)&msg_ptr, TX_NO_WAIT);

    if (ret != TX_SUCCESS)
    {
       MAC_PRINTF(TRACE_CRITICAL, "MacUsbInitMsg no message headers\n");
       return (MacUsbMsg *)NULL;  
    } 
    memset(msg_ptr, 0, sizeof(MacUsbMsg)); 

    ret = tx_block_allocate(&usb_message_pool, (void **)&msg_ptr->start, TX_NO_WAIT);

    if (ret != TX_SUCCESS)
    {
       MAC_PRINTF(TRACE_CRITICAL, "MacUsbInitMsg no message headers\n");
       return (MacUsbMsg *)NULL;  
    } 

    return msg_ptr;
}

/*
 * Host to device write packets have the following format:
 * Bit 
 * 31:24    Packet ID
 * 23:22    (Operation, 0=MAC_OP_WRITE, 1=MAC_OP_AND, 2=MAC_OP_OR)
 * 21:15    Length MSB
 * 15:8     Length LSB
 * 7:0      ID^A5
 */
#define  WRITE_PACKET_ID  24
#define  WRITE_PACKET_OP  22 
#define  WRITE_PACKET_LEN 8 

/*
 * Routine used to write registers over USB, we try to fit as much into
 * one trasfer so we use a flag to indicate whether the message is
 * complete, in between or the end.
 */
int MacUsbWriteReg(uint32 reg, unsigned int data, 
               MacUsbMsgFlag flag, MacUsbOp op, MacUsbMsg *msg_ptr)
{
    int    bytesTransferred, errorCode, ret=0, len=2; 
    uint32 packet[2];
    
    if (flag == MAC_COMPLETE_MSG)
    {
        // We have a complete message
        if (msg_ptr == (MacUsbMsg *)NULL)
        {
            // This is not a multi-message packet
            packet[0] = (reg << WRITE_PACKET_ID)  |
                        (op  << WRITE_PACKET_OP)  |
                        (len << WRITE_PACKET_LEN) |
                        (reg^0x5A); 
                        
            packet[1] = data;
            usb_wifi_write((unsigned char *)&packet[0], 
                           sizeof packet, &bytesTransferred, 
                           &errorCode);
        }
        else
        {
            /* 
             * This is the end of multi-part message, add this message
             * to the end and send it out.
             */ 
             unsigned long *ptr_ulong;
             
             msg_ptr->len += len;
             
             ptr_ulong = msg_ptr->start + msg_ptr->offset;
                                         
             *ptr_ulong++ = (reg << WRITE_PACKET_ID)  |
                            (op  << WRITE_PACKET_OP)  |
                            (len << WRITE_PACKET_LEN) |
                            (reg^0x5A); 
             *ptr_ulong = (unsigned long)data;


            // The 'len' field is in 4 byte words. 
            usb_wifi_write((unsigned char *)msg_ptr->start, 
                           msg_ptr->len*4, &bytesTransferred, 
                           &errorCode);
                           
            ret = tx_block_release(msg_ptr->start);
            if (ret != TX_SUCCESS)
            {
                panic("tx_block_release failed1");
		        return -1;
            }

            ret = tx_block_release(msg_ptr);
            if (ret != TX_SUCCESS)
            {
                panic("tx_block_release failed");
		        return -1;
            }
         }
    
    }
    else if (((flag == MAC_START_MSG) || (flag == MAC_CONTINUE_MSG)) &&
             (msg_ptr != (MacUsbMsg *)NULL))
    {
        // Continiuation of an existing message, append to the end
        unsigned long *ptr_ulong;
             
        msg_ptr->len += len;
             
        ptr_ulong = msg_ptr->start + msg_ptr->offset; 
                                         
        msg_ptr->offset += len;
                                         
        *ptr_ulong++ = (reg << WRITE_PACKET_ID)  |
                       (op  << WRITE_PACKET_OP)  |
                       (len << WRITE_PACKET_LEN) |
                       (reg^0x5A); 
        *ptr_ulong = (unsigned long)data;
    }

    return ret;
}

// Add four bytes for the frame header word and four bytes for the packet header
#define MAC_DATA_OFFSET 8


/*
 * Routine used to write data over USB.
 * This is called while holding wln_tx_mutex
 */
static int MacUsbWriteData(uint8 reg, uint16 len, void *data)
{
    int           bytesTransferred, errorCode; 
    unsigned int *packet, ret=0;
    char         *buffer;

    // If no data, just return
    if (len == 0) 
    {
        return -1;
    }

    ret = tx_block_allocate(&usb_message_pool, (void **)&buffer, TX_NO_WAIT);
    if (ret != TX_SUCCESS)
    {
        panic("MacUsbMsg * tx_block_allocate failed");
        return -1;
    }

    memcpy(buffer+4, data, len);


    // len needs to be converted to a multiple of 32 bit words

    while (len % 4) 
    { 
       len++;
    }

    packet = (unsigned int *)buffer;

    len /= 4;  // convert to 32 bit words
    
    len += 1; // Add in the size of the packet header (one word)

    /* First send out the packet header */
    *packet++ = (reg << WRITE_PACKET_ID)  |
                (len << WRITE_PACKET_LEN) |
                (reg^0x5A); 
              
    ret = usb_wifi_write((unsigned char *)buffer, 
                         len*4, &bytesTransferred, 
                         &errorCode);
                   
    ret = tx_block_release(buffer);
    if (ret != TX_SUCCESS)
    {
       MAC_PRINTF(TRACE_CRITICAL, "tx_block_release failed [%d]\n", ret);
	   return -1;
    }

    return ret;
}

/*
 * Routine used to write data to a fifo over USB.
 * ***NOTE: The first four bytes of whats passed into this
 * routine is OVERWRITTEN with the packet header.
 * Pad the data pointer with four extra bytes.***
 *
 * Set block to one for a blocking write
 *
 * This is called while holding wln_tx_mutex
 *
 */
static int MacUsbWriteFifoData(uint8 reg, uint16 len, void *data, int block)
{
    int bytesTransferred, errorCode, ret=0; 
    unsigned int *packet;


    // len needs to be converted to a multiple of 32 bit words
    while (len % 4) 
    { 
       len++;
    }

    packet = (unsigned int *)data;  

    len /= 4; // Convert to 32-bit words
    
    /* Fill in the packet header */
    *packet = (reg << WRITE_PACKET_ID)  |
             (len << WRITE_PACKET_LEN) |
             (reg^0x5A); 
    if (block)          
    {
        ret = usb_wifi_write((unsigned char *)packet, 
                             len*4, &bytesTransferred, 
                             &errorCode);
    }
    else
    {
        ret = usb_wifi_write_async((unsigned char *)packet, 
                                   len*4, &bytesTransferred, 
                                   &errorCode, NULL, NULL);
    }
                   
    return ret;
}


//
// Register read functions.
// Only one read operation may be pending at a time.
//
static TX_MUTEX read_mutex;
static int read_mutex_created = 0;
static TX_EVENT_FLAGS_GROUP read_event;
static int read_event_created = 0;
static void *read_data;
static unsigned int read_length;

/*
 * Initialize register read functions
 */
static int mac_usb_read_req_init(void)
{
    int ret;
    
    read_data = NULL;

    /* With WPS and WCN UFD, we need to restart the wireless interface */
    /* but we don't need to recreate global THREADX objects, so use    */
    /* flags to track initialization state of global THREADX objects.  */
    if (!read_mutex_created)
    {
        ret = tx_mutex_create (&read_mutex, "Wireless read mutex", TX_NO_INHERIT);
        if (ret != TX_SUCCESS)
        {
            MAC_PRINTF (TRACE_CRITICAL, "mac_usb_read_req_init: tx_mutex_create fails %d\n", ret);
            return ret;
        }
        read_mutex_created = 1;
    }

    if (!read_event_created)
    {
        ret = tx_event_flags_create (&read_event, "Wireless read event");
        if (ret != TX_SUCCESS)
        {
            MAC_PRINTF (TRACE_CRITICAL, "mac_usb_read_req_init: tx_event_flags_create fails %d\n", ret);
            return ret;
        }
        read_event_created = 1;
    }

    return 0;
}

/*
 * Read data from a Wi-Wave register
 * Returns 0 if successful
 */
int MacUsbReadReg(uint8 reg, void *data, uint16 len)
{
    ULONG request[2], flags;
    int bytesTransferred, errorCode, ret;    

    // get read mutex
    // only one read request may be pending at a time
    ret = tx_mutex_get (&read_mutex, 2*NS_MILLISECONDS_TO_TICKS(MAC_USB_READ_TIMEOUT_MS));
    if (ret != TX_SUCCESS)
		            {
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReg: tx_get_mutex fails %d\n", ret);
        return -1;
            }
            
    // set response info
    read_data = data;
    read_length = len;
    len = (len+3)/4; // length in words

	        // format the READ REQUEST PACKET
    request[0] = (0xFD << WRITE_PACKET_ID) | (2 << WRITE_PACKET_LEN) | 0xA7;
    request[1] = (reg << WRITE_PACKET_ID) | (len << 16);
            
    // clear event flag
    ret = tx_event_flags_set (&read_event, 0, TX_AND);
    if (ret != TX_SUCCESS)
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReg: tx_event_flags_set fails %d\n", ret);
    
    // send request
    ret = usb_wifi_write ((unsigned char *)request, sizeof request,
                          &bytesTransferred, &errorCode);
    if (ret < 0)
    {
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReg: usb_wifi_write fails %d\n", errorCode);
        goto exit;
                }
        
    // wait for response
    ret = tx_event_flags_get (&read_event, 1, TX_OR_CLEAR, &flags, 
            NS_MILLISECONDS_TO_TICKS(MAC_USB_READ_TIMEOUT_MS));
    if (ret == TX_NO_EVENTS)
        {
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReg: no response\n");
        goto exit;
    }
    else if (ret != TX_SUCCESS) 
    {
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReg: tx_event_flags_get fails %d\n", ret);
        goto exit;
    }
    
    // complete
        ret = 0;

exit:
    read_data = NULL;
    tx_mutex_put (&read_mutex);

    return ret;
}    
	
/*
 * This function is called by WIFI class driver ISR when read response is received
 */
int MacUsbReadReqHandleResponse(unsigned long *data, unsigned int length)
{
    int ret;

    if (read_data == NULL)
        return -1;

    // set read_length to number of bytes to copy
    if (read_length > 4*length)
        read_length = 4*length;

    // copy data to user buffer
    memcpy (read_data, data, read_length);
    read_data = NULL;

    // set event
    ret = tx_event_flags_set (&read_event, 1, TX_OR);
    if (ret != TX_SUCCESS)
    {
        MAC_PRINTF(TRACE_DEBUG, "MacUsbReadReqHandleResponse: tx_event_flags_set fails %d\n", ret);
        return -1;
    }

    return 0;
}


/**
 * This function writes given data to EEPROM
 *
 * @external
 * @include "mac_api.h"
 * @category 
 * @since 7.2
 *
 * @param location  Location address of the EEPROM to be written
 * @param data      Pointer to data to be written to the EEPROM
 * @param length    Length of the data in bytes
 *
 * @return  -1      Error
 * @return  0       Data was successfully written to the EEPROM
 * 
**/
int MacUsbWriteEEPROM(unsigned int location, char *data, uint16 length)
{
#define _MAC_4_BYTE_WRITE   4

    int     ret = 0, i, j;
    unsigned int startAddr, endAddr;
    unsigned int rValue, dataValue;
    unsigned int *dataPtr;
    char        *destPtr, *srcPtr;

    uint8   sRemainBytes, eRemainBytes;
    uint16  rLength;

    if (data == NULL || length == 0)
    {
        MAC_PRINTF(TRACE_WARNING, "MacUsbWriteEEPROM: invalid given parameters\n");
        ret = -1;
        goto _ret;
    }

    /* if the eeprom location is not in 4-byte boundry,
     * we need to calculate number of bytes that we
     * need to skip.
     */
    sRemainBytes = (location % _MAC_4_BYTE_WRITE);
    eRemainBytes = _MAC_4_BYTE_WRITE;

    /* get the eeprom location */        
    startAddr = location - sRemainBytes;
    endAddr = location + length;

    for (i=0; startAddr < endAddr; startAddr += _MAC_4_BYTE_WRITE)
    {
        /* get user's data */
        dataPtr = (unsigned int *)&dataValue;

        destPtr = (char *)&dataValue;
        srcPtr = (char *)(data + i);

        for (j=0; j < (eRemainBytes - sRemainBytes); j++)
        {
            *(destPtr+j) = *(srcPtr+j);
        }

        /* Write EEPROM Control for EEPROM location */
        if (MacUsbWriteReg(HW_EEPROM_CONTROL, startAddr, MAC_COMPLETE_MSG, MAC_OP_WRITE, NULL) != 0)
        {
            MAC_PRINTF(TRACE_CRITICAL, "MacUsbWriteEEPROM: MacUsbWriteReg fails to write EEPROM CONTROL\n");
            ret = -1;
            goto _ret;
        }

        tx_thread_sleep(NS_MILLISECONDS_TO_TICKS(MAC_USB_EEPROM_ACCESS_MS));

        if ((endAddr - startAddr) < _MAC_4_BYTE_WRITE)
        {
            sRemainBytes = 0;
            eRemainBytes = (uint8)(endAddr - startAddr);
        }

        if ((eRemainBytes - sRemainBytes) < _MAC_4_BYTE_WRITE)
        {
            rLength = sizeof rValue;
            if (MacUsbReadReg(HW_EEPROM_DATA, (void *)&rValue, rLength) != 0)
            {
                MAC_PRINTF(TRACE_CRITICAL, "MacUsbWriteEEPROM: MacUsbWriteReg fails to Read EEPROM Data\n");
                ret = -1;
                goto _ret;
            }

            /* skip the bytes */
            destPtr = (char *)&rValue;
            srcPtr = (char *)dataPtr;

            /* copy the remain bytes */
            for (j=sRemainBytes; j<eRemainBytes; j++)
            {
                *(destPtr+j) = *srcPtr;
                srcPtr++;
            }
            dataPtr = &rValue;

            i += (eRemainBytes - sRemainBytes);

            sRemainBytes = 0;
            eRemainBytes = _MAC_4_BYTE_WRITE;
        }
        else
        {
            i += _MAC_4_BYTE_WRITE;
        }

        /* Write EEPROM Data for actual data */
        if (MacUsbWriteReg(HW_EEPROM_DATA, *dataPtr, MAC_COMPLETE_MSG, MAC_OP_WRITE, NULL) != 0)
        {
            MAC_PRINTF(TRACE_CRITICAL, "MacUsbWriteEEPROM: MacUsbWriteReg fails to write EEPROM Data\n");
            ret = -1;
            goto _ret;
        }

        tx_thread_sleep(NS_MILLISECONDS_TO_TICKS(MAC_USB_EEPROM_ACCESS_MS));

    }

_ret:
    return ret;
}


/**
 * This function reads data from EEPROM
 *
 * @external
 * @include "mac_api.h"
 * @category 
 * @since 7.2
 *
 * @param location  Location address of the EEPROM to be read
 * @param data      Pointer to memory where data will be written to
 * @param length    Size of the data in bytes
 *
 * @return  -1      Error
 * @return  0       Data was successfully obtained from the EEPROM
**/
int MacUsbReadEEPROM(unsigned int location, char *data, uint16 length)
{
    int ret = 0;
    unsigned int eepromAddr;

    if (data == NULL || length == 0)
    {
        MAC_PRINTF(TRACE_WARNING, "MacUsbWriteEEPROM: invalid given parameters\n");
        ret = -1;
        goto _ret;
    }

    /* Write EEPROM Control for EEPROM location */
    eepromAddr = location;

    if (MacUsbWriteReg(HW_EEPROM_CONTROL, eepromAddr, MAC_COMPLETE_MSG, MAC_OP_WRITE, NULL) != 0)
    {
        MAC_PRINTF(TRACE_CRITICAL, "MacUsbReadEEPROM fails to write EEPROM Control\n");
        ret = -1;
        goto _ret;
    }

    tx_thread_sleep(NS_MILLISECONDS_TO_TICKS(MAC_USB_EEPROM_ACCESS_MS));

    /* Read EEPROM Data */
    if (MacUsbReadReg(HW_EEPROM_DATA, (void *)data, length) != 0)
    {
        MAC_PRINTF(TRACE_CRITICAL, "MacUsbReadEEPROM fails to read EEPROM Data\n");
        ret = -1;
        goto _ret;
    }

_ret:
    return ret;
}

// Load a key to the WiWave 
void SetAESKey(int id, AES_KEY *key)
{
    unsigned long val;
//    unsigned int  len = sizeof(AES_KEY);
#ifdef NETOS_GNU_TOOLS
    static uint8 buf[512]  __attribute__ ((aligned(32)));
#else
#pragma alignvar (32)
    static uint8 buf[512];
#endif

    if (hwAES)
    {
        // Enable HW AES decryption and this AES key.
        // Other keys may remain disabled to support mixed mode (TKIP+AES).
        // HW_MAC_CONTROL &= ~(CTRL_AES_DISABLE | (CTRL_KEY0_DIS << id));
        MacUsbWriteReg(HW_MAC_CONTROL, ~(CTRL_AES_DISABLE | (CTRL_KEY0_DIS << id)),
                           MAC_COMPLETE_MSG, MAC_OP_AND, (MacUsbMsg *)NULL);

        // Select mode 1, load AES key
        val = AES_MODE_BIT | AES_KEY_LOAD_BIT | id;

        MacUsbWriteReg(HW_AES_CONTROL, val, 
                      MAC_COMPLETE_MSG, MAC_OP_WRITE,
                      (MacUsbMsg *)NULL);

        // Write plaintext key, IV and data to HW_AES_FIFO_END (0x30) 
        memcpy(&buf[16], key, 4*44+4);
        HWWriteAESFifo(&buf[16], 4*44+4, 1); 
    }
}
#endif 
