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