mutex.c 31 KB

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