9ddf5010ab2e2a11cd665d898e2b122ebe68d36d
[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         if (lock_ptr != 0) {
598                 spin_lock(lock_ptr);
599                 /*
600                  * q->lock_ptr can change between reading it and
601                  * spin_lock(), causing us to take the wrong lock.  This
602                  * corrects the race condition.
603                  *
604                  * Reasoning goes like this: if we have the wrong lock,
605                  * q->lock_ptr must have changed (maybe several times)
606                  * between reading it and the spin_lock().  It can
607                  * change again after the spin_lock() but only if it was
608                  * already changed before the spin_lock().  It cannot,
609                  * however, change back to the original value.  Therefore
610                  * we can detect whether we acquired the correct lock.
611                  */
612                 if (unlikely(lock_ptr != q->lock_ptr)) {
613                         spin_unlock(lock_ptr);
614                         goto retry;
615                 }
616                 WARN_ON(list_empty(&q->list));
617                 list_del(&q->list);
618                 spin_unlock(lock_ptr);
619                 ret = 1;
620         }
621
622         drop_key_refs(&q->key);
623         return ret;
624 }
625
626 static int futex_wait(unsigned long uaddr, int val, unsigned long time)
627 {
628         DECLARE_WAITQUEUE(wait, current);
629         int ret, curval;
630         struct futex_q q;
631         struct futex_hash_bucket *bh;
632
633  retry:
634         down_read(&current->mm->mmap_sem);
635
636         ret = get_futex_key(uaddr, &q.key);
637         if (unlikely(ret != 0))
638                 goto out_release_sem;
639
640         bh = queue_lock(&q, -1, NULL);
641
642         /*
643          * Access the page AFTER the futex is queued.
644          * Order is important:
645          *
646          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
647          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
648          *
649          * The basic logical guarantee of a futex is that it blocks ONLY
650          * if cond(var) is known to be true at the time of blocking, for
651          * any cond.  If we queued after testing *uaddr, that would open
652          * a race condition where we could block indefinitely with
653          * cond(var) false, which would violate the guarantee.
654          *
655          * A consequence is that futex_wait() can return zero and absorb
656          * a wakeup when *uaddr != val on entry to the syscall.  This is
657          * rare, but normal.
658          *
659          * We hold the mmap semaphore, so the mapping cannot have changed
660          * since we looked it up in get_futex_key.
661          */
662
663         ret = get_futex_value_locked(&curval, (int __user *)uaddr);
664
665         if (unlikely(ret)) {
666                 queue_unlock(&q, bh);
667
668                 /* If we would have faulted, release mmap_sem, fault it in and
669                  * start all over again.
670                  */
671                 up_read(&current->mm->mmap_sem);
672
673                 ret = get_user(curval, (int __user *)uaddr);
674
675                 if (!ret)
676                         goto retry;
677                 return ret;
678         }
679         if (curval != val) {
680                 ret = -EWOULDBLOCK;
681                 queue_unlock(&q, bh);
682                 goto out_release_sem;
683         }
684
685         /* Only actually queue if *uaddr contained val.  */
686         __queue_me(&q, bh);
687
688         /*
689          * Now the futex is queued and we have checked the data, we
690          * don't want to hold mmap_sem while we sleep.
691          */     
692         up_read(&current->mm->mmap_sem);
693
694         /*
695          * There might have been scheduling since the queue_me(), as we
696          * cannot hold a spinlock across the get_user() in case it
697          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
698          * queueing ourselves into the futex hash.  This code thus has to
699          * rely on the futex_wake() code removing us from hash when it
700          * wakes us up.
701          */
702
703         /* add_wait_queue is the barrier after __set_current_state. */
704         __set_current_state(TASK_INTERRUPTIBLE);
705         add_wait_queue(&q.waiters, &wait);
706         /*
707          * !list_empty() is safe here without any lock.
708          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
709          */
710         if (likely(!list_empty(&q.list)))
711                 time = schedule_timeout(time);
712         __set_current_state(TASK_RUNNING);
713
714         /*
715          * NOTE: we don't remove ourselves from the waitqueue because
716          * we are the only user of it.
717          */
718
719         /* If we were woken (and unqueued), we succeeded, whatever. */
720         if (!unqueue_me(&q))
721                 return 0;
722         if (time == 0)
723                 return -ETIMEDOUT;
724         /* We expect signal_pending(current), but another thread may
725          * have handled it for us already. */
726         return -EINTR;
727
728  out_release_sem:
729         up_read(&current->mm->mmap_sem);
730         return ret;
731 }
732
733 static int futex_close(struct inode *inode, struct file *filp)
734 {
735         struct futex_q *q = filp->private_data;
736
737         unqueue_me(q);
738         kfree(q);
739         return 0;
740 }
741
742 /* This is one-shot: once it's gone off you need a new fd */
743 static unsigned int futex_poll(struct file *filp,
744                                struct poll_table_struct *wait)
745 {
746         struct futex_q *q = filp->private_data;
747         int ret = 0;
748
749         poll_wait(filp, &q->waiters, wait);
750
751         /*
752          * list_empty() is safe here without any lock.
753          * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
754          */
755         if (list_empty(&q->list))
756                 ret = POLLIN | POLLRDNORM;
757
758         return ret;
759 }
760
761 static struct file_operations futex_fops = {
762         .release        = futex_close,
763         .poll           = futex_poll,
764 };
765
766 /*
767  * Signal allows caller to avoid the race which would occur if they
768  * set the sigio stuff up afterwards.
769  */
770 static int futex_fd(unsigned long uaddr, int signal)
771 {
772         struct futex_q *q;
773         struct file *filp;
774         int ret, err;
775
776         ret = -EINVAL;
777         if (!valid_signal(signal))
778                 goto out;
779
780         ret = get_unused_fd();
781         if (ret < 0)
782                 goto out;
783         filp = get_empty_filp();
784         if (!filp) {
785                 put_unused_fd(ret);
786                 ret = -ENFILE;
787                 goto out;
788         }
789         filp->f_op = &futex_fops;
790         filp->f_vfsmnt = mntget(futex_mnt);
791         filp->f_dentry = dget(futex_mnt->mnt_root);
792         filp->f_mapping = filp->f_dentry->d_inode->i_mapping;
793
794         if (signal) {
795                 err = f_setown(filp, current->pid, 1);
796                 if (err < 0) {
797                         goto error;
798                 }
799                 filp->f_owner.signum = signal;
800         }
801
802         q = kmalloc(sizeof(*q), GFP_KERNEL);
803         if (!q) {
804                 err = -ENOMEM;
805                 goto error;
806         }
807
808         down_read(&current->mm->mmap_sem);
809         err = get_futex_key(uaddr, &q->key);
810
811         if (unlikely(err != 0)) {
812                 up_read(&current->mm->mmap_sem);
813                 kfree(q);
814                 goto error;
815         }
816
817         /*
818          * queue_me() must be called before releasing mmap_sem, because
819          * key->shared.inode needs to be referenced while holding it.
820          */
821         filp->private_data = q;
822
823         queue_me(q, ret, filp);
824         up_read(&current->mm->mmap_sem);
825
826         /* Now we map fd to filp, so userspace can access it */
827         fd_install(ret, filp);
828 out:
829         return ret;
830 error:
831         put_unused_fd(ret);
832         put_filp(filp);
833         ret = err;
834         goto out;
835 }
836
837 /*
838  * Support for robust futexes: the kernel cleans up held futexes at
839  * thread exit time.
840  *
841  * Implementation: user-space maintains a per-thread list of locks it
842  * is holding. Upon do_exit(), the kernel carefully walks this list,
843  * and marks all locks that are owned by this thread with the
844  * FUTEX_OWNER_DEAD bit, and wakes up a waiter (if any). The list is
845  * always manipulated with the lock held, so the list is private and
846  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
847  * field, to allow the kernel to clean up if the thread dies after
848  * acquiring the lock, but just before it could have added itself to
849  * the list. There can only be one such pending lock.
850  */
851
852 /**
853  * sys_set_robust_list - set the robust-futex list head of a task
854  * @head: pointer to the list-head
855  * @len: length of the list-head, as userspace expects
856  */
857 asmlinkage long
858 sys_set_robust_list(struct robust_list_head __user *head,
859                     size_t len)
860 {
861         /*
862          * The kernel knows only one size for now:
863          */
864         if (unlikely(len != sizeof(*head)))
865                 return -EINVAL;
866
867         current->robust_list = head;
868
869         return 0;
870 }
871
872 /**
873  * sys_get_robust_list - get the robust-futex list head of a task
874  * @pid: pid of the process [zero for current task]
875  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
876  * @len_ptr: pointer to a length field, the kernel fills in the header size
877  */
878 asmlinkage long
879 sys_get_robust_list(int pid, struct robust_list_head __user **head_ptr,
880                     size_t __user *len_ptr)
881 {
882         struct robust_list_head *head;
883         unsigned long ret;
884
885         if (!pid)
886                 head = current->robust_list;
887         else {
888                 struct task_struct *p;
889
890                 ret = -ESRCH;
891                 read_lock(&tasklist_lock);
892                 p = find_task_by_pid(pid);
893                 if (!p)
894                         goto err_unlock;
895                 ret = -EPERM;
896                 if ((current->euid != p->euid) && (current->euid != p->uid) &&
897                                 !capable(CAP_SYS_PTRACE))
898                         goto err_unlock;
899                 head = p->robust_list;
900                 read_unlock(&tasklist_lock);
901         }
902
903         if (put_user(sizeof(*head), len_ptr))
904                 return -EFAULT;
905         return put_user(head, head_ptr);
906
907 err_unlock:
908         read_unlock(&tasklist_lock);
909
910         return ret;
911 }
912
913 /*
914  * Process a futex-list entry, check whether it's owned by the
915  * dying task, and do notification if so:
916  */
917 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr)
918 {
919         u32 uval;
920
921 retry:
922         if (get_user(uval, uaddr))
923                 return -1;
924
925         if ((uval & FUTEX_TID_MASK) == curr->pid) {
926                 /*
927                  * Ok, this dying thread is truly holding a futex
928                  * of interest. Set the OWNER_DIED bit atomically
929                  * via cmpxchg, and if the value had FUTEX_WAITERS
930                  * set, wake up a waiter (if any). (We have to do a
931                  * futex_wake() even if OWNER_DIED is already set -
932                  * to handle the rare but possible case of recursive
933                  * thread-death.) The rest of the cleanup is done in
934                  * userspace.
935                  */
936                 if (futex_atomic_cmpxchg_inatomic(uaddr, uval,
937                                          uval | FUTEX_OWNER_DIED) != uval)
938                         goto retry;
939
940                 if (uval & FUTEX_WAITERS)
941                         futex_wake((unsigned long)uaddr, 1);
942         }
943         return 0;
944 }
945
946 /*
947  * Walk curr->robust_list (very carefully, it's a userspace list!)
948  * and mark any locks found there dead, and notify any waiters.
949  *
950  * We silently return on any sign of list-walking problem.
951  */
952 void exit_robust_list(struct task_struct *curr)
953 {
954         struct robust_list_head __user *head = curr->robust_list;
955         struct robust_list __user *entry, *pending;
956         unsigned int limit = ROBUST_LIST_LIMIT;
957         unsigned long futex_offset;
958
959         /*
960          * Fetch the list head (which was registered earlier, via
961          * sys_set_robust_list()):
962          */
963         if (get_user(entry, &head->list.next))
964                 return;
965         /*
966          * Fetch the relative futex offset:
967          */
968         if (get_user(futex_offset, &head->futex_offset))
969                 return;
970         /*
971          * Fetch any possibly pending lock-add first, and handle it
972          * if it exists:
973          */
974         if (get_user(pending, &head->list_op_pending))
975                 return;
976         if (pending)
977                 handle_futex_death((void *)pending + futex_offset, curr);
978
979         while (entry != &head->list) {
980                 /*
981                  * A pending lock might already be on the list, so
982                  * dont process it twice:
983                  */
984                 if (entry != pending)
985                         if (handle_futex_death((void *)entry + futex_offset,
986                                                 curr))
987                                 return;
988                 /*
989                  * Fetch the next entry in the list:
990                  */
991                 if (get_user(entry, &entry->next))
992                         return;
993                 /*
994                  * Avoid excessively long or circular lists:
995                  */
996                 if (!--limit)
997                         break;
998
999                 cond_resched();
1000         }
1001 }
1002
1003 long do_futex(unsigned long uaddr, int op, int val, unsigned long timeout,
1004                 unsigned long uaddr2, int val2, int val3)
1005 {
1006         int ret;
1007
1008         switch (op) {
1009         case FUTEX_WAIT:
1010                 ret = futex_wait(uaddr, val, timeout);
1011                 break;
1012         case FUTEX_WAKE:
1013                 ret = futex_wake(uaddr, val);
1014                 break;
1015         case FUTEX_FD:
1016                 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
1017                 ret = futex_fd(uaddr, val);
1018                 break;
1019         case FUTEX_REQUEUE:
1020                 ret = futex_requeue(uaddr, uaddr2, val, val2, NULL);
1021                 break;
1022         case FUTEX_CMP_REQUEUE:
1023                 ret = futex_requeue(uaddr, uaddr2, val, val2, &val3);
1024                 break;
1025         case FUTEX_WAKE_OP:
1026                 ret = futex_wake_op(uaddr, uaddr2, val, val2, val3);
1027                 break;
1028         default:
1029                 ret = -ENOSYS;
1030         }
1031         return ret;
1032 }
1033
1034
1035 asmlinkage long sys_futex(u32 __user *uaddr, int op, int val,
1036                           struct timespec __user *utime, u32 __user *uaddr2,
1037                           int val3)
1038 {
1039         struct timespec t;
1040         unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
1041         int val2 = 0;
1042
1043         if (utime && (op == FUTEX_WAIT)) {
1044                 if (copy_from_user(&t, utime, sizeof(t)) != 0)
1045                         return -EFAULT;
1046                 if (!timespec_valid(&t))
1047                         return -EINVAL;
1048                 timeout = timespec_to_jiffies(&t) + 1;
1049         }
1050         /*
1051          * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
1052          */
1053         if (op >= FUTEX_REQUEUE)
1054                 val2 = (int) (unsigned long) utime;
1055
1056         return do_futex((unsigned long)uaddr, op, val, timeout,
1057                         (unsigned long)uaddr2, val2, val3);
1058 }
1059
1060 static struct super_block *
1061 futexfs_get_sb(struct file_system_type *fs_type,
1062                int flags, const char *dev_name, void *data)
1063 {
1064         return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA);
1065 }
1066
1067 static struct file_system_type futex_fs_type = {
1068         .name           = "futexfs",
1069         .get_sb         = futexfs_get_sb,
1070         .kill_sb        = kill_anon_super,
1071 };
1072
1073 static int __init init(void)
1074 {
1075         unsigned int i;
1076
1077         register_filesystem(&futex_fs_type);
1078         futex_mnt = kern_mount(&futex_fs_type);
1079
1080         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
1081                 INIT_LIST_HEAD(&futex_queues[i].chain);
1082                 spin_lock_init(&futex_queues[i].lock);
1083         }
1084         return 0;
1085 }
1086 __initcall(init);