Merge to Fedora kernel-2.6.17-1.2187_FC5 patched with stable patch-2.6.17.13-vs2...
[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  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
16  *  enough at me, Linus for the original (flawed) idea, Matthew
17  *  Kirkwood for proof-of-concept implementation.
18  *
19  *  "The futexes are also cursed."
20  *  "But they come in a choice of three flavours!"
21  *
22  *  This program is free software; you can redistribute it and/or modify
23  *  it under the terms of the GNU General Public License as published by
24  *  the Free Software Foundation; either version 2 of the License, or
25  *  (at your option) any later version.
26  *
27  *  This program is distributed in the hope that it will be useful,
28  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
29  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30  *  GNU General Public License for more details.
31  *
32  *  You should have received a copy of the GNU General Public License
33  *  along with this program; if not, write to the Free Software
34  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
35  */
36 #include <linux/slab.h>
37 #include <linux/poll.h>
38 #include <linux/fs.h>
39 #include <linux/file.h>
40 #include <linux/jhash.h>
41 #include <linux/init.h>
42 #include <linux/futex.h>
43 #include <linux/mount.h>
44 #include <linux/pagemap.h>
45 #include <linux/syscalls.h>
46 #include <linux/signal.h>
47 #include <linux/vs_cvirt.h>
48 #include <asm/futex.h>
49
50 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
51
52 /*
53  * Futexes are matched on equal values of this key.
54  * The key type depends on whether it's a shared or private mapping.
55  * Don't rearrange members without looking at hash_futex().
56  *
57  * offset is aligned to a multiple of sizeof(u32) (== 4) by definition.
58  * We set bit 0 to indicate if it's an inode-based key.
59  */
60 union futex_key {
61         struct {
62                 unsigned long pgoff;
63                 struct inode *inode;
64                 int offset;
65         } shared;
66         struct {
67                 unsigned long uaddr;
68                 struct mm_struct *mm;
69                 int offset;
70         } private;
71         struct {
72                 unsigned long word;
73                 void *ptr;
74                 int offset;
75         } both;
76 };
77
78 /*
79  * We use this hashed waitqueue instead of a normal wait_queue_t, so
80  * we can wake only the relevant ones (hashed queues may be shared).
81  *
82  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
83  * It is considered woken when list_empty(&q->list) || q->lock_ptr == 0.
84  * The order of wakup is always to make the first condition true, then
85  * wake up q->waiters, then make the second condition true.
86  */
87 struct futex_q {
88         struct list_head list;
89         wait_queue_head_t waiters;
90
91         /* Which hash list lock to use. */
92         spinlock_t *lock_ptr;
93
94         /* Key which the futex is hashed on. */
95         union futex_key key;
96
97         /* For fd, sigio sent using these. */
98         int fd;
99         struct file *filp;
100 };
101
102 /*
103  * Split the global futex_lock into every hash list lock.
104  */
105 struct futex_hash_bucket {
106        spinlock_t              lock;
107        struct list_head       chain;
108 };
109
110 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
111
112 /* Futex-fs vfsmount entry: */
113 static struct vfsmount *futex_mnt;
114
115 /*
116  * We hash on the keys returned from get_futex_key (see below).
117  */
118 static struct futex_hash_bucket *hash_futex(union futex_key *key)
119 {
120         u32 hash = jhash2((u32*)&key->both.word,
121                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
122                           key->both.offset);
123         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
124 }
125
126 /*
127  * Return 1 if two futex_keys are equal, 0 otherwise.
128  */
129 static inline int match_futex(union futex_key *key1, union futex_key *key2)
130 {
131         return (key1->both.word == key2->both.word
132                 && key1->both.ptr == key2->both.ptr
133                 && key1->both.offset == key2->both.offset);
134 }
135
136 /*
137  * Get parameters which are the keys for a futex.
138  *
139  * For shared mappings, it's (page->index, vma->vm_file->f_dentry->d_inode,
140  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
141  * We can usually work out the index without swapping in the page.
142  *
143  * Returns: 0, or negative error code.
144  * The key words are stored in *key on success.
145  *
146  * Should be called with &current->mm->mmap_sem but NOT any spinlocks.
147  */
148 static int get_futex_key(unsigned long uaddr, union futex_key *key)
149 {
150         struct mm_struct *mm = current->mm;
151         struct vm_area_struct *vma;
152         struct page *page;
153         int err;
154
155         /*
156          * The futex address must be "naturally" aligned.
157          */
158         key->both.offset = uaddr % PAGE_SIZE;
159         if (unlikely((key->both.offset % sizeof(u32)) != 0))
160                 return -EINVAL;
161         uaddr -= key->both.offset;
162
163         /*
164          * The futex is hashed differently depending on whether
165          * it's in a shared or private mapping.  So check vma first.
166          */
167         vma = find_extend_vma(mm, uaddr);
168         if (unlikely(!vma))
169                 return -EFAULT;
170
171         /*
172          * Permissions.
173          */
174         if (unlikely((vma->vm_flags & (VM_IO|VM_READ)) != VM_READ))
175                 return (vma->vm_flags & VM_IO) ? -EPERM : -EACCES;
176
177         /*
178          * Private mappings are handled in a simple way.
179          *
180          * NOTE: When userspace waits on a MAP_SHARED mapping, even if
181          * it's a read-only handle, it's expected that futexes attach to
182          * the object not the particular process.  Therefore we use
183          * VM_MAYSHARE here, not VM_SHARED which is restricted to shared
184          * mappings of _writable_ handles.
185          */
186         if (likely(!(vma->vm_flags & VM_MAYSHARE))) {
187                 key->private.mm = mm;
188                 key->private.uaddr = uaddr;
189                 return 0;
190         }
191
192         /*
193          * Linear file mappings are also simple.
194          */
195         key->shared.inode = vma->vm_file->f_dentry->d_inode;
196         key->both.offset++; /* Bit 0 of offset indicates inode-based key. */
197         if (likely(!(vma->vm_flags & VM_NONLINEAR))) {
198                 key->shared.pgoff = (((uaddr - vma->vm_start) >> PAGE_SHIFT)
199                                      + vma->vm_pgoff);
200                 return 0;
201         }
202
203         /*
204          * We could walk the page table to read the non-linear
205          * pte, and get the page index without fetching the page
206          * from swap.  But that's a lot of code to duplicate here
207          * for a rare case, so we simply fetch the page.
208          */
209         err = get_user_pages(current, mm, uaddr, 1, 0, 0, &page, NULL);
210         if (err >= 0) {
211                 key->shared.pgoff =
212                         page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
213                 put_page(page);
214                 return 0;
215         }
216         return err;
217 }
218
219 /*
220  * Take a reference to the resource addressed by a key.
221  * Can be called while holding spinlocks.
222  *
223  * NOTE: mmap_sem MUST be held between get_futex_key() and calling this
224  * function, if it is called at all.  mmap_sem keeps key->shared.inode valid.
225  */
226 static inline void get_key_refs(union futex_key *key)
227 {
228         if (key->both.ptr != 0) {
229                 if (key->both.offset & 1)
230                         atomic_inc(&key->shared.inode->i_count);
231                 else
232                         atomic_inc(&key->private.mm->mm_count);
233         }
234 }
235
236 /*
237  * Drop a reference to the resource addressed by a key.
238  * The hash bucket spinlock must not be held.
239  */
240 static void drop_key_refs(union futex_key *key)
241 {
242         if (key->both.ptr != 0) {
243                 if (key->both.offset & 1)
244                         iput(key->shared.inode);
245                 else
246                         mmdrop(key->private.mm);
247         }
248 }
249
250 static inline int get_futex_value_locked(int *dest, int __user *from)
251 {
252         int ret;
253
254         inc_preempt_count();
255         ret = __copy_from_user_inatomic(dest, from, sizeof(int));
256         dec_preempt_count();
257
258         return ret ? -EFAULT : 0;
259 }
260
261 /*
262  * The hash bucket lock must be held when this is called.
263  * Afterwards, the futex_q must not be accessed.
264  */
265 static void wake_futex(struct futex_q *q)
266 {
267         list_del_init(&q->list);
268         if (q->filp)
269                 send_sigio(&q->filp->f_owner, q->fd, POLL_IN);
270         /*
271          * The lock in wake_up_all() is a crucial memory barrier after the
272          * list_del_init() and also before assigning to q->lock_ptr.
273          */
274         wake_up_all(&q->waiters);
275         /*
276          * The waiting task can free the futex_q as soon as this is written,
277          * without taking any locks.  This must come last.
278          *
279          * A memory barrier is required here to prevent the following store
280          * to lock_ptr from getting ahead of the wakeup. Clearing the lock
281          * at the end of wake_up_all() does not prevent this store from
282          * moving.
283          */
284         wmb();
285         q->lock_ptr = NULL;
286 }
287
288 /*
289  * Wake up all waiters hashed on the physical page that is mapped
290  * to this virtual address:
291  */
292 static int futex_wake(unsigned long uaddr, int nr_wake)
293 {
294         union futex_key key;
295         struct futex_hash_bucket *bh;
296         struct list_head *head;
297         struct futex_q *this, *next;
298         int ret;
299
300         down_read(&current->mm->mmap_sem);
301
302         ret = get_futex_key(uaddr, &key);
303         if (unlikely(ret != 0))
304                 goto out;
305
306         bh = hash_futex(&key);
307         spin_lock(&bh->lock);
308         head = &bh->chain;
309
310         list_for_each_entry_safe(this, next, head, list) {
311                 if (match_futex (&this->key, &key)) {
312                         wake_futex(this);
313                         if (++ret >= nr_wake)
314                                 break;
315                 }
316         }
317
318         spin_unlock(&bh->lock);
319 out:
320         up_read(&current->mm->mmap_sem);
321         return ret;
322 }
323
324 /*
325  * Wake up all waiters hashed on the physical page that is mapped
326  * to this virtual address:
327  */
328 static int futex_wake_op(unsigned long uaddr1, unsigned long uaddr2, int nr_wake, int nr_wake2, int op)
329 {
330         union futex_key key1, key2;
331         struct futex_hash_bucket *bh1, *bh2;
332         struct list_head *head;
333         struct futex_q *this, *next;
334         int ret, op_ret, attempt = 0;
335
336 retryfull:
337         down_read(&current->mm->mmap_sem);
338
339         ret = get_futex_key(uaddr1, &key1);
340         if (unlikely(ret != 0))
341                 goto out;
342         ret = get_futex_key(uaddr2, &key2);
343         if (unlikely(ret != 0))
344                 goto out;
345
346         bh1 = hash_futex(&key1);
347         bh2 = hash_futex(&key2);
348
349 retry:
350         if (bh1 < bh2)
351                 spin_lock(&bh1->lock);
352         spin_lock(&bh2->lock);
353         if (bh1 > bh2)
354                 spin_lock(&bh1->lock);
355
356         op_ret = futex_atomic_op_inuser(op, (int __user *)uaddr2);
357         if (unlikely(op_ret < 0)) {
358                 int dummy;
359
360                 spin_unlock(&bh1->lock);
361                 if (bh1 != bh2)
362                         spin_unlock(&bh2->lock);
363
364 #ifndef CONFIG_MMU
365                 /* we don't get EFAULT from MMU faults if we don't have an MMU,
366                  * but we might get them from range checking */
367                 ret = op_ret;
368                 goto out;
369 #endif
370
371                 if (unlikely(op_ret != -EFAULT)) {
372                         ret = op_ret;
373                         goto out;
374                 }
375
376                 /* futex_atomic_op_inuser needs to both read and write
377                  * *(int __user *)uaddr2, but we can't modify it
378                  * non-atomically.  Therefore, if get_user below is not
379                  * enough, we need to handle the fault ourselves, while
380                  * still holding the mmap_sem.  */
381                 if (attempt++) {
382                         struct vm_area_struct * vma;
383                         struct mm_struct *mm = current->mm;
384
385                         ret = -EFAULT;
386                         if (attempt >= 2 ||
387                             !(vma = find_vma(mm, uaddr2)) ||
388                             vma->vm_start > uaddr2 ||
389                             !(vma->vm_flags & VM_WRITE))
390                                 goto out;
391
392                         switch (handle_mm_fault(mm, vma, uaddr2, 1)) {
393                         case VM_FAULT_MINOR:
394                                 current->min_flt++;
395                                 break;
396                         case VM_FAULT_MAJOR:
397                                 current->maj_flt++;
398                                 break;
399                         default:
400                                 goto out;
401                         }
402                         goto retry;
403                 }
404
405                 /* If we would have faulted, release mmap_sem,
406                  * fault it in and start all over again.  */
407                 up_read(&current->mm->mmap_sem);
408
409                 ret = get_user(dummy, (int __user *)uaddr2);
410                 if (ret)
411                         return ret;
412
413                 goto retryfull;
414         }
415
416         head = &bh1->chain;
417
418         list_for_each_entry_safe(this, next, head, list) {
419                 if (match_futex (&this->key, &key1)) {
420                         wake_futex(this);
421                         if (++ret >= nr_wake)
422                                 break;
423                 }
424         }
425
426         if (op_ret > 0) {
427                 head = &bh2->chain;
428
429                 op_ret = 0;
430                 list_for_each_entry_safe(this, next, head, list) {
431                         if (match_futex (&this->key, &key2)) {
432                                 wake_futex(this);
433                                 if (++op_ret >= nr_wake2)
434                                         break;
435                         }
436                 }
437                 ret += op_ret;
438         }
439
440         spin_unlock(&bh1->lock);
441         if (bh1 != bh2)
442                 spin_unlock(&bh2->lock);
443 out:
444         up_read(&current->mm->mmap_sem);
445         return ret;
446 }
447
448 /*
449  * Requeue all waiters hashed on one physical page to another
450  * physical page.
451  */
452 static int futex_requeue(unsigned long uaddr1, unsigned long uaddr2,
453                          int nr_wake, int nr_requeue, int *valp)
454 {
455         union futex_key key1, key2;
456         struct futex_hash_bucket *bh1, *bh2;
457         struct list_head *head1;
458         struct futex_q *this, *next;
459         int ret, drop_count = 0;
460
461  retry:
462         down_read(&current->mm->mmap_sem);
463
464         ret = get_futex_key(uaddr1, &key1);
465         if (unlikely(ret != 0))
466                 goto out;
467         ret = get_futex_key(uaddr2, &key2);
468         if (unlikely(ret != 0))
469                 goto out;
470
471         bh1 = hash_futex(&key1);
472         bh2 = hash_futex(&key2);
473
474         if (bh1 < bh2)
475                 spin_lock(&bh1->lock);
476         spin_lock(&bh2->lock);
477         if (bh1 > bh2)
478                 spin_lock(&bh1->lock);
479
480         if (likely(valp != NULL)) {
481                 int curval;
482
483                 ret = get_futex_value_locked(&curval, (int __user *)uaddr1);
484
485                 if (unlikely(ret)) {
486                         spin_unlock(&bh1->lock);
487                         if (bh1 != bh2)
488                                 spin_unlock(&bh2->lock);
489
490                         /* If we would have faulted, release mmap_sem, fault
491                          * it in and start all over again.
492                          */
493                         up_read(&current->mm->mmap_sem);
494
495                         ret = get_user(curval, (int __user *)uaddr1);
496
497                         if (!ret)
498                                 goto retry;
499
500                         return ret;
501                 }
502                 if (curval != *valp) {
503                         ret = -EAGAIN;
504                         goto out_unlock;
505                 }
506         }
507
508         head1 = &bh1->chain;
509         list_for_each_entry_safe(this, next, head1, list) {
510                 if (!match_futex (&this->key, &key1))
511                         continue;
512                 if (++ret <= nr_wake) {
513                         wake_futex(this);
514                 } else {
515                         list_move_tail(&this->list, &bh2->chain);
516                         this->lock_ptr = &bh2->lock;
517                         this->key = key2;
518                         get_key_refs(&key2);
519                         drop_count++;
520
521                         if (ret - nr_wake >= nr_requeue)
522                                 break;
523                         /* Make sure to stop if key1 == key2 */
524                         if (head1 == &bh2->chain && head1 != &next->list)
525                                 head1 = &this->list;
526                 }
527         }
528
529 out_unlock:
530         spin_unlock(&bh1->lock);
531         if (bh1 != bh2)
532                 spin_unlock(&bh2->lock);
533
534         /* drop_key_refs() must be called outside the spinlocks. */
535         while (--drop_count >= 0)
536                 drop_key_refs(&key1);
537
538 out:
539         up_read(&current->mm->mmap_sem);
540         return ret;
541 }
542
543 /* The key must be already stored in q->key. */
544 static inline struct futex_hash_bucket *
545 queue_lock(struct futex_q *q, int fd, struct file *filp)
546 {
547         struct futex_hash_bucket *bh;
548
549         q->fd = fd;
550         q->filp = filp;
551
552         init_waitqueue_head(&q->waiters);
553
554         get_key_refs(&q->key);
555         bh = hash_futex(&q->key);
556         q->lock_ptr = &bh->lock;
557
558         spin_lock(&bh->lock);
559         return bh;
560 }
561
562 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *bh)
563 {
564         list_add_tail(&q->list, &bh->chain);
565         spin_unlock(&bh->lock);
566 }
567
568 static inline void
569 queue_unlock(struct futex_q *q, struct futex_hash_bucket *bh)
570 {
571         spin_unlock(&bh->lock);
572         drop_key_refs(&q->key);
573 }
574
575 /*
576  * queue_me and unqueue_me must be called as a pair, each
577  * exactly once.  They are called with the hashed spinlock held.
578  */
579
580 /* The key must be already stored in q->key. */
581 static void queue_me(struct futex_q *q, int fd, struct file *filp)
582 {
583         struct futex_hash_bucket *bh;
584         bh = queue_lock(q, fd, filp);
585         __queue_me(q, bh);
586 }
587
588 /* Return 1 if we were still queued (ie. 0 means we were woken) */
589 static int unqueue_me(struct futex_q *q)
590 {
591         int ret = 0;
592         spinlock_t *lock_ptr;
593
594         /* In the common case we don't take the spinlock, which is nice. */
595  retry:
596         lock_ptr = q->lock_ptr;
597         barrier();
598         if (lock_ptr != 0) {
599                 spin_lock(lock_ptr);
600                 /*
601                  * q->lock_ptr can change between reading it and
602                  * spin_lock(), causing us to take the wrong lock.  This
603                  * corrects the race condition.
604                  *
605                  * Reasoning goes like this: if we have the wrong lock,
606                  * q->lock_ptr must have changed (maybe several times)
607                  * between reading it and the spin_lock().  It can
608                  * change again after the spin_lock() but only if it was
609                  * already changed before the spin_lock().  It cannot,
610                  * however, change back to the original value.  Therefore
611                  * we can detect whether we acquired the correct lock.
612                  */
613                 if (unlikely(lock_ptr != q->lock_ptr)) {
614                         spin_unlock(lock_ptr);
615                         goto retry;
616                 }
617                 WARN_ON(list_empty(&q->list));
618                 list_del(&q->list);
619                 spin_unlock(lock_ptr);
620                 ret = 1;
621         }
622
623         drop_key_refs(&q->key);
624         return ret;
625 }
626
627 static int futex_wait(unsigned long uaddr, int val, unsigned long time)
628 {
629         DECLARE_WAITQUEUE(wait, current);
630         int ret, curval;
631         struct futex_q q;
632         struct futex_hash_bucket *bh;
633
634  retry:
635         down_read(&current->mm->mmap_sem);
636
637         ret = get_futex_key(uaddr, &q.key);
638         if (unlikely(ret != 0))
639                 goto out_release_sem;
640
641         bh = queue_lock(&q, -1, NULL);
642
643         /*
644          * Access the page AFTER the futex is queued.
645          * Order is important:
646          *
647          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
648          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
649          *
650          * The basic logical guarantee of a futex is that it blocks ONLY
651          * if cond(var) is known to be true at the time of blocking, for
652          * any cond.  If we queued after testing *uaddr, that would open
653          * a race condition where we could block indefinitely with
654          * cond(var) false, which would violate the guarantee.
655          *
656          * A consequence is that futex_wait() can return zero and absorb
657          * a wakeup when *uaddr != val on entry to the syscall.  This is
658          * rare, but normal.
659          *
660          * We hold the mmap semaphore, so the mapping cannot have changed
661          * since we looked it up in get_futex_key.
662          */
663
664         ret = get_futex_value_locked(&curval, (int __user *)uaddr);
665
666         if (unlikely(ret)) {
667                 queue_unlock(&q, bh);
668
669                 /* If we would have faulted, release mmap_sem, fault it in and
670                  * start all over again.
671                  */
672                 up_read(&current->mm->mmap_sem);
673
674                 ret = get_user(curval, (int __user *)uaddr);
675
676                 if (!ret)
677                         goto retry;
678                 return ret;
679         }
680         if (curval != val) {
681                 ret = -EWOULDBLOCK;
682                 queue_unlock(&q, bh);
683                 goto out_release_sem;
684         }
685
686         /* Only actually queue if *uaddr contained val.  */
687         __queue_me(&q, bh);
688
689         /*
690          * Now the futex is queued and we have checked the data, we
691          * don't want to hold mmap_sem while we sleep.
692          */     
693         up_read(&current->mm->mmap_sem);
694
695         /*
696          * There might have been scheduling since the queue_me(), as we
697          * cannot hold a spinlock across the get_user() in case it
698          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
699          * queueing ourselves into the futex hash.  This code thus has to
700          * rely on the futex_wake() code removing us from hash when it
701          * wakes us up.
702          */
703
704         /* add_wait_queue is the barrier after __set_current_state. */
705         __set_current_state(TASK_INTERRUPTIBLE);
706         add_wait_queue(&q.waiters, &wait);
707         /*
708          * !list_empty() is safe here without any lock.
709          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
710          */
711         if (likely(!list_empty(&q.list)))
712                 time = schedule_timeout(time);
713         __set_current_state(TASK_RUNNING);
714
715         /*
716          * NOTE: we don't remove ourselves from the waitqueue because
717          * we are the only user of it.
718          */
719
720         /* If we were woken (and unqueued), we succeeded, whatever. */
721         if (!unqueue_me(&q))
722                 return 0;
723         if (time == 0)
724                 return -ETIMEDOUT;
725         /* We expect signal_pending(current), but another thread may
726          * have handled it for us already. */
727         return -EINTR;
728
729  out_release_sem:
730         up_read(&current->mm->mmap_sem);
731         return ret;
732 }
733
734 static int futex_close(struct inode *inode, struct file *filp)
735 {
736         struct futex_q *q = filp->private_data;
737
738         unqueue_me(q);
739         kfree(q);
740         return 0;
741 }
742
743 /* This is one-shot: once it's gone off you need a new fd */
744 static unsigned int futex_poll(struct file *filp,
745                                struct poll_table_struct *wait)
746 {
747         struct futex_q *q = filp->private_data;
748         int ret = 0;
749
750         poll_wait(filp, &q->waiters, wait);
751
752         /*
753          * list_empty() is safe here without any lock.
754          * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
755          */
756         if (list_empty(&q->list))
757                 ret = POLLIN | POLLRDNORM;
758
759         return ret;
760 }
761
762 static struct file_operations futex_fops = {
763         .release        = futex_close,
764         .poll           = futex_poll,
765 };
766
767 /*
768  * Signal allows caller to avoid the race which would occur if they
769  * set the sigio stuff up afterwards.
770  */
771 static int futex_fd(unsigned long uaddr, int signal)
772 {
773         struct futex_q *q;
774         struct file *filp;
775         int ret, err;
776
777         ret = -EINVAL;
778         if (!valid_signal(signal))
779                 goto out;
780
781         ret = get_unused_fd();
782         if (ret < 0)
783                 goto out;
784         filp = get_empty_filp();
785         if (!filp) {
786                 put_unused_fd(ret);
787                 ret = -ENFILE;
788                 goto out;
789         }
790         filp->f_op = &futex_fops;
791         filp->f_vfsmnt = mntget(futex_mnt);
792         filp->f_dentry = dget(futex_mnt->mnt_root);
793         filp->f_mapping = filp->f_dentry->d_inode->i_mapping;
794
795         if (signal) {
796                 err = f_setown(filp, current->pid, 1);
797                 if (err < 0) {
798                         goto error;
799                 }
800                 filp->f_owner.signum = signal;
801         }
802
803         q = kmalloc(sizeof(*q), GFP_KERNEL);
804         if (!q) {
805                 err = -ENOMEM;
806                 goto error;
807         }
808
809         down_read(&current->mm->mmap_sem);
810         err = get_futex_key(uaddr, &q->key);
811
812         if (unlikely(err != 0)) {
813                 up_read(&current->mm->mmap_sem);
814                 kfree(q);
815                 goto error;
816         }
817
818         /*
819          * queue_me() must be called before releasing mmap_sem, because
820          * key->shared.inode needs to be referenced while holding it.
821          */
822         filp->private_data = q;
823
824         queue_me(q, ret, filp);
825         up_read(&current->mm->mmap_sem);
826
827         /* Now we map fd to filp, so userspace can access it */
828         fd_install(ret, filp);
829 out:
830         return ret;
831 error:
832         put_unused_fd(ret);
833         put_filp(filp);
834         ret = err;
835         goto out;
836 }
837
838 /*
839  * Support for robust futexes: the kernel cleans up held futexes at
840  * thread exit time.
841  *
842  * Implementation: user-space maintains a per-thread list of locks it
843  * is holding. Upon do_exit(), the kernel carefully walks this list,
844  * and marks all locks that are owned by this thread with the
845  * FUTEX_OWNER_DEAD bit, and wakes up a waiter (if any). The list is
846  * always manipulated with the lock held, so the list is private and
847  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
848  * field, to allow the kernel to clean up if the thread dies after
849  * acquiring the lock, but just before it could have added itself to
850  * the list. There can only be one such pending lock.
851  */
852
853 /**
854  * sys_set_robust_list - set the robust-futex list head of a task
855  * @head: pointer to the list-head
856  * @len: length of the list-head, as userspace expects
857  */
858 asmlinkage long
859 sys_set_robust_list(struct robust_list_head __user *head,
860                     size_t len)
861 {
862         /*
863          * The kernel knows only one size for now:
864          */
865         if (unlikely(len != sizeof(*head)))
866                 return -EINVAL;
867
868         current->robust_list = head;
869
870         return 0;
871 }
872
873 /**
874  * sys_get_robust_list - get the robust-futex list head of a task
875  * @pid: pid of the process [zero for current task]
876  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
877  * @len_ptr: pointer to a length field, the kernel fills in the header size
878  */
879 asmlinkage long
880 sys_get_robust_list(int pid, struct robust_list_head __user **head_ptr,
881                     size_t __user *len_ptr)
882 {
883         struct robust_list_head *head;
884         unsigned long ret;
885
886         if (!pid)
887                 head = current->robust_list;
888         else {
889                 struct task_struct *p;
890
891                 ret = -ESRCH;
892                 read_lock(&tasklist_lock);
893                 p = find_task_by_pid(pid);
894                 if (!p)
895                         goto err_unlock;
896                 ret = -EPERM;
897                 if ((current->euid != p->euid) && (current->euid != p->uid) &&
898                                 !capable(CAP_SYS_PTRACE))
899                         goto err_unlock;
900                 head = p->robust_list;
901                 read_unlock(&tasklist_lock);
902         }
903
904         if (put_user(sizeof(*head), len_ptr))
905                 return -EFAULT;
906         return put_user(head, head_ptr);
907
908 err_unlock:
909         read_unlock(&tasklist_lock);
910
911         return ret;
912 }
913
914 /*
915  * Process a futex-list entry, check whether it's owned by the
916  * dying task, and do notification if so:
917  */
918 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr)
919 {
920         u32 uval;
921
922 retry:
923         if (get_user(uval, uaddr))
924                 return -1;
925
926         if ((uval & FUTEX_TID_MASK) == curr->pid) {
927                 /*
928                  * Ok, this dying thread is truly holding a futex
929                  * of interest. Set the OWNER_DIED bit atomically
930                  * via cmpxchg, and if the value had FUTEX_WAITERS
931                  * set, wake up a waiter (if any). (We have to do a
932                  * futex_wake() even if OWNER_DIED is already set -
933                  * to handle the rare but possible case of recursive
934                  * thread-death.) The rest of the cleanup is done in
935                  * userspace.
936                  */
937                 if (futex_atomic_cmpxchg_inatomic(uaddr, uval,
938                                          uval | FUTEX_OWNER_DIED) != uval)
939                         goto retry;
940
941                 if (uval & FUTEX_WAITERS)
942                         futex_wake((unsigned long)uaddr, 1);
943         }
944         return 0;
945 }
946
947 /*
948  * Walk curr->robust_list (very carefully, it's a userspace list!)
949  * and mark any locks found there dead, and notify any waiters.
950  *
951  * We silently return on any sign of list-walking problem.
952  */
953 void exit_robust_list(struct task_struct *curr)
954 {
955         struct robust_list_head __user *head = curr->robust_list;
956         struct robust_list __user *entry, *pending;
957         unsigned int limit = ROBUST_LIST_LIMIT;
958         unsigned long futex_offset;
959
960         /*
961          * Fetch the list head (which was registered earlier, via
962          * sys_set_robust_list()):
963          */
964         if (get_user(entry, &head->list.next))
965                 return;
966         /*
967          * Fetch the relative futex offset:
968          */
969         if (get_user(futex_offset, &head->futex_offset))
970                 return;
971         /*
972          * Fetch any possibly pending lock-add first, and handle it
973          * if it exists:
974          */
975         if (get_user(pending, &head->list_op_pending))
976                 return;
977         if (pending)
978                 handle_futex_death((void *)pending + futex_offset, curr);
979
980         while (entry != &head->list) {
981                 /*
982                  * A pending lock might already be on the list, so
983                  * dont process it twice:
984                  */
985                 if (entry != pending)
986                         if (handle_futex_death((void *)entry + futex_offset,
987                                                 curr))
988                                 return;
989                 /*
990                  * Fetch the next entry in the list:
991                  */
992                 if (get_user(entry, &entry->next))
993                         return;
994                 /*
995                  * Avoid excessively long or circular lists:
996                  */
997                 if (!--limit)
998                         break;
999
1000                 cond_resched();
1001         }
1002 }
1003
1004 long do_futex(unsigned long uaddr, int op, int val, unsigned long timeout,
1005                 unsigned long uaddr2, int val2, int val3)
1006 {
1007         int ret;
1008
1009         switch (op) {
1010         case FUTEX_WAIT:
1011                 ret = futex_wait(uaddr, val, timeout);
1012                 break;
1013         case FUTEX_WAKE:
1014                 ret = futex_wake(uaddr, val);
1015                 break;
1016         case FUTEX_FD:
1017                 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
1018                 ret = futex_fd(uaddr, val);
1019                 break;
1020         case FUTEX_REQUEUE:
1021                 ret = futex_requeue(uaddr, uaddr2, val, val2, NULL);
1022                 break;
1023         case FUTEX_CMP_REQUEUE:
1024                 ret = futex_requeue(uaddr, uaddr2, val, val2, &val3);
1025                 break;
1026         case FUTEX_WAKE_OP:
1027                 ret = futex_wake_op(uaddr, uaddr2, val, val2, val3);
1028                 break;
1029         default:
1030                 ret = -ENOSYS;
1031         }
1032         return ret;
1033 }
1034
1035
1036 asmlinkage long sys_futex(u32 __user *uaddr, int op, int val,
1037                           struct timespec __user *utime, u32 __user *uaddr2,
1038                           int val3)
1039 {
1040         struct timespec t;
1041         unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
1042         int val2 = 0;
1043
1044         if (utime && (op == FUTEX_WAIT)) {
1045                 if (copy_from_user(&t, utime, sizeof(t)) != 0)
1046                         return -EFAULT;
1047                 if (!timespec_valid(&t))
1048                         return -EINVAL;
1049                 timeout = timespec_to_jiffies(&t) + 1;
1050         }
1051         /*
1052          * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
1053          */
1054         if (op >= FUTEX_REQUEUE)
1055                 val2 = (int) (unsigned long) utime;
1056
1057         return do_futex((unsigned long)uaddr, op, val, timeout,
1058                         (unsigned long)uaddr2, val2, val3);
1059 }
1060
1061 static struct super_block *
1062 futexfs_get_sb(struct file_system_type *fs_type,
1063                int flags, const char *dev_name, void *data)
1064 {
1065         return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA);
1066 }
1067
1068 static struct file_system_type futex_fs_type = {
1069         .name           = "futexfs",
1070         .get_sb         = futexfs_get_sb,
1071         .kill_sb        = kill_anon_super,
1072 };
1073
1074 static int __init init(void)
1075 {
1076         unsigned int i;
1077
1078         register_filesystem(&futex_fs_type);
1079         futex_mnt = kern_mount(&futex_fs_type);
1080
1081         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
1082                 INIT_LIST_HEAD(&futex_queues[i].chain);
1083                 spin_lock_init(&futex_queues[i].lock);
1084         }
1085         return 0;
1086 }
1087 __initcall(init);