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