USB Resource Managers

Contents

  1. Introduction
  2. Overview of USB hardware
  3. Overview of USB resource managers
  4. Accessing USB resource managers
  5. Common USB files
  6. OHCI0 resource manager
  7. EHCI Resource Manager
  8. References
  9. Minimal reading list

Introduction

This document describes the implementation of USB resource managers on the IOP.

It assumes that the reader is familiar with the USB 2.0 and USB 1.1 specifications, as well as the EHCI and OHCI specifications. It also assumes the reader has access to the AHB sub-system hardware specifications. Please see the list of references for links to these documents. Also see the reading list for a minimal list of sections to read from the specifications.

This document describes details specific to our system and does not try to explain the specifications, themselves. The sections are generally arranged in the order they should be read. OHCI0 is the simpler RM. The EHCI RM is based on the OHCI0 RM. However, transfer mechanisms and so on are significantly different in EHCI.

Note on terminology

In this document, EHCI, OHCI0 and OHCI1 refer to the host-controllers. EHC, OH0 and OH1 refer to the corresponding resource managers. Ports are numbered starting at 1. Resource managers are also called RMs. When section numbers are quoted, they refer to USB and host-controller specifications listed in the references.

Overview of USB hardware

Host-controllers and ports

The Wii has an EHCI host-controller with 4 ports. 2 companion 1.1 OHCI controllers are included. Port 3 is wired to a USB 1.1 Bluetooth host-controller, BRCM2045 and ports 1, 2 are externally accessible. Port 4 is not used.

Please note that even though port 3 is wired to BRCM2045, it is controlled by a companion host-controller to EHCI. The EHCI RM needs to explicitly transfer the port to OHCI for the port to be accessible to OHCI1. See the section about port transfer in EHCI for details.

Memory access

The USB host-controllers are on the DMA AHB bus and can access buffers in DDR and Napa in normal mode. In compat mode, OHCI1 can access SRAM. Interrupts generated by the the host-controllers are received by the IOP and events are sent to the appropriate resource managers. The PPC does not normally have direct access to USB host-controllers.

Coherence

Proper flushing and invalidation must be done to maintain cache coherence between the OHCI0 RM and the OHCI0 hardware. There is a data cache in the IOP, in addition to read and write AHB caches for the IOP and OH0 blocks. Please see "AHB sub-system specification", section 1.5.

Also, as defined by the OHCI specifications, there are no hardware interlocks for the data structures operated on by the host-controller as well as the host-controller driver. Procedures to enqueue and dequeue transfer and endpoint descriptors described in the OHCI specifications must be followed, in order to avoid race conditions in the processing of queues.

Endianness

USB host-controllers are always little-endian. However, the rest of our system is big-endian. The hardware supports data-lane steering in some cases. It it important to understand how endian-ness works in the system. It is explained in the document "AHB sub-system specification", section 1.6 .

Initialization

Initialization of USB hardware (like USB PLLs) is done by the IOP kernel, when the system boots up. However, some of the chicken-bits in ACR related to USB need to be initialized after the host-controller is reset. This is handled by the USB host-controller resource managers.

Overview of USB resource managers

In the sources, you will find 3 kinds of OHCI resource managers and 1 EHCI resource manager. The 3 OHCI RMs are:

Accessing USB resource managers

The USB resource managers (OHCI1, OHCI0, EHCI) can be accessed via the standard IOP OS resource manager interface. However, a "shim layer" library is provided on the IOP as well as the PPC, in order to allow easier access to them. This API is also referred to as the "IUSB API".

The IOP version of this library is described in the "IOP USB API" document and can be found in "libusb.a" included in the IOP SDK. The PPC version is described in the "PPC USB API" document and can be found in "usb.a" or "usbD.a" in the PPC SDK.

USB common files

USB public headers

IOP USB API library

OHCI0 Resource Manager

Features supported

Internals of the OHCI0 resource manager

This section describes some of the internals of the OHCI0 resource manager. A description of the individual files can be found in a later section.

Data structures

This section describes some of the data structures used by the OHCI0 RM. All sections referenced are from the OHCI specifications.

