/*
 *               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.
 *
 */
/* Functions to handle device nodes, etc */
#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]; 
extern ohci_dev_notify __ohci_dev_notify[OHCI_DEV_MAX];

void
initOHCIDevNodes(void)
{ 
  memset(__ohci_dev, 0, sizeof(__ohci_dev)); /* UNUSED == 0 */
}

s8 
getEndpointIdx(u8 devnum, u8 epAddr)
{
  s8 rv;
  for (rv = 1; rv < OHCI_DEV_MAX_EP; ++rv) 
     if (epAddr == __ohci_dev[devnum].dev.ep[rv].ep) 
         goto done;
  rv = -1;
done:
  return rv;
}

void
setDevNodeAddr(u8 devnum, u8 addr)
{
    u32 flags;
    struct ohci_ed *ed0 = __ohci_dev[devnum].dev.ep0.ed;
    flags = OHCI_TO_CPU32(ed0->flags);
    flags |= (devnum << OHCI_ED_FA_SHIFT);
    ed0->flags = CPU_TO_OHCI32(flags);
    return;
}

void 
setEp0MaxP(u8 devnum, u16 maxP)
{
    u32 flags;
    struct ohci_ed *ed0;
    IOS_FlushMem(IOS_WB_OHCI0); 
    IOS_InvalidateRdb(IOS_RB_IOD);

    ed0 = __ohci_dev[devnum].dev.ep0.ed;
    flags = OHCI_TO_CPU32(ed0->flags);
    flags &= ~OHCI_ED_MPS_MASK;
    flags |= (maxP << OHCI_ED_MPS_SHIFT);
    ed0->flags = CPU_TO_OHCI32(flags);
    __ohci_dev[devnum].dev.ep0.maxP = maxP;

    IOS_FlushMem(IOS_WB_IOD); 
    IOS_InvalidateRdb(IOS_RB_OHCI0);
    return;
}

#if OH0
IOSError
setEdLoad(ohci_hcd *hcd, usb_dev_ep *ep, u32 spd)
{
  /* ed load in ns, per frame */
  u32 load_ns = calcBusTransTime_ns(spd, 
                              (ep->ep & 0x80)? OHCI_ED_DIR_IN: OHCI_ED_DIR_OUT,
                              ep->attr & USB_ENDPT_ATTR_MASK,
                              ep->maxP)/ ep->interval;
  hcd->load_ns += load_ns;
  if (hcd->load_ns > OHCI_FRAME_TIME_PERIODIC_US*1000L) {
      OHCI_ERR("WARNING: Possible scheduling overflow: periodic xfer load for hcd = %lu ns (frame_max = %lu ns)\n", hcd->load_ns, OHCI_FRAME_TIME_PERIODIC_US*1000L);

      return IOS_ERROR_MAX; /* schedule overrun possible */
  } else  {
      OHCI_DBG("Periodic xfer load for hcd = %lu ns (frame_max = %lu ns)\n", 
              hcd->load_ns, OHCI_FRAME_TIME_PERIODIC_US*1000L);
      return IOS_ERROR_OK;
  }
}
#endif /* OH0 */

void    
setDevVid(u8 devnum, u16 idVendor)
{
  __ohci_dev[devnum].dev.vid = idVendor;
}

void
setDevPid(u8 devnum, u16 idProduct)
{
 __ohci_dev[devnum].dev.pid= idProduct;
}

void
setDevClass(u8 devnum, u8 devClass, u8 subClass, u8 protocol)
{
     __ohci_dev[devnum].dev.devClass= devClass;
     __ohci_dev[devnum].dev.subClass= subClass;
     __ohci_dev[devnum].dev.protocol= protocol;
      OHCI_DBG("set class of device %u to %u\n", devnum, devClass);
}

void
setDevMaxPower(u8 devnum, u8 maxPower)
{
 __ohci_dev[devnum].dev.maxPower = maxPower;
}

/* This is called once per interface. It doesn't check
 * if the interface is already present in the list.
 */
