685ee2362a5e3eebc700cfb9ceedb921c4552cdb
[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  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
20  *  enough at me, Linus for the original (flawed) idea, Matthew
21  *  Kirkwood for proof-of-concept implementation.
22  *
23  *  "The futexes are also cursed."
24  *  "But they come in a choice of three flavours!"
25  *
26  *  This program is free software; you can redistribute it and/or modify
27  *  it under the terms of the GNU General Public License as published by
28  *  the Free Software Foundation; either version 2 of the License, or
29  *  (at your option) any later version.
30  *
31  *  This program is distributed in the hope that it will be useful,
32  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
33  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34  *  GNU General Public License for more details.
35  *
36  *  You should have received a copy of the GNU General Public License
37  *  along with this program; if not, write to the Free Software
38  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
39  */
40 #include <linux/slab.h>
41 #include <linux/poll.h>
42 #include <linux/fs.h>
43 #include <linux/file.h>
44 #include <linux/jhash.h>
45 #include <linux/init.h>
46 #include <linux/futex.h>
47 #include <linux/mount.h>
48 #include <linux/pagemap.h>
49 #include <linux/syscalls.h>
50 #include <linux/signal.h>
51 #include <linux/module.h>
52 #include <asm/futex.h>
53
54 #include "rtmutex_common.h"
55
56 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
57
58 /*
59  * Priority Inheritance state:
60  */
61 struct futex_pi_state {
62         /*
63          * list of 'owned' pi_state instances - these have to be
64          * cleaned up in do_exit() if the task exits prematurely:
65          */
66         struct list_head list;
67
68         /*
69          * The PI object:
70          */
71         struct rt_mutex pi_mutex;
72
73         struct task_struct *owner;
74         atomic_t refcount;
75
76         union futex_key key;
77 };
78
79 /*
80  * We use this hashed waitqueue instead of a normal wait_queue_t, so
81  * we can wake only the relevant ones (hashed queues may be shared).
82  *
83  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
84  * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
85  * The order of wakup is always to make the first condition true, then
86  * wake up q->waiters, then make the second condition true.
87  */
88 struct futex_q {
89         struct plist_node list;
90         wait_queue_head_t waiters;
91
92         /* Which hash list lock to use: */
93         spinlock_t *lock_ptr;
94
95         /* Key which the futex is hashed on: */
96         union futex_key key;
97
98         /* For fd, sigio sent using these: */
99         int fd;
100         struct file *filp;
101
102         /* Optional priority inheritance state: */
103         struct futex_pi_state *pi_state;
104         struct task_struct *task;
105 };
106
107 /*
108  * Split the global futex_lock into every hash list lock.
109  */
110 struct futex_hash_bucket {
111         spinlock_t lock;
112         struct plist_head chain;
113 };
114
115 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
116
117 /* Futex-fs vfsmount entry: */
118 static struct vfsmount *futex_mnt;
119
120 /*
121  * We hash on the keys returned from get_futex_key (see below).
122  */
123 static struct futex_hash_bucket *hash_futex(union futex_key *key)
124 {
125         u32 hash = jhash2((u32*)&key->both.word,
126                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
127                           key->both.offset);
128         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
129 }
130
131 /*
132  * Return 1 if two futex_keys are equal, 0 otherwise.
133  */
134 static inline int match_futex(union futex_key *key1, union futex_key *key2)
135 {
136         return (key1->both.word == key2->both.word
137                 && key1->both.ptr == key2->both.ptr
138                 && key1->both.offset == key2->both.offset);
139 }
140
141 /*
142  * Get parameters which are the keys for a futex.
143  *
144  * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
145  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
146  * We can usually work out the index without swapping in the page.
147  *
148  * Returns: 0, or negative error code.
149  * The key words are stored in *key on success.
150  *
151  * Should be called with &current->mm->mmap_sem but NOT any spinlocks.
152  */
153 int get_futex_key(u32 __user *uaddr, union futex_key *key)
154 {
155         unsigned long address = (unsigned long)uaddr;
156         struct mm_struct *mm = current->mm;
157         struct vm_area_struct *vma;
158         struct page *page;
159         int err;
160
161         /*
162          * The futex address must be "naturally" aligned.
163          */
164         key->both.offset = address % PAGE_SIZE;
165         if (unlikely((key->both.offset % sizeof(u32)) != 0))
166                 return -EINVAL;
167         address -= key->both.offset;
168
169         /*
170          * The futex is hashed differently depending on whether
171          * it's in a shared or private mapping.  So check vma first.
172          */
173         vma = find_extend_vma(mm, address);
174         if (unlikely(!vma))
175                 return -EFAULT;
176
177         /*
178          * Permissions.
179          */
180         if (unlikely((vma->vm_flags & (VM_IO|VM_READ)) != VM_READ))
181                 return (vma->vm_flags & VM_IO) ? -EPERM : -EACCES;
182
183         /*
184          * Private mappings are handled in a simple way.
185          *
186          * NOTE: When userspace waits on a MAP_SHARED mapping, even if
187          * it's a read-only handle, it's expected that futexes attach to
188          * the object not the particular process.  Therefore we use
189          * VM_MAYSHARE here, not VM_SHARED which is restricted to shared
190          * mappings of _writable_ handles.
191          */
192         if (likely(!(vma->vm_flags & VM_MAYSHARE))) {
193                 key->private.mm = mm;
194                 key->private.address = address;
195                 return 0;
196         }
197
198         /*
199          * Linear file mappings are also simple.
200          */
201         key->shared.inode = vma->vm_file->f_path.dentry->d_inode;
202         key->both.offset++; /* Bit 0 of offset indicates inode-based key. */
203         if (likely(!(vma->vm_flags & VM_NONLINEAR))) {
204                 key->shared.pgoff = (((address - vma->vm_start) >> PAGE_SHIFT)
205                                      + vma->vm_pgoff);
206                 return 0;
207         }
208
209         /*
210          * We could walk the page table to read the non-linear
211          * pte, and get the page index without fetching the page
212          * from swap.  But that's a lot of code to duplicate here
213          * for a rare case, so we simply fetch the page.
214          */
215         err = get_user_pages(current, mm, address, 1, 0, 0, &page, NULL);
216         if (err >= 0) {
217                 key->shared.pgoff =
218                         page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
219                 put_page(page);
220                 return 0;
221         }
222         return err;
223 }
224 EXPORT_SYMBOL_GPL(get_futex_key);
225
226 /*
227  * Take a reference to the resource addressed by a key.
228  * Can be called while holding spinlocks.
229  *
230  * NOTE: mmap_sem MUST be held between get_futex_key() and calling this
231  * function, if it is called at all.  mmap_sem keeps key->shared.inode valid.
232  */
233 inline void get_futex_key_refs(union futex_key *key)
234 {
235         if (key->both.ptr != 0) {
236                 if (key->both.offset & 1)
237                         atomic_inc(&key->shared.inode->i_count);
238                 else
239                         atomic_inc(&key->private.mm->mm_count);
240         }
241 }
242 EXPORT_SYMBOL_GPL(get_futex_key_refs);
243
244 /*
245  * Drop a reference to the resource addressed by a key.
246  * The hash bucket spinlock must not be held.
247  */
248 void drop_futex_key_refs(union futex_key *key)
249 {
250         if (key->both.ptr != 0) {
251                 if (key->both.offset & 1)
252                         iput(key->shared.inode);
253                 else
254                         mmdrop(key->private.mm);
255         }
256 }
257 EXPORT_SYMBOL_GPL(drop_futex_key_refs);
258
259 static inline int get_futex_value_locked(u32 *dest, u32 __user *from)
260 {
261         int ret;
262
263         pagefault_disable();
264         ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
265         pagefault_enable();
266
267         return ret ? -EFAULT : 0;
268 }
269
270 /*
271  * Fault handling. Called with current->mm->mmap_sem held.
272  */
273 static int futex_handle_fault(unsigned long address, int attempt)
274 {
275         struct vm_area_struct * vma;
276         struct mm_struct *mm = current->mm;
277
278         if (attempt > 2 || !(vma = find_vma(mm, address)) ||
279             vma->vm_start > address || !(vma->vm_flags & VM_WRITE))
280                 return -EFAULT;
281
282         switch (handle_mm_fault(mm, vma, address, 1)) {
283         case VM_FAULT_MINOR:
284                 current->min_flt++;
285                 break;
286         case VM_FAULT_MAJOR:
287                 current->maj_flt++;
288                 break;
289         default:
290                 return -EFAULT;
291         }
292         return 0;
293 }
294
295 /*
296  * PI code:
297  */
298 static int refill_pi_state_cache(void)
299 {
300         struct futex_pi_state *pi_state;
301
302         if (likely(current->pi_state_cache))
303                 return 0;
304
305         pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
306
307         if (!pi_state)
308                 return -ENOMEM;
309
310         INIT_LIST_HEAD(&pi_state->list);
311         /* pi_mutex gets initialized later */
312         pi_state->owner = NULL;
313         atomic_set(&pi_state->refcount, 1);
314
315         current->pi_state_cache = pi_state;
316
317         return 0;
318 }
319
320 static struct futex_pi_state * alloc_pi_state(void)
321 {
322         struct futex_pi_state *pi_state = current->pi_state_cache;
323
324         WARN_ON(!pi_state);
325         current->pi_state_cache = NULL;
326
327         return pi_state;
328 }
329
330 static void free_pi_state(struct futex_pi_state *pi_state)
331 {
332         if (!atomic_dec_and_test(&pi_state->refcount))
333                 return;
334
335         /*
336          * If pi_state->owner is NULL, the owner is most probably dying
337          * and has cleaned up the pi_state already
338          */
339         if (pi_state->owner) {
340                 spin_lock_irq(&pi_state->owner->pi_lock);
341                 list_del_init(&pi_state->list);
342                 spin_unlock_irq(&pi_state->owner->pi_lock);
343
344                 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
345         }
346
347         if (current->pi_state_cache)
348                 kfree(pi_state);
349         else {
350                 /*
351                  * pi_state->list is already empty.
352                  * clear pi_state->owner.
353                  * refcount is at 0 - put it back to 1.
354                  */
355                 pi_state->owner = NULL;
356                 atomic_set(&pi_state->refcount, 1);
357                 current->pi_state_cache = pi_state;
358         }
359 }
360
361 /*
362  * Look up the task based on what TID userspace gave us.
363  * We dont trust it.
364  */
365 static struct task_struct * futex_find_get_task(pid_t pid)
366 {
367         struct task_struct *p;
368
369         rcu_read_lock();
370         p = find_task_by_pid(pid);
371         if (!p)
372                 goto out_unlock;
373         if ((current->euid != p->euid) && (current->euid != p->uid)) {
374                 p = NULL;
375                 goto out_unlock;
376         }
377         if (p->exit_state != 0) {
378                 p = NULL;
379                 goto out_unlock;
380         }
381         get_task_struct(p);
382 out_unlock:
383         rcu_read_unlock();
384
385         return p;
386 }
387
388 /*
389  * This task is holding PI mutexes at exit time => bad.
390  * Kernel cleans up PI-state, but userspace is likely hosed.
391  * (Robust-futex cleanup is separate and might save the day for userspace.)
392  */
393 void exit_pi_state_list(struct task_struct *curr)
394 {
395         struct list_head *next, *head = &curr->pi_state_list;
396         struct futex_pi_state *pi_state;
397         struct futex_hash_bucket *hb;
398         union futex_key key;
399
400         /*
401          * We are a ZOMBIE and nobody can enqueue itself on
402          * pi_state_list anymore, but we have to be careful
403          * versus waiters unqueueing themselves:
404          */
405         spin_lock_irq(&curr->pi_lock);
406         while (!list_empty(head)) {
407
408                 next = head->next;
409                 pi_state = list_entry(next, struct futex_pi_state, list);
410                 key = pi_state->key;
411                 hb = hash_futex(&key);
412                 spin_unlock_irq(&curr->pi_lock);
413
414                 spin_lock(&hb->lock);
415
416                 spin_lock_irq(&curr->pi_lock);
417                 /*
418                  * We dropped the pi-lock, so re-check whether this
419                  * task still owns the PI-state:
420                  */
421                 if (head->next != next) {
422                         spin_unlock(&hb->lock);
423                         continue;
424                 }
425
426                 WARN_ON(pi_state->owner != curr);
427                 WARN_ON(list_empty(&pi_state->list));
428                 list_del_init(&pi_state->list);
429                 pi_state->owner = NULL;
430                 spin_unlock_irq(&curr->pi_lock);
431
432                 rt_mutex_unlock(&pi_state->pi_mutex);
433
434                 spin_unlock(&hb->lock);
435
436                 spin_lock_irq(&curr->pi_lock);
437         }
438         spin_unlock_irq(&curr->pi_lock);
439 }
440
441 static int
442 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb, struct futex_q *me)
443 {
444         struct futex_pi_state *pi_state = NULL;
445         struct futex_q *this, *next;
446         struct plist_head *head;
447         struct task_struct *p;
448         pid_t pid;
449
450         head = &hb->chain;
451
452         plist_for_each_entry_safe(this, next, head, list) {
453                 if (match_futex(&this->key, &me->key)) {
454                         /*
455                          * Another waiter already exists - bump up
456                          * the refcount and return its pi_state:
457                          */
458                         pi_state = this->pi_state;
459                         /*
460                          * Userspace might have messed up non PI and PI futexes
461                          */
462                         if (unlikely(!pi_state))
463                                 return -EINVAL;
464
465                         WARN_ON(!atomic_read(&pi_state->refcount));
466
467                         atomic_inc(&pi_state->refcount);
468                         me->pi_state = pi_state;
469
470                         return 0;
471                 }
472         }
473
474         /*
475          * We are the first waiter - try to look up the real owner and attach
476          * the new pi_state to it, but bail out when the owner died bit is set
477          * and TID = 0:
478          */
479         pid = uval & FUTEX_TID_MASK;
480         if (!pid && (uval & FUTEX_OWNER_DIED))
481                 return -ESRCH;
482         p = futex_find_get_task(pid);
483         if (!p)
484                 return -ESRCH;
485
486         pi_state = alloc_pi_state();
487
488         /*
489          * Initialize the pi_mutex in locked state and make 'p'
490          * the owner of it:
491          */
492         rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
493
494         /* Store the key for possible exit cleanups: */
495         pi_state->key = me->key;
496
497         spin_lock_irq(&p->pi_lock);
498         WARN_ON(!list_empty(&pi_state->list));
499         list_add(&pi_state->list, &p->pi_state_list);
500         pi_state->owner = p;
501         spin_unlock_irq(&p->pi_lock);
502
503         put_task_struct(p);
504
505         me->pi_state = pi_state;
506
507         return 0;
508 }
509
510 /*
511  * The hash bucket lock must be held when this is called.
512  * Afterwards, the futex_q must not be accessed.
513  */
514 static void wake_futex(struct futex_q *q)
515 {
516         plist_del(&q->list, &q->list.plist);
517         if (q->filp)
518                 send_sigio(&q->filp->f_owner, q->fd, POLL_IN);
519         /*
520          * The lock in wake_up_all() is a crucial memory barrier after the
521          * plist_del() and also before assigning to q->lock_ptr.
522          */
523         wake_up_all(&q->waiters);
524         /*
525          * The waiting task can free the futex_q as soon as this is written,
526          * without taking any locks.  This must come last.
527          *
528          * A memory barrier is required here to prevent the following store
529          * to lock_ptr from getting ahead of the wakeup. Clearing the lock
530          * at the end of wake_up_all() does not prevent this store from
531          * moving.
532          */
533         smp_wmb();
534         q->lock_ptr = NULL;
535 }
536
537 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
538 {
539         struct task_struct *new_owner;
540         struct futex_pi_state *pi_state = this->pi_state;
541         u32 curval, newval;
542
543         if (!pi_state)
544                 return -EINVAL;
545
546         spin_lock(&pi_state->pi_mutex.wait_lock);
547         new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
548
549         /*
550          * This happens when we have stolen the lock and the original
551          * pending owner did not enqueue itself back on the rt_mutex.
552          * Thats not a tragedy. We know that way, that a lock waiter
553          * is on the fly. We make the futex_q waiter the pending owner.
554          */
555         if (!new_owner)
556                 new_owner = this->task;
557
558         /*
559          * We pass it to the next owner. (The WAITERS bit is always
560          * kept enabled while there is PI state around. We must also
561          * preserve the owner died bit.)
562          */
563         if (!(uval & FUTEX_OWNER_DIED)) {
564                 newval = FUTEX_WAITERS | new_owner->pid;
565
566                 pagefault_disable();
567                 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
568                 pagefault_enable();
569                 if (curval == -EFAULT)
570                         return -EFAULT;
571                 if (curval != uval)
572                         return -EINVAL;
573         }
574
575         spin_lock_irq(&pi_state->owner->pi_lock);
576         WARN_ON(list_empty(&pi_state->list));
577         list_del_init(&pi_state->list);
578         spin_unlock_irq(&pi_state->owner->pi_lock);
579
580         spin_lock_irq(&new_owner->pi_lock);
581         WARN_ON(!list_empty(&pi_state->list));
582         list_add(&pi_state->list, &new_owner->pi_state_list);
583         pi_state->owner = new_owner;
584         spin_unlock_irq(&new_owner->pi_lock);
585
586         spin_unlock(&pi_state->pi_mutex.wait_lock);
587         rt_mutex_unlock(&pi_state->pi_mutex);
588
589         return 0;
590 }
591
592 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
593 {
594         u32 oldval;
595
596         /*
597          * There is no waiter, so we unlock the futex. The owner died
598          * bit has not to be preserved here. We are the owner:
599          */
600         pagefault_disable();
601         oldval = futex_atomic_cmpxchg_inatomic(uaddr, uval, 0);
602         pagefault_enable();
603
604         if (oldval == -EFAULT)
605                 return oldval;
606         if (oldval != uval)
607                 return -EAGAIN;
608
609         return 0;
610 }
611
612 /*
613  * Express the locking dependencies for lockdep:
614  */
615 static inline void
616 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
617 {
618         if (hb1 <= hb2) {
619                 spin_lock(&hb1->lock);
620                 if (hb1 < hb2)
621                         spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
622         } else { /* hb1 > hb2 */
623                 spin_lock(&hb2->lock);
624                 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
625         }
626 }
627
628 /*
629  * Wake up all waiters hashed on the physical page that is mapped
630  * to this virtual address:
631  */
632 static int futex_wake(u32 __user *uaddr, int nr_wake)
633 {
634         struct futex_hash_bucket *hb;
635         struct futex_q *this, *next;
636         struct plist_head *head;
637         union futex_key key;
638         int ret;
639
640         down_read(&current->mm->mmap_sem);
641
642         ret = get_futex_key(uaddr, &key);
643         if (unlikely(ret != 0))
644                 goto out;
645
646         hb = hash_futex(&key);
647         spin_lock(&hb->lock);
648         head = &hb->chain;
649
650         plist_for_each_entry_safe(this, next, head, list) {
651                 if (match_futex (&this->key, &key)) {
652                         if (this->pi_state) {
653                                 ret = -EINVAL;
654                                 break;
655                         }
656                         wake_futex(this);
657                         if (++ret >= nr_wake)
658                                 break;
659                 }
660         }
661
662         spin_unlock(&hb->lock);
663 out:
664         up_read(&current->mm->mmap_sem);
665         return ret;
666 }
667
668 /*
669  * Wake up all waiters hashed on the physical page that is mapped
670  * to this virtual address:
671  */
672 static int
673 futex_wake_op(u32 __user *uaddr1, u32 __user *uaddr2,
674               int nr_wake, int nr_wake2, int op)
675 {
676         union futex_key key1, key2;
677         struct futex_hash_bucket *hb1, *hb2;
678         struct plist_head *head;
679         struct futex_q *this, *next;
680         int ret, op_ret, attempt = 0;
681
682 retryfull:
683         down_read(&current->mm->mmap_sem);
684
685         ret = get_futex_key(uaddr1, &key1);
686         if (unlikely(ret != 0))
687                 goto out;
688         ret = get_futex_key(uaddr2, &key2);
689         if (unlikely(ret != 0))
690                 goto out;
691
692         hb1 = hash_futex(&key1);
693         hb2 = hash_futex(&key2);
694
695 retry:
696         double_lock_hb(hb1, hb2);
697
698         op_ret = futex_atomic_op_inuser(op, uaddr2);
699         if (unlikely(op_ret < 0)) {
700                 u32 dummy;
701
702                 spin_unlock(&hb1->lock);
703                 if (hb1 != hb2)
704                         spin_unlock(&hb2->lock);
705
706 #ifndef CONFIG_MMU
707                 /*
708                  * we don't get EFAULT from MMU faults if we don't have an MMU,
709                  * but we might get them from range checking
710                  */
711                 ret = op_ret;
712                 goto out;
713 #endif
714
715                 if (unlikely(op_ret != -EFAULT)) {
716                         ret = op_ret;
717                         goto out;
718                 }
719
720                 /*
721                  * futex_atomic_op_inuser needs to both read and write
722                  * *(int __user *)uaddr2, but we can't modify it
723                  * non-atomically.  Therefore, if get_user below is not
724                  * enough, we need to handle the fault ourselves, while
725                  * still holding the mmap_sem.
726                  */
727                 if (attempt++) {
728                         if (futex_handle_fault((unsigned long)uaddr2,
729                                                 attempt)) {
730                                 ret = -EFAULT;
731                                 goto out;
732                         }
733                         goto retry;
734                 }
735
736                 /*
737                  * If we would have faulted, release mmap_sem,
738                  * fault it in and start all over again.
739                  */
740                 up_read(&current->mm->mmap_sem);
741
742                 ret = get_user(dummy, uaddr2);
743                 if (ret)
744                         return ret;
745
746                 goto retryfull;
747         }
748
749         head = &hb1->chain;
750
751         plist_for_each_entry_safe(this, next, head, list) {
752                 if (match_futex (&this->key, &key1)) {
753                         wake_futex(this);
754                         if (++ret >= nr_wake)
755                                 break;
756                 }
757         }
758
759         if (op_ret > 0) {
760                 head = &hb2->chain;
761
762                 op_ret = 0;
763                 plist_for_each_entry_safe(this, next, head, list) {
764                         if (match_futex (&this->key, &key2)) {
765                                 wake_futex(this);
766                                 if (++op_ret >= nr_wake2)
767                                         break;
768                         }
769                 }
770                 ret += op_ret;
771         }
772
773         spin_unlock(&hb1->lock);
774         if (hb1 != hb2)
775                 spin_unlock(&hb2->lock);
776 out:
777         up_read(&current->mm->mmap_sem);
778         return ret;
779 }
780
781 /*
782  * Requeue all waiters hashed on one physical page to another
783  * physical page.
784  */
785 static int futex_requeue(u32 __user *uaddr1, u32 __user *uaddr2,
786                          int nr_wake, int nr_requeue, u32 *cmpval)
787 {
788         union futex_key key1, key2;
789         struct futex_hash_bucket *hb1, *hb2;
790         struct plist_head *head1;
791         struct futex_q *this, *next;
792         int ret, drop_count = 0;
793
794  retry:
795         down_read(&current->mm->mmap_sem);
796
797         ret = get_futex_key(uaddr1, &key1);
798         if (unlikely(ret != 0))
799                 goto out;
800         ret = get_futex_key(uaddr2, &key2);
801         if (unlikely(ret != 0))
802                 goto out;
803
804         hb1 = hash_futex(&key1);
805         hb2 = hash_futex(&key2);
806
807         double_lock_hb(hb1, hb2);
808
809         if (likely(cmpval != NULL)) {
810                 u32 curval;
811
812                 ret = get_futex_value_locked(&curval, uaddr1);
813
814                 if (unlikely(ret)) {
815                         spin_unlock(&hb1->lock);
816                         if (hb1 != hb2)
817                                 spin_unlock(&hb2->lock);
818
819                         /*
820                          * If we would have faulted, release mmap_sem, fault
821                          * it in and start all over again.
822                          */
823                         up_read(&current->mm->mmap_sem);
824
825                         ret = get_user(curval, uaddr1);
826
827                         if (!ret)
828                                 goto retry;
829
830                         return ret;
831                 }
832                 if (curval != *cmpval) {
833                         ret = -EAGAIN;
834                         goto out_unlock;
835                 }
836         }
837
838         head1 = &hb1->chain;
839         plist_for_each_entry_safe(this, next, head1, list) {
840                 if (!match_futex (&this->key, &key1))
841                         continue;
842                 if (++ret <= nr_wake) {
843                         wake_futex(this);
844                 } else {
845                         /*
846                          * If key1 and key2 hash to the same bucket, no need to
847                          * requeue.
848                          */
849                         if (likely(head1 != &hb2->chain)) {
850                                 plist_del(&this->list, &hb1->chain);
851                                 plist_add(&this->list, &hb2->chain);
852                                 this->lock_ptr = &hb2->lock;
853 #ifdef CONFIG_DEBUG_PI_LIST
854                                 this->list.plist.lock = &hb2->lock;
855 #endif
856                         }
857                         this->key = key2;
858                         get_futex_key_refs(&key2);
859                         drop_count++;
860
861                         if (ret - nr_wake >= nr_requeue)
862                                 break;
863                 }
864         }
865
866 out_unlock:
867         spin_unlock(&hb1->lock);
868         if (hb1 != hb2)
869                 spin_unlock(&hb2->lock);
870
871         /* drop_futex_key_refs() must be called outside the spinlocks. */
872         while (--drop_count >= 0)
873                 drop_futex_key_refs(&key1);
874
875 out:
876         up_read(&current->mm->mmap_sem);
877         return ret;
878 }
879
880 /* The key must be already stored in q->key. */
881 static inline struct futex_hash_bucket *
882 queue_lock(struct futex_q *q, int fd, struct file *filp)
883 {
884         struct futex_hash_bucket *hb;
885
886         q->fd = fd;
887         q->filp = filp;
888
889         init_waitqueue_head(&q->waiters);
890
891         get_futex_key_refs(&q->key);
892         hb = hash_futex(&q->key);
893         q->lock_ptr = &hb->lock;
894
895         spin_lock(&hb->lock);
896         return hb;
897 }
898
899 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
900 {
901         int prio;
902
903         /*
904          * The priority used to register this element is
905          * - either the real thread-priority for the real-time threads
906          * (i.e. threads with a priority lower than MAX_RT_PRIO)
907          * - or MAX_RT_PRIO for non-RT threads.
908          * Thus, all RT-threads are woken first in priority order, and
909          * the others are woken last, in FIFO order.
910          */
911         prio = min(current->normal_prio, MAX_RT_PRIO);
912
913         plist_node_init(&q->list, prio);
914 #ifdef CONFIG_DEBUG_PI_LIST
915         q->list.plist.lock = &hb->lock;
916 #endif
917         plist_add(&q->list, &hb->chain);
918         q->task = current;
919         spin_unlock(&hb->lock);
920 }
921
922 static inline void
923 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
924 {
925         spin_unlock(&hb->lock);
926         drop_futex_key_refs(&q->key);
927 }
928
929 /*
930  * queue_me and unqueue_me must be called as a pair, each
931  * exactly once.  They are called with the hashed spinlock held.
932  */
933
934 /* The key must be already stored in q->key. */
935 static void queue_me(struct futex_q *q, int fd, struct file *filp)
936 {
937         struct futex_hash_bucket *hb;
938
939         hb = queue_lock(q, fd, filp);
940         __queue_me(q, hb);
941 }
942
943 /* Return 1 if we were still queued (ie. 0 means we were woken) */
944 static int unqueue_me(struct futex_q *q)
945 {
946         spinlock_t *lock_ptr;
947         int ret = 0;
948
949         /* In the common case we don't take the spinlock, which is nice. */
950  retry:
951         lock_ptr = q->lock_ptr;
952         barrier();
953         if (lock_ptr != 0) {
954                 spin_lock(lock_ptr);
955                 /*
956                  * q->lock_ptr can change between reading it and
957                  * spin_lock(), causing us to take the wrong lock.  This
958                  * corrects the race condition.
959                  *
960                  * Reasoning goes like this: if we have the wrong lock,
961                  * q->lock_ptr must have changed (maybe several times)
962                  * between reading it and the spin_lock().  It can
963                  * change again after the spin_lock() but only if it was
964                  * already changed before the spin_lock().  It cannot,
965                  * however, change back to the original value.  Therefore
966                  * we can detect whether we acquired the correct lock.
967                  */
968                 if (unlikely(lock_ptr != q->lock_ptr)) {
969                         spin_unlock(lock_ptr);
970                         goto retry;
971                 }
972                 WARN_ON(plist_node_empty(&q->list));
973                 plist_del(&q->list, &q->list.plist);
974
975                 BUG_ON(q->pi_state);
976
977                 spin_unlock(lock_ptr);
978                 ret = 1;
979         }
980
981         drop_futex_key_refs(&q->key);
982         return ret;
983 }
984
985 /*
986  * PI futexes can not be requeued and must remove themself from the
987  * hash bucket. The hash bucket lock is held on entry and dropped here.
988  */
989 static void unqueue_me_pi(struct futex_q *q, struct futex_hash_bucket *hb)
990 {
991         WARN_ON(plist_node_empty(&q->list));
992         plist_del(&q->list, &q->list.plist);
993
994         BUG_ON(!q->pi_state);
995         free_pi_state(q->pi_state);
996         q->pi_state = NULL;
997
998         spin_unlock(&hb->lock);
999
1000         drop_futex_key_refs(&q->key);
1001 }
1002
1003 static long futex_wait_restart(struct restart_block *restart);
1004 static int futex_wait_abstime(u32 __user *uaddr, u32 val,
1005                         int timed, unsigned long abs_time)
1006 {
1007         struct task_struct *curr = current;
1008         DECLARE_WAITQUEUE(wait, curr);
1009         struct futex_hash_bucket *hb;
1010         struct futex_q q;
1011         unsigned long time_left = 0;
1012         u32 uval;
1013         int ret;
1014
1015         q.pi_state = NULL;
1016  retry:
1017         down_read(&curr->mm->mmap_sem);
1018
1019         ret = get_futex_key(uaddr, &q.key);
1020         if (unlikely(ret != 0))
1021                 goto out_release_sem;
1022
1023         hb = queue_lock(&q, -1, NULL);
1024
1025         /*
1026          * Access the page AFTER the futex is queued.
1027          * Order is important:
1028          *
1029          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1030          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
1031          *
1032          * The basic logical guarantee of a futex is that it blocks ONLY
1033          * if cond(var) is known to be true at the time of blocking, for
1034          * any cond.  If we queued after testing *uaddr, that would open
1035          * a race condition where we could block indefinitely with
1036          * cond(var) false, which would violate the guarantee.
1037          *
1038          * A consequence is that futex_wait() can return zero and absorb
1039          * a wakeup when *uaddr != val on entry to the syscall.  This is
1040          * rare, but normal.
1041          *
1042          * We hold the mmap semaphore, so the mapping cannot have changed
1043          * since we looked it up in get_futex_key.
1044          */
1045         ret = get_futex_value_locked(&uval, uaddr);
1046
1047         if (unlikely(ret)) {
1048                 queue_unlock(&q, hb);
1049
1050                 /*
1051                  * If we would have faulted, release mmap_sem, fault it in and
1052                  * start all over again.
1053                  */
1054                 up_read(&curr->mm->mmap_sem);
1055
1056                 ret = get_user(uval, uaddr);
1057
1058                 if (!ret)
1059                         goto retry;
1060                 return ret;
1061         }
1062         ret = -EWOULDBLOCK;
1063         if (uval != val)
1064                 goto out_unlock_release_sem;
1065
1066         /* Only actually queue if *uaddr contained val.  */
1067         __queue_me(&q, hb);
1068
1069         /*
1070          * Now the futex is queued and we have checked the data, we
1071          * don't want to hold mmap_sem while we sleep.
1072          */
1073         up_read(&curr->mm->mmap_sem);
1074
1075         /*
1076          * There might have been scheduling since the queue_me(), as we
1077          * cannot hold a spinlock across the get_user() in case it
1078          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1079          * queueing ourselves into the futex hash.  This code thus has to
1080          * rely on the futex_wake() code removing us from hash when it
1081          * wakes us up.
1082          */
1083
1084         /* add_wait_queue is the barrier after __set_current_state. */
1085         __set_current_state(TASK_INTERRUPTIBLE);
1086         add_wait_queue(&q.waiters, &wait);
1087         /*
1088          * !plist_node_empty() is safe here without any lock.
1089          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1090          */
1091         time_left = 0;
1092         if (likely(!plist_node_empty(&q.list))) {
1093                 unsigned long rel_time;
1094
1095                 if (timed) {
1096                         unsigned long now = jiffies;
1097                         if (time_after(now, abs_time))
1098                                 rel_time = 0;
1099                         else
1100                                 rel_time = abs_time - now;
1101                 } else
1102                         rel_time = MAX_SCHEDULE_TIMEOUT;
1103
1104                 time_left = schedule_timeout(rel_time);
1105         }
1106         __set_current_state(TASK_RUNNING);
1107
1108         /*
1109          * NOTE: we don't remove ourselves from the waitqueue because
1110          * we are the only user of it.
1111          */
1112
1113         /* If we were woken (and unqueued), we succeeded, whatever. */
1114         if (!unqueue_me(&q))
1115                 return 0;
1116         if (time_left == 0)
1117                 return -ETIMEDOUT;
1118
1119         /*
1120          * We expect signal_pending(current), but another thread may
1121          * have handled it for us already.
1122          */
1123         if (time_left == MAX_SCHEDULE_TIMEOUT)
1124                 return -ERESTARTSYS;
1125         else {
1126                 struct restart_block *restart;
1127                 restart = &current_thread_info()->restart_block;
1128                 restart->fn = futex_wait_restart;
1129                 restart->arg0 = (unsigned long)uaddr;
1130                 restart->arg1 = (unsigned long)val;
1131                 restart->arg2 = (unsigned long)timed;
1132                 restart->arg3 = abs_time;
1133                 return -ERESTART_RESTARTBLOCK;
1134         }
1135
1136  out_unlock_release_sem:
1137         queue_unlock(&q, hb);
1138
1139  out_release_sem:
1140         up_read(&curr->mm->mmap_sem);
1141         return ret;
1142 }
1143
1144 static int futex_wait(u32 __user *uaddr, u32 val, unsigned long rel_time)
1145 {
1146         int timed = (rel_time != MAX_SCHEDULE_TIMEOUT);
1147         return futex_wait_abstime(uaddr, val, timed, jiffies+rel_time);
1148 }
1149
1150 static long futex_wait_restart(struct restart_block *restart)
1151 {
1152         u32 __user *uaddr = (u32 __user *)restart->arg0;
1153         u32 val = (u32)restart->arg1;
1154         int timed = (int)restart->arg2;
1155         unsigned long abs_time = restart->arg3;
1156
1157         restart->fn = do_no_restart_syscall;
1158         return (long)futex_wait_abstime(uaddr, val, timed, abs_time);
1159 }
1160
1161
1162 /*
1163  * Userspace tried a 0 -> TID atomic transition of the futex value
1164  * and failed. The kernel side here does the whole locking operation:
1165  * if there are waiters then it will block, it does PI, etc. (Due to
1166  * races the kernel might see a 0 value of the futex too.)
1167  */
1168 static int futex_lock_pi(u32 __user *uaddr, int detect, unsigned long sec,
1169                          long nsec, int trylock)
1170 {
1171         struct hrtimer_sleeper timeout, *to = NULL;
1172         struct task_struct *curr = current;
1173         struct futex_hash_bucket *hb;
1174         u32 uval, newval, curval;
1175         struct futex_q q;
1176         int ret, attempt = 0;
1177
1178         if (refill_pi_state_cache())
1179                 return -ENOMEM;
1180
1181         if (sec != MAX_SCHEDULE_TIMEOUT) {
1182                 to = &timeout;
1183                 hrtimer_init(&to->timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
1184                 hrtimer_init_sleeper(to, current);
1185                 to->timer.expires = ktime_set(sec, nsec);
1186         }
1187
1188         q.pi_state = NULL;
1189  retry:
1190         down_read(&curr->mm->mmap_sem);
1191
1192         ret = get_futex_key(uaddr, &q.key);
1193         if (unlikely(ret != 0))
1194                 goto out_release_sem;
1195
1196         hb = queue_lock(&q, -1, NULL);
1197
1198  retry_locked:
1199         /*
1200          * To avoid races, we attempt to take the lock here again
1201          * (by doing a 0 -> TID atomic cmpxchg), while holding all
1202          * the locks. It will most likely not succeed.
1203          */
1204         newval = current->pid;
1205
1206         pagefault_disable();
1207         curval = futex_atomic_cmpxchg_inatomic(uaddr, 0, newval);
1208         pagefault_enable();
1209
1210         if (unlikely(curval == -EFAULT))
1211                 goto uaddr_faulted;
1212
1213         /* We own the lock already */
1214         if (unlikely((curval & FUTEX_TID_MASK) == current->pid)) {
1215                 if (!detect && 0)
1216                         force_sig(SIGKILL, current);
1217                 ret = -EDEADLK;
1218                 goto out_unlock_release_sem;
1219         }
1220
1221         /*
1222          * Surprise - we got the lock. Just return
1223          * to userspace:
1224          */
1225         if (unlikely(!curval))
1226                 goto out_unlock_release_sem;
1227
1228         uval = curval;
1229         newval = uval | FUTEX_WAITERS;
1230
1231         pagefault_disable();
1232         curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
1233         pagefault_enable();
1234
1235         if (unlikely(curval == -EFAULT))
1236                 goto uaddr_faulted;
1237         if (unlikely(curval != uval))
1238                 goto retry_locked;
1239
1240         /*
1241          * We dont have the lock. Look up the PI state (or create it if
1242          * we are the first waiter):
1243          */
1244         ret = lookup_pi_state(uval, hb, &q);
1245
1246         if (unlikely(ret)) {
1247                 /*
1248                  * There were no waiters and the owner task lookup
1249                  * failed. When the OWNER_DIED bit is set, then we
1250                  * know that this is a robust futex and we actually
1251                  * take the lock. This is safe as we are protected by
1252                  * the hash bucket lock. We also set the waiters bit
1253                  * unconditionally here, to simplify glibc handling of
1254                  * multiple tasks racing to acquire the lock and
1255                  * cleanup the problems which were left by the dead
1256                  * owner.
1257                  */
1258                 if (curval & FUTEX_OWNER_DIED) {
1259                         uval = newval;
1260                         newval = current->pid |
1261                                 FUTEX_OWNER_DIED | FUTEX_WAITERS;
1262
1263                         pagefault_disable();
1264                         curval = futex_atomic_cmpxchg_inatomic(uaddr,
1265                                                                uval, newval);
1266                         pagefault_enable();
1267
1268                         if (unlikely(curval == -EFAULT))
1269                                 goto uaddr_faulted;
1270                         if (unlikely(curval != uval))
1271                                 goto retry_locked;
1272                         ret = 0;
1273                 }
1274                 goto out_unlock_release_sem;
1275         }
1276
1277         /*
1278          * Only actually queue now that the atomic ops are done:
1279          */
1280         __queue_me(&q, hb);
1281
1282         /*
1283          * Now the futex is queued and we have checked the data, we
1284          * don't want to hold mmap_sem while we sleep.
1285          */
1286         up_read(&curr->mm->mmap_sem);
1287
1288         WARN_ON(!q.pi_state);
1289         /*
1290          * Block on the PI mutex:
1291          */
1292         if (!trylock)
1293                 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1294         else {
1295                 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1296                 /* Fixup the trylock return value: */
1297                 ret = ret ? 0 : -EWOULDBLOCK;
1298         }
1299
1300         down_read(&curr->mm->mmap_sem);
1301         spin_lock(q.lock_ptr);
1302
1303         /*
1304          * Got the lock. We might not be the anticipated owner if we
1305          * did a lock-steal - fix up the PI-state in that case.
1306          */
1307         if (!ret && q.pi_state->owner != curr) {
1308                 u32 newtid = current->pid | FUTEX_WAITERS;
1309
1310                 /* Owner died? */
1311                 if (q.pi_state->owner != NULL) {
1312                         spin_lock_irq(&q.pi_state->owner->pi_lock);
1313                         WARN_ON(list_empty(&q.pi_state->list));
1314                         list_del_init(&q.pi_state->list);
1315                         spin_unlock_irq(&q.pi_state->owner->pi_lock);
1316                 } else
1317                         newtid |= FUTEX_OWNER_DIED;
1318
1319                 q.pi_state->owner = current;
1320
1321                 spin_lock_irq(&current->pi_lock);
1322                 WARN_ON(!list_empty(&q.pi_state->list));
1323                 list_add(&q.pi_state->list, &current->pi_state_list);
1324                 spin_unlock_irq(&current->pi_lock);
1325
1326                 /* Unqueue and drop the lock */
1327                 unqueue_me_pi(&q, hb);
1328                 up_read(&curr->mm->mmap_sem);
1329                 /*
1330                  * We own it, so we have to replace the pending owner
1331                  * TID. This must be atomic as we have preserve the
1332                  * owner died bit here.
1333                  */
1334                 ret = get_user(uval, uaddr);
1335                 while (!ret) {
1336                         newval = (uval & FUTEX_OWNER_DIED) | newtid;
1337                         curval = futex_atomic_cmpxchg_inatomic(uaddr,
1338                                                                uval, newval);
1339                         if (curval == -EFAULT)
1340                                 ret = -EFAULT;
1341                         if (curval == uval)
1342                                 break;
1343                         uval = curval;
1344                 }
1345         } else {
1346                 /*
1347                  * Catch the rare case, where the lock was released
1348                  * when we were on the way back before we locked
1349                  * the hash bucket.
1350                  */
1351                 if (ret && q.pi_state->owner == curr) {
1352                         if (rt_mutex_trylock(&q.pi_state->pi_mutex))
1353                                 ret = 0;
1354                 }
1355                 /* Unqueue and drop the lock */
1356                 unqueue_me_pi(&q, hb);
1357                 up_read(&curr->mm->mmap_sem);
1358         }
1359
1360         if (!detect && ret == -EDEADLK && 0)
1361                 force_sig(SIGKILL, current);
1362
1363         return ret != -EINTR ? ret : -ERESTARTNOINTR;
1364
1365  out_unlock_release_sem:
1366         queue_unlock(&q, hb);
1367
1368  out_release_sem:
1369         up_read(&curr->mm->mmap_sem);
1370         return ret;
1371
1372  uaddr_faulted:
1373         /*
1374          * We have to r/w  *(int __user *)uaddr, but we can't modify it
1375          * non-atomically.  Therefore, if get_user below is not
1376          * enough, we need to handle the fault ourselves, while
1377          * still holding the mmap_sem.
1378          */
1379         if (attempt++) {
1380                 if (futex_handle_fault((unsigned long)uaddr, attempt)) {
1381                         ret = -EFAULT;
1382                         goto out_unlock_release_sem;
1383                 }
1384                 goto retry_locked;
1385         }
1386
1387         queue_unlock(&q, hb);
1388         up_read(&curr->mm->mmap_sem);
1389
1390         ret = get_user(uval, uaddr);
1391         if (!ret && (uval != -EFAULT))
1392                 goto retry;
1393
1394         return ret;
1395 }
1396
1397 /*
1398  * Userspace attempted a TID -> 0 atomic transition, and failed.
1399  * This is the in-kernel slowpath: we look up the PI state (if any),
1400  * and do the rt-mutex unlock.
1401  */
1402 static int futex_unlock_pi(u32 __user *uaddr)
1403 {
1404         struct futex_hash_bucket *hb;
1405         struct futex_q *this, *next;
1406         u32 uval;
1407         struct plist_head *head;
1408         union futex_key key;
1409         int ret, attempt = 0;
1410
1411 retry:
1412         if (get_user(uval, uaddr))
1413                 return -EFAULT;
1414         /*
1415          * We release only a lock we actually own:
1416          */
1417         if ((uval & FUTEX_TID_MASK) != current->pid)
1418                 return -EPERM;
1419         /*
1420          * First take all the futex related locks:
1421          */
1422         down_read(&current->mm->mmap_sem);
1423
1424         ret = get_futex_key(uaddr, &key);
1425         if (unlikely(ret != 0))
1426                 goto out;
1427
1428         hb = hash_futex(&key);
1429         spin_lock(&hb->lock);
1430
1431 retry_locked:
1432         /*
1433          * To avoid races, try to do the TID -> 0 atomic transition
1434          * again. If it succeeds then we can return without waking
1435          * anyone else up:
1436          */
1437         if (!(uval & FUTEX_OWNER_DIED)) {
1438                 pagefault_disable();
1439                 uval = futex_atomic_cmpxchg_inatomic(uaddr, current->pid, 0);
1440                 pagefault_enable();
1441         }
1442
1443         if (unlikely(uval == -EFAULT))
1444                 goto pi_faulted;
1445         /*
1446          * Rare case: we managed to release the lock atomically,
1447          * no need to wake anyone else up:
1448          */
1449         if (unlikely(uval == current->pid))
1450                 goto out_unlock;
1451
1452         /*
1453          * Ok, other tasks may need to be woken up - check waiters
1454          * and do the wakeup if necessary:
1455          */
1456         head = &hb->chain;
1457
1458         plist_for_each_entry_safe(this, next, head, list) {
1459                 if (!match_futex (&this->key, &key))
1460                         continue;
1461                 ret = wake_futex_pi(uaddr, uval, this);
1462                 /*
1463                  * The atomic access to the futex value
1464                  * generated a pagefault, so retry the
1465                  * user-access and the wakeup:
1466                  */
1467                 if (ret == -EFAULT)
1468                         goto pi_faulted;
1469                 goto out_unlock;
1470         }
1471         /*
1472          * No waiters - kernel unlocks the futex:
1473          */
1474         if (!(uval & FUTEX_OWNER_DIED)) {
1475                 ret = unlock_futex_pi(uaddr, uval);
1476                 if (ret == -EFAULT)
1477                         goto pi_faulted;
1478         }
1479
1480 out_unlock:
1481         spin_unlock(&hb->lock);
1482 out:
1483         up_read(&current->mm->mmap_sem);
1484
1485         return ret;
1486
1487 pi_faulted:
1488         /*
1489          * We have to r/w  *(int __user *)uaddr, but we can't modify it
1490          * non-atomically.  Therefore, if get_user below is not
1491          * enough, we need to handle the fault ourselves, while
1492          * still holding the mmap_sem.
1493          */
1494         if (attempt++) {
1495                 if (futex_handle_fault((unsigned long)uaddr, attempt)) {
1496                         ret = -EFAULT;
1497                         goto out_unlock;
1498                 }
1499                 goto retry_locked;
1500         }
1501
1502         spin_unlock(&hb->lock);
1503         up_read(&current->mm->mmap_sem);
1504
1505         ret = get_user(uval, uaddr);
1506         if (!ret && (uval != -EFAULT))
1507                 goto retry;
1508
1509         return ret;
1510 }
1511
1512 static int futex_close(struct inode *inode, struct file *filp)
1513 {
1514         struct futex_q *q = filp->private_data;
1515
1516         unqueue_me(q);
1517         kfree(q);
1518
1519         return 0;
1520 }
1521
1522 /* This is one-shot: once it's gone off you need a new fd */
1523 static unsigned int futex_poll(struct file *filp,
1524                                struct poll_table_struct *wait)
1525 {
1526         struct futex_q *q = filp->private_data;
1527         int ret = 0;
1528
1529         poll_wait(filp, &q->waiters, wait);
1530
1531         /*
1532          * plist_node_empty() is safe here without any lock.
1533          * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
1534          */
1535         if (plist_node_empty(&q->list))
1536                 ret = POLLIN | POLLRDNORM;
1537
1538         return ret;
1539 }
1540
1541 static const struct file_operations futex_fops = {
1542         .release        = futex_close,
1543         .poll           = futex_poll,
1544 };
1545
1546 /*
1547  * Signal allows caller to avoid the race which would occur if they
1548  * set the sigio stuff up afterwards.
1549  */
1550 static int futex_fd(u32 __user *uaddr, int signal)
1551 {
1552         struct futex_q *q;
1553         struct file *filp;
1554         int ret, err;
1555         static unsigned long printk_interval;
1556
1557         if (printk_timed_ratelimit(&printk_interval, 60 * 60 * 1000)) {
1558                 printk(KERN_WARNING "Process `%s' used FUTEX_FD, which "
1559                         "will be removed from the kernel in June 2007\n",
1560                         current->comm);
1561         }
1562
1563         ret = -EINVAL;
1564         if (!valid_signal(signal))
1565                 goto out;
1566
1567         ret = get_unused_fd();
1568         if (ret < 0)
1569                 goto out;
1570         filp = get_empty_filp();
1571         if (!filp) {
1572                 put_unused_fd(ret);
1573                 ret = -ENFILE;
1574                 goto out;
1575         }
1576         filp->f_op = &futex_fops;
1577         filp->f_path.mnt = mntget(futex_mnt);
1578         filp->f_path.dentry = dget(futex_mnt->mnt_root);
1579         filp->f_mapping = filp->f_path.dentry->d_inode->i_mapping;
1580
1581         if (signal) {
1582                 err = __f_setown(filp, task_pid(current), PIDTYPE_PID, 1);
1583                 if (err < 0) {
1584                         goto error;
1585                 }
1586                 filp->f_owner.signum = signal;
1587         }
1588
1589         q = kmalloc(sizeof(*q), GFP_KERNEL);
1590         if (!q) {
1591                 err = -ENOMEM;
1592                 goto error;
1593         }
1594         q->pi_state = NULL;
1595
1596         down_read(&current->mm->mmap_sem);
1597         err = get_futex_key(uaddr, &q->key);
1598
1599         if (unlikely(err != 0)) {
1600                 up_read(&current->mm->mmap_sem);
1601                 kfree(q);
1602                 goto error;
1603         }
1604
1605         /*
1606          * queue_me() must be called before releasing mmap_sem, because
1607          * key->shared.inode needs to be referenced while holding it.
1608          */
1609         filp->private_data = q;
1610
1611         queue_me(q, ret, filp);
1612         up_read(&current->mm->mmap_sem);
1613
1614         /* Now we map fd to filp, so userspace can access it */
1615         fd_install(ret, filp);
1616 out:
1617         return ret;
1618 error:
1619         put_unused_fd(ret);
1620         put_filp(filp);
1621         ret = err;
1622         goto out;
1623 }
1624
1625 /*
1626  * Support for robust futexes: the kernel cleans up held futexes at
1627  * thread exit time.
1628  *
1629  * Implementation: user-space maintains a per-thread list of locks it
1630  * is holding. Upon do_exit(), the kernel carefully walks this list,
1631  * and marks all locks that are owned by this thread with the
1632  * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
1633  * always manipulated with the lock held, so the list is private and
1634  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
1635  * field, to allow the kernel to clean up if the thread dies after
1636  * acquiring the lock, but just before it could have added itself to
1637  * the list. There can only be one such pending lock.
1638  */
1639
1640 /**
1641  * sys_set_robust_list - set the robust-futex list head of a task
1642  * @head: pointer to the list-head
1643  * @len: length of the list-head, as userspace expects
1644  */
1645 asmlinkage long
1646 sys_set_robust_list(struct robust_list_head __user *head,
1647                     size_t len)
1648 {
1649         /*
1650          * The kernel knows only one size for now:
1651          */
1652         if (unlikely(len != sizeof(*head)))
1653                 return -EINVAL;
1654
1655         current->robust_list = head;
1656
1657         return 0;
1658 }
1659
1660 /**
1661  * sys_get_robust_list - get the robust-futex list head of a task
1662  * @pid: pid of the process [zero for current task]
1663  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
1664  * @len_ptr: pointer to a length field, the kernel fills in the header size
1665  */
1666 asmlinkage long
1667 sys_get_robust_list(int pid, struct robust_list_head __user * __user *head_ptr,
1668                     size_t __user *len_ptr)
1669 {
1670         struct robust_list_head __user *head;
1671         unsigned long ret;
1672
1673         if (!pid)
1674                 head = current->robust_list;
1675         else {
1676                 struct task_struct *p;
1677
1678                 ret = -ESRCH;
1679                 rcu_read_lock();
1680                 p = find_task_by_pid(pid);
1681                 if (!p)
1682                         goto err_unlock;
1683                 ret = -EPERM;
1684                 if ((current->euid != p->euid) && (current->euid != p->uid) &&
1685                                 !capable(CAP_SYS_PTRACE))
1686                         goto err_unlock;
1687                 head = p->robust_list;
1688                 rcu_read_unlock();
1689         }
1690
1691         if (put_user(sizeof(*head), len_ptr))
1692                 return -EFAULT;
1693         return put_user(head, head_ptr);
1694
1695 err_unlock:
1696         rcu_read_unlock();
1697
1698         return ret;
1699 }
1700
1701 /*
1702  * Process a futex-list entry, check whether it's owned by the
1703  * dying task, and do notification if so:
1704  */
1705 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
1706 {
1707         u32 uval, nval, mval;
1708
1709 retry:
1710         if (get_user(uval, uaddr))
1711                 return -1;
1712
1713         if ((uval & FUTEX_TID_MASK) == curr->pid) {
1714                 /*
1715                  * Ok, this dying thread is truly holding a futex
1716                  * of interest. Set the OWNER_DIED bit atomically
1717                  * via cmpxchg, and if the value had FUTEX_WAITERS
1718                  * set, wake up a waiter (if any). (We have to do a
1719                  * futex_wake() even if OWNER_DIED is already set -
1720                  * to handle the rare but possible case of recursive
1721                  * thread-death.) The rest of the cleanup is done in
1722                  * userspace.
1723                  */
1724                 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
1725                 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
1726
1727                 if (nval == -EFAULT)
1728                         return -1;
1729
1730                 if (nval != uval)
1731                         goto retry;
1732
1733                 /*
1734                  * Wake robust non-PI futexes here. The wakeup of
1735                  * PI futexes happens in exit_pi_state():
1736                  */
1737                 if (!pi) {
1738                         if (uval & FUTEX_WAITERS)
1739                                 futex_wake(uaddr, 1);
1740                 }
1741         }
1742         return 0;
1743 }
1744
1745 /*
1746  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
1747  */
1748 static inline int fetch_robust_entry(struct robust_list __user **entry,
1749                                      struct robust_list __user * __user *head,
1750                                      int *pi)
1751 {
1752         unsigned long uentry;
1753
1754         if (get_user(uentry, (unsigned long __user *)head))
1755                 return -EFAULT;
1756
1757         *entry = (void __user *)(uentry & ~1UL);
1758         *pi = uentry & 1;
1759
1760         return 0;
1761 }
1762
1763 /*
1764  * Walk curr->robust_list (very carefully, it's a userspace list!)
1765  * and mark any locks found there dead, and notify any waiters.
1766  *
1767  * We silently return on any sign of list-walking problem.
1768  */
1769 void exit_robust_list(struct task_struct *curr)
1770 {
1771         struct robust_list_head __user *head = curr->robust_list;
1772         struct robust_list __user *entry, *pending;
1773         unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
1774         unsigned long futex_offset;
1775
1776         /*
1777          * Fetch the list head (which was registered earlier, via
1778          * sys_set_robust_list()):
1779          */
1780         if (fetch_robust_entry(&entry, &head->list.next, &pi))
1781                 return;
1782         /*
1783          * Fetch the relative futex offset:
1784          */
1785         if (get_user(futex_offset, &head->futex_offset))
1786                 return;
1787         /*
1788          * Fetch any possibly pending lock-add first, and handle it
1789          * if it exists:
1790          */
1791         if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
1792                 return;
1793
1794         if (pending)
1795                 handle_futex_death((void __user *)pending + futex_offset, curr, pip);
1796
1797         while (entry != &head->list) {
1798                 /*
1799                  * A pending lock might already be on the list, so
1800                  * don't process it twice:
1801                  */
1802                 if (entry != pending)
1803                         if (handle_futex_death((void __user *)entry + futex_offset,
1804                                                 curr, pi))
1805                                 return;
1806                 /*
1807                  * Fetch the next entry in the list:
1808                  */
1809                 if (fetch_robust_entry(&entry, &entry->next, &pi))
1810                         return;
1811                 /*
1812                  * Avoid excessively long or circular lists:
1813                  */
1814                 if (!--limit)
1815                         break;
1816
1817                 cond_resched();
1818         }
1819 }
1820
1821 long do_futex(u32 __user *uaddr, int op, u32 val, unsigned long timeout,
1822                 u32 __user *uaddr2, u32 val2, u32 val3)
1823 {
1824         int ret;
1825
1826         switch (op) {
1827         case FUTEX_WAIT:
1828                 ret = futex_wait(uaddr, val, timeout);
1829                 break;
1830         case FUTEX_WAKE:
1831                 ret = futex_wake(uaddr, val);
1832                 break;
1833         case FUTEX_FD:
1834                 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
1835                 ret = futex_fd(uaddr, val);
1836                 break;
1837         case FUTEX_REQUEUE:
1838                 ret = futex_requeue(uaddr, uaddr2, val, val2, NULL);
1839                 break;
1840         case FUTEX_CMP_REQUEUE:
1841                 ret = futex_requeue(uaddr, uaddr2, val, val2, &val3);
1842                 break;
1843         case FUTEX_WAKE_OP:
1844                 ret = futex_wake_op(uaddr, uaddr2, val, val2, val3);
1845                 break;
1846         case FUTEX_LOCK_PI:
1847                 ret = futex_lock_pi(uaddr, val, timeout, val2, 0);
1848                 break;
1849         case FUTEX_UNLOCK_PI:
1850                 ret = futex_unlock_pi(uaddr);
1851                 break;
1852         case FUTEX_TRYLOCK_PI:
1853                 ret = futex_lock_pi(uaddr, 0, timeout, val2, 1);
1854                 break;
1855         default:
1856                 ret = -ENOSYS;
1857         }
1858         return ret;
1859 }
1860
1861
1862 asmlinkage long sys_futex(u32 __user *uaddr, int op, u32 val,
1863                           struct timespec __user *utime, u32 __user *uaddr2,
1864                           u32 val3)
1865 {
1866         struct timespec t;
1867         unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
1868         u32 val2 = 0;
1869
1870         if (utime && (op == FUTEX_WAIT || op == FUTEX_LOCK_PI)) {
1871                 if (copy_from_user(&t, utime, sizeof(t)) != 0)
1872                         return -EFAULT;
1873                 if (!timespec_valid(&t))
1874                         return -EINVAL;
1875                 if (op == FUTEX_WAIT)
1876                         timeout = timespec_to_jiffies(&t) + 1;
1877                 else {
1878                         timeout = t.tv_sec;
1879                         val2 = t.tv_nsec;
1880                 }
1881         }
1882         /*
1883          * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
1884          */
1885         if (op == FUTEX_REQUEUE || op == FUTEX_CMP_REQUEUE)
1886                 val2 = (u32) (unsigned long) utime;
1887
1888         return do_futex(uaddr, op, val, timeout, uaddr2, val2, val3);
1889 }
1890
1891 static int futexfs_get_sb(struct file_system_type *fs_type,
1892                           int flags, const char *dev_name, void *data,
1893                           struct vfsmount *mnt)
1894 {
1895         return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA, mnt);
1896 }
1897
1898 static struct file_system_type futex_fs_type = {
1899         .name           = "futexfs",
1900         .get_sb         = futexfs_get_sb,
1901         .kill_sb        = kill_anon_super,
1902 };
1903
1904 static int __init init(void)
1905 {
1906         int i = register_filesystem(&futex_fs_type);
1907
1908         if (i)
1909                 return i;
1910
1911         futex_mnt = kern_mount(&futex_fs_type);
1912         if (IS_ERR(futex_mnt)) {
1913                 unregister_filesystem(&futex_fs_type);
1914                 return PTR_ERR(futex_mnt);
1915         }
1916
1917         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
1918                 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
1919                 spin_lock_init(&futex_queues[i].lock);
1920         }
1921         return 0;
1922 }
1923 __initcall(init);