USB device stack
The USB device stack lets an embedded product present one or more USB functions to a host. It joins the public device API, the device controller, descriptor data, endpoint transfers, and class drivers into one event-driven path. The device core lifecycle page covers bus and control state in more detail. The USB class drivers page covers device-side protocol families and their application contracts.
Device stack boundary
The device stack sits between application code and the device controller driver. Application code selects device mode, supplies descriptors, calls class APIs, and runs the device task. The stack turns controller events into control replies, endpoint transfers, and callbacks without exposing controller registers to the application.
The public surface has four related parts:
- Stack control:
tud_configure(),tud_rhport_init(),tud_deinit(),tud_inited(),tud_task(),tud_task_ext(),tud_task_stop(), andtud_int_handler()select and manage a root-hub port.tud_task_event_ready()reports queued work, andtud_init()remains as a compatibility wrapper. - Device state:
tud_connected(),tud_mounted(),tud_ready(),tud_suspended(), andtud_speed_get()report the link state that matters to an application. - Application participation: descriptor callbacks and bus callbacks provide the data and notifications needed during enumeration and later operation.
- Class capability: class headers expose application APIs for serial data, reports, storage commands, media streams, network data, and other device functions.
The device build selects the device-mode port and speed, validation policy, memory limits, event-processing budget, and enabled class drivers. These settings define which device features exist and how much checking the stack applies to USB input. Pre-initialization configuration can also set port-specific stack behavior. Class support is selected at build time, and enabled class headers become part of the umbrella interface in src/tusb.h.
References: src/…/usbd.h• L17-137 src/tusb.h• L131-160 src/tusb_option.h• L235-311 src/tusb_option.h• L474-505 src/tusb_option.h• L613-755
Initialization and event path
Initialization prepares the device stack, its class drivers, its event path, and the controller for device mode. The application can set port-specific stack behavior before initialization through tud_configure(). It then lets the controller interrupt path publish events and calls tud_task() from the main loop or the matching RTOS task to process them. A controller may report reset as a start edge and an end edge. The end event carries the negotiated speed and is sufficient on controllers that report only one reset event.
The normal path is:
- The application applies any port-specific configuration, then configures the device root-hub port and speed through
tusb_init()ortud_rhport_init(). - The stack starts its event queue, endpoint state, class drivers, and device controller. Application class drivers are placed before built-in drivers so they can override a built-in match. The application driver table must remain available while the stack is active.
- The controller interrupt handler reports reset, setup, transfer, suspend, resume, unplug, and frame events. Setup events carry a sequence tag so a newer setup or reset can invalidate an older control transfer.
tud_task()consumes these events. It resets state at the reset edge and sends standard control work to the device core or data work to the owning class driver.- Class callbacks and device callbacks return status or data to the application.
This diagram shows how controller events move through the stack before they reach application code.
flowchart LR
A[Application] -->|init and descriptors| B[Public device API]
B --> C[Device stack]
C --> D[Device controller]
D -->|interrupt events| E[Event queue]
E -->|tud_task| C
C --> F[Device core]
C --> G[Class drivers]
F --> A
G --> A
The interrupt path also gives enabled class drivers their frame callbacks. User frame callbacks are queued for the device task. A class transfer callback can instead run in the interrupt path when TUP_USBD_XFER_ISR enables that option. When the option is disabled, completion goes to the normal task-context callback even though the class-driver contract still includes the optional hook. Suspend and resume state is updated at the event boundary, while the matching application callbacks run as queued device work. A frame event can also end a remote-wake suspend period and queue a resume callback. If the event queue is full, the stack restores setup and transfer state so a dropped event does not permanently block later work. A setup received after unplug is ignored until the next bus reset. tud_task_stop() queues a stop request after earlier queued work and lets the task exit before tud_deinit() removes the queue. tud_task_ext() can wait for a chosen time and reports when the task should leave its loop. tud_task_event_ready() lets a task check for pending work before it waits.
With an RTOS, initialization and the device task must use the context expected by the stack. The interrupt path captures events. The device task owns normal event work. The task-stop and deinitialization sequence must complete in the task context that owns the event queue.
References: src/…/usbd.h• L40-102 src/…/usbd.c• L542-655 src/…/usbd.c• L678-910 src/…/usbd.c• L1522-1653 src/…/dcd.h• L23-76
Device state model
The stack exposes state in stages because a USB link can be present before the host has configured the device. tud_connected() becomes true after the stack receives the first setup request. tud_mounted() becomes true after the host selects a non-zero configuration. tud_ready() combines mounted state with the absence of suspend state.
| State | Meaning | Application use |
|---|---|---|
| Connected | The host has started control exchange after reset. | Accept enumeration-related activity. |
| Mounted | The host has selected a configuration and the class endpoints are active. | Start normal class traffic. |
| Ready | The device is mounted and not suspended. | Submit normal data transfers. |
| Suspended | The bus is suspended. | Stop or reduce traffic. Use remote wake only when the host enabled it. |
The stack also reports the negotiated USB speed. Bus reset and unplug events clear configuration state, so class traffic must wait for the next mount cycle. A frame after remote wake can also mark the bus active and produce the resume callback.
References: src/…/usbd.h• L104-139 src/…/usbd.c• L497-523 src/…/usbd.c• L700-717 src/…/usbd.c• L1522-1573
Descriptor and configuration contract
Descriptors define the device identity that the host sees and the interfaces and endpoints that class drivers must operate. The application supplies device, configuration, string, and optional capability descriptors through callbacks. Descriptor templates in the public device header help applications describe common functions and composite devices.
During SET_CONFIGURATION, the stack reads the returned configuration descriptor in order. It asks each enabled class driver whether it owns the next interface block. A matching driver opens its endpoints and receives the interface and endpoint mapping for later control and transfer events. This lets one device expose several functions while keeping each function's protocol logic in its class driver.
When the host changes from one non-zero configuration to another, the stack closes the current endpoints and resets class state before it binds the new configuration. A configuration value of zero unmounts the device.
The descriptor contract has two important sides:
- The configuration descriptor must describe interfaces and endpoints that an enabled class driver can recognize.
- The class API and application callbacks must match the data shape promised by those descriptors.
References: src/…/usbd.h• L151-200 src/…/usbd.h• L240-295 src/…/usbd.c• L1100-1135 src/…/usbd.c• L1380-1431 src/…/usbd.c• L1433-1517
Endpoint transfer model
Endpoints carry class data after configuration. A class driver opens endpoints from the configuration descriptor, claims an endpoint before it starts work, submits a transfer, and receives a completion callback when the controller reports the result. The device stack tracks busy, claimed, stalled, and pending OUT data states so that transfers do not overlap silently. A completed OUT transfer stays pending until the class consumes its buffer.
The transfer path separates ownership from completion. A class that cannot submit work at once releases its claim. A stall stops the endpoint and a clear-stall operation makes it available again. For an OUT endpoint, the class must consume the received data before it claims or re-arms the endpoint. Clearing a stall also releases a claim held by the aborted transfer, while a clear on a non-stalled endpoint keeps another task's claim. An abort uses a controller-supported cancellation when available. Otherwise, the stack stalls and clears the endpoint as a fallback. Closing an endpoint clears its stack state, but a controller may still report an in-progress transfer after the close.
The device endpoint interface supports these common operations:
- Open endpoints described by the active configuration.
- Submit buffer or FIFO transfers.
- Claim and release endpoint ownership.
- Test readiness and busy state.
- Stall, clear, or abort a transfer.
- Allocate and activate isochronous endpoint resources where the controller needs them.
Endpoint completion normally runs in the device task. A class can provide an optional interrupt-time completion hook for work that must happen before deferred processing. The hook is used only when TUP_USBD_XFER_ISR is enabled. When that setting is disabled, completion goes to the normal task-context callback even though the class-driver contract still includes the optional hook. The class remains responsible for safe buffer and ownership handling. The stack restores endpoint state if a queued completion cannot be accepted, and it clears the busy state when the controller refuses a transfer.
References: src/…/usbd_pvt.h• L33-130 src/…/usbd.c• L751-789 src/…/usbd.c• L1581-1653 src/…/usbd.c• L1693-1913 src/…/tusb_private.h• L27-34 src/…/dcd.h• L141-194
Control request routing
Endpoint zero carries enumeration, standard USB requests, vendor requests, and class requests. The device core handles requests for device state and descriptors. It routes interface and endpoint requests to the class driver bound to that object. The same control-transfer path supports data and status stages and stalls both control directions when a request cannot be completed.
The routing relationship is:
- Device recipient: standard requests such as descriptors, address, configuration, status, and remote wake state go to the device core.
- Interface recipient: class and interface requests go to the driver mapped to the interface.
- Endpoint recipient: standard halt requests are handled by the stack, while class requests go to the driver mapped to the endpoint.
- Vendor type: the application vendor-control callback receives the request.
Class drivers use the control callback to handle protocol setup. They use the transfer callback for data endpoints. A controller can reject a stale EP0 operation when a newer setup arrives, so the stack checks the setup tag before it starts processing the request. When a control status stage completes, the controller can receive a notification before the class or application completion callback runs. The stack also clamps received control data to the request buffer size before it copies the data. These rules keep USB request sequencing in the device core while leaving protocol meaning to the class layer.
References: src/…/usbd.h• L139-203 src/…/usbd.c• L935-1069 src/…/usbd.c• L1075-1378 src/…/dcd.h• L141-151
Class-driver integration
The class layer turns USB interfaces into application-facing capabilities. Each enabled built-in class driver supplies a common set of lifecycle, descriptor matching, control-request, and transfer hooks. An optional interrupt-time transfer hook is part of the shared driver contract, and the stack dispatches it only when interrupt-time transfer handling is enabled. Frame hooks serve class timing needs in the controller event path. Applications can also provide class drivers through the application-driver callback to extend or replace built-in support. The returned driver table must remain valid while the device stack is active.
The umbrella API makes class choice a product decision. Device builds can enable combinations such as CDC and HID for control and input, MSC for storage, audio or video for streams, network classes for connectivity, or vendor and specialized classes for custom protocols. The USB class drivers page describes the shared class layer.
The application-facing model differs by class. CDC exposes buffered byte streams and line state. HID exposes reports and report callbacks. MSC exposes storage and SCSI callbacks. Stream and specialized classes expose their own buffers, controls, and event rules. The common stack still supplies the same mount, control, endpoint, and transfer foundation.
References: src/…/usbd.c• L156-370 src/…/usbd.c• L372-394 src/…/usbd.c• L589-599 src/…/usbd.c• L1552-1559 src/…/usbd_pvt.h• L33-50 src/tusb.h• L61-123 src/…/cdc_device.h• L81-138 src/…/hid_device.h• L31-137 src/…/msc_device.h• L41-107
Application callback model
Callbacks let an application provide product data and react to USB state without taking ownership of the device core. Descriptor callbacks answer host requests. Mount and unmount callbacks mark when class functions become available or must stop. Suspend and resume callbacks let the application manage power and activity. Class callbacks carry protocol data into the product's own storage, input, stream, or service code.
The callback model creates a clear boundary:
- The stack owns USB state, request sequencing, endpoint scheduling, and driver dispatch.
- The application owns descriptor contents, product data, device behavior, and storage or stream back ends.
- A callback that cannot complete a request can return failure. The stack then reports the USB error through the proper stall or failed-transfer path.
References: src/…/usbd.h• L150-203 src/…/usbd.c• L985-1069 src/…/usbd.c• L1199-1378 src/…/hid_device.h• L106-137 src/…/msc_device.h• L54-135
Change checklist
When these files or sections are changed, remember to consider these:
- Keep device-mode root-port selection aligned with the controller port passed to
tusb_init()and the controller integration. - Keep pre-initialization
tud_configure()parameters aligned with the controller and their documented lifetime. - Keep device validation settings aligned with the peer trust model. A stricter policy can change accepted requests and resource use.
- Keep each enabled class feature, its descriptor block, and its class-driver match path aligned. A mismatch can leave an interface without an owner during
SET_CONFIGURATION. - Keep the application class-driver table available for the full initialized lifetime. The stack does not copy that table.
- Keep interface and endpoint numbering unique across composite descriptors. The stack uses those numbers to route later control and transfer events.
- Keep descriptor callback lifetime valid through the complete control transfer. The stack may send descriptor data after the callback returns.
- Keep endpoint claim, OUT-data consumption, and re-arm order aligned with the class transfer callback. Otherwise an endpoint can remain pending or busy.
- Keep interrupt-time transfer behavior aligned with
TUP_USBD_XFER_ISR. A class hook can remain in the driver contract while its completion work moves to task context when the setting is disabled. - Keep class frame hooks safe for their controller event context. They can run before the device task handles the frame event.
- Keep controller reset-edge, unplug, setup-tag, and control-status completion behavior aligned with the device core. A stale reset, unplug, or setup can invalidate control state before the task handles it.
- Keep event queue capacity and
CFG_TUD_TASK_EVENTS_PER_RUNaligned with the event rate. Dropped or delayed events change control and class timing. - Keep
tud_task_stop()andtud_deinit()in the same task context as the device task when an RTOS is used.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Configuration descriptor has an unsupported or malformed interface block | SET_CONFIGURATION fails and the device does not mount | Match every interface block to an enabled class driver and keep descriptor lengths valid. |
| Application class-driver table is changed or freed while the stack is active | Class dispatch can call invalid or changed hooks | Keep the table and each hook valid until deinitialization. |
| Application submits a transfer while its endpoint is busy or still claimed | The transfer is rejected or the endpoint can become unavailable to later work | Check readiness and follow claim, transfer, completion, and release ownership rules. |
Application assumes an interrupt-time transfer hook runs while TUP_USBD_XFER_ISR is disabled | Completion work runs later in the device task, which can break code that requires interrupt context | Use the normal transfer callback for the disabled setting and reserve interrupt-only work for builds that enable it. |
| A class frame hook performs task-only work | The interrupt path can corrupt shared state or violate the platform's interrupt rules | Keep frame hooks short and safe for the controller event context. Defer longer work to the device task. |
| Application uses class APIs before mount or during suspend | Data does not move or the class sees a not-ready state | Gate normal traffic on tud_ready() and restart traffic after mount or resume. |
| Descriptor or callback returns invalid data for a host request | The control request stalls and host enumeration or class setup stops | Return valid descriptors and complete each class request through the control-transfer API. |
| Device task does not run often enough or runs in the wrong RTOS context | Queued reset, setup, and transfer events remain unprocessed | Run tud_task() in the intended main loop or device task after initialization. |
| Device task event budget is too small for the incoming event rate | Work remains queued longer than expected, which delays control or class traffic | Set CFG_TUD_TASK_EVENTS_PER_RUN for the workload and service the device task without long blocking work. |
| Event queue fills while a setup or transfer completion is reported | The event is deferred or dropped, which can delay control work or class traffic | Size CFG_TUD_TASK_QUEUE_SZ for the workload and keep the device task active. |
| Controller reports a stale setup, reset, or setup from before unplug | The stack can process obsolete EP0 work or discard a valid request | Use setup sequencing and report reset and unplug events as defined by the device-controller contract. |
| DCD cannot abort a non-control transfer and the caller expects a silent cancel | The fallback briefly stalls the endpoint and resets its data toggle | Treat usbd_edpt_abort() as a controller-dependent operation and account for the stall-and-clear fallback. |
| A transfer completes after its endpoint was closed | The stack drops the completion because the endpoint no longer maps to a class driver | Close and rebind endpoints as part of configuration changes, and do not depend on late completions. |
tud_deinit() runs before the device task has stopped | The task can access deleted queue or synchronization state | Queue tud_task_stop(), wait for the task to return, then deinitialize in the same context. |
Key files
| File | Why to read it |
|---|---|
| src/tusb.h | Primary umbrella API and the feature-gated device class surface. |
| src/tusb.c | Root-port role selection, stack initialization dispatch, interrupt dispatch, and deinitialization. |
| src/…/usbd.h | Public device lifecycle, state, control, callback, descriptor-template, dynamic configuration, and root-port initialization contracts. |
| src/…/usbd.c | Central device event path, control routing, configuration binding, class dispatch, and endpoint state. |
| src/…/usbd_pvt.h | Internal contract between the device core and class drivers for endpoints, deferred work, and callbacks. |
| src/…/dcd.h | Device controller contract for reset edges, setup tags, control completion, interrupts, endpoint work, and transfer cancellation. |
| src/tusb_option.h | Device-mode selection, validation policy, speed, endpoint, memory, event, and class defaults. |
| src/…/cdc_device.h | Example of a buffered serial device API and its application integration points. |
| src/…/hid_device.h | Example of report-based input and output device integration. |
| src/…/msc_device.h | Example of storage command callbacks and asynchronous back-end I/O. |