Introducing a new way to review your PRs.

Read the announcement

hathach / tinyusb

An open source cross-platform USB stack for embedded system

View on GitHub

18 documents · Updated Nov 23, 2026

docs / usb-host-core

Host core lifecycle

The host core is the control center for USB host operation. It connects a host-controller driver to device discovery, descriptor reading, hub changes, data transfers, and callbacks for the rest of the host stack. It gives class drivers a stable view of devices while it manages bus timing, device state, and event order. See the host stack and class drivers pages for the surrounding layers.

Host-controller boundary

The host core uses a host-controller driver (HCD) to turn common host actions into controller operations. The HCD reports attach, removal, and transfer completion events to the core. The core then places those events into its host task path so that device and class state changes happen in one managed flow.

Controller lifecycle

The application starts a root-hub port (rhport) in host mode before it runs the host task. The host core initializes shared state and class drivers, starts the HCD, and enables controller interrupts. Deinitialization disables the controller, removes devices on the port, and completes queued asynchronous control requests as failed so callers do not wait forever. The host task can also receive a queued stop request so the application can leave its task loop before deinitialization.

References: src/…/usbh.h• L141-188 src/…/usbh.c• L544-705 src/…/usbh.c• L988-1011 src/…/hcd.h• L91-109

Controller contract

The HCD owns controller-specific port and endpoint work. The host core expects it to provide port status and reset actions, endpoint open and close actions, transfer submission, transfer abort, and event reporting. This boundary lets the same host lifecycle serve different controller hardware.

References: src/…/hcd.h• L114-163 src/…/usbh.c• L1397-1459 src/…/usbh.c• L1501-1542

Device lifecycle

An attached device moves from a physical connection to a configured device that class drivers can use. A removal can happen at any point in that path, so the host core treats device state and pending work as disposable and closes the affected device tree.

Attachment sequence

The attachment path debounces the connection, resets the device, finds its link speed, and assigns a device address. It then reads the descriptors needed to identify the device and its interfaces. The device becomes visible through the mount callback only after the selected configuration is set and every matching class driver finishes its setup. A failed root-port attachment can be retried while the port still reports a connection.

The sequence is serialized because enumeration uses shared control-transfer state and a shared enumeration buffer. A hub attachment waits until the current device reaches a final success or failure state. Failed control requests can restart enumeration up to the configured attempt limit while the connection remains valid. Root-port enumeration also has a separate retry budget for an attachment that fails after the port still reports a device.

An attach event first removes any device at the same physical location. This also handles repeated attach reports or a reset that lacks a separate remove event. The new attachment then enters the normal enumeration path.

This diagram shows how a connection becomes a configured device.

flowchart TD
    A[Attach event] --> B[Debounce connection]
    B --> C[Reset port]
    C --> D[Read device descriptor]
    D --> E[Assign device address]
    E --> F[Read configuration descriptors]
    F --> G[Select configuration]
    G --> H[Bind class drivers]
    H --> I[Mount callback]
    I -. failed root attach .-> C

References: src/…/usbh.c• L743-769 src/…/usbh.c• L1920-2058 src/…/usbh.c• L2099-2143 src/…/usbh.c• L2600-2672

Removal sequence

The host core matches a removal to a physical location: an rhport and, when a hub is involved, a hub address and port. It marks the full affected branch as removing before it calls callbacks. This makes the branch appear disconnected during teardown. It sends the unmount callback only for a device that previously completed mounting. It then closes class drivers before it releases controller resources. If the removed device is a hub, the same process also closes all devices below that hub.

An attach at an already occupied location first tears down the old device. This handles repeated attach reports or a reset that lacks a separate remove event. Removal also ends enumeration and any active control transfer for the device. A device-address generation value marks queued control work from the old device, which prevents that work from being sent to a new device that later receives the same address. If an attachment ends before the normal enumeration completion path, its root-port retry state is returned to the next attachment.

References: src/…/usbh.c• L449-477 src/…/usbh.c• L743-765 src/…/usbh.c• L1798-1912 src/…/usbh.c• L2600-2612