void 
setDevIntf(u8 devnum, u8 intf, u8 alt,
        u8 devClass, u8 subClass, u8 protocol)
{
    u8 nintf;
    struct usb_intf *devIntf;
    
    nintf  =  __ohci_dev[devnum].dev.nintf;
    devIntf = &__ohci_dev[devnum].dev.intf[nintf];
    if (0 == devIntf->devClass) {
        devIntf->intf = intf;
        devIntf->alt = alt;
        devIntf->subClass= subClass;
        devIntf->devClass= devClass;
        devIntf->protocol= protocol;
        ++__ohci_dev[devnum].dev.nintf;
        OHCI_DBG("devnum = %u: intf = %u alt = %u class = %u subClass = %u protocol= %u\n", devnum, intf, alt, devClass, subClass, protocol);
    }
}

struct usb_intf *
getDevIntf(u8 devnum)
{
    return __ohci_dev[devnum].dev.intf;
}


s8
getDeviceIdx(u32 handle)
{
    s8 idx;
    u16 openid;
    idx = (handle & DEV_OPENID_IDX_MASK) >> DEV_OPENID_IDX_SHIFT;
    /* Assume no opens for roothub */
    if (idx <= 0 || OHC_RSVD_HANDLE == handle) {
        idx = -1;
        OHCI_DBG("getDeviceIdx: Invalid handle: 0x%08x\n", handle);
        goto done;
    }
    openid = (handle & DEV_OPENID_ID_MASK) >> DEV_OPENID_ID_SHIFT; 
    
    if (OHCI_DEV_UNUSED == __ohci_dev[idx].type) {
        OHCI_DBG("getDeviceIdx: device does not exist\n");
        idx = -1;
        goto done;
    }
    if (__ohci_dev[idx].openid != openid) {
        OHCI_DBG("getDeviceIdx: invalid open id: 0x%x expect: 0x%x\n", openid, __ohci_dev[idx].openid);
        idx = -1;
        goto done;
    }
done:
    return idx;
}

IOSError 
setOpen(s32 devid)
{
  IOSError rv = IOS_ERROR_OK;
  s32 idx = getDeviceIdx(devid);
  if (idx < 0) {
      rv = IOS_ERROR_INVALID;
      goto done;
  }
  __ohci_dev[idx].opened = DEV_OPENED; 
done:
  return rv;
}

/* Send NULL vid, pid pointer, to just check valid devnum */
IOSError 
getVidPid(u8 devnum, u16 *vid, u16 *pid)
{
    IOSError rv = IOS_ERROR_OK;
    if ((devnum > OHCI_DEV_MAX) ||
         (OHCI_DEV_UNUSED == __ohci_dev[devnum].type)) {
        rv = IOS_ERROR_INVALID;
        goto done;
    }
    if (NULL != vid)
        *vid =  __ohci_dev[devnum].dev.vid;
    if (NULL != pid)
        *pid =  __ohci_dev[devnum].dev.pid; 
done:
    return rv;
}

IOSError
setDevNotifyRemoval(u8 devnum, IOSResourceRequest *resReq)
{
  IOSError rv = IOS_ERROR_OK;
  if (NULL != __ohci_dev[devnum].dev.notifyRemoval) {
      OHCI_DBG("Request already registered for device removal\n");
      rv = IOS_ERROR_EXISTS;
      goto done;
  }
  OHCI_DBG("Registered request for device removal\n");
  __ohci_dev[devnum].dev.notifyRemoval = resReq;
done:
  return rv;
}

static IOSError
__checkDevClass(u8 devnum, u8 devClass)
{
    IOSError rv = IOS_ERROR_INVALID;
    if (OHCI_DEV_UNUSED == __ohci_dev[devnum].type
            || 0 == devClass) {
        goto done;
    }
    if (devClass == __ohci_dev[devnum].dev.devClass) {
        rv = IOS_ERROR_OK;
        goto done;
    }
    {
        struct usb_intf *intfList = __ohci_dev[devnum].dev.intf;
        u8 nintf = __ohci_dev[devnum].dev.nintf;
        u8 k;
        for (k = 0; k < nintf; ++k) { 
            if (devClass == intfList[k].devClass) {
                rv = IOS_ERROR_OK;
                goto done;
            }
        }
    }
done:
    return rv;
}

