Skip to content

HardwareSerial: race in Uart::write() restarts TX from an empty buffer and resends the whole TX buffer #3125

In review

Description

@nedseb

Uart::write() queues the data, then starts a HAL transfer if none is ongoing. The two steps are not atomic
(Serial.cpp L641-L651):

    // 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)) {
      _serial.tx_size = size_intermediate;
      uart_attach_tx_callback(&_serial, _tx_complete_irq, size_intermediate);
    }

If I read the code correctly, when the main loop is preempted between the tx_head update and the
serial_tx_active() check for longer than the new data takes to send:

  1. the TX complete interrupt (_tx_complete_irq(),
    L372-L391)
    sees the new data, sends it, and leaves the UART idle with tx_tail == tx_head;
  2. write() then finds no transfer ongoing and starts one from &tx_buff[tx_tail]
    (uart_serial.c L87-L109),
    although the buffer is empty: a stale byte is sent;
  3. at the end of that transfer tx_tail has passed tx_head, so _tx_complete_irq() sees
    SERIAL_TX_BUFFER_SIZE - 1 bytes pending and sends them.

The result is that the last SERIAL_TX_BUFFER_SIZE bytes (64 by default) are sent a second time. Less often, one
byte is replaced by the byte written SERIAL_TX_BUFFER_SIZE bytes earlier. Nothing is lost, so the output just looks
like repeated or garbled text.

It seems to need the main loop to be held by interrupts for about a character time at that exact point, so it
probably only shows up under heavy interrupt load: full-duplex traffic at high baud rates, or a busy application ISR.

This was already seen in Marlin

Marlin identified the same race on STM32F0 and STM32F1 boards and fixed it on their side in
MarlinFirmware/Marlin#28904 ("Make STM32 serial write atomic"), by calling the core's write() with interrupts
disabled. As far as I could find, no issue was opened here, and the code still looks the same on main.

To Reproduce

Any sketch that writes while receiving at a high rate, for example an echo:

void setup() {
  Serial.begin(921600);
}

void loop() {
  while (Serial.available()) {
    Serial.write(Serial.read());
  }
}

From the host, stream random bytes and compare what comes back. With an echo sketch along these lines (ours also
buffers and throttles the echo), 64 KB echoed at full rate come back with a few blocks of exactly 64 bytes repeated,
each one a copy of the 64 bytes just before it. To check where they come from:

  • built with -D SERIAL_TX_BUFFER_SIZE=128, the repeated blocks become exactly 128 bytes long;
  • with Serial.write() called with interrupts disabled (Marlin's workaround, from the sketch), there are no repeated
    blocks at all, and no lost bytes either.

Possible fix

I may be missing something, but making these lines a critical section in Uart::write() might be enough. I think
it would need PRIMASK, saved and restored (#1834), since uart_attach_tx_callback() re-enables the UART IRQ itself:

    uint32_t primask = __get_PRIMASK();
    __disable_irq();
    _serial.tx_head = (_serial.tx_head + size) % SERIAL_TX_BUFFER_SIZE;
    if (!serial_tx_active(&_serial)) {
      _serial.tx_size = size_intermediate;
      uart_attach_tx_callback(&_serial, _tx_complete_irq, size_intermediate);
    }
    __set_PRIMASK(primask);

I have only tested the equivalent from the sketch, not a patched core. If it seems reasonable, I would be happy to
try a PR.

Related

Activity

  1. added
    bug 🐛
    on Nov 30, 2026
  2. added this to the 3.2.0 milestone on Nov 30, 2026
  3. fpistm commented on Nov 30, 2026

    @fpistm
    Member

    Hi @nedseb,

    Thank you for the very detailed report: the analysis of the race, the links to
    the related issues and the Marlin fix, and the reproduction hints made it easy
    to confirm and fix.

    I reproduced it on a NUCLEO_C562RE and opened #3128 with a fix along the lines
    you proposed (the tx_head update and the transfer start in a critical section
    with PRIMASK saved/restored). The transfer size is also computed from
    tx_head/tx_tail inside the critical section, and a transfer is started only
    if data are pending.

    Could you please review the PR and test it with your setup (the full-rate echo
    sketch that showed the repeated 64-byte blocks)? Feedback on other boards or
    baud rates would be welcome.

    Thanks!

  4. nedseb commented on Nov 30, 2026

    @nedseb
    ContributorAuthor

    Thank you so much!

    I'll try it tomorrow. I am on this bug for several weeks and I investigate mainly on Daplink without finding the reason of this repeated 64 bytes.

    Best regards

    Sébastien

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug 🐛

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions