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/compat.h>
48 #include <linux/slab.h>
49 #include <linux/poll.h>
51 #include <linux/file.h>
52 #include <linux/jhash.h>
53 #include <linux/init.h>
54 #include <linux/futex.h>
55 #include <linux/mount.h>
56 #include <linux/pagemap.h>
57 #include <linux/syscalls.h>
58 #include <linux/signal.h>
59 #include <linux/export.h>
60 #include <linux/magic.h>
61 #include <linux/pid.h>
62 #include <linux/nsproxy.h>
63 #include <linux/ptrace.h>
64 #include <linux/sched/rt.h>
65 #include <linux/hugetlb.h>
66 #include <linux/freezer.h>
67 #include <linux/bootmem.h>
68 #include <linux/fault-inject.h>
70 #include <asm/futex.h>
72 #include "locking/rtmutex_common.h"
75 * READ this before attempting to hack on futexes!
77 * Basic futex operation and ordering guarantees
78 * =============================================
80 * The waiter reads the futex value in user space and calls
81 * futex_wait(). This function computes the hash bucket and acquires
82 * the hash bucket lock. After that it reads the futex user space value
83 * again and verifies that the data has not changed. If it has not changed
84 * it enqueues itself into the hash bucket, releases the hash bucket lock
87 * The waker side modifies the user space value of the futex and calls
88 * futex_wake(). This function computes the hash bucket and acquires the
89 * hash bucket lock. Then it looks for waiters on that futex in the hash
90 * bucket and wakes them.
92 * In futex wake up scenarios where no tasks are blocked on a futex, taking
93 * the hb spinlock can be avoided and simply return. In order for this
94 * optimization to work, ordering guarantees must exist so that the waiter
95 * being added to the list is acknowledged when the list is concurrently being
96 * checked by the waker, avoiding scenarios like the following:
100 * sys_futex(WAIT, futex, val);
101 * futex_wait(futex, val);
104 * sys_futex(WAKE, futex);
109 * lock(hash_bucket(futex));
111 * unlock(hash_bucket(futex));
114 * This would cause the waiter on CPU 0 to wait forever because it
115 * missed the transition of the user space value from val to newval
116 * and the waker did not find the waiter in the hash bucket queue.
118 * The correct serialization ensures that a waiter either observes
119 * the changed user space value before blocking or is woken by a
124 * sys_futex(WAIT, futex, val);
125 * futex_wait(futex, val);
128 * mb(); (A) <-- paired with -.
130 * lock(hash_bucket(futex)); |
134 * | sys_futex(WAKE, futex);
135 * | futex_wake(futex);
137 * `-------> mb(); (B)
140 * unlock(hash_bucket(futex));
141 * schedule(); if (waiters)
142 * lock(hash_bucket(futex));
143 * else wake_waiters(futex);
144 * waiters--; (b) unlock(hash_bucket(futex));
146 * Where (A) orders the waiters increment and the futex value read through
147 * atomic operations (see hb_waiters_inc) and where (B) orders the write
148 * to futex and the waiters read -- this is done by the barriers for both
149 * shared and private futexes in get_futex_key_refs().
151 * This yields the following case (where X:=waiters, Y:=futex):
159 * Which guarantees that x==0 && y==0 is impossible; which translates back into
160 * the guarantee that we cannot both miss the futex variable change and the
163 * Note that a new waiter is accounted for in (a) even when it is possible that
164 * the wait call can return error, in which case we backtrack from it in (b).
165 * Refer to the comment in queue_lock().
167 * Similarly, in order to account for waiters being requeued on another
168 * address we always increment the waiters for the destination bucket before
169 * acquiring the lock. It then decrements them again after releasing it -
170 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
171 * will do the additional required waiter count housekeeping. This is done for
172 * double_lock_hb() and double_unlock_hb(), respectively.
175 #ifdef CONFIG_HAVE_FUTEX_CMPXCHG
176 #define futex_cmpxchg_enabled 1
178 static int __read_mostly futex_cmpxchg_enabled;
182 * Futex flags used to encode options to functions and preserve them across
185 #define FLAGS_SHARED 0x01
186 #define FLAGS_CLOCKRT 0x02
187 #define FLAGS_HAS_TIMEOUT 0x04
190 * Priority Inheritance state:
192 struct futex_pi_state {
194 * list of 'owned' pi_state instances - these have to be
195 * cleaned up in do_exit() if the task exits prematurely:
197 struct list_head list;
202 struct rt_mutex pi_mutex;
204 struct task_struct *owner;
211 * struct futex_q - The hashed futex queue entry, one per waiting task
212 * @list: priority-sorted list of tasks waiting on this futex
213 * @task: the task waiting on the futex
214 * @lock_ptr: the hash bucket lock
215 * @key: the key the futex is hashed on
216 * @pi_state: optional priority inheritance state
217 * @rt_waiter: rt_waiter storage for use with requeue_pi
218 * @requeue_pi_key: the requeue_pi target futex key
219 * @bitset: bitset for the optional bitmasked wakeup
221 * We use this hashed waitqueue, instead of a normal wait_queue_t, so
222 * we can wake only the relevant ones (hashed queues may be shared).
224 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
225 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
226 * The order of wakeup is always to make the first condition true, then
229 * PI futexes are typically woken before they are removed from the hash list via
230 * the rt_mutex code. See unqueue_me_pi().
233 struct plist_node list;
235 struct task_struct *task;
236 spinlock_t *lock_ptr;
238 struct futex_pi_state *pi_state;
239 struct rt_mutex_waiter *rt_waiter;
240 union futex_key *requeue_pi_key;
244 static const struct futex_q futex_q_init = {
245 /* list gets initialized in queue_me()*/
246 .key = FUTEX_KEY_INIT,
247 .bitset = FUTEX_BITSET_MATCH_ANY
251 * Hash buckets are shared by all the futex_keys that hash to the same
252 * location. Each key may have multiple futex_q structures, one for each task
253 * waiting on a futex.
255 struct futex_hash_bucket {
258 struct plist_head chain;
259 } ____cacheline_aligned_in_smp;
262 * The base of the bucket array and its size are always used together
263 * (after initialization only in hash_futex()), so ensure that they
264 * reside in the same cacheline.
267 struct futex_hash_bucket *queues;
268 unsigned long hashsize;
269 } __futex_data __read_mostly __aligned(2*sizeof(long));
270 #define futex_queues (__futex_data.queues)
271 #define futex_hashsize (__futex_data.hashsize)
275 * Fault injections for futexes.
277 #ifdef CONFIG_FAIL_FUTEX
280 struct fault_attr attr;
284 .attr = FAULT_ATTR_INITIALIZER,
285 .ignore_private = false,
288 static int __init setup_fail_futex(char *str)
290 return setup_fault_attr(&fail_futex.attr, str);
292 __setup("fail_futex=", setup_fail_futex);
294 static bool should_fail_futex(bool fshared)
296 if (fail_futex.ignore_private && !fshared)
299 return should_fail(&fail_futex.attr, 1);
302 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
304 static int __init fail_futex_debugfs(void)
306 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
309 dir = fault_create_debugfs_attr("fail_futex", NULL,
314 if (!debugfs_create_bool("ignore-private", mode, dir,
315 &fail_futex.ignore_private)) {
316 debugfs_remove_recursive(dir);
323 late_initcall(fail_futex_debugfs);
325 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
328 static inline bool should_fail_futex(bool fshared)
332 #endif /* CONFIG_FAIL_FUTEX */
335 static void compat_exit_robust_list(struct task_struct *curr);
337 static inline void compat_exit_robust_list(struct task_struct *curr) { }
340 static inline void futex_get_mm(union futex_key *key)
342 atomic_inc(&key->private.mm->mm_count);
344 * Ensure futex_get_mm() implies a full barrier such that
345 * get_futex_key() implies a full barrier. This is relied upon
346 * as full barrier (B), see the ordering comment above.
348 smp_mb__after_atomic();
352 * Reflects a new waiter being added to the waitqueue.
354 static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
357 atomic_inc(&hb->waiters);
359 * Full barrier (A), see the ordering comment above.
361 smp_mb__after_atomic();
366 * Reflects a waiter being removed from the waitqueue by wakeup
369 static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
372 atomic_dec(&hb->waiters);
376 static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
379 return atomic_read(&hb->waiters);
386 * We hash on the keys returned from get_futex_key (see below).
388 static struct futex_hash_bucket *hash_futex(union futex_key *key)
390 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
393 return &futex_queues[hash & (futex_hashsize - 1)];
397 * Return 1 if two futex_keys are equal, 0 otherwise.
399 static inline int match_futex(union futex_key *key1, union futex_key *key2)
402 && key1->both.word == key2->both.word
403 && key1->both.ptr == key2->both.ptr
404 && key1->both.offset == key2->both.offset);
408 * Take a reference to the resource addressed by a key.
409 * Can be called while holding spinlocks.
412 static void get_futex_key_refs(union futex_key *key)
417 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
419 smp_mb(); /* explicit smp_mb(); (B) */
421 case FUT_OFF_MMSHARED:
422 futex_get_mm(key); /* implies MB (B) */
426 * Private futexes do not hold reference on an inode or
427 * mm, therefore the only purpose of calling get_futex_key_refs
428 * is because we need the barrier for the lockless waiter check.
430 smp_mb(); /* explicit MB (B) */
435 * Drop a reference to the resource addressed by a key.
436 * The hash bucket spinlock must not be held. This is
437 * a no-op for private futexes, see comment in the get
440 static void drop_futex_key_refs(union futex_key *key)
442 if (!key->both.ptr) {
443 /* If we're here then we tried to put a key we failed to get */
448 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
451 case FUT_OFF_MMSHARED:
452 mmdrop(key->private.mm);
458 * Generate a machine wide unique identifier for this inode.
460 * This relies on u64 not wrapping in the life-time of the machine; which with
461 * 1ns resolution means almost 585 years.
463 * This further relies on the fact that a well formed program will not unmap
464 * the file while it has a (shared) futex waiting on it. This mapping will have
465 * a file reference which pins the mount and inode.
467 * If for some reason an inode gets evicted and read back in again, it will get
468 * a new sequence number and will _NOT_ match, even though it is the exact same
471 * It is important that match_futex() will never have a false-positive, esp.
472 * for PI futexes that can mess up the state. The above argues that false-negatives
473 * are only possible for malformed programs.
475 static u64 get_inode_sequence_number(struct inode *inode)
477 static atomic64_t i_seq;
480 /* Does the inode already have a sequence number? */
481 old = atomic64_read(&inode->i_sequence);
486 u64 new = atomic64_add_return(1, &i_seq);
487 if (WARN_ON_ONCE(!new))
490 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
498 * get_futex_key() - Get parameters which are the keys for a futex
499 * @uaddr: virtual address of the futex
500 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
501 * @key: address where result is stored.
502 * @rw: mapping needs to be read/write (values: VERIFY_READ,
505 * Return: a negative error code or 0
507 * The key words are stored in *key on success.
509 * For shared mappings (when @fshared), the key is:
510 * ( inode->i_sequence, page->index, offset_within_page )
511 * [ also see get_inode_sequence_number() ]
513 * For private mappings (or when !@fshared), the key is:
514 * ( current->mm, address, 0 )
516 * This allows (cross process, where applicable) identification of the futex
517 * without keeping the page pinned for the duration of the FUTEX_WAIT.
519 * lock_page() might sleep, the caller should not hold a spinlock.
522 get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, int rw)
524 unsigned long address = (unsigned long)uaddr;
525 struct mm_struct *mm = current->mm;
526 struct page *page, *page_head;
527 struct address_space *mapping;
531 * The futex address must be "naturally" aligned.
533 key->both.offset = address % PAGE_SIZE;
534 if (unlikely((address % sizeof(u32)) != 0))
536 address -= key->both.offset;
538 if (unlikely(!access_ok(rw, uaddr, sizeof(u32))))
541 if (unlikely(should_fail_futex(fshared)))
545 * PROCESS_PRIVATE futexes are fast.
546 * As the mm cannot disappear under us and the 'key' only needs
547 * virtual address, we dont even have to find the underlying vma.
548 * Note : We do have to check 'uaddr' is a valid user address,
549 * but access_ok() should be faster than find_vma()
552 key->private.mm = mm;
553 key->private.address = address;
554 get_futex_key_refs(key); /* implies MB (B) */
559 /* Ignore any VERIFY_READ mapping (futex common case) */
560 if (unlikely(should_fail_futex(fshared)))
563 err = get_user_pages_fast(address, 1, 1, &page);
565 * If write access is not required (eg. FUTEX_WAIT), try
566 * and get read-only access.
568 if (err == -EFAULT && rw == VERIFY_READ) {
569 err = get_user_pages_fast(address, 1, 0, &page);
577 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
579 if (unlikely(PageTail(page))) {
581 /* serialize against __split_huge_page_splitting() */
583 if (likely(__get_user_pages_fast(address, 1, !ro, &page) == 1)) {
584 page_head = compound_head(page);
586 * page_head is valid pointer but we must pin
587 * it before taking the PG_lock and/or
588 * PG_compound_lock. The moment we re-enable
589 * irqs __split_huge_page_splitting() can
590 * return and the head page can be freed from
591 * under us. We can't take the PG_lock and/or
592 * PG_compound_lock on a page that could be
593 * freed from under us.
595 if (page != page_head) {
606 page_head = compound_head(page);
607 if (page != page_head) {
614 * The treatment of mapping from this point on is critical. The page
615 * lock protects many things but in this context the page lock
616 * stabilizes mapping, prevents inode freeing in the shared
617 * file-backed region case and guards against movement to swap cache.
619 * Strictly speaking the page lock is not needed in all cases being
620 * considered here and page lock forces unnecessarily serialization
621 * From this point on, mapping will be re-verified if necessary and
622 * page lock will be acquired only if it is unavoidable
625 mapping = READ_ONCE(page_head->mapping);
628 * If page_head->mapping is NULL, then it cannot be a PageAnon
629 * page; but it might be the ZERO_PAGE or in the gate area or
630 * in a special mapping (all cases which we are happy to fail);
631 * or it may have been a good file page when get_user_pages_fast
632 * found it, but truncated or holepunched or subjected to
633 * invalidate_complete_page2 before we got the page lock (also
634 * cases which we are happy to fail). And we hold a reference,
635 * so refcount care in invalidate_complete_page's remove_mapping
636 * prevents drop_caches from setting mapping to NULL beneath us.
638 * The case we do have to guard against is when memory pressure made
639 * shmem_writepage move it from filecache to swapcache beneath us:
640 * an unlikely race, but we do need to retry for page_head->mapping.
642 if (unlikely(!mapping)) {
646 * Page lock is required to identify which special case above
647 * applies. If this is really a shmem page then the page lock
648 * will prevent unexpected transitions.
650 lock_page(page_head);
651 shmem_swizzled = PageSwapCache(page_head) || page_head->mapping;
652 unlock_page(page_head);
662 * Private mappings are handled in a simple way.
664 * If the futex key is stored on an anonymous page, then the associated
665 * object is the mm which is implicitly pinned by the calling process.
667 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
668 * it's a read-only handle, it's expected that futexes attach to
669 * the object not the particular process.
671 if (PageAnon(page_head)) {
673 * A RO anonymous page will never change and thus doesn't make
674 * sense for futex operations.
676 if (unlikely(should_fail_futex(fshared)) || ro) {
681 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
682 key->private.mm = mm;
683 key->private.address = address;
689 * The associated futex object in this case is the inode and
690 * the page->mapping must be traversed. Ordinarily this should
691 * be stabilised under page lock but it's not strictly
692 * necessary in this case as we just want to pin the inode, not
693 * update the radix tree or anything like that.
695 * The RCU read lock is taken as the inode is finally freed
696 * under RCU. If the mapping still matches expectations then the
697 * mapping->host can be safely accessed as being a valid inode.
701 if (READ_ONCE(page_head->mapping) != mapping) {
708 inode = READ_ONCE(mapping->host);
716 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
717 key->shared.i_seq = get_inode_sequence_number(inode);
718 key->shared.pgoff = basepage_index(page);
722 get_futex_key_refs(key); /* implies smp_mb(); (B) */
729 static inline void put_futex_key(union futex_key *key)
731 drop_futex_key_refs(key);
735 * fault_in_user_writeable() - Fault in user address and verify RW access
736 * @uaddr: pointer to faulting user space address
738 * Slow path to fixup the fault we just took in the atomic write
741 * We have no generic implementation of a non-destructive write to the
742 * user address. We know that we faulted in the atomic pagefault
743 * disabled section so we can as well avoid the #PF overhead by
744 * calling get_user_pages() right away.
746 static int fault_in_user_writeable(u32 __user *uaddr)
748 struct mm_struct *mm = current->mm;
751 down_read(&mm->mmap_sem);
752 ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
754 up_read(&mm->mmap_sem);
756 return ret < 0 ? ret : 0;
760 * futex_top_waiter() - Return the highest priority waiter on a futex
761 * @hb: the hash bucket the futex_q's reside in
762 * @key: the futex key (to distinguish it from other futex futex_q's)
764 * Must be called with the hb lock held.
766 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
767 union futex_key *key)
769 struct futex_q *this;
771 plist_for_each_entry(this, &hb->chain, list) {
772 if (match_futex(&this->key, key))
778 static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
779 u32 uval, u32 newval)
784 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
790 static int get_futex_value_locked(u32 *dest, u32 __user *from)
795 ret = __copy_from_user_inatomic(dest, from, sizeof(u32));
798 return ret ? -EFAULT : 0;
805 static int refill_pi_state_cache(void)
807 struct futex_pi_state *pi_state;
809 if (likely(current->pi_state_cache))
812 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
817 INIT_LIST_HEAD(&pi_state->list);
818 /* pi_mutex gets initialized later */
819 pi_state->owner = NULL;
820 atomic_set(&pi_state->refcount, 1);
821 pi_state->key = FUTEX_KEY_INIT;
823 current->pi_state_cache = pi_state;
828 static struct futex_pi_state *alloc_pi_state(void)
830 struct futex_pi_state *pi_state = current->pi_state_cache;
833 current->pi_state_cache = NULL;
838 static void pi_state_update_owner(struct futex_pi_state *pi_state,
839 struct task_struct *new_owner)
841 struct task_struct *old_owner = pi_state->owner;
843 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
846 raw_spin_lock(&old_owner->pi_lock);
847 WARN_ON(list_empty(&pi_state->list));
848 list_del_init(&pi_state->list);
849 raw_spin_unlock(&old_owner->pi_lock);
853 raw_spin_lock(&new_owner->pi_lock);
854 WARN_ON(!list_empty(&pi_state->list));
855 list_add(&pi_state->list, &new_owner->pi_state_list);
856 pi_state->owner = new_owner;
857 raw_spin_unlock(&new_owner->pi_lock);
861 static void get_pi_state(struct futex_pi_state *pi_state)
863 WARN_ON_ONCE(!atomic_inc_not_zero(&pi_state->refcount));
867 * Drops a reference to the pi_state object and frees or caches it
868 * when the last reference is gone.
870 * Must be called with the hb lock held.
872 static void put_pi_state(struct futex_pi_state *pi_state)
877 if (!atomic_dec_and_test(&pi_state->refcount))
881 * If pi_state->owner is NULL, the owner is most probably dying
882 * and has cleaned up the pi_state already
884 if (pi_state->owner) {
885 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
886 pi_state_update_owner(pi_state, NULL);
887 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
888 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
891 if (current->pi_state_cache)
895 * pi_state->list is already empty.
896 * clear pi_state->owner.
897 * refcount is at 0 - put it back to 1.
899 pi_state->owner = NULL;
900 atomic_set(&pi_state->refcount, 1);
901 current->pi_state_cache = pi_state;
906 * Look up the task based on what TID userspace gave us.
909 static struct task_struct *futex_find_get_task(pid_t pid)
911 struct task_struct *p;
914 p = find_task_by_vpid(pid);
924 * This task is holding PI mutexes at exit time => bad.
925 * Kernel cleans up PI-state, but userspace is likely hosed.
926 * (Robust-futex cleanup is separate and might save the day for userspace.)
928 static void exit_pi_state_list(struct task_struct *curr)
930 struct list_head *next, *head = &curr->pi_state_list;
931 struct futex_pi_state *pi_state;
932 struct futex_hash_bucket *hb;
933 union futex_key key = FUTEX_KEY_INIT;
935 if (!futex_cmpxchg_enabled)
938 * We are a ZOMBIE and nobody can enqueue itself on
939 * pi_state_list anymore, but we have to be careful
940 * versus waiters unqueueing themselves:
942 raw_spin_lock_irq(&curr->pi_lock);
943 while (!list_empty(head)) {
946 pi_state = list_entry(next, struct futex_pi_state, list);
948 hb = hash_futex(&key);
949 raw_spin_unlock_irq(&curr->pi_lock);
951 spin_lock(&hb->lock);
953 raw_spin_lock_irq(&curr->pi_lock);
955 * We dropped the pi-lock, so re-check whether this
956 * task still owns the PI-state:
958 if (head->next != next) {
959 spin_unlock(&hb->lock);
963 WARN_ON(pi_state->owner != curr);
964 WARN_ON(list_empty(&pi_state->list));
965 list_del_init(&pi_state->list);
966 pi_state->owner = NULL;
967 raw_spin_unlock_irq(&curr->pi_lock);
969 get_pi_state(pi_state);
970 spin_unlock(&hb->lock);
972 rt_mutex_futex_unlock(&pi_state->pi_mutex);
973 put_pi_state(pi_state);
975 raw_spin_lock_irq(&curr->pi_lock);
977 raw_spin_unlock_irq(&curr->pi_lock);
981 * We need to check the following states:
983 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
985 * [1] NULL | --- | --- | 0 | 0/1 | Valid
986 * [2] NULL | --- | --- | >0 | 0/1 | Valid
988 * [3] Found | NULL | -- | Any | 0/1 | Invalid
990 * [4] Found | Found | NULL | 0 | 1 | Valid
991 * [5] Found | Found | NULL | >0 | 1 | Invalid
993 * [6] Found | Found | task | 0 | 1 | Valid
995 * [7] Found | Found | NULL | Any | 0 | Invalid
997 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
998 * [9] Found | Found | task | 0 | 0 | Invalid
999 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
1001 * [1] Indicates that the kernel can acquire the futex atomically. We
1002 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
1004 * [2] Valid, if TID does not belong to a kernel thread. If no matching
1005 * thread is found then it indicates that the owner TID has died.
1007 * [3] Invalid. The waiter is queued on a non PI futex
1009 * [4] Valid state after exit_robust_list(), which sets the user space
1010 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
1012 * [5] The user space value got manipulated between exit_robust_list()
1013 * and exit_pi_state_list()
1015 * [6] Valid state after exit_pi_state_list() which sets the new owner in
1016 * the pi_state but cannot access the user space value.
1018 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
1020 * [8] Owner and user space value match
1022 * [9] There is no transient state which sets the user space TID to 0
1023 * except exit_robust_list(), but this is indicated by the
1024 * FUTEX_OWNER_DIED bit. See [4]
1026 * [10] There is no transient state which leaves owner and user space
1027 * TID out of sync. Except one error case where the kernel is denied
1028 * write access to the user address, see fixup_pi_state_owner().
1031 * Serialization and lifetime rules:
1035 * hb -> futex_q, relation
1036 * futex_q -> pi_state, relation
1038 * (cannot be raw because hb can contain arbitrary amount
1041 * pi_mutex->wait_lock:
1045 * (and pi_mutex 'obviously')
1049 * p->pi_state_list -> pi_state->list, relation
1051 * pi_state->refcount:
1059 * pi_mutex->wait_lock
1065 * Validate that the existing waiter has a pi_state and sanity check
1066 * the pi_state against the user space value. If correct, attach to
1069 static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1070 struct futex_pi_state *pi_state,
1071 struct futex_pi_state **ps)
1073 pid_t pid = uval & FUTEX_TID_MASK;
1077 * Userspace might have messed up non-PI and PI futexes [3]
1079 if (unlikely(!pi_state))
1083 * We get here with hb->lock held, and having found a
1084 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1085 * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
1086 * which in turn means that futex_lock_pi() still has a reference on
1089 * The waiter holding a reference on @pi_state also protects against
1090 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1091 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1092 * free pi_state before we can take a reference ourselves.
1094 WARN_ON(!atomic_read(&pi_state->refcount));
1097 * Now that we have a pi_state, we can acquire wait_lock
1098 * and do the state validation.
1100 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1103 * Since {uval, pi_state} is serialized by wait_lock, and our current
1104 * uval was read without holding it, it can have changed. Verify it
1105 * still is what we expect it to be, otherwise retry the entire
1108 if (get_futex_value_locked(&uval2, uaddr))
1115 * Handle the owner died case:
1117 if (uval & FUTEX_OWNER_DIED) {
1119 * exit_pi_state_list sets owner to NULL and wakes the
1120 * topmost waiter. The task which acquires the
1121 * pi_state->rt_mutex will fixup owner.
1123 if (!pi_state->owner) {
1125 * No pi state owner, but the user space TID
1126 * is not 0. Inconsistent state. [5]
1131 * Take a ref on the state and return success. [4]
1137 * If TID is 0, then either the dying owner has not
1138 * yet executed exit_pi_state_list() or some waiter
1139 * acquired the rtmutex in the pi state, but did not
1140 * yet fixup the TID in user space.
1142 * Take a ref on the state and return success. [6]
1148 * If the owner died bit is not set, then the pi_state
1149 * must have an owner. [7]
1151 if (!pi_state->owner)
1156 * Bail out if user space manipulated the futex value. If pi
1157 * state exists then the owner TID must be the same as the
1158 * user space TID. [9/10]
1160 if (pid != task_pid_vnr(pi_state->owner))
1164 get_pi_state(pi_state);
1165 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1182 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1187 * wait_for_owner_exiting - Block until the owner has exited
1188 * @exiting: Pointer to the exiting task
1190 * Caller must hold a refcount on @exiting.
1192 static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1194 if (ret != -EBUSY) {
1195 WARN_ON_ONCE(exiting);
1199 if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
1202 mutex_lock(&exiting->futex_exit_mutex);
1204 * No point in doing state checking here. If the waiter got here
1205 * while the task was in exec()->exec_futex_release() then it can
1206 * have any FUTEX_STATE_* value when the waiter has acquired the
1207 * mutex. OK, if running, EXITING or DEAD if it reached exit()
1208 * already. Highly unlikely and not a problem. Just one more round
1209 * through the futex maze.
1211 mutex_unlock(&exiting->futex_exit_mutex);
1213 put_task_struct(exiting);
1216 static int handle_exit_race(u32 __user *uaddr, u32 uval,
1217 struct task_struct *tsk)
1222 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1223 * caller that the alleged owner is busy.
1225 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
1229 * Reread the user space value to handle the following situation:
1233 * sys_exit() sys_futex()
1234 * do_exit() futex_lock_pi()
1235 * futex_lock_pi_atomic()
1236 * exit_signals(tsk) No waiters:
1237 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1238 * mm_release(tsk) Set waiter bit
1239 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1240 * Set owner died attach_to_pi_owner() {
1241 * *uaddr = 0xC0000000; tsk = get_task(PID);
1242 * } if (!tsk->flags & PF_EXITING) {
1244 * tsk->futex_state = } else {
1245 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1248 * return -ESRCH; <--- FAIL
1251 * Returning ESRCH unconditionally is wrong here because the
1252 * user space value has been changed by the exiting task.
1254 * The same logic applies to the case where the exiting task is
1257 if (get_futex_value_locked(&uval2, uaddr))
1260 /* If the user space value has changed, try again. */
1265 * The exiting task did not have a robust list, the robust list was
1266 * corrupted or the user space value in *uaddr is simply bogus.
1267 * Give up and tell user space.
1273 * Lookup the task for the TID provided from user space and attach to
1274 * it after doing proper sanity checks.
1276 static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
1277 struct futex_pi_state **ps,
1278 struct task_struct **exiting)
1280 pid_t pid = uval & FUTEX_TID_MASK;
1281 struct futex_pi_state *pi_state;
1282 struct task_struct *p;
1285 * We are the first waiter - try to look up the real owner and attach
1286 * the new pi_state to it, but bail out when TID = 0 [1]
1288 * The !pid check is paranoid. None of the call sites should end up
1289 * with pid == 0, but better safe than sorry. Let the caller retry
1293 p = futex_find_get_task(pid);
1295 return handle_exit_race(uaddr, uval, NULL);
1297 if (unlikely(p->flags & PF_KTHREAD)) {
1303 * We need to look at the task state to figure out, whether the
1304 * task is exiting. To protect against the change of the task state
1305 * in futex_exit_release(), we do this protected by p->pi_lock:
1307 raw_spin_lock_irq(&p->pi_lock);
1308 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
1310 * The task is on the way out. When the futex state is
1311 * FUTEX_STATE_DEAD, we know that the task has finished
1314 int ret = handle_exit_race(uaddr, uval, p);
1316 raw_spin_unlock_irq(&p->pi_lock);
1318 * If the owner task is between FUTEX_STATE_EXITING and
1319 * FUTEX_STATE_DEAD then store the task pointer and keep
1320 * the reference on the task struct. The calling code will
1321 * drop all locks, wait for the task to reach
1322 * FUTEX_STATE_DEAD and then drop the refcount. This is
1323 * required to prevent a live lock when the current task
1324 * preempted the exiting task between the two states.
1334 * No existing pi state. First waiter. [2]
1336 * This creates pi_state, we have hb->lock held, this means nothing can
1337 * observe this state, wait_lock is irrelevant.
1339 pi_state = alloc_pi_state();
1342 * Initialize the pi_mutex in locked state and make @p
1345 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1347 /* Store the key for possible exit cleanups: */
1348 pi_state->key = *key;
1350 WARN_ON(!list_empty(&pi_state->list));
1351 list_add(&pi_state->list, &p->pi_state_list);
1352 pi_state->owner = p;
1353 raw_spin_unlock_irq(&p->pi_lock);
1362 static int lookup_pi_state(u32 __user *uaddr, u32 uval,
1363 struct futex_hash_bucket *hb,
1364 union futex_key *key, struct futex_pi_state **ps,
1365 struct task_struct **exiting)
1367 struct futex_q *match = futex_top_waiter(hb, key);
1370 * If there is a waiter on that futex, validate it and
1371 * attach to the pi_state when the validation succeeds.
1374 return attach_to_pi_state(uaddr, uval, match->pi_state, ps);
1377 * We are the first waiter - try to look up the owner based on
1378 * @uval and attach to it.
1380 return attach_to_pi_owner(uaddr, uval, key, ps, exiting);
1383 static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1385 u32 uninitialized_var(curval);
1387 if (unlikely(should_fail_futex(true)))
1390 if (unlikely(cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)))
1393 /* If user space value changed, let the caller retry */
1394 return curval != uval ? -EAGAIN : 0;
1398 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
1399 * @uaddr: the pi futex user address
1400 * @hb: the pi futex hash bucket
1401 * @key: the futex key associated with uaddr and hb
1402 * @ps: the pi_state pointer where we store the result of the
1404 * @task: the task to perform the atomic lock work for. This will
1405 * be "current" except in the case of requeue pi.
1406 * @exiting: Pointer to store the task pointer of the owner task
1407 * which is in the middle of exiting
1408 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1411 * 0 - ready to wait;
1412 * 1 - acquired the lock;
1415 * The hb->lock and futex_key refs shall be held by the caller.
1417 * @exiting is only set when the return value is -EBUSY. If so, this holds
1418 * a refcount on the exiting task on return and the caller needs to drop it
1419 * after waiting for the exit to complete.
1421 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1422 union futex_key *key,
1423 struct futex_pi_state **ps,
1424 struct task_struct *task,
1425 struct task_struct **exiting,
1428 u32 uval, newval, vpid = task_pid_vnr(task);
1429 struct futex_q *match;
1433 * Read the user space value first so we can validate a few
1434 * things before proceeding further.
1436 if (get_futex_value_locked(&uval, uaddr))
1439 if (unlikely(should_fail_futex(true)))
1445 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1448 if ((unlikely(should_fail_futex(true))))
1452 * Lookup existing state first. If it exists, try to attach to
1455 match = futex_top_waiter(hb, key);
1457 return attach_to_pi_state(uaddr, uval, match->pi_state, ps);
1460 * No waiter and user TID is 0. We are here because the
1461 * waiters or the owner died bit is set or called from
1462 * requeue_cmp_pi or for whatever reason something took the
1465 if (!(uval & FUTEX_TID_MASK)) {
1467 * We take over the futex. No other waiters and the user space
1468 * TID is 0. We preserve the owner died bit.
1470 newval = uval & FUTEX_OWNER_DIED;
1473 /* The futex requeue_pi code can enforce the waiters bit */
1475 newval |= FUTEX_WAITERS;
1477 ret = lock_pi_update_atomic(uaddr, uval, newval);
1478 /* If the take over worked, return 1 */
1479 return ret < 0 ? ret : 1;
1483 * First waiter. Set the waiters bit before attaching ourself to
1484 * the owner. If owner tries to unlock, it will be forced into
1485 * the kernel and blocked on hb->lock.
1487 newval = uval | FUTEX_WAITERS;
1488 ret = lock_pi_update_atomic(uaddr, uval, newval);
1492 * If the update of the user space value succeeded, we try to
1493 * attach to the owner. If that fails, no harm done, we only
1494 * set the FUTEX_WAITERS bit in the user space variable.
1496 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
1500 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1501 * @q: The futex_q to unqueue
1503 * The q->lock_ptr must not be NULL and must be held by the caller.
1505 static void __unqueue_futex(struct futex_q *q)
1507 struct futex_hash_bucket *hb;
1509 if (WARN_ON_SMP(!q->lock_ptr || !spin_is_locked(q->lock_ptr))
1510 || WARN_ON(plist_node_empty(&q->list)))
1513 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1514 plist_del(&q->list, &hb->chain);
1519 * The hash bucket lock must be held when this is called.
1520 * Afterwards, the futex_q must not be accessed. Callers
1521 * must ensure to later call wake_up_q() for the actual
1524 static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
1526 struct task_struct *p = q->task;
1528 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1532 * Queue the task for later wakeup for after we've released
1533 * the hb->lock. wake_q_add() grabs reference to p.
1535 wake_q_add(wake_q, p);
1538 * The waiting task can free the futex_q as soon as
1539 * q->lock_ptr = NULL is written, without taking any locks. A
1540 * memory barrier is required here to prevent the following
1541 * store to lock_ptr from getting ahead of the plist_del.
1548 * Caller must hold a reference on @pi_state.
1550 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
1552 u32 uninitialized_var(curval), newval;
1553 struct task_struct *new_owner;
1554 bool deboost = false;
1558 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
1559 if (WARN_ON_ONCE(!new_owner)) {
1561 * As per the comment in futex_unlock_pi() this should not happen.
1563 * When this happens, give up our locks and try again, giving
1564 * the futex_lock_pi() instance time to complete, either by
1565 * waiting on the rtmutex or removing itself from the futex
1573 * We pass it to the next owner. The WAITERS bit is always kept
1574 * enabled while there is PI state around. We cleanup the owner
1575 * died bit, because we are the owner.
1577 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
1579 if (unlikely(should_fail_futex(true)))
1582 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval)) {
1585 } else if (curval != uval) {
1587 * If a unconditional UNLOCK_PI operation (user space did not
1588 * try the TID->0 transition) raced with a waiter setting the
1589 * FUTEX_WAITERS flag between get_user() and locking the hash
1590 * bucket lock, retry the operation.
1592 if ((FUTEX_TID_MASK & curval) == uval)
1600 * This is a point of no return; once we modified the uval
1601 * there is no going back and subsequent operations must
1604 pi_state_update_owner(pi_state, new_owner);
1605 deboost = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
1609 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1613 rt_mutex_adjust_prio(current);
1620 * Express the locking dependencies for lockdep:
1623 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1626 spin_lock(&hb1->lock);
1628 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1629 } else { /* hb1 > hb2 */
1630 spin_lock(&hb2->lock);
1631 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1636 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1638 spin_unlock(&hb1->lock);
1640 spin_unlock(&hb2->lock);
1644 * Wake up waiters matching bitset queued on this futex (uaddr).
1647 futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1649 struct futex_hash_bucket *hb;
1650 struct futex_q *this, *next;
1651 union futex_key key = FUTEX_KEY_INIT;
1658 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_READ);
1659 if (unlikely(ret != 0))
1662 hb = hash_futex(&key);
1664 /* Make sure we really have tasks to wakeup */
1665 if (!hb_waiters_pending(hb))
1668 spin_lock(&hb->lock);
1670 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1671 if (match_futex (&this->key, &key)) {
1672 if (this->pi_state || this->rt_waiter) {
1677 /* Check if one of the bits is set in both bitsets */
1678 if (!(this->bitset & bitset))
1681 mark_wake_futex(&wake_q, this);
1682 if (++ret >= nr_wake)
1687 spin_unlock(&hb->lock);
1690 put_futex_key(&key);
1695 static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1697 unsigned int op = (encoded_op & 0x70000000) >> 28;
1698 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
1699 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1700 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
1703 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
1704 if (oparg < 0 || oparg > 31) {
1705 char comm[sizeof(current->comm)];
1707 * kill this print and return -EINVAL when userspace
1710 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1711 get_task_comm(comm, current), oparg);
1717 if (!access_ok(VERIFY_WRITE, uaddr, sizeof(u32)))
1720 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
1725 case FUTEX_OP_CMP_EQ:
1726 return oldval == cmparg;
1727 case FUTEX_OP_CMP_NE:
1728 return oldval != cmparg;
1729 case FUTEX_OP_CMP_LT:
1730 return oldval < cmparg;
1731 case FUTEX_OP_CMP_GE:
1732 return oldval >= cmparg;
1733 case FUTEX_OP_CMP_LE:
1734 return oldval <= cmparg;
1735 case FUTEX_OP_CMP_GT:
1736 return oldval > cmparg;
1743 * Wake up all waiters hashed on the physical page that is mapped
1744 * to this virtual address:
1747 futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
1748 int nr_wake, int nr_wake2, int op)
1750 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1751 struct futex_hash_bucket *hb1, *hb2;
1752 struct futex_q *this, *next;
1757 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
1758 if (unlikely(ret != 0))
1760 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
1761 if (unlikely(ret != 0))
1764 hb1 = hash_futex(&key1);
1765 hb2 = hash_futex(&key2);
1768 double_lock_hb(hb1, hb2);
1769 op_ret = futex_atomic_op_inuser(op, uaddr2);
1770 if (unlikely(op_ret < 0)) {
1772 double_unlock_hb(hb1, hb2);
1776 * we don't get EFAULT from MMU faults if we don't have an MMU,
1777 * but we might get them from range checking
1783 if (unlikely(op_ret != -EFAULT)) {
1788 ret = fault_in_user_writeable(uaddr2);
1792 if (!(flags & FLAGS_SHARED))
1795 put_futex_key(&key2);
1796 put_futex_key(&key1);
1800 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
1801 if (match_futex (&this->key, &key1)) {
1802 if (this->pi_state || this->rt_waiter) {
1806 mark_wake_futex(&wake_q, this);
1807 if (++ret >= nr_wake)
1814 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
1815 if (match_futex (&this->key, &key2)) {
1816 if (this->pi_state || this->rt_waiter) {
1820 mark_wake_futex(&wake_q, this);
1821 if (++op_ret >= nr_wake2)
1829 double_unlock_hb(hb1, hb2);
1832 put_futex_key(&key2);
1834 put_futex_key(&key1);
1840 * requeue_futex() - Requeue a futex_q from one hb to another
1841 * @q: the futex_q to requeue
1842 * @hb1: the source hash_bucket
1843 * @hb2: the target hash_bucket
1844 * @key2: the new key for the requeued futex_q
1847 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1848 struct futex_hash_bucket *hb2, union futex_key *key2)
1852 * If key1 and key2 hash to the same bucket, no need to
1855 if (likely(&hb1->chain != &hb2->chain)) {
1856 plist_del(&q->list, &hb1->chain);
1857 hb_waiters_dec(hb1);
1858 hb_waiters_inc(hb2);
1859 plist_add(&q->list, &hb2->chain);
1860 q->lock_ptr = &hb2->lock;
1862 get_futex_key_refs(key2);
1867 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1869 * @key: the key of the requeue target futex
1870 * @hb: the hash_bucket of the requeue target futex
1872 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1873 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1874 * to the requeue target futex so the waiter can detect the wakeup on the right
1875 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1876 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1877 * to protect access to the pi_state to fixup the owner later. Must be called
1878 * with both q->lock_ptr and hb->lock held.
1881 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1882 struct futex_hash_bucket *hb)
1884 get_futex_key_refs(key);
1889 WARN_ON(!q->rt_waiter);
1890 q->rt_waiter = NULL;
1892 q->lock_ptr = &hb->lock;
1894 wake_up_state(q->task, TASK_NORMAL);
1898 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1899 * @pifutex: the user address of the to futex
1900 * @hb1: the from futex hash bucket, must be locked by the caller
1901 * @hb2: the to futex hash bucket, must be locked by the caller
1902 * @key1: the from futex key
1903 * @key2: the to futex key
1904 * @ps: address to store the pi_state pointer
1905 * @exiting: Pointer to store the task pointer of the owner task
1906 * which is in the middle of exiting
1907 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1909 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1910 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1911 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1912 * hb1 and hb2 must be held by the caller.
1914 * @exiting is only set when the return value is -EBUSY. If so, this holds
1915 * a refcount on the exiting task on return and the caller needs to drop it
1916 * after waiting for the exit to complete.
1919 * 0 - failed to acquire the lock atomically;
1920 * >0 - acquired the lock, return value is vpid of the top_waiter
1924 futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
1925 struct futex_hash_bucket *hb2, union futex_key *key1,
1926 union futex_key *key2, struct futex_pi_state **ps,
1927 struct task_struct **exiting, int set_waiters)
1929 struct futex_q *top_waiter = NULL;
1933 if (get_futex_value_locked(&curval, pifutex))
1936 if (unlikely(should_fail_futex(true)))
1940 * Find the top_waiter and determine if there are additional waiters.
1941 * If the caller intends to requeue more than 1 waiter to pifutex,
1942 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1943 * as we have means to handle the possible fault. If not, don't set
1944 * the bit unecessarily as it will force the subsequent unlock to enter
1947 top_waiter = futex_top_waiter(hb1, key1);
1949 /* There are no waiters, nothing for us to do. */
1953 /* Ensure we requeue to the expected futex. */
1954 if (!match_futex(top_waiter->requeue_pi_key, key2))
1958 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1959 * the contended case or if set_waiters is 1. The pi_state is returned
1960 * in ps in contended cases.
1962 vpid = task_pid_vnr(top_waiter->task);
1963 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
1964 exiting, set_waiters);
1966 requeue_pi_wake_futex(top_waiter, key2, hb2);
1973 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
1974 * @uaddr1: source futex user address
1975 * @flags: futex flags (FLAGS_SHARED, etc.)
1976 * @uaddr2: target futex user address
1977 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1978 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1979 * @cmpval: @uaddr1 expected value (or %NULL)
1980 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
1981 * pi futex (pi to pi requeue is not supported)
1983 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1984 * uaddr2 atomically on behalf of the top waiter.
1987 * >=0 - on success, the number of tasks requeued or woken;
1990 static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
1991 u32 __user *uaddr2, int nr_wake, int nr_requeue,
1992 u32 *cmpval, int requeue_pi)
1994 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1995 int drop_count = 0, task_count = 0, ret;
1996 struct futex_pi_state *pi_state = NULL;
1997 struct futex_hash_bucket *hb1, *hb2;
1998 struct futex_q *this, *next;
2001 if (nr_wake < 0 || nr_requeue < 0)
2006 * Requeue PI only works on two distinct uaddrs. This
2007 * check is only valid for private futexes. See below.
2009 if (uaddr1 == uaddr2)
2013 * requeue_pi requires a pi_state, try to allocate it now
2014 * without any locks in case it fails.
2016 if (refill_pi_state_cache())
2019 * requeue_pi must wake as many tasks as it can, up to nr_wake
2020 * + nr_requeue, since it acquires the rt_mutex prior to
2021 * returning to userspace, so as to not leave the rt_mutex with
2022 * waiters and no owner. However, second and third wake-ups
2023 * cannot be predicted as they involve race conditions with the
2024 * first wake and a fault while looking up the pi_state. Both
2025 * pthread_cond_signal() and pthread_cond_broadcast() should
2033 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ);
2034 if (unlikely(ret != 0))
2036 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
2037 requeue_pi ? VERIFY_WRITE : VERIFY_READ);
2038 if (unlikely(ret != 0))
2042 * The check above which compares uaddrs is not sufficient for
2043 * shared futexes. We need to compare the keys:
2045 if (requeue_pi && match_futex(&key1, &key2)) {
2050 hb1 = hash_futex(&key1);
2051 hb2 = hash_futex(&key2);
2054 hb_waiters_inc(hb2);
2055 double_lock_hb(hb1, hb2);
2057 if (likely(cmpval != NULL)) {
2060 ret = get_futex_value_locked(&curval, uaddr1);
2062 if (unlikely(ret)) {
2063 double_unlock_hb(hb1, hb2);
2064 hb_waiters_dec(hb2);
2066 ret = get_user(curval, uaddr1);
2070 if (!(flags & FLAGS_SHARED))
2073 put_futex_key(&key2);
2074 put_futex_key(&key1);
2077 if (curval != *cmpval) {
2083 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
2084 struct task_struct *exiting = NULL;
2087 * Attempt to acquire uaddr2 and wake the top waiter. If we
2088 * intend to requeue waiters, force setting the FUTEX_WAITERS
2089 * bit. We force this here where we are able to easily handle
2090 * faults rather in the requeue loop below.
2092 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
2094 &exiting, nr_requeue);
2097 * At this point the top_waiter has either taken uaddr2 or is
2098 * waiting on it. If the former, then the pi_state will not
2099 * exist yet, look it up one more time to ensure we have a
2100 * reference to it. If the lock was taken, ret contains the
2101 * vpid of the top waiter task.
2108 * If we acquired the lock, then the user
2109 * space value of uaddr2 should be vpid. It
2110 * cannot be changed by the top waiter as it
2111 * is blocked on hb2 lock if it tries to do
2112 * so. If something fiddled with it behind our
2113 * back the pi state lookup might unearth
2114 * it. So we rather use the known value than
2115 * rereading and handing potential crap to
2118 ret = lookup_pi_state(uaddr2, ret, hb2, &key2,
2119 &pi_state, &exiting);
2126 put_pi_state(pi_state);
2128 double_unlock_hb(hb1, hb2);
2129 hb_waiters_dec(hb2);
2130 put_futex_key(&key2);
2131 put_futex_key(&key1);
2132 ret = fault_in_user_writeable(uaddr2);
2139 * Two reasons for this:
2140 * - EBUSY: Owner is exiting and we just wait for the
2142 * - EAGAIN: The user space value changed.
2144 put_pi_state(pi_state);
2146 double_unlock_hb(hb1, hb2);
2147 hb_waiters_dec(hb2);
2148 put_futex_key(&key2);
2149 put_futex_key(&key1);
2151 * Handle the case where the owner is in the middle of
2152 * exiting. Wait for the exit to complete otherwise
2153 * this task might loop forever, aka. live lock.
2155 wait_for_owner_exiting(ret, exiting);
2163 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
2164 if (task_count - nr_wake >= nr_requeue)
2167 if (!match_futex(&this->key, &key1))
2171 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
2172 * be paired with each other and no other futex ops.
2174 * We should never be requeueing a futex_q with a pi_state,
2175 * which is awaiting a futex_unlock_pi().
2177 if ((requeue_pi && !this->rt_waiter) ||
2178 (!requeue_pi && this->rt_waiter) ||
2185 * Wake nr_wake waiters. For requeue_pi, if we acquired the
2186 * lock, we already woke the top_waiter. If not, it will be
2187 * woken by futex_unlock_pi().
2189 if (++task_count <= nr_wake && !requeue_pi) {
2190 mark_wake_futex(&wake_q, this);
2194 /* Ensure we requeue to the expected futex for requeue_pi. */
2195 if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
2201 * Requeue nr_requeue waiters and possibly one more in the case
2202 * of requeue_pi if we couldn't acquire the lock atomically.
2205 /* Prepare the waiter to take the rt_mutex. */
2206 get_pi_state(pi_state);
2207 this->pi_state = pi_state;
2208 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
2212 /* We got the lock. */
2213 requeue_pi_wake_futex(this, &key2, hb2);
2218 this->pi_state = NULL;
2219 put_pi_state(pi_state);
2223 requeue_futex(this, hb1, hb2, &key2);
2228 put_pi_state(pi_state);
2229 double_unlock_hb(hb1, hb2);
2231 hb_waiters_dec(hb2);
2234 * drop_futex_key_refs() must be called outside the spinlocks. During
2235 * the requeue we moved futex_q's from the hash bucket at key1 to the
2236 * one at key2 and updated their key pointer. We no longer need to
2237 * hold the references to key1.
2239 while (--drop_count >= 0)
2240 drop_futex_key_refs(&key1);
2243 put_futex_key(&key2);
2245 put_futex_key(&key1);
2247 return ret ? ret : task_count;
2250 /* The key must be already stored in q->key. */
2251 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
2252 __acquires(&hb->lock)
2254 struct futex_hash_bucket *hb;
2256 hb = hash_futex(&q->key);
2259 * Increment the counter before taking the lock so that
2260 * a potential waker won't miss a to-be-slept task that is
2261 * waiting for the spinlock. This is safe as all queue_lock()
2262 * users end up calling queue_me(). Similarly, for housekeeping,
2263 * decrement the counter at queue_unlock() when some error has
2264 * occurred and we don't end up adding the task to the list.
2268 q->lock_ptr = &hb->lock;
2270 spin_lock(&hb->lock); /* implies MB (A) */
2275 queue_unlock(struct futex_hash_bucket *hb)
2276 __releases(&hb->lock)
2278 spin_unlock(&hb->lock);
2282 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2287 * The priority used to register this element is
2288 * - either the real thread-priority for the real-time threads
2289 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2290 * - or MAX_RT_PRIO for non-RT threads.
2291 * Thus, all RT-threads are woken first in priority order, and
2292 * the others are woken last, in FIFO order.
2294 prio = min(current->normal_prio, MAX_RT_PRIO);
2296 plist_node_init(&q->list, prio);
2297 plist_add(&q->list, &hb->chain);
2302 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2303 * @q: The futex_q to enqueue
2304 * @hb: The destination hash bucket
2306 * The hb->lock must be held by the caller, and is released here. A call to
2307 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2308 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2309 * or nothing if the unqueue is done as part of the wake process and the unqueue
2310 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2313 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2314 __releases(&hb->lock)
2317 spin_unlock(&hb->lock);
2321 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2322 * @q: The futex_q to unqueue
2324 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2325 * be paired with exactly one earlier call to queue_me().
2328 * 1 - if the futex_q was still queued (and we removed unqueued it);
2329 * 0 - if the futex_q was already removed by the waking thread
2331 static int unqueue_me(struct futex_q *q)
2333 spinlock_t *lock_ptr;
2336 /* In the common case we don't take the spinlock, which is nice. */
2339 * q->lock_ptr can change between this read and the following spin_lock.
2340 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2341 * optimizing lock_ptr out of the logic below.
2343 lock_ptr = READ_ONCE(q->lock_ptr);
2344 if (lock_ptr != NULL) {
2345 spin_lock(lock_ptr);
2347 * q->lock_ptr can change between reading it and
2348 * spin_lock(), causing us to take the wrong lock. This
2349 * corrects the race condition.
2351 * Reasoning goes like this: if we have the wrong lock,
2352 * q->lock_ptr must have changed (maybe several times)
2353 * between reading it and the spin_lock(). It can
2354 * change again after the spin_lock() but only if it was
2355 * already changed before the spin_lock(). It cannot,
2356 * however, change back to the original value. Therefore
2357 * we can detect whether we acquired the correct lock.
2359 if (unlikely(lock_ptr != q->lock_ptr)) {
2360 spin_unlock(lock_ptr);
2365 BUG_ON(q->pi_state);
2367 spin_unlock(lock_ptr);
2371 drop_futex_key_refs(&q->key);
2376 * PI futexes can not be requeued and must remove themself from the
2377 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
2380 static void unqueue_me_pi(struct futex_q *q)
2381 __releases(q->lock_ptr)
2385 BUG_ON(!q->pi_state);
2386 put_pi_state(q->pi_state);
2389 spin_unlock(q->lock_ptr);
2392 static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2393 struct task_struct *argowner)
2395 struct futex_pi_state *pi_state = q->pi_state;
2396 struct task_struct *oldowner, *newowner;
2397 u32 uval, curval, newval, newtid;
2400 oldowner = pi_state->owner;
2402 * We are here because either:
2404 * - we stole the lock and pi_state->owner needs updating to reflect
2405 * that (@argowner == current),
2409 * - someone stole our lock and we need to fix things to point to the
2410 * new owner (@argowner == NULL).
2412 * Either way, we have to replace the TID in the user space variable.
2413 * This must be atomic as we have to preserve the owner died bit here.
2415 * Note: We write the user space value _before_ changing the pi_state
2416 * because we can fault here. Imagine swapped out pages or a fork
2417 * that marked all the anonymous memory readonly for cow.
2419 * Modifying pi_state _before_ the user space value would leave the
2420 * pi_state in an inconsistent state when we fault here, because we
2421 * need to drop the locks to handle the fault. This might be observed
2422 * in the PID check in lookup_pi_state.
2426 if (oldowner != current) {
2428 * We raced against a concurrent self; things are
2429 * already fixed up. Nothing to do.
2434 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
2435 /* We got the lock. pi_state is correct. Tell caller */
2440 * The trylock just failed, so either there is an owner or
2441 * there is a higher priority waiter than this one.
2443 newowner = rt_mutex_owner(&pi_state->pi_mutex);
2445 * If the higher priority waiter has not yet taken over the
2446 * rtmutex then newowner is NULL. We can't return here with
2447 * that state because it's inconsistent vs. the user space
2448 * state. So drop the locks and try again. It's a valid
2449 * situation and not any different from the other retry
2452 if (unlikely(!newowner)) {
2457 WARN_ON_ONCE(argowner != current);
2458 if (oldowner == current) {
2460 * We raced against a concurrent self; things are
2461 * already fixed up. Nothing to do.
2465 newowner = argowner;
2468 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
2470 if (!pi_state->owner)
2471 newtid |= FUTEX_OWNER_DIED;
2473 if (get_futex_value_locked(&uval, uaddr))
2477 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2479 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, newval))
2487 * We fixed up user space. Now we need to fix the pi_state
2490 pi_state_update_owner(pi_state, newowner);
2492 return argowner == current;
2495 * To handle the page fault we need to drop the locks here. That gives
2496 * the other task (either the highest priority waiter itself or the
2497 * task which stole the rtmutex) the chance to try the fixup of the
2498 * pi_state. So once we are back from handling the fault we need to
2499 * check the pi_state after reacquiring the locks and before trying to
2500 * do another fixup. When the fixup has been done already we simply
2503 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2504 * drop hb->lock since the caller owns the hb -> futex_q relation.
2505 * Dropping the pi_mutex->wait_lock requires the state revalidate.
2508 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2509 spin_unlock(q->lock_ptr);
2511 err = fault_in_user_writeable(uaddr);
2513 spin_lock(q->lock_ptr);
2514 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2517 * Check if someone else fixed it for us:
2519 if (pi_state->owner != oldowner)
2520 return argowner == current;
2522 /* Retry if err was -EAGAIN or the fault in succeeded */
2527 * fault_in_user_writeable() failed so user state is immutable. At
2528 * best we can make the kernel state consistent but user state will
2529 * be most likely hosed and any subsequent unlock operation will be
2530 * rejected due to PI futex rule [10].
2532 * Ensure that the rtmutex owner is also the pi_state owner despite
2533 * the user space value claiming something different. There is no
2534 * point in unlocking the rtmutex if current is the owner as it
2535 * would need to wait until the next waiter has taken the rtmutex
2536 * to guarantee consistent state. Keep it simple. Userspace asked
2537 * for this wreckaged state.
2539 * The rtmutex has an owner - either current or some other
2540 * task. See the EAGAIN loop above.
2542 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
2547 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2548 struct task_struct *argowner)
2550 struct futex_pi_state *pi_state = q->pi_state;
2553 lockdep_assert_held(q->lock_ptr);
2555 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2556 ret = __fixup_pi_state_owner(uaddr, q, argowner);
2557 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2561 static long futex_wait_restart(struct restart_block *restart);
2564 * fixup_owner() - Post lock pi_state and corner case management
2565 * @uaddr: user address of the futex
2566 * @q: futex_q (contains pi_state and access to the rt_mutex)
2567 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2569 * After attempting to lock an rt_mutex, this function is called to cleanup
2570 * the pi_state owner as well as handle race conditions that may allow us to
2571 * acquire the lock. Must be called with the hb lock held.
2574 * 1 - success, lock taken;
2575 * 0 - success, lock not taken;
2576 * <0 - on error (-EFAULT)
2578 static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
2582 * Got the lock. We might not be the anticipated owner if we
2583 * did a lock-steal - fix up the PI-state in that case:
2585 * Speculative pi_state->owner read (we don't hold wait_lock);
2586 * since we own the lock pi_state->owner == current is the
2587 * stable state, anything else needs more attention.
2589 if (q->pi_state->owner != current)
2590 return fixup_pi_state_owner(uaddr, q, current);
2595 * If we didn't get the lock; check if anybody stole it from us. In
2596 * that case, we need to fix up the uval to point to them instead of
2597 * us, otherwise bad things happen. [10]
2599 * Another speculative read; pi_state->owner == current is unstable
2600 * but needs our attention.
2602 if (q->pi_state->owner == current)
2603 return fixup_pi_state_owner(uaddr, q, NULL);
2606 * Paranoia check. If we did not take the lock, then we should not be
2607 * the owner of the rt_mutex. Warn and establish consistent state.
2609 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
2610 return fixup_pi_state_owner(uaddr, q, current);
2616 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2617 * @hb: the futex hash bucket, must be locked by the caller
2618 * @q: the futex_q to queue up on
2619 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
2621 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
2622 struct hrtimer_sleeper *timeout)
2625 * The task state is guaranteed to be set before another task can
2626 * wake it. set_current_state() is implemented using smp_store_mb() and
2627 * queue_me() calls spin_unlock() upon completion, both serializing
2628 * access to the hash list and forcing another memory barrier.
2630 set_current_state(TASK_INTERRUPTIBLE);
2635 hrtimer_start_expires(&timeout->timer, HRTIMER_MODE_ABS);
2638 * If we have been removed from the hash list, then another task
2639 * has tried to wake us, and we can skip the call to schedule().
2641 if (likely(!plist_node_empty(&q->list))) {
2643 * If the timer has already expired, current will already be
2644 * flagged for rescheduling. Only call schedule if there
2645 * is no timeout, or if it has yet to expire.
2647 if (!timeout || timeout->task)
2648 freezable_schedule();
2650 __set_current_state(TASK_RUNNING);
2654 * futex_wait_setup() - Prepare to wait on a futex
2655 * @uaddr: the futex userspace address
2656 * @val: the expected value
2657 * @flags: futex flags (FLAGS_SHARED, etc.)
2658 * @q: the associated futex_q
2659 * @hb: storage for hash_bucket pointer to be returned to caller
2661 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2662 * compare it with the expected value. Handle atomic faults internally.
2663 * Return with the hb lock held and a q.key reference on success, and unlocked
2664 * with no q.key reference on failure.
2667 * 0 - uaddr contains val and hb has been locked;
2668 * <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
2670 static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
2671 struct futex_q *q, struct futex_hash_bucket **hb)
2677 * Access the page AFTER the hash-bucket is locked.
2678 * Order is important:
2680 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2681 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2683 * The basic logical guarantee of a futex is that it blocks ONLY
2684 * if cond(var) is known to be true at the time of blocking, for
2685 * any cond. If we locked the hash-bucket after testing *uaddr, that
2686 * would open a race condition where we could block indefinitely with
2687 * cond(var) false, which would violate the guarantee.
2689 * On the other hand, we insert q and release the hash-bucket only
2690 * after testing *uaddr. This guarantees that futex_wait() will NOT
2691 * absorb a wakeup if *uaddr does not match the desired values
2692 * while the syscall executes.
2695 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, VERIFY_READ);
2696 if (unlikely(ret != 0))
2700 *hb = queue_lock(q);
2702 ret = get_futex_value_locked(&uval, uaddr);
2707 ret = get_user(uval, uaddr);
2711 if (!(flags & FLAGS_SHARED))
2714 put_futex_key(&q->key);
2725 put_futex_key(&q->key);
2729 static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2730 ktime_t *abs_time, u32 bitset)
2732 struct hrtimer_sleeper timeout, *to = NULL;
2733 struct restart_block *restart;
2734 struct futex_hash_bucket *hb;
2735 struct futex_q q = futex_q_init;
2745 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
2746 CLOCK_REALTIME : CLOCK_MONOTONIC,
2748 hrtimer_init_sleeper(to, current);
2749 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
2750 current->timer_slack_ns);
2755 * Prepare to wait on uaddr. On success, holds hb lock and increments
2758 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
2762 /* queue_me and wait for wakeup, timeout, or a signal. */
2763 futex_wait_queue_me(hb, &q, to);
2765 /* If we were woken (and unqueued), we succeeded, whatever. */
2767 /* unqueue_me() drops q.key ref */
2768 if (!unqueue_me(&q))
2771 if (to && !to->task)
2775 * We expect signal_pending(current), but we might be the
2776 * victim of a spurious wakeup as well.
2778 if (!signal_pending(current))
2785 restart = ¤t->restart_block;
2786 restart->fn = futex_wait_restart;
2787 restart->futex.uaddr = uaddr;
2788 restart->futex.val = val;
2789 restart->futex.time = abs_time->tv64;
2790 restart->futex.bitset = bitset;
2791 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
2793 ret = -ERESTART_RESTARTBLOCK;
2797 hrtimer_cancel(&to->timer);
2798 destroy_hrtimer_on_stack(&to->timer);
2804 static long futex_wait_restart(struct restart_block *restart)
2806 u32 __user *uaddr = restart->futex.uaddr;
2807 ktime_t t, *tp = NULL;
2809 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2810 t.tv64 = restart->futex.time;
2813 restart->fn = do_no_restart_syscall;
2815 return (long)futex_wait(uaddr, restart->futex.flags,
2816 restart->futex.val, tp, restart->futex.bitset);
2821 * Userspace tried a 0 -> TID atomic transition of the futex value
2822 * and failed. The kernel side here does the whole locking operation:
2823 * if there are waiters then it will block as a consequence of relying
2824 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2825 * a 0 value of the futex too.).
2827 * Also serves as futex trylock_pi()'ing, and due semantics.
2829 static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
2830 ktime_t *time, int trylock)
2832 struct hrtimer_sleeper timeout, *to = NULL;
2833 struct task_struct *exiting = NULL;
2834 struct rt_mutex_waiter rt_waiter;
2835 struct futex_hash_bucket *hb;
2836 struct futex_q q = futex_q_init;
2839 if (refill_pi_state_cache())
2844 hrtimer_init_on_stack(&to->timer, CLOCK_REALTIME,
2846 hrtimer_init_sleeper(to, current);
2847 hrtimer_set_expires(&to->timer, *time);
2851 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, VERIFY_WRITE);
2852 if (unlikely(ret != 0))
2856 hb = queue_lock(&q);
2858 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
2860 if (unlikely(ret)) {
2862 * Atomic work succeeded and we got the lock,
2863 * or failed. Either way, we do _not_ block.
2867 /* We got the lock. */
2869 goto out_unlock_put_key;
2875 * Two reasons for this:
2876 * - EBUSY: Task is exiting and we just wait for the
2878 * - EAGAIN: The user space value changed.
2881 put_futex_key(&q.key);
2883 * Handle the case where the owner is in the middle of
2884 * exiting. Wait for the exit to complete otherwise
2885 * this task might loop forever, aka. live lock.
2887 wait_for_owner_exiting(ret, exiting);
2891 goto out_unlock_put_key;
2895 WARN_ON(!q.pi_state);
2898 * Only actually queue now that the atomic ops are done:
2903 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
2904 /* Fixup the trylock return value: */
2905 ret = ret ? 0 : -EWOULDBLOCK;
2910 * We must add ourselves to the rt_mutex waitlist while holding hb->lock
2911 * such that the hb and rt_mutex wait lists match.
2913 rt_mutex_init_waiter(&rt_waiter);
2914 ret = rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
2922 spin_unlock(q.lock_ptr);
2925 hrtimer_start_expires(&to->timer, HRTIMER_MODE_ABS);
2927 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
2929 spin_lock(q.lock_ptr);
2931 * If we failed to acquire the lock (signal/timeout), we must
2932 * first acquire the hb->lock before removing the lock from the
2933 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex
2934 * wait lists consistent.
2936 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
2941 * Fixup the pi_state owner and possibly acquire the lock if we
2944 res = fixup_owner(uaddr, &q, !ret);
2946 * If fixup_owner() returned an error, proprogate that. If it acquired
2947 * the lock, clear our -ETIMEDOUT or -EINTR.
2950 ret = (res < 0) ? res : 0;
2952 /* Unqueue and drop the lock */
2961 put_futex_key(&q.key);
2964 hrtimer_cancel(&to->timer);
2965 destroy_hrtimer_on_stack(&to->timer);
2967 return ret != -EINTR ? ret : -ERESTARTNOINTR;
2972 ret = fault_in_user_writeable(uaddr);
2976 if (!(flags & FLAGS_SHARED))
2979 put_futex_key(&q.key);
2984 * Userspace attempted a TID -> 0 atomic transition, and failed.
2985 * This is the in-kernel slowpath: we look up the PI state (if any),
2986 * and do the rt-mutex unlock.
2988 static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
2990 u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
2991 union futex_key key = FUTEX_KEY_INIT;
2992 struct futex_hash_bucket *hb;
2993 struct futex_q *match;
2997 if (get_user(uval, uaddr))
3000 * We release only a lock we actually own:
3002 if ((uval & FUTEX_TID_MASK) != vpid)
3005 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, VERIFY_WRITE);
3009 hb = hash_futex(&key);
3010 spin_lock(&hb->lock);
3013 * Check waiters first. We do not trust user space values at
3014 * all and we at least want to know if user space fiddled
3015 * with the futex value instead of blindly unlocking.
3017 match = futex_top_waiter(hb, &key);
3019 struct futex_pi_state *pi_state = match->pi_state;
3026 * If current does not own the pi_state then the futex is
3027 * inconsistent and user space fiddled with the futex value.
3029 if (pi_state->owner != current)
3032 get_pi_state(pi_state);
3034 * Since modifying the wait_list is done while holding both
3035 * hb->lock and wait_lock, holding either is sufficient to
3038 * By taking wait_lock while still holding hb->lock, we ensure
3039 * there is no point where we hold neither; and therefore
3040 * wake_futex_pi() must observe a state consistent with what we
3043 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
3044 spin_unlock(&hb->lock);
3046 ret = wake_futex_pi(uaddr, uval, pi_state);
3048 put_pi_state(pi_state);
3051 * Success, we're done! No tricky corner cases.
3056 * The atomic access to the futex value generated a
3057 * pagefault, so retry the user-access and the wakeup:
3062 * A unconditional UNLOCK_PI op raced against a waiter
3063 * setting the FUTEX_WAITERS bit. Try again.
3065 if (ret == -EAGAIN) {
3066 put_futex_key(&key);
3070 * wake_futex_pi has detected invalid state. Tell user
3077 * We have no kernel internal state, i.e. no waiters in the
3078 * kernel. Waiters which are about to queue themselves are stuck
3079 * on hb->lock. So we can safely ignore them. We do neither
3080 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3083 if (cmpxchg_futex_value_locked(&curval, uaddr, uval, 0)) {
3084 spin_unlock(&hb->lock);
3089 * If uval has changed, let user space handle it.
3091 ret = (curval == uval) ? 0 : -EAGAIN;
3094 spin_unlock(&hb->lock);
3096 put_futex_key(&key);
3100 put_futex_key(&key);
3102 ret = fault_in_user_writeable(uaddr);
3110 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
3111 * @hb: the hash_bucket futex_q was original enqueued on
3112 * @q: the futex_q woken while waiting to be requeued
3113 * @key2: the futex_key of the requeue target futex
3114 * @timeout: the timeout associated with the wait (NULL if none)
3116 * Detect if the task was woken on the initial futex as opposed to the requeue
3117 * target futex. If so, determine if it was a timeout or a signal that caused
3118 * the wakeup and return the appropriate error code to the caller. Must be
3119 * called with the hb lock held.
3122 * 0 = no early wakeup detected;
3123 * <0 = -ETIMEDOUT or -ERESTARTNOINTR
3126 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
3127 struct futex_q *q, union futex_key *key2,
3128 struct hrtimer_sleeper *timeout)
3133 * With the hb lock held, we avoid races while we process the wakeup.
3134 * We only need to hold hb (and not hb2) to ensure atomicity as the
3135 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
3136 * It can't be requeued from uaddr2 to something else since we don't
3137 * support a PI aware source futex for requeue.
3139 if (!match_futex(&q->key, key2)) {
3140 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
3142 * We were woken prior to requeue by a timeout or a signal.
3143 * Unqueue the futex_q and determine which it was.
3145 plist_del(&q->list, &hb->chain);
3148 /* Handle spurious wakeups gracefully */
3150 if (timeout && !timeout->task)
3152 else if (signal_pending(current))
3153 ret = -ERESTARTNOINTR;
3159 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
3160 * @uaddr: the futex we initially wait on (non-pi)
3161 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
3162 * the same type, no requeueing from private to shared, etc.
3163 * @val: the expected value of uaddr
3164 * @abs_time: absolute timeout
3165 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
3166 * @uaddr2: the pi futex we will take prior to returning to user-space
3168 * The caller will wait on uaddr and will be requeued by futex_requeue() to
3169 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
3170 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
3171 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
3172 * without one, the pi logic would not know which task to boost/deboost, if
3173 * there was a need to.
3175 * We call schedule in futex_wait_queue_me() when we enqueue and return there
3176 * via the following--
3177 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
3178 * 2) wakeup on uaddr2 after a requeue
3182 * If 3, cleanup and return -ERESTARTNOINTR.
3184 * If 2, we may then block on trying to take the rt_mutex and return via:
3185 * 5) successful lock
3188 * 8) other lock acquisition failure
3190 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
3192 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
3198 static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
3199 u32 val, ktime_t *abs_time, u32 bitset,
3202 struct hrtimer_sleeper timeout, *to = NULL;
3203 struct rt_mutex_waiter rt_waiter;
3204 struct futex_hash_bucket *hb;
3205 union futex_key key2 = FUTEX_KEY_INIT;
3206 struct futex_q q = futex_q_init;
3209 if (uaddr == uaddr2)
3217 hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ?
3218 CLOCK_REALTIME : CLOCK_MONOTONIC,
3220 hrtimer_init_sleeper(to, current);
3221 hrtimer_set_expires_range_ns(&to->timer, *abs_time,
3222 current->timer_slack_ns);
3226 * The waiter is allocated on our stack, manipulated by the requeue
3227 * code while we sleep on uaddr.
3229 rt_mutex_init_waiter(&rt_waiter);
3231 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE);
3232 if (unlikely(ret != 0))
3236 q.rt_waiter = &rt_waiter;
3237 q.requeue_pi_key = &key2;
3240 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
3243 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
3248 * The check above which compares uaddrs is not sufficient for
3249 * shared futexes. We need to compare the keys:
3251 if (match_futex(&q.key, &key2)) {
3257 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
3258 futex_wait_queue_me(hb, &q, to);
3260 spin_lock(&hb->lock);
3261 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
3262 spin_unlock(&hb->lock);
3267 * In order for us to be here, we know our q.key == key2, and since
3268 * we took the hb->lock above, we also know that futex_requeue() has
3269 * completed and we no longer have to concern ourselves with a wakeup
3270 * race with the atomic proxy lock acquisition by the requeue code. The
3271 * futex_requeue dropped our key1 reference and incremented our key2
3275 /* Check if the requeue code acquired the second futex for us. */
3278 * Got the lock. We might not be the anticipated owner if we
3279 * did a lock-steal - fix up the PI-state in that case.
3281 if (q.pi_state && (q.pi_state->owner != current)) {
3282 spin_lock(q.lock_ptr);
3283 ret = fixup_pi_state_owner(uaddr2, &q, current);
3285 * Drop the reference to the pi state which
3286 * the requeue_pi() code acquired for us.
3288 put_pi_state(q.pi_state);
3289 spin_unlock(q.lock_ptr);
3291 * Adjust the return value. It's either -EFAULT or
3292 * success (1) but the caller expects 0 for success.
3294 ret = ret < 0 ? ret : 0;
3297 struct rt_mutex *pi_mutex;
3300 * We have been woken up by futex_unlock_pi(), a timeout, or a
3301 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
3304 WARN_ON(!q.pi_state);
3305 pi_mutex = &q.pi_state->pi_mutex;
3306 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
3308 spin_lock(q.lock_ptr);
3309 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
3312 debug_rt_mutex_free_waiter(&rt_waiter);
3314 * Fixup the pi_state owner and possibly acquire the lock if we
3317 res = fixup_owner(uaddr2, &q, !ret);
3319 * If fixup_owner() returned an error, proprogate that. If it
3320 * acquired the lock, clear -ETIMEDOUT or -EINTR.
3323 ret = (res < 0) ? res : 0;
3325 /* Unqueue and drop the lock. */
3329 if (ret == -EINTR) {
3331 * We've already been requeued, but cannot restart by calling
3332 * futex_lock_pi() directly. We could restart this syscall, but
3333 * it would detect that the user space "val" changed and return
3334 * -EWOULDBLOCK. Save the overhead of the restart and return
3335 * -EWOULDBLOCK directly.
3341 put_futex_key(&q.key);
3343 put_futex_key(&key2);
3347 hrtimer_cancel(&to->timer);
3348 destroy_hrtimer_on_stack(&to->timer);
3354 * Support for robust futexes: the kernel cleans up held futexes at
3357 * Implementation: user-space maintains a per-thread list of locks it
3358 * is holding. Upon do_exit(), the kernel carefully walks this list,
3359 * and marks all locks that are owned by this thread with the
3360 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
3361 * always manipulated with the lock held, so the list is private and
3362 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
3363 * field, to allow the kernel to clean up if the thread dies after
3364 * acquiring the lock, but just before it could have added itself to
3365 * the list. There can only be one such pending lock.
3369 * sys_set_robust_list() - Set the robust-futex list head of a task
3370 * @head: pointer to the list-head
3371 * @len: length of the list-head, as userspace expects
3373 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
3376 if (!futex_cmpxchg_enabled)
3379 * The kernel knows only one size for now:
3381 if (unlikely(len != sizeof(*head)))
3384 current->robust_list = head;
3390 * sys_get_robust_list() - Get the robust-futex list head of a task
3391 * @pid: pid of the process [zero for current task]
3392 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
3393 * @len_ptr: pointer to a length field, the kernel fills in the header size
3395 SYSCALL_DEFINE3(get_robust_list, int, pid,
3396 struct robust_list_head __user * __user *, head_ptr,
3397 size_t __user *, len_ptr)
3399 struct robust_list_head __user *head;
3401 struct task_struct *p;
3403 if (!futex_cmpxchg_enabled)
3412 p = find_task_by_vpid(pid);
3418 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3421 head = p->robust_list;
3424 if (put_user(sizeof(*head), len_ptr))
3426 return put_user(head, head_ptr);
3435 * Process a futex-list entry, check whether it's owned by the
3436 * dying task, and do notification if so:
3438 static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr, int pi)
3440 u32 uval, uninitialized_var(nval), mval;
3442 /* Futex address must be 32bit aligned */
3443 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3447 if (get_user(uval, uaddr))
3450 if ((uval & FUTEX_TID_MASK) == task_pid_vnr(curr)) {
3452 * Ok, this dying thread is truly holding a futex
3453 * of interest. Set the OWNER_DIED bit atomically
3454 * via cmpxchg, and if the value had FUTEX_WAITERS
3455 * set, wake up a waiter (if any). (We have to do a
3456 * futex_wake() even if OWNER_DIED is already set -
3457 * to handle the rare but possible case of recursive
3458 * thread-death.) The rest of the cleanup is done in
3461 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3463 * We are not holding a lock here, but we want to have
3464 * the pagefault_disable/enable() protection because
3465 * we want to handle the fault gracefully. If the
3466 * access fails we try to fault in the futex with R/W
3467 * verification via get_user_pages. get_user() above
3468 * does not guarantee R/W access. If that fails we
3469 * give up and leave the futex locked.
3471 if (cmpxchg_futex_value_locked(&nval, uaddr, uval, mval)) {
3472 if (fault_in_user_writeable(uaddr))
3480 * Wake robust non-PI futexes here. The wakeup of
3481 * PI futexes happens in exit_pi_state():
3483 if (!pi && (uval & FUTEX_WAITERS))
3484 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3490 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3492 static inline int fetch_robust_entry(struct robust_list __user **entry,
3493 struct robust_list __user * __user *head,
3496 unsigned long uentry;
3498 if (get_user(uentry, (unsigned long __user *)head))
3501 *entry = (void __user *)(uentry & ~1UL);
3508 * Walk curr->robust_list (very carefully, it's a userspace list!)
3509 * and mark any locks found there dead, and notify any waiters.
3511 * We silently return on any sign of list-walking problem.
3513 static void exit_robust_list(struct task_struct *curr)
3515 struct robust_list_head __user *head = curr->robust_list;
3516 struct robust_list __user *entry, *next_entry, *pending;
3517 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3518 unsigned int uninitialized_var(next_pi);
3519 unsigned long futex_offset;
3522 if (!futex_cmpxchg_enabled)
3526 * Fetch the list head (which was registered earlier, via
3527 * sys_set_robust_list()):
3529 if (fetch_robust_entry(&entry, &head->list.next, &pi))
3532 * Fetch the relative futex offset:
3534 if (get_user(futex_offset, &head->futex_offset))
3537 * Fetch any possibly pending lock-add first, and handle it
3540 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
3543 next_entry = NULL; /* avoid warning with gcc */
3544 while (entry != &head->list) {
3546 * Fetch the next entry in the list before calling
3547 * handle_futex_death:
3549 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
3551 * A pending lock might already be on the list, so
3552 * don't process it twice:
3554 if (entry != pending)
3555 if (handle_futex_death((void __user *)entry + futex_offset,
3563 * Avoid excessively long or circular lists:
3572 handle_futex_death((void __user *)pending + futex_offset,
3576 static void futex_cleanup(struct task_struct *tsk)
3578 if (unlikely(tsk->robust_list)) {
3579 exit_robust_list(tsk);
3580 tsk->robust_list = NULL;
3583 #ifdef CONFIG_COMPAT
3584 if (unlikely(tsk->compat_robust_list)) {
3585 compat_exit_robust_list(tsk);
3586 tsk->compat_robust_list = NULL;
3590 if (unlikely(!list_empty(&tsk->pi_state_list)))
3591 exit_pi_state_list(tsk);
3595 * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
3596 * @tsk: task to set the state on
3598 * Set the futex exit state of the task lockless. The futex waiter code
3599 * observes that state when a task is exiting and loops until the task has
3600 * actually finished the futex cleanup. The worst case for this is that the
3601 * waiter runs through the wait loop until the state becomes visible.
3603 * This is called from the recursive fault handling path in do_exit().
3605 * This is best effort. Either the futex exit code has run already or
3606 * not. If the OWNER_DIED bit has been set on the futex then the waiter can
3607 * take it over. If not, the problem is pushed back to user space. If the
3608 * futex exit code did not run yet, then an already queued waiter might
3609 * block forever, but there is nothing which can be done about that.
3611 void futex_exit_recursive(struct task_struct *tsk)
3613 /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
3614 if (tsk->futex_state == FUTEX_STATE_EXITING)
3615 mutex_unlock(&tsk->futex_exit_mutex);
3616 tsk->futex_state = FUTEX_STATE_DEAD;
3619 static void futex_cleanup_begin(struct task_struct *tsk)
3622 * Prevent various race issues against a concurrent incoming waiter
3623 * including live locks by forcing the waiter to block on
3624 * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
3625 * attach_to_pi_owner().
3627 mutex_lock(&tsk->futex_exit_mutex);
3630 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
3632 * This ensures that all subsequent checks of tsk->futex_state in
3633 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
3634 * tsk->pi_lock held.
3636 * It guarantees also that a pi_state which was queued right before
3637 * the state change under tsk->pi_lock by a concurrent waiter must
3638 * be observed in exit_pi_state_list().
3640 raw_spin_lock_irq(&tsk->pi_lock);
3641 tsk->futex_state = FUTEX_STATE_EXITING;
3642 raw_spin_unlock_irq(&tsk->pi_lock);
3645 static void futex_cleanup_end(struct task_struct *tsk, int state)
3648 * Lockless store. The only side effect is that an observer might
3649 * take another loop until it becomes visible.
3651 tsk->futex_state = state;
3653 * Drop the exit protection. This unblocks waiters which observed
3654 * FUTEX_STATE_EXITING to reevaluate the state.
3656 mutex_unlock(&tsk->futex_exit_mutex);
3659 void futex_exec_release(struct task_struct *tsk)
3662 * The state handling is done for consistency, but in the case of
3663 * exec() there is no way to prevent futher damage as the PID stays
3664 * the same. But for the unlikely and arguably buggy case that a
3665 * futex is held on exec(), this provides at least as much state
3666 * consistency protection which is possible.
3668 futex_cleanup_begin(tsk);
3671 * Reset the state to FUTEX_STATE_OK. The task is alive and about
3672 * exec a new binary.
3674 futex_cleanup_end(tsk, FUTEX_STATE_OK);
3677 void futex_exit_release(struct task_struct *tsk)
3679 futex_cleanup_begin(tsk);
3681 futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
3684 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
3685 u32 __user *uaddr2, u32 val2, u32 val3)
3687 int cmd = op & FUTEX_CMD_MASK;
3688 unsigned int flags = 0;
3690 if (!(op & FUTEX_PRIVATE_FLAG))
3691 flags |= FLAGS_SHARED;
3693 if (op & FUTEX_CLOCK_REALTIME) {
3694 flags |= FLAGS_CLOCKRT;
3695 if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI)
3701 case FUTEX_UNLOCK_PI:
3702 case FUTEX_TRYLOCK_PI:
3703 case FUTEX_WAIT_REQUEUE_PI:
3704 case FUTEX_CMP_REQUEUE_PI:
3705 if (!futex_cmpxchg_enabled)
3711 val3 = FUTEX_BITSET_MATCH_ANY;
3712 case FUTEX_WAIT_BITSET:
3713 return futex_wait(uaddr, flags, val, timeout, val3);
3715 val3 = FUTEX_BITSET_MATCH_ANY;
3716 case FUTEX_WAKE_BITSET:
3717 return futex_wake(uaddr, flags, val, val3);
3719 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
3720 case FUTEX_CMP_REQUEUE:
3721 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
3723 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
3725 return futex_lock_pi(uaddr, flags, timeout, 0);
3726 case FUTEX_UNLOCK_PI:
3727 return futex_unlock_pi(uaddr, flags);
3728 case FUTEX_TRYLOCK_PI:
3729 return futex_lock_pi(uaddr, flags, NULL, 1);
3730 case FUTEX_WAIT_REQUEUE_PI:
3731 val3 = FUTEX_BITSET_MATCH_ANY;
3732 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3734 case FUTEX_CMP_REQUEUE_PI:
3735 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
3741 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3742 struct timespec __user *, utime, u32 __user *, uaddr2,
3746 ktime_t t, *tp = NULL;
3748 int cmd = op & FUTEX_CMD_MASK;
3750 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
3751 cmd == FUTEX_WAIT_BITSET ||
3752 cmd == FUTEX_WAIT_REQUEUE_PI)) {
3753 if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
3755 if (copy_from_user(&ts, utime, sizeof(ts)) != 0)
3757 if (!timespec_valid(&ts))
3760 t = timespec_to_ktime(ts);
3761 if (cmd == FUTEX_WAIT)
3762 t = ktime_add_safe(ktime_get(), t);
3766 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
3767 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
3769 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
3770 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
3771 val2 = (u32) (unsigned long) utime;
3773 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
3776 #ifdef CONFIG_COMPAT
3778 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3781 compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
3782 compat_uptr_t __user *head, unsigned int *pi)
3784 if (get_user(*uentry, head))
3787 *entry = compat_ptr((*uentry) & ~1);
3788 *pi = (unsigned int)(*uentry) & 1;
3793 static void __user *futex_uaddr(struct robust_list __user *entry,
3794 compat_long_t futex_offset)
3796 compat_uptr_t base = ptr_to_compat(entry);
3797 void __user *uaddr = compat_ptr(base + futex_offset);
3803 * Walk curr->robust_list (very carefully, it's a userspace list!)
3804 * and mark any locks found there dead, and notify any waiters.
3806 * We silently return on any sign of list-walking problem.
3808 void compat_exit_robust_list(struct task_struct *curr)
3810 struct compat_robust_list_head __user *head = curr->compat_robust_list;
3811 struct robust_list __user *entry, *next_entry, *pending;
3812 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3813 unsigned int uninitialized_var(next_pi);
3814 compat_uptr_t uentry, next_uentry, upending;
3815 compat_long_t futex_offset;
3818 if (!futex_cmpxchg_enabled)
3822 * Fetch the list head (which was registered earlier, via
3823 * sys_set_robust_list()):
3825 if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
3828 * Fetch the relative futex offset:
3830 if (get_user(futex_offset, &head->futex_offset))
3833 * Fetch any possibly pending lock-add first, and handle it
3836 if (compat_fetch_robust_entry(&upending, &pending,
3837 &head->list_op_pending, &pip))
3840 next_entry = NULL; /* avoid warning with gcc */
3841 while (entry != (struct robust_list __user *) &head->list) {
3843 * Fetch the next entry in the list before calling
3844 * handle_futex_death:
3846 rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
3847 (compat_uptr_t __user *)&entry->next, &next_pi);
3849 * A pending lock might already be on the list, so
3850 * dont process it twice:
3852 if (entry != pending) {
3853 void __user *uaddr = futex_uaddr(entry, futex_offset);
3855 if (handle_futex_death(uaddr, curr, pi))
3860 uentry = next_uentry;
3864 * Avoid excessively long or circular lists:
3872 void __user *uaddr = futex_uaddr(pending, futex_offset);
3874 handle_futex_death(uaddr, curr, pip);
3878 COMPAT_SYSCALL_DEFINE2(set_robust_list,
3879 struct compat_robust_list_head __user *, head,
3882 if (!futex_cmpxchg_enabled)
3885 if (unlikely(len != sizeof(*head)))
3888 current->compat_robust_list = head;
3893 COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
3894 compat_uptr_t __user *, head_ptr,
3895 compat_size_t __user *, len_ptr)
3897 struct compat_robust_list_head __user *head;
3899 struct task_struct *p;
3901 if (!futex_cmpxchg_enabled)
3910 p = find_task_by_vpid(pid);
3916 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3919 head = p->compat_robust_list;
3922 if (put_user(sizeof(*head), len_ptr))
3924 return put_user(ptr_to_compat(head), head_ptr);
3932 COMPAT_SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3933 struct compat_timespec __user *, utime, u32 __user *, uaddr2,
3937 ktime_t t, *tp = NULL;
3939 int cmd = op & FUTEX_CMD_MASK;
3941 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
3942 cmd == FUTEX_WAIT_BITSET ||
3943 cmd == FUTEX_WAIT_REQUEUE_PI)) {
3944 if (compat_get_timespec(&ts, utime))
3946 if (!timespec_valid(&ts))
3949 t = timespec_to_ktime(ts);
3950 if (cmd == FUTEX_WAIT)
3951 t = ktime_add_safe(ktime_get(), t);
3954 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
3955 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
3956 val2 = (int) (unsigned long) utime;
3958 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
3960 #endif /* CONFIG_COMPAT */
3962 static void __init futex_detect_cmpxchg(void)
3964 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
3968 * This will fail and we want it. Some arch implementations do
3969 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3970 * functionality. We want to know that before we call in any
3971 * of the complex code paths. Also we want to prevent
3972 * registration of robust lists in that case. NULL is
3973 * guaranteed to fault and we get -EFAULT on functional
3974 * implementation, the non-functional ones will return
3977 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
3978 futex_cmpxchg_enabled = 1;
3982 static int __init futex_init(void)
3984 unsigned int futex_shift;
3987 #if CONFIG_BASE_SMALL
3988 futex_hashsize = 16;
3990 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
3993 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
3995 futex_hashsize < 256 ? HASH_SMALL : 0,
3997 futex_hashsize, futex_hashsize);
3998 futex_hashsize = 1UL << futex_shift;
4000 futex_detect_cmpxchg();
4002 for (i = 0; i < futex_hashsize; i++) {
4003 atomic_set(&futex_queues[i].waiters, 0);
4004 plist_head_init(&futex_queues[i].chain);
4005 spin_lock_init(&futex_queues[i].lock);
4010 core_initcall(futex_init);