mutex.c 31 KB

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