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

/* XXX horti:
 * Do nothing to the device on close. Perhaps we want to 
 * reset it?
 */
static IOSError
ohcClose(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    u16 vid, pid;
    u16 devnum = (u16) req->handle;
    
    if ( IOS_ERROR_OK == (rv = getVidPid(devnum, &vid, &pid)))
        OHCI_DBG("Closing device: %u [vid:0x%x pid:0x%x]\n", 
                devnum, vid, pid);
    else
        OHCI_DBG("Failed to find device: %u\n");
    return rv;
}

static IOSError
ohciSuspendDevice(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    u8 port = getPortNum(resReq->handle);
    return suspendRHubPort(hcd, port);
}

static IOSError
ohciResumeDevice(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    u8 port = getPortNum(resReq->handle);
    return resumeRHubPort(hcd, port);
}

static IOSError
ohciGetDevList(struct ohci_hcd *hcd, IOSResourceRequest *resReq)
{
    IOSError rv;
    OHCGetDevListReq *req = (OHCGetDevListReq *) resReq->args.ioctl.inPtr;
    if (NULL == req->deviceList || 0 == req->maxDev || NULL == req->numDev) {
         rv = IOS_ERROR_INVALID;
         goto done;
    }
    rv = getDevList(req->deviceList, req->maxDev, req->deviceClass, req->numDev);
    IOS_FlushDCache(req->deviceList, sizeof(OHCDeviceInfo)*req->maxDev);
    IOS_FlushDCache(req->numDev, sizeof(u8));
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;
    u16 devnum = (u16) resReq->handle;
    
    /* Requests to the driver */
    if (OHC_RSVD_HANDLE == devnum) {
        switch (resReq->args.ioctl.cmd) {
            case OHC_GET_DEVLIST_MSG:
                rv = ohciGetDevList(hcd, resReq);
                goto reply;
            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_CTRL_MSG:
            rv = ohci_CtrlIRP(hcd, resReq, -1);
            break;
        case OHC_INTR_MSG:
        case OHC_BLK_MSG:
            rv = ohci_IRP(hcd, resReq, -1);
            break;
        case OHC_SUSPEND_MSG:
            rv = ohciSuspendDevice(hcd, resReq);
            goto reply;
        case OHC_RESUME_MSG:
            rv = ohciResumeDevice(hcd, resReq);
            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;
}

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(req);
            break;
        case IOS_IOCTL:
            OHCI_DBG("  IOS_IOCTL\n");
            rv = ohcIoctl(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;
}
