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 / osal-and-runtime-services

OS abstraction and runtime services

The OS abstraction and runtime services provide the shared base that lets the TinyUSB device and host stacks run across bare-metal systems, RTOS environments, and different compilers. They define common contracts for time, tasks, locks, semaphores, queues, buffers, logging, checks, and configuration while leaving scheduling and hardware work to the selected platform.

OS abstraction layer

The OS abstraction layer, or OSAL, presents one task and synchronization interface to the USB stack. The build selects one adapter through CFG_TUSB_OS, so higher layers can use time, delays, critical sections, semaphores, mutexes, and queues without calling an RTOS API directly. See the parent platform integration page for the wider relationship between this layer and the MCU and USB controller ports.

The shared OSAL contract covers these services:

  • Current task identity and millisecond time.
  • Task delay and timeout values for immediate, normal, and forever waits.
  • Spin locks for short shared-state and interrupt-safe sections.
  • Binary semaphores for event notification.
  • Mutexes for ownership of shared state.
  • Queues for fixed-size event transfer between interrupt and task contexts.

The USB stack passes an in_isr flag to operations that can run from an interrupt service routine. An adapter must preserve the difference between interrupt-safe signaling and task-context blocking. It also maps the common millisecond timeout model to the selected system's clock units.

flowchart LR
  USB[USB device or host stack] --> API[OSAL contract]
  API --> Select{CFG_TUSB_OS}
  Select --> Bare[No-OS mode]
  Select --> RTOS[RTOS adapter]
  Select --> Custom[Application adapter]
  Bare --> Services[Time, locks, events, queues]
  RTOS --> Services
  Custom --> Services

References: src/…/osal.h• L15-54 src/…/osal.h• L57-86 src/tusb_option.h• L628-651

Supported operating systems

TinyUSB supplies adapters for no-OS mode, FreeRTOS, Mynewt OS, the Raspberry Pi Pico SDK, RT-Thread, Keil RTX 4, Zephyr, ThreadX, and SuperTinyKernel (STK). Applications can also select OPT_OS_CUSTOM and provide tusb_os_custom.h when the required contract is implemented outside the stack.

SelectionRuntime modelMain system role
OPT_OS_NONESingle application contextUses application time and interrupt control instead of a scheduler
OPT_OS_PICOPico SDK single-context modelUses Pico time, semaphores, mutexes, and critical sections
OPT_OS_FREERTOSPreemptive task systemUses FreeRTOS tasks, queues, semaphores, mutexes, and critical sections
OPT_OS_MYNEWTRTOSUses Mynewt tasks, event queues, memory pools, and synchronization
OPT_OS_RTTHREADRTOSUses RT-Thread tasks, message queues, semaphores, mutexes, and spin locks
OPT_OS_RTX4RTOSUses RTX tasks, mailboxes, semaphores, and mutexes
OPT_OS_ZEPHYRRTOSUses Zephyr tasks, message queues, semaphores, mutexes, and spin locks
OPT_OS_THREADXRTOSUses ThreadX threads, queues, semaphores, mutexes, and interrupt masking
OPT_OS_STKRTOSUses STK tasks, time, critical sections, semaphores, mutexes, and message queues
OPT_OS_CUSTOMApplication-definedRequires the application to supply the OSAL port header

The STK adapter can bind to STK's C API by default or to its native C++ API when CFG_TUH_OSAL_STK_USE_CPP is enabled. The C++ choice requires the adapter's companion C++ source to be part of the application build. The scheduler flag is a separate policy value. It is off for no-OS and Pico builds and on for the RTOS adapters by default. Host behavior uses this distinction when it decides whether work can wait or must remain in the calling context.

The ThreadX adapter converts the shared millisecond time model to ThreadX ticks. It preserves immediate and forever waits and rounds a nonzero short wait up to one tick. Queue sends from interrupt context do not wait for space, while task-context sends can wait. Its spin lock masks interrupts only outside interrupt context, so it is not a hardware lock for SMP use.

The RTX 4 adapter maps the shared time, wait, semaphore, mutex, and queue contracts to RTX services. Its spin-lock interface is a compatibility stub, so shared state must use the supported mutex and interrupt-context rules instead of relying on that interface for exclusion.

