mutex.c 32 KB

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