Operational registers structure

Host-controller operational registers [Section 7.1].
 
            typedef struct ohci_opregs { 
                    u32 rev;                 /* HcRevision           */
                    u32 ctrl;                /* HcControl            */
                    u32 cmd_stat;            /* HcCommandStatus      */
                    u32 int_stat;            /* HcInterruptStatus    */
                    u32 int_en;              /* HcInterruptEnable    */
                    u32 int_dis;             /* HcInterruptDisable   */
                    u32 hcca;                /* HcHCCA               */
                    u32 prd_curr;            /* HcPeriodCurrentED    */
                    u32 ctrl_head;           /* HcControlHeadED      */
                    u32 ctrl_curr;           /* HcControlCurrentED   */
                    u32 blk_head;            /* HcBulkHeadED         */
                    u32 blk_curr;            /* HcBulkCurrentED      */
                    u32 done_head;           /* HcDoneHead           */
                    u32 frm_int;             /* HcFmInterval         */
                    u32 frm_rem;             /* HcFmRemaining        */
                    u32 frm_num;             /* HcFmNumber           */
                    u32 prd_start;           /* HcPeriodicStart      */
                    u32 ls_thres;            /* HcLSThreshold        */
                    u32 rhub_desca;          /* HcRhDescriptorA      */
                    u32 rhub_descb;          /* HcRhDescriptorB      */
                    u32 rhub_stat;           /* HcRhStatus           */
                    u32 rhub_pstat[USB_RHUB_PORT_MAX];  /* HcRhPortStatus    */
            } ohci_opregs __attribute__((aligned(32)));
         

HCCA structure

Host-controller communications area [Section 4.4].
            #define OHCI_HCCA_ALIGN    256
            typedef struct ohci_hcca {
                    u32 inttbl[OHCI_HCCA_NINT];
                    u32 frmnum; /* includes 2 byte pad */
                    u32 donehead; 
                    u8 hcrsvd[116]; /* reserved for HC */
                    u8 pad[4]; /* undefined bytes in spec */
            } ohci_hcca __attribute__((aligned(OHCI_HCCA_ALIGN)));
        

Transfer and endpoint descriptors

The following transfer descriptors and endpoint descriptors are defined. Elements for the RM's internal use are noted. [Section 4]
            #define OHCI_ED_ALIGN 16
            typedef struct ohci_ed {
                    u32 flags;  
                    u32 tailP;
                    u32 headP;
                    u32 nextED;
            }  ohci_ed __attribute__((aligned(OHCI_ED_ALIGN)));

            #define OHCI_TD_ALIGN 32   /* at least 16 for general td, 32 for itd */
            typedef struct ohci_td {
                    u32 flags;      /* Transfer flags */
                    u32 cbp;        /* Current buffer pointer or bp0*/
                    u32 nextTD;     /* Next TD */
                    u32 be;         /* Buffer end */
                    u32 psw[4];     /* Packet status word for iTD only */

                    /* Stuff for HCD's use */
                    OHCIrp *irp;  /* IRP containing this transfer */
                    u16 len;      /* Transfer length */
            } ohci_td __attribute((aligned(OHCI_TD_ALIGN)));

        

Host-controller structure

             typedef struct ohci_hcd {
                   struct ohci_opregs *opregs; /* Operational registers in IO space */
                   struct ohci_hcca *hcca;     /*  Memory shared with HC (sec ) */

                   /* For HCD use */
                   u32 frm_int;                /* Save frame interval */
                   ohci_ed *intr_list;         /* Interrupt endpoint list */

                   IOSTimerId tmr;             /* Timer used by main thread */
                   IOSTimerId tmrEv;           /* Timer used by event thread */
                   IOSMessageQueueId qid;      /* QueueId used by main thread */
                   IOSMessageQueueId qidEv;    /* QueueId used by event thread */
                   IOSMessageQueueId rm_qid;   /* QueueId used for RM loop */
                   IOSMessage mq[1];           /* Queue used by main thread */
                   IOSMessage mqEv[1];         /* Queue used by event thread */
                   IOSEvent event;             /* Constant: IOS_EVENT_OH0 for OHCI0 RM */
                   u8 ndp;                     /* Number of downstream ports for root-hub */
                   u32 flags;                  /* HCD initialization flag */
                   u32 openid;                 /* Used to assign device numbers */
                   OHCCtrlReq *req;            /* Used for internal control requests */
                   IOSThreadId rmId;           /* Main thread id */
                   u8 rwc;                     /* Save remote wakeup connected bit */
                   u8 hc_rdb;                  /* Constant: IOS_RB_OHCI0 for OHCI0 RM */
                   u8 hc_wb;                   /* Constant: IOS_WB_OHCI0 for OHCI0 RM */
                   u32 load_ns;                /* Periodic transfer load */
            } ohci_hcd;

