ww-mutex-design.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. ======================================
  2. Wound/Wait Deadlock-Proof Mutex Design
  3. ======================================
  4. Please read mutex-design.rst first, as it applies to wait/wound mutexes too.
  5. Motivation for WW-Mutexes
  6. -------------------------
  7. GPU's do operations that commonly involve many buffers. Those buffers
  8. can be shared across contexts/processes, exist in different memory
  9. domains (for example VRAM vs system memory), and so on. And with
  10. PRIME / dmabuf, they can even be shared across devices. So there are
  11. a handful of situations where the driver needs to wait for buffers to
  12. become ready. If you think about this in terms of waiting on a buffer
  13. mutex for it to become available, this presents a problem because
  14. there is no way to guarantee that buffers appear in a execbuf/batch in
  15. the same order in all contexts. That is directly under control of
  16. userspace, and a result of the sequence of GL calls that an application
  17. makes. Which results in the potential for deadlock. The problem gets
  18. more complex when you consider that the kernel may need to migrate the
  19. buffer(s) into VRAM before the GPU operates on the buffer(s), which
  20. may in turn require evicting some other buffers (and you don't want to
  21. evict other buffers which are already queued up to the GPU), but for a
  22. simplified understanding of the problem you can ignore this.
  23. The algorithm that the TTM graphics subsystem came up with for dealing with
  24. this problem is quite simple. For each group of buffers (execbuf) that need
  25. to be locked, the caller would be assigned a unique reservation id/ticket,
  26. from a global counter. In case of deadlock while locking all the buffers
  27. associated with a execbuf, the one with the lowest reservation ticket (i.e.
  28. the oldest task) wins, and the one with the higher reservation id (i.e. the
  29. younger task) unlocks all of the buffers that it has already locked, and then
  30. tries again.
  31. In the RDBMS literature, a reservation ticket is associated with a transaction.
  32. and the deadlock handling approach is called Wait-Die. The name is based on
  33. the actions of a locking thread when it encounters an already locked mutex.
  34. If the transaction holding the lock is younger, the locking transaction waits.
  35. If the transaction holding the lock is older, the locking transaction backs off
  36. and dies. Hence Wait-Die.
  37. There is also another algorithm called Wound-Wait:
  38. If the transaction holding the lock is younger, the locking transaction
  39. wounds the transaction holding the lock, requesting it to die.
  40. If the transaction holding the lock is older, it waits for the other
  41. transaction. Hence Wound-Wait.
  42. The two algorithms are both fair in that a transaction will eventually succeed.
  43. However, the Wound-Wait algorithm is typically stated to generate fewer backoffs
  44. compared to Wait-Die, but is, on the other hand, associated with more work than
  45. Wait-Die when recovering from a backoff. Wound-Wait is also a preemptive
  46. algorithm in that transactions are wounded by other transactions, and that
  47. requires a reliable way to pick up the wounded condition and preempt the
  48. running transaction. Note that this is not the same as process preemption. A
  49. Wound-Wait transaction is considered preempted when it dies (returning
  50. -EDEADLK) following a wound.
  51. Concepts
  52. --------
  53. Compared to normal mutexes two additional concepts/objects show up in the lock
  54. interface for w/w mutexes:
  55. Acquire context: To ensure eventual forward progress it is important that a task
  56. trying to acquire locks doesn't grab a new reservation id, but keeps the one it
  57. acquired when starting the lock acquisition. This ticket is stored in the
  58. acquire context. Furthermore the acquire context keeps track of debugging state
  59. to catch w/w mutex interface abuse. An acquire context is representing a
  60. transaction.
  61. W/w class: In contrast to normal mutexes the lock class needs to be explicit for
  62. w/w mutexes, since it is required to initialize the acquire context. The lock
  63. class also specifies what algorithm to use, Wound-Wait or Wait-Die.
  64. Furthermore there are three different class of w/w lock acquire functions:
  65. * Normal lock acquisition with a context, using ww_mutex_lock.
  66. * Slowpath lock acquisition on the contending lock, used by the task that just
  67. killed its transaction after having dropped all already acquired locks.
  68. These functions have the _slow postfix.
  69. From a simple semantics point-of-view the _slow functions are not strictly
  70. required, since simply calling the normal ww_mutex_lock functions on the
  71. contending lock (after having dropped all other already acquired locks) will
  72. work correctly. After all if no other ww mutex has been acquired yet there's
  73. no deadlock potential and hence the ww_mutex_lock call will block and not
  74. prematurely return -EDEADLK. The advantage of the _slow functions is in
  75. interface safety:
  76. - ww_mutex_lock has a __must_check int return type, whereas ww_mutex_lock_slow
  77. has a void return type. Note that since ww mutex code needs loops/retries
  78. anyway the __must_check doesn't result in spurious warnings, even though the
  79. very first lock operation can never fail.
  80. - When full debugging is enabled ww_mutex_lock_slow checks that all acquired
  81. ww mutex have been released (preventing deadlocks) and makes sure that we
  82. block on the contending lock (preventing spinning through the -EDEADLK
  83. slowpath until the contended lock can be acquired).
  84. * Functions to only acquire a single w/w mutex, which results in the exact same
  85. semantics as a normal mutex. This is done by calling ww_mutex_lock with a NULL
  86. context.
  87. Again this is not strictly required. But often you only want to acquire a
  88. single lock in which case it's pointless to set up an acquire context (and so
  89. better to avoid grabbing a deadlock avoidance ticket).
  90. Of course, all the usual variants for handling wake-ups due to signals are also
  91. provided.
  92. Usage
  93. -----
  94. The algorithm (Wait-Die vs Wound-Wait) is chosen by using either
  95. DEFINE_WW_CLASS() (Wound-Wait) or DEFINE_WD_CLASS() (Wait-Die)
  96. As a rough rule of thumb, use Wound-Wait iff you
  97. expect the number of simultaneous competing transactions to be typically small,
  98. and you want to reduce the number of rollbacks.
  99. Three different ways to acquire locks within the same w/w class. Common
  100. definitions for methods #1 and #2::
  101. static DEFINE_WW_CLASS(ww_class);
  102. struct obj {
  103. struct ww_mutex lock;
  104. /* obj data */
  105. };
  106. struct obj_entry {
  107. struct list_head head;
  108. struct obj *obj;
  109. };
  110. Method 1, using a list in execbuf->buffers that's not allowed to be reordered.
  111. This is useful if a list of required objects is already tracked somewhere.
  112. Furthermore the lock helper can use propagate the -EALREADY return code back to
  113. the caller as a signal that an object is twice on the list. This is useful if
  114. the list is constructed from userspace input and the ABI requires userspace to
  115. not have duplicate entries (e.g. for a gpu commandbuffer submission ioctl)::
  116. int lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
  117. {
  118. struct obj *res_obj = NULL;
  119. struct obj_entry *contended_entry = NULL;
  120. struct obj_entry *entry;
  121. ww_acquire_init(ctx, &ww_class);
  122. retry:
  123. list_for_each_entry (entry, list, head) {
  124. if (entry->obj == res_obj) {
  125. res_obj = NULL;
  126. continue;
  127. }
  128. ret = ww_mutex_lock(&entry->obj->lock, ctx);
  129. if (ret < 0) {
  130. contended_entry = entry;
  131. goto err;
  132. }
  133. }
  134. ww_acquire_done(ctx);
  135. return 0;
  136. err:
  137. list_for_each_entry_continue_reverse (entry, list, head)
  138. ww_mutex_unlock(&entry->obj->lock);
  139. if (res_obj)
  140. ww_mutex_unlock(&res_obj->lock);
  141. if (ret == -EDEADLK) {
  142. /* we lost out in a seqno race, lock and retry.. */
  143. ww_mutex_lock_slow(&contended_entry->obj->lock, ctx);
  144. res_obj = contended_entry->obj;
  145. goto retry;
  146. }
  147. ww_acquire_fini(ctx);
  148. return ret;
  149. }
  150. Method 2, using a list in execbuf->buffers that can be reordered. Same semantics
  151. of duplicate entry detection using -EALREADY as method 1 above. But the
  152. list-reordering allows for a bit more idiomatic code::
  153. int lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
  154. {
  155. struct obj_entry *entry, *entry2;
  156. ww_acquire_init(ctx, &ww_class);
  157. list_for_each_entry (entry, list, head) {
  158. ret = ww_mutex_lock(&entry->obj->lock, ctx);
  159. if (ret < 0) {
  160. entry2 = entry;
  161. list_for_each_entry_continue_reverse (entry2, list, head)
  162. ww_mutex_unlock(&entry2->obj->lock);
  163. if (ret != -EDEADLK) {
  164. ww_acquire_fini(ctx);
  165. return ret;
  166. }
  167. /* we lost out in a seqno race, lock and retry.. */
  168. ww_mutex_lock_slow(&entry->obj->lock, ctx);
  169. /*
  170. * Move buf to head of the list, this will point
  171. * buf->next to the first unlocked entry,
  172. * restarting the for loop.
  173. */
  174. list_del(&entry->head);
  175. list_add(&entry->head, list);
  176. }
  177. }
  178. ww_acquire_done(ctx);
  179. return 0;
  180. }
  181. Unlocking works the same way for both methods #1 and #2::
  182. void unlock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
  183. {
  184. struct obj_entry *entry;
  185. list_for_each_entry (entry, list, head)
  186. ww_mutex_unlock(&entry->obj->lock);
  187. ww_acquire_fini(ctx);
  188. }
  189. Method 3 is useful if the list of objects is constructed ad-hoc and not upfront,
  190. e.g. when adjusting edges in a graph where each node has its own ww_mutex lock,
  191. and edges can only be changed when holding the locks of all involved nodes. w/w
  192. mutexes are a natural fit for such a case for two reasons:
  193. - They can handle lock-acquisition in any order which allows us to start walking
  194. a graph from a starting point and then iteratively discovering new edges and
  195. locking down the nodes those edges connect to.
  196. - Due to the -EALREADY return code signalling that a given objects is already
  197. held there's no need for additional book-keeping to break cycles in the graph
  198. or keep track off which looks are already held (when using more than one node
  199. as a starting point).
  200. Note that this approach differs in two important ways from the above methods:
  201. - Since the list of objects is dynamically constructed (and might very well be
  202. different when retrying due to hitting the -EDEADLK die condition) there's
  203. no need to keep any object on a persistent list when it's not locked. We can
  204. therefore move the list_head into the object itself.
  205. - On the other hand the dynamic object list construction also means that the -EALREADY return
  206. code can't be propagated.
  207. Note also that methods #1 and #2 and method #3 can be combined, e.g. to first lock a
  208. list of starting nodes (passed in from userspace) using one of the above
  209. methods. And then lock any additional objects affected by the operations using
  210. method #3 below. The backoff/retry procedure will be a bit more involved, since
  211. when the dynamic locking step hits -EDEADLK we also need to unlock all the
  212. objects acquired with the fixed list. But the w/w mutex debug checks will catch
  213. any interface misuse for these cases.
  214. Also, method 3 can't fail the lock acquisition step since it doesn't return
  215. -EALREADY. Of course this would be different when using the _interruptible
  216. variants, but that's outside of the scope of these examples here::
  217. struct obj {
  218. struct ww_mutex ww_mutex;
  219. struct list_head locked_list;
  220. };
  221. static DEFINE_WW_CLASS(ww_class);
  222. void __unlock_objs(struct list_head *list)
  223. {
  224. struct obj *entry, *temp;
  225. list_for_each_entry_safe (entry, temp, list, locked_list) {
  226. /* need to do that before unlocking, since only the current lock holder is
  227. allowed to use object */
  228. list_del(&entry->locked_list);
  229. ww_mutex_unlock(entry->ww_mutex)
  230. }
  231. }
  232. void lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
  233. {
  234. struct obj *obj;
  235. ww_acquire_init(ctx, &ww_class);
  236. retry:
  237. /* re-init loop start state */
  238. loop {
  239. /* magic code which walks over a graph and decides which objects
  240. * to lock */
  241. ret = ww_mutex_lock(obj->ww_mutex, ctx);
  242. if (ret == -EALREADY) {
  243. /* we have that one already, get to the next object */
  244. continue;
  245. }
  246. if (ret == -EDEADLK) {
  247. __unlock_objs(list);
  248. ww_mutex_lock_slow(obj, ctx);
  249. list_add(&entry->locked_list, list);
  250. goto retry;
  251. }
  252. /* locked a new object, add it to the list */
  253. list_add_tail(&entry->locked_list, list);
  254. }
  255. ww_acquire_done(ctx);
  256. return 0;
  257. }
  258. void unlock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
  259. {
  260. __unlock_objs(list);
  261. ww_acquire_fini(ctx);
  262. }
  263. Method 4: Only lock one single objects. In that case deadlock detection and
  264. prevention is obviously overkill, since with grabbing just one lock you can't
  265. produce a deadlock within just one class. To simplify this case the w/w mutex
  266. api can be used with a NULL context.
  267. Implementation Details
  268. ----------------------
  269. Design:
  270. ^^^^^^^
  271. ww_mutex currently encapsulates a struct mutex, this means no extra overhead for
  272. normal mutex locks, which are far more common. As such there is only a small
  273. increase in code size if wait/wound mutexes are not used.
  274. We maintain the following invariants for the wait list:
  275. (1) Waiters with an acquire context are sorted by stamp order; waiters
  276. without an acquire context are interspersed in FIFO order.
  277. (2) For Wait-Die, among waiters with contexts, only the first one can have
  278. other locks acquired already (ctx->acquired > 0). Note that this waiter
  279. may come after other waiters without contexts in the list.
  280. The Wound-Wait preemption is implemented with a lazy-preemption scheme:
  281. The wounded status of the transaction is checked only when there is
  282. contention for a new lock and hence a true chance of deadlock. In that
  283. situation, if the transaction is wounded, it backs off, clears the
  284. wounded status and retries. A great benefit of implementing preemption in
  285. this way is that the wounded transaction can identify a contending lock to
  286. wait for before restarting the transaction. Just blindly restarting the
  287. transaction would likely make the transaction end up in a situation where
  288. it would have to back off again.
  289. In general, not much contention is expected. The locks are typically used to
  290. serialize access to resources for devices, and optimization focus should
  291. therefore be directed towards the uncontended cases.
  292. Lockdep:
  293. ^^^^^^^^
  294. Special care has been taken to warn for as many cases of api abuse
  295. as possible. Some common api abuses will be caught with
  296. CONFIG_DEBUG_MUTEXES, but CONFIG_PROVE_LOCKING is recommended.
  297. Some of the errors which will be warned about:
  298. - Forgetting to call ww_acquire_fini or ww_acquire_init.
  299. - Attempting to lock more mutexes after ww_acquire_done.
  300. - Attempting to lock the wrong mutex after -EDEADLK and
  301. unlocking all mutexes.
  302. - Attempting to lock the right mutex after -EDEADLK,
  303. before unlocking all mutexes.
  304. - Calling ww_mutex_lock_slow before -EDEADLK was returned.
  305. - Unlocking mutexes with the wrong unlock function.
  306. - Calling one of the ww_acquire_* twice on the same context.
  307. - Using a different ww_class for the mutex than for the ww_acquire_ctx.
  308. - Normal lockdep errors that can result in deadlocks.
  309. Some of the lockdep errors that can result in deadlocks:
  310. - Calling ww_acquire_init to initialize a second ww_acquire_ctx before
  311. having called ww_acquire_fini on the first.
  312. - 'normal' deadlocks that can occur.
  313. FIXME:
  314. Update this section once we have the TASK_DEADLOCK task state flag magic
  315. implemented.