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