Device nodes

Each inserted device or hub is allocated a device node. The following structures describe device and hub nodes.
            typedef struct usb_hub {
                    u8 devnum;        /* Index into device nodes list */
                    u8 ndp;           /* Number of downstream ports */
                    u8 ndp_stat;      /* Status */
                    u8 potpgt;        /*  Power-up to power-good time */
                    u8 data[4] __attribute__((aligned(32))); /* Status data */
            } usb_hub;

            typedef struct usb_dev {
                    u8 hub;           /* Hub for current device */
                    u8 port;          /* Port for current device */
                    u16 spd;          /* High, full or low speed */
                    u8 maxPower;      /* Max power */
                    u16 vid;          /* Vendor id */
                    u16 pid;          /* Product id */
                    u8 devClass;      /* Device class */
                    u8 subClass;      /* Device subclass */
                    u8 protocol;      /* Protocol */
                    u8 nintf;         /* Number of interfaces */
                    IOSResourceRequest *notifyRemoval;  /* Notify removal request */
                    usb_intf intf[OHCI_DEV_MAX_INTF];   /* Interface data */
                    struct usb_dev_ep ep0;      /* Device endpoint 0 */
                    struct usb_dev_ep ep[OHCI_DEV_MAX_EP]; /* Other device endpoints */
                    struct usb_hub *hubp;  /* Hub node used for hubs */
            } usb_dev;

            typedef struct ohci_device {
                  u8 type;               /* Device or hub */
                  struct usb_dev dev;    /* usb device structure */
                  u32 openid;            /* Id for repeated open/close */
                  u32 opened;            /* Device currently opened? */
            } ohci_device;

OHCI error codes

Error codes are defined based on error flags set for TDs by the host-controller.
            #define OHCI_CC_ERROR_SHIFT 28
            #define OHCI_CC_NOERROR    0x00000000  /* No error            */
            #define OHCI_CC_CRC        0x10000000  /* CRC                 */
            #define OHCI_CC_BITSTUFF   0x20000000  /* Bitstuffing         */
            #define OHCI_CC_DTMISMATCH 0x30000000  /* DataToggleMismatch  */
            #define OHCI_CC_STALL      0x40000000  /* Stall               */
            #define OHCI_CC_DEVNOTRESP 0x50000000  /* DeviceNotResponding */
            #define OHCI_CC_PIDCHK     0x60000000  /* PidCheckFailure     */
            #define OHCI_CC_PID        0x70000000  /* UnexpectedPid       */
            #define OHCI_CC_DOVERRUN   0x80000000  /* DataOverrun         */
            #define OHCI_CC_DUNDERRUN  0x90000000  /* DataUnderrun        */
            #define IUSB_CC_ERR(X)   (-(7000 + (X >>OHCI_CC_ERROR_SHIFT)))
            #define IUSB_ERROR_CRC          IUSB_CC_ERR(OHCI_CC_CRC)
            #define IUSB_ERROR_BITSTUFF     IUSB_CC_ERR(OHCI_CC_BITSTUFF)
            #define IUSB_ERROR_DTMISMATCH   IUSB_CC_ERR(OHCI_CC_DTMISMATCH)
            #define IUSB_ERROR_STALL        IUSB_CC_ERR(OHCI_CC_STALL)
            #define IUSB_ERROR_DEVNOTRESP   IUSB_CC_ERR(OHCI_CC_DEVNOTRESP)
            #define IUSB_ERROR_PIDCHK       IUSB_CC_ERR(OHCI_CC_PICCHK)
            #define IUSB_ERROR_PID          IUSB_CC_ERR(OHCI_CC_PID)
            #define IUSB_ERROR_DOVERRUN     IUSB_CC_ERR(OHCI_CC_DOVERRUN)
            #define IUSB_ERROR_DUNDERRUN    IUSB_CC_ERR(OHCI_CC_DUNDERRUN)
            #define IUSB_ERROR_CC_ABORT     IUSB_CC_ERR(OHCI_CC_ABORT)
            #define IUSB_ERROR_BOVERRUN     IUSB_CC_ERR(OHCI_CC_BOVERRUN)
            #define IUSB_ERROR_BUNDERRUN    IUSB_CC_ERR(OHCI_CC_BUNDERRUN)
            #define IUSB_ERROR_NOTACCESSED  IUSB_CC_ERR(OHCI_CC_NOTACC)
            #define IUSB_ERROR_NOTACCESSED2 IUSB_CC_ERR(OHCI_CC_NOTACC2)
            #define IUSB_ERROR_CTRL_XFER    -7021
            #define IUSB_ERROR_CANCELLED    -7022

            #define IUSB_ERROR_TIMEOUT      -7023
            #define IUSB_TIMEOUT_MESSAGE    0xdeadbeef

