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