IPoIB/cm: Fix SRQ WR leak
[linux-2.6/verdex.git] / kernel / futex.c
blobb7ce15c67e324b468d13599d47df7423adcd69d4
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, 2004 Jamie Lokier
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.
15 * PI-futex support started by Ingo Molnar and Thomas Gleixner
16 * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
17 * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
19 * PRIVATE futexes by Eric Dumazet
20 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
22 * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
23 * enough at me, Linus for the original (flawed) idea, Matthew
24 * Kirkwood for proof-of-concept implementation.
26 * "The futexes are also cursed."
27 * "But they come in a choice of three flavours!"
29 * This program is free software; you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation; either version 2 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program; if not, write to the Free Software
41 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/fs.h>
46 #include <linux/file.h>
47 #include <linux/jhash.h>
48 #include <linux/init.h>
49 #include <linux/futex.h>
50 #include <linux/mount.h>
51 #include <linux/pagemap.h>
52 #include <linux/syscalls.h>
53 #include <linux/signal.h>
54 #include <linux/module.h>
55 #include <asm/futex.h>
57 #include "rtmutex_common.h"
59 #ifdef CONFIG_DEBUG_RT_MUTEXES
60 # include "rtmutex-debug.h"
61 #else
62 # include "rtmutex.h"
63 #endif
65 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
68 * Priority Inheritance state:
70 struct futex_pi_state {
72 * list of 'owned' pi_state instances - these have to be
73 * cleaned up in do_exit() if the task exits prematurely:
75 struct list_head list;
78 * The PI object:
80 struct rt_mutex pi_mutex;
82 struct task_struct *owner;
83 atomic_t refcount;
85 union futex_key key;
89 * We use this hashed waitqueue instead of a normal wait_queue_t, so
90 * we can wake only the relevant ones (hashed queues may be shared).
92 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
93 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
94 * The order of wakup is always to make the first condition true, then
95 * wake up q->waiters, then make the second condition true.
97 struct futex_q {
98 struct plist_node list;
99 wait_queue_head_t waiters;
101 /* Which hash list lock to use: */
102 spinlock_t *lock_ptr;
104 /* Key which the futex is hashed on: */
105 union futex_key key;
107 /* For fd, sigio sent using these: */
108 int fd;
109 struct file *filp;
111 /* Optional priority inheritance state: */
112 struct futex_pi_state *pi_state;
113 struct task_struct *task;
116 * This waiter is used in case of requeue from a
117 * normal futex to a PI-futex
119 struct rt_mutex_waiter waiter;
123 * Split the global futex_lock into every hash list lock.
125 struct futex_hash_bucket {
126 spinlock_t lock;
127 struct plist_head chain;
130 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
132 /* Futex-fs vfsmount entry: */
133 static struct vfsmount *futex_mnt;
136 * We hash on the keys returned from get_futex_key (see below).
138 static struct futex_hash_bucket *hash_futex(union futex_key *key)
140 u32 hash = jhash2((u32*)&key->both.word,
141 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
142 key->both.offset);
143 return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
147 * Return 1 if two futex_keys are equal, 0 otherwise.
149 static inline int match_futex(union futex_key *key1, union futex_key *key2)
151 return (key1->both.word == key2->both.word
152 && key1->both.ptr == key2->both.ptr
153 && key1->both.offset == key2->both.offset);
157 * get_futex_key - Get parameters which are the keys for a futex.
158 * @uaddr: virtual address of the futex
159 * @shared: NULL for a PROCESS_PRIVATE futex,
160 * &current->mm->mmap_sem for a PROCESS_SHARED futex
161 * @key: address where result is stored.
163 * Returns a negative error code or 0
164 * The key words are stored in *key on success.
166 * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
167 * offset_within_page). For private mappings, it's (uaddr, current->mm).
168 * We can usually work out the index without swapping in the page.
170 * fshared is NULL for PROCESS_PRIVATE futexes
171 * For other futexes, it points to &current->mm->mmap_sem and
172 * caller must have taken the reader lock. but NOT any spinlocks.
174 int get_futex_key(u32 __user *uaddr, struct rw_semaphore *fshared,
175 union futex_key *key)
177 unsigned long address = (unsigned long)uaddr;
178 struct mm_struct *mm = current->mm;
179 struct vm_area_struct *vma;
180 struct page *page;
181 int err;
184 * The futex address must be "naturally" aligned.
186 key->both.offset = address % PAGE_SIZE;
187 if (unlikely((address % sizeof(u32)) != 0))
188 return -EINVAL;
189 address -= key->both.offset;
192 * PROCESS_PRIVATE futexes are fast.
193 * As the mm cannot disappear under us and the 'key' only needs
194 * virtual address, we dont even have to find the underlying vma.
195 * Note : We do have to check 'uaddr' is a valid user address,
196 * but access_ok() should be faster than find_vma()
198 if (!fshared) {
199 if (unlikely(!access_ok(VERIFY_WRITE, uaddr, sizeof(u32))))
200 return -EFAULT;
201 key->private.mm = mm;
202 key->private.address = address;
203 return 0;
206 * The futex is hashed differently depending on whether
207 * it's in a shared or private mapping. So check vma first.
209 vma = find_extend_vma(mm, address);
210 if (unlikely(!vma))
211 return -EFAULT;
214 * Permissions.
216 if (unlikely((vma->vm_flags & (VM_IO|VM_READ)) != VM_READ))
217 return (vma->vm_flags & VM_IO) ? -EPERM : -EACCES;
219 /* Save the user address in the ley */
220 key->uaddr = uaddr;
223 * Private mappings are handled in a simple way.
225 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
226 * it's a read-only handle, it's expected that futexes attach to
227 * the object not the particular process. Therefore we use
228 * VM_MAYSHARE here, not VM_SHARED which is restricted to shared
229 * mappings of _writable_ handles.
231 if (likely(!(vma->vm_flags & VM_MAYSHARE))) {
232 key->both.offset |= FUT_OFF_MMSHARED; /* reference taken on mm */
233 key->private.mm = mm;
234 key->private.address = address;
235 return 0;
239 * Linear file mappings are also simple.
241 key->shared.inode = vma->vm_file->f_path.dentry->d_inode;
242 key->both.offset |= FUT_OFF_INODE; /* inode-based key. */
243 if (likely(!(vma->vm_flags & VM_NONLINEAR))) {
244 key->shared.pgoff = (((address - vma->vm_start) >> PAGE_SHIFT)
245 + vma->vm_pgoff);
246 return 0;
250 * We could walk the page table to read the non-linear
251 * pte, and get the page index without fetching the page
252 * from swap. But that's a lot of code to duplicate here
253 * for a rare case, so we simply fetch the page.
255 err = get_user_pages(current, mm, address, 1, 0, 0, &page, NULL);
256 if (err >= 0) {
257 key->shared.pgoff =
258 page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
259 put_page(page);
260 return 0;
262 return err;
264 EXPORT_SYMBOL_GPL(get_futex_key);
267 * Take a reference to the resource addressed by a key.
268 * Can be called while holding spinlocks.
271 inline void get_futex_key_refs(union futex_key *key)
273 if (key->both.ptr == 0)
274 return;
275 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
276 case FUT_OFF_INODE:
277 atomic_inc(&key->shared.inode->i_count);
278 break;
279 case FUT_OFF_MMSHARED:
280 atomic_inc(&key->private.mm->mm_count);
281 break;
284 EXPORT_SYMBOL_GPL(get_futex_key_refs);
287 * Drop a reference to the resource addressed by a key.
288 * The hash bucket spinlock must not be held.
290 void drop_futex_key_refs(union futex_key *key)
292 if (key->both.ptr == 0)
293 return;
294 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
295 case FUT_OFF_INODE:
296 iput(key->shared.inode);
297 break;
298 case FUT_OFF_MMSHARED:
299 mmdrop(key->private.mm);
300 break;
303 EXPORT_SYMBOL_GPL(drop_futex_key_refs);
305 static inline int get_futex_value_locked(u32 *dest, u32 __user *from)
307 int ret;
309 pagefault_disable();
310 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
311 pagefault_enable();
313 return ret ? -EFAULT : 0;
317 * Fault handling.
318 * if fshared is non NULL, current->mm->mmap_sem is already held
320 static int futex_handle_fault(unsigned long address,
321 struct rw_semaphore *fshared, int attempt)
323 struct vm_area_struct * vma;
324 struct mm_struct *mm = current->mm;
325 int ret = -EFAULT;
327 if (attempt > 2)
328 return ret;
330 if (!fshared)
331 down_read(&mm->mmap_sem);
332 vma = find_vma(mm, address);
333 if (vma && address >= vma->vm_start &&
334 (vma->vm_flags & VM_WRITE)) {
335 switch (handle_mm_fault(mm, vma, address, 1)) {
336 case VM_FAULT_MINOR:
337 ret = 0;
338 current->min_flt++;
339 break;
340 case VM_FAULT_MAJOR:
341 ret = 0;
342 current->maj_flt++;
343 break;
346 if (!fshared)
347 up_read(&mm->mmap_sem);
348 return ret;
352 * PI code:
354 static int refill_pi_state_cache(void)
356 struct futex_pi_state *pi_state;
358 if (likely(current->pi_state_cache))
359 return 0;
361 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
363 if (!pi_state)
364 return -ENOMEM;
366 INIT_LIST_HEAD(&pi_state->list);
367 /* pi_mutex gets initialized later */
368 pi_state->owner = NULL;
369 atomic_set(&pi_state->refcount, 1);
371 current->pi_state_cache = pi_state;
373 return 0;
376 static struct futex_pi_state * alloc_pi_state(void)
378 struct futex_pi_state *pi_state = current->pi_state_cache;
380 WARN_ON(!pi_state);
381 current->pi_state_cache = NULL;
383 return pi_state;
386 static void free_pi_state(struct futex_pi_state *pi_state)
388 if (!atomic_dec_and_test(&pi_state->refcount))
389 return;
392 * If pi_state->owner is NULL, the owner is most probably dying
393 * and has cleaned up the pi_state already
395 if (pi_state->owner) {
396 spin_lock_irq(&pi_state->owner->pi_lock);
397 list_del_init(&pi_state->list);
398 spin_unlock_irq(&pi_state->owner->pi_lock);
400 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
403 if (current->pi_state_cache)
404 kfree(pi_state);
405 else {
407 * pi_state->list is already empty.
408 * clear pi_state->owner.
409 * refcount is at 0 - put it back to 1.
411 pi_state->owner = NULL;
412 atomic_set(&pi_state->refcount, 1);
413 current->pi_state_cache = pi_state;
418 * Look up the task based on what TID userspace gave us.
419 * We dont trust it.
421 static struct task_struct * futex_find_get_task(pid_t pid)
423 struct task_struct *p;
425 rcu_read_lock();
426 p = find_task_by_pid(pid);
427 if (!p)
428 goto out_unlock;
429 if ((current->euid != p->euid) && (current->euid != p->uid)) {
430 p = NULL;
431 goto out_unlock;
433 if (p->exit_state != 0) {
434 p = NULL;
435 goto out_unlock;
437 get_task_struct(p);
438 out_unlock:
439 rcu_read_unlock();
441 return p;
445 * This task is holding PI mutexes at exit time => bad.
446 * Kernel cleans up PI-state, but userspace is likely hosed.
447 * (Robust-futex cleanup is separate and might save the day for userspace.)
449 void exit_pi_state_list(struct task_struct *curr)
451 struct list_head *next, *head = &curr->pi_state_list;
452 struct futex_pi_state *pi_state;
453 struct futex_hash_bucket *hb;
454 union futex_key key;
457 * We are a ZOMBIE and nobody can enqueue itself on
458 * pi_state_list anymore, but we have to be careful
459 * versus waiters unqueueing themselves:
461 spin_lock_irq(&curr->pi_lock);
462 while (!list_empty(head)) {
464 next = head->next;
465 pi_state = list_entry(next, struct futex_pi_state, list);
466 key = pi_state->key;
467 hb = hash_futex(&key);
468 spin_unlock_irq(&curr->pi_lock);
470 spin_lock(&hb->lock);
472 spin_lock_irq(&curr->pi_lock);
474 * We dropped the pi-lock, so re-check whether this
475 * task still owns the PI-state:
477 if (head->next != next) {
478 spin_unlock(&hb->lock);
479 continue;
482 WARN_ON(pi_state->owner != curr);
483 WARN_ON(list_empty(&pi_state->list));
484 list_del_init(&pi_state->list);
485 pi_state->owner = NULL;
486 spin_unlock_irq(&curr->pi_lock);
488 rt_mutex_unlock(&pi_state->pi_mutex);
490 spin_unlock(&hb->lock);
492 spin_lock_irq(&curr->pi_lock);
494 spin_unlock_irq(&curr->pi_lock);
497 static int
498 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
499 union futex_key *key, struct futex_pi_state **ps)
501 struct futex_pi_state *pi_state = NULL;
502 struct futex_q *this, *next;
503 struct plist_head *head;
504 struct task_struct *p;
505 pid_t pid;
507 head = &hb->chain;
509 plist_for_each_entry_safe(this, next, head, list) {
510 if (match_futex(&this->key, key)) {
512 * Another waiter already exists - bump up
513 * the refcount and return its pi_state:
515 pi_state = this->pi_state;
517 * Userspace might have messed up non PI and PI futexes
519 if (unlikely(!pi_state))
520 return -EINVAL;
522 WARN_ON(!atomic_read(&pi_state->refcount));
524 atomic_inc(&pi_state->refcount);
525 *ps = pi_state;
527 return 0;
532 * We are the first waiter - try to look up the real owner and attach
533 * the new pi_state to it, but bail out when the owner died bit is set
534 * and TID = 0:
536 pid = uval & FUTEX_TID_MASK;
537 if (!pid && (uval & FUTEX_OWNER_DIED))
538 return -ESRCH;
539 p = futex_find_get_task(pid);
540 if (!p)
541 return -ESRCH;
543 pi_state = alloc_pi_state();
546 * Initialize the pi_mutex in locked state and make 'p'
547 * the owner of it:
549 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
551 /* Store the key for possible exit cleanups: */
552 pi_state->key = *key;
554 spin_lock_irq(&p->pi_lock);
555 WARN_ON(!list_empty(&pi_state->list));
556 list_add(&pi_state->list, &p->pi_state_list);
557 pi_state->owner = p;
558 spin_unlock_irq(&p->pi_lock);
560 put_task_struct(p);
562 *ps = pi_state;
564 return 0;
568 * The hash bucket lock must be held when this is called.
569 * Afterwards, the futex_q must not be accessed.
571 static void wake_futex(struct futex_q *q)
573 plist_del(&q->list, &q->list.plist);
574 if (q->filp)
575 send_sigio(&q->filp->f_owner, q->fd, POLL_IN);
577 * The lock in wake_up_all() is a crucial memory barrier after the
578 * plist_del() and also before assigning to q->lock_ptr.
580 wake_up_all(&q->waiters);
582 * The waiting task can free the futex_q as soon as this is written,
583 * without taking any locks. This must come last.
585 * A memory barrier is required here to prevent the following store
586 * to lock_ptr from getting ahead of the wakeup. Clearing the lock
587 * at the end of wake_up_all() does not prevent this store from
588 * moving.
590 smp_wmb();
591 q->lock_ptr = NULL;
594 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
596 struct task_struct *new_owner;
597 struct futex_pi_state *pi_state = this->pi_state;
598 u32 curval, newval;
600 if (!pi_state)
601 return -EINVAL;
603 spin_lock(&pi_state->pi_mutex.wait_lock);
604 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
607 * This happens when we have stolen the lock and the original
608 * pending owner did not enqueue itself back on the rt_mutex.
609 * Thats not a tragedy. We know that way, that a lock waiter
610 * is on the fly. We make the futex_q waiter the pending owner.
612 if (!new_owner)
613 new_owner = this->task;
616 * We pass it to the next owner. (The WAITERS bit is always
617 * kept enabled while there is PI state around. We must also
618 * preserve the owner died bit.)
620 if (!(uval & FUTEX_OWNER_DIED)) {
621 newval = FUTEX_WAITERS | new_owner->pid;
622 /* Keep the FUTEX_WAITER_REQUEUED flag if it was set */
623 newval |= (uval & FUTEX_WAITER_REQUEUED);
625 pagefault_disable();
626 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
627 pagefault_enable();
628 if (curval == -EFAULT)
629 return -EFAULT;
630 if (curval != uval)
631 return -EINVAL;
634 spin_lock_irq(&pi_state->owner->pi_lock);
635 WARN_ON(list_empty(&pi_state->list));
636 list_del_init(&pi_state->list);
637 spin_unlock_irq(&pi_state->owner->pi_lock);
639 spin_lock_irq(&new_owner->pi_lock);
640 WARN_ON(!list_empty(&pi_state->list));
641 list_add(&pi_state->list, &new_owner->pi_state_list);
642 pi_state->owner = new_owner;
643 spin_unlock_irq(&new_owner->pi_lock);
645 spin_unlock(&pi_state->pi_mutex.wait_lock);
646 rt_mutex_unlock(&pi_state->pi_mutex);
648 return 0;
651 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
653 u32 oldval;
656 * There is no waiter, so we unlock the futex. The owner died
657 * bit has not to be preserved here. We are the owner:
659 pagefault_disable();
660 oldval = futex_atomic_cmpxchg_inatomic(uaddr, uval, 0);
661 pagefault_enable();
663 if (oldval == -EFAULT)
664 return oldval;
665 if (oldval != uval)
666 return -EAGAIN;
668 return 0;
672 * Express the locking dependencies for lockdep:
674 static inline void
675 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
677 if (hb1 <= hb2) {
678 spin_lock(&hb1->lock);
679 if (hb1 < hb2)
680 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
681 } else { /* hb1 > hb2 */
682 spin_lock(&hb2->lock);
683 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
688 * Wake up all waiters hashed on the physical page that is mapped
689 * to this virtual address:
691 static int futex_wake(u32 __user *uaddr, struct rw_semaphore *fshared,
692 int nr_wake)
694 struct futex_hash_bucket *hb;
695 struct futex_q *this, *next;
696 struct plist_head *head;
697 union futex_key key;
698 int ret;
700 if (fshared)
701 down_read(fshared);
703 ret = get_futex_key(uaddr, fshared, &key);
704 if (unlikely(ret != 0))
705 goto out;
707 hb = hash_futex(&key);
708 spin_lock(&hb->lock);
709 head = &hb->chain;
711 plist_for_each_entry_safe(this, next, head, list) {
712 if (match_futex (&this->key, &key)) {
713 if (this->pi_state) {
714 ret = -EINVAL;
715 break;
717 wake_futex(this);
718 if (++ret >= nr_wake)
719 break;
723 spin_unlock(&hb->lock);
724 out:
725 if (fshared)
726 up_read(fshared);
727 return ret;
731 * Called from futex_requeue_pi.
732 * Set FUTEX_WAITERS and FUTEX_WAITER_REQUEUED flags on the
733 * PI-futex value; search its associated pi_state if an owner exist
734 * or create a new one without owner.
736 static inline int
737 lookup_pi_state_for_requeue(u32 __user *uaddr, struct futex_hash_bucket *hb,
738 union futex_key *key,
739 struct futex_pi_state **pi_state)
741 u32 curval, uval, newval;
743 retry:
745 * We can't handle a fault cleanly because we can't
746 * release the locks here. Simply return the fault.
748 if (get_futex_value_locked(&curval, uaddr))
749 return -EFAULT;
751 /* set the flags FUTEX_WAITERS and FUTEX_WAITER_REQUEUED */
752 if ((curval & (FUTEX_WAITERS | FUTEX_WAITER_REQUEUED))
753 != (FUTEX_WAITERS | FUTEX_WAITER_REQUEUED)) {
755 * No waiters yet, we prepare the futex to have some waiters.
758 uval = curval;
759 newval = uval | FUTEX_WAITERS | FUTEX_WAITER_REQUEUED;
761 pagefault_disable();
762 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
763 pagefault_enable();
765 if (unlikely(curval == -EFAULT))
766 return -EFAULT;
767 if (unlikely(curval != uval))
768 goto retry;
771 if (!(curval & FUTEX_TID_MASK)
772 || lookup_pi_state(curval, hb, key, pi_state)) {
773 /* the futex has no owner (yet) or the lookup failed:
774 allocate one pi_state without owner */
776 *pi_state = alloc_pi_state();
778 /* Already stores the key: */
779 (*pi_state)->key = *key;
781 /* init the mutex without owner */
782 __rt_mutex_init(&(*pi_state)->pi_mutex, NULL);
785 return 0;
789 * Keep the first nr_wake waiter from futex1, wake up one,
790 * and requeue the next nr_requeue waiters following hashed on
791 * one physical page to another physical page (PI-futex uaddr2)
793 static int futex_requeue_pi(u32 __user *uaddr1,
794 struct rw_semaphore *fshared,
795 u32 __user *uaddr2,
796 int nr_wake, int nr_requeue, u32 *cmpval)
798 union futex_key key1, key2;
799 struct futex_hash_bucket *hb1, *hb2;
800 struct plist_head *head1;
801 struct futex_q *this, *next;
802 struct futex_pi_state *pi_state2 = NULL;
803 struct rt_mutex_waiter *waiter, *top_waiter = NULL;
804 struct rt_mutex *lock2 = NULL;
805 int ret, drop_count = 0;
807 if (refill_pi_state_cache())
808 return -ENOMEM;
810 retry:
812 * First take all the futex related locks:
814 if (fshared)
815 down_read(fshared);
817 ret = get_futex_key(uaddr1, fshared, &key1);
818 if (unlikely(ret != 0))
819 goto out;
820 ret = get_futex_key(uaddr2, fshared, &key2);
821 if (unlikely(ret != 0))
822 goto out;
824 hb1 = hash_futex(&key1);
825 hb2 = hash_futex(&key2);
827 double_lock_hb(hb1, hb2);
829 if (likely(cmpval != NULL)) {
830 u32 curval;
832 ret = get_futex_value_locked(&curval, uaddr1);
834 if (unlikely(ret)) {
835 spin_unlock(&hb1->lock);
836 if (hb1 != hb2)
837 spin_unlock(&hb2->lock);
840 * If we would have faulted, release mmap_sem, fault
841 * it in and start all over again.
843 if (fshared)
844 up_read(fshared);
846 ret = get_user(curval, uaddr1);
848 if (!ret)
849 goto retry;
851 return ret;
853 if (curval != *cmpval) {
854 ret = -EAGAIN;
855 goto out_unlock;
859 head1 = &hb1->chain;
860 plist_for_each_entry_safe(this, next, head1, list) {
861 if (!match_futex (&this->key, &key1))
862 continue;
863 if (++ret <= nr_wake) {
864 wake_futex(this);
865 } else {
867 * FIRST: get and set the pi_state
869 if (!pi_state2) {
870 int s;
871 /* do this only the first time we requeue someone */
872 s = lookup_pi_state_for_requeue(uaddr2, hb2,
873 &key2, &pi_state2);
874 if (s) {
875 ret = s;
876 goto out_unlock;
879 lock2 = &pi_state2->pi_mutex;
880 spin_lock(&lock2->wait_lock);
882 /* Save the top waiter of the wait_list */
883 if (rt_mutex_has_waiters(lock2))
884 top_waiter = rt_mutex_top_waiter(lock2);
885 } else
886 atomic_inc(&pi_state2->refcount);
889 this->pi_state = pi_state2;
892 * SECOND: requeue futex_q to the correct hashbucket
896 * If key1 and key2 hash to the same bucket, no need to
897 * requeue.
899 if (likely(head1 != &hb2->chain)) {
900 plist_del(&this->list, &hb1->chain);
901 plist_add(&this->list, &hb2->chain);
902 this->lock_ptr = &hb2->lock;
903 #ifdef CONFIG_DEBUG_PI_LIST
904 this->list.plist.lock = &hb2->lock;
905 #endif
907 this->key = key2;
908 get_futex_key_refs(&key2);
909 drop_count++;
913 * THIRD: queue it to lock2
915 spin_lock_irq(&this->task->pi_lock);
916 waiter = &this->waiter;
917 waiter->task = this->task;
918 waiter->lock = lock2;
919 plist_node_init(&waiter->list_entry, this->task->prio);
920 plist_node_init(&waiter->pi_list_entry, this->task->prio);
921 plist_add(&waiter->list_entry, &lock2->wait_list);
922 this->task->pi_blocked_on = waiter;
923 spin_unlock_irq(&this->task->pi_lock);
925 if (ret - nr_wake >= nr_requeue)
926 break;
930 /* If we've requeued some tasks and the top_waiter of the rt_mutex
931 has changed, we must adjust the priority of the owner, if any */
932 if (drop_count) {
933 struct task_struct *owner = rt_mutex_owner(lock2);
934 if (owner &&
935 (top_waiter != (waiter = rt_mutex_top_waiter(lock2)))) {
936 int chain_walk = 0;
938 spin_lock_irq(&owner->pi_lock);
939 if (top_waiter)
940 plist_del(&top_waiter->pi_list_entry, &owner->pi_waiters);
941 else
943 * There was no waiters before the requeue,
944 * the flag must be updated
946 mark_rt_mutex_waiters(lock2);
948 plist_add(&waiter->pi_list_entry, &owner->pi_waiters);
949 __rt_mutex_adjust_prio(owner);
950 if (owner->pi_blocked_on) {
951 chain_walk = 1;
952 get_task_struct(owner);
955 spin_unlock_irq(&owner->pi_lock);
956 spin_unlock(&lock2->wait_lock);
958 if (chain_walk)
959 rt_mutex_adjust_prio_chain(owner, 0, lock2, NULL,
960 current);
961 } else {
962 /* No owner or the top_waiter does not change */
963 mark_rt_mutex_waiters(lock2);
964 spin_unlock(&lock2->wait_lock);
968 out_unlock:
969 spin_unlock(&hb1->lock);
970 if (hb1 != hb2)
971 spin_unlock(&hb2->lock);
973 /* drop_futex_key_refs() must be called outside the spinlocks. */
974 while (--drop_count >= 0)
975 drop_futex_key_refs(&key1);
977 out:
978 if (fshared)
979 up_read(fshared);
980 return ret;
984 * Wake up all waiters hashed on the physical page that is mapped
985 * to this virtual address:
987 static int
988 futex_wake_op(u32 __user *uaddr1, struct rw_semaphore *fshared,
989 u32 __user *uaddr2,
990 int nr_wake, int nr_wake2, int op)
992 union futex_key key1, key2;
993 struct futex_hash_bucket *hb1, *hb2;
994 struct plist_head *head;
995 struct futex_q *this, *next;
996 int ret, op_ret, attempt = 0;
998 retryfull:
999 if (fshared)
1000 down_read(fshared);
1002 ret = get_futex_key(uaddr1, fshared, &key1);
1003 if (unlikely(ret != 0))
1004 goto out;
1005 ret = get_futex_key(uaddr2, fshared, &key2);
1006 if (unlikely(ret != 0))
1007 goto out;
1009 hb1 = hash_futex(&key1);
1010 hb2 = hash_futex(&key2);
1012 retry:
1013 double_lock_hb(hb1, hb2);
1015 op_ret = futex_atomic_op_inuser(op, uaddr2);
1016 if (unlikely(op_ret < 0)) {
1017 u32 dummy;
1019 spin_unlock(&hb1->lock);
1020 if (hb1 != hb2)
1021 spin_unlock(&hb2->lock);
1023 #ifndef CONFIG_MMU
1025 * we don't get EFAULT from MMU faults if we don't have an MMU,
1026 * but we might get them from range checking
1028 ret = op_ret;
1029 goto out;
1030 #endif
1032 if (unlikely(op_ret != -EFAULT)) {
1033 ret = op_ret;
1034 goto out;
1038 * futex_atomic_op_inuser needs to both read and write
1039 * *(int __user *)uaddr2, but we can't modify it
1040 * non-atomically. Therefore, if get_user below is not
1041 * enough, we need to handle the fault ourselves, while
1042 * still holding the mmap_sem.
1044 if (attempt++) {
1045 ret = futex_handle_fault((unsigned long)uaddr2,
1046 fshared, attempt);
1047 if (ret)
1048 goto out;
1049 goto retry;
1053 * If we would have faulted, release mmap_sem,
1054 * fault it in and start all over again.
1056 if (fshared)
1057 up_read(fshared);
1059 ret = get_user(dummy, uaddr2);
1060 if (ret)
1061 return ret;
1063 goto retryfull;
1066 head = &hb1->chain;
1068 plist_for_each_entry_safe(this, next, head, list) {
1069 if (match_futex (&this->key, &key1)) {
1070 wake_futex(this);
1071 if (++ret >= nr_wake)
1072 break;
1076 if (op_ret > 0) {
1077 head = &hb2->chain;
1079 op_ret = 0;
1080 plist_for_each_entry_safe(this, next, head, list) {
1081 if (match_futex (&this->key, &key2)) {
1082 wake_futex(this);
1083 if (++op_ret >= nr_wake2)
1084 break;
1087 ret += op_ret;
1090 spin_unlock(&hb1->lock);
1091 if (hb1 != hb2)
1092 spin_unlock(&hb2->lock);
1093 out:
1094 if (fshared)
1095 up_read(fshared);
1096 return ret;
1100 * Requeue all waiters hashed on one physical page to another
1101 * physical page.
1103 static int futex_requeue(u32 __user *uaddr1, struct rw_semaphore *fshared,
1104 u32 __user *uaddr2,
1105 int nr_wake, int nr_requeue, u32 *cmpval)
1107 union futex_key key1, key2;
1108 struct futex_hash_bucket *hb1, *hb2;
1109 struct plist_head *head1;
1110 struct futex_q *this, *next;
1111 int ret, drop_count = 0;
1113 retry:
1114 if (fshared)
1115 down_read(fshared);
1117 ret = get_futex_key(uaddr1, fshared, &key1);
1118 if (unlikely(ret != 0))
1119 goto out;
1120 ret = get_futex_key(uaddr2, fshared, &key2);
1121 if (unlikely(ret != 0))
1122 goto out;
1124 hb1 = hash_futex(&key1);
1125 hb2 = hash_futex(&key2);
1127 double_lock_hb(hb1, hb2);
1129 if (likely(cmpval != NULL)) {
1130 u32 curval;
1132 ret = get_futex_value_locked(&curval, uaddr1);
1134 if (unlikely(ret)) {
1135 spin_unlock(&hb1->lock);
1136 if (hb1 != hb2)
1137 spin_unlock(&hb2->lock);
1140 * If we would have faulted, release mmap_sem, fault
1141 * it in and start all over again.
1143 if (fshared)
1144 up_read(fshared);
1146 ret = get_user(curval, uaddr1);
1148 if (!ret)
1149 goto retry;
1151 return ret;
1153 if (curval != *cmpval) {
1154 ret = -EAGAIN;
1155 goto out_unlock;
1159 head1 = &hb1->chain;
1160 plist_for_each_entry_safe(this, next, head1, list) {
1161 if (!match_futex (&this->key, &key1))
1162 continue;
1163 if (++ret <= nr_wake) {
1164 wake_futex(this);
1165 } else {
1167 * If key1 and key2 hash to the same bucket, no need to
1168 * requeue.
1170 if (likely(head1 != &hb2->chain)) {
1171 plist_del(&this->list, &hb1->chain);
1172 plist_add(&this->list, &hb2->chain);
1173 this->lock_ptr = &hb2->lock;
1174 #ifdef CONFIG_DEBUG_PI_LIST
1175 this->list.plist.lock = &hb2->lock;
1176 #endif
1178 this->key = key2;
1179 get_futex_key_refs(&key2);
1180 drop_count++;
1182 if (ret - nr_wake >= nr_requeue)
1183 break;
1187 out_unlock:
1188 spin_unlock(&hb1->lock);
1189 if (hb1 != hb2)
1190 spin_unlock(&hb2->lock);
1192 /* drop_futex_key_refs() must be called outside the spinlocks. */
1193 while (--drop_count >= 0)
1194 drop_futex_key_refs(&key1);
1196 out:
1197 if (fshared)
1198 up_read(fshared);
1199 return ret;
1202 /* The key must be already stored in q->key. */
1203 static inline struct futex_hash_bucket *
1204 queue_lock(struct futex_q *q, int fd, struct file *filp)
1206 struct futex_hash_bucket *hb;
1208 q->fd = fd;
1209 q->filp = filp;
1211 init_waitqueue_head(&q->waiters);
1213 get_futex_key_refs(&q->key);
1214 hb = hash_futex(&q->key);
1215 q->lock_ptr = &hb->lock;
1217 spin_lock(&hb->lock);
1218 return hb;
1221 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
1223 int prio;
1226 * The priority used to register this element is
1227 * - either the real thread-priority for the real-time threads
1228 * (i.e. threads with a priority lower than MAX_RT_PRIO)
1229 * - or MAX_RT_PRIO for non-RT threads.
1230 * Thus, all RT-threads are woken first in priority order, and
1231 * the others are woken last, in FIFO order.
1233 prio = min(current->normal_prio, MAX_RT_PRIO);
1235 plist_node_init(&q->list, prio);
1236 #ifdef CONFIG_DEBUG_PI_LIST
1237 q->list.plist.lock = &hb->lock;
1238 #endif
1239 plist_add(&q->list, &hb->chain);
1240 q->task = current;
1241 spin_unlock(&hb->lock);
1244 static inline void
1245 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
1247 spin_unlock(&hb->lock);
1248 drop_futex_key_refs(&q->key);
1252 * queue_me and unqueue_me must be called as a pair, each
1253 * exactly once. They are called with the hashed spinlock held.
1256 /* The key must be already stored in q->key. */
1257 static void queue_me(struct futex_q *q, int fd, struct file *filp)
1259 struct futex_hash_bucket *hb;
1261 hb = queue_lock(q, fd, filp);
1262 __queue_me(q, hb);
1265 /* Return 1 if we were still queued (ie. 0 means we were woken) */
1266 static int unqueue_me(struct futex_q *q)
1268 spinlock_t *lock_ptr;
1269 int ret = 0;
1271 /* In the common case we don't take the spinlock, which is nice. */
1272 retry:
1273 lock_ptr = q->lock_ptr;
1274 barrier();
1275 if (lock_ptr != 0) {
1276 spin_lock(lock_ptr);
1278 * q->lock_ptr can change between reading it and
1279 * spin_lock(), causing us to take the wrong lock. This
1280 * corrects the race condition.
1282 * Reasoning goes like this: if we have the wrong lock,
1283 * q->lock_ptr must have changed (maybe several times)
1284 * between reading it and the spin_lock(). It can
1285 * change again after the spin_lock() but only if it was
1286 * already changed before the spin_lock(). It cannot,
1287 * however, change back to the original value. Therefore
1288 * we can detect whether we acquired the correct lock.
1290 if (unlikely(lock_ptr != q->lock_ptr)) {
1291 spin_unlock(lock_ptr);
1292 goto retry;
1294 WARN_ON(plist_node_empty(&q->list));
1295 plist_del(&q->list, &q->list.plist);
1297 BUG_ON(q->pi_state);
1299 spin_unlock(lock_ptr);
1300 ret = 1;
1303 drop_futex_key_refs(&q->key);
1304 return ret;
1308 * PI futexes can not be requeued and must remove themself from the
1309 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1310 * and dropped here.
1312 static void unqueue_me_pi(struct futex_q *q)
1314 WARN_ON(plist_node_empty(&q->list));
1315 plist_del(&q->list, &q->list.plist);
1317 BUG_ON(!q->pi_state);
1318 free_pi_state(q->pi_state);
1319 q->pi_state = NULL;
1321 spin_unlock(q->lock_ptr);
1323 drop_futex_key_refs(&q->key);
1327 * Fixup the pi_state owner with current.
1329 * The cur->mm semaphore must be held, it is released at return of this
1330 * function.
1332 static int fixup_pi_state_owner(u32 __user *uaddr, struct rw_semaphore *fshared,
1333 struct futex_q *q,
1334 struct futex_hash_bucket *hb,
1335 struct task_struct *curr)
1337 u32 newtid = curr->pid | FUTEX_WAITERS;
1338 struct futex_pi_state *pi_state = q->pi_state;
1339 u32 uval, curval, newval;
1340 int ret;
1342 /* Owner died? */
1343 if (pi_state->owner != NULL) {
1344 spin_lock_irq(&pi_state->owner->pi_lock);
1345 WARN_ON(list_empty(&pi_state->list));
1346 list_del_init(&pi_state->list);
1347 spin_unlock_irq(&pi_state->owner->pi_lock);
1348 } else
1349 newtid |= FUTEX_OWNER_DIED;
1351 pi_state->owner = curr;
1353 spin_lock_irq(&curr->pi_lock);
1354 WARN_ON(!list_empty(&pi_state->list));
1355 list_add(&pi_state->list, &curr->pi_state_list);
1356 spin_unlock_irq(&curr->pi_lock);
1358 /* Unqueue and drop the lock */
1359 unqueue_me_pi(q);
1360 if (fshared)
1361 up_read(fshared);
1363 * We own it, so we have to replace the pending owner
1364 * TID. This must be atomic as we have preserve the
1365 * owner died bit here.
1367 ret = get_user(uval, uaddr);
1368 while (!ret) {
1369 newval = (uval & FUTEX_OWNER_DIED) | newtid;
1370 newval |= (uval & FUTEX_WAITER_REQUEUED);
1371 curval = futex_atomic_cmpxchg_inatomic(uaddr,
1372 uval, newval);
1373 if (curval == -EFAULT)
1374 ret = -EFAULT;
1375 if (curval == uval)
1376 break;
1377 uval = curval;
1379 return ret;
1383 * In case we must use restart_block to restart a futex_wait,
1384 * we encode in the 'arg3' shared capability
1386 #define ARG3_SHARED 1
1388 static long futex_wait_restart(struct restart_block *restart);
1389 static int futex_wait(u32 __user *uaddr, struct rw_semaphore *fshared,
1390 u32 val, ktime_t *abs_time)
1392 struct task_struct *curr = current;
1393 DECLARE_WAITQUEUE(wait, curr);
1394 struct futex_hash_bucket *hb;
1395 struct futex_q q;
1396 u32 uval;
1397 int ret;
1398 struct hrtimer_sleeper t, *to = NULL;
1399 int rem = 0;
1401 q.pi_state = NULL;
1402 retry:
1403 if (fshared)
1404 down_read(fshared);
1406 ret = get_futex_key(uaddr, fshared, &q.key);
1407 if (unlikely(ret != 0))
1408 goto out_release_sem;
1410 hb = queue_lock(&q, -1, NULL);
1413 * Access the page AFTER the futex is queued.
1414 * Order is important:
1416 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1417 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
1419 * The basic logical guarantee of a futex is that it blocks ONLY
1420 * if cond(var) is known to be true at the time of blocking, for
1421 * any cond. If we queued after testing *uaddr, that would open
1422 * a race condition where we could block indefinitely with
1423 * cond(var) false, which would violate the guarantee.
1425 * A consequence is that futex_wait() can return zero and absorb
1426 * a wakeup when *uaddr != val on entry to the syscall. This is
1427 * rare, but normal.
1429 * for shared futexes, we hold the mmap semaphore, so the mapping
1430 * cannot have changed since we looked it up in get_futex_key.
1432 ret = get_futex_value_locked(&uval, uaddr);
1434 if (unlikely(ret)) {
1435 queue_unlock(&q, hb);
1438 * If we would have faulted, release mmap_sem, fault it in and
1439 * start all over again.
1441 if (fshared)
1442 up_read(fshared);
1444 ret = get_user(uval, uaddr);
1446 if (!ret)
1447 goto retry;
1448 return ret;
1450 ret = -EWOULDBLOCK;
1451 if (uval != val)
1452 goto out_unlock_release_sem;
1455 * This rt_mutex_waiter structure is prepared here and will
1456 * be used only if this task is requeued from a normal futex to
1457 * a PI-futex with futex_requeue_pi.
1459 debug_rt_mutex_init_waiter(&q.waiter);
1460 q.waiter.task = NULL;
1462 /* Only actually queue if *uaddr contained val. */
1463 __queue_me(&q, hb);
1466 * Now the futex is queued and we have checked the data, we
1467 * don't want to hold mmap_sem while we sleep.
1469 if (fshared)
1470 up_read(fshared);
1473 * There might have been scheduling since the queue_me(), as we
1474 * cannot hold a spinlock across the get_user() in case it
1475 * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1476 * queueing ourselves into the futex hash. This code thus has to
1477 * rely on the futex_wake() code removing us from hash when it
1478 * wakes us up.
1481 /* add_wait_queue is the barrier after __set_current_state. */
1482 __set_current_state(TASK_INTERRUPTIBLE);
1483 add_wait_queue(&q.waiters, &wait);
1485 * !plist_node_empty() is safe here without any lock.
1486 * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1488 if (likely(!plist_node_empty(&q.list))) {
1489 if (!abs_time)
1490 schedule();
1491 else {
1492 to = &t;
1493 hrtimer_init(&t.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1494 hrtimer_init_sleeper(&t, current);
1495 t.timer.expires = *abs_time;
1497 hrtimer_start(&t.timer, t.timer.expires, HRTIMER_MODE_ABS);
1500 * the timer could have already expired, in which
1501 * case current would be flagged for rescheduling.
1502 * Don't bother calling schedule.
1504 if (likely(t.task))
1505 schedule();
1507 hrtimer_cancel(&t.timer);
1509 /* Flag if a timeout occured */
1510 rem = (t.task == NULL);
1513 __set_current_state(TASK_RUNNING);
1516 * NOTE: we don't remove ourselves from the waitqueue because
1517 * we are the only user of it.
1520 if (q.pi_state) {
1522 * We were woken but have been requeued on a PI-futex.
1523 * We have to complete the lock acquisition by taking
1524 * the rtmutex.
1527 struct rt_mutex *lock = &q.pi_state->pi_mutex;
1529 spin_lock(&lock->wait_lock);
1530 if (unlikely(q.waiter.task)) {
1531 remove_waiter(lock, &q.waiter);
1533 spin_unlock(&lock->wait_lock);
1535 if (rem)
1536 ret = -ETIMEDOUT;
1537 else
1538 ret = rt_mutex_timed_lock(lock, to, 1);
1540 if (fshared)
1541 down_read(fshared);
1542 spin_lock(q.lock_ptr);
1545 * Got the lock. We might not be the anticipated owner if we
1546 * did a lock-steal - fix up the PI-state in that case.
1548 if (!ret && q.pi_state->owner != curr) {
1550 * We MUST play with the futex we were requeued on,
1551 * NOT the current futex.
1552 * We can retrieve it from the key of the pi_state
1554 uaddr = q.pi_state->key.uaddr;
1556 /* mmap_sem and hash_bucket lock are unlocked at
1557 return of this function */
1558 ret = fixup_pi_state_owner(uaddr, fshared,
1559 &q, hb, curr);
1560 } else {
1562 * Catch the rare case, where the lock was released
1563 * when we were on the way back before we locked
1564 * the hash bucket.
1566 if (ret && q.pi_state->owner == curr) {
1567 if (rt_mutex_trylock(&q.pi_state->pi_mutex))
1568 ret = 0;
1570 /* Unqueue and drop the lock */
1571 unqueue_me_pi(&q);
1572 if (fshared)
1573 up_read(fshared);
1576 debug_rt_mutex_free_waiter(&q.waiter);
1578 return ret;
1581 debug_rt_mutex_free_waiter(&q.waiter);
1583 /* If we were woken (and unqueued), we succeeded, whatever. */
1584 if (!unqueue_me(&q))
1585 return 0;
1586 if (rem)
1587 return -ETIMEDOUT;
1590 * We expect signal_pending(current), but another thread may
1591 * have handled it for us already.
1593 if (!abs_time)
1594 return -ERESTARTSYS;
1595 else {
1596 struct restart_block *restart;
1597 restart = &current_thread_info()->restart_block;
1598 restart->fn = futex_wait_restart;
1599 restart->arg0 = (unsigned long)uaddr;
1600 restart->arg1 = (unsigned long)val;
1601 restart->arg2 = (unsigned long)abs_time;
1602 restart->arg3 = 0;
1603 if (fshared)
1604 restart->arg3 |= ARG3_SHARED;
1605 return -ERESTART_RESTARTBLOCK;
1608 out_unlock_release_sem:
1609 queue_unlock(&q, hb);
1611 out_release_sem:
1612 if (fshared)
1613 up_read(fshared);
1614 return ret;
1618 static long futex_wait_restart(struct restart_block *restart)
1620 u32 __user *uaddr = (u32 __user *)restart->arg0;
1621 u32 val = (u32)restart->arg1;
1622 ktime_t *abs_time = (ktime_t *)restart->arg2;
1623 struct rw_semaphore *fshared = NULL;
1625 restart->fn = do_no_restart_syscall;
1626 if (restart->arg3 & ARG3_SHARED)
1627 fshared = &current->mm->mmap_sem;
1628 return (long)futex_wait(uaddr, fshared, val, abs_time);
1632 static void set_pi_futex_owner(struct futex_hash_bucket *hb,
1633 union futex_key *key, struct task_struct *p)
1635 struct plist_head *head;
1636 struct futex_q *this, *next;
1637 struct futex_pi_state *pi_state = NULL;
1638 struct rt_mutex *lock;
1640 /* Search a waiter that should already exists */
1642 head = &hb->chain;
1644 plist_for_each_entry_safe(this, next, head, list) {
1645 if (match_futex (&this->key, key)) {
1646 pi_state = this->pi_state;
1647 break;
1651 BUG_ON(!pi_state);
1653 /* set p as pi_state's owner */
1654 lock = &pi_state->pi_mutex;
1656 spin_lock(&lock->wait_lock);
1657 spin_lock_irq(&p->pi_lock);
1659 list_add(&pi_state->list, &p->pi_state_list);
1660 pi_state->owner = p;
1663 /* set p as pi_mutex's owner */
1664 debug_rt_mutex_proxy_lock(lock, p);
1665 WARN_ON(rt_mutex_owner(lock));
1666 rt_mutex_set_owner(lock, p, 0);
1667 rt_mutex_deadlock_account_lock(lock, p);
1669 plist_add(&rt_mutex_top_waiter(lock)->pi_list_entry,
1670 &p->pi_waiters);
1671 __rt_mutex_adjust_prio(p);
1673 spin_unlock_irq(&p->pi_lock);
1674 spin_unlock(&lock->wait_lock);
1678 * Userspace tried a 0 -> TID atomic transition of the futex value
1679 * and failed. The kernel side here does the whole locking operation:
1680 * if there are waiters then it will block, it does PI, etc. (Due to
1681 * races the kernel might see a 0 value of the futex too.)
1683 static int futex_lock_pi(u32 __user *uaddr, struct rw_semaphore *fshared,
1684 int detect, ktime_t *time, int trylock)
1686 struct hrtimer_sleeper timeout, *to = NULL;
1687 struct task_struct *curr = current;
1688 struct futex_hash_bucket *hb;
1689 u32 uval, newval, curval;
1690 struct futex_q q;
1691 int ret, lock_held, attempt = 0;
1693 if (refill_pi_state_cache())
1694 return -ENOMEM;
1696 if (time) {
1697 to = &timeout;
1698 hrtimer_init(&to->timer, CLOCK_REALTIME, HRTIMER_MODE_ABS);
1699 hrtimer_init_sleeper(to, current);
1700 to->timer.expires = *time;
1703 q.pi_state = NULL;
1704 retry:
1705 if (fshared)
1706 down_read(fshared);
1708 ret = get_futex_key(uaddr, fshared, &q.key);
1709 if (unlikely(ret != 0))
1710 goto out_release_sem;
1712 hb = queue_lock(&q, -1, NULL);
1714 retry_locked:
1715 lock_held = 0;
1718 * To avoid races, we attempt to take the lock here again
1719 * (by doing a 0 -> TID atomic cmpxchg), while holding all
1720 * the locks. It will most likely not succeed.
1722 newval = current->pid;
1724 pagefault_disable();
1725 curval = futex_atomic_cmpxchg_inatomic(uaddr, 0, newval);
1726 pagefault_enable();
1728 if (unlikely(curval == -EFAULT))
1729 goto uaddr_faulted;
1731 /* We own the lock already */
1732 if (unlikely((curval & FUTEX_TID_MASK) == current->pid)) {
1733 if (!detect && 0)
1734 force_sig(SIGKILL, current);
1736 * Normally, this check is done in user space.
1737 * In case of requeue, the owner may attempt to lock this futex,
1738 * even if the ownership has already been given by the previous
1739 * waker.
1740 * In the usual case, this is a case of deadlock, but not in case
1741 * of REQUEUE_PI.
1743 if (!(curval & FUTEX_WAITER_REQUEUED))
1744 ret = -EDEADLK;
1745 goto out_unlock_release_sem;
1749 * Surprise - we got the lock. Just return
1750 * to userspace:
1752 if (unlikely(!curval))
1753 goto out_unlock_release_sem;
1755 uval = curval;
1757 * In case of a requeue, check if there already is an owner
1758 * If not, just take the futex.
1760 if ((curval & FUTEX_WAITER_REQUEUED) && !(curval & FUTEX_TID_MASK)) {
1761 /* set current as futex owner */
1762 newval = curval | current->pid;
1763 lock_held = 1;
1764 } else
1765 /* Set the WAITERS flag, so the owner will know it has someone
1766 to wake at next unlock */
1767 newval = curval | FUTEX_WAITERS;
1769 pagefault_disable();
1770 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
1771 pagefault_enable();
1773 if (unlikely(curval == -EFAULT))
1774 goto uaddr_faulted;
1775 if (unlikely(curval != uval))
1776 goto retry_locked;
1778 if (lock_held) {
1779 set_pi_futex_owner(hb, &q.key, curr);
1780 goto out_unlock_release_sem;
1784 * We dont have the lock. Look up the PI state (or create it if
1785 * we are the first waiter):
1787 ret = lookup_pi_state(uval, hb, &q.key, &q.pi_state);
1789 if (unlikely(ret)) {
1791 * There were no waiters and the owner task lookup
1792 * failed. When the OWNER_DIED bit is set, then we
1793 * know that this is a robust futex and we actually
1794 * take the lock. This is safe as we are protected by
1795 * the hash bucket lock. We also set the waiters bit
1796 * unconditionally here, to simplify glibc handling of
1797 * multiple tasks racing to acquire the lock and
1798 * cleanup the problems which were left by the dead
1799 * owner.
1801 if (curval & FUTEX_OWNER_DIED) {
1802 uval = newval;
1803 newval = current->pid |
1804 FUTEX_OWNER_DIED | FUTEX_WAITERS;
1806 pagefault_disable();
1807 curval = futex_atomic_cmpxchg_inatomic(uaddr,
1808 uval, newval);
1809 pagefault_enable();
1811 if (unlikely(curval == -EFAULT))
1812 goto uaddr_faulted;
1813 if (unlikely(curval != uval))
1814 goto retry_locked;
1815 ret = 0;
1817 goto out_unlock_release_sem;
1821 * Only actually queue now that the atomic ops are done:
1823 __queue_me(&q, hb);
1826 * Now the futex is queued and we have checked the data, we
1827 * don't want to hold mmap_sem while we sleep.
1829 if (fshared)
1830 up_read(fshared);
1832 WARN_ON(!q.pi_state);
1834 * Block on the PI mutex:
1836 if (!trylock)
1837 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1838 else {
1839 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1840 /* Fixup the trylock return value: */
1841 ret = ret ? 0 : -EWOULDBLOCK;
1844 if (fshared)
1845 down_read(fshared);
1846 spin_lock(q.lock_ptr);
1849 * Got the lock. We might not be the anticipated owner if we
1850 * did a lock-steal - fix up the PI-state in that case.
1852 if (!ret && q.pi_state->owner != curr)
1853 /* mmap_sem is unlocked at return of this function */
1854 ret = fixup_pi_state_owner(uaddr, fshared, &q, hb, curr);
1855 else {
1857 * Catch the rare case, where the lock was released
1858 * when we were on the way back before we locked
1859 * the hash bucket.
1861 if (ret && q.pi_state->owner == curr) {
1862 if (rt_mutex_trylock(&q.pi_state->pi_mutex))
1863 ret = 0;
1865 /* Unqueue and drop the lock */
1866 unqueue_me_pi(&q);
1867 if (fshared)
1868 up_read(fshared);
1871 if (!detect && ret == -EDEADLK && 0)
1872 force_sig(SIGKILL, current);
1874 return ret != -EINTR ? ret : -ERESTARTNOINTR;
1876 out_unlock_release_sem:
1877 queue_unlock(&q, hb);
1879 out_release_sem:
1880 if (fshared)
1881 up_read(fshared);
1882 return ret;
1884 uaddr_faulted:
1886 * We have to r/w *(int __user *)uaddr, but we can't modify it
1887 * non-atomically. Therefore, if get_user below is not
1888 * enough, we need to handle the fault ourselves, while
1889 * still holding the mmap_sem.
1891 if (attempt++) {
1892 ret = futex_handle_fault((unsigned long)uaddr, fshared,
1893 attempt);
1894 if (ret)
1895 goto out_unlock_release_sem;
1896 goto retry_locked;
1899 queue_unlock(&q, hb);
1900 if (fshared)
1901 up_read(fshared);
1903 ret = get_user(uval, uaddr);
1904 if (!ret && (uval != -EFAULT))
1905 goto retry;
1907 return ret;
1911 * Userspace attempted a TID -> 0 atomic transition, and failed.
1912 * This is the in-kernel slowpath: we look up the PI state (if any),
1913 * and do the rt-mutex unlock.
1915 static int futex_unlock_pi(u32 __user *uaddr, struct rw_semaphore *fshared)
1917 struct futex_hash_bucket *hb;
1918 struct futex_q *this, *next;
1919 u32 uval;
1920 struct plist_head *head;
1921 union futex_key key;
1922 int ret, attempt = 0;
1924 retry:
1925 if (get_user(uval, uaddr))
1926 return -EFAULT;
1928 * We release only a lock we actually own:
1930 if ((uval & FUTEX_TID_MASK) != current->pid)
1931 return -EPERM;
1933 * First take all the futex related locks:
1935 if (fshared)
1936 down_read(fshared);
1938 ret = get_futex_key(uaddr, fshared, &key);
1939 if (unlikely(ret != 0))
1940 goto out;
1942 hb = hash_futex(&key);
1943 spin_lock(&hb->lock);
1945 retry_locked:
1947 * To avoid races, try to do the TID -> 0 atomic transition
1948 * again. If it succeeds then we can return without waking
1949 * anyone else up:
1951 if (!(uval & FUTEX_OWNER_DIED)) {
1952 pagefault_disable();
1953 uval = futex_atomic_cmpxchg_inatomic(uaddr, current->pid, 0);
1954 pagefault_enable();
1957 if (unlikely(uval == -EFAULT))
1958 goto pi_faulted;
1960 * Rare case: we managed to release the lock atomically,
1961 * no need to wake anyone else up:
1963 if (unlikely(uval == current->pid))
1964 goto out_unlock;
1967 * Ok, other tasks may need to be woken up - check waiters
1968 * and do the wakeup if necessary:
1970 head = &hb->chain;
1972 plist_for_each_entry_safe(this, next, head, list) {
1973 if (!match_futex (&this->key, &key))
1974 continue;
1975 ret = wake_futex_pi(uaddr, uval, this);
1977 * The atomic access to the futex value
1978 * generated a pagefault, so retry the
1979 * user-access and the wakeup:
1981 if (ret == -EFAULT)
1982 goto pi_faulted;
1983 goto out_unlock;
1986 * No waiters - kernel unlocks the futex:
1988 if (!(uval & FUTEX_OWNER_DIED)) {
1989 ret = unlock_futex_pi(uaddr, uval);
1990 if (ret == -EFAULT)
1991 goto pi_faulted;
1994 out_unlock:
1995 spin_unlock(&hb->lock);
1996 out:
1997 if (fshared)
1998 up_read(fshared);
2000 return ret;
2002 pi_faulted:
2004 * We have to r/w *(int __user *)uaddr, but we can't modify it
2005 * non-atomically. Therefore, if get_user below is not
2006 * enough, we need to handle the fault ourselves, while
2007 * still holding the mmap_sem.
2009 if (attempt++) {
2010 ret = futex_handle_fault((unsigned long)uaddr, fshared,
2011 attempt);
2012 if (ret)
2013 goto out_unlock;
2014 goto retry_locked;
2017 spin_unlock(&hb->lock);
2018 if (fshared)
2019 up_read(fshared);
2021 ret = get_user(uval, uaddr);
2022 if (!ret && (uval != -EFAULT))
2023 goto retry;
2025 return ret;
2028 static int futex_close(struct inode *inode, struct file *filp)
2030 struct futex_q *q = filp->private_data;
2032 unqueue_me(q);
2033 kfree(q);
2035 return 0;
2038 /* This is one-shot: once it's gone off you need a new fd */
2039 static unsigned int futex_poll(struct file *filp,
2040 struct poll_table_struct *wait)
2042 struct futex_q *q = filp->private_data;
2043 int ret = 0;
2045 poll_wait(filp, &q->waiters, wait);
2048 * plist_node_empty() is safe here without any lock.
2049 * q->lock_ptr != 0 is not safe, because of ordering against wakeup.
2051 if (plist_node_empty(&q->list))
2052 ret = POLLIN | POLLRDNORM;
2054 return ret;
2057 static const struct file_operations futex_fops = {
2058 .release = futex_close,
2059 .poll = futex_poll,
2063 * Signal allows caller to avoid the race which would occur if they
2064 * set the sigio stuff up afterwards.
2066 static int futex_fd(u32 __user *uaddr, int signal)
2068 struct futex_q *q;
2069 struct file *filp;
2070 int ret, err;
2071 struct rw_semaphore *fshared;
2072 static unsigned long printk_interval;
2074 if (printk_timed_ratelimit(&printk_interval, 60 * 60 * 1000)) {
2075 printk(KERN_WARNING "Process `%s' used FUTEX_FD, which "
2076 "will be removed from the kernel in June 2007\n",
2077 current->comm);
2080 ret = -EINVAL;
2081 if (!valid_signal(signal))
2082 goto out;
2084 ret = get_unused_fd();
2085 if (ret < 0)
2086 goto out;
2087 filp = get_empty_filp();
2088 if (!filp) {
2089 put_unused_fd(ret);
2090 ret = -ENFILE;
2091 goto out;
2093 filp->f_op = &futex_fops;
2094 filp->f_path.mnt = mntget(futex_mnt);
2095 filp->f_path.dentry = dget(futex_mnt->mnt_root);
2096 filp->f_mapping = filp->f_path.dentry->d_inode->i_mapping;
2098 if (signal) {
2099 err = __f_setown(filp, task_pid(current), PIDTYPE_PID, 1);
2100 if (err < 0) {
2101 goto error;
2103 filp->f_owner.signum = signal;
2106 q = kmalloc(sizeof(*q), GFP_KERNEL);
2107 if (!q) {
2108 err = -ENOMEM;
2109 goto error;
2111 q->pi_state = NULL;
2113 fshared = &current->mm->mmap_sem;
2114 down_read(fshared);
2115 err = get_futex_key(uaddr, fshared, &q->key);
2117 if (unlikely(err != 0)) {
2118 up_read(fshared);
2119 kfree(q);
2120 goto error;
2124 * queue_me() must be called before releasing mmap_sem, because
2125 * key->shared.inode needs to be referenced while holding it.
2127 filp->private_data = q;
2129 queue_me(q, ret, filp);
2130 up_read(fshared);
2132 /* Now we map fd to filp, so userspace can access it */
2133 fd_install(ret, filp);
2134 out:
2135 return ret;
2136 error:
2137 put_unused_fd(ret);
2138 put_filp(filp);
2139 ret = err;
2140 goto out;
2144 * Support for robust futexes: the kernel cleans up held futexes at
2145 * thread exit time.
2147 * Implementation: user-space maintains a per-thread list of locks it
2148 * is holding. Upon do_exit(), the kernel carefully walks this list,
2149 * and marks all locks that are owned by this thread with the
2150 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
2151 * always manipulated with the lock held, so the list is private and
2152 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
2153 * field, to allow the kernel to clean up if the thread dies after
2154 * acquiring the lock, but just before it could have added itself to
2155 * the list. There can only be one such pending lock.
2159 * sys_set_robust_list - set the robust-futex list head of a task
2160 * @head: pointer to the list-head
2161 * @len: length of the list-head, as userspace expects
2163 asmlinkage long
2164 sys_set_robust_list(struct robust_list_head __user *head,
2165 size_t len)
2168 * The kernel knows only one size for now:
2170 if (unlikely(len != sizeof(*head)))
2171 return -EINVAL;
2173 current->robust_list = head;
2175 return 0;
2179 * sys_get_robust_list - get the robust-futex list head of a task
2180 * @pid: pid of the process [zero for current task]
2181 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
2182 * @len_ptr: pointer to a length field, the kernel fills in the header size
2184 asmlinkage long
2185 sys_get_robust_list(int pid, struct robust_list_head __user * __user *head_ptr,
2186 size_t __user *len_ptr)
2188 struct robust_list_head __user *head;
2189 unsigned long ret;
2191 if (!pid)
2192 head = current->robust_list;
2193 else {
2194 struct task_struct *p;
2196 ret = -ESRCH;
2197 rcu_read_lock();
2198 p = find_task_by_pid(pid);
2199 if (!p)
2200 goto err_unlock;
2201 ret = -EPERM;
2202 if ((current->euid != p->euid) && (current->euid != p->uid) &&
2203 !capable(CAP_SYS_PTRACE))
2204 goto err_unlock;
2205 head = p->robust_list;
2206 rcu_read_unlock();
2209 if (put_user(sizeof(*head), len_ptr))
2210 return -EFAULT;
2211 return put_user(head, head_ptr);
2213 err_unlock:
2214 rcu_read_unlock();
2216 return ret;
2220 * Process a futex-list entry, check whether it's owned by the
2221 * dying task, and do notification if so:
2223 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
2225 u32 uval, nval, mval;
2227 retry:
2228 if (get_user(uval, uaddr))
2229 return -1;
2231 if ((uval & FUTEX_TID_MASK) == curr->pid) {
2233 * Ok, this dying thread is truly holding a futex
2234 * of interest. Set the OWNER_DIED bit atomically
2235 * via cmpxchg, and if the value had FUTEX_WAITERS
2236 * set, wake up a waiter (if any). (We have to do a
2237 * futex_wake() even if OWNER_DIED is already set -
2238 * to handle the rare but possible case of recursive
2239 * thread-death.) The rest of the cleanup is done in
2240 * userspace.
2242 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
2243 /* Also keep the FUTEX_WAITER_REQUEUED flag if set */
2244 mval |= (uval & FUTEX_WAITER_REQUEUED);
2245 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
2247 if (nval == -EFAULT)
2248 return -1;
2250 if (nval != uval)
2251 goto retry;
2254 * Wake robust non-PI futexes here. The wakeup of
2255 * PI futexes happens in exit_pi_state():
2257 if (!pi) {
2258 if (uval & FUTEX_WAITERS)
2259 futex_wake(uaddr, &curr->mm->mmap_sem, 1);
2262 return 0;
2266 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
2268 static inline int fetch_robust_entry(struct robust_list __user **entry,
2269 struct robust_list __user * __user *head,
2270 int *pi)
2272 unsigned long uentry;
2274 if (get_user(uentry, (unsigned long __user *)head))
2275 return -EFAULT;
2277 *entry = (void __user *)(uentry & ~1UL);
2278 *pi = uentry & 1;
2280 return 0;
2284 * Walk curr->robust_list (very carefully, it's a userspace list!)
2285 * and mark any locks found there dead, and notify any waiters.
2287 * We silently return on any sign of list-walking problem.
2289 void exit_robust_list(struct task_struct *curr)
2291 struct robust_list_head __user *head = curr->robust_list;
2292 struct robust_list __user *entry, *pending;
2293 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
2294 unsigned long futex_offset;
2297 * Fetch the list head (which was registered earlier, via
2298 * sys_set_robust_list()):
2300 if (fetch_robust_entry(&entry, &head->list.next, &pi))
2301 return;
2303 * Fetch the relative futex offset:
2305 if (get_user(futex_offset, &head->futex_offset))
2306 return;
2308 * Fetch any possibly pending lock-add first, and handle it
2309 * if it exists:
2311 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
2312 return;
2314 if (pending)
2315 handle_futex_death((void __user *)pending + futex_offset,
2316 curr, pip);
2318 while (entry != &head->list) {
2320 * A pending lock might already be on the list, so
2321 * don't process it twice:
2323 if (entry != pending)
2324 if (handle_futex_death((void __user *)entry + futex_offset,
2325 curr, pi))
2326 return;
2328 * Fetch the next entry in the list:
2330 if (fetch_robust_entry(&entry, &entry->next, &pi))
2331 return;
2333 * Avoid excessively long or circular lists:
2335 if (!--limit)
2336 break;
2338 cond_resched();
2342 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
2343 u32 __user *uaddr2, u32 val2, u32 val3)
2345 int ret;
2346 int cmd = op & FUTEX_CMD_MASK;
2347 struct rw_semaphore *fshared = NULL;
2349 if (!(op & FUTEX_PRIVATE_FLAG))
2350 fshared = &current->mm->mmap_sem;
2352 switch (cmd) {
2353 case FUTEX_WAIT:
2354 ret = futex_wait(uaddr, fshared, val, timeout);
2355 break;
2356 case FUTEX_WAKE:
2357 ret = futex_wake(uaddr, fshared, val);
2358 break;
2359 case FUTEX_FD:
2360 /* non-zero val means F_SETOWN(getpid()) & F_SETSIG(val) */
2361 ret = futex_fd(uaddr, val);
2362 break;
2363 case FUTEX_REQUEUE:
2364 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL);
2365 break;
2366 case FUTEX_CMP_REQUEUE:
2367 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3);
2368 break;
2369 case FUTEX_WAKE_OP:
2370 ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3);
2371 break;
2372 case FUTEX_LOCK_PI:
2373 ret = futex_lock_pi(uaddr, fshared, val, timeout, 0);
2374 break;
2375 case FUTEX_UNLOCK_PI:
2376 ret = futex_unlock_pi(uaddr, fshared);
2377 break;
2378 case FUTEX_TRYLOCK_PI:
2379 ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1);
2380 break;
2381 case FUTEX_CMP_REQUEUE_PI:
2382 ret = futex_requeue_pi(uaddr, fshared, uaddr2, val, val2, &val3);
2383 break;
2384 default:
2385 ret = -ENOSYS;
2387 return ret;
2391 asmlinkage long sys_futex(u32 __user *uaddr, int op, u32 val,
2392 struct timespec __user *utime, u32 __user *uaddr2,
2393 u32 val3)
2395 struct timespec ts;
2396 ktime_t t, *tp = NULL;
2397 u32 val2 = 0;
2398 int cmd = op & FUTEX_CMD_MASK;
2400 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI)) {
2401 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
2402 return -EFAULT;
2403 if (!timespec_valid(&ts))
2404 return -EINVAL;
2406 t = timespec_to_ktime(ts);
2407 if (cmd == FUTEX_WAIT)
2408 t = ktime_add(ktime_get(), t);
2409 tp = &t;
2412 * requeue parameter in 'utime' if cmd == FUTEX_REQUEUE.
2414 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE
2415 || cmd == FUTEX_CMP_REQUEUE_PI)
2416 val2 = (u32) (unsigned long) utime;
2418 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
2421 static int futexfs_get_sb(struct file_system_type *fs_type,
2422 int flags, const char *dev_name, void *data,
2423 struct vfsmount *mnt)
2425 return get_sb_pseudo(fs_type, "futex", NULL, 0xBAD1DEA, mnt);
2428 static struct file_system_type futex_fs_type = {
2429 .name = "futexfs",
2430 .get_sb = futexfs_get_sb,
2431 .kill_sb = kill_anon_super,
2434 static int __init init(void)
2436 int i = register_filesystem(&futex_fs_type);
2438 if (i)
2439 return i;
2441 futex_mnt = kern_mount(&futex_fs_type);
2442 if (IS_ERR(futex_mnt)) {
2443 unregister_filesystem(&futex_fs_type);
2444 return PTR_ERR(futex_mnt);
2447 for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
2448 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
2449 spin_lock_init(&futex_queues[i].lock);
2451 return 0;
2453 __initcall(init);