Operational model

It is assumed that root-hub ports with low and full speed devices are transferred to OH0. Port routing is transparent to the OH0 and is entirely handled by the EHC (and the EHCI hardware). Ports with low and full speed devices are handed over to OH0 and when the devices are disconnected, they revert to being under the control of EHC.

Threads and priorities

The OHCI0 RM has 2 threads
  1. Resource manager thread
  2. Event thread

The resource manager thread starts as the main thread at priority IOS_PRIORITY_OH0 (72). After the host-controller is initialized, the event thread is started at priority IOS_PRIORITY_OH0 and the main thread lowers its own priority to (IOS_PRIORITY_OH0 - 1) and becomes the resource manager thread.

The main thread initializes the RM and the host-controller hardware. As the resource manager thread, it handles user requests for transfers, etc.

The event handler thread handles the event, IOS_EVENT_OH0.

Memory

The OHCI0 resource manager is allocated space in the secure region of DDR. It allocates TDs, EDs and other data structures for its internal use from a heap of size 16KB. OHCI restricts data transfers per TD to 8K. This means depending upon connected devices, on-going transfers, etc the maximum buffer that can be transferred per user request is constrained. In practice, this is found to be about 1M per request. Larger transfers can be accomplished by breaking up the request into smaller chunks.

The OHCI0 RM has separate memory regions allocated for the HCCA (1K) and interrupt ED space (4K).

Initialization

When the IOP OS starts, it loads and runs the OHCI0 RM. As described above, the resource manager thread is started first. The following initialization steps are performed The event handler thread handles interrupts from

Device enumeration

The device enumeration process is described in Chapter 9 of the USB specifications. When the root-hub is initialized, any connected devices are enumerated. Devices are also enumerated, when the event-handler thread receives an event corresponding to a root-hub status change and informs the resource manager thread about it. If the device enumerated is a hub, all devices connected to the hub are also enumerated.

Certain pathological devices randomly fail to respond to requests during enumeration. It was found that retrying a few times always works. So we make up to 3 attempts to enumerate any attached device.

Enumerated devices are assigned an address as required. However, this device address is not exposed to users directly. Users specify devices via a handle obtained by using the IOS_Open call.

Resource manager

List of commands

The resource manager loop handles The following is a list of commands handled by the main resource manager loop The following IOCTLs are supported The following IOCTLVs are supported

