/*
 *               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.
 *
 */
/* Main resource manager loop. */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>
#include "ehci.h"
#include "ehci_regs.h"

#include "ehci_core.h"
extern struct ehci_device __ehci_dev[EHCI_DEV_MAX]; 

#define DEV_EHC "/dev/usb/ehc"
#define EHC_DEV_NAME_SIZE  12

static IOSMessageQueueId mq;
static IOSMessage msgArray[8];
static char ehcDev[16];

static u32
__atou32(char *str)
{
    u32 v = 0;
    if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
        str += 2;
    }
    while ((*str >= '0' && *str <= '9') ||
            (*str >= 'a' && *str <= 'f') ||
            (*str >= 'A' && *str <= 'F')) {
        char c = *str++;
        if (c <= '9') c -= '0';
        else if (c <= 'F') c -= 'A'-10;
        else c -= 'a'-10;
        v = (v << 4) + c;
    }
    return v;
}


static IOSError
__parseVidPid(char *tmp, u16 *vid, u16 *pid)
{
    IOSError rv = IOS_ERROR_OK;

    *vid = (u16) __atou32(tmp);
    if (NULL == (tmp = strchr(tmp, '/'))) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    ++tmp; /* Skip '/' */
    *pid = (u16) __atou32(tmp);

    /* "generic" devices could have vid = 0. 0 is a valid value
     * for pid. Forbid vid = 0 and pid = 0.
     */
    if (0 == *vid && 0 == *pid) {
        rv = IOS_ERROR_INVALID;
    } 
done:
    return rv;
}

/* Opening /dev/usb/ehc will return a handle,
 *  which can be used to talk the the EHC driver itself.
 */
static IOSError
__ehcOpen(IOSResourceRequest *req)
{
    s32 devid = 1;
    u16 vid, pid;
    IOSResourceOpen *args = &req->args.open;

    if (0 == strncmp(args->path, ehcDev, IOS_PATH_MAX)) {
        devid = EHC_RSVD_HANDLE;
        goto done;
    }
    /* Get vid, pid */
    devid = (s32) __parseVidPid(((u8 *)args->path + EHC_DEV_NAME_SIZE + 1),
            &vid, &pid);
    if (devid < 0) {
        EHCI_ERR("Parsing vid, pid in path failed\n");
        goto done;
    }
    if ((devid = getUnopenedDeviceId(0, vid, pid)) < 0) {
        EHCI_DBG("Unopened device (%x, %x) not found\n", vid, pid);
    } else {
        EHCI_DBG("Found unopened device (%x, %x): id = 0x%x\n", vid, pid, devid);
        setOpen(devid);
    }
done:
    return ((IOSError)devid);
}

