From a9061d20685adaec8d2474b8de6787e5b63b5246 Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Wed, 2 Dec 2026 14:41:48 +0100 Subject: [PATCH] fix(uart): don't resend old data on flush() timeout When Uart::flush(timeout) expired during a HAL transfer, it set tx_head = tx_tail to discard the pending data. But the transfer in progress can't be cancelled: at its completion _tx_complete_irq() moves tx_tail by tx_size, past tx_head. The buffer then looks almost full and up to SERIAL_TX_BUFFER_SIZE - tx_size old bytes are sent again. On timeout, only discard the data which is not in the transfer in progress: tx_head = tx_tail + tx_size. This is done in a critical section, as the TX complete IRQ may end the transfer and start the next one at any time. If no transfer is active, reset tx_head to tx_tail as before. Tested on NUCLEO_G431RB (Serial on LPUART1) and NUCLEO_L053R8 (Serial on USART2): with a TX buffer filled and sent, then 32 bytes written and flush(3) at 57600 baud, 32 stale bytes were received after the 32 bytes without this change, and none with it (20 runs). Fixes: #3130 Assisted-by: GitHub Copilot: claude-sonnet-5.5 Signed-off-by: Frederic Pillon --- cores/arduino/Serial.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index e4f77b076d..62ba97f995 100644 --- a/cores/arduino/Serial.cpp +++ b/cores/arduino/Serial.cpp @@ -581,8 +581,20 @@ void Uart::flush(uint32_t timeout) } // Only manage timeout if any if ((timeout != 0) && ((HAL_GetTick() - tickstart) >= timeout)) { - // clear any transmit data - _serial.tx_head = _serial.tx_tail; + // Discard the pending transmit data, except the bytes of the HAL + // transfer in progress: it can't be cancelled, and its completion + // moves tail by tx_size. Doing it atomically as the TX complete IRQ + // may end this transfer and start the next one at any time. + // PRIMASK is restored (not unconditionally enabled) as flush() may be + // called with interrupts already disabled. + uint32_t primask = __get_PRIMASK(); + __disable_irq(); + if (serial_tx_active(&_serial)) { + _serial.tx_head = (_serial.tx_tail + _serial.tx_size) % SERIAL_TX_BUFFER_SIZE; + } else { + _serial.tx_head = _serial.tx_tail; + } + __set_PRIMASK(primask); break; } }