Notes

  1. Device handles

    The value returned to IOS_Open() for a specific device, (VID, PID), is a combination of the index of the device node in the device node list, __ohci_dev in bits [7:0] and openid, which assigns a unique identifier for the current instance of this device in bits [31:8]. IOP OS maintains the mapping between handles assigned by resource managers and the actual file-descriptors returned to the callers of IOS_Open.

    Opening the host-controller driver /dev/usb/oh0 returns the reserved handle OHC_RSVD_HANDLE.

  2. Suspending and resuming devices

    These commands are used to resume or suspend devices. For devices connected to the root hub, SUSPEND or RESUME signalling is sent over the bus by appropriate settings of root-hub registers. For devices connected to via a hub, a PORT_SUSPEND set or clear feature request is send to the appropriate port of the hub to suspend or resume the device.
  3. Device insertion and removal notification

    Requests for device insertion are maintained in a separate list, __ohci_dev_notify. Multiple insertion notification requests may exist for a given VID, PID pair.
    Device removal requests are noted in the appropriate device node in the device list, __ohci_dev. Exactly one removal notification request is enqueued for an inserted device.
    When OHC_NOTIFYINSERT_ID_MSG request is received, a random id is returned to the caller, which can be used to cancel the request later.
  4. Low and full speed transfers

    Transfers are always handled in an asynchronous manner. The RM thread handles transfer requests by enqueueing transfer descriptors to the appropriate endpoints. The event handler thread processes transfer completions and sends replies to the original caller. The OHCIrp structure is used to record information used to process transfers. For example, it is used to record the number of TDs in the request and the IOSResourceRequest structure used to send a reply to the caller.

    Control transfers are used internally by the OHCI0 RM in device enumeration and to control hubs. The OHCI0 RM uses interrupt transfers to detect changes in hub status. An internal message queue is used by the RM thread to get completion replies from the event handler thread.

    The endpoints in the interrupt transfer tree are allocated statically and enqueued into a tree structure as specified by the OHCI specifications. Control, bulk and isochronous endpoints are allocated and enqueued, when they are found in connected devices.

    OHCI imposes constraints on the size and number of packets per isochronous transfer. Please see Chapter 4 of the OHCI specifications for information about the handling of data buffers in isochronous transfers.

  5. Multiple identical devices

    When multiple devices with identical vendor and product ids are present, each IOS_Open returns a file descriptor to a different instance of the device. From then on, the file descriptor is used to communicate with the particular device. For this to work, the OHCI0 RM allows each device to be opened exactly once. There is currently no support to "clone" file descriptors. Also, APIs which list currently connected devices will show multiple instances of the same vendor and product ids, if multiple identical devices are present.
  6. Closing and resetting devices

    When a device is closed, all pending transfers are aborted. There is a separate API to reset devices. If a device is reset, all pending transfers are aborted. The device is reset and re-enumerated. All open file descriptors are now invalid. However, the user should close open file descriptors, to inform IOS to close them inside the OS.
  7. Device insertion and removal

    When a device is inserted, it is enumerated and can be opened using IOS_Open. When a device is removed, all pending transfers are cancelled. Any open file descriptors to the device are no longer valid. Attempts to use an open descriptor to the device will generate IOS_ERROR_INVALID.

OHCI RM files

Resource manager headers

Resource manager sources

EHCI Resource Manager

Features supported

Internals of the EHCI resource manager

The EHCI RM is based on the OHCI0 RM. However, the EHCI host-controller is based on UHCI (another implementation of hardware for USB 1.1). Hence transfer mechanisms and related data structures in the EHCI RM are substantially different from OHCI. EHCI also needs to handle the case, when USB 1.1 devices are connected to USB 2.0 hubs. A special mechanism, "split transactions", is used to support this case. It is useful to read the sections about OHCI0 before reading this section. A description of the individual files can be found in a later section.

Data structures

Capability registers structure

EHCI capability registers [Section 2.2, Table 2-5].
            typedef struct ehci_capregs { 
                    u8 caplength;   /* Capability register length */
                    u8 rsvd;        /* Reserved */
                    u16 hciversion; /* Interface version number */
                    u32 hcsparams;  /* Structural parameters */
                    u32 hccparams;  /* Capability parameters */
                    u32 hcsp;       /* Companion port route description */
            } ehci_capregs __attribute__((aligned(32)));

Operational registers structure

