1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * RT-Mutexes: simple blocking mutual exclusion locks with PI support
4  *
5  * started by Ingo Molnar and Thomas Gleixner.
6  *
7  *  Copyright (C) 2004-2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
8  *  Copyright (C) 2005-2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
9  *  Copyright (C) 2005 Kihon Technologies Inc., Steven Rostedt
10  *  Copyright (C) 2006 Esben Nielsen
11  * Adaptive Spinlocks:
12  *  Copyright (C) 2008 Novell, Inc., Gregory Haskins, Sven Dietrich,
13  *				     and Peter Morreale,
14  * Adaptive Spinlocks simplification:
15  *  Copyright (C) 2008 Red Hat, Inc., Steven Rostedt <srostedt@redhat.com>
16  *
17  *  See Documentation/locking/rt-mutex-design.rst for details.
18  */
19 #include <linux/sched.h>
20 #include <linux/sched/debug.h>
21 #include <linux/sched/deadline.h>
22 #include <linux/sched/signal.h>
23 #include <linux/sched/rt.h>
24 #include <linux/sched/wake_q.h>
25 #include <linux/ww_mutex.h>
26 
27 #include <trace/events/lock.h>
28 #include <trace/hooks/dtask.h>
29 
30 #include "rtmutex_common.h"
31 
32 #ifndef WW_RT
33 # define build_ww_mutex()	(false)
34 # define ww_container_of(rtm)	NULL
35 
__ww_mutex_add_waiter(struct rt_mutex_waiter * waiter,struct rt_mutex * lock,struct ww_acquire_ctx * ww_ctx,struct wake_q_head * wake_q)36 static inline int __ww_mutex_add_waiter(struct rt_mutex_waiter *waiter,
37 					struct rt_mutex *lock,
38 					struct ww_acquire_ctx *ww_ctx,
39 					struct wake_q_head *wake_q)
40 {
41 	return 0;
42 }
43 
__ww_mutex_check_waiters(struct rt_mutex * lock,struct ww_acquire_ctx * ww_ctx,struct wake_q_head * wake_q)44 static inline void __ww_mutex_check_waiters(struct rt_mutex *lock,
45 					    struct ww_acquire_ctx *ww_ctx,
46 					    struct wake_q_head *wake_q)
47 {
48 }
49 
ww_mutex_lock_acquired(struct ww_mutex * lock,struct ww_acquire_ctx * ww_ctx)50 static inline void ww_mutex_lock_acquired(struct ww_mutex *lock,
51 					  struct ww_acquire_ctx *ww_ctx)
52 {
53 }
54 
__ww_mutex_check_kill(struct rt_mutex * lock,struct rt_mutex_waiter * waiter,struct ww_acquire_ctx * ww_ctx)55 static inline int __ww_mutex_check_kill(struct rt_mutex *lock,
56 					struct rt_mutex_waiter *waiter,
57 					struct ww_acquire_ctx *ww_ctx)
58 {
59 	return 0;
60 }
61 
62 #else
63 # define build_ww_mutex()	(true)
64 # define ww_container_of(rtm)	container_of(rtm, struct ww_mutex, base)
65 # include "ww_mutex.h"
66 #endif
67 
68 /*
69  * lock->owner state tracking:
70  *
71  * lock->owner holds the task_struct pointer of the owner. Bit 0
72  * is used to keep track of the "lock has waiters" state.
73  *
74  * owner	bit0
75  * NULL		0	lock is free (fast acquire possible)
76  * NULL		1	lock is free and has waiters and the top waiter
77  *				is going to take the lock*
78  * taskpointer	0	lock is held (fast release possible)
79  * taskpointer	1	lock is held and has waiters**
80  *
81  * The fast atomic compare exchange based acquire and release is only
82  * possible when bit 0 of lock->owner is 0.
83  *
84  * (*) It also can be a transitional state when grabbing the lock
85  * with ->wait_lock is held. To prevent any fast path cmpxchg to the lock,
86  * we need to set the bit0 before looking at the lock, and the owner may be
87  * NULL in this small time, hence this can be a transitional state.
88  *
89  * (**) There is a small time when bit 0 is set but there are no
90  * waiters. This can happen when grabbing the lock in the slow path.
91  * To prevent a cmpxchg of the owner releasing the lock, we need to
92  * set this bit before looking at the lock.
93  */
94 
95 static __always_inline struct task_struct *
rt_mutex_owner_encode(struct rt_mutex_base * lock,struct task_struct * owner)96 rt_mutex_owner_encode(struct rt_mutex_base *lock, struct task_struct *owner)
97 {
98 	unsigned long val = (unsigned long)owner;
99 
100 	if (rt_mutex_has_waiters(lock))
101 		val |= RT_MUTEX_HAS_WAITERS;
102 
103 	return (struct task_struct *)val;
104 }
105 
106 static __always_inline void
rt_mutex_set_owner(struct rt_mutex_base * lock,struct task_struct * owner)107 rt_mutex_set_owner(struct rt_mutex_base *lock, struct task_struct *owner)
108 {
109 	/*
110 	 * lock->wait_lock is held but explicit acquire semantics are needed
111 	 * for a new lock owner so WRITE_ONCE is insufficient.
112 	 */
113 	xchg_acquire(&lock->owner, rt_mutex_owner_encode(lock, owner));
114 }
115 
rt_mutex_clear_owner(struct rt_mutex_base * lock)116 static __always_inline void rt_mutex_clear_owner(struct rt_mutex_base *lock)
117 {
118 	/* lock->wait_lock is held so the unlock provides release semantics. */
119 	WRITE_ONCE(lock->owner, rt_mutex_owner_encode(lock, NULL));
120 }
121 
clear_rt_mutex_waiters(struct rt_mutex_base * lock)122 static __always_inline void clear_rt_mutex_waiters(struct rt_mutex_base *lock)
123 {
124 	lock->owner = (struct task_struct *)
125 			((unsigned long)lock->owner & ~RT_MUTEX_HAS_WAITERS);
126 }
127 
128 static __always_inline void
fixup_rt_mutex_waiters(struct rt_mutex_base * lock,bool acquire_lock)129 fixup_rt_mutex_waiters(struct rt_mutex_base *lock, bool acquire_lock)
130 {
131 	unsigned long owner, *p = (unsigned long *) &lock->owner;
132 
133 	if (rt_mutex_has_waiters(lock))
134 		return;
135 
136 	/*
137 	 * The rbtree has no waiters enqueued, now make sure that the
138 	 * lock->owner still has the waiters bit set, otherwise the
139 	 * following can happen:
140 	 *
141 	 * CPU 0	CPU 1		CPU2
142 	 * l->owner=T1
143 	 *		rt_mutex_lock(l)
144 	 *		lock(l->lock)
145 	 *		l->owner = T1 | HAS_WAITERS;
146 	 *		enqueue(T2)
147 	 *		boost()
148 	 *		  unlock(l->lock)
149 	 *		block()
150 	 *
151 	 *				rt_mutex_lock(l)
152 	 *				lock(l->lock)
153 	 *				l->owner = T1 | HAS_WAITERS;
154 	 *				enqueue(T3)
155 	 *				boost()
156 	 *				  unlock(l->lock)
157 	 *				block()
158 	 *		signal(->T2)	signal(->T3)
159 	 *		lock(l->lock)
160 	 *		dequeue(T2)
161 	 *		deboost()
162 	 *		  unlock(l->lock)
163 	 *				lock(l->lock)
164 	 *				dequeue(T3)
165 	 *				 ==> wait list is empty
166 	 *				deboost()
167 	 *				 unlock(l->lock)
168 	 *		lock(l->lock)
169 	 *		fixup_rt_mutex_waiters()
170 	 *		  if (wait_list_empty(l) {
171 	 *		    l->owner = owner
172 	 *		    owner = l->owner & ~HAS_WAITERS;
173 	 *		      ==> l->owner = T1
174 	 *		  }
175 	 *				lock(l->lock)
176 	 * rt_mutex_unlock(l)		fixup_rt_mutex_waiters()
177 	 *				  if (wait_list_empty(l) {
178 	 *				    owner = l->owner & ~HAS_WAITERS;
179 	 * cmpxchg(l->owner, T1, NULL)
180 	 *  ===> Success (l->owner = NULL)
181 	 *
182 	 *				    l->owner = owner
183 	 *				      ==> l->owner = T1
184 	 *				  }
185 	 *
186 	 * With the check for the waiter bit in place T3 on CPU2 will not
187 	 * overwrite. All tasks fiddling with the waiters bit are
188 	 * serialized by l->lock, so nothing else can modify the waiters
189 	 * bit. If the bit is set then nothing can change l->owner either
190 	 * so the simple RMW is safe. The cmpxchg() will simply fail if it
191 	 * happens in the middle of the RMW because the waiters bit is
192 	 * still set.
193 	 */
194 	owner = READ_ONCE(*p);
195 	if (owner & RT_MUTEX_HAS_WAITERS) {
196 		/*
197 		 * See rt_mutex_set_owner() and rt_mutex_clear_owner() on
198 		 * why xchg_acquire() is used for updating owner for
199 		 * locking and WRITE_ONCE() for unlocking.
200 		 *
201 		 * WRITE_ONCE() would work for the acquire case too, but
202 		 * in case that the lock acquisition failed it might
203 		 * force other lockers into the slow path unnecessarily.
204 		 */
205 		if (acquire_lock)
206 			xchg_acquire(p, owner & ~RT_MUTEX_HAS_WAITERS);
207 		else
208 			WRITE_ONCE(*p, owner & ~RT_MUTEX_HAS_WAITERS);
209 	}
210 }
211 
212 /*
213  * We can speed up the acquire/release, if there's no debugging state to be
214  * set up.
215  */
216 #ifndef CONFIG_DEBUG_RT_MUTEXES
rt_mutex_cmpxchg_acquire(struct rt_mutex_base * lock,struct task_struct * old,struct task_struct * new)217 static __always_inline bool rt_mutex_cmpxchg_acquire(struct rt_mutex_base *lock,
218 						     struct task_struct *old,
219 						     struct task_struct *new)
220 {
221 	return try_cmpxchg_acquire(&lock->owner, &old, new);
222 }
223 
rt_mutex_try_acquire(struct rt_mutex_base * lock)224 static __always_inline bool rt_mutex_try_acquire(struct rt_mutex_base *lock)
225 {
226 	return rt_mutex_cmpxchg_acquire(lock, NULL, current);
227 }
228 
rt_mutex_cmpxchg_release(struct rt_mutex_base * lock,struct task_struct * old,struct task_struct * new)229 static __always_inline bool rt_mutex_cmpxchg_release(struct rt_mutex_base *lock,
230 						     struct task_struct *old,
231 						     struct task_struct *new)
232 {
233 	return try_cmpxchg_release(&lock->owner, &old, new);
234 }
235 
236 /*
237  * Callers must hold the ->wait_lock -- which is the whole purpose as we force
238  * all future threads that attempt to [Rmw] the lock to the slowpath. As such
239  * relaxed semantics suffice.
240  */
mark_rt_mutex_waiters(struct rt_mutex_base * lock)241 static __always_inline void mark_rt_mutex_waiters(struct rt_mutex_base *lock)
242 {
243 	unsigned long *p = (unsigned long *) &lock->owner;
244 	unsigned long owner, new;
245 
246 	owner = READ_ONCE(*p);
247 	do {
248 		new = owner | RT_MUTEX_HAS_WAITERS;
249 	} while (!try_cmpxchg_relaxed(p, &owner, new));
250 
251 	/*
252 	 * The cmpxchg loop above is relaxed to avoid back-to-back ACQUIRE
253 	 * operations in the event of contention. Ensure the successful
254 	 * cmpxchg is visible.
255 	 */
256 	smp_mb__after_atomic();
257 }
258 
259 /*
260  * Safe fastpath aware unlock:
261  * 1) Clear the waiters bit
262  * 2) Drop lock->wait_lock
263  * 3) Try to unlock the lock with cmpxchg
264  */
unlock_rt_mutex_safe(struct rt_mutex_base * lock,unsigned long flags)265 static __always_inline bool unlock_rt_mutex_safe(struct rt_mutex_base *lock,
266 						 unsigned long flags)
267 	__releases(lock->wait_lock)
268 {
269 	struct task_struct *owner = rt_mutex_owner(lock);
270 
271 	clear_rt_mutex_waiters(lock);
272 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
273 	/*
274 	 * If a new waiter comes in between the unlock and the cmpxchg
275 	 * we have two situations:
276 	 *
277 	 * unlock(wait_lock);
278 	 *					lock(wait_lock);
279 	 * cmpxchg(p, owner, 0) == owner
280 	 *					mark_rt_mutex_waiters(lock);
281 	 *					acquire(lock);
282 	 * or:
283 	 *
284 	 * unlock(wait_lock);
285 	 *					lock(wait_lock);
286 	 *					mark_rt_mutex_waiters(lock);
287 	 *
288 	 * cmpxchg(p, owner, 0) != owner
289 	 *					enqueue_waiter();
290 	 *					unlock(wait_lock);
291 	 * lock(wait_lock);
292 	 * wake waiter();
293 	 * unlock(wait_lock);
294 	 *					lock(wait_lock);
295 	 *					acquire(lock);
296 	 */
297 	return rt_mutex_cmpxchg_release(lock, owner, NULL);
298 }
299 
300 #else
rt_mutex_cmpxchg_acquire(struct rt_mutex_base * lock,struct task_struct * old,struct task_struct * new)301 static __always_inline bool rt_mutex_cmpxchg_acquire(struct rt_mutex_base *lock,
302 						     struct task_struct *old,
303 						     struct task_struct *new)
304 {
305 	return false;
306 
307 }
308 
309 static int __sched rt_mutex_slowtrylock(struct rt_mutex_base *lock);
310 
rt_mutex_try_acquire(struct rt_mutex_base * lock)311 static __always_inline bool rt_mutex_try_acquire(struct rt_mutex_base *lock)
312 {
313 	/*
314 	 * With debug enabled rt_mutex_cmpxchg trylock() will always fail.
315 	 *
316 	 * Avoid unconditionally taking the slow path by using
317 	 * rt_mutex_slow_trylock() which is covered by the debug code and can
318 	 * acquire a non-contended rtmutex.
319 	 */
320 	return rt_mutex_slowtrylock(lock);
321 }
322 
rt_mutex_cmpxchg_release(struct rt_mutex_base * lock,struct task_struct * old,struct task_struct * new)323 static __always_inline bool rt_mutex_cmpxchg_release(struct rt_mutex_base *lock,
324 						     struct task_struct *old,
325 						     struct task_struct *new)
326 {
327 	return false;
328 }
329 
mark_rt_mutex_waiters(struct rt_mutex_base * lock)330 static __always_inline void mark_rt_mutex_waiters(struct rt_mutex_base *lock)
331 {
332 	lock->owner = (struct task_struct *)
333 			((unsigned long)lock->owner | RT_MUTEX_HAS_WAITERS);
334 }
335 
336 /*
337  * Simple slow path only version: lock->owner is protected by lock->wait_lock.
338  */
unlock_rt_mutex_safe(struct rt_mutex_base * lock,unsigned long flags)339 static __always_inline bool unlock_rt_mutex_safe(struct rt_mutex_base *lock,
340 						 unsigned long flags)
341 	__releases(lock->wait_lock)
342 {
343 	lock->owner = NULL;
344 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
345 	return true;
346 }
347 #endif
348 
__waiter_prio(struct task_struct * task)349 static __always_inline int __waiter_prio(struct task_struct *task)
350 {
351 	return task->prio;
352 }
353 
354 /*
355  * Update the waiter->tree copy of the sort keys.
356  */
357 static __always_inline void
waiter_update_prio(struct rt_mutex_waiter * waiter,struct task_struct * task)358 waiter_update_prio(struct rt_mutex_waiter *waiter, struct task_struct *task)
359 {
360 	lockdep_assert_held(&waiter->lock->wait_lock);
361 	lockdep_assert(RB_EMPTY_NODE(&waiter->tree.entry));
362 
363 	waiter->tree.prio = __waiter_prio(task);
364 	waiter->tree.deadline = task->dl.deadline;
365 }
366 
367 /*
368  * Update the waiter->pi_tree copy of the sort keys (from the tree copy).
369  */
370 static __always_inline void
waiter_clone_prio(struct rt_mutex_waiter * waiter,struct task_struct * task)371 waiter_clone_prio(struct rt_mutex_waiter *waiter, struct task_struct *task)
372 {
373 	lockdep_assert_held(&waiter->lock->wait_lock);
374 	lockdep_assert_held(&task->pi_lock);
375 	lockdep_assert(RB_EMPTY_NODE(&waiter->pi_tree.entry));
376 
377 	waiter->pi_tree.prio = waiter->tree.prio;
378 	waiter->pi_tree.deadline = waiter->tree.deadline;
379 }
380 
381 /*
382  * Only use with rt_waiter_node_{less,equal}()
383  */
384 #define task_to_waiter_node(p)	\
385 	&(struct rt_waiter_node){ .prio = __waiter_prio(p), .deadline = (p)->dl.deadline }
386 #define task_to_waiter(p)	\
387 	&(struct rt_mutex_waiter){ .tree = *task_to_waiter_node(p) }
388 
rt_waiter_node_less(struct rt_waiter_node * left,struct rt_waiter_node * right)389 static __always_inline int rt_waiter_node_less(struct rt_waiter_node *left,
390 					       struct rt_waiter_node *right)
391 {
392 	if (left->prio < right->prio)
393 		return 1;
394 
395 	/*
396 	 * If both waiters have dl_prio(), we check the deadlines of the
397 	 * associated tasks.
398 	 * If left waiter has a dl_prio(), and we didn't return 1 above,
399 	 * then right waiter has a dl_prio() too.
400 	 */
401 	if (dl_prio(left->prio))
402 		return dl_time_before(left->deadline, right->deadline);
403 
404 	return 0;
405 }
406 
rt_waiter_node_equal(struct rt_waiter_node * left,struct rt_waiter_node * right)407 static __always_inline int rt_waiter_node_equal(struct rt_waiter_node *left,
408 						 struct rt_waiter_node *right)
409 {
410 	if (left->prio != right->prio)
411 		return 0;
412 
413 	/*
414 	 * If both waiters have dl_prio(), we check the deadlines of the
415 	 * associated tasks.
416 	 * If left waiter has a dl_prio(), and we didn't return 0 above,
417 	 * then right waiter has a dl_prio() too.
418 	 */
419 	if (dl_prio(left->prio))
420 		return left->deadline == right->deadline;
421 
422 	return 1;
423 }
424 
rt_mutex_steal(struct rt_mutex_waiter * waiter,struct rt_mutex_waiter * top_waiter)425 static inline bool rt_mutex_steal(struct rt_mutex_waiter *waiter,
426 				  struct rt_mutex_waiter *top_waiter)
427 {
428 	if (rt_waiter_node_less(&waiter->tree, &top_waiter->tree))
429 		return true;
430 
431 #ifdef RT_MUTEX_BUILD_SPINLOCKS
432 	/*
433 	 * Note that RT tasks are excluded from same priority (lateral)
434 	 * steals to prevent the introduction of an unbounded latency.
435 	 */
436 	if (rt_or_dl_prio(waiter->tree.prio))
437 		return false;
438 
439 	return rt_waiter_node_equal(&waiter->tree, &top_waiter->tree);
440 #else
441 	return false;
442 #endif
443 }
444 
445 #define __node_2_waiter(node) \
446 	rb_entry((node), struct rt_mutex_waiter, tree.entry)
447 
__waiter_less(struct rb_node * a,const struct rb_node * b)448 static __always_inline bool __waiter_less(struct rb_node *a, const struct rb_node *b)
449 {
450 	struct rt_mutex_waiter *aw = __node_2_waiter(a);
451 	struct rt_mutex_waiter *bw = __node_2_waiter(b);
452 
453 	if (rt_waiter_node_less(&aw->tree, &bw->tree))
454 		return 1;
455 
456 	if (!build_ww_mutex())
457 		return 0;
458 
459 	if (rt_waiter_node_less(&bw->tree, &aw->tree))
460 		return 0;
461 
462 	/* NOTE: relies on waiter->ww_ctx being set before insertion */
463 	if (aw->ww_ctx) {
464 		if (!bw->ww_ctx)
465 			return 1;
466 
467 		return (signed long)(aw->ww_ctx->stamp -
468 				     bw->ww_ctx->stamp) < 0;
469 	}
470 
471 	return 0;
472 }
473 
474 static __always_inline void
rt_mutex_enqueue(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter)475 rt_mutex_enqueue(struct rt_mutex_base *lock, struct rt_mutex_waiter *waiter)
476 {
477 	lockdep_assert_held(&lock->wait_lock);
478 
479 	rb_add_cached(&waiter->tree.entry, &lock->waiters, __waiter_less);
480 }
481 
482 static __always_inline void
rt_mutex_dequeue(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter)483 rt_mutex_dequeue(struct rt_mutex_base *lock, struct rt_mutex_waiter *waiter)
484 {
485 	lockdep_assert_held(&lock->wait_lock);
486 
487 	if (RB_EMPTY_NODE(&waiter->tree.entry))
488 		return;
489 
490 	rb_erase_cached(&waiter->tree.entry, &lock->waiters);
491 	RB_CLEAR_NODE(&waiter->tree.entry);
492 }
493 
494 #define __node_2_rt_node(node) \
495 	rb_entry((node), struct rt_waiter_node, entry)
496 
__pi_waiter_less(struct rb_node * a,const struct rb_node * b)497 static __always_inline bool __pi_waiter_less(struct rb_node *a, const struct rb_node *b)
498 {
499 	return rt_waiter_node_less(__node_2_rt_node(a), __node_2_rt_node(b));
500 }
501 
502 static __always_inline void
rt_mutex_enqueue_pi(struct task_struct * task,struct rt_mutex_waiter * waiter)503 rt_mutex_enqueue_pi(struct task_struct *task, struct rt_mutex_waiter *waiter)
504 {
505 	lockdep_assert_held(&task->pi_lock);
506 
507 	rb_add_cached(&waiter->pi_tree.entry, &task->pi_waiters, __pi_waiter_less);
508 }
509 
510 static __always_inline void
rt_mutex_dequeue_pi(struct task_struct * task,struct rt_mutex_waiter * waiter)511 rt_mutex_dequeue_pi(struct task_struct *task, struct rt_mutex_waiter *waiter)
512 {
513 	lockdep_assert_held(&task->pi_lock);
514 
515 	if (RB_EMPTY_NODE(&waiter->pi_tree.entry))
516 		return;
517 
518 	rb_erase_cached(&waiter->pi_tree.entry, &task->pi_waiters);
519 	RB_CLEAR_NODE(&waiter->pi_tree.entry);
520 }
521 
rt_mutex_adjust_prio(struct rt_mutex_base * lock,struct task_struct * p)522 static __always_inline void rt_mutex_adjust_prio(struct rt_mutex_base *lock,
523 						 struct task_struct *p)
524 {
525 	struct task_struct *pi_task = NULL;
526 
527 	lockdep_assert_held(&lock->wait_lock);
528 	lockdep_assert(rt_mutex_owner(lock) == p);
529 	lockdep_assert_held(&p->pi_lock);
530 
531 	if (task_has_pi_waiters(p))
532 		pi_task = task_top_pi_waiter(p)->task;
533 
534 	rt_mutex_setprio(p, pi_task);
535 }
536 
537 /* RT mutex specific wake_q wrappers */
rt_mutex_wake_q_add_task(struct rt_wake_q_head * wqh,struct task_struct * task,unsigned int wake_state)538 static __always_inline void rt_mutex_wake_q_add_task(struct rt_wake_q_head *wqh,
539 						     struct task_struct *task,
540 						     unsigned int wake_state)
541 {
542 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && wake_state == TASK_RTLOCK_WAIT) {
543 		if (IS_ENABLED(CONFIG_PROVE_LOCKING))
544 			WARN_ON_ONCE(wqh->rtlock_task);
545 		get_task_struct(task);
546 		wqh->rtlock_task = task;
547 	} else {
548 		wake_q_add(&wqh->head, task);
549 	}
550 }
551 
rt_mutex_wake_q_add(struct rt_wake_q_head * wqh,struct rt_mutex_waiter * w)552 static __always_inline void rt_mutex_wake_q_add(struct rt_wake_q_head *wqh,
553 						struct rt_mutex_waiter *w)
554 {
555 	rt_mutex_wake_q_add_task(wqh, w->task, w->wake_state);
556 }
557 
rt_mutex_wake_up_q(struct rt_wake_q_head * wqh)558 static __always_inline void rt_mutex_wake_up_q(struct rt_wake_q_head *wqh)
559 {
560 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && wqh->rtlock_task) {
561 		wake_up_state(wqh->rtlock_task, TASK_RTLOCK_WAIT);
562 		put_task_struct(wqh->rtlock_task);
563 		wqh->rtlock_task = NULL;
564 	}
565 
566 	if (!wake_q_empty(&wqh->head))
567 		wake_up_q(&wqh->head);
568 
569 	/* Pairs with preempt_disable() in mark_wakeup_next_waiter() */
570 	preempt_enable();
571 }
572 
573 /*
574  * Deadlock detection is conditional:
575  *
576  * If CONFIG_DEBUG_RT_MUTEXES=n, deadlock detection is only conducted
577  * if the detect argument is == RT_MUTEX_FULL_CHAINWALK.
578  *
579  * If CONFIG_DEBUG_RT_MUTEXES=y, deadlock detection is always
580  * conducted independent of the detect argument.
581  *
582  * If the waiter argument is NULL this indicates the deboost path and
583  * deadlock detection is disabled independent of the detect argument
584  * and the config settings.
585  */
586 static __always_inline bool
rt_mutex_cond_detect_deadlock(struct rt_mutex_waiter * waiter,enum rtmutex_chainwalk chwalk)587 rt_mutex_cond_detect_deadlock(struct rt_mutex_waiter *waiter,
588 			      enum rtmutex_chainwalk chwalk)
589 {
590 	if (IS_ENABLED(CONFIG_DEBUG_RT_MUTEXES))
591 		return waiter != NULL;
592 	return chwalk == RT_MUTEX_FULL_CHAINWALK;
593 }
594 
task_blocked_on_lock(struct task_struct * p)595 static __always_inline struct rt_mutex_base *task_blocked_on_lock(struct task_struct *p)
596 {
597 	return p->pi_blocked_on ? p->pi_blocked_on->lock : NULL;
598 }
599 
600 /*
601  * Adjust the priority chain. Also used for deadlock detection.
602  * Decreases task's usage by one - may thus free the task.
603  *
604  * @task:	the task owning the mutex (owner) for which a chain walk is
605  *		probably needed
606  * @chwalk:	do we have to carry out deadlock detection?
607  * @orig_lock:	the mutex (can be NULL if we are walking the chain to recheck
608  *		things for a task that has just got its priority adjusted, and
609  *		is waiting on a mutex)
610  * @next_lock:	the mutex on which the owner of @orig_lock was blocked before
611  *		we dropped its pi_lock. Is never dereferenced, only used for
612  *		comparison to detect lock chain changes.
613  * @orig_waiter: rt_mutex_waiter struct for the task that has just donated
614  *		its priority to the mutex owner (can be NULL in the case
615  *		depicted above or if the top waiter is gone away and we are
616  *		actually deboosting the owner)
617  * @top_task:	the current top waiter
618  *
619  * Returns 0 or -EDEADLK.
620  *
621  * Chain walk basics and protection scope
622  *
623  * [R] refcount on task
624  * [Pn] task->pi_lock held
625  * [L] rtmutex->wait_lock held
626  *
627  * Normal locking order:
628  *
629  *   rtmutex->wait_lock
630  *     task->pi_lock
631  *
632  * Step	Description				Protected by
633  *	function arguments:
634  *	@task					[R]
635  *	@orig_lock if != NULL			@top_task is blocked on it
636  *	@next_lock				Unprotected. Cannot be
637  *						dereferenced. Only used for
638  *						comparison.
639  *	@orig_waiter if != NULL			@top_task is blocked on it
640  *	@top_task				current, or in case of proxy
641  *						locking protected by calling
642  *						code
643  *	again:
644  *	  loop_sanity_check();
645  *	retry:
646  * [1]	  lock(task->pi_lock);			[R] acquire [P1]
647  * [2]	  waiter = task->pi_blocked_on;		[P1]
648  * [3]	  check_exit_conditions_1();		[P1]
649  * [4]	  lock = waiter->lock;			[P1]
650  * [5]	  if (!try_lock(lock->wait_lock)) {	[P1] try to acquire [L]
651  *	    unlock(task->pi_lock);		release [P1]
652  *	    goto retry;
653  *	  }
654  * [6]	  check_exit_conditions_2();		[P1] + [L]
655  * [7]	  requeue_lock_waiter(lock, waiter);	[P1] + [L]
656  * [8]	  unlock(task->pi_lock);		release [P1]
657  *	  put_task_struct(task);		release [R]
658  * [9]	  check_exit_conditions_3();		[L]
659  * [10]	  task = owner(lock);			[L]
660  *	  get_task_struct(task);		[L] acquire [R]
661  *	  lock(task->pi_lock);			[L] acquire [P2]
662  * [11]	  requeue_pi_waiter(tsk, waiters(lock));[P2] + [L]
663  * [12]	  check_exit_conditions_4();		[P2] + [L]
664  * [13]	  unlock(task->pi_lock);		release [P2]
665  *	  unlock(lock->wait_lock);		release [L]
666  *	  goto again;
667  *
668  * Where P1 is the blocking task and P2 is the lock owner; going up one step
669  * the owner becomes the next blocked task etc..
670  *
671 *
672  */
rt_mutex_adjust_prio_chain(struct task_struct * task,enum rtmutex_chainwalk chwalk,struct rt_mutex_base * orig_lock,struct rt_mutex_base * next_lock,struct rt_mutex_waiter * orig_waiter,struct task_struct * top_task)673 static int __sched rt_mutex_adjust_prio_chain(struct task_struct *task,
674 					      enum rtmutex_chainwalk chwalk,
675 					      struct rt_mutex_base *orig_lock,
676 					      struct rt_mutex_base *next_lock,
677 					      struct rt_mutex_waiter *orig_waiter,
678 					      struct task_struct *top_task)
679 {
680 	struct rt_mutex_waiter *waiter, *top_waiter = orig_waiter;
681 	struct rt_mutex_waiter *prerequeue_top_waiter;
682 	int ret = 0, depth = 0;
683 	struct rt_mutex_base *lock;
684 	bool detect_deadlock;
685 	bool requeue = true;
686 
687 	detect_deadlock = rt_mutex_cond_detect_deadlock(orig_waiter, chwalk);
688 
689 	/*
690 	 * The (de)boosting is a step by step approach with a lot of
691 	 * pitfalls. We want this to be preemptible and we want hold a
692 	 * maximum of two locks per step. So we have to check
693 	 * carefully whether things change under us.
694 	 */
695  again:
696 	/*
697 	 * We limit the lock chain length for each invocation.
698 	 */
699 	if (++depth > max_lock_depth) {
700 		static int prev_max;
701 
702 		/*
703 		 * Print this only once. If the admin changes the limit,
704 		 * print a new message when reaching the limit again.
705 		 */
706 		if (prev_max != max_lock_depth) {
707 			prev_max = max_lock_depth;
708 			printk(KERN_WARNING "Maximum lock depth %d reached "
709 			       "task: %s (%d)\n", max_lock_depth,
710 			       top_task->comm, task_pid_nr(top_task));
711 		}
712 		put_task_struct(task);
713 
714 		return -EDEADLK;
715 	}
716 
717 	/*
718 	 * We are fully preemptible here and only hold the refcount on
719 	 * @task. So everything can have changed under us since the
720 	 * caller or our own code below (goto retry/again) dropped all
721 	 * locks.
722 	 */
723  retry:
724 	/*
725 	 * [1] Task cannot go away as we did a get_task() before !
726 	 */
727 	raw_spin_lock_irq(&task->pi_lock);
728 
729 	/*
730 	 * [2] Get the waiter on which @task is blocked on.
731 	 */
732 	waiter = task->pi_blocked_on;
733 
734 	/*
735 	 * [3] check_exit_conditions_1() protected by task->pi_lock.
736 	 */
737 
738 	/*
739 	 * Check whether the end of the boosting chain has been
740 	 * reached or the state of the chain has changed while we
741 	 * dropped the locks.
742 	 */
743 	if (!waiter)
744 		goto out_unlock_pi;
745 
746 	/*
747 	 * Check the orig_waiter state. After we dropped the locks,
748 	 * the previous owner of the lock might have released the lock.
749 	 */
750 	if (orig_waiter && !rt_mutex_owner(orig_lock))
751 		goto out_unlock_pi;
752 
753 	/*
754 	 * We dropped all locks after taking a refcount on @task, so
755 	 * the task might have moved on in the lock chain or even left
756 	 * the chain completely and blocks now on an unrelated lock or
757 	 * on @orig_lock.
758 	 *
759 	 * We stored the lock on which @task was blocked in @next_lock,
760 	 * so we can detect the chain change.
761 	 */
762 	if (next_lock != waiter->lock)
763 		goto out_unlock_pi;
764 
765 	/*
766 	 * There could be 'spurious' loops in the lock graph due to ww_mutex,
767 	 * consider:
768 	 *
769 	 *   P1: A, ww_A, ww_B
770 	 *   P2: ww_B, ww_A
771 	 *   P3: A
772 	 *
773 	 * P3 should not return -EDEADLK because it gets trapped in the cycle
774 	 * created by P1 and P2 (which will resolve -- and runs into
775 	 * max_lock_depth above). Therefore disable detect_deadlock such that
776 	 * the below termination condition can trigger once all relevant tasks
777 	 * are boosted.
778 	 *
779 	 * Even when we start with ww_mutex we can disable deadlock detection,
780 	 * since we would supress a ww_mutex induced deadlock at [6] anyway.
781 	 * Supressing it here however is not sufficient since we might still
782 	 * hit [6] due to adjustment driven iteration.
783 	 *
784 	 * NOTE: if someone were to create a deadlock between 2 ww_classes we'd
785 	 * utterly fail to report it; lockdep should.
786 	 */
787 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && waiter->ww_ctx && detect_deadlock)
788 		detect_deadlock = false;
789 
790 	/*
791 	 * Drop out, when the task has no waiters. Note,
792 	 * top_waiter can be NULL, when we are in the deboosting
793 	 * mode!
794 	 */
795 	if (top_waiter) {
796 		if (!task_has_pi_waiters(task))
797 			goto out_unlock_pi;
798 		/*
799 		 * If deadlock detection is off, we stop here if we
800 		 * are not the top pi waiter of the task. If deadlock
801 		 * detection is enabled we continue, but stop the
802 		 * requeueing in the chain walk.
803 		 */
804 		if (top_waiter != task_top_pi_waiter(task)) {
805 			if (!detect_deadlock)
806 				goto out_unlock_pi;
807 			else
808 				requeue = false;
809 		}
810 	}
811 
812 	/*
813 	 * If the waiter priority is the same as the task priority
814 	 * then there is no further priority adjustment necessary.  If
815 	 * deadlock detection is off, we stop the chain walk. If its
816 	 * enabled we continue, but stop the requeueing in the chain
817 	 * walk.
818 	 */
819 	if (rt_waiter_node_equal(&waiter->tree, task_to_waiter_node(task))) {
820 		if (!detect_deadlock)
821 			goto out_unlock_pi;
822 		else
823 			requeue = false;
824 	}
825 
826 	/*
827 	 * [4] Get the next lock; per holding task->pi_lock we can't unblock
828 	 * and guarantee @lock's existence.
829 	 */
830 	lock = waiter->lock;
831 	/*
832 	 * [5] We need to trylock here as we are holding task->pi_lock,
833 	 * which is the reverse lock order versus the other rtmutex
834 	 * operations.
835 	 *
836 	 * Per the above, holding task->pi_lock guarantees lock exists, so
837 	 * inverting this lock order is infeasible from a life-time
838 	 * perspective.
839 	 */
840 	if (!raw_spin_trylock(&lock->wait_lock)) {
841 		raw_spin_unlock_irq(&task->pi_lock);
842 		cpu_relax();
843 		goto retry;
844 	}
845 
846 	/*
847 	 * [6] check_exit_conditions_2() protected by task->pi_lock and
848 	 * lock->wait_lock.
849 	 *
850 	 * Deadlock detection. If the lock is the same as the original
851 	 * lock which caused us to walk the lock chain or if the
852 	 * current lock is owned by the task which initiated the chain
853 	 * walk, we detected a deadlock.
854 	 */
855 	if (lock == orig_lock || rt_mutex_owner(lock) == top_task) {
856 		ret = -EDEADLK;
857 
858 		/*
859 		 * When the deadlock is due to ww_mutex; also see above. Don't
860 		 * report the deadlock and instead let the ww_mutex wound/die
861 		 * logic pick which of the contending threads gets -EDEADLK.
862 		 *
863 		 * NOTE: assumes the cycle only contains a single ww_class; any
864 		 * other configuration and we fail to report; also, see
865 		 * lockdep.
866 		 */
867 		if (IS_ENABLED(CONFIG_PREEMPT_RT) && orig_waiter && orig_waiter->ww_ctx)
868 			ret = 0;
869 
870 		raw_spin_unlock(&lock->wait_lock);
871 		goto out_unlock_pi;
872 	}
873 
874 	/*
875 	 * If we just follow the lock chain for deadlock detection, no
876 	 * need to do all the requeue operations. To avoid a truckload
877 	 * of conditionals around the various places below, just do the
878 	 * minimum chain walk checks.
879 	 */
880 	if (!requeue) {
881 		/*
882 		 * No requeue[7] here. Just release @task [8]
883 		 */
884 		raw_spin_unlock(&task->pi_lock);
885 		put_task_struct(task);
886 
887 		/*
888 		 * [9] check_exit_conditions_3 protected by lock->wait_lock.
889 		 * If there is no owner of the lock, end of chain.
890 		 */
891 		if (!rt_mutex_owner(lock)) {
892 			raw_spin_unlock_irq(&lock->wait_lock);
893 			return 0;
894 		}
895 
896 		/* [10] Grab the next task, i.e. owner of @lock */
897 		task = get_task_struct(rt_mutex_owner(lock));
898 		raw_spin_lock(&task->pi_lock);
899 
900 		/*
901 		 * No requeue [11] here. We just do deadlock detection.
902 		 *
903 		 * [12] Store whether owner is blocked
904 		 * itself. Decision is made after dropping the locks
905 		 */
906 		next_lock = task_blocked_on_lock(task);
907 		/*
908 		 * Get the top waiter for the next iteration
909 		 */
910 		top_waiter = rt_mutex_top_waiter(lock);
911 
912 		/* [13] Drop locks */
913 		raw_spin_unlock(&task->pi_lock);
914 		raw_spin_unlock_irq(&lock->wait_lock);
915 
916 		/* If owner is not blocked, end of chain. */
917 		if (!next_lock)
918 			goto out_put_task;
919 		goto again;
920 	}
921 
922 	/*
923 	 * Store the current top waiter before doing the requeue
924 	 * operation on @lock. We need it for the boost/deboost
925 	 * decision below.
926 	 */
927 	prerequeue_top_waiter = rt_mutex_top_waiter(lock);
928 
929 	/* [7] Requeue the waiter in the lock waiter tree. */
930 	rt_mutex_dequeue(lock, waiter);
931 
932 	/*
933 	 * Update the waiter prio fields now that we're dequeued.
934 	 *
935 	 * These values can have changed through either:
936 	 *
937 	 *   sys_sched_set_scheduler() / sys_sched_setattr()
938 	 *
939 	 * or
940 	 *
941 	 *   DL CBS enforcement advancing the effective deadline.
942 	 */
943 	waiter_update_prio(waiter, task);
944 
945 	rt_mutex_enqueue(lock, waiter);
946 
947 	/*
948 	 * [8] Release the (blocking) task in preparation for
949 	 * taking the owner task in [10].
950 	 *
951 	 * Since we hold lock->waiter_lock, task cannot unblock, even if we
952 	 * release task->pi_lock.
953 	 */
954 	raw_spin_unlock(&task->pi_lock);
955 	put_task_struct(task);
956 
957 	/*
958 	 * [9] check_exit_conditions_3 protected by lock->wait_lock.
959 	 *
960 	 * We must abort the chain walk if there is no lock owner even
961 	 * in the dead lock detection case, as we have nothing to
962 	 * follow here. This is the end of the chain we are walking.
963 	 */
964 	if (!rt_mutex_owner(lock)) {
965 		/*
966 		 * If the requeue [7] above changed the top waiter,
967 		 * then we need to wake the new top waiter up to try
968 		 * to get the lock.
969 		 */
970 		top_waiter = rt_mutex_top_waiter(lock);
971 		if (prerequeue_top_waiter != top_waiter)
972 			wake_up_state(top_waiter->task, top_waiter->wake_state);
973 		raw_spin_unlock_irq(&lock->wait_lock);
974 		return 0;
975 	}
976 
977 	/*
978 	 * [10] Grab the next task, i.e. the owner of @lock
979 	 *
980 	 * Per holding lock->wait_lock and checking for !owner above, there
981 	 * must be an owner and it cannot go away.
982 	 */
983 	task = get_task_struct(rt_mutex_owner(lock));
984 	raw_spin_lock(&task->pi_lock);
985 
986 	/* [11] requeue the pi waiters if necessary */
987 	if (waiter == rt_mutex_top_waiter(lock)) {
988 		/*
989 		 * The waiter became the new top (highest priority)
990 		 * waiter on the lock. Replace the previous top waiter
991 		 * in the owner tasks pi waiters tree with this waiter
992 		 * and adjust the priority of the owner.
993 		 */
994 		rt_mutex_dequeue_pi(task, prerequeue_top_waiter);
995 		waiter_clone_prio(waiter, task);
996 		rt_mutex_enqueue_pi(task, waiter);
997 		rt_mutex_adjust_prio(lock, task);
998 
999 	} else if (prerequeue_top_waiter == waiter) {
1000 		/*
1001 		 * The waiter was the top waiter on the lock, but is
1002 		 * no longer the top priority waiter. Replace waiter in
1003 		 * the owner tasks pi waiters tree with the new top
1004 		 * (highest priority) waiter and adjust the priority
1005 		 * of the owner.
1006 		 * The new top waiter is stored in @waiter so that
1007 		 * @waiter == @top_waiter evaluates to true below and
1008 		 * we continue to deboost the rest of the chain.
1009 		 */
1010 		rt_mutex_dequeue_pi(task, waiter);
1011 		waiter = rt_mutex_top_waiter(lock);
1012 		waiter_clone_prio(waiter, task);
1013 		rt_mutex_enqueue_pi(task, waiter);
1014 		rt_mutex_adjust_prio(lock, task);
1015 	} else {
1016 		/*
1017 		 * Nothing changed. No need to do any priority
1018 		 * adjustment.
1019 		 */
1020 	}
1021 
1022 	/*
1023 	 * [12] check_exit_conditions_4() protected by task->pi_lock
1024 	 * and lock->wait_lock. The actual decisions are made after we
1025 	 * dropped the locks.
1026 	 *
1027 	 * Check whether the task which owns the current lock is pi
1028 	 * blocked itself. If yes we store a pointer to the lock for
1029 	 * the lock chain change detection above. After we dropped
1030 	 * task->pi_lock next_lock cannot be dereferenced anymore.
1031 	 */
1032 	next_lock = task_blocked_on_lock(task);
1033 	/*
1034 	 * Store the top waiter of @lock for the end of chain walk
1035 	 * decision below.
1036 	 */
1037 	top_waiter = rt_mutex_top_waiter(lock);
1038 
1039 	/* [13] Drop the locks */
1040 	raw_spin_unlock(&task->pi_lock);
1041 	raw_spin_unlock_irq(&lock->wait_lock);
1042 
1043 	/*
1044 	 * Make the actual exit decisions [12], based on the stored
1045 	 * values.
1046 	 *
1047 	 * We reached the end of the lock chain. Stop right here. No
1048 	 * point to go back just to figure that out.
1049 	 */
1050 	if (!next_lock)
1051 		goto out_put_task;
1052 
1053 	/*
1054 	 * If the current waiter is not the top waiter on the lock,
1055 	 * then we can stop the chain walk here if we are not in full
1056 	 * deadlock detection mode.
1057 	 */
1058 	if (!detect_deadlock && waiter != top_waiter)
1059 		goto out_put_task;
1060 
1061 	goto again;
1062 
1063  out_unlock_pi:
1064 	raw_spin_unlock_irq(&task->pi_lock);
1065  out_put_task:
1066 	put_task_struct(task);
1067 
1068 	return ret;
1069 }
1070 
1071 /*
1072  * Try to take an rt-mutex
1073  *
1074  * Must be called with lock->wait_lock held and interrupts disabled
1075  *
1076  * @lock:   The lock to be acquired.
1077  * @task:   The task which wants to acquire the lock
1078  * @waiter: The waiter that is queued to the lock's wait tree if the
1079  *	    callsite called task_blocked_on_lock(), otherwise NULL
1080  */
1081 static int __sched
try_to_take_rt_mutex(struct rt_mutex_base * lock,struct task_struct * task,struct rt_mutex_waiter * waiter)1082 try_to_take_rt_mutex(struct rt_mutex_base *lock, struct task_struct *task,
1083 		     struct rt_mutex_waiter *waiter)
1084 {
1085 	lockdep_assert_held(&lock->wait_lock);
1086 
1087 	/*
1088 	 * Before testing whether we can acquire @lock, we set the
1089 	 * RT_MUTEX_HAS_WAITERS bit in @lock->owner. This forces all
1090 	 * other tasks which try to modify @lock into the slow path
1091 	 * and they serialize on @lock->wait_lock.
1092 	 *
1093 	 * The RT_MUTEX_HAS_WAITERS bit can have a transitional state
1094 	 * as explained at the top of this file if and only if:
1095 	 *
1096 	 * - There is a lock owner. The caller must fixup the
1097 	 *   transient state if it does a trylock or leaves the lock
1098 	 *   function due to a signal or timeout.
1099 	 *
1100 	 * - @task acquires the lock and there are no other
1101 	 *   waiters. This is undone in rt_mutex_set_owner(@task) at
1102 	 *   the end of this function.
1103 	 */
1104 	mark_rt_mutex_waiters(lock);
1105 
1106 	/*
1107 	 * If @lock has an owner, give up.
1108 	 */
1109 	if (rt_mutex_owner(lock))
1110 		return 0;
1111 
1112 	/*
1113 	 * If @waiter != NULL, @task has already enqueued the waiter
1114 	 * into @lock waiter tree. If @waiter == NULL then this is a
1115 	 * trylock attempt.
1116 	 */
1117 	if (waiter) {
1118 		struct rt_mutex_waiter *top_waiter = rt_mutex_top_waiter(lock);
1119 
1120 		/*
1121 		 * If waiter is the highest priority waiter of @lock,
1122 		 * or allowed to steal it, take it over.
1123 		 */
1124 		if (waiter == top_waiter || rt_mutex_steal(waiter, top_waiter)) {
1125 			/*
1126 			 * We can acquire the lock. Remove the waiter from the
1127 			 * lock waiters tree.
1128 			 */
1129 			rt_mutex_dequeue(lock, waiter);
1130 		} else {
1131 			return 0;
1132 		}
1133 	} else {
1134 		/*
1135 		 * If the lock has waiters already we check whether @task is
1136 		 * eligible to take over the lock.
1137 		 *
1138 		 * If there are no other waiters, @task can acquire
1139 		 * the lock.  @task->pi_blocked_on is NULL, so it does
1140 		 * not need to be dequeued.
1141 		 */
1142 		if (rt_mutex_has_waiters(lock)) {
1143 			/* Check whether the trylock can steal it. */
1144 			if (!rt_mutex_steal(task_to_waiter(task),
1145 					    rt_mutex_top_waiter(lock)))
1146 				return 0;
1147 
1148 			/*
1149 			 * The current top waiter stays enqueued. We
1150 			 * don't have to change anything in the lock
1151 			 * waiters order.
1152 			 */
1153 		} else {
1154 			/*
1155 			 * No waiters. Take the lock without the
1156 			 * pi_lock dance.@task->pi_blocked_on is NULL
1157 			 * and we have no waiters to enqueue in @task
1158 			 * pi waiters tree.
1159 			 */
1160 			goto takeit;
1161 		}
1162 	}
1163 
1164 	/*
1165 	 * Clear @task->pi_blocked_on. Requires protection by
1166 	 * @task->pi_lock. Redundant operation for the @waiter == NULL
1167 	 * case, but conditionals are more expensive than a redundant
1168 	 * store.
1169 	 */
1170 	raw_spin_lock(&task->pi_lock);
1171 	task->pi_blocked_on = NULL;
1172 	/*
1173 	 * Finish the lock acquisition. @task is the new owner. If
1174 	 * other waiters exist we have to insert the highest priority
1175 	 * waiter into @task->pi_waiters tree.
1176 	 */
1177 	if (rt_mutex_has_waiters(lock))
1178 		rt_mutex_enqueue_pi(task, rt_mutex_top_waiter(lock));
1179 	raw_spin_unlock(&task->pi_lock);
1180 
1181 takeit:
1182 	/*
1183 	 * This either preserves the RT_MUTEX_HAS_WAITERS bit if there
1184 	 * are still waiters or clears it.
1185 	 */
1186 	rt_mutex_set_owner(lock, task);
1187 
1188 	return 1;
1189 }
1190 
1191 /*
1192  * Task blocks on lock.
1193  *
1194  * Prepare waiter and propagate pi chain
1195  *
1196  * This must be called with lock->wait_lock held and interrupts disabled
1197  */
task_blocks_on_rt_mutex(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter,struct task_struct * task,struct ww_acquire_ctx * ww_ctx,enum rtmutex_chainwalk chwalk,struct wake_q_head * wake_q)1198 static int __sched task_blocks_on_rt_mutex(struct rt_mutex_base *lock,
1199 					   struct rt_mutex_waiter *waiter,
1200 					   struct task_struct *task,
1201 					   struct ww_acquire_ctx *ww_ctx,
1202 					   enum rtmutex_chainwalk chwalk,
1203 					   struct wake_q_head *wake_q)
1204 {
1205 	struct task_struct *owner = rt_mutex_owner(lock);
1206 	struct rt_mutex_waiter *top_waiter = waiter;
1207 	struct rt_mutex_base *next_lock;
1208 	int chain_walk = 0, res;
1209 
1210 	lockdep_assert_held(&lock->wait_lock);
1211 
1212 	/*
1213 	 * Early deadlock detection. We really don't want the task to
1214 	 * enqueue on itself just to untangle the mess later. It's not
1215 	 * only an optimization. We drop the locks, so another waiter
1216 	 * can come in before the chain walk detects the deadlock. So
1217 	 * the other will detect the deadlock and return -EDEADLOCK,
1218 	 * which is wrong, as the other waiter is not in a deadlock
1219 	 * situation.
1220 	 *
1221 	 * Except for ww_mutex, in that case the chain walk must already deal
1222 	 * with spurious cycles, see the comments at [3] and [6].
1223 	 */
1224 	if (owner == task && !(build_ww_mutex() && ww_ctx))
1225 		return -EDEADLK;
1226 
1227 	raw_spin_lock(&task->pi_lock);
1228 	waiter->task = task;
1229 	waiter->lock = lock;
1230 	waiter_update_prio(waiter, task);
1231 	waiter_clone_prio(waiter, task);
1232 
1233 	/* Get the top priority waiter on the lock */
1234 	if (rt_mutex_has_waiters(lock))
1235 		top_waiter = rt_mutex_top_waiter(lock);
1236 	rt_mutex_enqueue(lock, waiter);
1237 
1238 	task->pi_blocked_on = waiter;
1239 
1240 	raw_spin_unlock(&task->pi_lock);
1241 
1242 	if (build_ww_mutex() && ww_ctx) {
1243 		struct rt_mutex *rtm;
1244 
1245 		/* Check whether the waiter should back out immediately */
1246 		rtm = container_of(lock, struct rt_mutex, rtmutex);
1247 		res = __ww_mutex_add_waiter(waiter, rtm, ww_ctx, wake_q);
1248 		if (res) {
1249 			raw_spin_lock(&task->pi_lock);
1250 			rt_mutex_dequeue(lock, waiter);
1251 			task->pi_blocked_on = NULL;
1252 			raw_spin_unlock(&task->pi_lock);
1253 			return res;
1254 		}
1255 	}
1256 
1257 	if (!owner)
1258 		return 0;
1259 
1260 	raw_spin_lock(&owner->pi_lock);
1261 	if (waiter == rt_mutex_top_waiter(lock)) {
1262 		rt_mutex_dequeue_pi(owner, top_waiter);
1263 		rt_mutex_enqueue_pi(owner, waiter);
1264 
1265 		rt_mutex_adjust_prio(lock, owner);
1266 		if (owner->pi_blocked_on)
1267 			chain_walk = 1;
1268 	} else if (rt_mutex_cond_detect_deadlock(waiter, chwalk)) {
1269 		chain_walk = 1;
1270 	}
1271 
1272 	/* Store the lock on which owner is blocked or NULL */
1273 	next_lock = task_blocked_on_lock(owner);
1274 
1275 	raw_spin_unlock(&owner->pi_lock);
1276 	/*
1277 	 * Even if full deadlock detection is on, if the owner is not
1278 	 * blocked itself, we can avoid finding this out in the chain
1279 	 * walk.
1280 	 */
1281 	if (!chain_walk || !next_lock)
1282 		return 0;
1283 
1284 	/*
1285 	 * The owner can't disappear while holding a lock,
1286 	 * so the owner struct is protected by wait_lock.
1287 	 * Gets dropped in rt_mutex_adjust_prio_chain()!
1288 	 */
1289 	get_task_struct(owner);
1290 
1291 	preempt_disable();
1292 	raw_spin_unlock_irq(&lock->wait_lock);
1293 	/* wake up any tasks on the wake_q before calling rt_mutex_adjust_prio_chain */
1294 	wake_up_q(wake_q);
1295 	wake_q_init(wake_q);
1296 	preempt_enable();
1297 
1298 
1299 	res = rt_mutex_adjust_prio_chain(owner, chwalk, lock,
1300 					 next_lock, waiter, task);
1301 
1302 	raw_spin_lock_irq(&lock->wait_lock);
1303 
1304 	return res;
1305 }
1306 
1307 /*
1308  * Remove the top waiter from the current tasks pi waiter tree and
1309  * queue it up.
1310  *
1311  * Called with lock->wait_lock held and interrupts disabled.
1312  */
mark_wakeup_next_waiter(struct rt_wake_q_head * wqh,struct rt_mutex_base * lock)1313 static void __sched mark_wakeup_next_waiter(struct rt_wake_q_head *wqh,
1314 					    struct rt_mutex_base *lock)
1315 {
1316 	struct rt_mutex_waiter *waiter;
1317 
1318 	lockdep_assert_held(&lock->wait_lock);
1319 
1320 	raw_spin_lock(¤t->pi_lock);
1321 
1322 	waiter = rt_mutex_top_waiter(lock);
1323 
1324 	/*
1325 	 * Remove it from current->pi_waiters and deboost.
1326 	 *
1327 	 * We must in fact deboost here in order to ensure we call
1328 	 * rt_mutex_setprio() to update p->pi_top_task before the
1329 	 * task unblocks.
1330 	 */
1331 	rt_mutex_dequeue_pi(current, waiter);
1332 	rt_mutex_adjust_prio(lock, current);
1333 
1334 	/*
1335 	 * As we are waking up the top waiter, and the waiter stays
1336 	 * queued on the lock until it gets the lock, this lock
1337 	 * obviously has waiters. Just set the bit here and this has
1338 	 * the added benefit of forcing all new tasks into the
1339 	 * slow path making sure no task of lower priority than
1340 	 * the top waiter can steal this lock.
1341 	 */
1342 	lock->owner = (void *) RT_MUTEX_HAS_WAITERS;
1343 
1344 	/*
1345 	 * We deboosted before waking the top waiter task such that we don't
1346 	 * run two tasks with the 'same' priority (and ensure the
1347 	 * p->pi_top_task pointer points to a blocked task). This however can
1348 	 * lead to priority inversion if we would get preempted after the
1349 	 * deboost but before waking our donor task, hence the preempt_disable()
1350 	 * before unlock.
1351 	 *
1352 	 * Pairs with preempt_enable() in rt_mutex_wake_up_q();
1353 	 */
1354 	preempt_disable();
1355 	rt_mutex_wake_q_add(wqh, waiter);
1356 	raw_spin_unlock(¤t->pi_lock);
1357 }
1358 
__rt_mutex_slowtrylock(struct rt_mutex_base * lock)1359 static int __sched __rt_mutex_slowtrylock(struct rt_mutex_base *lock)
1360 {
1361 	int ret = try_to_take_rt_mutex(lock, current, NULL);
1362 
1363 	/*
1364 	 * try_to_take_rt_mutex() sets the lock waiters bit
1365 	 * unconditionally. Clean this up.
1366 	 */
1367 	fixup_rt_mutex_waiters(lock, true);
1368 
1369 	return ret;
1370 }
1371 
1372 /*
1373  * Slow path try-lock function:
1374  */
rt_mutex_slowtrylock(struct rt_mutex_base * lock)1375 static int __sched rt_mutex_slowtrylock(struct rt_mutex_base *lock)
1376 {
1377 	unsigned long flags;
1378 	int ret;
1379 
1380 	/*
1381 	 * If the lock already has an owner we fail to get the lock.
1382 	 * This can be done without taking the @lock->wait_lock as
1383 	 * it is only being read, and this is a trylock anyway.
1384 	 */
1385 	if (rt_mutex_owner(lock))
1386 		return 0;
1387 
1388 	/*
1389 	 * The mutex has currently no owner. Lock the wait lock and try to
1390 	 * acquire the lock. We use irqsave here to support early boot calls.
1391 	 */
1392 	raw_spin_lock_irqsave(&lock->wait_lock, flags);
1393 
1394 	ret = __rt_mutex_slowtrylock(lock);
1395 
1396 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
1397 
1398 	return ret;
1399 }
1400 
__rt_mutex_trylock(struct rt_mutex_base * lock)1401 static __always_inline int __rt_mutex_trylock(struct rt_mutex_base *lock)
1402 {
1403 	if (likely(rt_mutex_cmpxchg_acquire(lock, NULL, current)))
1404 		return 1;
1405 
1406 	return rt_mutex_slowtrylock(lock);
1407 }
1408 
1409 /*
1410  * Slow path to release a rt-mutex.
1411  */
rt_mutex_slowunlock(struct rt_mutex_base * lock)1412 static void __sched rt_mutex_slowunlock(struct rt_mutex_base *lock)
1413 {
1414 	DEFINE_RT_WAKE_Q(wqh);
1415 	unsigned long flags;
1416 
1417 	/* irqsave required to support early boot calls */
1418 	raw_spin_lock_irqsave(&lock->wait_lock, flags);
1419 
1420 	debug_rt_mutex_unlock(lock);
1421 
1422 	/*
1423 	 * We must be careful here if the fast path is enabled. If we
1424 	 * have no waiters queued we cannot set owner to NULL here
1425 	 * because of:
1426 	 *
1427 	 * foo->lock->owner = NULL;
1428 	 *			rtmutex_lock(foo->lock);   <- fast path
1429 	 *			free = atomic_dec_and_test(foo->refcnt);
1430 	 *			rtmutex_unlock(foo->lock); <- fast path
1431 	 *			if (free)
1432 	 *				kfree(foo);
1433 	 * raw_spin_unlock(foo->lock->wait_lock);
1434 	 *
1435 	 * So for the fastpath enabled kernel:
1436 	 *
1437 	 * Nothing can set the waiters bit as long as we hold
1438 	 * lock->wait_lock. So we do the following sequence:
1439 	 *
1440 	 *	owner = rt_mutex_owner(lock);
1441 	 *	clear_rt_mutex_waiters(lock);
1442 	 *	raw_spin_unlock(&lock->wait_lock);
1443 	 *	if (cmpxchg(&lock->owner, owner, 0) == owner)
1444 	 *		return;
1445 	 *	goto retry;
1446 	 *
1447 	 * The fastpath disabled variant is simple as all access to
1448 	 * lock->owner is serialized by lock->wait_lock:
1449 	 *
1450 	 *	lock->owner = NULL;
1451 	 *	raw_spin_unlock(&lock->wait_lock);
1452 	 */
1453 	while (!rt_mutex_has_waiters(lock)) {
1454 		/* Drops lock->wait_lock ! */
1455 		if (unlock_rt_mutex_safe(lock, flags) == true)
1456 			return;
1457 		/* Relock the rtmutex and try again */
1458 		raw_spin_lock_irqsave(&lock->wait_lock, flags);
1459 	}
1460 
1461 	/*
1462 	 * The wakeup next waiter path does not suffer from the above
1463 	 * race. See the comments there.
1464 	 *
1465 	 * Queue the next waiter for wakeup once we release the wait_lock.
1466 	 */
1467 	mark_wakeup_next_waiter(&wqh, lock);
1468 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
1469 
1470 	rt_mutex_wake_up_q(&wqh);
1471 }
1472 
__rt_mutex_unlock(struct rt_mutex_base * lock)1473 static __always_inline void __rt_mutex_unlock(struct rt_mutex_base *lock)
1474 {
1475 	if (likely(rt_mutex_cmpxchg_release(lock, current, NULL)))
1476 		return;
1477 
1478 	rt_mutex_slowunlock(lock);
1479 }
1480 
1481 #ifdef CONFIG_SMP
rtmutex_spin_on_owner(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter,struct task_struct * owner)1482 static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
1483 				  struct rt_mutex_waiter *waiter,
1484 				  struct task_struct *owner)
1485 {
1486 	bool res = true;
1487 
1488 	rcu_read_lock();
1489 	for (;;) {
1490 		/* If owner changed, trylock again. */
1491 		if (owner != rt_mutex_owner(lock))
1492 			break;
1493 		/*
1494 		 * Ensure that @owner is dereferenced after checking that
1495 		 * the lock owner still matches @owner. If that fails,
1496 		 * @owner might point to freed memory. If it still matches,
1497 		 * the rcu_read_lock() ensures the memory stays valid.
1498 		 */
1499 		barrier();
1500 		/*
1501 		 * Stop spinning when:
1502 		 *  - the lock owner has been scheduled out
1503 		 *  - current is not longer the top waiter
1504 		 *  - current is requested to reschedule (redundant
1505 		 *    for CONFIG_PREEMPT_RCU=y)
1506 		 *  - the VCPU on which owner runs is preempted
1507 		 */
1508 		if (!owner_on_cpu(owner) || need_resched() ||
1509 		    !rt_mutex_waiter_is_top_waiter(lock, waiter)) {
1510 			res = false;
1511 			break;
1512 		}
1513 		cpu_relax();
1514 	}
1515 	rcu_read_unlock();
1516 	return res;
1517 }
1518 #else
rtmutex_spin_on_owner(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter,struct task_struct * owner)1519 static bool rtmutex_spin_on_owner(struct rt_mutex_base *lock,
1520 				  struct rt_mutex_waiter *waiter,
1521 				  struct task_struct *owner)
1522 {
1523 	return false;
1524 }
1525 #endif
1526 
1527 #ifdef RT_MUTEX_BUILD_MUTEX
1528 /*
1529  * Functions required for:
1530  *	- rtmutex, futex on all kernels
1531  *	- mutex and rwsem substitutions on RT kernels
1532  */
1533 
1534 /*
1535  * Remove a waiter from a lock and give up
1536  *
1537  * Must be called with lock->wait_lock held and interrupts disabled. It must
1538  * have just failed to try_to_take_rt_mutex().
1539  */
remove_waiter(struct rt_mutex_base * lock,struct rt_mutex_waiter * waiter)1540 static void __sched remove_waiter(struct rt_mutex_base *lock,
1541 				  struct rt_mutex_waiter *waiter)
1542 {
1543 	bool is_top_waiter = (waiter == rt_mutex_top_waiter(lock));
1544 	struct task_struct *owner = rt_mutex_owner(lock);
1545 	struct rt_mutex_base *next_lock;
1546 
1547 	lockdep_assert_held(&lock->wait_lock);
1548 
1549 	raw_spin_lock(¤t->pi_lock);
1550 	rt_mutex_dequeue(lock, waiter);
1551 	current->pi_blocked_on = NULL;
1552 	raw_spin_unlock(¤t->pi_lock);
1553 
1554 	/*
1555 	 * Only update priority if the waiter was the highest priority
1556 	 * waiter of the lock and there is an owner to update.
1557 	 */
1558 	if (!owner || !is_top_waiter)
1559 		return;
1560 
1561 	raw_spin_lock(&owner->pi_lock);
1562 
1563 	rt_mutex_dequeue_pi(owner, waiter);
1564 
1565 	if (rt_mutex_has_waiters(lock))
1566 		rt_mutex_enqueue_pi(owner, rt_mutex_top_waiter(lock));
1567 
1568 	rt_mutex_adjust_prio(lock, owner);
1569 
1570 	/* Store the lock on which owner is blocked or NULL */
1571 	next_lock = task_blocked_on_lock(owner);
1572 
1573 	raw_spin_unlock(&owner->pi_lock);
1574 
1575 	/*
1576 	 * Don't walk the chain, if the owner task is not blocked
1577 	 * itself.
1578 	 */
1579 	if (!next_lock)
1580 		return;
1581 
1582 	/* gets dropped in rt_mutex_adjust_prio_chain()! */
1583 	get_task_struct(owner);
1584 
1585 	raw_spin_unlock_irq(&lock->wait_lock);
1586 
1587 	rt_mutex_adjust_prio_chain(owner, RT_MUTEX_MIN_CHAINWALK, lock,
1588 				   next_lock, NULL, current);
1589 
1590 	raw_spin_lock_irq(&lock->wait_lock);
1591 }
1592 
1593 /**
1594  * rt_mutex_slowlock_block() - Perform the wait-wake-try-to-take loop
1595  * @lock:		 the rt_mutex to take
1596  * @ww_ctx:		 WW mutex context pointer
1597  * @state:		 the state the task should block in (TASK_INTERRUPTIBLE
1598  *			 or TASK_UNINTERRUPTIBLE)
1599  * @timeout:		 the pre-initialized and started timer, or NULL for none
1600  * @waiter:		 the pre-initialized rt_mutex_waiter
1601  * @wake_q:		 wake_q of tasks to wake when we drop the lock->wait_lock
1602  *
1603  * Must be called with lock->wait_lock held and interrupts disabled
1604  */
rt_mutex_slowlock_block(struct rt_mutex_base * lock,struct ww_acquire_ctx * ww_ctx,unsigned int state,struct hrtimer_sleeper * timeout,struct rt_mutex_waiter * waiter,struct wake_q_head * wake_q)1605 static int __sched rt_mutex_slowlock_block(struct rt_mutex_base *lock,
1606 					   struct ww_acquire_ctx *ww_ctx,
1607 					   unsigned int state,
1608 					   struct hrtimer_sleeper *timeout,
1609 					   struct rt_mutex_waiter *waiter,
1610 					   struct wake_q_head *wake_q)
1611 {
1612 	struct rt_mutex *rtm = container_of(lock, struct rt_mutex, rtmutex);
1613 	struct task_struct *owner;
1614 	int ret = 0;
1615 
1616 	trace_android_vh_rtmutex_wait_start(lock);
1617 	for (;;) {
1618 		/* Try to acquire the lock: */
1619 		if (try_to_take_rt_mutex(lock, current, waiter))
1620 			break;
1621 
1622 		if (timeout && !timeout->task) {
1623 			ret = -ETIMEDOUT;
1624 			break;
1625 		}
1626 		if (signal_pending_state(state, current)) {
1627 			ret = -EINTR;
1628 			break;
1629 		}
1630 
1631 		if (build_ww_mutex() && ww_ctx) {
1632 			ret = __ww_mutex_check_kill(rtm, waiter, ww_ctx);
1633 			if (ret)
1634 				break;
1635 		}
1636 
1637 		if (waiter == rt_mutex_top_waiter(lock))
1638 			owner = rt_mutex_owner(lock);
1639 		else
1640 			owner = NULL;
1641 		preempt_disable();
1642 		raw_spin_unlock_irq(&lock->wait_lock);
1643 		if (wake_q) {
1644 			wake_up_q(wake_q);
1645 			wake_q_init(wake_q);
1646 		}
1647 		preempt_enable();
1648 
1649 		if (!owner || !rtmutex_spin_on_owner(lock, waiter, owner))
1650 			rt_mutex_schedule();
1651 
1652 		raw_spin_lock_irq(&lock->wait_lock);
1653 		set_current_state(state);
1654 	}
1655 
1656 	trace_android_vh_rtmutex_wait_finish(lock);
1657 	__set_current_state(TASK_RUNNING);
1658 	return ret;
1659 }
1660 
rt_mutex_handle_deadlock(int res,int detect_deadlock,struct rt_mutex_base * lock,struct rt_mutex_waiter * w)1661 static void __sched rt_mutex_handle_deadlock(int res, int detect_deadlock,
1662 					     struct rt_mutex_base *lock,
1663 					     struct rt_mutex_waiter *w)
1664 {
1665 	/*
1666 	 * If the result is not -EDEADLOCK or the caller requested
1667 	 * deadlock detection, nothing to do here.
1668 	 */
1669 	if (res != -EDEADLOCK || detect_deadlock)
1670 		return;
1671 
1672 	if (build_ww_mutex() && w->ww_ctx)
1673 		return;
1674 
1675 	raw_spin_unlock_irq(&lock->wait_lock);
1676 
1677 	WARN(1, "rtmutex deadlock detected\n");
1678 
1679 	while (1) {
1680 		set_current_state(TASK_INTERRUPTIBLE);
1681 		rt_mutex_schedule();
1682 	}
1683 }
1684 
1685 /**
1686  * __rt_mutex_slowlock - Locking slowpath invoked with lock::wait_lock held
1687  * @lock:	The rtmutex to block lock
1688  * @ww_ctx:	WW mutex context pointer
1689  * @state:	The task state for sleeping
1690  * @chwalk:	Indicator whether full or partial chainwalk is requested
1691  * @waiter:	Initializer waiter for blocking
1692  * @wake_q:	The wake_q to wake tasks after we release the wait_lock
1693  */
__rt_mutex_slowlock(struct rt_mutex_base * lock,struct ww_acquire_ctx * ww_ctx,unsigned int state,enum rtmutex_chainwalk chwalk,struct rt_mutex_waiter * waiter,struct wake_q_head * wake_q)1694 static int __sched __rt_mutex_slowlock(struct rt_mutex_base *lock,
1695 				       struct ww_acquire_ctx *ww_ctx,
1696 				       unsigned int state,
1697 				       enum rtmutex_chainwalk chwalk,
1698 				       struct rt_mutex_waiter *waiter,
1699 				       struct wake_q_head *wake_q)
1700 {
1701 	struct rt_mutex *rtm = container_of(lock, struct rt_mutex, rtmutex);
1702 	struct ww_mutex *ww = ww_container_of(rtm);
1703 	int ret;
1704 
1705 	lockdep_assert_held(&lock->wait_lock);
1706 
1707 	/* Try to acquire the lock again: */
1708 	if (try_to_take_rt_mutex(lock, current, NULL)) {
1709 		if (build_ww_mutex() && ww_ctx) {
1710 			__ww_mutex_check_waiters(rtm, ww_ctx, wake_q);
1711 			ww_mutex_lock_acquired(ww, ww_ctx);
1712 		}
1713 		return 0;
1714 	}
1715 
1716 	set_current_state(state);
1717 
1718 	trace_contention_begin(lock, LCB_F_RT);
1719 
1720 	ret = task_blocks_on_rt_mutex(lock, waiter, current, ww_ctx, chwalk, wake_q);
1721 	if (likely(!ret))
1722 		ret = rt_mutex_slowlock_block(lock, ww_ctx, state, NULL, waiter, wake_q);
1723 
1724 	if (likely(!ret)) {
1725 		/* acquired the lock */
1726 		if (build_ww_mutex() && ww_ctx) {
1727 			if (!ww_ctx->is_wait_die)
1728 				__ww_mutex_check_waiters(rtm, ww_ctx, wake_q);
1729 			ww_mutex_lock_acquired(ww, ww_ctx);
1730 		}
1731 	} else {
1732 		__set_current_state(TASK_RUNNING);
1733 		remove_waiter(lock, waiter);
1734 		rt_mutex_handle_deadlock(ret, chwalk, lock, waiter);
1735 	}
1736 
1737 	/*
1738 	 * try_to_take_rt_mutex() sets the waiter bit
1739 	 * unconditionally. We might have to fix that up.
1740 	 */
1741 	fixup_rt_mutex_waiters(lock, true);
1742 
1743 	trace_contention_end(lock, ret);
1744 
1745 	return ret;
1746 }
1747 
__rt_mutex_slowlock_locked(struct rt_mutex_base * lock,struct ww_acquire_ctx * ww_ctx,unsigned int state,struct wake_q_head * wake_q)1748 static inline int __rt_mutex_slowlock_locked(struct rt_mutex_base *lock,
1749 					     struct ww_acquire_ctx *ww_ctx,
1750 					     unsigned int state,
1751 					     struct wake_q_head *wake_q)
1752 {
1753 	struct rt_mutex_waiter waiter;
1754 	int ret;
1755 
1756 	rt_mutex_init_waiter(&waiter);
1757 	waiter.ww_ctx = ww_ctx;
1758 
1759 	ret = __rt_mutex_slowlock(lock, ww_ctx, state, RT_MUTEX_MIN_CHAINWALK,
1760 				  &waiter, wake_q);
1761 
1762 	debug_rt_mutex_free_waiter(&waiter);
1763 	return ret;
1764 }
1765 
1766 /*
1767  * rt_mutex_slowlock - Locking slowpath invoked when fast path fails
1768  * @lock:	The rtmutex to block lock
1769  * @ww_ctx:	WW mutex context pointer
1770  * @state:	The task state for sleeping
1771  */
rt_mutex_slowlock(struct rt_mutex_base * lock,struct ww_acquire_ctx * ww_ctx,unsigned int state)1772 static int __sched rt_mutex_slowlock(struct rt_mutex_base *lock,
1773 				     struct ww_acquire_ctx *ww_ctx,
1774 				     unsigned int state)
1775 {
1776 	DEFINE_WAKE_Q(wake_q);
1777 	unsigned long flags;
1778 	int ret;
1779 
1780 	/*
1781 	 * Do all pre-schedule work here, before we queue a waiter and invoke
1782 	 * PI -- any such work that trips on rtlock (PREEMPT_RT spinlock) would
1783 	 * otherwise recurse back into task_blocks_on_rt_mutex() through
1784 	 * rtlock_slowlock() and will then enqueue a second waiter for this
1785 	 * same task and things get really confusing real fast.
1786 	 */
1787 	rt_mutex_pre_schedule();
1788 
1789 	/*
1790 	 * Technically we could use raw_spin_[un]lock_irq() here, but this can
1791 	 * be called in early boot if the cmpxchg() fast path is disabled
1792 	 * (debug, no architecture support). In this case we will acquire the
1793 	 * rtmutex with lock->wait_lock held. But we cannot unconditionally
1794 	 * enable interrupts in that early boot case. So we need to use the
1795 	 * irqsave/restore variants.
1796 	 */
1797 	raw_spin_lock_irqsave(&lock->wait_lock, flags);
1798 	ret = __rt_mutex_slowlock_locked(lock, ww_ctx, state, &wake_q);
1799 	preempt_disable();
1800 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
1801 	wake_up_q(&wake_q);
1802 	preempt_enable();
1803 	rt_mutex_post_schedule();
1804 
1805 	return ret;
1806 }
1807 
__rt_mutex_lock(struct rt_mutex_base * lock,unsigned int state)1808 static __always_inline int __rt_mutex_lock(struct rt_mutex_base *lock,
1809 					   unsigned int state)
1810 {
1811 	lockdep_assert(!current->pi_blocked_on);
1812 
1813 	if (likely(rt_mutex_try_acquire(lock)))
1814 		return 0;
1815 
1816 	return rt_mutex_slowlock(lock, NULL, state);
1817 }
1818 #endif /* RT_MUTEX_BUILD_MUTEX */
1819 
1820 #ifdef RT_MUTEX_BUILD_SPINLOCKS
1821 /*
1822  * Functions required for spin/rw_lock substitution on RT kernels
1823  */
1824 
1825 /**
1826  * rtlock_slowlock_locked - Slow path lock acquisition for RT locks
1827  * @lock:	The underlying RT mutex
1828  * @wake_q:	The wake_q to wake tasks after we release the wait_lock
1829  */
rtlock_slowlock_locked(struct rt_mutex_base * lock,struct wake_q_head * wake_q)1830 static void __sched rtlock_slowlock_locked(struct rt_mutex_base *lock,
1831 					   struct wake_q_head *wake_q)
1832 {
1833 	struct rt_mutex_waiter waiter;
1834 	struct task_struct *owner;
1835 
1836 	lockdep_assert_held(&lock->wait_lock);
1837 
1838 	if (try_to_take_rt_mutex(lock, current, NULL))
1839 		return;
1840 
1841 	rt_mutex_init_rtlock_waiter(&waiter);
1842 
1843 	/* Save current state and set state to TASK_RTLOCK_WAIT */
1844 	current_save_and_set_rtlock_wait_state();
1845 
1846 	trace_contention_begin(lock, LCB_F_RT);
1847 
1848 	task_blocks_on_rt_mutex(lock, &waiter, current, NULL, RT_MUTEX_MIN_CHAINWALK, wake_q);
1849 
1850 	for (;;) {
1851 		/* Try to acquire the lock again */
1852 		if (try_to_take_rt_mutex(lock, current, &waiter))
1853 			break;
1854 
1855 		if (&waiter == rt_mutex_top_waiter(lock))
1856 			owner = rt_mutex_owner(lock);
1857 		else
1858 			owner = NULL;
1859 		preempt_disable();
1860 		raw_spin_unlock_irq(&lock->wait_lock);
1861 		wake_up_q(wake_q);
1862 		wake_q_init(wake_q);
1863 		preempt_enable();
1864 
1865 		if (!owner || !rtmutex_spin_on_owner(lock, &waiter, owner))
1866 			schedule_rtlock();
1867 
1868 		raw_spin_lock_irq(&lock->wait_lock);
1869 		set_current_state(TASK_RTLOCK_WAIT);
1870 	}
1871 
1872 	/* Restore the task state */
1873 	current_restore_rtlock_saved_state();
1874 
1875 	/*
1876 	 * try_to_take_rt_mutex() sets the waiter bit unconditionally.
1877 	 * We might have to fix that up:
1878 	 */
1879 	fixup_rt_mutex_waiters(lock, true);
1880 	debug_rt_mutex_free_waiter(&waiter);
1881 
1882 	trace_contention_end(lock, 0);
1883 }
1884 
rtlock_slowlock(struct rt_mutex_base * lock)1885 static __always_inline void __sched rtlock_slowlock(struct rt_mutex_base *lock)
1886 {
1887 	unsigned long flags;
1888 	DEFINE_WAKE_Q(wake_q);
1889 
1890 	raw_spin_lock_irqsave(&lock->wait_lock, flags);
1891 	rtlock_slowlock_locked(lock, &wake_q);
1892 	preempt_disable();
1893 	raw_spin_unlock_irqrestore(&lock->wait_lock, flags);
1894 	wake_up_q(&wake_q);
1895 	preempt_enable();
1896 }
1897 
1898 #endif /* RT_MUTEX_BUILD_SPINLOCKS */
1899