static IOSError
__checkDevice(u8 devnum, u8 devClass, u16 vid, u16 pid)
{
    IOSError rv = IOS_ERROR_INVALID;
    if (OHCI_DEV_UNUSED == __ohci_dev[devnum].type) {
        goto done;
    }
    if (0 != devClass) {
        rv = __checkDevClass(devnum, devClass);
        if (rv < 0) goto done;
    }
    if (0 != vid) {
       if (( __ohci_dev[devnum].dev.vid != vid)
             ||  __ohci_dev[devnum].dev.pid != pid) {
           rv = IOS_ERROR_INVALID;
           goto done;
       }
       rv = IOS_ERROR_OK;
    } 
done:
  return rv;
}

static s16
__findDevNotify(u8 devClass, u16 vid, u16 pid)
{
    s16 idx;
    for (idx = 0; idx < OHCI_DEV_MAX; ++idx) {
        ohci_dev_notify d = __ohci_dev_notify[idx];
        if (devClass && devClass != 0xff) {
              if (devClass == d.devClass) {
                  OHCI_DBG("idx for class %u (vid = 0x%x pid = 0x%x) = %d\n",
                          devClass, d.vid, d.pid, idx);
                  goto done;
              } 
              continue;
        }
        if (vid && d.vid == vid && d.pid == pid) {
            OHCI_DBG("idx for vid = 0x%x pid = 0x%x = %d\n", vid, pid, idx);
            goto done;
        }
    }
    /* Not found */
    idx = -1; 
done:
    return idx;
}

static IOSError
__notifyDevInsert(s16 idx)
{
  IOSError rv = IOS_ERROR_INVALID;
  if (idx < 0) { 
      goto done;
  }
  if (NULL != __ohci_dev_notify[idx].req) {
      rv = IOS_ResourceReply(__ohci_dev_notify[idx].req, IOS_ERROR_OK);
  } else {
      OHCI_ERR("devnodes: internal error: resource req is null\n");
      rv = IOS_ERROR_INVALID;
  }
  memset(__ohci_dev_notify + idx, 0, sizeof(struct ohci_dev_notify));
done: 
  return rv;
}

IOSError
devNotifyDevInsert(u8 devnum)
{
    IOSError rv = IOS_ERROR_OK;
    s16 idx = __findDevNotify(__ohci_dev[devnum].dev.devClass,
            __ohci_dev[devnum].dev.vid, __ohci_dev[devnum].dev.pid);

    if (idx >= 0) {
        rv = __notifyDevInsert(idx);
        goto done;
    } 
    {
        struct usb_intf *intfList = __ohci_dev[devnum].dev.intf;
        u32 nintf = __ohci_dev[devnum].dev.nintf;
        u32 k;
        for (k = 0; k < nintf; ++k) { 
            idx = __findDevNotify(intfList[k].devClass, 0, 0);
            if (idx >= 0) {
                rv = __notifyDevInsert(idx);
            }
        }
    }
done:
    return rv;
}

