sched: fix __sched_setscheduler() vs load balancing race
[pandora-kernel.git] / kernel / 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/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/timer.h>
17
18 #include "rtmutex_common.h"
19
20 /*
21  * lock->owner state tracking:
22  *
23  * lock->owner holds the task_struct pointer of the owner. Bit 0
24  * is used to keep track of the "lock has waiters" state.
25  *
26  * owner        bit0
27  * NULL         0       lock is free (fast acquire possible)
28  * NULL         1       lock is free and has waiters and the top waiter
29  *                              is going to take the lock*
30  * taskpointer  0       lock is held (fast release possible)
31  * taskpointer  1       lock is held and has waiters**
32  *
33  * The fast atomic compare exchange based acquire and release is only
34  * possible when bit 0 of lock->owner is 0.
35  *
36  * (*) It also can be a transitional state when grabbing the lock
37  * with ->wait_lock is held. To prevent any fast path cmpxchg to the lock,
38  * we need to set the bit0 before looking at the lock, and the owner may be
39  * NULL in this small time, hence this can be a transitional state.
40  *
41  * (**) There is a small time when bit 0 is set but there are no
42  * waiters. This can happen when grabbing the lock in the slow path.
43  * To prevent a cmpxchg of the owner releasing the lock, we need to
44  * set this bit before looking at the lock.
45  */
46
47 static void
48 rt_mutex_set_owner(struct rt_mutex *lock, struct task_struct *owner)
49 {
50         unsigned long val = (unsigned long)owner;
51
52         if (rt_mutex_has_waiters(lock))
53                 val |= RT_MUTEX_HAS_WAITERS;
54
55         lock->owner = (struct task_struct *)val;
56 }
57
58 static inline void clear_rt_mutex_waiters(struct rt_mutex *lock)
59 {
60         lock->owner = (struct task_struct *)
61                         ((unsigned long)lock->owner & ~RT_MUTEX_HAS_WAITERS);
62 }
63
64 static void fixup_rt_mutex_waiters(struct rt_mutex *lock)
65 {
66         if (!rt_mutex_has_waiters(lock))
67                 clear_rt_mutex_waiters(lock);
68 }
69
70 /*
71  * We can speed up the acquire/release, if the architecture
72  * supports cmpxchg and if there's no debugging state to be set up
73  */
74 #if defined(__HAVE_ARCH_CMPXCHG) && !defined(CONFIG_DEBUG_RT_MUTEXES)
75 # define rt_mutex_cmpxchg(l,c,n)        (cmpxchg(&l->owner, c, n) == c)
76 static inline void mark_rt_mutex_waiters(struct rt_mutex *lock)
77 {
78         unsigned long owner, *p = (unsigned long *) &lock->owner;
79
80         do {
81                 owner = *p;
82         } while (cmpxchg(p, owner, owner | RT_MUTEX_HAS_WAITERS) != owner);
83 }
84
85 /*
86  * Safe fastpath aware unlock:
87  * 1) Clear the waiters bit
88  * 2) Drop lock->wait_lock
89  * 3) Try to unlock the lock with cmpxchg
90  */
91 static inline bool unlock_rt_mutex_safe(struct rt_mutex *lock)
92         __releases(lock->wait_lock)
93 {
94         struct task_struct *owner = rt_mutex_owner(lock);
95
96         clear_rt_mutex_waiters(lock);
97         raw_spin_unlock(&lock->wait_lock);
98         /*
99          * If a new waiter comes in between the unlock and the cmpxchg
100          * we have two situations:
101          *
102          * unlock(wait_lock);
103          *                                      lock(wait_lock);
104          * cmpxchg(p, owner, 0) == owner
105          *                                      mark_rt_mutex_waiters(lock);
106          *                                      acquire(lock);
107          * or:
108          *
109          * unlock(wait_lock);
110          *                                      lock(wait_lock);
111          *                                      mark_rt_mutex_waiters(lock);
112          *
113          * cmpxchg(p, owner, 0) != owner
114          *                                      enqueue_waiter();
115          *                                      unlock(wait_lock);
116          * lock(wait_lock);
117          * wake waiter();
118          * unlock(wait_lock);
119          *                                      lock(wait_lock);
120          *                                      acquire(lock);
121          */
122         return rt_mutex_cmpxchg(lock, owner, NULL);
123 }
124
125 #else
126 # define rt_mutex_cmpxchg(l,c,n)        (0)
127 static inline void mark_rt_mutex_waiters(struct rt_mutex *lock)
128 {
129         lock->owner = (struct task_struct *)
130                         ((unsigned long)lock->owner | RT_MUTEX_HAS_WAITERS);
131 }
132
133 /*
134  * Simple slow path only version: lock->owner is protected by lock->wait_lock.
135  */
136 static inline bool unlock_rt_mutex_safe(struct rt_mutex *lock)
137         __releases(lock->wait_lock)
138 {
139         lock->owner = NULL;
140         raw_spin_unlock(&lock->wait_lock);
141         return true;
142 }
143 #endif
144
145 /*
146  * Calculate task priority from the waiter list priority
147  *
148  * Return task->normal_prio when the waiter list is empty or when
149  * the waiter is not allowed to do priority boosting
150  */
151 int rt_mutex_getprio(struct task_struct *task)
152 {
153         if (likely(!task_has_pi_waiters(task)))
154                 return task->normal_prio;
155
156         return min(task_top_pi_waiter(task)->pi_list_entry.prio,
157                    task->normal_prio);
158 }
159
160 /*
161  * Adjust the priority of a task, after its pi_waiters got modified.
162  *
163  * This can be both boosting and unboosting. task->pi_lock must be held.
164  */
165 static void __rt_mutex_adjust_prio(struct task_struct *task)
166 {
167         int prio = rt_mutex_getprio(task);
168
169         if (task->prio != prio)
170                 rt_mutex_setprio(task, prio);
171 }
172
173 /*
174  * Adjust task priority (undo boosting). Called from the exit path of
175  * rt_mutex_slowunlock() and rt_mutex_slowlock().
176  *
177  * (Note: We do this outside of the protection of lock->wait_lock to
178  * allow the lock to be taken while or before we readjust the priority
179  * of task. We do not use the spin_xx_mutex() variants here as we are
180  * outside of the debug path.)
181  */
182 static void rt_mutex_adjust_prio(struct task_struct *task)
183 {
184         unsigned long flags;
185
186         raw_spin_lock_irqsave(&task->pi_lock, flags);
187         __rt_mutex_adjust_prio(task);
188         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
189 }
190
191 /*
192  * Max number of times we'll walk the boosting chain:
193  */
194 int max_lock_depth = 1024;
195
196 static inline struct rt_mutex *task_blocked_on_lock(struct task_struct *p)
197 {
198         return p->pi_blocked_on ? p->pi_blocked_on->lock : NULL;
199 }
200
201 /*
202  * Adjust the priority chain. Also used for deadlock detection.
203  * Decreases task's usage by one - may thus free the task.
204  *
205  * @task:       the task owning the mutex (owner) for which a chain walk is
206  *              probably needed
207  * @deadlock_detect: do we have to carry out deadlock detection?
208  * @orig_lock:  the mutex (can be NULL if we are walking the chain to recheck
209  *              things for a task that has just got its priority adjusted, and
210  *              is waiting on a mutex)
211  * @next_lock:  the mutex on which the owner of @orig_lock was blocked before
212  *              we dropped its pi_lock. Is never dereferenced, only used for
213  *              comparison to detect lock chain changes.
214  * @orig_waiter: rt_mutex_waiter struct for the task that has just donated
215  *              its priority to the mutex owner (can be NULL in the case
216  *              depicted above or if the top waiter is gone away and we are
217  *              actually deboosting the owner)
218  * @top_task:   the current top waiter
219  *
220  * Returns 0 or -EDEADLK.
221  */
222 static int rt_mutex_adjust_prio_chain(struct task_struct *task,
223                                       int deadlock_detect,
224                                       struct rt_mutex *orig_lock,
225                                       struct rt_mutex *next_lock,
226                                       struct rt_mutex_waiter *orig_waiter,
227                                       struct task_struct *top_task)
228 {
229         struct rt_mutex *lock;
230         struct rt_mutex_waiter *waiter, *top_waiter = orig_waiter;
231         int detect_deadlock, ret = 0, depth = 0;
232         unsigned long flags;
233
234         detect_deadlock = debug_rt_mutex_detect_deadlock(orig_waiter,
235                                                          deadlock_detect);
236
237         /*
238          * The (de)boosting is a step by step approach with a lot of
239          * pitfalls. We want this to be preemptible and we want hold a
240          * maximum of two locks per step. So we have to check
241          * carefully whether things change under us.
242          */
243  again:
244         if (++depth > max_lock_depth) {
245                 static int prev_max;
246
247                 /*
248                  * Print this only once. If the admin changes the limit,
249                  * print a new message when reaching the limit again.
250                  */
251                 if (prev_max != max_lock_depth) {
252                         prev_max = max_lock_depth;
253                         printk(KERN_WARNING "Maximum lock depth %d reached "
254                                "task: %s (%d)\n", max_lock_depth,
255                                top_task->comm, task_pid_nr(top_task));
256                 }
257                 put_task_struct(task);
258
259                 return -EDEADLK;
260         }
261  retry:
262         /*
263          * Task can not go away as we did a get_task() before !
264          */
265         raw_spin_lock_irqsave(&task->pi_lock, flags);
266
267         waiter = task->pi_blocked_on;
268         /*
269          * Check whether the end of the boosting chain has been
270          * reached or the state of the chain has changed while we
271          * dropped the locks.
272          */
273         if (!waiter)
274                 goto out_unlock_pi;
275
276         /*
277          * Check the orig_waiter state. After we dropped the locks,
278          * the previous owner of the lock might have released the lock.
279          */
280         if (orig_waiter && !rt_mutex_owner(orig_lock))
281                 goto out_unlock_pi;
282
283         /*
284          * We dropped all locks after taking a refcount on @task, so
285          * the task might have moved on in the lock chain or even left
286          * the chain completely and blocks now on an unrelated lock or
287          * on @orig_lock.
288          *
289          * We stored the lock on which @task was blocked in @next_lock,
290          * so we can detect the chain change.
291          */
292         if (next_lock != waiter->lock)
293                 goto out_unlock_pi;
294
295         /*
296          * Drop out, when the task has no waiters. Note,
297          * top_waiter can be NULL, when we are in the deboosting
298          * mode!
299          */
300         if (top_waiter) {
301                 if (!task_has_pi_waiters(task))
302                         goto out_unlock_pi;
303                 /*
304                  * If deadlock detection is off, we stop here if we
305                  * are not the top pi waiter of the task.
306                  */
307                 if (!detect_deadlock && top_waiter != task_top_pi_waiter(task))
308                         goto out_unlock_pi;
309         }
310
311         /*
312          * When deadlock detection is off then we check, if further
313          * priority adjustment is necessary.
314          */
315         if (!detect_deadlock && waiter->list_entry.prio == task->prio)
316                 goto out_unlock_pi;
317
318         lock = waiter->lock;
319         if (!raw_spin_trylock(&lock->wait_lock)) {
320                 raw_spin_unlock_irqrestore(&task->pi_lock, flags);
321                 cpu_relax();
322                 goto retry;
323         }
324
325         /*
326          * Deadlock detection. If the lock is the same as the original
327          * lock which caused us to walk the lock chain or if the
328          * current lock is owned by the task which initiated the chain
329          * walk, we detected a deadlock.
330          */
331         if (lock == orig_lock || rt_mutex_owner(lock) == top_task) {
332                 debug_rt_mutex_deadlock(deadlock_detect, orig_waiter, lock);
333                 raw_spin_unlock(&lock->wait_lock);
334                 ret = -EDEADLK;
335                 goto out_unlock_pi;
336         }
337
338         top_waiter = rt_mutex_top_waiter(lock);
339
340         /* Requeue the waiter */
341         plist_del(&waiter->list_entry, &lock->wait_list);
342         waiter->list_entry.prio = task->prio;
343         plist_add(&waiter->list_entry, &lock->wait_list);
344
345         /* Release the task */
346         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
347         if (!rt_mutex_owner(lock)) {
348                 /*
349                  * If the requeue above changed the top waiter, then we need
350                  * to wake the new top waiter up to try to get the lock.
351                  */
352
353                 if (top_waiter != rt_mutex_top_waiter(lock))
354                         wake_up_process(rt_mutex_top_waiter(lock)->task);
355                 raw_spin_unlock(&lock->wait_lock);
356                 goto out_put_task;
357         }
358         put_task_struct(task);
359
360         /* Grab the next task */
361         task = rt_mutex_owner(lock);
362         get_task_struct(task);
363         raw_spin_lock_irqsave(&task->pi_lock, flags);
364
365         if (waiter == rt_mutex_top_waiter(lock)) {
366                 /* Boost the owner */
367                 plist_del(&top_waiter->pi_list_entry, &task->pi_waiters);
368                 waiter->pi_list_entry.prio = waiter->list_entry.prio;
369                 plist_add(&waiter->pi_list_entry, &task->pi_waiters);
370                 __rt_mutex_adjust_prio(task);
371
372         } else if (top_waiter == waiter) {
373                 /* Deboost the owner */
374                 plist_del(&waiter->pi_list_entry, &task->pi_waiters);
375                 waiter = rt_mutex_top_waiter(lock);
376                 waiter->pi_list_entry.prio = waiter->list_entry.prio;
377                 plist_add(&waiter->pi_list_entry, &task->pi_waiters);
378                 __rt_mutex_adjust_prio(task);
379         }
380
381         /*
382          * Check whether the task which owns the current lock is pi
383          * blocked itself. If yes we store a pointer to the lock for
384          * the lock chain change detection above. After we dropped
385          * task->pi_lock next_lock cannot be dereferenced anymore.
386          */
387         next_lock = task_blocked_on_lock(task);
388
389         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
390
391         top_waiter = rt_mutex_top_waiter(lock);
392         raw_spin_unlock(&lock->wait_lock);
393
394         /*
395          * We reached the end of the lock chain. Stop right here. No
396          * point to go back just to figure that out.
397          */
398         if (!next_lock)
399                 goto out_put_task;
400
401         if (!detect_deadlock && waiter != top_waiter)
402                 goto out_put_task;
403
404         goto again;
405
406  out_unlock_pi:
407         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
408  out_put_task:
409         put_task_struct(task);
410
411         return ret;
412 }
413
414 /*
415  * Try to take an rt-mutex
416  *
417  * Must be called with lock->wait_lock held.
418  *
419  * @lock:   the lock to be acquired.
420  * @task:   the task which wants to acquire the lock
421  * @waiter: the waiter that is queued to the lock's wait list. (could be NULL)
422  */
423 static int try_to_take_rt_mutex(struct rt_mutex *lock, struct task_struct *task,
424                 struct rt_mutex_waiter *waiter)
425 {
426         /*
427          * We have to be careful here if the atomic speedups are
428          * enabled, such that, when
429          *  - no other waiter is on the lock
430          *  - the lock has been released since we did the cmpxchg
431          * the lock can be released or taken while we are doing the
432          * checks and marking the lock with RT_MUTEX_HAS_WAITERS.
433          *
434          * The atomic acquire/release aware variant of
435          * mark_rt_mutex_waiters uses a cmpxchg loop. After setting
436          * the WAITERS bit, the atomic release / acquire can not
437          * happen anymore and lock->wait_lock protects us from the
438          * non-atomic case.
439          *
440          * Note, that this might set lock->owner =
441          * RT_MUTEX_HAS_WAITERS in the case the lock is not contended
442          * any more. This is fixed up when we take the ownership.
443          * This is the transitional state explained at the top of this file.
444          */
445         mark_rt_mutex_waiters(lock);
446
447         if (rt_mutex_owner(lock))
448                 return 0;
449
450         /*
451          * It will get the lock because of one of these conditions:
452          * 1) there is no waiter
453          * 2) higher priority than waiters
454          * 3) it is top waiter
455          */
456         if (rt_mutex_has_waiters(lock)) {
457                 if (task->prio >= rt_mutex_top_waiter(lock)->list_entry.prio) {
458                         if (!waiter || waiter != rt_mutex_top_waiter(lock))
459                                 return 0;
460                 }
461         }
462
463         if (waiter || rt_mutex_has_waiters(lock)) {
464                 unsigned long flags;
465                 struct rt_mutex_waiter *top;
466
467                 raw_spin_lock_irqsave(&task->pi_lock, flags);
468
469                 /* remove the queued waiter. */
470                 if (waiter) {
471                         plist_del(&waiter->list_entry, &lock->wait_list);
472                         task->pi_blocked_on = NULL;
473                 }
474
475                 /*
476                  * We have to enqueue the top waiter(if it exists) into
477                  * task->pi_waiters list.
478                  */
479                 if (rt_mutex_has_waiters(lock)) {
480                         top = rt_mutex_top_waiter(lock);
481                         top->pi_list_entry.prio = top->list_entry.prio;
482                         plist_add(&top->pi_list_entry, &task->pi_waiters);
483                 }
484                 raw_spin_unlock_irqrestore(&task->pi_lock, flags);
485         }
486
487         /* We got the lock. */
488         debug_rt_mutex_lock(lock);
489
490         rt_mutex_set_owner(lock, task);
491
492         rt_mutex_deadlock_account_lock(lock, task);
493
494         return 1;
495 }
496
497 /*
498  * Task blocks on lock.
499  *
500  * Prepare waiter and propagate pi chain
501  *
502  * This must be called with lock->wait_lock held.
503  */
504 static int task_blocks_on_rt_mutex(struct rt_mutex *lock,
505                                    struct rt_mutex_waiter *waiter,
506                                    struct task_struct *task,
507                                    int detect_deadlock)
508 {
509         struct task_struct *owner = rt_mutex_owner(lock);
510         struct rt_mutex_waiter *top_waiter = waiter;
511         struct rt_mutex *next_lock;
512         int chain_walk = 0, res;
513         unsigned long flags;
514
515         /*
516          * Early deadlock detection. We really don't want the task to
517          * enqueue on itself just to untangle the mess later. It's not
518          * only an optimization. We drop the locks, so another waiter
519          * can come in before the chain walk detects the deadlock. So
520          * the other will detect the deadlock and return -EDEADLOCK,
521          * which is wrong, as the other waiter is not in a deadlock
522          * situation.
523          */
524         if (owner == task)
525                 return -EDEADLK;
526
527         raw_spin_lock_irqsave(&task->pi_lock, flags);
528         __rt_mutex_adjust_prio(task);
529         waiter->task = task;
530         waiter->lock = lock;
531         plist_node_init(&waiter->list_entry, task->prio);
532         plist_node_init(&waiter->pi_list_entry, task->prio);
533
534         /* Get the top priority waiter on the lock */
535         if (rt_mutex_has_waiters(lock))
536                 top_waiter = rt_mutex_top_waiter(lock);
537         plist_add(&waiter->list_entry, &lock->wait_list);
538
539         task->pi_blocked_on = waiter;
540
541         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
542
543         if (!owner)
544                 return 0;
545
546         raw_spin_lock_irqsave(&owner->pi_lock, flags);
547         if (waiter == rt_mutex_top_waiter(lock)) {
548                 plist_del(&top_waiter->pi_list_entry, &owner->pi_waiters);
549                 plist_add(&waiter->pi_list_entry, &owner->pi_waiters);
550
551                 __rt_mutex_adjust_prio(owner);
552                 if (owner->pi_blocked_on)
553                         chain_walk = 1;
554         } else if (debug_rt_mutex_detect_deadlock(waiter, detect_deadlock)) {
555                 chain_walk = 1;
556         }
557
558         /* Store the lock on which owner is blocked or NULL */
559         next_lock = task_blocked_on_lock(owner);
560
561         raw_spin_unlock_irqrestore(&owner->pi_lock, flags);
562         /*
563          * Even if full deadlock detection is on, if the owner is not
564          * blocked itself, we can avoid finding this out in the chain
565          * walk.
566          */
567         if (!chain_walk || !next_lock)
568                 return 0;
569
570         /*
571          * The owner can't disappear while holding a lock,
572          * so the owner struct is protected by wait_lock.
573          * Gets dropped in rt_mutex_adjust_prio_chain()!
574          */
575         get_task_struct(owner);
576
577         raw_spin_unlock(&lock->wait_lock);
578
579         res = rt_mutex_adjust_prio_chain(owner, detect_deadlock, lock,
580                                          next_lock, waiter, task);
581
582         raw_spin_lock(&lock->wait_lock);
583
584         return res;
585 }
586
587 /*
588  * Wake up the next waiter on the lock.
589  *
590  * Remove the top waiter from the current tasks pi waiter list and
591  * wake it up.
592  *
593  * Called with lock->wait_lock held.
594  */
595 static void wakeup_next_waiter(struct rt_mutex *lock)
596 {
597         struct rt_mutex_waiter *waiter;
598         unsigned long flags;
599
600         raw_spin_lock_irqsave(&current->pi_lock, flags);
601
602         waiter = rt_mutex_top_waiter(lock);
603
604         /*
605          * Remove it from current->pi_waiters. We do not adjust a
606          * possible priority boost right now. We execute wakeup in the
607          * boosted mode and go back to normal after releasing
608          * lock->wait_lock.
609          */
610         plist_del(&waiter->pi_list_entry, &current->pi_waiters);
611
612         /*
613          * As we are waking up the top waiter, and the waiter stays
614          * queued on the lock until it gets the lock, this lock
615          * obviously has waiters. Just set the bit here and this has
616          * the added benefit of forcing all new tasks into the
617          * slow path making sure no task of lower priority than
618          * the top waiter can steal this lock.
619          */
620         lock->owner = (void *) RT_MUTEX_HAS_WAITERS;
621
622         raw_spin_unlock_irqrestore(&current->pi_lock, flags);
623
624         /*
625          * It's safe to dereference waiter as it cannot go away as
626          * long as we hold lock->wait_lock. The waiter task needs to
627          * acquire it in order to dequeue the waiter.
628          */
629         wake_up_process(waiter->task);
630 }
631
632 /*
633  * Remove a waiter from a lock and give up
634  *
635  * Must be called with lock->wait_lock held and
636  * have just failed to try_to_take_rt_mutex().
637  */
638 static void remove_waiter(struct rt_mutex *lock,
639                           struct rt_mutex_waiter *waiter)
640 {
641         int first = (waiter == rt_mutex_top_waiter(lock));
642         struct task_struct *owner = rt_mutex_owner(lock);
643         struct rt_mutex *next_lock = NULL;
644         unsigned long flags;
645
646         raw_spin_lock_irqsave(&current->pi_lock, flags);
647         plist_del(&waiter->list_entry, &lock->wait_list);
648         current->pi_blocked_on = NULL;
649         raw_spin_unlock_irqrestore(&current->pi_lock, flags);
650
651         if (!owner)
652                 return;
653
654         if (first) {
655
656                 raw_spin_lock_irqsave(&owner->pi_lock, flags);
657
658                 plist_del(&waiter->pi_list_entry, &owner->pi_waiters);
659
660                 if (rt_mutex_has_waiters(lock)) {
661                         struct rt_mutex_waiter *next;
662
663                         next = rt_mutex_top_waiter(lock);
664                         plist_add(&next->pi_list_entry, &owner->pi_waiters);
665                 }
666                 __rt_mutex_adjust_prio(owner);
667
668                 /* Store the lock on which owner is blocked or NULL */
669                 next_lock = task_blocked_on_lock(owner);
670
671                 raw_spin_unlock_irqrestore(&owner->pi_lock, flags);
672         }
673
674         WARN_ON(!plist_node_empty(&waiter->pi_list_entry));
675
676         if (!next_lock)
677                 return;
678
679         /* gets dropped in rt_mutex_adjust_prio_chain()! */
680         get_task_struct(owner);
681
682         raw_spin_unlock(&lock->wait_lock);
683
684         rt_mutex_adjust_prio_chain(owner, 0, lock, next_lock, NULL, current);
685
686         raw_spin_lock(&lock->wait_lock);
687 }
688
689 /*
690  * Recheck the pi chain, in case we got a priority setting
691  *
692  * Called from sched_setscheduler
693  */
694 void rt_mutex_adjust_pi(struct task_struct *task)
695 {
696         struct rt_mutex_waiter *waiter;
697         struct rt_mutex *next_lock;
698         unsigned long flags;
699
700         raw_spin_lock_irqsave(&task->pi_lock, flags);
701
702         waiter = task->pi_blocked_on;
703         if (!waiter || waiter->list_entry.prio == task->prio) {
704                 raw_spin_unlock_irqrestore(&task->pi_lock, flags);
705                 return;
706         }
707         next_lock = waiter->lock;
708         raw_spin_unlock_irqrestore(&task->pi_lock, flags);
709
710         /* gets dropped in rt_mutex_adjust_prio_chain()! */
711         get_task_struct(task);
712
713         rt_mutex_adjust_prio_chain(task, 0, NULL, next_lock, NULL, task);
714 }
715
716 /**
717  * __rt_mutex_slowlock() - Perform the wait-wake-try-to-take loop
718  * @lock:                the rt_mutex to take
719  * @state:               the state the task should block in (TASK_INTERRUPTIBLE
720  *                       or TASK_UNINTERRUPTIBLE)
721  * @timeout:             the pre-initialized and started timer, or NULL for none
722  * @waiter:              the pre-initialized rt_mutex_waiter
723  *
724  * lock->wait_lock must be held by the caller.
725  */
726 static int __sched
727 __rt_mutex_slowlock(struct rt_mutex *lock, int state,
728                     struct hrtimer_sleeper *timeout,
729                     struct rt_mutex_waiter *waiter)
730 {
731         int ret = 0;
732         int was_disabled;
733
734         for (;;) {
735                 /* Try to acquire the lock: */
736                 if (try_to_take_rt_mutex(lock, current, waiter))
737                         break;
738
739                 /*
740                  * TASK_INTERRUPTIBLE checks for signals and
741                  * timeout. Ignored otherwise.
742                  */
743                 if (unlikely(state == TASK_INTERRUPTIBLE)) {
744                         /* Signal pending? */
745                         if (signal_pending(current))
746                                 ret = -EINTR;
747                         if (timeout && !timeout->task)
748                                 ret = -ETIMEDOUT;
749                         if (ret)
750                                 break;
751                 }
752
753                 raw_spin_unlock(&lock->wait_lock);
754
755                 was_disabled = irqs_disabled();
756                 if (was_disabled)
757                         local_irq_enable();
758
759                 debug_rt_mutex_print_deadlock(waiter);
760
761                 schedule_rt_mutex(lock);
762
763                 if (was_disabled)
764                         local_irq_disable();
765
766                 raw_spin_lock(&lock->wait_lock);
767                 set_current_state(state);
768         }
769
770         return ret;
771 }
772
773 static void rt_mutex_handle_deadlock(int res, int detect_deadlock,
774                                      struct rt_mutex_waiter *w)
775 {
776         /*
777          * If the result is not -EDEADLOCK or the caller requested
778          * deadlock detection, nothing to do here.
779          */
780         if (res != -EDEADLOCK || detect_deadlock)
781                 return;
782
783         /*
784          * Yell lowdly and stop the task right here.
785          */
786         rt_mutex_print_deadlock(w);
787         while (1) {
788                 set_current_state(TASK_INTERRUPTIBLE);
789                 schedule();
790         }
791 }
792
793 /*
794  * Slow path lock function:
795  */
796 static int __sched
797 rt_mutex_slowlock(struct rt_mutex *lock, int state,
798                   struct hrtimer_sleeper *timeout,
799                   int detect_deadlock)
800 {
801         struct rt_mutex_waiter waiter;
802         int ret = 0;
803
804         debug_rt_mutex_init_waiter(&waiter);
805
806         raw_spin_lock(&lock->wait_lock);
807
808         /* Try to acquire the lock again: */
809         if (try_to_take_rt_mutex(lock, current, NULL)) {
810                 raw_spin_unlock(&lock->wait_lock);
811                 return 0;
812         }
813
814         set_current_state(state);
815
816         /* Setup the timer, when timeout != NULL */
817         if (unlikely(timeout)) {
818                 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
819                 if (!hrtimer_active(&timeout->timer))
820                         timeout->task = NULL;
821         }
822
823         ret = task_blocks_on_rt_mutex(lock, &waiter, current, detect_deadlock);
824
825         if (likely(!ret))
826                 ret = __rt_mutex_slowlock(lock, state, timeout, &waiter);
827
828         set_current_state(TASK_RUNNING);
829
830         if (unlikely(ret)) {
831                 remove_waiter(lock, &waiter);
832                 rt_mutex_handle_deadlock(ret, detect_deadlock, &waiter);
833         }
834
835         /*
836          * try_to_take_rt_mutex() sets the waiter bit
837          * unconditionally. We might have to fix that up.
838          */
839         fixup_rt_mutex_waiters(lock);
840
841         raw_spin_unlock(&lock->wait_lock);
842
843         /* Remove pending timer: */
844         if (unlikely(timeout))
845                 hrtimer_cancel(&timeout->timer);
846
847         debug_rt_mutex_free_waiter(&waiter);
848
849         return ret;
850 }
851
852 /*
853  * Slow path try-lock function:
854  */
855 static inline int
856 rt_mutex_slowtrylock(struct rt_mutex *lock)
857 {
858         int ret = 0;
859
860         raw_spin_lock(&lock->wait_lock);
861
862         if (likely(rt_mutex_owner(lock) != current)) {
863
864                 ret = try_to_take_rt_mutex(lock, current, NULL);
865                 /*
866                  * try_to_take_rt_mutex() sets the lock waiters
867                  * bit unconditionally. Clean this up.
868                  */
869                 fixup_rt_mutex_waiters(lock);
870         }
871
872         raw_spin_unlock(&lock->wait_lock);
873
874         return ret;
875 }
876
877 /*
878  * Slow path to release a rt-mutex:
879  */
880 static void __sched
881 rt_mutex_slowunlock(struct rt_mutex *lock)
882 {
883         raw_spin_lock(&lock->wait_lock);
884
885         debug_rt_mutex_unlock(lock);
886
887         rt_mutex_deadlock_account_unlock(current);
888
889         /*
890          * We must be careful here if the fast path is enabled. If we
891          * have no waiters queued we cannot set owner to NULL here
892          * because of:
893          *
894          * foo->lock->owner = NULL;
895          *                      rtmutex_lock(foo->lock);   <- fast path
896          *                      free = atomic_dec_and_test(foo->refcnt);
897          *                      rtmutex_unlock(foo->lock); <- fast path
898          *                      if (free)
899          *                              kfree(foo);
900          * raw_spin_unlock(foo->lock->wait_lock);
901          *
902          * So for the fastpath enabled kernel:
903          *
904          * Nothing can set the waiters bit as long as we hold
905          * lock->wait_lock. So we do the following sequence:
906          *
907          *      owner = rt_mutex_owner(lock);
908          *      clear_rt_mutex_waiters(lock);
909          *      raw_spin_unlock(&lock->wait_lock);
910          *      if (cmpxchg(&lock->owner, owner, 0) == owner)
911          *              return;
912          *      goto retry;
913          *
914          * The fastpath disabled variant is simple as all access to
915          * lock->owner is serialized by lock->wait_lock:
916          *
917          *      lock->owner = NULL;
918          *      raw_spin_unlock(&lock->wait_lock);
919          */
920         while (!rt_mutex_has_waiters(lock)) {
921                 /* Drops lock->wait_lock ! */
922                 if (unlock_rt_mutex_safe(lock) == true)
923                         return;
924                 /* Relock the rtmutex and try again */
925                 raw_spin_lock(&lock->wait_lock);
926         }
927
928         /*
929          * The wakeup next waiter path does not suffer from the above
930          * race. See the comments there.
931          */
932         wakeup_next_waiter(lock);
933
934         raw_spin_unlock(&lock->wait_lock);
935
936         /* Undo pi boosting if necessary: */
937         rt_mutex_adjust_prio(current);
938 }
939
940 /*
941  * debug aware fast / slowpath lock,trylock,unlock
942  *
943  * The atomic acquire/release ops are compiled away, when either the
944  * architecture does not support cmpxchg or when debugging is enabled.
945  */
946 static inline int
947 rt_mutex_fastlock(struct rt_mutex *lock, int state,
948                   int detect_deadlock,
949                   int (*slowfn)(struct rt_mutex *lock, int state,
950                                 struct hrtimer_sleeper *timeout,
951                                 int detect_deadlock))
952 {
953         if (!detect_deadlock && likely(rt_mutex_cmpxchg(lock, NULL, current))) {
954                 rt_mutex_deadlock_account_lock(lock, current);
955                 return 0;
956         } else
957                 return slowfn(lock, state, NULL, detect_deadlock);
958 }
959
960 static inline int
961 rt_mutex_timed_fastlock(struct rt_mutex *lock, int state,
962                         struct hrtimer_sleeper *timeout, int detect_deadlock,
963                         int (*slowfn)(struct rt_mutex *lock, int state,
964                                       struct hrtimer_sleeper *timeout,
965                                       int detect_deadlock))
966 {
967         if (!detect_deadlock && likely(rt_mutex_cmpxchg(lock, NULL, current))) {
968                 rt_mutex_deadlock_account_lock(lock, current);
969                 return 0;
970         } else
971                 return slowfn(lock, state, timeout, detect_deadlock);
972 }
973
974 static inline int
975 rt_mutex_fasttrylock(struct rt_mutex *lock,
976                      int (*slowfn)(struct rt_mutex *lock))
977 {
978         if (likely(rt_mutex_cmpxchg(lock, NULL, current))) {
979                 rt_mutex_deadlock_account_lock(lock, current);
980                 return 1;
981         }
982         return slowfn(lock);
983 }
984
985 static inline void
986 rt_mutex_fastunlock(struct rt_mutex *lock,
987                     void (*slowfn)(struct rt_mutex *lock))
988 {
989         if (likely(rt_mutex_cmpxchg(lock, current, NULL)))
990                 rt_mutex_deadlock_account_unlock(current);
991         else
992                 slowfn(lock);
993 }
994
995 /**
996  * rt_mutex_lock - lock a rt_mutex
997  *
998  * @lock: the rt_mutex to be locked
999  */
1000 void __sched rt_mutex_lock(struct rt_mutex *lock)
1001 {
1002         might_sleep();
1003
1004         rt_mutex_fastlock(lock, TASK_UNINTERRUPTIBLE, 0, rt_mutex_slowlock);
1005 }
1006 EXPORT_SYMBOL_GPL(rt_mutex_lock);
1007
1008 /**
1009  * rt_mutex_lock_interruptible - lock a rt_mutex interruptible
1010  *
1011  * @lock:               the rt_mutex to be locked
1012  * @detect_deadlock:    deadlock detection on/off
1013  *
1014  * Returns:
1015  *  0           on success
1016  * -EINTR       when interrupted by a signal
1017  * -EDEADLK     when the lock would deadlock (when deadlock detection is on)
1018  */
1019 int __sched rt_mutex_lock_interruptible(struct rt_mutex *lock,
1020                                                  int detect_deadlock)
1021 {
1022         might_sleep();
1023
1024         return rt_mutex_fastlock(lock, TASK_INTERRUPTIBLE,
1025                                  detect_deadlock, rt_mutex_slowlock);
1026 }
1027 EXPORT_SYMBOL_GPL(rt_mutex_lock_interruptible);
1028
1029 /**
1030  * rt_mutex_timed_lock - lock a rt_mutex interruptible
1031  *                      the timeout structure is provided
1032  *                      by the caller
1033  *
1034  * @lock:               the rt_mutex to be locked
1035  * @timeout:            timeout structure or NULL (no timeout)
1036  * @detect_deadlock:    deadlock detection on/off
1037  *
1038  * Returns:
1039  *  0           on success
1040  * -EINTR       when interrupted by a signal
1041  * -ETIMEDOUT   when the timeout expired
1042  * -EDEADLK     when the lock would deadlock (when deadlock detection is on)
1043  */
1044 int
1045 rt_mutex_timed_lock(struct rt_mutex *lock, struct hrtimer_sleeper *timeout,
1046                     int detect_deadlock)
1047 {
1048         might_sleep();
1049
1050         return rt_mutex_timed_fastlock(lock, TASK_INTERRUPTIBLE, timeout,
1051                                        detect_deadlock, rt_mutex_slowlock);
1052 }
1053 EXPORT_SYMBOL_GPL(rt_mutex_timed_lock);
1054
1055 /**
1056  * rt_mutex_trylock - try to lock a rt_mutex
1057  *
1058  * @lock:       the rt_mutex to be locked
1059  *
1060  * Returns 1 on success and 0 on contention
1061  */
1062 int __sched rt_mutex_trylock(struct rt_mutex *lock)
1063 {
1064         return rt_mutex_fasttrylock(lock, rt_mutex_slowtrylock);
1065 }
1066 EXPORT_SYMBOL_GPL(rt_mutex_trylock);
1067
1068 /**
1069  * rt_mutex_unlock - unlock a rt_mutex
1070  *
1071  * @lock: the rt_mutex to be unlocked
1072  */
1073 void __sched rt_mutex_unlock(struct rt_mutex *lock)
1074 {
1075         rt_mutex_fastunlock(lock, rt_mutex_slowunlock);
1076 }
1077 EXPORT_SYMBOL_GPL(rt_mutex_unlock);
1078
1079 /**
1080  * rt_mutex_destroy - mark a mutex unusable
1081  * @lock: the mutex to be destroyed
1082  *
1083  * This function marks the mutex uninitialized, and any subsequent
1084  * use of the mutex is forbidden. The mutex must not be locked when
1085  * this function is called.
1086  */
1087 void rt_mutex_destroy(struct rt_mutex *lock)
1088 {
1089         WARN_ON(rt_mutex_is_locked(lock));
1090 #ifdef CONFIG_DEBUG_RT_MUTEXES
1091         lock->magic = NULL;
1092 #endif
1093 }
1094
1095 EXPORT_SYMBOL_GPL(rt_mutex_destroy);
1096
1097 /**
1098  * __rt_mutex_init - initialize the rt lock
1099  *
1100  * @lock: the rt lock to be initialized
1101  *
1102  * Initialize the rt lock to unlocked state.
1103  *
1104  * Initializing of a locked rt lock is not allowed
1105  */
1106 void __rt_mutex_init(struct rt_mutex *lock, const char *name)
1107 {
1108         lock->owner = NULL;
1109         raw_spin_lock_init(&lock->wait_lock);
1110         plist_head_init(&lock->wait_list);
1111
1112         debug_rt_mutex_init(lock, name);
1113 }
1114 EXPORT_SYMBOL_GPL(__rt_mutex_init);
1115
1116 /**
1117  * rt_mutex_init_proxy_locked - initialize and lock a rt_mutex on behalf of a
1118  *                              proxy owner
1119  *
1120  * @lock:       the rt_mutex to be locked
1121  * @proxy_owner:the task to set as owner
1122  *
1123  * No locking. Caller has to do serializing itself
1124  * Special API call for PI-futex support
1125  */
1126 void rt_mutex_init_proxy_locked(struct rt_mutex *lock,
1127                                 struct task_struct *proxy_owner)
1128 {
1129         __rt_mutex_init(lock, NULL);
1130         debug_rt_mutex_proxy_lock(lock, proxy_owner);
1131         rt_mutex_set_owner(lock, proxy_owner);
1132         rt_mutex_deadlock_account_lock(lock, proxy_owner);
1133 }
1134
1135 /**
1136  * rt_mutex_proxy_unlock - release a lock on behalf of owner
1137  *
1138  * @lock:       the rt_mutex to be locked
1139  *
1140  * No locking. Caller has to do serializing itself
1141  * Special API call for PI-futex support
1142  */
1143 void rt_mutex_proxy_unlock(struct rt_mutex *lock,
1144                            struct task_struct *proxy_owner)
1145 {
1146         debug_rt_mutex_proxy_unlock(lock);
1147         rt_mutex_set_owner(lock, NULL);
1148         rt_mutex_deadlock_account_unlock(proxy_owner);
1149 }
1150
1151 /**
1152  * rt_mutex_start_proxy_lock() - Start lock acquisition for another task
1153  * @lock:               the rt_mutex to take
1154  * @waiter:             the pre-initialized rt_mutex_waiter
1155  * @task:               the task to prepare
1156  * @detect_deadlock:    perform deadlock detection (1) or not (0)
1157  *
1158  * Returns:
1159  *  0 - task blocked on lock
1160  *  1 - acquired the lock for task, caller should wake it up
1161  * <0 - error
1162  *
1163  * Special API call for FUTEX_REQUEUE_PI support.
1164  */
1165 int rt_mutex_start_proxy_lock(struct rt_mutex *lock,
1166                               struct rt_mutex_waiter *waiter,
1167                               struct task_struct *task, int detect_deadlock)
1168 {
1169         int ret;
1170
1171         raw_spin_lock(&lock->wait_lock);
1172
1173         if (try_to_take_rt_mutex(lock, task, NULL)) {
1174                 raw_spin_unlock(&lock->wait_lock);
1175                 return 1;
1176         }
1177
1178         /* We enforce deadlock detection for futexes */
1179         ret = task_blocks_on_rt_mutex(lock, waiter, task, 1);
1180
1181         if (ret && !rt_mutex_owner(lock)) {
1182                 /*
1183                  * Reset the return value. We might have
1184                  * returned with -EDEADLK and the owner
1185                  * released the lock while we were walking the
1186                  * pi chain.  Let the waiter sort it out.
1187                  */
1188                 ret = 0;
1189         }
1190
1191         if (unlikely(ret))
1192                 remove_waiter(lock, waiter);
1193
1194         raw_spin_unlock(&lock->wait_lock);
1195
1196         debug_rt_mutex_print_deadlock(waiter);
1197
1198         return ret;
1199 }
1200
1201 /**
1202  * rt_mutex_next_owner - return the next owner of the lock
1203  *
1204  * @lock: the rt lock query
1205  *
1206  * Returns the next owner of the lock or NULL
1207  *
1208  * Caller has to serialize against other accessors to the lock
1209  * itself.
1210  *
1211  * Special API call for PI-futex support
1212  */
1213 struct task_struct *rt_mutex_next_owner(struct rt_mutex *lock)
1214 {
1215         if (!rt_mutex_has_waiters(lock))
1216                 return NULL;
1217
1218         return rt_mutex_top_waiter(lock)->task;
1219 }
1220
1221 /**
1222  * rt_mutex_finish_proxy_lock() - Complete lock acquisition
1223  * @lock:               the rt_mutex we were woken on
1224  * @to:                 the timeout, null if none. hrtimer should already have
1225  *                      been started.
1226  * @waiter:             the pre-initialized rt_mutex_waiter
1227  * @detect_deadlock:    perform deadlock detection (1) or not (0)
1228  *
1229  * Complete the lock acquisition started our behalf by another thread.
1230  *
1231  * Returns:
1232  *  0 - success
1233  * <0 - error, one of -EINTR, -ETIMEDOUT, or -EDEADLK
1234  *
1235  * Special API call for PI-futex requeue support
1236  */
1237 int rt_mutex_finish_proxy_lock(struct rt_mutex *lock,
1238                                struct hrtimer_sleeper *to,
1239                                struct rt_mutex_waiter *waiter,
1240                                int detect_deadlock)
1241 {
1242         int ret;
1243
1244         raw_spin_lock(&lock->wait_lock);
1245
1246         set_current_state(TASK_INTERRUPTIBLE);
1247
1248         ret = __rt_mutex_slowlock(lock, TASK_INTERRUPTIBLE, to, waiter);
1249
1250         set_current_state(TASK_RUNNING);
1251
1252         if (unlikely(ret))
1253                 remove_waiter(lock, waiter);
1254
1255         /*
1256          * try_to_take_rt_mutex() sets the waiter bit unconditionally. We might
1257          * have to fix that up.
1258          */
1259         fixup_rt_mutex_waiters(lock);
1260
1261         raw_spin_unlock(&lock->wait_lock);
1262
1263         return ret;
1264 }