From 2dd89163b55c1c61abc907ccbeb740b9a7eda783 Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Tue, 1 Dec 2026 09:01:22 +0100 Subject: [PATCH] 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.