Host-controller operational registers [Section 2.3].
            typedef struct ehci_opregs { 
                    u32 usbcmd;      /* Command */
                    u32 usbsts;      /* Status */
                    u32 usbintr;     /* Interrupt enable */
                    u32 fridx;       /* Frame index */
                    u32 ctrldss;     /* 4G segment */
                    u32 plbase;      /* Frame list base */
                    u32 aladdr;      /* Async list address */
                    u32 rsvd[9];     /* Reserved */
                    u32 cfgflg;      /* Configured flag */
                    u32 portsc[4];   /* Port status/control*/
            } ehci_opregs __attribute__((aligned(32)));

Queue transfer descriptors

Basic data structure used to specify transfers [Section 3.5].
            #define EHC_QTD_ALIGN 32
            typedef struct ehci_qtd {
                u32 nextQTD;
                u32 altNextQTD;
                u32 token;
                u32 buf[5];
               /* Stuff for HCD's use */
                EHCIrp *irp;
                u32 len;
             } ehci_qtd __attribute__((aligned(EHC_QTD_ALIGN)));

Queue heads

Queue heads used for control, bulk and interrupt transfers. [ Section 3.6].
            #define EHC_QH_ALIGN 32
            typedef struct ehci_qh {
                u32 qhlp;
                u32 ecap1;
                u32 ecap2;
                u32 qtd;
                /* xfer overlay */
                u32 nextQTD;
                u32 altNextQTD;
                u32 token;
                u32 buf0;
                u32 buf1;
                u32 buf2;
                u32 buf3;
                u32 buf4;
                /* HCD use only */
                u32 ep; /* devEp pointer */
            } ehci_qh __attribute__((aligned(EHC_QH_ALIGN)));

Isochronous queue transfer descriptors

Queue transfer descriptors used for isochronous transfers [ Section 3.3].
            #define EHC_ITD_ALIGN 32
            typedef struct ehci_itd {
                u32 next;
                u32 stat[8];
                u32 buf[7];

                /* Stuff for HCD's use */
                EHCIrp *irp;
                u32 len;
                u32 ep;
            }  ehci_itd __attribute__((aligned(EHC_ITD_ALIGN)));

Split isochronous queue transfer descriptors

Queue transfer descriptors used for split isochronous transfer [ Section 3.4].
            #define EHC_SITD_ALIGN 32
            typedef struct ehci_sitd {
                u32 next;
                u32 ecap;
                u32 sched;
                u32 stat;
                u32 buf0;
                u32 buf1;
                u32 back;
                /* Stuff for HCD's use */
                EHCIrp *irp;
                u32 len;
                u32 ep;
            } ehci_sitd __attribute__((aligned(EHC_SITD_ALIGN)));

Host-controller structure

Contains pointers to host-controller registers and other data structures.
             typedef struct ehci_hcd {
                 ehci_opregs *opregs;  /* Operational registers in IO space */
                 ehci_capregs *capregs; /* Capability registers */
                 u32 *pflist;          /* Periodic frame list */

                 /* For HCD use */
                 u32 frm_int; /* need to save frame interval */

                 IOSTimerId tmr;
                 IOSTimerId tmrEv;
                 IOSMessageQueueId qid;
                 IOSMessageQueueId qidEv;
                 IOSMessageQueueId rm_qid;
                 IOSMessage mq[1];
                 IOSMessage mqEv[1];
                 IOSEvent event;
                 u8 ndp;
                 u8 ncc;
                 u32 flags;
                 u8 hc_rdb;
                 u8 hc_wb;
                 IOSThreadId rmId;
                 u32 loadns;
                 u32 openid;
                 EHCCtrlReq *req;
                 IRPList irp;
                 u32 asyncH;
                 DBList db;
                 u32 split_us; /* periodic split txn us allocated */
            } ehci_hcd;

Device nodes