IOSError
setDevNotifyInsertion(u16 vid, u16 pid, u8 devClass,
        IOSResourceRequest *resReq)
{
    s32 id;
    s8 idx;
    IOSError rv = IOS_ERROR_OK;
    OHCI_DBG("%s: class %u vid %04x pid %04x\n", __FUNCTION__,
            devClass, vid, pid);
    /* If device already present, send reply */
    if ((id = getUnopenedDeviceId(devClass, vid, pid)) > 0) {
        OHCI_DBG("ohci: Device already present. Sending reply\n");
        rv = IOS_ResourceReply(resReq, IOS_ERROR_OK);
        goto done;
    }
    OHCI_DBG("ohci: Device (class %u vid 0x%x, pid 0x%x) not inserted yet..\n", devClass, vid, pid);
    idx = __findDevNotify(devClass, vid, pid);
    if (idx < 0) {  /* new */
        OHCI_DBG("ohci: no clients waiting for device\n");
    } else { /* multiple identical devices possible */
        OHCI_DBG("ohci: client(s) already waiting for device\n");
    }
    for (idx = 0; idx < OHCI_DEV_MAX; ++idx) {
        if (0 == __ohci_dev_notify[idx].vid &&
            0 == __ohci_dev_notify[idx].pid &&
            0 == __ohci_dev_notify[idx].devClass) {
            break;
        }
    }
    if (OHCI_DEV_MAX == idx) {
        OHCI_ERR("no empty slot for new device\n");
        rv = IOS_ERROR_MAX; /* no space for new device */
        goto done;
    }
    __ohci_dev_notify[idx].devClass = devClass;
    __ohci_dev_notify[idx].vid = vid;
    __ohci_dev_notify[idx].pid = pid;
    __ohci_dev_notify[idx].req = resReq;
    __ohci_dev_notify[idx].id = rv = getRand32() & 0x7fffff00;
    rv |= idx;
    OHCI_DBG("saved device (class %u vid 0x%04x, pid 0x%04x) in insertion"
            "notify list at idx %d\n", devClass, vid, pid, idx);
done:
    return rv;
}

IOSResourceRequest *
cancelDevNotifyInsertion(u32 id)
{
    IOSResourceRequest *cancelReq = NULL;
    u32 idx = id & 0xff;
    id &= 0x7fffff00;
   
    if (idx > OHCI_DEV_MAX) {
        goto done;
    }
    if (__ohci_dev_notify[idx].id != id) {
            goto done;
    }
    cancelReq = __ohci_dev_notify[idx].req;
    memset(__ohci_dev_notify + idx, 0, sizeof(struct ohci_dev_notify));
    OHCI_DBG("Insertion notification canceled\n");
done:
    return cancelReq;
}

IOSError
initHubDevNode(ohci_hcd *hcd, u8 devnum, u8 ndp, u8 potpgt)
{
    IOSError rv;
    __ohci_dev[devnum].dev.hubp = IOS_AllocAligned(__ohcdHeapId, sizeof(usb_hub), 32);
    if (NULL == __ohci_dev[devnum].dev.hubp) {
      OHCI_ERR("Failed to allocate hub device node\n");
      rv = IOS_ERROR_MAX;
      goto done;
    }
    if (ndp > 32) {
        ndp = 32;
        OHCI_ERR("max allowed ports per hub = 32\n");
    }
    __ohci_dev[devnum].type = OHCI_DEV_HUB;
    __ohci_dev[devnum].dev.hubp->ndp = ndp;
    /* Hubs report 1 bit per port + 1 bit for hub itself, rounded up to
     * nearest byte. Sec 11.13.4
     */
    __ohci_dev[devnum].dev.hubp->ndp_stat = (((ndp + 1)+ 7) & ~7)/8;
    OHCI_DBG("%s: ndp = %u ndp_stat = %u bytes\n", __FUNCTION__, 
            ndp, __ohci_dev[devnum].dev.hubp->ndp_stat);
    __ohci_dev[devnum].dev.hubp->potpgt = potpgt;
    memset(__ohci_dev[devnum].dev.hubp->data, 0, 4);
    rv = IOS_ERROR_OK;
done:
    return rv;
}

