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