mutex.c 30 KB

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