Descriptor enumeration

Enumeration uses standard control requests to learn the device identity and the interfaces it offers. The host core keeps a small device record with bus location, speed, address state, cached device identity, and interface-to-driver bindings. Class drivers use the configuration descriptor to decide which interfaces they can support.

Descriptor sequence

The core first reads enough of the device descriptor to learn the control endpoint packet size. After it assigns an address, it reads the full device descriptor, optional string descriptors, and the configuration descriptor. It reads the configuration header first so it can request the full descriptor without guessing its size.

The application can inspect the device and configuration descriptors during this path. It can also reject a configuration so the core can try the next one when the device reports more than one configuration. The public descriptor APIs also let applications request device, configuration, string, and HID report descriptors after discovery.

References: src/…/usbh.h• L116-123 src/…/usbh.h• L226-255 src/…/usbh.h• L271-360 src/…/usbh.c• L1612-1712 src/…/usbh.c• L2222-2405

Interface binding

After configuration selection, the core walks the configuration descriptor and offers each interface to the available class drivers. A driver claims the interface and its related endpoints when it recognizes the descriptor. The core records those bindings so later transfer completions reach the right driver.

The core marks a device configured when the device accepts its configuration. If the device stalls the configuration request, the core treats it as an incomplete configuration and starts a fresh enumeration attempt instead of exposing a half-configured device. After all interfaces complete, it marks the device as mounted and calls the mount callback for a non-hub device. A completion that arrives after the mount callback removes the device is ignored, so it cannot continue setup for a removed device or a later device that reuses the same address. The public mounted query reports the configured state, while the separate internal mounted state controls whether removal sends an unmount callback.

References: src/…/usbh_pvt.h• L26-48 src/…/usbh.c• L122-144 src/…/usbh.c• L482-495 src/…/usbh.c• L2136-2143 src/…/usbh.c• L2408-2494 src/…/usbh.c• L2544-2575

Hub topology

A hub adds a second level of USB connection points below the root hub. The host core records each device with its rhport, parent hub address, and parent hub port. This location data allows the core to enumerate a downstream device and later remove the whole branch when its hub disappears.

Downstream attachment

The hub class driver watches its interrupt status endpoint for changes. For a changed port, it reads the port status, clears the change flag, and emits the same attach or remove event used for a root-hub port. The host core then runs the normal device lifecycle with the hub address and port as the connection location. If status polling fails several times, the hub class driver reads hub and port status through control transfers so a latched change can still reach the host core.

The hub is configured before it reports downstream devices. Its setup reads hub information, powers its ports, and starts status polling. A multi-transaction-translator hub uses its multi-TT mode when the device accepts it; otherwise the host schedules it conservatively as a single-TT hub. A downstream enumeration resets the hub port and checks the port status before it continues with the device at address zero. If a port-power request fails, setup continues with the other ports; the affected port may still be powered by a ganged or non-switching hub.

References: src/…/hub.c• L195-239 src/…/hub.c• L274-384 src/…/hub.c• L389-529 src/…/hub.c• L536-566 src/…/usbh.c• L2150-2220

Topology removal

The core removes devices by location rather than only by device address. When it closes a hub, it marks that hub and then walks its downstream locations. This preserves the parent-child relationship during cleanup and prevents child devices from remaining mounted after their upstream path is gone.

References: src/…/usbh.c• L1820-1912 src/…/usbh.c• L2329-2349

Transfer scheduling

The host core presents control transfers and non-control endpoint transfers through common host APIs. It tracks endpoint ownership and busy state so a class driver or application does not submit two transfers to the same endpoint at once. The HCD performs the actual bus transaction and reports the result back to the host task.

Control transfer scheduling

The core allows one control transfer to use the shared control path at a time. Synchronous callers wait for its result. Asynchronous callers use a pending queue when the control path is busy. A completed, aborted, disconnected, or timed-out transfer frees the path before its callback runs, so a callback can submit the next control request.

