Now it works.
[cbs-scheduler.git] / kernel / futex.c
blob3ddfb89f63a3d2a1c124a6ac670e71f7a9f35f5f
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 * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
23 * Copyright (C) IBM Corporation, 2009
24 * Thanks to Thomas Gleixner for conceptual design and careful reviews.
26 * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
27 * enough at me, Linus for the original (flawed) idea, Matthew
28 * Kirkwood for proof-of-concept implementation.
30 * "The futexes are also cursed."
31 * "But they come in a choice of three flavours!"
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
43 * You should have received a copy of the GNU General Public License
44 * along with this program; if not, write to the Free Software
45 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
47 #include <linux/slab.h>
48 #include <linux/poll.h>
49 #include <linux/fs.h>
50 #include <linux/file.h>
51 #include <linux/jhash.h>
52 #include <linux/init.h>
53 #include <linux/futex.h>
54 #include <linux/mount.h>
55 #include <linux/pagemap.h>
56 #include <linux/syscalls.h>
57 #include <linux/signal.h>
58 #include <linux/module.h>
59 #include <linux/magic.h>
60 #include <linux/pid.h>
61 #include <linux/nsproxy.h>
63 #include <asm/futex.h>
65 #include "rtmutex_common.h"
67 int __read_mostly futex_cmpxchg_enabled;
69 #define FUTEX_HASHBITS (CONFIG_BASE_SMALL ? 4 : 8)
72 * Priority Inheritance state:
74 struct futex_pi_state {
76 * list of 'owned' pi_state instances - these have to be
77 * cleaned up in do_exit() if the task exits prematurely:
79 struct list_head list;
82 * The PI object:
84 struct rt_mutex pi_mutex;
86 struct task_struct *owner;
87 atomic_t refcount;
89 union futex_key key;
93 * We use this hashed waitqueue instead of a normal wait_queue_t, so
94 * we can wake only the relevant ones (hashed queues may be shared).
96 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
97 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
98 * The order of wakup is always to make the first condition true, then
99 * wake up q->waiter, then make the second condition true.
101 struct futex_q {
102 struct plist_node list;
103 /* Waiter reference */
104 struct task_struct *task;
106 /* Which hash list lock to use: */
107 spinlock_t *lock_ptr;
109 /* Key which the futex is hashed on: */
110 union futex_key key;
112 /* Optional priority inheritance state: */
113 struct futex_pi_state *pi_state;
115 /* rt_waiter storage for requeue_pi: */
116 struct rt_mutex_waiter *rt_waiter;
118 /* Bitset for the optional bitmasked wakeup */
119 u32 bitset;
123 * Hash buckets are shared by all the futex_keys that hash to the same
124 * location. Each key may have multiple futex_q structures, one for each task
125 * waiting on a futex.
127 struct futex_hash_bucket {
128 spinlock_t lock;
129 struct plist_head chain;
132 static struct futex_hash_bucket futex_queues[1<<FUTEX_HASHBITS];
135 * We hash on the keys returned from get_futex_key (see below).
137 static struct futex_hash_bucket *hash_futex(union futex_key *key)
139 u32 hash = jhash2((u32*)&key->both.word,
140 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
141 key->both.offset);
142 return &futex_queues[hash & ((1 << FUTEX_HASHBITS)-1)];
146 * Return 1 if two futex_keys are equal, 0 otherwise.
148 static inline int match_futex(union futex_key *key1, union futex_key *key2)
150 return (key1->both.word == key2->both.word
151 && key1->both.ptr == key2->both.ptr
152 && key1->both.offset == key2->both.offset);
156 * Take a reference to the resource addressed by a key.
157 * Can be called while holding spinlocks.
160 static void get_futex_key_refs(union futex_key *key)
162 if (!key->both.ptr)
163 return;
165 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
166 case FUT_OFF_INODE:
167 atomic_inc(&key->shared.inode->i_count);
168 break;
169 case FUT_OFF_MMSHARED:
170 atomic_inc(&key->private.mm->mm_count);
171 break;
176 * Drop a reference to the resource addressed by a key.
177 * The hash bucket spinlock must not be held.
179 static void drop_futex_key_refs(union futex_key *key)
181 if (!key->both.ptr) {
182 /* If we're here then we tried to put a key we failed to get */
183 WARN_ON_ONCE(1);
184 return;
187 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
188 case FUT_OFF_INODE:
189 iput(key->shared.inode);
190 break;
191 case FUT_OFF_MMSHARED:
192 mmdrop(key->private.mm);
193 break;
198 * get_futex_key - Get parameters which are the keys for a futex.
199 * @uaddr: virtual address of the futex
200 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
201 * @key: address where result is stored.
202 * @rw: mapping needs to be read/write (values: VERIFY_READ, VERIFY_WRITE)
204 * Returns a negative error code or 0
205 * The key words are stored in *key on success.
207 * For shared mappings, it's (page->index, vma->vm_file->f_path.dentry->d_inode,
208 * offset_within_page). For private mappings, it's (uaddr, current->mm).
209 * We can usually work out the index without swapping in the page.
211 * lock_page() might sleep, the caller should not hold a spinlock.
213 static int
214 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
216 unsigned long address = (unsigned long)uaddr;
217 struct mm_struct *mm = current->mm;
218 struct page *page;
219 int err;
222 * The futex address must be "naturally" aligned.
224 key->both.offset = address % PAGE_SIZE;
225 if (unlikely((address % sizeof(u32)) != 0))
226 return -EINVAL;
227 address -= key->both.offset;
230 * PROCESS_PRIVATE futexes are fast.
231 * As the mm cannot disappear under us and the 'key' only needs
232 * virtual address, we dont even have to find the underlying vma.
233 * Note : We do have to check 'uaddr' is a valid user address,
234 * but access_ok() should be faster than find_vma()
236 if (!fshared) {
237 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
238 return -EFAULT;
239 key->private.mm = mm;
240 key->private.address = address;
241 get_futex_key_refs(key);
242 return 0;
245 again:
246 err = get_user_pages_fast(address, 1, rw == VERIFY_WRITE, &page);
247 if (err < 0)
248 return err;
250 lock_page(page);
251 if (!page->mapping) {
252 unlock_page(page);
253 put_page(page);
254 goto again;
258 * Private mappings are handled in a simple way.
260 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
261 * it's a read-only handle, it's expected that futexes attach to
262 * the object not the particular process.
264 if (PageAnon(page)) {
265 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
266 key->private.mm = mm;
267 key->private.address = address;
268 } else {
269 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
270 key->shared.inode = page->mapping->host;
271 key->shared.pgoff = page->index;
274 get_futex_key_refs(key);
276 unlock_page(page);
277 put_page(page);
278 return 0;
281 static inline
282 void put_futex_key(int fshared, union futex_key *key)
284 drop_futex_key_refs(key);
288 * get_user_writeable - get user page and verify RW access
289 * @uaddr: pointer to faulting user space address
291 * We cannot write to the user space address and get_user just faults
292 * the page in, but does not tell us whether the mapping is writeable.
294 * We can not rely on access_ok() for private futexes as it is just a
295 * range check and we can neither rely on get_user_pages() as there
296 * might be a mprotect(PROT_READ) for that mapping after
297 * get_user_pages() and before the fault in the atomic write access.
299 static int get_user_writeable(u32 __user *uaddr)
301 unsigned long addr = (unsigned long)uaddr;
302 struct page *page;
303 int ret;
305 ret = get_user_pages_fast(addr, 1, 1, &page);
306 if (ret > 0)
307 put_page(page);
309 return ret;
313 * futex_top_waiter() - Return the highest priority waiter on a futex
314 * @hb: the hash bucket the futex_q's reside in
315 * @key: the futex key (to distinguish it from other futex futex_q's)
317 * Must be called with the hb lock held.
319 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
320 union futex_key *key)
322 struct futex_q *this;
324 plist_for_each_entry(this, &hb->chain, list) {
325 if (match_futex(&this->key, key))
326 return this;
328 return NULL;
331 static u32 cmpxchg_futex_value_locked(u32 __user *uaddr, u32 uval, u32 newval)
333 u32 curval;
335 pagefault_disable();
336 curval = futex_atomic_cmpxchg_inatomic(uaddr, uval, newval);
337 pagefault_enable();
339 return curval;
342 static int get_futex_value_locked(u32 *dest, u32 __user *from)
344 int ret;
346 pagefault_disable();
347 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
348 pagefault_enable();
350 return ret ? -EFAULT : 0;
355 * PI code:
357 static int refill_pi_state_cache(void)
359 struct futex_pi_state *pi_state;
361 if (likely(current->pi_state_cache))
362 return 0;
364 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
366 if (!pi_state)
367 return -ENOMEM;
369 INIT_LIST_HEAD(&pi_state->list);
370 /* pi_mutex gets initialized later */
371 pi_state->owner = NULL;
372 atomic_set(&pi_state->refcount, 1);
373 pi_state->key = FUTEX_KEY_INIT;
375 current->pi_state_cache = pi_state;
377 return 0;
380 static struct futex_pi_state * alloc_pi_state(void)
382 struct futex_pi_state *pi_state = current->pi_state_cache;
384 WARN_ON(!pi_state);
385 current->pi_state_cache = NULL;
387 return pi_state;
390 static void free_pi_state(struct futex_pi_state *pi_state)
392 if (!atomic_dec_and_test(&pi_state->refcount))
393 return;
396 * If pi_state->owner is NULL, the owner is most probably dying
397 * and has cleaned up the pi_state already
399 if (pi_state->owner) {
400 spin_lock_irq(&pi_state->owner->pi_lock);
401 list_del_init(&pi_state->list);
402 spin_unlock_irq(&pi_state->owner->pi_lock);
404 rt_mutex_proxy_unlock(&pi_state->pi_mutex, pi_state->owner);
407 if (current->pi_state_cache)
408 kfree(pi_state);
409 else {
411 * pi_state->list is already empty.
412 * clear pi_state->owner.
413 * refcount is at 0 - put it back to 1.
415 pi_state->owner = NULL;
416 atomic_set(&pi_state->refcount, 1);
417 current->pi_state_cache = pi_state;
422 * Look up the task based on what TID userspace gave us.
423 * We dont trust it.
425 static struct task_struct * futex_find_get_task(pid_t pid)
427 struct task_struct *p;
428 const struct cred *cred = current_cred(), *pcred;
430 rcu_read_lock();
431 p = find_task_by_vpid(pid);
432 if (!p) {
433 p = ERR_PTR(-ESRCH);
434 } else {
435 pcred = __task_cred(p);
436 if (cred->euid != pcred->euid &&
437 cred->euid != pcred->uid)
438 p = ERR_PTR(-ESRCH);
439 else
440 get_task_struct(p);
443 rcu_read_unlock();
445 return p;
449 * This task is holding PI mutexes at exit time => bad.
450 * Kernel cleans up PI-state, but userspace is likely hosed.
451 * (Robust-futex cleanup is separate and might save the day for userspace.)
453 void exit_pi_state_list(struct task_struct *curr)
455 struct list_head *next, *head = &curr->pi_state_list;
456 struct futex_pi_state *pi_state;
457 struct futex_hash_bucket *hb;
458 union futex_key key = FUTEX_KEY_INIT;
460 if (!futex_cmpxchg_enabled)
461 return;
463 * We are a ZOMBIE and nobody can enqueue itself on
464 * pi_state_list anymore, but we have to be careful
465 * versus waiters unqueueing themselves:
467 spin_lock_irq(&curr->pi_lock);
468 while (!list_empty(head)) {
470 next = head->next;
471 pi_state = list_entry(next, struct futex_pi_state, list);
472 key = pi_state->key;
473 hb = hash_futex(&key);
474 spin_unlock_irq(&curr->pi_lock);
476 spin_lock(&hb->lock);
478 spin_lock_irq(&curr->pi_lock);
480 * We dropped the pi-lock, so re-check whether this
481 * task still owns the PI-state:
483 if (head->next != next) {
484 spin_unlock(&hb->lock);
485 continue;
488 WARN_ON(pi_state->owner != curr);
489 WARN_ON(list_empty(&pi_state->list));
490 list_del_init(&pi_state->list);
491 pi_state->owner = NULL;
492 spin_unlock_irq(&curr->pi_lock);
494 rt_mutex_unlock(&pi_state->pi_mutex);
496 spin_unlock(&hb->lock);
498 spin_lock_irq(&curr->pi_lock);
500 spin_unlock_irq(&curr->pi_lock);
503 static int
504 lookup_pi_state(u32 uval, struct futex_hash_bucket *hb,
505 union futex_key *key, struct futex_pi_state **ps)
507 struct futex_pi_state *pi_state = NULL;
508 struct futex_q *this, *next;
509 struct plist_head *head;
510 struct task_struct *p;
511 pid_t pid = uval & FUTEX_TID_MASK;
513 head = &hb->chain;
515 plist_for_each_entry_safe(this, next, head, list) {
516 if (match_futex(&this->key, key)) {
518 * Another waiter already exists - bump up
519 * the refcount and return its pi_state:
521 pi_state = this->pi_state;
523 * Userspace might have messed up non PI and PI futexes
525 if (unlikely(!pi_state))
526 return -EINVAL;
528 WARN_ON(!atomic_read(&pi_state->refcount));
529 WARN_ON(pid && pi_state->owner &&
530 pi_state->owner->pid != pid);
532 atomic_inc(&pi_state->refcount);
533 *ps = pi_state;
535 return 0;
540 * We are the first waiter - try to look up the real owner and attach
541 * the new pi_state to it, but bail out when TID = 0
543 if (!pid)
544 return -ESRCH;
545 p = futex_find_get_task(pid);
546 if (IS_ERR(p))
547 return PTR_ERR(p);
550 * We need to look at the task state flags to figure out,
551 * whether the task is exiting. To protect against the do_exit
552 * change of the task flags, we do this protected by
553 * p->pi_lock:
555 spin_lock_irq(&p->pi_lock);
556 if (unlikely(p->flags & PF_EXITING)) {
558 * The task is on the way out. When PF_EXITPIDONE is
559 * set, we know that the task has finished the
560 * cleanup:
562 int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN;
564 spin_unlock_irq(&p->pi_lock);
565 put_task_struct(p);
566 return ret;
569 pi_state = alloc_pi_state();
572 * Initialize the pi_mutex in locked state and make 'p'
573 * the owner of it:
575 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
577 /* Store the key for possible exit cleanups: */
578 pi_state->key = *key;
580 WARN_ON(!list_empty(&pi_state->list));
581 list_add(&pi_state->list, &p->pi_state_list);
582 pi_state->owner = p;
583 spin_unlock_irq(&p->pi_lock);
585 put_task_struct(p);
587 *ps = pi_state;
589 return 0;
593 * futex_lock_pi_atomic() - atomic work required to acquire a pi aware futex
594 * @uaddr: the pi futex user address
595 * @hb: the pi futex hash bucket
596 * @key: the futex key associated with uaddr and hb
597 * @ps: the pi_state pointer where we store the result of the
598 * lookup
599 * @task: the task to perform the atomic lock work for. This will
600 * be "current" except in the case of requeue pi.
601 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
603 * Returns:
604 * 0 - ready to wait
605 * 1 - acquired the lock
606 * <0 - error
608 * The hb->lock and futex_key refs shall be held by the caller.
610 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
611 union futex_key *key,
612 struct futex_pi_state **ps,
613 struct task_struct *task, int set_waiters)
615 int lock_taken, ret, ownerdied = 0;
616 u32 uval, newval, curval;
618 retry:
619 ret = lock_taken = 0;
622 * To avoid races, we attempt to take the lock here again
623 * (by doing a 0 -> TID atomic cmpxchg), while holding all
624 * the locks. It will most likely not succeed.
626 newval = task_pid_vnr(task);
627 if (set_waiters)
628 newval |= FUTEX_WAITERS;
630 curval = cmpxchg_futex_value_locked(uaddr, 0, newval);
632 if (unlikely(curval == -EFAULT))
633 return -EFAULT;
636 * Detect deadlocks.
638 if ((unlikely((curval & FUTEX_TID_MASK) == task_pid_vnr(task))))
639 return -EDEADLK;
642 * Surprise - we got the lock. Just return to userspace:
644 if (unlikely(!curval))
645 return 1;
647 uval = curval;
650 * Set the FUTEX_WAITERS flag, so the owner will know it has someone
651 * to wake at the next unlock.
653 newval = curval | FUTEX_WAITERS;
656 * There are two cases, where a futex might have no owner (the
657 * owner TID is 0): OWNER_DIED. We take over the futex in this
658 * case. We also do an unconditional take over, when the owner
659 * of the futex died.
661 * This is safe as we are protected by the hash bucket lock !
663 if (unlikely(ownerdied || !(curval & FUTEX_TID_MASK))) {
664 /* Keep the OWNER_DIED bit */
665 newval = (curval & ~FUTEX_TID_MASK) | task_pid_vnr(task);
666 ownerdied = 0;
667 lock_taken = 1;
670 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
672 if (unlikely(curval == -EFAULT))
673 return -EFAULT;
674 if (unlikely(curval != uval))
675 goto retry;
678 * We took the lock due to owner died take over.
680 if (unlikely(lock_taken))
681 return 1;
684 * We dont have the lock. Look up the PI state (or create it if
685 * we are the first waiter):
687 ret = lookup_pi_state(uval, hb, key, ps);
689 if (unlikely(ret)) {
690 switch (ret) {
691 case -ESRCH:
693 * No owner found for this futex. Check if the
694 * OWNER_DIED bit is set to figure out whether
695 * this is a robust futex or not.
697 if (get_futex_value_locked(&curval, uaddr))
698 return -EFAULT;
701 * We simply start over in case of a robust
702 * futex. The code above will take the futex
703 * and return happy.
705 if (curval & FUTEX_OWNER_DIED) {
706 ownerdied = 1;
707 goto retry;
709 default:
710 break;
714 return ret;
718 * The hash bucket lock must be held when this is called.
719 * Afterwards, the futex_q must not be accessed.
721 static void wake_futex(struct task_struct **wake_list, struct futex_q *q)
723 struct task_struct *p = q->task;
726 * We set q->lock_ptr = NULL _before_ we wake up the task. If
727 * a non futex wake up happens on another CPU then the task
728 * might exit and p would dereference a non existing task
729 * struct. Prevent this by holding a reference on p across the
730 * wake up.
732 get_task_struct(p);
734 plist_del(&q->list, &q->list.plist);
736 * The waiting task can free the futex_q as soon as
737 * q->lock_ptr = NULL is written, without taking any locks. A
738 * memory barrier is required here to prevent the following
739 * store to lock_ptr from getting ahead of the plist_del.
741 smp_wmb();
742 q->lock_ptr = NULL;
745 * Atomically grab the task, if ->futex_wakeup is !0 already it means
746 * its already queued (either by us or someone else) and will get the
747 * wakeup due to that.
749 * This cmpxchg() implies a full barrier, which pairs with the write
750 * barrier implied by the wakeup in wake_futex_list().
752 if (cmpxchg(&p->futex_wakeup, 0, p) != 0) {
754 * It was already queued, drop the extra ref and we're done.
756 put_task_struct(p);
757 return;
761 * Put the task on our wakeup list by atomically switching it with
762 * the list head. (XXX its a local list, no possible concurrency,
763 * this could be written without cmpxchg).
765 do {
766 p->futex_wakeup = *wake_list;
767 } while (cmpxchg(wake_list, p->futex_wakeup, p) != p->futex_wakeup);
771 * For each task on the list, deliver the pending wakeup and release the
772 * task reference obtained in wake_futex().
774 static void wake_futex_list(struct task_struct *head)
776 while (head != &init_task) {
777 struct task_struct *next = head->futex_wakeup;
779 head->futex_wakeup = NULL;
781 * wake_up_state() implies a wmb() to pair with the queueing
782 * in wake_futex() so as to not miss wakeups.
784 wake_up_state(head, TASK_NORMAL);
785 put_task_struct(head);
787 head = next;
791 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_q *this)
793 struct task_struct *new_owner;
794 struct futex_pi_state *pi_state = this->pi_state;
795 u32 curval, newval;
797 if (!pi_state)
798 return -EINVAL;
800 spin_lock(&pi_state->pi_mutex.wait_lock);
801 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
804 * This happens when we have stolen the lock and the original
805 * pending owner did not enqueue itself back on the rt_mutex.
806 * Thats not a tragedy. We know that way, that a lock waiter
807 * is on the fly. We make the futex_q waiter the pending owner.
809 if (!new_owner)
810 new_owner = this->task;
813 * We pass it to the next owner. (The WAITERS bit is always
814 * kept enabled while there is PI state around. We must also
815 * preserve the owner died bit.)
817 if (!(uval & FUTEX_OWNER_DIED)) {
818 int ret = 0;
820 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
822 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
824 if (curval == -EFAULT)
825 ret = -EFAULT;
826 else if (curval != uval)
827 ret = -EINVAL;
828 if (ret) {
829 spin_unlock(&pi_state->pi_mutex.wait_lock);
830 return ret;
834 spin_lock_irq(&pi_state->owner->pi_lock);
835 WARN_ON(list_empty(&pi_state->list));
836 list_del_init(&pi_state->list);
837 spin_unlock_irq(&pi_state->owner->pi_lock);
839 spin_lock_irq(&new_owner->pi_lock);
840 WARN_ON(!list_empty(&pi_state->list));
841 list_add(&pi_state->list, &new_owner->pi_state_list);
842 pi_state->owner = new_owner;
843 spin_unlock_irq(&new_owner->pi_lock);
845 spin_unlock(&pi_state->pi_mutex.wait_lock);
846 rt_mutex_unlock(&pi_state->pi_mutex);
848 return 0;
851 static int unlock_futex_pi(u32 __user *uaddr, u32 uval)
853 u32 oldval;
856 * There is no waiter, so we unlock the futex. The owner died
857 * bit has not to be preserved here. We are the owner:
859 oldval = cmpxchg_futex_value_locked(uaddr, uval, 0);
861 if (oldval == -EFAULT)
862 return oldval;
863 if (oldval != uval)
864 return -EAGAIN;
866 return 0;
870 * Express the locking dependencies for lockdep:
872 static inline void
873 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
875 if (hb1 <= hb2) {
876 spin_lock(&hb1->lock);
877 if (hb1 < hb2)
878 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
879 } else { /* hb1 > hb2 */
880 spin_lock(&hb2->lock);
881 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
885 static inline void
886 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
888 spin_unlock(&hb1->lock);
889 if (hb1 != hb2)
890 spin_unlock(&hb2->lock);
894 * Wake up waiters matching bitset queued on this futex (uaddr).
896 static int futex_wake(u32 __user *uaddr, int fshared, int nr_wake, u32 bitset)
898 struct futex_hash_bucket *hb;
899 struct futex_q *this, *next;
900 struct plist_head *head;
901 union futex_key key = FUTEX_KEY_INIT;
902 struct task_struct *wake_list = &init_task;
903 int ret;
905 if (!bitset)
906 return -EINVAL;
908 ret = get_futex_key(uaddr, fshared, &key, VERIFY_READ);
909 if (unlikely(ret != 0))
910 goto out;
912 hb = hash_futex(&key);
913 spin_lock(&hb->lock);
914 head = &hb->chain;
916 plist_for_each_entry_safe(this, next, head, list) {
917 if (match_futex (&this->key, &key)) {
918 if (this->pi_state || this->rt_waiter) {
919 ret = -EINVAL;
920 break;
923 /* Check if one of the bits is set in both bitsets */
924 if (!(this->bitset & bitset))
925 continue;
927 wake_futex(&wake_list, this);
928 if (++ret >= nr_wake)
929 break;
933 spin_unlock(&hb->lock);
934 put_futex_key(fshared, &key);
936 wake_futex_list(wake_list);
937 out:
938 return ret;
942 * Wake up all waiters hashed on the physical page that is mapped
943 * to this virtual address:
945 static int
946 futex_wake_op(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
947 int nr_wake, int nr_wake2, int op)
949 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
950 struct futex_hash_bucket *hb1, *hb2;
951 struct plist_head *head;
952 struct futex_q *this, *next;
953 struct task_struct *wake_list = &init_task;
954 int ret, op_ret;
956 retry:
957 ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
958 if (unlikely(ret != 0))
959 goto out;
960 ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_WRITE);
961 if (unlikely(ret != 0))
962 goto out_put_key1;
964 hb1 = hash_futex(&key1);
965 hb2 = hash_futex(&key2);
967 double_lock_hb(hb1, hb2);
968 retry_private:
969 op_ret = futex_atomic_op_inuser(op, uaddr2);
970 if (unlikely(op_ret < 0)) {
972 double_unlock_hb(hb1, hb2);
974 #ifndef CONFIG_MMU
976 * we don't get EFAULT from MMU faults if we don't have an MMU,
977 * but we might get them from range checking
979 ret = op_ret;
980 goto out_put_keys;
981 #endif
983 if (unlikely(op_ret != -EFAULT)) {
984 ret = op_ret;
985 goto out_put_keys;
988 ret = get_user_writeable(uaddr2);
989 if (ret)
990 goto out_put_keys;
992 if (!fshared)
993 goto retry_private;
995 put_futex_key(fshared, &key2);
996 put_futex_key(fshared, &key1);
997 goto retry;
1000 head = &hb1->chain;
1002 plist_for_each_entry_safe(this, next, head, list) {
1003 if (match_futex (&this->key, &key1)) {
1004 wake_futex(&wake_list, this);
1005 if (++ret >= nr_wake)
1006 break;
1010 if (op_ret > 0) {
1011 head = &hb2->chain;
1013 op_ret = 0;
1014 plist_for_each_entry_safe(this, next, head, list) {
1015 if (match_futex (&this->key, &key2)) {
1016 wake_futex(&wake_list, this);
1017 if (++op_ret >= nr_wake2)
1018 break;
1021 ret += op_ret;
1024 double_unlock_hb(hb1, hb2);
1025 out_put_keys:
1026 put_futex_key(fshared, &key2);
1027 out_put_key1:
1028 put_futex_key(fshared, &key1);
1030 wake_futex_list(wake_list);
1031 out:
1032 return ret;
1036 * requeue_futex() - Requeue a futex_q from one hb to another
1037 * @q: the futex_q to requeue
1038 * @hb1: the source hash_bucket
1039 * @hb2: the target hash_bucket
1040 * @key2: the new key for the requeued futex_q
1042 static inline
1043 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1044 struct futex_hash_bucket *hb2, union futex_key *key2)
1048 * If key1 and key2 hash to the same bucket, no need to
1049 * requeue.
1051 if (likely(&hb1->chain != &hb2->chain)) {
1052 plist_del(&q->list, &hb1->chain);
1053 plist_add(&q->list, &hb2->chain);
1054 q->lock_ptr = &hb2->lock;
1055 #ifdef CONFIG_DEBUG_PI_LIST
1056 # ifdef CONFIG_PREEMPT_RT
1057 q->list.plist.lock = NULL;
1058 # else
1059 q->list.plist.lock = &hb2->lock;
1060 # endif
1061 #endif
1063 get_futex_key_refs(key2);
1064 q->key = *key2;
1068 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1069 * q: the futex_q
1070 * key: the key of the requeue target futex
1072 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1073 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1074 * to the requeue target futex so the waiter can detect the wakeup on the right
1075 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1076 * atomic lock acquisition. Must be called with the q->lock_ptr held.
1078 static inline
1079 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key)
1081 drop_futex_key_refs(&q->key);
1082 get_futex_key_refs(key);
1083 q->key = *key;
1085 WARN_ON(plist_node_empty(&q->list));
1086 plist_del(&q->list, &q->list.plist);
1088 WARN_ON(!q->rt_waiter);
1089 q->rt_waiter = NULL;
1091 wake_up_state(q->task, TASK_NORMAL);
1095 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1096 * @pifutex: the user address of the to futex
1097 * @hb1: the from futex hash bucket, must be locked by the caller
1098 * @hb2: the to futex hash bucket, must be locked by the caller
1099 * @key1: the from futex key
1100 * @key2: the to futex key
1101 * @ps: address to store the pi_state pointer
1102 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1104 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1105 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1106 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1107 * hb1 and hb2 must be held by the caller.
1109 * Returns:
1110 * 0 - failed to acquire the lock atomicly
1111 * 1 - acquired the lock
1112 * <0 - error
1114 static int futex_proxy_trylock_atomic(u32 __user *pifutex,
1115 struct futex_hash_bucket *hb1,
1116 struct futex_hash_bucket *hb2,
1117 union futex_key *key1, union futex_key *key2,
1118 struct futex_pi_state **ps, int set_waiters)
1120 struct futex_q *top_waiter = NULL;
1121 u32 curval;
1122 int ret;
1124 if (get_futex_value_locked(&curval, pifutex))
1125 return -EFAULT;
1128 * Find the top_waiter and determine if there are additional waiters.
1129 * If the caller intends to requeue more than 1 waiter to pifutex,
1130 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1131 * as we have means to handle the possible fault. If not, don't set
1132 * the bit unecessarily as it will force the subsequent unlock to enter
1133 * the kernel.
1135 top_waiter = futex_top_waiter(hb1, key1);
1137 /* There are no waiters, nothing for us to do. */
1138 if (!top_waiter)
1139 return 0;
1142 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1143 * the contended case or if set_waiters is 1. The pi_state is returned
1144 * in ps in contended cases.
1146 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1147 set_waiters);
1148 if (ret == 1)
1149 requeue_pi_wake_futex(top_waiter, key2);
1151 return ret;
1155 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1156 * uaddr1: source futex user address
1157 * uaddr2: target futex user address
1158 * nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1159 * nr_requeue: number of waiters to requeue (0-INT_MAX)
1160 * requeue_pi: if we are attempting to requeue from a non-pi futex to a
1161 * pi futex (pi to pi requeue is not supported)
1163 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1164 * uaddr2 atomically on behalf of the top waiter.
1166 * Returns:
1167 * >=0 - on success, the number of tasks requeued or woken
1168 * <0 - on error
1170 static int futex_requeue(u32 __user *uaddr1, int fshared, u32 __user *uaddr2,
1171 int nr_wake, int nr_requeue, u32 *cmpval,
1172 int requeue_pi)
1174 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1175 int drop_count = 0, task_count = 0, ret;
1176 struct futex_pi_state *pi_state = NULL;
1177 struct futex_hash_bucket *hb1, *hb2;
1178 struct plist_head *head1;
1179 struct futex_q *this, *next;
1180 struct task_struct *wake_list = &init_task;
1181 u32 curval2;
1183 if (requeue_pi) {
1185 * requeue_pi requires a pi_state, try to allocate it now
1186 * without any locks in case it fails.
1188 if (refill_pi_state_cache())
1189 return -ENOMEM;
1191 * requeue_pi must wake as many tasks as it can, up to nr_wake
1192 * + nr_requeue, since it acquires the rt_mutex prior to
1193 * returning to userspace, so as to not leave the rt_mutex with
1194 * waiters and no owner. However, second and third wake-ups
1195 * cannot be predicted as they involve race conditions with the
1196 * first wake and a fault while looking up the pi_state. Both
1197 * pthread_cond_signal() and pthread_cond_broadcast() should
1198 * use nr_wake=1.
1200 if (nr_wake != 1)
1201 return -EINVAL;
1204 retry:
1205 if (pi_state != NULL) {
1207 * We will have to lookup the pi_state again, so free this one
1208 * to keep the accounting correct.
1210 free_pi_state(pi_state);
1211 pi_state = NULL;
1214 ret = get_futex_key(uaddr1, fshared, &key1, VERIFY_READ);
1215 if (unlikely(ret != 0))
1216 goto out;
1217 ret = get_futex_key(uaddr2, fshared, &key2,
1218 requeue_pi ? VERIFY_WRITE : VERIFY_READ);
1219 if (unlikely(ret != 0))
1220 goto out_put_key1;
1222 hb1 = hash_futex(&key1);
1223 hb2 = hash_futex(&key2);
1225 retry_private:
1226 double_lock_hb(hb1, hb2);
1228 if (likely(cmpval != NULL)) {
1229 u32 curval;
1231 ret = get_futex_value_locked(&curval, uaddr1);
1233 if (unlikely(ret)) {
1234 double_unlock_hb(hb1, hb2);
1236 ret = get_user(curval, uaddr1);
1237 if (ret)
1238 goto out_put_keys;
1240 if (!fshared)
1241 goto retry_private;
1243 put_futex_key(fshared, &key2);
1244 put_futex_key(fshared, &key1);
1245 goto retry;
1247 if (curval != *cmpval) {
1248 ret = -EAGAIN;
1249 goto out_unlock;
1253 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
1255 * Attempt to acquire uaddr2 and wake the top waiter. If we
1256 * intend to requeue waiters, force setting the FUTEX_WAITERS
1257 * bit. We force this here where we are able to easily handle
1258 * faults rather in the requeue loop below.
1260 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
1261 &key2, &pi_state, nr_requeue);
1264 * At this point the top_waiter has either taken uaddr2 or is
1265 * waiting on it. If the former, then the pi_state will not
1266 * exist yet, look it up one more time to ensure we have a
1267 * reference to it.
1269 if (ret == 1) {
1270 WARN_ON(pi_state);
1271 task_count++;
1272 ret = get_futex_value_locked(&curval2, uaddr2);
1273 if (!ret)
1274 ret = lookup_pi_state(curval2, hb2, &key2,
1275 &pi_state);
1278 switch (ret) {
1279 case 0:
1280 break;
1281 case -EFAULT:
1282 double_unlock_hb(hb1, hb2);
1283 put_futex_key(fshared, &key2);
1284 put_futex_key(fshared, &key1);
1285 ret = get_user_writeable(uaddr2);
1286 if (!ret)
1287 goto retry;
1288 goto out;
1289 case -EAGAIN:
1290 /* The owner was exiting, try again. */
1291 double_unlock_hb(hb1, hb2);
1292 put_futex_key(fshared, &key2);
1293 put_futex_key(fshared, &key1);
1294 cond_resched();
1295 goto retry;
1296 default:
1297 goto out_unlock;
1301 head1 = &hb1->chain;
1302 plist_for_each_entry_safe(this, next, head1, list) {
1303 if (task_count - nr_wake >= nr_requeue)
1304 break;
1306 if (!match_futex(&this->key, &key1))
1307 continue;
1309 WARN_ON(!requeue_pi && this->rt_waiter);
1310 WARN_ON(requeue_pi && !this->rt_waiter);
1313 * Wake nr_wake waiters. For requeue_pi, if we acquired the
1314 * lock, we already woke the top_waiter. If not, it will be
1315 * woken by futex_unlock_pi().
1317 if (++task_count <= nr_wake && !requeue_pi) {
1318 wake_futex(&wake_list, this);
1319 continue;
1323 * Requeue nr_requeue waiters and possibly one more in the case
1324 * of requeue_pi if we couldn't acquire the lock atomically.
1326 if (requeue_pi) {
1327 /* Prepare the waiter to take the rt_mutex. */
1328 atomic_inc(&pi_state->refcount);
1329 this->pi_state = pi_state;
1330 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
1331 this->rt_waiter,
1332 this->task, 1);
1333 if (ret == 1) {
1334 /* We got the lock. */
1335 requeue_pi_wake_futex(this, &key2);
1336 continue;
1337 } else if (ret) {
1338 /* -EDEADLK */
1339 this->pi_state = NULL;
1340 free_pi_state(pi_state);
1341 goto out_unlock;
1344 requeue_futex(this, hb1, hb2, &key2);
1345 drop_count++;
1348 out_unlock:
1349 double_unlock_hb(hb1, hb2);
1352 * drop_futex_key_refs() must be called outside the spinlocks. During
1353 * the requeue we moved futex_q's from the hash bucket at key1 to the
1354 * one at key2 and updated their key pointer. We no longer need to
1355 * hold the references to key1.
1357 while (--drop_count >= 0)
1358 drop_futex_key_refs(&key1);
1360 out_put_keys:
1361 put_futex_key(fshared, &key2);
1362 out_put_key1:
1363 put_futex_key(fshared, &key1);
1365 wake_futex_list(wake_list);
1366 out:
1367 if (pi_state != NULL)
1368 free_pi_state(pi_state);
1369 return ret ? ret : task_count;
1372 /* The key must be already stored in q->key. */
1373 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
1375 struct futex_hash_bucket *hb;
1377 get_futex_key_refs(&q->key);
1378 hb = hash_futex(&q->key);
1379 q->lock_ptr = &hb->lock;
1381 spin_lock(&hb->lock);
1382 return hb;
1385 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
1387 int prio;
1390 * The priority used to register this element is
1391 * - either the real thread-priority for the real-time threads
1392 * (i.e. threads with a priority lower than MAX_RT_PRIO)
1393 * - or MAX_RT_PRIO for non-RT threads.
1394 * Thus, all RT-threads are woken first in priority order, and
1395 * the others are woken last, in FIFO order.
1397 prio = min(current->normal_prio, MAX_RT_PRIO);
1399 plist_node_init(&q->list, prio);
1400 #ifdef CONFIG_DEBUG_PI_LIST
1401 #ifdef CONFIG_PREEMPT_RT
1402 q->list.plist.lock = NULL;
1403 #else
1404 q->list.plist.lock = &hb->lock;
1405 #endif
1406 #endif
1407 plist_add(&q->list, &hb->chain);
1408 q->task = current;
1409 spin_unlock(&hb->lock);
1412 static inline void
1413 queue_unlock(struct futex_q *q, struct futex_hash_bucket *hb)
1415 spin_unlock(&hb->lock);
1416 drop_futex_key_refs(&q->key);
1420 * queue_me and unqueue_me must be called as a pair, each
1421 * exactly once. They are called with the hashed spinlock held.
1424 /* Return 1 if we were still queued (ie. 0 means we were woken) */
1425 static int unqueue_me(struct futex_q *q)
1427 spinlock_t *lock_ptr;
1428 int ret = 0;
1430 /* In the common case we don't take the spinlock, which is nice. */
1431 retry:
1432 lock_ptr = q->lock_ptr;
1433 barrier();
1434 if (lock_ptr != NULL) {
1435 spin_lock(lock_ptr);
1437 * q->lock_ptr can change between reading it and
1438 * spin_lock(), causing us to take the wrong lock. This
1439 * corrects the race condition.
1441 * Reasoning goes like this: if we have the wrong lock,
1442 * q->lock_ptr must have changed (maybe several times)
1443 * between reading it and the spin_lock(). It can
1444 * change again after the spin_lock() but only if it was
1445 * already changed before the spin_lock(). It cannot,
1446 * however, change back to the original value. Therefore
1447 * we can detect whether we acquired the correct lock.
1449 if (unlikely(lock_ptr != q->lock_ptr)) {
1450 spin_unlock(lock_ptr);
1451 goto retry;
1453 WARN_ON(plist_node_empty(&q->list));
1454 plist_del(&q->list, &q->list.plist);
1456 BUG_ON(q->pi_state);
1458 spin_unlock(lock_ptr);
1459 ret = 1;
1462 drop_futex_key_refs(&q->key);
1463 return ret;
1467 * PI futexes can not be requeued and must remove themself from the
1468 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
1469 * and dropped here.
1471 static void unqueue_me_pi(struct futex_q *q)
1473 WARN_ON(plist_node_empty(&q->list));
1474 plist_del(&q->list, &q->list.plist);
1476 BUG_ON(!q->pi_state);
1477 free_pi_state(q->pi_state);
1478 q->pi_state = NULL;
1480 spin_unlock(q->lock_ptr);
1482 drop_futex_key_refs(&q->key);
1486 * Fixup the pi_state owner with the new owner.
1488 * Must be called with hash bucket lock held and mm->sem held for non
1489 * private futexes.
1491 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
1492 struct task_struct *newowner, int fshared)
1494 u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
1495 struct futex_pi_state *pi_state = q->pi_state;
1496 struct task_struct *oldowner = pi_state->owner;
1497 u32 uval, curval, newval;
1498 int ret;
1500 /* Owner died? */
1501 if (!pi_state->owner)
1502 newtid |= FUTEX_OWNER_DIED;
1505 * We are here either because we stole the rtmutex from the
1506 * pending owner or we are the pending owner which failed to
1507 * get the rtmutex. We have to replace the pending owner TID
1508 * in the user space variable. This must be atomic as we have
1509 * to preserve the owner died bit here.
1511 * Note: We write the user space value _before_ changing the pi_state
1512 * because we can fault here. Imagine swapped out pages or a fork
1513 * that marked all the anonymous memory readonly for cow.
1515 * Modifying pi_state _before_ the user space value would
1516 * leave the pi_state in an inconsistent state when we fault
1517 * here, because we need to drop the hash bucket lock to
1518 * handle the fault. This might be observed in the PID check
1519 * in lookup_pi_state.
1521 retry:
1522 if (get_futex_value_locked(&uval, uaddr))
1523 goto handle_fault;
1525 while (1) {
1526 newval = (uval & FUTEX_OWNER_DIED) | newtid;
1528 curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
1530 if (curval == -EFAULT)
1531 goto handle_fault;
1532 if (curval == uval)
1533 break;
1534 uval = curval;
1538 * We fixed up user space. Now we need to fix the pi_state
1539 * itself.
1541 if (pi_state->owner != NULL) {
1542 spin_lock_irq(&pi_state->owner->pi_lock);
1543 WARN_ON(list_empty(&pi_state->list));
1544 list_del_init(&pi_state->list);
1545 spin_unlock_irq(&pi_state->owner->pi_lock);
1548 pi_state->owner = newowner;
1550 spin_lock_irq(&newowner->pi_lock);
1551 WARN_ON(!list_empty(&pi_state->list));
1552 list_add(&pi_state->list, &newowner->pi_state_list);
1553 spin_unlock_irq(&newowner->pi_lock);
1554 return 0;
1557 * To handle the page fault we need to drop the hash bucket
1558 * lock here. That gives the other task (either the pending
1559 * owner itself or the task which stole the rtmutex) the
1560 * chance to try the fixup of the pi_state. So once we are
1561 * back from handling the fault we need to check the pi_state
1562 * after reacquiring the hash bucket lock and before trying to
1563 * do another fixup. When the fixup has been done already we
1564 * simply return.
1566 handle_fault:
1567 spin_unlock(q->lock_ptr);
1569 ret = get_user_writeable(uaddr);
1571 spin_lock(q->lock_ptr);
1574 * Check if someone else fixed it for us:
1576 if (pi_state->owner != oldowner)
1577 return 0;
1579 if (ret)
1580 return ret;
1582 goto retry;
1586 * In case we must use restart_block to restart a futex_wait,
1587 * we encode in the 'flags' shared capability
1589 #define FLAGS_SHARED 0x01
1590 #define FLAGS_CLOCKRT 0x02
1591 #define FLAGS_HAS_TIMEOUT 0x04
1593 static long futex_wait_restart(struct restart_block *restart);
1596 * fixup_owner() - Post lock pi_state and corner case management
1597 * @uaddr: user address of the futex
1598 * @fshared: whether the futex is shared (1) or not (0)
1599 * @q: futex_q (contains pi_state and access to the rt_mutex)
1600 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
1602 * After attempting to lock an rt_mutex, this function is called to cleanup
1603 * the pi_state owner as well as handle race conditions that may allow us to
1604 * acquire the lock. Must be called with the hb lock held.
1606 * Returns:
1607 * 1 - success, lock taken
1608 * 0 - success, lock not taken
1609 * <0 - on error (-EFAULT)
1611 static int fixup_owner(u32 __user *uaddr, int fshared, struct futex_q *q,
1612 int locked)
1614 struct task_struct *owner;
1615 int ret = 0;
1617 if (locked) {
1619 * Got the lock. We might not be the anticipated owner if we
1620 * did a lock-steal - fix up the PI-state in that case:
1622 if (q->pi_state->owner != current)
1623 ret = fixup_pi_state_owner(uaddr, q, current, fshared);
1624 goto out;
1628 * Catch the rare case, where the lock was released when we were on the
1629 * way back before we locked the hash bucket.
1631 if (q->pi_state->owner == current) {
1633 * Try to get the rt_mutex now. This might fail as some other
1634 * task acquired the rt_mutex after we removed ourself from the
1635 * rt_mutex waiters list.
1637 if (rt_mutex_trylock(&q->pi_state->pi_mutex)) {
1638 locked = 1;
1639 goto out;
1643 * pi_state is incorrect, some other task did a lock steal and
1644 * we returned due to timeout or signal without taking the
1645 * rt_mutex. Too late. We can access the rt_mutex_owner without
1646 * locking, as the other task is now blocked on the hash bucket
1647 * lock. Fix the state up.
1649 owner = rt_mutex_owner(&q->pi_state->pi_mutex);
1650 ret = fixup_pi_state_owner(uaddr, q, owner, fshared);
1651 goto out;
1655 * Paranoia check. If we did not take the lock, then we should not be
1656 * the owner, nor the pending owner, of the rt_mutex.
1658 if (rt_mutex_owner(&q->pi_state->pi_mutex) == current)
1659 printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
1660 "pi-state %p\n", ret,
1661 q->pi_state->pi_mutex.owner,
1662 q->pi_state->owner);
1664 out:
1665 return ret ? ret : locked;
1669 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
1670 * @hb: the futex hash bucket, must be locked by the caller
1671 * @q: the futex_q to queue up on
1672 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
1674 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
1675 struct hrtimer_sleeper *timeout)
1677 queue_me(q, hb);
1680 * There might have been scheduling since the queue_me(), as we
1681 * cannot hold a spinlock across the get_user() in case it
1682 * faults, and we cannot just set TASK_INTERRUPTIBLE state when
1683 * queueing ourselves into the futex hash. This code thus has to
1684 * rely on the futex_wake() code removing us from hash when it
1685 * wakes us up.
1687 set_current_state(TASK_INTERRUPTIBLE);
1689 /* Arm the timer */
1690 if (timeout) {
1691 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
1692 if (!hrtimer_active(&timeout->timer))
1693 timeout->task = NULL;
1697 * !plist_node_empty() is safe here without any lock.
1698 * q.lock_ptr != 0 is not safe, because of ordering against wakeup.
1700 if (likely(!plist_node_empty(&q->list))) {
1701 unsigned long nosched_flag = current->flags & PF_NOSCHED;
1703 current->flags &= ~PF_NOSCHED;
1706 * If the timer has already expired, current will already be
1707 * flagged for rescheduling. Only call schedule if there
1708 * is no timeout, or if it has yet to expire.
1710 if (!timeout || timeout->task)
1711 schedule();
1713 current->flags |= nosched_flag;
1715 __set_current_state(TASK_RUNNING);
1719 * futex_wait_setup() - Prepare to wait on a futex
1720 * @uaddr: the futex userspace address
1721 * @val: the expected value
1722 * @fshared: whether the futex is shared (1) or not (0)
1723 * @q: the associated futex_q
1724 * @hb: storage for hash_bucket pointer to be returned to caller
1726 * Setup the futex_q and locate the hash_bucket. Get the futex value and
1727 * compare it with the expected value. Handle atomic faults internally.
1728 * Return with the hb lock held and a q.key reference on success, and unlocked
1729 * with no q.key reference on failure.
1731 * Returns:
1732 * 0 - uaddr contains val and hb has been locked
1733 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlcoked
1735 static int futex_wait_setup(u32 __user *uaddr, u32 val, int fshared,
1736 struct futex_q *q, struct futex_hash_bucket **hb)
1738 u32 uval;
1739 int ret;
1742 * Access the page AFTER the hash-bucket is locked.
1743 * Order is important:
1745 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
1746 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
1748 * The basic logical guarantee of a futex is that it blocks ONLY
1749 * if cond(var) is known to be true at the time of blocking, for
1750 * any cond. If we queued after testing *uaddr, that would open
1751 * a race condition where we could block indefinitely with
1752 * cond(var) false, which would violate the guarantee.
1754 * A consequence is that futex_wait() can return zero and absorb
1755 * a wakeup when *uaddr != val on entry to the syscall. This is
1756 * rare, but normal.
1758 retry:
1759 q->key = FUTEX_KEY_INIT;
1760 ret = get_futex_key(uaddr, fshared, &q->key, VERIFY_READ);
1761 if (unlikely(ret != 0))
1762 return ret;
1764 retry_private:
1765 *hb = queue_lock(q);
1767 ret = get_futex_value_locked(&uval, uaddr);
1769 if (ret) {
1770 queue_unlock(q, *hb);
1772 ret = get_user(uval, uaddr);
1773 if (ret)
1774 goto out;
1776 if (!fshared)
1777 goto retry_private;
1779 put_futex_key(fshared, &q->key);
1780 goto retry;
1783 if (uval != val) {
1784 queue_unlock(q, *hb);
1785 ret = -EWOULDBLOCK;
1788 out:
1789 if (ret)
1790 put_futex_key(fshared, &q->key);
1791 return ret;
1794 static int futex_wait(u32 __user *uaddr, int fshared,
1795 u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
1797 struct hrtimer_sleeper timeout, *to = NULL;
1798 struct restart_block *restart;
1799 struct futex_hash_bucket *hb;
1800 struct futex_q q;
1801 int ret;
1803 if (!bitset)
1804 return -EINVAL;
1806 q.pi_state = NULL;
1807 q.bitset = bitset;
1808 q.rt_waiter = NULL;
1810 if (abs_time) {
1811 to = &timeout;
1813 hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
1814 CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
1815 hrtimer_init_sleeper(to, current);
1816 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
1817 current->timer_slack_ns);
1820 /* Prepare to wait on uaddr. */
1821 ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
1822 if (ret)
1823 goto out;
1825 /* queue_me and wait for wakeup, timeout, or a signal. */
1826 futex_wait_queue_me(hb, &q, to);
1828 /* If we were woken (and unqueued), we succeeded, whatever. */
1829 ret = 0;
1830 if (!unqueue_me(&q))
1831 goto out_put_key;
1832 ret = -ETIMEDOUT;
1833 if (to && !to->task)
1834 goto out_put_key;
1837 * We expect signal_pending(current), but another thread may
1838 * have handled it for us already.
1840 ret = -ERESTARTSYS;
1841 if (!abs_time)
1842 goto out_put_key;
1844 restart = &current_thread_info()->restart_block;
1845 restart->fn = futex_wait_restart;
1846 restart->futex.uaddr = (u32 *)uaddr;
1847 restart->futex.val = val;
1848 restart->futex.time = abs_time->tv64;
1849 restart->futex.bitset = bitset;
1850 restart->futex.flags = FLAGS_HAS_TIMEOUT;
1852 if (fshared)
1853 restart->futex.flags |= FLAGS_SHARED;
1854 if (clockrt)
1855 restart->futex.flags |= FLAGS_CLOCKRT;
1857 ret = -ERESTART_RESTARTBLOCK;
1859 out_put_key:
1860 put_futex_key(fshared, &q.key);
1861 out:
1862 if (to) {
1863 hrtimer_cancel(&to->timer);
1864 destroy_hrtimer_on_stack(&to->timer);
1866 return ret;
1870 static long futex_wait_restart(struct restart_block *restart)
1872 u32 __user *uaddr = (u32 __user *)restart->futex.uaddr;
1873 int fshared = 0;
1874 ktime_t t, *tp = NULL;
1876 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
1877 t.tv64 = restart->futex.time;
1878 tp = &t;
1880 restart->fn = do_no_restart_syscall;
1881 if (restart->futex.flags & FLAGS_SHARED)
1882 fshared = 1;
1883 return (long)futex_wait(uaddr, fshared, restart->futex.val, tp,
1884 restart->futex.bitset,
1885 restart->futex.flags & FLAGS_CLOCKRT);
1890 * Userspace tried a 0 -> TID atomic transition of the futex value
1891 * and failed. The kernel side here does the whole locking operation:
1892 * if there are waiters then it will block, it does PI, etc. (Due to
1893 * races the kernel might see a 0 value of the futex too.)
1895 static int futex_lock_pi(u32 __user *uaddr, int fshared,
1896 int detect, ktime_t *time, int trylock)
1898 struct hrtimer_sleeper timeout, *to = NULL;
1899 struct futex_hash_bucket *hb;
1900 struct futex_q q;
1901 int res, ret;
1903 if (refill_pi_state_cache())
1904 return -ENOMEM;
1906 if (time) {
1907 to = &timeout;
1908 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
1909 HRTIMER_MODE_ABS);
1910 hrtimer_init_sleeper(to, current);
1911 hrtimer_set_expires(&to->timer, *time);
1914 q.pi_state = NULL;
1915 q.rt_waiter = NULL;
1916 retry:
1917 q.key = FUTEX_KEY_INIT;
1918 ret = get_futex_key(uaddr, fshared, &q.key, VERIFY_WRITE);
1919 if (unlikely(ret != 0))
1920 goto out;
1922 retry_private:
1923 hb = queue_lock(&q);
1925 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current, 0);
1926 if (unlikely(ret)) {
1927 switch (ret) {
1928 case 1:
1929 /* We got the lock. */
1930 ret = 0;
1931 goto out_unlock_put_key;
1932 case -EFAULT:
1933 goto uaddr_faulted;
1934 case -EAGAIN:
1936 * Task is exiting and we just wait for the
1937 * exit to complete.
1939 queue_unlock(&q, hb);
1940 put_futex_key(fshared, &q.key);
1941 cond_resched();
1942 goto retry;
1943 default:
1944 goto out_unlock_put_key;
1949 * Only actually queue now that the atomic ops are done:
1951 queue_me(&q, hb);
1953 WARN_ON(!q.pi_state);
1955 * Block on the PI mutex:
1957 if (!trylock)
1958 ret = rt_mutex_timed_lock(&q.pi_state->pi_mutex, to, 1);
1959 else {
1960 ret = rt_mutex_trylock(&q.pi_state->pi_mutex);
1961 /* Fixup the trylock return value: */
1962 ret = ret ? 0 : -EWOULDBLOCK;
1965 spin_lock(q.lock_ptr);
1967 * Fixup the pi_state owner and possibly acquire the lock if we
1968 * haven't already.
1970 res = fixup_owner(uaddr, fshared, &q, !ret);
1972 * If fixup_owner() returned an error, proprogate that. If it acquired
1973 * the lock, clear our -ETIMEDOUT or -EINTR.
1975 if (res)
1976 ret = (res < 0) ? res : 0;
1979 * If fixup_owner() faulted and was unable to handle the fault, unlock
1980 * it and return the fault to userspace.
1982 if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current))
1983 rt_mutex_unlock(&q.pi_state->pi_mutex);
1985 /* Unqueue and drop the lock */
1986 unqueue_me_pi(&q);
1988 goto out;
1990 out_unlock_put_key:
1991 queue_unlock(&q, hb);
1993 out_put_key:
1994 put_futex_key(fshared, &q.key);
1995 out:
1996 if (to)
1997 destroy_hrtimer_on_stack(&to->timer);
1998 return ret != -EINTR ? ret : -ERESTARTNOINTR;
2000 uaddr_faulted:
2001 queue_unlock(&q, hb);
2003 ret = get_user_writeable(uaddr);
2004 if (ret)
2005 goto out_put_key;
2007 if (!fshared)
2008 goto retry_private;
2010 put_futex_key(fshared, &q.key);
2011 goto retry;
2015 * Userspace attempted a TID -> 0 atomic transition, and failed.
2016 * This is the in-kernel slowpath: we look up the PI state (if any),
2017 * and do the rt-mutex unlock.
2019 static int futex_unlock_pi(u32 __user *uaddr, int fshared)
2021 struct futex_hash_bucket *hb;
2022 struct futex_q *this, *next;
2023 u32 uval;
2024 struct plist_head *head;
2025 union futex_key key = FUTEX_KEY_INIT;
2026 int ret;
2028 retry:
2029 if (get_user(uval, uaddr))
2030 return -EFAULT;
2032 * We release only a lock we actually own:
2034 if ((uval & FUTEX_TID_MASK) != task_pid_vnr(current))
2035 return -EPERM;
2037 ret = get_futex_key(uaddr, fshared, &key, VERIFY_WRITE);
2038 if (unlikely(ret != 0))
2039 goto out;
2041 hb = hash_futex(&key);
2042 spin_lock(&hb->lock);
2045 * To avoid races, try to do the TID -> 0 atomic transition
2046 * again. If it succeeds then we can return without waking
2047 * anyone else up:
2049 if (!(uval & FUTEX_OWNER_DIED))
2050 uval = cmpxchg_futex_value_locked(uaddr, task_pid_vnr(current), 0);
2053 if (unlikely(uval == -EFAULT))
2054 goto pi_faulted;
2056 * Rare case: we managed to release the lock atomically,
2057 * no need to wake anyone else up:
2059 if (unlikely(uval == task_pid_vnr(current)))
2060 goto out_unlock;
2063 * Ok, other tasks may need to be woken up - check waiters
2064 * and do the wakeup if necessary:
2066 head = &hb->chain;
2068 plist_for_each_entry_safe(this, next, head, list) {
2069 if (!match_futex (&this->key, &key))
2070 continue;
2071 ret = wake_futex_pi(uaddr, uval, this);
2073 * The atomic access to the futex value
2074 * generated a pagefault, so retry the
2075 * user-access and the wakeup:
2077 if (ret == -EFAULT)
2078 goto pi_faulted;
2079 goto out_unlock;
2082 * No waiters - kernel unlocks the futex:
2084 if (!(uval & FUTEX_OWNER_DIED)) {
2085 ret = unlock_futex_pi(uaddr, uval);
2086 if (ret == -EFAULT)
2087 goto pi_faulted;
2090 out_unlock:
2091 spin_unlock(&hb->lock);
2092 put_futex_key(fshared, &key);
2094 out:
2095 return ret;
2097 pi_faulted:
2098 spin_unlock(&hb->lock);
2099 put_futex_key(fshared, &key);
2101 ret = get_user_writeable(uaddr);
2102 if (!ret)
2103 goto retry;
2105 return ret;
2109 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
2110 * @hb: the hash_bucket futex_q was original enqueued on
2111 * @q: the futex_q woken while waiting to be requeued
2112 * @key2: the futex_key of the requeue target futex
2113 * @timeout: the timeout associated with the wait (NULL if none)
2115 * Detect if the task was woken on the initial futex as opposed to the requeue
2116 * target futex. If so, determine if it was a timeout or a signal that caused
2117 * the wakeup and return the appropriate error code to the caller. Must be
2118 * called with the hb lock held.
2120 * Returns
2121 * 0 - no early wakeup detected
2122 * <0 - -ETIMEDOUT or -ERESTARTNOINTR
2124 static inline
2125 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
2126 struct futex_q *q, union futex_key *key2,
2127 struct hrtimer_sleeper *timeout)
2129 int ret = 0;
2132 * With the hb lock held, we avoid races while we process the wakeup.
2133 * We only need to hold hb (and not hb2) to ensure atomicity as the
2134 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
2135 * It can't be requeued from uaddr2 to something else since we don't
2136 * support a PI aware source futex for requeue.
2138 if (!match_futex(&q->key, key2)) {
2139 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
2141 * We were woken prior to requeue by a timeout or a signal.
2142 * Unqueue the futex_q and determine which it was.
2144 plist_del(&q->list, &q->list.plist);
2145 drop_futex_key_refs(&q->key);
2147 if (timeout && !timeout->task)
2148 ret = -ETIMEDOUT;
2149 else
2150 ret = -ERESTARTNOINTR;
2152 return ret;
2156 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
2157 * @uaddr: the futex we initialyl wait on (non-pi)
2158 * @fshared: whether the futexes are shared (1) or not (0). They must be
2159 * the same type, no requeueing from private to shared, etc.
2160 * @val: the expected value of uaddr
2161 * @abs_time: absolute timeout
2162 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all.
2163 * @clockrt: whether to use CLOCK_REALTIME (1) or CLOCK_MONOTONIC (0)
2164 * @uaddr2: the pi futex we will take prior to returning to user-space
2166 * The caller will wait on uaddr and will be requeued by futex_requeue() to
2167 * uaddr2 which must be PI aware. Normal wakeup will wake on uaddr2 and
2168 * complete the acquisition of the rt_mutex prior to returning to userspace.
2169 * This ensures the rt_mutex maintains an owner when it has waiters; without
2170 * one, the pi logic wouldn't know which task to boost/deboost, if there was a
2171 * need to.
2173 * We call schedule in futex_wait_queue_me() when we enqueue and return there
2174 * via the following:
2175 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
2176 * 2) wakeup on uaddr2 after a requeue and subsequent unlock
2177 * 3) signal (before or after requeue)
2178 * 4) timeout (before or after requeue)
2180 * If 3, we setup a restart_block with futex_wait_requeue_pi() as the function.
2182 * If 2, we may then block on trying to take the rt_mutex and return via:
2183 * 5) successful lock
2184 * 6) signal
2185 * 7) timeout
2186 * 8) other lock acquisition failure
2188 * If 6, we setup a restart_block with futex_lock_pi() as the function.
2190 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
2192 * Returns:
2193 * 0 - On success
2194 * <0 - On error
2196 static int futex_wait_requeue_pi(u32 __user *uaddr, int fshared,
2197 u32 val, ktime_t *abs_time, u32 bitset,
2198 int clockrt, u32 __user *uaddr2)
2200 struct hrtimer_sleeper timeout, *to = NULL;
2201 struct rt_mutex_waiter rt_waiter;
2202 struct rt_mutex *pi_mutex = NULL;
2203 struct futex_hash_bucket *hb;
2204 union futex_key key2;
2205 struct futex_q q;
2206 int res, ret;
2208 if (!bitset)
2209 return -EINVAL;
2211 if (abs_time) {
2212 to = &timeout;
2213 hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
2214 CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2215 hrtimer_init_sleeper(to, current);
2216 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2217 current->timer_slack_ns);
2221 * The waiter is allocated on our stack, manipulated by the requeue
2222 * code while we sleep on uaddr.
2224 debug_rt_mutex_init_waiter(&rt_waiter);
2225 rt_waiter.task = NULL;
2227 q.pi_state = NULL;
2228 q.bitset = bitset;
2229 q.rt_waiter = &rt_waiter;
2231 key2 = FUTEX_KEY_INIT;
2232 ret = get_futex_key(uaddr2, fshared, &key2, VERIFY_WRITE);
2233 if (unlikely(ret != 0))
2234 goto out;
2236 /* Prepare to wait on uaddr. */
2237 ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
2238 if (ret)
2239 goto out_key2;
2241 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
2242 futex_wait_queue_me(hb, &q, to);
2244 spin_lock(&hb->lock);
2245 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
2246 spin_unlock(&hb->lock);
2247 if (ret)
2248 goto out_put_keys;
2251 * In order for us to be here, we know our q.key == key2, and since
2252 * we took the hb->lock above, we also know that futex_requeue() has
2253 * completed and we no longer have to concern ourselves with a wakeup
2254 * race with the atomic proxy lock acquition by the requeue code.
2257 /* Check if the requeue code acquired the second futex for us. */
2258 if (!q.rt_waiter) {
2260 * Got the lock. We might not be the anticipated owner if we
2261 * did a lock-steal - fix up the PI-state in that case.
2263 if (q.pi_state && (q.pi_state->owner != current)) {
2264 spin_lock(q.lock_ptr);
2265 ret = fixup_pi_state_owner(uaddr2, &q, current,
2266 fshared);
2267 spin_unlock(q.lock_ptr);
2269 } else {
2271 * We have been woken up by futex_unlock_pi(), a timeout, or a
2272 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
2273 * the pi_state.
2275 WARN_ON(!&q.pi_state);
2276 pi_mutex = &q.pi_state->pi_mutex;
2277 ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1);
2278 debug_rt_mutex_free_waiter(&rt_waiter);
2280 spin_lock(q.lock_ptr);
2282 * Fixup the pi_state owner and possibly acquire the lock if we
2283 * haven't already.
2285 res = fixup_owner(uaddr2, fshared, &q, !ret);
2287 * If fixup_owner() returned an error, proprogate that. If it
2288 * acquired the lock, clear our -ETIMEDOUT or -EINTR.
2290 if (res)
2291 ret = (res < 0) ? res : 0;
2293 /* Unqueue and drop the lock. */
2294 unqueue_me_pi(&q);
2298 * If fixup_pi_state_owner() faulted and was unable to handle the
2299 * fault, unlock the rt_mutex and return the fault to userspace.
2301 if (ret == -EFAULT) {
2302 if (rt_mutex_owner(pi_mutex) == current)
2303 rt_mutex_unlock(pi_mutex);
2304 } else if (ret == -EINTR) {
2306 * We've already been requeued, but we have no way to
2307 * restart by calling futex_lock_pi() directly. We
2308 * could restart the syscall, but that will look at
2309 * the user space value and return right away. So we
2310 * drop back with EWOULDBLOCK to tell user space that
2311 * "val" has been changed. That's the same what the
2312 * restart of the syscall would do in
2313 * futex_wait_setup().
2315 ret = -EWOULDBLOCK;
2318 out_put_keys:
2319 put_futex_key(fshared, &q.key);
2320 out_key2:
2321 put_futex_key(fshared, &key2);
2323 out:
2324 if (to) {
2325 hrtimer_cancel(&to->timer);
2326 destroy_hrtimer_on_stack(&to->timer);
2328 return ret;
2332 * Support for robust futexes: the kernel cleans up held futexes at
2333 * thread exit time.
2335 * Implementation: user-space maintains a per-thread list of locks it
2336 * is holding. Upon do_exit(), the kernel carefully walks this list,
2337 * and marks all locks that are owned by this thread with the
2338 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
2339 * always manipulated with the lock held, so the list is private and
2340 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
2341 * field, to allow the kernel to clean up if the thread dies after
2342 * acquiring the lock, but just before it could have added itself to
2343 * the list. There can only be one such pending lock.
2347 * sys_set_robust_list - set the robust-futex list head of a task
2348 * @head: pointer to the list-head
2349 * @len: length of the list-head, as userspace expects
2351 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
2352 size_t, len)
2354 if (!futex_cmpxchg_enabled)
2355 return -ENOSYS;
2357 * The kernel knows only one size for now:
2359 if (unlikely(len != sizeof(*head)))
2360 return -EINVAL;
2362 current->robust_list = head;
2364 return 0;
2368 * sys_get_robust_list - get the robust-futex list head of a task
2369 * @pid: pid of the process [zero for current task]
2370 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
2371 * @len_ptr: pointer to a length field, the kernel fills in the header size
2373 SYSCALL_DEFINE3(get_robust_list, int, pid,
2374 struct robust_list_head __user * __user *, head_ptr,
2375 size_t __user *, len_ptr)
2377 struct robust_list_head __user *head;
2378 unsigned long ret;
2379 const struct cred *cred = current_cred(), *pcred;
2381 if (!futex_cmpxchg_enabled)
2382 return -ENOSYS;
2384 if (!pid)
2385 head = current->robust_list;
2386 else {
2387 struct task_struct *p;
2389 ret = -ESRCH;
2390 rcu_read_lock();
2391 p = find_task_by_vpid(pid);
2392 if (!p)
2393 goto err_unlock;
2394 ret = -EPERM;
2395 pcred = __task_cred(p);
2396 if (cred->euid != pcred->euid &&
2397 cred->euid != pcred->uid &&
2398 !capable(CAP_SYS_PTRACE))
2399 goto err_unlock;
2400 head = p->robust_list;
2401 rcu_read_unlock();
2404 if (put_user(sizeof(*head), len_ptr))
2405 return -EFAULT;
2406 return put_user(head, head_ptr);
2408 err_unlock:
2409 rcu_read_unlock();
2411 return ret;
2415 * Process a futex-list entry, check whether it's owned by the
2416 * dying task, and do notification if so:
2418 int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
2420 u32 uval, nval, mval;
2422 retry:
2423 if (get_user(uval, uaddr))
2424 return -1;
2426 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
2428 * Ok, this dying thread is truly holding a futex
2429 * of interest. Set the OWNER_DIED bit atomically
2430 * via cmpxchg, and if the value had FUTEX_WAITERS
2431 * set, wake up a waiter (if any). (We have to do a
2432 * futex_wake() even if OWNER_DIED is already set -
2433 * to handle the rare but possible case of recursive
2434 * thread-death.) The rest of the cleanup is done in
2435 * userspace.
2437 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
2438 nval = futex_atomic_cmpxchg_inatomic(uaddr, uval, mval);
2440 if (nval == -EFAULT)
2441 return -1;
2443 if (nval != uval)
2444 goto retry;
2447 * Wake robust non-PI futexes here. The wakeup of
2448 * PI futexes happens in exit_pi_state():
2450 if (!pi && (uval & FUTEX_WAITERS))
2451 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
2453 return 0;
2457 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
2459 static inline int fetch_robust_entry(struct robust_list __user **entry,
2460 struct robust_list __user * __user *head,
2461 int *pi)
2463 unsigned long uentry;
2465 if (get_user(uentry, (unsigned long __user *)head))
2466 return -EFAULT;
2468 *entry = (void __user *)(uentry & ~1UL);
2469 *pi = uentry & 1;
2471 return 0;
2475 * Walk curr->robust_list (very carefully, it's a userspace list!)
2476 * and mark any locks found there dead, and notify any waiters.
2478 * We silently return on any sign of list-walking problem.
2480 void exit_robust_list(struct task_struct *curr)
2482 struct robust_list_head __user *head = curr->robust_list;
2483 struct robust_list __user *entry, *next_entry, *pending;
2484 unsigned int limit = ROBUST_LIST_LIMIT, pi, next_pi, pip;
2485 unsigned long futex_offset;
2486 int rc;
2488 if (!futex_cmpxchg_enabled)
2489 return;
2492 * Fetch the list head (which was registered earlier, via
2493 * sys_set_robust_list()):
2495 if (fetch_robust_entry(&entry, &head->list.next, &pi))
2496 return;
2498 * Fetch the relative futex offset:
2500 if (get_user(futex_offset, &head->futex_offset))
2501 return;
2503 * Fetch any possibly pending lock-add first, and handle it
2504 * if it exists:
2506 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
2507 return;
2509 next_entry = NULL; /* avoid warning with gcc */
2510 while (entry != &head->list) {
2512 * Fetch the next entry in the list before calling
2513 * handle_futex_death:
2515 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
2517 * A pending lock might already be on the list, so
2518 * don't process it twice:
2520 if (entry != pending)
2521 if (handle_futex_death((void __user *)entry + futex_offset,
2522 curr, pi))
2523 return;
2524 if (rc)
2525 return;
2526 entry = next_entry;
2527 pi = next_pi;
2529 * Avoid excessively long or circular lists:
2531 if (!--limit)
2532 break;
2534 cond_resched();
2537 if (pending)
2538 handle_futex_death((void __user *)pending + futex_offset,
2539 curr, pip);
2542 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
2543 u32 __user *uaddr2, u32 val2, u32 val3)
2545 int clockrt, ret = -ENOSYS;
2546 int cmd = op & FUTEX_CMD_MASK;
2547 int fshared = 0;
2549 if (!(op & FUTEX_PRIVATE_FLAG))
2550 fshared = 1;
2552 clockrt = op & FUTEX_CLOCK_REALTIME;
2553 if (clockrt && cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
2554 return -ENOSYS;
2556 switch (cmd) {
2557 case FUTEX_WAIT:
2558 val3 = FUTEX_BITSET_MATCH_ANY;
2559 case FUTEX_WAIT_BITSET:
2560 ret = futex_wait(uaddr, fshared, val, timeout, val3, clockrt);
2561 break;
2562 case FUTEX_WAKE:
2563 val3 = FUTEX_BITSET_MATCH_ANY;
2564 case FUTEX_WAKE_BITSET:
2565 ret = futex_wake(uaddr, fshared, val, val3);
2566 break;
2567 case FUTEX_REQUEUE:
2568 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, NULL, 0);
2569 break;
2570 case FUTEX_CMP_REQUEUE:
2571 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3,
2573 break;
2574 case FUTEX_WAKE_OP:
2575 ret = futex_wake_op(uaddr, fshared, uaddr2, val, val2, val3);
2576 break;
2577 case FUTEX_LOCK_PI:
2578 if (futex_cmpxchg_enabled)
2579 ret = futex_lock_pi(uaddr, fshared, val, timeout, 0);
2580 break;
2581 case FUTEX_UNLOCK_PI:
2582 if (futex_cmpxchg_enabled)
2583 ret = futex_unlock_pi(uaddr, fshared);
2584 break;
2585 case FUTEX_TRYLOCK_PI:
2586 if (futex_cmpxchg_enabled)
2587 ret = futex_lock_pi(uaddr, fshared, 0, timeout, 1);
2588 break;
2589 case FUTEX_WAIT_REQUEUE_PI:
2590 val3 = FUTEX_BITSET_MATCH_ANY;
2591 ret = futex_wait_requeue_pi(uaddr, fshared, val, timeout, val3,
2592 clockrt, uaddr2);
2593 break;
2594 case FUTEX_CMP_REQUEUE_PI:
2595 ret = futex_requeue(uaddr, fshared, uaddr2, val, val2, &val3,
2597 break;
2598 default:
2599 ret = -ENOSYS;
2601 return ret;
2605 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
2606 struct timespec __user *, utime, u32 __user *, uaddr2,
2607 u32, val3)
2609 struct timespec ts;
2610 ktime_t t, *tp = NULL;
2611 u32 val2 = 0;
2612 int cmd = op & FUTEX_CMD_MASK;
2614 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
2615 cmd == FUTEX_WAIT_BITSET ||
2616 cmd == FUTEX_WAIT_REQUEUE_PI)) {
2617 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
2618 return -EFAULT;
2619 if (!timespec_valid(&ts))
2620 return -EINVAL;
2622 t = timespec_to_ktime(ts);
2623 if (cmd == FUTEX_WAIT)
2624 t = ktime_add_safe(ktime_get(), t);
2625 tp = &t;
2628 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
2629 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
2631 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
2632 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
2633 val2 = (u32) (unsigned long) utime;
2635 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
2638 static int __init futex_init(void)
2640 u32 curval;
2641 int i;
2644 * This will fail and we want it. Some arch implementations do
2645 * runtime detection of the futex_atomic_cmpxchg_inatomic()
2646 * functionality. We want to know that before we call in any
2647 * of the complex code paths. Also we want to prevent
2648 * registration of robust lists in that case. NULL is
2649 * guaranteed to fault and we get -EFAULT on functional
2650 * implementation, the non functional ones will return
2651 * -ENOSYS.
2653 curval = cmpxchg_futex_value_locked(NULL, 0, 0);
2654 if (curval == -EFAULT)
2655 futex_cmpxchg_enabled = 1;
2657 for (i = 0; i < ARRAY_SIZE(futex_queues); i++) {
2658 #ifdef CONFIG_PREEMPT_RT
2659 plist_head_init(&futex_queues[i].chain, NULL);
2660 #else
2661 plist_head_init(&futex_queues[i].chain, &futex_queues[i].lock);
2662 #endif
2663 spin_lock_init(&futex_queues[i].lock);
2666 return 0;
2668 __initcall(futex_init);