u8
initDevNode(ohci_hcd *hcd, u8 hub, u8 port, u8 spd)
{
    u8 devnum = 0;
    u8 k;
    struct ohci_td * td0;
    struct ohci_ed * ed0;
    u32 flags;
    u16 maxP;

    for (devnum = 1; devnum < OHCI_DEV_MAX; ++devnum) {
        if (OHCI_DEV_UNUSED == __ohci_dev[devnum].type) {
            __ohci_dev[devnum].type = OHCI_DEV_DEV;
            __ohci_dev[devnum].openid = ++hcd->openid;
            __ohci_dev[devnum].dev.port = port;
            __ohci_dev[devnum].dev.hub = hub;

            /* Initialize info for endpoint 0 */
            __ohci_dev[devnum].dev.ep0.ep =0;
            __ohci_dev[devnum].dev.ep0.ed = ed0 = allocED();
            __ohci_dev[devnum].dev.ep0.td_dummy = td0 = allocTD();
            if (NULL == ed0 || NULL == td0) {
                memset(__ohci_dev + devnum, 0, sizeof(struct ohci_device)); 
                devnum = 0;
                freeED(ed0);
                freeTD(td0);
                OHCI_ERR("initDevNode: failed to allocated ED or TD\n");
                goto done;
            }

            __ohci_dev[devnum].dev.spd = spd;
            if (OHCI_SPD_LOW == spd) { /* slow */
                __ohci_dev[devnum].dev.ep0.maxP = maxP = 8;
            } else {
                /* Initial guess. Can be 8, 16, 32, 64. 
                 * Get device descriptor and set it later.
                 */
                __ohci_dev[devnum].dev.ep0.maxP = maxP = 32;
            }
            for (k = 1; k < OHCI_DEV_MAX_EP; ++k) 
                __ohci_dev[devnum].dev.ep[k].ep = 0;
            __ohci_dev[devnum].dev.nintf = 0;


            /* Add ed0 to HCD */
            ed0->headP = ed0->tailP = CPU_TO_OHCI32((u32) td0);
            ed0->nextED = 0;
            /* Initially set address of device = 0.
             * Set to actual address after a SET_ADDRESS operation
             * is completed.
             */
            flags =  OHCI_ED_DIR_TD1
                | ((spd << OHCI_ED_SPD_SHIFT) & OHCI_ED_SPD_MASK)
                | ((maxP << OHCI_ED_MPS_SHIFT) & OHCI_ED_MPS_MASK)
                | OHCI_ED_SKIP_MASK;
            ed0->flags = CPU_TO_OHCI32(flags);
            IOS_FlushMem(IOS_WB_IOD); 
            IOS_InvalidateRdb(hcd->hc_rdb);
            enqueueCtrlED(hcd, ed0);
            goto done;
        }
    }
    /* No slots available for device */
    devnum = 0;
done:
    return devnum;
}

static void
__deleteEPInt(ohci_hcd *hcd, usb_dev_ep ep)
{
    u8 attr =  ep.attr & USB_ENDPT_ATTR_MASK;
    /* Free dummy if present */
    struct ohci_td *dummy = (struct ohci_td *)
        (OHCI_TO_CPU32(ep.ed->headP) & 0xfffffff0);
    OHCI_DBG("freeing dummy td: %p\n", dummy);
    freeTD(dummy);
    switch (attr) {
        case USB_ENDPT_ATTR_CTRL:
            dequeueED(hcd, ep.ed, OHC_CTRL_MSG);
            break;
        case USB_ENDPT_ATTR_BLK:
            dequeueED(hcd, ep.ed, OHC_BLK_MSG);
            break;
        case USB_ENDPT_ATTR_INTR:
            freeIntrED(hcd, ep.ed);
            break;
        case USB_ENDPT_ATTR_ISO:
            dequeueISOED(hcd, ep.ed);
            break;
    }
}

static void
__deleteEP(ohci_hcd *hcd, u8 devnum, u8 epNum)
{
    struct usb_dev_ep ep =  __ohci_dev[devnum].dev.ep[epNum];
    if (0 == ep.ep) {
        goto done; /* unused */
    }
    __deleteEPInt(hcd, ep);

done:
    return;
}

/* Stop ED (set skip flag)
 * Dequeue and free TD's (handle corresponding IRPs as though the
 * TD completed).
 * Leave ED ready for reuse (in case someone opens 
 * this device again). Don't reset/reenumerate.
 */

