/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/*
 * Hardware interface routines for the Asix AX88772 USB to 10/100
 * Ethernet/HomePNA Controller chip
 *
 * all of the AX88772-specific routines are located here
 *
 * To Do list --
 * 1.
 *
 * 
 * Notes --
 * 1. the AX88772 chip has a feature to allow a zero-length packet
 *    to be sent in response to a bulk read request.  This feature
 *    is used to force any outstanding bulk reads to be completed
 *    prior to shutting down the packet receive thread.  However,
 *    when the USB (ohci) driver receives the zero-length packet
 *    it erroneously reports it as an error (saying the the USB
 *    device is not responding).  The author of the ohci driver
 *    agrees that the zero-length packet is not a sign of a true
 *    error in this case, and that it is therefore safe to dis-
 *    regard the message reported/displayed by the USB (ohci)
 *    driver.
 *
 */

#include <ios.h>
#include <ioslibc.h>
#include <iosusb.h>
#include <iop_netif.h>

#include "ax.h"
#include "ax_defs.h"

#define AX_LARGE_BUFFER 1

/* debugging macros */
#ifdef AX_DEBUG
#define AX_LOG(...) printf("AX: " __VA_ARGS__)
#define AX_LOG_CONT(...) printf(__VA_ARGS__)
#define AX_ERROR(...) printf("AX: Error: " __VA_ARGS__)
#else
#define AX_LOG(...)
#define AX_LOG_CONT(...)
#ifdef AX_DEBUG_ERROR
#define AX_ERROR(...) printf("AX: Error: " __VA_ARGS__)
#else
#define AX_ERROR(...) /* printf("AX: Error: " __VA_ARGS__) */
#endif
#endif

#if defined(AX_DEBUG) || defined(AX_DUMP_STATE)
static char *phyRegName[] = {
    "BMCR", "BMSR", "PHYIDR1", "PHYIDR2", "ANAR", "ANLPAR", "ANER", "RESERVED",
    "IEEE_Reserved", "IEEE_Reserved", "IEEE_Reserved", "IEEE_Reserved",
    "IEEE_Reserved", "IEEE_Reserved", "IEEE_Reserved", "IEEE_Reserved"
};
#endif

/*
 * receive packet buffer size
 */
#ifdef AX_LARGE_BUFFER
#define AX_MFB_SIZE  16384 /* must match RX Control Register setting */
#else
#define AX_MFB_SIZE  2048 /* must match RX Control Register setting */
#endif
extern u32 ethDevMFBSize;

/*
 * receive packet buffer size
 */
#define AX_MAX_RETRY  10 /* max allowable retries when opening ohci RM */

/*
 * little-endian to big-endian conversion, since USB data transfer is
 * all little-endian but driver code is big-endian
 */
#define SWAP16(val) \
    ((u16)( \
            (((u16)(val) & (u16)0x00ffUL) << 8) | \
            (((u16)(val) & (u16)0xff00) >> 8) ))


#ifdef AX_LARGE_BUFFER
/*
 * recv buffer
 */
static int sAlloced = FALSE;
static u8 sRecvBuff[AX_MFB_SIZE] __attribute__((aligned(32)));;
#endif

/*
 * private routines for accessing ASIX hardware
 */

static s32
axWriteSoftwareSerialManagementControlRegister(IOSFd dev)
{
    s32 status;
    
    AX_LOG("%s: entry\n", __FUNCTION__);
    status = IUSB_WriteCtrlMsg(dev, 0x40, 0x06, 0x0000, 0, 0, 0);
    return status;
}

static s32
axReadSerialManagementStatusRegister(IOSFd dev, u8 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_ReadCtrlMsg(dev, 0xc0, 0x09, 0x0000, 0x0000, 1, data);
}

static s32
axWriteHardwareSerialManagementControlRegister(IOSFd dev)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x0a, 0x0000, 0x0000, 0, 0);
}

