ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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 Jamie Lokier
10  *
11  *  Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
12  *  enough at me, Linus for the original (flawed) idea, Matthew
13  *  Kirkwood for proof-of-concept implementation.
14  *
15  *  "The futexes are also cursed."
16  *  "But they come in a choice of three flavours!"
17  *
18  *  This program is free software; you can redistribute it and/or modify
19  *  it under the terms of the GNU General Public License as published by
20  *  the Free Software Foundation; either version 2 of the License, or
21  *  (at your option) any later version.
22  *
23  *  This program is distributed in the hope that it will be useful,
24  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
25  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  *  GNU General Public License for more details.
27  *
28  *  You should have received a copy of the GNU General Public License
29  *  along with this program; if not, write to the Free Software
30  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
31  */
32 #include <linux/slab.h>
33 #include <linux/poll.h>
34 #include <linux/fs.h>
35 #include <linux/file.h>
36 #include <linux/jhash.h>
37 #include <linux/init.h>
38 #include <linux/futex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41
42 #define FUTEX_HASHBITS 8
43
44 /*
45  * Futexes are matched on equal values of this key.
46  * The key type depends on whether it's a shared or private mapping.
47  * Don't rearrange members without looking at hash_futex().
48  *
49  * offset is aligned to a multiple of sizeof(u32) (== 4) by definition.
50  * We set bit 0 to indicate if it's an inode-based key.
51  */
52 union futex_key {
53         struct {
54                 unsigned long pgoff;
55                 struct inode *inode;
56                 int offset;
57         } shared;
58         struct {
59                 unsigned long uaddr;
60                 struct mm_struct *mm;
61                 int offset;
62         } private;
63         struct {
64                 unsigned long word;
65                 void *ptr;
66                 int offset;
67         } both;
68 };
69
70 /*
71  * We use this hashed waitqueue instead of a normal wait_queue_t, so
72  * we can wake only the relevant ones (hashed queues may be shared).
73  *
74  * A futex_q has a woken state, just like tasks have TASK_RUNNING.
75  * It is considered woken when list_empty(&q->list) || q->lock_ptr == 0.
76  * The order of wakup is always to make the first condition true, then
77  * wake up q->waiters, then make the second condition true.
78  */
79 struct futex_q {
80         struct list_head list;
81         wait_queue_head_t waiters;
82
83         /* Which hash list lock to use. */
84         spinlock_t *lock_ptr;
85
86         /* Key which the futex is hashed on. */
87         union futex_key key;
88
89         /* For fd, sigio sent using these. */
90         int fd;
91         struct file *filp;
92 };
93
94 /*
95  * Split the global futex_lock into every hash list lock.
96  */
97 struct futex_hash_bucket {
98        spinlock_t              lock;
99        struct list_head       chain;
100 };
101
102 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
103
104 /* Futex-fs vfsmount entry: */
105 static struct vfsmount *futex_mnt;
106
107 /*
108  * We hash on the keys returned from get_futex_key (see below).
109  */
110 static struct futex_hash_bucket *hash_futex(union futex_key *key)
111 {
112         u32 hash = jhash2((u32*)&key->both.word,
113                           (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
114                           key->both.offset);
115         return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
116 }
117
118 /*
119  * Return 1 if two futex_keys are equal, 0 otherwise.
120  */
121 static inline int match_futex(union futex_key *key1, union futex_key *key2)
122 {
123         return (key1->both.word == key2->both.word
124                 && key1->both.ptr == key2->both.ptr
125                 && key1->both.offset == key2->both.offset);
126 }
127
128 /*
129  * Get parameters which are the keys for a futex.
130  *
131  * For shared mappings, it's (page->index, vma->vm_file->f_dentry->d_inode,
132  * offset_within_page).  For private mappings, it's (uaddr, current->mm).
133  * We can usually work out the index without swapping in the page.
134  *
135  * Returns: 0, or negative error code.
136  * The key words are stored in *key on success.
137  *
138  * Should be called with &current->mm->mmap_sem but NOT any spinlocks.
139  */
140 static int get_futex_key(unsigned long uaddr, union futex_key *key)
141 {
142         struct mm_struct *mm = current->mm;
143         struct vm_area_struct *vma;
144         struct page *page;
145         int err;
146
147         /*
148          * The futex address must be "naturally" aligned.
149          */
150         key->both.offset = uaddr % PAGE_SIZE;
151         if (unlikely((key->both.offset % sizeof(u32)) != 0))
152                 return -EINVAL;
153         uaddr -= key->both.offset;
154
155         /*
156          * The futex is hashed differently depending on whether
157          * it's in a shared or private mapping.  So check vma first.
158          */
159         vma = find_extend_vma(mm, uaddr);
160         if (unlikely(!vma))
161                 return -EFAULT;
162
163         /*
164          * Permissions.
165          */
166         if (unlikely((vma->vm_flags & (VM_IO|VM_READ)) != VM_READ))
167                 return (vma->vm_flags & VM_IO) ? -EPERM : -EACCES;
168
169         /*
170          * Private mappings are handled in a simple way.
171          *
172          * NOTE: When userspace waits on a MAP_SHARED mapping, even if
173          * it's a read-only handle, it's expected that futexes attach to
174          * the object not the particular process.  Therefore we use
175          * VM_MAYSHARE here, not VM_SHARED which is restricted to shared
176          * mappings of _writable_ handles.
177          */
178         if (likely(!(vma->vm_flags & VM_MAYSHARE))) {
179                 key->private.mm = mm;
180                 key->private.uaddr = uaddr;
181                 return 0;
182         }
183
184         /*
185          * Linear file mappings are also simple.
186          */
187         key->shared.inode = vma->vm_file->f_dentry->d_inode;
188         key->both.offset++; /* Bit 0 of offset indicates inode-based key. */
189         if (likely(!(vma->vm_flags & VM_NONLINEAR))) {
190                 key->shared.pgoff = (((uaddr - vma->vm_start) >> PAGE_SHIFT)
191                                      + vma->vm_pgoff);
192                 return 0;
193         }
194
195         /*
196          * We could walk the page table to read the non-linear
197          * pte, and get the page index without fetching the page
198          * from swap.  But that's a lot of code to duplicate here
199          * for a rare case, so we simply fetch the page.
200          */
201
202         /*
203          * Do a quick atomic lookup first - this is the fastpath.
204          */
205         spin_lock(&current->mm->page_table_lock);
206         page = follow_page(mm, uaddr, 0);
207         if (likely(page != NULL)) {
208                 key->shared.pgoff =
209                         page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
210                 spin_unlock(&current->mm->page_table_lock);
211                 return 0;
212         }
213         spin_unlock(&current->mm->page_table_lock);
214
215         /*
216          * Do it the general way.
217          */
218         err = get_user_pages(current, mm, uaddr, 1, 0, 0, &page, NULL);
219         if (err >= 0) {
220                 key->shared.pgoff =
221                         page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
222                 put_page(page);
223                 return 0;
224         }
225         return err;
226 }
227
228 /*
229  * Take a reference to the resource addressed by a key.
230  * Can be called while holding spinlocks.
231  *
232  * NOTE: mmap_sem MUST be held between get_futex_key() and calling this
233  * function, if it is called at all.  mmap_sem keeps key->shared.inode valid.
234  */
235 static inline void get_key_refs(union futex_key *key)
236 {
237         if (key->both.ptr != 0) {
238                 if (key->both.offset & 1)
239                         atomic_inc(&key->shared.inode->i_count);
240                 else
241                         atomic_inc(&key->private.mm->mm_count);
242         }
243 }
244
245 /*
246  * Drop a reference to the resource addressed by a key.
247  * The hash bucket spinlock must not be held.
248  */
249 static void drop_key_refs(union futex_key *key)
250 {
251         if (key->both.ptr != 0) {
252                 if (key->both.offset & 1)
253                         iput(key->shared.inode);
254                 else
255                         mmdrop(key->private.mm);
256         }
257 }
258
259 /*
260  * The hash bucket lock must be held when this is called.
261  * Afterwards, the futex_q must not be accessed.
262  */
263 static void wake_futex(struct futex_q *q)
264 {
265         list_del_init(&q->list);
266         if (q->filp)
267                 send_sigio(&q->filp->f_owner, q->fd, POLL_IN);
268         /*
269          * The lock in wake_up_all() is a crucial memory barrier after the
270          * list_del_init() and also before assigning to q->lock_ptr.
271          */
272         wake_up_all(&q->waiters);
273         /*
274          * The waiting task can free the futex_q as soon as this is written,
275          * without taking any locks.  This must come last.
276          */
277         q->lock_ptr = 0;
278 }
279
280 /*
281  * Wake up all waiters hashed on the physical page that is mapped
282  * to this virtual address:
283  */
284 static int futex_wake(unsigned long uaddr, int nr_wake)
285 {
286         union futex_key key;
287         struct futex_hash_bucket *bh;
288         struct list_head *head;
289         struct futex_q *this, *next;
290         int ret;
291
292         down_read(&current->mm->mmap_sem);
293
294         ret = get_futex_key(uaddr, &key);
295         if (unlikely(ret != 0))
296                 goto out;
297
298         bh = hash_futex(&key);
299         spin_lock(&bh->lock);
300         head = &bh->chain;
301
302         list_for_each_entry_safe(this, next, head, list) {
303                 if (match_futex (&this->key, &key)) {
304                         wake_futex(this);
305                         if (++ret >= nr_wake)
306                                 break;
307                 }
308         }
309
310         spin_unlock(&bh->lock);
311 out:
312         up_read(&current->mm->mmap_sem);
313         return ret;
314 }
315
316 /*
317  * Requeue all waiters hashed on one physical page to another
318  * physical page.
319  */
320 static int futex_requeue(unsigned long uaddr1, unsigned long uaddr2,
321                                 int nr_wake, int nr_requeue)
322 {
323         union futex_key key1, key2;
324         struct futex_hash_bucket *bh1, *bh2;
325         struct list_head *head1;
326         struct futex_q *this, *next;
327         int ret, drop_count = 0;
328
329         down_read(&current->mm->mmap_sem);
330
331         ret = get_futex_key(uaddr1, &key1);
332         if (unlikely(ret != 0))
333                 goto out;
334         ret = get_futex_key(uaddr2, &key2);
335         if (unlikely(ret != 0))
336                 goto out;
337
338         bh1 = hash_futex(&key1);
339         bh2 = hash_futex(&key2);
340
341         if (bh1 < bh2)
342                 spin_lock(&bh1->lock);
343         spin_lock(&bh2->lock);
344         if (bh1 > bh2)
345                 spin_lock(&bh1->lock);
346
347         head1 = &bh1->chain;
348         list_for_each_entry_safe(this, next, head1, list) {
349                 if (!match_futex (&this->key, &key1))
350                         continue;
351                 if (++ret <= nr_wake) {
352                         wake_futex(this);
353                 } else {
354                         list_move_tail(&this->list, &bh2->chain);
355                         this->lock_ptr = &bh2->lock;
356                         this->key = key2;
357                         get_key_refs(&key2);
358                         drop_count++;
359
360                         if (ret - nr_wake >= nr_requeue)
361                                 break;
362                         /* Make sure to stop if key1 == key2 */
363                         if (head1 == &bh2->chain && head1 != &next->list)
364                                 head1 = &this->list;
365                 }
366         }
367
368         spin_unlock(&bh1->lock);
369         if (bh1 != bh2)
370                 spin_unlock(&bh2->lock);
371
372         /* drop_key_refs() must be called outside the spinlocks. */
373         while (--drop_count >= 0)
374                 drop_key_refs(&key1);
375
376 out:
377         up_read(&current->mm->mmap_sem);
378         return ret;
379 }
380
381 /*
382  * queue_me and unqueue_me must be called as a pair, each
383  * exactly once.  They are called with the hashed spinlock held.
384  */
385
386 /* The key must be already stored in q->key. */
387 static void queue_me(struct futex_q *q, int fd, struct file *filp)
388 {
389         struct futex_hash_bucket *bh;
390
391         q->fd = fd;
392         q->filp = filp;
393
394         init_waitqueue_head(&q->waiters);
395
396         get_key_refs(&q->key);
397         bh = hash_futex(&q->key);
398         q->lock_ptr = &bh->lock;
399
400         spin_lock(&bh->lock);
401         list_add_tail(&q->list, &bh->chain);
402         spin_unlock(&bh->lock);
403 }
404
405 /* Return 1 if we were still queued (ie. 0 means we were woken) */
406 static int unqueue_me(struct futex_q *q)
407 {
408         int ret = 0;
409         spinlock_t *lock_ptr;
410
411         /* In the common case we don't take the spinlock, which is nice. */
412  retry:
413         lock_ptr = q->lock_ptr;
414         if (lock_ptr != 0) {
415                 spin_lock(lock_ptr);
416                 /*
417                  * q->lock_ptr can change between reading it and
418                  * spin_lock(), causing us to take the wrong lock.  This
419                  * corrects the race condition.
420                  *
421                  * Reasoning goes like this: if we have the wrong lock,
422                  * q->lock_ptr must have changed (maybe several times)
423                  * between reading it and the spin_lock().  It can
424                  * change again after the spin_lock() but only if it was
425                  * already changed before the spin_lock().  It cannot,
426                  * however, change back to the original value.  Therefore
427                  * we can detect whether we acquired the correct lock.
428                  */
429                 if (unlikely(lock_ptr != q->lock_ptr)) {
430                         spin_unlock(lock_ptr);
431                         goto retry;
432                 }
433                 WARN_ON(list_empty(&q->list));
434                 list_del(&q->list);
435                 spin_unlock(lock_ptr);
436                 ret = 1;
437         }
438
439         drop_key_refs(&q->key);
440         return ret;
441 }
442
443 static int futex_wait(unsigned long uaddr, int val, unsigned long time)
444 {
445         DECLARE_WAITQUEUE(wait, current);
446         int ret, curval;
447         struct futex_q q;
448
449         down_read(&current->mm->mmap_sem);
450
451         ret = get_futex_key(uaddr, &q.key);
452         if (unlikely(ret != 0))
453                 goto out_release_sem;
454
455         queue_me(&q, -1, NULL);
456
457         /*
458          * Access the page after the futex is queued.
459          * We hold the mmap semaphore, so the mapping cannot have changed
460          * since we looked it up.
461          */
462         if (get_user(curval, (int *)uaddr) != 0) {
463                 ret = -EFAULT;
464                 goto out_unqueue;
465         }
466         if (curval != val) {
467                 ret = -EWOULDBLOCK;
468                 goto out_unqueue;
469         }
470
471         /*
472          * Now the futex is queued and we have checked the data, we
473          * don't want to hold mmap_sem while we sleep.
474          */     
475         up_read(&current->mm->mmap_sem);
476
477         /*
478          * There might have been scheduling since the queue_me(), as we
479          * cannot hold a spinlock across the get_user() in case it
480          * faults, and we cannot just set TASK_INTERRUPTIBLE state when
481          * queueing ourselves into the futex hash.  This code thus has to
482          * rely on the futex_wake() code removing us from hash when it
483          * wakes us up.
484          */
485
486         /* add_wait_queue is the barrier after __set_current_state. */
487         __set_current_state(TASK_INTERRUPTIBLE);
488         add_wait_queue(&q.waiters, &wait);
489         /*
490          * !list_empty() is safe here without any lock.
491          * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
492          */
493         if (likely(!list_empty(&q.list)))
494                 time = schedule_timeout(time);
495         __set_current_state(TASK_RUNNING);
496
497         /*
498          * NOTE: we don't remove ourselves from the waitqueue because
499          * we are the only user of it.
500          */
501
502         /* If we were woken (and unqueued), we succeeded, whatever. */
503         if (!unqueue_me(&q))
504                 return 0;
505         if (time == 0)
506                 return -ETIMEDOUT;
507         /* A spurious wakeup should never happen. */
508         WARN_ON(!signal_pending(current));
509         return -EINTR;
510
511  out_unqueue:
512         /* If we were woken (and unqueued), we succeeded, whatever. */
513         if (!unqueue_me(&q))
514                 ret = 0;
515  out_release_sem:
516         up_read(&current->mm->mmap_sem);
517         return ret;
518 }
519
520 static int futex_close(struct inode *inode, struct file *filp)
521 {
522         struct futex_q *q = filp->private_data;
523
524         unqueue_me(q);
525         kfree(q);
526         return 0;
527 }
528
529 /* This is one-shot: once it's gone off you need a new fd */
530 static unsigned int futex_poll(struct file *filp,
531                                struct poll_table_struct *wait)
532 {
533         struct futex_q *q = filp->private_data;
534         int ret = 0;
535
536         poll_wait(filp, &q->waiters, wait);
537
538         /*
539          * list_empty() is safe here without any lock.
540          * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
541          */
542         if (list_empty(&q->list))
543                 ret = POLLIN | POLLRDNORM;
544
545         return ret;
546 }
547
548 static struct file_operations futex_fops = {
549         .release        = futex_close,
550         .poll           = futex_poll,
551 };
552
553 /*
554  * Signal allows caller to avoid the race which would occur if they
555  * set the sigio stuff up afterwards.
556  */
557 static int futex_fd(unsigned long uaddr, int signal)
558 {
559         struct futex_q *q;
560         struct file *filp;
561         int ret, err;
562
563         ret = -EINVAL;
564         if (signal < 0 || signal > _NSIG)
565                 goto out;
566
567         ret = get_unused_fd();
568         if (ret < 0)
569                 goto out;
570         filp = get_empty_filp();
571         if (!filp) {
572                 put_unused_fd(ret);
573                 ret = -ENFILE;
574                 goto out;
575         }
576         filp->f_op = &futex_fops;
577         filp->f_vfsmnt = mntget(futex_mnt);
578         filp->f_dentry = dget(futex_mnt->mnt_root);
579         filp->f_mapping = filp->f_dentry->d_inode->i_mapping;
580
581         if (signal) {
582                 int err;
583                 err = f_setown(filp, current->pid, 1);
584                 if (err < 0) {
585                         put_unused_fd(ret);
586                         put_filp(filp);
587                         ret = err;
588                         goto out;
589                 }
590                 filp->f_owner.signum = signal;
591         }
592
593         q = kmalloc(sizeof(*q), GFP_KERNEL);
594         if (!q) {
595                 put_unused_fd(ret);
596                 put_filp(filp);
597                 ret = -ENOMEM;
598                 goto out;
599         }
600
601         down_read(&current->mm->mmap_sem);
602         err = get_futex_key(uaddr, &q->key);
603
604         if (unlikely(err != 0)) {
605                 up_read(&current->mm->mmap_sem);
606                 put_unused_fd(ret);
607                 put_filp(filp);
608                 kfree(q);
609                 return err;
610         }
611
612         /*
613          * queue_me() must be called before releasing mmap_sem, because
614          * key->shared.inode needs to be referenced while holding it.
615          */
616         filp->private_data = q;
617
618         queue_me(q, ret, filp);
619         up_read(&current->mm->mmap_sem);
620
621         /* Now we map fd to filp, so userspace can access it */
622         fd_install(ret, filp);
623 out:
624         return ret;
625 }
626
627 long do_futex(unsigned long uaddr, int op, int val, unsigned long timeout,
628                 unsigned long uaddr2, int val2)
629 {
630         int ret;
631
632         switch (op) {
633         case FUTEX_WAIT:
634                 ret = futex_wait(uaddr, val, timeout);
635                 break;
636         case FUTEX_WAKE:
637                 ret = futex_wake(uaddr, val);
638                 break;
639         case FUTEX_FD:
640                 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
641                 ret = futex_fd(uaddr, val);
642                 break;
643         case FUTEX_REQUEUE:
644                 ret = futex_requeue(uaddr, uaddr2, val, val2);
645                 break;
646         default:
647                 ret = -ENOSYS;
648         }
649         return ret;
650 }
651
652
653 asmlinkage long sys_futex(u32 __user *uaddr, int op, int val,
654                           struct timespec __user *utime, u32 __user *uaddr2)
655 {
656         struct timespec t;
657         unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
658         int val2 = 0;
659
660         if ((op == FUTEX_WAIT) && utime) {
661                 if (copy_from_user(&t, utime, sizeof(t)) != 0)
662                         return -EFAULT;
663                 timeout = timespec_to_jiffies(&t) + 1;
664         }
665         /*
666          * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
667          */
668         if (op == FUTEX_REQUEUE)
669                 val2 = (int) (long) utime;
670
671         return do_futex((unsigned long)uaddr, op, val, timeout,
672                         (unsigned long)uaddr2, val2);
673 }
674
675 static struct super_block *
676 futexfs_get_sb(struct file_system_type *fs_type,
677                int flags, const char *dev_name, void *data)
678 {
679         return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA);
680 }
681
682 static struct file_system_type futex_fs_type = {
683         .name           = "futexfs",
684         .get_sb         = futexfs_get_sb,
685         .kill_sb        = kill_anon_super,
686 };
687
688 static int __init init(void)
689 {
690         unsigned int i;
691
692         register_filesystem(&futex_fs_type);
693         futex_mnt = kern_mount(&futex_fs_type);
694
695         for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
696                 INIT_LIST_HEAD(&futex_queues[i].chain);
697                 futex_queues[i].lock = SPIN_LOCK_UNLOCKED;
698         }
699         return 0;
700 }
701 __initcall(init);