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