Kind of a weird question, but I'm in a class about linux kernel driver development and the prof couldn't answer this.
Let's suppose I have a finite state machine of some kind attached to an SPI or I2C bus (In real life this is actually an accelerometer, but the implementation isn't important). If I write a misc character driver for it, and insmod it, any user on the system can now access this device.
Let's suppose that I want to read 200 bytes of data from this FSM device. A read is performed by sending the register address of the data location, and performing a continuous read until I have my 200 bytes (program#1).
The confusion comes in when I know my user level program is getting time-sliced. If another (program#2) user level program is also going to ask for 10 bytes from this accelerometer, it will address and continuously read until it has it's 10 bytes.
If program#1 has run and read 50 bytes when it gets time-sliced out, and program#2 is run to completion, then when program#1 returns, the address it was reading from is corrupted, and it's reading data from the wrong address.
Time slices are invisible to the user. As far as I know they're also invisible to the kernel driver code. Is there some mechanism to avoid this? Atomic read and writes would make the most sense, but these I2C/SPI devices are slow by CPU standards. I can't imagine the CPU would sit idly by for the entire time just to ensure an I2C/SPI read/write is atomic?
The answer the prof gave me is that this problem has been solved for memory a long time ago, and linux is "probably doing something fancy under the hood" to make it happen. But that didn't really address the root of the question. I'd love a proper answer. If anyone can recommend better search terms to approach the question I would also appreciate it.
Thank you
If I get your question right, the whole problem is about locking the device that is used by multiple programs (threads, etc.) and this post may have an answer to it.
Your professor was partially right. The problem was discovered a long time ago, it's called the race conditions. But, the solution isn't provided by the kernel itself in a fancy way. It is the user's responsibility to implement a mechanism that can prevent race conditions on devices or any other resources.