Each inserted device or hub is allocated a device node. The following structures describe device and hub nodes.
            typedef struct usb20_hub {
                 u8 devnum;
                 u8 ndp;
                 u8 ndp_stat;
                 u8 potpgt;
                 u8 data[4] __attribute__((aligned(32)));
            } usb20_hub;

            typedef struct usb20_dev {
                 u8 hub;
                 u8 port;
                 u16 spd;
                 u8 maxPower;
                 u16 vid;
                 u16 pid;
                 u8 devClass;
                 u8 subClass;
                 u8 protocol;
                 u8 nintf;
                 IOSResourceRequest *notifyRemoval;
                 usb_intf intf[EHCI_DEV_MAX_INTF];
                 /* XXX Assumes 1 configuration for now */
                 usb20_dev_ep ep[EHCI_DEV_MAX_EP]; 
                 struct usb20_hub *hubp; 
            } usb20_dev;
            
            typedef struct ehci_device {
                 u8 type;
                 usb20_dev dev;
                 u32 openid; 
                 u32 opened;
            } ehci_device;

IO Request Packets (IRPs)

An IO request packet (IRP) is a structure used to specify and track transfer requests. Unlike OHCI, completed transfer requests (descriptors) are not dequeued by hardware in EHCI. Only the completion flag is set and the RM is expected to track completions.
            typedef struct EHCIrp {
                IOSResourceRequest *req;
                s8 ntd;              /* Number of TDs in this request */
                u8 err;              /* Number of TDs which reported errors */
                s32 done;            /* Bytes transferred */
                void *data;          /* Data to be read or written */
                u32 datalen;         /* Size of transferred data */
                struct ehci_qh *qh;     
                struct EHCIrp *nxt;
                struct ehci_qtd *qtd;
                struct ehci_itd *itd;
                struct ehci_sitd **sitd;
                IOSMessageQueueId qid; /* for internal use only */
                EHCCtrlReq *clean1;
                u16 *size;           /* isoc packet sizes */
                u8 numPkts;          /* number of isoc packets */
                u8 devnum;           /* Destination device number */
            } EHCIrp;

EHCI error codes

Error codes are defined based on error flags set for QTDs by the host-controller.
        #define IUSB_ERROR_NOERROR       0
        #define IUSB_ERROR_DBUFFER   -7100  /* Data buffer error */
        #define IUSB_ERROR_BABBLE    -7101  /* Babble detected */
        #define IUSB_ERROR_HALT      -7102  /* Endpoint halted */
        #define IUSB_ERROR_DEVERR    -7103  /* Transaction error. Invalid
                                             * response from device - CRC,
                                             * timeout, bad PID, etc.
                                             */
        #define IUSB_ERROR_TT_ERR    -7104  /* Transaction translator error */
        #define IUSB_ERROR_XACT_ERR  -7105  /* XactErr */
        #define IUSB_ERROR_MUF_ERR   -7106  /* Missed uframe */
        #define IUSB_ERROR_CTRL_XFER -7021
        #define IUSB_ERROR_CANCELLED -7022
        #define IUSB_ERROR_SCHED     -7024  /* EHCI scheduling error */

Operational model

The EHCI RM handles root-hub ports with high-speed devices and high-speed hubs. Root-hub ports, which have low or full speed devices are handed off to the companion host-controllers (USB 1.1). This process is called "port routing" and is described below.

Threads and priorities

The EHCI RM has 2 threads
  1. Resource manager thread
  2. Event thread

The resource manager thread starts as the main thread at priority IOS_PRIORITY_EHC (97). As described in a section, after port transfer, the priority is lowered to IOS_PRIORITY_EHC_RUN (73). After the host-controller is initialized, the event thread is started at priority IOS_PRIORITY_EHC_RUN and the main thread lowers its own priority to (IOS_PRIORITY_EHC_RUN - 1) and becomes the resource manager thread.

The main thread initializes the RM and the host-controller hardware. As the resource manager thread, it handles user requests for transfers, etc.

The event handler thread handles the event, IOS_EVENT_EHC.

Port routing and control

The basic structure of the ports was described in an earlier section. When the EHCI host-controller is not initialized, all ports are owned by the companion host-controllers. When the EHCI host controller is reset and initialized, it comes up owning all the ports in the system. It then looks at the devices connected to the root-hub ports and hands off low and full speed devices to the companion host controllers. The procedure for port-handoff is described in section 4.2. In particular, port 3 is always handed off to OHCI1.

