50356fb5d72685fb6c68d0bcf3ed0ec1074b693b
[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  *  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 <asm/futex.h>
48
49 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
50
51 /*
52  * Futexes are matched on equal values of this key.
53  * The key type depends on whether it's a shared or private mapping.
54  * Don't rearrange members without looking at hash_futex().
55  *
56  * offset is aligned to a multiple of sizeof(u32) (== 4) by definition.
57  * We set bit 0 to indicate if it's an inode-based key.
58  */
59 union futex_key {
60         struct {
61                 unsigned long pgoff;
62                 struct inode *inode;
63                 int offset;
64         } shared;
65         struct {
66                 unsigned long address;
67                 struct mm_struct *mm;
68                 int offset;
69         } private;
70         struct {
71                 unsigned long word;
72                 void *ptr;
73                 int offset;
74         } both;
75 };
76
77 /*
78  * We use this hashed waitqueue instead of a normal wait_queue_t, so
79  * we can wake only the relevant ones (hashed queues may be shared).
80  *
81  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
82  * It is considered woken when list_empty(&q->list) || q->lock_ptr == 0.
83  * The order of wakup is always to make the first condition true, then
84  * wake up q->waiters, then make the second condition true.
85  */
86 struct futex_q {
87         struct list_head list;
88         wait_queue_head_t waiters;
89
90         /* Which hash list lock to use: */
91         spinlock_t *lock_ptr;
92
93         /* Key which the futex is hashed on: */
94         union futex_key key;
95
96         /* For fd, sigio sent using these: */
97         int fd;
98         struct file *filp;
99 };
100
101 /*
102  * Split the global futex_lock into every hash list lock.
103  */
104 struct futex_hash_bucket {
105        spinlock_t              lock;
106        struct list_head       chain;
107 };
108
109 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
110
111 /* Futex-fs vfsmount entry: */
112 static struct vfsmount *futex_mnt;
113
114 /*
115  * We hash on the keys returned from get_futex_key (see below).
116  */
117 static struct futex_hash_bucket *hash_futex(union futex_key *key)
118 {
119         u32 hash = jhash2((u32*)&key->both.word,
120                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
121                           key->both.offset);
122         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
123 }
124
125 /*
126  * Return 1 if two futex_keys are equal, 0 otherwise.
127  */
128 static inline int match_futex(union futex_key *key1, union futex_key *key2)
129 {
130         return (key1->both.word == key2->both.word
131                 && key1->both.ptr == key2->both.ptr
132                 && key1->both.offset == key2->both.offset);
133 }
134
135 /*
136  * Get parameters which are the keys for a futex.
137  *
138  * For shared mappings, it's (page->index, vma->vm_file->f_dentry->d_inode,
139  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
140  * We can usually work out the index without swapping in the page.
141  *
142  * Returns: 0, or negative error code.
143  * The key words are stored in *key on success.
144  *
145  * Should be called with &current->mm->mmap_sem but NOT any spinlocks.
146  */
147 static int get_futex_key(u32 __user *uaddr, union futex_key *key)
148 {
149         unsigned long address = (unsigned long)uaddr;
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 = address % PAGE_SIZE;
159         if (unlikely((key->both.offset % sizeof(u32)) != 0))
160                 return -EINVAL;
161         address -= 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, address);
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.address = address;
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 = (((address - 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, address, 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(u32 *dest, u32 __user *from)
251 {
252         int ret;
253
254         inc_preempt_count();
255         ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
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(u32 __user *uaddr, int nr_wake)
293 {
294         struct futex_hash_bucket *hb;
295         struct futex_q *this, *next;
296         struct list_head *head;
297         union futex_key key;
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         hb = hash_futex(&key);
307         spin_lock(&hb->lock);
308         head = &hb->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(&hb->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
329 futex_wake_op(u32 __user *uaddr1, u32 __user *uaddr2,
330               int nr_wake, int nr_wake2, int op)
331 {
332         union futex_key key1, key2;
333         struct futex_hash_bucket *hb1, *hb2;
334         struct list_head *head;
335         struct futex_q *this, *next;
336         int ret, op_ret, attempt = 0;
337
338 retryfull:
339         down_read(&current->mm->mmap_sem);
340
341         ret = get_futex_key(uaddr1, &key1);
342         if (unlikely(ret != 0))
343                 goto out;
344         ret = get_futex_key(uaddr2, &key2);
345         if (unlikely(ret != 0))
346                 goto out;
347
348         hb1 = hash_futex(&key1);
349         hb2 = hash_futex(&key2);
350
351 retry:
352         if (hb1 < hb2)
353                 spin_lock(&hb1->lock);
354         spin_lock(&hb2->lock);
355         if (hb1 > hb2)
356                 spin_lock(&hb1->lock);
357
358         op_ret = futex_atomic_op_inuser(op, uaddr2);
359         if (unlikely(op_ret < 0)) {
360                 u32 dummy;
361
362                 spin_unlock(&hb1->lock);
363                 if (hb1 != hb2)
364                         spin_unlock(&hb2->lock);
365
366 #ifndef CONFIG_MMU
367                 /*
368                  * we don't get EFAULT from MMU faults if we don't have an MMU,
369                  * but we might get them from range checking
370                  */
371                 ret = op_ret;
372                 goto out;
373 #endif
374
375                 if (unlikely(op_ret != -EFAULT)) {
376                         ret = op_ret;
377                         goto out;
378                 }
379
380                 /*
381                  * futex_atomic_op_inuser needs to both read and write
382                  * *(int __user *)uaddr2, but we can't modify it
383                  * non-atomically.  Therefore, if get_user below is not
384                  * enough, we need to handle the fault ourselves, while
385                  * still holding the mmap_sem.
386                  */
387                 if (attempt++) {
388                         struct vm_area_struct * vma;
389                         struct mm_struct *mm = current->mm;
390                         unsigned long address = (unsigned long)uaddr2;
391
392                         ret = -EFAULT;
393                         if (attempt >= 2 ||
394                             !(vma = find_vma(mm, address)) ||
395                             vma->vm_start > address ||
396                             !(vma->vm_flags & VM_WRITE))
397                                 goto out;
398
399                         switch (handle_mm_fault(mm, vma, address, 1)) {
400                         case VM_FAULT_MINOR:
401                                 current->min_flt++;
402                                 break;
403                         case VM_FAULT_MAJOR:
404                                 current->maj_flt++;
405                                 break;
406                         default:
407                                 goto out;
408                         }
409                         goto retry;
410                 }
411
412                 /*
413                  * If we would have faulted, release mmap_sem,
414                  * fault it in and start all over again.
415                  */
416                 up_read(&current->mm->mmap_sem);
417
418                 ret = get_user(dummy, uaddr2);
419                 if (ret)
420                         return ret;
421
422                 goto retryfull;
423         }
424
425         head = &hb1->chain;
426
427         list_for_each_entry_safe(this, next, head, list) {
428                 if (match_futex (&this->key, &key1)) {
429                         wake_futex(this);
430                         if (++ret >= nr_wake)
431                                 break;
432                 }
433         }
434
435         if (op_ret > 0) {
436                 head = &hb2->chain;
437
438                 op_ret = 0;
439                 list_for_each_entry_safe(this, next, head, list) {
440                         if (match_futex (&this->key, &key2)) {
441                                 wake_futex(this);
442                                 if (++op_ret >= nr_wake2)
443                                         break;
444                         }
445                 }
446                 ret += op_ret;
447         }
448
449         spin_unlock(&hb1->lock);
450         if (hb1 != hb2)
451                 spin_unlock(&hb2->lock);
452 out:
453         up_read(&current->mm->mmap_sem);
454         return ret;
455 }
456
457 /*
458  * Requeue all waiters hashed on one physical page to another
459  * physical page.
460  */
461 static int futex_requeue(u32 __user *uaddr1, u32 __user *uaddr2,
462                          int nr_wake, int nr_requeue, u32 *cmpval)
463 {
464         union futex_key key1, key2;
465         struct futex_hash_bucket *hb1, *hb2;
466         struct list_head *head1;
467         struct futex_q *this, *next;
468         int ret, drop_count = 0;
469
470  retry:
471         down_read(&current->mm->mmap_sem);
472
473         ret = get_futex_key(uaddr1, &key1);
474         if (unlikely(ret != 0))
475                 goto out;
476         ret = get_futex_key(uaddr2, &key2);
477         if (unlikely(ret != 0))
478                 goto out;
479
480         hb1 = hash_futex(&key1);
481         hb2 = hash_futex(&key2);
482
483         if (hb1 < hb2)
484                 spin_lock(&hb1->lock);
485         spin_lock(&hb2->lock);
486         if (hb1 > hb2)
487                 spin_lock(&hb1->lock);
488
489         if (likely(cmpval != NULL)) {
490                 u32 curval;
491
492                 ret = get_futex_value_locked(&curval, uaddr1);
493
494                 if (unlikely(ret)) {
495                         spin_unlock(&hb1->lock);
496                         if (hb1 != hb2)
497                                 spin_unlock(&hb2->lock);
498
499                         /*
500                          * If we would have faulted, release mmap_sem, fault
501                          * it in and start all over again.
502                          */
503                         up_read(&current->mm->mmap_sem);
504
505                         ret = get_user(curval, uaddr1);
506
507                         if (!ret)
508                                 goto retry;
509
510                         return ret;
511                 }
512                 if (curval != *cmpval) {
513                         ret = -EAGAIN;
514                         goto out_unlock;
515                 }
516         }
517
518         head1 = &hb1->chain;
519         list_for_each_entry_safe(this, next, head1, list) {
520                 if (!match_futex (&this->key, &key1))
521                         continue;
522                 if (++ret <= nr_wake) {
523                         wake_futex(this);
524                 } else {
525                         list_move_tail(&this->list, &hb2->chain);
526                         this->lock_ptr = &hb2->lock;
527                         this->key = key2;
528                         get_key_refs(&key2);
529                         drop_count++;
530
531                         if (ret - nr_wake >= nr_requeue)
532                                 break;
533                         /* Make sure to stop if key1 == key2: */
534                         if (head1 == &hb2->chain && head1 != &next->list)
535                                 head1 = &this->list;
536                 }
537         }
538
539 out_unlock:
540         spin_unlock(&hb1->lock);
541         if (hb1 != hb2)
542                 spin_unlock(&hb2->lock);
543
544         /* drop_key_refs() must be called outside the spinlocks. */
545         while (--drop_count >= 0)
546                 drop_key_refs(&key1);
547
548 out:
549         up_read(&current->mm->mmap_sem);
550         return ret;
551 }
552
553 /* The key must be already stored in q->key. */
554 static inline struct futex_hash_bucket *
555 queue_lock(struct futex_q *q, int fd, struct file *filp)
556 {
557         struct futex_hash_bucket *hb;
558
559         q->fd = fd;
560         q->filp = filp;
561
562         init_waitqueue_head(&q->waiters);
563
564         get_key_refs(&q->key);
565         hb = hash_futex(&q->key);
566         q->lock_ptr = &hb->lock;
567
568         spin_lock(&hb->lock);
569         return hb;
570 }
571
572 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
573 {
574         list_add_tail(&q->list, &hb->chain);
575         spin_unlock(&hb->lock);
576 }
577
578 static inline void
579 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
580 {
581         spin_unlock(&hb->lock);
582         drop_key_refs(&q->key);
583 }
584
585 /*
586  * queue_me and unqueue_me must be called as a pair, each
587  * exactly once.  They are called with the hashed spinlock held.
588  */
589
590 /* The key must be already stored in q->key. */
591 static void queue_me(struct futex_q *q, int fd, struct file *filp)
592 {
593         struct futex_hash_bucket *hb;
594
595         hb = queue_lock(q, fd, filp);
596         __queue_me(q, hb);
597 }
598
599 /* Return 1 if we were still queued (ie. 0 means we were woken) */
600 static int unqueue_me(struct futex_q *q)
601 {
602         spinlock_t *lock_ptr;
603         int ret = 0;
604
605         /* In the common case we don't take the spinlock, which is nice. */
606  retry:
607         lock_ptr = q->lock_ptr;
608         if (lock_ptr != 0) {
609                 spin_lock(lock_ptr);
610                 /*
611                  * q->lock_ptr can change between reading it and
612                  * spin_lock(), causing us to take the wrong lock.  This
613                  * corrects the race condition.
614                  *
615                  * Reasoning goes like this: if we have the wrong lock,
616                  * q->lock_ptr must have changed (maybe several times)
617                  * between reading it and the spin_lock().  It can
618                  * change again after the spin_lock() but only if it was
619                  * already changed before the spin_lock().  It cannot,
620                  * however, change back to the original value.  Therefore
621                  * we can detect whether we acquired the correct lock.
622                  */
623                 if (unlikely(lock_ptr != q->lock_ptr)) {
624                         spin_unlock(lock_ptr);
625                         goto retry;
626                 }
627                 WARN_ON(list_empty(&q->list));
628                 list_del(&q->list);
629                 spin_unlock(lock_ptr);
630                 ret = 1;
631         }
632
633         drop_key_refs(&q->key);
634         return ret;
635 }
636
637 static int futex_wait(u32 __user *uaddr, u32 val, unsigned long time)
638 {
639         DECLARE_WAITQUEUE(wait, current);
640         struct futex_hash_bucket *hb;
641         struct futex_q q;
642         u32 uval;
643         int ret;
644
645  retry:
646         down_read(&current->mm->mmap_sem);
647
648         ret = get_futex_key(uaddr, &q.key);
649         if (unlikely(ret != 0))
650                 goto out_release_sem;
651
652         hb = queue_lock(&q, -1, NULL);
653
654         /*
655          * Access the page AFTER the futex is queued.
656          * Order is important:
657          *
658          *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
659          *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
660          *
661          * The basic logical guarantee of a futex is that it blocks ONLY
662          * if cond(var) is known to be true at the time of blocking, for
663          * any cond.  If we queued after testing *uaddr, that would open
664          * a race condition where we could block indefinitely with
665          * cond(var) false, which would violate the guarantee.
666          *
667          * A consequence is that futex_wait() can return zero and absorb
668          * a wakeup when *uaddr != val on entry to the syscall.  This is
669          * rare, but normal.
670          *
671          * We hold the mmap semaphore, so the mapping cannot have changed
672          * since we looked it up in get_futex_key.
673          */
674         ret = get_futex_value_locked(&uval, uaddr);
675
676         if (unlikely(ret)) {
677                 queue_unlock(&q, hb);
678
679                 /*
680                  * If we would have faulted, release mmap_sem, fault it in and
681                  * start all over again.
682                  */
683                 up_read(&current->mm->mmap_sem);
684
685                 ret = get_user(uval, uaddr);
686
687                 if (!ret)
688                         goto retry;
689                 return ret;
690         }
691         if (uval != val) {
692                 ret = -EWOULDBLOCK;
693                 queue_unlock(&q, hb);
694                 goto out_release_sem;
695         }
696
697         /* Only actually queue if *uaddr contained val.  */
698         __queue_me(&q, hb);
699
700         /*
701          * Now the futex is queued and we have checked the data, we
702          * don't want to hold mmap_sem while we sleep.
703          */     
704         up_read(&current->mm->mmap_sem);
705
706         /*
707          * There might have been scheduling since the queue_me(), as we
708          * cannot hold a spinlock across the get_user() in case it
709          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
710          * queueing ourselves into the futex hash.  This code thus has to
711          * rely on the futex_wake() code removing us from hash when it
712          * wakes us up.
713          */
714
715         /* add_wait_queue is the barrier after __set_current_state. */
716         __set_current_state(TASK_INTERRUPTIBLE);
717         add_wait_queue(&q.waiters, &wait);
718         /*
719          * !list_empty() is safe here without any lock.
720          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
721          */
722         if (likely(!list_empty(&q.list)))
723                 time = schedule_timeout(time);
724         __set_current_state(TASK_RUNNING);
725
726         /*
727          * NOTE: we don't remove ourselves from the waitqueue because
728          * we are the only user of it.
729          */
730
731         /* If we were woken (and unqueued), we succeeded, whatever. */
732         if (!unqueue_me(&q))
733                 return 0;
734         if (time == 0)
735                 return -ETIMEDOUT;
736         /*
737          * We expect signal_pending(current), but another thread may
738          * have handled it for us already.
739          */
740         return -EINTR;
741
742  out_release_sem:
743         up_read(&current->mm->mmap_sem);
744         return ret;
745 }
746
747 static int futex_close(struct inode *inode, struct file *filp)
748 {
749         struct futex_q *q = filp->private_data;
750
751         unqueue_me(q);
752         kfree(q);
753
754         return 0;
755 }
756
757 /* This is one-shot: once it's gone off you need a new fd */
758 static unsigned int futex_poll(struct file *filp,
759                                struct poll_table_struct *wait)
760 {
761         struct futex_q *q = filp->private_data;
762         int ret = 0;
763
764         poll_wait(filp, &q->waiters, wait);
765
766         /*
767          * list_empty() is safe here without any lock.
768          * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
769          */
770         if (list_empty(&q->list))
771                 ret = POLLIN | POLLRDNORM;
772
773         return ret;
774 }
775
776 static struct file_operations futex_fops = {
777         .release        = futex_close,
778         .poll           = futex_poll,
779 };
780
781 /*
782  * Signal allows caller to avoid the race which would occur if they
783  * set the sigio stuff up afterwards.
784  */
785 static int futex_fd(u32 __user *uaddr, int signal)
786 {
787         struct futex_q *q;
788         struct file *filp;
789         int ret, err;
790
791         ret = -EINVAL;
792         if (!valid_signal(signal))
793                 goto out;
794
795         ret = get_unused_fd();
796         if (ret < 0)
797                 goto out;
798         filp = get_empty_filp();
799         if (!filp) {
800                 put_unused_fd(ret);
801                 ret = -ENFILE;
802                 goto out;
803         }
804         filp->f_op = &futex_fops;
805         filp->f_vfsmnt = mntget(futex_mnt);
806         filp->f_dentry = dget(futex_mnt->mnt_root);
807         filp->f_mapping = filp->f_dentry->d_inode->i_mapping;
808
809         if (signal) {
810                 err = f_setown(filp, current->pid, 1);
811                 if (err < 0) {
812                         goto error;
813                 }
814                 filp->f_owner.signum = signal;
815         }
816
817         q = kmalloc(sizeof(*q), GFP_KERNEL);
818         if (!q) {
819                 err = -ENOMEM;
820                 goto error;
821         }
822
823         down_read(&current->mm->mmap_sem);
824         err = get_futex_key(uaddr, &q->key);
825
826         if (unlikely(err != 0)) {
827                 up_read(&current->mm->mmap_sem);
828                 kfree(q);
829                 goto error;
830         }
831
832         /*
833          * queue_me() must be called before releasing mmap_sem, because
834          * key->shared.inode needs to be referenced while holding it.
835          */
836         filp->private_data = q;
837
838         queue_me(q, ret, filp);
839         up_read(&current->mm->mmap_sem);
840
841         /* Now we map fd to filp, so userspace can access it */
842         fd_install(ret, filp);
843 out:
844         return ret;
845 error:
846         put_unused_fd(ret);
847         put_filp(filp);
848         ret = err;
849         goto out;
850 }
851
852 /*
853  * Support for robust futexes: the kernel cleans up held futexes at
854  * thread exit time.
855  *
856  * Implementation: user-space maintains a per-thread list of locks it
857  * is holding. Upon do_exit(), the kernel carefully walks this list,
858  * and marks all locks that are owned by this thread with the
859  * FUTEX_OWNER_DEAD bit, and wakes up a waiter (if any). The list is
860  * always manipulated with the lock held, so the list is private and
861  * per-thread. Userspace also maintains a per-thread 'list_op_pending'
862  * field, to allow the kernel to clean up if the thread dies after
863  * acquiring the lock, but just before it could have added itself to
864  * the list. There can only be one such pending lock.
865  */
866
867 /**
868  * sys_set_robust_list - set the robust-futex list head of a task
869  * @head: pointer to the list-head
870  * @len: length of the list-head, as userspace expects
871  */
872 asmlinkage long
873 sys_set_robust_list(struct robust_list_head __user *head,
874                     size_t len)
875 {
876         /*
877          * The kernel knows only one size for now:
878          */
879         if (unlikely(len != sizeof(*head)))
880                 return -EINVAL;
881
882         current->robust_list = head;
883
884         return 0;
885 }
886
887 /**
888  * sys_get_robust_list - get the robust-futex list head of a task
889  * @pid: pid of the process [zero for current task]
890  * @head_ptr: pointer to a list-head pointer, the kernel fills it in
891  * @len_ptr: pointer to a length field, the kernel fills in the header size
892  */
893 asmlinkage long
894 sys_get_robust_list(int pid, struct robust_list_head __user **head_ptr,
895                     size_t __user *len_ptr)
896 {
897         struct robust_list_head *head;
898         unsigned long ret;
899
900         if (!pid)
901                 head = current->robust_list;
902         else {
903                 struct task_struct *p;
904
905                 ret = -ESRCH;
906                 read_lock(&tasklist_lock);
907                 p = find_task_by_pid(pid);
908                 if (!p)
909                         goto err_unlock;
910                 ret = -EPERM;
911                 if ((current->euid != p->euid) && (current->euid != p->uid) &&
912                                 !capable(CAP_SYS_PTRACE))
913                         goto err_unlock;
914                 head = p->robust_list;
915                 read_unlock(&tasklist_lock);
916         }
917
918         if (put_user(sizeof(*head), len_ptr))
919                 return -EFAULT;
920         return put_user(head, head_ptr);
921
922 err_unlock:
923         read_unlock(&tasklist_lock);
924
925         return ret;
926 }
927
928 /*
929  * Process a futex-list entry, check whether it's owned by the
930  * dying task, and do notification if so:
931  */
932 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr)
933 {
934         u32 uval;
935
936 retry:
937         if (get_user(uval, uaddr))
938                 return -1;
939
940         if ((uval & FUTEX_TID_MASK) == curr->pid) {
941                 /*
942                  * Ok, this dying thread is truly holding a futex
943                  * of interest. Set the OWNER_DIED bit atomically
944                  * via cmpxchg, and if the value had FUTEX_WAITERS
945                  * set, wake up a waiter (if any). (We have to do a
946                  * futex_wake() even if OWNER_DIED is already set -
947                  * to handle the rare but possible case of recursive
948                  * thread-death.) The rest of the cleanup is done in
949                  * userspace.
950                  */
951                 if (futex_atomic_cmpxchg_inatomic(uaddr, uval,
952                                          uval | FUTEX_OWNER_DIED) != uval)
953                         goto retry;
954
955                 if (uval & FUTEX_WAITERS)
956                         futex_wake(uaddr, 1);
957         }
958         return 0;
959 }
960
961 /*
962  * Walk curr->robust_list (very carefully, it's a userspace list!)
963  * and mark any locks found there dead, and notify any waiters.
964  *
965  * We silently return on any sign of list-walking problem.
966  */
967 void exit_robust_list(struct task_struct *curr)
968 {
969         struct robust_list_head __user *head = curr->robust_list;
970         struct robust_list __user *entry, *pending;
971         unsigned int limit = ROBUST_LIST_LIMIT;
972         unsigned long futex_offset;
973
974         /*
975          * Fetch the list head (which was registered earlier, via
976          * sys_set_robust_list()):
977          */
978         if (get_user(entry, &head->list.next))
979                 return;
980         /*
981          * Fetch the relative futex offset:
982          */
983         if (get_user(futex_offset, &head->futex_offset))
984                 return;
985         /*
986          * Fetch any possibly pending lock-add first, and handle it
987          * if it exists:
988          */
989         if (get_user(pending, &head->list_op_pending))
990                 return;
991         if (pending)
992                 handle_futex_death((void *)pending + futex_offset, curr);
993
994         while (entry != &head->list) {
995                 /*
996                  * A pending lock might already be on the list, so
997                  * dont process it twice:
998                  */
999                 if (entry != pending)
1000                         if (handle_futex_death((void *)entry + futex_offset,
1001                                                 curr))
1002                                 return;
1003                 /*
1004                  * Fetch the next entry in the list:
1005                  */
1006                 if (get_user(entry, &entry->next))
1007                         return;
1008                 /*
1009                  * Avoid excessively long or circular lists:
1010                  */
1011                 if (!--limit)
1012                         break;
1013
1014                 cond_resched();
1015         }
1016 }
1017
1018 long do_futex(u32 __user *uaddr, int op, u32 val, unsigned long timeout,
1019                 u32 __user *uaddr2, u32 val2, u32 val3)
1020 {
1021         int ret;
1022
1023         switch (op) {
1024         case FUTEX_WAIT:
1025                 ret = futex_wait(uaddr, val, timeout);
1026                 break;
1027         case FUTEX_WAKE:
1028                 ret = futex_wake(uaddr, val);
1029                 break;
1030         case FUTEX_FD:
1031                 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
1032                 ret = futex_fd(uaddr, val);
1033                 break;
1034         case FUTEX_REQUEUE:
1035                 ret = futex_requeue(uaddr, uaddr2, val, val2, NULL);
1036                 break;
1037         case FUTEX_CMP_REQUEUE:
1038                 ret = futex_requeue(uaddr, uaddr2, val, val2, &val3);
1039                 break;
1040         case FUTEX_WAKE_OP:
1041                 ret = futex_wake_op(uaddr, uaddr2, val, val2, val3);
1042                 break;
1043         default:
1044                 ret = -ENOSYS;
1045         }
1046         return ret;
1047 }
1048
1049
1050 asmlinkage long sys_futex(u32 __user *uaddr, int op, u32 val,
1051                           struct timespec __user *utime, u32 __user *uaddr2,
1052                           u32 val3)
1053 {
1054         struct timespec t;
1055         unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
1056         u32 val2 = 0;
1057
1058         if (utime && (op == FUTEX_WAIT)) {
1059                 if (copy_from_user(&t, utime, sizeof(t)) != 0)
1060                         return -EFAULT;
1061                 if (!timespec_valid(&t))
1062                         return -EINVAL;
1063                 timeout = timespec_to_jiffies(&t) + 1;
1064         }
1065         /*
1066          * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
1067          */
1068         if (op >= FUTEX_REQUEUE)
1069                 val2 = (u32) (unsigned long) utime;
1070
1071         return do_futex(uaddr, op, val, timeout, uaddr2, val2, val3);
1072 }
1073
1074 static int futexfs_get_sb(struct file_system_type *fs_type,
1075                           int flags, const char *dev_name, void *data,
1076                           struct vfsmount *mnt)
1077 {
1078         return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA, mnt);
1079 }
1080
1081 static struct file_system_type futex_fs_type = {
1082         .name           = "futexfs",
1083         .get_sb         = futexfs_get_sb,
1084         .kill_sb        = kill_anon_super,
1085 };
1086
1087 static int __init init(void)
1088 {
1089         unsigned int i;
1090
1091         register_filesystem(&futex_fs_type);
1092         futex_mnt = kern_mount(&futex_fs_type);
1093
1094         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
1095                 INIT_LIST_HEAD(&futex_queues[i].chain);
1096                 spin_lock_init(&futex_queues[i].lock);
1097         }
1098         return 0;
1099 }
1100 __initcall(init);