References: src/tusb_option.h• L228-237 src/tusb_option.h• L633-643 src/…/osal.h• L34-56 src/…/osal_stk.h• L9-21 src/…/osal_stk.h• L43-51 src/…/osal_stk.h• L149-173 src/…/osal_threadx.h• L18-52 src/…/osal_threadx.h• L54-86 src/…/osal_threadx.h• L147-188 src/…/osal_rtx4.h• L18-48 src/…/osal_rtx4.h• L50-70 src/…/osal_rtx4.h• L73-190

No-OS mode

No-OS mode targets a single execution context with no scheduler. It uses nested interrupt enable and disable callbacks for short critical sections, a FIFO-backed queue for fixed-size messages, and a blocking semaphore when a caller must wait. Queue receive is an immediate check rather than a timed wait, so the caller must arrange any required retry or wait behavior.

The application owns the time source in this mode. It must provide tusb_time_millis_api(). The default delay helper measures elapsed time with that function, while semaphore waits remain busy waits and ignore their millisecond argument. A stale or non-advancing clock can stop timeout and delay behavior.

On a single-core system, mutexes are normally unnecessary. On a multi-core target, the configuration keeps them active because interrupt masking alone does not protect shared state across cores. The no-OS spin lock is intended for nested use in one execution context and is not a hardware lock for true SMP systems.

References: src/…/osal_none.h• L15-39 src/…/osal_none.h• L41-76 src/…/osal_none.h• L80-154 src/…/osal_none.h• L156-214 src/tusb.c• L35-52 src/…/tusb_common.h• L74-88

Common runtime types

The common headers define the data and status vocabulary shared by device code, host code, controller ports, and class drivers. These types keep USB roles, speeds, transfer kinds, directions, transfer results, buffers, and descriptors consistent across the stack.

The most important type groups are:

  • tusb_role_t identifies host or device operation.
  • tusb_speed_t identifies low, full, and high speed operation.
  • tusb_xfer_type_t identifies control, isochronous, bulk, and interrupt transfers.
  • tusb_dir_t identifies IN and OUT endpoint direction.
  • xfer_result_t reports success, failure, stall, timeout, abort, or invalid transfer state.
  • tusb_buffer_t pairs a byte length with a buffer pointer.
  • Descriptor and control-request structures describe the USB wire format with fixed layout checks.

These definitions are the shared language between the USB device stack, the USB host stack, and the controller ports described by platform integration. They also carry buffer alignment and data-cache rules for endpoint memory.

References: src/…/tusb_types.h• L19-53 src/…/tusb_types.h• L60-114 src/…/tusb_types.h• L261-323 src/…/tusb_types.h• L329-376 src/…/tusb_types.h• L521-549

FIFO data paths

The TinyUSB FIFO is a byte ring buffer used to decouple USB interrupt or DMA activity from application and class-driver work. It tracks independent read and write indices, supports normal or overwritable operation, and exposes copied access plus linear buffer windows for DMA transfers.

The FIFO links runtime synchronization to USB data flow. In RTOS builds, read and write mutexes protect the corresponding side of the buffer. In single-context builds, separate indices support producer and consumer use when no other execution context interferes. An overwritable FIFO keeps the newest data by discarding the oldest data when it reaches capacity, so concurrent overflow reads can return torn data and must accept that trade-off.

DMA users can inspect the linear and wrapped windows, then advance the related index after the transfer. These index-advance operations do not perform safety checks or take mutexes. Hardware-FIFO access modes also let controller ports use a fixed register address or a required 16-bit or 32-bit access width. The selected MCU and controller rules derive these settings as described in USB controller drivers.

flowchart LR
  Producer[USB ISR, DMA, or class code] --> Write[Write side]
  Write --> Ring[Ring buffer]
  Ring --> Read[Read side]
  Read --> Consumer[USB transfer or application]
  Ring --> Window[Linear and wrapped windows]
  Window --> DMA[DMA or hardware FIFO]
  Lock[OSAL mutex when required] -. protects .-> Write
  Lock -. protects .-> Read

References: src/…/tusb_fifo.h• L22-44 src/…/tusb_fifo.h• L90-117 src/…/tusb_fifo.h• L148-172 src/…/tusb_fifo.h• L176-231 src/…/tusb_fifo.h• L255-288 src/…/tusb_fifo.c• L15-33 src/…/tusb_fifo.c• L723-815

