ww-mutex-design.txt 12 KB

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