/*
 *               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.
 *
 */
/* USB API library to access USB host-controller resource managers. */
#include <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>
#include "usb11.h"
#include "iosusbtypes.h"

/* Only supported by EHCI */
static s32
__LongBlkMsg(IOSFd fd, u8 ep, u32 buflen, char *buf)
{
    IOSError rv = IOS_ERROR_OK;
    IOSIoVector vector[3];

    vector[0].base = &ep; 
    vector[0].length = sizeof(u8);


    vector[1].base = (u8 *)&buflen; 
    vector[1].length = sizeof(u32);

    vector[2].base = (u8*) buf; 
    vector[2].length = buflen;
    rv = IOS_Ioctlv(fd, EHC_BLK_LONG_MSG, 2, 1, vector);

    return rv;
}

static s32
__IntrBlkMsg(IOSFd fd, u8 ep, u16 buflen, char *buf, u32 typ)
{
    IOSError rv = IOS_ERROR_OK;
    IOSIoVector vector[3];

    vector[0].base = &ep; 
    vector[0].length = sizeof(u8);


    vector[1].base = (u8 *)&buflen; 
    vector[1].length = sizeof(u16);

    vector[2].base = (u8*) buf; 
    vector[2].length = buflen;
    rv = IOS_Ioctlv(fd, typ, 2, 1, vector);

    return rv;
}

s32
IUSB_ReadIntrMsg(IOSFd fd, u32 ep, u32 buflen, char *buf)
{
    return __IntrBlkMsg(fd, (u8) ep, (u16)buflen, buf, OHC_INTR_MSG);
}

s32
IUSB_WriteIntrMsg(IOSFd fd, u32 ep, u32 buflen, char *buf)
{
    return __IntrBlkMsg(fd, (u8)ep, (u16)buflen, buf, OHC_INTR_MSG);
}

s32
IUSB_ReadBlkMsg(IOSFd fd, u32 ep, u32 buflen, char *buf)
{
    IOSError rv;
    if (NULL == buf || 0 == buflen) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if (buflen <= 0xffff) {
        rv = __IntrBlkMsg(fd, ep, buflen, buf, OHC_BLK_MSG);
    } else {
        rv = __LongBlkMsg(fd, ep, buflen, buf);
    }
done:
    return rv;
}

s32
IUSB_WriteBlkMsg(IOSFd fd, u32 ep, u32 buflen, char *buf)
{
    return IUSB_ReadBlkMsg(fd, ep, buflen, buf);
}

static s32
__CtrlMsg(IOSFd fd, u8 reqType, u8 request, u16 value,
        u16 index, u16 length, u32 data)
{
    IOSError rv = IOS_ERROR_OK;
    u8 ep = 0;
    IOSIoVector vector[7];
    u16 svalue = SWAP16(value);
    u16 sindex= SWAP16(index) ;
    u16 slength= SWAP16(length);

    vector[0].base = &reqType; /*bmRequestType */
    vector[0].length = sizeof(u8);

    vector[1].base = &request; /*bRequest */
    vector[1].length = sizeof(u8);

    vector[2].base =  (u8 *) &svalue; /* wValue */
    vector[2].length = sizeof(u16);

    vector[3].base = (u8 *) &sindex;  /* wIndex */
    vector[3].length = sizeof(u16);

    vector[4].base = (u8 *) &slength; /* wLength */
    vector[4].length = sizeof(u16);

    vector[5].base =  &ep;    /* endpoint number */
    vector[5].length = sizeof(u8);

    vector[6].base = (u8 *)data; 
    vector[6].length = length;

    rv = IOS_Ioctlv(fd, OHC_CTRL_MSG, 6, 1, vector);
    //    printf("ioctlv (fd %d) returned %d\n", fd, rv);
    return rv;
}

s32
IUSB_ReadCtrlMsg(IOSFd fd, u8 reqType, u8 request, u16 value,
        u16 index, u16 length, u32 data)
{
    return __CtrlMsg(fd, reqType, request, value, index, length, data);
}

s32
IUSB_WriteCtrlMsg(IOSFd fd, u8 reqType, u8 request, u16 value,
        u16 index, u16 length, u32 data)
{
    return __CtrlMsg(fd, reqType, request, value, index, length, data);
}

