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