Skip to content

HardwareSerial atomicity issues #177

Open
@matthijskooijman

Description

@matthijskooijman

I just realized that there might be an atomicity issue in HardwareSerial. So far, we've assumed that the RX buffer is filled by an ISR and emptied by the main loop and that the TX buffer is filled by the main loop and emptied by an ISR (in other words, the head and tail pointers are only written in one "thread" and read by the other). However, when writing to or reading from the serial port from inside an (other) ISR violates this assumption.

Recently, HardwareSerial was modified to not lock up when writing from inside an ISR, but right now bytes written inside an ISR could still be dropped (or bytes read could be read twice). Note that it can still happen that serial printing blocks for a while when the buffer is full, which is typically a bad idea inside an ISR.

The problem is that updating the head and tail pointers is not atomic - it's read - increment - write. If, inside the write function an interrupt triggers between the read and the write that also calls write, the change of the head pointer that happens inside the ISR will be overwritten by the main thread - effectively dropping the byte.

To fix this, the increment should happen with (all) interrupts disabled, incurring a small overhead and interrupt latency.

Do we think this is a problem? Or is serial printing from inside an ISR considered bad practice and to be used for debugging only and is dropping a byte here or there acceptable?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions