/*
 *               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.
 *
 */

/*
 * Resource Manager for USB-to-Ethernet bridge
 *
 * this file only contains generic routines that are not specific
 * to any ethernet MAC/PHY hardware; hardware-specific routines
 * are located elsewhere
 *
 * To Do list --
 * 1. it seems that the IP stack does not pad-out illegally-short
 *    ethernet packets; it appears that the ASIX chip will supply
 *    its own padding, but since there's no documentation on this
 *    feature it's not clean exactly when/how it can be relied on;
 *    best would be to modify the IP stack to provide the needed
 *    padding
 * 2. waiting for a new ioctl to be defined for reporting link
 *    status
 * 
 */

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

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

char const __version[] = "$IOSVersion: ETH: "BUILD_TIME" "MEM_SIZE_ID" $";

#define UE_DEBUG_ERROR 1
/* debugging macros */
#ifdef UE_DEBUG
#define UE_LOG(...) printf("UE: " __VA_ARGS__)
#define UE_LOG_CONT(...) printf(__VA_ARGS__)
#define UE_ERROR(...) printf("UE: Error: " __VA_ARGS__)
#else
#define UE_LOG(...)
#define UE_LOG_CONT(...)
#ifdef UE_DEBUG_ERROR
#define UE_ERROR(...) printf("UE: Error: " __VA_ARGS__)
#else
#define UE_ERROR(...) /* printf("UE: Error: " __VA_ARGS__) */
#endif
#endif

/*
 * context info for each usbeth device
 */

typedef volatile struct {
    u8 devState;                     /* current state of device */
    u8 netState;                     /* current state of network */
    IOSFd ipbFd;                     /* handle for IP stack bottom half */
    IPInterfaceStat stats;           /* link statistics; packet counts, etc. */
    NETEthTool defLinkInfo;          /* default link characteristics; speed, etc. */
    NETEthTool linkInfo;             /* link characteristics; speed, etc. */
    u8 linkStatus;                   /* link status */
    NETMcAddrList mcast;             /* multicast settings */
    IOSIobDebugInfo iobufDebugInfo;  /* debug info for iobuf's */
    IOSThreadId monId;               /* monitor thread's id */
    IOSMessageQueueId monMsgQ;       /* message queue for monitor operations */
    IOSThreadId rxId;                /* receive thread's id */
    u8 rxRunning;                    /* 1 if receive thread is running */
    IOSMessageQueueId rxMsgQ;        /* message queue for recv operations */
    IOSMessage rxMsgArray[1];        /* message array for recv operations */
    IOSTimerId tmId;                 /* link status timer's id */
    EthHwInfo ethHw;                 /* ethernet hardware info */
} UsbEthContext;

#define USBETH_NUM_DEV 1
static UsbEthContext usbEthContext[USBETH_NUM_DEV];
char ethDev[64];
u32  ethDevMFBSize;
#define USBETH_MFB_SIZE_UH      4096
#define USBETH_MFB_SIZE_EH      16384
static u32 __runRecvThrdFlag;
static u32 oh0RegId __attribute__((aligned(32)));
static u32 ehcRegId __attribute__((aligned(32)));
/*
 * usbeth device states
 */
#define USBETH_DEVSTATE_REMOVED 0    /* device removed */
#define USBETH_DEVSTATE_DOWN    1    /* device down */
#define USBETH_DEVSTATE_UP      2    /* device up */

/*
 * usbeth network stack states
 */
#define USBETH_NETSTATE_CLOSED  0    /* resource manager closed */
#define USBETH_NETSTATE_DOWN    1    /* network down */
#define USBETH_NETSTATE_UP      2    /* network up */

/*
 * usbeth link status
 */
#define USBETH_LINKSTATE_DOWN   0    /* link down */
#define USBETH_LINKSTATE_UP     1    /* link up */

/* usbeth RM thread stack, stack size, priority */
#define USBETH_STACK_SIZE  (32 * 1024)
#define USBETH_MAIN_PRIORITY  (IOS_PRIORITY_USBETH - 2)
const u8 _initStack[USBETH_STACK_SIZE];
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = IOS_PRIORITY_USBETH;

/* usbeth receive thread stack, stack size, priority */
#define USBETH_RECV_STACK_SIZE  (2 * 1024)
#define USBETH_RECV_PRIORITY  (IOS_PRIORITY_USBETH - 3)
static u8 _recvStack[USBETH_RECV_STACK_SIZE];

/* usbeth monitor thread stack, stack size, priority */
#define USBETH_MON_STACK_SIZE  (2 * 1024)
#define USBETH_MON_PRIORITY  (IOS_PRIORITY_USBETH - 1)
static u8 _monStack[USBETH_MON_STACK_SIZE];

/* queue size for usbeth RM */
#define USBETH_MSGQ_SIZE  64

/* messages to the monitor thread */
#define USBETH_MSG_NETUP    1
#define USBETH_MSG_NETDOWN  2
#define USBETH_MSG_TIMER    3
#define USBETH_MSG_KILLMON  4

/*
 * Ethernet packet types (unicast versus multicast) are distinguished
 * by the lsb of the first octet of the destination address; note that
 * broadcast is a special case of multicast in which the destination
 * address is ff:ff:ff:ff:ff:ff
 */
#define ETH_ADDR_UNICAST(da)  ( ((da)&0x1) == 0 )  /* lsb of 1st DA byte */
#define ETH_ADDR_MULTICAST(da)  ((da)&0x1)  /* lsb of 1st DA byte */

/*
 * these min/max ethernet packet lengths do not including the FCS
 * since hardware automatically adds it and strips it off; ditto
 * for the preamble
 *
 * also, hardware automatically pads short packets, so a legal-length
 * packet goes out over the wire so long as a complete header is
 * provided
 *
 * NOTE: if VLAN support is desired, then add 4 to ETH_MAX_PACKET_SIZE
 */
#define ETH_MIN_PACKET_SIZE  (ETH_HLEN)
#define ETH_MAX_PACKET_SIZE  (ETH_HLEN+1500)

typedef IOSMessageQueueId UsbEthMutexId;
static IOSMessage __usbEthMutexQueue[1];
static UsbEthMutexId __usbEthMutex;

/* Data structures to handle net UP/DOWN requests */
static IOSMessage __netUpDownMutexQueue[1];
static UsbEthMutexId __netUpDownMutex;
static IOSResourceRequest *__upDownReq;

/*
 * create mutex for mutual exclusion among threads
 */
