gpt4 book ai didi

linux设备驱动文件操作: it is possible to have race conditions?

转载 作者:IT王子 更新时间:2023-10-29 01:23:13 30 4
gpt4 key购买 nike

考虑一个实现 open()、read()、write()、close()、unlocked_ioctl() 和 mmap() 的 linux 设备驱动程序。

现在,假设多个(或相同的)进程同时打开同一个设备 (/dev/device)。

这些文件操作是否以任何方式保证是原子的 w.r.t.彼此或 open()、read()、write()、close() 中的每一个都应该采用互斥锁,以便它们中的一对不会在更改过程中抢占它们,例如,缓冲区数据(通过相同的 inode)?

如果内核保证它们相对于彼此的原子性,并且如果每个操作找到并使缓冲区/硬件处于一致状态,则没有必要。

请将我重定向到一些引用(如果你知道的话)。

谢谢。

编辑:它在其中一条评论中,但我找到的最佳引用在这里:

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

它还展示了缓解问题的策略,可以通过限制单个用户使用、通过创建副本、或者通过强制用户等待等方式来解决。

最佳答案

设备驱动程序代码在调用系统调用的进程中运行。内核没有在调用模块代码之前锁定的隐式“模块锁”。当单独的进程调用最终出现在您的驱动程序代码中的系统调用时,并发驱动程序调用肯定有可能发生。

如您所料,内核更注重简单性和性能,而不是易于实现。在访问共享状态时获取必要的自旋锁和信号量取决于您。

参见 Chapter 5Linux Device Drivers ,其中非常详细地讨论了并发和竞争条件。

Concurrency and Its Management

In a modern Linux system, there are numerous sources of concurrency and, therefore, possible race conditions. Multiple user-space processes are running, and they can access your code in surprising combinations of ways. SMP systems can be executing your code simultaneously on different processors. Kernel code is preemptible; your driver’s code can lose the processor at any time, and the process that replaces it could also be running in your driver. Device interrupts are asynchronous events that can cause concurrent execution of your code. The kernel also provides various mechanisms for delayed code execution, such as workqueues, tasklets, and timers, which can cause your code to run at any time in ways unrelated to what the current process is doing. In the modern, hot-pluggable world, your device could simply disappear while you are in the middle of working with it.

关于linux设备驱动文件操作: it is possible to have race conditions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874962/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com