diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index 6ee2e1a42a..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 } @@ -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;