static void
__abortEPInt(ohci_hcd *hcd, struct usb_dev_ep ep)
{
    OHCI_DBG("aborting TD's for endpoint: 0x%x\n", ep.ep);
    IOS_FlushMem(hcd->hc_wb);
    IOS_InvalidateRdb(IOS_RB_IOD);
    stopED(hcd, ep.ed);
    abortTDs(hcd, ep.ed); 
    IOS_FlushMem(IOS_WB_IOD);
    IOS_InvalidateRdb(hcd->hc_rdb);
}

static void
__abortEP(ohci_hcd *hcd, u8 devnum, u8 epnum)
{
    struct usb_dev_ep ep =  __ohci_dev[devnum].dev.ep[epnum];
    if (ep.ep != 0) {
        __abortEPInt(hcd, ep);
    }
    /* ED will get restarted when the device is opened and the first
     * transfer is enqueued
     */
}

/* Endpoints are stopped and have no active transfers 
 * when this function is called.
 * Delete and free EDs + dummy TDs.
 * Free device node.
 */
static IOSResourceRequest *
__closeCleanupDevNode(ohci_hcd *hcd, u8 devnum)
{
  u8 i; 
  IOSResourceRequest *req;
  req = __ohci_dev[devnum].dev.notifyRemoval;
  for (i = 0; i < OHCI_DEV_MAX_EP; ++i) {
      __abortEP(hcd, devnum, i);
      __deleteEP(hcd, devnum, i);
  }
  __abortEPInt(hcd, __ohci_dev[devnum].dev.ep0);
  __deleteEPInt(hcd, __ohci_dev[devnum].dev.ep0);

  __ohci_dev[devnum].type = OHCI_DEV_UNUSED;
  if (NULL != __ohci_dev[devnum].dev.hubp) {
      OHCI_DBG("freeing hubp: %p\n", __ohci_dev[devnum].dev.hubp);
      IOS_Free(__ohcdHeapId, __ohci_dev[devnum].dev.hubp);
  }
  memset(&__ohci_dev[devnum], 0, sizeof(struct ohci_device));  
  return req;
}

static IOSResourceRequest *
__closeCleanupHubNode(ohci_hcd *hcd, u8 hub)
{
  u8 devnum; 
  IOSResourceRequest *resReq;
  for (devnum = 1; devnum < OHCI_DEV_MAX; ++devnum) {
      struct ohci_device dev = __ohci_dev[devnum];
      if (OHCI_DEV_UNUSED == dev.type) {
          continue;
      }
      if (hub == dev.dev.hub) {
          if (OHCI_DEV_HUB == dev.type) {
              printf("OH0: deleting hub %u connected to hub %u\n",
                      devnum, hub);
              resReq = __closeCleanupHubNode(hcd, devnum);
          } else {
              u32 p = __ohci_dev[devnum].dev.port;
              resReq = __closeCleanupDevNode(hcd, devnum);
              printf("OH0: deleted USB device (hub %u, port %u)\n",
                      hub, p);
          }
          if (NULL != resReq) {
              IOS_ResourceReply(resReq, IOS_ERROR_OK);
          }
      } 
  }
  resReq = __closeCleanupDevNode(hcd, hub);
  return resReq;
}

IOSError
delDevNode(ohci_hcd *hcd, u8 hub, u8 port)
{
    IOSError rv = IOS_ERROR_INVALID;
    u8 devnum;
    IOSResourceRequest *resReq;
    for (devnum = 1; devnum < OHCI_DEV_MAX; ++devnum) {
        struct ohci_device dev = __ohci_dev[devnum];
        if (OHCI_DEV_UNUSED == dev.type) {
            continue;
        }
        if (port == dev.dev.port && hub == dev.dev.hub) {
            if (OHCI_DEV_DEV == dev.type) {
                OHCI_DBG("Deleting device (hub %u, port %u)\n", hub, port);
                resReq = __closeCleanupDevNode(hcd, devnum);
            } else { /* hub */
                OHCI_DBG("Deleting hub %u (hub %u, port %u)\n", devnum, hub, port);
                resReq = __closeCleanupHubNode(hcd, devnum);
            }
            if (NULL != resReq) {
                rv = IOS_ResourceReply(resReq, IOS_ERROR_OK);
                OHCI_DBG("Sent device removal notification\n");
            } else {
                rv = IOS_ERROR_OK;
            }
            goto done;
        }
    }
    OHCI_DBG("%s: device (hub %u port %u) not found \n", 
            __FUNCTION__, hub, port);
done:
    return rv;
}

