mutex.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  1. /*
  2. * kernel/locking/mutex.c
  3. *
  4. * Mutexes: blocking mutual exclusion locks
  5. *
  6. * Started by Ingo Molnar:
  7. *
  8. * Copyright (C) 2004, 2005, 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
  9. *
  10. * Many thanks to Arjan van de Ven, Thomas Gleixner, Steven Rostedt and
  11. * David Howells for suggestions and improvements.
  12. *
  13. * - Adaptive spinning for mutexes by Peter Zijlstra. (Ported to mainline
  14. * from the -rt tree, where it was originally implemented for rtmutexes
  15. * by Steven Rostedt, based on work by Gregory Haskins, Peter Morreale
  16. * and Sven Dietrich.
  17. *
  18. * Also see Documentation/locking/mutex-design.txt.
  19. */
  20. #include <linux/mutex.h>
  21. #include <linux/ww_mutex.h>
  22. #include <linux/sched/signal.h>
  23. #include <linux/sched/rt.h>
  24. #include <linux/sched/wake_q.h>
  25. #include <linux/sched/debug.h>
  26. #include <linux/export.h>
  27. #include <linux/spinlock.h>
  28. #include <linux/interrupt.h>
  29. #include <linux/debug_locks.h>
  30. #include <linux/osq_lock.h>
  31. #ifdef CONFIG_DEBUG_MUTEXES
  32. # include "mutex-debug.h"
  33. #else
  34. # include "mutex.h"
  35. #endif
  36. void
  37. __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)
  38. {
  39. atomic_long_set(&lock->owner, 0);
  40. spin_lock_init(&lock->wait_lock);
  41. INIT_LIST_HEAD(&lock->wait_list);
  42. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
  43. osq_lock_init(&lock->osq);
  44. #endif
  45. debug_mutex_init(lock, name, key);
  46. }
  47. EXPORT_SYMBOL(__mutex_init);
  48. /*
  49. * @owner: contains: 'struct task_struct *' to the current lock owner,
  50. * NULL means not owned. Since task_struct pointers are aligned at
  51. * at least L1_CACHE_BYTES, we have low bits to store extra state.
  52. *
  53. * Bit0 indicates a non-empty waiter list; unlock must issue a wakeup.
  54. * Bit1 indicates unlock needs to hand the lock to the top-waiter
  55. * Bit2 indicates handoff has been done and we're waiting for pickup.
  56. */
  57. #define MUTEX_FLAG_WAITERS 0x01
  58. #define MUTEX_FLAG_HANDOFF 0x02
  59. #define MUTEX_FLAG_PICKUP 0x04
  60. #define MUTEX_FLAGS 0x07
  61. static inline struct task_struct *__owner_task(unsigned long owner)
  62. {
  63. return (struct task_struct *)(owner & ~MUTEX_FLAGS);
  64. }
  65. static inline unsigned long __owner_flags(unsigned long owner)
  66. {
  67. return owner & MUTEX_FLAGS;
  68. }
  69. /*
  70. * Trylock variant that retuns the owning task on failure.
  71. */
  72. static inline struct task_struct *__mutex_trylock_or_owner(struct mutex *lock)
  73. {
  74. unsigned long owner, curr = (unsigned long)current;
  75. owner = atomic_long_read(&lock->owner);
  76. for (;;) { /* must loop, can race against a flag */
  77. unsigned long old, flags = __owner_flags(owner);
  78. unsigned long task = owner & ~MUTEX_FLAGS;
  79. if (task) {
  80. if (likely(task != curr))
  81. break;
  82. if (likely(!(flags & MUTEX_FLAG_PICKUP)))
  83. break;
  84. flags &= ~MUTEX_FLAG_PICKUP;
  85. } else {
  86. #ifdef CONFIG_DEBUG_MUTEXES
  87. DEBUG_LOCKS_WARN_ON(flags & MUTEX_FLAG_PICKUP);
  88. #endif
  89. }
  90. /*
  91. * We set the HANDOFF bit, we must make sure it doesn't live
  92. * past the point where we acquire it. This would be possible
  93. * if we (accidentally) set the bit on an unlocked mutex.
  94. */
  95. flags &= ~MUTEX_FLAG_HANDOFF;
  96. old = atomic_long_cmpxchg_acquire(&lock->owner, owner, curr | flags);
  97. if (old == owner)
  98. return NULL;
  99. owner = old;
  100. }
  101. return __owner_task(owner);
  102. }
  103. /*
  104. * Actual trylock that will work on any unlocked state.
  105. */
  106. static inline bool __mutex_trylock(struct mutex *lock)
  107. {
  108. return !__mutex_trylock_or_owner(lock);
  109. }
  110. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  111. /*
  112. * Lockdep annotations are contained to the slow paths for simplicity.
  113. * There is nothing that would stop spreading the lockdep annotations outwards
  114. * except more code.
  115. */
  116. /*
  117. * Optimistic trylock that only works in the uncontended case. Make sure to
  118. * follow with a __mutex_trylock() before failing.
  119. */
  120. static __always_inline bool __mutex_trylock_fast(struct mutex *lock)
  121. {
  122. unsigned long curr = (unsigned long)current;
  123. if (!atomic_long_cmpxchg_acquire(&lock->owner, 0UL, curr))
  124. return true;
  125. return false;
  126. }
  127. static __always_inline bool __mutex_unlock_fast(struct mutex *lock)
  128. {
  129. unsigned long curr = (unsigned long)current;
  130. if (atomic_long_cmpxchg_release(&lock->owner, curr, 0UL) == curr)
  131. return true;
  132. return false;
  133. }
  134. #endif
  135. static inline void __mutex_set_flag(struct mutex *lock, unsigned long flag)
  136. {
  137. atomic_long_or(flag, &lock->owner);
  138. }
  139. static inline void __mutex_clear_flag(struct mutex *lock, unsigned long flag)
  140. {
  141. atomic_long_andnot(flag, &lock->owner);
  142. }
  143. static inline bool __mutex_waiter_is_first(struct mutex *lock, struct mutex_waiter *waiter)
  144. {
  145. return list_first_entry(&lock->wait_list, struct mutex_waiter, list) == waiter;
  146. }
  147. /*
  148. * Give up ownership to a specific task, when @task = NULL, this is equivalent
  149. * to a regular unlock. Sets PICKUP on a handoff, clears HANDOF, preserves
  150. * WAITERS. Provides RELEASE semantics like a regular unlock, the
  151. * __mutex_trylock() provides a matching ACQUIRE semantics for the handoff.
  152. */
  153. static void __mutex_handoff(struct mutex *lock, struct task_struct *task)
  154. {
  155. unsigned long owner = atomic_long_read(&lock->owner);
  156. for (;;) {
  157. unsigned long old, new;
  158. #ifdef CONFIG_DEBUG_MUTEXES
  159. DEBUG_LOCKS_WARN_ON(__owner_task(owner) != current);
  160. DEBUG_LOCKS_WARN_ON(owner & MUTEX_FLAG_PICKUP);
  161. #endif
  162. new = (owner & MUTEX_FLAG_WAITERS);
  163. new |= (unsigned long)task;
  164. if (task)
  165. new |= MUTEX_FLAG_PICKUP;
  166. old = atomic_long_cmpxchg_release(&lock->owner, owner, new);
  167. if (old == owner)
  168. break;
  169. owner = old;
  170. }
  171. }
  172. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  173. /*
  174. * We split the mutex lock/unlock logic into separate fastpath and
  175. * slowpath functions, to reduce the register pressure on the fastpath.
  176. * We also put the fastpath first in the kernel image, to make sure the
  177. * branch is predicted by the CPU as default-untaken.
  178. */
  179. static void __sched __mutex_lock_slowpath(struct mutex *lock);
  180. /**
  181. * mutex_lock - acquire the mutex
  182. * @lock: the mutex to be acquired
  183. *
  184. * Lock the mutex exclusively for this task. If the mutex is not
  185. * available right now, it will sleep until it can get it.
  186. *
  187. * The mutex must later on be released by the same task that
  188. * acquired it. Recursive locking is not allowed. The task
  189. * may not exit without first unlocking the mutex. Also, kernel
  190. * memory where the mutex resides must not be freed with
  191. * the mutex still locked. The mutex must first be initialized
  192. * (or statically defined) before it can be locked. memset()-ing
  193. * the mutex to 0 is not allowed.
  194. *
  195. * (The CONFIG_DEBUG_MUTEXES .config option turns on debugging
  196. * checks that will enforce the restrictions and will also do
  197. * deadlock debugging)
  198. *
  199. * This function is similar to (but not equivalent to) down().
  200. */
  201. void __sched mutex_lock(struct mutex *lock)
  202. {
  203. might_sleep();
  204. if (!__mutex_trylock_fast(lock))
  205. __mutex_lock_slowpath(lock);
  206. }
  207. EXPORT_SYMBOL(mutex_lock);
  208. #endif
  209. static __always_inline void
  210. ww_mutex_lock_acquired(struct ww_mutex *ww, struct ww_acquire_ctx *ww_ctx)
  211. {
  212. #ifdef CONFIG_DEBUG_MUTEXES
  213. /*
  214. * If this WARN_ON triggers, you used ww_mutex_lock to acquire,
  215. * but released with a normal mutex_unlock in this call.
  216. *
  217. * This should never happen, always use ww_mutex_unlock.
  218. */
  219. DEBUG_LOCKS_WARN_ON(ww->ctx);
  220. /*
  221. * Not quite done after calling ww_acquire_done() ?
  222. */
  223. DEBUG_LOCKS_WARN_ON(ww_ctx->done_acquire);
  224. if (ww_ctx->contending_lock) {
  225. /*
  226. * After -EDEADLK you tried to
  227. * acquire a different ww_mutex? Bad!
  228. */
  229. DEBUG_LOCKS_WARN_ON(ww_ctx->contending_lock != ww);
  230. /*
  231. * You called ww_mutex_lock after receiving -EDEADLK,
  232. * but 'forgot' to unlock everything else first?
  233. */
  234. DEBUG_LOCKS_WARN_ON(ww_ctx->acquired > 0);
  235. ww_ctx->contending_lock = NULL;
  236. }
  237. /*
  238. * Naughty, using a different class will lead to undefined behavior!
  239. */
  240. DEBUG_LOCKS_WARN_ON(ww_ctx->ww_class != ww->ww_class);
  241. #endif
  242. ww_ctx->acquired++;
  243. }
  244. static inline bool __sched
  245. __ww_ctx_stamp_after(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b)
  246. {
  247. return a->stamp - b->stamp <= LONG_MAX &&
  248. (a->stamp != b->stamp || a > b);
  249. }
  250. /*
  251. * Wake up any waiters that may have to back off when the lock is held by the
  252. * given context.
  253. *
  254. * Due to the invariants on the wait list, this can only affect the first
  255. * waiter with a context.
  256. *
  257. * The current task must not be on the wait list.
  258. */
  259. static void __sched
  260. __ww_mutex_wakeup_for_backoff(struct mutex *lock, struct ww_acquire_ctx *ww_ctx)
  261. {
  262. struct mutex_waiter *cur;
  263. lockdep_assert_held(&lock->wait_lock);
  264. list_for_each_entry(cur, &lock->wait_list, list) {
  265. if (!cur->ww_ctx)
  266. continue;
  267. if (cur->ww_ctx->acquired > 0 &&
  268. __ww_ctx_stamp_after(cur->ww_ctx, ww_ctx)) {
  269. debug_mutex_wake_waiter(lock, cur);
  270. wake_up_process(cur->task);
  271. }
  272. break;
  273. }
  274. }
  275. /*
  276. * After acquiring lock with fastpath or when we lost out in contested
  277. * slowpath, set ctx and wake up any waiters so they can recheck.
  278. */
  279. static __always_inline void
  280. ww_mutex_set_context_fastpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  281. {
  282. ww_mutex_lock_acquired(lock, ctx);
  283. lock->ctx = ctx;
  284. /*
  285. * The lock->ctx update should be visible on all cores before
  286. * the atomic read is done, otherwise contended waiters might be
  287. * missed. The contended waiters will either see ww_ctx == NULL
  288. * and keep spinning, or it will acquire wait_lock, add itself
  289. * to waiter list and sleep.
  290. */
  291. smp_mb(); /* ^^^ */
  292. /*
  293. * Check if lock is contended, if not there is nobody to wake up
  294. */
  295. if (likely(!(atomic_long_read(&lock->base.owner) & MUTEX_FLAG_WAITERS)))
  296. return;
  297. /*
  298. * Uh oh, we raced in fastpath, wake up everyone in this case,
  299. * so they can see the new lock->ctx.
  300. */
  301. spin_lock(&lock->base.wait_lock);
  302. __ww_mutex_wakeup_for_backoff(&lock->base, ctx);
  303. spin_unlock(&lock->base.wait_lock);
  304. }
  305. /*
  306. * After acquiring lock in the slowpath set ctx.
  307. *
  308. * Unlike for the fast path, the caller ensures that waiters are woken up where
  309. * necessary.
  310. *
  311. * Callers must hold the mutex wait_lock.
  312. */
  313. static __always_inline void
  314. ww_mutex_set_context_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  315. {
  316. ww_mutex_lock_acquired(lock, ctx);
  317. lock->ctx = ctx;
  318. }
  319. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
  320. static inline
  321. bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
  322. struct mutex_waiter *waiter)
  323. {
  324. struct ww_mutex *ww;
  325. ww = container_of(lock, struct ww_mutex, base);
  326. /*
  327. * If ww->ctx is set the contents are undefined, only
  328. * by acquiring wait_lock there is a guarantee that
  329. * they are not invalid when reading.
  330. *
  331. * As such, when deadlock detection needs to be
  332. * performed the optimistic spinning cannot be done.
  333. *
  334. * Check this in every inner iteration because we may
  335. * be racing against another thread's ww_mutex_lock.
  336. */
  337. if (ww_ctx->acquired > 0 && READ_ONCE(ww->ctx))
  338. return false;
  339. /*
  340. * If we aren't on the wait list yet, cancel the spin
  341. * if there are waiters. We want to avoid stealing the
  342. * lock from a waiter with an earlier stamp, since the
  343. * other thread may already own a lock that we also
  344. * need.
  345. */
  346. if (!waiter && (atomic_long_read(&lock->owner) & MUTEX_FLAG_WAITERS))
  347. return false;
  348. /*
  349. * Similarly, stop spinning if we are no longer the
  350. * first waiter.
  351. */
  352. if (waiter && !__mutex_waiter_is_first(lock, waiter))
  353. return false;
  354. return true;
  355. }
  356. /*
  357. * Look out! "owner" is an entirely speculative pointer access and not
  358. * reliable.
  359. *
  360. * "noinline" so that this function shows up on perf profiles.
  361. */
  362. static noinline
  363. bool mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner,
  364. struct ww_acquire_ctx *ww_ctx, struct mutex_waiter *waiter)
  365. {
  366. bool ret = true;
  367. rcu_read_lock();
  368. while (__mutex_owner(lock) == owner) {
  369. /*
  370. * Ensure we emit the owner->on_cpu, dereference _after_
  371. * checking lock->owner still matches owner. If that fails,
  372. * owner might point to freed memory. If it still matches,
  373. * the rcu_read_lock() ensures the memory stays valid.
  374. */
  375. barrier();
  376. /*
  377. * Use vcpu_is_preempted to detect lock holder preemption issue.
  378. */
  379. if (!owner->on_cpu || need_resched() ||
  380. vcpu_is_preempted(task_cpu(owner))) {
  381. ret = false;
  382. break;
  383. }
  384. if (ww_ctx && !ww_mutex_spin_on_owner(lock, ww_ctx, waiter)) {
  385. ret = false;
  386. break;
  387. }
  388. cpu_relax();
  389. }
  390. rcu_read_unlock();
  391. return ret;
  392. }
  393. /*
  394. * Initial check for entering the mutex spinning loop
  395. */
  396. static inline int mutex_can_spin_on_owner(struct mutex *lock)
  397. {
  398. struct task_struct *owner;
  399. int retval = 1;
  400. if (need_resched())
  401. return 0;
  402. rcu_read_lock();
  403. owner = __mutex_owner(lock);
  404. /*
  405. * As lock holder preemption issue, we both skip spinning if task is not
  406. * on cpu or its cpu is preempted
  407. */
  408. if (owner)
  409. retval = owner->on_cpu && !vcpu_is_preempted(task_cpu(owner));
  410. rcu_read_unlock();
  411. /*
  412. * If lock->owner is not set, the mutex has been released. Return true
  413. * such that we'll trylock in the spin path, which is a faster option
  414. * than the blocking slow path.
  415. */
  416. return retval;
  417. }
  418. /*
  419. * Optimistic spinning.
  420. *
  421. * We try to spin for acquisition when we find that the lock owner
  422. * is currently running on a (different) CPU and while we don't
  423. * need to reschedule. The rationale is that if the lock owner is
  424. * running, it is likely to release the lock soon.
  425. *
  426. * The mutex spinners are queued up using MCS lock so that only one
  427. * spinner can compete for the mutex. However, if mutex spinning isn't
  428. * going to happen, there is no point in going through the lock/unlock
  429. * overhead.
  430. *
  431. * Returns true when the lock was taken, otherwise false, indicating
  432. * that we need to jump to the slowpath and sleep.
  433. *
  434. * The waiter flag is set to true if the spinner is a waiter in the wait
  435. * queue. The waiter-spinner will spin on the lock directly and concurrently
  436. * with the spinner at the head of the OSQ, if present, until the owner is
  437. * changed to itself.
  438. */
  439. static __always_inline bool
  440. mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
  441. const bool use_ww_ctx, struct mutex_waiter *waiter)
  442. {
  443. if (!waiter) {
  444. /*
  445. * The purpose of the mutex_can_spin_on_owner() function is
  446. * to eliminate the overhead of osq_lock() and osq_unlock()
  447. * in case spinning isn't possible. As a waiter-spinner
  448. * is not going to take OSQ lock anyway, there is no need
  449. * to call mutex_can_spin_on_owner().
  450. */
  451. if (!mutex_can_spin_on_owner(lock))
  452. goto fail;
  453. /*
  454. * In order to avoid a stampede of mutex spinners trying to
  455. * acquire the mutex all at once, the spinners need to take a
  456. * MCS (queued) lock first before spinning on the owner field.
  457. */
  458. if (!osq_lock(&lock->osq))
  459. goto fail;
  460. }
  461. for (;;) {
  462. struct task_struct *owner;
  463. /* Try to acquire the mutex... */
  464. owner = __mutex_trylock_or_owner(lock);
  465. if (!owner)
  466. break;
  467. /*
  468. * There's an owner, wait for it to either
  469. * release the lock or go to sleep.
  470. */
  471. if (!mutex_spin_on_owner(lock, owner, ww_ctx, waiter))
  472. goto fail_unlock;
  473. /*
  474. * The cpu_relax() call is a compiler barrier which forces
  475. * everything in this loop to be re-loaded. We don't need
  476. * memory barriers as we'll eventually observe the right
  477. * values at the cost of a few extra spins.
  478. */
  479. cpu_relax();
  480. }
  481. if (!waiter)
  482. osq_unlock(&lock->osq);
  483. return true;
  484. fail_unlock:
  485. if (!waiter)
  486. osq_unlock(&lock->osq);
  487. fail:
  488. /*
  489. * If we fell out of the spin path because of need_resched(),
  490. * reschedule now, before we try-lock the mutex. This avoids getting
  491. * scheduled out right after we obtained the mutex.
  492. */
  493. if (need_resched()) {
  494. /*
  495. * We _should_ have TASK_RUNNING here, but just in case
  496. * we do not, make it so, otherwise we might get stuck.
  497. */
  498. __set_current_state(TASK_RUNNING);
  499. schedule_preempt_disabled();
  500. }
  501. return false;
  502. }
  503. #else
  504. static __always_inline bool
  505. mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
  506. const bool use_ww_ctx, struct mutex_waiter *waiter)
  507. {
  508. return false;
  509. }
  510. #endif
  511. static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip);
  512. /**
  513. * mutex_unlock - release the mutex
  514. * @lock: the mutex to be released
  515. *
  516. * Unlock a mutex that has been locked by this task previously.
  517. *
  518. * This function must not be used in interrupt context. Unlocking
  519. * of a not locked mutex is not allowed.
  520. *
  521. * This function is similar to (but not equivalent to) up().
  522. */
  523. void __sched mutex_unlock(struct mutex *lock)
  524. {
  525. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  526. if (__mutex_unlock_fast(lock))
  527. return;
  528. #endif
  529. __mutex_unlock_slowpath(lock, _RET_IP_);
  530. }
  531. EXPORT_SYMBOL(mutex_unlock);
  532. /**
  533. * ww_mutex_unlock - release the w/w mutex
  534. * @lock: the mutex to be released
  535. *
  536. * Unlock a mutex that has been locked by this task previously with any of the
  537. * ww_mutex_lock* functions (with or without an acquire context). It is
  538. * forbidden to release the locks after releasing the acquire context.
  539. *
  540. * This function must not be used in interrupt context. Unlocking
  541. * of a unlocked mutex is not allowed.
  542. */
  543. void __sched ww_mutex_unlock(struct ww_mutex *lock)
  544. {
  545. /*
  546. * The unlocking fastpath is the 0->1 transition from 'locked'
  547. * into 'unlocked' state:
  548. */
  549. if (lock->ctx) {
  550. #ifdef CONFIG_DEBUG_MUTEXES
  551. DEBUG_LOCKS_WARN_ON(!lock->ctx->acquired);
  552. #endif
  553. if (lock->ctx->acquired > 0)
  554. lock->ctx->acquired--;
  555. lock->ctx = NULL;
  556. }
  557. mutex_unlock(&lock->base);
  558. }
  559. EXPORT_SYMBOL(ww_mutex_unlock);
  560. static inline int __sched
  561. __ww_mutex_lock_check_stamp(struct mutex *lock, struct mutex_waiter *waiter,
  562. struct ww_acquire_ctx *ctx)
  563. {
  564. struct ww_mutex *ww = container_of(lock, struct ww_mutex, base);
  565. struct ww_acquire_ctx *hold_ctx = READ_ONCE(ww->ctx);
  566. struct mutex_waiter *cur;
  567. if (hold_ctx && __ww_ctx_stamp_after(ctx, hold_ctx))
  568. goto deadlock;
  569. /*
  570. * If there is a waiter in front of us that has a context, then its
  571. * stamp is earlier than ours and we must back off.
  572. */
  573. cur = waiter;
  574. list_for_each_entry_continue_reverse(cur, &lock->wait_list, list) {
  575. if (cur->ww_ctx)
  576. goto deadlock;
  577. }
  578. return 0;
  579. deadlock:
  580. #ifdef CONFIG_DEBUG_MUTEXES
  581. DEBUG_LOCKS_WARN_ON(ctx->contending_lock);
  582. ctx->contending_lock = ww;
  583. #endif
  584. return -EDEADLK;
  585. }
  586. static inline int __sched
  587. __ww_mutex_add_waiter(struct mutex_waiter *waiter,
  588. struct mutex *lock,
  589. struct ww_acquire_ctx *ww_ctx)
  590. {
  591. struct mutex_waiter *cur;
  592. struct list_head *pos;
  593. if (!ww_ctx) {
  594. list_add_tail(&waiter->list, &lock->wait_list);
  595. return 0;
  596. }
  597. /*
  598. * Add the waiter before the first waiter with a higher stamp.
  599. * Waiters without a context are skipped to avoid starving
  600. * them.
  601. */
  602. pos = &lock->wait_list;
  603. list_for_each_entry_reverse(cur, &lock->wait_list, list) {
  604. if (!cur->ww_ctx)
  605. continue;
  606. if (__ww_ctx_stamp_after(ww_ctx, cur->ww_ctx)) {
  607. /* Back off immediately if necessary. */
  608. if (ww_ctx->acquired > 0) {
  609. #ifdef CONFIG_DEBUG_MUTEXES
  610. struct ww_mutex *ww;
  611. ww = container_of(lock, struct ww_mutex, base);
  612. DEBUG_LOCKS_WARN_ON(ww_ctx->contending_lock);
  613. ww_ctx->contending_lock = ww;
  614. #endif
  615. return -EDEADLK;
  616. }
  617. break;
  618. }
  619. pos = &cur->list;
  620. /*
  621. * Wake up the waiter so that it gets a chance to back
  622. * off.
  623. */
  624. if (cur->ww_ctx->acquired > 0) {
  625. debug_mutex_wake_waiter(lock, cur);
  626. wake_up_process(cur->task);
  627. }
  628. }
  629. list_add_tail(&waiter->list, pos);
  630. return 0;
  631. }
  632. /*
  633. * Lock a mutex (possibly interruptible), slowpath:
  634. */
  635. static __always_inline int __sched
  636. __mutex_lock_common(struct mutex *lock, long state, unsigned int subclass,
  637. struct lockdep_map *nest_lock, unsigned long ip,
  638. struct ww_acquire_ctx *ww_ctx, const bool use_ww_ctx)
  639. {
  640. struct mutex_waiter waiter;
  641. bool first = false;
  642. struct ww_mutex *ww;
  643. int ret;
  644. might_sleep();
  645. ww = container_of(lock, struct ww_mutex, base);
  646. if (use_ww_ctx && ww_ctx) {
  647. if (unlikely(ww_ctx == READ_ONCE(ww->ctx)))
  648. return -EALREADY;
  649. }
  650. preempt_disable();
  651. mutex_acquire_nest(&lock->dep_map, subclass, 0, nest_lock, ip);
  652. if (__mutex_trylock(lock) ||
  653. mutex_optimistic_spin(lock, ww_ctx, use_ww_ctx, NULL)) {
  654. /* got the lock, yay! */
  655. lock_acquired(&lock->dep_map, ip);
  656. if (use_ww_ctx && ww_ctx)
  657. ww_mutex_set_context_fastpath(ww, ww_ctx);
  658. preempt_enable();
  659. return 0;
  660. }
  661. spin_lock(&lock->wait_lock);
  662. /*
  663. * After waiting to acquire the wait_lock, try again.
  664. */
  665. if (__mutex_trylock(lock)) {
  666. if (use_ww_ctx && ww_ctx)
  667. __ww_mutex_wakeup_for_backoff(lock, ww_ctx);
  668. goto skip_wait;
  669. }
  670. debug_mutex_lock_common(lock, &waiter);
  671. debug_mutex_add_waiter(lock, &waiter, current);
  672. lock_contended(&lock->dep_map, ip);
  673. if (!use_ww_ctx) {
  674. /* add waiting tasks to the end of the waitqueue (FIFO): */
  675. list_add_tail(&waiter.list, &lock->wait_list);
  676. #ifdef CONFIG_DEBUG_MUTEXES
  677. waiter.ww_ctx = MUTEX_POISON_WW_CTX;
  678. #endif
  679. } else {
  680. /* Add in stamp order, waking up waiters that must back off. */
  681. ret = __ww_mutex_add_waiter(&waiter, lock, ww_ctx);
  682. if (ret)
  683. goto err_early_backoff;
  684. waiter.ww_ctx = ww_ctx;
  685. }
  686. waiter.task = current;
  687. if (__mutex_waiter_is_first(lock, &waiter))
  688. __mutex_set_flag(lock, MUTEX_FLAG_WAITERS);
  689. set_current_state(state);
  690. for (;;) {
  691. /*
  692. * Once we hold wait_lock, we're serialized against
  693. * mutex_unlock() handing the lock off to us, do a trylock
  694. * before testing the error conditions to make sure we pick up
  695. * the handoff.
  696. */
  697. if (__mutex_trylock(lock))
  698. goto acquired;
  699. /*
  700. * Check for signals and wound conditions while holding
  701. * wait_lock. This ensures the lock cancellation is ordered
  702. * against mutex_unlock() and wake-ups do not go missing.
  703. */
  704. if (unlikely(signal_pending_state(state, current))) {
  705. ret = -EINTR;
  706. goto err;
  707. }
  708. if (use_ww_ctx && ww_ctx && ww_ctx->acquired > 0) {
  709. ret = __ww_mutex_lock_check_stamp(lock, &waiter, ww_ctx);
  710. if (ret)
  711. goto err;
  712. }
  713. spin_unlock(&lock->wait_lock);
  714. schedule_preempt_disabled();
  715. /*
  716. * ww_mutex needs to always recheck its position since its waiter
  717. * list is not FIFO ordered.
  718. */
  719. if ((use_ww_ctx && ww_ctx) || !first) {
  720. first = __mutex_waiter_is_first(lock, &waiter);
  721. if (first)
  722. __mutex_set_flag(lock, MUTEX_FLAG_HANDOFF);
  723. }
  724. set_current_state(state);
  725. /*
  726. * Here we order against unlock; we must either see it change
  727. * state back to RUNNING and fall through the next schedule(),
  728. * or we must see its unlock and acquire.
  729. */
  730. if (__mutex_trylock(lock) ||
  731. (first && mutex_optimistic_spin(lock, ww_ctx, use_ww_ctx, &waiter)))
  732. break;
  733. spin_lock(&lock->wait_lock);
  734. }
  735. spin_lock(&lock->wait_lock);
  736. acquired:
  737. __set_current_state(TASK_RUNNING);
  738. mutex_remove_waiter(lock, &waiter, current);
  739. if (likely(list_empty(&lock->wait_list)))
  740. __mutex_clear_flag(lock, MUTEX_FLAGS);
  741. debug_mutex_free_waiter(&waiter);
  742. skip_wait:
  743. /* got the lock - cleanup and rejoice! */
  744. lock_acquired(&lock->dep_map, ip);
  745. if (use_ww_ctx && ww_ctx)
  746. ww_mutex_set_context_slowpath(ww, ww_ctx);
  747. spin_unlock(&lock->wait_lock);
  748. preempt_enable();
  749. return 0;
  750. err:
  751. __set_current_state(TASK_RUNNING);
  752. mutex_remove_waiter(lock, &waiter, current);
  753. err_early_backoff:
  754. spin_unlock(&lock->wait_lock);
  755. debug_mutex_free_waiter(&waiter);
  756. mutex_release(&lock->dep_map, 1, ip);
  757. preempt_enable();
  758. return ret;
  759. }
  760. static int __sched
  761. __mutex_lock(struct mutex *lock, long state, unsigned int subclass,
  762. struct lockdep_map *nest_lock, unsigned long ip)
  763. {
  764. return __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false);
  765. }
  766. static int __sched
  767. __ww_mutex_lock(struct mutex *lock, long state, unsigned int subclass,
  768. struct lockdep_map *nest_lock, unsigned long ip,
  769. struct ww_acquire_ctx *ww_ctx)
  770. {
  771. return __mutex_lock_common(lock, state, subclass, nest_lock, ip, ww_ctx, true);
  772. }
  773. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  774. void __sched
  775. mutex_lock_nested(struct mutex *lock, unsigned int subclass)
  776. {
  777. __mutex_lock(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_);
  778. }
  779. EXPORT_SYMBOL_GPL(mutex_lock_nested);
  780. void __sched
  781. _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest)
  782. {
  783. __mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_);
  784. }
  785. EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock);
  786. int __sched
  787. mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass)
  788. {
  789. return __mutex_lock(lock, TASK_KILLABLE, subclass, NULL, _RET_IP_);
  790. }
  791. EXPORT_SYMBOL_GPL(mutex_lock_killable_nested);
  792. int __sched
  793. mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass)
  794. {
  795. return __mutex_lock(lock, TASK_INTERRUPTIBLE, subclass, NULL, _RET_IP_);
  796. }
  797. EXPORT_SYMBOL_GPL(mutex_lock_interruptible_nested);
  798. void __sched
  799. mutex_lock_io_nested(struct mutex *lock, unsigned int subclass)
  800. {
  801. int token;
  802. might_sleep();
  803. token = io_schedule_prepare();
  804. __mutex_lock_common(lock, TASK_UNINTERRUPTIBLE,
  805. subclass, NULL, _RET_IP_, NULL, 0);
  806. io_schedule_finish(token);
  807. }
  808. EXPORT_SYMBOL_GPL(mutex_lock_io_nested);
  809. static inline int
  810. ww_mutex_deadlock_injection(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  811. {
  812. #ifdef CONFIG_DEBUG_WW_MUTEX_SLOWPATH
  813. unsigned tmp;
  814. if (ctx->deadlock_inject_countdown-- == 0) {
  815. tmp = ctx->deadlock_inject_interval;
  816. if (tmp > UINT_MAX/4)
  817. tmp = UINT_MAX;
  818. else
  819. tmp = tmp*2 + tmp + tmp/2;
  820. ctx->deadlock_inject_interval = tmp;
  821. ctx->deadlock_inject_countdown = tmp;
  822. ctx->contending_lock = lock;
  823. ww_mutex_unlock(lock);
  824. return -EDEADLK;
  825. }
  826. #endif
  827. return 0;
  828. }
  829. int __sched
  830. ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  831. {
  832. int ret;
  833. might_sleep();
  834. ret = __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE,
  835. 0, ctx ? &ctx->dep_map : NULL, _RET_IP_,
  836. ctx);
  837. if (!ret && ctx && ctx->acquired > 1)
  838. return ww_mutex_deadlock_injection(lock, ctx);
  839. return ret;
  840. }
  841. EXPORT_SYMBOL_GPL(ww_mutex_lock);
  842. int __sched
  843. ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  844. {
  845. int ret;
  846. might_sleep();
  847. ret = __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE,
  848. 0, ctx ? &ctx->dep_map : NULL, _RET_IP_,
  849. ctx);
  850. if (!ret && ctx && ctx->acquired > 1)
  851. return ww_mutex_deadlock_injection(lock, ctx);
  852. return ret;
  853. }
  854. EXPORT_SYMBOL_GPL(ww_mutex_lock_interruptible);
  855. #endif
  856. /*
  857. * Release the lock, slowpath:
  858. */
  859. static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
  860. {
  861. struct task_struct *next = NULL;
  862. DEFINE_WAKE_Q(wake_q);
  863. unsigned long owner;
  864. mutex_release(&lock->dep_map, 1, ip);
  865. /*
  866. * Release the lock before (potentially) taking the spinlock such that
  867. * other contenders can get on with things ASAP.
  868. *
  869. * Except when HANDOFF, in that case we must not clear the owner field,
  870. * but instead set it to the top waiter.
  871. */
  872. owner = atomic_long_read(&lock->owner);
  873. for (;;) {
  874. unsigned long old;
  875. #ifdef CONFIG_DEBUG_MUTEXES
  876. DEBUG_LOCKS_WARN_ON(__owner_task(owner) != current);
  877. DEBUG_LOCKS_WARN_ON(owner & MUTEX_FLAG_PICKUP);
  878. #endif
  879. if (owner & MUTEX_FLAG_HANDOFF)
  880. break;
  881. old = atomic_long_cmpxchg_release(&lock->owner, owner,
  882. __owner_flags(owner));
  883. if (old == owner) {
  884. if (owner & MUTEX_FLAG_WAITERS)
  885. break;
  886. return;
  887. }
  888. owner = old;
  889. }
  890. spin_lock(&lock->wait_lock);
  891. debug_mutex_unlock(lock);
  892. if (!list_empty(&lock->wait_list)) {
  893. /* get the first entry from the wait-list: */
  894. struct mutex_waiter *waiter =
  895. list_first_entry(&lock->wait_list,
  896. struct mutex_waiter, list);
  897. next = waiter->task;
  898. debug_mutex_wake_waiter(lock, waiter);
  899. wake_q_add(&wake_q, next);
  900. }
  901. if (owner & MUTEX_FLAG_HANDOFF)
  902. __mutex_handoff(lock, next);
  903. spin_unlock(&lock->wait_lock);
  904. wake_up_q(&wake_q);
  905. }
  906. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  907. /*
  908. * Here come the less common (and hence less performance-critical) APIs:
  909. * mutex_lock_interruptible() and mutex_trylock().
  910. */
  911. static noinline int __sched
  912. __mutex_lock_killable_slowpath(struct mutex *lock);
  913. static noinline int __sched
  914. __mutex_lock_interruptible_slowpath(struct mutex *lock);
  915. /**
  916. * mutex_lock_interruptible() - Acquire the mutex, interruptible by signals.
  917. * @lock: The mutex to be acquired.
  918. *
  919. * Lock the mutex like mutex_lock(). If a signal is delivered while the
  920. * process is sleeping, this function will return without acquiring the
  921. * mutex.
  922. *
  923. * Context: Process context.
  924. * Return: 0 if the lock was successfully acquired or %-EINTR if a
  925. * signal arrived.
  926. */
  927. int __sched mutex_lock_interruptible(struct mutex *lock)
  928. {
  929. might_sleep();
  930. if (__mutex_trylock_fast(lock))
  931. return 0;
  932. return __mutex_lock_interruptible_slowpath(lock);
  933. }
  934. EXPORT_SYMBOL(mutex_lock_interruptible);
  935. /**
  936. * mutex_lock_killable() - Acquire the mutex, interruptible by fatal signals.
  937. * @lock: The mutex to be acquired.
  938. *
  939. * Lock the mutex like mutex_lock(). If a signal which will be fatal to
  940. * the current process is delivered while the process is sleeping, this
  941. * function will return without acquiring the mutex.
  942. *
  943. * Context: Process context.
  944. * Return: 0 if the lock was successfully acquired or %-EINTR if a
  945. * fatal signal arrived.
  946. */
  947. int __sched mutex_lock_killable(struct mutex *lock)
  948. {
  949. might_sleep();
  950. if (__mutex_trylock_fast(lock))
  951. return 0;
  952. return __mutex_lock_killable_slowpath(lock);
  953. }
  954. EXPORT_SYMBOL(mutex_lock_killable);
  955. /**
  956. * mutex_lock_io() - Acquire the mutex and mark the process as waiting for I/O
  957. * @lock: The mutex to be acquired.
  958. *
  959. * Lock the mutex like mutex_lock(). While the task is waiting for this
  960. * mutex, it will be accounted as being in the IO wait state by the
  961. * scheduler.
  962. *
  963. * Context: Process context.
  964. */
  965. void __sched mutex_lock_io(struct mutex *lock)
  966. {
  967. int token;
  968. token = io_schedule_prepare();
  969. mutex_lock(lock);
  970. io_schedule_finish(token);
  971. }
  972. EXPORT_SYMBOL_GPL(mutex_lock_io);
  973. static noinline void __sched
  974. __mutex_lock_slowpath(struct mutex *lock)
  975. {
  976. __mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_);
  977. }
  978. static noinline int __sched
  979. __mutex_lock_killable_slowpath(struct mutex *lock)
  980. {
  981. return __mutex_lock(lock, TASK_KILLABLE, 0, NULL, _RET_IP_);
  982. }
  983. static noinline int __sched
  984. __mutex_lock_interruptible_slowpath(struct mutex *lock)
  985. {
  986. return __mutex_lock(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_);
  987. }
  988. static noinline int __sched
  989. __ww_mutex_lock_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  990. {
  991. return __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE, 0, NULL,
  992. _RET_IP_, ctx);
  993. }
  994. static noinline int __sched
  995. __ww_mutex_lock_interruptible_slowpath(struct ww_mutex *lock,
  996. struct ww_acquire_ctx *ctx)
  997. {
  998. return __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE, 0, NULL,
  999. _RET_IP_, ctx);
  1000. }
  1001. #endif
  1002. /**
  1003. * mutex_trylock - try to acquire the mutex, without waiting
  1004. * @lock: the mutex to be acquired
  1005. *
  1006. * Try to acquire the mutex atomically. Returns 1 if the mutex
  1007. * has been acquired successfully, and 0 on contention.
  1008. *
  1009. * NOTE: this function follows the spin_trylock() convention, so
  1010. * it is negated from the down_trylock() return values! Be careful
  1011. * about this when converting semaphore users to mutexes.
  1012. *
  1013. * This function must not be used in interrupt context. The
  1014. * mutex must be released by the same task that acquired it.
  1015. */
  1016. int __sched mutex_trylock(struct mutex *lock)
  1017. {
  1018. bool locked = __mutex_trylock(lock);
  1019. if (locked)
  1020. mutex_acquire(&lock->dep_map, 0, 1, _RET_IP_);
  1021. return locked;
  1022. }
  1023. EXPORT_SYMBOL(mutex_trylock);
  1024. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  1025. int __sched
  1026. ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  1027. {
  1028. might_sleep();
  1029. if (__mutex_trylock_fast(&lock->base)) {
  1030. if (ctx)
  1031. ww_mutex_set_context_fastpath(lock, ctx);
  1032. return 0;
  1033. }
  1034. return __ww_mutex_lock_slowpath(lock, ctx);
  1035. }
  1036. EXPORT_SYMBOL(ww_mutex_lock);
  1037. int __sched
  1038. ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
  1039. {
  1040. might_sleep();
  1041. if (__mutex_trylock_fast(&lock->base)) {
  1042. if (ctx)
  1043. ww_mutex_set_context_fastpath(lock, ctx);
  1044. return 0;
  1045. }
  1046. return __ww_mutex_lock_interruptible_slowpath(lock, ctx);
  1047. }
  1048. EXPORT_SYMBOL(ww_mutex_lock_interruptible);
  1049. #endif
  1050. /**
  1051. * atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
  1052. * @cnt: the atomic which we are to dec
  1053. * @lock: the mutex to return holding if we dec to 0
  1054. *
  1055. * return true and hold lock if we dec to 0, return false otherwise
  1056. */
  1057. int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock)
  1058. {
  1059. /* dec if we can't possibly hit 0 */
  1060. if (atomic_add_unless(cnt, -1, 1))
  1061. return 0;
  1062. /* we might hit 0, so take the lock */
  1063. mutex_lock(lock);
  1064. if (!atomic_dec_and_test(cnt)) {
  1065. /* when we actually did the dec, we didn't hit 0 */
  1066. mutex_unlock(lock);
  1067. return 0;
  1068. }
  1069. /* we hit 0, and we hold the lock */
  1070. return 1;
  1071. }
  1072. EXPORT_SYMBOL(atomic_dec_and_mutex_lock);