From eb030d52651cb8d04d9cc1528e3b06802a7f419e Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Mon, 30 Nov 2026 15:48:19 +0100 Subject: [PATCH 1/3] fix(uart): make Uart::write() TX start atomic Uart::write() updated tx_head and then checked whether a HAL transfer was ongoing, without protection. If write() was preempted between the two steps for longer than the new data takes to send, the TX complete IRQ sent the data and left the UART idle with tx_tail == tx_head. write() then started a transfer from the empty buffer, and at its end tx_tail went past tx_head, so the last SERIAL_TX_BUFFER_SIZE bytes were sent a second time. Update tx_head and start the transfer in a critical section, restoring PRIMASK afterwards as write() may be called with interrupts disabled. Compute the transfer size from tx_head and tx_tail inside the critical section, and only start a transfer if data are pending. Fixes: #3125 Assisted-by: GitHub Copilot: claude-sonnet-5.5 Signed-off-by: Frederic Pillon --- cores/arduino/Serial.cpp | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index 6ee2e1a42a..eb16c52861 100644 --- a/cores/arduino/Serial.cpp +++ b/cores/arduino/Serial.cpp @@ -628,7 +628,6 @@ size_t Uart::write(const uint8_t *buffer, size_t size) // Copy data to buffer. Take into account rollover if necessary. if (_serial.tx_head + size <= SERIAL_TX_BUFFER_SIZE) { memcpy(&_serial.tx_buff[_serial.tx_head], buffer, size); - size_intermediate = size; } else { // memcpy till end of buffer then continue memcpy from beginning of buffer size_intermediate = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; @@ -637,18 +636,31 @@ size_t Uart::write(const uint8_t *buffer, size_t size) size - size_intermediate); } + // Moving the head and starting the transfer must be atomic: if the TX + // complete IRQ drained the buffer in between, a transfer would be started + // from an empty buffer and stale data would be sent again. + // PRIMASK is restored (not unconditionally enabled) as write() may be + // called with interrupts already disabled. + uint32_t primask = __get_PRIMASK(); + __disable_irq(); + // Data are copied to buffer, move head pointer accordingly _serial.tx_head = (_serial.tx_head + size) % SERIAL_TX_BUFFER_SIZE; // Transfer data with HAL only is there is no TX data transfer ongoing // otherwise, data transfer will be done asynchronously from callback - if (!serial_tx_active(&_serial)) { + if (!serial_tx_active(&_serial) && (_serial.tx_head != _serial.tx_tail)) { + size_t pending = (SERIAL_TX_BUFFER_SIZE + _serial.tx_head - _serial.tx_tail) + % SERIAL_TX_BUFFER_SIZE; // note: tx_size correspond to size of HAL data transfer, // not the total amount of data in the buffer. - // To compute size of data in buffer compare head and tail - _serial.tx_size = size_intermediate; - uart_attach_tx_callback(&_serial, _tx_complete_irq, size_intermediate); + // Limit the transmission to the buffer end because HAL is not able + // to manage rollover, the remaining is sent from the callback. + _serial.tx_size = min(pending, (size_t)(SERIAL_TX_BUFFER_SIZE - _serial.tx_tail)); + uart_attach_tx_callback(&_serial, _tx_complete_irq, _serial.tx_size); } + + __set_PRIMASK(primask); } /* Return 0 if not ready else requested transfer size */ return ret; From 25d356b10725b57107406062be5d6711dba8046c Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Mon, 30 Nov 2026 17:02:26 +0100 Subject: [PATCH 2/3] refactor(uart): refresh free space after Uart::write() waits When the TX buffer was full, Uart::write() waited for the TX interrupt to free space but kept the free space value read before the wait, so it was 0. The split loop then recursed with a zero-length write before the real one. Read the free space again in the wait loop so the data are queued directly. Tested on NUCLEO_C562RE at 921600 baud with an echo using single byte and 200 bytes write() calls, with and without interrupt load. Assisted-by: GitHub Copilot: claude-sonnet-5.5 Signed-off-by: Frederic Pillon --- cores/arduino/Serial.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index eb16c52861..3f43bdd2fa 100644 --- a/cores/arduino/Serial.cpp +++ b/cores/arduino/Serial.cpp @@ -597,7 +597,7 @@ size_t Uart::write(const uint8_t *buffer, size_t size) ret = 0; } else { size_t size_intermediate; - size_t available = availableForWrite(); + size_t available; size_t available_till_buffer_end = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; _written = true; @@ -610,7 +610,7 @@ size_t Uart::write(const uint8_t *buffer, size_t size) // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to free space - while (!availableForWrite()) { + while ((available = availableForWrite()) == 0) { // nop, the interrupt handler will free up space for us } From 9e016e953d51022d4f5073288247ac7398819245 Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Tue, 1 Dec 2026 09:01:22 +0100 Subject: [PATCH 3/3] fix(uart): don't lock up when the UART IRQ can't run Uart::write() on a full TX buffer, Uart::flush() and uart_debug_write() wait for the U(S)ART interrupt to make the transfer progress. When this interrupt can't be executed they wait for ever: interrupts disabled (PRIMASK, BASEPRI), or called from an exception with an equal or higher priority than the U(S)ART one (SysTick, HardFault, ...). The timeouts don't help as they rely on the SysTick interrupt. Add uart_irq_poll() which detects this situation and then processes the pending events by calling the HAL IRQ handler, as the interrupt would have done. Use it in the wait loops. If the handler can't be called safely (called from the U(S)ART interrupt itself, or while it is preempted), write() drops the remaining data and flush() returns, instead of locking up. write() returns the number of bytes queued. Tested on NUCLEO_C562RE (HAL v2, Cortex-M33): write() of 300 bytes then flush() with PRIMASK set, with BASEPRI masking the UART, from timer ISRs of a higher, equal and lower priority than the UART, and from a HardFault handler. All locked up before, except the lower priority one, and now output the data. Echo test at 921600 baud with interrupt load unchanged. Built for F4 (HAL v1, Cortex-M4) and G0 (Cortex-M0+). Fixes: #1834 Assisted-by: GitHub Copilot: claude-sonnet-5.5 Signed-off-by: Frederic Pillon --- cores/arduino/Serial.cpp | 48 ++++++++++++++++++++------- cores/arduino/Serial.h | 8 +++++ cores/arduino/stm32/uart.c | 57 ++++++++++++++++++++++++++++++++- libraries/SrcWrapper/inc/uart.h | 25 +++++++++++++++ 4 files changed, 125 insertions(+), 13 deletions(-) diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index 3f43bdd2fa..e4f77b076d 100644 --- a/cores/arduino/Serial.cpp +++ b/cores/arduino/Serial.cpp @@ -573,7 +573,12 @@ void Uart::flush(uint32_t timeout) if (_written) { uint32_t tickstart = HAL_GetTick(); while ((_serial.tx_head != _serial.tx_tail)) { - // the interrupt handler will free up space for us + // the interrupt handler will free up space for us, unless it can't + // be executed: then process its events here + if (uart_irq_poll(&_serial) == UART_IRQ_UNAVAILABLE) { + // nothing can make the transmission progress, don't wait for ever + break; + } // Only manage timeout if any if ((timeout != 0) && ((HAL_GetTick() - tickstart) >= timeout)) { // clear any transmit data @@ -586,6 +591,21 @@ void Uart::flush(uint32_t timeout) } } +size_t Uart::waitTxSpace(void) +{ + size_t space; + // If the output buffer is full, there's nothing for it other than to + // wait for the interrupt handler to free space + while ((space = availableForWrite()) == 0) { + // The interrupt handler will free up space for us, unless it can't be + // executed: then process its events here + if (uart_irq_poll(&_serial) == UART_IRQ_UNAVAILABLE) { + break; + } + } + return space; +} + size_t Uart::write(const uint8_t *buffer, size_t size) { size_t ret = size; @@ -596,10 +616,6 @@ size_t Uart::write(const uint8_t *buffer, size_t size) if (!_ready) { ret = 0; } else { - size_t size_intermediate; - size_t available; - size_t available_till_buffer_end = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; - _written = true; if (isHalfDuplex()) { if (_rx_enabled) { @@ -608,23 +624,31 @@ size_t Uart::write(const uint8_t *buffer, size_t size) } } - // If the output buffer is full, there's nothing for it other than to - // wait for the interrupt handler to free space - while ((available = availableForWrite()) == 0) { - // nop, the interrupt handler will free up space for us + size_t size_intermediate; + size_t available = availableForWrite(); + if (available == 0) { + available = waitTxSpace(); } + size_t available_till_buffer_end = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; // HAL doesn't manage rollover, so split transfer till end of TX buffer // Also, split transfer according to available space in buffer - while ((size > available_till_buffer_end) || (size > available)) { + while ((available != 0) && ((size > available_till_buffer_end) || (size > available))) { size_intermediate = min(available, available_till_buffer_end); write(buffer, size_intermediate); size -= size_intermediate; buffer += size_intermediate; - available = availableForWrite(); + available = waitTxSpace(); available_till_buffer_end = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; } + if (available == 0) { + // The TX interrupt can't free space and can't be polled: drop the + // remaining data instead of waiting for ever + ret -= size; + size = 0; + } + // Copy data to buffer. Take into account rollover if necessary. if (_serial.tx_head + size <= SERIAL_TX_BUFFER_SIZE) { memcpy(&_serial.tx_buff[_serial.tx_head], buffer, size); @@ -662,7 +686,7 @@ size_t Uart::write(const uint8_t *buffer, size_t size) __set_PRIMASK(primask); } - /* Return 0 if not ready else requested transfer size */ + /* Return 0 if not ready, else the number of bytes queued */ return ret; } diff --git a/cores/arduino/Serial.h b/cores/arduino/Serial.h index e317a4fdf0..a0f729c0c4 100644 --- a/cores/arduino/Serial.h +++ b/cores/arduino/Serial.h @@ -533,6 +533,14 @@ class Uart : public arduino::HardwareSerial { * @brief Reconfigure the UART for low-power operation. */ void configForLowPower(void); + /** + * @brief Wait until there is free space in the TX buffer. + * + * The TX interrupt is polled if it can't be executed (interrupts disabled, + * call from a high priority exception). + * @return The free space in bytes, 0 if it can't be freed. + */ + size_t waitTxSpace(void); }; diff --git a/cores/arduino/stm32/uart.c b/cores/arduino/stm32/uart.c index 97429714c8..fbfb12ca77 100644 --- a/cores/arduino/stm32/uart.c +++ b/cores/arduino/stm32/uart.c @@ -948,7 +948,8 @@ size_t uart_debug_write(uint8_t *data, uint32_t size) } while (serial_tx_active(obj)) { - if ((HAL_GetTick() - tickstart) >= TX_TIMEOUT) { + if ((uart_irq_poll(obj) == UART_IRQ_UNAVAILABLE) + || ((HAL_GetTick() - tickstart) >= TX_TIMEOUT)) { return 0; } } @@ -969,6 +970,60 @@ uint8_t serial_tx_active(serial_t *obj) #endif } +/** + * @brief Check if the U(S)ART interrupt can't be executed now + * @param obj Pointer on the serial object + * @return true if the interrupt is masked or can't preempt the current context + */ +static bool uart_irq_blocked(serial_t *obj) +{ + bool blocked = (__get_PRIMASK() != 0U); + + /* NVIC_GetPriority() returns the priority without the unused low bits. + * It reads the NVIC (slow), only do it when needed: this function is called + * in loops waiting for the interrupt. */ +#if defined(__CORTEX_M) && (__CORTEX_M > 0U) + if (!blocked) { + uint32_t basepri = __get_BASEPRI(); + /* BASEPRI masks the interrupts with a priority value greater or equal */ + blocked = (basepri != 0U) + && ((NVIC_GetPriority(obj->irq) << (8U - __NVIC_PRIO_BITS)) >= basepri); + } +#endif + + if (!blocked) { + uint32_t ipsr = __get_IPSR(); + if (ipsr != 0U) { + /* NMI and HardFault (exception 2 and 3) have a fixed priority, above any interrupt. + * Otherwise, an exception can't be preempted by one of an equal or lower priority */ + blocked = (ipsr < 4U) + || (NVIC_GetPriority((IRQn_Type)((int32_t)ipsr - 16)) <= NVIC_GetPriority(obj->irq)); + } + } + return blocked; +} + +uart_irq_status_t uart_irq_poll(serial_t *obj) +{ + uart_irq_status_t status = UART_IRQ_AVAILABLE; + + if (uart_irq_blocked(obj)) { + /* The HAL handler is not reentrant: don't call it from the U(S)ART interrupt itself + * (e.g. from a hook) or if it has been preempted. The latter can't be detected on Cortex-M0(+) */ + bool reentrant = (__get_IPSR() == ((uint32_t)obj->irq + 16U)); +#if defined(__CORTEX_M) && (__CORTEX_M > 0U) + reentrant = reentrant || (NVIC_GetActive(obj->irq) != 0U); +#endif + if (reentrant) { + status = UART_IRQ_UNAVAILABLE; + } else { + HAL_UART_IRQHandler(uart_handlers[obj->index]); + status = UART_IRQ_POLLED; + } + } + return status; +} + /* * Unused: return the index of the serial handler (UART_NUM if not found) * diff --git a/libraries/SrcWrapper/inc/uart.h b/libraries/SrcWrapper/inc/uart.h index 441e8c3658..05907adef0 100644 --- a/libraries/SrcWrapper/inc/uart.h +++ b/libraries/SrcWrapper/inc/uart.h @@ -351,6 +351,31 @@ void uart_attach_tx_callback(serial_t *obj, int (*callback)(serial_t *), size_t * @return Non-zero if the TX transaction is ongoing, 0 otherwise. */ uint8_t serial_tx_active(serial_t *obj); + +/** + * @brief Result of uart_irq_poll(). + */ +typedef enum { + /** The U(S)ART interrupt can be executed: just wait for it. */ + UART_IRQ_AVAILABLE, + /** The U(S)ART interrupt is blocked: its events have been processed by hand. */ + UART_IRQ_POLLED, + /** The U(S)ART interrupt is blocked and can't be polled: waiting is endless. */ + UART_IRQ_UNAVAILABLE +} uart_irq_status_t; + +/** + * @brief Let a transfer progress when the U(S)ART interrupt can't be executed. + * + * It is the case when interrupts are disabled (PRIMASK, BASEPRI), or when called + * from an exception of an equal or higher priority than the U(S)ART interrupt + * (SysTick, HardFault, ...). The pending events are then processed by calling + * the HAL IRQ handler, as if the interrupt occurred. + * To be called in the loops which wait for the end of a transfer. + * @param obj The serial object. + * @return The status, see uart_irq_status_t. + */ +uart_irq_status_t uart_irq_poll(serial_t *obj); /** * @brief Determine if the serial peripheral is already in use for RX. * @param obj The serial object.