USB host stack
The USB host stack turns a USB controller into a managed bus host. It finds peripherals on root-hub and external-hub ports, assigns device addresses, reads descriptors, binds supported interfaces, and exposes device and transfer events to applications.
Host stack role
The host stack converts controller reports into ordered host work. The controller boundary reports attach, removal, and transfer events. The host task then drives enumeration, device teardown, class-driver setup, transfer completion, and application callbacks. See host core lifecycle for the host-wide lifecycle model.
Applications use a device address (daddr) as the handle for an enumerated device. They use the tuh_ API to query identity and bus position, request descriptors, submit transfers, and react to mount and unmount callbacks. Class drivers turn mounted interfaces into device-specific functions through the shared contract described in shared class-driver protocols.
Host initialization
Root-hub activation
The application starts host operation with tuh_rhport_init() in src/…/usbh.h. The stack creates its event resources, loads built-in and application class drivers, starts the controller in host mode, and enables controller interrupts. tuh_init() remains a compatibility wrapper. tuh_configure() supplies controller-specific settings before initialization.
The application must call tuh_task() or tuh_task_ext() from its main loop or host task. This task dispatches queued events and runs delayed enumeration, transfer completion, and callback work. tuh_task_event_ready() supports a loop that checks for work without blocking.
References: src/…/usbh.h• L141-191 src/…/usbh.c• L549-647
Controller event boundary
The host controller driver, or HCD, is the hardware-specific side of the stack. It reports root-port and transfer changes through a common event path. The host event queue moves those reports into host-task context, so root-port changes, hub-port changes, and transfer results follow one dispatch model.
Each transfer completion identifies a device and endpoint. It also carries the transfer result and the number of bytes received or sent. The host sends the completion to an application callback when the application owns the endpoint. Otherwise it sends the event to the class driver that owns the endpoint.
References: src/…/usbh.c• L404-408 src/…/usbh.c• L747-851 src/…/usbh.c• L1588-1611
Device topology and enumeration
Root-device enumeration
When a device appears on a root-hub port, the host waits for a stable connection before it resets the port. It then detects the link speed and talks to the device at address zero. After the host assigns an address, it reads the device and configuration descriptors and selects an acceptable configuration.
The host parses the selected configuration and offers each interface to the enabled class drivers. The device becomes available to normal application code only after configuration and all accepted class interfaces complete setup.
The root-device flow moves from a port event to a mounted device through these stages:
flowchart TD
A[Root-port attach] --> B[Debounce and reset]
B --> C[Read descriptors at address zero]
C --> D[Assign device address]
D --> E[Read configuration]
E --> F[Select configuration]
F --> G[Bind supported interfaces]
G --> H[Configure class drivers]
H --> I[Mount callback]
Enumeration is serialized because the host shares control-transfer and descriptor state. A failed request can be retried before the host restarts an enumeration attempt. A disconnect ends the current attempt and invalidates work that belongs to the old device instance.
References: src/…/usbh.c• L1925-1968 src/…/usbh.c• L2103-2146 src/…/usbh.c• L2215-2443 src/…/usbh.c• L2619-2699
Interface binding and mounting
After the host selects a configuration, it offers each interface descriptor range to the class drivers. Application-provided drivers are considered before built-in drivers. This lets an application add support or replace a built-in match.
Unsupported interfaces do not stop supported interfaces from operating. When each accepted interface reports setup complete, the host marks the device mounted and calls tuh_mount_cb(daddr). Applications can then use the class API or general host API and query cached identity, speed, and bus position.
The host also normalizes endpoint values for the device link before class drivers inspect or open them. This gives drivers link-valid packet sizes when they prepare endpoint transfers.
References: src/…/usbh.c• L358-379 src/…/usbh.c• L2413-2433 src/…/usbh.c• L2473-2547 src/…/usbh.c• L2549-2581
External hub topology
An external hub is an enumerated USB device with downstream ports. After the hub is configured, the host learns its port count, powers its ports, and watches for port changes. A downstream attach or removal becomes the same host event type as a root-port change, with the hub address and port number identifying the device location.
The hub normally reports changes through its interrupt status endpoint. The host reads one changed port, clears the change, and then starts or removes the device below that port. If status polling fails repeatedly, the host reads hub or port status through control transfers so a latched change can still reach the normal attach or removal path. This recovery reports changes but does not repair the status endpoint.
The host checks that a downstream high-speed device is possible on its parent link. It also records whether a high-speed hub has one shared transaction translator or one translator per port. That information keeps split isochronous traffic within the correct shared bus window.
Removing a hub removes its downstream tree. The host closes the hub and all devices below it before it releases their state, so applications do not keep using stale topology or device addresses.
References: src/…/hub.c• L201-249 src/…/hub.c• L278-384 src/…/hub.c• L399-540 src/…/hub.c• L546-575 src/…/usbh.c• L1803-1917 src/…/usbh.c• L2154-2225
Transfer management
Control transfers
Control transfers use endpoint zero for standard requests, descriptor reads, configuration changes, interface changes, and class requests. tuh_control_xfer() accepts a tuh_xfer_t request. A non-null callback gives asynchronous behavior. A null callback gives blocking behavior.
The host runs one control transfer at a time. Asynchronous requests that arrive while the slot is busy wait in a pending queue. Failed requests can be retried. Stalled, timed-out, aborted, or disconnected requests complete with a failure result. A queued request is also rejected if its device address now refers to a new device instance.
Applications should use asynchronous control transfers from host callbacks. Blocking calls belong in application context outside the host task when a scheduler is present. The host task must remain free to process the completion event.
References: src/…/usbh.h• L36-54 src/…/usbh.h• L257-302 src/…/usbh.c• L181-225 src/…/usbh.c• L1037-1160 src/…/usbh.c• L1163-1329
Endpoint transfers
Non-control transfers use endpoints opened from the selected configuration. A caller claims an endpoint, submits a buffer with tuh_edpt_xfer(), and receives a completion callback with the result and actual byte count. The endpoint stays busy until completion or abort, so the claim prevents overlapping transfers.
The general endpoint API supports bulk and interrupt traffic. Class drivers normally own their endpoints and receive completions through the class-driver boundary. Applications can use the general API when endpoint transfers are enabled. Closing an endpoint aborts pending work before the controller endpoint closes.
References: src/…/usbh.h• L287-302 src/…/usbh.c• L1335-1383 src/…/usbh.c• L1428-1505 src/…/usbh.c• L1531-1550
Transfer results and buffers
Each completion reports a result such as success, failure, stall, timeout, or abort. actual_len reports the number of bytes transferred. The caller owns the transfer buffer and must keep it valid until completion. Controller memory rules can also require alignment or extra space for an incoming packet.
Descriptor helpers use the same control-transfer model. Applications can request device, configuration, string, and HID report descriptors after mount. The host uses the same request path during enumeration.
References: src/…/usbh.h• L36-54 src/…/usbh.h• L271-285 src/…/usbh.h• L322-421 src/…/usbh.c• L1617-1717
Application API and event model
Device lifecycle callbacks
Applications discover devices through enumeration callbacks and lifecycle callbacks. Descriptor callbacks expose device and configuration data while enumeration is in progress. tuh_mount_cb(daddr) marks a configured device ready for application use. tuh_umount_cb(daddr) marks it unavailable during removal.
The device address is the handle for general host calls. tuh_connected() means the host has a live device record. tuh_mounted() reports that configuration and class setup reached the mounted state. tuh_ready() combines mounted state with the suspension check. Applications should start class operations from the mount path and release device state from the unmount path.
The main device queries are:
tuh_vid_pid_get()for vendor and product identity.tuh_descriptor_get_device_local()for the cached device descriptor.tuh_speed_get()for link speed.tuh_bus_info_get()for root-port, parent hub, parent port, and speed.
References: src/…/usbh.h• L113-135 src/…/usbh.h• L223-255 src/…/usbh.c• L487-530 src/…/usbh.c• L1578-1585 src/…/usbh.c• L1872-1892
Event-loop scheduling
The host task owns event dispatch. It processes controller events, deferred hub attachments, delayed enumeration steps, pending control transfers, and timeout work. A hub attachment waits until the current enumeration finishes because the host shares enumeration state.
Callbacks run in host-task context. They should record state or signal other application work instead of doing long or blocking work. A callback that needs another control request should submit it asynchronously and continue from its completion callback.
tuh_task_stop() queues an ordered stop request. Work already ahead of that request is processed before the task returns. The application can then deinitialize the host from the host-task context.
References: src/…/usbh.h• L171-191 src/…/usbh.c• L854-1015
Peripheral class APIs
Class drivers connect descriptor matching to application-facing peripheral APIs. The host gives a driver interface ownership, endpoint access, configuration progress, transfer completion, and close notifications. The application uses a class API after that class reports its setup is ready.
This separation lets the host manage bus topology and transfer timing while each class manages its device protocol. Built-in and application-provided drivers use the same lifecycle contract. See shared class-driver protocols.
References: src/…/usbh_pvt.h• L26-48 src/…/usbh.c• L271-379 src/…/usbh.c• L2473-2581
Change checklist
When these files or sections are changed, remember to consider these:
- Keep controller event fields aligned with queue dispatch for root-port events, hub-port events, and transfer completions.
- Preserve mount ordering: configuration and every bound class interface must complete before
tuh_mount_cb(). - Keep root-port debounce and reset timing sufficient for speed detection and the first control request.
- Preserve serialized enumeration and deferred hub attachments when shared control-transfer state changes.
- Keep hub status recovery converting downstream changes into normal attach and removal events.
- Keep parent-link speed checks and transaction-translator mode aligned with downstream transfer scheduling.
- Normalize link-specific endpoint values before class drivers inspect or open endpoints.
- Preserve tree removal and device-instance checks when topology or teardown logic changes.
- Keep endpoint claim, busy, callback, abort, and release states consistent across application and class-driver transfers.
- Keep task-stop ordering safe until queued events and pending callbacks no longer depend on host resources.
- Keep blocking and callback-based control APIs safe for both host-task and application contexts.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
The application does not run tuh_task() | Attach, enumeration, transfer completion, and removal work stays queued | Run the task in the main loop or a dedicated host task |
| A blocking control transfer runs from a host-task callback | The host task waits for an event that it must process | Use an asynchronous request with a callback chain |
| A device disconnects while enumeration or a queued control request is active | The request fails, and the address can later identify another device | Handle failure results and stop using the address after unmount |
| A hub status poll keeps failing without fallback status reads | A downstream change can remain unseen | Keep interrupt polling and control-status recovery active |
| A hub reports a high-speed child on a non-high-speed parent link | Enumeration uses a speed the bus cannot support | Reject the child during hub-port enumeration |
| A single-transaction-translator hub is treated as per-port resources | Split isochronous traffic can overcommit the shared translator | Use the hub translator mode for scheduling |
| A full-speed bulk endpoint reports an oversized packet before normalization | A class driver can size or open a transfer from an invalid value | Normalize the configuration before driver open |
| An endpoint is submitted while busy or without a claim | The transfer is rejected or conflicts with its current owner | Claim before submit and release after completion or abort |
| No class driver accepts an interface | The device can mount without that function being usable | Enable the needed class driver or provide an application driver |
| A late completion targets a removed or changed enumeration | Setup can advance the wrong device state | Keep device-instance and current-enumeration checks active |
| Root-port enumeration fails after its retry budget | The attachment remains unavailable until a later attach | Verify port debounce, reset timing, and enumeration recovery |
Key files
| File | Why to read it |
|---|---|
| src/…/usbh.h | Defines host initialization, task control, lifecycle callbacks, device queries, and transfer APIs. |
| src/…/usbh.c | Connects controller events to enumeration, topology removal, class binding, transfers, and callbacks. |
| src/…/hcd.h | Defines the hardware-independent controller boundary for port, endpoint, and event behavior. |
| src/…/hub.c | Shows hub setup, port power, status monitoring, recovery reads, downstream events, and translator information. |
| src/…/hub.h | Defines hub status data and the operations used to manage hub ports. |
| src/…/usbh_pvt.h | Defines the private contract between the host core and class drivers. |