Device core lifecycle
The USB device core links a device controller to the USB behavior that a host sees. It manages enumeration, control requests, configuration, and endpoint traffic. Applications define the device contract with descriptors and callbacks. Class drivers provide the behavior for each USB function and can be extended or replaced by application drivers.
System boundary
The device core sits between the device controller driver and class drivers. The controller reports bus and transfer events. The core tracks USB state, routes work, and sends controller operations. Class drivers handle the behavior of configured interfaces.
This boundary shows how the device side of the stack moves data and events:
flowchart LR
H[USB host] --> D[Device controller]
D -->|bus and transfer events| C[Device core]
C -->|controller operations| D
C -->|requests and transfers| F[Class drivers]
A[Application] -->|descriptors and callbacks| C
A -->|class data and custom drivers| F
The application configures controller-specific behavior with tud_configure() before initialization. It starts the device role with tud_rhport_init() and services events with tud_task() or tud_task_ext(). In an RTOS, initialization and deinitialization run in the same task or context as the device task. tud_task_stop() lets another task drain queued work before that task deinitializes the stack.
Controller event path
The controller reports reset, setup, transfer, suspend, resume, unplug, and start-of-frame events. The device event handler updates connection and suspend state at the controller boundary, then normally queues work for the device task. A class driver can process a non-control transfer in its interrupt callback when its work is safe in that context.
The core keeps state for work that spans more than one USB packet. It rejects a response when a newer setup or reset has replaced the request. If the event queue is full, it clears related pending state so a later request or transfer can recover. Code that must run after all queued events can use the device-task defer hooks.
This sequence shows the normal relationship between the controller interrupt path and the device task:
sequenceDiagram
participant DCD as Device controller driver
participant Core as Device core
participant Task as Device task
participant App as Application or class driver
DCD->>Core: Report bus or transfer event
Core->>Core: Update fast state or queue event
Core->>App: Optional interrupt transfer callback
Task->>Core: Run tud_task()
Core->>App: Dispatch lifecycle or class callback
App->>Core: Queue response or next transfer
Core->>DCD: Submit controller operation
References: src/…/usbd.h• L17-89 src/…/usbd.c• L402-435 src/…/usbd.c• L680-930 src/…/usbd.c• L1525-1649 src/…/usbd_pvt.h• L118-123
Device lifecycle
The core tracks connection, address assignment, configuration, and suspend state. These states mark different points in USB setup. A connected device is not yet ready for normal data traffic.
| State | Meaning | Application view |
|---|---|---|
| Connected | The core has received a setup request after reset. | tud_connected() is true. |
| Addressed | The host has assigned a device address. | Enumeration has progressed, but interfaces are not active. |
| Mounted | The host has selected a configuration and the core has opened its interfaces and endpoints. | tud_mounted() is true. |
| Suspended | The host has suspended the bus after an idle period. | tud_suspended() is true and tud_ready() is false. |
Reset and configuration flow
Enumeration starts with a bus reset and reaches normal operation after the host selects a configuration. Reset handling clears class, endpoint, mapping, and start-of-frame state so the next host session starts from a clean state.
flowchart TD
R[Bus reset] --> D[Host reads device descriptor]
D --> A[Host assigns device address]
A --> Q[Host reads configuration and capability descriptors]
Q --> S[Host selects a configuration]
S --> O[Core opens interfaces and endpoints]
O --> M[Mount callback]
M --> T[Normal transfers]
T --> X[Reset or unplug]
X --> U[State closes and unmount callback]
The core calls tud_mount_cb() after it accepts the selected configuration. It calls tud_umount_cb() when the host selects configuration zero, when the device is unplugged, or when deinitialization ends an active configuration. Suspend changes transfer readiness. It does not unmount the device. A resume event restores active bus state and calls tud_resume_cb() when the device is connected.
References: src/…/usbd.h• L104-137 src/…/usbd.c• L542-659 src/…/usbd.c• L662-678 src/…/usbd.c• L700-810 src/…/usbd.c• L1528-1566
Control request processing
Endpoint zero carries enumeration and device-management requests. Each request has a setup stage, an optional data stage, and a status stage. The core owns this sequence and gives application or class code a chance to provide or validate request data. Control data moves in complete endpoint-zero packets, so the core requires its control buffer size to be a multiple of the endpoint-zero packet size.
Request routing
The core handles standard device requests such as descriptors, address, configuration, status, and remote wakeup. It sends interface requests to the class driver bound to that interface. It sends class-specific endpoint requests to the driver bound to that endpoint. Unsupported requests stall the control transfer so the host sees an error.
The core rejects a setup that the controller has superseded with a newer setup or reset. This prevents an old response from changing the state of the active request.
References: src/…/usbd.c• L721-789 src/…/usbd.c• L1071-1384 src/…/usbd.c• L1592-1605
Application control participation
An application or class driver accepts a request at the setup stage and then starts its data or status stage. tud_control_xfer() carries data. tud_control_status() carries a zero-length status response. A callback can reject data at completion, which causes the core to stall the request.
Vendor requests use tud_vendor_control_xfer_cb(). An application can add a class driver through usbd_app_driver_get_cb(). Application drivers are considered before built-in drivers, so an application driver can replace a built-in match when its interface rules accept the descriptor. The returned driver table must remain available while the device stack is active.
References: src/…/usbd.h• L139-208 src/…/usbd.c• L457-477 src/…/usbd.c• L983-1068 src/…/usbd.c• L1074-1079 src/…/usbd.c• L1200-1384 src/…/usbd.c• L376-397 src/…/usbd_pvt.h• L33-50 src/…/usbd.c• L151-154
Descriptor configuration
Descriptors are the contract that tells the host what the device is and how its functions connect. The application supplies device, configuration, string, and optional speed or capability descriptors through callbacks.
Descriptor callbacks
The core asks for the descriptor that matches each host request. Descriptor data must remain valid until its control transfer completes. Optional callbacks can return no descriptor when the device does not support that descriptor type.
| Callback | Host-visible role |
|---|---|
tud_descriptor_device_cb() | Identifies the device and endpoint-zero limits. |
tud_descriptor_configuration_cb() | Describes interfaces, alternate settings, and endpoints. |
tud_descriptor_string_cb() | Supplies human-readable device and interface text. |
tud_descriptor_bos_cb() | Supplies optional device capability data. |
tud_descriptor_device_qualifier_cb() | Describes the device at its other USB 2.x speed. |
tud_descriptor_other_speed_configuration_cb() | Supplies the configuration for the other speed. |
High-speed support requires the qualifier and other-speed configuration to agree with the device configuration. The configuration descriptor also defines power and remote-wakeup properties that the core reports in device status.
References: src/…/usbd.h• L156-181 src/…/usbd.c• L1439-1522
Configuration ownership
When the host selects a configuration, the core walks its interface descriptors. It gives each interface group to the first class driver that accepts it. That accepted descriptor range determines the interfaces and endpoints owned by the driver.
This binding joins the descriptor interface numbers, class-driver matching rules, and endpoint addresses. A composite device mounts only when these contracts describe the same functions.
References: src/…/usbd.c• L1386-1437 src/…/usbd.c• L376-397 src/…/usbd_pvt.h• L33-43
Endpoint transfer scheduling
Non-control endpoints carry class data after configuration. A class driver claims an endpoint, submits one transfer, and receives a completion before it schedules the next transfer. The core tracks endpoint ownership so two producers do not use the same endpoint at the same time.
Transfer ownership
The endpoint contract uses these operations:
usbd_edpt_claim()reserves an endpoint for one producer.usbd_edpt_xfer()submits a buffer and byte count to the controller.usbd_edpt_xfer_fifo()submits data from a FIFO when the controller supports it.usbd_edpt_release()returns a claim when no transfer was submitted.usbd_edpt_abort()stops an in-flight non-control transfer and releases its claim.usbd_edpt_busy()reports whether a transfer is active.usbd_edpt_stall()andusbd_edpt_clear_stall()manage a halted endpoint.
An OUT completion stays pending until the class driver consumes the received data. The driver must consume that data before it claims and arms the endpoint again. This prevents a new receive operation from replacing data that the application has not used. A transfer abort first uses the controller's direct abort path when available. The core falls back to a stall-and-clear sequence when that path is not available. Clearing a real stall also releases the endpoint claim because the stalled transfer has no completion event. Clearing a non-stalled endpoint does not release an active claim.
Isochronous endpoints have an additional allocation and activation path. Their descriptor still defines the endpoint contract, while the controller supplies the packet storage or timing support.
References: src/…/usbd.c• L1670-1713 src/…/usbd.c• L1717-1997 src/…/usbd_pvt.h• L63-115
Completion and frame timing
The core maps a completed endpoint address to its class driver and passes the result and byte count to the transfer callback. A driver can process a completion in interrupt context through its xfer_isr callback. If that callback defers the work, the device task calls the normal transfer callback instead.
Start-of-frame callbacks support time-based work such as isochronous scheduling. Class-driver SOF handlers run at the controller event boundary. The user SOF callback runs through the device task after SOF support is enabled. A reset or configuration change clears that request. Code that needs it again enables it after mounting.
References: src/…/usbd.h• L134-137 src/…/usbd.c• L750-788 src/…/usbd.c• L819-824 src/…/usbd.c• L1568-1589 src/…/usbd.c• L1608-1647 src/…/usbd_pvt.h• L33-43
Application callbacks
Application callbacks are the points where product code supplies USB-facing data and observes device state. Most callbacks are optional weak hooks, so an application implements only the parts of the lifecycle that it uses.
Descriptor callbacks
Descriptor callbacks return device or string data to the control-transfer engine. Fixed descriptors normally remain in static storage. Generated descriptors must remain valid for the complete transfer.
References: src/…/usbd.h• L156-181 src/…/usbd.c• L1439-1522
State callbacks
The address callback reports when the host assigns a device address. Mount and unmount callbacks mark when the selected configuration becomes active or inactive. Suspend and resume callbacks let an application reduce work and restore it when bus traffic returns. The suspend callback reports whether the host enabled remote wakeup.
The application can query tud_ready() before ordinary traffic. It can call tud_remote_wakeup() only while suspended and only when the host enabled remote wakeup. It can use tud_connect() and tud_disconnect() to control the bus pull-up when the controller supports those operations.
References: src/…/usbd.h• L104-137 src/…/usbd.h• L183-199 src/…/usbd.c• L501-536 src/…/usbd.c• L1081-1092 src/…/usbd.c• L1530-1566
Event and vendor callbacks
The event hook observes events queued for device-task processing. It can support application logging or scheduling. The SOF callback receives frame counts after user SOF support is enabled. The vendor control callback handles requests outside the standard and class request spaces.
On DWC2 ports that use guarded setup memory, tud_dwc2_setup_dma_error_cb() observes recovery from an invalid sequence of short setup packets. The stack disconnects and reinitializes the device before this callback runs.
Class-driver callbacks provide the integration point for custom device functions. A driver participates through initialization, reset, interface opening, control requests, transfers, and optional SOF processing. Its transfer callback can run in the device task or use the optional interrupt callback when the port enables that path. See USB device stack for the wider stack model and USB class drivers for the function-level driver contract.
References: src/…/usbd.h• L151-154 src/…/usbd.h• L201-208 src/…/usbd.c• L29-35 src/…/usbd.c• L431-435 src/…/usbd.c• L812-824 src/…/usbd.c• L1568-1589 src/…/usbd_pvt.h• L33-50
Change checklist
When these files or sections are changed, remember to consider these:
- Keep interface numbers, endpoint addresses, and class-driver matching aligned when a configuration descriptor changes.
- Keep full-speed, high-speed, qualifier, and other-speed descriptors consistent when speed support changes.
- Keep descriptor storage valid for the full control transfer when callbacks return generated or temporary data.
- Keep the endpoint-zero control buffer size a multiple of the endpoint-zero packet size so every armed control packet fits.
- Preserve reset, setup, transfer, and queue behavior when changing the controller boundary. The device task depends on these events to clear state and dispatch work.
- Preserve setup-tag handling when changing control request flow. A stale response must not run after a newer setup or reset.
- Apply port-specific settings before
tud_rhport_init()and keep initialization, deinitialization, and device-task calls in the required task or context. - Keep an application class-driver table valid for the full time that the device stack is active. Preserve its driver order when an application must override a built-in match.
- Ensure each accepted control request completes its data or status stage exactly once.
- Consume OUT data before claiming and re-arming its endpoint.
- Prefer the controller abort path when it is available. Keep the stall-and-clear fallback for controllers that cannot abort an active transfer directly.
- Preserve endpoint claim release when a transfer is aborted or a stalled endpoint is cleared. Do not release a claim when clearing a non-stalled endpoint that may still have active work.
- Preserve recovery when the event queue is full. Dropped setup and transfer events must not leave EP0 or a data endpoint blocked.
- Keep the return contract of
xfer_israligned with event queuing. A handled completion must not run again in the device task. A deferred completion must retain the state needed byxfer_cb. - Enable SOF again after reset or a configuration change when frame callbacks are required. Account for both class-driver and user SOF consumers.
- Use the after-queue defer hook only for work that must run after earlier device events. Do not assume it adds another queued event.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A required descriptor callback returns no descriptor. | Enumeration stops with a stalled control request. | Implement every descriptor type the device advertises. |
| The endpoint-zero control buffer size is not a multiple of the endpoint-zero packet size. | The build rejects the device core configuration. | Keep CFG_TUD_ENDPOINT0_BUFSIZE aligned with CFG_TUD_ENDPOINT0_SIZE. |
| Interface or endpoint values do not match class-driver rules. | Configuration cannot open all functions, so the device does not mount. | Treat descriptors and class-driver matching as one contract. |
| Normal traffic starts before mounting or during suspend. | Transfers are not ready for normal bus traffic. | Check tud_ready() before ordinary transfers. |
| An OUT completion is not consumed before the next claim. | The endpoint remains receive-pending and cannot be re-armed. | Consume the data before claiming the endpoint again. |
| A control callback accepts a request but starts no data or status stage. | The host waits for a response or sees a malformed transfer. | Use tud_control_xfer() or tud_control_status() for every accepted request. |
| A newer setup or reset replaces an older control request. | A stale response can interfere with the active request. | Let setup-tag checks reject superseded work. |
| The event queue drops a setup or transfer event without clearing its pending state. | EP0 or a data endpoint can remain blocked until reinitialization. | Preserve the queue-full recovery path. |
| An interrupt transfer callback handles a completion but reports that it should be deferred. | The class callback runs again in task context or endpoint state is restored incorrectly. | Keep the xfer_isr return meaning and busy-state transition consistent. |
| A direct controller abort is assumed but not supported. | The transfer remains active or its claim is not released. | Use the stall-and-clear fallback when the controller has no abort operation. |
| An application driver table is released or changed while the stack is active. | Driver lookup can use invalid or mismatched callbacks. | Keep the table stable for the full stack lifetime. |
| SOF is enabled before a reset or configuration change. | The expected SOF callback is not active after the lifecycle transition. | Enable SOF from the mount callback when the application needs it. |
Key files
| File | Why to read it |
|---|---|
| src/…/usbd.h | Defines the device setup, task, state, control-transfer, descriptor, and callback contracts. |
| src/…/usbd.c | Shows the lifecycle from controller events through enumeration, request routing, configuration binding, and transfer completion. |
| src/…/usbd_pvt.h | Defines the internal class-driver, endpoint ownership, transfer, SOF, and task-defer contracts used by built-in and application drivers. |
| src/…/dcd.h | Defines the boundary between the core and device controller drivers. |
| src/tusb.c | Shows root-hub role selection and the shared initialization and deinitialization path. |
| examples/…/usb_descriptors.c | Shows how a composite device connects configuration, interfaces, endpoints, and strings. |