Repository navigation
Conversation
…tack Replace the free-index queue with an index stack linked through the slots. The final release pushes the slot with a CAS loop and cannot fail, so the queue-full return path and its capacity reasoning are gone. Acquire pops from the same stack and requires one acquirer per pool at a time, which is the contract the pool already had; debug builds now detect overlapping acquisitions. ObjectPool<Data> is the only pool type. BasicObjectPool, SPSCObjectPool, MPMCObjectPool, the IndexType parameter and the external free-queue constructors are removed. External storage still takes Slot*. Free slots are now reused last-in first-out.
The STDIO threads that PlatformInit starts never exit and are never joined, but stdo_sem and stdi_space_sem were file-scope objects. Their static destructors freed the semaphore handle while StdoThread was still parked in Wait() on it, so any STDIO write during exit (another static destructor, an atexit handler, a thread that is still running, libxr_fatal_error) posted to freed memory. ThreadSanitizer reported this race at the end of almost every libxr_test case. Both semaphores are now allocated once and never destroyed, like STDIO::write_ and STDIO::read_. Construction time, STDIO behavior and the Semaphore class are unchanged; output still queued at exit is not drained, as before.
Handle is move-only again and is the only writable access to a slot. ConstHandle stays copyable and can only take over a Handle by move, so a slot never has two writers. Copying a Handle and converting a Handle to a ConstHandle by copy are removed. The two handle types are now plain classes instead of one access-qualified template.
test_linux_uart_rx_backpressure created a stack Semaphore for each of its three reads. Wait() can return as soon as the count is incremented, so the loop could destroy the semaphore, and build the next one at the same address, while the io_uart thread was still inside Post(). ThreadSanitizer reported this in uart_rx_space. The test now allocates one semaphore before the loop, like test_linux_uart_block_timeout. The manual I2C, SPI and UART tests had the same pattern: their BLOCK semaphores lived on the stack of the test function, or in a stack TransferTestCompletion, and the driver completion that posts them is never joined. These functions and TransferTestCompletion now take a caller-retained Semaphore& right after the driver argument, and the READMEs show it. BLOCK operations that run one after another in the same call share it. Calls written for the old signatures no longer compile.
Keep the Linux and Webots STDIO semaphores alive during process exit
Keep test semaphores alive while a driver can still post to them
The README lists every device class with its header, the device controllers with their drivers, and drops the Host Stack section, the TODO and the unverifiable feature claims. The STM32 FSDEV row names USB_BASE and USB_DRD_FS instead of USB_DRV_FS.
Merge the XRUSB README into one bilingual file that matches the code
A single-producer, single-consumer mailbox with three slots that keeps only the latest complete value: Store() may overwrite a value the consumer has not taken, but never the one it is copying; LoadLatest() reports whether it acquired a newer publication. Taken from d0b0e66 on codex/uart-dma-models-20260710 (never merged), with bilingual documentation and the test moved to the automatic test framework. Motor modules use it to keep the latest CAN feedback frame.
feat(structure): add LatestSnapshot latest-value mailbox
…0910 feat(structure)!: shared ObjectPool handles with a single-acquirer free stack
Audit of all 865 ASSERT/DEV_ASSERT/REQUIRE uses against the policy (ASSERT: caller preconditions and fixed configuration; DEV_ASSERT: internal invariants; REQUIRE: failures that can occur at runtime with correct code). Decisions: a condition that cannot recur once the code is written correctly is ASSERT, otherwise REQUIRE or an error return; results of HAL/SDK operations on library-owned state are DEV_ASSERT; a condition that was both asserted and returned keeps only one, chosen by whether the caller can recover. Compile-time platform branches use static_assert where valid. Required operations stay outside the checks.
refactor: apply the assertion policy across drivers and core
PlatformInit started the STDIO read and write threads before it created _libxr_webots_time_notify, the condition variable that Thread::Sleep waits on. When stdin is not a TTY, StdiThread parks at once with Thread::Sleep(UINT32_MAX) and locked the mutex of the still-null handle, so a controller started with stdin redirected from a file or /dev/null crashed in pthread_mutex_lock. The condition variable is now created right after the timebase, before any thread starts. Its fields, the timebase thread and the STDIO behavior are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Init() resets the FIFO bookkeeping before Start() enables the USB core clock, where GetHardwareFifoDepthWords() reads 0; Start() recomputes it later. #321 turned the check in ResetFifoState() into REQUIRE, so every ESP32-S3 USB device stopped in Init() and the host saw a failed device descriptor request. The check moves to ResetDeviceState(), which runs on a powered core, as DEV_ASSERT (internal invariant).
Create the Webots timebase condition variable before the STDIO threads
fix(esp): check the USB FIFO depth only after the core is powered
STAT.BUSY also covers an ongoing reception. Construction spun in ApplyConfig() on BUSY, so a floating or held RX line hung the MCU at start-up; at run time a published configuration waited for BUSY with an RX-timeout retry, so continuous RX traffic deferred it forever and FillTx stayed blocked behind the pending configuration. The driver now tracks its own TX end like the STM32/CH32 drivers do with TC: StartTxDma() sets tx_draining_, EVENT_EOT_DONE clears it, and TryApplyPublishedConfig() waits only for that (enabling the EOT interrupt fires at once if EOT is already set). ApplyConfig() no longer waits; a byte being received is dropped with the configuration.
fix(mspm0): apply UART configuration after TX end, not after BUSY clears
HPM drivers share one HDMA interrupt. The I2C driver used the HPM SDK dma_mgr only when __has_include found it, so on SDKs without the component its DMA path was compiled out, and a driver installing its own HDMA handler would clash with dma_mgr. dma_mgr (the HPM-recommended DMA manager) is now required: hpm_dma.hpp stops the build with a message when hpm_dma_mgr.h is missing, and HPMDmaManager::EnsureInitialized() calls dma_mgr_init() once for every driver. HPMI2C drops LIBXR_HPM_I2C_HAS_DMA_MGR and its gates; POLLING/CALLBACK/NONE always take the DMA path, and the init call moves from the first async transfer (possibly in an ISR) to the constructor.
- mspm0_atomic_shim.c: GCC declares __atomic_compare_exchange_4 with the weak argument of the generic builtin, while the sized runtime call has five arguments; turn off -Wbuiltin-declaration-mismatch around this definition only. - mspm0_timebase.cpp: replace ++ on the volatile tick counter (deprecated in C++20) with an explicit read and write; only the SysTick interrupt writes it. - mspm0_gpio.cpp: with ASSERT disabled, GCC sees the -1 port index of an unknown port and reports -Warray-bounds; after the ASSERT, mark that case unreachable. - system/none/thread.hpp: initialize the thread handle, so Thread::Current() no longer returns an uninitialized value (-Wuninitialized at -Og).
fix(mspm0, none): build without GCC warnings
HPMGPIO enabled the port IRQ in the PLIC but left the ISR to the board: without a board ISR that calls libxr_hpm_gpio_check_interrupt(), EnableInterrupt() succeeded and the callback never ran. The driver now declares SDK_DECLARE_EXT_ISR_M for each IRQn_GPIO0_<port> the SoC defines and dispatches with CheckInterrupt(). Applications must not declare these ISRs any more; libxr_hpm_gpio_check_interrupt() stays for C callers.
…e bound Writes made while the device is suspended or not yet configured are queued, but WriteFun does not start a transfer then. Once the queue is full, later writes return FULL without calling WriteFun, so nothing ever started the IN endpoint again. CDCUart::BindEndpoints now advances transmission after binding.
HAL_PCDEx_SetTxFiFo(0) places TX0 at GRXFSIZ. EP0 IN was constructed first, so TX0 started at the reset GRXFSIZ (0x200 words on OTG_FS, 0x400 on OTG_HS), outside the FIFO RAM. Construct EP0 OUT first.
HAL_PCD_EP_Close only requests the disable of an enabled IN endpoint. HAL flushes the endpoint TxFIFO later, in the EPDISD interrupt. When a class rebinds on SET_CONFIGURATION and restarts a transfer in the same interrupt, that late flush discards the packet already written to the FIFO while the endpoint stays enabled, so the transfer never completes. Close now sets NAK, waits for the disable, clears EPDISD and flushes the FIFO itself.
fix(usb): CDC sends nothing after enumeration on STM32 OTG
HPM SDK's find_package(hpm-sdk) forces the compiler, so the feature detection results are unavailable and target_compile_features(cxx_std_20) cannot run; the BSPs had to restore the detection before project() for this one item (cmake/compiler_probe.cmake). When cxx_std_20 is not in the feature list, add the standard option directly instead: -std=gnu++20 or -std=c++20 following CMAKE_CXX_EXTENSIONS (the detection path produces gnu++20 with the default extensions), and /std:c++20 for MSVC.
…0261006 cmake: require C++20 directly when the compiler is forced
PowerManager gains RegisterCommand(RamFS&), which adds a `power` command (`power reset|shutdown|bootloader`, usage and -1 otherwise), and CheckBootloaderPin(GPIO&, level), which enters the bootloader when the pin reads the given level at startup. Both are platform independent. MSPM0PowerManager::JumpToBootloader() now clears SRAM_BANK0 and its ECC codes before the BOOTLOADERENTRY reset, as the SDK example bsl_software_invoke_app_demo_uart does for BSL_ERR_01; without it the BSL hits an SRAMDED NMI and stops responding. The size comes from __StackTop instead of the FACTORY SRAMFLASH word the example reads, because a FACTORY access with flash wait state 2 HardFaults on the MSPM0Gx51x (FLASH_ERR_01, SLAZ758E). Verified on MSPM0G3507 and MSPM0G3519: a terminal command enters the BSL and the board is flashed over UART without touching it. Shutdown() notes SYSCTL_ERR_05. The HPM ISP entry reaches the same ROM state as the KEY&BOOT entry (J-Link); a test covers the command and the pin check.
WFI returns at once while an interrupt is pending, so a single WFI could leave the device spinning awake; WFI now runs in the loop until SHUTDOWN is entered. The constructor releases the IO latched by a SHUTDOWN exit (SYSSTATUS.SHDNIOLOCK, SLAU846B 2.4.7) after SysConfig has configured the pins; RSTCAUSE is not used since it clears on read and reports the wrong cause after an NRST wake on the G351x (PMCU_ERR_11).
Commands that only take argc/argv previously had to go through the
context-taking CreateCommand with a dummy argument, e.g.
CreateCommand<void*>(name, [](void*, int, char**){...}, nullptr).
Add a two-argument overload that stores the function pointer itself
as the execution context, and document why Add() only accepts
lvalues: RamFS stores node addresses, so a temporary would dangle.
… type LIBXR_DEBUG_BUILD was hard-wired to CMAKE_BUILD_TYPE=Debug, so the in-library failure checks could not be enabled in optimized builds. Turn it into a CMake option that defaults to on for Debug and off otherwise and can be overridden with -DLIBXR_DEBUG_BUILD=ON/OFF, and list it in the README CMake options table.
option() wrote its computed default into the cache on the first configure, so switching the build type in an existing build directory (e.g. Release and then Debug) kept LIBXR_DEBUG_BUILD OFF forever, regressing against the previous behaviour where the definition followed CMAKE_BUILD_TYPE on every configure. Compute the default as a normal variable whenever LIBXR_DEBUG_BUILD is not defined, so it tracks the build type at each configure without touching the cache, and respect the user's value once it has been set explicitly with -DLIBXR_DEBUG_BUILD=ON/OFF.
Make LIBXR_DEBUG_BUILD settable for any build type
…1009 Add RamFS::CreateCommand without an execution context
Add MSPM0 and HPM power managers, the power command and the boot pin check
|
| DL_Timer_getClockConfig(timer, &config); | ||
| return timer_clock_hz * (static_cast<uint32_t>(config.divideRatio) + 1U) * | ||
| (static_cast<uint32_t>(config.prescale) + 1U); |
There was a problem hiding this comment.
SourceClockFromSysCfg combines the fixed SysConfig frequency with the timer's current dividers. If an application constructs one channel, calls SetConfig, then constructs another channel on the same timer, the second channel gets the wrong source clock.
For example, a 48 MHz timer initially without dividers gets prescale 8 after SetConfig({100}). The next MSPM0_PWM_CH reports 432 MHz instead of 48 MHz, so later frequency settings produce the wrong output. Capture the source clock before any channel changes the timer, or pass the source clock directly.
Prompt To Fix With AI
This is a comment left during a code review.
Path: driver/mspm0/mspm0_pwm.cpp
Line: 59-61
Comment:
**Later PWM clocks are wrong**
`SourceClockFromSysCfg` combines the fixed SysConfig frequency with the timer's current dividers. If an application constructs one channel, calls `SetConfig`, then constructs another channel on the same timer, the second channel gets the wrong source clock.
For example, a 48 MHz timer initially without dividers gets prescale 8 after `SetConfig({100})`. The next `MSPM0_PWM_CH` reports 432 MHz instead of 48 MHz, so later frequency settings produce the wrong output. Capture the source clock before any channel changes the timer, or pass the source clock directly.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| if (dma_mgr_initialized) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| dma_mgr_init(); | ||
| dma_mgr_initialized = true; |
There was a problem hiding this comment.
DMA initialization can run twice
EnsureInitialized allows calls from threads, but its plain dma_mgr_initialized flag does not protect initialization. Two threads calling it for the first time can both see false and both run dma_mgr_init(), violating the promised once-per-program behavior. Their reads and writes of the flag also race.
Protect the whole initialization step so other callers wait until the first call finishes. Merely setting an atomic flag before initialization would still let callers proceed too early.
Prompt To Fix With AI
This is a comment left during a code review.
Path: driver/hpm/hpm_dma.cpp
Line: 15-21
Comment:
**DMA initialization can run twice**
`EnsureInitialized` allows calls from threads, but its plain `dma_mgr_initialized` flag does not protect initialization. Two threads calling it for the first time can both see `false` and both run `dma_mgr_init()`, violating the promised once-per-program behavior. Their reads and writes of the flag also race.
Protect the whole initialization step so other callers wait until the first call finishes. Merely setting an atomic flag before initialization would still let callers proceed too early.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Drive the real CDCUart, WritePort and endpoint completion state machines with a mock endpoint whose Transfer() invokes the completion callback inline, injecting the reentry that corrupts the TX queue when WriteFun and OnDataInComplete both advance ProgressTx. Covers queued-before-bind data, completion reentry with single and double buffering (including writes from inside the completion callback), ZLP handling, rebind cleanup of prepared data and pending ZLPs, and 1024 repeated inline completions; asserts Transfer nesting depth stays at 1. Also asserts that a full-packet transfer completing inline still gets its ZLP, that two writes coalesced into one wakeup all reach the wire in FIFO order, and that write-completion callbacks observe the in_isr of the context that claimed execution.
WriteFun and OnDataInComplete both entered ProgressTx, so a transfer completing inline inside Endpoint::Transfer() recursively re-entered the same WriteQueue, and task-context progress interleaved with the IN completion IRQ over the endpoint state, need_write_zlp_ and the write queue. On single-core targets this lost queue progress (a 2048-byte chunk arrived as 1664 bytes on CH32V203) and could corrupt the endpoint state machine. WriteFun and OnDataInComplete now only publish an event to a SerializedService; a single consumer advances ServiceTx/ProgressTx in the claiming caller's context. BindEndpoints re-requests TX so data queued before configuration is sent after enumeration; routing it through the service keeps the one-consumer invariant instead of reintroducing a second entry into ProgressTx. The ZLP flag handling keeps the previous order: with a single consumer the reentrant caller can no longer observe the flag between arming a transfer and setting the pending-ZLP flag, which is what made the old order lose or double the ZLP; the new inline-ZLP regression covers this. The write-completion callbacks run serially in the consumer's context with an in_isr flag matching that context. Return codes, blocking behavior and completion semantics are unchanged.
SlotPool keeps one atomic state word (free/writing/ready/reading) and one publish sequence per slot. Acquire/Publish/Take/Release move the state with CAS, Publish takes a globally increasing sequence with fetch_add, Take picks the ready slot with the smallest sequence (wraparound-safe signed compare), and the release/publish counters drive one bounded rescan so a scan that ran while a slot was freed or published cannot return a stale FULL/EMPTY. An interrupted operation only occupies its own slot, so Put/Get from interrupts never observe the transient false FULL/EMPTY of the Vyukov MPMC queue; the pool targets small capacities where the O(N) scans are cheap, and Put/Get require trivially copyable types. Includes automatic tests (state transitions, publish-completion order, sequence wraparound, FULL/EMPTY boundaries, abandoned slots, multi-producer stress) and a Unicorn Cortex-M preemption regression that interrupts every intermediate point and compares the same scenarios against the baseline MPMC queue. Updates the MPMC queue class doc with the retry/wait guidance and the SlotPool pointer, and lowers the doxygen warning baseline to the new count.
The bxCAN, FDCAN (classic and FD queues) and CH32 CAN drivers used a Vyukov MPMCQueue as the TX software queue. On a single core, when a task is interrupted inside TxService's Pop (head claimed, cell sequence not yet published), AddMessage from an interrupt wraps onto that cell and receives a false FULL, silently dropping the frame; symmetrically a preempted push hides published frames behind its cell. SlotPool's Put/Get only fail with FULL/EMPTY when the pool truly has no free/ready slot at that moment. The tx_lock_/tx_pend_ serialization, the retry-slot logic, the constructor arguments, the public interface and the return-value sets are unchanged. The dequeue order changes from claim order to publish-completion order; the order inside one sender is preserved and no driver or in-repo consumer depends on cross-sender FIFO (the manual CAN test explicitly does not assume arbitration order, and bxCAN/CH32 hardware transmits by ID priority anyway). The Unicorn preemption harness for the queue layer lives in test/manual/structure/slot_pool.
…elease precondition, shorter CAN comments
…lication A Take pass could skip a slot that became ready after it had been scanned and then pick a newer item of the same publisher from a later slot, so one consumer received the second item first. CI caught it in the per-producer order test. An item that took its sequence before the pass began was ready before the next item of its publisher took a sequence. Take now records the publish count at the start of each pass and rescans when the chosen item took its sequence after that point. A scan inside an interrupt on a single core is not interleaved with lower-priority publications and never rescans for this. The order test uses three producers and four slots, which fails 2 of 10 suite runs without the fix on a 14-core host and passes 10 of 10 with it; a standalone 3-producer stress shows 19/20 and 11/20 failing runs before and 0/40 after.
fix(usb): serialize CDCUart TX progress through one consumer
# Conflicts: # test/automatic/main.cpp
…, a wraparound test with several ready slots, clang-format
feat(structure): SlotPool, and use it for the CAN TX queues
Release LibXR v2.0.1 (with xrobot 1.0.1 and CodeGenerator 6.0.1). Merge commit: release tag
v2.0.1(RELEASE.md step 1). After the merge, dev is fast-forwarded to master.Candidate: dev
2712e5c557a4b5b2abd48a21836f41fdb1f98791. master has only the merge commit of #314, whose tree equals its dev parent, so after this merge master's tree is dev's.Changes since V2.0.0
powerterminal command andCheckBootloaderPin(Add MSPM0 and HPM power managers, the power command and the boot pin check #335); drivers set their own interrupts and priorities and the C++ runtime symbols are provided (mspm0: drivers set their interrupts and priorities; provide the C++ runtime symbols #331); I2C/SPI/PWM init macros take the right clocks (fix(mspm0): I2C/SPI init macros take the input clock; PWM macro derives the source clock #329); UART configuration applied after TX end (fix(mspm0): apply UART configuration after TX end, not after BUSY clears #324); HPM drivers no longer call SDK board helpers (hpm: drivers no longer call SDK board helpers #332), dma_mgr required and initialized once (feat(hpm): require dma_mgr and initialize it once #325), GPIO port interrupt entries defined by the driver (feat(hpm): the GPIO driver defines the GPIO port interrupt entries #327); no GCC warnings (fix(mspm0, none): build without GCC warnings #326).ObjectPoolhandles with a single-acquirer free stack (feat(structure)!: shared ObjectPool handles with a single-acquirer free stack #295, breaking for ObjectPool users; released as a patch version by maintainer decision);LatestSnapshotlatest-value mailbox (feat(structure): add LatestSnapshot latest-value mailbox #320);SlotPoolfor small task/interrupt shared buffers, used for the TX queues of the STM32 bxCAN, STM32 FDCAN and CH32 CAN drivers (feat(structure): SlotPool, and use it for the CAN TX queues #340).LIBXR_DEBUG_BUILDsettable for any build type (Make LIBXR_DEBUG_BUILD settable for any build type #336);RamFS::CreateCommandwithout an execution context (Add RamFS::CreateCommand without an execution context #337); C++20 required directly when the compiler is forced (cmake: require C++20 directly when the compiler is forced #334); assertion policy applied across drivers and core (refactor: apply the assertion policy across drivers and core #321); bare-metaloperator new/delete(feat(none): provide operator new/delete in the bare-metal system #330);string_viewslicing withoutsubstr(fix: slice string_view without substr #328).ProgressTx()(fix(usb): serialize CDCUart TX progress through one consumer #339); CDC transmits after enumeration on STM32 OTG (fix(usb): CDC sends nothing after enumeration on STM32 OTG #333); ESP USB FIFO depth checked after power-up (fix(esp): check the USB FIFO depth only after the core is powered #323); Webots timebase created before the STDIO threads (Create the Webots timebase condition variable before the STDIO threads #322); STDIO and test semaphores kept alive through exit (Keep the Linux and Webots STDIO semaphores alive during process exit #317, Keep test semaphores alive while a driver can still post to them #318); XRUSB README merged into one bilingual file (Merge the XRUSB README into one bilingual file that matches the code #319).Acceptance (RELEASE.md, all six checks pass;
tools/check_release.pyagrees with the record)2712e5c5all green.70eaffefand CodeGeneratord5153df2CI all green.-O2 -g,LIBXR_DEBUG_BUILD=ON).power bootloader, reset, shutdown, keys, terminal), HPM5301 (reset, shutdown, LED/GPIO), RMCS Slave Lite (GPIO acceptance with JTAG kept).Known limitation: HPM ROM ISP over USB did not enumerate on HPM5301/5361 in tests (see #335).