/*
 *               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 <iop.h>
#include <ioslibc.h>

#include "ohci.h"
#include "ohci_regs.h"
#include "usb11.h"
#include "ohci_core.h"
#include "ohci_transfers.h"

extern struct ohci_device __ohci_dev[OHCI_DEV_MAX]; 
static OHCCtrlReq *req; /* use for all ctrl transfers here */

/* Reset ports which have a device connected */
static inline void
__waitPOTPGT(struct ohci_hcd *hcd)
{
    u32 interval = (OHCI_READ(hcd->opregs->rhub_desca)
            & OHCI_RHUB_DESCA_POTPGT_MASK) >> OHCI_RHUB_DESCA_POTPGT_SHIFT;
    interval *= 2000; /* units 2ms */
    OHCI_DBG("Sleeping for POTPGT[%u usec]\n", interval);
    usleept(hcd, interval);
}

static inline void
__initPowerSwitching(struct ohci_hcd *hcd, u32 rega)
{
    u32 reg;
    u8 i;
    u8 ndp = hcd->ndp;
    if ( 0 == (rega & OHCI_RHUB_DESCA_NPS_MASK) ) {
        OHCI_DBG("NPS is 0. Will enable PS\n");
        rega |= OHCI_RHUB_DESCA_PSM_MASK;
        reg = OHCI_READ(hcd->opregs->rhub_descb) & OHCI_RHUB_DESCB_DR_MASK;
        for (i = 1; i <= ndp; ++i) {
            reg |= (1 << (OHCI_RHUB_DESCB_PPCM_SHIFT + i));
            OHCI_DBG("reg [%u] = 0x%08x\n", i, reg);
        }
        if (0 == (rega & OHCI_RHUB_DESCA_NOCP_MASK)) 
            rega |= OHCI_RHUB_DESCA_OCPM_MASK;
        OHCI_WRITE(hcd->opregs->rhub_desca, rega);
        OHCI_DBG("writing 0x%08x to descb\n", reg);
        OHCI_WRITE(hcd->opregs->rhub_descb, reg);
    }
}

static inline void
__initOverCurrent(struct ohci_hcd *hcd, u32 rega)
{
    rega |= OHCI_RHUB_DESCA_NPS_MASK;
    rega &= ~OHCI_RHUB_DESCA_OCPM_MASK;
    rega &= ~OHCI_RHUB_DESCA_NOCP_MASK;
    OHCI_WRITE(hcd->opregs->rhub_desca, rega);
}

static inline void
__initRemoteWakeup(struct ohci_hcd *hcd)
{
    u32 reg = OHCI_READ(hcd->opregs->rhub_stat) & OHCI_RHUB_STAT_RSVD_MASK;
    reg |= OHCI_RHUB_STAT_DRWE_MASK | OHCI_RHUB_STAT_OCIC_MASK;
    OHCI_WRITE(hcd->opregs->rhub_stat, reg);
}

static inline void
__powerOnPorts(struct ohci_hcd *hcd)
{
    u8 i;
    u8 ndp = hcd->ndp;
    OHCI_DBG(" number of ports = [%u] completed\n", ndp);
    for (i = 0; i < ndp; ++i ) {
        OHCI_DBG("power on for port[%u] completed\n", i);
        OHCI_WRITE(hcd->opregs->rhub_pstat[i], OHCI_RHUB_PSTAT_PPS_MASK);
    }
}

static inline void
__clearRHubPortChanges(struct ohci_hcd *hcd)
{
    u8 i;
    u8 ndp = hcd->ndp;
    u32 reg =  OHCI_RHUB_PSTAT_OCIC_MASK
        | OHCI_RHUB_PSTAT_PESC_MASK
        | OHCI_RHUB_PSTAT_PSSC_MASK
        | OHCI_RHUB_PSTAT_CSC_MASK;
    for (i = 0; i < ndp; ++i ) {
        OHCI_WRITE(hcd->opregs->rhub_pstat[i], reg);
    }
}

static inline void
__createRhubDevice(struct ohci_hcd *hcd)
{
    __ohci_dev[0].type =  OHCI_DEV_HUB;
    __ohci_dev[0].dev.hub.ndp = hcd->ndp;
}

static IOSError
__resetRHubPort(struct ohci_hcd *hcd, u8 i)
{ 
    IOSError rv = IOS_ERROR_OK;
    u32 cnt = 5;
    u32 reg = OHCI_READ(hcd->opregs->rhub_pstat[i]);
    if (reg & OHCI_RHUB_PSTAT_CCS_MASK) {
        OHCI_WRITE(hcd->opregs->rhub_pstat[i], OHCI_RHUB_PSTAT_PRS_MASK);
        /* Wait for reset completion or 10ms[20ms?] 11.5.1.5 USB 1.1*/
        usleept(hcd, 20000);
        while (--cnt) {
            if (OHCI_READ(hcd->opregs->rhub_pstat[i])
                    & OHCI_RHUB_PSTAT_PRSC_MASK) {
                /* Clear PRSC */
                OHCI_WRITE(hcd->opregs->rhub_pstat[i], 
                        OHCI_RHUB_PSTAT_PRSC_MASK);
                OHCI_DBG("rhub: Reset of port[%u] completed\n", i);
                goto done;
            }
            usleept(hcd, 10); 
        }
        rv = IOS_ERROR_NOTREADY;
        OHCI_DBG("rhub: No device connected to port [%u] (or reset failed)\n", i);
    } else {
        rv = IOS_ERROR_NOTREADY;
    }
done:
    return rv;
}

IOSError
suspendRHubPort(struct ohci_hcd *hcd, u8 p)
{
    IOSError rv = IOS_ERROR_OK;
    u32 reg;
    if (p > hcd->ndp) {
        OHCI_DBG("ndp = %u. Requested to suspend port: %u\n", hcd->ndp, p);
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    reg = OHCI_READ(hcd->opregs->rhub_pstat[p]);
    if (0 == (reg & OHCI_RHUB_PSTAT_CCS_MASK)) {
        OHCI_DBG("suspend: no device connected\n", hcd->ndp, p);
        rv = IOS_ERROR_NOTREADY; /* No device connected */
        goto done;
    }
    OHCI_WRITE(hcd->opregs->rhub_pstat[p], OHCI_RHUB_PSTAT_PSS_MASK);
    reg = OHCI_READ(hcd->opregs->rhub_pstat[p]);
    if (0 == (reg & OHCI_RHUB_PSTAT_PSS_MASK)) {
        OHCI_DBG("suspend: failed\n");
        rv = IOS_ERROR_UNKNOWN; /* Suspend failed */
        goto done;
    }
done:
    return rv;
}

IOSError
resumeRHubPort(struct ohci_hcd *hcd, u8 p)
{
    IOSError rv = IOS_ERROR_OK;
    u32 reg;
    
    if (p > hcd->ndp) {
        OHCI_DBG("ndp = %u requested to resume: %u\n", hcd->ndp, p);
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    reg = OHCI_READ(hcd->opregs->rhub_pstat[p]);
    if (0 == (reg & OHCI_RHUB_PSTAT_PSS_MASK)) {
        /* Not suspended. Do nothing. */
        OHCI_DBG("resume: device not suspended\n");
        goto done;
    }
    OHCI_WRITE(hcd->opregs->rhub_pstat[p], OHCI_RHUB_PSTAT_POCI_MASK);
    reg = OHCI_READ(hcd->opregs->rhub_pstat[p]);
    if (1 == (reg & OHCI_RHUB_PSTAT_PSS_MASK)) {
        OHCI_DBG("resume: failed\n");
        rv = IOS_ERROR_UNKNOWN; /* Resume failed */
        goto done;
    }
done:
    return rv;
}

static IOSError
__setDeviceAddress(struct ohci_hcd *hcd, u8 devnum)
{
    IOSError rv;
    
    memset(req, 0, sizeof(OHCCtrlReq));
    req->bmRequestType = USB_REQTYPE_SETADDR;
    req->bRequest = USB_REQ_SET_ADDRESS;
    req->wValue = CPU_TO_OHCI16(devnum);
    req->wIndex = req->wLength = 0;
    req->data = NULL;   
    req->ep = 0;
    req->addr = 0;

    if (IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: setting address for device %u succeeded\n", devnum);
        setDevNodeAddr(devnum, devnum);
    } else {
        OHCI_DBG("rhub: setting address for device %u failed\n", devnum);
    }
    return rv;
}

static IOSError
__setDeviceConfig(struct ohci_hcd *hcd, u8 devnum, 
        u8 addr, u8 config)
{
    IOSError rv;
    
    memset(req, 0, sizeof(OHCCtrlReq));
    req->bmRequestType = USB_REQTYPE_SETADDR;
    req->bRequest = USB_REQ_SET_CONFIGURATION;
    req->wValue = CPU_TO_OHCI16(config);
    req->wIndex = req->wLength = 0;
    req->data = NULL;
    req->ep = 0;
    req->addr = 0;

    if ( IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: setting configuration %u for device succeeded\n", config);
    } else {
        OHCI_DBG("rhub: setting configuration %u for device failed\n", config);
    }
    return rv;
}

static IOSError
__setDeviceIntf(struct ohci_hcd *hcd, u8 devnum, 
        u8 addr, u8 intf, u8 alt)
{
    IOSError rv;
    
    memset(req, 0, sizeof(OHCCtrlReq));
    req->bmRequestType = USB_REQTYPE_SETFEAT_INTF;
    req->bRequest = USB_REQ_SET_INTERFACE;
    req->wValue = CPU_TO_OHCI16(alt);
    req->wIndex = CPU_TO_OHCI16(intf);
    req->wLength = 0;
    req->data = NULL;
    req->ep = 0;
    req->addr = 0;

    if ( IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: setting interface %u (alt %u) for device succeeded\n", intf, alt);
    } else {
        OHCI_DBG("rhub: setting interface %u (alt %u) for device failed\n", intf, alt);
    }
    return rv;
}

static IOSError
__setInterfaceAltsettings(struct ohci_hcd *hcd, u8 devnum)
{
    IOSError rv;
    u8 k;
    struct usb_intf *intfList = __ohci_dev[devnum].dev.dev.intf;
    u8 nintf = __ohci_dev[devnum].dev.dev.nintf;
    for (k = 0; k < nintf; ++k) { 
        OHCI_DBG("Setting alt %u for intf %u\n", intfList[k].alt, 
                intfList[k].intf);
        if (0 != intfList[k].alt) {
            rv = __setDeviceIntf(hcd, devnum, devnum, 
                    intfList[k].intf, intfList[k].alt);
            if (rv < 0) {
                OHCI_DBG("Setting alt %u for intf %u failed\n", 
                        intfList[k].alt, intfList[k].intf);
                goto done;
            }
        }
    }
    rv = IOS_ERROR_OK;
done:
    return rv;
}

static IOSError
__getDevDescr(struct ohci_hcd *hcd, u8 devnum, u8 addr,
        struct USB_DevDescr *dev_descr)
{
    IOSError rv;

    memset(req, 0, sizeof(OHCCtrlReq));
    req->bmRequestType = USB_REQTYPE_GETDESC;
    req->bRequest = USB_REQ_GET_DESCRIPTOR;
    req->wValue = 0x01; /* Device descr */
    req->wIndex = 0;
    req->wLength = CPU_TO_OHCI16((u16)sizeof(struct USB_DevDescr));
    req->data = (u32)dev_descr;
    req->ep = 0;
    req->addr = addr;

    if (IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: get descr succeeded\n");
    } else {
        OHCI_DBG("rhub: get descr failed\n");
    }
    return rv;
}

static IOSError
__getConfDescrNoIntf(struct ohci_hcd *hcd,
        u8 devnum,
        u8 addr,
        struct USB_ConfDescrNoIntf *cdescr)
{
    IOSError rv;

    memset(req, 0, sizeof(OHCCtrlReq));
    req->bmRequestType = USB_REQTYPE_GETDESC;
    req->bRequest = USB_REQ_GET_DESCRIPTOR;
    req->wValue = 0x02; /* Config descr */
    req->wIndex = 0;
    req->wLength = CPU_TO_OHCI16((u16)sizeof(*cdescr));
    req->data = (u32)cdescr;
    req->ep = 0;
    req->addr = addr;

    if (IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: get conf descr succeeded\n", devnum);
    } else {
        OHCI_DBG("rhub: get conf descr failed\n", devnum);
    }
    cdescr->wTotalLength = OHCI_TO_CPU16(cdescr->wTotalLength);
    return rv;
}

IOSError
__initEndpoint(struct ohci_hcd *hcd, struct usb_dev_ep *devEp,
        u8 addr)
{ 
    struct ohci_ed *ed;
    void *td;
    u32 flags = 0;
    u8 typ = devEp->attr & USB_ENDPT_ATTR_MASK;
    u8 spd = __ohci_dev[addr].dev.dev.spd;
    IOSError rv = IOS_ERROR_MAX;

    /* Allocate dummy TD */
    if (USB_ENDPT_ATTR_ISO == typ) {
        devEp->itd_dummy = td = allocITD();
    } else {
        devEp->td_dummy = td = allocTD();
    }
    if (NULL == td) {
            OHCI_DBG("Failed to allocate dummy TD for endpoint address\n",
                    devEp->ep);
            goto done;
    }
    if (USB_ENDPT_ATTR_INTR == typ) { /* Interrupt endpoints */
        devEp->ed = ed = allocIntrED(hcd, devEp->interval); 
    } else {
        devEp->ed = ed = allocED();
    }
    if (devEp->ed == NULL) {
        OHCI_DBG("Failed to allocate ed for endpoint address\n",
                devEp->ep);
        goto done;
    }
    ed->headP = CPU_TO_OHCI32((u32)td);
    ed->tailP = ed->headP;
    
    flags = 
        (addr << OHCI_ED_FA_SHIFT) 
        | ((devEp->ep &0xf) << OHCI_ED_EN_SHIFT)
        | (spd << OHCI_ED_SPD_SHIFT)
        | (devEp->maxP << OHCI_ED_MPS_SHIFT) 
        | OHCI_ED_USED_MASK;
    flags |= (devEp->ep & 0x80)? 
        OHCI_ED_DIR_IN:OHCI_ED_DIR_OUT;
    flags |= OHCI_ED_SKIP_MASK;
    if (USB_ENDPT_ATTR_ISO == typ) {
       flags |= OHCI_ED_FRMT_ISO;
    }
    devEp->ed->flags = CPU_TO_OHCI32(flags);
    rv = IOS_ERROR_OK; 

done:
    return rv;
}

static void 
__saveEndpoint(struct ohci_hcd *hcd, u8 devnum, u8 *buf, u8 savedEp)
{
    u8 *current = buf;
    struct usb_dev_ep *epList = __ohci_dev[devnum].dev.dev.ep;

    epList[savedEp].ep = *EPDESCR_FIELD(current, bEndpointAddress);
    epList[savedEp].attr = *EPDESCR_FIELD(current, bAttributes); 
    epList[savedEp].maxP = *EPDESCR_FIELD(current, wMaxPacketSize);
    epList[savedEp].interval = *EPDESCR_FIELD(current, bInterval);

    __initEndpoint(hcd, &epList[savedEp], devnum);
    switch (epList[savedEp].attr & USB_ENDPT_ATTR_MASK) {
        case USB_ENDPT_ATTR_CTRL:
            enqueueCtrlED(hcd, epList[savedEp].ed);
            break;
        case USB_ENDPT_ATTR_BLK:
            enqueueBlkED(hcd, epList[savedEp].ed);
            break;
        case USB_ENDPT_ATTR_ISO:
            enqueueISOED(hcd, epList[savedEp].ed);
            break;
            /* default :  INTR */
            /* Do nothing. Intr eps are already enqueued */
    }
}

/* saveFlag: 
 *  bit i == 0 => haven't saved endpoints for intf i for 
 *                any altsetting
 *           1 => saved endpoints for some altsetting 
 *                for intf i
 *  XXX horti
 *  For a given intf, if we save endpoints for 1 altsetting,
 *  we skip the other alt settings.
 */

static void
__parseSaveConfDescr(struct ohci_hcd *hcd, u8 *buf, u16 size, u8 devnum)
{
    u8 savedEp = 1; /* skip ep 0 */
    u8 *current = buf;
    u32 saveFlag = 0; 

    current = buf + *CONFDESCR_FIELD(current, bLength);
    while (current < buf + size) {
        u8 numEp = (u8) *INTFDESCR_FIELD(current, bNumEndpoints);
        u8 intf = (u8) *INTFDESCR_FIELD(current, bInterfaceNumber);
        u8 alt = (u8) *INTFDESCR_FIELD(current, bAlternateSetting);
        u8 devClass = (u8) *INTFDESCR_FIELD(current, bInterfaceClass);
        u8 subClass = (u8) *INTFDESCR_FIELD(current, bInterfaceSubClass);
        u8 protocol = (u8) *INTFDESCR_FIELD(current, bInterfaceProtocol);

        if (intf > OHCI_DEV_MAX_INTF) { 
            OHCI_DBG("Have >%u interfaces. Skipping.\n", OHCI_DEV_MAX_INTF);
            goto parse_done;
        }
        /* Done with interface descr */
        current += (u8) *INTFDESCR_FIELD(current, bLength);
        if (0 == numEp) {
            /* There can be class specific descriptors interleaved.
             * They need to be skipped.
             */
            while (1) {
                /* ran through the whole buffer */
                if (current >= buf + size) {
                    goto parse_done;
                }
                /* Hit the next intf desc */
                if (USB_DT_INTERFACE == *EPDESCR_FIELD(current, bDescriptorType))
                    break;
                current += *(u8 *)current; /* skip this class specific desc */
            } 
            continue; /* continue parsing remaining interfaces */     
        }

        if (numEp == 0) {
            continue; /* parse next interface */
        }
        /* Have some endpoint descrs to parse */

        /* If we are saving endpoints for this interface,
         * save class information.
         */
        if (0 == (saveFlag & (1 << intf))) {
            setDevIntf(devnum, intf, alt, devClass, subClass, protocol);
        }
        while (numEp > 0) {
            u8 *ep = current;
            /* Skip class specific descr */
            if (*EPDESCR_FIELD(ep, bDescriptorType) != 0x05) {
                current += *(u8 *)current; /* bLength for class specific desc */
                ep = current;
                /* Ran through the whole buffer */
                if (current >= buf + size)
                    goto parse_done; 
                continue; /* continue parsing remaining interfaces */
            }
            --numEp;
            if (0 == (saveFlag & (1 << intf))) {
                OHCI_DBG("Saving endpoint for intf %u\n", intf);
                __saveEndpoint(hcd, devnum, current, savedEp);
                savedEp++;
                if (savedEp > OHCI_DEV_MAX_EP) {
                    OHCI_DBG("Only saving up to %u endpoints per device(including endpoint 0)\n", OHCI_DEV_MAX_EP);
                    /* Just skip the remaining endpoints */
                    goto parse_done;
                }
            }

            current += *EPDESCR_FIELD(ep, bLength);
            if (current >= buf + size)
                goto parse_done; 
        }
        /* Don't save endpoints for other altsettings for this interface*/
        saveFlag |= (1 <<intf); 
    }
parse_done:
#ifdef OHCI_ENABLE_DBG
    printSavedDevice(devnum);
#endif
    return;
}

static IOSError
__getConfDescr(struct ohci_hcd *hcd,
        u8 devnum,
        u8 addr,
        u16 size)
{
    IOSError rv;
    u8 *buf = IOS_AllocAligned(__ohcdHeapId, size, 32);
    if (NULL == buf) {
        rv = IOS_ERROR_MAX;
        goto done;
    }
    memset(buf, 0, size);
    memset(req, 0, sizeof(OHCCtrlReq));

    req->bmRequestType = USB_REQTYPE_GETDESC;
    req->bRequest = USB_REQ_GET_DESCRIPTOR;
    req->wValue = 0x02; /* Config descr */
    req->wIndex = 0;
    req->wLength = CPU_TO_OHCI16(size);
    req->data = (u32)buf;
    req->ep = 0;
    req->addr = addr;
    if (IOS_ERROR_OK == (rv = ohci_BlockCtrlMsg(hcd, devnum, req))) {
        OHCI_DBG("rhub: get conf descr size %u succeeded\n", size);
        __parseSaveConfDescr(hcd, buf, size, devnum);
    } else {
        OHCI_DBG("rhub: get conf descr failed\n", devnum);
    }
    IOS_Free(__ohcdHeapId, buf);

done:
    return rv;
}

/* Configure device. Return device address (> 0). */
static u8
__configureUSBDevice(struct ohci_hcd *hcd, u8 port)
{
    u8 devnum = 0; 
    u8 spd = 0;
   
    struct USB_DevDescr *ddescr = (struct USB_DevDescr *)
        IOS_AllocAligned(__ohcdHeapId, sizeof(struct USB_DevDescr), 32);
    struct USB_ConfDescrNoIntf *cdescr = (struct USB_ConfDescrNoIntf *)
        IOS_AllocAligned(__ohcdHeapId, sizeof(struct USB_ConfDescrNoIntf), 32);

    memset(ddescr, 0, sizeof(struct USB_DevDescr));
    memset(cdescr, 0, sizeof(struct USB_ConfDescrNoIntf));
    /* Initialize a device node */
    if (OHCI_READ(hcd->opregs->rhub_pstat[port])
            & OHCI_RHUB_PSTAT_LSDA_MASK) {
        spd = 1;
    } else {
        OHCI_DBG("Full speed device detected\n");
    }
    if ((devnum = initDevNode(hcd, port, 0, spd)) == 0) /* 0 is always rhub */
        goto done;

    OHCI_DBG("Got devnum = %u for device at port %u\n", devnum, port);
    /* Set address = devnum */
    if (IOS_ERROR_OK != __setDeviceAddress(hcd, devnum)) 
        goto done;

    /* Save device descriptor into device node */
    if ( IOS_ERROR_OK != __getDevDescr(hcd, devnum, devnum, ddescr))
        goto done;
    setEp0MaxP(devnum, ddescr->bMaxPacketSize0);

    if ( IOS_ERROR_OK != __getDevDescr(hcd, devnum, devnum, ddescr))
        goto done;
#ifdef OHCI_ENABLE_DBG
    dumpDevDescr(*ddescr);
#endif /* OHCI_ENABLE_DBG */
    OHCI_DBG("Found device: vid %x pid %x\n",
            OHCI_TO_CPU16(ddescr->idVendor), OHCI_TO_CPU16(ddescr->idProduct));
    setDevVid(devnum, OHCI_TO_CPU16(ddescr->idVendor));
    setDevPid(devnum, OHCI_TO_CPU16(ddescr->idProduct));
   
    if (USB_CLASS_UNDEF != ddescr->bDeviceClass 
            && USB_CLASS_HUB != ddescr->bDeviceClass) {
        setDevClass(devnum, ddescr->bDeviceClass, ddescr->bDeviceSubClass,
                ddescr->bDeviceProtocol);
    }

    if (ddescr->bNumConfigurations > 1) {
        OHCI_DBG("Currently support only 1 configuration of available %u\n",
                ddescr->bNumConfigurations);
    } else {
        OHCI_DBG("Found 1 configuration\n");
    }
    /* Save configuration descriptor into device node */
    __getConfDescrNoIntf(hcd, devnum, devnum, cdescr); 
    setDevMaxPower(devnum, cdescr->MaxPower);

    /* Fetch entire configuration descriptor (including interface and
     * endpoint descriptors). Save and enqueue ed's. */
    __getConfDescr(hcd, devnum, devnum, cdescr->wTotalLength); 

    /* Set configuration */
    __setDeviceConfig(hcd, devnum, devnum, cdescr->bConfigurationValue);

    /* Set interface alternate settings if needed */
    __setInterfaceAltsettings(hcd, devnum);

    if (IOS_EVENT_OH0 == hcd->event) {
        printf("OH0:");
    } else {
        printf("OH1:");
    }
    printf("configured USB device at port %u, vid: 0x%04x pid: 0x%04x\n", port,
            OHCI_TO_CPU16(ddescr->idVendor), OHCI_TO_CPU16(ddescr->idProduct));
#ifdef DIAG_TEST
    printf("Starting diag control transfer test\n");
    while (1) {
        __getConfDescrNoIntf(hcd, devnum, devnum, cdescr); 
        usleep(100);
    }
#endif
done:
    IOS_Free(__ohcdHeapId, ddescr);
    IOS_Free(__ohcdHeapId, cdescr);
    return devnum;
}

static inline void
__configureRHubPorts(struct ohci_hcd *hcd)
{
    u8 i;
    u8 devnum = 0;
    u8 ndp = hcd->ndp;
    for ( i = 0; i < ndp; ++i ) {
        OHCI_DBG("rhub: Attempting to reset port %u\n", i);
        if (IOS_ERROR_OK == __resetRHubPort(hcd, i)) {
            OHCI_DBG("rhub: Device at port %u was reset successfully\n", i);
            if ( 0 == (devnum = __configureUSBDevice(hcd, i))) {
                OHCI_DBG("rhub: Configuring device at port %u failed.\n", i);
                continue;
            }
            OHCI_DBG("rhub: *** Device at port %u configured.\n", i);
        }
    }
    return;
}

/* Public functions */

void
handleRHSCEvent(struct ohci_hcd *hcd)
{
    u8 ndp = hcd->ndp;
    u8 i;
    OHCI_WRITE(hcd->opregs->int_dis, OHCI_INTDIS_RHSC_MASK);
    for (i = 0; i < ndp; ++i ) {
        u32 reg = OHCI_READ(hcd->opregs->rhub_pstat[i]);
        if (reg & OHCI_RHUB_PSTAT_CSC_MASK) {
            if (reg & OHCI_RHUB_PSTAT_CCS_MASK) {
                OHCI_DBG("hot_plug: Port status for port %u changed\n", i);
                OHCI_WRITE(hcd->opregs->rhub_pstat[i], OHCI_RHUB_PSTAT_PPS_MASK);
                OHCI_DBG("hot_plug: Attempting to reset port %u\n", i);
                if (IOS_ERROR_OK == __resetRHubPort(hcd, i)) {
                    OHCI_DBG("hot_plug: Device at port %u was reset successfully\n", i);
#if 0
                    /* XXX horti: Do this after delDevNode is modified to cleanup all
                     * endpoints for removed device. Cleaning up partially and trying to
                     * reconnect will just lead to instability.
                     */
                    if (0 == __configureUSBDevice(hcd, i)) {
                        OHCI_DBG("hot_plug: Configuring device at port %u failed.\n", i);
                    } else {
                        OHCI_DBG("hot_plug: New device at port %u configured.\n", i);
                    }
#endif
                }
            } else {
                OHCI_DBG("hot_plug: Detected device removal\n");
                delDevNode(hcd,i); /* Needed to send device removal notifications */
            }
            reg = OHCI_RHUB_PSTAT_PESC_MASK | OHCI_RHUB_PSTAT_CSC_MASK;
            OHCI_WRITE(hcd->opregs->rhub_pstat[i], reg);
        }
    }
    OHCI_WRITE(hcd->opregs->int_en, OHCI_INTEN_RHSC_MASK);
}

IOSError
startOHCIRootHub(struct ohci_hcd *hcd)
{
    IOSError rv = IOS_ERROR_OK;

    u32 rega = OHCI_READ(hcd->opregs->rhub_desca) 
        & OHCI_RHUB_DESCA_RSVD_MASK;
    /* Use for all control transfers */
    req = (OHCCtrlReq *)IOS_AllocAligned(__ohcdHeapId, sizeof(OHCCtrlReq), 32);
    if ( NULL == req) {
        rv = IOS_ERROR_MAX;
        goto done;
    }

    hcd->ndp = (rega & OHCI_RHUB_DESCA_NDP_MASK) >> OHCI_RHUB_DESCA_NDP_SHIFT;
    __createRhubDevice(hcd);
    __initPowerSwitching(hcd, rega);
    __initOverCurrent(hcd, rega);
    __initRemoteWakeup(hcd);
    __powerOnPorts(hcd);
    __waitPOTPGT(hcd);
    __configureRHubPorts(hcd);
    __clearRHubPortChanges(hcd);
    hcd->flags |= HCD_RHUB_INIT_MASK; /* root hub is initialized */

    IOS_Free(__ohcdHeapId, req);
done:
    return rv;
}
