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

#include <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <iosresource.h>
#include <iosiobuf.h>
#include <priority.h>
#include <iop_ethtool.h>
#include <iop_netif.h>
#include "dolphin/os.h"
#include "private/eth.h"
#include "IPPrivate.h"


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

char __netIfStack[NET_IF_STACK_SIZE] ATTRIBUTE_ALIGN(4);
char __netXmitStack[NET_XMIT_STACK_SIZE] ATTRIBUTE_ALIGN(4);
extern IPInterface __IFDefault;
IOSMessageQueueId netXmitQid;
extern u32 netMuted;

/*---------------------------------------------------------------------------*
 * 
 * Network Interface Resource Manager
 * 
 *---------------------------------------------------------------------------*/

/* check if pkts/control msgs are coming from the correct interface */
static BOOL
netIfMatched(u32 ifID)
{
    BOOL ifMatched = FALSE;

    switch( __IFDefault.type )
    {
        case IF_TYPE_AUTO:
        case IF_TYPE_100FULL:
        case IF_TYPE_100HALF:
        case IF_TYPE_10FULL:
        case IF_TYPE_10HALF:
            ifMatched = ( ifID == NET_IF_ETH_USB );
            break;

        case IF_TYPE_WIFI:
            ifMatched = ( ifID == NET_IF_ETH_WIFI );
            break;

        default:
            break;
    }

    return ifMatched;
}

static IOSError
netIfIoctlv(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceIoctlv *ioctlv = (IOSResourceIoctlv *) &req->args.ioctlv;
    BOOL         enabled;

    switch (ioctlv->cmd)
    {
        case NET_IP_RECV_PKT:
        {
            u32 ifID = *( (u32 *) ioctlv->vector[0].base);
            IOSIobuf * iob = (IOSIobuf *) ioctlv->vector[1].base;

            if (iob == NULL) {
                rv = IOS_ERROR_INVALID;
                break;
            }

            if ( !netIfMatched(ifID) ) {
                /* Silently drop it */
                IOS_FreeIob(iob);
                break;
            }

#ifdef _DEBUG
            if (ioctlv->vector[1].length != sizeof(IOSIobuf)) {
                OSReport("%s: the length for iobuf parameter is not correct\n", __FUNCTION__);
            }
#endif // _DEBUG
 
            /* Emulate external interrupt condition */
            enabled = OSDisableInterrupts();
            OSDisableScheduler();
            if (!netMuted) {
                ETHIn(&__IFDefault, (ETHHeader *) IOS_IOB_DATA(iob), IOS_IOB_DATA_LEN(iob));
            }
            OSEnableScheduler();
            OSYieldThread();
            OSRestoreInterrupts(enabled);

            IOS_FreeIob(iob);
            rv = 0;
        }
            break;

        case NET_IP_NOTIFY:
        {
            u32 ifID        = *( (u32 *) ioctlv->vector[0].base);
            int notifyID    = *( (int *) ioctlv->vector[1].base);

            if ( !netIfMatched(ifID) ) {
                /* Silently drop it */
                break;
            }

            /* Emulate external interrupt condition */
            enabled = OSDisableInterrupts();
            OSDisableScheduler();

            if (notifyID == NET_NOTIFY_DEV_UP)
            {
                __IFDefault.linkState = TRUE;

                if (!__IFDefault.up)
                {
                    ETHGetMACAddr(__IFDefault.mac);
                    memcpy((u8 *) &__IFDefault.seed + 2, __IFDefault.mac, ETH_ALEN);
                    __IFDefault.up = TRUE;
                    DHCPReboot();
                    if (IP_ADDR_NE(__IFDefault.alias, IPAddrAny))
                    {
                        IPAutoConfig();
                    }
                }
            }
            else if (notifyID == NET_NOTIFY_DEV_DOWN)
            {
                __IFDefault.linkState = FALSE;

                if (__IFDefault.up)
                {
                    __IFDefault.up = FALSE;
                    IPSetConfigError(&__IFDefault, IP_ERR_LINK_DOWN);
                }
            }

            OSEnableScheduler();
            OSYieldThread();
            OSRestoreInterrupts(enabled);

            rv = 0;
        }
            break;
            
        default:
            rv = IOS_ERROR_INVALID;
            break;
    }

    return rv;
}

