• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifdef CONFIG_DEBUG_MUTEXES
34 # include "mutex-debug.h"
35 #else
36 # include "mutex.h"
37 #endif
38 
39 #include <trace/hooks/dtask.h>
40 
41 void
__mutex_init(struct mutex * lock,const char * name,struct lock_class_key * key)42 __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)
43 {
44 	atomic_long_set(&lock->owner, 0);
45 	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  */
__mutex_owner(struct mutex * lock)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 
__owner_task(unsigned long owner)80 static inline struct task_struct *__owner_task(unsigned long owner)
81 {
82 	return (struct task_struct *)(owner & ~MUTEX_FLAGS);
83 }
84 
mutex_is_locked(struct mutex * lock)85 bool mutex_is_locked(struct mutex *lock)
86 {
87 	return __mutex_owner(lock) != NULL;
88 }
89 EXPORT_SYMBOL(mutex_is_locked);
90 
91 __must_check enum mutex_trylock_recursive_enum
mutex_trylock_recursive(struct mutex * lock)92 mutex_trylock_recursive(struct mutex *lock)
93 {
94 	if (unlikely(__mutex_owner(lock) == current))
95 		return MUTEX_TRYLOCK_RECURSIVE;
96 
97 	return mutex_trylock(lock);
98 }
99 EXPORT_SYMBOL(mutex_trylock_recursive);
100 
__owner_flags(unsigned long owner)101 static inline unsigned long __owner_flags(unsigned long owner)
102 {
103 	return owner & MUTEX_FLAGS;
104 }
105 
106 /*
107  * Trylock variant that retuns the owning task on failure.
108  */
__mutex_trylock_or_owner(struct mutex * lock)109 static inline struct task_struct *__mutex_trylock_or_owner(struct mutex *lock)
110 {
111 	unsigned long owner, curr = (unsigned long)current;
112 
113 	owner = atomic_long_read(&lock->owner);
114 	for (;;) { /* must loop, can race against a flag */
115 		unsigned long old, flags = __owner_flags(owner);
116 		unsigned long task = owner & ~MUTEX_FLAGS;
117 
118 		if (task) {
119 			if (likely(task != curr))
120 				break;
121 
122 			if (likely(!(flags & MUTEX_FLAG_PICKUP)))
123 				break;
124 
125 			flags &= ~MUTEX_FLAG_PICKUP;
126 		} else {
127 #ifdef CONFIG_DEBUG_MUTEXES
128 			DEBUG_LOCKS_WARN_ON(flags & MUTEX_FLAG_PICKUP);
129 #endif
130 		}
131 
132 		/*
133 		 * We set the HANDOFF bit, we must make sure it doesn't live
134 		 * past the point where we acquire it. This would be possible
135 		 * if we (accidentally) set the bit on an unlocked mutex.
136 		 */
137 		flags &= ~MUTEX_FLAG_HANDOFF;
138 
139 		old = atomic_long_cmpxchg_acquire(&lock->owner, owner, curr | flags);
140 		if (old == owner)
141 			return NULL;
142 
143 		owner = old;
144 	}
145 
146 	return __owner_task(owner);
147 }
148 
149 /*
150  * Actual trylock that will work on any unlocked state.
151  */
__mutex_trylock(struct mutex * lock)152 static inline bool __mutex_trylock(struct mutex *lock)
153 {
154 	return !__mutex_trylock_or_owner(lock);
155 }
156 
157 #ifndef CONFIG_DEBUG_LOCK_ALLOC
158 /*
159  * Lockdep annotations are contained to the slow paths for simplicity.
160  * There is nothing that would stop spreading the lockdep annotations outwards
161  * except more code.
162  */
163 
164 /*
165  * Optimistic trylock that only works in the uncontended case. Make sure to
166  * follow with a __mutex_trylock() before failing.
167  */
__mutex_trylock_fast(struct mutex * lock)168 static __always_inline bool __mutex_trylock_fast(struct mutex *lock)
169 {
170 	unsigned long curr = (unsigned long)current;
171 	unsigned long zero = 0UL;
172 
173 	if (atomic_long_try_cmpxchg_acquire(&lock->owner, &zero, curr))
174 		return true;
175 
176 	return false;
177 }
178 
__mutex_unlock_fast(struct mutex * lock)179 static __always_inline bool __mutex_unlock_fast(struct mutex *lock)
180 {
181 	unsigned long curr = (unsigned long)current;
182 
183 	if (atomic_long_cmpxchg_release(&lock->owner, curr, 0UL) == curr)
184 		return true;
185 
186 	return false;
187 }
188 #endif
189 
__mutex_set_flag(struct mutex * lock,unsigned long flag)190 static inline void __mutex_set_flag(struct mutex *lock, unsigned long flag)
191 {
192 	atomic_long_or(flag, &lock->owner);
193 }
194 
__mutex_clear_flag(struct mutex * lock,unsigned long flag)195 static inline void __mutex_clear_flag(struct mutex *lock, unsigned long flag)
196 {
197 	atomic_long_andnot(flag, &lock->owner);
198 }
199 
__mutex_waiter_is_first(struct mutex * lock,struct mutex_waiter * waiter)200 static inline bool __mutex_waiter_is_first(struct mutex *lock, struct mutex_waiter *waiter)
201 {
202 	return list_first_entry(&lock->wait_list, struct mutex_waiter, list) == waiter;
203 }
204 
205 /*
206  * Add @waiter to a given location in the lock wait_list and set the
207  * FLAG_WAITERS flag if it's the first waiter.
208  */
209 static void
__mutex_add_waiter(struct mutex * lock,struct mutex_waiter * waiter,struct list_head * list)210 __mutex_add_waiter(struct mutex *lock, struct mutex_waiter *waiter,
211 		   struct list_head *list)
212 {
213 	bool already_on_list = false;
214 	debug_mutex_add_waiter(lock, waiter, current);
215 
216 	trace_android_vh_alter_mutex_list_add(lock, waiter, list, &already_on_list);
217 	if (!already_on_list)
218 		list_add_tail(&waiter->list, list);
219 	if (__mutex_waiter_is_first(lock, waiter))
220 		__mutex_set_flag(lock, MUTEX_FLAG_WAITERS);
221 }
222 
223 static void
__mutex_remove_waiter(struct mutex * lock,struct mutex_waiter * waiter)224 __mutex_remove_waiter(struct mutex *lock, struct mutex_waiter *waiter)
225 {
226 	list_del(&waiter->list);
227 	if (likely(list_empty(&lock->wait_list)))
228 		__mutex_clear_flag(lock, MUTEX_FLAGS);
229 
230 	debug_mutex_remove_waiter(lock, waiter, current);
231 }
232 
233 /*
234  * Give up ownership to a specific task, when @task = NULL, this is equivalent
235  * to a regular unlock. Sets PICKUP on a handoff, clears HANDOF, preserves
236  * WAITERS. Provides RELEASE semantics like a regular unlock, the
237  * __mutex_trylock() provides a matching ACQUIRE semantics for the handoff.
238  */
__mutex_handoff(struct mutex * lock,struct task_struct * task)239 static void __mutex_handoff(struct mutex *lock, struct task_struct *task)
240 {
241 	unsigned long owner = atomic_long_read(&lock->owner);
242 
243 	for (;;) {
244 		unsigned long old, new;
245 
246 #ifdef CONFIG_DEBUG_MUTEXES
247 		DEBUG_LOCKS_WARN_ON(__owner_task(owner) != current);
248 		DEBUG_LOCKS_WARN_ON(owner & MUTEX_FLAG_PICKUP);
249 #endif
250 
251 		new = (owner & MUTEX_FLAG_WAITERS);
252 		new |= (unsigned long)task;
253 		if (task)
254 			new |= MUTEX_FLAG_PICKUP;
255 
256 		old = atomic_long_cmpxchg_release(&lock->owner, owner, new);
257 		if (old == owner)
258 			break;
259 
260 		owner = old;
261 	}
262 }
263 
264 #ifndef CONFIG_DEBUG_LOCK_ALLOC
265 /*
266  * We split the mutex lock/unlock logic into separate fastpath and
267  * slowpath functions, to reduce the register pressure on the fastpath.
268  * We also put the fastpath first in the kernel image, to make sure the
269  * branch is predicted by the CPU as default-untaken.
270  */
271 static void __sched __mutex_lock_slowpath(struct mutex *lock);
272 
273 /**
274  * mutex_lock - acquire the mutex
275  * @lock: the mutex to be acquired
276  *
277  * Lock the mutex exclusively for this task. If the mutex is not
278  * available right now, it will sleep until it can get it.
279  *
280  * The mutex must later on be released by the same task that
281  * acquired it. Recursive locking is not allowed. The task
282  * may not exit without first unlocking the mutex. Also, kernel
283  * memory where the mutex resides must not be freed with
284  * the mutex still locked. The mutex must first be initialized
285  * (or statically defined) before it can be locked. memset()-ing
286  * the mutex to 0 is not allowed.
287  *
288  * (The CONFIG_DEBUG_MUTEXES .config option turns on debugging
289  * checks that will enforce the restrictions and will also do
290  * deadlock debugging)
291  *
292  * This function is similar to (but not equivalent to) down().
293  */
mutex_lock(struct mutex * lock)294 void __sched mutex_lock(struct mutex *lock)
295 {
296 	might_sleep();
297 
298 	if (!__mutex_trylock_fast(lock))
299 		__mutex_lock_slowpath(lock);
300 }
301 EXPORT_SYMBOL(mutex_lock);
302 #endif
303 
304 /*
305  * Wait-Die:
306  *   The newer transactions are killed when:
307  *     It (the new transaction) makes a request for a lock being held
308  *     by an older transaction.
309  *
310  * Wound-Wait:
311  *   The newer transactions are wounded when:
312  *     An older transaction makes a request for a lock being held by
313  *     the newer transaction.
314  */
315 
316 /*
317  * Associate the ww_mutex @ww with the context @ww_ctx under which we acquired
318  * it.
319  */
320 static __always_inline void
ww_mutex_lock_acquired(struct ww_mutex * ww,struct ww_acquire_ctx * ww_ctx)321 ww_mutex_lock_acquired(struct ww_mutex *ww, struct ww_acquire_ctx *ww_ctx)
322 {
323 #ifdef CONFIG_DEBUG_MUTEXES
324 	/*
325 	 * If this WARN_ON triggers, you used ww_mutex_lock to acquire,
326 	 * but released with a normal mutex_unlock in this call.
327 	 *
328 	 * This should never happen, always use ww_mutex_unlock.
329 	 */
330 	DEBUG_LOCKS_WARN_ON(ww->ctx);
331 
332 	/*
333 	 * Not quite done after calling ww_acquire_done() ?
334 	 */
335 	DEBUG_LOCKS_WARN_ON(ww_ctx->done_acquire);
336 
337 	if (ww_ctx->contending_lock) {
338 		/*
339 		 * After -EDEADLK you tried to
340 		 * acquire a different ww_mutex? Bad!
341 		 */
342 		DEBUG_LOCKS_WARN_ON(ww_ctx->contending_lock != ww);
343 
344 		/*
345 		 * You called ww_mutex_lock after receiving -EDEADLK,
346 		 * but 'forgot' to unlock everything else first?
347 		 */
348 		DEBUG_LOCKS_WARN_ON(ww_ctx->acquired > 0);
349 		ww_ctx->contending_lock = NULL;
350 	}
351 
352 	/*
353 	 * Naughty, using a different class will lead to undefined behavior!
354 	 */
355 	DEBUG_LOCKS_WARN_ON(ww_ctx->ww_class != ww->ww_class);
356 #endif
357 	ww_ctx->acquired++;
358 	ww->ctx = ww_ctx;
359 }
360 
361 /*
362  * Determine if context @a is 'after' context @b. IOW, @a is a younger
363  * transaction than @b and depending on algorithm either needs to wait for
364  * @b or die.
365  */
366 static inline bool __sched
__ww_ctx_stamp_after(struct ww_acquire_ctx * a,struct ww_acquire_ctx * b)367 __ww_ctx_stamp_after(struct ww_acquire_ctx *a, struct ww_acquire_ctx *b)
368 {
369 
370 	return (signed long)(a->stamp - b->stamp) > 0;
371 }
372 
373 /*
374  * Wait-Die; wake a younger waiter context (when locks held) such that it can
375  * die.
376  *
377  * Among waiters with context, only the first one can have other locks acquired
378  * already (ctx->acquired > 0), because __ww_mutex_add_waiter() and
379  * __ww_mutex_check_kill() wake any but the earliest context.
380  */
381 static bool __sched
__ww_mutex_die(struct mutex * lock,struct mutex_waiter * waiter,struct ww_acquire_ctx * ww_ctx)382 __ww_mutex_die(struct mutex *lock, struct mutex_waiter *waiter,
383 	       struct ww_acquire_ctx *ww_ctx)
384 {
385 	if (!ww_ctx->is_wait_die)
386 		return false;
387 
388 	if (waiter->ww_ctx->acquired > 0 &&
389 			__ww_ctx_stamp_after(waiter->ww_ctx, ww_ctx)) {
390 		debug_mutex_wake_waiter(lock, waiter);
391 		wake_up_process(waiter->task);
392 	}
393 
394 	return true;
395 }
396 
397 /*
398  * Wound-Wait; wound a younger @hold_ctx if it holds the lock.
399  *
400  * Wound the lock holder if there are waiters with older transactions than
401  * the lock holders. Even if multiple waiters may wound the lock holder,
402  * it's sufficient that only one does.
403  */
__ww_mutex_wound(struct mutex * lock,struct ww_acquire_ctx * ww_ctx,struct ww_acquire_ctx * hold_ctx)404 static bool __ww_mutex_wound(struct mutex *lock,
405 			     struct ww_acquire_ctx *ww_ctx,
406 			     struct ww_acquire_ctx *hold_ctx)
407 {
408 	struct task_struct *owner = __mutex_owner(lock);
409 
410 	lockdep_assert_held(&lock->wait_lock);
411 
412 	/*
413 	 * Possible through __ww_mutex_add_waiter() when we race with
414 	 * ww_mutex_set_context_fastpath(). In that case we'll get here again
415 	 * through __ww_mutex_check_waiters().
416 	 */
417 	if (!hold_ctx)
418 		return false;
419 
420 	/*
421 	 * Can have !owner because of __mutex_unlock_slowpath(), but if owner,
422 	 * it cannot go away because we'll have FLAG_WAITERS set and hold
423 	 * wait_lock.
424 	 */
425 	if (!owner)
426 		return false;
427 
428 	if (ww_ctx->acquired > 0 && __ww_ctx_stamp_after(hold_ctx, ww_ctx)) {
429 		hold_ctx->wounded = 1;
430 
431 		/*
432 		 * wake_up_process() paired with set_current_state()
433 		 * inserts sufficient barriers to make sure @owner either sees
434 		 * it's wounded in __ww_mutex_check_kill() or has a
435 		 * wakeup pending to re-read the wounded state.
436 		 */
437 		if (owner != current)
438 			wake_up_process(owner);
439 
440 		return true;
441 	}
442 
443 	return false;
444 }
445 
446 /*
447  * We just acquired @lock under @ww_ctx, if there are later contexts waiting
448  * behind us on the wait-list, check if they need to die, or wound us.
449  *
450  * See __ww_mutex_add_waiter() for the list-order construction; basically the
451  * list is ordered by stamp, smallest (oldest) first.
452  *
453  * This relies on never mixing wait-die/wound-wait on the same wait-list;
454  * which is currently ensured by that being a ww_class property.
455  *
456  * The current task must not be on the wait list.
457  */
458 static void __sched
__ww_mutex_check_waiters(struct mutex * lock,struct ww_acquire_ctx * ww_ctx)459 __ww_mutex_check_waiters(struct mutex *lock, struct ww_acquire_ctx *ww_ctx)
460 {
461 	struct mutex_waiter *cur;
462 
463 	lockdep_assert_held(&lock->wait_lock);
464 
465 	list_for_each_entry(cur, &lock->wait_list, list) {
466 		if (!cur->ww_ctx)
467 			continue;
468 
469 		if (__ww_mutex_die(lock, cur, ww_ctx) ||
470 		    __ww_mutex_wound(lock, cur->ww_ctx, ww_ctx))
471 			break;
472 	}
473 }
474 
475 /*
476  * After acquiring lock with fastpath, where we do not hold wait_lock, set ctx
477  * and wake up any waiters so they can recheck.
478  */
479 static __always_inline void
ww_mutex_set_context_fastpath(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)480 ww_mutex_set_context_fastpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
481 {
482 	ww_mutex_lock_acquired(lock, ctx);
483 
484 	/*
485 	 * The lock->ctx update should be visible on all cores before
486 	 * the WAITERS check is done, otherwise contended waiters might be
487 	 * missed. The contended waiters will either see ww_ctx == NULL
488 	 * and keep spinning, or it will acquire wait_lock, add itself
489 	 * to waiter list and sleep.
490 	 */
491 	smp_mb(); /* See comments above and below. */
492 
493 	/*
494 	 * [W] ww->ctx = ctx	    [W] MUTEX_FLAG_WAITERS
495 	 *     MB		        MB
496 	 * [R] MUTEX_FLAG_WAITERS   [R] ww->ctx
497 	 *
498 	 * The memory barrier above pairs with the memory barrier in
499 	 * __ww_mutex_add_waiter() and makes sure we either observe ww->ctx
500 	 * and/or !empty list.
501 	 */
502 	if (likely(!(atomic_long_read(&lock->base.owner) & MUTEX_FLAG_WAITERS)))
503 		return;
504 
505 	/*
506 	 * Uh oh, we raced in fastpath, check if any of the waiters need to
507 	 * die or wound us.
508 	 */
509 	spin_lock(&lock->base.wait_lock);
510 	__ww_mutex_check_waiters(&lock->base, ctx);
511 	spin_unlock(&lock->base.wait_lock);
512 }
513 
514 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
515 
516 static inline
ww_mutex_spin_on_owner(struct mutex * lock,struct ww_acquire_ctx * ww_ctx,struct mutex_waiter * waiter)517 bool ww_mutex_spin_on_owner(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
518 			    struct mutex_waiter *waiter)
519 {
520 	struct ww_mutex *ww;
521 
522 	ww = container_of(lock, struct ww_mutex, base);
523 
524 	/*
525 	 * If ww->ctx is set the contents are undefined, only
526 	 * by acquiring wait_lock there is a guarantee that
527 	 * they are not invalid when reading.
528 	 *
529 	 * As such, when deadlock detection needs to be
530 	 * performed the optimistic spinning cannot be done.
531 	 *
532 	 * Check this in every inner iteration because we may
533 	 * be racing against another thread's ww_mutex_lock.
534 	 */
535 	if (ww_ctx->acquired > 0 && READ_ONCE(ww->ctx))
536 		return false;
537 
538 	/*
539 	 * If we aren't on the wait list yet, cancel the spin
540 	 * if there are waiters. We want  to avoid stealing the
541 	 * lock from a waiter with an earlier stamp, since the
542 	 * other thread may already own a lock that we also
543 	 * need.
544 	 */
545 	if (!waiter && (atomic_long_read(&lock->owner) & MUTEX_FLAG_WAITERS))
546 		return false;
547 
548 	/*
549 	 * Similarly, stop spinning if we are no longer the
550 	 * first waiter.
551 	 */
552 	if (waiter && !__mutex_waiter_is_first(lock, waiter))
553 		return false;
554 
555 	return true;
556 }
557 
558 /*
559  * Look out! "owner" is an entirely speculative pointer access and not
560  * reliable.
561  *
562  * "noinline" so that this function shows up on perf profiles.
563  */
564 static noinline
mutex_spin_on_owner(struct mutex * lock,struct task_struct * owner,struct ww_acquire_ctx * ww_ctx,struct mutex_waiter * waiter)565 bool mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner,
566 			 struct ww_acquire_ctx *ww_ctx, struct mutex_waiter *waiter)
567 {
568 	bool ret = true;
569 
570 	rcu_read_lock();
571 	while (__mutex_owner(lock) == owner) {
572 		/*
573 		 * Ensure we emit the owner->on_cpu, dereference _after_
574 		 * checking lock->owner still matches owner. If that fails,
575 		 * owner might point to freed memory. If it still matches,
576 		 * the rcu_read_lock() ensures the memory stays valid.
577 		 */
578 		barrier();
579 
580 		/*
581 		 * Use vcpu_is_preempted to detect lock holder preemption issue.
582 		 */
583 		if (!owner->on_cpu || need_resched() ||
584 				vcpu_is_preempted(task_cpu(owner))) {
585 			ret = false;
586 			break;
587 		}
588 
589 		if (ww_ctx && !ww_mutex_spin_on_owner(lock, ww_ctx, waiter)) {
590 			ret = false;
591 			break;
592 		}
593 
594 		cpu_relax();
595 	}
596 	rcu_read_unlock();
597 
598 	return ret;
599 }
600 
601 /*
602  * Initial check for entering the mutex spinning loop
603  */
mutex_can_spin_on_owner(struct mutex * lock)604 static inline int mutex_can_spin_on_owner(struct mutex *lock)
605 {
606 	struct task_struct *owner;
607 	int retval = 1;
608 
609 	if (need_resched())
610 		return 0;
611 
612 	rcu_read_lock();
613 	owner = __mutex_owner(lock);
614 
615 	/*
616 	 * As lock holder preemption issue, we both skip spinning if task is not
617 	 * on cpu or its cpu is preempted
618 	 */
619 	if (owner)
620 		retval = owner->on_cpu && !vcpu_is_preempted(task_cpu(owner));
621 	rcu_read_unlock();
622 
623 	/*
624 	 * If lock->owner is not set, the mutex has been released. Return true
625 	 * such that we'll trylock in the spin path, which is a faster option
626 	 * than the blocking slow path.
627 	 */
628 	return retval;
629 }
630 
631 /*
632  * Optimistic spinning.
633  *
634  * We try to spin for acquisition when we find that the lock owner
635  * is currently running on a (different) CPU and while we don't
636  * need to reschedule. The rationale is that if the lock owner is
637  * running, it is likely to release the lock soon.
638  *
639  * The mutex spinners are queued up using MCS lock so that only one
640  * spinner can compete for the mutex. However, if mutex spinning isn't
641  * going to happen, there is no point in going through the lock/unlock
642  * overhead.
643  *
644  * Returns true when the lock was taken, otherwise false, indicating
645  * that we need to jump to the slowpath and sleep.
646  *
647  * The waiter flag is set to true if the spinner is a waiter in the wait
648  * queue. The waiter-spinner will spin on the lock directly and concurrently
649  * with the spinner at the head of the OSQ, if present, until the owner is
650  * changed to itself.
651  */
652 static __always_inline bool
mutex_optimistic_spin(struct mutex * lock,struct ww_acquire_ctx * ww_ctx,struct mutex_waiter * waiter)653 mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
654 		      struct mutex_waiter *waiter)
655 {
656 	if (!waiter) {
657 		/*
658 		 * The purpose of the mutex_can_spin_on_owner() function is
659 		 * to eliminate the overhead of osq_lock() and osq_unlock()
660 		 * in case spinning isn't possible. As a waiter-spinner
661 		 * is not going to take OSQ lock anyway, there is no need
662 		 * to call mutex_can_spin_on_owner().
663 		 */
664 		if (!mutex_can_spin_on_owner(lock))
665 			goto fail;
666 
667 		/*
668 		 * In order to avoid a stampede of mutex spinners trying to
669 		 * acquire the mutex all at once, the spinners need to take a
670 		 * MCS (queued) lock first before spinning on the owner field.
671 		 */
672 		if (!osq_lock(&lock->osq))
673 			goto fail;
674 	}
675 
676 	for (;;) {
677 		struct task_struct *owner;
678 
679 		/* Try to acquire the mutex... */
680 		owner = __mutex_trylock_or_owner(lock);
681 		if (!owner)
682 			break;
683 
684 		/*
685 		 * There's an owner, wait for it to either
686 		 * release the lock or go to sleep.
687 		 */
688 		if (!mutex_spin_on_owner(lock, owner, ww_ctx, waiter))
689 			goto fail_unlock;
690 
691 		/*
692 		 * The cpu_relax() call is a compiler barrier which forces
693 		 * everything in this loop to be re-loaded. We don't need
694 		 * memory barriers as we'll eventually observe the right
695 		 * values at the cost of a few extra spins.
696 		 */
697 		cpu_relax();
698 	}
699 
700 	if (!waiter)
701 		osq_unlock(&lock->osq);
702 
703 	return true;
704 
705 
706 fail_unlock:
707 	if (!waiter)
708 		osq_unlock(&lock->osq);
709 
710 fail:
711 	/*
712 	 * If we fell out of the spin path because of need_resched(),
713 	 * reschedule now, before we try-lock the mutex. This avoids getting
714 	 * scheduled out right after we obtained the mutex.
715 	 */
716 	if (need_resched()) {
717 		/*
718 		 * We _should_ have TASK_RUNNING here, but just in case
719 		 * we do not, make it so, otherwise we might get stuck.
720 		 */
721 		__set_current_state(TASK_RUNNING);
722 		schedule_preempt_disabled();
723 	}
724 
725 	return false;
726 }
727 #else
728 static __always_inline bool
mutex_optimistic_spin(struct mutex * lock,struct ww_acquire_ctx * ww_ctx,struct mutex_waiter * waiter)729 mutex_optimistic_spin(struct mutex *lock, struct ww_acquire_ctx *ww_ctx,
730 		      struct mutex_waiter *waiter)
731 {
732 	return false;
733 }
734 #endif
735 
736 static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip);
737 
738 /**
739  * mutex_unlock - release the mutex
740  * @lock: the mutex to be released
741  *
742  * Unlock a mutex that has been locked by this task previously.
743  *
744  * This function must not be used in interrupt context. Unlocking
745  * of a not locked mutex is not allowed.
746  *
747  * This function is similar to (but not equivalent to) up().
748  */
mutex_unlock(struct mutex * lock)749 void __sched mutex_unlock(struct mutex *lock)
750 {
751 #ifndef CONFIG_DEBUG_LOCK_ALLOC
752 	if (__mutex_unlock_fast(lock))
753 		return;
754 #endif
755 	__mutex_unlock_slowpath(lock, _RET_IP_);
756 }
757 EXPORT_SYMBOL(mutex_unlock);
758 
759 /**
760  * ww_mutex_unlock - release the w/w mutex
761  * @lock: the mutex to be released
762  *
763  * Unlock a mutex that has been locked by this task previously with any of the
764  * ww_mutex_lock* functions (with or without an acquire context). It is
765  * forbidden to release the locks after releasing the acquire context.
766  *
767  * This function must not be used in interrupt context. Unlocking
768  * of a unlocked mutex is not allowed.
769  */
ww_mutex_unlock(struct ww_mutex * lock)770 void __sched ww_mutex_unlock(struct ww_mutex *lock)
771 {
772 	/*
773 	 * The unlocking fastpath is the 0->1 transition from 'locked'
774 	 * into 'unlocked' state:
775 	 */
776 	if (lock->ctx) {
777 #ifdef CONFIG_DEBUG_MUTEXES
778 		DEBUG_LOCKS_WARN_ON(!lock->ctx->acquired);
779 #endif
780 		if (lock->ctx->acquired > 0)
781 			lock->ctx->acquired--;
782 		lock->ctx = NULL;
783 	}
784 
785 	mutex_unlock(&lock->base);
786 }
787 EXPORT_SYMBOL(ww_mutex_unlock);
788 
789 
790 static __always_inline int __sched
__ww_mutex_kill(struct mutex * lock,struct ww_acquire_ctx * ww_ctx)791 __ww_mutex_kill(struct mutex *lock, struct ww_acquire_ctx *ww_ctx)
792 {
793 	if (ww_ctx->acquired > 0) {
794 #ifdef CONFIG_DEBUG_MUTEXES
795 		struct ww_mutex *ww;
796 
797 		ww = container_of(lock, struct ww_mutex, base);
798 		DEBUG_LOCKS_WARN_ON(ww_ctx->contending_lock);
799 		ww_ctx->contending_lock = ww;
800 #endif
801 		return -EDEADLK;
802 	}
803 
804 	return 0;
805 }
806 
807 
808 /*
809  * Check the wound condition for the current lock acquire.
810  *
811  * Wound-Wait: If we're wounded, kill ourself.
812  *
813  * Wait-Die: If we're trying to acquire a lock already held by an older
814  *           context, kill ourselves.
815  *
816  * Since __ww_mutex_add_waiter() orders the wait-list on stamp, we only have to
817  * look at waiters before us in the wait-list.
818  */
819 static inline int __sched
__ww_mutex_check_kill(struct mutex * lock,struct mutex_waiter * waiter,struct ww_acquire_ctx * ctx)820 __ww_mutex_check_kill(struct mutex *lock, struct mutex_waiter *waiter,
821 		      struct ww_acquire_ctx *ctx)
822 {
823 	struct ww_mutex *ww = container_of(lock, struct ww_mutex, base);
824 	struct ww_acquire_ctx *hold_ctx = READ_ONCE(ww->ctx);
825 	struct mutex_waiter *cur;
826 
827 	if (ctx->acquired == 0)
828 		return 0;
829 
830 	if (!ctx->is_wait_die) {
831 		if (ctx->wounded)
832 			return __ww_mutex_kill(lock, ctx);
833 
834 		return 0;
835 	}
836 
837 	if (hold_ctx && __ww_ctx_stamp_after(ctx, hold_ctx))
838 		return __ww_mutex_kill(lock, ctx);
839 
840 	/*
841 	 * If there is a waiter in front of us that has a context, then its
842 	 * stamp is earlier than ours and we must kill ourself.
843 	 */
844 	cur = waiter;
845 	list_for_each_entry_continue_reverse(cur, &lock->wait_list, list) {
846 		if (!cur->ww_ctx)
847 			continue;
848 
849 		return __ww_mutex_kill(lock, ctx);
850 	}
851 
852 	return 0;
853 }
854 
855 /*
856  * Add @waiter to the wait-list, keep the wait-list ordered by stamp, smallest
857  * first. Such that older contexts are preferred to acquire the lock over
858  * younger contexts.
859  *
860  * Waiters without context are interspersed in FIFO order.
861  *
862  * Furthermore, for Wait-Die kill ourself immediately when possible (there are
863  * older contexts already waiting) to avoid unnecessary waiting and for
864  * Wound-Wait ensure we wound the owning context when it is younger.
865  */
866 static inline int __sched
__ww_mutex_add_waiter(struct mutex_waiter * waiter,struct mutex * lock,struct ww_acquire_ctx * ww_ctx)867 __ww_mutex_add_waiter(struct mutex_waiter *waiter,
868 		      struct mutex *lock,
869 		      struct ww_acquire_ctx *ww_ctx)
870 {
871 	struct mutex_waiter *cur;
872 	struct list_head *pos;
873 	bool is_wait_die;
874 
875 	if (!ww_ctx) {
876 		__mutex_add_waiter(lock, waiter, &lock->wait_list);
877 		return 0;
878 	}
879 
880 	is_wait_die = ww_ctx->is_wait_die;
881 
882 	/*
883 	 * Add the waiter before the first waiter with a higher stamp.
884 	 * Waiters without a context are skipped to avoid starving
885 	 * them. Wait-Die waiters may die here. Wound-Wait waiters
886 	 * never die here, but they are sorted in stamp order and
887 	 * may wound the lock holder.
888 	 */
889 	pos = &lock->wait_list;
890 	list_for_each_entry_reverse(cur, &lock->wait_list, list) {
891 		if (!cur->ww_ctx)
892 			continue;
893 
894 		if (__ww_ctx_stamp_after(ww_ctx, cur->ww_ctx)) {
895 			/*
896 			 * Wait-Die: if we find an older context waiting, there
897 			 * is no point in queueing behind it, as we'd have to
898 			 * die the moment it would acquire the lock.
899 			 */
900 			if (is_wait_die) {
901 				int ret = __ww_mutex_kill(lock, ww_ctx);
902 
903 				if (ret)
904 					return ret;
905 			}
906 
907 			break;
908 		}
909 
910 		pos = &cur->list;
911 
912 		/* Wait-Die: ensure younger waiters die. */
913 		__ww_mutex_die(lock, cur, ww_ctx);
914 	}
915 
916 	__mutex_add_waiter(lock, waiter, pos);
917 
918 	/*
919 	 * Wound-Wait: if we're blocking on a mutex owned by a younger context,
920 	 * wound that such that we might proceed.
921 	 */
922 	if (!is_wait_die) {
923 		struct ww_mutex *ww = container_of(lock, struct ww_mutex, base);
924 
925 		/*
926 		 * See ww_mutex_set_context_fastpath(). Orders setting
927 		 * MUTEX_FLAG_WAITERS vs the ww->ctx load,
928 		 * such that either we or the fastpath will wound @ww->ctx.
929 		 */
930 		smp_mb();
931 		__ww_mutex_wound(lock, ww_ctx, ww->ctx);
932 	}
933 
934 	return 0;
935 }
936 
937 /*
938  * Lock a mutex (possibly interruptible), slowpath:
939  */
940 static __always_inline int __sched
__mutex_lock_common(struct mutex * lock,long state,unsigned int subclass,struct lockdep_map * nest_lock,unsigned long ip,struct ww_acquire_ctx * ww_ctx,const bool use_ww_ctx)941 __mutex_lock_common(struct mutex *lock, long state, unsigned int subclass,
942 		    struct lockdep_map *nest_lock, unsigned long ip,
943 		    struct ww_acquire_ctx *ww_ctx, const bool use_ww_ctx)
944 {
945 	struct mutex_waiter waiter;
946 	struct ww_mutex *ww;
947 	int ret;
948 
949 	if (!use_ww_ctx)
950 		ww_ctx = NULL;
951 
952 	might_sleep();
953 
954 #ifdef CONFIG_DEBUG_MUTEXES
955 	DEBUG_LOCKS_WARN_ON(lock->magic != lock);
956 #endif
957 
958 	ww = container_of(lock, struct ww_mutex, base);
959 	if (ww_ctx) {
960 		if (unlikely(ww_ctx == READ_ONCE(ww->ctx)))
961 			return -EALREADY;
962 
963 		/*
964 		 * Reset the wounded flag after a kill. No other process can
965 		 * race and wound us here since they can't have a valid owner
966 		 * pointer if we don't have any locks held.
967 		 */
968 		if (ww_ctx->acquired == 0)
969 			ww_ctx->wounded = 0;
970 	}
971 
972 	preempt_disable();
973 	mutex_acquire_nest(&lock->dep_map, subclass, 0, nest_lock, ip);
974 
975 	if (__mutex_trylock(lock) ||
976 	    mutex_optimistic_spin(lock, ww_ctx, NULL)) {
977 		/* got the lock, yay! */
978 		lock_acquired(&lock->dep_map, ip);
979 		if (ww_ctx)
980 			ww_mutex_set_context_fastpath(ww, ww_ctx);
981 		preempt_enable();
982 		return 0;
983 	}
984 
985 	spin_lock(&lock->wait_lock);
986 	/*
987 	 * After waiting to acquire the wait_lock, try again.
988 	 */
989 	if (__mutex_trylock(lock)) {
990 		if (ww_ctx)
991 			__ww_mutex_check_waiters(lock, ww_ctx);
992 
993 		goto skip_wait;
994 	}
995 
996 	debug_mutex_lock_common(lock, &waiter);
997 
998 	lock_contended(&lock->dep_map, ip);
999 
1000 	if (!use_ww_ctx) {
1001 		/* add waiting tasks to the end of the waitqueue (FIFO): */
1002 		__mutex_add_waiter(lock, &waiter, &lock->wait_list);
1003 
1004 
1005 #ifdef CONFIG_DEBUG_MUTEXES
1006 		waiter.ww_ctx = MUTEX_POISON_WW_CTX;
1007 #endif
1008 	} else {
1009 		/*
1010 		 * Add in stamp order, waking up waiters that must kill
1011 		 * themselves.
1012 		 */
1013 		ret = __ww_mutex_add_waiter(&waiter, lock, ww_ctx);
1014 		if (ret)
1015 			goto err_early_kill;
1016 
1017 		waiter.ww_ctx = ww_ctx;
1018 	}
1019 
1020 	waiter.task = current;
1021 
1022 	trace_android_vh_mutex_wait_start(lock);
1023 	set_current_state(state);
1024 	for (;;) {
1025 		bool first;
1026 
1027 		/*
1028 		 * Once we hold wait_lock, we're serialized against
1029 		 * mutex_unlock() handing the lock off to us, do a trylock
1030 		 * before testing the error conditions to make sure we pick up
1031 		 * the handoff.
1032 		 */
1033 		if (__mutex_trylock(lock))
1034 			goto acquired;
1035 
1036 		/*
1037 		 * Check for signals and kill conditions while holding
1038 		 * wait_lock. This ensures the lock cancellation is ordered
1039 		 * against mutex_unlock() and wake-ups do not go missing.
1040 		 */
1041 		if (signal_pending_state(state, current)) {
1042 			ret = -EINTR;
1043 			goto err;
1044 		}
1045 
1046 		if (ww_ctx) {
1047 			ret = __ww_mutex_check_kill(lock, &waiter, ww_ctx);
1048 			if (ret)
1049 				goto err;
1050 		}
1051 
1052 		spin_unlock(&lock->wait_lock);
1053 		schedule_preempt_disabled();
1054 
1055 		first = __mutex_waiter_is_first(lock, &waiter);
1056 		if (first)
1057 			__mutex_set_flag(lock, MUTEX_FLAG_HANDOFF);
1058 
1059 		set_current_state(state);
1060 		/*
1061 		 * Here we order against unlock; we must either see it change
1062 		 * state back to RUNNING and fall through the next schedule(),
1063 		 * or we must see its unlock and acquire.
1064 		 */
1065 		if (__mutex_trylock(lock) ||
1066 		    (first && mutex_optimistic_spin(lock, ww_ctx, &waiter)))
1067 			break;
1068 
1069 		spin_lock(&lock->wait_lock);
1070 	}
1071 	spin_lock(&lock->wait_lock);
1072 acquired:
1073 	__set_current_state(TASK_RUNNING);
1074 	trace_android_vh_mutex_wait_finish(lock);
1075 
1076 	if (ww_ctx) {
1077 		/*
1078 		 * Wound-Wait; we stole the lock (!first_waiter), check the
1079 		 * waiters as anyone might want to wound us.
1080 		 */
1081 		if (!ww_ctx->is_wait_die &&
1082 		    !__mutex_waiter_is_first(lock, &waiter))
1083 			__ww_mutex_check_waiters(lock, ww_ctx);
1084 	}
1085 
1086 	__mutex_remove_waiter(lock, &waiter);
1087 
1088 	debug_mutex_free_waiter(&waiter);
1089 
1090 skip_wait:
1091 	/* got the lock - cleanup and rejoice! */
1092 	lock_acquired(&lock->dep_map, ip);
1093 
1094 	if (ww_ctx)
1095 		ww_mutex_lock_acquired(ww, ww_ctx);
1096 
1097 	spin_unlock(&lock->wait_lock);
1098 	preempt_enable();
1099 	return 0;
1100 
1101 err:
1102 	__set_current_state(TASK_RUNNING);
1103 	trace_android_vh_mutex_wait_finish(lock);
1104 	__mutex_remove_waiter(lock, &waiter);
1105 err_early_kill:
1106 	spin_unlock(&lock->wait_lock);
1107 	debug_mutex_free_waiter(&waiter);
1108 	mutex_release(&lock->dep_map, ip);
1109 	preempt_enable();
1110 	return ret;
1111 }
1112 
1113 static int __sched
__mutex_lock(struct mutex * lock,long state,unsigned int subclass,struct lockdep_map * nest_lock,unsigned long ip)1114 __mutex_lock(struct mutex *lock, long state, unsigned int subclass,
1115 	     struct lockdep_map *nest_lock, unsigned long ip)
1116 {
1117 	return __mutex_lock_common(lock, state, subclass, nest_lock, ip, NULL, false);
1118 }
1119 
1120 static int __sched
__ww_mutex_lock(struct mutex * lock,long state,unsigned int subclass,struct lockdep_map * nest_lock,unsigned long ip,struct ww_acquire_ctx * ww_ctx)1121 __ww_mutex_lock(struct mutex *lock, long state, unsigned int subclass,
1122 		struct lockdep_map *nest_lock, unsigned long ip,
1123 		struct ww_acquire_ctx *ww_ctx)
1124 {
1125 	return __mutex_lock_common(lock, state, subclass, nest_lock, ip, ww_ctx, true);
1126 }
1127 
1128 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1129 void __sched
mutex_lock_nested(struct mutex * lock,unsigned int subclass)1130 mutex_lock_nested(struct mutex *lock, unsigned int subclass)
1131 {
1132 	__mutex_lock(lock, TASK_UNINTERRUPTIBLE, subclass, NULL, _RET_IP_);
1133 }
1134 
1135 EXPORT_SYMBOL_GPL(mutex_lock_nested);
1136 
1137 void __sched
_mutex_lock_nest_lock(struct mutex * lock,struct lockdep_map * nest)1138 _mutex_lock_nest_lock(struct mutex *lock, struct lockdep_map *nest)
1139 {
1140 	__mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, nest, _RET_IP_);
1141 }
1142 EXPORT_SYMBOL_GPL(_mutex_lock_nest_lock);
1143 
1144 int __sched
mutex_lock_killable_nested(struct mutex * lock,unsigned int subclass)1145 mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass)
1146 {
1147 	return __mutex_lock(lock, TASK_KILLABLE, subclass, NULL, _RET_IP_);
1148 }
1149 EXPORT_SYMBOL_GPL(mutex_lock_killable_nested);
1150 
1151 int __sched
mutex_lock_interruptible_nested(struct mutex * lock,unsigned int subclass)1152 mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass)
1153 {
1154 	return __mutex_lock(lock, TASK_INTERRUPTIBLE, subclass, NULL, _RET_IP_);
1155 }
1156 EXPORT_SYMBOL_GPL(mutex_lock_interruptible_nested);
1157 
1158 void __sched
mutex_lock_io_nested(struct mutex * lock,unsigned int subclass)1159 mutex_lock_io_nested(struct mutex *lock, unsigned int subclass)
1160 {
1161 	int token;
1162 
1163 	might_sleep();
1164 
1165 	token = io_schedule_prepare();
1166 	__mutex_lock_common(lock, TASK_UNINTERRUPTIBLE,
1167 			    subclass, NULL, _RET_IP_, NULL, 0);
1168 	io_schedule_finish(token);
1169 }
1170 EXPORT_SYMBOL_GPL(mutex_lock_io_nested);
1171 
1172 static inline int
ww_mutex_deadlock_injection(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1173 ww_mutex_deadlock_injection(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1174 {
1175 #ifdef CONFIG_DEBUG_WW_MUTEX_SLOWPATH
1176 	unsigned tmp;
1177 
1178 	if (ctx->deadlock_inject_countdown-- == 0) {
1179 		tmp = ctx->deadlock_inject_interval;
1180 		if (tmp > UINT_MAX/4)
1181 			tmp = UINT_MAX;
1182 		else
1183 			tmp = tmp*2 + tmp + tmp/2;
1184 
1185 		ctx->deadlock_inject_interval = tmp;
1186 		ctx->deadlock_inject_countdown = tmp;
1187 		ctx->contending_lock = lock;
1188 
1189 		ww_mutex_unlock(lock);
1190 
1191 		return -EDEADLK;
1192 	}
1193 #endif
1194 
1195 	return 0;
1196 }
1197 
1198 int __sched
ww_mutex_lock(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1199 ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1200 {
1201 	int ret;
1202 
1203 	might_sleep();
1204 	ret =  __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE,
1205 			       0, ctx ? &ctx->dep_map : NULL, _RET_IP_,
1206 			       ctx);
1207 	if (!ret && ctx && ctx->acquired > 1)
1208 		return ww_mutex_deadlock_injection(lock, ctx);
1209 
1210 	return ret;
1211 }
1212 EXPORT_SYMBOL_GPL(ww_mutex_lock);
1213 
1214 int __sched
ww_mutex_lock_interruptible(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1215 ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1216 {
1217 	int ret;
1218 
1219 	might_sleep();
1220 	ret = __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE,
1221 			      0, ctx ? &ctx->dep_map : NULL, _RET_IP_,
1222 			      ctx);
1223 
1224 	if (!ret && ctx && ctx->acquired > 1)
1225 		return ww_mutex_deadlock_injection(lock, ctx);
1226 
1227 	return ret;
1228 }
1229 EXPORT_SYMBOL_GPL(ww_mutex_lock_interruptible);
1230 
1231 #endif
1232 
1233 /*
1234  * Release the lock, slowpath:
1235  */
__mutex_unlock_slowpath(struct mutex * lock,unsigned long ip)1236 static noinline void __sched __mutex_unlock_slowpath(struct mutex *lock, unsigned long ip)
1237 {
1238 	struct task_struct *next = NULL;
1239 	DEFINE_WAKE_Q(wake_q);
1240 	unsigned long owner;
1241 
1242 	mutex_release(&lock->dep_map, ip);
1243 
1244 	/*
1245 	 * Release the lock before (potentially) taking the spinlock such that
1246 	 * other contenders can get on with things ASAP.
1247 	 *
1248 	 * Except when HANDOFF, in that case we must not clear the owner field,
1249 	 * but instead set it to the top waiter.
1250 	 */
1251 	owner = atomic_long_read(&lock->owner);
1252 	for (;;) {
1253 		unsigned long old;
1254 
1255 #ifdef CONFIG_DEBUG_MUTEXES
1256 		DEBUG_LOCKS_WARN_ON(__owner_task(owner) != current);
1257 		DEBUG_LOCKS_WARN_ON(owner & MUTEX_FLAG_PICKUP);
1258 #endif
1259 
1260 		if (owner & MUTEX_FLAG_HANDOFF)
1261 			break;
1262 
1263 		old = atomic_long_cmpxchg_release(&lock->owner, owner,
1264 						  __owner_flags(owner));
1265 		if (old == owner) {
1266 			if (owner & MUTEX_FLAG_WAITERS)
1267 				break;
1268 
1269 			return;
1270 		}
1271 
1272 		owner = old;
1273 	}
1274 
1275 	spin_lock(&lock->wait_lock);
1276 	debug_mutex_unlock(lock);
1277 	if (!list_empty(&lock->wait_list)) {
1278 		/* get the first entry from the wait-list: */
1279 		struct mutex_waiter *waiter =
1280 			list_first_entry(&lock->wait_list,
1281 					 struct mutex_waiter, list);
1282 
1283 		next = waiter->task;
1284 
1285 		debug_mutex_wake_waiter(lock, waiter);
1286 		wake_q_add(&wake_q, next);
1287 	}
1288 
1289 	if (owner & MUTEX_FLAG_HANDOFF)
1290 		__mutex_handoff(lock, next);
1291 
1292 	trace_android_vh_mutex_unlock_slowpath(lock);
1293 	spin_unlock(&lock->wait_lock);
1294 
1295 	wake_up_q(&wake_q);
1296 }
1297 
1298 #ifndef CONFIG_DEBUG_LOCK_ALLOC
1299 /*
1300  * Here come the less common (and hence less performance-critical) APIs:
1301  * mutex_lock_interruptible() and mutex_trylock().
1302  */
1303 static noinline int __sched
1304 __mutex_lock_killable_slowpath(struct mutex *lock);
1305 
1306 static noinline int __sched
1307 __mutex_lock_interruptible_slowpath(struct mutex *lock);
1308 
1309 /**
1310  * mutex_lock_interruptible() - Acquire the mutex, interruptible by signals.
1311  * @lock: The mutex to be acquired.
1312  *
1313  * Lock the mutex like mutex_lock().  If a signal is delivered while the
1314  * process is sleeping, this function will return without acquiring the
1315  * mutex.
1316  *
1317  * Context: Process context.
1318  * Return: 0 if the lock was successfully acquired or %-EINTR if a
1319  * signal arrived.
1320  */
mutex_lock_interruptible(struct mutex * lock)1321 int __sched mutex_lock_interruptible(struct mutex *lock)
1322 {
1323 	might_sleep();
1324 
1325 	if (__mutex_trylock_fast(lock))
1326 		return 0;
1327 
1328 	return __mutex_lock_interruptible_slowpath(lock);
1329 }
1330 
1331 EXPORT_SYMBOL(mutex_lock_interruptible);
1332 
1333 /**
1334  * mutex_lock_killable() - Acquire the mutex, interruptible by fatal signals.
1335  * @lock: The mutex to be acquired.
1336  *
1337  * Lock the mutex like mutex_lock().  If a signal which will be fatal to
1338  * the current process is delivered while the process is sleeping, this
1339  * function will return without acquiring the mutex.
1340  *
1341  * Context: Process context.
1342  * Return: 0 if the lock was successfully acquired or %-EINTR if a
1343  * fatal signal arrived.
1344  */
mutex_lock_killable(struct mutex * lock)1345 int __sched mutex_lock_killable(struct mutex *lock)
1346 {
1347 	might_sleep();
1348 
1349 	if (__mutex_trylock_fast(lock))
1350 		return 0;
1351 
1352 	return __mutex_lock_killable_slowpath(lock);
1353 }
1354 EXPORT_SYMBOL(mutex_lock_killable);
1355 
1356 /**
1357  * mutex_lock_io() - Acquire the mutex and mark the process as waiting for I/O
1358  * @lock: The mutex to be acquired.
1359  *
1360  * Lock the mutex like mutex_lock().  While the task is waiting for this
1361  * mutex, it will be accounted as being in the IO wait state by the
1362  * scheduler.
1363  *
1364  * Context: Process context.
1365  */
mutex_lock_io(struct mutex * lock)1366 void __sched mutex_lock_io(struct mutex *lock)
1367 {
1368 	int token;
1369 
1370 	token = io_schedule_prepare();
1371 	mutex_lock(lock);
1372 	io_schedule_finish(token);
1373 }
1374 EXPORT_SYMBOL_GPL(mutex_lock_io);
1375 
1376 static noinline void __sched
__mutex_lock_slowpath(struct mutex * lock)1377 __mutex_lock_slowpath(struct mutex *lock)
1378 {
1379 	__mutex_lock(lock, TASK_UNINTERRUPTIBLE, 0, NULL, _RET_IP_);
1380 }
1381 
1382 static noinline int __sched
__mutex_lock_killable_slowpath(struct mutex * lock)1383 __mutex_lock_killable_slowpath(struct mutex *lock)
1384 {
1385 	return __mutex_lock(lock, TASK_KILLABLE, 0, NULL, _RET_IP_);
1386 }
1387 
1388 static noinline int __sched
__mutex_lock_interruptible_slowpath(struct mutex * lock)1389 __mutex_lock_interruptible_slowpath(struct mutex *lock)
1390 {
1391 	return __mutex_lock(lock, TASK_INTERRUPTIBLE, 0, NULL, _RET_IP_);
1392 }
1393 
1394 static noinline int __sched
__ww_mutex_lock_slowpath(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1395 __ww_mutex_lock_slowpath(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1396 {
1397 	return __ww_mutex_lock(&lock->base, TASK_UNINTERRUPTIBLE, 0, NULL,
1398 			       _RET_IP_, ctx);
1399 }
1400 
1401 static noinline int __sched
__ww_mutex_lock_interruptible_slowpath(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1402 __ww_mutex_lock_interruptible_slowpath(struct ww_mutex *lock,
1403 					    struct ww_acquire_ctx *ctx)
1404 {
1405 	return __ww_mutex_lock(&lock->base, TASK_INTERRUPTIBLE, 0, NULL,
1406 			       _RET_IP_, ctx);
1407 }
1408 
1409 #endif
1410 
1411 /**
1412  * mutex_trylock - try to acquire the mutex, without waiting
1413  * @lock: the mutex to be acquired
1414  *
1415  * Try to acquire the mutex atomically. Returns 1 if the mutex
1416  * has been acquired successfully, and 0 on contention.
1417  *
1418  * NOTE: this function follows the spin_trylock() convention, so
1419  * it is negated from the down_trylock() return values! Be careful
1420  * about this when converting semaphore users to mutexes.
1421  *
1422  * This function must not be used in interrupt context. The
1423  * mutex must be released by the same task that acquired it.
1424  */
mutex_trylock(struct mutex * lock)1425 int __sched mutex_trylock(struct mutex *lock)
1426 {
1427 	bool locked;
1428 
1429 #ifdef CONFIG_DEBUG_MUTEXES
1430 	DEBUG_LOCKS_WARN_ON(lock->magic != lock);
1431 #endif
1432 
1433 	locked = __mutex_trylock(lock);
1434 	if (locked)
1435 		mutex_acquire(&lock->dep_map, 0, 1, _RET_IP_);
1436 
1437 	return locked;
1438 }
1439 EXPORT_SYMBOL(mutex_trylock);
1440 
1441 #ifndef CONFIG_DEBUG_LOCK_ALLOC
1442 int __sched
ww_mutex_lock(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1443 ww_mutex_lock(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1444 {
1445 	might_sleep();
1446 
1447 	if (__mutex_trylock_fast(&lock->base)) {
1448 		if (ctx)
1449 			ww_mutex_set_context_fastpath(lock, ctx);
1450 		return 0;
1451 	}
1452 
1453 	return __ww_mutex_lock_slowpath(lock, ctx);
1454 }
1455 EXPORT_SYMBOL(ww_mutex_lock);
1456 
1457 int __sched
ww_mutex_lock_interruptible(struct ww_mutex * lock,struct ww_acquire_ctx * ctx)1458 ww_mutex_lock_interruptible(struct ww_mutex *lock, struct ww_acquire_ctx *ctx)
1459 {
1460 	might_sleep();
1461 
1462 	if (__mutex_trylock_fast(&lock->base)) {
1463 		if (ctx)
1464 			ww_mutex_set_context_fastpath(lock, ctx);
1465 		return 0;
1466 	}
1467 
1468 	return __ww_mutex_lock_interruptible_slowpath(lock, ctx);
1469 }
1470 EXPORT_SYMBOL(ww_mutex_lock_interruptible);
1471 
1472 #endif
1473 
1474 /**
1475  * atomic_dec_and_mutex_lock - return holding mutex if we dec to 0
1476  * @cnt: the atomic which we are to dec
1477  * @lock: the mutex to return holding if we dec to 0
1478  *
1479  * return true and hold lock if we dec to 0, return false otherwise
1480  */
atomic_dec_and_mutex_lock(atomic_t * cnt,struct mutex * lock)1481 int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock)
1482 {
1483 	/* dec if we can't possibly hit 0 */
1484 	if (atomic_add_unless(cnt, -1, 1))
1485 		return 0;
1486 	/* we might hit 0, so take the lock */
1487 	mutex_lock(lock);
1488 	if (!atomic_dec_and_test(cnt)) {
1489 		/* when we actually did the dec, we didn't hit 0 */
1490 		mutex_unlock(lock);
1491 		return 0;
1492 	}
1493 	/* we hit 0, and we hold the lock */
1494 	return 1;
1495 }
1496 EXPORT_SYMBOL(atomic_dec_and_mutex_lock);
1497