English Chinese (Simplified) (zh_CN)
Chapter 2. Locking Notes
Locking Notes 内核中的锁
_This chapter is maintained by the FreeBSD SMP Next Generation Project._
This document outlines the locking used in the FreeBSD kernel to permit effective multi-processing within the kernel. Locking can be achieved via several means. Data structures can be protected by mutexes or man:lockmgr[9] locks. A few variables are protected simply by always using atomic operations to access them.
Mutexes Mutex
A mutex is simply a lock used to guarantee mutual exclusion. Specifically, a mutex may only be owned by one entity at a time. If another entity wishes to obtain a mutex that is already owned, it must wait until the mutex is released. In the FreeBSD kernel, mutexes are owned by processes. Mutex就是一种用来解决共享/排它矛盾的锁。 一个mutex在一个时刻只可以被一个实体拥有。如果另一个实体要获得已经被拥有的mutex, 就会进入等待,直到这个mutex被释放。在FreeBSD内核中,mutex被进程所拥有。
Mutexes may be recursively acquired, but they are intended to be held for a short period of time. Specifically, one may not sleep while holding a mutex. If you need to hold a lock across a sleep, use a man:lockmgr[9] lock.
Each mutex has several properties of interest: 每个mutex有几个令人感兴趣的属性:
Variable Name 变量名
The name of the struct mtx variable in the kernel source.
Logical Name 逻辑名
The name of the mutex assigned to it by `mtx_init`. This name is displayed in KTR trace messages and witness errors and warnings and is used to distinguish mutexes in the witness code.
Type 类型
The type of the mutex in terms of the `MTX_*` flags. The meaning for each flag is related to its meaning as documented in man:mutex[9].
A sleep mutex 一个睡眠 mutex
A spin mutex 一个循环 mutex
This mutex is allowed to recurse. 这个 mutex 允许递归。