The handling of port routing in our system is somewhat complicated. OH0 needs to run at a higher priority that EHCI or OH1 RMs, in order for the wiimote to be responsive. However, OH0 cannot be started before EHC, because EHC needs to hand off port 3 to OH0. If the OH1 RM were running and handling the wired Bluetooth device, initializing EHC would cause the device to be disconnected from OH1 and reconnected. However, OH1 and the Bluetooth software do not handle hotplug.

The EHCI RM is started by the IOP OS at priority IOS_PRIORITY_EHC, which is higher than the priority of the OHCI RMs. It transfers port 3 to OH1 and lowers its priority to IOS_PRIORITY_EHC_RUN. At this point, OH1 gets to run. Later, when EHC runs again, it transfers any low and full speed devices connected to port 1 or port 2 to OH0. Port 4 is not accessible and cannot be used.

Memory

The EHCI resource manager is allocated space in the secure region of DDR. It allocates QTDs, QHs and other data structures for its internal use from a heap of size 32KB. It uses the IOS API to allocate aligned blocks of memory from this heap. Note that unlike in OHCI0, interrupt QHs are allocated from the same heap.

Resource manager

List of commands

The resource manager loop handles The structure of the above is the same as that of OHCI0. The following is a list of commands handled by the main resource manager loop. Note that the definitions for the constants are the same as the corresponding number of OHCI. This allows us to use a common shim layer library. Please preserve this feature for simplicity. The following IOCTLs are supported The following IOCTLVs are supported

Mechanisms in EHCI similar to those in OHCI0

Mechanisms for the following are similar to those used in OHCI0:

Notes

  1. High-speed transfers

    Transfers are handled in an asynchronous manner, as described for OHCI0. However, the OHCI hardware dequeues completed TDs and enqueues them into the done queue. In EHCI, a flag is set in the QTD to indicate completion. But the QTD is enqueued into a done queue. When a completion interrupt occurs, we go through the IRP list and process completed or failed transfers. Completed QTDs are dequeued and completed transfers are processed by sending status messages to the callers.

    As in OHCI0, internal blocking control transfers are used to enumerate devices and control hubs. Internal non-blocking interrupt transfers are used to detect changes in hub status.

    EHCI uses a frame list size of 1024. Interrupt QHs are allocated, enqueued and dequeued dynamically in the EHCI RM.

  2. Split transfers

    If USB 1.1 devices are connected to the root-hub, they are transferred to the companion host controllers as described above. However, if USB 1.1 devices are connected to 2.0 hubs, low/full speed transfers need to be handled by EHCI. This is done using a special mechanism called "split transfers" [Section 4.12]. When devices are enumerated and endpoints are enqueued, QHs which need split transfers (low and full speed endpoints) have flags set appropriately. Split isochronous transfers need special handling. Isochronous transfers have no queue heads. Split isochronous QTDs, need to be allocated and enqueued.
  3. Large bulk transfers

    For high-speed transfers, each QTD can handle transfers of upto 20K. If the user request buffer is bigger than 20K, the request is decomposed into multiple QTDs. Since the number of QTDs that can be allocated is limited, the maximum buffer size per transfer is about 4M and depends on what other requests and events are being processes by the EHCI RM. Performance measurements with flash drives and USB hard-drives show that the numbers are in line with expected transfer rates.

Files for the EHCI RM

Resource manager headers

Resource manager sources

References

  1. USB 2.0 specification [local copy]
  2. Errata for USB 2.0 specification[local copy]
  3. USB 1.1 specification [local copy]
  4. EHCI specifications[local copy]
  5. OHCI specifications [local copy]
  6. UHCI specifications[local copy]
  7. Device class documents
  8. USB Language ID codes [local copy]
  9. AHB sub-system specification [ATI (AMD) document]

Minimal reading list

Minimal reading list for background (need more information for actual implementation):

Notation:
"section x.y (main section)" means read the main description for section x.y. Subsections are indicated separately.

USB 1.1 specification

OHCI specification

USB 2.0 specification

EHCI specification