static s32
axLockAccessToPhy(IOSFd dev)
{
    s32 status;
    u8 ownership;
    s32 i;
    
    AX_LOG("%s: entry\n", __FUNCTION__);
    if ( (status = axWriteSoftwareSerialManagementControlRegister(dev)) < 0 ) {
        AX_ERROR("%s: can't read Software Serial Management Control Register, status = %d\n",
                 __FUNCTION__, status);
        goto out;
    }

    for (i=0; i<100; i++) {
        status = axReadSerialManagementStatusRegister(dev, &ownership);
        if( status < 0) {
            AX_ERROR("%s: can't read Serial Management Status Register, status = %d\n",
                     __FUNCTION__, status);
            goto out;
        }
        if (ownership & AX88772_SERIAL_REG_HOSTEN)
            break;
    }
    
    if ( (ownership & AX88772_SERIAL_REG_HOSTEN) == 0) {
        AX_ERROR("%s: can't get PHY ownership, status = %d\n", __FUNCTION__, status);
        status = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    status = IOS_ERROR_OK;
    
out:
    return status;
}

static s32
axUnlockAccessToPhy(IOSFd dev)
{
    s32 status;
    u8 ownership;
    s32 i;
	
    AX_LOG("%s: entry\n", __FUNCTION__);
    if ( (status = axWriteHardwareSerialManagementControlRegister(dev)) < 0 ) {
        AX_ERROR("%s: can't read Hardware Serial Management Control Register, status = %d\n",
                 __FUNCTION__, status);
        goto out;
    }

    for (i=0; i<100; i++) {
        status = axReadSerialManagementStatusRegister(dev, &ownership);
        if( status < 0) {
            AX_ERROR("%s: can't read Serial Management Status Register, status = %d\n",
                     __FUNCTION__, status);
            goto out;
        }
        if ( (ownership & AX88772_SERIAL_REG_HOSTEN) == 0)
            break;
    }
    
    if (ownership & AX88772_SERIAL_REG_HOSTEN) {
        AX_ERROR("%s: can't release PHY ownership, status = %d\n", __FUNCTION__, status);
        status = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    status = IOS_ERROR_OK;
    
out:
    return status;
}

static s32
axReadPHYRegister(IOSFd dev, u16 phy, u16 reg, u16 *data)
{
    s32 status;

    AX_LOG("%s: entry\n", __FUNCTION__);
    AX_LOG("%s: reg %s (%d)\n", __FUNCTION__, phyRegName[reg], reg);
    if ( (status = axLockAccessToPhy(dev)) < 0 ) {
        return status;
    }
    status = IUSB_ReadCtrlMsg(dev, 0xc0, 0x07, phy, reg, 2, (u8 *)data);
    *data = SWAP16(*data);
    AX_LOG("%s: reg %s (%d) = 0x%x\n", __FUNCTION__, phyRegName[reg], reg, *data);
    return axUnlockAccessToPhy(dev);
}

static s32
axWritePHYRegister(IOSFd dev, u16 phy, u16 reg, u16 *data)
{
    s32 status;
    
    AX_LOG("%s: reg %s (%d), data %x\n", __FUNCTION__, phyRegName[reg], reg, *data);
    if ( (status = axLockAccessToPhy(dev)) < 0 ) {
        AX_ERROR("%s: unable to lock access to PHY, status = %d\n",
                 __FUNCTION__, status);
        goto out;
    }
    *data = SWAP16(*data);
    if ( (status = IUSB_WriteCtrlMsg(dev, 0x40, 0x08, phy, reg, 2, (u8 *)data)) < 0 ) {
        AX_ERROR("%s: unable to write PHY register, status = %d\n",
                 __FUNCTION__, status);
        goto out;
    }
    *data = SWAP16(*data);
    if ( (status = axUnlockAccessToPhy(dev)) < 0 ) {
        AX_ERROR("%s: unable to unlock access to PHY, status = %d\n",
                 __FUNCTION__, status);
        goto out;
    }
out:
    return status;
}

static s32
axReadSROMRegister(IOSFd dev, u16 i, u8 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    s32 status = IUSB_ReadCtrlMsg(dev, 0xc0, 0x0b, i, 0x0000, 2, data);
    return status;
    
}

static s32
axReadRxControlRegister(IOSFd dev, u16 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    s32 status = IUSB_ReadCtrlMsg(dev, 0xc0, 0x0f, 0x0000, 0x0000, 2, (u8 *)data);
    *data = SWAP16(*data);
    AX_LOG("%s: data = 0x%x\n", __FUNCTION__, *data);
    return status;
}

static s32
axWriteRxControlRegister(IOSFd dev, u16 i)
{
    AX_LOG("%s: entry, i=0x%x\n", __FUNCTION__, i);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x10, i, 0x0000, 0, 0);
}

#ifdef AX_DUMP_STATE
static s32
axReadMulticastFilterArrayRegister(IOSFd dev, u8 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_ReadCtrlMsg(dev, 0xc0, 0x15, 0x0000, 0x0000, 8, data);
}
#endif

static s32
axWriteMulticastFilterArrayRegister(IOSFd dev, u8 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x16, 0x0000, 0x0000, 8, data);
}

static s32
axReadMediumStatusRegister(IOSFd dev, u16 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    s32 status = IUSB_ReadCtrlMsg(dev, 0xc0, 0x1a, 0x0000, 0x0000, 2, (u8 *)data);
    *data = SWAP16(*data);
    return status;
}

static s32
axWriteMediumModeRegister(IOSFd dev, u16 i)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x1b, i, 0x0000, 0, 0);
}

static s32
axReadMonitorModeStatusRegister(IOSFd dev, u8 *data)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_ReadCtrlMsg(dev, 0xc0, 0x1c, 0x0000, 0x0000, 1, data);
}

static s32
axWriteMonitorModeRegister(IOSFd dev, u16 i)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x1d, i, 0x0000, 0, 0);
}

static s32
axWriteSoftwareResetRegister(IOSFd dev, u16 i)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x20, i, 0x0000, 0, 0);
}

#if defined(AX_DEBUG) || defined(AX_DUMP_STATE)
static s32
axReadSoftwarePHYSelectStatusRegister(IOSFd dev, u16 i, u8 *data )
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_ReadCtrlMsg(dev, 0xc0, 0x21, i, 0x0000, 1, data);
}
#endif

static s32
axWriteSoftwarePHYSelectRegister(IOSFd dev, u16 i)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    return IUSB_WriteCtrlMsg(dev, 0x40, 0x22, i, 0x0000, 0, 0);
}

static s32
axReadEEProm(IOSFd dev, u16 *data)
{
    s32 status;
    int i;
    AX_LOG("%s: entry\n", __FUNCTION__);
    for (i=0; i<sizeof(AX88772_EEProm)/sizeof(u16); i++) {
        if ( (status = axReadSROMRegister(dev, i, (u8 *)data))< 0 ) {
            AX_ERROR("%s: i=%d failed with status = %d\n", __FUNCTION__,
                     i, status);
            goto out;
        }
        *data = SWAP16(*data);
        AX_LOG("%s: eeprom[0x%02x] = 0x%04x\n", __FUNCTION__, i, *data);
        *data = SWAP16(*data);
        data++;
    }
    status = 0;
out:
    return status;
}

static s32
axReadInterruptEndPoint(IOSFd dev, u8 *data)
{
    s32 status;

    AX_LOG("%s: entry\n", __FUNCTION__);
    status = IUSB_ReadIntrMsg(dev, 0x81, 8, data);
    AX_LOG("%s: intr msg = %x:%x:%x:%x:%x:%x:%x:%x, status = %d\n",
           __FUNCTION__,
           data[0], data[1], data[2], data[3],
           data[4], data[5], data[6], data[7],
           status);
    
    return status;
}

