Skip to content

HardwareSerial: flush(timeout) can resend old bytes when the timeout expires during a transfer #3130

Backlog

Description

@nedseb

Follow-up to #3128, as suggested there.

Uart::flush(uint32_t timeout) is documented as "On timeout, the pending transmit data is discarded". On timeout it sets tx_head = tx_tail
(Serial.cpp L578-L581):

      if ((timeout != 0) && ((HAL_GetTick() - tickstart) >= timeout)) {
        // clear any transmit data
        _serial.tx_head = _serial.tx_tail;
        break;
      }

The HAL transfer started for these bytes (tx_size bytes from tx_tail) is still running at that point. When it completes, _tx_complete_irq() moves the tail past the head.
(Serial.cpp L376):

  obj->tx_tail = (obj->tx_tail + obj->tx_size) % SERIAL_TX_BUFFER_SIZE;

so tx_head != tx_tail, and it sends the SERIAL_TX_BUFFER_SIZE - tx_size bytes that follow in the ring, which are old data. Instead of being discarded, the output gets up to a whole buffer of stale bytes.

It needs a timeout shorter than the transfer in progress, so it probably shows up mostly at low baud rates or with a short timeout. end() calls flush(TX_TIMEOUT) (1 s) and then uart_deinit(), which resets the U(S)ART, so I think end() itself is not affected in practice.

At 9600 baud, 10 bytes take about 10 ms, so a 3 ms timeout expires in the middle of the transfer:

void setup() {
  Serial.begin(9600);
  // Fill the whole TX ring with 'x' (64 bytes by default), and send it.
  for (int i = 0; i < SERIAL_TX_BUFFER_SIZE; i++) {
    Serial.write('x');
  }
  Serial.flush();
  // 10 new bytes, then a timeout shorter than their transfer.
  Serial.write("ABCDEFGHIJ", 10);
  Serial.flush(3);
}

void loop() {}

Expected on the host: 64 x then ABCDEFGHIJ (74 bytes).

What I get on a STeaMi (STM32WB55, Serial on LPUART1) with main (5bdb3b9): 64 x, ABCDEFGHIJ, then 54 more x, the rest of the ring (128 bytes). This happened in all 5 runs.

Possible fix

I may be missing something, but one way could be to drop only what is not in the running transfer in a critical section like the one #3128 adds to write(). With this change in flush(uint32_t), the same test gives the expected 74 bytes in all 5 runs:

        uint32_t primask = __get_PRIMASK();
        __disable_irq();
        if (serial_tx_active(&_serial)) {
          // keep the bytes being sent, drop the rest
          _serial.tx_head = (_serial.tx_tail + _serial.tx_size) % SERIAL_TX_BUFFER_SIZE;
        } else {
          _serial.tx_head = _serial.tx_tail;
        }
        __set_PRIMASK(primask);

Related

Activity

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions