initial commit with v2.6.9
[linux-2.6.9-moxart.git] / kernel / futex.c
blob9a25d76bd6bd9aa13b9f74be1c0778ffe99c6039
1 /*
2 * Fast Userspace Mutexes (which I call "Futexes!").
3 * (C) Rusty Russell, IBM 2002
5 * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
6 * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
8 * Removed page pinning, fix privately mapped COW pages and other cleanups
9 * (C) Copyright 2003 Jamie Lokier
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.
15 * "The futexes are also cursed."
16 * "But they come in a choice of three flavours!"
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.
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.
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
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 #include <linux/syscalls.h>
43 #define FUTEX_HASHBITS 8
46 * Futexes are matched on equal values of this key.
47 * The key type depends on whether it's a shared or private mapping.
48 * Don't rearrange members without looking at hash_futex().
50 * offset is aligned to a multiple of sizeof(u32) (== 4) by definition.
51 * We set bit 0 to indicate if it's an inode-based key.
53 union futex_key {
54 struct {
55 unsigned long pgoff;
56 struct inode *inode;
57 int offset;
58 } shared;
59 struct {
60 unsigned long uaddr;
61 struct mm_struct *mm;
62 int offset;
63 } private;
64 struct {
65 unsigned long word;
66 void *ptr;
67 int offset;
68 } both;
72 * We use this hashed waitqueue instead of a normal wait_queue_t, so
73 * we can wake only the relevant ones (hashed queues may be shared).
75 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
76 * It is considered woken when list_empty(&q->list) || q->lock_ptr == 0.
77 * The order of wakup is always to make the first condition true, then
78 * wake up q->waiters, then make the second condition true.
80 struct futex_q {
81 struct list_head list;
82 wait_queue_head_t waiters;
84 /* Which hash list lock to use. */
85 spinlock_t *lock_ptr;
87 /* Key which the futex is hashed on. */
88 union futex_key key;
90 /* For fd, sigio sent using these. */
91 int fd;
92 struct file *filp;
96 * Split the global futex_lock into every hash list lock.
98 struct futex_hash_bucket {
99 spinlock_t lock;
100 unsigned int nqueued;
101 struct list_head chain;
104 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
106 /* Futex-fs vfsmount entry: */
107 static struct vfsmount *futex_mnt;
110 * We hash on the keys returned from get_futex_key (see below).
112 static struct futex_hash_bucket *hash_futex(union futex_key *key)
114 u32 hash = jhash2((u32*)&key->both.word,
115 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
116 key->both.offset);
117 return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
121 * Return 1 if two futex_keys are equal, 0 otherwise.
123 static inline int match_futex(union futex_key *key1, union futex_key *key2)
125 return (key1->both.word == key2->both.word
126 && key1->both.ptr == key2->both.ptr
127 && key1->both.offset == key2->both.offset);
131 * Get parameters which are the keys for a futex.
133 * For shared mappings, it's (page->index, vma->vm_file->f_dentry->d_inode,
134 * offset_within_page). For private mappings, it's (uaddr, current->mm).
135 * We can usually work out the index without swapping in the page.
137 * Returns: 0, or negative error code.
138 * The key words are stored in *key on success.
140 * Should be called with &current->mm->mmap_sem but NOT any spinlocks.
142 static int get_futex_key(unsigned long uaddr, union futex_key *key)
144 struct mm_struct *mm = current->mm;
145 struct vm_area_struct *vma;
146 struct page *page;
147 int err;
150 * The futex address must be "naturally" aligned.
152 key->both.offset = uaddr % PAGE_SIZE;
153 if (unlikely((key->both.offset % sizeof(u32)) != 0))
154 return -EINVAL;
155 uaddr -= key->both.offset;
158 * The futex is hashed differently depending on whether
159 * it's in a shared or private mapping. So check vma first.
161 vma = find_extend_vma(mm, uaddr);
162 if (unlikely(!vma))
163 return -EFAULT;
166 * Permissions.
168 if (unlikely((vma->vm_flags & (VM_IO|VM_READ)) != VM_READ))
169 return (vma->vm_flags & VM_IO) ? -EPERM : -EACCES;
172 * Private mappings are handled in a simple way.
174 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
175 * it's a read-only handle, it's expected that futexes attach to
176 * the object not the particular process. Therefore we use
177 * VM_MAYSHARE here, not VM_SHARED which is restricted to shared
178 * mappings of _writable_ handles.
180 if (likely(!(vma->vm_flags & VM_MAYSHARE))) {
181 key->private.mm = mm;
182 key->private.uaddr = uaddr;
183 return 0;
187 * Linear file mappings are also simple.
189 key->shared.inode = vma->vm_file->f_dentry->d_inode;
190 key->both.offset++; /* Bit 0 of offset indicates inode-based key. */
191 if (likely(!(vma->vm_flags & VM_NONLINEAR))) {
192 key->shared.pgoff = (((uaddr - vma->vm_start) >> PAGE_SHIFT)
193 + vma->vm_pgoff);
194 return 0;
198 * We could walk the page table to read the non-linear
199 * pte, and get the page index without fetching the page
200 * from swap. But that's a lot of code to duplicate here
201 * for a rare case, so we simply fetch the page.
205 * Do a quick atomic lookup first - this is the fastpath.
207 spin_lock(&current->mm->page_table_lock);
208 page = follow_page(mm, uaddr, 0);
209 if (likely(page != NULL)) {
210 key->shared.pgoff =
211 page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
212 spin_unlock(&current->mm->page_table_lock);
213 return 0;
215 spin_unlock(&current->mm->page_table_lock);
218 * Do it the general way.
220 err = get_user_pages(current, mm, uaddr, 1, 0, 0, &page, NULL);
221 if (err >= 0) {
222 key->shared.pgoff =
223 page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
224 put_page(page);
225 return 0;
227 return err;
231 * Take a reference to the resource addressed by a key.
232 * Can be called while holding spinlocks.
234 * NOTE: mmap_sem MUST be held between get_futex_key() and calling this
235 * function, if it is called at all. mmap_sem keeps key->shared.inode valid.
237 static inline void get_key_refs(union futex_key *key)
239 if (key->both.ptr != 0) {
240 if (key->both.offset & 1)
241 atomic_inc(&key->shared.inode->i_count);
242 else
243 atomic_inc(&key->private.mm->mm_count);
248 * Drop a reference to the resource addressed by a key.
249 * The hash bucket spinlock must not be held.
251 static void drop_key_refs(union futex_key *key)
253 if (key->both.ptr != 0) {
254 if (key->both.offset & 1)
255 iput(key->shared.inode);
256 else
257 mmdrop(key->private.mm);
262 * The hash bucket lock must be held when this is called.
263 * Afterwards, the futex_q must not be accessed.
265 static void wake_futex(struct futex_q *q)
267 list_del_init(&q->list);
268 if (q->filp)
269 send_sigio(&q->filp->f_owner, q->fd, POLL_IN);
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.
274 wake_up_all(&q->waiters);
276 * The waiting task can free the futex_q as soon as this is written,
277 * without taking any locks. This must come last.
279 q->lock_ptr = NULL;
283 * Wake up all waiters hashed on the physical page that is mapped
284 * to this virtual address:
286 static int futex_wake(unsigned long uaddr, int nr_wake)
288 union futex_key key;
289 struct futex_hash_bucket *bh;
290 struct list_head *head;
291 struct futex_q *this, *next;
292 int ret;
294 down_read(&current->mm->mmap_sem);
296 ret = get_futex_key(uaddr, &key);
297 if (unlikely(ret != 0))
298 goto out;
300 bh = hash_futex(&key);
301 spin_lock(&bh->lock);
302 head = &bh->chain;
304 list_for_each_entry_safe(this, next, head, list) {
305 if (match_futex (&this->key, &key)) {
306 wake_futex(this);
307 if (++ret >= nr_wake)
308 break;
312 spin_unlock(&bh->lock);
313 out:
314 up_read(&current->mm->mmap_sem);
315 return ret;
319 * Requeue all waiters hashed on one physical page to another
320 * physical page.
322 static int futex_requeue(unsigned long uaddr1, unsigned long uaddr2,
323 int nr_wake, int nr_requeue, int *valp)
325 union futex_key key1, key2;
326 struct futex_hash_bucket *bh1, *bh2;
327 struct list_head *head1;
328 struct futex_q *this, *next;
329 int ret, drop_count = 0;
330 unsigned int nqueued;
332 down_read(&current->mm->mmap_sem);
334 ret = get_futex_key(uaddr1, &key1);
335 if (unlikely(ret != 0))
336 goto out;
337 ret = get_futex_key(uaddr2, &key2);
338 if (unlikely(ret != 0))
339 goto out;
341 bh1 = hash_futex(&key1);
342 bh2 = hash_futex(&key2);
344 nqueued = bh1->nqueued;
345 if (likely(valp != NULL)) {
346 int curval;
348 /* In order to avoid doing get_user while
349 holding bh1->lock and bh2->lock, nqueued
350 (monotonically increasing field) must be first
351 read, then *uaddr1 fetched from userland and
352 after acquiring lock nqueued field compared with
353 the stored value. The smp_mb () below
354 makes sure that bh1->nqueued is read from memory
355 before *uaddr1. */
356 smp_mb();
358 if (get_user(curval, (int __user *)uaddr1) != 0) {
359 ret = -EFAULT;
360 goto out;
362 if (curval != *valp) {
363 ret = -EAGAIN;
364 goto out;
368 if (bh1 < bh2)
369 spin_lock(&bh1->lock);
370 spin_lock(&bh2->lock);
371 if (bh1 > bh2)
372 spin_lock(&bh1->lock);
374 if (unlikely(nqueued != bh1->nqueued && valp != NULL)) {
375 ret = -EAGAIN;
376 goto out_unlock;
379 head1 = &bh1->chain;
380 list_for_each_entry_safe(this, next, head1, list) {
381 if (!match_futex (&this->key, &key1))
382 continue;
383 if (++ret <= nr_wake) {
384 wake_futex(this);
385 } else {
386 list_move_tail(&this->list, &bh2->chain);
387 this->lock_ptr = &bh2->lock;
388 this->key = key2;
389 get_key_refs(&key2);
390 drop_count++;
392 if (ret - nr_wake >= nr_requeue)
393 break;
394 /* Make sure to stop if key1 == key2 */
395 if (head1 == &bh2->chain && head1 != &next->list)
396 head1 = &this->list;
400 out_unlock:
401 spin_unlock(&bh1->lock);
402 if (bh1 != bh2)
403 spin_unlock(&bh2->lock);
405 /* drop_key_refs() must be called outside the spinlocks. */
406 while (--drop_count >= 0)
407 drop_key_refs(&key1);
409 out:
410 up_read(&current->mm->mmap_sem);
411 return ret;
415 * queue_me and unqueue_me must be called as a pair, each
416 * exactly once. They are called with the hashed spinlock held.
419 /* The key must be already stored in q->key. */
420 static void queue_me(struct futex_q *q, int fd, struct file *filp)
422 struct futex_hash_bucket *bh;
424 q->fd = fd;
425 q->filp = filp;
427 init_waitqueue_head(&q->waiters);
429 get_key_refs(&q->key);
430 bh = hash_futex(&q->key);
431 q->lock_ptr = &bh->lock;
433 spin_lock(&bh->lock);
434 bh->nqueued++;
435 list_add_tail(&q->list, &bh->chain);
436 spin_unlock(&bh->lock);
439 /* Return 1 if we were still queued (ie. 0 means we were woken) */
440 static int unqueue_me(struct futex_q *q)
442 int ret = 0;
443 spinlock_t *lock_ptr;
445 /* In the common case we don't take the spinlock, which is nice. */
446 retry:
447 lock_ptr = q->lock_ptr;
448 if (lock_ptr != 0) {
449 spin_lock(lock_ptr);
451 * q->lock_ptr can change between reading it and
452 * spin_lock(), causing us to take the wrong lock. This
453 * corrects the race condition.
455 * Reasoning goes like this: if we have the wrong lock,
456 * q->lock_ptr must have changed (maybe several times)
457 * between reading it and the spin_lock(). It can
458 * change again after the spin_lock() but only if it was
459 * already changed before the spin_lock(). It cannot,
460 * however, change back to the original value. Therefore
461 * we can detect whether we acquired the correct lock.
463 if (unlikely(lock_ptr != q->lock_ptr)) {
464 spin_unlock(lock_ptr);
465 goto retry;
467 WARN_ON(list_empty(&q->list));
468 list_del(&q->list);
469 spin_unlock(lock_ptr);
470 ret = 1;
473 drop_key_refs(&q->key);
474 return ret;
477 static int futex_wait(unsigned long uaddr, int val, unsigned long time)
479 DECLARE_WAITQUEUE(wait, current);
480 int ret, curval;
481 struct futex_q q;
483 down_read(&current->mm->mmap_sem);
485 ret = get_futex_key(uaddr, &q.key);
486 if (unlikely(ret != 0))
487 goto out_release_sem;
489 queue_me(&q, -1, NULL);
492 * Access the page after the futex is queued.
493 * We hold the mmap semaphore, so the mapping cannot have changed
494 * since we looked it up.
496 if (get_user(curval, (int __user *)uaddr) != 0) {
497 ret = -EFAULT;
498 goto out_unqueue;
500 if (curval != val) {
501 ret = -EWOULDBLOCK;
502 goto out_unqueue;
506 * Now the futex is queued and we have checked the data, we
507 * don't want to hold mmap_sem while we sleep.
509 up_read(&current->mm->mmap_sem);
512 * There might have been scheduling since the queue_me(), as we
513 * cannot hold a spinlock across the get_user() in case it
514 * faults, and we cannot just set TASK_INTERRUPTIBLE state when
515 * queueing ourselves into the futex hash. This code thus has to
516 * rely on the futex_wake() code removing us from hash when it
517 * wakes us up.
520 /* add_wait_queue is the barrier after __set_current_state. */
521 __set_current_state(TASK_INTERRUPTIBLE);
522 add_wait_queue(&q.waiters, &wait);
524 * !list_empty() is safe here without any lock.
525 * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
527 if (likely(!list_empty(&q.list)))
528 time = schedule_timeout(time);
529 __set_current_state(TASK_RUNNING);
532 * NOTE: we don't remove ourselves from the waitqueue because
533 * we are the only user of it.
536 /* If we were woken (and unqueued), we succeeded, whatever. */
537 if (!unqueue_me(&q))
538 return 0;
539 if (time == 0)
540 return -ETIMEDOUT;
541 /* A spurious wakeup should never happen. */
542 WARN_ON(!signal_pending(current));
543 return -EINTR;
545 out_unqueue:
546 /* If we were woken (and unqueued), we succeeded, whatever. */
547 if (!unqueue_me(&q))
548 ret = 0;
549 out_release_sem:
550 up_read(&current->mm->mmap_sem);
551 return ret;
554 static int futex_close(struct inode *inode, struct file *filp)
556 struct futex_q *q = filp->private_data;
558 unqueue_me(q);
559 kfree(q);
560 return 0;
563 /* This is one-shot: once it's gone off you need a new fd */
564 static unsigned int futex_poll(struct file *filp,
565 struct poll_table_struct *wait)
567 struct futex_q *q = filp->private_data;
568 int ret = 0;
570 poll_wait(filp, &q->waiters, wait);
573 * list_empty() is safe here without any lock.
574 * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
576 if (list_empty(&q->list))
577 ret = POLLIN | POLLRDNORM;
579 return ret;
582 static struct file_operations futex_fops = {
583 .release = futex_close,
584 .poll = futex_poll,
588 * Signal allows caller to avoid the race which would occur if they
589 * set the sigio stuff up afterwards.
591 static int futex_fd(unsigned long uaddr, int signal)
593 struct futex_q *q;
594 struct file *filp;
595 int ret, err;
597 ret = -EINVAL;
598 if (signal < 0 || signal > _NSIG)
599 goto out;
601 ret = get_unused_fd();
602 if (ret < 0)
603 goto out;
604 filp = get_empty_filp();
605 if (!filp) {
606 put_unused_fd(ret);
607 ret = -ENFILE;
608 goto out;
610 filp->f_op = &futex_fops;
611 filp->f_vfsmnt = mntget(futex_mnt);
612 filp->f_dentry = dget(futex_mnt->mnt_root);
613 filp->f_mapping = filp->f_dentry->d_inode->i_mapping;
615 if (signal) {
616 int err;
617 err = f_setown(filp, current->pid, 1);
618 if (err < 0) {
619 put_unused_fd(ret);
620 put_filp(filp);
621 ret = err;
622 goto out;
624 filp->f_owner.signum = signal;
627 q = kmalloc(sizeof(*q), GFP_KERNEL);
628 if (!q) {
629 put_unused_fd(ret);
630 put_filp(filp);
631 ret = -ENOMEM;
632 goto out;
635 down_read(&current->mm->mmap_sem);
636 err = get_futex_key(uaddr, &q->key);
638 if (unlikely(err != 0)) {
639 up_read(&current->mm->mmap_sem);
640 put_unused_fd(ret);
641 put_filp(filp);
642 kfree(q);
643 return err;
647 * queue_me() must be called before releasing mmap_sem, because
648 * key->shared.inode needs to be referenced while holding it.
650 filp->private_data = q;
652 queue_me(q, ret, filp);
653 up_read(&current->mm->mmap_sem);
655 /* Now we map fd to filp, so userspace can access it */
656 fd_install(ret, filp);
657 out:
658 return ret;
661 long do_futex(unsigned long uaddr, int op, int val, unsigned long timeout,
662 unsigned long uaddr2, int val2, int val3)
664 int ret;
666 switch (op) {
667 case FUTEX_WAIT:
668 ret = futex_wait(uaddr, val, timeout);
669 break;
670 case FUTEX_WAKE:
671 ret = futex_wake(uaddr, val);
672 break;
673 case FUTEX_FD:
674 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
675 ret = futex_fd(uaddr, val);
676 break;
677 case FUTEX_REQUEUE:
678 ret = futex_requeue(uaddr, uaddr2, val, val2, NULL);
679 break;
680 case FUTEX_CMP_REQUEUE:
681 ret = futex_requeue(uaddr, uaddr2, val, val2, &val3);
682 break;
683 default:
684 ret = -ENOSYS;
686 return ret;
690 asmlinkage long sys_futex(u32 __user *uaddr, int op, int val,
691 struct timespec __user *utime, u32 __user *uaddr2,
692 int val3)
694 struct timespec t;
695 unsigned long timeout = MAX_SCHEDULE_TIMEOUT;
696 int val2 = 0;
698 if ((op == FUTEX_WAIT) && utime) {
699 if (copy_from_user(&t, utime, sizeof(t)) != 0)
700 return -EFAULT;
701 timeout = timespec_to_jiffies(&t) + 1;
704 * requeue parameter in 'utime' if op == FUTEX_REQUEUE.
706 if (op >= FUTEX_REQUEUE)
707 val2 = (int) (unsigned long) utime;
709 return do_futex((unsigned long)uaddr, op, val, timeout,
710 (unsigned long)uaddr2, val2, val3);
713 static struct super_block *
714 futexfs_get_sb(struct file_system_type *fs_type,
715 int flags, const char *dev_name, void *data)
717 return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA);
720 static struct file_system_type futex_fs_type = {
721 .name = "futexfs",
722 .get_sb = futexfs_get_sb,
723 .kill_sb = kill_anon_super,
726 static int __init init(void)
728 unsigned int i;
730 register_filesystem(&futex_fs_type);
731 futex_mnt = kern_mount(&futex_fs_type);
733 for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
734 INIT_LIST_HEAD(&futex_queues[i].chain);
735 futex_queues[i].lock = SPIN_LOCK_UNLOCKED;
737 return 0;
739 __initcall(init);