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