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