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