mutex.c 15 KB

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