Merge git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb-2.6
[linux-2.6] / kernel / futex.c
1 /*
2  *  Fast Userspace Mutexes (which I call "Futexes!").
3  *  (C) Rusty Russell, IBM 2002
4  *
5  *  Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
6  *  (C) Copyright 2003 Red Hat Inc, All Rights Reserved
7  *
8  *  Removed page pinning, fix privately mapped COW pages and other cleanups
9  *  (C) Copyright 2003, 2004 Jamie Lokier
10  *
11  *  Robust futex support started by Ingo Molnar
12  *  (C) Copyright 2006 Red Hat Inc, All Rights Reserved
13  *  Thanks to Thomas Gleixner for suggestions, analysis and fixes.
14  *
15  *  PI-futex support started by Ingo Molnar and Thomas Gleixner
16  *  Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
17  *  Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
18  *
19  *  PRIVATE futexes by Eric Dumazet
20  *  Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
21  *
22  *  Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
23  *  Copyright (C) IBM Corporation, 2009
24  *  Thanks to Thomas Gleixner for conceptual design and careful reviews.
25  *
26  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
27  *  enough at me, Linus for the original (flawed) idea, Matthew
28  *  Kirkwood for proof-of-concept implementation.
29  *
30  *  "The futexes are also cursed."
31  *  "But they come in a choice of three flavours!"
32  *
33  *  This program is free software; you can redistribute it and/or modify
34  *  it under the terms of the GNU General Public License as published by
35  *  the Free Software Foundation; either version 2 of the License, or
36  *  (at your option) any later version.
37  *
38  *  This program is distributed in the hope that it will be useful,
39  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
40  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41  *  GNU General Public License for more details.
42  *
43  *  You should have received a copy of the GNU General Public License
44  *  along with this program; if not, write to the Free Software
45  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
46  */
47 #include <linux/slab.h>
48 #include <linux/poll.h>
49 #include <linux/fs.h>
50 #include <linux/file.h>
51 #include <linux/jhash.h>
52 #include <linux/init.h>
53 #include <linux/futex.h>
54 #include <linux/mount.h>
55 #include <linux/pagemap.h>
56 #include <linux/syscalls.h>
57 #include <linux/signal.h>
58 #include <linux/module.h>
59 #include <linux/magic.h>
60 #include <linux/pid.h>
61 #include <linux/nsproxy.h>
62
63 #include <asm/futex.h>
64
65 #include "rtmutex_common.h"
66
67 int __read_mostly futex_cmpxchg_enabled;
68
69 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
70
71 /*
72  * Priority Inheritance state:
73  */
74 struct futex_pi_state {
75         /*
76          * list of 'owned' pi_state instances - these have to be
77          * cleaned up in do_exit() if the task exits prematurely:
78          */
79         struct list_head list;
80
81         /*
82          * The PI object:
83          */
84         struct rt_mutex pi_mutex;
85
86         struct task_struct *owner;
87         atomic_t refcount;
88
89         union futex_key key;
90 };
91
92 /*
93  * We use this hashed waitqueue instead of a normal wait_queue_t, so
94  * we can wake only the relevant ones (hashed queues may be shared).
95  *
96  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
97  * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
98  * The order of wakup is always to make the first condition true, then
99  * wake up q->waiter, then make the second condition true.
100  */
101 struct futex_q {
102         struct plist_node list;
103         /* Waiter reference */
104         struct task_struct *task;
105
106         /* Which hash list lock to use: */
107         spinlock_t *lock_ptr;
108
109         /* Key which the futex is hashed on: */
110         union futex_key key;
111
112         /* Optional priority inheritance state: */
113         struct futex_pi_state *pi_state;
114
115         /* rt_waiter storage for requeue_pi: */
116         struct rt_mutex_waiter *rt_waiter;
117
118         /* Bitset for the optional bitmasked wakeup */
119         u32 bitset;
120 };
121
122 /*
123  * Hash buckets are shared by all the futex_keys that hash to the same
124  * location.  Each key may have multiple futex_q structures, one for each task
125  * waiting on a futex.
126  */
127 struct futex_hash_bucket {
128         spinlock_t lock;
129         struct plist_head chain;
130 };
131
132 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
133
134 /*
135  * We hash on the keys returned from get_futex_key (see below).
136  */
137 static struct futex_hash_bucket *hash_futex(union futex_key *key)
138 {
139         u32 hash = jhash2((u32*)&key->both.word,
140                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
141                           key->both.offset);
142         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
143 }
144
145 /*
146  * Return 1 if two futex_keys are equal, 0 otherwise.
147  */
148 static inline int match_futex(union futex_key *key1, union futex_key *key2)
149 {
150         return (key1->both.word == key2->both.word
151                 && key1->both.ptr == key2->both.ptr
152                 && key1->both.offset == key2->both.offset);
153 }
154
155 /*
156  * Take a reference to the resource addressed by a key.
157  * Can be called while holding spinlocks.
158  *
159  */
160 static void get_futex_key_refs(union futex_key *key)
161 {
162         if (!key->both.ptr)
163                 return;
164
165         switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
166         case FUT_OFF_INODE:
167                 atomic_inc(&key->shared.inode->i_count);
168                 break;
169         case FUT_OFF_MMSHARED:
170                 atomic_inc(&key->private.mm->mm_count);
171                 break;
172         }
173 }
174
175 /*
176  * Drop a reference to the resource addressed by a key.
177  * The hash bucket spinlock must not be held.
178  */
179 static void drop_futex_key_refs(union futex_key *key)
180 {
181         if (!key->both.ptr) {
182                 /* If we're here then we tried to put a key we failed to get */
183                 WARN_ON_ONCE(1);
184                 return;
185         }
186
187         switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
188         case FUT_OFF_INODE:
189                 iput(key->shared.inode);
190                 break;
191         case FUT_OFF_MMSHARED:
192                 mmdrop(key->private.mm);
193                 break;
194         }
195 }
196
197 /**
198  * get_futex_key - Get parameters which are the keys for a futex.
199  * @uaddr: virtual address of the futex
200  * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
201  * @key: address where result is stored.
202  * @rw: mapping needs to be read/write (values: VERIFY_READ, VERIFY_WRITE)
203  *
204  * Returns a negative error code or 0
205  * The key words are stored in *key on success.
206  *
207  * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
208  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
209  * We can usually work out the index without swapping in the page.
210  *
211  * lock_page() might sleep, the caller should not hold a spinlock.
212  */
213 static int
214 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
215 {
216         unsigned long address = (unsigned long)uaddr;
217         struct mm_struct *mm = current->mm;
218         struct page *page;
219         int err;
220
221         /*
222          * The futex address must be "naturally" aligned.
223          */
224         key->both.offset = address % PAGE_SIZE;
225         if (unlikely((address % sizeof(u32)) != 0))
226                 return -EINVAL;
227         address -= key->both.offset;
228
229         /*
230          * PROCESS_PRIVATE futexes are fast.
231          * As the mm cannot disappear under us and the 'key' only needs
232          * virtual address, we dont even have to find the underlying vma.
233          * Note : We do have to check 'uaddr' is a valid user address,
234          *        but access_ok() should be faster than find_vma()
235          */
236         if (!fshared) {
237                 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
238                         return -EFAULT;
239                 key->private.mm = mm;
240                 key->private.address = address;
241                 get_futex_key_refs(key);
242                 return 0;
243         }
244
245 again:
246         err = get_user_pages_fast(address, 1, rw == VERIFY_WRITE, &page);
247         if (err < 0)
248                 return err;
249
250         lock_page(page);
251         if (!page->mapping) {
252                 unlock_page(page);
253                 put_page(page);
254                 goto again;
255         }
256
257         /*
258          * Private mappings are handled in a simple way.
259          *
260          * NOTE: When userspace waits on a MAP_SHARED mapping, even if
261          * it's a read-only handle, it's expected that futexes attach to
262          * the object not the particular process.
263          */
264         if (PageAnon(page)) {
265                 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
266                 key->private.mm = mm;
267                 key->private.address = address;
268         } else {
269                 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
270                 key->shared.inode = page->mapping->host;
271                 key->shared.pgoff = page->index;
272         }
273
274         get_futex_key_refs(key);
275
276         unlock_page(page);
277         put_page(page);
278         return 0;
279 }
280
281 static inline
282 void put_futex_key(int fshared, union futex_key *key)
283 {
284         drop_futex_key_refs(key);
285 }
286
287 /*
288  * fault_in_user_writeable - fault in user address and verify RW access
289  * @uaddr:      pointer to faulting user space address
290  *
291  * Slow path to fixup the fault we just took in the atomic write
292  * access to @uaddr.
293  *
294  * We have no generic implementation of a non destructive write to the
295  * user address. We know that we faulted in the atomic pagefault
296  * disabled section so we can as well avoid the #PF overhead by
297  * calling get_user_pages() right away.
298  */
299 static int fault_in_user_writeable(u32 __user *uaddr)
300 {
301         int ret = get_user_pages(current, current->mm, (unsigned long)uaddr,
302                                  1, 1, 0, NULL, NULL);
303         return ret < 0 ? ret : 0;
304 }
305
306 /**
307  * futex_top_waiter() - Return the highest priority waiter on a futex
308  * @hb:     the hash bucket the futex_q's reside in
309  * @key:    the futex key (to distinguish it from other futex futex_q's)
310  *
311  * Must be called with the hb lock held.
312  */
313 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
314                                         union futex_key *key)
315 {
316         struct futex_q *this;
317
318         plist_for_each_entry(this, &hb->chain, list) {
319                 if (match_futex(&this->key, key))
320                         return this;
321         }
322         return NULL;
323 }
324
325 static u32 cmpxchg_futex_value_locked(u32 __user *uaddr, u32 uval, u32 newval)
326 {
327         u32 curval;
328
329         pagefault_disable();
330         curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
331         pagefault_enable();
332
333         return curval;
334 }
335
336 static int get_futex_value_locked(u32 *dest, u32 __user *from)
337 {
338         int ret;
339
340         pagefault_disable();
341         ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
342         pagefault_enable();
343
344         return ret ? -EFAULT : 0;
345 }
346
347
348 /*
349  * PI code:
350  */
351 static int refill_pi_state_cache(void)
352 {
353         struct futex_pi_state *pi_state;
354
355         if (likely(current->pi_state_cache))
356                 return 0;
357
358         pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
359
360         if (!pi_state)
361                 return -ENOMEM;
362
363         INIT_LIST_HEAD(&pi_state->list);
364         /* pi_mutex gets initialized later */
365         pi_state->owner = NULL;
366         atomic_set(&pi_state->refcount, 1);
367         pi_state->key = FUTEX_KEY_INIT;
368
369         current->pi_state_cache = pi_state;
370
371         return 0;
372 }
373
374 static struct futex_pi_state * alloc_pi_state(void)
375 {
376         struct futex_pi_state *pi_state = current->pi_state_cache;
377
378         WARN_ON(!pi_state);
379         current->pi_state_cache = NULL;
380
381         return pi_state;
382 }
383
384 static void free_pi_state(struct futex_pi_state *pi_state)
385 {
386         if (!atomic_dec_and_test(&pi_state->refcount))
387                 return;
388
389         /*
390          * If pi_state->owner is NULL, the owner is most probably dying
391          * and has cleaned up the pi_state already
392          */
393         if (pi_state->owner) {
394                 spin_lock_irq(&pi_state->owner->pi_lock);
395                 list_del_init(&pi_state->list);
396                 spin_unlock_irq(&pi_state->owner->pi_lock);
397
398                 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
399         }
400
401         if (current->pi_state_cache)
402                 kfree(pi_state);
403         else {
404                 /*
405                  * pi_state->list is already empty.
406                  * clear pi_state->owner.
407                  * refcount is at 0 - put it back to 1.
408                  */
409                 pi_state->owner = NULL;
410                 atomic_set(&pi_state->refcount, 1);
411                 current->pi_state_cache = pi_state;
412         }
413 }
414
415 /*
416  * Look up the task based on what TID userspace gave us.
417  * We dont trust it.
418  */
419 static struct task_struct * futex_find_get_task(pid_t pid)
420 {
421         struct task_struct *p;
422         const struct cred *cred = current_cred(), *pcred;
423
424         rcu_read_lock();
425         p = find_task_by_vpid(pid);
426         if (!p) {
427                 p = ERR_PTR(-ESRCH);
428         } else {
429                 pcred = __task_cred(p);
430                 if (cred->euid != pcred->euid &&
431                     cred->euid != pcred->uid)
432                         p = ERR_PTR(-ESRCH);
433                 else
434                         get_task_struct(p);
435         }
436
437         rcu_read_unlock();
438
439         return p;
440 }
441
442 /*
443  * This task is holding PI mutexes at exit time => bad.
444  * Kernel cleans up PI-state, but userspace is likely hosed.
445  * (Robust-futex cleanup is separate and might save the day for userspace.)
446  */
447 void exit_pi_state_list(struct task_struct *curr)
448 {
449         struct list_head *next, *head = &curr->pi_state_list;
450         struct futex_pi_state *pi_state;
451         struct futex_hash_bucket *hb;
452         union futex_key key = FUTEX_KEY_INIT;
453
454         if (!futex_cmpxchg_enabled)
455                 return;
456         /*
457          * We are a ZOMBIE and nobody can enqueue itself on
458          * pi_state_list anymore, but we have to be careful
459          * versus waiters unqueueing themselves:
460          */
461         spin_lock_irq(&curr->pi_lock);
462         while (!list_empty(head)) {
463
464                 next = head->next;
465                 pi_state = list_entry(next, struct futex_pi_state, list);
466                 key = pi_state->key;
467                 hb = hash_futex(&key);
468                 spin_unlock_irq(&curr->pi_lock);
469
470                 spin_lock(&hb->lock);
471
472                 spin_lock_irq(&curr->pi_lock);
473                 /*
474                  * We dropped the pi-lock, so re-check whether this
475                  * task still owns the PI-state:
476                  */
477                 if (head->next != next) {
478                         spin_unlock(&hb->lock);
479                         continue;
480                 }
481
482                 WARN_ON(pi_state->owner != curr);
483                 WARN_ON(list_empty(&pi_state->list));
484                 list_del_init(&pi_state->list);
485                 pi_state->owner = NULL;
486                 spin_unlock_irq(&curr->pi_lock);
487
488                 rt_mutex_unlock(&pi_state->pi_mutex);
489
490                 spin_unlock(&hb->lock);
491
492                 spin_lock_irq(&curr->pi_lock);
493         }
494         spin_unlock_irq(&curr->pi_lock);
495 }
496
497 static int
498 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
499                 union futex_key *key, struct futex_pi_state **ps)
500 {
501         struct futex_pi_state *pi_state = NULL;
502         struct futex_q *this, *next;
503         struct plist_head *head;
504         struct task_struct *p;
505         pid_t pid = uval & FUTEX_TID_MASK;
506
507         head = &hb->chain;
508
509         plist_for_each_entry_safe(this, next, head, list) {
510                 if (match_futex(&this->key, key)) {
511                         /*
512                          * Another waiter already exists - bump up
513                          * the refcount and return its pi_state:
514                          */
515                         pi_state = this->pi_state;
516                         /*
517                          * Userspace might have messed up non PI and PI futexes
518                          */
519                         if (unlikely(!pi_state))
520                                 return -EINVAL;
521
522                         WARN_ON(!atomic_read(&pi_state->refcount));
523                         WARN_ON(pid && pi_state->owner &&
524                                 pi_state->owner->pid != pid);
525
526                         atomic_inc(&pi_state->refcount);
527                         *ps = pi_state;
528
529                         return 0;
530                 }
531         }
532
533         /*
534          * We are the first waiter - try to look up the real owner and attach
535          * the new pi_state to it, but bail out when TID = 0
536          */
537         if (!pid)
538                 return -ESRCH;
539         p = futex_find_get_task(pid);
540         if (IS_ERR(p))
541                 return PTR_ERR(p);
542
543         /*
544          * We need to look at the task state flags to figure out,
545          * whether the task is exiting. To protect against the do_exit
546          * change of the task flags, we do this protected by
547          * p->pi_lock:
548          */
549         spin_lock_irq(&p->pi_lock);
550         if (unlikely(p->flags & PF_EXITING)) {
551                 /*
552                  * The task is on the way out. When PF_EXITPIDONE is
553                  * set, we know that the task has finished the
554                  * cleanup:
555                  */
556                 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
557
558                 spin_unlock_irq(&p->pi_lock);
559                 put_task_struct(p);
560                 return ret;
561         }
562
563         pi_state = alloc_pi_state();
564
565         /*
566          * Initialize the pi_mutex in locked state and make 'p'
567          * the owner of it:
568          */
569         rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
570
571         /* Store the key for possible exit cleanups: */
572         pi_state->key = *key;
573
574         WARN_ON(!list_empty(&pi_state->list));
575         list_add(&pi_state->list, &p->pi_state_list);
576         pi_state->owner = p;
577         spin_unlock_irq(&p->pi_lock);
578
579         put_task_struct(p);
580
581         *ps = pi_state;
582
583         return 0;
584 }
585
586 /**
587  * futex_lock_pi_atomic() - atomic work required to acquire a pi aware futex
588  * @uaddr:              the pi futex user address
589  * @hb:                 the pi futex hash bucket
590  * @key:                the futex key associated with uaddr and hb
591  * @ps:                 the pi_state pointer where we store the result of the
592  *                      lookup
593  * @task:               the task to perform the atomic lock work for.  This will
594  *                      be "current" except in the case of requeue pi.
595  * @set_waiters:        force setting the FUTEX_WAITERS bit (1) or not (0)
596  *
597  * Returns:
598  *  0 - ready to wait
599  *  1 - acquired the lock
600  * <0 - error
601  *
602  * The hb->lock and futex_key refs shall be held by the caller.
603  */
604 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
605                                 union futex_key *key,
606                                 struct futex_pi_state **ps,
607                                 struct task_struct *task, int set_waiters)
608 {
609         int lock_taken, ret, ownerdied = 0;
610         u32 uval, newval, curval;
611
612 retry:
613         ret = lock_taken = 0;
614
615         /*
616          * To avoid races, we attempt to take the lock here again
617          * (by doing a 0 -> TID atomic cmpxchg), while holding all
618          * the locks. It will most likely not succeed.
619          */
620         newval = task_pid_vnr(task);
621         if (set_waiters)
622                 newval |= FUTEX_WAITERS;
623
624         curval = cmpxchg_futex_value_locked(uaddr, 0, newval);
625
626         if (unlikely(curval == -EFAULT))
627                 return -EFAULT;
628
629         /*
630          * Detect deadlocks.
631          */
632         if ((unlikely((curval & FUTEX_TID_MASK) == task_pid_vnr(task))))
633                 return -EDEADLK;
634
635         /*
636          * Surprise - we got the lock. Just return to userspace:
637          */
638         if (unlikely(!curval))
639                 return 1;
640
641         uval = curval;
642
643         /*
644          * Set the FUTEX_WAITERS flag, so the owner will know it has someone
645          * to wake at the next unlock.
646          */
647         newval = curval | FUTEX_WAITERS;
648
649         /*
650          * There are two cases, where a futex might have no owner (the
651          * owner TID is 0): OWNER_DIED. We take over the futex in this
652          * case. We also do an unconditional take over, when the owner
653          * of the futex died.
654          *
655          * This is safe as we are protected by the hash bucket lock !
656          */
657         if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) {
658                 /* Keep the OWNER_DIED bit */
659                 newval = (curval & ~FUTEX_TID_MASK) | task_pid_vnr(task);
660                 ownerdied = 0;
661                 lock_taken = 1;
662         }
663
664         curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
665
666         if (unlikely(curval == -EFAULT))
667                 return -EFAULT;
668         if (unlikely(curval != uval))
669                 goto retry;
670
671         /*
672          * We took the lock due to owner died take over.
673          */
674         if (unlikely(lock_taken))
675                 return 1;
676
677         /*
678          * We dont have the lock. Look up the PI state (or create it if
679          * we are the first waiter):
680          */
681         ret = lookup_pi_state(uval, hb, key, ps);
682
683         if (unlikely(ret)) {
684                 switch (ret) {
685                 case -ESRCH:
686                         /*
687                          * No owner found for this futex. Check if the
688                          * OWNER_DIED bit is set to figure out whether
689                          * this is a robust futex or not.
690                          */
691                         if (get_futex_value_locked(&curval, uaddr))
692                                 return -EFAULT;
693
694                         /*
695                          * We simply start over in case of a robust
696                          * futex. The code above will take the futex
697                          * and return happy.
698                          */
699                         if (curval & FUTEX_OWNER_DIED) {
700                                 ownerdied = 1;
701                                 goto retry;
702                         }
703                 default:
704                         break;
705                 }
706         }
707
708         return ret;
709 }
710
711 /*
712  * The hash bucket lock must be held when this is called.
713  * Afterwards, the futex_q must not be accessed.
714  */
715 static void wake_futex(struct futex_q *q)
716 {
717         struct task_struct *p = q->task;
718
719         /*
720          * We set q->lock_ptr = NULL _before_ we wake up the task. If
721          * a non futex wake up happens on another CPU then the task
722          * might exit and p would dereference a non existing task
723          * struct. Prevent this by holding a reference on p across the
724          * wake up.
725          */
726         get_task_struct(p);
727
728         plist_del(&q->list, &q->list.plist);
729         /*
730          * The waiting task can free the futex_q as soon as
731          * q->lock_ptr = NULL is written, without taking any locks. A
732          * memory barrier is required here to prevent the following
733          * store to lock_ptr from getting ahead of the plist_del.
734          */
735         smp_wmb();
736         q->lock_ptr = NULL;
737
738         wake_up_state(p, TASK_NORMAL);
739         put_task_struct(p);
740 }
741
742 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
743 {
744         struct task_struct *new_owner;
745         struct futex_pi_state *pi_state = this->pi_state;
746         u32 curval, newval;
747
748         if (!pi_state)
749                 return -EINVAL;
750
751         spin_lock(&pi_state->pi_mutex.wait_lock);
752         new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
753
754         /*
755          * This happens when we have stolen the lock and the original
756          * pending owner did not enqueue itself back on the rt_mutex.
757          * Thats not a tragedy. We know that way, that a lock waiter
758          * is on the fly. We make the futex_q waiter the pending owner.
759          */
760         if (!new_owner)
761                 new_owner = this->task;
762
763         /*
764          * We pass it to the next owner. (The WAITERS bit is always
765          * kept enabled while there is PI state around. We must also
766          * preserve the owner died bit.)
767          */
768         if (!(uval & FUTEX_OWNER_DIED)) {
769                 int ret = 0;
770
771                 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
772
773                 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
774
775                 if (curval == -EFAULT)
776                         ret = -EFAULT;
777                 else if (curval != uval)
778                         ret = -EINVAL;
779                 if (ret) {
780                         spin_unlock(&pi_state->pi_mutex.wait_lock);
781                         return ret;
782                 }
783         }
784
785         spin_lock_irq(&pi_state->owner->pi_lock);
786         WARN_ON(list_empty(&pi_state->list));
787         list_del_init(&pi_state->list);
788         spin_unlock_irq(&pi_state->owner->pi_lock);
789
790         spin_lock_irq(&new_owner->pi_lock);
791         WARN_ON(!list_empty(&pi_state->list));
792         list_add(&pi_state->list, &new_owner->pi_state_list);
793         pi_state->owner = new_owner;
794         spin_unlock_irq(&new_owner->pi_lock);
795
796         spin_unlock(&pi_state->pi_mutex.wait_lock);
797         rt_mutex_unlock(&pi_state->pi_mutex);
798
799         return 0;
800 }
801
802 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
803 {
804         u32 oldval;
805
806         /*
807          * There is no waiter, so we unlock the futex. The owner died
808          * bit has not to be preserved here. We are the owner:
809          */
810         oldval = cmpxchg_futex_value_locked(uaddr, uval, 0);
811
812         if (oldval == -EFAULT)
813                 return oldval;
814         if (oldval != uval)
815                 return -EAGAIN;
816
817         return 0;
818 }
819
820 /*
821  * Express the locking dependencies for lockdep:
822  */
823 static inline void
824 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
825 {
826         if (hb1 <= hb2) {
827                 spin_lock(&hb1->lock);
828                 if (hb1 < hb2)
829                         spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
830         } else { /* hb1 > hb2 */
831                 spin_lock(&hb2->lock);
832                 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
833         }
834 }
835
836 static inline void
837 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
838 {
839         spin_unlock(&hb1->lock);
840         if (hb1 != hb2)
841                 spin_unlock(&hb2->lock);
842 }
843
844 /*
845  * Wake up waiters matching bitset queued on this futex (uaddr).
846  */
847 static int futex_wake(u32 __user *uaddr, int fshared, int nr_wake, u32 bitset)
848 {
849         struct futex_hash_bucket *hb;
850         struct futex_q *this, *next;
851         struct plist_head *head;
852         union futex_key key = FUTEX_KEY_INIT;
853         int ret;
854
855         if (!bitset)
856                 return -EINVAL;
857
858         ret = get_futex_key(uaddr, fshared, &key, VERIFY_READ);
859         if (unlikely(ret != 0))
860                 goto out;
861
862         hb = hash_futex(&key);
863         spin_lock(&hb->lock);
864         head = &hb->chain;
865
866         plist_for_each_entry_safe(this, next, head, list) {
867                 if (match_futex (&this->key, &key)) {
868                         if (this->pi_state || this->rt_waiter) {
869                                 ret = -EINVAL;
870                                 break;
871                         }
872
873                         /* Check if one of the bits is set in both bitsets */
874                         if (!(this->bitset & bitset))
875                                 continue;
876
877                         wake_futex(this);
878                         if (++ret >= nr_wake)
879                                 break;
880                 }
881         }
882
883         spin_unlock(&hb->lock);
884         put_futex_key(fshared, &key);
885 out:
886         return ret;
887 }
888
889 /*
890  * Wake up all waiters hashed on the physical page that is mapped
891  * to this virtual address:
892  */
893 static int
894 futex_wake_op(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
895               int nr_wake, int nr_wake2, int op)
896 {
897         union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
898         struct futex_hash_bucket *hb1, *hb2;
899         struct plist_head *head;
900         struct futex_q *this, *next;
901         int ret, op_ret;
902
903 retry:
904         ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
905         if (unlikely(ret != 0))
906                 goto out;
907         ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_WRITE);
908         if (unlikely(ret != 0))
909                 goto out_put_key1;
910
911         hb1 = hash_futex(&key1);
912         hb2 = hash_futex(&key2);
913
914         double_lock_hb(hb1, hb2);
915 retry_private:
916         op_ret = futex_atomic_op_inuser(op, uaddr2);
917         if (unlikely(op_ret < 0)) {
918
919                 double_unlock_hb(hb1, hb2);
920
921 #ifndef CONFIG_MMU
922                 /*
923                  * we don't get EFAULT from MMU faults if we don't have an MMU,
924                  * but we might get them from range checking
925                  */
926                 ret = op_ret;
927                 goto out_put_keys;
928 #endif
929
930                 if (unlikely(op_ret != -EFAULT)) {
931                         ret = op_ret;
932                         goto out_put_keys;
933                 }
934
935                 ret = fault_in_user_writeable(uaddr2);
936                 if (ret)
937                         goto out_put_keys;
938
939                 if (!fshared)
940                         goto retry_private;
941
942                 put_futex_key(fshared, &key2);
943                 put_futex_key(fshared, &key1);
944                 goto retry;
945         }
946
947         head = &hb1->chain;
948
949         plist_for_each_entry_safe(this, next, head, list) {
950                 if (match_futex (&this->key, &key1)) {
951                         wake_futex(this);
952                         if (++ret >= nr_wake)
953                                 break;
954                 }
955         }
956
957         if (op_ret > 0) {
958                 head = &hb2->chain;
959
960                 op_ret = 0;
961                 plist_for_each_entry_safe(this, next, head, list) {
962                         if (match_futex (&this->key, &key2)) {
963                                 wake_futex(this);
964                                 if (++op_ret >= nr_wake2)
965                                         break;
966                         }
967                 }
968                 ret += op_ret;
969         }
970
971         double_unlock_hb(hb1, hb2);
972 out_put_keys:
973         put_futex_key(fshared, &key2);
974 out_put_key1:
975         put_futex_key(fshared, &key1);
976 out:
977         return ret;
978 }
979
980 /**
981  * requeue_futex() - Requeue a futex_q from one hb to another
982  * @q:          the futex_q to requeue
983  * @hb1:        the source hash_bucket
984  * @hb2:        the target hash_bucket
985  * @key2:       the new key for the requeued futex_q
986  */
987 static inline
988 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
989                    struct futex_hash_bucket *hb2, union futex_key *key2)
990 {
991
992         /*
993          * If key1 and key2 hash to the same bucket, no need to
994          * requeue.
995          */
996         if (likely(&hb1->chain != &hb2->chain)) {
997                 plist_del(&q->list, &hb1->chain);
998                 plist_add(&q->list, &hb2->chain);
999                 q->lock_ptr = &hb2->lock;
1000 #ifdef CONFIG_DEBUG_PI_LIST
1001                 q->list.plist.lock = &hb2->lock;
1002 #endif
1003         }
1004         get_futex_key_refs(key2);
1005         q->key = *key2;
1006 }
1007
1008 /**
1009  * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1010  * q:   the futex_q
1011  * key: the key of the requeue target futex
1012  *
1013  * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1014  * target futex if it is uncontended or via a lock steal.  Set the futex_q key
1015  * to the requeue target futex so the waiter can detect the wakeup on the right
1016  * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1017  * atomic lock acquisition.  Must be called with the q->lock_ptr held.
1018  */
1019 static inline
1020 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key)
1021 {
1022         drop_futex_key_refs(&q->key);
1023         get_futex_key_refs(key);
1024         q->key = *key;
1025
1026         WARN_ON(plist_node_empty(&q->list));
1027         plist_del(&q->list, &q->list.plist);
1028
1029         WARN_ON(!q->rt_waiter);
1030         q->rt_waiter = NULL;
1031
1032         wake_up_state(q->task, TASK_NORMAL);
1033 }
1034
1035 /**
1036  * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1037  * @pifutex:            the user address of the to futex
1038  * @hb1:                the from futex hash bucket, must be locked by the caller
1039  * @hb2:                the to futex hash bucket, must be locked by the caller
1040  * @key1:               the from futex key
1041  * @key2:               the to futex key
1042  * @ps:                 address to store the pi_state pointer
1043  * @set_waiters:        force setting the FUTEX_WAITERS bit (1) or not (0)
1044  *
1045  * Try and get the lock on behalf of the top waiter if we can do it atomically.
1046  * Wake the top waiter if we succeed.  If the caller specified set_waiters,
1047  * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1048  * hb1 and hb2 must be held by the caller.
1049  *
1050  * Returns:
1051  *  0 - failed to acquire the lock atomicly
1052  *  1 - acquired the lock
1053  * <0 - error
1054  */
1055 static int futex_proxy_trylock_atomic(u32 __user *pifutex,
1056                                  struct futex_hash_bucket *hb1,
1057                                  struct futex_hash_bucket *hb2,
1058                                  union futex_key *key1, union futex_key *key2,
1059                                  struct futex_pi_state **ps, int set_waiters)
1060 {
1061         struct futex_q *top_waiter = NULL;
1062         u32 curval;
1063         int ret;
1064
1065         if (get_futex_value_locked(&curval, pifutex))
1066                 return -EFAULT;
1067
1068         /*
1069          * Find the top_waiter and determine if there are additional waiters.
1070          * If the caller intends to requeue more than 1 waiter to pifutex,
1071          * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1072          * as we have means to handle the possible fault.  If not, don't set
1073          * the bit unecessarily as it will force the subsequent unlock to enter
1074          * the kernel.
1075          */
1076         top_waiter = futex_top_waiter(hb1, key1);
1077
1078         /* There are no waiters, nothing for us to do. */
1079         if (!top_waiter)
1080                 return 0;
1081
1082         /*
1083          * Try to take the lock for top_waiter.  Set the FUTEX_WAITERS bit in
1084          * the contended case or if set_waiters is 1.  The pi_state is returned
1085          * in ps in contended cases.
1086          */
1087         ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1088                                    set_waiters);
1089         if (ret == 1)
1090                 requeue_pi_wake_futex(top_waiter, key2);
1091
1092         return ret;
1093 }
1094
1095 /**
1096  * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1097  * uaddr1:      source futex user address
1098  * uaddr2:      target futex user address
1099  * nr_wake:     number of waiters to wake (must be 1 for requeue_pi)
1100  * nr_requeue:  number of waiters to requeue (0-INT_MAX)
1101  * requeue_pi:  if we are attempting to requeue from a non-pi futex to a
1102  *              pi futex (pi to pi requeue is not supported)
1103  *
1104  * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1105  * uaddr2 atomically on behalf of the top waiter.
1106  *
1107  * Returns:
1108  * >=0 - on success, the number of tasks requeued or woken
1109  *  <0 - on error
1110  */
1111 static int futex_requeue(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
1112                          int nr_wake, int nr_requeue, u32 *cmpval,
1113                          int requeue_pi)
1114 {
1115         union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1116         int drop_count = 0, task_count = 0, ret;
1117         struct futex_pi_state *pi_state = NULL;
1118         struct futex_hash_bucket *hb1, *hb2;
1119         struct plist_head *head1;
1120         struct futex_q *this, *next;
1121         u32 curval2;
1122
1123         if (requeue_pi) {
1124                 /*
1125                  * requeue_pi requires a pi_state, try to allocate it now
1126                  * without any locks in case it fails.
1127                  */
1128                 if (refill_pi_state_cache())
1129                         return -ENOMEM;
1130                 /*
1131                  * requeue_pi must wake as many tasks as it can, up to nr_wake
1132                  * + nr_requeue, since it acquires the rt_mutex prior to
1133                  * returning to userspace, so as to not leave the rt_mutex with
1134                  * waiters and no owner.  However, second and third wake-ups
1135                  * cannot be predicted as they involve race conditions with the
1136                  * first wake and a fault while looking up the pi_state.  Both
1137                  * pthread_cond_signal() and pthread_cond_broadcast() should
1138                  * use nr_wake=1.
1139                  */
1140                 if (nr_wake != 1)
1141                         return -EINVAL;
1142         }
1143
1144 retry:
1145         if (pi_state != NULL) {
1146                 /*
1147                  * We will have to lookup the pi_state again, so free this one
1148                  * to keep the accounting correct.
1149                  */
1150                 free_pi_state(pi_state);
1151                 pi_state = NULL;
1152         }
1153
1154         ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
1155         if (unlikely(ret != 0))
1156                 goto out;
1157         ret = get_futex_key(uaddr2, fshared, &key2,
1158                             requeue_pi ? VERIFY_WRITE : VERIFY_READ);
1159         if (unlikely(ret != 0))
1160                 goto out_put_key1;
1161
1162         hb1 = hash_futex(&key1);
1163         hb2 = hash_futex(&key2);
1164
1165 retry_private:
1166         double_lock_hb(hb1, hb2);
1167
1168         if (likely(cmpval != NULL)) {
1169                 u32 curval;
1170
1171                 ret = get_futex_value_locked(&curval, uaddr1);
1172
1173                 if (unlikely(ret)) {
1174                         double_unlock_hb(hb1, hb2);
1175
1176                         ret = get_user(curval, uaddr1);
1177                         if (ret)
1178                                 goto out_put_keys;
1179
1180                         if (!fshared)
1181                                 goto retry_private;
1182
1183                         put_futex_key(fshared, &key2);
1184                         put_futex_key(fshared, &key1);
1185                         goto retry;
1186                 }
1187                 if (curval != *cmpval) {
1188                         ret = -EAGAIN;
1189                         goto out_unlock;
1190                 }
1191         }
1192
1193         if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
1194                 /*
1195                  * Attempt to acquire uaddr2 and wake the top waiter. If we
1196                  * intend to requeue waiters, force setting the FUTEX_WAITERS
1197                  * bit.  We force this here where we are able to easily handle
1198                  * faults rather in the requeue loop below.
1199                  */
1200                 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
1201                                                  &key2, &pi_state, nr_requeue);
1202
1203                 /*
1204                  * At this point the top_waiter has either taken uaddr2 or is
1205                  * waiting on it.  If the former, then the pi_state will not
1206                  * exist yet, look it up one more time to ensure we have a
1207                  * reference to it.
1208                  */
1209                 if (ret == 1) {
1210                         WARN_ON(pi_state);
1211                         task_count++;
1212                         ret = get_futex_value_locked(&curval2, uaddr2);
1213                         if (!ret)
1214                                 ret = lookup_pi_state(curval2, hb2, &key2,
1215                                                       &pi_state);
1216                 }
1217
1218                 switch (ret) {
1219                 case 0:
1220                         break;
1221                 case -EFAULT:
1222                         double_unlock_hb(hb1, hb2);
1223                         put_futex_key(fshared, &key2);
1224                         put_futex_key(fshared, &key1);
1225                         ret = fault_in_user_writeable(uaddr2);
1226                         if (!ret)
1227                                 goto retry;
1228                         goto out;
1229                 case -EAGAIN:
1230                         /* The owner was exiting, try again. */
1231                         double_unlock_hb(hb1, hb2);
1232                         put_futex_key(fshared, &key2);
1233                         put_futex_key(fshared, &key1);
1234                         cond_resched();
1235                         goto retry;
1236                 default:
1237                         goto out_unlock;
1238                 }
1239         }
1240
1241         head1 = &hb1->chain;
1242         plist_for_each_entry_safe(this, next, head1, list) {
1243                 if (task_count - nr_wake >= nr_requeue)
1244                         break;
1245
1246                 if (!match_futex(&this->key, &key1))
1247                         continue;
1248
1249                 WARN_ON(!requeue_pi && this->rt_waiter);
1250                 WARN_ON(requeue_pi && !this->rt_waiter);
1251
1252                 /*
1253                  * Wake nr_wake waiters.  For requeue_pi, if we acquired the
1254                  * lock, we already woke the top_waiter.  If not, it will be
1255                  * woken by futex_unlock_pi().
1256                  */
1257                 if (++task_count <= nr_wake && !requeue_pi) {
1258                         wake_futex(this);
1259                         continue;
1260                 }
1261
1262                 /*
1263                  * Requeue nr_requeue waiters and possibly one more in the case
1264                  * of requeue_pi if we couldn't acquire the lock atomically.
1265                  */
1266                 if (requeue_pi) {
1267                         /* Prepare the waiter to take the rt_mutex. */
1268                         atomic_inc(&pi_state->refcount);
1269                         this->pi_state = pi_state;
1270                         ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
1271                                                         this->rt_waiter,
1272                                                         this->task, 1);
1273                         if (ret == 1) {
1274                                 /* We got the lock. */
1275                                 requeue_pi_wake_futex(this, &key2);
1276                                 continue;
1277                         } else if (ret) {
1278                                 /* -EDEADLK */
1279                                 this->pi_state = NULL;
1280                                 free_pi_state(pi_state);
1281                                 goto out_unlock;
1282                         }
1283                 }
1284                 requeue_futex(this, hb1, hb2, &key2);
1285                 drop_count++;
1286         }
1287
1288 out_unlock:
1289         double_unlock_hb(hb1, hb2);
1290
1291         /*
1292          * drop_futex_key_refs() must be called outside the spinlocks. During
1293          * the requeue we moved futex_q's from the hash bucket at key1 to the
1294          * one at key2 and updated their key pointer.  We no longer need to
1295          * hold the references to key1.
1296          */
1297         while (--drop_count >= 0)
1298                 drop_futex_key_refs(&key1);
1299
1300 out_put_keys:
1301         put_futex_key(fshared, &key2);
1302 out_put_key1:
1303         put_futex_key(fshared, &key1);
1304 out:
1305         if (pi_state != NULL)
1306                 free_pi_state(pi_state);
1307         return ret ? ret : task_count;
1308 }
1309
1310 /* The key must be already stored in q->key. */
1311 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
1312 {
1313         struct futex_hash_bucket *hb;
1314
1315         get_futex_key_refs(&q->key);
1316         hb = hash_futex(&q->key);
1317         q->lock_ptr = &hb->lock;
1318
1319         spin_lock(&hb->lock);
1320         return hb;
1321 }
1322
1323 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
1324 {
1325         int prio;
1326
1327         /*
1328          * The priority used to register this element is
1329          * - either the real thread-priority for the real-time threads
1330          * (i.e. threads with a priority lower than MAX_RT_PRIO)
1331          * - or MAX_RT_PRIO for non-RT threads.
1332          * Thus, all RT-threads are woken first in priority order, and
1333          * the others are woken last, in FIFO order.
1334          */
1335         prio = min(current->normal_prio, MAX_RT_PRIO);
1336
1337         plist_node_init(&q->list, prio);
1338 #ifdef CONFIG_DEBUG_PI_LIST
1339         q->list.plist.lock = &hb->lock;
1340 #endif
1341         plist_add(&q->list, &hb->chain);
1342         q->task = current;
1343         spin_unlock(&hb->lock);
1344 }
1345
1346 static inline void
1347 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
1348 {
1349         spin_unlock(&hb->lock);
1350         drop_futex_key_refs(&q->key);
1351 }
1352
1353 /*
1354  * queue_me and unqueue_me must be called as a pair, each
1355  * exactly once.  They are called with the hashed spinlock held.
1356  */
1357
1358 /* Return 1 if we were still queued (ie. 0 means we were woken) */
1359 static int unqueue_me(struct futex_q *q)
1360 {
1361         spinlock_t *lock_ptr;
1362         int ret = 0;
1363
1364         /* In the common case we don't take the spinlock, which is nice. */
1365 retry:
1366         lock_ptr = q->lock_ptr;
1367         barrier();
1368         if (lock_ptr != NULL) {
1369                 spin_lock(lock_ptr);
1370                 /*
1371                  * q->lock_ptr can change between reading it and
1372                  * spin_lock(), causing us to take the wrong lock.  This
1373                  * corrects the race condition.
1374                  *
1375                  * Reasoning goes like this: if we have the wrong lock,
1376                  * q->lock_ptr must have changed (maybe several times)
1377                  * between reading it and the spin_lock().  It can
1378                  * change again after the spin_lock() but only if it was
1379                  * already changed before the spin_lock().  It cannot,
1380                  * however, change back to the original value.  Therefore
1381                  * we can detect whether we acquired the correct lock.
1382                  */
1383                 if (unlikely(lock_ptr != q->lock_ptr)) {
1384                         spin_unlock(lock_ptr);
1385                         goto retry;
1386                 }
1387                 WARN_ON(plist_node_empty(&q->list));
1388                 plist_del(&q->list, &q->list.plist);
1389
1390                 BUG_ON(q->pi_state);
1391
1392                 spin_unlock(lock_ptr);
1393                 ret = 1;
1394         }
1395
1396         drop_futex_key_refs(&q->key);
1397         return ret;
1398 }
1399
1400 /*
1401  * PI futexes can not be requeued and must remove themself from the
1402  * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1403  * and dropped here.
1404  */
1405 static void unqueue_me_pi(struct futex_q *q)
1406 {
1407         WARN_ON(plist_node_empty(&q->list));
1408         plist_del(&q->list, &q->list.plist);
1409
1410         BUG_ON(!q->pi_state);
1411         free_pi_state(q->pi_state);
1412         q->pi_state = NULL;
1413
1414         spin_unlock(q->lock_ptr);
1415
1416         drop_futex_key_refs(&q->key);
1417 }
1418
1419 /*
1420  * Fixup the pi_state owner with the new owner.
1421  *
1422  * Must be called with hash bucket lock held and mm->sem held for non
1423  * private futexes.
1424  */
1425 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
1426                                 struct task_struct *newowner, int fshared)
1427 {
1428         u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
1429         struct futex_pi_state *pi_state = q->pi_state;
1430         struct task_struct *oldowner = pi_state->owner;
1431         u32 uval, curval, newval;
1432         int ret;
1433
1434         /* Owner died? */
1435         if (!pi_state->owner)
1436                 newtid |= FUTEX_OWNER_DIED;
1437
1438         /*
1439          * We are here either because we stole the rtmutex from the
1440          * pending owner or we are the pending owner which failed to
1441          * get the rtmutex. We have to replace the pending owner TID
1442          * in the user space variable. This must be atomic as we have
1443          * to preserve the owner died bit here.
1444          *
1445          * Note: We write the user space value _before_ changing the pi_state
1446          * because we can fault here. Imagine swapped out pages or a fork
1447          * that marked all the anonymous memory readonly for cow.
1448          *
1449          * Modifying pi_state _before_ the user space value would
1450          * leave the pi_state in an inconsistent state when we fault
1451          * here, because we need to drop the hash bucket lock to
1452          * handle the fault. This might be observed in the PID check
1453          * in lookup_pi_state.
1454          */
1455 retry:
1456         if (get_futex_value_locked(&uval, uaddr))
1457                 goto handle_fault;
1458
1459         while (1) {
1460                 newval = (uval & FUTEX_OWNER_DIED) | newtid;
1461
1462                 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1463
1464                 if (curval == -EFAULT)
1465                         goto handle_fault;
1466                 if (curval == uval)
1467                         break;
1468                 uval = curval;
1469         }
1470
1471         /*
1472          * We fixed up user space. Now we need to fix the pi_state
1473          * itself.
1474          */
1475         if (pi_state->owner != NULL) {
1476                 spin_lock_irq(&pi_state->owner->pi_lock);
1477                 WARN_ON(list_empty(&pi_state->list));
1478                 list_del_init(&pi_state->list);
1479                 spin_unlock_irq(&pi_state->owner->pi_lock);
1480         }
1481
1482         pi_state->owner = newowner;
1483
1484         spin_lock_irq(&newowner->pi_lock);
1485         WARN_ON(!list_empty(&pi_state->list));
1486         list_add(&pi_state->list, &newowner->pi_state_list);
1487         spin_unlock_irq(&newowner->pi_lock);
1488         return 0;
1489
1490         /*
1491          * To handle the page fault we need to drop the hash bucket
1492          * lock here. That gives the other task (either the pending
1493          * owner itself or the task which stole the rtmutex) the
1494          * chance to try the fixup of the pi_state. So once we are
1495          * back from handling the fault we need to check the pi_state
1496          * after reacquiring the hash bucket lock and before trying to
1497          * do another fixup. When the fixup has been done already we
1498          * simply return.
1499          */
1500 handle_fault:
1501         spin_unlock(q->lock_ptr);
1502
1503         ret = fault_in_user_writeable(uaddr);
1504
1505         spin_lock(q->lock_ptr);
1506
1507         /*
1508          * Check if someone else fixed it for us:
1509          */
1510         if (pi_state->owner != oldowner)
1511                 return 0;
1512
1513         if (ret)
1514                 return ret;
1515
1516         goto retry;
1517 }
1518
1519 /*
1520  * In case we must use restart_block to restart a futex_wait,
1521  * we encode in the 'flags' shared capability
1522  */
1523 #define FLAGS_SHARED            0x01
1524 #define FLAGS_CLOCKRT           0x02
1525 #define FLAGS_HAS_TIMEOUT       0x04
1526
1527 static long futex_wait_restart(struct restart_block *restart);
1528
1529 /**
1530  * fixup_owner() - Post lock pi_state and corner case management
1531  * @uaddr:      user address of the futex
1532  * @fshared:    whether the futex is shared (1) or not (0)
1533  * @q:          futex_q (contains pi_state and access to the rt_mutex)
1534  * @locked:     if the attempt to take the rt_mutex succeeded (1) or not (0)
1535  *
1536  * After attempting to lock an rt_mutex, this function is called to cleanup
1537  * the pi_state owner as well as handle race conditions that may allow us to
1538  * acquire the lock. Must be called with the hb lock held.
1539  *
1540  * Returns:
1541  *  1 - success, lock taken
1542  *  0 - success, lock not taken
1543  * <0 - on error (-EFAULT)
1544  */
1545 static int fixup_owner(u32 __user *uaddr, int fshared, struct futex_q *q,
1546                        int locked)
1547 {
1548         struct task_struct *owner;
1549         int ret = 0;
1550
1551         if (locked) {
1552                 /*
1553                  * Got the lock. We might not be the anticipated owner if we
1554                  * did a lock-steal - fix up the PI-state in that case:
1555                  */
1556                 if (q->pi_state->owner != current)
1557                         ret = fixup_pi_state_owner(uaddr, q, current, fshared);
1558                 goto out;
1559         }
1560
1561         /*
1562          * Catch the rare case, where the lock was released when we were on the
1563          * way back before we locked the hash bucket.
1564          */
1565         if (q->pi_state->owner == current) {
1566                 /*
1567                  * Try to get the rt_mutex now. This might fail as some other
1568                  * task acquired the rt_mutex after we removed ourself from the
1569                  * rt_mutex waiters list.
1570                  */
1571                 if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
1572                         locked = 1;
1573                         goto out;
1574                 }
1575
1576                 /*
1577                  * pi_state is incorrect, some other task did a lock steal and
1578                  * we returned due to timeout or signal without taking the
1579                  * rt_mutex. Too late. We can access the rt_mutex_owner without
1580                  * locking, as the other task is now blocked on the hash bucket
1581                  * lock. Fix the state up.
1582                  */
1583                 owner = rt_mutex_owner(&q->pi_state->pi_mutex);
1584                 ret = fixup_pi_state_owner(uaddr, q, owner, fshared);
1585                 goto out;
1586         }
1587
1588         /*
1589          * Paranoia check. If we did not take the lock, then we should not be
1590          * the owner, nor the pending owner, of the rt_mutex.
1591          */
1592         if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
1593                 printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
1594                                 "pi-state %p\n", ret,
1595                                 q->pi_state->pi_mutex.owner,
1596                                 q->pi_state->owner);
1597
1598 out:
1599         return ret ? ret : locked;
1600 }
1601
1602 /**
1603  * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
1604  * @hb:         the futex hash bucket, must be locked by the caller
1605  * @q:          the futex_q to queue up on
1606  * @timeout:    the prepared hrtimer_sleeper, or null for no timeout
1607  */
1608 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
1609                                 struct hrtimer_sleeper *timeout)
1610 {
1611         queue_me(q, hb);
1612
1613         /*
1614          * There might have been scheduling since the queue_me(), as we
1615          * cannot hold a spinlock across the get_user() in case it
1616          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1617          * queueing ourselves into the futex hash. This code thus has to
1618          * rely on the futex_wake() code removing us from hash when it
1619          * wakes us up.
1620          */
1621         set_current_state(TASK_INTERRUPTIBLE);
1622
1623         /* Arm the timer */
1624         if (timeout) {
1625                 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
1626                 if (!hrtimer_active(&timeout->timer))
1627                         timeout->task = NULL;
1628         }
1629
1630         /*
1631          * !plist_node_empty() is safe here without any lock.
1632          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1633          */
1634         if (likely(!plist_node_empty(&q->list))) {
1635                 /*
1636                  * If the timer has already expired, current will already be
1637                  * flagged for rescheduling. Only call schedule if there
1638                  * is no timeout, or if it has yet to expire.
1639                  */
1640                 if (!timeout || timeout->task)
1641                         schedule();
1642         }
1643         __set_current_state(TASK_RUNNING);
1644 }
1645
1646 /**
1647  * futex_wait_setup() - Prepare to wait on a futex
1648  * @uaddr:      the futex userspace address
1649  * @val:        the expected value
1650  * @fshared:    whether the futex is shared (1) or not (0)
1651  * @q:          the associated futex_q
1652  * @hb:         storage for hash_bucket pointer to be returned to caller
1653  *
1654  * Setup the futex_q and locate the hash_bucket.  Get the futex value and
1655  * compare it with the expected value.  Handle atomic faults internally.
1656  * Return with the hb lock held and a q.key reference on success, and unlocked
1657  * with no q.key reference on failure.
1658  *
1659  * Returns:
1660  *  0 - uaddr contains val and hb has been locked
1661  * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlcoked
1662  */
1663 static int futex_wait_setup(u32 __user *uaddr, u32 val, int fshared,
1664                            struct futex_q *q, struct futex_hash_bucket **hb)
1665 {
1666         u32 uval;
1667         int ret;
1668
1669         /*
1670          * Access the page AFTER the hash-bucket is locked.
1671          * Order is important:
1672          *
1673          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1674          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
1675          *
1676          * The basic logical guarantee of a futex is that it blocks ONLY
1677          * if cond(var) is known to be true at the time of blocking, for
1678          * any cond.  If we queued after testing *uaddr, that would open
1679          * a race condition where we could block indefinitely with
1680          * cond(var) false, which would violate the guarantee.
1681          *
1682          * A consequence is that futex_wait() can return zero and absorb
1683          * a wakeup when *uaddr != val on entry to the syscall.  This is
1684          * rare, but normal.
1685          */
1686 retry:
1687         q->key = FUTEX_KEY_INIT;
1688         ret = get_futex_key(uaddr, fshared, &q->key, VERIFY_READ);
1689         if (unlikely(ret != 0))
1690                 return ret;
1691
1692 retry_private:
1693         *hb = queue_lock(q);
1694
1695         ret = get_futex_value_locked(&uval, uaddr);
1696
1697         if (ret) {
1698                 queue_unlock(q, *hb);
1699
1700                 ret = get_user(uval, uaddr);
1701                 if (ret)
1702                         goto out;
1703
1704                 if (!fshared)
1705                         goto retry_private;
1706
1707                 put_futex_key(fshared, &q->key);
1708                 goto retry;
1709         }
1710
1711         if (uval != val) {
1712                 queue_unlock(q, *hb);
1713                 ret = -EWOULDBLOCK;
1714         }
1715
1716 out:
1717         if (ret)
1718                 put_futex_key(fshared, &q->key);
1719         return ret;
1720 }
1721
1722 static int futex_wait(u32 __user *uaddr, int fshared,
1723                       u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
1724 {
1725         struct hrtimer_sleeper timeout, *to = NULL;
1726         struct restart_block *restart;
1727         struct futex_hash_bucket *hb;
1728         struct futex_q q;
1729         int ret;
1730
1731         if (!bitset)
1732                 return -EINVAL;
1733
1734         q.pi_state = NULL;
1735         q.bitset = bitset;
1736         q.rt_waiter = NULL;
1737
1738         if (abs_time) {
1739                 to = &timeout;
1740
1741                 hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
1742                                       CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1743                 hrtimer_init_sleeper(to, current);
1744                 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
1745                                              current->timer_slack_ns);
1746         }
1747
1748         /* Prepare to wait on uaddr. */
1749         ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
1750         if (ret)
1751                 goto out;
1752
1753         /* queue_me and wait for wakeup, timeout, or a signal. */
1754         futex_wait_queue_me(hb, &q, to);
1755
1756         /* If we were woken (and unqueued), we succeeded, whatever. */
1757         ret = 0;
1758         if (!unqueue_me(&q))
1759                 goto out_put_key;
1760         ret = -ETIMEDOUT;
1761         if (to && !to->task)
1762                 goto out_put_key;
1763
1764         /*
1765          * We expect signal_pending(current), but another thread may
1766          * have handled it for us already.
1767          */
1768         ret = -ERESTARTSYS;
1769         if (!abs_time)
1770                 goto out_put_key;
1771
1772         restart = &current_thread_info()->restart_block;
1773         restart->fn = futex_wait_restart;
1774         restart->futex.uaddr = (u32 *)uaddr;
1775         restart->futex.val = val;
1776         restart->futex.time = abs_time->tv64;
1777         restart->futex.bitset = bitset;
1778         restart->futex.flags = FLAGS_HAS_TIMEOUT;
1779
1780         if (fshared)
1781                 restart->futex.flags |= FLAGS_SHARED;
1782         if (clockrt)
1783                 restart->futex.flags |= FLAGS_CLOCKRT;
1784
1785         ret = -ERESTART_RESTARTBLOCK;
1786
1787 out_put_key:
1788         put_futex_key(fshared, &q.key);
1789 out:
1790         if (to) {
1791                 hrtimer_cancel(&to->timer);
1792                 destroy_hrtimer_on_stack(&to->timer);
1793         }
1794         return ret;
1795 }
1796
1797
1798 static long futex_wait_restart(struct restart_block *restart)
1799 {
1800         u32 __user *uaddr = (u32 __user *)restart->futex.uaddr;
1801         int fshared = 0;
1802         ktime_t t, *tp = NULL;
1803
1804         if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
1805                 t.tv64 = restart->futex.time;
1806                 tp = &t;
1807         }
1808         restart->fn = do_no_restart_syscall;
1809         if (restart->futex.flags & FLAGS_SHARED)
1810                 fshared = 1;
1811         return (long)futex_wait(uaddr, fshared, restart->futex.val, tp,
1812                                 restart->futex.bitset,
1813                                 restart->futex.flags & FLAGS_CLOCKRT);
1814 }
1815
1816
1817 /*
1818  * Userspace tried a 0 -> TID atomic transition of the futex value
1819  * and failed. The kernel side here does the whole locking operation:
1820  * if there are waiters then it will block, it does PI, etc. (Due to
1821  * races the kernel might see a 0 value of the futex too.)
1822  */
1823 static int futex_lock_pi(u32 __user *uaddr, int fshared,
1824                          int detect, ktime_t *time, int trylock)
1825 {
1826         struct hrtimer_sleeper timeout, *to = NULL;
1827         struct futex_hash_bucket *hb;
1828         struct futex_q q;
1829         int res, ret;
1830
1831         if (refill_pi_state_cache())
1832                 return -ENOMEM;
1833
1834         if (time) {
1835                 to = &timeout;
1836                 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
1837                                       HRTIMER_MODE_ABS);
1838                 hrtimer_init_sleeper(to, current);
1839                 hrtimer_set_expires(&to->timer, *time);
1840         }
1841
1842         q.pi_state = NULL;
1843         q.rt_waiter = NULL;
1844 retry:
1845         q.key = FUTEX_KEY_INIT;
1846         ret = get_futex_key(uaddr, fshared, &q.key, VERIFY_WRITE);
1847         if (unlikely(ret != 0))
1848                 goto out;
1849
1850 retry_private:
1851         hb = queue_lock(&q);
1852
1853         ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
1854         if (unlikely(ret)) {
1855                 switch (ret) {
1856                 case 1:
1857                         /* We got the lock. */
1858                         ret = 0;
1859                         goto out_unlock_put_key;
1860                 case -EFAULT:
1861                         goto uaddr_faulted;
1862                 case -EAGAIN:
1863                         /*
1864                          * Task is exiting and we just wait for the
1865                          * exit to complete.
1866                          */
1867                         queue_unlock(&q, hb);
1868                         put_futex_key(fshared, &q.key);
1869                         cond_resched();
1870                         goto retry;
1871                 default:
1872                         goto out_unlock_put_key;
1873                 }
1874         }
1875
1876         /*
1877          * Only actually queue now that the atomic ops are done:
1878          */
1879         queue_me(&q, hb);
1880
1881         WARN_ON(!q.pi_state);
1882         /*
1883          * Block on the PI mutex:
1884          */
1885         if (!trylock)
1886                 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1887         else {
1888                 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1889                 /* Fixup the trylock return value: */
1890                 ret = ret ? 0 : -EWOULDBLOCK;
1891         }
1892
1893         spin_lock(q.lock_ptr);
1894         /*
1895          * Fixup the pi_state owner and possibly acquire the lock if we
1896          * haven't already.
1897          */
1898         res = fixup_owner(uaddr, fshared, &q, !ret);
1899         /*
1900          * If fixup_owner() returned an error, proprogate that.  If it acquired
1901          * the lock, clear our -ETIMEDOUT or -EINTR.
1902          */
1903         if (res)
1904                 ret = (res < 0) ? res : 0;
1905
1906         /*
1907          * If fixup_owner() faulted and was unable to handle the fault, unlock
1908          * it and return the fault to userspace.
1909          */
1910         if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
1911                 rt_mutex_unlock(&q.pi_state->pi_mutex);
1912
1913         /* Unqueue and drop the lock */
1914         unqueue_me_pi(&q);
1915
1916         goto out;
1917
1918 out_unlock_put_key:
1919         queue_unlock(&q, hb);
1920
1921 out_put_key:
1922         put_futex_key(fshared, &q.key);
1923 out:
1924         if (to)
1925                 destroy_hrtimer_on_stack(&to->timer);
1926         return ret != -EINTR ? ret : -ERESTARTNOINTR;
1927
1928 uaddr_faulted:
1929         queue_unlock(&q, hb);
1930
1931         ret = fault_in_user_writeable(uaddr);
1932         if (ret)
1933                 goto out_put_key;
1934
1935         if (!fshared)
1936                 goto retry_private;
1937
1938         put_futex_key(fshared, &q.key);
1939         goto retry;
1940 }
1941
1942 /*
1943  * Userspace attempted a TID -> 0 atomic transition, and failed.
1944  * This is the in-kernel slowpath: we look up the PI state (if any),
1945  * and do the rt-mutex unlock.
1946  */
1947 static int futex_unlock_pi(u32 __user *uaddr, int fshared)
1948 {
1949         struct futex_hash_bucket *hb;
1950         struct futex_q *this, *next;
1951         u32 uval;
1952         struct plist_head *head;
1953         union futex_key key = FUTEX_KEY_INIT;
1954         int ret;
1955
1956 retry:
1957         if (get_user(uval, uaddr))
1958                 return -EFAULT;
1959         /*
1960          * We release only a lock we actually own:
1961          */
1962         if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current))
1963                 return -EPERM;
1964
1965         ret = get_futex_key(uaddr, fshared, &key, VERIFY_WRITE);
1966         if (unlikely(ret != 0))
1967                 goto out;
1968
1969         hb = hash_futex(&key);
1970         spin_lock(&hb->lock);
1971
1972         /*
1973          * To avoid races, try to do the TID -> 0 atomic transition
1974          * again. If it succeeds then we can return without waking
1975          * anyone else up:
1976          */
1977         if (!(uval & FUTEX_OWNER_DIED))
1978                 uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0);
1979
1980
1981         if (unlikely(uval == -EFAULT))
1982                 goto pi_faulted;
1983         /*
1984          * Rare case: we managed to release the lock atomically,
1985          * no need to wake anyone else up:
1986          */
1987         if (unlikely(uval == task_pid_vnr(current)))
1988                 goto out_unlock;
1989
1990         /*
1991          * Ok, other tasks may need to be woken up - check waiters
1992          * and do the wakeup if necessary:
1993          */
1994         head = &hb->chain;
1995
1996         plist_for_each_entry_safe(this, next, head, list) {
1997                 if (!match_futex (&this->key, &key))
1998                         continue;
1999                 ret = wake_futex_pi(uaddr, uval, this);
2000                 /*
2001                  * The atomic access to the futex value
2002                  * generated a pagefault, so retry the
2003                  * user-access and the wakeup:
2004                  */
2005                 if (ret == -EFAULT)
2006                         goto pi_faulted;
2007                 goto out_unlock;
2008         }
2009         /*
2010          * No waiters - kernel unlocks the futex:
2011          */
2012         if (!(uval & FUTEX_OWNER_DIED)) {
2013                 ret = unlock_futex_pi(uaddr, uval);
2014                 if (ret == -EFAULT)
2015                         goto pi_faulted;
2016         }
2017
2018 out_unlock:
2019         spin_unlock(&hb->lock);
2020         put_futex_key(fshared, &key);
2021
2022 out:
2023         return ret;
2024
2025 pi_faulted:
2026         spin_unlock(&hb->lock);
2027         put_futex_key(fshared, &key);
2028
2029         ret = fault_in_user_writeable(uaddr);
2030         if (!ret)
2031                 goto retry;
2032
2033         return ret;
2034 }
2035
2036 /**
2037  * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
2038  * @hb:         the hash_bucket futex_q was original enqueued on
2039  * @q:          the futex_q woken while waiting to be requeued
2040  * @key2:       the futex_key of the requeue target futex
2041  * @timeout:    the timeout associated with the wait (NULL if none)
2042  *
2043  * Detect if the task was woken on the initial futex as opposed to the requeue
2044  * target futex.  If so, determine if it was a timeout or a signal that caused
2045  * the wakeup and return the appropriate error code to the caller.  Must be
2046  * called with the hb lock held.
2047  *
2048  * Returns
2049  *  0 - no early wakeup detected
2050  * <0 - -ETIMEDOUT or -ERESTARTNOINTR
2051  */
2052 static inline
2053 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
2054                                    struct futex_q *q, union futex_key *key2,
2055                                    struct hrtimer_sleeper *timeout)
2056 {
2057         int ret = 0;
2058
2059         /*
2060          * With the hb lock held, we avoid races while we process the wakeup.
2061          * We only need to hold hb (and not hb2) to ensure atomicity as the
2062          * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
2063          * It can't be requeued from uaddr2 to something else since we don't
2064          * support a PI aware source futex for requeue.
2065          */
2066         if (!match_futex(&q->key, key2)) {
2067                 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
2068                 /*
2069                  * We were woken prior to requeue by a timeout or a signal.
2070                  * Unqueue the futex_q and determine which it was.
2071                  */
2072                 plist_del(&q->list, &q->list.plist);
2073                 drop_futex_key_refs(&q->key);
2074
2075                 if (timeout && !timeout->task)
2076                         ret = -ETIMEDOUT;
2077                 else
2078                         ret = -ERESTARTNOINTR;
2079         }
2080         return ret;
2081 }
2082
2083 /**
2084  * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
2085  * @uaddr:      the futex we initialyl wait on (non-pi)
2086  * @fshared:    whether the futexes are shared (1) or not (0).  They must be
2087  *              the same type, no requeueing from private to shared, etc.
2088  * @val:        the expected value of uaddr
2089  * @abs_time:   absolute timeout
2090  * @bitset:     32 bit wakeup bitset set by userspace, defaults to all.
2091  * @clockrt:    whether to use CLOCK_REALTIME (1) or CLOCK_MONOTONIC (0)
2092  * @uaddr2:     the pi futex we will take prior to returning to user-space
2093  *
2094  * The caller will wait on uaddr and will be requeued by futex_requeue() to
2095  * uaddr2 which must be PI aware.  Normal wakeup will wake on uaddr2 and
2096  * complete the acquisition of the rt_mutex prior to returning to userspace.
2097  * This ensures the rt_mutex maintains an owner when it has waiters; without
2098  * one, the pi logic wouldn't know which task to boost/deboost, if there was a
2099  * need to.
2100  *
2101  * We call schedule in futex_wait_queue_me() when we enqueue and return there
2102  * via the following:
2103  * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
2104  * 2) wakeup on uaddr2 after a requeue and subsequent unlock
2105  * 3) signal (before or after requeue)
2106  * 4) timeout (before or after requeue)
2107  *
2108  * If 3, we setup a restart_block with futex_wait_requeue_pi() as the function.
2109  *
2110  * If 2, we may then block on trying to take the rt_mutex and return via:
2111  * 5) successful lock
2112  * 6) signal
2113  * 7) timeout
2114  * 8) other lock acquisition failure
2115  *
2116  * If 6, we setup a restart_block with futex_lock_pi() as the function.
2117  *
2118  * If 4 or 7, we cleanup and return with -ETIMEDOUT.
2119  *
2120  * Returns:
2121  *  0 - On success
2122  * <0 - On error
2123  */
2124 static int futex_wait_requeue_pi(u32 __user *uaddr, int fshared,
2125                                  u32 val, ktime_t *abs_time, u32 bitset,
2126                                  int clockrt, u32 __user *uaddr2)
2127 {
2128         struct hrtimer_sleeper timeout, *to = NULL;
2129         struct rt_mutex_waiter rt_waiter;
2130         struct rt_mutex *pi_mutex = NULL;
2131         struct futex_hash_bucket *hb;
2132         union futex_key key2;
2133         struct futex_q q;
2134         int res, ret;
2135
2136         if (!bitset)
2137                 return -EINVAL;
2138
2139         if (abs_time) {
2140                 to = &timeout;
2141                 hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
2142                                       CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2143                 hrtimer_init_sleeper(to, current);
2144                 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2145                                              current->timer_slack_ns);
2146         }
2147
2148         /*
2149          * The waiter is allocated on our stack, manipulated by the requeue
2150          * code while we sleep on uaddr.
2151          */
2152         debug_rt_mutex_init_waiter(&rt_waiter);
2153         rt_waiter.task = NULL;
2154
2155         q.pi_state = NULL;
2156         q.bitset = bitset;
2157         q.rt_waiter = &rt_waiter;
2158
2159         key2 = FUTEX_KEY_INIT;
2160         ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_WRITE);
2161         if (unlikely(ret != 0))
2162                 goto out;
2163
2164         /* Prepare to wait on uaddr. */
2165         ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
2166         if (ret)
2167                 goto out_key2;
2168
2169         /* Queue the futex_q, drop the hb lock, wait for wakeup. */
2170         futex_wait_queue_me(hb, &q, to);
2171
2172         spin_lock(&hb->lock);
2173         ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
2174         spin_unlock(&hb->lock);
2175         if (ret)
2176                 goto out_put_keys;
2177
2178         /*
2179          * In order for us to be here, we know our q.key == key2, and since
2180          * we took the hb->lock above, we also know that futex_requeue() has
2181          * completed and we no longer have to concern ourselves with a wakeup
2182          * race with the atomic proxy lock acquition by the requeue code.
2183          */
2184
2185         /* Check if the requeue code acquired the second futex for us. */
2186         if (!q.rt_waiter) {
2187                 /*
2188                  * Got the lock. We might not be the anticipated owner if we
2189                  * did a lock-steal - fix up the PI-state in that case.
2190                  */
2191                 if (q.pi_state && (q.pi_state->owner != current)) {
2192                         spin_lock(q.lock_ptr);
2193                         ret = fixup_pi_state_owner(uaddr2, &q, current,
2194                                                    fshared);
2195                         spin_unlock(q.lock_ptr);
2196                 }
2197         } else {
2198                 /*
2199                  * We have been woken up by futex_unlock_pi(), a timeout, or a
2200                  * signal.  futex_unlock_pi() will not destroy the lock_ptr nor
2201                  * the pi_state.
2202                  */
2203                 WARN_ON(!&q.pi_state);
2204                 pi_mutex = &q.pi_state->pi_mutex;
2205                 ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);
2206                 debug_rt_mutex_free_waiter(&rt_waiter);
2207
2208                 spin_lock(q.lock_ptr);
2209                 /*
2210                  * Fixup the pi_state owner and possibly acquire the lock if we
2211                  * haven't already.
2212                  */
2213                 res = fixup_owner(uaddr2, fshared, &q, !ret);
2214                 /*
2215                  * If fixup_owner() returned an error, proprogate that.  If it
2216                  * acquired the lock, clear our -ETIMEDOUT or -EINTR.
2217                  */
2218                 if (res)
2219                         ret = (res < 0) ? res : 0;
2220
2221                 /* Unqueue and drop the lock. */
2222                 unqueue_me_pi(&q);
2223         }
2224
2225         /*
2226          * If fixup_pi_state_owner() faulted and was unable to handle the
2227          * fault, unlock the rt_mutex and return the fault to userspace.
2228          */
2229         if (ret == -EFAULT) {
2230                 if (rt_mutex_owner(pi_mutex) == current)
2231                         rt_mutex_unlock(pi_mutex);
2232         } else if (ret == -EINTR) {
2233                 /*
2234                  * We've already been requeued, but we have no way to
2235                  * restart by calling futex_lock_pi() directly. We
2236                  * could restart the syscall, but that will look at
2237                  * the user space value and return right away. So we
2238                  * drop back with EWOULDBLOCK to tell user space that
2239                  * "val" has been changed. That's the same what the
2240                  * restart of the syscall would do in
2241                  * futex_wait_setup().
2242                  */
2243                 ret = -EWOULDBLOCK;
2244         }
2245
2246 out_put_keys:
2247         put_futex_key(fshared, &q.key);
2248 out_key2:
2249         put_futex_key(fshared, &key2);
2250
2251 out:
2252         if (to) {
2253                 hrtimer_cancel(&to->timer);
2254                 destroy_hrtimer_on_stack(&to->timer);
2255         }
2256         return ret;
2257 }
2258
2259 /*
2260  * Support for robust futexes: the kernel cleans up held futexes at
2261  * thread exit time.
2262  *
2263  * Implementation: user-space maintains a per-thread list of locks it
2264  * is holding. Upon do_exit(), the kernel carefully walks this list,
2265  * and marks all locks that are owned by this thread with the
2266  * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
2267  * always manipulated with the lock held, so the list is private and
2268  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
2269  * field, to allow the kernel to clean up if the thread dies after
2270  * acquiring the lock, but just before it could have added itself to
2271  * the list. There can only be one such pending lock.
2272  */
2273
2274 /**
2275  * sys_set_robust_list - set the robust-futex list head of a task
2276  * @head: pointer to the list-head
2277  * @len: length of the list-head, as userspace expects
2278  */
2279 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
2280                 size_t, len)
2281 {
2282         if (!futex_cmpxchg_enabled)
2283                 return -ENOSYS;
2284         /*
2285          * The kernel knows only one size for now:
2286          */
2287         if (unlikely(len != sizeof(*head)))
2288                 return -EINVAL;
2289
2290         current->robust_list = head;
2291
2292         return 0;
2293 }
2294
2295 /**
2296  * sys_get_robust_list - get the robust-futex list head of a task
2297  * @pid: pid of the process [zero for current task]
2298  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
2299  * @len_ptr: pointer to a length field, the kernel fills in the header size
2300  */
2301 SYSCALL_DEFINE3(get_robust_list, int, pid,
2302                 struct robust_list_head __user * __user *, head_ptr,
2303                 size_t __user *, len_ptr)
2304 {
2305         struct robust_list_head __user *head;
2306         unsigned long ret;
2307         const struct cred *cred = current_cred(), *pcred;
2308
2309         if (!futex_cmpxchg_enabled)
2310                 return -ENOSYS;
2311
2312         if (!pid)
2313                 head = current->robust_list;
2314         else {
2315                 struct task_struct *p;
2316
2317                 ret = -ESRCH;
2318                 rcu_read_lock();
2319                 p = find_task_by_vpid(pid);
2320                 if (!p)
2321                         goto err_unlock;
2322                 ret = -EPERM;
2323                 pcred = __task_cred(p);
2324                 if (cred->euid != pcred->euid &&
2325                     cred->euid != pcred->uid &&
2326                     !capable(CAP_SYS_PTRACE))
2327                         goto err_unlock;
2328                 head = p->robust_list;
2329                 rcu_read_unlock();
2330         }
2331
2332         if (put_user(sizeof(*head), len_ptr))
2333                 return -EFAULT;
2334         return put_user(head, head_ptr);
2335
2336 err_unlock:
2337         rcu_read_unlock();
2338
2339         return ret;
2340 }
2341
2342 /*
2343  * Process a futex-list entry, check whether it's owned by the
2344  * dying task, and do notification if so:
2345  */
2346 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
2347 {
2348         u32 uval, nval, mval;
2349
2350 retry:
2351         if (get_user(uval, uaddr))
2352                 return -1;
2353
2354         if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
2355                 /*
2356                  * Ok, this dying thread is truly holding a futex
2357                  * of interest. Set the OWNER_DIED bit atomically
2358                  * via cmpxchg, and if the value had FUTEX_WAITERS
2359                  * set, wake up a waiter (if any). (We have to do a
2360                  * futex_wake() even if OWNER_DIED is already set -
2361                  * to handle the rare but possible case of recursive
2362                  * thread-death.) The rest of the cleanup is done in
2363                  * userspace.
2364                  */
2365                 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
2366                 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
2367
2368                 if (nval == -EFAULT)
2369                         return -1;
2370
2371                 if (nval != uval)
2372                         goto retry;
2373
2374                 /*
2375                  * Wake robust non-PI futexes here. The wakeup of
2376                  * PI futexes happens in exit_pi_state():
2377                  */
2378                 if (!pi && (uval & FUTEX_WAITERS))
2379                         futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
2380         }
2381         return 0;
2382 }
2383
2384 /*
2385  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
2386  */
2387 static inline int fetch_robust_entry(struct robust_list __user **entry,
2388                                      struct robust_list __user * __user *head,
2389                                      int *pi)
2390 {
2391         unsigned long uentry;
2392
2393         if (get_user(uentry, (unsigned long __user *)head))
2394                 return -EFAULT;
2395
2396         *entry = (void __user *)(uentry & ~1UL);
2397         *pi = uentry & 1;
2398
2399         return 0;
2400 }
2401
2402 /*
2403  * Walk curr->robust_list (very carefully, it's a userspace list!)
2404  * and mark any locks found there dead, and notify any waiters.
2405  *
2406  * We silently return on any sign of list-walking problem.
2407  */
2408 void exit_robust_list(struct task_struct *curr)
2409 {
2410         struct robust_list_head __user *head = curr->robust_list;
2411         struct robust_list __user *entry, *next_entry, *pending;
2412         unsigned int limit = ROBUST_LIST_LIMIT, pi, next_pi, pip;
2413         unsigned long futex_offset;
2414         int rc;
2415
2416         if (!futex_cmpxchg_enabled)
2417                 return;
2418
2419         /*
2420          * Fetch the list head (which was registered earlier, via
2421          * sys_set_robust_list()):
2422          */
2423         if (fetch_robust_entry(&entry, &head->list.next, &pi))
2424                 return;
2425         /*
2426          * Fetch the relative futex offset:
2427          */
2428         if (get_user(futex_offset, &head->futex_offset))
2429                 return;
2430         /*
2431          * Fetch any possibly pending lock-add first, and handle it
2432          * if it exists:
2433          */
2434         if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
2435                 return;
2436
2437         next_entry = NULL;      /* avoid warning with gcc */
2438         while (entry != &head->list) {
2439                 /*
2440                  * Fetch the next entry in the list before calling
2441                  * handle_futex_death:
2442                  */
2443                 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
2444                 /*
2445                  * A pending lock might already be on the list, so
2446                  * don't process it twice:
2447                  */
2448                 if (entry != pending)
2449                         if (handle_futex_death((void __user *)entry + futex_offset,
2450                                                 curr, pi))
2451                                 return;
2452                 if (rc)
2453                         return;
2454                 entry = next_entry;
2455                 pi = next_pi;
2456                 /*
2457                  * Avoid excessively long or circular lists:
2458                  */
2459                 if (!--limit)
2460                         break;
2461
2462                 cond_resched();
2463         }
2464
2465         if (pending)
2466                 handle_futex_death((void __user *)pending + futex_offset,
2467                                    curr, pip);
2468 }
2469
2470 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
2471                 u32 __user *uaddr2, u32 val2, u32 val3)
2472 {
2473         int clockrt, ret = -ENOSYS;
2474         int cmd = op & FUTEX_CMD_MASK;
2475         int fshared = 0;
2476
2477         if (!(op & FUTEX_PRIVATE_FLAG))
2478                 fshared = 1;
2479
2480         clockrt = op & FUTEX_CLOCK_REALTIME;
2481         if (clockrt && cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
2482                 return -ENOSYS;
2483
2484         switch (cmd) {
2485         case FUTEX_WAIT:
2486                 val3 = FUTEX_BITSET_MATCH_ANY;
2487         case FUTEX_WAIT_BITSET:
2488                 ret = futex_wait(uaddr, fshared, val, timeout, val3, clockrt);
2489                 break;
2490         case FUTEX_WAKE:
2491                 val3 = FUTEX_BITSET_MATCH_ANY;
2492         case FUTEX_WAKE_BITSET:
2493                 ret = futex_wake(uaddr, fshared, val, val3);
2494                 break;
2495         case FUTEX_REQUEUE:
2496                 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL, 0);
2497                 break;
2498         case FUTEX_CMP_REQUEUE:
2499                 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3,
2500                                     0);
2501                 break;
2502         case FUTEX_WAKE_OP:
2503                 ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3);
2504                 break;
2505         case FUTEX_LOCK_PI:
2506                 if (futex_cmpxchg_enabled)
2507                         ret = futex_lock_pi(uaddr, fshared, val, timeout, 0);
2508                 break;
2509         case FUTEX_UNLOCK_PI:
2510                 if (futex_cmpxchg_enabled)
2511                         ret = futex_unlock_pi(uaddr, fshared);
2512                 break;
2513         case FUTEX_TRYLOCK_PI:
2514                 if (futex_cmpxchg_enabled)
2515                         ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1);
2516                 break;
2517         case FUTEX_WAIT_REQUEUE_PI:
2518                 val3 = FUTEX_BITSET_MATCH_ANY;
2519                 ret = futex_wait_requeue_pi(uaddr, fshared, val, timeout, val3,
2520                                             clockrt, uaddr2);
2521                 break;
2522         case FUTEX_CMP_REQUEUE_PI:
2523                 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3,
2524                                     1);
2525                 break;
2526         default:
2527                 ret = -ENOSYS;
2528         }
2529         return ret;
2530 }
2531
2532
2533 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
2534                 struct timespec __user *, utime, u32 __user *, uaddr2,
2535                 u32, val3)
2536 {
2537         struct timespec ts;
2538         ktime_t t, *tp = NULL;
2539         u32 val2 = 0;
2540         int cmd = op & FUTEX_CMD_MASK;
2541
2542         if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
2543                       cmd == FUTEX_WAIT_BITSET ||
2544                       cmd == FUTEX_WAIT_REQUEUE_PI)) {
2545                 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
2546                         return -EFAULT;
2547                 if (!timespec_valid(&ts))
2548                         return -EINVAL;
2549
2550                 t = timespec_to_ktime(ts);
2551                 if (cmd == FUTEX_WAIT)
2552                         t = ktime_add_safe(ktime_get(), t);
2553                 tp = &t;
2554         }
2555         /*
2556          * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
2557          * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
2558          */
2559         if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
2560             cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
2561                 val2 = (u32) (unsigned long) utime;
2562
2563         return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
2564 }
2565
2566 static int __init futex_init(void)
2567 {
2568         u32 curval;
2569         int i;
2570
2571         /*
2572          * This will fail and we want it. Some arch implementations do
2573          * runtime detection of the futex_atomic_cmpxchg_inatomic()
2574          * functionality. We want to know that before we call in any
2575          * of the complex code paths. Also we want to prevent
2576          * registration of robust lists in that case. NULL is
2577          * guaranteed to fault and we get -EFAULT on functional
2578          * implementation, the non functional ones will return
2579          * -ENOSYS.
2580          */
2581         curval = cmpxchg_futex_value_locked(NULL, 0, 0);
2582         if (curval == -EFAULT)
2583                 futex_cmpxchg_enabled = 1;
2584
2585         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
2586                 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
2587                 spin_lock_init(&futex_queues[i].lock);
2588         }
2589
2590         return 0;
2591 }
2592 __initcall(futex_init);