IOSError 
closeDevNode(ohci_hcd *hcd, u8 devnum)
{
    u8 i; 
    IOSResourceRequest *req;
    for (i = 0; i < OHCI_DEV_MAX_EP; ++i) {
        __abortEP(hcd, devnum, i);
    }
    req = __ohci_dev[devnum].dev.notifyRemoval;
    if (NULL != req) {
        OHCI_DBG("Sending removal notice on close\n");
        IOS_ResourceReply(req, IOS_ERROR_NOEXISTS);
        __ohci_dev[devnum].dev.notifyRemoval = NULL;
    }
    __ohci_dev[devnum].opened = DEV_CLOSED; 
    __ohci_dev[devnum].openid = ++hcd->openid; /* "close" device */
    return IOS_ERROR_OK;
}

/* Find at most 'size' devices of class 'class' and save the number of devices
 * found in 'num'.
 */

static void
__addDevInfo(OHCDeviceInfo *list, u8 *n, u32 i)
{
    list[*n].vid = __ohci_dev[i].dev.vid;
    list[*n].pid = __ohci_dev[i].dev.pid;
    *n = *n + 1;
}

IOSError
getDevList(OHCDeviceInfo *list, u8 size, u8 devClass, u8 *num)
{
    u32 i;

    *num = 0;
    for (i = 1; i < OHCI_DEV_MAX; ++i) { /* Exclude dev 0 (root hub) */
        if (OHCI_DEV_UNUSED == __ohci_dev[i].type) 
            continue;

        /* Check if dev descr has this class */
        if (0 == devClass || devClass == __ohci_dev[i].dev.devClass) {
            __addDevInfo(list, num, i);
            goto device_done;
        }
        /* Look in interface descrs */
        {
            struct usb_intf *intfList = __ohci_dev[i].dev.intf;
            u8 nintf = __ohci_dev[i].dev.nintf;
            u8 k;
            for (k = 0; k < nintf; ++k) { 
                if (devClass == intfList[k].devClass) {
                    __addDevInfo(list, num, i);
                    goto device_done;
                }
            }
        }
device_done:
        if (*num == size)
            break;
    }
    return IOS_ERROR_OK;
}

static s32
__getDeviceId(u8 devClass, u16 vid, u16 pid, u8 check)
{
    u8 devnum;
    s32 devid = IOS_ERROR_NOEXISTS;
    for (devnum = 1; devnum < OHCI_DEV_MAX; ++devnum) {
        if (IOS_ERROR_OK == __checkDevice(devnum, devClass, vid, pid)) {
            if (check && (DEV_OPENED == __ohci_dev[devnum].opened)) {
                OHCI_DBG("Found device vid = 0x%x pid = 0x%x already open: %u\n", vid, pid, devnum);
                devid = IOS_ERROR_EXISTS;
                continue;
            }
            devid = (devnum & DEV_OPENID_IDX_MASK) << DEV_OPENID_IDX_SHIFT
                | ((__ohci_dev[devnum].openid & 0xffffff) << DEV_OPENID_ID_SHIFT);
            goto done;
        }
    }
    /* If you get here, devid = IOS_ERROR_EXISTS if the device was found 
     * but is already opened. If the device was not found, devid will be
     * IOS_ERROR_NOEXISTS.
     */
done:
    return devid;
}

s32
getDeviceId(u8 devClass, u16 vid, u16 pid)
{
    return __getDeviceId(devClass, vid, pid, 0 /* don't check*/);
}

s32
getUnopenedDeviceId(u8 devClass, u16 vid, u16 pid)
{
    return __getDeviceId(devClass, vid, pid, 1 /* check */);
}