static void
netIfRM(u32 arg)
{   
    IOSMessageQueueId qid;
    IOSMessage msgQ[NET_IF_MSGQ_SIZE];
    IOSError rv = IOS_ERROR_OK;
    IOSMessage msg;
    IOSResourceRequest *req;
    IOSResourceOpen *openArgs;

    OSDbgReport(("*** Network Device Interface Started ***\n"));

    /* Create a RM message queue for socket interface layer */
    qid = IOS_CreateMessageQueue(msgQ, NET_IF_MSGQ_SIZE);
    ASSERT(qid >= 0);
    
    /* Register RM */
    rv = IOS_RegisterResourceManager(NET_RM_IP_BOT, qid);
    ASSERT(rv == IOS_ERROR_OK);

    /* Sit in a loop processing requests */
    while(1) {
        IOS_ReceiveMessage(qid, &msg, IOS_MESSAGE_BLOCK);
        req = (IOSResourceRequest *)msg;
        switch(req->cmd) {
            case IOS_OPEN:
                /* Only accept the open request if it's from usbeth or NCD */
                openArgs = (IOSResourceOpen *) &(req->args.open);
                if ((openArgs->uid != IOS_USBETH_PROCESS) &&
                        (openArgs->uid != IOS_NCD_PROCESS)) {
                    rv = IOS_ERROR_ACCESS;
                } else {
                    rv = IOS_ERROR_OK;
                }

                break;

            case IOS_CLOSE:
                rv = IOS_ERROR_OK;
                break;

            case IOS_IOCTLV:
                rv = netIfIoctlv(req);
                break;

            default:
                OSReport("%s: Network IF RM got UNKNOWN request\n", __FUNCTION__);
                rv = IOS_ERROR_INVALID;
                break;
        }
        IOS_ResourceReply(req, rv);
    }

    OSDbgReport(("*** Network Device Interface Ended ***\n"));
    
    /* Unregister RM. Destroys message queue. */
    IOS_DestroyMessageQueue(qid);
    return;
}

static void
netXmitThr(u32 arg)
{   
    IOSMessage msgQ[NET_XMIT_MSGQ_SIZE];
    IOSError rv = IOS_ERROR_OK;
    IOSMessage msg;
    IOSIoVector v[1];
    ETHXmitMsg *xmitMsg;
    BOOL enabled;

    OSDbgReport(("*** Network Device Xmit Started ***\n"));

    /* Create a message queue for receiving network send requests */
    netXmitQid = IOS_CreateMessageQueue(msgQ, NET_XMIT_MSGQ_SIZE);
    ASSERT(netXmitQid >= 0);
    
    /* Sit in a loop processing requests */
    while(1) {
        rv = IOS_ReceiveMessage(netXmitQid, &msg, IOS_MESSAGE_BLOCK);
        if (rv != IOS_ERROR_OK) {
            OSReport("%s: ReceiveMessage failed in XMIT thread, rv=%d\n",
                __FUNCTION__, rv);
            continue;
        }
        xmitMsg = (ETHXmitMsg *) msg;
        ASSERT(xmitMsg->used == 1);

        if (xmitMsg->iob != NULL) {
            /* Transmit the message */
            v[0].base = (u8 *) xmitMsg->iob;
            v[0].length = sizeof (IOSIobuf);
            if ((rv = IOS_Ioctlv(xmitMsg->fd, NET_DEV_XMIT_PKT, 1, 0, v)) < 0) {
                IOS_FreeIob(xmitMsg->iob);
            }
        }

        /* Callback */
        xmitMsg->used = 0;

        /* Emulate external interrupt condition */
        enabled = OSDisableInterrupts();
        OSDisableScheduler();
        xmitMsg->callback(0);
        OSEnableScheduler();
        OSYieldThread();
        OSRestoreInterrupts(enabled);
    }

    OSDbgReport(("*** Network Device Xmit Ended ***\n"));
    
    /* Destroy message queue. */
    IOS_DestroyMessageQueue(netXmitQid);
    return;
}

void
NetInitIfRM(void)
{
    IOSThreadId ifThreadId, xmitThreadId;
    IOSError rv;

    /* Create the first thread for receiving requests from the network */
    ifThreadId = IOS_CreateThread(netIfRM, NULL, __netIfStack + sizeof(__netIfStack),
        sizeof(__netIfStack), IOS_PRIORITY_NET, IOS_THREAD_CREATE_DETACHED);
    ASSERT(ifThreadId >= 0);
    IOS_SetThreadPriority(ifThreadId, NET_DEVIF_PRIORITY);
    OSInitThread(ifThreadId, NET_DEVIF_PRIORITY);

    /* Create the second thread for sending requests to the network */
    xmitThreadId = IOS_CreateThread(netXmitThr, NULL, __netXmitStack + sizeof(__netXmitStack),
        sizeof(__netXmitStack), IOS_PRIORITY_NET, IOS_THREAD_CREATE_DETACHED);
    ASSERT(xmitThreadId >= 0);
    IOS_SetThreadPriority(xmitThreadId, NET_DEVXMIT_PRIORITY);
    OSInitThread(xmitThreadId, NET_DEVXMIT_PRIORITY);

    rv = IOS_StartThread(ifThreadId);
    ASSERT(rv == IOS_ERROR_OK);

    rv = IOS_StartThread(xmitThreadId);
    ASSERT(rv == IOS_ERROR_OK);
}
