mutex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. /*
  2. * kernel/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/mutex-design.txt.
  19. */
  20. #include <linux/mutex.h>
  21. #include <linux/sched.h>
  22. #include <linux/sched/rt.h>
  23. #include <linux/export.h>
  24. #include <linux/spinlock.h>
  25. #include <linux/interrupt.h>
  26. #include <linux/debug_locks.h>
  27. /*
  28. * In the DEBUG case we are using the "NULL fastpath" for mutexes,
  29. * which forces all calls into the slowpath:
  30. */
  31. #ifdef CONFIG_DEBUG_MUTEXES
  32. # include "mutex-debug.h"
  33. # include <asm-generic/mutex-null.h>
  34. #else
  35. # include "mutex.h"
  36. # include <asm/mutex.h>
  37. #endif
  38. /*
  39. * A mutex count of -1 indicates that waiters are sleeping waiting for the
  40. * mutex. Some architectures can allow any negative number, not just -1, for
  41. * this purpose.
  42. */
  43. #ifdef __ARCH_ALLOW_ANY_NEGATIVE_MUTEX_COUNT
  44. #define MUTEX_SHOW_NO_WAITER(mutex) (atomic_read(&(mutex)->count) >= 0)
  45. #else
  46. #define MUTEX_SHOW_NO_WAITER(mutex) (atomic_read(&(mutex)->count) != -1)
  47. #endif
  48. void
  49. __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)
  50. {
  51. atomic_set(&lock->count, 1);
  52. spin_lock_init(&lock->wait_lock);
  53. INIT_LIST_HEAD(&lock->wait_list);
  54. mutex_clear_owner(lock);
  55. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
  56. lock->spin_mlock = NULL;
  57. #endif
  58. debug_mutex_init(lock, name, key);
  59. }
  60. EXPORT_SYMBOL(__mutex_init);
  61. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  62. /*
  63. * We split the mutex lock/unlock logic into separate fastpath and
  64. * slowpath functions, to reduce the register pressure on the fastpath.
  65. * We also put the fastpath first in the kernel image, to make sure the
  66. * branch is predicted by the CPU as default-untaken.
  67. */
  68. static __used noinline void __sched
  69. __mutex_lock_slowpath(atomic_t *lock_count);
  70. /**
  71. * mutex_lock - acquire the mutex
  72. * @lock: the mutex to be acquired
  73. *
  74. * Lock the mutex exclusively for this task. If the mutex is not
  75. * available right now, it will sleep until it can get it.
  76. *
  77. * The mutex must later on be released by the same task that
  78. * acquired it. Recursive locking is not allowed. The task
  79. * may not exit without first unlocking the mutex. Also, kernel
  80. * memory where the mutex resides mutex must not be freed with
  81. * the mutex still locked. The mutex must first be initialized
  82. * (or statically defined) before it can be locked. memset()-ing
  83. * the mutex to 0 is not allowed.
  84. *
  85. * ( The CONFIG_DEBUG_MUTEXES .config option turns on debugging
  86. * checks that will enforce the restrictions and will also do
  87. * deadlock debugging. )
  88. *
  89. * This function is similar to (but not equivalent to) down().
  90. */
  91. void __sched mutex_lock(struct mutex *lock)
  92. {
  93. might_sleep();
  94. /*
  95. * The locking fastpath is the 1->0 transition from
  96. * 'unlocked' into 'locked' state.
  97. */
  98. __mutex_fastpath_lock(&lock->count, __mutex_lock_slowpath);
  99. mutex_set_owner(lock);
  100. }
  101. EXPORT_SYMBOL(mutex_lock);
  102. #endif
  103. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
  104. /*
  105. * In order to avoid a stampede of mutex spinners from acquiring the mutex
  106. * more or less simultaneously, the spinners need to acquire a MCS lock
  107. * first before spinning on the owner field.
  108. *
  109. * We don't inline mspin_lock() so that perf can correctly account for the
  110. * time spent in this lock function.
  111. */
  112. struct mspin_node {
  113. struct mspin_node *next ;
  114. int locked; /* 1 if lock acquired */
  115. };
  116. #define MLOCK(mutex) ((struct mspin_node **)&((mutex)->spin_mlock))
  117. static noinline
  118. void mspin_lock(struct mspin_node **lock, struct mspin_node *node)
  119. {
  120. struct mspin_node *prev;
  121. /* Init node */
  122. node->locked = 0;
  123. node->next = NULL;
  124. prev = xchg(lock, node);
  125. if (likely(prev == NULL)) {
  126. /* Lock acquired */
  127. node->locked = 1;
  128. return;
  129. }
  130. ACCESS_ONCE(prev->next) = node;
  131. smp_wmb();
  132. /* Wait until the lock holder passes the lock down */
  133. while (!ACCESS_ONCE(node->locked))
  134. arch_mutex_cpu_relax();
  135. }
  136. static void mspin_unlock(struct mspin_node **lock, struct mspin_node *node)
  137. {
  138. struct mspin_node *next = ACCESS_ONCE(node->next);
  139. if (likely(!next)) {
  140. /*
  141. * Release the lock by setting it to NULL
  142. */
  143. if (cmpxchg(lock, node, NULL) == node)
  144. return;
  145. /* Wait until the next pointer is set */
  146. while (!(next = ACCESS_ONCE(node->next)))
  147. arch_mutex_cpu_relax();
  148. }
  149. ACCESS_ONCE(next->locked) = 1;
  150. smp_wmb();
  151. }
  152. /*
  153. * Mutex spinning code migrated from kernel/sched/core.c
  154. */
  155. static inline bool owner_running(struct mutex *lock, struct task_struct *owner)
  156. {
  157. if (lock->owner != owner)
  158. return false;
  159. /*
  160. * Ensure we emit the owner->on_cpu, dereference _after_ checking
  161. * lock->owner still matches owner, if that fails, owner might
  162. * point to free()d memory, if it still matches, the rcu_read_lock()
  163. * ensures the memory stays valid.
  164. */
  165. barrier();
  166. return owner->on_cpu;
  167. }
  168. /*
  169. * Look out! "owner" is an entirely speculative pointer
  170. * access and not reliable.
  171. */
  172. static noinline
  173. int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner)
  174. {
  175. rcu_read_lock();
  176. while (owner_running(lock, owner)) {
  177. if (need_resched())
  178. break;
  179. arch_mutex_cpu_relax();
  180. }
  181. rcu_read_unlock();
  182. /*
  183. * We break out the loop above on need_resched() and when the
  184. * owner changed, which is a sign for heavy contention. Return
  185. * success only when lock->owner is NULL.
  186. */
  187. return lock->owner == NULL;
  188. }
  189. /*
  190. * Initial check for entering the mutex spinning loop
  191. */
  192. static inline int mutex_can_spin_on_owner(struct mutex *lock)
  193. {
  194. int retval = 1;
  195. rcu_read_lock();
  196. if (lock->owner)
  197. retval = lock->owner->on_cpu;
  198. rcu_read_unlock();
  199. /*
  200. * if lock->owner is not set, the mutex owner may have just acquired
  201. * it and not set the owner yet or the mutex has been released.
  202. */
  203. return retval;
  204. }
  205. #endif
  206. static __used noinline void __sched __mutex_unlock_slowpath(atomic_t *lock_count);
  207. /**
  208. * mutex_unlock - release the mutex
  209. * @lock: the mutex to be released
  210. *
  211. * Unlock a mutex that has been locked by this task previously.
  212. *
  213. * This function must not be used in interrupt context. Unlocking
  214. * of a not locked mutex is not allowed.
  215. *
  216. * This function is similar to (but not equivalent to) up().
  217. */
  218. void __sched mutex_unlock(struct mutex *lock)
  219. {
  220. /*
  221. * The unlocking fastpath is the 0->1 transition from 'locked'
  222. * into 'unlocked' state:
  223. */
  224. #ifndef CONFIG_DEBUG_MUTEXES
  225. /*
  226. * When debugging is enabled we must not clear the owner before time,
  227. * the slow path will always be taken, and that clears the owner field
  228. * after verifying that it was indeed current.
  229. */
  230. mutex_clear_owner(lock);
  231. #endif
  232. __mutex_fastpath_unlock(&lock->count, __mutex_unlock_slowpath);
  233. }
  234. EXPORT_SYMBOL(mutex_unlock);
  235. /*
  236. * Lock a mutex (possibly interruptible), slowpath:
  237. */
  238. static inline int __sched
  239. __mutex_lock_common(struct mutex *lock, long state, unsigned int subclass,
  240. struct lockdep_map *nest_lock, unsigned long ip)
  241. {
  242. struct task_struct *task = current;
  243. struct mutex_waiter waiter;
  244. unsigned long flags;
  245. preempt_disable();
  246. mutex_acquire_nest(&lock->dep_map, subclass, 0, nest_lock, ip);
  247. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
  248. /*
  249. * Optimistic spinning.
  250. *
  251. * We try to spin for acquisition when we find that there are no
  252. * pending waiters and the lock owner is currently running on a
  253. * (different) CPU.
  254. *
  255. * The rationale is that if the lock owner is running, it is likely to
  256. * release the lock soon.
  257. *
  258. * Since this needs the lock owner, and this mutex implementation
  259. * doesn't track the owner atomically in the lock field, we need to
  260. * track it non-atomically.
  261. *
  262. * We can't do this for DEBUG_MUTEXES because that relies on wait_lock
  263. * to serialize everything.
  264. *
  265. * The mutex spinners are queued up using MCS lock so that only one
  266. * spinner can compete for the mutex. However, if mutex spinning isn't
  267. * going to happen, there is no point in going through the lock/unlock
  268. * overhead.
  269. */
  270. if (!mutex_can_spin_on_owner(lock))
  271. goto slowpath;
  272. for (;;) {
  273. struct task_struct *owner;
  274. struct mspin_node node;
  275. /*
  276. * If there's an owner, wait for it to either
  277. * release the lock or go to sleep.
  278. */
  279. mspin_lock(MLOCK(lock), &node);
  280. owner = ACCESS_ONCE(lock->owner);
  281. if (owner && !mutex_spin_on_owner(lock, owner)) {
  282. mspin_unlock(MLOCK(lock), &node);
  283. break;
  284. }
  285. if ((atomic_read(&lock->count) == 1) &&
  286. (atomic_cmpxchg(&lock->count, 1, 0) == 1)) {
  287. lock_acquired(&lock->dep_map, ip);
  288. mutex_set_owner(lock);
  289. mspin_unlock(MLOCK(lock), &node);
  290. preempt_enable();
  291. return 0;
  292. }
  293. mspin_unlock(MLOCK(lock), &node);
  294. /*
  295. * When there's no owner, we might have preempted between the
  296. * owner acquiring the lock and setting the owner field. If
  297. * we're an RT task that will live-lock because we won't let
  298. * the owner complete.
  299. */
  300. if (!owner && (need_resched() || rt_task(task)))
  301. break;
  302. /*
  303. * The cpu_relax() call is a compiler barrier which forces
  304. * everything in this loop to be re-loaded. We don't need
  305. * memory barriers as we'll eventually observe the right
  306. * values at the cost of a few extra spins.
  307. */
  308. arch_mutex_cpu_relax();
  309. }
  310. slowpath:
  311. #endif
  312. spin_lock_mutex(&lock->wait_lock, flags);
  313. debug_mutex_lock_common(lock, &waiter);
  314. debug_mutex_add_waiter(lock, &waiter, task_thread_info(task));
  315. /* add waiting tasks to the end of the waitqueue (FIFO): */
  316. list_add_tail(&waiter.list, &lock->wait_list);
  317. waiter.task = task;
  318. if (MUTEX_SHOW_NO_WAITER(lock) && (atomic_xchg(&lock->count, -1) == 1))
  319. goto done;
  320. lock_contended(&lock->dep_map, ip);
  321. for (;;) {
  322. /*
  323. * Lets try to take the lock again - this is needed even if
  324. * we get here for the first time (shortly after failing to
  325. * acquire the lock), to make sure that we get a wakeup once
  326. * it's unlocked. Later on, if we sleep, this is the
  327. * operation that gives us the lock. We xchg it to -1, so
  328. * that when we release the lock, we properly wake up the
  329. * other waiters:
  330. */
  331. if (MUTEX_SHOW_NO_WAITER(lock) &&
  332. (atomic_xchg(&lock->count, -1) == 1))
  333. break;
  334. /*
  335. * got a signal? (This code gets eliminated in the
  336. * TASK_UNINTERRUPTIBLE case.)
  337. */
  338. if (unlikely(signal_pending_state(state, task))) {
  339. mutex_remove_waiter(lock, &waiter,
  340. task_thread_info(task));
  341. mutex_release(&lock->dep_map, 1, ip);
  342. spin_unlock_mutex(&lock->wait_lock, flags);
  343. debug_mutex_free_waiter(&waiter);
  344. preempt_enable();
  345. return -EINTR;
  346. }
  347. __set_task_state(task, state);
  348. /* didn't get the lock, go to sleep: */
  349. spin_unlock_mutex(&lock->wait_lock, flags);
  350. schedule_preempt_disabled();
  351. spin_lock_mutex(&lock->wait_lock, flags);
  352. }
  353. done:
  354. lock_acquired(&lock->dep_map, ip);
  355. /* got the lock - rejoice! */
  356. mutex_remove_waiter(lock, &waiter, current_thread_info());
  357. mutex_set_owner(lock);
  358. /* set it to 0 if there are no waiters left: */
  359. if (likely(list_empty(&lock->wait_list)))
  360. atomic_set(&lock->count, 0);
  361. spin_unlock_mutex(&lock->wait_lock, flags);
  362. debug_mutex_free_waiter(&waiter);
  363. preempt_enable();
  364. return 0;
  365. }
  366. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  367. void __sched
  368. mutex_lock_nested(struct mutex *lock, unsigned int subclass)
  369. {
  370. might_sleep();
  371. __mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_);
  372. }
  373. EXPORT_SYMBOL_GPL(mutex_lock_nested);
  374. void __sched
  375. _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest)
  376. {
  377. might_sleep();
  378. __mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_);
  379. }
  380. EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock);
  381. int __sched
  382. mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass)
  383. {
  384. might_sleep();
  385. return __mutex_lock_common(lock, TASK_KILLABLE, subclass, NULL, _RET_IP_);
  386. }
  387. EXPORT_SYMBOL_GPL(mutex_lock_killable_nested);
  388. int __sched
  389. mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass)
  390. {
  391. might_sleep();
  392. return __mutex_lock_common(lock, TASK_INTERRUPTIBLE,
  393. subclass, NULL, _RET_IP_);
  394. }
  395. EXPORT_SYMBOL_GPL(mutex_lock_interruptible_nested);
  396. #endif
  397. /*
  398. * Release the lock, slowpath:
  399. */
  400. static inline void
  401. __mutex_unlock_common_slowpath(atomic_t *lock_count, int nested)
  402. {
  403. struct mutex *lock = container_of(lock_count, struct mutex, count);
  404. unsigned long flags;
  405. spin_lock_mutex(&lock->wait_lock, flags);
  406. mutex_release(&lock->dep_map, nested, _RET_IP_);
  407. debug_mutex_unlock(lock);
  408. /*
  409. * some architectures leave the lock unlocked in the fastpath failure
  410. * case, others need to leave it locked. In the later case we have to
  411. * unlock it here
  412. */
  413. if (__mutex_slowpath_needs_to_unlock())
  414. atomic_set(&lock->count, 1);
  415. if (!list_empty(&lock->wait_list)) {
  416. /* get the first entry from the wait-list: */
  417. struct mutex_waiter *waiter =
  418. list_entry(lock->wait_list.next,
  419. struct mutex_waiter, list);
  420. debug_mutex_wake_waiter(lock, waiter);
  421. wake_up_process(waiter->task);
  422. }
  423. spin_unlock_mutex(&lock->wait_lock, flags);
  424. }
  425. /*
  426. * Release the lock, slowpath:
  427. */
  428. static __used noinline void
  429. __mutex_unlock_slowpath(atomic_t *lock_count)
  430. {
  431. __mutex_unlock_common_slowpath(lock_count, 1);
  432. }
  433. #ifndef CONFIG_DEBUG_LOCK_ALLOC
  434. /*
  435. * Here come the less common (and hence less performance-critical) APIs:
  436. * mutex_lock_interruptible() and mutex_trylock().
  437. */
  438. static noinline int __sched
  439. __mutex_lock_killable_slowpath(atomic_t *lock_count);
  440. static noinline int __sched
  441. __mutex_lock_interruptible_slowpath(atomic_t *lock_count);
  442. /**
  443. * mutex_lock_interruptible - acquire the mutex, interruptible
  444. * @lock: the mutex to be acquired
  445. *
  446. * Lock the mutex like mutex_lock(), and return 0 if the mutex has
  447. * been acquired or sleep until the mutex becomes available. If a
  448. * signal arrives while waiting for the lock then this function
  449. * returns -EINTR.
  450. *
  451. * This function is similar to (but not equivalent to) down_interruptible().
  452. */
  453. int __sched mutex_lock_interruptible(struct mutex *lock)
  454. {
  455. int ret;
  456. might_sleep();
  457. ret = __mutex_fastpath_lock_retval
  458. (&lock->count, __mutex_lock_interruptible_slowpath);
  459. if (!ret)
  460. mutex_set_owner(lock);
  461. return ret;
  462. }
  463. EXPORT_SYMBOL(mutex_lock_interruptible);
  464. int __sched mutex_lock_killable(struct mutex *lock)
  465. {
  466. int ret;
  467. might_sleep();
  468. ret = __mutex_fastpath_lock_retval
  469. (&lock->count, __mutex_lock_killable_slowpath);
  470. if (!ret)
  471. mutex_set_owner(lock);
  472. return ret;
  473. }
  474. EXPORT_SYMBOL(mutex_lock_killable);
  475. static __used noinline void __sched
  476. __mutex_lock_slowpath(atomic_t *lock_count)
  477. {
  478. struct mutex *lock = container_of(lock_count, struct mutex, count);
  479. __mutex_lock_common(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_);
  480. }
  481. static noinline int __sched
  482. __mutex_lock_killable_slowpath(atomic_t *lock_count)
  483. {
  484. struct mutex *lock = container_of(lock_count, struct mutex, count);
  485. return __mutex_lock_common(lock, TASK_KILLABLE, 0, NULL, _RET_IP_);
  486. }
  487. static noinline int __sched
  488. __mutex_lock_interruptible_slowpath(atomic_t *lock_count)
  489. {
  490. struct mutex *lock = container_of(lock_count, struct mutex, count);
  491. return __mutex_lock_common(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_);
  492. }
  493. #endif
  494. /*
  495. * Spinlock based trylock, we take the spinlock and check whether we
  496. * can get the lock:
  497. */
  498. static inline int __mutex_trylock_slowpath(atomic_t *lock_count)
  499. {
  500. struct mutex *lock = container_of(lock_count, struct mutex, count);
  501. unsigned long flags;
  502. int prev;
  503. spin_lock_mutex(&lock->wait_lock, flags);
  504. prev = atomic_xchg(&lock->count, -1);
  505. if (likely(prev == 1)) {
  506. mutex_set_owner(lock);
  507. mutex_acquire(&lock->dep_map, 0, 1, _RET_IP_);
  508. }
  509. /* Set it back to 0 if there are no waiters: */
  510. if (likely(list_empty(&lock->wait_list)))
  511. atomic_set(&lock->count, 0);
  512. spin_unlock_mutex(&lock->wait_lock, flags);
  513. return prev == 1;
  514. }
  515. /**
  516. * mutex_trylock - try to acquire the mutex, without waiting
  517. * @lock: the mutex to be acquired
  518. *
  519. * Try to acquire the mutex atomically. Returns 1 if the mutex
  520. * has been acquired successfully, and 0 on contention.
  521. *
  522. * NOTE: this function follows the spin_trylock() convention, so
  523. * it is negated from the down_trylock() return values! Be careful
  524. * about this when converting semaphore users to mutexes.
  525. *
  526. * This function must not be used in interrupt context. The
  527. * mutex must be released by the same task that acquired it.
  528. */
  529. int __sched mutex_trylock(struct mutex *lock)
  530. {
  531. int ret;
  532. ret = __mutex_fastpath_trylock(&lock->count, __mutex_trylock_slowpath);
  533. if (ret)
  534. mutex_set_owner(lock);
  535. return ret;
  536. }
  537. EXPORT_SYMBOL(mutex_trylock);
  538. /**
  539. * atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
  540. * @cnt: the atomic which we are to dec
  541. * @lock: the mutex to return holding if we dec to 0
  542. *
  543. * return true and hold lock if we dec to 0, return false otherwise
  544. */
  545. int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock)
  546. {
  547. /* dec if we can't possibly hit 0 */
  548. if (atomic_add_unless(cnt, -1, 1))
  549. return 0;
  550. /* we might hit 0, so take the lock */
  551. mutex_lock(lock);
  552. if (!atomic_dec_and_test(cnt)) {
  553. /* when we actually did the dec, we didn't hit 0 */
  554. mutex_unlock(lock);
  555. return 0;
  556. }
  557. /* we hit 0, and we hold the lock */
  558. return 1;
  559. }
  560. EXPORT_SYMBOL(atomic_dec_and_mutex_lock);