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