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

#include "ohci_core.h"

#define DEV_OH0 "/dev/usb/oh0"
#define DEV_OH1 "/dev/usb/oh1"
#define OHC_DEV_NAME_SIZE  12
static IOSMessageQueueId mq;
static IOSMessage msgArray[4];
static char ohcDev[16];

/* XXX horti: This should come from libc? */
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)
{
    u8 i = 0;
    char svid[16];
    char spid[16];
    
    memset(svid, 0, sizeof(svid));
    memset(spid, 0, sizeof(spid));
    while ((tmp[i] != '\0') && (tmp[i] != '/')) ++i;
    memcpy(svid, tmp, i);
    tmp += i + 1;
    while ( (tmp[i] != '\0') && (tmp[i] != '/')) ++i;
    memcpy(spid, tmp, i);
   
    *vid = (u16) atou32(svid);
    *pid = (u16) atou32(spid);
    
    if (0 == *vid || 0 == *pid) {
        return IOS_ERROR_INVALID;
    } else  {
        return IOS_ERROR_OK;
    }
}

 /* Opening /dev/usb/ohX will return a handle,
 *  which can be used to talk the the OHC driver itself.
 */
static IOSError
ohcOpen(IOSResourceRequest *req)
{
    s16 devnum;
    u16 vid, pid;
    IOSResourceOpen *args = &req->args.open;

    if (0 == strncmp(args->path, ohcDev, IOS_PATH_MAX)) {
        devnum = OHC_RSVD_HANDLE;
        goto done;
    }
    /* Get vid, pid */
    parseVidPid(((u8 *)args->path + OHC_DEV_NAME_SIZE + 1),
                 &vid, &pid);
    if ((devnum = getDeviceId(vid, pid)) < 0) {
        OHCI_DBG("Device (%x, %x) not found\n", vid, pid);
        devnum = IOS_ERROR_INVALID;
    }
    OHCI_DBG("Found device (%x, %x)\n", vid, pid);
done:
    return ((IOSError)devnum);
}

/* 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;
    u16 devnum = (u16) req->handle;
    if (OHC_RSVD_HANDLE == devnum) { /* Handle to driver. Do nothing */
        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;
    IOSError rv;
    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;
    }
    port = getPortNum(resReq->handle);
    rv = (OHC_SUSPEND_MSG == typ)? suspendRHubPort(hcd, port):
             resumeRHubPort(hcd, port);
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)
{
    return setDevNotifyRemoval(resReq->handle, resReq);
}
    
/* 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;
    u16 devnum = (u16) resReq->handle;
    
    /* Requests to the driver */
    if (OHC_RSVD_HANDLE == devnum) {
        switch (resReq->args.ioctl.cmd) {
#if defined(ENABLE_TEST_FUNCTIONS)
            case OHC_GET_RHDESCA_MSG:
                rv = ohciGetRhDesca(hcd, resReq);
                goto reply;
#endif
            default:
                rv = IOS_ERROR_INVALID; /* invalid request */
        }
        goto done;
    }

    /* Requests to devices */
    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;
        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;
    u16 devnum = (u16) resReq->handle;
    IOSResourceIoctlv *args = (IOSResourceIoctlv *)&resReq->args.ioctlv;

    /* Requests to the driver */
    if (OHC_RSVD_HANDLE == devnum) {
        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
            default:
                rv = IOS_ERROR_INVALID;
                goto done;
        }
    }

    /* Requests to actual devices */
    switch (args->cmd) {
        case OHC_CTRL_MSG:
            rv = ohci_CtrlvIRP(hcd, resReq, -1);
            break;
        case OHC_INTR_MSG:
        case OHC_BLK_MSG:
            rv = ohci_IntrBlkvIRP(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 
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));
    if (IOS_EVENT_OH0 == hc_event) {
        strncpy(ohcDev, DEV_OH0, sizeof(ohcDev) - 1);
    } else {
        strncpy(ohcDev, DEV_OH1, 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_DBG("ohci_rm: IOS_ReceiveMessage failed: %d\n", rv);
            goto done;
        }
        /* First, check for internal messages */
        switch (msg) {
            case HCD_RHUB_EVENT:
                OHCI_DBG("  RHUB_EVENT\n");
                handleRHSCEvent(hcd);
                continue; /* Done. Get next request. */
            default:
                break;  /* Continue to RM msg handling */
        }
        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;
}