/*
 * axSetLinkConfig -- configure ethernet link as requested by the
 * supplied NETEthTool structure
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axSetLinkConfig(AsixInfo *ai, NETEthTool *pLink)
{
    IOSError rv;
    u16 bmcr, anar;

    IOSFd dev = ai->usbFd;
    u16 phy = ai->eeprom.primaryPhyType;

    AX_LOG("%s: entry, phy = %d (0x%x)\n", __FUNCTION__, phy, phy);

    /* update advertised capabilities */
    if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_ANAR, &anar)) < 0 ) {
        AX_ERROR("%s: unable to read ANAR register, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    if ( pLink->advertising & NET_SUPPORTED_100BASET_FULL )
        anar |= AX88772_PHY_REG_ANALPAR_100_FD;
    else
        anar &= ~AX88772_PHY_REG_ANALPAR_100_FD;

    if ( pLink->advertising & NET_SUPPORTED_100BASET_HALF )
        anar |= AX88772_PHY_REG_ANALPAR_100_HD;
    else
        anar &= ~AX88772_PHY_REG_ANALPAR_100_HD;

    if ( pLink->advertising & NET_SUPPORTED_10BASET_FULL )
        anar |= AX88772_PHY_REG_ANALPAR_10_FD;
    else
        anar &= ~AX88772_PHY_REG_ANALPAR_10_FD;

    if ( pLink->advertising & NET_SUPPORTED_10BASET_HALF )
        anar |= AX88772_PHY_REG_ANALPAR_10_HD;
    else
        anar &= ~AX88772_PHY_REG_ANALPAR_10_HD;

    if ( (rv = axWritePHYRegister(dev, phy, AX88772_PHY_REG_ANAR, &anar)) < 0 ) {
        AX_ERROR("%s: unable to update auto-negotiation advertisement, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* perform auto or manual link configuration */

    if( pLink->autoneg & NET_AUTONEG_ENABLE ) {

        /* enable auto-negotiation */
        AX_LOG("%s: enabling auto-negotiation\n", __FUNCTION__);

        if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_BMCR, &bmcr)) < 0 ) {
            AX_ERROR("%s: unable to read BMCR register #1, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }

        bmcr |= AX88772_PHY_REG_BMCR_AN_ENABLE; /* enable AN */
        bmcr |= AX88772_PHY_REG_BMCR_RST_AN; /* restart AN */

        if ( (rv = axWritePHYRegister(dev, phy, AX88772_PHY_REG_BMCR, &bmcr)) <
0 ) {
            
            AX_ERROR("%s: unable to enable auto-negotiation, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }

    } else {

        /* configure link without auto-negotiation */

        AX_LOG("%s: configuring link without auto-negotiation\n", __FUNCTION__);

        if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_BMCR, &bmcr)) < 0 ) {
            AX_ERROR("%s: unable to read BMCR register #4, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }

        AX_LOG("%s: setting speed = %d Mbit/sec\n", __FUNCTION__,
               pLink->speed == NET_SPEED_100 ? 100 : 10);

        if (pLink->speed == NET_SPEED_100)
            bmcr |= AX88772_PHY_REG_BMCR_SPEED;
        else
            bmcr &= ~AX88772_PHY_REG_BMCR_SPEED;

        AX_LOG("%s: setting duplex = %s\n", __FUNCTION__,
               pLink->duplex == NET_DUPLEX_FULL ? "full" : "half");

        if (pLink->duplex==NET_DUPLEX_FULL)
            bmcr |= AX88772_PHY_REG_BMCR_DUPLEX;
        else
            bmcr &= ~AX88772_PHY_REG_BMCR_DUPLEX;

        bmcr &= ~AX88772_PHY_REG_BMCR_AN_ENABLE; /* disable auto-negotiation */

        if ( (rv = axWritePHYRegister(dev, phy, AX88772_PHY_REG_BMCR, &bmcr)) < 0 ) {
            AX_ERROR("%s: unable to write BMCR register, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }

    }

    rv = IOS_ERROR_OK;

out:
    return rv;
}

/*
 * axGetLinkInfo -- query the mac/phy to obtain information
 * about the link and then populate the NETEthTool structure
 *
 * return IOS_ERROR_OK on success, else an error code
 */
static IOSError
axGetLinkInfo(IOSFd dev, u16 phy, NETEthTool *linkInfo)
{
    IOSError rv;
    u16 bmcr, bmsr, anar;
    
    if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_BMCR, &bmcr)) < 0 ) {
        AX_ERROR("%s: unable to read BMCR register, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    if ( bmcr & AX88772_PHY_REG_BMCR_SPEED )
        linkInfo->speed = NET_SPEED_100;
    else
        linkInfo->speed = NET_SPEED_10;

    if ( bmcr & AX88772_PHY_REG_BMCR_AN_ENABLE )
        linkInfo->autoneg = NET_AUTONEG_ENABLE;
    else
        linkInfo->autoneg = NET_AUTONEG_DISABLE;

    if ( bmcr & AX88772_PHY_REG_BMCR_DUPLEX )
        linkInfo->duplex = NET_DUPLEX_FULL;
    else
        linkInfo->duplex = NET_DUPLEX_HALF;

    if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_BMSR, &bmsr)) < 0 ) {
        AX_ERROR("%s: unable to read BMSR register, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    linkInfo->supported = 0x0;
    
    if ( bmsr & AX88772_PHY_REG_BMSR_AN_CAPABLE )
        linkInfo->supported |= NET_SUPPORTED_AUTONEG;

    if ( bmsr & AX88772_PHY_REG_BMSR_100_FULL )
        linkInfo->supported |= NET_SUPPORTED_100BASET_FULL;

    if ( bmsr & AX88772_PHY_REG_BMSR_100_HALF )
        linkInfo->supported |= NET_SUPPORTED_100BASET_HALF;

    if ( bmsr & AX88772_PHY_REG_BMSR_10_FULL )
        linkInfo->supported |= NET_SUPPORTED_10BASET_FULL;

    if ( bmsr & AX88772_PHY_REG_BMSR_10_HALF )
        linkInfo->supported |= NET_SUPPORTED_10BASET_HALF;

    if ( (rv = axReadPHYRegister(dev, phy, AX88772_PHY_REG_ANAR, &anar)) < 0 ) {
        AX_ERROR("%s: unable to read ANAR register, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    linkInfo->advertising = 0x0;
    
    if ( bmcr & AX88772_PHY_REG_BMCR_AN_ENABLE )
        linkInfo->advertising |= NET_SUPPORTED_AUTONEG;

    if ( anar & AX88772_PHY_REG_ANALPAR_100_FD )
        linkInfo->advertising |= NET_SUPPORTED_100BASET_FULL;

    if ( anar & AX88772_PHY_REG_ANALPAR_100_HD )
        linkInfo->advertising |= NET_SUPPORTED_100BASET_HALF;

    if ( anar & AX88772_PHY_REG_ANALPAR_10_FD )
        linkInfo->advertising |= NET_SUPPORTED_10BASET_FULL;

    if ( anar & AX88772_PHY_REG_ANALPAR_10_HD )
        linkInfo->advertising |= NET_SUPPORTED_10BASET_HALF;

    rv = IOS_ERROR_OK;
    
out:
    return rv;
}

/*
 * crc32 -- standard crc32 calculation
 *
 * see "A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS"
 * by Ross N. Williams (available widely on the net)
 *
 * Note that this is a reflected algorithms and the result is
 * also reflected.  The reflected algorithm is used because 803.2
 * transmits the least-significant bit (lsb) of the stream first,
 * so when computing the CRC each byte is processed from lsb to
 * msb.
 */

static u32
crc32(u8 *data, int nb)
{
    u32 poly = 0xedb88320; /* this is the reflected version of 0x04c11db7 */
    u32 crc;
    u8 crc_lsb;
    
    int i, j;

    crc = 0xffffffff;

    for ( i=0; i<nb; i++ ) {
        for ( j=0x01; j<=0x80; j<<=1 ) {
            crc_lsb = crc & 0x1;
            crc >>= 1;
            if ( data[i] & j )
                crc_lsb ^= 0x1;
            if ( crc_lsb )
                crc ^= poly;
        }
    }
    
    crc ^= 0xffffffff;
    
    return crc;
}

/*
 * axPrintReg -- print a register's value to stdout
 */
#ifdef AX_DUMP_STATE
static void
axPrintReg(char *name, u8 *data, u32 len)
{
    s32 i;

    AX_LOG("%s: %s = ", __FUNCTION__, name);
    if ( !len ) {
        AX_LOG_CONT("<zero length>\n");
    } else {
        if ( len == 2 )
            *((u16 *)data) = SWAP16(*((u16 *)data));
        for (i=0; i<len-1; i++) {
            AX_LOG_CONT("%02x:", data[i]);
        }
        AX_LOG_CONT("%02x\n", data[len-1]);
        if ( len == 2 )
            *data = SWAP16(*data);
    }
}
#endif

/*
 * axPrintState -- read and print current register settings of ASIX chip
 */
#ifdef AX_DUMP_STATE
static void
axPrintState(AsixInfo *ai, const char *msg)
{
    IOSError rv;
    u8 data[8];
    IOSFd dev = ai->usbFd;
    u16 phy =ai->eeprom.primaryPhyType;
        
    AX_LOG("%s: %s\n", __FUNCTION__, msg);
    AX_LOG("%s: reading USB registers\n", __FUNCTION__);

    if ( (rv = axReadSerialManagementStatusRegister(dev, data)) < 0 )
        AX_LOG("%s: error reading SerialManagementStatus register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("SerialManagementStatus", data, 1);
    
    if ( (rv = axReadRxControlRegister(dev, (u16 *)data)) < 0 )
        AX_LOG("%s: error reading RxControl register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("RxControl", data, 2);

    if ( (rv = axReadMac(ai, data)) < 0 )
        AX_LOG("%s: error reading NodeId register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("NodeId", data, 6);

    if ( (rv = axReadMulticastFilterArrayRegister(dev, data)) < 0 )
        AX_LOG("%s: error reading MulticastFilterArray register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("MulticastFilterArray", data, 8);
    
    if ( (rv = axReadMediumStatusRegister(dev, (u16 *)data)) < 0 )
        AX_LOG("%s: error reading MediumStatus register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("MediumStatus", data, 2);

    if ( (rv = axReadMonitorModeStatusRegister(dev, data)) < 0 )
        AX_LOG("%s: error reading MonitorModeStatus register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("MonitorModeStatus", data, 1);

    if ( (rv = axReadSoftwarePHYSelectStatusRegister(dev, phy, data)) < 0 )
        AX_LOG("%s: error reading PHYSelectStatus register, rv = %d\n", __FUNCTION__, rv);
    axPrintReg("PHYSelectStatus", data, 1);

    /* read/print PHY register */
    
    AX_LOG("%s: reading PHY registers (phy = %d = 0x%x)\n", __FUNCTION__, phy, phy);
    u32 reg;
    for (reg=0; reg<7; reg++) {
        if ( (rv = axReadPHYRegister(ai->usbFd, phy, reg, (u16 *)data)) < 0 )
            AX_LOG("%s: error reading %s register, rv = %d\n", __FUNCTION__, phyRegName[reg], rv);
        *((u16 *)data) = SWAP16(*((u16 *)data));
        axPrintReg(phyRegName[reg], data, 2);
        *((u16 *)data) = SWAP16(*((u16 *)data));
    }
}
#endif

/*
 * public routines for accessing ASIX hardware
 */

IOSError
axReadMac(AsixInfo *ai, u8 *mac)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    IOSError rv = IUSB_ReadCtrlMsg(ai->usbFd, 0xc0, 0x13, 0, 0, ETH_ALEN, mac);
    AX_LOG("%s: rv = %d\n", __FUNCTION__, rv);
    return rv;
}

IOSError
axWriteMac(AsixInfo *ai, u8 *mac)
{
    AX_LOG("%s: entry\n", __FUNCTION__);
    IOSError rv = IUSB_WriteCtrlMsg(ai->usbFd, 0x40, 0x14, 0, 0, ETH_ALEN, mac);
    AX_LOG("%s: rv = %d\n", __FUNCTION__, rv);
    return rv;
}

/*
 * axConfigMulticast -- configure mac/phy to receive multicast packets
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axConfigMulticast(AsixInfo *ai, NETMcAddrList *mc)
{
    IOSError rv;
    u16 data;
    s32 i;
    u32 crc;
    u8 ma[8];  /* multicast filter array */
    
    /*
     * update RX Control Register to (optionally)
     * * enable promiscuous mode
     * * enable reception of all multicast packets
     */
    
    if ( (rv = axReadRxControlRegister(ai->usbFd, &data)) < 0 ) {
        AX_ERROR("%s: unable to read RX Control Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    if ( mc->flags & NET_IF_PROMISC )
        rv |= AX88772_RX_CONTROL_REG_PRO;
    else
        rv &= ~AX88772_RX_CONTROL_REG_PRO;

    if ( mc->flags & NET_IF_ALLMULTI )
        rv |= AX88772_RX_CONTROL_REG_AMALL;
    else
        rv &= ~AX88772_RX_CONTROL_REG_AMALL;

    AX_LOG("%s: updating RX Control Register with 0x%x (prom=%s, allmulti=%s)\n",
           __FUNCTION__,
           ( mc->flags & NET_IF_PROMISC ) ? "on" : "off",
           ( mc->flags & NET_IF_ALLMULTI ) ? "on" : "off");
    
    if ( (rv = axWriteRxControlRegister(ai->usbFd, data)) < 0 ) {
        AX_ERROR("%s: unable to write RX Control Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    /*
     * update Multicast Filter Array
     *
     * the filter is an array of 64 bits.  The CRC32 is computed over the Destination
     * Address on received filters.  The upper 6 bits of the crc are used as an index
     * into the filter array.  If the selected bit of the filter array is set (1),
     * then the packet is sent from the ethernet chip to the host.
     */
    
    memset(ma, 0, sizeof(ma)); /* clear the filter */

    for ( i=0; i<mc->count; i++ ) { /* compute the filter array */
        crc = crc32(mc->mcAddr[i], ETH_ALEN);
        crc >>= 26; /* use upper 6 bits as an index */
        ma[crc / 8] = 1<<(crc % 8); /* set crc'th bit */
    }

    AX_LOG("%s: Multicast Array Filter = %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x\n",
           __FUNCTION__, ma[0], ma[1], ma[2], ma[3], ma[4], ma[5], ma[6], ma[7]);

    if ( (rv = axWriteMulticastFilterArrayRegister(ai->usbFd, ma)) < 0 ) {
        AX_ERROR("%s: unable to write Multicast Filter Array Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

    rv = IOS_ERROR_OK;
    
out:
    return rv;
}

/*
 * axLinkStatus -- get current status
 *
 * return IOS_ERROR_OK if link is present, IOS_ERROR_NO_LINK if there
 * is no link present, or an error code if the link status cannot be
 * determined
 */
IOSError
axLinkStatus(AsixInfo *ai)
{
    IOSError rv;
    u8 data[8];	

    if ( (rv = axReadInterruptEndPoint(ai->usbFd, data)) < 0 ) {
        AX_ERROR("%s: unable to read interrupt endpoint, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    if( data[2] & AX88772_INTR_PPLS ) {
        AX_LOG("%s: link rv ok\n", __FUNCTION__);
        rv = IOS_ERROR_OK;
    } else {
        AX_LOG("%s: no link\n", __FUNCTION__);
        rv = IOS_ERROR_NO_LINK;
    }

out:
    return rv;
}

/*
 * axXmitPacket -- transmit a packet
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axXmitPacket(AsixInfo *ai, IOSIobuf *iob)
{
    IOSError rv;
    u8 *pkt;
    u16 *pPkt;
    
    /* add space to beginning of packet to hold ASIX-specific
     * packet size fields
     */
    if ( (pkt = IOS_PushIob(iob, 4)) == 0x0 ) {
        AX_ERROR("%s: IOS_PushIob failed\n", __FUNCTION__);
        rv = IOS_ERROR_FAIL_ALLOC;
        goto out;
    }
    
    /* populate ASIX-specific packet-size fields; first 16-bit
     * integer is size of packet (excluding this 16-bit integer
     * and the following one); second 16-bit integer is the
     * bit-inverse of the first
     */
    pPkt = (u16 *)pkt;
    
    pPkt[0] = SWAP16(iob->dataLen-4); 
    pPkt[1] = pPkt[0]^0xffff; 
    
    /* write packet to ASIX chip */
    rv = IUSB_WriteBlkMsg(ai->usbFd, 0x03, iob->dataLen, (u8*)pkt);
    if ( rv < 0 ) {
        AX_ERROR("%s: WriteBlkMsg failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* restore packet to its original configuration by removing the space
     * that was added to beginning of the packet
     */
    if ( (pkt = IOS_PullIob(iob, 4)) == 0x0 ) {
        AX_ERROR("%s: IOS_PullIob failed\n", __FUNCTION__);
        rv = IOS_ERROR_FAIL_ALLOC;
        goto out;
    }
    
    rv = IOS_ERROR_OK;
out:
    return rv;
}


/*
 * axRecvPacket -- get a received packet from the ASIX chip
 *
 * return IOS_ERROR_OK as well as a pointer to the packet and
 * the packet's size on success; else return an error code
 *
 * Note that the ASIX chip transfers a buffer containing (potentially)
 * multiple ethernet packets.  Each packet is prepended by 2 16-bit
 * integers, the first giving the packet size in bytes (excluding the
 * 2 16-bit integers), and the second set to the bit-inverse of the
 * first (for error-detection purposes).  This routines decodes the
 * packet size information and returns the packets one at a time,
 * reading a new buffer from the ASIX chip when needed.
 */
IOSError
axRecvPacket(AsixInfo *ai, u8 **packet, u16 *pktLen)
{
    IOSError rv;
    u16 len, checkLen;
    u16 *p16;
    u8 *buf = ai->rxPkt;
#ifdef AX_LARGE_BUFFER
    u32 bufLen = ethDevMFBSize;
#else
    u32 bufLen = ai->rxIob->dataLen;
#endif

    /* sanity check */
    if ( ai->rxSizeLeft < 0 || ( ai->rxSizeLeft > 0 && ai->rxNextPkt >= bufLen ) || buf == 0x0 || bufLen == 0x0 ) {
        AX_ERROR("%s: bad input values: rxSizeLeft = %d, rxNextPkt = %d, buf=0x%08x, bufLen = %d\n",
                 __FUNCTION__, ai->rxSizeLeft, ai->rxNextPkt, (u32)buf, bufLen);
        ai->rxSizeLeft = 0;
    }
    
    /* read more data if buffer is empty */
    if ( !ai->rxSizeLeft ) {
        AX_LOG("%s: start bulk read\n", __FUNCTION__);
        ai->rxSizeLeft = rv = IUSB_ReadBlkMsg( ai->usbFd, 0x82, bufLen, buf);
        if ( rv < (IOSError) (2*sizeof(u16)) ) {
            if ( rv == 0 ) {
                /* received zero-length packet, which is software-triggered
                 * to allow the blocking USB read to complete
                 */
                AX_LOG("%s: received zero-length packet\n", __FUNCTION__);
                ai->rxSizeLeft = 0;
                goto out;
            } else if ( rv < 0 ) {
                /* received an error while reading */
                AX_ERROR("%s: bad bulk read, rv = %d\n", __FUNCTION__, rv);
                ai->rxSizeLeft = 0;
                goto out;
            } else {
                /* not enough data -- need at least the packet size info */
                AX_ERROR("%s: not enough data from bulk read, size = %d\n",
                         __FUNCTION__, rv);
                rv = IOS_ERROR_INVALID_SIZE;
                ai->rxSizeLeft = 0;
                goto out;
            }
        }
        ai->rxNextPkt = 0;
        AX_LOG("%s: read: rxSizeLeft=%d, rxNextPkt=%d\n", __FUNCTION__,
               ai->rxSizeLeft, ai->rxNextPkt);
    }

    /* extract size of next packet in buffer */
    p16 =  (u16 *) &buf[ai->rxNextPkt];
    len = SWAP16(p16[0]);
    checkLen = SWAP16(p16[1]);
    
    AX_LOG("%s: rxSizeLeft=%d, len = %d (0x%x), checkLen = 0x%x\n",
           __FUNCTION__, ai->rxSizeLeft, len, len, checkLen);

    /* verify size data */
    if ( len != (u16) ~checkLen ) {
        ai->rxNextPkt = 0;
        ai->rxSizeLeft = 0;
        AX_ERROR("%s: packet size mismatch, %x != ~0x%x (%x)\n",
                 __FUNCTION__, len, checkLen, (u16) ~checkLen);
        rv = IOS_ERROR_FAIL_CHECKVALUE;
        goto out;
    }

    /* keep track of packet length and pointer to contents (starting
     * after the prepended length info)
     */
    *pktLen = len;
    *packet = &buf[ai->rxNextPkt+4];

    /* compute buffer size remaining after current packet;
     * check for buffer overflow
     */
    len += 4;       /* account for length info */
    if( len & 1 )   /* apparently, packets are all 16-bit aligned */
        len++;

    if ( len <= ai->rxSizeLeft ) {
        ai->rxSizeLeft -= len;
        ai->rxNextPkt += len;
    } else {
        ai->rxSizeLeft = 0;
        ai->rxNextPkt = 0;
        AX_ERROR("%s: recv buffer overflow, len = %d, rxSizeLeft = %d\n",
                 __FUNCTION__, len, ai->rxSizeLeft);
        rv = IOS_ERROR_INVALID_RNG;
        goto out;
    }

    rv = IOS_ERROR_OK;
    
out:
    return rv;
}

/*
 * axUp -- configure the mac/phy hardware and bring up the
 *         ethernet link
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError 
axUp(AsixInfo *ai, NETEthTool *pLink)
{  
    u16  data;
    IOSError rv;

#ifdef AX_DEBUG
    u16 phy = ai->eeprom.primaryPhyType;
    AX_LOG("%s: entry, phy = %d (0x%x)\n", __FUNCTION__, phy, phy);
#endif
    
    /* select internal PHY */
    AX_LOG("%s: select internal PHY\n", __FUNCTION__);
    u16 physel = AX88772_PHY_SELECT_REG_PSEL;
    if ( (rv = axWriteSoftwarePHYSelectRegister(ai->usbFd, physel)) < 0 ) {
        AX_ERROR("%s: unable to select internal PHY, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
#ifdef AX_DEBUG
    /* verify write */
    u8 phySelStatus;
    if ( (rv = axReadSoftwarePHYSelectStatusRegister(ai->usbFd, phy, &phySelStatus)) < 0 ) {
        AX_ERROR("%s: unable to read/verify PHY selection, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    AX_LOG("%s: verify Software PHY Select Status = 0x%02x\n", __FUNCTION__, phySelStatus);
#endif

    /* start the PHY */
    AX_LOG("%s: starting the phy\n", __FUNCTION__);

    /* power up internal phy, but keep in reset */
    u16 rst = AX88772_RESET_REG_PRTE;
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to power up internal PHY, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* bring internal phy out of reset */
    rst = AX88772_RESET_REG_PRTE | AX88772_RESET_REG_PRL | AX88772_RESET_REG_IPRL;
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to bring internal PHY out of reset, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    
    /* Read PHY registers */
#ifdef AX_DUMP_STATE
    AX_LOG("%s: dumping initial state\n", __FUNCTION__);
    axPrintState(ai, "axUp initial state");
#endif

    /* init RX Control Register */
    AX_LOG("%s: init RX Control Register\n", __FUNCTION__);
    if ( (rv = axReadRxControlRegister(ai->usbFd, &data)) < 0 ) {
        AX_ERROR("%s: unable to init RX Control register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    AX_LOG("%s: pre setup: rx ctrl reg = %x\n", __FUNCTION__, data);
    data |= AX88772_RX_CONTROL_REG_SO; /* start op=1 */
    if ( (rv = axWriteRxControlRegister(ai->usbFd, data)) < 0 ) {
        AX_ERROR("%s: unable to update RX Control register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

#ifdef AX_DEBUG
    /* verify write */
    if ( (rv = axReadRxControlRegister(ai->usbFd, &data)) < 0 ) {
        AX_ERROR("%s: unable to read/verify RX path enable, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    AX_LOG("%s: post setup: rx ctrl reg = %x\n", __FUNCTION__, data);
#endif
    
    /* Enable remote wake up */
    u8 remWake;
    AX_LOG("%s: Enable remote wake up\n", __FUNCTION__);
    if ( (rv = axReadMonitorModeStatusRegister(ai->usbFd, &remWake)) < 0 ) {
        AX_ERROR("%s: unable read Monitor Mode Status register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    AX_LOG("monitor mode status reg data = 0x%x\n", remWake);
    remWake |= AX88772_MONITOR_REG_RWLU;
    if ( (rv = axWriteMonitorModeRegister(ai->usbFd, remWake)) < 0 ) {
        AX_ERROR("%s: unable to set remote wake-up, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    /* enable RX path */
    AX_LOG("%s: enable RX path\n", __FUNCTION__);
    if ( (rv = axReadMediumStatusRegister(ai->usbFd, &data)) < 0 ) {
        AX_ERROR("%s: unable to read Medium Status register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
    AX_LOG("media mode status reg data = %x\n", data);
    data |= AX88772_MEDIUM_REG_RE; /* enable rx */
    if ( (rv = axWriteMediumModeRegister(ai->usbFd, data)) < 0 ) {
        AX_ERROR("%s: unable to enable RX path, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }
 
    /* configure link */
    AX_LOG("%s: configure link\n", __FUNCTION__);
    if ( (rv = axSetLinkConfig(ai, pLink)) != IOS_ERROR_OK ) {
        AX_ERROR("%s: link configuration failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
 
    /* (re-)initialize receive buffer */
    ai->rxSizeLeft = 0;
    ai->rxNextPkt = 0;

#ifdef AX_DUMP_STATE
    AX_LOG("%s: dumping final state\n", __FUNCTION__);
    axPrintState(ai, "axUp final state");
#endif

out:
    AX_LOG("%s: exiting, rv = %d\n", __FUNCTION__, rv);
    return rv;
}

/*
 * axInit
 *
 * initialize the mac/phy and query it for information about
 * its configuration and capabilities
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axInit(AsixInfo *ai, NETEthTool *pLink)
{
    IOSError rv;
    
    /* read EEPROM contents */
    if ( (rv = axReadEEProm(ai->usbFd, (u16 *)&ai->eeprom)) < 0 ) {
        AX_ERROR("%s: usbEthReadEEProm failed with rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    u16 phy = ai->eeprom.primaryPhyType;

    /* reset ASIX internal PHY */
    u16 rst = AX88772_RESET_REG_RR |
        AX88772_RESET_REG_RT |
        AX88772_RESET_REG_PRTE;
    
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to power-up device, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    rst = AX88772_RESET_REG_PRTE |
        AX88772_RESET_REG_PRL |
        AX88772_RESET_REG_IPRL;
    
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to bring internal PHY out of reset, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
#ifdef AX_DUMP_STATE
    AX_LOG("%s: dumping state\n", __FUNCTION__);
    axPrintState(ai, __FUNCTION__);
#endif

    /* initialize Medium Mode register -- disable read path */
    if ( (rv = axWriteMediumModeRegister(ai->usbFd, AX88772_MEDIUM_REG_DEFAULT)) < 0 ) {
        AX_ERROR("%s: unable to init Medium Mode register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    /* initialize Multicast Filter Array register */
    u8 ma[8];  /* multicast filter array */
    memset(ma, 0, sizeof(ma)); /* clear the filter */
    if ( (rv = axWriteMulticastFilterArrayRegister(ai->usbFd, ma)) < 0 ) {
        AX_ERROR("%s: unable to init Multicast Filter Array Register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    /* initialize RX Control register --
     * * disable MAC operation
     * * disable promiscuous mode, allmulti mode
     * * enable multicast filtering
     * * enable recv of all broadcast packets
     * * set Maximum Frame Burst (MFB) size
     */
    u16 rxctrl = AX88772_RX_CONTROL_REG_DEFAULT;
    rxctrl &= ~AX88772_RX_CONTROL_REG_MFB_MASK; /* clear MFB field */
#ifdef AX_LARGE_BUFFER
    if ( ethDevMFBSize > AX_MFB_SIZE ) {
        ethDevMFBSize = AX_MFB_SIZE;
    }
    switch (ethDevMFBSize) {  /* set MFB field */
#else
    switch (AX_MFB_SIZE) {  /* set MFB field */
#endif
    case  2048: rxctrl |= AX88772_RX_CONTROL_REG_MFB_2K; break;
    case  4096: rxctrl |= AX88772_RX_CONTROL_REG_MFB_4K; break;
    case  8192: rxctrl |= AX88772_RX_CONTROL_REG_MFB_8K; break;
    case 16384: rxctrl |= AX88772_RX_CONTROL_REG_MFB_16K; break;
    default:
        AX_ERROR("%s: illegal MFB size = %d\n", __FUNCTION__, AX_MFB_SIZE);
        rv = IOS_ERROR_INVALID_RNG;
        goto out;
    }
    if ( (rv = axWriteRxControlRegister(ai->usbFd, rxctrl)) < 0 ) {
        AX_ERROR("%s: unable to init RX Control register, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    /* initialize MAC address from EEPROM */
    if ( (rv = axWriteMac(ai, (u8 *) ai->eeprom.NodeId)) < 0 ) {
        AX_ERROR("%s: unable to init MAC address, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
    /* populate NETEthTool structure with default link info */
    if ( (rv = axGetLinkInfo(ai->usbFd, phy, pLink)) != IOS_ERROR_OK ) {
        AX_ERROR("%s: unable to get link info, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* put ASIX internal PHY back into reset and power down */
    rst = AX88772_RESET_REG_PRTE |
        AX88772_RESET_REG_IPPD;
    
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to power down device, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
out:
    return rv;
}

/*
 * axOpen -- open the Asix hardware driver
 *
 * return IOS_ERROR_OK on success, else an error code
 */
extern char ethDev[64];
IOSError
axOpen(AsixInfo *ai)
{
    IOSError rv;
    
    /* initialize context */
    AX_LOG("%s: initializing context\n", __FUNCTION__);
    ai->usbFd = -1;
    memset((void *) &ai->eeprom, 0, sizeof(ai->eeprom));
    ai->rxIob = (IOSIobuf *)0x0;
    ai->rxPkt = (u8 *)0x0;
    ai->rxSizeLeft = 0;
    ai->rxNextPkt = 0;
    /* ai->iobufDebugInfo = 0; */  /* struct not defined yet */
    
    /* open usb device, retrying up to AX_MAX_RETRY times */
    AX_LOG("%s: opening \"%s\"\n", __FUNCTION__, ethDev);
    s32 retry = 0;
    
    while ( (ai->usbFd = rv = IOS_Open(ethDev, 0)) < 0 ) {
        AX_LOG("%s: open of usb device %s failed, rv = %d\n",
                __FUNCTION__, ethDev, rv);
        if ( retry >= AX_MAX_RETRY )
            break;
        if ( (rv = usleep(1e6)) < 0 ) { /* wait 1 second */
            AX_ERROR("%s: unable to sleep waiting for open, rv = %d\n",
                     __FUNCTION__, rv);
            /* ignore error, fall through */
        }
        retry++;
        AX_LOG("%s: opening \"%s\", retry = %d\n", __FUNCTION__, ethDev, retry);
    }
    
    if ( rv < 0 ) {
        AX_ERROR("%s: open of usb device failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    AX_LOG("%s: open \"%s\" succeeded, usbFd = %d (0x%x)\n", __FUNCTION__, ethDev, ai->usbFd, ai->usbFd);

#ifdef AX_LARGE_BUFFER
    if ( sAlloced ) {
        AX_ERROR("%s: cannot allocate recv buf\n", __FUNCTION__);
        rv = IOS_ERROR_FAIL_ALLOC;
        goto out;
    }
    else
    {
        ai->rxPkt = sRecvBuff;
        sAlloced = TRUE;
        rv = IOS_ERROR_OK;
    }
#else
    /* allocate an iobuf to hold the received packets */
    if ( ai->rxIob == 0x0 ) {
        if ( (rv = IOS_AccessIobPool(POOL_DEFAULT)) != IOS_ERROR_OK ) {
            AX_ERROR("%s: cannot access iobuf pool, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }
        
        if ( (ai->rxIob = IOS_AllocIob(POOL_DEFAULT, AX_MFB_SIZE, ai->iobufDebugInfo)) == 0x0 ) {
            AX_ERROR("%s: cannot allocate recv iobuf\n", __FUNCTION__);
            rv = IOS_ERROR_FAIL_ALLOC;
            goto out;
        }
        
        ai->rxPkt = IOS_PutIob(ai->rxIob, AX_MFB_SIZE);
        if ( ! ai->rxPkt ) {
            AX_ERROR("%s: cannot put %d bytes of data in recv iobuf\n", __FUNCTION__, AX_MFB_SIZE);
            rv = IOS_ERROR_FAIL_ALLOC;
            goto out;
        }
    }
#endif
    
out:
    if ( rv < 0 ) {
        if ( ai->rxIob )
            IOS_FreeIob(ai->rxIob);
        if ( ai->usbFd >= 0 )
            IOS_Close(ai->usbFd);
    }
    
    return rv;
}

/*
 * axForceReadCompletion -- force any outstanding bulk reads to
 *  complete even if no read data is available
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axForceReadCompletion(AsixInfo *ai)
{
    IOSError rv = IOS_ERROR_OK;

    u16 rst = AX88772_RESET_REG_PRTE |
        AX88772_RESET_REG_PRL |
        AX88772_RESET_REG_IPRL |
        AX88772_RESET_REG_BZ;
    
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to force read completion, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

out:
    return rv;
}

/*
 * axDown -- shut down the Asix hardware
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axDown(AsixInfo *ai)
{
    IOSError rv = IOS_ERROR_OK;

    /* turn off RX operations in the MAC/PHY hardware */
    u16 mmode;
    AX_LOG("%s: disable RX path\n", __FUNCTION__);
    if ( (rv = axReadMediumStatusRegister(ai->usbFd, &mmode)) < 0 ) {
        AX_ERROR("%s: unable to read Medium Status, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    mmode &= ~AX88772_MEDIUM_REG_RE; /* disable rx */
    if ( (rv = axWriteMediumModeRegister(ai->usbFd, mmode)) < 0 ) {
        AX_ERROR("%s: unable to write Medium Mode Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    
    /* stop MAC */
    u16 rxctrl;
    AX_LOG("%s: stopping internal MAC\n", __FUNCTION__);
    if ( (rv = axReadRxControlRegister(ai->usbFd, &rxctrl)) < 0 ) {
        AX_ERROR("%s: unable to read RX Control Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    rxctrl &= ~AX88772_RX_CONTROL_REG_SO;  /* stop mac/phy operations */
    if ( (rv = axWriteRxControlRegister(ai->usbFd, rxctrl)) < 0 ) {
        AX_ERROR("%s: unable to write RX Control Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }

#ifdef AX_DUMP_STATE
    AX_LOG("%s: dumping pre-shutdown state\n", __FUNCTION__);
    axPrintState(ai, __FUNCTION__);
#endif

    /* reset and power down internal PHY */
    u16 rst = AX88772_RESET_REG_PRTE | AX88772_RESET_REG_PRL | AX88772_RESET_REG_IPPD;
    if ( (rv = axWriteSoftwareResetRegister(ai->usbFd, rst)) < 0 ) {
        AX_ERROR("%s: unable to write Software Reset Register, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    
    rv = IOS_ERROR_OK;
    
out:
    return rv;
}

/*
 * axClose -- close the Asix hardware driver
 *
 * return IOS_ERROR_OK on success, else an error code
 */
IOSError
axClose(AsixInfo *ai)
{
    IOSError rv = IOS_ERROR_OK;
    
    /* close usb device */
    if ( ai->usbFd >= 0 ) {
        AX_LOG("%s: closing \"%s\"\n", __FUNCTION__, ethDev);
        if ( (rv = IOS_Close(ai->usbFd)) != IOS_ERROR_OK ) {
            AX_ERROR("%s: unable to close usb RM, rv = %d\n", __FUNCTION__, rv);
            /* ignore error since fd may already be invalid, fall through */
        }
        ai->usbFd = -1;
    }

#ifdef AX_LARGE_BUFFER
    ai->rxPkt = NULL;
    sAlloced = FALSE;
#else
    /* release the receive buffer */
    if ( ai->rxIob != 0x0 && (rv = IOS_FreeIob(ai->rxIob)) != IOS_ERROR_OK ) {
        AX_ERROR("%s: unable to free receive iob = 0x%x, rv = %d\n",
                 __FUNCTION__, (u32)ai->rxIob, rv);
        rv = IOS_ERROR_FAIL_ALLOC;
    }
#endif
    
    ai->rxIob = (IOSIobuf *) 0x0;

    return rv;
}