static s8
unicode2ascii(char *tbuf, int buflen)
{
    char buf[IOS_USB_STR_MAX];
    int di, si;
    if (tbuf[1] != USB_DT_STRING )
        return -1;
    for (di = 0, si = 2; si < tbuf[0]; si += 2) {
        if (di >= (buflen - 1))
            break;
        if (tbuf[si + 1])   /* high byte */
            buf[di++] = '?';
        else
            buf[di++] = tbuf[si];
    }
    buf[di] = 0;
    memcpy(tbuf, buf, di + 1);
    return (di);
}

s32 
IUSB_GetAsciiStr(IOSFd fd, u8 ep, u16 index, u16 langId,
        char *buf, u16 buflen)
{
    s8 len = __CtrlMsg(fd, USB_REQTYPE_GETDESC, USB_REQ_GET_DESCRIPTOR,
            (USB_DT_STRING << 8) + index,  langId, buflen, (u32)buf);
    if (len < 0)
        goto done;

    if ((len = unicode2ascii(buf, buflen)) < 0) 
        printf("failed to convert buffer from unicode 2 ascii\n");
    else
        buf[len] = '\0';
done:
    return len;
}

IOSError
IUSB_GetDevDescr(IOSFd fd, struct USB_DevDescr *d)
{
    return  __CtrlMsg(fd, USB_REQTYPE_GETDESC, USB_REQ_GET_DESCRIPTOR,
            SWAP16(0x01), 0, sizeof(struct USB_DevDescr), (u32)d);
}

IOSError
IUSB_SuspendDevice(IOSFd fd)
{
    return IOS_Ioctl(fd, OHC_SUSPEND_MSG, NULL, 0, 0, 0);
}

IOSError
IUSB_ResetDevice(IOSFd fd)
{
    return IOS_Ioctl(fd, OHC_RESET_MSG, NULL, 0, 0, 0);
}

IOSError
IUSB_ResumeDevice(IOSFd fd)
{
    return IOS_Ioctl(fd, OHC_RESUME_MSG, NULL, 0, 0, 0);
}

IOSError 
IUSB_GetDeviceList(const char *path, USBDeviceInfo *deviceList, u8 maxDev, 
        u8 deviceClass, u8 *numDev)
{
    IOSError rv = IOS_ERROR_OK;
    IOSIoVector vector[4]; 

    if (NULL == path || NULL == deviceList || NULL == numDev) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    IOSFd fd = IOS_Open(path, 0);
    if (fd < 0) {
        rv = fd;
        goto done;
    }

    vector[0].base = &maxDev;
    vector[0].length = sizeof(u8);
    vector[1].base = &deviceClass;
    vector[1].length = sizeof(u8);
    vector[2].base = (u8 *)numDev;
    vector[2].length = sizeof(u8);
    vector[3].base = (u8 *)deviceList;
    vector[3].length = maxDev*sizeof(USBDeviceInfo);

    rv = IOS_Ioctlv(fd, OHC_GET_DEVLIST_MSG, 2, 2, vector);
    IOS_Close(fd);

done:
    return rv;
}

#ifndef OH1
#if defined (ENABLE_TEST_FUNCTIONS)
IOSError 
IUSB_GetRhDesca(IOSFd fd, u32 *desca)
{
    IOSError rv = IOS_ERROR_OK;

    if (NULL == desca) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    rv = IOS_Ioctl(fd, OHC_GET_RHDESCA_MSG, 0, 0, desca, sizeof(u32));
done:
    return rv;
}

static IOSError
__getsetRhPortStat(IOSFd fd, u32 cmd, u8 *v0, u32 s0,
        u8 *v1, u32 s1, u32 rd, u32 wr)
{
    IOSError rv;
    IOSIoVector vector[2];
    if (NULL == v0 || NULL == v1) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    vector[0].base = v0;
    vector[0].length = s0;
    vector[1].base = v1;
    vector[1].length = s1;
    rv = IOS_Ioctlv(fd, cmd, rd, wr, vector);
done:
    return rv;
}

IOSError 
IUSB_GetRhPortStatus(IOSFd fd, u8 port, u32 *stat)
{
    u8 p __attribute__((aligned(32)));
    p = port;
    return __getsetRhPortStat(fd, OHC_GET_RHPSTAT_MSG, (u8 *)&p, sizeof(u8), 
            (u8 *)stat, sizeof(u32), 1, 1);
}

IOSError 
IUSB_SetRhPortStatus(IOSFd fd, u8 port, u32 stat)
{
    return __getsetRhPortStat(fd, OHC_SET_RHPSTAT_MSG, (u8 *)&port, sizeof(u8),
            (u8 *) &stat, sizeof(u32), 2, 0);
}
#endif /* ENABLE_TEST_FUNCTIONS */

