![How does preemption work during hardware I/O?](https://linux22.com/image/183776/How%20does%20preemption%20work%20during%20hardware%20I%2FO%3F.png)
Say I have a device that uses SPI or another communication protocol to talk with my computer running Linux, Raspberry Pi for instance. For this communication to succeed, no interruptions are allowed, because otherwise the time window for data to be transmitted or received would be missed. However, doesn't Linux exactly do that? Interrupt a process and perform a context switch to run the next process? If for some reason this doesn't happen in the case I described, why not and why doesn't the desktop appear frozen?
Also, how can we guarantee that a peer will write/read data exactly when the clock signal goes high or low? What if the peer is doing something else other than monitoring the clock when it changes? Even in Arduino, how is any data through Serial saved in a buffer somewhere while the Arduino might be doing something else?
答案1
This is where interrupt priority comes in:
An interrupt can only interrupt a lower priority interrupt (background processing is the lowest priority). The pre-emption interrupt will be lower priority than the time-critical interrupt, so it will not be interrupted by a task switch, the task switch just has to wait.
There are a few rules that system (hardware and kernel) designers must follow to make this work.
- Time critical interrupts have the higher priority.
- High priority interrupts must do their thing and get out of the way as soon as possible. e.g. just shift the data, or better set up the hardware to shift the data. It could then ask a low priority interrupt, or regular process to do the processing.