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

/*---------------------------------------------------------------------------*
 * 
 * Network Device Interface Layer
 * 
 *---------------------------------------------------------------------------*/

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <iosresource.h>
#include <iosiobuf.h>

#include <iop_ethtool.h>
#include <iop_netif.h>
#include <dolphin/os.h>
#include <dolphin/ip.h>
#include "private/eth.h" 

/*---------------------------------------------------------------------------*
 * 
 * global variables
 * 
 *---------------------------------------------------------------------------*/

static IOSFd __fdUsbEthRM = -1;
static IOSFd __fdWdRM = -1;
static IOSIobDebugInfo __iobufDebugInfo;
static u32 __ifID = NET_IF_ETH_USB;
extern IPInterface __IFDefault;
extern IOSMessageQueueId netXmitQid;
static ETHXmitMsg netXmitMsg;
static NETMcAddrList __mcAddrList;
u32 netMuted = 1;

static IOSFd
getDevFd(u32 ifID)
{
    IOSFd fd = -1;

    if (ifID == NET_IF_ETH_USB) {
        if (__fdUsbEthRM < 0) {
            __fdUsbEthRM = IOS_Open(NET_RM_USBETH_TOP, 0);
            if (__fdUsbEthRM < 0)
                OSReport("%s: can not open usb-ethernet RM\n", __FUNCTION__);
        }
        fd = __fdUsbEthRM;
    } else if (ifID == NET_IF_ETH_WIFI) {
        if (__fdWdRM < 0) {
            __fdWdRM = IOS_Open(NET_RM_WD_TOP, 0);
            if (__fdWdRM < 0)
                OSReport("%s: can not open WD RM\n", __FUNCTION__);
        }
        fd = __fdWdRM;
    }

    return fd;
}

s32
ETHInit(s32 mode)
{
    IOSError ret;
    IOSFd fd = -1;

    if (mode == IF_TYPE_WIFI) {
        __ifID = NET_IF_ETH_WIFI;
        fd = getDevFd(NET_IF_ETH_WIFI);
    } else {
        __ifID = NET_IF_ETH_USB;
        fd = getDevFd(NET_IF_ETH_USB);
    }

    ret = IOS_Ioctlv(fd, NET_DEV_UP, 0, 0, NULL);
    if (ret != IOS_ERROR_OK) {
        /*
         * This should only fail in case of a catastrophic
         * failure (e.g. USB not accessible). Link up/down
         * or dongle insertion/removal should be handled
         * separately. In addition, the stack code doesn't
         * seem to handle the case when ETHInit() returns
         * an error correctly, so just print out the error
         * here and don't return it to the caller
         */
        OSReport("NET_DEV_UP Ioctl returns rc=%d\n", ret);
    }
    ret = ETH_OK;

    /* Initialize to not used */
    netXmitMsg.used = 0;

    memset(&__mcAddrList, 0, sizeof(__mcAddrList));

    return ret;
}

void
ETHSendAsync(void *addr, s32 length, ETHCallback2 callback2)
{
    IOSFd fd;
    u32 * ptr;
    IOSIobuf * iob;

    /*
     * Only one xmit message can be outstanding at any time.
     * A NULL iob indicates an error, but the xmit thread
     * will still need to trigger the callback so that other
     * messages can be sent
     */
    ASSERT(netXmitMsg.used == 0);
    netXmitMsg.used = 1;
    netXmitMsg.iob = NULL;
    netXmitMsg.callback = callback2;

    fd = getDevFd(__ifID);
    if (fd < 0)
        goto error;

    /* Set the tranport file descriptor */
    netXmitMsg.fd = fd;

    if (IOS_AccessIobPool(POOL_DEFAULT) != IOS_ERROR_OK) {
        OSReport("%s: getting access to iobuf pool failed\n", __FUNCTION__);
        goto error;
    }

    iob = IOS_AllocIob(POOL_DEFAULT, length+NET_IP_DRV_RESERVE, __iobufDebugInfo);
    if (!iob) {
        OSReport("%s: allocating iobuf failed\n", __FUNCTION__);
        goto error;
    }

    IOS_IOB_RESERVE(iob, NET_IP_DRV_RESERVE);
    ptr = (u32 *) IOS_PutIob(iob, length);
    memcpy(ptr, addr, length);

    /* Send a request to the xmit thread */
    netXmitMsg.iob = iob;

error:
    /*
     * Since only one message can be outstanding at any time, we
     * should not hit queue full here. Put an ASSERT to catch
     * any errors
     */
    ASSERT(IOS_SendMessage(netXmitQid, (IOSMessage) &netXmitMsg, IOS_MESSAGE_NOBLOCK) == IOS_ERROR_OK);
}

void
ETHGetMACAddr(u8 *macaddr)
{
    IOSFd fd;
    IOSIoVector v[1];

    fd = getDevFd(__ifID);
    if (fd < 0)
        return;

    v[0].base   = macaddr;
    v[0].length = ETH_ALEN;
    IOS_Ioctlv(fd, NET_DEV_GET_MAC_ADDRESS, 0, 1, v);
}

void
ETHSetMACAddr(u8* macaddr)
{
    IOSFd fd;
    IOSIoVector v[1];

    fd = getDevFd(__ifID);
    if (fd < 0)
        return;

    v[0].base   = macaddr;
    v[0].length = ETH_ALEN;
    IOS_Ioctlv(fd, NET_DEV_SET_MAC_ADDRESS, 1, 0, v);
}

void
ETHAddMulticastAddress(const u8* macaddr)
{
    IOSFd fd;
    IOSIoVector v[1];
    u8 *pos;
    int i;
    BOOL enabled;
    
    fd = getDevFd(__ifID);
    if (fd < 0)
        return;

    enabled = OSDisableInterrupts();

    // check if the macaddr is already being added
    pos = (u8 *) &__mcAddrList.mcAddr;
    for (i=0; i<__mcAddrList.count; i++)
    {
        if (memcmp(pos, macaddr, ETH_ALEN) == 0) {
            OSRestoreInterrupts(enabled);
            return;
        }
        pos += ETH_ALEN;
    }
    
    pos = (u8 *) &__mcAddrList.mcAddr;
    if (__mcAddrList.count == NET_MAX_MC_ADDR)
    {
        u8 *src, *dst;

        pos = pos + (NET_MAX_MC_ADDR-1) * ETH_ALEN;

        src = (u8 *) &__mcAddrList.mcAddr;
        dst = src + ETH_ALEN;
        memmove(src, dst, (NET_MAX_MC_ADDR-1) * ETH_ALEN);
    }
    else
    {
        pos = pos + __mcAddrList.count * ETH_ALEN;
        __mcAddrList.count++;
    }
    memcpy(pos, macaddr, ETH_ALEN);

    v[0].base   = (u8 *) &__mcAddrList;
    v[0].length = sizeof(NETMcAddrList);

    IOS_Ioctlv(fd, NET_DEV_SET_MULTICAST_LIST, 1, 0, v);

    OSRestoreInterrupts(enabled);

    return;
}

void
ETHClearMulticastAddresses(void)
{
    IOSFd fd;
    IOSIoVector v[1];
    BOOL enabled;
        
    fd = getDevFd(__ifID);
    if (fd < 0)
        return;

    enabled = OSDisableInterrupts();

    __mcAddrList.count = 0;

    v[0].base   = (u8 *) &__mcAddrList;
    v[0].length = sizeof(NETMcAddrList);

    IOS_Ioctlv(fd, NET_DEV_SET_MULTICAST_LIST, 1, 0, v);

    OSRestoreInterrupts(enabled);

    return;
}

void
ETHSetRecvCallback(ETHCallback0 callback0, ETHCallback1 callback1)
{
    BOOL enabled;

    /*
     * Ignore callback0, since it is used only for packet
     * filtering, which is already handled by ETHIn(). Also,
     * callback0 returns a receive buffer to be read in by
     * ETHIn(), but in our implementation we use IObufs instead
     */

    /*
     * As for callback1, it internally triggers ETHIn(). In our
     * implementation, we trigger ETHIn() directly, so it's not
     * needed. However, if callback1 is NULL, then we should set
     * the interface to mute (i.e. drop all receive packets)
     */
    enabled = OSDisableInterrupts();
    netMuted = (callback1 == NULL) ? 1 : 0;
    OSRestoreInterrupts(enabled);
}

void
ETHSetProtoType(u16 *array, s32 num)
{
    /*
     * Ignore this function, it seems that this is used only
     * for packet filtering, which is already handled by ETHIn()
     */
}
