Skip to content

Commit eb86af7

Browse files
Fix lockup when writing to HardwareSerial with interrupts disabled
When interrupts are disabled, writing to HardwareSerial could cause a lockup. When the tx buffer is full, a busy-wait loop is used to wait for the interrupt handler to free up a byte in the buffer. However, when interrupts are disabled, this will of course never happen and the Arduino will lock up. This often caused lockups when doing (big) debug printing from an interrupt handler. Additionally, calling flush() with interrupts disabled while transmission was in progress would also cause a lockup. When interrupts are disabled, the code now actively checks the UDRE (UART Data Register Empty) and calls the interrupt handler to free up room if the bit is set. This can lead to delays in interrupt handlers when the serial buffer is full, but a delay is of course always preferred to a lockup. Closes: arduino#672 References: arduino#1147
1 parent b7e9bb4 commit eb86af7

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

hardware/arduino/avr/cores/arduino/HardwareSerial.cpp

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,14 @@ void HardwareSerial::flush()
349349
if (!_written)
350350
return;
351351

352-
while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0));
352+
while (bit_is_set(*_ucsrb, UDRIE0) || bit_is_clear(*_ucsra, TXC0)) {
353+
if (bit_is_clear(SREG, SREG_I) && bit_is_set(*_ucsrb, UDRIE0))
354+
// Interrupts are globally disabled, but the DR empty
355+
// interrupt should be enabled, so poll the DR empty flag to
356+
// prevent deadlock
357+
if (bit_is_set(*_ucsra, UDRE0))
358+
_tx_udr_empty_irq();
359+
}
353360
// If we get here, nothing is queued anymore (DRIE is disabled) and
354361
// the hardware finished tranmission (TXC is set).
355362
}
@@ -360,10 +367,19 @@ size_t HardwareSerial::write(uint8_t c)
360367

361368
// If the output buffer is full, there's nothing for it other than to
362369
// wait for the interrupt handler to empty it a bit
363-
// ???: return 0 here instead?
364-
while (i == _tx_buffer_tail)
365-
;
366-
370+
while (i == _tx_buffer_tail) {
371+
if (bit_is_clear(SREG, SREG_I)) {
372+
// Interrupts are disabled, so we'll have to poll the data
373+
// register empty flag ourselves. If it is set, pretend an
374+
// interrupt has happened and call the handler to free up
375+
// space for us.
376+
if(bit_is_set(*_ucsra, UDRE0))
377+
_tx_udr_empty_irq();
378+
} else {
379+
// nop, the interrupt handler will free up space for us
380+
}
381+
}
382+
367383
_tx_buffer[_tx_buffer_head] = c;
368384
_tx_buffer_head = i;
369385

0 commit comments

Comments
 (0)