IOSError 
IUSB_RegisterRemovalNotify(IOSFd fd, IOSMessageQueueId mqid, IOSResourceRequest *reply)
{
    return IOS_IoctlAsync(fd, OHC_NOTIFYREMOVAL_MSG, 0, 0, 0, 0, mqid, reply);
}

/* Transfer direction determined by endpoint */
IOSError
IUSB_IsoMsgAsync(IOSFd fd, u8 *ep, u16 *bufLen, u8 *buf,
        u8 *numPackets, u16 *pktSize,
        IOSMessageQueueId mqid, IOSResourceRequest *reply, u8 *vecBuffer)
{
    IOSError rv = IOS_ERROR_OK;
    IOSIoVector *vector = (IOSIoVector *)vecBuffer;
    u32 i, sz = 0;

    if (NULL == buf || NULL == ep || 0 == *ep || NULL == bufLen
            || NULL == numPackets || NULL == pktSize
            || *numPackets > 8 || *bufLen > (8 *1023)) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    for (i = 0; i < *numPackets; ++i) {
        pktSize[i] &= 0xfff;
        if (pktSize[i] > 1023) {
            rv = IOS_ERROR_INVALID;
            goto done;
        }
        sz += pktSize[i];
    }
    if (sz != *bufLen) {
        rv = IOS_ERROR_INVALID;
        goto done;
    } 
    vector[0].base = ep;
    vector[0].length = sizeof(u8);

    vector[1].base = (u8 *)bufLen;
    vector[1].length = sizeof(u16);

    vector[2].base = numPackets; 
    vector[2].length = sizeof(u8);

    vector[3].base = (u8 *) pktSize; 
    vector[3].length = sizeof(u16)*(*numPackets) ;

    vector[4].base = (u8*) buf; 
    vector[4].length = *bufLen;

    rv = IOS_IoctlvAsync(fd, OHC_ISO_NEW_MSG, 3, 2, vector, mqid, reply);
done:
    return rv;
}

IOSError 
IUSB_RegisterInsertionNotify(const char *path, IOSMessageQueueId mqid, IOSResourceRequest *reply, u16 *vid, u16 *pid, u8 *vecBuffer)
{
    IOSError rv;
    IOSFd fd;
    IOSIoVector *vector = (IOSIoVector *)vecBuffer;

    if (NULL == vector || NULL == path || NULL == vid 
            || NULL == pid || NULL == reply || mqid < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if ((fd = IOS_Open(path, 0)) < 0) {
        rv = fd;
        goto done;
    }
    vector[0].base = (u8 *) vid;
    vector[0].length = sizeof(u16);
    vector[1].base = (u8 *) pid;
    vector[1].length = sizeof(u16);
    rv = IOS_IoctlvAsync(fd, OHC_NOTIFYINSERT_MSG, 2, 0, vector, mqid, reply);
    IOS_Close(fd);
done:
    return rv;
}

IOSError 
IUSB_RegisterClassInsertionNotify(const char *path, IOSMessageQueueId mqid, IOSResourceRequest *reply, u8 *devClass, u8 *vecBuffer)
{
    IOSError rv;
    IOSFd fd;
    IOSIoVector *vector = (IOSIoVector *)vecBuffer;

    if (NULL == vector || NULL == path || NULL == devClass 
            || NULL == reply || mqid < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if ((fd = IOS_Open(path, 0)) < 0) {
        rv = fd;
        goto done;
    }
    vector[0].base = (u8 *) devClass;
    vector[0].length = sizeof(u8);
    rv = IOS_IoctlvAsync(fd, OHC_NOTIFYCLASSINSERT_MSG, 1, 0, vector, mqid, reply);
    IOS_Close(fd);
done:
    return rv;
}

IOSError 
IUSB_CancelInsertionNotify(const char *path, u32 *id)
{
    IOSError rv;
    IOSFd fd;

    if (NULL == path) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if ((fd = IOS_Open(path, 0)) < 0) {
        rv = fd;
        goto done;
    }
    rv = IOS_Ioctl(fd, OHC_CANCELNOTIFY_MSG, id, sizeof(u32), 0, 0);
    IOS_Close(fd);
done:
    return rv;
}

IOSError 
IUSB_RegisterInsertionNotifyWithId(const char *path, IOSMessageQueueId mqid,
        IOSResourceRequest *reply, u16 *vid, u16 *pid, u8 * devClass, 
        u32 *reqId, u8 *vecBuffer)
{
    IOSError rv;
    IOSFd fd;
    IOSIoVector *vector = (IOSIoVector *)vecBuffer;

    if (NULL == vector || NULL == path || NULL == vid 
            || NULL == pid || NULL == reply || NULL == devClass
            || NULL == reqId || mqid < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if ((fd = IOS_Open(path, 0)) < 0) {
        rv = fd;
        goto done;
    }
    vector[0].base = (u8 *) vid;
    vector[0].length = sizeof(u16);
    vector[1].base = (u8 *) pid;
    vector[1].length = sizeof(u16);
    vector[2].base = (u8 *) devClass;
    vector[2].length  = sizeof(u8);
    vector[3].base =  (u8 *) reqId;
    vector[3].length = sizeof(u32);
    rv = IOS_IoctlvAsync(fd, OHC_NOTIFYINSERT_ID_MSG, 3, 1, vector, mqid, reply);
    IOS_Close(fd);
done:
    return rv;
}

s32
IUSB_CtrlMsgAsync(IOSFd fd, u8 *ep, u8 *reqType, u8 *request, u16 *value,
        u16 *index, u16 *length, u32 data, IOSMessageQueueId mqid,
        IOSResourceRequest *reply, u8 *vecBuffer)
{
    s32 rv = 0;
    IOSIoVector *vector = (IOSIoVector *)vecBuffer;
    u16 ulength = *length;
    
    if (NULL == reqType || NULL == request || NULL == value 
            || NULL == index || NULL == length || 0 == data 
            || mqid < 0 || NULL == reply || NULL == vecBuffer) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    *value = SWAP16(*value);
    *index= SWAP16(*index) ;
    *length= SWAP16(*length);
    *ep = SWAP16(*ep); 

    vector[0].base = reqType; /*bmRequestType */
    vector[0].length = sizeof(u8);

    vector[1].base = request; /*bRequest */
    vector[1].length = sizeof(u8);

    vector[2].base =  (u8 *) value; /* wValue */
    vector[2].length = sizeof(u16);

    vector[3].base = (u8 *) index;  /* wIndex */
    vector[3].length = sizeof(u16);

    vector[4].base = (u8 *) length; /* wLength */
    vector[4].length = sizeof(u16);

    vector[5].base =  ep;    /* endpoint number */
    vector[5].length = sizeof(u8);

    vector[6].base = (u8 *)data;
    vector[6].length = ulength;
    rv = IOS_IoctlvAsync(fd, OHC_CTRL_MSG, 6, 1, vector, mqid, reply);
done:
    return rv;
}

s32
IUSB_CtrlMsgWithTimeout(IOSFd fd, u8 reqType, u8 request, u16 value,
        u16 index, u16 length, u32 data,
        u32 timeout, IOSMessageQueueId qid, IOSTimerId t)
{
    s32 rv;
    IOSMessage msg = 0;
    u32 start, end;

    IOSResourceRequest reply; 
    IOSIoVector vector[IUSB_CTRL_ASYNC_SIZE];
    u16 svalue = value;
    u16 sindex = index;
    u16 slength = length;
    u8 sep = 0;

    if (0 == timeout || qid < 0 || t < 0) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }

    IOS_StopTimer(t);
    IOS_RestartTimer(t, timeout, 0);
    
    start = busRd32(SYS_TIMER_REG);
    rv = (s32) IUSB_CtrlMsgAsync(fd, &sep, &reqType, &request, &svalue,
            &sindex, &slength, (u32) data, qid, &reply, (u8 *)vector);
    if (rv < 0) {
        goto done;
    }
    rv = (s32) IOS_ReceiveMessage(qid, &msg, IOS_MESSAGE_BLOCK);
    end = busRd32(SYS_TIMER_REG);
    
    if (IOS_ERROR_OK != rv) {
        goto done;
    }
    if (IUSB_TIMEOUT_MESSAGE == msg) {
        rv = IUSB_ERROR_TIMEOUT;
        printf("%s: control transfer timed out (%u ticks)\n", 
                __FUNCTION__, end - start);
        goto done;
    } 
    rv = reply.status; /* Preserve control transfer return value */
done:
    IOS_StopTimer(t);
    return rv;
}

#endif /* !OH1 */
