/*
 *               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 "ohci.h"
#include "ohci_regs.h"

#include "ohci_core.h"
extern struct ohci_device __ohci_dev[OHCI_DEV_MAX]; 

#define DEV_OH0 "/dev/usb/oh0"
#define OHC_DEV_NAME_SIZE  12
static IOSMessageQueueId mq;
static IOSMessage msgArray[8];
static char ohcDev[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/ohX will return a handle,
 *  which can be used to talk the the OHC driver itself.
 */
static IOSError
__ohcOpen(IOSResourceRequest *req)
{
    s32 devid;
    u16 vid, pid;
    IOSResourceOpen *args = &req->args.open;

    if (0 == strncmp(args->path, ohcDev, IOS_PATH_MAX)) {
        devid = OHC_RSVD_HANDLE;
        goto done;
    }
    /* Get vid, pid */
    devid = (s32) __parseVidPid(((u8 *)args->path + OHC_DEV_NAME_SIZE + 1),
            &vid, &pid);
    if (devid < 0) {
        OHCI_ERR("Parsing vid, pid in path failed\n");
        goto done;
    }
    if ((devid = getUnopenedDeviceId(0, vid, pid)) < 0) {
        OHCI_DBG("Unopened device (%x, %x) not found\n", vid, pid);
    } else {
        OHCI_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
__ohcClose(struct ohci_hcd *hcd, IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    u16 vid, pid;
    s8 devnum;

    if (OHC_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
__ohciSuspendResumeDevice(struct ohci_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 = __ohci_dev[devnum].dev.port;
    hub =  __ohci_dev[devnum].dev.hub;
    if (typ == OHC_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
__ohciGetDevList(struct ohci_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(OHCDeviceInfo))) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = getDevList((OHCDeviceInfo *)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;
}

#if defined(ENABLE_TEST_FUNCTIONS)
static IOSError
__ohciGetRhDesca(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    u32 *stat;
    if (NULL == resReq->args.ioctl.outPtr 
            || sizeof(u32) != resReq->args.ioctl.outLen) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    stat = (u32 *)resReq->args.ioctl.outPtr;
    *stat = OHCI_READ(hcd->opregs->rhub_desca) & OHCI_RHUB_DESCA_RSVD_MASK;
done:
    return rv;
}
#endif

IOSError
__ohciRegisterNotifyRemoval(struct ohci_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
__ohciRegisterNotifyInsertionWithId(struct ohci_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;
        OHCI_DBG("ohc: set reg id = 0x%08x\n", rv);
    }
done:
    return rv;
}

IOSError
__ohciCancelNotifyInsertion(ohci_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) {
        OHCI_ERR("%s: sending cancel notification failed: %d\n", __FUNCTION__, rv);
    }
    else {
        OHCI_DBG("%s: sent cancel notification: %d\n", __FUNCTION__, rv);
    }
done:
    return rv;
}

IOSError
__ohciRegisterNotifyInsertion(struct ohci_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
__ohciRegisterNotifyClassInsertion(ohci_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;
}

static IOSError
__ohciResetDevice(ohci_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 =  __ohci_dev[devnum].dev.hub;
        port = __ohci_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.
 */
static IOSError
__ohcIoctl(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    s8 devnum;

    /* Requests to the driver */
    if (OHC_RSVD_HANDLE == resReq->handle) {
        switch (resReq->args.ioctl.cmd) {
#if defined(ENABLE_TEST_FUNCTIONS)
            case OHC_GET_RHDESCA_MSG:
                rv = __ohciGetRhDesca(hcd, resReq);
                goto reply;
#endif
            case OHC_CANCELNOTIFY_MSG:
                rv = __ohciCancelNotifyInsertion(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)) {
        OHCI_DBG("Got incorrect handle: %u\n", devnum);
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    switch (resReq->args.ioctl.cmd) {
        case OHC_SUSPEND_MSG:
        case OHC_RESUME_MSG:
            rv = __ohciSuspendResumeDevice(hcd, resReq, resReq->args.ioctl.cmd);
            goto reply;
        case OHC_NOTIFYREMOVAL_MSG:
            rv = __ohciRegisterNotifyRemoval(hcd, resReq);
            break;
        case OHC_RESET_MSG:
            rv = __ohciResetDevice(hcd, devnum);
            goto reply;
        default:
            OHCI_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 defined(ENABLE_TEST_FUNCTIONS)
static IOSError
getRHPortStatus(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    u8 port;
    u32 *stat;
    IOSError rv = IOS_ERROR_INVALID;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    if (1 != args->readCount || 1 != args->writeCount
            || NULL == args->vector[0].base || sizeof(u8) != args->vector[0].length
            || NULL == args->vector[1].base || sizeof(u32) != args->vector[1].length ) {
        goto done;
    }
    port = *args->vector[0].base;
    if (port >= hcd->ndp) goto done;

    stat = (u32 *)args->vector[1].base;
    *stat = OHCI_READ(hcd->opregs->rhub_pstat[port]);
    IOS_FlushDCache(stat, sizeof(u32));
    rv = IOS_ERROR_OK;
done:
    return rv;
}

static IOSError
setRHPortStatus(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    u8 port;
    u32 *stat;
    IOSError rv = IOS_ERROR_INVALID;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;
    if (2 != args->readCount 
            || NULL == args->vector[0].base || sizeof(u8) != args->vector[0].length
            || NULL == args->vector[1].base || sizeof(u32) != args->vector[1].length ) {
        goto done;
    }

    port = *args->vector[0].base;
    if (port >= hcd->ndp) goto done;

    stat = (u32 *)args->vector[1].base;
    OHCI_WRITE(hcd->opregs->rhub_pstat[port], *stat);
    rv = IOS_ERROR_OK;
done:
    return rv;
}
#endif

/* 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
__ohcIoctlv(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv = IOS_ERROR_OK;
    s8 devnum;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;

    /* Requests to the driver */
    if (OHC_RSVD_HANDLE == resReq->handle) {
        switch (args->cmd) {
            case OHC_GET_DEVLIST_MSG:
                rv = __ohciGetDevList(hcd, resReq);
                goto reply;
#if defined(ENABLE_TEST_FUNCTIONS)
            case OHC_GET_RHPSTAT_MSG:
                rv = getRHPortStatus(hcd, resReq);
                goto reply;
            case OHC_SET_RHPSTAT_MSG:
                rv = setRHPortStatus(hcd, resReq);
                goto reply;
#endif
            case OHC_NOTIFYINSERT_MSG:
                rv = __ohciRegisterNotifyInsertion(hcd, resReq);
                goto done;
            case OHC_NOTIFYCLASSINSERT_MSG:
                rv = __ohciRegisterNotifyClassInsertion(hcd, resReq);
                goto done;
            case OHC_NOTIFYINSERT_ID_MSG:
                rv = __ohciRegisterNotifyInsertionWithId(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 OHC_CTRL_MSG:
            rv = ohci_CtrlIRP(hcd, resReq, -1);
            goto done;
        case OHC_INTR_MSG:
        case OHC_BLK_MSG:
            rv = ohci_IntrBlkIRP(hcd, resReq);
            goto done;
        case OHC_ISO_NEW_MSG:
            rv = ohci_IsoIRP(hcd, resReq);
            goto done;
        default:
            rv = IOS_ERROR_INVALID;
            goto done;
    }
    goto done;

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

IOSError 
registerOHCResourceManager(struct ohci_hcd *hcd, IOSEvent hc_event)
{
    IOSError rv = IOS_ERROR_OK;

    /* Create a message queue */
    OHCI_DBG("Create RM message queue\n");
    if ((mq = IOS_CreateMessageQueue(msgArray,
                    sizeof(msgArray)/sizeof(msgArray[0]))) < 0) {
        rv = mq;
        OHCI_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(ohcDev, 0, sizeof(ohcDev));
    strncpy(ohcDev, DEV_OH0, sizeof(ohcDev) - 1);

    /*Use same message queue for internal messages */
    hcd->rm_qid = mq;

    /* Register */
    if ((rv = IOS_RegisterResourceManager(ohcDev, mq)) != IOS_ERROR_OK) {
        OHCI_DBG("IOS_RegisterResourceManager failed\n", rv);
        goto done;
    }
    OHCI_DBG("OHCI resource manager for [%s] registered\n", ohcDev);

done:
    return rv;
}

IOSError
startOHCResourceManager(struct ohci_hcd *hcd)
{
    IOSError rv;
    IOSMessage msg;

    OHCI_DBG("OHCI resource manager for [%s] started\n", ohcDev);
    hcd->flags |= HCD_RM_INIT_MASK; /* RM initialized */
    while (1) {
        if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) 
                != IOS_ERROR_OK) {
            OHCI_ERR("ohci_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:
                    OHCI_DBG("  RHUB_EVENT\n");
                    handleRHSCEvent(hcd);
                    break;
                default:
                    {
                        u32 stat = msg & HCD_HUB_STAT_MASK;
                        if (HCD_HUB_STAT_FAIL == stat) {
                            OHCI_DBG("GetHubStatus failed. No need to process hub event.\n");
                        } else {
                            OHCI_DBG(" HUB_EVENT %u\n", hubId);
                            handleHubEvent(hcd, hubId);
                        }
                        break;
                    }
            }
            continue; /* Done. Get next request. */
        }
        OHCI_DBG("ohci_rm: Received resource request: %08x\n", msg);

        /* Dispatch command */
        IOSResourceRequest *req = (IOSResourceRequest *) msg;
        switch (req->cmd) {
            case IOS_OPEN:
                OHCI_DBG("  IOS_OPEN\n");
                rv = __ohcOpen(req);
                break;
            case IOS_CLOSE:
                OHCI_DBG("  IOS_CLOSE\n");
                rv = __ohcClose(hcd, req);
                break;
            case IOS_IOCTL:
                OHCI_DBG("  IOS_IOCTL\n");
                rv = __ohcIoctl(hcd, req);
                break;
            case IOS_IOCTLV:
                OHCI_DBG("  IOS_IOCTLV\n");
                rv = __ohcIoctlv(hcd, req);
                break;
            default:
                OHCI_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;
}
