lockdep-design.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. Runtime locking correctness validator
  2. =====================================
  3. started by Ingo Molnar <[email protected]>
  4. additions by Arjan van de Ven <[email protected]>
  5. Lock-class
  6. ----------
  7. The basic object the validator operates upon is a 'class' of locks.
  8. A class of locks is a group of locks that are logically the same with
  9. respect to locking rules, even if the locks may have multiple (possibly
  10. tens of thousands of) instantiations. For example a lock in the inode
  11. struct is one class, while each inode has its own instantiation of that
  12. lock class.
  13. The validator tracks the 'usage state' of lock-classes, and it tracks
  14. the dependencies between different lock-classes. Lock usage indicates
  15. how a lock is used with regard to its IRQ contexts, while lock
  16. dependency can be understood as lock order, where L1 -> L2 suggests that
  17. a task is attempting to acquire L2 while holding L1. From lockdep's
  18. perspective, the two locks (L1 and L2) are not necessarily related; that
  19. dependency just means the order ever happened. The validator maintains a
  20. continuing effort to prove lock usages and dependencies are correct or
  21. the validator will shoot a splat if incorrect.
  22. A lock-class's behavior is constructed by its instances collectively:
  23. when the first instance of a lock-class is used after bootup the class
  24. gets registered, then all (subsequent) instances will be mapped to the
  25. class and hence their usages and dependecies will contribute to those of
  26. the class. A lock-class does not go away when a lock instance does, but
  27. it can be removed if the memory space of the lock class (static or
  28. dynamic) is reclaimed, this happens for example when a module is
  29. unloaded or a workqueue is destroyed.
  30. State
  31. -----
  32. The validator tracks lock-class usage history and divides the usage into
  33. (4 usages * n STATEs + 1) categories:
  34. where the 4 usages can be:
  35. - 'ever held in STATE context'
  36. - 'ever held as readlock in STATE context'
  37. - 'ever held with STATE enabled'
  38. - 'ever held as readlock with STATE enabled'
  39. where the n STATEs are coded in kernel/locking/lockdep_states.h and as of
  40. now they include:
  41. - hardirq
  42. - softirq
  43. where the last 1 category is:
  44. - 'ever used' [ == !unused ]
  45. When locking rules are violated, these usage bits are presented in the
  46. locking error messages, inside curlies, with a total of 2 * n STATEs bits.
  47. A contrived example::
  48. modprobe/2287 is trying to acquire lock:
  49. (&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24
  50. but task is already holding lock:
  51. (&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24
  52. For a given lock, the bit positions from left to right indicate the usage
  53. of the lock and readlock (if exists), for each of the n STATEs listed
  54. above respectively, and the character displayed at each bit position
  55. indicates:
  56. === ===================================================
  57. '.' acquired while irqs disabled and not in irq context
  58. '-' acquired in irq context
  59. '+' acquired with irqs enabled
  60. '?' acquired in irq context with irqs enabled.
  61. === ===================================================
  62. The bits are illustrated with an example::
  63. (&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24
  64. ||||
  65. ||| \-> softirq disabled and not in softirq context
  66. || \--> acquired in softirq context
  67. | \---> hardirq disabled and not in hardirq context
  68. \----> acquired in hardirq context
  69. For a given STATE, whether the lock is ever acquired in that STATE
  70. context and whether that STATE is enabled yields four possible cases as
  71. shown in the table below. The bit character is able to indicate which
  72. exact case is for the lock as of the reporting time.
  73. +--------------+-------------+--------------+
  74. | | irq enabled | irq disabled |
  75. +--------------+-------------+--------------+
  76. | ever in irq | '?' | '-' |
  77. +--------------+-------------+--------------+
  78. | never in irq | '+' | '.' |
  79. +--------------+-------------+--------------+
  80. The character '-' suggests irq is disabled because if otherwise the
  81. charactor '?' would have been shown instead. Similar deduction can be
  82. applied for '+' too.
  83. Unused locks (e.g., mutexes) cannot be part of the cause of an error.
  84. Single-lock state rules:
  85. ------------------------
  86. A lock is irq-safe means it was ever used in an irq context, while a lock
  87. is irq-unsafe means it was ever acquired with irq enabled.
  88. A softirq-unsafe lock-class is automatically hardirq-unsafe as well. The
  89. following states must be exclusive: only one of them is allowed to be set
  90. for any lock-class based on its usage::
  91. <hardirq-safe> or <hardirq-unsafe>
  92. <softirq-safe> or <softirq-unsafe>
  93. This is because if a lock can be used in irq context (irq-safe) then it
  94. cannot be ever acquired with irq enabled (irq-unsafe). Otherwise, a
  95. deadlock may happen. For example, in the scenario that after this lock
  96. was acquired but before released, if the context is interrupted this
  97. lock will be attempted to acquire twice, which creates a deadlock,
  98. referred to as lock recursion deadlock.
  99. The validator detects and reports lock usage that violates these
  100. single-lock state rules.
  101. Multi-lock dependency rules:
  102. ----------------------------
  103. The same lock-class must not be acquired twice, because this could lead
  104. to lock recursion deadlocks.
  105. Furthermore, two locks can not be taken in inverse order::
  106. <L1> -> <L2>
  107. <L2> -> <L1>
  108. because this could lead to a deadlock - referred to as lock inversion
  109. deadlock - as attempts to acquire the two locks form a circle which
  110. could lead to the two contexts waiting for each other permanently. The
  111. validator will find such dependency circle in arbitrary complexity,
  112. i.e., there can be any other locking sequence between the acquire-lock
  113. operations; the validator will still find whether these locks can be
  114. acquired in a circular fashion.
  115. Furthermore, the following usage based lock dependencies are not allowed
  116. between any two lock-classes::
  117. <hardirq-safe> -> <hardirq-unsafe>
  118. <softirq-safe> -> <softirq-unsafe>
  119. The first rule comes from the fact that a hardirq-safe lock could be
  120. taken by a hardirq context, interrupting a hardirq-unsafe lock - and
  121. thus could result in a lock inversion deadlock. Likewise, a softirq-safe
  122. lock could be taken by an softirq context, interrupting a softirq-unsafe
  123. lock.
  124. The above rules are enforced for any locking sequence that occurs in the
  125. kernel: when acquiring a new lock, the validator checks whether there is
  126. any rule violation between the new lock and any of the held locks.
  127. When a lock-class changes its state, the following aspects of the above
  128. dependency rules are enforced:
  129. - if a new hardirq-safe lock is discovered, we check whether it
  130. took any hardirq-unsafe lock in the past.
  131. - if a new softirq-safe lock is discovered, we check whether it took
  132. any softirq-unsafe lock in the past.
  133. - if a new hardirq-unsafe lock is discovered, we check whether any
  134. hardirq-safe lock took it in the past.
  135. - if a new softirq-unsafe lock is discovered, we check whether any
  136. softirq-safe lock took it in the past.
  137. (Again, we do these checks too on the basis that an interrupt context
  138. could interrupt _any_ of the irq-unsafe or hardirq-unsafe locks, which
  139. could lead to a lock inversion deadlock - even if that lock scenario did
  140. not trigger in practice yet.)
  141. Exception: Nested data dependencies leading to nested locking
  142. -------------------------------------------------------------
  143. There are a few cases where the Linux kernel acquires more than one
  144. instance of the same lock-class. Such cases typically happen when there
  145. is some sort of hierarchy within objects of the same type. In these
  146. cases there is an inherent "natural" ordering between the two objects
  147. (defined by the properties of the hierarchy), and the kernel grabs the
  148. locks in this fixed order on each of the objects.
  149. An example of such an object hierarchy that results in "nested locking"
  150. is that of a "whole disk" block-dev object and a "partition" block-dev
  151. object; the partition is "part of" the whole device and as long as one
  152. always takes the whole disk lock as a higher lock than the partition
  153. lock, the lock ordering is fully correct. The validator does not
  154. automatically detect this natural ordering, as the locking rule behind
  155. the ordering is not static.
  156. In order to teach the validator about this correct usage model, new
  157. versions of the various locking primitives were added that allow you to
  158. specify a "nesting level". An example call, for the block device mutex,
  159. looks like this::
  160. enum bdev_bd_mutex_lock_class
  161. {
  162. BD_MUTEX_NORMAL,
  163. BD_MUTEX_WHOLE,
  164. BD_MUTEX_PARTITION
  165. };
  166. mutex_lock_nested(&bdev->bd_contains->bd_mutex, BD_MUTEX_PARTITION);
  167. In this case the locking is done on a bdev object that is known to be a
  168. partition.
  169. The validator treats a lock that is taken in such a nested fashion as a
  170. separate (sub)class for the purposes of validation.
  171. Note: When changing code to use the _nested() primitives, be careful and
  172. check really thoroughly that the hierarchy is correctly mapped; otherwise
  173. you can get false positives or false negatives.
  174. Annotations
  175. -----------
  176. Two constructs can be used to annotate and check where and if certain locks
  177. must be held: lockdep_assert_held*(&lock) and lockdep_*pin_lock(&lock).
  178. As the name suggests, lockdep_assert_held* family of macros assert that a
  179. particular lock is held at a certain time (and generate a WARN() otherwise).
  180. This annotation is largely used all over the kernel, e.g. kernel/sched/
  181. core.c::
  182. void update_rq_clock(struct rq *rq)
  183. {
  184. s64 delta;
  185. lockdep_assert_held(&rq->lock);
  186. [...]
  187. }
  188. where holding rq->lock is required to safely update a rq's clock.
  189. The other family of macros is lockdep_*pin_lock(), which is admittedly only
  190. used for rq->lock ATM. Despite their limited adoption these annotations
  191. generate a WARN() if the lock of interest is "accidentally" unlocked. This turns
  192. out to be especially helpful to debug code with callbacks, where an upper
  193. layer assumes a lock remains taken, but a lower layer thinks it can maybe drop
  194. and reacquire the lock ("unwittingly" introducing races). lockdep_pin_lock()
  195. returns a 'struct pin_cookie' that is then used by lockdep_unpin_lock() to check
  196. that nobody tampered with the lock, e.g. kernel/sched/sched.h::
  197. static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf)
  198. {
  199. rf->cookie = lockdep_pin_lock(&rq->lock);
  200. [...]
  201. }
  202. static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf)
  203. {
  204. [...]
  205. lockdep_unpin_lock(&rq->lock, rf->cookie);
  206. }
  207. While comments about locking requirements might provide useful information,
  208. the runtime checks performed by annotations are invaluable when debugging
  209. locking problems and they carry the same level of details when inspecting
  210. code. Always prefer annotations when in doubt!
  211. Proof of 100% correctness:
  212. --------------------------
  213. The validator achieves perfect, mathematical 'closure' (proof of locking
  214. correctness) in the sense that for every simple, standalone single-task
  215. locking sequence that occurred at least once during the lifetime of the
  216. kernel, the validator proves it with a 100% certainty that no
  217. combination and timing of these locking sequences can cause any class of
  218. lock related deadlock. [1]_
  219. I.e. complex multi-CPU and multi-task locking scenarios do not have to
  220. occur in practice to prove a deadlock: only the simple 'component'
  221. locking chains have to occur at least once (anytime, in any
  222. task/context) for the validator to be able to prove correctness. (For
  223. example, complex deadlocks that would normally need more than 3 CPUs and
  224. a very unlikely constellation of tasks, irq-contexts and timings to
  225. occur, can be detected on a plain, lightly loaded single-CPU system as
  226. well!)
  227. This radically decreases the complexity of locking related QA of the
  228. kernel: what has to be done during QA is to trigger as many "simple"
  229. single-task locking dependencies in the kernel as possible, at least
  230. once, to prove locking correctness - instead of having to trigger every
  231. possible combination of locking interaction between CPUs, combined with
  232. every possible hardirq and softirq nesting scenario (which is impossible
  233. to do in practice).
  234. .. [1]
  235. assuming that the validator itself is 100% correct, and no other
  236. part of the system corrupts the state of the validator in any way.
  237. We also assume that all NMI/SMM paths [which could interrupt
  238. even hardirq-disabled codepaths] are correct and do not interfere
  239. with the validator. We also assume that the 64-bit 'chain hash'
  240. value is unique for every lock-chain in the system. Also, lock
  241. recursion must not be higher than 20.
  242. Performance:
  243. ------------
  244. The above rules require **massive** amounts of runtime checking. If we did
  245. that for every lock taken and for every irqs-enable event, it would
  246. render the system practically unusably slow. The complexity of checking
  247. is O(N^2), so even with just a few hundred lock-classes we'd have to do
  248. tens of thousands of checks for every event.
  249. This problem is solved by checking any given 'locking scenario' (unique
  250. sequence of locks taken after each other) only once. A simple stack of
  251. held locks is maintained, and a lightweight 64-bit hash value is
  252. calculated, which hash is unique for every lock chain. The hash value,
  253. when the chain is validated for the first time, is then put into a hash
  254. table, which hash-table can be checked in a lockfree manner. If the
  255. locking chain occurs again later on, the hash table tells us that we
  256. don't have to validate the chain again.
  257. Troubleshooting:
  258. ----------------
  259. The validator tracks a maximum of MAX_LOCKDEP_KEYS number of lock classes.
  260. Exceeding this number will trigger the following lockdep warning::
  261. (DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
  262. By default, MAX_LOCKDEP_KEYS is currently set to 8191, and typical
  263. desktop systems have less than 1,000 lock classes, so this warning
  264. normally results from lock-class leakage or failure to properly
  265. initialize locks. These two problems are illustrated below:
  266. 1. Repeated module loading and unloading while running the validator
  267. will result in lock-class leakage. The issue here is that each
  268. load of the module will create a new set of lock classes for
  269. that module's locks, but module unloading does not remove old
  270. classes (see below discussion of reuse of lock classes for why).
  271. Therefore, if that module is loaded and unloaded repeatedly,
  272. the number of lock classes will eventually reach the maximum.
  273. 2. Using structures such as arrays that have large numbers of
  274. locks that are not explicitly initialized. For example,
  275. a hash table with 8192 buckets where each bucket has its own
  276. spinlock_t will consume 8192 lock classes -unless- each spinlock
  277. is explicitly initialized at runtime, for example, using the
  278. run-time spin_lock_init() as opposed to compile-time initializers
  279. such as __SPIN_LOCK_UNLOCKED(). Failure to properly initialize
  280. the per-bucket spinlocks would guarantee lock-class overflow.
  281. In contrast, a loop that called spin_lock_init() on each lock
  282. would place all 8192 locks into a single lock class.
  283. The moral of this story is that you should always explicitly
  284. initialize your locks.
  285. One might argue that the validator should be modified to allow
  286. lock classes to be reused. However, if you are tempted to make this
  287. argument, first review the code and think through the changes that would
  288. be required, keeping in mind that the lock classes to be removed are
  289. likely to be linked into the lock-dependency graph. This turns out to
  290. be harder to do than to say.
  291. Of course, if you do run out of lock classes, the next thing to do is
  292. to find the offending lock classes. First, the following command gives
  293. you the number of lock classes currently in use along with the maximum::
  294. grep "lock-classes" /proc/lockdep_stats
  295. This command produces the following output on a modest system::
  296. lock-classes: 748 [max: 8191]
  297. If the number allocated (748 above) increases continually over time,
  298. then there is likely a leak. The following command can be used to
  299. identify the leaking lock classes::
  300. grep "BD" /proc/lockdep
  301. Run the command and save the output, then compare against the output from
  302. a later run of this command to identify the leakers. This same output
  303. can also help you find situations where runtime lock initialization has
  304. been omitted.
  305. Recursive read locks:
  306. ---------------------
  307. The whole of the rest document tries to prove a certain type of cycle is equivalent
  308. to deadlock possibility.
  309. There are three types of lockers: writers (i.e. exclusive lockers, like
  310. spin_lock() or write_lock()), non-recursive readers (i.e. shared lockers, like
  311. down_read()) and recursive readers (recursive shared lockers, like rcu_read_lock()).
  312. And we use the following notations of those lockers in the rest of the document:
  313. W or E: stands for writers (exclusive lockers).
  314. r: stands for non-recursive readers.
  315. R: stands for recursive readers.
  316. S: stands for all readers (non-recursive + recursive), as both are shared lockers.
  317. N: stands for writers and non-recursive readers, as both are not recursive.
  318. Obviously, N is "r or W" and S is "r or R".
  319. Recursive readers, as their name indicates, are the lockers allowed to acquire
  320. even inside the critical section of another reader of the same lock instance,
  321. in other words, allowing nested read-side critical sections of one lock instance.
  322. While non-recursive readers will cause a self deadlock if trying to acquire inside
  323. the critical section of another reader of the same lock instance.
  324. The difference between recursive readers and non-recursive readers is because:
  325. recursive readers get blocked only by a write lock *holder*, while non-recursive
  326. readers could get blocked by a write lock *waiter*. Considering the follow
  327. example::
  328. TASK A: TASK B:
  329. read_lock(X);
  330. write_lock(X);
  331. read_lock_2(X);
  332. Task A gets the reader (no matter whether recursive or non-recursive) on X via
  333. read_lock() first. And when task B tries to acquire writer on X, it will block
  334. and become a waiter for writer on X. Now if read_lock_2() is recursive readers,
  335. task A will make progress, because writer waiters don't block recursive readers,
  336. and there is no deadlock. However, if read_lock_2() is non-recursive readers,
  337. it will get blocked by writer waiter B, and cause a self deadlock.
  338. Block conditions on readers/writers of the same lock instance:
  339. --------------------------------------------------------------
  340. There are simply four block conditions:
  341. 1. Writers block other writers.
  342. 2. Readers block writers.
  343. 3. Writers block both recursive readers and non-recursive readers.
  344. 4. And readers (recursive or not) don't block other recursive readers but
  345. may block non-recursive readers (because of the potential co-existing
  346. writer waiters)
  347. Block condition matrix, Y means the row blocks the column, and N means otherwise.
  348. +---+---+---+---+
  349. | | W | r | R |
  350. +---+---+---+---+
  351. | W | Y | Y | Y |
  352. +---+---+---+---+
  353. | r | Y | Y | N |
  354. +---+---+---+---+
  355. | R | Y | Y | N |
  356. +---+---+---+---+
  357. (W: writers, r: non-recursive readers, R: recursive readers)
  358. acquired recursively. Unlike non-recursive read locks, recursive read locks
  359. only get blocked by current write lock *holders* other than write lock
  360. *waiters*, for example::
  361. TASK A: TASK B:
  362. read_lock(X);
  363. write_lock(X);
  364. read_lock(X);
  365. is not a deadlock for recursive read locks, as while the task B is waiting for
  366. the lock X, the second read_lock() doesn't need to wait because it's a recursive
  367. read lock. However if the read_lock() is non-recursive read lock, then the above
  368. case is a deadlock, because even if the write_lock() in TASK B cannot get the
  369. lock, but it can block the second read_lock() in TASK A.
  370. Note that a lock can be a write lock (exclusive lock), a non-recursive read
  371. lock (non-recursive shared lock) or a recursive read lock (recursive shared
  372. lock), depending on the lock operations used to acquire it (more specifically,
  373. the value of the 'read' parameter for lock_acquire()). In other words, a single
  374. lock instance has three types of acquisition depending on the acquisition
  375. functions: exclusive, non-recursive read, and recursive read.
  376. To be concise, we call that write locks and non-recursive read locks as
  377. "non-recursive" locks and recursive read locks as "recursive" locks.
  378. Recursive locks don't block each other, while non-recursive locks do (this is
  379. even true for two non-recursive read locks). A non-recursive lock can block the
  380. corresponding recursive lock, and vice versa.
  381. A deadlock case with recursive locks involved is as follow::
  382. TASK A: TASK B:
  383. read_lock(X);
  384. read_lock(Y);
  385. write_lock(Y);
  386. write_lock(X);
  387. Task A is waiting for task B to read_unlock() Y and task B is waiting for task
  388. A to read_unlock() X.
  389. Dependency types and strong dependency paths:
  390. ---------------------------------------------
  391. Lock dependencies record the orders of the acquisitions of a pair of locks, and
  392. because there are 3 types for lockers, there are, in theory, 9 types of lock
  393. dependencies, but we can show that 4 types of lock dependencies are enough for
  394. deadlock detection.
  395. For each lock dependency::
  396. L1 -> L2
  397. , which means lockdep has seen L1 held before L2 held in the same context at runtime.
  398. And in deadlock detection, we care whether we could get blocked on L2 with L1 held,
  399. IOW, whether there is a locker L3 that L1 blocks L3 and L2 gets blocked by L3. So
  400. we only care about 1) what L1 blocks and 2) what blocks L2. As a result, we can combine
  401. recursive readers and non-recursive readers for L1 (as they block the same types) and
  402. we can combine writers and non-recursive readers for L2 (as they get blocked by the
  403. same types).
  404. With the above combination for simplification, there are 4 types of dependency edges
  405. in the lockdep graph:
  406. 1) -(ER)->:
  407. exclusive writer to recursive reader dependency, "X -(ER)-> Y" means
  408. X -> Y and X is a writer and Y is a recursive reader.
  409. 2) -(EN)->:
  410. exclusive writer to non-recursive locker dependency, "X -(EN)-> Y" means
  411. X -> Y and X is a writer and Y is either a writer or non-recursive reader.
  412. 3) -(SR)->:
  413. shared reader to recursive reader dependency, "X -(SR)-> Y" means
  414. X -> Y and X is a reader (recursive or not) and Y is a recursive reader.
  415. 4) -(SN)->:
  416. shared reader to non-recursive locker dependency, "X -(SN)-> Y" means
  417. X -> Y and X is a reader (recursive or not) and Y is either a writer or
  418. non-recursive reader.
  419. Note that given two locks, they may have multiple dependencies between them,
  420. for example::
  421. TASK A:
  422. read_lock(X);
  423. write_lock(Y);
  424. ...
  425. TASK B:
  426. write_lock(X);
  427. write_lock(Y);
  428. , we have both X -(SN)-> Y and X -(EN)-> Y in the dependency graph.
  429. We use -(xN)-> to represent edges that are either -(EN)-> or -(SN)->, the
  430. similar for -(Ex)->, -(xR)-> and -(Sx)->
  431. A "path" is a series of conjunct dependency edges in the graph. And we define a
  432. "strong" path, which indicates the strong dependency throughout each dependency
  433. in the path, as the path that doesn't have two conjunct edges (dependencies) as
  434. -(xR)-> and -(Sx)->. In other words, a "strong" path is a path from a lock
  435. walking to another through the lock dependencies, and if X -> Y -> Z is in the
  436. path (where X, Y, Z are locks), and the walk from X to Y is through a -(SR)-> or
  437. -(ER)-> dependency, the walk from Y to Z must not be through a -(SN)-> or
  438. -(SR)-> dependency.
  439. We will see why the path is called "strong" in next section.
  440. Recursive Read Deadlock Detection:
  441. ----------------------------------
  442. We now prove two things:
  443. Lemma 1:
  444. If there is a closed strong path (i.e. a strong circle), then there is a
  445. combination of locking sequences that causes deadlock. I.e. a strong circle is
  446. sufficient for deadlock detection.
  447. Lemma 2:
  448. If there is no closed strong path (i.e. strong circle), then there is no
  449. combination of locking sequences that could cause deadlock. I.e. strong
  450. circles are necessary for deadlock detection.
  451. With these two Lemmas, we can easily say a closed strong path is both sufficient
  452. and necessary for deadlocks, therefore a closed strong path is equivalent to
  453. deadlock possibility. As a closed strong path stands for a dependency chain that
  454. could cause deadlocks, so we call it "strong", considering there are dependency
  455. circles that won't cause deadlocks.
  456. Proof for sufficiency (Lemma 1):
  457. Let's say we have a strong circle::
  458. L1 -> L2 ... -> Ln -> L1
  459. , which means we have dependencies::
  460. L1 -> L2
  461. L2 -> L3
  462. ...
  463. Ln-1 -> Ln
  464. Ln -> L1
  465. We now can construct a combination of locking sequences that cause deadlock:
  466. Firstly let's make one CPU/task get the L1 in L1 -> L2, and then another get
  467. the L2 in L2 -> L3, and so on. After this, all of the Lx in Lx -> Lx+1 are
  468. held by different CPU/tasks.
  469. And then because we have L1 -> L2, so the holder of L1 is going to acquire L2
  470. in L1 -> L2, however since L2 is already held by another CPU/task, plus L1 ->
  471. L2 and L2 -> L3 are not -(xR)-> and -(Sx)-> (the definition of strong), which
  472. means either L2 in L1 -> L2 is a non-recursive locker (blocked by anyone) or
  473. the L2 in L2 -> L3, is writer (blocking anyone), therefore the holder of L1
  474. cannot get L2, it has to wait L2's holder to release.
  475. Moreover, we can have a similar conclusion for L2's holder: it has to wait L3's
  476. holder to release, and so on. We now can prove that Lx's holder has to wait for
  477. Lx+1's holder to release, and note that Ln+1 is L1, so we have a circular
  478. waiting scenario and nobody can get progress, therefore a deadlock.
  479. Proof for necessary (Lemma 2):
  480. Lemma 2 is equivalent to: If there is a deadlock scenario, then there must be a
  481. strong circle in the dependency graph.
  482. According to Wikipedia[1], if there is a deadlock, then there must be a circular
  483. waiting scenario, means there are N CPU/tasks, where CPU/task P1 is waiting for
  484. a lock held by P2, and P2 is waiting for a lock held by P3, ... and Pn is waiting
  485. for a lock held by P1. Let's name the lock Px is waiting as Lx, so since P1 is waiting
  486. for L1 and holding Ln, so we will have Ln -> L1 in the dependency graph. Similarly,
  487. we have L1 -> L2, L2 -> L3, ..., Ln-1 -> Ln in the dependency graph, which means we
  488. have a circle::
  489. Ln -> L1 -> L2 -> ... -> Ln
  490. , and now let's prove the circle is strong:
  491. For a lock Lx, Px contributes the dependency Lx-1 -> Lx and Px+1 contributes
  492. the dependency Lx -> Lx+1, and since Px is waiting for Px+1 to release Lx,
  493. so it's impossible that Lx on Px+1 is a reader and Lx on Px is a recursive
  494. reader, because readers (no matter recursive or not) don't block recursive
  495. readers, therefore Lx-1 -> Lx and Lx -> Lx+1 cannot be a -(xR)-> -(Sx)-> pair,
  496. and this is true for any lock in the circle, therefore, the circle is strong.
  497. References:
  498. -----------
  499. [1]: https://en.wikipedia.org/wiki/Deadlock
  500. [2]: Shibu, K. (2009). Intro To Embedded Systems (1st ed.). Tata McGraw-Hill