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