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

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

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

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:
        {
            // TODO: int ifID = *( (int *) ioctlv->vector[0].base);
            IOSIobuf * iob = (IOSIobuf *) ioctlv->vector[1].base;

            if (iob == NULL)
            {
                rv = IOS_ERROR_INVALID;
                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();
            OSRestoreInterrupts(enabled);

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

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

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

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

                if (!__IFDefault.up)
                {
                    __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();
            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;

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

    /* Create a RM message queue for socket interface layer */
    if ( (qid = IOS_CreateMessageQueue(msgQ, NET_IF_MSGQ_SIZE)) < 0 ) {
        OSReport("Creating message queue failed\n");
        return;
    }
    
    /* Register RM */
    if ( IOS_ERROR_OK != IOS_RegisterResourceManager(NET_RM_IP_BOT, qid) ) {
        OSReport("Registering network IF RM failed. Exiting...\n");
        return;
    }

    /* Sit in a loop processing requests */
    while(1) {
        IOS_ReceiveMessage(qid, &msg, IOS_MESSAGE_BLOCK);
        req = (IOSResourceRequest *)msg;
        switch(req->cmd) {
            case IOS_OPEN:
            case IOS_CLOSE:
                rv = 0;
                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 */
    if ( (netXmitQid = IOS_CreateMessageQueue(msgQ, NET_XMIT_MSGQ_SIZE)) < 0 ) {
        OSReport("Creating message queue failed\n");
        return;
    }
    
    /* 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, rc=%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();
        OSRestoreInterrupts(enabled);
    }

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

BOOL
NetInitIfRM(void)
{
    IOSThreadId ifThreadId, xmitThreadId;

    /* 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);

    if (ifThreadId < 0) {
        OSReport("%s: could not create net IF RM thread - exiting\n", __FUNCTION__);
        return FALSE;
    }
    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);

    if (xmitThreadId < 0) {
        OSReport("%s: could not create net XMIT thread - exiting\n", __FUNCTION__);
        return FALSE;
    }
    IOS_SetThreadPriority(xmitThreadId, NET_DEVXMIT_PRIORITY);
    OSInitThread(xmitThreadId, NET_DEVXMIT_PRIORITY);

    if (IOS_StartThread(ifThreadId) != IOS_ERROR_OK) {
        OSReport("%s: could not start net IF RM thread\n", __FUNCTION__);
        return FALSE;
    }

    if (IOS_StartThread(xmitThreadId) != IOS_ERROR_OK) {
        OSReport("%s: could not start net XMIT RM thread\n", __FUNCTION__);
        return FALSE;
    }

    return TRUE;
}
