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

#include <sc/sc.h>
#include <sc/ios.h>
#include <sc/priority.h>
#include <ioslibc.h>
#include "usb.h"
#include "usbdev.h"
#include "usbintr.h"
#include "usbhw.h"
#include "mux.h"

#define STACK_SIZE 2048
#define PRINTF_STACK_SIZE 512
/* Roughly 50ms on 100Mhz NC 200 x 10 x 25000 ns*/
#define VBUS_POLLING_INTERVAL   25000 

const u8 _initStack[STACK_SIZE];
const u32 _initStackSize = sizeof(_initStack);
u8 printfStack[PRINTF_STACK_SIZE];
/*
 * Start at very high priority so that the kernel will
 * allow the thread to set itself to a high priority
 * during device enumeration to get around a hardware
 * bug that affects control transfers.  Once enumeration
 * is complete, the code reverts to a normal priority.
 */
const u32 _initPriority = IOS_PRIORITY_USB_HIGH;

USBDeviceContext usbDevCtx[USB_NUM_DEV];
int curUsbDev = USB_NUM_DEV;             /* current device */
extern USBDeviceFuncs usbBulkDevFuncs, usbIsoDevFuncs, usbMsdDevFuncs;
static IOSMessage usbIntrMsg = (IOSMessage) &usbIntrMsg;
static IOSMessage usbPollingMsg = (IOSMessage) &usbPollingMsg;

#define PRINTF_RM "/dev/usb/mux/printfrm"

int
printfRm(void *arg)
{
    IOSFd fd = -1;
    IOSMessageQueueId mq = (IOSMessageQueueId) arg;
    IOSMessage msg;
    IOSError rv = 0;

    while (1) {
        if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
            USB_ERROR("IOS_ReceiveMessage failed in RM");
            goto out;
        }

        IOSResourceRequest *req = (IOSResourceRequest *) msg;
        if (fd < 0) rv = fd = IOS_Open(PRINTF_RM, 0);
        if ((fd < 0) || (curUsbDev != USB_DEV_MUX_BULK_ID)) { 
            IOS_ResourceReply(req, IOS_ERROR_INVALID);
            continue;
        }

        switch (req->cmd) {
        case IOS_WRITE:
            rv = IOS_Write(fd, req->args.write.inPtr, req->args.write.inLen);
            break;
        case IOS_OPEN:
        case IOS_CLOSE:
            break;
        default:
            rv = IOS_ERROR_INVALID;
            break;
        }
        IOS_ResourceReply(req, rv);
    }
out:
    if (fd >= 0) IOS_Close(fd);
    return rv;
}


/* Usb device open and close functions */
static IOSError
usbDevOpen(IOSResourceRequest *req)
{
    u32 dev;
    IOSError rv = IOS_ERROR_OK;
    const char *path = req->args.open.path;
   
    USB_LOG(" Open usb device %s \n", req->args.open.path);

    if (!strncmp(req->args.open.path, PRINTF_RM, sizeof(PRINTF_RM))) { 
        memcpy((char *)path, USB_DEV_MUX_BULK_PRINTF, sizeof(USB_DEV_MUX_BULK_PRINTF));
    }

    if (!strncmp(path, USB_DEV, sizeof(USB_DEV))) { 
        return NULL;
    } else if (!strncmp(path, USB_DEV_MUX_BULK, sizeof(USB_DEV_MUX_BULK) - 1)) {
        dev = USB_DEV_MUX_BULK_ID;
    } else if (!strncmp(path, USB_DEV_MUX_ISO, sizeof(USB_DEV_MUX_ISO) - 1)) {
        dev = USB_DEV_MUX_ISO_ID;
    } else if (!strncmp(path, USB_DEV_MSD, sizeof(USB_DEV_MSD) - 1)) {
        dev = USB_DEV_MSD_ID;
    } else if (!strncmp(path, USB_DEV_PTP, sizeof(USB_DEV_PTP) - 1)) {
        dev = USB_DEV_PTP_ID;
    } else {
        USB_ERROR(" unsupported USB device type");
        return IOS_ERROR_NOEXISTS;
    }
  
    if (dev != curUsbDev) { 
        USB_ERROR(" Open different type device");
        USB_ERROR(" Please open /dev/usb and use ioctl to set device type first");
        return IOS_ERROR_INVALID;
    }

    if (usbDevCtx[dev].pFuncs == NULL) {
        USB_ERROR(" not implement yet");
        return IOS_ERROR_INVALID;
    }

    rv = usbDevCtx[dev].pFuncs->skOpen(req);
    if (dev != USB_DEV_MUX_BULK_ID && dev != USB_DEV_MUX_ISO_ID && rv==IOS_ERROR_OK)
        rv = (IOSError) &usbDevCtx[dev];

    return rv;
}