static UsbEthMutexId
usbEthCreateMutex(IOSMessage *msgQ)
{
    IOSError rv;
    IOSMessageQueueId id = -1;

    if ( (id = IOS_CreateMessageQueue(msgQ, 1)) < IOS_ERROR_OK) {
        rv = id;
        UE_ERROR("%s: failed to create message queue, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    if ( (rv = IOS_SendMessage(id, 0, IOS_MESSAGE_NOBLOCK)) != IOS_ERROR_OK) {
        UE_ERROR("%s: failed to initialize mutex, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    rv = (IOSError) id;

out:
    if ( rv < 0 && id >= 0 ) {
        IOSError rv2;

        if ( (rv2 = IOS_DestroyMessageQueue(id)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: failed to destroy message queue, rv = %d\n", __FUNCTION__, rv2);
            /* ignore error, fall through */
        }
    }

    return rv;
}

static IOSError
usbEthLockMutex(UsbEthMutexId mux)
{
    IOSError rv;
    IOSMessage dummy;

    if ( (rv = IOS_ReceiveMessage(mux, &dummy, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: failed to lock mutex %x, rv = %d\n", __FUNCTION__, mux, rv);
        goto out;
    }

out:
    return rv;
}

static IOSError
usbEthUnlockMutex(UsbEthMutexId mux)
{
    IOSError rv;

    if ( (rv = IOS_SendMessage(mux, 0, IOS_MESSAGE_NOBLOCK)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: failed to unlock mutex %x, rv = %d\n", __FUNCTION__, mux, rv);
        goto out;
    }

out:
    return rv;
}

#define LOCK_USBETH()   usbEthLockMutex(__usbEthMutex)
#define UNLOCK_USBETH() usbEthUnlockMutex(__usbEthMutex)

#define LOCK_NET_UPDOWN()   usbEthLockMutex(__netUpDownMutex)
#define UNLOCK_NET_UPDOWN() usbEthUnlockMutex(__netUpDownMutex)

/*
 * print the contents of a packet to stdout, prepending a
 * user-supplied message
 */
#ifdef DUMP_PACKET
static void
dumpPacket( u8 *pkt, u32 length, char *msg )
{
    int i, j, k;

    printf("\n");
    printf("%s: dumping packet: length = %d\n", msg, length);
    for (i=0; i<length; i+= 16) {
        printf("%06d ", i);
        k = length - i;
        if ( k > 16 )
            k = 16;
        for ( j=0; j<k; j++ ) {
            printf("%02x ", pkt[i+j]);
        }
        printf("\n");
    }
}
#endif

/*
 * usbEthDiscardPacket -- determine whether received packets should
 * be discarded as a result of the current multicast filter settings
 *
 * returns 1 if packet should be discarded; IOS_ERROR_OK (0) if
 * packet should NOT be discarded
 */
static
IOSError usbEthDiscardPacket(NETMcAddrList *mcast, u8 *da)
{
    IOSError rv = IOS_ERROR_OK;
    s32 i;
    s32 found;

    UE_LOG("%s: da = %02x:%02x:%02x:%02x:%02x:%02x\n", __FUNCTION__,
           da[0], da[1], da[2], da[3], da[4], da[5]);
    
    if ( ETH_ADDR_UNICAST(da[0]) ) {
        /* never discard unicast packets because -
         * if promiscuous mode, we keep all packets;
         * if not promiscuous mode, ethernet hardware automatically
         * discards all unicast packets except for those specifically
         * addressed to it;
         */
        UE_LOG("%s: keeping unicast packet\n", __FUNCTION__);
    } else {
        
        if ( da[0] == 0xff && da[1] == 0xff && da[2] == 0xff &&
             da[3] == 0xff && da[4] == 0xff && da[5] == 0xff ) {
            /* never discard broadcast packets */
            UE_LOG("%s: keeping broadcast packet\n", __FUNCTION__);
        } else {
            /* don't discard multicast packets if
             * (1) the NET_IF_ALLMULTI flag is set
             * OR
             * (2) its on the user's list of multicast packets to keep
             */
            UE_LOG("%s: multicast\n", __FUNCTION__);

            if ( mcast->flags & NET_IF_ALLMULTI ) {
                UE_LOG("%s: keeping multicast packet (allmulti)\n", __FUNCTION__);
            } else {
                found = 0;
                for (i=0; i<mcast->count; i++) {
                    if ( memcmp( da, mcast->mcAddr[i], ETH_ALEN ) == 0 ) {
                        found = 1;
                        break;
                    }
                }

                if ( found ) {
                    UE_LOG("%s: keeping multicast packet (match=%d)\n", __FUNCTION__, i);
                } else {
                    UE_LOG("%s: discarding multicast filter (no match)\n", __FUNCTION__);
                    rv = 1;
                }
            }
        }
    }

    return rv;
}

/*
 * usbEthRecvThread -- packet receiver thread
 *
 * standalone thread which receives packets for the ethernet
 * MAC/PHY, filters them, and passes them on to the IP stack.
 */
static void
usbEthRecvThread(u32 arg)
{
    UsbEthContext *uec = (UsbEthContext *)arg;

    IOSError rv;
    u8 *ethHdr;
    u16 pktLen;
    IOSIobuf *iob;
    u8 *data;

    UE_LOG("%s: entry\n", __FUNCTION__);
                        
    /*
     * loop, receiving packets and sending them to the IP stack
     */

    /* __runRecvThrdFlag == 1 => run recv thread.
     *                   == 0 => stop recv thread.
     *
     * The recv thread only reads __runRecvThrdFlag.
     * The monitor thread sets the value of __runRecvThrdFlag.
     */
    while (1) {
        if (0 == __runRecvThrdFlag) {
            UE_LOG("%s: received stop message\n", __FUNCTION__);
            break;
        }

        /* recv a new packet */
        rv = axRecvPacket(&uec->ethHw, &ethHdr, &pktLen);
        if ( rv < 0 ) {
            uec->stats.inErrors++;
            UE_LOG("%s: received bad packet, skipping, rv = %d\n", __FUNCTION__, rv);
             usleep(10*1000); // To avoid attacking OHCI when USB-Eth is removed.
            continue;
        }

        UE_LOG("%s: pktLen = %d (%x)\n", __FUNCTION__, pktLen, pktLen);
        if ( pktLen < ETH_HLEN ) {
            if (pktLen == 0) {
                UE_LOG("%s: received zero-length packet\n", __FUNCTION__);
            } else {
                uec->stats.inErrors++;
                UE_ERROR("%s: invalid packet length = %d\n", __FUNCTION__, pktLen);
            }
            continue;
        }

        /* filter packet */
        if ( usbEthDiscardPacket((NETMcAddrList *) &uec->mcast, ethHdr) ) {
            uec->stats.inDiscards++;
            UE_LOG("%s: discarding packet\n", __FUNCTION__);
#ifdef DUMP_PACKET
            dumpPacket(ethHdr, pktLen, "usbEthRecvThread: DROP");
#endif
            continue;
        }
        
        /* obtain an iobuf to hold the new packet */
        iob = IOS_AllocIob(POOL_DEFAULT, pktLen+NET_IP_ALIGN, uec->iobufDebugInfo);
        if (!iob) {
            uec->stats.inDiscards++;
            UE_ERROR("%s: allocating iobuf failed\n", __FUNCTION__);
            continue;
        }

        /* copy the new packet into the iobuf */
        data = IOS_PutIob(iob, pktLen+NET_IP_ALIGN);
        if (!data) {
            uec->stats.inDiscards++;
            UE_ERROR("%s: iobuf too small\n", __FUNCTION__);
            if ( (rv = IOS_FreeIob(iob)) != IOS_ERROR_OK ) {
               UE_ERROR("%s: too small: failed to free iob @ 0x%x, rv = %d\n",
                        __FUNCTION__, (u32)iob, rv);
               /* ignore error, fall through */
            }
            continue;
        }
            
        u8 *src = ethHdr;
        u8 *dst = data;
        memcpy((void *)dst, (const void *)src, ETH_HLEN);
        dst += ETH_HLEN;
        src += ETH_HLEN;
        memset((void *)dst, 0, NET_IP_ALIGN);
        dst += NET_IP_ALIGN;
        memcpy((void *)dst, (const void *)src, (int) pktLen - ETH_HLEN );

        /* optionally, dump the packet contents */
#ifdef DUMP_PACKET
        dumpPacket(data, pktLen, "usbEthRecvThread");
#endif

        /* send packet to IP stack */
        IOSError rv;
        IOSIoVector v[2];
        u32 ifID = NET_IF_ETH_USB;
        
        v[0].base   = (u8 *) &ifID;
        v[0].length = sizeof(ifID);
        v[1].base   = (u8 *) iob;
        v[1].length = sizeof(IOSIobuf);

        if ( (rv = IOS_Ioctlv(uec->ipbFd, NET_IP_RECV_PKT, sizeof(v)/sizeof(v[0]), 0, v)) < 0 ) {
            uec->stats.inErrors++;
            UE_ERROR("%s: NET_IP_RECV_PKT failed, rv = %d\n", __FUNCTION__, rv);
            if ( (rv = IOS_FreeIob(iob)) != IOS_ERROR_OK ) {
                UE_ERROR("%s: unable to free packet iob = 0x%x, rv = %d\n",
                         __FUNCTION__, (u32)iob, rv);
            }
        }
        
        /* update statistics */
        if ( ETH_ADDR_UNICAST(ethHdr[0]) ) {
            uec->stats.inUcastPackets++;
        } else {
            uec->stats.inNonUcastPackets++;
        }
        
    }
    
    UE_LOG("%s: exiting\n", __FUNCTION__);
    return;
}

/*
 * usbEthStartRecvThread -- start thread to read received packets from
 * ethernet MAC/PHY and forward them to IP stack
 *
 * return IOS_ERROR_OK if thread is started successfully, else error code
 */
static IOSError
usbEthStartRecvThread(UsbEthContext *uec)
{
    IOSError rv = IOS_ERROR_OK;

    /*
     * create receive message queue
     */
    if ( uec->rxMsgQ < 0 ) {
        uec->rxMsgQ = rv = IOS_CreateMessageQueue((IOSMessage *) uec->rxMsgArray, sizeof(uec->rxMsgArray)/sizeof(IOSMessage));
        if ( rv < 0 ) {
            UE_ERROR("%s: unable to create recv message queue, rv = %d\n",
                     __FUNCTION__, rv);
            goto out;
        }
    }

    /*
     * create receive thread
     */
    if ( uec->rxId < 0 ) {
        UE_LOG("%s: creating thread\n", __FUNCTION__);
        __runRecvThrdFlag = 1; /* see description in usbEthRecvThread */
        uec->rxId = rv = IOS_CreateThread(usbEthRecvThread,
                                          (void *) uec,
                                          _recvStack + USBETH_RECV_STACK_SIZE,
                                          USBETH_RECV_STACK_SIZE,
                                          USBETH_RECV_PRIORITY,
                                          IOS_THREAD_CREATE_JOINABLE);
        
        if (rv < 0) {
            UE_ERROR("%s: could not create recv thread, rv = %d\n", __FUNCTION__, rv);
            __runRecvThrdFlag = 0;
            goto out;
        }
    }
    
    /*
     * start receive thread
     */
    if ( ! uec->rxRunning ) {
        UE_LOG("%s: starting thread\n", __FUNCTION__);
        if ( (rv = IOS_StartThread(uec->rxId)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: could not start recv thread, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }
        uec->rxRunning = 1;
    }

out:
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * usbEthStopRecvThread -- stop thread receiving packets from ethernet
 * MAC/PHY
 *
 * returns IOS_ERROR_OK on success, else an error code
 *
 * Note that the receive thread performed blocking reads from the
 * ethernet hardware.  If closing the ethernet device does not terminate 
 * the read (as is currently the case), then the thread must be manually
 * terminated because otherwise it can block indefinitely waiting for
 * a receive packets (which may not be forthcoming).  If (in the future)
 * the ethernet driver is modified to terminate any outstanding trans-
 * actions when a close is requested, then the receive thread can be sent
 * a message instructing it to exit cleanly.
 */
static IOSError
usbEthStopRecvThread(UsbEthContext *uec)
{
    IOSError rv = IOS_ERROR_OK;

    if ( uec->rxRunning ) {

        /* send stop message to receive thread
         *
         * since there's only one message (the "stop" message), the content
         * of the message doesn't matter; simply send the address of the UE
         * context
         */
        UE_LOG("%s: setting stop recv thread flag\n", __FUNCTION__);
        __runRecvThrdFlag = 0;
        /* recv thread may be blocking on a bulk read from the ethernet
         * hardware; force ethernet to complete the read, even if no
         * data is returned
         */
        UE_LOG("%s: forcing bulk read to complete\n", __FUNCTION__);
        LOCK_USBETH();
        if ( (rv = axForceReadCompletion(&uec->ethHw)) < 0 ) {
            UE_ERROR("%s: unable to force read completion, rv = %d\n", __FUNCTION__, rv);
            /* ignore error since device may be unplugged, fall through */
        }
        UNLOCK_USBETH();
      
        /* wait for receive thread to exit */
        if (rv >= 0) {
            UE_LOG("%s: waiting for recv thread to exit\n", __FUNCTION__);
            if ((rv = IOS_JoinThread(uec->rxId, 0x0)) != IOS_ERROR_OK ) {
                UE_ERROR("%s: unable to join receive thread, rv = %d\n", __FUNCTION__, rv);
                goto out;
            }
            uec->rxId = -1;
            uec->rxRunning = 0;
            UE_LOG("%s: recv thread has exited properly\n", __FUNCTION__);
        } 
    }
    if (uec->rxId >= 0) {
        u32 val;
        /* thread was created but never started; or we were unable to stop
         * thread. 
         */
        if ((rv = IOS_DestroyThread(uec->rxId, &val)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: unable to kill recv thread, rv = %d\n", __FUNCTION__, rv);
            /* Fall through and do rest of cleanup anyway */
        }
        uec->rxId = -1;
        uec->rxRunning = 0;
    }

    /* destroy message queue */
    if ( uec->rxMsgQ >= 0 ) {
        if ( (rv = IOS_DestroyMessageQueue(uec->rxMsgQ)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: unable to destroy recv message queue, rv = %d\n",
                        __FUNCTION__, rv);
            goto out;
        }
        uec->rxMsgQ = -1;
    }
    
out:
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * usbEthNotify -- notify IP stack of a status change
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthNotify(UsbEthContext *uec, u32 notifyID)
{
    IOSIoVector v[2];
    IOSError rv;
    u32 ifID = NET_IF_ETH_USB;

    UE_LOG("%s: entry\n", __FUNCTION__);

    /* check network state */
    if ( uec->netState != USBETH_NETSTATE_UP ) {
        rv = IOS_ERROR_NOTREADY;
        goto out;
    }

    v[0].base   = (u8 *) &ifID;
    v[0].length = sizeof(ifID);
    v[1].base   = (u8 *) &notifyID;
    v[1].length = sizeof(notifyID);

    if ( (rv = IOS_Ioctlv(uec->ipbFd, NET_IP_NOTIFY, 2, 0, v)) < 0 ) {
        UE_ERROR("%s: IP stack notify %d, rv = %d\n", __FUNCTION__, notifyID, rv);
        goto out;
    }

out:
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}


/* Get EHC, OH0 device lists. One of them will contain usbeth. */
static IOSError
__findEthDevice(USBDeviceInfo *deviceList, u32 numDev)
{
  IOSError rv = IOS_ERROR_NOEXISTS;
  u32 i;
  for (i = 0; i < numDev; ++i) {
      if (deviceList[i].vid == AX_VID && deviceList[i].pid == AX_PID) {
          rv = IOS_ERROR_OK;
          goto out;
      }
  }
out:
  return rv;
}

static IOSError
__getEthDevice(void)
{
  u8 numDev;
  IOSError rv;
  USBDeviceInfo deviceList[32];
 
  rv = IUSB_GetDeviceList("/dev/usb/oh0", deviceList, 32, 0, &numDev);
  if (rv < 0) {
      UE_ERROR("Failed to get OH0 device list\n");
  } else {
      rv = __findEthDevice(deviceList, numDev);
      if (IOS_ERROR_OK == rv) { /* found device */
          strncpy(ethDev, "/dev/usb/oh0/0b95/7720", 63);
          ethDevMFBSize = USBETH_MFB_SIZE_UH;
          /* Cancel notification request enqueued for other HC */
          rv = IUSB_CancelInsertionNotify("/dev/usb/ehc", &ehcRegId);
          goto out;
      }
  }
 
  memset(deviceList, 0, sizeof(deviceList));
  rv = IUSB_GetDeviceList("/dev/usb/ehc", deviceList, 32, 0, &numDev);
  if (rv < 0) {
      UE_ERROR("Failed to get EHC device list\n");
  } else {
      rv = __findEthDevice(deviceList, numDev);
      if (IOS_ERROR_OK == rv) { /* found device */
          strncpy(ethDev, "/dev/usb/ehc/0b95/7720", 63);
          ethDevMFBSize = USBETH_MFB_SIZE_EH;
          /* Cancel notification request enqueued for other HC */
          rv = IUSB_CancelInsertionNotify("/dev/usb/oh0", &oh0RegId);
      }
  }
  UE_LOG("usbeth: using buffer size %u\n", ethDevMFBSize);

out:
  UE_LOG("%s: ethDev is set to: %s\n", __FUNCTION__, ethDev);
  return rv;
}

/*
 * usbEthDevInit -- initialize the Ethernet hardware when inserted
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthDevInit(UsbEthContext *uec)
{
    IOSError rv;
    u32 opened = 0;
  
    UE_LOG("%s: entry\n", __FUNCTION__);

    LOCK_USBETH();

    /* check device state */
    if ( uec->devState != USBETH_DEVSTATE_REMOVED ) {
        rv = IOS_ERROR_OK;
        goto out;
    }

    __getEthDevice(); /* Figure out path */
    /* open the ethernet hardware driver */
    UE_LOG("%s: opening ethernet hardware\n", __FUNCTION__);
    if ( (rv = axOpen(&uec->ethHw)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: open of ethernet hardware failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    opened = 1;
    
    /* initialize the ethernet hardware */
    UE_LOG("%s: initializing ethernet hardware\n", __FUNCTION__);
    if ( (rv = axInit(&uec->ethHw, (NETEthTool *) &uec->defLinkInfo)) < 0 ) {
        UE_ERROR("%s: initialize of ethernet hardware failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    memcpy((void *) &uec->linkInfo, (void *) &uec->defLinkInfo, sizeof(NETEthTool));

    /* device is initialized */
    uec->devState = USBETH_DEVSTATE_DOWN;

out:
    if ( rv < 0 && opened == 1 ) {
        IOSError rv2;

        if ( (rv2 = axClose(&uec->ethHw)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: failed to close ethernet hardware, rv = %d\n", __FUNCTION__, rv2);
            /* ignore error, fall through */
        }
    }

    UNLOCK_USBETH();
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * usbEthShutdown -- close fd to USB when removed
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthDevShutdown(UsbEthContext *uec)
{
    IOSError rv;

    UE_LOG("%s: entry\n", __FUNCTION__);

    LOCK_USBETH();

    /* check device state */
    if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
        rv = IOS_ERROR_OK;
        goto out;
    }

    /* close the ethernet device */
    memset(ethDev, 0, sizeof(ethDev));
    ethDevMFBSize = 0;
    if ( (rv = axClose(&uec->ethHw)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to close ethernet MAC/PHY, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
    /* device is de-initialized */
    uec->devState = USBETH_DEVSTATE_REMOVED;

out:
    UNLOCK_USBETH();
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * usbEthDevUp -- configure ethernet link
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthDevUp(UsbEthContext *uec)
{
    IOSError rv;

    UE_LOG("%s: entry\n", __FUNCTION__);

    LOCK_USBETH();

    /* check device state */
    if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
        UE_ERROR("%s: device not inserted, can't bring up\n", __FUNCTION__);
        rv = IOS_ERROR_NOTREADY;
        goto out;
    } else if ( uec->devState == USBETH_DEVSTATE_UP ) {
        rv = IOS_ERROR_OK;
        goto out;
    }
    
    /* axInit() has configured PHY/MAC. Do any other initializations. */
    if ( (rv = axUp(&uec->ethHw, (NETEthTool *) &uec->linkInfo)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to start up phy/mac, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* device is up */
    uec->devState = USBETH_DEVSTATE_UP;

out:
    UNLOCK_USBETH();
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}
    
/*
 * usbEthDevDown -- shut down ethernet link
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthDevDown(UsbEthContext *uec)
{
    IOSError rv = IOS_ERROR_OK;

    UE_LOG("%s: entry\n", __FUNCTION__);

    LOCK_USBETH();

    /* check device state */
    if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
        UE_ERROR("%s: device not inserted, can't bring down\n", __FUNCTION__);
        rv = IOS_ERROR_NOTREADY;
        goto out;
    } else if ( uec->devState == USBETH_DEVSTATE_DOWN ) {
        rv = IOS_ERROR_OK;
        goto out;
    }
   
#if 0
    /*
     * turn off RX operations in the MAC/PHY hardware and
     * shut down the MAC/PHY
     */
 
    if ( (rv = axDown(&uec->ethHw)) < 0 ) {
        UE_ERROR("%s: unable to shut down the ethernet MAC/PHY, rv = %d\n", __FUNCTION__, rv);
        rv = IOS_ERROR_FAIL_INTERNAL;
        goto out;
    }
    /* device is down */   
    uec->devState = USBETH_DEVSTATE_DOWN;
#endif

out:
    UNLOCK_USBETH();
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * usbEthLinkStatus -- check link status
 *
 * return IOS_ERROR_OK if link is up, IOS_ERROR_NO_LINK if link is down,
 * else error code
 */
static u32
usbEthLinkStatus(UsbEthContext *uec)
{
    IOSError rv = IOS_ERROR_OK;

    UE_LOG("%s: checking link status\n", __FUNCTION__);

    LOCK_USBETH();

    /* don't bother to check link status if device is not up */
    if ( uec->devState != USBETH_DEVSTATE_UP ) {
        rv = IOS_ERROR_NO_LINK;
        goto out;
    }
    
    /* check link status */
    if ( (rv = axLinkStatus(&uec->ethHw)) != IOS_ERROR_OK ) {
        rv = IOS_ERROR_NO_LINK;
        goto out;
    }

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

static void
__handleNetUpDown(UsbEthContext *uec, u32 msg)
{
    IOSError rv = IOS_ERROR_OK;

    LOCK_NET_UPDOWN();
    if (USBETH_MSG_NETUP == msg) {
        if (uec->netState == USBETH_NETSTATE_UP) { /* Already up */
            goto out;
        }
        (void) usbEthDevUp(uec);

     /* To prevent reading wrong state by the monitor-thread, 
      * we put off a first result. After usbEthDevUp, second and subsequent
      * calls of usbEthLinkStatus() gets correct status. 
      */  
      (void) usbEthLinkStatus(uec);
        /* start link status timer */
        UE_LOG("%s: kick off timer\n", __FUNCTION__);
        rv = IOS_SendMessage(uec->monMsgQ, USBETH_MSG_TIMER, IOS_MESSAGE_BLOCK);
        if (rv != IOS_ERROR_OK) {
            UE_ERROR("%s: unable to kick off timer, rv = %d\n", __FUNCTION__, rv);
            goto out;
        } 
        uec->netState = USBETH_NETSTATE_UP; /* Set internal state */
    } else {
        if (uec->netState == USBETH_NETSTATE_DOWN) { /* Already down*/
            goto out;
        }
        /* bring down the device, may not succeed */
        (void) usbEthDevDown(uec);
        /* notify IP stack */
        rv = usbEthNotify(uec, NET_NOTIFY_DEV_DOWN);
        if (rv < 0) {
            UE_ERROR("%s: notify device up/down, rv = %d\n", __FUNCTION__, rv);
            /* ignore error, fall through */
            rv = IOS_ERROR_OK;
        }
        /* set internal state */
        uec->netState = USBETH_NETSTATE_DOWN;
    }
out:
    UE_LOG("%s: sending reply %d to request %p\n", __FUNCTION__, rv, __upDownReq);
    IOS_ResourceReply(__upDownReq, rv);
    __upDownReq = NULL;
    UNLOCK_NET_UPDOWN();
    return;
}

/*
 * usbEthMonThread -- dongle/cable monitor thread
 *
 * standalone thread which monitors the dongle/cable insertion
 * and removal
 */

static void
usbEthMonThread(u32 arg)
{
    UsbEthContext *uec = (UsbEthContext *)arg;
    IOSError rv, rv1;
    IOSMessage monMsgArray[USBETH_MSGQ_SIZE], msg;
    IOSResourceRequest oh0StateMsg;
    IOSResourceRequest ehcStateMsg;
    u8 oh0Buffer[IUSB_DEVINSERT_BUFSIZE];
    u8 ehcBuffer[IUSB_DEVINSERT_BUFSIZE];
    u16 vid __attribute__((aligned(32)));
    u16 pid __attribute__((aligned(32)));
    u32 devClass __attribute__((aligned(32)));
    u32 probeDev = 1;

    UE_LOG("%s: entry\n", __FUNCTION__);

    vid = AX_VID;
    pid = AX_PID;
    devClass = 0;

    /*
     * create message queue
     *
     * the message queue can handle four kinds of messages, one from
     * the link status timer, one from the dongle status, one from
     * the main thread to kill the monitor thread, and the last one
     * also from the main thread to signal network up/down
     *
     * although sending network up/down messages in a loop could
     * potentially flood this queue and causes insertion/removal
     * notification to be lost, this shouldn't happen in real life
     * usage
     */
    uec->monMsgQ = rv = IOS_CreateMessageQueue(monMsgArray, sizeof(monMsgArray)/sizeof(IOSMessage));
    if ( rv < 0 ) {
        UE_ERROR("%s: unable to create monitor message queue, rv = %d\n",
                 __FUNCTION__, rv);
        goto out;
    }

    /* allocate timer */
    uec->tmId = rv = IOS_CreateTimer((IOSTime)0, (IOSTime)0, uec->monMsgQ, USBETH_MSG_TIMER);
    if ( rv < 0 ) {
        UE_ERROR("%s: unable to create timer, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    oh0RegId = 0;
    ehcRegId = 0;

    while (1) {
        /* register for dongle insertion/removal event */
        if (probeDev) {
            if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
                oh0RegId = 0;
                rv = IUSB_RegisterInsertionNotifyWithId(AX_OH0, uec->monMsgQ, &oh0StateMsg, &vid, &pid, (u8 *) &devClass, &oh0RegId, oh0Buffer);
                if ((rv == IOS_ERROR_OK && oh0RegId != 0) || rv != IOS_ERROR_OK) {
                    ehcRegId = 0;
                    rv1 = IUSB_RegisterInsertionNotifyWithId(AX_EHC, uec->monMsgQ, &ehcStateMsg, &vid, &pid, (u8 *) &devClass, &ehcRegId, ehcBuffer);
                } else {
                    rv1 = -1;
                }
                if (rv != IOS_ERROR_OK && rv1 != IOS_ERROR_OK) {
                    /* sleep for 1 sec, then re-try */
                    UE_ERROR("%s: unable to register for insertion event, rv(OH0) = %d rv(EHC) = %d\n", __FUNCTION__, rv, rv1);
                    usleep(1e6);
                    continue;
                }
            } else {
                if ( (rv = IUSB_RegisterRemovalNotify(uec->ethHw.usbFd, uec->monMsgQ, &oh0StateMsg)) != IOS_ERROR_OK) {
                    /* device has been removed prior to the call, re-try */
                    UE_ERROR("%s: unable to register for removal event, rv = %d\n", __FUNCTION__, rv);
                    (void) usbEthDevShutdown(uec);
                    continue;
                }
            }
        }

        probeDev = 0;

        /* Wait for probe reply message */
        UE_LOG("%s: waiting for msg\n", __FUNCTION__);
        if ( (rv = IOS_ReceiveMessage(uec->monMsgQ, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: IOS_ReceiveMessage failed, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }
        UE_LOG("%s: received message 0x%x (%d)\n", __FUNCTION__, msg, msg);

        /* handle the message */
        switch (msg) {
            case USBETH_MSG_NETUP:
            case USBETH_MSG_NETDOWN:
                __handleNetUpDown(uec, msg);
                break;
            case USBETH_MSG_TIMER:
                /* refresh link status */
                rv = usbEthLinkStatus(uec);

                /* detect change in link status */
                if ( rv != IOS_ERROR_OK && uec->linkStatus == USBETH_LINKSTATE_UP ) {
                    /* stop receive thread */
                    UE_LOG("%s: stop receive thread\n", __FUNCTION__);
                    if ( (rv = usbEthStopRecvThread(uec)) != IOS_ERROR_OK ) {
                        UE_ERROR("%s: unable to stop receive thread, rv = %d\n", __FUNCTION__, rv);
                        goto out;
                    }

                    if ( (rv = usbEthNotify(uec, NET_NOTIFY_DEV_DOWN)) < 0 ) {
                        UE_LOG("%s: notify device down\n", __FUNCTION__);
                        /* ignore error since network may be down, fall through */
                    }
                    uec->linkStatus = USBETH_LINKSTATE_DOWN;
                } else if ( rv == IOS_ERROR_OK && uec->linkStatus == USBETH_LINKSTATE_DOWN ) {
                    /* start receive thread */
                    UE_LOG("%s: start receive thread\n", __FUNCTION__);
                    if ( (rv = usbEthStartRecvThread(uec)) != IOS_ERROR_OK ) {
                        UE_ERROR("%s: unable to start receive thread, rv = %d\n", __FUNCTION__, rv);
                        goto out;
                    }

                    if ( (rv = usbEthNotify(uec, NET_NOTIFY_DEV_UP)) < 0 ) {
                        UE_LOG("%s: notify device down\n", __FUNCTION__);
                        /* ignore error since network may be down, fall through */
                    }

                    uec->linkStatus = USBETH_LINKSTATE_UP;
                }

                /* re-start link status timer if network still up */
                if ( uec->netState == USBETH_NETSTATE_UP ) {
                    UE_LOG("%s: stop timer\n", __FUNCTION__);
                    if ( (rv = IOS_StopTimer(uec->tmId)) != IOS_ERROR_OK ) {
                        UE_ERROR("%s: unable to stop timer, rv = %d\n", __FUNCTION__, rv);
                        goto out;
                    }

                    UE_LOG("%s: start timer (1 sec heartbeat)\n", __FUNCTION__);
                    if ( (rv = IOS_RestartTimer(uec->tmId, 1000000, 0)) != IOS_ERROR_OK ) {
                        UE_ERROR("%s: unable to start timer, rv = %d\n", __FUNCTION__, rv);
                        goto out;
                    }
                }

                break;

            case USBETH_MSG_KILLMON:
                /* exit while-loop */
                goto out;

            default:
                /* must be state change event, do sanity check */
                if (msg != (IOSMessage) &oh0StateMsg 
                        && msg != (IOSMessage) &ehcStateMsg) {
                    UE_ERROR("%s: received bad msg = 0x%x\n",  msg);
                    goto out;
                }
                if (IUSB_ERROR_CANCELLED == ((IOSResourceRequest *)msg)->status) {
                    /* Do nothing */
                    break;
                }
                memset(&oh0StateMsg, 0, sizeof(IOSResourceRequest));
                memset(&ehcStateMsg, 0, sizeof(IOSResourceRequest));
                if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
                    UE_LOG("received device connect message\n");
                    /* initialize and bring up device */
                    (void) usbEthDevInit(uec);
                    if ( uec->netState == USBETH_NETSTATE_UP ) {
                        (void) usbEthDevUp(uec);
                    }
                } else {
                    UE_LOG("received device disconnect message\n");
                    /* de-initialize device */
                    (void) usbEthDevShutdown(uec);
                }

                /* check for insertion/removal */
                probeDev = 1;
                break;
        }
    }

out:
    if ( (rv = usbEthStopRecvThread(uec)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to stop receive thread, rv = %d\n", __FUNCTION__, rv);
        /* ignore error, fall through */
    }

    (void) usbEthDevDown(uec);
    (void) usbEthDevShutdown(uec);

    if ( (rv = IOS_DestroyTimer(uec->tmId)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to destroy timer %d, rv = %d\n", __FUNCTION__, uec->tmId, rv);
        /* ignore error, fall through */
    }

    uec->tmId = -1;

    if ( (rv = IOS_DestroyMessageQueue(uec->monMsgQ)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to destroy msgQ %d, rv = %d\n", __FUNCTION__, uec->monMsgQ, rv);
        /* ignore error, fall through */
    }

    uec->monMsgQ = -1;

    UE_LOG("%s: exiting MonThread, rv = %d\n", __FUNCTION__, rv);
}

/*
 * usbEthOpen -- open usbeth device
 *
 * return IOS_ERROR_OK on success, else error code
 */ 
static IOSError
usbEthOpen(IOSResourceRequest *req, IOSMessageQueueId qid)
{
    IOSResourceOpen *args = &req->args.open;
    IOSError rv = IOS_ERROR_OK;
    UsbEthContext *uec = (UsbEthContext *)0x0;

    /* check user-specified path against paths handled by this RM */
    UE_LOG("%s: opening \"%s\"\n", __FUNCTION__, args->path);
    if ( strncmp(args->path, NET_RM_USBETH_TOP, sizeof(NET_RM_USBETH_TOP)) != 0 ) {
        UE_ERROR("%s: %s is not a usbeth device\n", __FUNCTION__, args->path);
        rv = IOS_ERROR_NOEXISTS;
        goto out;
    }

    /* determine if device already opened */
    if ( usbEthContext[0].netState != USBETH_NETSTATE_CLOSED ) {
        UE_ERROR("%s: %s is already open\n", __FUNCTION__, args->path);
        rv = IOS_ERROR_MAX;
        goto out;
    }

    /* initialize context */
    uec = &usbEthContext[0];

    uec->devState = USBETH_DEVSTATE_REMOVED;
    uec->netState = USBETH_NETSTATE_DOWN;
    uec->ipbFd = -1;
    memset((void *) &uec->stats, 0, sizeof(uec->stats));
    memset((void *) &uec->defLinkInfo, 0, sizeof(uec->defLinkInfo));
    memset((void *) &uec->linkInfo, 0, sizeof(uec->linkInfo));
    uec->linkStatus = USBETH_LINKSTATE_DOWN;
    memset((void *) &uec->mcast, 0, sizeof(uec->mcast));
    /* uec->iobufDebugInfo = 0; */  /* struct not defined yet */
    uec->monId = -1;
    uec->monMsgQ = -1;
    uec->rxId = -1;
    uec->rxRunning = 0;
    uec->rxMsgQ = -1;
    uec->tmId = -1;

    /* open IP bottom-half device */
    if ( (uec->ipbFd = rv = IOS_Open(NET_RM_IP_BOT, 0)) < 0 ) {
        UE_ERROR("%s: %s open failed with rv = %d\n", __FUNCTION__, NET_RM_IP_BOT, rv);
        goto out;
    }
    UE_LOG("%s: ip success!\n", __FUNCTION__);

    /* start a separate thread to monitor dongle/cable insertion and removal */
    uec->monId = IOS_CreateThread(usbEthMonThread, (void *) uec,
                      _monStack + USBETH_MON_STACK_SIZE, USBETH_MON_STACK_SIZE,
                      USBETH_MON_PRIORITY, IOS_THREAD_CREATE_JOINABLE);
    if ( uec->monId < 0 ) {
        rv = uec->monId;
        UE_ERROR("%s: nCreateThread failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    rv = IOS_StartThread(uec->monId);
    if ( rv != IOS_ERROR_OK ) {
        UE_ERROR("%s: StartThread failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* lower the priority of current thread */
    rv = IOS_SetThreadPriority(0, USBETH_MAIN_PRIORITY);
    if ( rv != IOS_ERROR_OK ) {
        UE_ERROR("%s: SetThreadPriority failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    rv = (IOSError) uec;
    
out:
    if ( uec != 0x0 && rv < 0 ) {
        IOSError rv2;

        if ( uec->ipbFd >= 0 ) {
            if ( (rv2 = IOS_Close(uec->ipbFd)) < 0 ) {
                UE_ERROR("%s: unable to close %s, rv = %d\n", __FUNCTION__,
                         NET_RM_IP_BOT, rv2);
                /* ignore error, fall through */
            }
        }

        if ( uec->monId >= 0 ) {
            u32 val;
            if ( (rv2 = IOS_DestroyThread(uec->monId, &val)) < 0 ) {
                UE_ERROR("%s: unable to destroy thread %d, rv = %d\n",
                        __FUNCTION__, uec->monId, rv2);
                /* ignore error, fall through */
            }
        }
    }
    UE_LOG("%s: exiting with rv = %d (0x%x)\n", __FUNCTION__, rv, rv);
    return rv;
}

/*
 * usbEthClose -- close the usbeth device
 *
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthClose(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    UsbEthContext *uec = (UsbEthContext *) req->handle;

    UE_LOG("%s: entry\n", __FUNCTION__);

    /* determine if device already closed */
    if (uec->netState == USBETH_NETSTATE_CLOSED) {
        UE_ERROR("%s: already closed\n", __FUNCTION__);
        rv = IOS_ERROR_NOTREADY;
        goto out;
    }

    /* raise priority back to highest */
    rv = IOS_SetThreadPriority(0, IOS_PRIORITY_USBETH);
    if ( rv != IOS_ERROR_OK ) {
        UE_ERROR("%s: SetThreadPriority failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* send shutdown message to monitor thread */
    if ( (rv = IOS_SendMessage(uec->monMsgQ, USBETH_MSG_KILLMON, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to send stop message, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* wait for monitor thread to exit */
    UE_LOG("%s: waiting for monitor thread to exit\n", __FUNCTION__);
    if ( (rv = IOS_JoinThread(uec->monId, 0x0)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to join monitor thread, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    UE_LOG("%s: monitor thread has exited properly\n", __FUNCTION__);
        
    uec->monId = -1;

    /* close connection to IP stack */
    if ( uec->ipbFd >= 0 && (rv = IOS_Close(uec->ipbFd)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: unable to close IP stack connection, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
    uec->ipbFd = -1;
    
    /* mark as closed */
    uec->netState = USBETH_NETSTATE_CLOSED;
    
out:
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/* Save resource request in __upDownReq.
 * Monitor thread will send reply when UP/DOWN actions 
 * are done. This is needed to preserve pre-hotplug
 * semantics for DEV_UP/DEV_DOWN commands.
 */
static IOSError
__handleNetDevUpDown(UsbEthContext *uec, IOSResourceRequest *req, u32 msg)
{
    IOSError rv = IOS_ERROR_OK;

    UE_LOG("%s: NET_DEV_UP/DOWN\n", __FUNCTION__);

    LOCK_NET_UPDOWN();
    __upDownReq = req;
    rv = IOS_SendMessage(uec->monMsgQ, 
            (NET_DEV_UP == msg)? USBETH_MSG_NETUP : USBETH_MSG_NETDOWN,
            IOS_MESSAGE_BLOCK);
    UNLOCK_NET_UPDOWN();
    
    if (rv != IOS_ERROR_OK) {
        UE_ERROR("%s: unable to send NET UP/DOWN message, rv = %d\n", __FUNCTION__, rv);
    }

    return rv;
}

/*
 * usbEthIoctlv -- perform IOCTLV operations
 * Send reply for most commands. For net UP/DOWN, the
 * monitor thread sends replies.
 * return IOS_ERROR_OK on success, else error code
 */
static IOSError
usbEthIoctlv(IOSResourceRequest *req)
{
    IOSResourceIoctlv *ioctlv;
    IOSError rv = IOS_ERROR_INVALID;
    UsbEthContext *uec = (UsbEthContext *) req->handle;
    IOSIobuf *iob;

    ioctlv = &req->args.ioctlv;

    UE_LOG("%s: cmd=%d\n", __FUNCTION__, ioctlv->cmd);

    switch (ioctlv->cmd) {
        case NET_DEV_XMIT_PKT:
            UE_LOG("%s: NET_DEV_XMIT_PKT\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 1 || ioctlv->writeCount != 0 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != sizeof(IOSIobuf) ) {
                goto reply;
            }

            /* check link state */
            if ( uec->linkStatus != USBETH_LINKSTATE_UP ) {
                UE_ERROR("%s: link not established, can't send packet\n", __FUNCTION__);
                uec->stats.outErrors++;
                rv = IOS_ERROR_NOTREADY;
                goto reply;

            }

            /* check packet size */
            iob = (IOSIobuf *) ioctlv->vector[0].base;
            if ( iob->dataLen < ETH_MIN_PACKET_SIZE || iob->dataLen > ETH_MAX_PACKET_SIZE ) {
                UE_ERROR("%s: invalid packet size = %d\n", __FUNCTION__, iob->dataLen);
                uec->stats.outErrors++;
                rv = IOS_ERROR_INVALID_SIZE;
                goto reply;
            } 
#ifdef DUMP_PACKET
            dumpPacket( iob->data, iob->dataLen, "NET_DEV_XMIT_PKT");
#endif

            /* write packet to ethernet hardware */
            rv = axXmitPacket(&uec->ethHw, iob);
            if ( rv == IOS_ERROR_FAIL_ALLOC ) {
                uec->stats.outDiscards++;
            } else if ( rv < 0 ) {
                uec->stats.outErrors++;
            }
            if( rv < 0  ) {
                UE_ERROR("%s: WriteBlkMsg failed, rv = %d\n", __FUNCTION__, rv);
                rv = IOS_ERROR_FAIL_INTERNAL;
                goto reply;
            }

            /* update sent-packet statistics */
            ETHHeader *eh = (ETHHeader *) iob->data;
#ifdef DUMP_PACKET
            dumpPacket( iob->data, iob->dataLen, "NET_DEV_XMIT_PKT2");
#endif

            if ( ETH_ADDR_UNICAST(eh->dst[0]) ) {
                uec->stats.outUcastPackets++;
            } else {
                uec->stats.outNonUcastPackets++;
            }

            /* free buffer that packets used to occupy */
            if ( (rv = IOS_FreeIob(iob)) != IOS_ERROR_OK ) {
                UE_ERROR("%s: failed to free iob @ 0x%x, rv = %d\n",
                        __FUNCTION__, (u32)iob, rv);
                /* ignore error, fall through */
            }

            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_UP:
        case NET_DEV_DOWN:
            rv = __handleNetDevUpDown(uec, req, ioctlv->cmd);
            if (rv < 0) {
                goto reply;
            }
            goto out;

        case NET_DEV_SET_MULTICAST_LIST:
            UE_LOG("%s: NET_DEV_SET_MULTICAST_LIST\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 1 || ioctlv->writeCount != 0 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != sizeof(NETMcAddrList) ) {
                goto reply;
            }

            /* check multicast settings for validity */
            NETMcAddrList *mcast = (NETMcAddrList *)ioctlv->vector[0].base;
            if ( mcast->count > NET_MAX_MC_ADDR ) {
                UE_ERROR("%s: invalid multicast address count = %d\n", __FUNCTION__,
                        mcast->count);
                rv = IOS_ERROR_INVALID_SIZE;
                goto reply;
            }

            /* copy multicast info into device context */
            memcpy((void *) &uec->mcast, mcast, sizeof(NETMcAddrList));

            /* check device is inserted */
            if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
                UE_ERROR("%s: device not inserted", __FUNCTION__);
                rv = IOS_ERROR_NOTREADY;
                goto reply;
            }

            /* reconfigure hardware multicast filter */
            LOCK_USBETH();
            if ( (rv = axConfigMulticast(&uec->ethHw, (NETMcAddrList *) &uec->mcast)) != IOS_ERROR_OK ) {
                UNLOCK_USBETH();
                UE_ERROR("%s: usbEthConfigMulticast failed, rv = %d\n", __FUNCTION__, rv);
                goto reply;
            }
            UNLOCK_USBETH();
            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_SET_MAC_ADDRESS:
            UE_LOG("%s: NET_DEV_SET_MAC_ADDRESS\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 1 || ioctlv->writeCount != 0 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != ETH_ALEN ) {
                goto reply;
            }

            /* check device is inserted */
            if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
                UE_ERROR("%s: device not inserted", __FUNCTION__);
                rv = IOS_ERROR_NOTREADY;
                goto reply;
            }

            /* set hardware MAC address as specified */
            LOCK_USBETH();
            if ( (rv = axWriteMac(&uec->ethHw, ioctlv->vector[0].base)) < 0 ) {
#if defined(UE_DEBUG) || defined(UE_DEBUG_ERROR)
                u8 *mac = ioctlv->vector[0].base;
#endif
                UNLOCK_USBETH();
                UE_ERROR("%s: unable to write MAC address (%d-%d-%d-%d-%d-%d, 0x%x-%x-%x-%x-%x-%x), rv = %d\n",
                        __FUNCTION__,
                        mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
                        mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
                        rv);
                rv = IOS_ERROR_FAIL_INTERNAL;
                goto reply;
            }
            UNLOCK_USBETH();
            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_GET_MAC_ADDRESS:
            UE_LOG("%s: NET_DEV_GET_MAC_ADDRESS\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 0 || ioctlv->writeCount != 1 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != ETH_ALEN ) {
                goto reply;
            }

            /* check device is inserted */
            if ( uec->devState == USBETH_DEVSTATE_REMOVED ) {
                UE_ERROR("%s: device not inserted", __FUNCTION__);
                rv = IOS_ERROR_NOTREADY;
                goto reply;
            }

            /* get MAC address from hardware */
            LOCK_USBETH();
            if ( (rv = axReadMac(&uec->ethHw, ioctlv->vector[0].base)) < 0 ) {
                UNLOCK_USBETH();
                UE_ERROR("%s: unable to read MAC address, rv = %d\n", __FUNCTION__, rv);
                rv = IOS_ERROR_FAIL_INTERNAL;
                goto reply;
            }
            UNLOCK_USBETH();
            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_GET_STATS:
            UE_LOG("%s: NET_DEV_GET_STATS\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 0 || ioctlv->writeCount != 1 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != sizeof(IPInterfaceStat) ) {
                goto reply;
            }

            /* copy statistics into user's buffer */
            memcpy(ioctlv->vector[0].base, (IPInterfaceStat *) &uec->stats, sizeof(IPInterfaceStat));
            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_SET_ETHTOOL:
            UE_LOG("%s: NET_DEV_SET_ETHTOOL\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 1 || ioctlv->writeCount != 0 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != sizeof(NETEthTool) ) {
                UE_ERROR("%s: rc=%d, wc=%d, base=0x%x, len=%d(%d)\n",
                        __FUNCTION__, ioctlv->readCount, ioctlv->writeCount,
                        (u32) ioctlv->vector[0].base,
                        ioctlv->vector[0].length, sizeof(NETEthTool));
                goto reply;
            }

            /* check that device is inserted and link is down */
            if ( uec->devState != USBETH_DEVSTATE_DOWN ) {
                UE_ERROR("%s: link isn't down, can't set ethtool\n");
                rv = IOS_ERROR_NOTREADY;
                goto reply;
            }

            /* check link config settings for validity */
            NETEthTool *et = (NETEthTool *)ioctlv->vector[0].base;
            NETEthTool *det = (NETEthTool *)&uec->defLinkInfo;
            if ( et->supported != det->supported ) {
                UE_ERROR("%s: 'supported' field cannot be modified, must be set to 0x%x\n",
                        __FUNCTION__, det->supported);
                rv = IOS_ERROR_INVALID_FLAG;
                goto reply;
            }

            if ( et->advertising & ~et->supported ) {
                UE_ERROR("%s: cannot advertise features (0x%x) that aren't supported (0x%x)\n",
                        __FUNCTION__, et->advertising, et->supported);
                rv = IOS_ERROR_INVALID_FLAG;
                goto reply;
            }

            if ( et->autoneg ) {
                if ( !(det->supported & NET_SUPPORTED_AUTONEG) ) {
                    UE_ERROR("%s: autoneg selected, but not supported\n", __FUNCTION__);
                    rv = IOS_ERROR_INVALID_FLAG;
                    goto reply;
                } else if ( !(et->advertising & NET_SUPPORTED_AUTONEG) ) {
                    UE_ERROR("%s: autoneg selected, but not advertised\n", __FUNCTION__);
                    rv = IOS_ERROR_INVALID_FLAG;
                    goto reply;
                }
            } else {
                if ( et->speed == NET_SPEED_10 ) {
                    if ( et->duplex == NET_DUPLEX_HALF && !(det->supported & NET_SUPPORTED_10BASET_HALF) ) {
                        UE_ERROR("%s: 10Mbps half-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } else if ( et->duplex == NET_DUPLEX_FULL && !(det->supported & NET_SUPPORTED_10BASET_FULL) ) {
                        UE_ERROR("%s: 10Mbps full-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } 
                } else if ( et->speed == NET_SPEED_100 ) {
                    if ( et->duplex == NET_DUPLEX_HALF && !(det->supported & NET_SUPPORTED_100BASET_HALF) ) {
                        UE_ERROR("%s: 100Mbps half-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } else if ( et->duplex == NET_DUPLEX_FULL && !(det->supported & NET_SUPPORTED_100BASET_FULL) ) {
                        UE_ERROR("%s: 100Mbps full-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } 
                } else if ( et->speed == NET_SPEED_1000 ) {
                    if ( et->duplex == NET_DUPLEX_HALF && !(det->supported & NET_SUPPORTED_1000BASET_HALF) ) {
                        UE_ERROR("%s: 1000Mbps half-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } else if ( et->duplex == NET_DUPLEX_FULL && !(det->supported & NET_SUPPORTED_1000BASET_FULL) ) {
                        UE_ERROR("%s: 1000Mbps full-duplex selected, but not supported\n", __FUNCTION__);
                        rv = IOS_ERROR_INVALID_FLAG;
                        goto reply;
                    } 
                } else {
                    UE_ERROR("%s: no autoneg and no speed selected\n", __FUNCTION__);
                    rv = IOS_ERROR_INVALID_FLAG;
                    goto reply; 
                }
            }

            /* copy desired link config info into device context */
            LOCK_USBETH();
            memcpy((void *) &uec->linkInfo, ioctlv->vector[0].base, sizeof(NETEthTool));
            UNLOCK_USBETH();
            rv = IOS_ERROR_OK;
            break;

        case NET_DEV_GET_ETHTOOL:
            UE_LOG("%s: NET_DEV_GET_ETHTOOL\n", __FUNCTION__);
            /* check input parameters */
            if ( ioctlv->readCount != 0 || ioctlv->writeCount != 1 ||
                    ioctlv->vector[0].base == 0x0 ||
                    ioctlv->vector[0].length != sizeof(NETEthTool) ) {
                goto reply;
            }

            /* copy link config info into user's buffer */
            LOCK_USBETH();
            memcpy(ioctlv->vector[0].base, (void *) &uec->linkInfo, sizeof(NETEthTool));
            UNLOCK_USBETH();
            rv = IOS_ERROR_OK;
            break;

        default:
            UE_ERROR("%s: unknown command = %d (0x%x)\n", __FUNCTION__, ioctlv->cmd, ioctlv->cmd);
            break;
    }
    /* Fall through and send reply */

reply:
    /* Note: Caller doesn't send replies for ioctlv's, because of the NET 
     *        UP/DOWN special case. 
     */
    IOS_ResourceReply(req, rv);

out:
    UE_LOG("%s: exit\n", __FUNCTION__);
    return rv;
}

/*
 * main
 *
 * allocate resources for usbeth Resource Manager (RM), register the
 * RM, then enter an infinite loop processing requests
 */
int main(void)
{   
    IOSMessageQueueId qid;
    IOSMessage msgQ[USBETH_MSGQ_SIZE];
    IOSMessage msg;
    IOSError rv;
    
    printf("%s\n", __version);
    UE_LOG("%s: *** USB Ethernet RM Starting ***\n", __FUNCTION__);

    /* Create usbeth mutex */
    if ( (__usbEthMutex = usbEthCreateMutex(__usbEthMutexQueue)) < 0 ) {
        rv = __usbEthMutex;
        UE_ERROR("%s: usbEthCreateMutex failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
    /* Create up/down mutex */
    if ( (__netUpDownMutex = usbEthCreateMutex(__netUpDownMutexQueue)) < 0 ) {
        rv = __netUpDownMutex;
        UE_ERROR("%s: usbEthCreateMutex failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }

    /* Create a RM message queue for usb-eth interface layer */
    if ( (qid = rv = IOS_CreateMessageQueue(msgQ, USBETH_MSGQ_SIZE)) < 0 ) {
        UE_ERROR("%s: IOS_CreateMessageQueue failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
    
    /* Register RM */
    if ( (rv = IOS_RegisterResourceManager(NET_RM_USBETH_TOP, qid)) != IOS_ERROR_OK ) {
        UE_ERROR("%s: RegisterResourceManager failed, rv = %d\n", __FUNCTION__, rv);
        goto out;
    }
                
    /* Sit in a loop processing requests */
    while (1) {
        IOSResourceRequest *req;
        IOSResourceOpen *openArgs;

        /* block waiting for a request */
        UE_LOG("%s: waiting for msg\n", __FUNCTION__);
        if ( (rv = IOS_ReceiveMessage(qid, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
            UE_ERROR("%s: IOS_ReceiveMessage failed, rv = %d\n", __FUNCTION__, rv);
            goto out;
        }
        UE_LOG("%s: received message = 0x%08x\n", __FUNCTION__, (u32)msg);

        req = (IOSResourceRequest *)msg;

        /* determine the type of request and process it */
        switch (req->cmd) {
        case IOS_OPEN:
            UE_LOG("%s: IOS_OPEN\n", __FUNCTION__);
            openArgs = (IOSResourceOpen *) &(req->args.open);
            if (openArgs->uid != IOS_NET_PROCESS) {
                rv = IOS_ERROR_ACCESS;
            } else {
                rv = usbEthOpen(req, qid);
            }
            UE_LOG("%s: IOS_OPEN returning rv = %d\n", __FUNCTION__, rv);
            break;
        case IOS_CLOSE:
            UE_LOG("%s: IOS_CLOSE\n", __FUNCTION__);
            rv = usbEthClose(req);
            UE_LOG("%s: IOS_CLOSE returning rv = %d\n", __FUNCTION__, rv);
            break;
        case IOS_IOCTLV:
            UE_LOG("%s: IOS_IOCTLV\n", __FUNCTION__);
            rv = usbEthIoctlv(req); /* Sends replies when needed */
            UE_LOG("%s: IOS_IOCTLV returning rv = %d\n", __FUNCTION__, rv);
            continue; /* Don't send reply */

        default:
            rv = IOS_ERROR_INVALID;
            UE_LOG("%s: unknown command = %d (0x%x) returning rv = %d\n", __FUNCTION__, req->cmd, req->cmd, rv);
            break;
        }
        IOS_ResourceReply(req, rv);
    }

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