Compiler portability

The compiler facility gives the stack one name for preprocessor helpers, compile-time checks, attributes, packing, byte order, bit-field order, and byte swapping. It also supplies shared argument-expansion helpers used by configuration macros. This keeps USB data layout and platform-specific declarations consistent across compiler families and MCU alignment rules.

Compiler support affects more than build syntax. It determines how descriptors are packed, how bit fields map to USB bytes, how endpoint buffers are aligned, and how byte-order conversion is performed. The common access helpers use packed scalar types when the target permits unaligned access and switch to byte-wise reads and writes when the MCU memory rules are stricter. The platform configuration can also require stricter handling when an MCU USB memory region cannot accept unaligned access.

References: src/…/tusb_compiler.h• L8-35 src/…/tusb_compiler.h• L37-135 src/…/tusb_compiler.h• L137-182 src/…/tusb_compiler.h• L184-279 src/…/tusb_compiler.h• L282-312 src/…/tusb_common.h• L235-297 src/tusb_option.h• L569-577 src/…/tusb_mcu.h• L15-28

Debug and fault checks

The debug and fault facilities give applications a common way to inspect USB activity and distinguish bad external data from firmware defects. CFG_TUSB_DEBUG enables error, warning, and information output. Applications can replace the default print path with CFG_TUSB_DEBUG_PRINTF, while lookup tables and buffer dumps make common USB values easier to read.

The same facility can expose stack timing through SEGGER SystemView. CFG_TUSB_SYSVIEW selects a trace level from USB interrupt activity up to class-driver calls, and the trace is active only when the related host or device stack is enabled. This gives platform work a view of where USB time is spent without changing the stack's normal control flow.

Verification macros return from invalid external-input paths. Assertion macros also report the failure and try to break into a debugger when the condition indicates a firmware error. This split lets a USB peer trigger a safe rejection without treating normal bad input as an internal crash.

References: src/…/tusb_debug.h• L19-41 src/…/tusb_debug.h• L43-82 src/…/tusb_debug.h• L94-123 src/…/tusb_debug.h• L159-180 src/…/tusb_debug.h• L182-270 src/…/tusb_verify.h• L16-42 src/…/tusb_verify.h• L48-78 src/…/tusb_verify.h• L80-113

Configuration facilities

The configuration layer turns one application header into the policy shared by the OSAL, device stack, host stack, memory paths, and USB controller ports. It selects the OS, scheduler model, include path, enabled roles, speed limits, validation level, debug and trace levels, memory placement, alignment, cache behavior, and event limits.

MCU and USB-IP selection adds the hardware facts that these policies depend on. The configuration derives hardware-FIFO access modes, data widths, address strides, DMA choices, endpoint limits, and memory rules from the selected controller and target. These defaults connect an application configuration to controller behavior without making the common stack know each MCU family.

Validation is a graded policy for data received from a USB peer. The common level applies to both roles unless a device or host override is set:

  • TUSB_VALIDATION_NONE favors small code for trusted peers.
  • TUSB_VALIDATION_BASIC enables structural memory-safety checks where supported.
  • TUSB_VALIDATION_STRICT adds USB and class-specific conformance checks.

Other configuration values fall into three related groups:

  • Execution policy: OS selection, scheduler presence, root-hub role, and maximum speed.
  • Data safety and placement: validation level, endpoint memory section, alignment, cache-line size, and cache enablement.
  • Work and visibility: enabled class drivers, task event limits, logging levels, SystemView trace levels, and optional debug hooks.

The defaults make no-OS mode the base case, then derive host and device behavior from root-port mode when the application does not set role-specific values. Controller-specific rules can add hardware FIFO, DMA, alignment, or cache requirements. The host configuration also sets the delay after a root-port reset and before speed or status is read. Its default is 2 ms, and an application can raise it for devices that need more time to respond. It also bounds control-transfer waits and sets the number of enumeration attempts so a device that stops responding does not hold host progress forever. The result is a compile-time contract that must agree with the board support definitions in board support and build targets and the selected USB controller driver.

