Skip to content

usb: slot endpoint model, device classes and backends - #362

Draft
Jiu-xiao wants to merge 105 commits into
devfrom
feat/usb-slot-model
Draft

Jiu-xiao wants to merge 105 commits into
devfrom
feat/usb-slot-model

Conversation

@Jiu-xiao

@Jiu-xiao Jiu-xiao commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Part 3 of the series that brings the LibXR 2.0.2 USB stack and the XR-DAP 0.6 work into dev (overview: #358). Parts 1 and 2 were #359 and #361.

The USB device stack moves to the slot model. Endpoint memory is handed to the core in slots and the controller's DMA points at the slots, so there is no separate software and hardware buffer. IN data borrows a slot (AcquireSlot), fills it and calls Submit; OUT data is armed with Receive, and the slot lent with a completion goes back with ReturnSlot (rearm) or ReleaseSlot. A handle is valid only for the lend that produced it. Each endpoint's state is one atomic word, and every class callback runs in the device's owner (SerializedService), which can be the controller interrupt or an application thread. What users of the previous stack change is listed at the end of this description; it goes into the release notes.

This is one change: after the first USB commit the classes and backends that still use the old endpoint API do not build firmware until their own commit, so the commits only make sense together. Every commit builds the host tests and passes them.

Reading order by directory:

Where Content
src/driver/usb/core ep.*, ep_pool.*: slots, the endpoint state word, the owner; the comment at the top of ep.hpp describes the model
src/driver/usb/device/dev_core*, device_class.*, device_composition.* device core, class interface, composition
src/driver/usb/device/{cdc,hid,dfu,gsusb,uac,dap} each class on the slot model; DAP commands run in an application Step() thread
src/driver/usb/backend/fsdev.hpp, fsdev.cpp FSDevDevice, the base class with the register model of the PMA-based full-speed controller (register offsets and bits, BTABLE and packet memory, reset and suspend); the device classes of driver/st and driver/ch derive from it, give the addresses of the controller and implement the pull-up
driver/st OTG and FSDEV register runtimes: no HAL PCD handle, CubeMX code taken over with --wrap
driver/ch, driver/esp CH32 and ESP32-S3 backends
test/automatic/driver/usb host tests, cases of libxr_test

Besides the model itself this part brings:

  • Documentation of every file it touches, in Chinese and English; the Doxygen warning baseline goes from 933 to 459.
  • Endpoint::Type::INTERRUPT is Endpoint::Type::INTR. The old name is a macro in the headers of one platform; the three #undef INTERRUPT workarounds (USB core, ESP driver, FreeRTOS system header) are removed.
  • A fix found while compiling the drivers against vendor headers: the STM32 DRD code took the register base from macros that the H5, U0 and U3 device headers do not define, so the driver did not compile there. They use USB_DRD_FS now.
  • Four more fixes found the same way, by compiling against the headers of more families and comparing with the ST HAL: the STM32 code for the classic FSDEV named the low-power bit of CNTR as the F1 header does, so the driver did not compile for F0, L0, L4, G4 and the other parts that call it USB_CNTR_LPMODE; the DRD code read the RX count at once, where the HAL waits PCD_RX_PMA_CNT cycles for the buffer descriptor to update; the DRD packet memory address is taken from the device header only, its distance from the register block differs between families; and on STM32L1, which has no BCDR, the driver switches the D+ pull-up through SYSCFG_PMC_USB_PU itself.
  • Link-time optimization and the --wrap takeover of driver/st: with LTO the compiler can bind a call to ST's function before the linker replaces the symbol, and which calls it does that to changes with the project and the optimization level. On the STM32H723 firmware built in Release with LTO, main called ST's HAL_PCD_Init directly while the interrupt handler still reached the wrapper; linked as a single LTO partition, the interrupt handler jumped to ST's HAL_PCD_IRQHandler as well. driver/st/CMakeLists.txt therefore compiles the HAL source that defines both functions (stm32*_hal_pcd.c) with -fno-lto in every target of the project, which leaves every reference to them to the linker; the rest of the project, LibXR included, stays in LTO. This needs CMake 3.18; an older CMake stops the configuration when LTO is on.
  • LIBXR_ALWAYS_INLINE in the endpoint core.
  • Function pointer aliases end in Fun (HardwareEnterFun, HardwareLeaveFun, CommandHookFun), and the JTAG build switch of the DAP classes is ENABLE_JTAG (was kEnableJtag; the profile headers daplink_v*_profile_*.hpp define it, so projects that select a profile by including one are not affected).
  • Members of the USB core, the FSDEV backend and the device classes that were set only in constructor lists also have a default at their declaration.
  • Two fixes brought forward from later parts so that Release builds have no warning: HardwareScope takes the pool by reference at the DeviceCore call sites (GCC reported writes to address zero through the pointer overload), and a keyboard report with more than six keys is the HID phantom state instead of a write past the report (it was an ASSERT, which Release builds do not enforce).
  • Backend fixes that a board needs at this head; most were planned for later parts (6, 16, 19 and 22 to 25), the rest were found while the boards were run. STM32 OTG: with DMA, EP0 OUT is enabled again for SETUP after an OUT transfer and after a STALL (without it an STM32H723 did not get past SET_ADDRESS); an IN endpoint whose stop is cut short by Stop() is disabled; an isochronous IN request that missed its frame ends with FAILED; one SOF is handled once where the core flags it twice. CH32, with two host tests: on USBHS a toggle advance lost while the other direction is being armed is repaired, a resent OUT packet is dropped without restarting the request, the SOF token reaches the device core, the OUT toggle is kept in software (with the SOF interrupt on the controller moves the toggle of an armed OUT endpoint), and every OUT event counts as a received packet whatever INT_ST.IS_NAK says (the flag shows up on about one real packet in two million, and dropping that packet lost it and the next one); on USBFS the shared endpoint block, small IN packets, the OUT resend, and EP0 OUT going back to NAK after each packet. ESP32-S3: the SETUP packet received last is the one processed; EP0 OUT is enabled for SETUP every time the controller disables it; EP0 IN is stopped in the hardware when a SETUP ends an IN data stage; an IN stop ends without EPDIS when the transfer has already completed; a closed endpoint is deactivated; an OUT endpoint is disabled only with the global OUT NAK in effect; every isochronous transfer is scheduled for the next frame and one that missed its frame ends with FAILED; a suspend raised inside a bus reset no longer leaves the device off the bus; the completion flag of a request that a stop has ended is not reported for the next request; Stop() confirms the endpoint stops that are still waiting; the DMA burst length is the INCR4 encoding; the paths that moved data through the FIFOs by hand, unreachable with the slot model, are removed.
  • The STM32 OTG, ESP32-S3, FSDEV and CH32 USBHS backends keep their SOF interrupt on while the device is on the bus and not suspended. They used to switch it at a few fixed points from what the classes needed, and a class that started to need frame ticks between two of those points got none. CH32 USBFS is unchanged: it enables the interrupt when a class wants bus time.
  • Two defects of the classes and the core found on the boards, each with a test. DapLinkV2Class ignored a completion that the endpoint delivers while the class is being unbound, together with the OUT slot it lends; the slot stayed void, and after two such packets the interface could not arm a receive again until power-off (seen on an ESP32-S3 probe within 20 to 40 configuration switches under OUT traffic). And a stop confirmation that a backend reports while no stop is waiting no longer ends the next stop of that endpoint.
  • Six fixes for findings of the automated review. A slot handle carries a 32-bit lend serial: the 6-bit lend count of the state word alone accepted a handle of an earlier lend again after 64 more lends of the slot. An HID send that an unbind interrupts drops only its own claim on the in-flight flag and does not submit its report in the next binding. A DAP v2 response staged for a session that has ended is dropped when the USB side sends: it carries the epoch of its command, and the comparison runs in the owner. These three have tests. Without a test, because the window is between two adjacent statements: DFU writes the start time of a step before it publishes RUNNING; the DAP v2 Step thread reads the IN endpoint through an atomic reference; gs_usb keeps the USER_ID RAM value in an atomic.

Behaviour changes for users:

Review focus:

  • src/driver/usb/core/ep.cpp and ep_pool.cpp: the state word transitions, unbind while a slot is lent (the slot turns stale, the holder gets ABORTED), and the owner hand-off between the interrupt and a thread (RequestService).
  • Any application thread can become the owner and run class callbacks while the interrupt only publishes work, so a low-priority thread that owns delays control transfers until it runs. The documentation of DeviceClass states the priority requirement; the model is unchanged.
  • src/driver/usb/backend/fsdev.hpp sits in src/ because it is a register model used by several platforms. A platform's device class passes the register and packet-memory addresses to the base class and implements Connect(); registers are read and written through two virtual functions, and the 32-bit DRD layout of the newer STM32 parts is a set of overrides in driver/st. driver/st checks the register offsets and bits of each device header against the constants of the base class with static_assert.

Not in this part:

  • Several defects in this code are fixed later in the series, each with a test. DAP v2 losing the OUT slots it holds when the session resets is in part 4. The DFU error kept across a stalled DNLOAD is in part 8. The UAC SET_RES data stage and the gs_usb lease counted as an armed receive are in part 12. The zero-padded DAP command groups are in part 13.
  • The host tests of the DWC2 backends (STM32 OTG, ESP32-S3) run against a model of the controller, which comes in a later part; the backend fixes listed above are here without them.
  • SOF on CH32 USBFS is enabled only while a class wants bus time, as before. No board with a USBFS device port whose header defines the device SOF bits was at hand to measure what a permanently enabled SOF interrupt does to bulk traffic there; on USBHS the measurement changed the driver (see above).
  • Platform delay loops for SwdGeneralGPIO other than the STM32 one.
  • LibXR on one STM32 USB controller and ST's middleware on another in the same project: the HAL_PCD wrappers act for every controller, and driver/st/stm32_usb_wrap.cpp states the restriction.

Tests: ten cases in libxr_test (usb_endpoint, usb_fsdev, usb_cdc_test, usb_cdc_uart, usb_hid, usb_dfu, usb_gsusb, usb_uac_mic, usb_daplink_v1, usb_daplink_v2) and two separate programs, ch32_usbhs_in and ch32_usbfs, which compile a CH32 endpoint source against a fake vendor header. The tests sit in the directories of the sources they test; the endpoint double and the other shared fixtures are in *_test_common.hpp. The threaded DAP tests and the DFU detach test wait for the state they need (WaitUntil) instead of sleeping a fixed time; 150 runs of the three cases on a fully loaded host passed.

Verification:

  • Host tests: every commit builds and passes ctest in Debug + LIBXR_DEV_ASSERT_BUILD. The head passes 12/12 with no compiler warning in Debug + LIBXR_DEV_ASSERT_BUILD and in Release with and without dev asserts, and under TSan without a report. Under ASan+UBSan all tests pass with no ASan report and no UBSan report in USB code; the big suite needs more than the 300 s ctest gives it there, so it was run directly.
  • clang-format passes; Doxygen reports 459 warnings, none in a file of this part.
  • Platform code the host tests do not compile was compiled against vendor headers at the head: the STM32H723 (MC02) firmware builds without warnings; the STM32 OTG driver compiles with the ST headers of STM32F107, F407, H723, L476, U575 and U5A5; the FSDEV backend and the STM32 FSDEV driver compile with the ST HAL headers of fifteen families, which cover each way the packet memory is accessed: STM32F103, F302 and L152 (16-bit words at every second address), STM32F072, L052, G431, L433, L552 and WB55 (contiguous 16-bit words) and STM32G0B1, C071, U083, H563, U385 and U545 (32-bit, DRD variant); the six CH32 USB sources and the FSDEV backend with the CH32V30x and the CH32V20x SDK headers; the ESP driver sources and the USB core with the compile commands of an ESP-IDF 5.5.2 ESP32-S3 project. The DAP v2, HID, DFU and gs_usb class templates are instantiated in full for Cortex-M3 with -Wall -Wextra, without a warning.
  • The packet memory sizes per family agree with the table of TinyUSB's FSDEV driver; the F3 sizes, their sharing with CAN and the access scheme were read in RM0365 (table 172) and RM0316 (table 178), the L1 pull-up in RM0038 (section 24.4.2). The contiguous 16-bit and the DRD variants are covered by compilation only.
  • Hardware at this head. The CMSIS-DAP probe images also carry part 4, which changes only the DAP class. An STM32H723 board (OTG HS core with the embedded full-speed PHY, DMA, 8-byte EP0) enumerates: the host reads the descriptors and strings and sets the address; its data endpoints were not exercised; it also enumerates with the firmware built in Release with CMAKE_INTERPROCEDURAL_OPTIMIZATION=ON (every C and C++ source in LTO except stm32h7xx_hal_pcd.c; both wrappers are reached and ST's two functions are not in the image). An ESP32-S3 probe (DAP v2 and CDC): 200 SET_CONFIGURATION 0/1 cycles, 300 more with an IN read pending, 100 with the host streaming bulk OUT at full rate, 50 port resets, 200 back-to-back switches and endpoint halts, 10000 DAP_Info round trips, responses of 64 to 1024 bytes, the CDC console and 30 autosuspend cycles pass, and the device is never enumerated again; after each of 30 stops and starts of the USB device under DAP traffic the probe answers; with a UAC microphone added, recordings of 5 s and 30 s are continuous (5000 of 5000 frames carry data), and 30 stream starts and stops and 150 port resets leave the device enumerated. The case with the streaming host used to lose the first DAP answer after the switch in about half of the cycles, for two reasons: the DapLinkV2Class defect listed above, and the test itself, because after a transfer error the Linux xHCI driver does not reset its data toggle on the first clear-halt, so the test now clears each halt twice. A CH32V307 USBHS probe, with the SOF interrupt on and about 8000 frame ticks per second reaching the device core: three runs of 1500 1024-byte, 900 512-byte and 6000 DAP_Info round trips and 70 runs of 100000 pipelined DAP_Info commands (four in flight) without an error. CH32 USBFS and the FSDEV backend were not run at this head; of FSDEV only the packet memory variant of F1 has run on a board (STM32F103 and CH32V203, an earlier state of this code). ESP32-S2 is not built by this part.
Notes for users of the previous stack (for the release notes)

从 2.0.2 起,端点缓冲改由槽模型统一管理:端点内存以"槽"为单位交给核心,硬件 DMA 直接指向槽,
不再区分软件缓冲与硬件缓冲。旧写法全部编译失败,不提供兼容垫片 / Starting with 2.0.2, endpoint
buffers are managed by the slot model: endpoint memory is handed to the core in slots and the
hardware DMA points at the slots directly; there is no separate software buffer and hardware
buffer. Old code fails to compile and no compatibility shims are provided.

使用方需要做的事 / What users need to change:

  • 端点缓冲区数组放在 DMA 可访问的内存段(LIBXR_DMA_BUFFER)并按 cache line 对齐,
    每个单向端点块长不小于 2 倍最大包长 / Put the endpoint buffer arrays in a DMA-accessible
    section (LIBXR_DMA_BUFFER) and align them to the cache line; each single-direction endpoint
    block is at least twice the maximum packet size.
  • 设备构造函数按平台接收端点列表。CH32 OTG FS/HS 接收 RX、TX 两个列表,下标就是端点号(EP0 第一项),
    EP0 的 RX[0] 与 TX[0] 是同一块,缺席的方向传 {nullptr, 0}。STM32 OTG FS/HS 接收 HardwareConfig
    (PHY、DMA、VBUS 检测、是否以高速枚举、使用 DMA 时的 EP0 OUT 缓冲)、RX FIFO 字节数、RX 列表和
    {槽内存, TX FIFO 字节数} 的 TX 列表;STM32 FSDEV 接收 {槽内存, PMA 字节数} 的 RX、TX 列表。用
    CodeGenerator 生成的 STM32 工程需要配套版本的 CodeGenerator。ESP32-S3 保持逐端点声明 / Device
    constructors take endpoint lists per platform. CH32 OTG FS/HS take an RX and a TX list indexed by
    endpoint number (EP0 first); EP0's RX[0] and TX[0] are the same block, and an absent direction
    passes {nullptr, 0}. STM32 OTG FS/HS take a HardwareConfig (PHY, DMA, VBUS sensing, whether to
    enumerate at high speed, the EP0 OUT buffer used with DMA), the RX FIFO size, an RX list and a TX
    list of {slot memory, TX FIFO bytes}; STM32 FSDEV takes RX and TX lists of
    {slot memory, PMA bytes}. STM32 projects generated by the CodeGenerator need the matching
    CodeGenerator release. ESP32-S3 keeps the per-endpoint declaration.
  • CH32:没有后端使用的通用类 CH32USBDevice 和枚举 ch32_usb_dev_id_t 已删除;设备类是
    CH32USBDeviceFS、CH32USBOtgFS 和 CH32USBOtgHS / CH32: the generic class CH32USBDevice, which
    no backend used, and the enum ch32_usb_dev_id_t are removed; the device classes are
    CH32USBDeviceFS, CH32USBOtgFS and CH32USBOtgHS.
  • driver/st 以 -Wl,--wrap=HAL_PCD_Init 和 -Wl,--wrap=HAL_PCD_IRQHandler 链接,CubeMX 生成的代码
    保持原样:MX_USB_*_PCD_Init() 不再初始化控制器,CubeMX 生成的中断函数进入 libxr 的驱动。包装对
    工程里所有 USB 设备控制器生效,同一个工程里不允许一个控制器用 libxr、另一个用 ST 中间件。开启链接时
    优化(LTO)的工程:libxr 的 CMake 让 stm32*_hal_pcd.c 不参与 LTO,要求 CMake 3.18 及以上(更低的
    版本在开启 LTO 时配置报错);不用 CMake 的工程需要自己给这个文件加 -fno-lto /
    driver/st links with -Wl,--wrap=HAL_PCD_Init and -Wl,--wrap=HAL_PCD_IRQHandler, so the CubeMX
    code stays as generated: MX_USB_*_PCD_Init() no longer initializes the controller and the CubeMX
    interrupt handler enters the libxr driver. The wrappers act for every USB device controller of the
    project; using libxr on one controller and ST's middleware on another in the same project is not
    allowed. With link-time optimization (LTO), libxr's CMake keeps stm32*_hal_pcd.c out of LTO, which
    needs CMake 3.18 (an older CMake stops the configuration when LTO is on); a project that does not
    use CMake has to compile that file with -fno-lto itself.
  • 只有 ESP32 的时基为驱动注册毫秒节拍(ESP32-S3 USB 后端的停止超时用它);STM32、CH32、HPM 和 MSPM0
    的时基与之前相同,不占用 HAL_IncTick、vApplicationTickHook 或 SysTick_Handler,也不要求
    configUSE_TICK_HOOK / Only the ESP32 timebase registers a millisecond tick for the drivers (the
    ESP32-S3 USB backend's stop timeout uses it); the STM32, CH32, HPM and MSPM0 timebases are unchanged
    and take none of HAL_IncTick, vApplicationTickHook or SysTick_Handler, nor do they require
    configUSE_TICK_HOOK.
  • DFU 运行时和 DFU 引导程序不创建 Timer 任务:擦写等慢操作和 DETACH 后的跳转都在应用调用 Process()
    的上下文里进行,DFUClass::Process() 是新接口 / The DFU runtime and the DFU bootloader create no Timer
    task: erase/program and the jump after DETACH run in the context that calls Process();
    DFUClass::Process() is new.
  • CDC:CDCUart 接受任何 7 字节的 SET_LINE_CODING;CDCToUart 不再 STALL,应用 UART 能接受的最接近的
    配置,GET_LINE_CODING 返回实际生效的值 / CDC: CDCUart accepts every 7-byte SET_LINE_CODING;
    CDCToUart never STALLs it, applies the nearest configuration the UART accepts, and GET_LINE_CODING
    returns the applied value.
  • ESP32-S3 的端点缓冲必须在 DMA 可用的内存里,起点按 64 字节对齐,构造时检查。EP0 缓冲对半分给 OUT 和
    IN,至少 2 倍 EP0 包长(64 字节包长用 128 字节)/ On ESP32-S3 the endpoint buffers must be in
    DMA-capable memory and start on a 64-byte boundary; the constructor checks it. The EP0 buffer is split
    in halves for OUT and IN, so it is at least twice the EP0 packet size (128 bytes for 64-byte packets).
  • 后端从 DeviceCore<Capabilities> 派生:FullSpeedCapabilities 或 HighSpeedCapabilities 给出支持的
    速度和 BOS、总线时间两项功能。原来的 DeviceCore::Context 改名为 ControlContext。设备核心在总线复位
    时读一次总线速度;控制器在速度协商结束前就报告复位时,后端要在速度确定后再报告一次复位 / Backends
    derive from DeviceCore<Capabilities>: FullSpeedCapabilities or HighSpeedCapabilities names the
    supported speeds and the BOS and bus-time features. The former DeviceCore::Context is now
    ControlContext. The device core reads the bus speed once, at the bus reset; a controller that
    reports the reset before speed negotiation ends has to report the reset again once the speed is
    known.
  • 端点完成回调的签名是 Callback<const Endpoint::Completion&>,经 Endpoint::SetOnComplete() 设置,
    Completion 带结果、实际字节数和 OUT 租约的槽。IN 数据用 AcquireSlot() 借槽、写入后 Submit();OUT
    数据用 Receive() 挂接收,完成时借出的槽用 ReturnSlot() 归还并重新挂接收,或用 ReleaseSlot() 只
    归还。每次借出的句柄只在这一次借出内有效,重复归还或用旧句柄归还得到 STATE_ERR / The endpoint
    completion callback is Callback<const Endpoint::Completion&>, set with Endpoint::SetOnComplete();
    a Completion carries the result, the byte count and the slot of an OUT lease. IN data borrows a
    slot with AcquireSlot(), fills it and calls Submit(); OUT data is armed with Receive(), and the
    slot lent with a completion goes back with ReturnSlot() (rearming) or ReleaseSlot() (no rearm).
    A handle is valid only for the lend that produced it; a double return or a return through an older
    handle gets STATE_ERR.
  • 解绑、Flush 或 STALL 结束的请求以 ErrorCode::ABORTED 完成;解绑之前借出的槽在 Submit() 或
    ReturnSlot() 时得到 ABORTED,槽回到空闲 / Requests ended by an unbind, a flush or a STALL complete
    with ErrorCode::ABORTED; a slot lent before an unbind gets ABORTED from Submit() or
    ReturnSlot() and becomes free.
  • 类回调(BindEndpoints/UnbindEndpoints、OnDeviceEvent、控制请求、OnService、OnBusTime、端点完成)都在
    设备的 owner 中执行。owner 由赢得 SerializedService::Invoke 的调用者执行:控制器中断,或者任何调用
    Submit/Receive/ReturnSlot/RequestClassService/Init 的应用线程,所以每个回调都可能在中断里
    (in_isr=true)或任意应用线程里(in_isr=false)运行,必须不阻塞。线程持有 owner 时,中断只发布工作,
    要等这个线程处理。所以调用这些接口的线程优先级不能太低:它持有 owner 时被抢占,控制传输和端点完成都要
    等它恢复运行 / Class callbacks (BindEndpoints/UnbindEndpoints, OnDeviceEvent, control requests,
    OnService, OnBusTime, endpoint completions) all run in the device's owner. The owner pass runs in
    whichever caller wins SerializedService::Invoke: the controller interrupt, or any application
    thread that calls Submit/Receive/ReturnSlot/RequestClassService/Init. Every callback can therefore run
    in an interrupt (in_isr=true) or in an arbitrary application thread (in_isr=false), and must not
    block. While a thread owns, interrupt work is only published and waits for that thread. A thread
    that calls these interfaces therefore must not run at a low priority: when it is preempted while it
    owns, control transfers and endpoint completions wait until it runs again.
  • Endpoint::Type::INTERRUPT 改名为 Endpoint::Type::INTR:原来的名字与某些平台头文件里的宏同名 /
    Endpoint::Type::INTERRUPT is now Endpoint::Type::INTR: the former name is a macro in the headers
    of some platforms.
  • 总线复位以 DeviceEvent::RESET 通知各设备类(OnDeviceEvent);后端不另外提供复位计数 / A bus reset
    reaches every class as DeviceEvent::RESET (OnDeviceEvent); backends provide no separate reset
    counter.
  • DapLinkV1Class 和 DapLinkV2Class 不在 USB 上下文里执行命令:应用起一个线程循环调用 Step(),例如
    while (true) { dap.Step(); },SWD/JTAG 操作只在这个线程里发生(SWD 引脚须能在该线程所在的核上
    使用),延时类命令也在这个线程里等待。Bind/Unbind 只发布会话开始/结束,由 Step 线程关闭 SWD、复位 DAP
    状态;绑定变化前取到的命令被丢弃而不执行 / DapLinkV1Class and DapLinkV2Class do not execute
    commands in the USB context: the application starts one thread that calls Step() in a loop, for
    example while (true) { dap.Step(); }. All SWD/JTAG work happens in that thread (the SWD pins must be
    usable from its core), and delay-type commands wait in it. Bind/unbind only publish the start or end
    of a session; the Step thread closes SWD and resets the DAP state, and a command taken before the
    binding changed is dropped, not executed.
  • DapLinkV2Class 去掉了模板参数 QueuedRequestBufferSize 和 QueuedCommandCountMax:每个
    DAP_QueueCommands / DAP_ExecuteCommands 包就地执行自己的命令 / DapLinkV2Class drops the template
    parameters QueuedRequestBufferSize and QueuedCommandCountMax: every DAP_QueueCommands /
    DAP_ExecuteCommands packet runs its own commands in place.
  • DapLinkV1Class::Step() 是新接口,DAP v1 不再注册 Timer 任务 / DapLinkV1Class::Step() is new, and
    DAP v1 no longer registers a Timer task.
  • DapLinkV2Class 的两个数据端点都用借用模式:OUT 每个包借给回调、拷进命令池后立即归还,两个槽交替接收;
    IN 方向的响应直接写进一个空闲的 IN 槽并提交,只有两个 IN 槽都在用时才先写进类里的暂存区,等 IN 槽空出后
    拷进去提交。通告给主机的 DAP 包长取配置值与 IN 槽容量中较小者,所以 IN 端点的缓冲块要不小于 2 倍 DAP
    包长(1024 字节包长用 2048 字节);在途命令数为 4 / DapLinkV2Class uses borrow mode on both data
    endpoints: every OUT packet is lent to the callback, copied into the command pool and given back at
    once, and the two slots alternate. A response is written straight into a free IN slot and
    submitted; only while both IN slots are busy is it staged in the class first and copied into an IN
    slot when one is free. The DAP packet size announced to the host is the smaller of the configured
    value and an IN slot, so the IN endpoint block must be at least twice the DAP packet size (2048 bytes
    for a 1024 byte packet); four commands are in flight.
  • 串口上的 DAP 传输(DapSerialTransport)不在 libxr 中,由 XR-DAP 固件提供 / The DAP transport over a
    serial link (DapSerialTransport) is not part of libxr; the XR-DAP firmware provides it.
  • MS OS 2.0 描述符集由 DeviceComposition 生成:类用 GetWinUsbInterfaceGuid() 声明自己需要 WinUSB,
    单个功能的非复合设备用设备级形式(否则 Windows 不绑定,问题代码 28),其余用配置/功能子集形式。
    DapLinkV2Class::GetWinUsbMsOs20DescriptorSet 和 DAP 自带的 BOS 能力已删除,改用
    DeviceComposition::WinUsbBosCapability()。DFU 类的构造函数去掉了 WinUSB vendor code 参数,vendor code
    由组合设备的 WinUSB BOS 能力给出 / The MS OS 2.0 descriptor set is built by DeviceComposition: a class declares that it
    wants WinUSB through GetWinUsbInterfaceGuid(), a single function on a non-composite device gets the
    device-level form (otherwise Windows does not bind, problem code 28) and every other case the
    configuration/function subset form. DapLinkV2Class::GetWinUsbMsOs20DescriptorSet and the BOS
    capability of the DAP class are gone, use DeviceComposition::WinUsbBosCapability(). The DFU class
    constructors no longer take a WinUSB vendor code; the WinUSB BOS capability of the
    composition supplies it.
  • HID 的 SET_IDLE 只记录空闲率,可由 GetIDLERate() 读出,类不按空闲率重发报告 / HID SET_IDLE only
    records the idle rate, readable through GetIDLERate(); the class does not resend reports by it.
  • HID::SendInputReport 与 CDC::SendSerialState 新增 in_isr 参数 / HID::SendInputReport
    and CDC::SendSerialState take a new in_isr argument.
  • 传入 Database 的 GsUsbClass 在构造时创建 user_id 键,Database 须先于它就绪,键添加失败为致命错误 / A GsUsbClass given a Database creates the user_id key at construction; the Database must be ready before it, and a failed key add is fatal.

Cortex-M0+ has no exclusive-access instructions, so GCC lowers a 4-byte
std::atomic fetch_and to a call to __atomic_fetch_and_4. The USB endpoint
core added later in this series clears state bits with fetch_and, and on
MSPM0 parts without a USB peripheral the DAP v2 class vtable still links
that code. The helper masks interrupts like the existing fetch_or.
Endpoint memory is handed to the core in fixed slots and the hardware DMA
points at the slots directly; there is no longer a software buffer next to
a hardware buffer. This is a breaking change for backends, classes and the
code that declares endpoint buffers. The platform backends and the other
classes follow in the next commits; until then only the host build and the
CDC class build against the new core.

Endpoint (usb/core):
- An endpoint owns one (EP0) or two slots for its lifetime. Slot memory
  must be cache-line aligned and a cache-line multiple; a slot that cannot
  hold one packet is NO_BUFF. Packet sizes are explicit and checked against
  the endpoint type and the bus speed.
- Classes borrow a slot, fill or read it in place, and submit or release
  it. A slot handle carries the lend it came from: Submit, ReleaseSlot and
  ReturnSlot reject a handle from an earlier lend (double release, release
  after an ABORTED submit) with STATE_ERR and leave the current holder's
  lease alone.
- A completion carries the slot, the length and a status; a transfer
  cancelled by a stop or an unbind completes with the new
  ErrorCode::ABORTED.
- Progress runs in one owner context per device, whichever context wins
  the serialized service: the controller interrupt or an application
  thread that submits, returns a slot, requests class service or inits the
  device. Every class callback may therefore run in an interrupt or in an
  application thread and must not block; the headers state this per
  callback. Interrupt handlers record events in a pending bitmap and wake
  the owner. Endpoint stops are bounded by a frame count. The request-path
  helpers are forced inline.
- usb_macro_guard.hpp drops the Xtensa INTERRUPT macro before every use of
  Endpoint::Type::INTERRUPT, independent of include order.

Device core:
- DeviceCore<Capabilities> serializes the device lifecycle (reset, address,
  configuration, suspend) with the endpoint owner; BOS, bus time (SOF) and
  high speed are compile-time capabilities of the backend. The bus speed is
  taken at the bus reset (USB 2.0 7.1.7.5).
- DeviceCore::IsConfigured() tells, from any context, whether the host has
  selected a non-zero configuration.
- DeviceComposition builds the MS OS 2.0 descriptor set from the WinUSB
  interface GUIDs its classes declare (GetWinUsbInterfaceGuid): the
  device-level form for a single-function non-composite device, which
  Windows requires, and configuration/function subsets otherwise.
- Classes that need SOF timing say so (WantsBusTime/OnBusTime).

CDC (CDCUart, CDCToUart, cdc_test) on the slot model:
- Bulk endpoints use 64/512-byte packets and arm one packet per request;
  SendSerialState takes in_isr.
- SET_LINE_CODING is acknowledged for every 7-byte coding. CDCToUart
  applies the nearest configuration its UART accepts (1 stop bit, then no
  parity, then 8 data bits, then the previous coding) and GET_LINE_CODING
  returns the applied value; on dev it returned the host's value even when
  the UART rejected it.
- CDCUart::SetConfig documents its single-writer rule.

Host tests drive the endpoint core, the device core and the CDC classes
through a mock endpoint; they replace the old CDC test.

GCC 14 reports the atomics reached through the endpoint pool reference as
writes to address zero, so -Wstringop-overflow is off for the affected
files.
Input reports are written into a borrowed IN slot and submitted;
SendInputReport takes in_isr. Output reports arrive as OUT leases that are
returned after the callback. SET_IDLE stores the idle rate and GET_IDLE /
GetIDLERate() return it, as before; the class does not resend reports by
the rate.
- Both DFU classes declare their WinUSB GUID; the composition builds the
  MS OS 2.0 set, so the vendor-code constructor parameter is gone.
- The control-transfer data stage uses the core-owned EP0 slot; a DNLOAD
  data stage shorter than wLength is rejected.
- The dfuDNBUSY/dfuMANIFEST poll deadline is set when the GETSTATUS answer
  is sent, so a host that waits exactly bwPollTimeout is not stalled, and
  bwPollTimeout reports the duration of the last write step of the same
  kind. A GETSTATUS that really comes early is still stalled (DFU 1.1).
- Slow work runs in the context that calls Process(): flash erase and
  program in the bootloader (DFUClass::Process(), new), the jump after
  DETACH in the runtime. No Timer task is created in a constructor.
- Bulk OUT frames arrive as leases; a lease that cannot be queued is held
  and the receive is re-armed when it is returned.
- Each channel has its own receive queue and its own error-frame queue
  (error frames come from the CAN error interrupt, data frames from the
  receive interrupt, which may run at different priorities). Echo frames
  go first, then the channels in turn, error queue before data queue.
- GsUsbClass given a Database creates the user_id key at construction.
A frame dropped because a channel's receive queue was full was lost
silently. The class now counts the drop and sets GS_CAN_FLAG_OVERFLOW on
that channel's next frame of any kind, echo included. This is what the
Linux gs_usb driver expects: it checks the flag on every frame it accepts
from the channel, RX or echo, counts one RX overflow per flagged frame and
queues its own CAN_ERR_CRTL_RX_OVERFLOW error frame. The flag rides on a
real frame; no extra frame is invented.
Streaming is paced by the SOF tick through WantsBusTime/OnBusTime while the
class is bound. Alternate-setting changes and failed transfers are handled
in the owner context: a FAILED completion only marks the stream for
recovery, and the next SOF re-configures the endpoint. An intentional
ABORTED stop does not re-arm the stream.
The STM32 backends drive the controllers through their registers instead of
the HAL PCD layer:
- OTG FS/HS: a register runtime with the FIFO layout and DMA on parts that
  have it. A stop that the core never confirms takes the device off the
  bus, completes every waiting stop and reports a disconnect; the device
  stays off until the application calls Stop() and Start().
- FSDEV and DRD: a shared runtime in src/driver/usb/backend/fsdev.hpp with
  PMA layout checks, also used by the CH32 DevFS backend; host-tested
  against a fake controller.

HAL_PCD_Init and HAL_PCD_IRQHandler are wrapped at link time
(-Wl,--wrap), so a BSP's CubeMX output stays as generated: the CubeMX init
call and interrupt handler reach the libxr runtime.

Constructors change: OTG devices take a HardwareConfig instead of a
PCD_HandleTypeDef, and FSDEV devices take RX/TX endpoint lists with their
PMA sizes. The handle-based STM32 device and endpoint classes are removed.
Generated STM32 projects need the matching CodeGenerator release.
- DevFS (USBD) runs on the shared FSDEV runtime.
- OTG FS and USBHS take RX/TX endpoint lists (EP0 first) and use the slots
  as their DMA buffers; IN transfers are split into packets and complete
  only for data the host acknowledged.
- USBHS: an IN packet the host ACKed is found by its data toggle. INT_ST
  can report a busy NAK for it, which made a multi-packet response repeat
  its first packet.
- USBHS reports the bus speed again when it changed after the bus reset:
  the controller still reads full speed at the reset, before the
  high-speed chirp has finished, so at the first SETUP after a reset the
  backend re-reports the reset at the negotiated speed. A high-speed device
  then answers GET_DESCRIPTOR with its high-speed configuration.
- Clearing an EP0 halt keeps the DATA1 toggle that the next SETUP restores.
- ch32_usb_guard.hpp holds the interrupt guard shared by the backends.

The USBHS IN path is host-tested against a fake register block.
- Endpoints use the slots as DMA buffers. EP0 OUT and IN get separate
  halves of the EP0 buffer, so it is at least twice the EP0 packet size.
- Every controller wait on the reset and close paths is bounded. A stop
  that times out escalates to a controller reset on the millisecond tick
  (DriverAsyncCondition), after which the global interrupt is enabled
  again before the device reconnects. The ESP32 timebase registers that
  tick as a FreeRTOS tick hook on CPU 0, skipped while the flash cache is
  off.
- The deferred class service runs after the hardware guard is released.
- IN endpoint numbers the controller cannot serve are rejected.
- Commands run in an application thread that calls Step(), not in the USB
  context. All SWD/JTAG traffic happens in that thread, and DAP_Delay,
  DAP_ResetTarget and DAP_SWJ_Pins wait in it with the same timing as
  before. Bind and unbind only publish the start or end of a session; the
  Step thread closes SWD, sets the default clock and resets the DAP state,
  and a command taken before the binding changed is dropped, not executed.
- Command and response channels are SlotPools sized to the number of
  commands advertised in flight. Both data endpoints use borrow mode. A
  response is written straight into a free IN slot; only when both IN
  slots are busy is it staged and copied in later from the USB side, so
  execution runs ahead of the host.
- The next command is received while one executes. A command ends at its
  own length; padding after a whole-packet command is consumed. A ZLP
  follows only responses shorter than the DAP packet size. DAP_TransferAbort
  gets no response, as in CMSIS-DAP.
- DAP_ExecuteCommands answers [0x7F, NumCmd, responses...]; a
  DAP_QueueCommands packet runs like DAP_ExecuteCommands and is answered in
  that format, one response per packet, as in the CMSIS-DAP reference
  implementation. Every packet runs its own commands in place, so the
  template parameters QueuedRequestBufferSize and QueuedCommandCountMax
  are gone.
- ExecuteExternal() runs one command in the caller's thread, for transports
  other than USB.
- The class declares its WinUSB GUID; the composition builds the MS OS 2.0
  descriptors.
SetCommandHook() installs a function that sees every command before the
standard dispatch, from USB as well as from ExecuteExternal(). Returning
true means it handled the command and wrote the response. Probe firmware
uses it for vendor commands shared by all transports.
At the end of a DAP_Transfer or DAP_TransferBlock with a posted AP write,
the probe read DP CTRL/STAT to collect the write's result. The DP answers
that read at once even while the AP write is still pending, so the probe
stopped SWCLK with the write in flight; with a slow AP (flash programming
at high SWD clocks) the DP discarded the write and the next packet got
FAULT. RDBUFF answers WAIT until the write is done, as in the CMSIS-DAP
reference. The check reuses the RDBUFF read helper.
DAP v1 (HID) runs its commands in an application thread through Step(),
like DAP v2; it no longer executes in the USB callback or in a Timer task.
OUT reports are handed to Step through a two-entry queue that holds the
lease and the session it came from, so two reports that arrive close
together are both answered in order and none overwrites the other. Step
submits the response itself, drops a command or response from an earlier
binding, and never releases a slot after a submit that returned ABORTED.
Bind and unbind do not touch SWD; the Step thread does.
The USB README lists what users of the previous USB stack must change:
endpoint buffer placement and alignment, the per-platform constructors,
the STM32 --wrap link options, the owner-context rule for class
callbacks, slot-handle validity, ErrorCode::ABORTED, the completion
callback signature, DeviceEvent::RESET, the Step() thread of the DAP
classes and their removed template parameters, the DFU Process() model,
the CDC line-coding behaviour, the HID idle rate, and that the serial DAP
transport lives in the XR-DAP firmware.
Comments for the endpoint pool, endpoints, device core, class interface, composition,
the device classes and the STM32, CH32 and ESP32 USB backends. Doxyfile expands the
packing macros so that packed structs are parsed.
…ted case

The endpoint core uses LIBXR_ALWAYS_INLINE instead of the GCC attribute. The FSDEV
case forks, so it runs isolated and without PlatformInit, and it checks the result of
Endpoint::Configure().
Bus time instead of frame ticks, the SET_ADDRESS result, the SOF interrupt in the
FSDEV Start(), the DFU busy states and abort, DFU inited_, and the OTG StallHardware.
…r names in src

The FSDEV hardware traits use upper-case constants like the rest of src/; the PMA step
is PMA_WORD_STRIDE because the vendor HAL defines PMA_ACCESS as a macro.
Endpoint::Type::INTERRUPT is INTR: the old name collided with a vendor macro, which
needed #undef workarounds in the USB core, the ESP driver and the FreeRTOS system
header; all three are removed. Comments in the generic USB sources no longer name chip
families or vendors.
The DRD traits took the register base from USB_DRD_FS_BASE or USB_BASE. The device
headers of H5, U0 and U3 define neither (they have USB_DRD_BASE), so the driver did not
compile there. USB_DRD_FS is defined by every family with this controller.
Each USB test sits in the directory named after the source file it tests, as
test/README.md describes. The endpoint double, recorder and fixture come from
driver/usb/usb_test_common.hpp (the endpoint and UAC tests had their own copies);
RamFlash moves to device/usb_device_test_common.hpp and FakeSwd to
device/dap/dap_test_common.hpp, each shared by two tests.
File headers describe what each test covers; the comments are Chinese and English.
Two CDC tests get their includes in formatter order.
The files of the slot model are documented, so the count drops from 933.
… call sites

GCC at -O2 followed the null-pointer path of the pointer overload into the pool's
atomics and reported writes to address zero (-Wstringop-overflow) in every translation
unit that inlines the device core. The pool of a DeviceCore is never null.
…six keys

PressKey guarded its six-slot key array with an ASSERT only, so a build without
assertions wrote past the array when it was given more than six keys.

More than six keys is now the phantom state of the HID specification: all six key
slots hold ErrorRollOver (0x01) and the modifiers are reported unchanged. Six or
fewer keys behave as before. The test presses six and seven keys.
Both programs carried their own copy of the storage block, the completion
recorder, the address helper and the assertion exit. The block and the recorder
come from usb_test_common.hpp, the rest is in ch32_test_common.hpp. The USBFS
program runs all its cases, as the USBHS one does.
The comment of the old behaviour, restarting the request, was still there under
the new one.
The STM32 OTG, ESP32 and FSDEV backends decided at a few fixed points whether
their SOF interrupt should be on: STM32 OTG and ESP32 in UpdateTick (start, a
stop starting, all stops settled, a TX FIFO flush finishing), FSDEV in
OnStopsSettled. The decision looked at WantsBusTime(), at pending stops and at
pending flushes.

That design has a hole. A class that comes to need frame ticks between two of
those points gets none until the next one. Measured on an STM32H723, a host
that selects the UAC streaming alternate setting directly, without the usual
0 then 1 sequence, received one packet and then silence, because no
re-evaluation ran after the class started to need ticks. Every new hook point
only moves the hole.

In these three backends the SOF interrupt is now enabled while the device is on
the bus and not suspended, and for no other reason:

- STM32 OTG: unmasked with the other device interrupts in Connect(), again at
  enumeration done, and at resume; masked at suspend, at session end, in Stop()
  and when a stop timeout takes the device off the bus.
- ESP32: unmasked with the other interrupts when the register baseline is
  rebuilt, at a bus reset and at resume; masked at suspend, and by the
  existing clear of the whole mask in Stop() and in the controller reset.
- FSDEV: SOFM is set in Start(), at a bus reset and at resume, cleared at
  suspend and in Stop().

The conditions that were only there to follow the classes are removed:
OnStopsSettled() (every override only re-evaluated the interrupt), UpdateTick()
of STM32 OTG and ESP32 with its call sites in the endpoints, and the connected_
flag of FSDEV that only guarded OnStopsSettled().

What the interrupt serves inside the backends keeps working because it is now
on in every state in which it can be needed: the stop timeout counts frames in
DeviceCore::OnSof, STM32 OTG checks a running TX FIFO flush at the end of
every interrupt and polls a pending stop on every SOF. While the bus is
suspended no frame arrives, so a stop that is pending at that moment is not
counted towards its timeout and is confirmed by its own endpoint interrupts or
at the first frame after the resume, as before.

DeviceCore::OnSof still posts the tick event only when some active class
needs ticks, so classes get the same ticks as before and with no class needing
them the SOF interrupt costs the backend handler and that check. Measured on an
STM32H723 at 550 MHz, a SOF-only interrupt takes about 450 to 530 cycles, which
is about 0.2 % CPU at 2000 interrupts per second.

CH32 OTG FS and HS are unchanged: they enable the SOF interrupt from
WantsBusTime() when the control endpoint becomes ready. Their endpoint stops
are synchronous, so nothing inside these backends needs frames. On a CH32V307
the high-speed controller loses about one pipelined bulk command in a million
while its SOF interrupt is on (measured, 6 events in 52 runs of 100000 commands
against none in 66 runs with the interrupt off), so it is not turned on there
without a class that needs it.
A host may send several SETUP packets back to back, and a new SETUP may replace a
control transfer at any time; the device has to answer the last one. The controller
stores each SETUP at the current address of DOEPDMA0 and advances the address by eight
bytes. The backend always decoded the first eight bytes of its SETUP buffer. After
back-to-back SETUP packets that is the first one, so the host got the answer to a
request it had already given up; a SETUP that arrived while an OUT data stage was
armed was stored in the data slot, and the backend ran the previous request again.

The SETUP is now taken from just below the DMA address, in the SETUP buffer or at the
start of the armed data slot, and from the start of the SETUP buffer otherwise.
An IN transfer that is still enabled has to be stopped by disabling the endpoint and
flushing its transmit FIFO before the next transfer is programmed (controller
programming model, "IN endpoint disable"). When a SETUP arrived in the middle of an IN
data stage the interrupt handler only cleared the software state of EP0 IN. The stop
that follows then found nothing to stop: the endpoint stayed enabled with the next
packet of the old data stage in its FIFO, the transfer size was rewritten while it was
enabled, and the host received that old packet as the first packet of the answer to
its new request.

The software state is now left alone, so the stop runs the disable sequence and the
FIFO flush. A SETUP makes the controller set the NAK on EP0 IN by itself; when the NAK
is already in effect the stop writes EPDIS at once instead of waiting for a
NAK-effective interrupt that was taken long before.
A device must accept a SETUP packet at any time (USB 2.0, 5.5.5). With the internal
DMA the controller stores a SETUP in memory only while EP0 OUT is enabled, and it
disables the endpoint itself at the end of a SETUP stage, after a completed OUT
transfer and when the host enters the status stage of a control write. The backend
enabled it again after a SETUP without an OUT data stage and after a zero-length OUT
packet only:

- a request with an OUT data stage that was refused left EP0 OUT disabled, and the
  device answered no further control request;
- between the last data packet of a control write and the end of its status stage
  EP0 OUT was disabled, so a SETUP sent instead of taking the status was never
  answered.

EP0 OUT is now enabled for SETUP packets in each of these cases. While OUT data is
still to come it keeps its NAK, so no data packet is taken into the SETUP buffer; the
data stage clears the NAK when it is started. Because the endpoint can now be enabled
while a data stage is programmed, its transfer size register is written as one word.
This is the sequence ST's HAL and TinyUSB use on cores after 3.00a.
…completed

EPDIS may only be written to an endpoint that is enabled, and until the NAK of the
stop sequence is in effect the controller can still send data (controller programming
model, "IN endpoint disable"). When the host took the last packet between the start
of a stop and the NAK-effective interrupt, the transfer was complete and the endpoint
disabled, but the backend wrote EPDIS all the same and waited for an endpoint-disabled
interrupt that never comes. The stop timed out after eight frames, the controller was
reset and the device dropped off the bus and enumerated again.

The stop now checks the enable bit while it waits for the NAK and ends at once when
the endpoint is already disabled; the request is reported as sent completely.

AdvanceStop takes the whole status copy of the endpoint interrupt and tells its
caller when the request in flight ended there. The handler then leaves the other
flags of that copy alone: they belong to the ended request, and the core may have
started the next request inside the stop confirmation, so a completion reported
afterwards would be attached to that request.
An endpoint that is no longer part of the configuration is deactivated by clearing
USBAEP in its control register; the controller then ignores tokens addressed to it
(controller programming model, "Endpoint deactivation"). Closing an endpoint only
dropped its interrupt mask, so after SET_CONFIGURATION 0 or a change of the alternate
setting the endpoints of the old configuration kept answering NAK to the host instead
of staying silent.

USBAEP is now cleared when an endpoint other than EP0 is closed; configuring the
endpoint again sets it as before.
An isochronous endpoint transfers only in a frame whose number has the parity
programmed into its control register (even or odd frame), and a transfer is scheduled
for one frame at a time, so the parity is set for each transfer (controller
programming model, "Generic periodic IN data transfers"; ST's HAL and TinyUSB do the
same). The backend selected the even frame once, when the endpoint was configured. An
isochronous IN endpoint then sent data in even frames only and answered with an empty
packet in the odd ones: the UAC1 microphone delivered 1500 packets in 3000 frames and
the host heard half the samples.

Each isochronous transfer, IN or OUT, is now given the parity of the frame after the
current one when it is started.
An isochronous IN transfer is scheduled for one frame. When it is not sent in that
frame (the host did not ask for it, or the token was corrupted) the controller raises
the incomplete isochronous IN transfer interrupt, and the application has to set the
NAK and disable the endpoint, wait for the endpoint-disabled interrupt and flush the
transmit FIFO (controller programming model, "Incomplete isochronous IN data
transfers"). The backend neither unmasked nor handled this interrupt: the request
stayed armed with a frame parity that had passed, its completion never came, and the
class that paces its stream on completions was not told to submit the next frame.

The interrupt is now unmasked. An isochronous IN endpoint that is still enabled and
whose even/odd frame bit equals the parity of the frame that ended is disabled with
the stop sequence, its FIFO is flushed and the request ends with FAILED, as on the
STM32 OTG backend. An endpoint armed for the next frame has the other parity and keeps
its request, so with two streams a miss on one does not end the request of the other.
A stop requested while this is under way takes the running sequence over and ends as a
confirmed stop.

On the ESP32-S3 the interrupt arrives a few microseconds after the SOF of the new
frame, and DSTS already holds the number of that new frame, so the parity of the frame
that ended is the opposite of the number read. Taking the number read as the frame
that ended aborted the endpoint armed for the frame that had just begun: SNAK and
EPDIS were written, the host's token still took the packet, and the endpoint disabled
itself by completing the transfer. EPDIS on an endpoint that is already disabled
raises no EPDISD, so a sequence that only accepted EPDISD waited for the rest of the
stream, and a later SET_INTERFACE alt 0 that adopted the abort timed out after eight
frames and reset the controller. In the disable wait, an IN endpoint that is no longer
enabled and has the transfer-complete flag set but no EPDISD has therefore finished
its transfer first: a waiting stop ends there and a waiting missed-frame abort is
void, the transfer completes as usual. A stop that adopts a missed-frame abort of an
endpoint that is already disabled ends at once.
Before an OUT endpoint is disabled the global OUT NAK has to be in effect, so that no
packet is being received while EPDIS acts: SGOUTNAK in DCTL, wait for GOUTNAKEFF, then
SNAK and EPDIS, wait for the endpoint-disabled interrupt, then CGOUTNAK (controller
programming model, "Disabling an OUT endpoint"). The backend wrote SNAK and EPDIS on
the endpoint directly, with a comment saying this controller has no global OUT NAK.
The register description of the ESP32-S2 and ESP32-S3 in ESP-IDF has SGOUTNAK,
CGOUTNAK and GOUTNAKEFF, and TinyUSB, the device stack ESP-IDF uses on these chips,
runs exactly this sequence. Without it a packet that arrives while the endpoint is
being disabled is in an undefined state.

Stopping an OUT request now takes the global OUT NAK first. It is shared by all OUT
endpoints that are stopping and released when the last of them is disabled; a transfer
that completes while the stop waits ends the stop without EPDIS. The bus reset path,
which disables every endpoint in one go, waits for the global OUT NAK as well and
releases it afterwards.
On an ESP32-S3 the core can raise USBSUSP during the SE0 of a bus reset,
before ENUMDONE (measured: 7.65 ms after USBRST in 11 of 11 captured
hangs, with DSTS.SUSPSTS=1). The line then stays SE0 and the device does
not come back to the bus: the host reports a disconnect after the reset
and nothing after it, until the chip is reset. About 1 to 3 in 100
USBDEVFS_RESET calls hit it. A DCTL.SFTDISCON pulse inside the reset
window restores enumeration every time it was tried.

Track the interval between a bus reset and its ENUMDONE. A USBSUSP inside
it is not taken for a suspend: pulse SFTDISCON (set, 20 us, clear). The
host's reset window is still open, so it sees no disconnect; the core
detects the reset again and enumerates when the reset ends. A suspend
after ENUMDONE is handled as before.

Ignoring that USBSUSP without the pulse still hung (10 of 450), so the
pulse is what recovers. Why the device stays off the bus is not
established.

Board (ESP32-S3, 450 USBDEVFS_RESET each, device number unchanged):
UAC image 13 hangs before, 0 after; plain image 7 before, 0 after.
…chronously

StopHardware ends a stop at once when the endpoint is no longer enabled: the
request has completed in the hardware, and the core takes its result from the
stop. The transfer-complete flag of that request stayed pending and was handled
after the stop had returned. The handler reports a completion with the tag of
the request that is current at that moment, so when the core had already
started the next request, that one was reported complete while the hardware was
still transferring it.

The flag is now cleared where the stop ends the request (IN and OUT endpoints
other than EP0; EP0 completions are consumed before a SETUP is handled).
ReapProgress no longer reads the flag from the register: every path that ends a
completed IN request records it in stopped_sent_all_.

The EP0 OUT scratch address goes to the 32-bit DMA address register through
uintptr_t, like the other DMA addresses of the file.
In device mode the USBHS controller reports a SOF as UIF_TRANSFER with the token
field of INT_ST set to SOF; UIF_HST_SOF is a host-mode flag and was never set on
a CH32V307 board (about 100000 interrupts seen with the SOF interrupt on), so the
OnSof call guarded by it never ran and the device core got no frame numbers or
microframe ticks from this backend.

HandleTransferToken now reports the SOF token with the frame number from the low
11 bits of FRAME_NO and the microframe number from the top 3. The dead
UIF_HST_SOF branch is removed. The points where the SOF interrupt is enabled and
disabled are unchanged.
With the SOF interrupt on, the CH32V307 USBHS reports each SOF as UIF_TRANSFER
with the token field of INT_ST set to SOF and the top four bits of the frame
number in the endpoint field (manual V2.5 p.339-340). Measured on a CH32V307
board, the controller then auto-toggles the RX toggle of the armed OUT endpoint
with that number once per SOF, for the 1024 SOFs of every 16384 whose frame bits
equal the endpoint number. The value is the same at interrupt entry, after the
flag clear and at exit, so the flip precedes any software. The next command from
the host arrives with the wrong phase, is dropped as a resend, and the host waits
for its 1 second timeout: 2000 DAP_Info round trips gave 6, 1 and 1 errors.

Bulk and interrupt OUT endpoints now run without R_TOG_AUTO and the RX toggle is
flipped in software after every TOG_OK packet, including one that lands after a
stop (the completion is dropped after the flip). A packet with TOG_OK=0 is a
resend and does not flip. EP0 and isochronous endpoints are unchanged. Cleared
R_TOG_AUTO was measured to hold the toggle across SOFs; the IN TX toggle does not
move on SOF and keeps its auto toggle.

The controller no longer writes the OUT toggle, so the repair of an OUT toggle
advance lost while an IN is armed is removed. The IN side stays: without it 15
runs of 100000 pipelined DAP_Info commands gave 29 errors, with it 0.

Every OUT event of an endpoint other than EP0 is now taken as a received
packet; INT_ST.IS_NAK is no longer looked at there. A NAKed token raises no
event (the OUT events of EP1 equal the packets the host sent), but IS_NAK does
appear on a real packet now and then: with the SOF interrupt on, 3 of 7 million
OUT packets came with IS_NAK set, a valid RX_LEN and TOG_OK, and the host
advanced its phase afterwards (one was captured 5 us after a SOF event). The
handler used to take such an event only while a request was armed and RX_LEN
was not zero, which was right with the hardware toggle. With the software
toggle an event that is not taken is a flip that is not made: the packet is
lost and the next one is dropped as a resend, which the host sees as a pair of
timeouts (measured: about one pair in a million pipelined commands when such
events are ignored, none in 7 million when they are taken).
…n the bus

The USBHS backend enabled its SOF interrupt when the control endpoint became
ready and a class wanted bus time, and never disabled it. A class that started
to need frame ticks later got none, as on the other backends before they
changed.

The interrupt is now enabled in Start(), at a bus reset and at a resume, and
disabled at a suspend and in Stop(), as on STM32 OTG, ESP32 and FSDEV. The SOF
token reaches the device core since the previous commits, and the OUT toggle no
longer depends on the controller, so the interrupt can stay on.

Measured on a CH32V307 CMSIS-DAP probe at high speed with this state: SOF
events arrive at 7980 per second under load; three runs of 1500 1024-byte, 900
512-byte and 6000 DAP_Info round trips and 70 runs of 100000 pipelined DAP_Info
commands (four in flight) pass without an error.

CH32 USBFS is unchanged: it enables the interrupt from WantsBusTime() when the
control endpoint becomes ready. No board with a USBFS device port whose header
defines the device SOF bits was available to measure what the interrupt does
to bulk traffic there.
Closing an endpoint first delivers a completion the hardware has already
reported, and for an OUT endpoint that completion lends its slot to the class.
DapLinkV2Class ignored every completion once it was unbound, lease included.
The slot stayed lent, the close turned it void, and nobody was left to give it
back. Each OUT packet that was received but not yet delivered when the
configuration was cleared cost one of the two receive slots; with both gone a
new binding could not arm a receive, and the interface accepted no command
until the device was powered off, a bus reset included.

The callback entry now gives such a lease back, as the CDC, HID and gs_usb
classes do.

Measured on an ESP32-S3 CMSIS-DAP probe with the host streaming DAP_Info at
full rate while SET_CONFIGURATION 0 and 1 are sent: before, the DAP interface
stopped answering within 20 to 40 switches, with both OUT slots void and no
receive armed; with the fix, 120 switches leave both slots in use.

Test: an OUT packet completed inside a controller interrupt batch in which the
class is unbound, twice; the next binding arms its receives and answers a
command. It fails without the fix.
Endpoint::OnHardwareStopped only sets a flag, and the flag was cleared when a
stop finished, not when one started. A confirmation that a backend reported
while no stop was waiting therefore stayed set, and the next stop that returned
PENDING was taken as confirmed at the owner's next pass: the in-flight request
was reaped and the next one started while the hardware was still stopping.

The flag is now cleared before StopHardware is called, so a stop is confirmed
only by a confirmation that follows its own request.

Test: a confirmation with no stop waiting, then a flush whose stop stays
pending while a further request is queued; the stop ends only at its own
confirmation and the queued request starts after it. It fails without the fix.
…ones on a reset

Stop() masked the interrupt and left the bus but did not confirm endpoint stops
that were still waiting for the hardware. Off the bus and with the interrupt
off nothing can confirm them any more, and no frame arrives to time them out,
so such an endpoint stayed in its stop. Stop() now confirms every waiting stop,
as the STM32 OTG backend does; Start() rebuilds the controller registers and
the FIFO bookkeeping. The soft disconnect is written inside the hardware guard
with the other register writes.

The escalation after a stop timeout reported a confirmation for every endpoint,
also for one with no stop waiting and for one whose disable sequence belongs to
a missed isochronous frame. It now confirms only a stop the core is waiting
for.
GAHBCFG.HBstLen was written with 4, which is not an encoding of the field
(0 SINGLE, 1 INCR, 3 INCR4, 5 INCR8, 7 INCR16); the constant is called INCR4
and INCR4 is 3. TinyUSB programs 3 for the same core.
…IFOs by hand

ESP32USBDevice::DmaEnabled() returned a constant true: the slot model hands the
slot memory to the controller's DMA and has no other way to move data. The
branches for the other case could not run: the RX FIFO level handler and its
status decoding, the TX FIFO refill on the FIFO-empty interrupt, the functions
that read and write a FIFO word by word, and the bookkeeping they kept
(transfer_actual_size_, transfer_queued_size_, the RX status byte count).

They are removed, together with DmaEnabled() itself, the dma_enabled parameters
of the two FIFO size helpers, the RX status and FIFO address constants, the
FIFO-empty level and mask writes that only that interrupt needed, and the RX
FIFO level mask that was written as 0 right after the whole mask register had
been cleared. No reachable statement changes.
…iceCapabilities

DeviceCore took `template <typename Capabilities>`; the three constants it
reads from that type (SPEEDS, BOS, BUS_TIME) were documented only on the two
policy types. The concept DeviceCapabilities states them with their types, and
DeviceCore, its forward declaration and its friend declaration in DeviceClass
are constrained by it. The member definitions in dev_core.tpp, which named the
parameter C, use the same head and the name Capabilities.

No change of behaviour.
FSDevDevice and FSDevEndpoint were class templates over a hardware-access type
that every platform supplied. That type carried the whole register model as
static members: the register access, every bit constant, the BTABLE and PMA
access and the reset and suspend sequences. The STM32 classic type, the CH32
type and the fake of the host test each had their own copy of the same code,
with the same offsets, bits, COUNT_RX encoding and PMA copy loops, and a reader
of FSDevDevice<HW> had no declaration to go to for HW.

FSDevDevice is now an ordinary base class and the register model of the
classic controller is in it once (fsdev.cpp replaces fsdev.tpp). The device
class of a platform derives from it and
- passes a MemoryMap to its constructor: register base, PMA base, PMA size,
  word stride and alignment;
- enables the clock, installs the hardware guard and calls InitController();
- implements Connect() for the pull-up.
Registers are read and written through two virtual functions, ReadRegister and
WriteRegister. The DRD variant (STM32 parts with USB_DRD_FS) overrides these
and the BTABLE, PMA, reset and suspend functions in driver/st; its extra EPnR
bits are three members the constructor sets. driver/st checks the register
offsets and bits of the device header against the constants of the base class
with static_assert, for the classic and for the DRD structure.

The host test routes the two register functions to its fake controller and
uses the fake's memory as PMA, so it now runs the BTABLE and PMA code of the
base class instead of a copy of it.

STM32USBDeviceDevFs and CH32USBDeviceFS take the same constructor arguments as
before. ch32_usb_fsdev_regs.hpp is removed.

The registers are written with the same values in the same order as before.
Two things differ: the controller is initialized by InitController(), which
the derived constructor calls after the base constructor has created the
endpoint objects (creating them does not touch the hardware), and a register
access is a virtual call.
PmaWrite and PmaRead read MemoryMap::word_stride inside the loop. The member
is a byte, so after every store to the packet memory the compiler has to read
it again. With the stride in a local the loop is the one the code had when
the stride was a compile-time constant, plus one add per word.
FSDevDevice is only a base class: applications and generated code use the
device class of the platform. It could not be instantiated before either,
since Connect() is pure virtual; the protected constructor says so in the
declaration.
dev now has the fatal error split (#364) and the shared Topic test cleanup
(#363). One conflict, in test/automatic/main.cpp: the USB cases of this branch
stay and the case assert takes the registration from dev (isolated, without
platform initialization).

The CH32 endpoint test programs define libxr_fatal_error themselves; they now
define libxr_fatal_error_and_print as well and accept a null file name.
--wrap replaces a symbol when the linker resolves it. With link-time
optimization the compiler resolves a call to a function whose definition it can
see before the linker does: ST's HAL_PCD_IRQHandler was inlined into the CubeMX
interrupt handler and HAL_PCD_Init into MX_USB_*_PCD_Init, and the wrappers of
LibXR were never called. Measured with GCC 14.2 and ld 2.43 on a four-file
reproduction: with everything in LTO the interrupt handler holds ST's code; with
only the file that defines the two functions compiled without LTO it calls the
wrapper, and the check in STM32USBRequireWrap() agrees with it.

The CMake fragment now finds stm32*_hal_pcd.c among the sources of every target
of the project and compiles it with -fno-lto. Its callers and LibXR stay in
LTO. This needs CMake 3.18; with an older CMake a project that enables LTO
stops at configuration with the reason.
Say next to the wrappers why the HAL PCD source stays out of link-time
optimization, and in the header what the check at construction can see.
@Jiu-xiao
Jiu-xiao marked this pull request as draft November 14, 2026 17:12

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant