Linux device driver file operations: is it possible to have race conditions?

Consider a Linux device driver that implements the functions open (), read (), write (), close (), unlocked_ioctl (), and possibly mmap ().

Now imagine that several (or the same) processes simultaneously open the same device (/ dev / device).

Are these file operations guaranteed in any way atomic wrt to each other or should each of open (), read (), write (), close () accept a mutex so that one of their pairs does not preempt them, being in the middle of the change, for example , buffer data (via the same index)?

It is not necessary that the kernel guarantees their atomicity with respect to each other, and if each operation finds and leaves the buffer / hardware in a consistent state.

Please redirect me to some link (if you know).

Thanks.

edit: it is in one of the comments, but the best link I found is here:

http://www.makelinux.net/ldd3/chp-6-sect-6

It also shows strategies to alleviate the problem, either by restricting one user, or by making copies, or by making the user wait, etc.

+4
source share
1 answer

The device driver code runs in a process that calls system calls. The kernel does not have a hidden module lock, which it blocks before calling the module code. Of course, simultaneous driver calls are possible when individual processes call system calls that fall into your driver code.

As expected, the kernel contributes to simplicity and performance due to its ease of implementation. You must capture the necessary spinlocks and semaphores when accessing the shared state.

See Chapter 5 Linux device drivers for more information on concurrency and race conditions.

Concurrency and its management

In a modern Linux system, there are many sources of concurrency and, therefore, possible race conditions. Several processes are running in user space, and they can access your code in amazing combinations of ways. SMP systems can simultaneously execute your code on different processors. Kernel code is preemptive; your driver code may lose the processor at any time, and the process that replaces it may also work in your driver. Device interrupts are asynchronous events that can cause your code to execute at the same time. The kernel also provides various mechanisms for executing slow-motion code, such as workqueues, tasklets, and timers, which can cause your code to be launched at any time in ways unrelated to what the current process is doing. In a modern, hot plug-in world, your device may simply disappear while you are in the middle of working with it.

+4
source

Source: https://habr.com/ru/post/1502833/


All Articles