References: src/tusb_option.h• L219-311 src/tusb_option.h• L320-475 src/tusb_option.h• L477-550 src/tusb_option.h• L552-625 src/tusb_option.h• L628-667 src/tusb_option.h• L779-845 src/…/tusb_mcu.h• L15-28 src/…/tusb_mcu.h• L153-159 src/…/tusb_mcu.h• L552-562 src/…/tusb_mcu.h• L779-847 src/…/tusb_types.h• L19-53 src/…/usbh.c• L1833-1840

Application runtime hooks

The application runtime hooks connect platform services that the common stack cannot choose by itself. They provide time and delay for no-OS or special controller paths, and they provide cache and address translation operations when USB buffers do not share the CPU's normal memory view.

The normal RTOS path supplies time and delay from the selected OSAL adapter. No-OS mode requires the application time function and derives delay from it. Cache and address hooks are weak defaults: cache operations are application responsibilities when enabled, while address conversion defaults to identity mapping when the platform has no separate physical address space.

References: src/…/tusb_common.h• L74-88 src/tusb.c• L31-60

Change checklist

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

  • Keep every CFG_TUSB_OS value aligned with a matching adapter and with CFG_TUSB_OS_HAS_SCHEDULER policy.
  • Preserve the millisecond timeout meaning when changing an adapter's tick conversion, especially for zero and forever waits.
  • Keep interrupt-context queue and semaphore behavior valid for both ISR callers and task callers.
  • Keep no-OS queue interrupt masking paired with the board's interrupt control callback.
  • Keep FIFO mutex requirements aligned with the selected OS and with endpoint stream ownership.
  • Keep FIFO DMA index updates bounded by the reported transfer windows and outside conflicting read or write operations.
  • Keep hardware-FIFO data and address stride settings aligned with the controller register access rules.
  • Keep compiler packing, bit-field order, byte order, alignment, and cache-line rules consistent with descriptor and endpoint buffer declarations.
  • Keep debug level and custom print or breakpoint hooks compatible with the application's logging and debug environment.
  • Keep SystemView category levels, event IDs, and stack/task reporting aligned with the trace decoder and the enabled host or device role.
  • Keep validation defaults and device or host overrides aligned with the peer trust and safety policy.
  • Keep host and device role, speed, memory, and event-limit defaults consistent with root-port mode.
  • Keep host enumeration timing, control-transfer timeout, and retry defaults consistent with the host state machine's recovery assumptions.
  • Keep MCU-derived controller, endpoint, speed, core, alignment, cache, hardware FIFO, and transfer-interrupt defaults aligned with the board and controller port.
  • Keep STK's selected C or C++ binding aligned with the source files and build language used by the application.

Important failure modes

