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