/* Abort all on going txns for this device. Don't reset it. */
static IOSError
__ehcClose(ehci_hcd *hcd, IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    u16 vid, pid;
    s8 devnum;

    if (EHC_RSVD_HANDLE == req->handle) { /* Handle to driver. Do nothing */
        goto done;
    }

    devnum = getDeviceIdx(req->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    if (IOS_ERROR_OK == (rv = getVidPid(devnum, &vid, &pid))) {
        closeDevNode(hcd, devnum);
    }
done:
    return rv;
}

static IOSError
__ehciSuspendResumeDevice(ehci_hcd *hcd, IOSResourceRequest *resReq,
        u32 typ)
{
    u8 port;
    u8 hub;
    IOSError rv;
    s8 devnum;
    if (NULL != resReq->args.ioctl.inPtr || 0 != resReq->args.ioctl.inLen
      || NULL != resReq->args.ioctl.outPtr || 0 != resReq->args.ioctl.outLen) {
      rv = IOS_ERROR_INVALID;  
      goto done;
    }
    devnum = getDeviceIdx(resReq->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    port = __ehci_dev[devnum].dev.port;
    hub =  __ehci_dev[devnum].dev.hub;
    if (typ == EHC_SUSPEND_MSG) {
        rv = (hub)? suspendResumeHubPort(hcd, hub, port, 1 /* suspend */):
            suspendResumeRHubPort(hcd, port, 1 /* suspend */);
    } else {
        rv = (hub)? suspendResumeHubPort(hcd, hub, port, 0 /* resume */):
            suspendResumeRHubPort(hcd, port, 0 /* resume */);
    }
done:
    return rv;
}

static IOSError
__ehciGetDevList(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    CHK_RDWR(2, 2); 
    if (CHK_VEC(0, sizeof(u8)) || CHK_VEC(1, sizeof(u8))
        || CHK_VEC(2, sizeof(u8)) || CHK_VEC(3, (*args->vector[0].base)*sizeof(EHCDeviceInfo))) {
         rv = IOS_ERROR_INVALID;
         goto done;
    }
    rv = getDevList((EHCDeviceInfo *)args->vector[3].base, /* deviceList */
                    *args->vector[0].base, /* maxDev */
                    *args->vector[1].base, /* deviceClass */
                     args->vector[2].base /* numDev */
                    );
    IOS_FlushDCache((void *)args->vector[3].base, *args->vector[0].base);
    IOS_FlushDCache((void *)args->vector[2].base, sizeof(u8));
done:
    return rv;
}

static IOSError
__ehciRegisterNotifyRemoval(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    s8 devnum = getDeviceIdx(resReq->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = setDevNotifyRemoval(devnum, resReq);
done:
    return rv;
}

IOSError
ehciRegisterNotifyInsertionWithId(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    CHK_RDWR(3, 1);
    if (CHK_VEC(0, sizeof(u16)) || CHK_VEC(1, sizeof(u16)) 
            || CHK_VEC(2, sizeof(u8)) || CHK_VEC(3, sizeof(u32))) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = setDevNotifyInsertion(*((u16 *) args->vector[0].base),
            *((u16 *) args->vector[1].base),
            *((u8 *) args->vector[2].base), resReq);
    if (rv > 0) {
        *((u32 *)args->vector[3].base) = rv;
        EHCI_DBG("ehc: set reg id = 0x%08x\n", rv);
    }
done:
    return rv;
}

IOSError
ehciCancelNotifyInsertion(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    IOSResourceRequest *cancelReq;

    if (NULL == resReq->args.ioctl.inPtr 
            || sizeof(u32) != resReq->args.ioctl.inLen) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    cancelReq = cancelDevNotifyInsertion(*((u32 *) resReq->args.ioctl.inPtr));
    if (NULL != cancelReq) {
        rv = IOS_ResourceReply(cancelReq, IUSB_ERROR_CANCELLED);
    }
    if (rv < 0) {
        EHCI_ERR("%s: sending cancel notification failed: %d\n", __FUNCTION__, rv);
    }
    else {
        EHCI_DBG("%s: sent cancel notification: %d\n", __FUNCTION__, rv);
    }
done:
    return rv;
}

static IOSError
__ehciRegisterNotifyInsertion(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    
    CHK_RDWR(2, 0);
    if (CHK_VEC(0, sizeof(u16)) || CHK_VEC(1, sizeof(u16))) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = setDevNotifyInsertion(*((u16 *) args->vector[0].base),
                               *((u16 *) args->vector[1].base),
                               0 /* ignore class */,
                               resReq);
done:
    return rv;
}
    
static IOSError
__ehciRegisterNotifyClassInsertion(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    
    CHK_RDWR(1, 0);
    if (CHK_VEC(0, sizeof(u8))) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = setDevNotifyInsertion(0 /* ignore vid */,
                               0 /* ignore pid */, 
                               *((u8 *) args->vector[0].base),
                               resReq);
done:
    return rv;
}

#ifdef EHC_ENABLE_FG
static IOSError
__ehciSecTest(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    s8 devnum;
    devnum = getDeviceIdx(resReq->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = secTest(hcd, devnum);
done:
    return rv;
}
#endif

static IOSError
__ehciResetDevice(ehci_hcd *hcd, u32 devnum)
{
    u32 port, hub;
    u16 vid, pid;
    IOSError rv = IOS_ERROR_OK;
    if (IOS_ERROR_OK == (rv = getVidPid(devnum, &vid, &pid))) {
        hub =  __ehci_dev[devnum].dev.hub;
        port = __ehci_dev[devnum].dev.port;
        delDevNode(hcd, hub, port);
    } else {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    rv = (hub)? enumerateHubPort(hcd, hub, port):
                enumerateRHubPort(hcd, port);
done:
    return rv;
}

/* If rv < 0, caller will send reply. If request is a transfer which 
 * completes later, the event handler will send reply. If request
 * completes successfully, we send a reply here.
 */
/* If rv < 0, caller will send reply. If request is a transfer which 
 * completes later, the event handler will send reply. If request
 * completes successfully, we send a reply here.
 */
static IOSError
__ehcIoctl(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    s8 devnum;
    
    /* Requests to the driver */
    if (EHC_RSVD_HANDLE == resReq->handle) {
        switch (resReq->args.ioctl.cmd) {
            case EHC_CANCELNOTIFY_MSG:
                rv = ehciCancelNotifyInsertion(hcd, resReq);
                goto reply;
            default:
                rv = IOS_ERROR_INVALID; /* invalid request */
        }
        goto done;
    }

    /* Requests to devices */
    devnum = getDeviceIdx(resReq->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if (IOS_ERROR_OK != getVidPid(devnum, NULL, NULL)) {
        EHCI_DBG("Got incorrect handle: %u\n", devnum);
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    switch (resReq->args.ioctl.cmd) {
        case EHC_SUSPEND_MSG:
        case EHC_RESUME_MSG:
            rv = __ehciSuspendResumeDevice(hcd, resReq, resReq->args.ioctl.cmd);
            goto reply;
        case EHC_NOTIFYREMOVAL_MSG:
            rv = __ehciRegisterNotifyRemoval(hcd, resReq);
            break;
        case EHC_RESET_MSG:
            rv = __ehciResetDevice(hcd, devnum);
            goto reply;
#ifdef EHC_ENABLE_FG
        case EHC_SECTEST_MSG:
            printf("SECTEST ioctl called\n");
            rv = __ehciSecTest(hcd, resReq);
            goto reply;
#endif
        default:
            EHCI_DBG("Unknown ioctl request: %u\n", resReq->args.ioctl.cmd);
            rv = IOS_ERROR_INVALID;
            break;
    }
    goto done;

reply:
    if (rv >= 0) { /* caller will send reply for all failed calls */
        IOS_ResourceReply(resReq, rv); 
    }
done:
    return rv;
}

/* If rv < 0, caller will send reply. If request is a transfer which 
 * completes later, the event handler will send reply. If request
 * completes successfully, we send a reply here.
 */
static IOSError
__ehcIoctlv(ehci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    s8 devnum;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;

    /* Requests to the driver */
    if (EHC_RSVD_HANDLE == resReq->handle) {
        switch (args->cmd) {
            case EHC_GET_DEVLIST_MSG:
                rv = __ehciGetDevList(hcd, resReq);
                goto reply;
            case EHC_NOTIFYINSERT_MSG:
                rv = __ehciRegisterNotifyInsertion(hcd, resReq);
                goto done;
            case EHC_NOTIFYCLASSINSERT_MSG:
                rv = __ehciRegisterNotifyClassInsertion(hcd, resReq);
                goto done;
            case EHC_NOTIFYINSERT_ID_MSG:
                rv = ehciRegisterNotifyInsertionWithId(hcd, resReq);
                goto done;
            default:
                rv = IOS_ERROR_INVALID;
                goto done;
        }
    }
    devnum = getDeviceIdx(resReq->handle);
    if (devnum < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    /* Requests to actual devices */
    switch (args->cmd) {
        case EHC_CTRL_MSG:
            rv = ehci_CtrlIRP(hcd, resReq, -1);
            break;
        case EHC_INTR_MSG:
        case EHC_BLK_MSG:
        case EHC_BLK_LONG_MSG:
            rv = ehci_IntrBlkIRP(hcd, resReq, args->cmd);
            break;
        case EHC_ISO_NEW_MSG:
        case EHC_ISO_MSG:
            rv = ehci_IsoIRP(hcd, resReq);
            break;
        default:
            rv = IOS_ERROR_INVALID;
            break;
    }
    goto done;

reply:
    if (rv >= 0) { /* caller will send reply for all failed calls */
        IOS_ResourceReply(resReq, rv); 
    }
done:
    return rv;
}

IOSError 
registerEHCResourceManager(ehci_hcd *hcd, IOSEvent hc_event)
{
    IOSError rv = IOS_ERROR_OK;
    
    /* Create a message queue */
    EHCI_DBG("Create RM message queue\n");
    if ((mq = IOS_CreateMessageQueue(msgArray,
                sizeof(msgArray)/sizeof(msgArray[0]))) < 0) {
        rv = mq;
        EHCI_DBG("IOS_CreateMessageQueue failed: %d\n", rv);
        goto done;
    }
    
    /* Path name. Don't use contents of hcd yet. hcd is allocated, but 
     * not initialized yet.
     */
    memset(ehcDev, 0, sizeof(ehcDev));
    strncpy(ehcDev, DEV_EHC, sizeof(ehcDev) - 1);

    /*Use same message queue for internal messages */
    hcd->rm_qid = mq;
    
    /* Register */
    if ((rv = IOS_RegisterResourceManager(ehcDev, mq)) != IOS_ERROR_OK) {
        EHCI_DBG("IOS_RegisterResourceManager failed\n", rv);
        goto done;
    }
    EHCI_DBG("EHCI resource manager for [%s] registered\n", ehcDev);
    
done:
    return rv;
}

IOSError
startEHCResourceManager(ehci_hcd *hcd)
{
    IOSError rv;
    IOSMessage msg;

    EHCI_DBG("EHCI resource manager for [%s] started\n", ehcDev);
    hcd->flags |= HCD_RM_INIT_MASK; /* RM initialized */
    while (1) {
        if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) 
                != IOS_ERROR_OK) {
            EHCI_ERR("ehci_rm: IOS_ReceiveMessage failed: %d\n", rv);
            goto done;
        }
        /* First, check for internal messages */
        if (HCD_RHUB_EVENT == (msg & HCD_RHUB_EVENT_MASK)) {
            u8 hubId = msg & HCD_HUB_ID_MASK;
            switch (hubId) {
                case 0:
                    EHCI_DBG("  RHUB_EVENT\n");
                    handlePortChgEvent(hcd);
                    break;
                default:
                    {
                        u32 stat = msg & HCD_HUB_STAT_MASK;
                        if (HCD_HUB_STAT_FAIL == stat) {
                            EHCI_DBG("GetHubStatus failed. No need to process hub event.\n");
                        } else {
                            EHCI_DBG(" HUB_EVENT %u\n", hubId);
                            handleHubEvent(hcd, hubId);
                        }
                        break;
                    }
            }
            continue; /* Done. Get next request. */
        }
        EHCI_DBG("ehci_rm: Received resource request: %08x\n", msg);

        /* Dispatch command */
        IOSResourceRequest *req = (IOSResourceRequest *) msg;
        switch (req->cmd) {
            case IOS_OPEN:
            EHCI_DBG("  IOS_OPEN\n");
            rv = __ehcOpen(req);
            break;
        case IOS_CLOSE:
            EHCI_DBG("  IOS_CLOSE\n");
            rv = __ehcClose(hcd, req);
            break;
        case IOS_IOCTL:
            EHCI_DBG("  IOS_IOCTL\n");
            rv = __ehcIoctl(hcd, req);
            break;
        case IOS_IOCTLV:
            EHCI_DBG("  IOS_IOCTLV\n");
            rv = __ehcIoctlv(hcd, req);
            break;
        default:
            EHCI_DBG("  Unsupported\n");
            rv = IOS_ERROR_INVALID;
            break;
        }
        /* For failed calls, send reply now. Open and close are 
         * done right away.
         */
        if (rv < 0 || IOS_OPEN == req->cmd || IOS_CLOSE == req->cmd) { 
            IOS_ResourceReply(req, rv);
        }
    }
done:
    return rv;
}