TriggerConsequenceGuard
No-OS application does not provide a working tusb_time_millis_api()Timeouts can never expire and delay loops can hangProvide a monotonic millisecond source before using no-OS mode
An OSAL adapter blocks or calls a task-only API from an ISRUSB event handling can deadlock or fail in interrupt contextUse the in_isr path for queue and semaphore operations
STK receives a nonzero delay or wait shorter than one system tick and maps it to zero ticksA delay can become a no-op or a timed wait can become an immediate pollPreserve the STK adapter's minimum one-tick conversion for nonzero durations
ThreadX receives a nonzero delay or wait shorter than one system tick and maps it to zero ticksA delay can become a no-op or a timed wait can become an immediate pollPreserve the ThreadX adapter's minimum one-tick conversion for nonzero durations
ThreadX queue send runs from interrupt context as a blocking operationThe interrupt path can stall or violate ThreadX context rules when the queue is fullUse the adapter's no-wait ISR path and handle a full queue as a dropped event
RTX 4 code relies on the OSAL spin-lock calls for exclusionShared state can remain unprotected because that adapter does not implement spin-lock behaviorUse RTX mutexes or the required interrupt-context protection
A preemptive build disables the mutexes needed by FIFO or endpoint streamsConcurrent read and write state can become inconsistentKeep CFG_TUSB_OS_HAS_SCHEDULER and OSAL_MUTEX_REQUIRED aligned with the execution model
FIFO DMA advances a pointer beyond the reported linear or wrapped windowThe FIFO can report the wrong empty, full, or data stateAdvance each pointer only for data actually transferred and serialize it with the matching side
Overwritable FIFO data is read while a concurrent writer replaces the oldest itemThe consumer can receive torn data or skip or replay itemsUse overwritable mode only when loss of the oldest data is acceptable
Endpoint buffers use the wrong alignment or cache policyDMA or USB hardware can read stale or inaccessible dataMatch memory section, alignment, cache enablement, and cache-line settings to the controller
Hardware-FIFO stride does not match the controller access ruleData can be read from the wrong address or with the wrong widthUse the controller-derived data and address stride settings
Compiler packing, bit-field order, or unaligned access rules do not match the targetUSB descriptors or control requests are encoded incorrectly, or a USB memory access can faultUse the compiler and MCU portability definitions and keep compile-time layout checks enabled
A validation level is too low for the peer or differs between host and device pathsMalformed USB data can pass through checks that the application expectsSelect the shared level or role-specific override for the required trust and safety policy
Assertion and verify paths are treated as the same error classExternal malformed data can halt debugging, or firmware bugs can be silently ignoredUse verify for peer-controlled input and assert for firmware invariants
SystemView is enabled at a level that does not match the linked recorder or event mapTrace data can be absent, unreadable, or mapped to the wrong USB operationKeep the SystemView dependency, event map, category levels, and build-time trace level aligned
A host sets the root-port post-reset delay too short for a device's response timeEnumeration can read speed or status before the device is ready and restart or failRaise CFG_TUH_ENUM_RESET_ROOT_POST_DELAY_MS for the affected device while keeping it within the accepted range
A host control transfer has no effective timeoutA device that acknowledges setup but never completes the transfer can stall enumeration or hub pollingKeep CFG_TUH_CONTROL_TIMEOUT_MS finite and raise it only for devices with slow control requests
Enumeration retry count is too low for a device that recovers after a second resetA transient enumeration failure can leave an otherwise usable device unrecognizedSet CFG_TUH_ENUM_ATTEMPT_MAX to allow the required reset and retry cycle
An MCU selection has no matching controller or endpoint defaultsThe build can use an invalid controller path or an unsafe fallback endpoint limitUse a supported MCU definition and resolve any unsupported-MCU compile error or warning

Key files

FileWhy to read it
src/…/osal.hDefines the OSAL selection, timeout model, mutex policy, and porting contract.
src/…/osal_none.hShows how single-context systems provide locks, events, queues, and application-owned time.
src/…/osal_stk.hDefines the STK adapter and its C and C++ binding choices for time, synchronization, and queues.
src/…/osal_freertos.hIllustrates the RTOS adapter shape and the ISR/task split for common services.
src/…/osal_rtx4.hShows the RTX 4 mapping for time, waits, synchronization, and mailbox-backed queues.
src/…/osal_threadx.hShows the ThreadX mapping for tick conversion, task and interrupt waits, synchronization, and queues.
src/…/osal_zephyr.hIllustrates a second RTOS mapping with native kernel objects and time.
src/tusb_option.hDefines OS, scheduler, validation, role, speed, memory, debug, SystemView, host timing, retry, timeout, event, and hardware-FIFO policy.
src/…/tusb_mcu.hMaps MCU and architecture facts to controller, endpoint, speed, alignment, cache, core, FIFO, and transfer-interrupt defaults.
src/…/tusb_types.hDefines shared USB roles, transfer values, buffers, descriptors, and endpoint helpers.
src/…/tusb_fifo.hDefines the FIFO contract, DMA windows, index rules, and hardware-FIFO access model.
src/…/tusb_fifo.cShows the FIFO data movement and synchronization behavior.
src/…/tusb_compiler.hDefines compiler macros, attributes, packing, byte order, and compile-time portability checks.
src/…/tusb_debug.hDefines log levels, print hooks, SystemView trace categories, event recording, and lookup support.
src/…/tusb_verify.hDefines the return-on-error and debugger-break behavior used across the stack.
src/…/tusb_common.hConnects shared helpers with application time, cache, address, alignment, byte-order, and descriptor services.
src/…/usbh.cShows where configurable host reset delay, control timeout, and enumeration retry policy enters host enumeration timing.
src/tusb.cSupplies default runtime hooks and shows how the common OSAL services reach the public stack.