thinkpad-acpi: fix CONFIG_THINKPAD_ACPI_HOTKEY_POLL build problem
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / futex.c
blob4d973bde85335f3c5e58d7662b7adf8d61f3cecf
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 <linux/magic.h>
56 #include <linux/pid.h>
57 #include <linux/nsproxy.h>
59 #include <asm/futex.h>
61 #include "rtmutex_common.h"
63 int __read_mostly futex_cmpxchg_enabled;
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->waiter, then make the second condition true.
97 struct futex_q {
98 struct plist_node list;
99 /* There can only be a single waiter */
100 wait_queue_head_t waiter;
102 /* Which hash list lock to use: */
103 spinlock_t *lock_ptr;
105 /* Key which the futex is hashed on: */
106 union futex_key key;
108 /* Optional priority inheritance state: */
109 struct futex_pi_state *pi_state;
110 struct task_struct *task;
112 /* Bitset for the optional bitmasked wakeup */
113 u32 bitset;
117 * Hash buckets are shared by all the futex_keys that hash to the same
118 * location. Each key may have multiple futex_q structures, one for each task
119 * waiting on a futex.
121 struct futex_hash_bucket {
122 spinlock_t lock;
123 struct plist_head chain;
126 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
129 * We hash on the keys returned from get_futex_key (see below).
131 static struct futex_hash_bucket *hash_futex(union futex_key *key)
133 u32 hash = jhash2((u32*)&key->both.word,
134 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
135 key->both.offset);
136 return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
140 * Return 1 if two futex_keys are equal, 0 otherwise.
142 static inline int match_futex(union futex_key *key1, union futex_key *key2)
144 return (key1->both.word == key2->both.word
145 && key1->both.ptr == key2->both.ptr
146 && key1->both.offset == key2->both.offset);
150 * Take a reference to the resource addressed by a key.
151 * Can be called while holding spinlocks.
154 static void get_futex_key_refs(union futex_key *key)
156 if (!key->both.ptr)
157 return;
159 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
160 case FUT_OFF_INODE:
161 atomic_inc(&key->shared.inode->i_count);
162 break;
163 case FUT_OFF_MMSHARED:
164 atomic_inc(&key->private.mm->mm_count);
165 break;
170 * Drop a reference to the resource addressed by a key.
171 * The hash bucket spinlock must not be held.
173 static void drop_futex_key_refs(union futex_key *key)
175 if (!key->both.ptr) {
176 /* If we're here then we tried to put a key we failed to get */
177 WARN_ON_ONCE(1);
178 return;
181 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
182 case FUT_OFF_INODE:
183 iput(key->shared.inode);
184 break;
185 case FUT_OFF_MMSHARED:
186 mmdrop(key->private.mm);
187 break;
192 * get_futex_key - Get parameters which are the keys for a futex.
193 * @uaddr: virtual address of the futex
194 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
195 * @key: address where result is stored.
196 * @rw: mapping needs to be read/write (values: VERIFY_READ, VERIFY_WRITE)
198 * Returns a negative error code or 0
199 * The key words are stored in *key on success.
201 * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
202 * offset_within_page). For private mappings, it's (uaddr, current->mm).
203 * We can usually work out the index without swapping in the page.
205 * lock_page() might sleep, the caller should not hold a spinlock.
207 static int
208 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
210 unsigned long address = (unsigned long)uaddr;
211 struct mm_struct *mm = current->mm;
212 struct page *page;
213 int err;
216 * The futex address must be "naturally" aligned.
218 key->both.offset = address % PAGE_SIZE;
219 if (unlikely((address % sizeof(u32)) != 0))
220 return -EINVAL;
221 address -= key->both.offset;
224 * PROCESS_PRIVATE futexes are fast.
225 * As the mm cannot disappear under us and the 'key' only needs
226 * virtual address, we dont even have to find the underlying vma.
227 * Note : We do have to check 'uaddr' is a valid user address,
228 * but access_ok() should be faster than find_vma()
230 if (!fshared) {
231 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
232 return -EFAULT;
233 key->private.mm = mm;
234 key->private.address = address;
235 get_futex_key_refs(key);
236 return 0;
239 again:
240 err = get_user_pages_fast(address, 1, rw == VERIFY_WRITE, &page);
241 if (err < 0)
242 return err;
244 page = compound_head(page);
245 lock_page(page);
246 if (!page->mapping) {
247 unlock_page(page);
248 put_page(page);
249 goto again;
253 * Private mappings are handled in a simple way.
255 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
256 * it's a read-only handle, it's expected that futexes attach to
257 * the object not the particular process.
259 if (PageAnon(page)) {
260 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
261 key->private.mm = mm;
262 key->private.address = address;
263 } else {
264 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
265 key->shared.inode = page->mapping->host;
266 key->shared.pgoff = page->index;
269 get_futex_key_refs(key);
271 unlock_page(page);
272 put_page(page);
273 return 0;
276 static inline
277 void put_futex_key(int fshared, union futex_key *key)
279 drop_futex_key_refs(key);
283 * fault_in_user_writeable - fault in user address and verify RW access
284 * @uaddr: pointer to faulting user space address
286 * Slow path to fixup the fault we just took in the atomic write
287 * access to @uaddr.
289 * We have no generic implementation of a non destructive write to the
290 * user address. We know that we faulted in the atomic pagefault
291 * disabled section so we can as well avoid the #PF overhead by
292 * calling get_user_pages() right away.
294 static int fault_in_user_writeable(u32 __user *uaddr)
296 int ret = get_user_pages(current, current->mm, (unsigned long)uaddr,
297 1, 1, 0, NULL, NULL);
298 return ret < 0 ? ret : 0;
301 static u32 cmpxchg_futex_value_locked(u32 __user *uaddr, u32 uval, u32 newval)
303 u32 curval;
305 pagefault_disable();
306 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
307 pagefault_enable();
309 return curval;
312 static int get_futex_value_locked(u32 *dest, u32 __user *from)
314 int ret;
316 pagefault_disable();
317 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
318 pagefault_enable();
320 return ret ? -EFAULT : 0;
325 * PI code:
327 static int refill_pi_state_cache(void)
329 struct futex_pi_state *pi_state;
331 if (likely(current->pi_state_cache))
332 return 0;
334 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
336 if (!pi_state)
337 return -ENOMEM;
339 INIT_LIST_HEAD(&pi_state->list);
340 /* pi_mutex gets initialized later */
341 pi_state->owner = NULL;
342 atomic_set(&pi_state->refcount, 1);
343 pi_state->key = FUTEX_KEY_INIT;
345 current->pi_state_cache = pi_state;
347 return 0;
350 static struct futex_pi_state * alloc_pi_state(void)
352 struct futex_pi_state *pi_state = current->pi_state_cache;
354 WARN_ON(!pi_state);
355 current->pi_state_cache = NULL;
357 return pi_state;
360 static void free_pi_state(struct futex_pi_state *pi_state)
362 if (!atomic_dec_and_test(&pi_state->refcount))
363 return;
366 * If pi_state->owner is NULL, the owner is most probably dying
367 * and has cleaned up the pi_state already
369 if (pi_state->owner) {
370 spin_lock_irq(&pi_state->owner->pi_lock);
371 list_del_init(&pi_state->list);
372 spin_unlock_irq(&pi_state->owner->pi_lock);
374 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
377 if (current->pi_state_cache)
378 kfree(pi_state);
379 else {
381 * pi_state->list is already empty.
382 * clear pi_state->owner.
383 * refcount is at 0 - put it back to 1.
385 pi_state->owner = NULL;
386 atomic_set(&pi_state->refcount, 1);
387 current->pi_state_cache = pi_state;
392 * Look up the task based on what TID userspace gave us.
393 * We dont trust it.
395 static struct task_struct * futex_find_get_task(pid_t pid)
397 struct task_struct *p;
398 const struct cred *cred = current_cred(), *pcred;
400 rcu_read_lock();
401 p = find_task_by_vpid(pid);
402 if (!p) {
403 p = ERR_PTR(-ESRCH);
404 } else {
405 pcred = __task_cred(p);
406 if (cred->euid != pcred->euid &&
407 cred->euid != pcred->uid)
408 p = ERR_PTR(-ESRCH);
409 else
410 get_task_struct(p);
413 rcu_read_unlock();
415 return p;
419 * This task is holding PI mutexes at exit time => bad.
420 * Kernel cleans up PI-state, but userspace is likely hosed.
421 * (Robust-futex cleanup is separate and might save the day for userspace.)
423 void exit_pi_state_list(struct task_struct *curr)
425 struct list_head *next, *head = &curr->pi_state_list;
426 struct futex_pi_state *pi_state;
427 struct futex_hash_bucket *hb;
428 union futex_key key = FUTEX_KEY_INIT;
430 if (!futex_cmpxchg_enabled)
431 return;
433 * We are a ZOMBIE and nobody can enqueue itself on
434 * pi_state_list anymore, but we have to be careful
435 * versus waiters unqueueing themselves:
437 spin_lock_irq(&curr->pi_lock);
438 while (!list_empty(head)) {
440 next = head->next;
441 pi_state = list_entry(next, struct futex_pi_state, list);
442 key = pi_state->key;
443 hb = hash_futex(&key);
444 spin_unlock_irq(&curr->pi_lock);
446 spin_lock(&hb->lock);
448 spin_lock_irq(&curr->pi_lock);
450 * We dropped the pi-lock, so re-check whether this
451 * task still owns the PI-state:
453 if (head->next != next) {
454 spin_unlock(&hb->lock);
455 continue;
458 WARN_ON(pi_state->owner != curr);
459 WARN_ON(list_empty(&pi_state->list));
460 list_del_init(&pi_state->list);
461 pi_state->owner = NULL;
462 spin_unlock_irq(&curr->pi_lock);
464 rt_mutex_unlock(&pi_state->pi_mutex);
466 spin_unlock(&hb->lock);
468 spin_lock_irq(&curr->pi_lock);
470 spin_unlock_irq(&curr->pi_lock);
473 static int
474 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
475 union futex_key *key, struct futex_pi_state **ps)
477 struct futex_pi_state *pi_state = NULL;
478 struct futex_q *this, *next;
479 struct plist_head *head;
480 struct task_struct *p;
481 pid_t pid = uval & FUTEX_TID_MASK;
483 head = &hb->chain;
485 plist_for_each_entry_safe(this, next, head, list) {
486 if (match_futex(&this->key, key)) {
488 * Another waiter already exists - bump up
489 * the refcount and return its pi_state:
491 pi_state = this->pi_state;
493 * Userspace might have messed up non PI and PI futexes
495 if (unlikely(!pi_state))
496 return -EINVAL;
498 WARN_ON(!atomic_read(&pi_state->refcount));
499 WARN_ON(pid && pi_state->owner &&
500 pi_state->owner->pid != pid);
502 atomic_inc(&pi_state->refcount);
503 *ps = pi_state;
505 return 0;
510 * We are the first waiter - try to look up the real owner and attach
511 * the new pi_state to it, but bail out when TID = 0
513 if (!pid)
514 return -ESRCH;
515 p = futex_find_get_task(pid);
516 if (IS_ERR(p))
517 return PTR_ERR(p);
520 * We need to look at the task state flags to figure out,
521 * whether the task is exiting. To protect against the do_exit
522 * change of the task flags, we do this protected by
523 * p->pi_lock:
525 spin_lock_irq(&p->pi_lock);
526 if (unlikely(p->flags & PF_EXITING)) {
528 * The task is on the way out. When PF_EXITPIDONE is
529 * set, we know that the task has finished the
530 * cleanup:
532 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
534 spin_unlock_irq(&p->pi_lock);
535 put_task_struct(p);
536 return ret;
539 pi_state = alloc_pi_state();
542 * Initialize the pi_mutex in locked state and make 'p'
543 * the owner of it:
545 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
547 /* Store the key for possible exit cleanups: */
548 pi_state->key = *key;
550 WARN_ON(!list_empty(&pi_state->list));
551 list_add(&pi_state->list, &p->pi_state_list);
552 pi_state->owner = p;
553 spin_unlock_irq(&p->pi_lock);
555 put_task_struct(p);
557 *ps = pi_state;
559 return 0;
563 * The hash bucket lock must be held when this is called.
564 * Afterwards, the futex_q must not be accessed.
566 static void wake_futex(struct futex_q *q)
568 plist_del(&q->list, &q->list.plist);
570 * The lock in wake_up_all() is a crucial memory barrier after the
571 * plist_del() and also before assigning to q->lock_ptr.
573 wake_up(&q->waiter);
575 * The waiting task can free the futex_q as soon as this is written,
576 * without taking any locks. This must come last.
578 * A memory barrier is required here to prevent the following store to
579 * lock_ptr from getting ahead of the wakeup. Clearing the lock at the
580 * end of wake_up() does not prevent this store from moving.
582 smp_wmb();
583 q->lock_ptr = NULL;
586 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
588 struct task_struct *new_owner;
589 struct futex_pi_state *pi_state = this->pi_state;
590 u32 curval, newval;
592 if (!pi_state)
593 return -EINVAL;
595 spin_lock(&pi_state->pi_mutex.wait_lock);
596 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
599 * This happens when we have stolen the lock and the original
600 * pending owner did not enqueue itself back on the rt_mutex.
601 * Thats not a tragedy. We know that way, that a lock waiter
602 * is on the fly. We make the futex_q waiter the pending owner.
604 if (!new_owner)
605 new_owner = this->task;
608 * We pass it to the next owner. (The WAITERS bit is always
609 * kept enabled while there is PI state around. We must also
610 * preserve the owner died bit.)
612 if (!(uval & FUTEX_OWNER_DIED)) {
613 int ret = 0;
615 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
617 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
619 if (curval == -EFAULT)
620 ret = -EFAULT;
621 else if (curval != uval)
622 ret = -EINVAL;
623 if (ret) {
624 spin_unlock(&pi_state->pi_mutex.wait_lock);
625 return ret;
629 spin_lock_irq(&pi_state->owner->pi_lock);
630 WARN_ON(list_empty(&pi_state->list));
631 list_del_init(&pi_state->list);
632 spin_unlock_irq(&pi_state->owner->pi_lock);
634 spin_lock_irq(&new_owner->pi_lock);
635 WARN_ON(!list_empty(&pi_state->list));
636 list_add(&pi_state->list, &new_owner->pi_state_list);
637 pi_state->owner = new_owner;
638 spin_unlock_irq(&new_owner->pi_lock);
640 spin_unlock(&pi_state->pi_mutex.wait_lock);
641 rt_mutex_unlock(&pi_state->pi_mutex);
643 return 0;
646 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
648 u32 oldval;
651 * There is no waiter, so we unlock the futex. The owner died
652 * bit has not to be preserved here. We are the owner:
654 oldval = cmpxchg_futex_value_locked(uaddr, uval, 0);
656 if (oldval == -EFAULT)
657 return oldval;
658 if (oldval != uval)
659 return -EAGAIN;
661 return 0;
665 * Express the locking dependencies for lockdep:
667 static inline void
668 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
670 if (hb1 <= hb2) {
671 spin_lock(&hb1->lock);
672 if (hb1 < hb2)
673 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
674 } else { /* hb1 > hb2 */
675 spin_lock(&hb2->lock);
676 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
680 static inline void
681 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
683 spin_unlock(&hb1->lock);
684 if (hb1 != hb2)
685 spin_unlock(&hb2->lock);
689 * Wake up waiters matching bitset queued on this futex (uaddr).
691 static int futex_wake(u32 __user *uaddr, int fshared, int nr_wake, u32 bitset)
693 struct futex_hash_bucket *hb;
694 struct futex_q *this, *next;
695 struct plist_head *head;
696 union futex_key key = FUTEX_KEY_INIT;
697 int ret;
699 if (!bitset)
700 return -EINVAL;
702 ret = get_futex_key(uaddr, fshared, &key, VERIFY_READ);
703 if (unlikely(ret != 0))
704 goto out;
706 hb = hash_futex(&key);
707 spin_lock(&hb->lock);
708 head = &hb->chain;
710 plist_for_each_entry_safe(this, next, head, list) {
711 if (match_futex (&this->key, &key)) {
712 if (this->pi_state) {
713 ret = -EINVAL;
714 break;
717 /* Check if one of the bits is set in both bitsets */
718 if (!(this->bitset & bitset))
719 continue;
721 wake_futex(this);
722 if (++ret >= nr_wake)
723 break;
727 spin_unlock(&hb->lock);
728 put_futex_key(fshared, &key);
729 out:
730 return ret;
734 * Wake up all waiters hashed on the physical page that is mapped
735 * to this virtual address:
737 static int
738 futex_wake_op(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
739 int nr_wake, int nr_wake2, int op)
741 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
742 struct futex_hash_bucket *hb1, *hb2;
743 struct plist_head *head;
744 struct futex_q *this, *next;
745 int ret, op_ret;
747 retry:
748 ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
749 if (unlikely(ret != 0))
750 goto out;
751 ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_WRITE);
752 if (unlikely(ret != 0))
753 goto out_put_key1;
755 hb1 = hash_futex(&key1);
756 hb2 = hash_futex(&key2);
758 double_lock_hb(hb1, hb2);
759 retry_private:
760 op_ret = futex_atomic_op_inuser(op, uaddr2);
761 if (unlikely(op_ret < 0)) {
763 double_unlock_hb(hb1, hb2);
765 #ifndef CONFIG_MMU
767 * we don't get EFAULT from MMU faults if we don't have an MMU,
768 * but we might get them from range checking
770 ret = op_ret;
771 goto out_put_keys;
772 #endif
774 if (unlikely(op_ret != -EFAULT)) {
775 ret = op_ret;
776 goto out_put_keys;
779 ret = fault_in_user_writeable(uaddr2);
780 if (ret)
781 goto out_put_keys;
783 if (!fshared)
784 goto retry_private;
786 put_futex_key(fshared, &key2);
787 put_futex_key(fshared, &key1);
788 goto retry;
791 head = &hb1->chain;
793 plist_for_each_entry_safe(this, next, head, list) {
794 if (match_futex (&this->key, &key1)) {
795 wake_futex(this);
796 if (++ret >= nr_wake)
797 break;
801 if (op_ret > 0) {
802 head = &hb2->chain;
804 op_ret = 0;
805 plist_for_each_entry_safe(this, next, head, list) {
806 if (match_futex (&this->key, &key2)) {
807 wake_futex(this);
808 if (++op_ret >= nr_wake2)
809 break;
812 ret += op_ret;
815 double_unlock_hb(hb1, hb2);
816 out_put_keys:
817 put_futex_key(fshared, &key2);
818 out_put_key1:
819 put_futex_key(fshared, &key1);
820 out:
821 return ret;
825 * Requeue all waiters hashed on one physical page to another
826 * physical page.
828 static int futex_requeue(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
829 int nr_wake, int nr_requeue, u32 *cmpval)
831 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
832 struct futex_hash_bucket *hb1, *hb2;
833 struct plist_head *head1;
834 struct futex_q *this, *next;
835 int ret, drop_count = 0;
837 retry:
838 ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
839 if (unlikely(ret != 0))
840 goto out;
841 ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_READ);
842 if (unlikely(ret != 0))
843 goto out_put_key1;
845 hb1 = hash_futex(&key1);
846 hb2 = hash_futex(&key2);
848 retry_private:
849 double_lock_hb(hb1, hb2);
851 if (likely(cmpval != NULL)) {
852 u32 curval;
854 ret = get_futex_value_locked(&curval, uaddr1);
856 if (unlikely(ret)) {
857 double_unlock_hb(hb1, hb2);
859 ret = get_user(curval, uaddr1);
860 if (ret)
861 goto out_put_keys;
863 if (!fshared)
864 goto retry_private;
866 put_futex_key(fshared, &key2);
867 put_futex_key(fshared, &key1);
868 goto retry;
870 if (curval != *cmpval) {
871 ret = -EAGAIN;
872 goto out_unlock;
876 head1 = &hb1->chain;
877 plist_for_each_entry_safe(this, next, head1, list) {
878 if (!match_futex (&this->key, &key1))
879 continue;
880 if (++ret <= nr_wake) {
881 wake_futex(this);
882 } else {
884 * If key1 and key2 hash to the same bucket, no need to
885 * requeue.
887 if (likely(head1 != &hb2->chain)) {
888 plist_del(&this->list, &hb1->chain);
889 plist_add(&this->list, &hb2->chain);
890 this->lock_ptr = &hb2->lock;
891 #ifdef CONFIG_DEBUG_PI_LIST
892 this->list.plist.lock = &hb2->lock;
893 #endif
895 this->key = key2;
896 get_futex_key_refs(&key2);
897 drop_count++;
899 if (ret - nr_wake >= nr_requeue)
900 break;
904 out_unlock:
905 double_unlock_hb(hb1, hb2);
908 * drop_futex_key_refs() must be called outside the spinlocks. During
909 * the requeue we moved futex_q's from the hash bucket at key1 to the
910 * one at key2 and updated their key pointer. We no longer need to
911 * hold the references to key1.
913 while (--drop_count >= 0)
914 drop_futex_key_refs(&key1);
916 out_put_keys:
917 put_futex_key(fshared, &key2);
918 out_put_key1:
919 put_futex_key(fshared, &key1);
920 out:
921 return ret;
924 /* The key must be already stored in q->key. */
925 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
927 struct futex_hash_bucket *hb;
929 init_waitqueue_head(&q->waiter);
931 get_futex_key_refs(&q->key);
932 hb = hash_futex(&q->key);
933 q->lock_ptr = &hb->lock;
935 spin_lock(&hb->lock);
936 return hb;
939 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
941 int prio;
944 * The priority used to register this element is
945 * - either the real thread-priority for the real-time threads
946 * (i.e. threads with a priority lower than MAX_RT_PRIO)
947 * - or MAX_RT_PRIO for non-RT threads.
948 * Thus, all RT-threads are woken first in priority order, and
949 * the others are woken last, in FIFO order.
951 prio = min(current->normal_prio, MAX_RT_PRIO);
953 plist_node_init(&q->list, prio);
954 #ifdef CONFIG_DEBUG_PI_LIST
955 q->list.plist.lock = &hb->lock;
956 #endif
957 plist_add(&q->list, &hb->chain);
958 q->task = current;
959 spin_unlock(&hb->lock);
962 static inline void
963 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
965 spin_unlock(&hb->lock);
966 drop_futex_key_refs(&q->key);
970 * queue_me and unqueue_me must be called as a pair, each
971 * exactly once. They are called with the hashed spinlock held.
974 /* Return 1 if we were still queued (ie. 0 means we were woken) */
975 static int unqueue_me(struct futex_q *q)
977 spinlock_t *lock_ptr;
978 int ret = 0;
980 /* In the common case we don't take the spinlock, which is nice. */
981 retry:
982 lock_ptr = q->lock_ptr;
983 barrier();
984 if (lock_ptr != NULL) {
985 spin_lock(lock_ptr);
987 * q->lock_ptr can change between reading it and
988 * spin_lock(), causing us to take the wrong lock. This
989 * corrects the race condition.
991 * Reasoning goes like this: if we have the wrong lock,
992 * q->lock_ptr must have changed (maybe several times)
993 * between reading it and the spin_lock(). It can
994 * change again after the spin_lock() but only if it was
995 * already changed before the spin_lock(). It cannot,
996 * however, change back to the original value. Therefore
997 * we can detect whether we acquired the correct lock.
999 if (unlikely(lock_ptr != q->lock_ptr)) {
1000 spin_unlock(lock_ptr);
1001 goto retry;
1003 WARN_ON(plist_node_empty(&q->list));
1004 plist_del(&q->list, &q->list.plist);
1006 BUG_ON(q->pi_state);
1008 spin_unlock(lock_ptr);
1009 ret = 1;
1012 drop_futex_key_refs(&q->key);
1013 return ret;
1017 * PI futexes can not be requeued and must remove themself from the
1018 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1019 * and dropped here.
1021 static void unqueue_me_pi(struct futex_q *q)
1023 WARN_ON(plist_node_empty(&q->list));
1024 plist_del(&q->list, &q->list.plist);
1026 BUG_ON(!q->pi_state);
1027 free_pi_state(q->pi_state);
1028 q->pi_state = NULL;
1030 spin_unlock(q->lock_ptr);
1032 drop_futex_key_refs(&q->key);
1036 * Fixup the pi_state owner with the new owner.
1038 * Must be called with hash bucket lock held and mm->sem held for non
1039 * private futexes.
1041 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
1042 struct task_struct *newowner, int fshared)
1044 u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
1045 struct futex_pi_state *pi_state = q->pi_state;
1046 struct task_struct *oldowner = pi_state->owner;
1047 u32 uval, curval, newval;
1048 int ret;
1050 /* Owner died? */
1051 if (!pi_state->owner)
1052 newtid |= FUTEX_OWNER_DIED;
1055 * We are here either because we stole the rtmutex from the
1056 * pending owner or we are the pending owner which failed to
1057 * get the rtmutex. We have to replace the pending owner TID
1058 * in the user space variable. This must be atomic as we have
1059 * to preserve the owner died bit here.
1061 * Note: We write the user space value _before_ changing the pi_state
1062 * because we can fault here. Imagine swapped out pages or a fork
1063 * that marked all the anonymous memory readonly for cow.
1065 * Modifying pi_state _before_ the user space value would
1066 * leave the pi_state in an inconsistent state when we fault
1067 * here, because we need to drop the hash bucket lock to
1068 * handle the fault. This might be observed in the PID check
1069 * in lookup_pi_state.
1071 retry:
1072 if (get_futex_value_locked(&uval, uaddr))
1073 goto handle_fault;
1075 while (1) {
1076 newval = (uval & FUTEX_OWNER_DIED) | newtid;
1078 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1080 if (curval == -EFAULT)
1081 goto handle_fault;
1082 if (curval == uval)
1083 break;
1084 uval = curval;
1088 * We fixed up user space. Now we need to fix the pi_state
1089 * itself.
1091 if (pi_state->owner != NULL) {
1092 spin_lock_irq(&pi_state->owner->pi_lock);
1093 WARN_ON(list_empty(&pi_state->list));
1094 list_del_init(&pi_state->list);
1095 spin_unlock_irq(&pi_state->owner->pi_lock);
1098 pi_state->owner = newowner;
1100 spin_lock_irq(&newowner->pi_lock);
1101 WARN_ON(!list_empty(&pi_state->list));
1102 list_add(&pi_state->list, &newowner->pi_state_list);
1103 spin_unlock_irq(&newowner->pi_lock);
1104 return 0;
1107 * To handle the page fault we need to drop the hash bucket
1108 * lock here. That gives the other task (either the pending
1109 * owner itself or the task which stole the rtmutex) the
1110 * chance to try the fixup of the pi_state. So once we are
1111 * back from handling the fault we need to check the pi_state
1112 * after reacquiring the hash bucket lock and before trying to
1113 * do another fixup. When the fixup has been done already we
1114 * simply return.
1116 handle_fault:
1117 spin_unlock(q->lock_ptr);
1119 ret = fault_in_user_writeable(uaddr);
1121 spin_lock(q->lock_ptr);
1124 * Check if someone else fixed it for us:
1126 if (pi_state->owner != oldowner)
1127 return 0;
1129 if (ret)
1130 return ret;
1132 goto retry;
1136 * In case we must use restart_block to restart a futex_wait,
1137 * we encode in the 'flags' shared capability
1139 #define FLAGS_SHARED 0x01
1140 #define FLAGS_CLOCKRT 0x02
1142 static long futex_wait_restart(struct restart_block *restart);
1144 static int futex_wait(u32 __user *uaddr, int fshared,
1145 u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
1147 struct task_struct *curr = current;
1148 struct restart_block *restart;
1149 DECLARE_WAITQUEUE(wait, curr);
1150 struct futex_hash_bucket *hb;
1151 struct futex_q q;
1152 u32 uval;
1153 int ret;
1154 struct hrtimer_sleeper t;
1155 int rem = 0;
1157 if (!bitset)
1158 return -EINVAL;
1160 q.pi_state = NULL;
1161 q.bitset = bitset;
1162 retry:
1163 q.key = FUTEX_KEY_INIT;
1164 ret = get_futex_key(uaddr, fshared, &q.key, VERIFY_READ);
1165 if (unlikely(ret != 0))
1166 goto out;
1168 retry_private:
1169 hb = queue_lock(&q);
1172 * Access the page AFTER the hash-bucket is locked.
1173 * Order is important:
1175 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1176 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
1178 * The basic logical guarantee of a futex is that it blocks ONLY
1179 * if cond(var) is known to be true at the time of blocking, for
1180 * any cond. If we queued after testing *uaddr, that would open
1181 * a race condition where we could block indefinitely with
1182 * cond(var) false, which would violate the guarantee.
1184 * A consequence is that futex_wait() can return zero and absorb
1185 * a wakeup when *uaddr != val on entry to the syscall. This is
1186 * rare, but normal.
1188 * For shared futexes, we hold the mmap semaphore, so the mapping
1189 * cannot have changed since we looked it up in get_futex_key.
1191 ret = get_futex_value_locked(&uval, uaddr);
1193 if (unlikely(ret)) {
1194 queue_unlock(&q, hb);
1196 ret = get_user(uval, uaddr);
1197 if (ret)
1198 goto out_put_key;
1200 if (!fshared)
1201 goto retry_private;
1203 put_futex_key(fshared, &q.key);
1204 goto retry;
1206 ret = -EWOULDBLOCK;
1207 if (unlikely(uval != val)) {
1208 queue_unlock(&q, hb);
1209 goto out_put_key;
1212 /* Only actually queue if *uaddr contained val. */
1213 queue_me(&q, hb);
1216 * There might have been scheduling since the queue_me(), as we
1217 * cannot hold a spinlock across the get_user() in case it
1218 * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1219 * queueing ourselves into the futex hash. This code thus has to
1220 * rely on the futex_wake() code removing us from hash when it
1221 * wakes us up.
1224 /* add_wait_queue is the barrier after __set_current_state. */
1225 __set_current_state(TASK_INTERRUPTIBLE);
1226 add_wait_queue(&q.waiter, &wait);
1228 * !plist_node_empty() is safe here without any lock.
1229 * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1231 if (likely(!plist_node_empty(&q.list))) {
1232 if (!abs_time)
1233 schedule();
1234 else {
1235 hrtimer_init_on_stack(&t.timer,
1236 clockrt ? CLOCK_REALTIME :
1237 CLOCK_MONOTONIC,
1238 HRTIMER_MODE_ABS);
1239 hrtimer_init_sleeper(&t, current);
1240 hrtimer_set_expires_range_ns(&t.timer, *abs_time,
1241 current->timer_slack_ns);
1243 hrtimer_start_expires(&t.timer, HRTIMER_MODE_ABS);
1244 if (!hrtimer_active(&t.timer))
1245 t.task = NULL;
1248 * the timer could have already expired, in which
1249 * case current would be flagged for rescheduling.
1250 * Don't bother calling schedule.
1252 if (likely(t.task))
1253 schedule();
1255 hrtimer_cancel(&t.timer);
1257 /* Flag if a timeout occured */
1258 rem = (t.task == NULL);
1260 destroy_hrtimer_on_stack(&t.timer);
1263 __set_current_state(TASK_RUNNING);
1266 * NOTE: we don't remove ourselves from the waitqueue because
1267 * we are the only user of it.
1270 /* If we were woken (and unqueued), we succeeded, whatever. */
1271 ret = 0;
1272 if (!unqueue_me(&q))
1273 goto out_put_key;
1274 ret = -ETIMEDOUT;
1275 if (rem)
1276 goto out_put_key;
1279 * We expect signal_pending(current), but another thread may
1280 * have handled it for us already.
1282 ret = -ERESTARTSYS;
1283 if (!abs_time)
1284 goto out_put_key;
1286 restart = &current_thread_info()->restart_block;
1287 restart->fn = futex_wait_restart;
1288 restart->futex.uaddr = (u32 *)uaddr;
1289 restart->futex.val = val;
1290 restart->futex.time = abs_time->tv64;
1291 restart->futex.bitset = bitset;
1292 restart->futex.flags = 0;
1294 if (fshared)
1295 restart->futex.flags |= FLAGS_SHARED;
1296 if (clockrt)
1297 restart->futex.flags |= FLAGS_CLOCKRT;
1299 ret = -ERESTART_RESTARTBLOCK;
1301 out_put_key:
1302 put_futex_key(fshared, &q.key);
1303 out:
1304 return ret;
1308 static long futex_wait_restart(struct restart_block *restart)
1310 u32 __user *uaddr = (u32 __user *)restart->futex.uaddr;
1311 int fshared = 0;
1312 ktime_t t;
1314 t.tv64 = restart->futex.time;
1315 restart->fn = do_no_restart_syscall;
1316 if (restart->futex.flags & FLAGS_SHARED)
1317 fshared = 1;
1318 return (long)futex_wait(uaddr, fshared, restart->futex.val, &t,
1319 restart->futex.bitset,
1320 restart->futex.flags & FLAGS_CLOCKRT);
1325 * Userspace tried a 0 -> TID atomic transition of the futex value
1326 * and failed. The kernel side here does the whole locking operation:
1327 * if there are waiters then it will block, it does PI, etc. (Due to
1328 * races the kernel might see a 0 value of the futex too.)
1330 static int futex_lock_pi(u32 __user *uaddr, int fshared,
1331 int detect, ktime_t *time, int trylock)
1333 struct hrtimer_sleeper timeout, *to = NULL;
1334 struct task_struct *curr = current;
1335 struct futex_hash_bucket *hb;
1336 u32 uval, newval, curval;
1337 struct futex_q q;
1338 int ret, lock_taken, ownerdied = 0;
1340 if (refill_pi_state_cache())
1341 return -ENOMEM;
1343 if (time) {
1344 to = &timeout;
1345 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
1346 HRTIMER_MODE_ABS);
1347 hrtimer_init_sleeper(to, current);
1348 hrtimer_set_expires(&to->timer, *time);
1351 q.pi_state = NULL;
1352 retry:
1353 q.key = FUTEX_KEY_INIT;
1354 ret = get_futex_key(uaddr, fshared, &q.key, VERIFY_WRITE);
1355 if (unlikely(ret != 0))
1356 goto out;
1358 retry_private:
1359 hb = queue_lock(&q);
1361 retry_locked:
1362 ret = lock_taken = 0;
1365 * To avoid races, we attempt to take the lock here again
1366 * (by doing a 0 -> TID atomic cmpxchg), while holding all
1367 * the locks. It will most likely not succeed.
1369 newval = task_pid_vnr(current);
1371 curval = cmpxchg_futex_value_locked(uaddr, 0, newval);
1373 if (unlikely(curval == -EFAULT))
1374 goto uaddr_faulted;
1377 * Detect deadlocks. In case of REQUEUE_PI this is a valid
1378 * situation and we return success to user space.
1380 if (unlikely((curval & FUTEX_TID_MASK) == task_pid_vnr(current))) {
1381 ret = -EDEADLK;
1382 goto out_unlock_put_key;
1386 * Surprise - we got the lock. Just return to userspace:
1388 if (unlikely(!curval))
1389 goto out_unlock_put_key;
1391 uval = curval;
1394 * Set the WAITERS flag, so the owner will know it has someone
1395 * to wake at next unlock
1397 newval = curval | FUTEX_WAITERS;
1400 * There are two cases, where a futex might have no owner (the
1401 * owner TID is 0): OWNER_DIED. We take over the futex in this
1402 * case. We also do an unconditional take over, when the owner
1403 * of the futex died.
1405 * This is safe as we are protected by the hash bucket lock !
1407 if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) {
1408 /* Keep the OWNER_DIED bit */
1409 newval = (curval & ~FUTEX_TID_MASK) | task_pid_vnr(current);
1410 ownerdied = 0;
1411 lock_taken = 1;
1414 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1416 if (unlikely(curval == -EFAULT))
1417 goto uaddr_faulted;
1418 if (unlikely(curval != uval))
1419 goto retry_locked;
1422 * We took the lock due to owner died take over.
1424 if (unlikely(lock_taken))
1425 goto out_unlock_put_key;
1428 * We dont have the lock. Look up the PI state (or create it if
1429 * we are the first waiter):
1431 ret = lookup_pi_state(uval, hb, &q.key, &q.pi_state);
1433 if (unlikely(ret)) {
1434 switch (ret) {
1436 case -EAGAIN:
1438 * Task is exiting and we just wait for the
1439 * exit to complete.
1441 queue_unlock(&q, hb);
1442 put_futex_key(fshared, &q.key);
1443 cond_resched();
1444 goto retry;
1446 case -ESRCH:
1448 * No owner found for this futex. Check if the
1449 * OWNER_DIED bit is set to figure out whether
1450 * this is a robust futex or not.
1452 if (get_futex_value_locked(&curval, uaddr))
1453 goto uaddr_faulted;
1456 * We simply start over in case of a robust
1457 * futex. The code above will take the futex
1458 * and return happy.
1460 if (curval & FUTEX_OWNER_DIED) {
1461 ownerdied = 1;
1462 goto retry_locked;
1464 default:
1465 goto out_unlock_put_key;
1470 * Only actually queue now that the atomic ops are done:
1472 queue_me(&q, hb);
1474 WARN_ON(!q.pi_state);
1476 * Block on the PI mutex:
1478 if (!trylock)
1479 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1480 else {
1481 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1482 /* Fixup the trylock return value: */
1483 ret = ret ? 0 : -EWOULDBLOCK;
1486 spin_lock(q.lock_ptr);
1488 if (!ret) {
1490 * Got the lock. We might not be the anticipated owner
1491 * if we did a lock-steal - fix up the PI-state in
1492 * that case:
1494 if (q.pi_state->owner != curr)
1495 ret = fixup_pi_state_owner(uaddr, &q, curr, fshared);
1496 } else {
1498 * Catch the rare case, where the lock was released
1499 * when we were on the way back before we locked the
1500 * hash bucket.
1502 if (q.pi_state->owner == curr) {
1504 * Try to get the rt_mutex now. This might
1505 * fail as some other task acquired the
1506 * rt_mutex after we removed ourself from the
1507 * rt_mutex waiters list.
1509 if (rt_mutex_trylock(&q.pi_state->pi_mutex))
1510 ret = 0;
1511 else {
1513 * pi_state is incorrect, some other
1514 * task did a lock steal and we
1515 * returned due to timeout or signal
1516 * without taking the rt_mutex. Too
1517 * late. We can access the
1518 * rt_mutex_owner without locking, as
1519 * the other task is now blocked on
1520 * the hash bucket lock. Fix the state
1521 * up.
1523 struct task_struct *owner;
1524 int res;
1526 owner = rt_mutex_owner(&q.pi_state->pi_mutex);
1527 res = fixup_pi_state_owner(uaddr, &q, owner,
1528 fshared);
1530 /* propagate -EFAULT, if the fixup failed */
1531 if (res)
1532 ret = res;
1534 } else {
1536 * Paranoia check. If we did not take the lock
1537 * in the trylock above, then we should not be
1538 * the owner of the rtmutex, neither the real
1539 * nor the pending one:
1541 if (rt_mutex_owner(&q.pi_state->pi_mutex) == curr)
1542 printk(KERN_ERR "futex_lock_pi: ret = %d "
1543 "pi-mutex: %p pi-state %p\n", ret,
1544 q.pi_state->pi_mutex.owner,
1545 q.pi_state->owner);
1550 * If fixup_pi_state_owner() faulted and was unable to handle the
1551 * fault, unlock it and return the fault to userspace.
1553 if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
1554 rt_mutex_unlock(&q.pi_state->pi_mutex);
1556 /* Unqueue and drop the lock */
1557 unqueue_me_pi(&q);
1559 if (to)
1560 destroy_hrtimer_on_stack(&to->timer);
1561 return ret != -EINTR ? ret : -ERESTARTNOINTR;
1563 out_unlock_put_key:
1564 queue_unlock(&q, hb);
1566 out_put_key:
1567 put_futex_key(fshared, &q.key);
1568 out:
1569 if (to)
1570 destroy_hrtimer_on_stack(&to->timer);
1571 return ret;
1573 uaddr_faulted:
1574 queue_unlock(&q, hb);
1576 ret = fault_in_user_writeable(uaddr);
1577 if (ret)
1578 goto out_put_key;
1580 if (!fshared)
1581 goto retry_private;
1583 put_futex_key(fshared, &q.key);
1584 goto retry;
1589 * Userspace attempted a TID -> 0 atomic transition, and failed.
1590 * This is the in-kernel slowpath: we look up the PI state (if any),
1591 * and do the rt-mutex unlock.
1593 static int futex_unlock_pi(u32 __user *uaddr, int fshared)
1595 struct futex_hash_bucket *hb;
1596 struct futex_q *this, *next;
1597 u32 uval;
1598 struct plist_head *head;
1599 union futex_key key = FUTEX_KEY_INIT;
1600 int ret;
1602 retry:
1603 if (get_user(uval, uaddr))
1604 return -EFAULT;
1606 * We release only a lock we actually own:
1608 if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current))
1609 return -EPERM;
1611 ret = get_futex_key(uaddr, fshared, &key, VERIFY_WRITE);
1612 if (unlikely(ret != 0))
1613 goto out;
1615 hb = hash_futex(&key);
1616 spin_lock(&hb->lock);
1619 * To avoid races, try to do the TID -> 0 atomic transition
1620 * again. If it succeeds then we can return without waking
1621 * anyone else up:
1623 if (!(uval & FUTEX_OWNER_DIED))
1624 uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0);
1627 if (unlikely(uval == -EFAULT))
1628 goto pi_faulted;
1630 * Rare case: we managed to release the lock atomically,
1631 * no need to wake anyone else up:
1633 if (unlikely(uval == task_pid_vnr(current)))
1634 goto out_unlock;
1637 * Ok, other tasks may need to be woken up - check waiters
1638 * and do the wakeup if necessary:
1640 head = &hb->chain;
1642 plist_for_each_entry_safe(this, next, head, list) {
1643 if (!match_futex (&this->key, &key))
1644 continue;
1645 ret = wake_futex_pi(uaddr, uval, this);
1647 * The atomic access to the futex value
1648 * generated a pagefault, so retry the
1649 * user-access and the wakeup:
1651 if (ret == -EFAULT)
1652 goto pi_faulted;
1653 goto out_unlock;
1656 * No waiters - kernel unlocks the futex:
1658 if (!(uval & FUTEX_OWNER_DIED)) {
1659 ret = unlock_futex_pi(uaddr, uval);
1660 if (ret == -EFAULT)
1661 goto pi_faulted;
1664 out_unlock:
1665 spin_unlock(&hb->lock);
1666 put_futex_key(fshared, &key);
1668 out:
1669 return ret;
1671 pi_faulted:
1672 spin_unlock(&hb->lock);
1673 put_futex_key(fshared, &key);
1675 ret = fault_in_user_writeable(uaddr);
1676 if (!ret)
1677 goto retry;
1679 return ret;
1683 * Support for robust futexes: the kernel cleans up held futexes at
1684 * thread exit time.
1686 * Implementation: user-space maintains a per-thread list of locks it
1687 * is holding. Upon do_exit(), the kernel carefully walks this list,
1688 * and marks all locks that are owned by this thread with the
1689 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
1690 * always manipulated with the lock held, so the list is private and
1691 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
1692 * field, to allow the kernel to clean up if the thread dies after
1693 * acquiring the lock, but just before it could have added itself to
1694 * the list. There can only be one such pending lock.
1698 * sys_set_robust_list - set the robust-futex list head of a task
1699 * @head: pointer to the list-head
1700 * @len: length of the list-head, as userspace expects
1702 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
1703 size_t, len)
1705 if (!futex_cmpxchg_enabled)
1706 return -ENOSYS;
1708 * The kernel knows only one size for now:
1710 if (unlikely(len != sizeof(*head)))
1711 return -EINVAL;
1713 current->robust_list = head;
1715 return 0;
1719 * sys_get_robust_list - get the robust-futex list head of a task
1720 * @pid: pid of the process [zero for current task]
1721 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
1722 * @len_ptr: pointer to a length field, the kernel fills in the header size
1724 SYSCALL_DEFINE3(get_robust_list, int, pid,
1725 struct robust_list_head __user * __user *, head_ptr,
1726 size_t __user *, len_ptr)
1728 struct robust_list_head __user *head;
1729 unsigned long ret;
1730 const struct cred *cred = current_cred(), *pcred;
1732 if (!futex_cmpxchg_enabled)
1733 return -ENOSYS;
1735 if (!pid)
1736 head = current->robust_list;
1737 else {
1738 struct task_struct *p;
1740 ret = -ESRCH;
1741 rcu_read_lock();
1742 p = find_task_by_vpid(pid);
1743 if (!p)
1744 goto err_unlock;
1745 ret = -EPERM;
1746 pcred = __task_cred(p);
1747 if (cred->euid != pcred->euid &&
1748 cred->euid != pcred->uid &&
1749 !capable(CAP_SYS_PTRACE))
1750 goto err_unlock;
1751 head = p->robust_list;
1752 rcu_read_unlock();
1755 if (put_user(sizeof(*head), len_ptr))
1756 return -EFAULT;
1757 return put_user(head, head_ptr);
1759 err_unlock:
1760 rcu_read_unlock();
1762 return ret;
1766 * Process a futex-list entry, check whether it's owned by the
1767 * dying task, and do notification if so:
1769 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
1771 u32 uval, nval, mval;
1773 retry:
1774 if (get_user(uval, uaddr))
1775 return -1;
1777 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
1779 * Ok, this dying thread is truly holding a futex
1780 * of interest. Set the OWNER_DIED bit atomically
1781 * via cmpxchg, and if the value had FUTEX_WAITERS
1782 * set, wake up a waiter (if any). (We have to do a
1783 * futex_wake() even if OWNER_DIED is already set -
1784 * to handle the rare but possible case of recursive
1785 * thread-death.) The rest of the cleanup is done in
1786 * userspace.
1788 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
1789 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
1791 if (nval == -EFAULT)
1792 return -1;
1794 if (nval != uval)
1795 goto retry;
1798 * Wake robust non-PI futexes here. The wakeup of
1799 * PI futexes happens in exit_pi_state():
1801 if (!pi && (uval & FUTEX_WAITERS))
1802 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
1804 return 0;
1808 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
1810 static inline int fetch_robust_entry(struct robust_list __user **entry,
1811 struct robust_list __user * __user *head,
1812 int *pi)
1814 unsigned long uentry;
1816 if (get_user(uentry, (unsigned long __user *)head))
1817 return -EFAULT;
1819 *entry = (void __user *)(uentry & ~1UL);
1820 *pi = uentry & 1;
1822 return 0;
1826 * Walk curr->robust_list (very carefully, it's a userspace list!)
1827 * and mark any locks found there dead, and notify any waiters.
1829 * We silently return on any sign of list-walking problem.
1831 void exit_robust_list(struct task_struct *curr)
1833 struct robust_list_head __user *head = curr->robust_list;
1834 struct robust_list __user *entry, *next_entry, *pending;
1835 unsigned int limit = ROBUST_LIST_LIMIT, pi, next_pi, pip;
1836 unsigned long futex_offset;
1837 int rc;
1839 if (!futex_cmpxchg_enabled)
1840 return;
1843 * Fetch the list head (which was registered earlier, via
1844 * sys_set_robust_list()):
1846 if (fetch_robust_entry(&entry, &head->list.next, &pi))
1847 return;
1849 * Fetch the relative futex offset:
1851 if (get_user(futex_offset, &head->futex_offset))
1852 return;
1854 * Fetch any possibly pending lock-add first, and handle it
1855 * if it exists:
1857 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
1858 return;
1860 next_entry = NULL; /* avoid warning with gcc */
1861 while (entry != &head->list) {
1863 * Fetch the next entry in the list before calling
1864 * handle_futex_death:
1866 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
1868 * A pending lock might already be on the list, so
1869 * don't process it twice:
1871 if (entry != pending)
1872 if (handle_futex_death((void __user *)entry + futex_offset,
1873 curr, pi))
1874 return;
1875 if (rc)
1876 return;
1877 entry = next_entry;
1878 pi = next_pi;
1880 * Avoid excessively long or circular lists:
1882 if (!--limit)
1883 break;
1885 cond_resched();
1888 if (pending)
1889 handle_futex_death((void __user *)pending + futex_offset,
1890 curr, pip);
1893 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
1894 u32 __user *uaddr2, u32 val2, u32 val3)
1896 int clockrt, ret = -ENOSYS;
1897 int cmd = op & FUTEX_CMD_MASK;
1898 int fshared = 0;
1900 if (!(op & FUTEX_PRIVATE_FLAG))
1901 fshared = 1;
1903 clockrt = op & FUTEX_CLOCK_REALTIME;
1904 if (clockrt && cmd != FUTEX_WAIT_BITSET)
1905 return -ENOSYS;
1907 switch (cmd) {
1908 case FUTEX_WAIT:
1909 val3 = FUTEX_BITSET_MATCH_ANY;
1910 case FUTEX_WAIT_BITSET:
1911 ret = futex_wait(uaddr, fshared, val, timeout, val3, clockrt);
1912 break;
1913 case FUTEX_WAKE:
1914 val3 = FUTEX_BITSET_MATCH_ANY;
1915 case FUTEX_WAKE_BITSET:
1916 ret = futex_wake(uaddr, fshared, val, val3);
1917 break;
1918 case FUTEX_REQUEUE:
1919 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL);
1920 break;
1921 case FUTEX_CMP_REQUEUE:
1922 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3);
1923 break;
1924 case FUTEX_WAKE_OP:
1925 ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3);
1926 break;
1927 case FUTEX_LOCK_PI:
1928 if (futex_cmpxchg_enabled)
1929 ret = futex_lock_pi(uaddr, fshared, val, timeout, 0);
1930 break;
1931 case FUTEX_UNLOCK_PI:
1932 if (futex_cmpxchg_enabled)
1933 ret = futex_unlock_pi(uaddr, fshared);
1934 break;
1935 case FUTEX_TRYLOCK_PI:
1936 if (futex_cmpxchg_enabled)
1937 ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1);
1938 break;
1939 default:
1940 ret = -ENOSYS;
1942 return ret;
1946 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
1947 struct timespec __user *, utime, u32 __user *, uaddr2,
1948 u32, val3)
1950 struct timespec ts;
1951 ktime_t t, *tp = NULL;
1952 u32 val2 = 0;
1953 int cmd = op & FUTEX_CMD_MASK;
1955 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
1956 cmd == FUTEX_WAIT_BITSET)) {
1957 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
1958 return -EFAULT;
1959 if (!timespec_valid(&ts))
1960 return -EINVAL;
1962 t = timespec_to_ktime(ts);
1963 if (cmd == FUTEX_WAIT)
1964 t = ktime_add_safe(ktime_get(), t);
1965 tp = &t;
1968 * requeue parameter in 'utime' if cmd == FUTEX_REQUEUE.
1969 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
1971 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
1972 cmd == FUTEX_WAKE_OP)
1973 val2 = (u32) (unsigned long) utime;
1975 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
1978 static int __init futex_init(void)
1980 u32 curval;
1981 int i;
1984 * This will fail and we want it. Some arch implementations do
1985 * runtime detection of the futex_atomic_cmpxchg_inatomic()
1986 * functionality. We want to know that before we call in any
1987 * of the complex code paths. Also we want to prevent
1988 * registration of robust lists in that case. NULL is
1989 * guaranteed to fault and we get -EFAULT on functional
1990 * implementation, the non functional ones will return
1991 * -ENOSYS.
1993 curval = cmpxchg_futex_value_locked(NULL, 0, 0);
1994 if (curval == -EFAULT)
1995 futex_cmpxchg_enabled = 1;
1997 for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
1998 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
1999 spin_lock_init(&futex_queues[i].lock);
2002 return 0;
2004 __initcall(futex_init);