diff --git a/cores/arduino/Serial.cpp b/cores/arduino/Serial.cpp index 6ee2e1a42a..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 = availableForWrite(); - size_t available_till_buffer_end = SERIAL_TX_BUFFER_SIZE - _serial.tx_head; - _written = true; if (isHalfDuplex()) { if (_rx_enabled) { @@ -608,27 +624,34 @@ 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()) { - // 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); - 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,20 +660,33 @@ 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 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.