Control requests move through setup, optional data, and acknowledgement stages. Failed requests can be retried while the device remains connected. A watchdog turns a request that does not complete before its deadline into a timeout. The event loop gives a completion already queued priority over a synthesized timeout, while sustained event traffic still lets the watchdog act. A disconnect or a stale device address ends the request with a failure result instead of sending it to a later device.

On systems with a scheduler, a host-task callback must use the asynchronous form instead of blocking on the same task. This prevents a callback from waiting for an event that its own task must process.

References: src/…/usbh.c• L1031-1155 src/…/usbh.c• L1158-1227 src/…/usbh.c• L1229-1323 src/…/usbh.c• L2578-2598 src/…/usbh.h• L271-279

Endpoint transfer scheduling

Class drivers and applications claim a non-control endpoint before they submit a transfer. The core marks the endpoint busy during the request and clears that state when the HCD reports completion. A failed submission releases the endpoint so later work can use it.

Endpoint completion data goes to an application callback when one is registered. Otherwise the core routes it to the class driver bound to that endpoint. This keeps transfer handling aligned with the interface discovery decisions made during enumeration.

References: src/…/usbh_pvt.h• L61-82 src/…/usbh.c• L1330-1377 src/…/usbh.c• L1422-1501

Host event dispatch

The host event path separates fast controller notification from host-state work. The HCD reports events to the core, and the core queues them for tuh_task() or tuh_task_ext(). That task drains attach, removal, transfer, and deferred-function events and calls the matching host or class behavior.

Event queue

The event queue carries the event type, rhport, device address, connection location, or transfer result needed by the host task. Each queued event can also reach the event hook for application tracing or wake-up logic. Root-hub attach events pass through a debounce guard. Hub attachment events can wait in a second queue while another device is being enumerated.

The task also handles delayed work, such as reset recovery and enumeration timing. It dispatches pending asynchronous control requests when the shared slot is free. It checks control-transfer deadlines while it drains controller events, which keeps timeout handling ordered with other host work. A stop request is itself queued, so the task consumes it in order after earlier host work and before the application deinitializes the stack.

References: src/…/hcd.h• L37-71 src/…/usbh.c• L390-403 src/…/usbh.c• L708-739 src/…/usbh.c• L849-985 src/…/usbh.c• L988-1011 src/…/usbh.c• L1583-1606

Completion dispatch

When the task receives a transfer completion, it first handles the control endpoint through the enumeration or control-transfer state machine. For another endpoint, it clears the endpoint state and chooses the application callback or the bound class driver. A function-call event uses the same queue so deferred host work runs in the host task context.

The control path ignores a completion after its request was already released or after the slot was assigned to another device. This prevents a late controller event from completing the wrong request.

This diagram shows the main event route from hardware to host behavior.

sequenceDiagram
    participant HCD as Host-controller driver
    participant Core as Host core
    participant Task as Host task
    participant Driver as Class or application callback
    HCD->>Core: Report attach, remove, or transfer event
    Core->>Core: Queue event and apply debounce rules
    Task->>Core: Drain queued event
    Core->>Core: Update device or endpoint state
    Core->>Driver: Dispatch mount, unmount, or transfer result

References: src/…/usbh.c• L743-846 src/…/usbh.c• L1229-1313 src/…/usbh.c• L1526-1555

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to HCD event fields must stay aligned with the event queue and with every controller that reports those events.
  • Changes to enumeration order must preserve the control-transfer serialization and the point at which a device becomes mounted.
  • Changes to device-address allocation or cleanup must preserve the distinction between normal devices and hub devices.
  • Changes to root-port retry state must preserve the boundary between one attachment and the next.
  • Changes to mount and unmount state must preserve the rule that an unmount callback follows a mount callback.
  • Changes to interface parsing must preserve both interface-to-driver and endpoint-to-driver bindings used for completion dispatch.
  • Changes to class-driver setup completion must preserve the guard against late callbacks after mount-triggered removal or address reuse.
  • Changes to hub status handling must preserve the link between a port change and its rhport, parent hub address, and port location.
  • Changes to hub status polling must preserve the fallback path that reads latched hub or port changes when interrupt polling fails.
  • Changes to hub port-power setup must preserve completion of hub configuration when an individual power request fails.
  • Changes to endpoint claim or close behavior must keep busy, claimed, and controller endpoint state in agreement.
  • Changes to control-transfer completion or timeout handling must release the shared slot and complete each queued request at most once.
  • Changes to device close or address reuse must preserve the generation check for queued asynchronous control requests.
  • Changes to public mounted-state checks must preserve the difference between a configured device and a device that completed all class-driver setup.
  • Changes to configuration completion must preserve the recovery path for a device that stalls SET_CONFIGURATION.
  • Changes to synchronous control calls must preserve the scheduler rule that the host task must not block on its own pending transfer.
  • Changes to task-stop or event-hook behavior must preserve the ordering between queued host work and task shutdown.

Important failure modes

TriggerConsequenceGuard
The HCD does not initialize or report a usable root-hub port.The host task cannot discover or serve devices on that port.tuh_rhport_init() requires successful HCD setup before it enables interrupts.
A device disconnects during enumeration.The current control request fails and the partial device record is released.Removal closes the device and invalidates delayed enumeration work.
A descriptor is invalid or larger than the enumeration buffer.Enumeration stops and the device is not mounted.The descriptor checks validate type, packet size, and total length before continuing.
A second device attaches while enumeration is active.Its work must not overwrite the shared enumeration state.The host core defers hub attachments until the current enumeration ends.
A new attach report arrives for an occupied location.The old device or enumeration can conflict with the new attachment.The attach path tears down the matching old location before it starts the new enumeration.
A root-port enumeration fails while the device remains connected.The port can stop serving the device even though the connection is still present.The host core re-posts the root-port attachment within the retry budget.
A device is removed after configuration starts but before mounting completes.The application can receive an unmount callback for a device it never saw mount.The core tracks completed mounting separately from configuration and checks it before unmount dispatch.
A device stalls SET_CONFIGURATION.The device can remain in a half-configured state with endpoints that do not exist.The host ends that attempt and re-enumerates the device from a fresh port reset within the enumeration retry budget.
A mount callback removes its device before class-driver setup completion returns.A late completion can advance setup for a removed device or a replacement at the same address.usbh_driver_set_config_complete() accepts completion only for the current configured device.
A hub's interrupt status poll keeps failing.A downstream connection change can remain latched and no attach or remove event reaches the host core.After the failure threshold, the hub reads one hub or port status through control transfer and resumes normal status polling.
A hub port-power request fails during setup.That port may not report a connection, but setup of other hub ports can still be blocked.The hub logs the failure and continues powering the remaining ports before completing hub configuration.
A control stage never produces a completion.The shared control path can remain occupied and block later requests.The control watchdog aborts the stage and completes it as XFER_RESULT_TIMEOUT.
A host-task callback submits a synchronous control transfer on a scheduled system.The host task can deadlock while it waits for an event it must process.Use an asynchronous control transfer and continue from its callback.
A hub branch is removed.Downstream devices could remain visible if cleanup stops at the hub.Removal marks the branch before callbacks and walks the hub's downstream tree.
A transfer is submitted to a busy endpoint.The endpoint can have overlapping state or an invalid completion owner.Endpoint claim and busy checks gate submission.
A queued control request belongs to a previous device at the same address.The request could reach the wrong physical device.Per-address generation values reject stale queued requests.
A stop request is queued after task shutdown has begun.The application can leave the task loop before all required ordering work is clear.tuh_task_stop() sends a function-call event and the task consumes the stop flag in queue order.

Key files

FileWhy to read it
src/…/usbh.cMain host lifecycle, enumeration, removal, transfer scheduling, and event dispatch.
src/…/usbh.hPublic host lifecycle, device, descriptor, and transfer contracts.
src/…/usbh_pvt.hInternal boundary between the host core and class drivers.
src/…/hcd.hContract between the common host core and controller-specific drivers.
src/…/hub.cHub setup, port status changes, downstream events, polling recovery, and topology behavior.
src/…/hub.hHub status model and hub operations used by enumeration and event handling.