static IOSError
usbDevClose(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;

    if (req->handle) { 
        if (curUsbDev >= USB_NUM_DEV) { 
            USB_ERROR("device type is not selected");
            rv = IOS_ERROR_INVALID;
        } else if (usbDevCtx[curUsbDev].pFuncs == NULL) {
            USB_ERROR(" not implement yet(close)");
            rv = IOS_ERROR_INVALID;
        } else rv = usbDevCtx[curUsbDev].pFuncs->skClose(req);
    } /* do nothing for /dev/usb */

    return rv;
}

static IOSError
usbDevRead(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;

    if (req->handle) {
        if (curUsbDev >= USB_NUM_DEV) {
            USB_ERROR("device type is not selected");
            rv = IOS_ERROR_INVALID;
        } else if  (usbDevCtx[curUsbDev].pFuncs == NULL) {
            USB_ERROR(" not implement yet(Read)");
            rv = IOS_ERROR_INVALID;
        } else rv = usbDevCtx[curUsbDev].pFuncs->skRead(req); 
    } else {
        USB_ERROR(" Read does not support on /dev/usb");
        rv = IOS_ERROR_INVALID;
    }
    
    return rv;
}

static IOSError
usbDevWrite(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;

    if (req->handle) {
        if (curUsbDev >= USB_NUM_DEV) {
            USB_ERROR("device type is not selected");
            rv = IOS_ERROR_INVALID;
        } else  if (usbDevCtx[curUsbDev].pFuncs == NULL) {
            USB_ERROR(" not implement yet(Write)");
            rv = IOS_ERROR_INVALID;
        } else rv = usbDevCtx[curUsbDev].pFuncs->skWrite(req); 
    } else {
        USB_ERROR(" Write does not support on /dev/usb");
        rv = IOS_ERROR_INVALID;
    }
    
    return rv;
}

static IOSError
usbDevIoctl(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    int newDev;

    if (req->handle) {
        if (curUsbDev >= USB_NUM_DEV) {
            USB_ERROR("device type is not selected");
            rv = IOS_ERROR_INVALID;
        } else if (usbDevCtx[curUsbDev].pFuncs == NULL) {
            USB_ERROR(" not implement yet(Read)");
            rv = IOS_ERROR_INVALID;
        } else rv = usbDevCtx[curUsbDev].pFuncs->skIoctl(req); 
    } else {
        switch (req->args.ioctl.cmd) {
        case USB_GET_DEV_TYPE:
            if (req->args.ioctl.outPtr) {
                *req->args.ioctl.outPtr = curUsbDev;
            } else {
                USB_ERROR(" need buffer to hold device type");
                rv = IOS_ERROR_INVALID;
            }
            break;
        case USB_FORCE_DEV_TYPE:
        case USB_SET_DEV_TYPE:
            newDev = *req->args.ioctl.inPtr;
            if ((newDev >= USB_NUM_DEV) || (newDev < 0)) {
                if (newDev == USB_NUM_DEV && req->args.ioctl.cmd == USB_FORCE_DEV_TYPE) {
                    if (curUsbDev < USB_NUM_DEV && usbDevCtx[curUsbDev].inUse) {
                        usbDevCtx[curUsbDev].pFuncs->devExit();
                    }
                    /* Shutdown USB device. Disable core and turn off pullup */
                    IO_WRITE(USB_CTRL_REG, USB_CTRL_WE); 
                    curUsbDev = USB_NUM_DEV;
                } else {
                    USB_ERROR(" invalid usb device");
                    rv = IOS_ERROR_INVALID;
                }
            } else if (newDev == curUsbDev) {
                USB_ERROR(" Usb dev type is already set");
                rv = IOS_ERROR_EXISTS;
            } else {
                if (curUsbDev < USB_NUM_DEV) {
                    if (usbDevCtx[curUsbDev].inUse) {
                        if (req->args.ioctl.cmd == USB_SET_DEV_TYPE) {
                            USB_ERROR(" please close exist device first");
                            rv = IOS_ERROR_EXISTS;
                        } else {
                            usbDevCtx[curUsbDev].pFuncs->devExit();
                        }
                    } 
                }

                if (rv == IOS_ERROR_OK) { /* Restart device */
                    USB_LOG("device set to %d \n", newDev);
                    curUsbDev = newDev;
                    usbDevCtx[curUsbDev].pFuncs->devInit(newDev == USB_DEV_MUX_ISO_ID);
                    usbHwRestart(usbHwUnplug());
                }
            }
            break;
        default:
            USB_ERROR(" unsupport ioctl cmd on /dev/usb");
            rv = IOS_ERROR_INVALID;
            break;
        }
    }
    
    return rv;
}

int
main(void) 
{
    int i, poll, prevPoll;
    IOSError rv;
    IOSMessageQueueId mq, mq2;
    IOSMessage msgArray[20], msgArray2[1];
    IOSMessage msg;
    IOSResourceRequest *req;
    IOSTimerId t=-1;
    u8 devType[USB_NUM_DEV] = { USB_DEV_MUX_BULK_ID, USB_DEV_MUX_ISO_ID, 
                                USB_DEV_MSD_ID, USB_DEV_PTP_ID};

    /* Run at normal priority except during enumeration */
    IOS_SetThreadPriority(0, IOS_PRIORITY_USB);

    /* Initial usb device contexts */
    for (i=0; i<USB_NUM_DEV; i++) {
        usbDevCtx[i].inUse = 0;
        usbDevCtx[i].devType = devType[i];
        usbDevCtx[i].pFuncs = NULL;
    }
    usbDevCtx[0].pFuncs = &usbBulkDevFuncs;
    usbDevCtx[1].pFuncs = &usbIsoDevFuncs;
    usbDevCtx[2].pFuncs = &usbMsdDevFuncs;
    muxInitData();

    USB_LOG("USB device driver [thread %d]\n", IOS_GetThreadId());
    if ((mq2 = IOS_CreateMessageQueue(msgArray2, sizeof(msgArray2)/sizeof(msgArray2[0]))) < 0) {
        USB_ERROR(" cannot create message Queue 2");
        return mq2;
    }
    if ((rv = IOS_RegisterResourceManager("/dev/usb/mux/bulk/printf", mq2)) != IOS_ERROR_OK) {
        USB_ERROR(" cannot register IOS msg queue 2");
        return rv;
    }

    if ((mq = IOS_CreateMessageQueue(msgArray, sizeof(msgArray)/sizeof(msgArray[0]))) < 0) {
        USB_ERROR(" cannot create message Queue");
        return mq;
    } 

    if ((rv = IOS_RegisterResourceManager("/dev/usb", mq)) != IOS_ERROR_OK) {
        USB_ERROR(" cannot register IOS msg queue");
        return rv;
    }

    if ((rv = IOS_HandleEvent(IOS_EVENT_USB, mq, usbIntrMsg)) != IOS_ERROR_OK) {
        USB_ERROR(" cannot handle USB event");
        USB_LOG("Error = %d", rv);
        goto out;
    }

    if ((rv = IOS_CreateThread((IOSEntryProc)printfRm, (void *) mq2, 
                printfStack+PRINTF_STACK_SIZE, PRINTF_STACK_SIZE, 
                IOS_PRIORITY_USB-1, IOS_THREAD_CREATE_DETACHED)) < 0) {
        USB_ERROR(" cannot create print RM thread");
        USB_LOG("Error = %d", rv);
        goto out;
    }
    IOS_StartThread(rv);

    t = IOS_CreateTimer(0, VBUS_POLLING_INTERVAL,  mq, usbPollingMsg);
    if (t < 0) {
        USB_ERROR(" cannot create USB polling timer");
        goto out;
    }

    poll = prevPoll = 0;
    while (1) {
        /* Receive a command */
        if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
            USB_ERROR("IOS_ReceiveMessage failed");
            return rv;
        }

        if (msg == usbIntrMsg) {
            usbEvent(0);
        } else if (msg != usbPollingMsg) {
            /* Dispatch command */
            req = (IOSResourceRequest *) msg;
            switch (req->cmd) {
            case IOS_OPEN:
                USB_LOG("  IOS_OPEN\n");
                rv = usbDevOpen(req);
                IOS_ResourceReply(req, rv);
                break;
            case IOS_CLOSE:
                USB_LOG("  IOS_CLOSE\n");
                rv = usbDevClose(req);
                IOS_ResourceReply(req, rv);
                break;
            case IOS_WRITE:
                USB_LOG("  IOS_WRITE\n");
                rv = usbDevWrite(req);
                if (rv != IOS_ERROR_OK) 
                    IOS_ResourceReply(req, rv);
                break;
            case IOS_READ:
                USB_LOG("  IOS_READ\n");
                rv = usbDevRead(req);
                if (rv != IOS_ERROR_OK) 
                    IOS_ResourceReply(req, rv);
                break;
            case IOS_IOCTL:
                USB_LOG("  IOS_IOCTL\n");
                rv = usbDevIoctl(req);
                if (rv != USB_WAIT_DEV_READY)
                    IOS_ResourceReply(req, rv);
                break;
            default:
                USB_ERROR("  Unsupported");
                rv = IOS_ERROR_INVALID;
                IOS_ResourceReply(req, rv);
                break;
            }
        }

        poll = curUsbDev < USB_NUM_DEV ? usbHwUnplug() : 0;
        if (poll != prevPoll) {
            if (poll == 1) {
                if (curUsbDev < USB_NUM_DEV) 
                    usbDevCtx[curUsbDev].pFuncs->devUnplug();
                IO_WRITE(USB_CTRL_REG, USB_CTRL_WE);
            } else usbHwTurnonPullup();
            prevPoll = poll;
        }
    }

out:
    IOS_UnhandleEvent(IOS_EVENT_USB);
    IOS_DestroyMessageQueue(mq);
    if (t >= 0) IOS_DestroyTimer(t);

    return 0;
}
