1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Fast Userspace Mutexes (which I call "Futexes!").
4 * (C) Rusty Russell, IBM 2002
6 * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
7 * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
9 * Removed page pinning, fix privately mapped COW pages and other cleanups
10 * (C) Copyright 2003, 2004 Jamie Lokier
12 * Robust futex support started by Ingo Molnar
13 * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
14 * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
16 * PI-futex support started by Ingo Molnar and Thomas Gleixner
17 * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
18 * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
20 * PRIVATE futexes by Eric Dumazet
21 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
23 * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
24 * Copyright (C) IBM Corporation, 2009
25 * Thanks to Thomas Gleixner for conceptual design and careful reviews.
27 * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
28 * enough at me, Linus for the original (flawed) idea, Matthew
29 * Kirkwood for proof-of-concept implementation.
31 * "The futexes are also cursed."
32 * "But they come in a choice of three flavours!"
34 #include <linux/compat.h>
35 #include <linux/jhash.h>
36 #include <linux/pagemap.h>
37 #include <linux/syscalls.h>
38 #include <linux/freezer.h>
39 #include <linux/memblock.h>
40 #include <linux/fault-inject.h>
41 #include <linux/time_namespace.h>
43 #include <asm/futex.h>
45 #include "locking/rtmutex_common.h"
48 * READ this before attempting to hack on futexes!
50 * Basic futex operation and ordering guarantees
51 * =============================================
53 * The waiter reads the futex value in user space and calls
54 * futex_wait(). This function computes the hash bucket and acquires
55 * the hash bucket lock. After that it reads the futex user space value
56 * again and verifies that the data has not changed. If it has not changed
57 * it enqueues itself into the hash bucket, releases the hash bucket lock
60 * The waker side modifies the user space value of the futex and calls
61 * futex_wake(). This function computes the hash bucket and acquires the
62 * hash bucket lock. Then it looks for waiters on that futex in the hash
63 * bucket and wakes them.
65 * In futex wake up scenarios where no tasks are blocked on a futex, taking
66 * the hb spinlock can be avoided and simply return. In order for this
67 * optimization to work, ordering guarantees must exist so that the waiter
68 * being added to the list is acknowledged when the list is concurrently being
69 * checked by the waker, avoiding scenarios like the following:
73 * sys_futex(WAIT, futex, val);
74 * futex_wait(futex, val);
77 * sys_futex(WAKE, futex);
82 * lock(hash_bucket(futex));
84 * unlock(hash_bucket(futex));
87 * This would cause the waiter on CPU 0 to wait forever because it
88 * missed the transition of the user space value from val to newval
89 * and the waker did not find the waiter in the hash bucket queue.
91 * The correct serialization ensures that a waiter either observes
92 * the changed user space value before blocking or is woken by a
97 * sys_futex(WAIT, futex, val);
98 * futex_wait(futex, val);
101 * smp_mb(); (A) <-- paired with -.
103 * lock(hash_bucket(futex)); |
107 * | sys_futex(WAKE, futex);
108 * | futex_wake(futex);
110 * `--------> smp_mb(); (B)
113 * unlock(hash_bucket(futex));
114 * schedule(); if (waiters)
115 * lock(hash_bucket(futex));
116 * else wake_waiters(futex);
117 * waiters--; (b) unlock(hash_bucket(futex));
119 * Where (A) orders the waiters increment and the futex value read through
120 * atomic operations (see hb_waiters_inc) and where (B) orders the write
121 * to futex and the waiters read (see hb_waiters_pending()).
123 * This yields the following case (where X:=waiters, Y:=futex):
131 * Which guarantees that x==0 && y==0 is impossible; which translates back into
132 * the guarantee that we cannot both miss the futex variable change and the
135 * Note that a new waiter is accounted for in (a) even when it is possible that
136 * the wait call can return error, in which case we backtrack from it in (b).
137 * Refer to the comment in queue_lock().
139 * Similarly, in order to account for waiters being requeued on another
140 * address we always increment the waiters for the destination bucket before
141 * acquiring the lock. It then decrements them again after releasing it -
142 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
143 * will do the additional required waiter count housekeeping. This is done for
144 * double_lock_hb() and double_unlock_hb(), respectively.
147 #ifdef CONFIG_HAVE_FUTEX_CMPXCHG
148 #define futex_cmpxchg_enabled 1
150 static int __read_mostly futex_cmpxchg_enabled;
154 * Futex flags used to encode options to functions and preserve them across
158 # define FLAGS_SHARED 0x01
161 * NOMMU does not have per process address space. Let the compiler optimize
164 # define FLAGS_SHARED 0x00
166 #define FLAGS_CLOCKRT 0x02
167 #define FLAGS_HAS_TIMEOUT 0x04
170 * Priority Inheritance state:
172 struct futex_pi_state {
174 * list of 'owned' pi_state instances - these have to be
175 * cleaned up in do_exit() if the task exits prematurely:
177 struct list_head list;
182 struct rt_mutex_base pi_mutex;
184 struct task_struct *owner;
188 } __randomize_layout;
191 * struct futex_q - The hashed futex queue entry, one per waiting task
192 * @list: priority-sorted list of tasks waiting on this futex
193 * @task: the task waiting on the futex
194 * @lock_ptr: the hash bucket lock
195 * @key: the key the futex is hashed on
196 * @pi_state: optional priority inheritance state
197 * @rt_waiter: rt_waiter storage for use with requeue_pi
198 * @requeue_pi_key: the requeue_pi target futex key
199 * @bitset: bitset for the optional bitmasked wakeup
200 * @requeue_state: State field for futex_requeue_pi()
201 * @requeue_wait: RCU wait for futex_requeue_pi() (RT only)
203 * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
204 * we can wake only the relevant ones (hashed queues may be shared).
206 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
207 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
208 * The order of wakeup is always to make the first condition true, then
211 * PI futexes are typically woken before they are removed from the hash list via
212 * the rt_mutex code. See unqueue_me_pi().
215 struct plist_node list;
217 struct task_struct *task;
218 spinlock_t *lock_ptr;
220 struct futex_pi_state *pi_state;
221 struct rt_mutex_waiter *rt_waiter;
222 union futex_key *requeue_pi_key;
224 atomic_t requeue_state;
225 #ifdef CONFIG_PREEMPT_RT
226 struct rcuwait requeue_wait;
228 } __randomize_layout;
231 * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an
232 * underlying rtmutex. The task which is about to be requeued could have
233 * just woken up (timeout, signal). After the wake up the task has to
234 * acquire hash bucket lock, which is held by the requeue code. As a task
235 * can only be blocked on _ONE_ rtmutex at a time, the proxy lock blocking
236 * and the hash bucket lock blocking would collide and corrupt state.
238 * On !PREEMPT_RT this is not a problem and everything could be serialized
239 * on hash bucket lock, but aside of having the benefit of common code,
240 * this allows to avoid doing the requeue when the task is already on the
241 * way out and taking the hash bucket lock of the original uaddr1 when the
242 * requeue has been completed.
244 * The following state transitions are valid:
246 * On the waiter side:
247 * Q_REQUEUE_PI_NONE -> Q_REQUEUE_PI_IGNORE
248 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_WAIT
250 * On the requeue side:
251 * Q_REQUEUE_PI_NONE -> Q_REQUEUE_PI_INPROGRESS
252 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_DONE/LOCKED
253 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_NONE (requeue failed)
254 * Q_REQUEUE_PI_WAIT -> Q_REQUEUE_PI_DONE/LOCKED
255 * Q_REQUEUE_PI_WAIT -> Q_REQUEUE_PI_IGNORE (requeue failed)
257 * The requeue side ignores a waiter with state Q_REQUEUE_PI_IGNORE as this
258 * signals that the waiter is already on the way out. It also means that
259 * the waiter is still on the 'wait' futex, i.e. uaddr1.
261 * The waiter side signals early wakeup to the requeue side either through
262 * setting state to Q_REQUEUE_PI_IGNORE or to Q_REQUEUE_PI_WAIT depending
263 * on the current state. In case of Q_REQUEUE_PI_IGNORE it can immediately
264 * proceed to take the hash bucket lock of uaddr1. If it set state to WAIT,
265 * which means the wakeup is interleaving with a requeue in progress it has
266 * to wait for the requeue side to change the state. Either to DONE/LOCKED
267 * or to IGNORE. DONE/LOCKED means the waiter q is now on the uaddr2 futex
268 * and either blocked (DONE) or has acquired it (LOCKED). IGNORE is set by
269 * the requeue side when the requeue attempt failed via deadlock detection
270 * and therefore the waiter q is still on the uaddr1 futex.
273 Q_REQUEUE_PI_NONE = 0,
275 Q_REQUEUE_PI_IN_PROGRESS,
281 static const struct futex_q futex_q_init = {
282 /* list gets initialized in queue_me()*/
283 .key = FUTEX_KEY_INIT,
284 .bitset = FUTEX_BITSET_MATCH_ANY,
285 .requeue_state = ATOMIC_INIT(Q_REQUEUE_PI_NONE),
289 * Hash buckets are shared by all the futex_keys that hash to the same
290 * location. Each key may have multiple futex_q structures, one for each task
291 * waiting on a futex.
293 struct futex_hash_bucket {
296 struct plist_head chain;
297 } ____cacheline_aligned_in_smp;
300 * The base of the bucket array and its size are always used together
301 * (after initialization only in hash_futex()), so ensure that they
302 * reside in the same cacheline.
305 struct futex_hash_bucket *queues;
306 unsigned long hashsize;
307 } __futex_data __read_mostly __aligned(2*sizeof(long));
308 #define futex_queues (__futex_data.queues)
309 #define futex_hashsize (__futex_data.hashsize)
313 * Fault injections for futexes.
315 #ifdef CONFIG_FAIL_FUTEX
318 struct fault_attr attr;
322 .attr = FAULT_ATTR_INITIALIZER,
323 .ignore_private = false,
326 static int __init setup_fail_futex(char *str)
328 return setup_fault_attr(&fail_futex.attr, str);
330 __setup("fail_futex=", setup_fail_futex);
332 static bool should_fail_futex(bool fshared)
334 if (fail_futex.ignore_private && !fshared)
337 return should_fail(&fail_futex.attr, 1);
340 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
342 static int __init fail_futex_debugfs(void)
344 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
347 dir = fault_create_debugfs_attr("fail_futex", NULL,
352 debugfs_create_bool("ignore-private", mode, dir,
353 &fail_futex.ignore_private);
357 late_initcall(fail_futex_debugfs);
359 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
362 static inline bool should_fail_futex(bool fshared)
366 #endif /* CONFIG_FAIL_FUTEX */
369 static void compat_exit_robust_list(struct task_struct *curr);
373 * Reflects a new waiter being added to the waitqueue.
375 static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
378 atomic_inc(&hb->waiters);
380 * Full barrier (A), see the ordering comment above.
382 smp_mb__after_atomic();
387 * Reflects a waiter being removed from the waitqueue by wakeup
390 static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
393 atomic_dec(&hb->waiters);
397 static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
401 * Full barrier (B), see the ordering comment above.
404 return atomic_read(&hb->waiters);
411 * hash_futex - Return the hash bucket in the global hash
412 * @key: Pointer to the futex key for which the hash is calculated
414 * We hash on the keys returned from get_futex_key (see below) and return the
415 * corresponding hash bucket in the global hash.
417 static struct futex_hash_bucket *hash_futex(union futex_key *key)
419 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
422 return &futex_queues[hash & (futex_hashsize - 1)];
427 * match_futex - Check whether two futex keys are equal
428 * @key1: Pointer to key1
429 * @key2: Pointer to key2
431 * Return 1 if two futex_keys are equal, 0 otherwise.
433 static inline int match_futex(union futex_key *key1, union futex_key *key2)
436 && key1->both.word == key2->both.word
437 && key1->both.ptr == key2->both.ptr
438 && key1->both.offset == key2->both.offset);
447 * futex_setup_timer - set up the sleeping hrtimer.
448 * @time: ptr to the given timeout value
449 * @timeout: the hrtimer_sleeper structure to be set up
450 * @flags: futex flags
451 * @range_ns: optional range in ns
453 * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
456 static inline struct hrtimer_sleeper *
457 futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
458 int flags, u64 range_ns)
463 hrtimer_init_sleeper_on_stack(timeout, (flags & FLAGS_CLOCKRT) ?
464 CLOCK_REALTIME : CLOCK_MONOTONIC,
467 * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
468 * effectively the same as calling hrtimer_set_expires().
470 hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
476 * Generate a machine wide unique identifier for this inode.
478 * This relies on u64 not wrapping in the life-time of the machine; which with
479 * 1ns resolution means almost 585 years.
481 * This further relies on the fact that a well formed program will not unmap
482 * the file while it has a (shared) futex waiting on it. This mapping will have
483 * a file reference which pins the mount and inode.
485 * If for some reason an inode gets evicted and read back in again, it will get
486 * a new sequence number and will _NOT_ match, even though it is the exact same
489 * It is important that match_futex() will never have a false-positive, esp.
490 * for PI futexes that can mess up the state. The above argues that false-negatives
491 * are only possible for malformed programs.
493 static u64 get_inode_sequence_number(struct inode *inode)
495 static atomic64_t i_seq;
498 /* Does the inode already have a sequence number? */
499 old = atomic64_read(&inode->i_sequence);
504 u64 new = atomic64_add_return(1, &i_seq);
505 if (WARN_ON_ONCE(!new))
508 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
516 * get_futex_key() - Get parameters which are the keys for a futex
517 * @uaddr: virtual address of the futex
518 * @fshared: false for a PROCESS_PRIVATE futex, true for PROCESS_SHARED
519 * @key: address where result is stored.
520 * @rw: mapping needs to be read/write (values: FUTEX_READ,
523 * Return: a negative error code or 0
525 * The key words are stored in @key on success.
527 * For shared mappings (when @fshared), the key is:
529 * ( inode->i_sequence, page->index, offset_within_page )
531 * [ also see get_inode_sequence_number() ]
533 * For private mappings (or when !@fshared), the key is:
535 * ( current->mm, address, 0 )
537 * This allows (cross process, where applicable) identification of the futex
538 * without keeping the page pinned for the duration of the FUTEX_WAIT.
540 * lock_page() might sleep, the caller should not hold a spinlock.
542 static int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,
543 enum futex_access rw)
545 unsigned long address = (unsigned long)uaddr;
546 struct mm_struct *mm = current->mm;
547 struct page *page, *tail;
548 struct address_space *mapping;
552 * The futex address must be "naturally" aligned.
554 key->both.offset = address % PAGE_SIZE;
555 if (unlikely((address % sizeof(u32)) != 0))
557 address -= key->both.offset;
559 if (unlikely(!access_ok(uaddr, sizeof(u32))))
562 if (unlikely(should_fail_futex(fshared)))
566 * PROCESS_PRIVATE futexes are fast.
567 * As the mm cannot disappear under us and the 'key' only needs
568 * virtual address, we dont even have to find the underlying vma.
569 * Note : We do have to check 'uaddr' is a valid user address,
570 * but access_ok() should be faster than find_vma()
573 key->private.mm = mm;
574 key->private.address = address;
579 /* Ignore any VERIFY_READ mapping (futex common case) */
580 if (unlikely(should_fail_futex(true)))
583 err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
585 * If write access is not required (eg. FUTEX_WAIT), try
586 * and get read-only access.
588 if (err == -EFAULT && rw == FUTEX_READ) {
589 err = get_user_pages_fast(address, 1, 0, &page);
598 * The treatment of mapping from this point on is critical. The page
599 * lock protects many things but in this context the page lock
600 * stabilizes mapping, prevents inode freeing in the shared
601 * file-backed region case and guards against movement to swap cache.
603 * Strictly speaking the page lock is not needed in all cases being
604 * considered here and page lock forces unnecessarily serialization
605 * From this point on, mapping will be re-verified if necessary and
606 * page lock will be acquired only if it is unavoidable
608 * Mapping checks require the head page for any compound page so the
609 * head page and mapping is looked up now. For anonymous pages, it
610 * does not matter if the page splits in the future as the key is
611 * based on the address. For filesystem-backed pages, the tail is
612 * required as the index of the page determines the key. For
613 * base pages, there is no tail page and tail == page.
616 page = compound_head(page);
617 mapping = READ_ONCE(page->mapping);
620 * If page->mapping is NULL, then it cannot be a PageAnon
621 * page; but it might be the ZERO_PAGE or in the gate area or
622 * in a special mapping (all cases which we are happy to fail);
623 * or it may have been a good file page when get_user_pages_fast
624 * found it, but truncated or holepunched or subjected to
625 * invalidate_complete_page2 before we got the page lock (also
626 * cases which we are happy to fail). And we hold a reference,
627 * so refcount care in invalidate_complete_page's remove_mapping
628 * prevents drop_caches from setting mapping to NULL beneath us.
630 * The case we do have to guard against is when memory pressure made
631 * shmem_writepage move it from filecache to swapcache beneath us:
632 * an unlikely race, but we do need to retry for page->mapping.
634 if (unlikely(!mapping)) {
638 * Page lock is required to identify which special case above
639 * applies. If this is really a shmem page then the page lock
640 * will prevent unexpected transitions.
643 shmem_swizzled = PageSwapCache(page) || page->mapping;
654 * Private mappings are handled in a simple way.
656 * If the futex key is stored on an anonymous page, then the associated
657 * object is the mm which is implicitly pinned by the calling process.
659 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
660 * it's a read-only handle, it's expected that futexes attach to
661 * the object not the particular process.
663 if (PageAnon(page)) {
665 * A RO anonymous page will never change and thus doesn't make
666 * sense for futex operations.
668 if (unlikely(should_fail_futex(true)) || ro) {
673 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
674 key->private.mm = mm;
675 key->private.address = address;
681 * The associated futex object in this case is the inode and
682 * the page->mapping must be traversed. Ordinarily this should
683 * be stabilised under page lock but it's not strictly
684 * necessary in this case as we just want to pin the inode, not
685 * update the radix tree or anything like that.
687 * The RCU read lock is taken as the inode is finally freed
688 * under RCU. If the mapping still matches expectations then the
689 * mapping->host can be safely accessed as being a valid inode.
693 if (READ_ONCE(page->mapping) != mapping) {
700 inode = READ_ONCE(mapping->host);
708 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
709 key->shared.i_seq = get_inode_sequence_number(inode);
710 key->shared.pgoff = page_to_pgoff(tail);
720 * fault_in_user_writeable() - Fault in user address and verify RW access
721 * @uaddr: pointer to faulting user space address
723 * Slow path to fixup the fault we just took in the atomic write
726 * We have no generic implementation of a non-destructive write to the
727 * user address. We know that we faulted in the atomic pagefault
728 * disabled section so we can as well avoid the #PF overhead by
729 * calling get_user_pages() right away.
731 static int fault_in_user_writeable(u32 __user *uaddr)
733 struct mm_struct *mm = current->mm;
737 ret = fixup_user_fault(mm, (unsigned long)uaddr,
738 FAULT_FLAG_WRITE, NULL);
739 mmap_read_unlock(mm);
741 return ret < 0 ? ret : 0;
745 * futex_top_waiter() - Return the highest priority waiter on a futex
746 * @hb: the hash bucket the futex_q's reside in
747 * @key: the futex key (to distinguish it from other futex futex_q's)
749 * Must be called with the hb lock held.
751 static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
752 union futex_key *key)
754 struct futex_q *this;
756 plist_for_each_entry(this, &hb->chain, list) {
757 if (match_futex(&this->key, key))
763 static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
764 u32 uval, u32 newval)
769 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
775 static int get_futex_value_locked(u32 *dest, u32 __user *from)
780 ret = __get_user(*dest, from);
783 return ret ? -EFAULT : 0;
790 static int refill_pi_state_cache(void)
792 struct futex_pi_state *pi_state;
794 if (likely(current->pi_state_cache))
797 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
802 INIT_LIST_HEAD(&pi_state->list);
803 /* pi_mutex gets initialized later */
804 pi_state->owner = NULL;
805 refcount_set(&pi_state->refcount, 1);
806 pi_state->key = FUTEX_KEY_INIT;
808 current->pi_state_cache = pi_state;
813 static struct futex_pi_state *alloc_pi_state(void)
815 struct futex_pi_state *pi_state = current->pi_state_cache;
818 current->pi_state_cache = NULL;
823 static void pi_state_update_owner(struct futex_pi_state *pi_state,
824 struct task_struct *new_owner)
826 struct task_struct *old_owner = pi_state->owner;
828 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
831 raw_spin_lock(&old_owner->pi_lock);
832 WARN_ON(list_empty(&pi_state->list));
833 list_del_init(&pi_state->list);
834 raw_spin_unlock(&old_owner->pi_lock);
838 raw_spin_lock(&new_owner->pi_lock);
839 WARN_ON(!list_empty(&pi_state->list));
840 list_add(&pi_state->list, &new_owner->pi_state_list);
841 pi_state->owner = new_owner;
842 raw_spin_unlock(&new_owner->pi_lock);
846 static void get_pi_state(struct futex_pi_state *pi_state)
848 WARN_ON_ONCE(!refcount_inc_not_zero(&pi_state->refcount));
852 * Drops a reference to the pi_state object and frees or caches it
853 * when the last reference is gone.
855 static void put_pi_state(struct futex_pi_state *pi_state)
860 if (!refcount_dec_and_test(&pi_state->refcount))
864 * If pi_state->owner is NULL, the owner is most probably dying
865 * and has cleaned up the pi_state already
867 if (pi_state->owner) {
870 raw_spin_lock_irqsave(&pi_state->pi_mutex.wait_lock, flags);
871 pi_state_update_owner(pi_state, NULL);
872 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
873 raw_spin_unlock_irqrestore(&pi_state->pi_mutex.wait_lock, flags);
876 if (current->pi_state_cache) {
880 * pi_state->list is already empty.
881 * clear pi_state->owner.
882 * refcount is at 0 - put it back to 1.
884 pi_state->owner = NULL;
885 refcount_set(&pi_state->refcount, 1);
886 current->pi_state_cache = pi_state;
890 #ifdef CONFIG_FUTEX_PI
893 * This task is holding PI mutexes at exit time => bad.
894 * Kernel cleans up PI-state, but userspace is likely hosed.
895 * (Robust-futex cleanup is separate and might save the day for userspace.)
897 static void exit_pi_state_list(struct task_struct *curr)
899 struct list_head *next, *head = &curr->pi_state_list;
900 struct futex_pi_state *pi_state;
901 struct futex_hash_bucket *hb;
902 union futex_key key = FUTEX_KEY_INIT;
904 if (!futex_cmpxchg_enabled)
907 * We are a ZOMBIE and nobody can enqueue itself on
908 * pi_state_list anymore, but we have to be careful
909 * versus waiters unqueueing themselves:
911 raw_spin_lock_irq(&curr->pi_lock);
912 while (!list_empty(head)) {
914 pi_state = list_entry(next, struct futex_pi_state, list);
916 hb = hash_futex(&key);
919 * We can race against put_pi_state() removing itself from the
920 * list (a waiter going away). put_pi_state() will first
921 * decrement the reference count and then modify the list, so
922 * its possible to see the list entry but fail this reference
925 * In that case; drop the locks to let put_pi_state() make
926 * progress and retry the loop.
928 if (!refcount_inc_not_zero(&pi_state->refcount)) {
929 raw_spin_unlock_irq(&curr->pi_lock);
931 raw_spin_lock_irq(&curr->pi_lock);
934 raw_spin_unlock_irq(&curr->pi_lock);
936 spin_lock(&hb->lock);
937 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
938 raw_spin_lock(&curr->pi_lock);
940 * We dropped the pi-lock, so re-check whether this
941 * task still owns the PI-state:
943 if (head->next != next) {
944 /* retain curr->pi_lock for the loop invariant */
945 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
946 spin_unlock(&hb->lock);
947 put_pi_state(pi_state);
951 WARN_ON(pi_state->owner != curr);
952 WARN_ON(list_empty(&pi_state->list));
953 list_del_init(&pi_state->list);
954 pi_state->owner = NULL;
956 raw_spin_unlock(&curr->pi_lock);
957 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
958 spin_unlock(&hb->lock);
960 rt_mutex_futex_unlock(&pi_state->pi_mutex);
961 put_pi_state(pi_state);
963 raw_spin_lock_irq(&curr->pi_lock);
965 raw_spin_unlock_irq(&curr->pi_lock);
968 static inline void exit_pi_state_list(struct task_struct *curr) { }
972 * We need to check the following states:
974 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
976 * [1] NULL | --- | --- | 0 | 0/1 | Valid
977 * [2] NULL | --- | --- | >0 | 0/1 | Valid
979 * [3] Found | NULL | -- | Any | 0/1 | Invalid
981 * [4] Found | Found | NULL | 0 | 1 | Valid
982 * [5] Found | Found | NULL | >0 | 1 | Invalid
984 * [6] Found | Found | task | 0 | 1 | Valid
986 * [7] Found | Found | NULL | Any | 0 | Invalid
988 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
989 * [9] Found | Found | task | 0 | 0 | Invalid
990 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
992 * [1] Indicates that the kernel can acquire the futex atomically. We
993 * came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
995 * [2] Valid, if TID does not belong to a kernel thread. If no matching
996 * thread is found then it indicates that the owner TID has died.
998 * [3] Invalid. The waiter is queued on a non PI futex
1000 * [4] Valid state after exit_robust_list(), which sets the user space
1001 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
1003 * [5] The user space value got manipulated between exit_robust_list()
1004 * and exit_pi_state_list()
1006 * [6] Valid state after exit_pi_state_list() which sets the new owner in
1007 * the pi_state but cannot access the user space value.
1009 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
1011 * [8] Owner and user space value match
1013 * [9] There is no transient state which sets the user space TID to 0
1014 * except exit_robust_list(), but this is indicated by the
1015 * FUTEX_OWNER_DIED bit. See [4]
1017 * [10] There is no transient state which leaves owner and user space
1018 * TID out of sync. Except one error case where the kernel is denied
1019 * write access to the user address, see fixup_pi_state_owner().
1022 * Serialization and lifetime rules:
1026 * hb -> futex_q, relation
1027 * futex_q -> pi_state, relation
1029 * (cannot be raw because hb can contain arbitrary amount
1032 * pi_mutex->wait_lock:
1036 * (and pi_mutex 'obviously')
1040 * p->pi_state_list -> pi_state->list, relation
1041 * pi_mutex->owner -> pi_state->owner, relation
1043 * pi_state->refcount:
1051 * pi_mutex->wait_lock
1057 * Validate that the existing waiter has a pi_state and sanity check
1058 * the pi_state against the user space value. If correct, attach to
1061 static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1062 struct futex_pi_state *pi_state,
1063 struct futex_pi_state **ps)
1065 pid_t pid = uval & FUTEX_TID_MASK;
1070 * Userspace might have messed up non-PI and PI futexes [3]
1072 if (unlikely(!pi_state))
1076 * We get here with hb->lock held, and having found a
1077 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1078 * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
1079 * which in turn means that futex_lock_pi() still has a reference on
1082 * The waiter holding a reference on @pi_state also protects against
1083 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1084 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1085 * free pi_state before we can take a reference ourselves.
1087 WARN_ON(!refcount_read(&pi_state->refcount));
1090 * Now that we have a pi_state, we can acquire wait_lock
1091 * and do the state validation.
1093 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1096 * Since {uval, pi_state} is serialized by wait_lock, and our current
1097 * uval was read without holding it, it can have changed. Verify it
1098 * still is what we expect it to be, otherwise retry the entire
1101 if (get_futex_value_locked(&uval2, uaddr))
1108 * Handle the owner died case:
1110 if (uval & FUTEX_OWNER_DIED) {
1112 * exit_pi_state_list sets owner to NULL and wakes the
1113 * topmost waiter. The task which acquires the
1114 * pi_state->rt_mutex will fixup owner.
1116 if (!pi_state->owner) {
1118 * No pi state owner, but the user space TID
1119 * is not 0. Inconsistent state. [5]
1124 * Take a ref on the state and return success. [4]
1130 * If TID is 0, then either the dying owner has not
1131 * yet executed exit_pi_state_list() or some waiter
1132 * acquired the rtmutex in the pi state, but did not
1133 * yet fixup the TID in user space.
1135 * Take a ref on the state and return success. [6]
1141 * If the owner died bit is not set, then the pi_state
1142 * must have an owner. [7]
1144 if (!pi_state->owner)
1149 * Bail out if user space manipulated the futex value. If pi
1150 * state exists then the owner TID must be the same as the
1151 * user space TID. [9/10]
1153 if (pid != task_pid_vnr(pi_state->owner))
1157 get_pi_state(pi_state);
1158 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1175 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1180 * wait_for_owner_exiting - Block until the owner has exited
1181 * @ret: owner's current futex lock status
1182 * @exiting: Pointer to the exiting task
1184 * Caller must hold a refcount on @exiting.
1186 static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1188 if (ret != -EBUSY) {
1189 WARN_ON_ONCE(exiting);
1193 if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
1196 mutex_lock(&exiting->futex_exit_mutex);
1198 * No point in doing state checking here. If the waiter got here
1199 * while the task was in exec()->exec_futex_release() then it can
1200 * have any FUTEX_STATE_* value when the waiter has acquired the
1201 * mutex. OK, if running, EXITING or DEAD if it reached exit()
1202 * already. Highly unlikely and not a problem. Just one more round
1203 * through the futex maze.
1205 mutex_unlock(&exiting->futex_exit_mutex);
1207 put_task_struct(exiting);
1210 static int handle_exit_race(u32 __user *uaddr, u32 uval,
1211 struct task_struct *tsk)
1216 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1217 * caller that the alleged owner is busy.
1219 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
1223 * Reread the user space value to handle the following situation:
1227 * sys_exit() sys_futex()
1228 * do_exit() futex_lock_pi()
1229 * futex_lock_pi_atomic()
1230 * exit_signals(tsk) No waiters:
1231 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1232 * mm_release(tsk) Set waiter bit
1233 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1234 * Set owner died attach_to_pi_owner() {
1235 * *uaddr = 0xC0000000; tsk = get_task(PID);
1236 * } if (!tsk->flags & PF_EXITING) {
1238 * tsk->futex_state = } else {
1239 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1242 * return -ESRCH; <--- FAIL
1245 * Returning ESRCH unconditionally is wrong here because the
1246 * user space value has been changed by the exiting task.
1248 * The same logic applies to the case where the exiting task is
1251 if (get_futex_value_locked(&uval2, uaddr))
1254 /* If the user space value has changed, try again. */
1259 * The exiting task did not have a robust list, the robust list was
1260 * corrupted or the user space value in *uaddr is simply bogus.
1261 * Give up and tell user space.
1267 * Lookup the task for the TID provided from user space and attach to
1268 * it after doing proper sanity checks.
1270 static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
1271 struct futex_pi_state **ps,
1272 struct task_struct **exiting)
1274 pid_t pid = uval & FUTEX_TID_MASK;
1275 struct futex_pi_state *pi_state;
1276 struct task_struct *p;
1279 * We are the first waiter - try to look up the real owner and attach
1280 * the new pi_state to it, but bail out when TID = 0 [1]
1282 * The !pid check is paranoid. None of the call sites should end up
1283 * with pid == 0, but better safe than sorry. Let the caller retry
1287 p = find_get_task_by_vpid(pid);
1289 return handle_exit_race(uaddr, uval, NULL);
1291 if (unlikely(p->flags & PF_KTHREAD)) {
1297 * We need to look at the task state to figure out, whether the
1298 * task is exiting. To protect against the change of the task state
1299 * in futex_exit_release(), we do this protected by p->pi_lock:
1301 raw_spin_lock_irq(&p->pi_lock);
1302 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
1304 * The task is on the way out. When the futex state is
1305 * FUTEX_STATE_DEAD, we know that the task has finished
1308 int ret = handle_exit_race(uaddr, uval, p);
1310 raw_spin_unlock_irq(&p->pi_lock);
1312 * If the owner task is between FUTEX_STATE_EXITING and
1313 * FUTEX_STATE_DEAD then store the task pointer and keep
1314 * the reference on the task struct. The calling code will
1315 * drop all locks, wait for the task to reach
1316 * FUTEX_STATE_DEAD and then drop the refcount. This is
1317 * required to prevent a live lock when the current task
1318 * preempted the exiting task between the two states.
1328 * No existing pi state. First waiter. [2]
1330 * This creates pi_state, we have hb->lock held, this means nothing can
1331 * observe this state, wait_lock is irrelevant.
1333 pi_state = alloc_pi_state();
1336 * Initialize the pi_mutex in locked state and make @p
1339 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1341 /* Store the key for possible exit cleanups: */
1342 pi_state->key = *key;
1344 WARN_ON(!list_empty(&pi_state->list));
1345 list_add(&pi_state->list, &p->pi_state_list);
1347 * Assignment without holding pi_state->pi_mutex.wait_lock is safe
1348 * because there is no concurrency as the object is not published yet.
1350 pi_state->owner = p;
1351 raw_spin_unlock_irq(&p->pi_lock);
1360 static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1365 if (unlikely(should_fail_futex(true)))
1368 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1372 /* If user space value changed, let the caller retry */
1373 return curval != uval ? -EAGAIN : 0;
1377 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
1378 * @uaddr: the pi futex user address
1379 * @hb: the pi futex hash bucket
1380 * @key: the futex key associated with uaddr and hb
1381 * @ps: the pi_state pointer where we store the result of the
1383 * @task: the task to perform the atomic lock work for. This will
1384 * be "current" except in the case of requeue pi.
1385 * @exiting: Pointer to store the task pointer of the owner task
1386 * which is in the middle of exiting
1387 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1390 * - 0 - ready to wait;
1391 * - 1 - acquired the lock;
1394 * The hb->lock must be held by the caller.
1396 * @exiting is only set when the return value is -EBUSY. If so, this holds
1397 * a refcount on the exiting task on return and the caller needs to drop it
1398 * after waiting for the exit to complete.
1400 static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1401 union futex_key *key,
1402 struct futex_pi_state **ps,
1403 struct task_struct *task,
1404 struct task_struct **exiting,
1407 u32 uval, newval, vpid = task_pid_vnr(task);
1408 struct futex_q *top_waiter;
1412 * Read the user space value first so we can validate a few
1413 * things before proceeding further.
1415 if (get_futex_value_locked(&uval, uaddr))
1418 if (unlikely(should_fail_futex(true)))
1424 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1427 if ((unlikely(should_fail_futex(true))))
1431 * Lookup existing state first. If it exists, try to attach to
1434 top_waiter = futex_top_waiter(hb, key);
1436 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
1439 * No waiter and user TID is 0. We are here because the
1440 * waiters or the owner died bit is set or called from
1441 * requeue_cmp_pi or for whatever reason something took the
1444 if (!(uval & FUTEX_TID_MASK)) {
1446 * We take over the futex. No other waiters and the user space
1447 * TID is 0. We preserve the owner died bit.
1449 newval = uval & FUTEX_OWNER_DIED;
1452 /* The futex requeue_pi code can enforce the waiters bit */
1454 newval |= FUTEX_WAITERS;
1456 ret = lock_pi_update_atomic(uaddr, uval, newval);
1457 /* If the take over worked, return 1 */
1458 return ret < 0 ? ret : 1;
1462 * First waiter. Set the waiters bit before attaching ourself to
1463 * the owner. If owner tries to unlock, it will be forced into
1464 * the kernel and blocked on hb->lock.
1466 newval = uval | FUTEX_WAITERS;
1467 ret = lock_pi_update_atomic(uaddr, uval, newval);
1471 * If the update of the user space value succeeded, we try to
1472 * attach to the owner. If that fails, no harm done, we only
1473 * set the FUTEX_WAITERS bit in the user space variable.
1475 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
1479 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1480 * @q: The futex_q to unqueue
1482 * The q->lock_ptr must not be NULL and must be held by the caller.
1484 static void __unqueue_futex(struct futex_q *q)
1486 struct futex_hash_bucket *hb;
1488 if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
1490 lockdep_assert_held(q->lock_ptr);
1492 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1493 plist_del(&q->list, &hb->chain);
1498 * The hash bucket lock must be held when this is called.
1499 * Afterwards, the futex_q must not be accessed. Callers
1500 * must ensure to later call wake_up_q() for the actual
1503 static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
1505 struct task_struct *p = q->task;
1507 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1513 * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
1514 * is written, without taking any locks. This is possible in the event
1515 * of a spurious wakeup, for example. A memory barrier is required here
1516 * to prevent the following store to lock_ptr from getting ahead of the
1517 * plist_del in __unqueue_futex().
1519 smp_store_release(&q->lock_ptr, NULL);
1522 * Queue the task for later wakeup for after we've released
1525 wake_q_add_safe(wake_q, p);
1529 * Caller must hold a reference on @pi_state.
1531 static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
1533 struct rt_mutex_waiter *top_waiter;
1534 struct task_struct *new_owner;
1535 bool postunlock = false;
1536 DEFINE_RT_WAKE_Q(wqh);
1540 top_waiter = rt_mutex_top_waiter(&pi_state->pi_mutex);
1541 if (WARN_ON_ONCE(!top_waiter)) {
1543 * As per the comment in futex_unlock_pi() this should not happen.
1545 * When this happens, give up our locks and try again, giving
1546 * the futex_lock_pi() instance time to complete, either by
1547 * waiting on the rtmutex or removing itself from the futex
1554 new_owner = top_waiter->task;
1557 * We pass it to the next owner. The WAITERS bit is always kept
1558 * enabled while there is PI state around. We cleanup the owner
1559 * died bit, because we are the owner.
1561 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
1563 if (unlikely(should_fail_futex(true))) {
1568 ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1569 if (!ret && (curval != uval)) {
1571 * If a unconditional UNLOCK_PI operation (user space did not
1572 * try the TID->0 transition) raced with a waiter setting the
1573 * FUTEX_WAITERS flag between get_user() and locking the hash
1574 * bucket lock, retry the operation.
1576 if ((FUTEX_TID_MASK & curval) == uval)
1584 * This is a point of no return; once we modified the uval
1585 * there is no going back and subsequent operations must
1588 pi_state_update_owner(pi_state, new_owner);
1589 postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wqh);
1593 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1596 rt_mutex_postunlock(&wqh);
1602 * Express the locking dependencies for lockdep:
1605 double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1608 spin_lock(&hb1->lock);
1610 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1611 } else { /* hb1 > hb2 */
1612 spin_lock(&hb2->lock);
1613 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1618 double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1620 spin_unlock(&hb1->lock);
1622 spin_unlock(&hb2->lock);
1626 * Wake up waiters matching bitset queued on this futex (uaddr).
1629 futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1631 struct futex_hash_bucket *hb;
1632 struct futex_q *this, *next;
1633 union futex_key key = FUTEX_KEY_INIT;
1635 DEFINE_WAKE_Q(wake_q);
1640 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_READ);
1641 if (unlikely(ret != 0))
1644 hb = hash_futex(&key);
1646 /* Make sure we really have tasks to wakeup */
1647 if (!hb_waiters_pending(hb))
1650 spin_lock(&hb->lock);
1652 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1653 if (match_futex (&this->key, &key)) {
1654 if (this->pi_state || this->rt_waiter) {
1659 /* Check if one of the bits is set in both bitsets */
1660 if (!(this->bitset & bitset))
1663 mark_wake_futex(&wake_q, this);
1664 if (++ret >= nr_wake)
1669 spin_unlock(&hb->lock);
1674 static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1676 unsigned int op = (encoded_op & 0x70000000) >> 28;
1677 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
1678 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1679 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
1682 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
1683 if (oparg < 0 || oparg > 31) {
1684 char comm[sizeof(current->comm)];
1686 * kill this print and return -EINVAL when userspace
1689 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1690 get_task_comm(comm, current), oparg);
1696 pagefault_disable();
1697 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
1703 case FUTEX_OP_CMP_EQ:
1704 return oldval == cmparg;
1705 case FUTEX_OP_CMP_NE:
1706 return oldval != cmparg;
1707 case FUTEX_OP_CMP_LT:
1708 return oldval < cmparg;
1709 case FUTEX_OP_CMP_GE:
1710 return oldval >= cmparg;
1711 case FUTEX_OP_CMP_LE:
1712 return oldval <= cmparg;
1713 case FUTEX_OP_CMP_GT:
1714 return oldval > cmparg;
1721 * Wake up all waiters hashed on the physical page that is mapped
1722 * to this virtual address:
1725 futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
1726 int nr_wake, int nr_wake2, int op)
1728 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
1729 struct futex_hash_bucket *hb1, *hb2;
1730 struct futex_q *this, *next;
1732 DEFINE_WAKE_Q(wake_q);
1735 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
1736 if (unlikely(ret != 0))
1738 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
1739 if (unlikely(ret != 0))
1742 hb1 = hash_futex(&key1);
1743 hb2 = hash_futex(&key2);
1746 double_lock_hb(hb1, hb2);
1747 op_ret = futex_atomic_op_inuser(op, uaddr2);
1748 if (unlikely(op_ret < 0)) {
1749 double_unlock_hb(hb1, hb2);
1751 if (!IS_ENABLED(CONFIG_MMU) ||
1752 unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
1754 * we don't get EFAULT from MMU faults if we don't have
1755 * an MMU, but we might get them from range checking
1761 if (op_ret == -EFAULT) {
1762 ret = fault_in_user_writeable(uaddr2);
1768 if (!(flags & FLAGS_SHARED))
1773 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
1774 if (match_futex (&this->key, &key1)) {
1775 if (this->pi_state || this->rt_waiter) {
1779 mark_wake_futex(&wake_q, this);
1780 if (++ret >= nr_wake)
1787 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
1788 if (match_futex (&this->key, &key2)) {
1789 if (this->pi_state || this->rt_waiter) {
1793 mark_wake_futex(&wake_q, this);
1794 if (++op_ret >= nr_wake2)
1802 double_unlock_hb(hb1, hb2);
1808 * requeue_futex() - Requeue a futex_q from one hb to another
1809 * @q: the futex_q to requeue
1810 * @hb1: the source hash_bucket
1811 * @hb2: the target hash_bucket
1812 * @key2: the new key for the requeued futex_q
1815 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1816 struct futex_hash_bucket *hb2, union futex_key *key2)
1820 * If key1 and key2 hash to the same bucket, no need to
1823 if (likely(&hb1->chain != &hb2->chain)) {
1824 plist_del(&q->list, &hb1->chain);
1825 hb_waiters_dec(hb1);
1826 hb_waiters_inc(hb2);
1827 plist_add(&q->list, &hb2->chain);
1828 q->lock_ptr = &hb2->lock;
1833 static inline bool futex_requeue_pi_prepare(struct futex_q *q,
1834 struct futex_pi_state *pi_state)
1839 * Set state to Q_REQUEUE_PI_IN_PROGRESS unless an early wakeup has
1840 * already set Q_REQUEUE_PI_IGNORE to signal that requeue should
1841 * ignore the waiter.
1843 old = atomic_read_acquire(&q->requeue_state);
1845 if (old == Q_REQUEUE_PI_IGNORE)
1849 * futex_proxy_trylock_atomic() might have set it to
1850 * IN_PROGRESS and a interleaved early wake to WAIT.
1852 * It was considered to have an extra state for that
1853 * trylock, but that would just add more conditionals
1854 * all over the place for a dubious value.
1856 if (old != Q_REQUEUE_PI_NONE)
1859 new = Q_REQUEUE_PI_IN_PROGRESS;
1860 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1862 q->pi_state = pi_state;
1866 static inline void futex_requeue_pi_complete(struct futex_q *q, int locked)
1870 old = atomic_read_acquire(&q->requeue_state);
1872 if (old == Q_REQUEUE_PI_IGNORE)
1876 /* Requeue succeeded. Set DONE or LOCKED */
1877 WARN_ON_ONCE(old != Q_REQUEUE_PI_IN_PROGRESS &&
1878 old != Q_REQUEUE_PI_WAIT);
1879 new = Q_REQUEUE_PI_DONE + locked;
1880 } else if (old == Q_REQUEUE_PI_IN_PROGRESS) {
1881 /* Deadlock, no early wakeup interleave */
1882 new = Q_REQUEUE_PI_NONE;
1884 /* Deadlock, early wakeup interleave. */
1885 WARN_ON_ONCE(old != Q_REQUEUE_PI_WAIT);
1886 new = Q_REQUEUE_PI_IGNORE;
1888 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1890 #ifdef CONFIG_PREEMPT_RT
1891 /* If the waiter interleaved with the requeue let it know */
1892 if (unlikely(old == Q_REQUEUE_PI_WAIT))
1893 rcuwait_wake_up(&q->requeue_wait);
1897 static inline int futex_requeue_pi_wakeup_sync(struct futex_q *q)
1901 old = atomic_read_acquire(&q->requeue_state);
1903 /* Is requeue done already? */
1904 if (old >= Q_REQUEUE_PI_DONE)
1908 * If not done, then tell the requeue code to either ignore
1909 * the waiter or to wake it up once the requeue is done.
1911 new = Q_REQUEUE_PI_WAIT;
1912 if (old == Q_REQUEUE_PI_NONE)
1913 new = Q_REQUEUE_PI_IGNORE;
1914 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1916 /* If the requeue was in progress, wait for it to complete */
1917 if (old == Q_REQUEUE_PI_IN_PROGRESS) {
1918 #ifdef CONFIG_PREEMPT_RT
1919 rcuwait_wait_event(&q->requeue_wait,
1920 atomic_read(&q->requeue_state) != Q_REQUEUE_PI_WAIT,
1921 TASK_UNINTERRUPTIBLE);
1923 (void)atomic_cond_read_relaxed(&q->requeue_state, VAL != Q_REQUEUE_PI_WAIT);
1928 * Requeue is now either prohibited or complete. Reread state
1929 * because during the wait above it might have changed. Nothing
1930 * will modify q->requeue_state after this point.
1932 return atomic_read(&q->requeue_state);
1936 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
1938 * @key: the key of the requeue target futex
1939 * @hb: the hash_bucket of the requeue target futex
1941 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1942 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1943 * to the requeue target futex so the waiter can detect the wakeup on the right
1944 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
1945 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1946 * to protect access to the pi_state to fixup the owner later. Must be called
1947 * with both q->lock_ptr and hb->lock held.
1950 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1951 struct futex_hash_bucket *hb)
1957 WARN_ON(!q->rt_waiter);
1958 q->rt_waiter = NULL;
1960 q->lock_ptr = &hb->lock;
1962 /* Signal locked state to the waiter */
1963 futex_requeue_pi_complete(q, 1);
1964 wake_up_state(q->task, TASK_NORMAL);
1968 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
1969 * @pifutex: the user address of the to futex
1970 * @hb1: the from futex hash bucket, must be locked by the caller
1971 * @hb2: the to futex hash bucket, must be locked by the caller
1972 * @key1: the from futex key
1973 * @key2: the to futex key
1974 * @ps: address to store the pi_state pointer
1975 * @exiting: Pointer to store the task pointer of the owner task
1976 * which is in the middle of exiting
1977 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1979 * Try and get the lock on behalf of the top waiter if we can do it atomically.
1980 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1981 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1982 * hb1 and hb2 must be held by the caller.
1984 * @exiting is only set when the return value is -EBUSY. If so, this holds
1985 * a refcount on the exiting task on return and the caller needs to drop it
1986 * after waiting for the exit to complete.
1989 * - 0 - failed to acquire the lock atomically;
1990 * - >0 - acquired the lock, return value is vpid of the top_waiter
1994 futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
1995 struct futex_hash_bucket *hb2, union futex_key *key1,
1996 union futex_key *key2, struct futex_pi_state **ps,
1997 struct task_struct **exiting, int set_waiters)
1999 struct futex_q *top_waiter = NULL;
2003 if (get_futex_value_locked(&curval, pifutex))
2006 if (unlikely(should_fail_futex(true)))
2010 * Find the top_waiter and determine if there are additional waiters.
2011 * If the caller intends to requeue more than 1 waiter to pifutex,
2012 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
2013 * as we have means to handle the possible fault. If not, don't set
2014 * the bit unnecessarily as it will force the subsequent unlock to enter
2017 top_waiter = futex_top_waiter(hb1, key1);
2019 /* There are no waiters, nothing for us to do. */
2024 * Ensure that this is a waiter sitting in futex_wait_requeue_pi()
2025 * and waiting on the 'waitqueue' futex which is always !PI.
2027 if (!top_waiter->rt_waiter || top_waiter->pi_state)
2030 /* Ensure we requeue to the expected futex. */
2031 if (!match_futex(top_waiter->requeue_pi_key, key2))
2034 /* Ensure that this does not race against an early wakeup */
2035 if (!futex_requeue_pi_prepare(top_waiter, NULL))
2039 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
2040 * the contended case or if set_waiters is 1. The pi_state is returned
2041 * in ps in contended cases.
2043 vpid = task_pid_vnr(top_waiter->task);
2044 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
2045 exiting, set_waiters);
2047 /* Dequeue, wake up and update top_waiter::requeue_state */
2048 requeue_pi_wake_futex(top_waiter, key2, hb2);
2050 } else if (ret < 0) {
2051 /* Rewind top_waiter::requeue_state */
2052 futex_requeue_pi_complete(top_waiter, ret);
2055 * futex_lock_pi_atomic() did not acquire the user space
2056 * futex, but managed to establish the proxy lock and pi
2057 * state. top_waiter::requeue_state cannot be fixed up here
2058 * because the waiter is not enqueued on the rtmutex
2059 * yet. This is handled at the callsite depending on the
2060 * result of rt_mutex_start_proxy_lock() which is
2061 * guaranteed to be reached with this function returning 0.
2068 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
2069 * @uaddr1: source futex user address
2070 * @flags: futex flags (FLAGS_SHARED, etc.)
2071 * @uaddr2: target futex user address
2072 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
2073 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
2074 * @cmpval: @uaddr1 expected value (or %NULL)
2075 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
2076 * pi futex (pi to pi requeue is not supported)
2078 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
2079 * uaddr2 atomically on behalf of the top waiter.
2082 * - >=0 - on success, the number of tasks requeued or woken;
2085 static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
2086 u32 __user *uaddr2, int nr_wake, int nr_requeue,
2087 u32 *cmpval, int requeue_pi)
2089 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
2090 int task_count = 0, ret;
2091 struct futex_pi_state *pi_state = NULL;
2092 struct futex_hash_bucket *hb1, *hb2;
2093 struct futex_q *this, *next;
2094 DEFINE_WAKE_Q(wake_q);
2096 if (nr_wake < 0 || nr_requeue < 0)
2100 * When PI not supported: return -ENOSYS if requeue_pi is true,
2101 * consequently the compiler knows requeue_pi is always false past
2102 * this point which will optimize away all the conditional code
2105 if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
2110 * Requeue PI only works on two distinct uaddrs. This
2111 * check is only valid for private futexes. See below.
2113 if (uaddr1 == uaddr2)
2117 * futex_requeue() allows the caller to define the number
2118 * of waiters to wake up via the @nr_wake argument. With
2119 * REQUEUE_PI, waking up more than one waiter is creating
2120 * more problems than it solves. Waking up a waiter makes
2121 * only sense if the PI futex @uaddr2 is uncontended as
2122 * this allows the requeue code to acquire the futex
2123 * @uaddr2 before waking the waiter. The waiter can then
2124 * return to user space without further action. A secondary
2125 * wakeup would just make the futex_wait_requeue_pi()
2126 * handling more complex, because that code would have to
2127 * look up pi_state and do more or less all the handling
2128 * which the requeue code has to do for the to be requeued
2129 * waiters. So restrict the number of waiters to wake to
2130 * one, and only wake it up when the PI futex is
2131 * uncontended. Otherwise requeue it and let the unlock of
2132 * the PI futex handle the wakeup.
2134 * All REQUEUE_PI users, e.g. pthread_cond_signal() and
2135 * pthread_cond_broadcast() must use nr_wake=1.
2141 * requeue_pi requires a pi_state, try to allocate it now
2142 * without any locks in case it fails.
2144 if (refill_pi_state_cache())
2149 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
2150 if (unlikely(ret != 0))
2152 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
2153 requeue_pi ? FUTEX_WRITE : FUTEX_READ);
2154 if (unlikely(ret != 0))
2158 * The check above which compares uaddrs is not sufficient for
2159 * shared futexes. We need to compare the keys:
2161 if (requeue_pi && match_futex(&key1, &key2))
2164 hb1 = hash_futex(&key1);
2165 hb2 = hash_futex(&key2);
2168 hb_waiters_inc(hb2);
2169 double_lock_hb(hb1, hb2);
2171 if (likely(cmpval != NULL)) {
2174 ret = get_futex_value_locked(&curval, uaddr1);
2176 if (unlikely(ret)) {
2177 double_unlock_hb(hb1, hb2);
2178 hb_waiters_dec(hb2);
2180 ret = get_user(curval, uaddr1);
2184 if (!(flags & FLAGS_SHARED))
2189 if (curval != *cmpval) {
2196 struct task_struct *exiting = NULL;
2199 * Attempt to acquire uaddr2 and wake the top waiter. If we
2200 * intend to requeue waiters, force setting the FUTEX_WAITERS
2201 * bit. We force this here where we are able to easily handle
2202 * faults rather in the requeue loop below.
2204 * Updates topwaiter::requeue_state if a top waiter exists.
2206 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
2208 &exiting, nr_requeue);
2211 * At this point the top_waiter has either taken uaddr2 or is
2212 * waiting on it. If the former, then the pi_state will not
2213 * exist yet, look it up one more time to ensure we have a
2214 * reference to it. If the lock was taken, @ret contains the
2215 * VPID of the top waiter task.
2216 * If the lock was not taken, we have pi_state and an initial
2217 * refcount on it. In case of an error we have nothing.
2219 * The top waiter's requeue_state is up to date:
2221 * - If the lock was acquired atomically (ret > 0), then
2222 * the state is Q_REQUEUE_PI_LOCKED.
2224 * - If the trylock failed with an error (ret < 0) then
2225 * the state is either Q_REQUEUE_PI_NONE, i.e. "nothing
2226 * happened", or Q_REQUEUE_PI_IGNORE when there was an
2227 * interleaved early wakeup.
2229 * - If the trylock did not succeed (ret == 0) then the
2230 * state is either Q_REQUEUE_PI_IN_PROGRESS or
2231 * Q_REQUEUE_PI_WAIT if an early wakeup interleaved.
2232 * This will be cleaned up in the loop below, which
2233 * cannot fail because futex_proxy_trylock_atomic() did
2234 * the same sanity checks for requeue_pi as the loop
2241 * If futex_proxy_trylock_atomic() acquired the
2242 * user space futex, then the user space value
2243 * @uaddr2 has been set to the @hb1's top waiter
2244 * task VPID. This task is guaranteed to be alive
2245 * and cannot be exiting because it is either
2246 * sleeping or blocked on @hb2 lock.
2248 * The @uaddr2 futex cannot have waiters either as
2249 * otherwise futex_proxy_trylock_atomic() would not
2252 * In order to requeue waiters to @hb2, pi state is
2253 * required. Hand in the VPID value (@ret) and
2254 * allocate PI state with an initial refcount on
2257 ret = attach_to_pi_owner(uaddr2, ret, &key2, &pi_state,
2264 /* We hold a reference on the pi state. */
2268 * If the above failed, then pi_state is NULL and
2269 * waiter::requeue_state is correct.
2272 double_unlock_hb(hb1, hb2);
2273 hb_waiters_dec(hb2);
2274 ret = fault_in_user_writeable(uaddr2);
2281 * Two reasons for this:
2282 * - EBUSY: Owner is exiting and we just wait for the
2284 * - EAGAIN: The user space value changed.
2286 double_unlock_hb(hb1, hb2);
2287 hb_waiters_dec(hb2);
2289 * Handle the case where the owner is in the middle of
2290 * exiting. Wait for the exit to complete otherwise
2291 * this task might loop forever, aka. live lock.
2293 wait_for_owner_exiting(ret, exiting);
2301 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
2302 if (task_count - nr_wake >= nr_requeue)
2305 if (!match_futex(&this->key, &key1))
2309 * FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI should always
2310 * be paired with each other and no other futex ops.
2312 * We should never be requeueing a futex_q with a pi_state,
2313 * which is awaiting a futex_unlock_pi().
2315 if ((requeue_pi && !this->rt_waiter) ||
2316 (!requeue_pi && this->rt_waiter) ||
2322 /* Plain futexes just wake or requeue and are done */
2324 if (++task_count <= nr_wake)
2325 mark_wake_futex(&wake_q, this);
2327 requeue_futex(this, hb1, hb2, &key2);
2331 /* Ensure we requeue to the expected futex for requeue_pi. */
2332 if (!match_futex(this->requeue_pi_key, &key2)) {
2338 * Requeue nr_requeue waiters and possibly one more in the case
2339 * of requeue_pi if we couldn't acquire the lock atomically.
2341 * Prepare the waiter to take the rt_mutex. Take a refcount
2342 * on the pi_state and store the pointer in the futex_q
2343 * object of the waiter.
2345 get_pi_state(pi_state);
2347 /* Don't requeue when the waiter is already on the way out. */
2348 if (!futex_requeue_pi_prepare(this, pi_state)) {
2350 * Early woken waiter signaled that it is on the
2351 * way out. Drop the pi_state reference and try the
2352 * next waiter. @this->pi_state is still NULL.
2354 put_pi_state(pi_state);
2358 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
2364 * We got the lock. We do neither drop the refcount
2365 * on pi_state nor clear this->pi_state because the
2366 * waiter needs the pi_state for cleaning up the
2367 * user space value. It will drop the refcount
2368 * after doing so. this::requeue_state is updated
2369 * in the wakeup as well.
2371 requeue_pi_wake_futex(this, &key2, hb2);
2374 /* Waiter is queued, move it to hb2 */
2375 requeue_futex(this, hb1, hb2, &key2);
2376 futex_requeue_pi_complete(this, 0);
2380 * rt_mutex_start_proxy_lock() detected a potential
2381 * deadlock when we tried to queue that waiter.
2382 * Drop the pi_state reference which we took above
2383 * and remove the pointer to the state from the
2384 * waiters futex_q object.
2386 this->pi_state = NULL;
2387 put_pi_state(pi_state);
2388 futex_requeue_pi_complete(this, ret);
2390 * We stop queueing more waiters and let user space
2391 * deal with the mess.
2398 * We took an extra initial reference to the pi_state either in
2399 * futex_proxy_trylock_atomic() or in attach_to_pi_owner(). We need
2400 * to drop it here again.
2402 put_pi_state(pi_state);
2405 double_unlock_hb(hb1, hb2);
2407 hb_waiters_dec(hb2);
2408 return ret ? ret : task_count;
2411 /* The key must be already stored in q->key. */
2412 static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
2413 __acquires(&hb->lock)
2415 struct futex_hash_bucket *hb;
2417 hb = hash_futex(&q->key);
2420 * Increment the counter before taking the lock so that
2421 * a potential waker won't miss a to-be-slept task that is
2422 * waiting for the spinlock. This is safe as all queue_lock()
2423 * users end up calling queue_me(). Similarly, for housekeeping,
2424 * decrement the counter at queue_unlock() when some error has
2425 * occurred and we don't end up adding the task to the list.
2427 hb_waiters_inc(hb); /* implies smp_mb(); (A) */
2429 q->lock_ptr = &hb->lock;
2431 spin_lock(&hb->lock);
2436 queue_unlock(struct futex_hash_bucket *hb)
2437 __releases(&hb->lock)
2439 spin_unlock(&hb->lock);
2443 static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2448 * The priority used to register this element is
2449 * - either the real thread-priority for the real-time threads
2450 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2451 * - or MAX_RT_PRIO for non-RT threads.
2452 * Thus, all RT-threads are woken first in priority order, and
2453 * the others are woken last, in FIFO order.
2455 prio = min(current->normal_prio, MAX_RT_PRIO);
2457 plist_node_init(&q->list, prio);
2458 plist_add(&q->list, &hb->chain);
2463 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2464 * @q: The futex_q to enqueue
2465 * @hb: The destination hash bucket
2467 * The hb->lock must be held by the caller, and is released here. A call to
2468 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2469 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2470 * or nothing if the unqueue is done as part of the wake process and the unqueue
2471 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2474 static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2475 __releases(&hb->lock)
2478 spin_unlock(&hb->lock);
2482 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2483 * @q: The futex_q to unqueue
2485 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2486 * be paired with exactly one earlier call to queue_me().
2489 * - 1 - if the futex_q was still queued (and we removed unqueued it);
2490 * - 0 - if the futex_q was already removed by the waking thread
2492 static int unqueue_me(struct futex_q *q)
2494 spinlock_t *lock_ptr;
2497 /* In the common case we don't take the spinlock, which is nice. */
2500 * q->lock_ptr can change between this read and the following spin_lock.
2501 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2502 * optimizing lock_ptr out of the logic below.
2504 lock_ptr = READ_ONCE(q->lock_ptr);
2505 if (lock_ptr != NULL) {
2506 spin_lock(lock_ptr);
2508 * q->lock_ptr can change between reading it and
2509 * spin_lock(), causing us to take the wrong lock. This
2510 * corrects the race condition.
2512 * Reasoning goes like this: if we have the wrong lock,
2513 * q->lock_ptr must have changed (maybe several times)
2514 * between reading it and the spin_lock(). It can
2515 * change again after the spin_lock() but only if it was
2516 * already changed before the spin_lock(). It cannot,
2517 * however, change back to the original value. Therefore
2518 * we can detect whether we acquired the correct lock.
2520 if (unlikely(lock_ptr != q->lock_ptr)) {
2521 spin_unlock(lock_ptr);
2526 BUG_ON(q->pi_state);
2528 spin_unlock(lock_ptr);
2536 * PI futexes can not be requeued and must remove themselves from the
2537 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held.
2539 static void unqueue_me_pi(struct futex_q *q)
2543 BUG_ON(!q->pi_state);
2544 put_pi_state(q->pi_state);
2548 static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2549 struct task_struct *argowner)
2551 struct futex_pi_state *pi_state = q->pi_state;
2552 struct task_struct *oldowner, *newowner;
2553 u32 uval, curval, newval, newtid;
2556 oldowner = pi_state->owner;
2559 * We are here because either:
2561 * - we stole the lock and pi_state->owner needs updating to reflect
2562 * that (@argowner == current),
2566 * - someone stole our lock and we need to fix things to point to the
2567 * new owner (@argowner == NULL).
2569 * Either way, we have to replace the TID in the user space variable.
2570 * This must be atomic as we have to preserve the owner died bit here.
2572 * Note: We write the user space value _before_ changing the pi_state
2573 * because we can fault here. Imagine swapped out pages or a fork
2574 * that marked all the anonymous memory readonly for cow.
2576 * Modifying pi_state _before_ the user space value would leave the
2577 * pi_state in an inconsistent state when we fault here, because we
2578 * need to drop the locks to handle the fault. This might be observed
2579 * in the PID checks when attaching to PI state .
2583 if (oldowner != current) {
2585 * We raced against a concurrent self; things are
2586 * already fixed up. Nothing to do.
2591 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
2592 /* We got the lock. pi_state is correct. Tell caller. */
2597 * The trylock just failed, so either there is an owner or
2598 * there is a higher priority waiter than this one.
2600 newowner = rt_mutex_owner(&pi_state->pi_mutex);
2602 * If the higher priority waiter has not yet taken over the
2603 * rtmutex then newowner is NULL. We can't return here with
2604 * that state because it's inconsistent vs. the user space
2605 * state. So drop the locks and try again. It's a valid
2606 * situation and not any different from the other retry
2609 if (unlikely(!newowner)) {
2614 WARN_ON_ONCE(argowner != current);
2615 if (oldowner == current) {
2617 * We raced against a concurrent self; things are
2618 * already fixed up. Nothing to do.
2622 newowner = argowner;
2625 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
2627 if (!pi_state->owner)
2628 newtid |= FUTEX_OWNER_DIED;
2630 err = get_futex_value_locked(&uval, uaddr);
2635 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2637 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
2647 * We fixed up user space. Now we need to fix the pi_state
2650 pi_state_update_owner(pi_state, newowner);
2652 return argowner == current;
2655 * In order to reschedule or handle a page fault, we need to drop the
2656 * locks here. In the case of a fault, this gives the other task
2657 * (either the highest priority waiter itself or the task which stole
2658 * the rtmutex) the chance to try the fixup of the pi_state. So once we
2659 * are back from handling the fault we need to check the pi_state after
2660 * reacquiring the locks and before trying to do another fixup. When
2661 * the fixup has been done already we simply return.
2663 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2664 * drop hb->lock since the caller owns the hb -> futex_q relation.
2665 * Dropping the pi_mutex->wait_lock requires the state revalidate.
2668 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2669 spin_unlock(q->lock_ptr);
2673 err = fault_in_user_writeable(uaddr);
2686 spin_lock(q->lock_ptr);
2687 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2690 * Check if someone else fixed it for us:
2692 if (pi_state->owner != oldowner)
2693 return argowner == current;
2695 /* Retry if err was -EAGAIN or the fault in succeeded */
2700 * fault_in_user_writeable() failed so user state is immutable. At
2701 * best we can make the kernel state consistent but user state will
2702 * be most likely hosed and any subsequent unlock operation will be
2703 * rejected due to PI futex rule [10].
2705 * Ensure that the rtmutex owner is also the pi_state owner despite
2706 * the user space value claiming something different. There is no
2707 * point in unlocking the rtmutex if current is the owner as it
2708 * would need to wait until the next waiter has taken the rtmutex
2709 * to guarantee consistent state. Keep it simple. Userspace asked
2710 * for this wreckaged state.
2712 * The rtmutex has an owner - either current or some other
2713 * task. See the EAGAIN loop above.
2715 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
2720 static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2721 struct task_struct *argowner)
2723 struct futex_pi_state *pi_state = q->pi_state;
2726 lockdep_assert_held(q->lock_ptr);
2728 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2729 ret = __fixup_pi_state_owner(uaddr, q, argowner);
2730 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2734 static long futex_wait_restart(struct restart_block *restart);
2737 * fixup_owner() - Post lock pi_state and corner case management
2738 * @uaddr: user address of the futex
2739 * @q: futex_q (contains pi_state and access to the rt_mutex)
2740 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2742 * After attempting to lock an rt_mutex, this function is called to cleanup
2743 * the pi_state owner as well as handle race conditions that may allow us to
2744 * acquire the lock. Must be called with the hb lock held.
2747 * - 1 - success, lock taken;
2748 * - 0 - success, lock not taken;
2749 * - <0 - on error (-EFAULT)
2751 static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
2755 * Got the lock. We might not be the anticipated owner if we
2756 * did a lock-steal - fix up the PI-state in that case:
2758 * Speculative pi_state->owner read (we don't hold wait_lock);
2759 * since we own the lock pi_state->owner == current is the
2760 * stable state, anything else needs more attention.
2762 if (q->pi_state->owner != current)
2763 return fixup_pi_state_owner(uaddr, q, current);
2768 * If we didn't get the lock; check if anybody stole it from us. In
2769 * that case, we need to fix up the uval to point to them instead of
2770 * us, otherwise bad things happen. [10]
2772 * Another speculative read; pi_state->owner == current is unstable
2773 * but needs our attention.
2775 if (q->pi_state->owner == current)
2776 return fixup_pi_state_owner(uaddr, q, NULL);
2779 * Paranoia check. If we did not take the lock, then we should not be
2780 * the owner of the rt_mutex. Warn and establish consistent state.
2782 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
2783 return fixup_pi_state_owner(uaddr, q, current);
2789 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2790 * @hb: the futex hash bucket, must be locked by the caller
2791 * @q: the futex_q to queue up on
2792 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
2794 static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
2795 struct hrtimer_sleeper *timeout)
2798 * The task state is guaranteed to be set before another task can
2799 * wake it. set_current_state() is implemented using smp_store_mb() and
2800 * queue_me() calls spin_unlock() upon completion, both serializing
2801 * access to the hash list and forcing another memory barrier.
2803 set_current_state(TASK_INTERRUPTIBLE);
2808 hrtimer_sleeper_start_expires(timeout, HRTIMER_MODE_ABS);
2811 * If we have been removed from the hash list, then another task
2812 * has tried to wake us, and we can skip the call to schedule().
2814 if (likely(!plist_node_empty(&q->list))) {
2816 * If the timer has already expired, current will already be
2817 * flagged for rescheduling. Only call schedule if there
2818 * is no timeout, or if it has yet to expire.
2820 if (!timeout || timeout->task)
2821 freezable_schedule();
2823 __set_current_state(TASK_RUNNING);
2827 * futex_wait_setup() - Prepare to wait on a futex
2828 * @uaddr: the futex userspace address
2829 * @val: the expected value
2830 * @flags: futex flags (FLAGS_SHARED, etc.)
2831 * @q: the associated futex_q
2832 * @hb: storage for hash_bucket pointer to be returned to caller
2834 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2835 * compare it with the expected value. Handle atomic faults internally.
2836 * Return with the hb lock held on success, and unlocked on failure.
2839 * - 0 - uaddr contains val and hb has been locked;
2840 * - <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
2842 static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
2843 struct futex_q *q, struct futex_hash_bucket **hb)
2849 * Access the page AFTER the hash-bucket is locked.
2850 * Order is important:
2852 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2853 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2855 * The basic logical guarantee of a futex is that it blocks ONLY
2856 * if cond(var) is known to be true at the time of blocking, for
2857 * any cond. If we locked the hash-bucket after testing *uaddr, that
2858 * would open a race condition where we could block indefinitely with
2859 * cond(var) false, which would violate the guarantee.
2861 * On the other hand, we insert q and release the hash-bucket only
2862 * after testing *uaddr. This guarantees that futex_wait() will NOT
2863 * absorb a wakeup if *uaddr does not match the desired values
2864 * while the syscall executes.
2867 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, FUTEX_READ);
2868 if (unlikely(ret != 0))
2872 *hb = queue_lock(q);
2874 ret = get_futex_value_locked(&uval, uaddr);
2879 ret = get_user(uval, uaddr);
2883 if (!(flags & FLAGS_SHARED))
2897 static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2898 ktime_t *abs_time, u32 bitset)
2900 struct hrtimer_sleeper timeout, *to;
2901 struct restart_block *restart;
2902 struct futex_hash_bucket *hb;
2903 struct futex_q q = futex_q_init;
2910 to = futex_setup_timer(abs_time, &timeout, flags,
2911 current->timer_slack_ns);
2914 * Prepare to wait on uaddr. On success, it holds hb->lock and q
2917 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
2921 /* queue_me and wait for wakeup, timeout, or a signal. */
2922 futex_wait_queue_me(hb, &q, to);
2924 /* If we were woken (and unqueued), we succeeded, whatever. */
2926 if (!unqueue_me(&q))
2929 if (to && !to->task)
2933 * We expect signal_pending(current), but we might be the
2934 * victim of a spurious wakeup as well.
2936 if (!signal_pending(current))
2943 restart = ¤t->restart_block;
2944 restart->futex.uaddr = uaddr;
2945 restart->futex.val = val;
2946 restart->futex.time = *abs_time;
2947 restart->futex.bitset = bitset;
2948 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
2950 ret = set_restart_fn(restart, futex_wait_restart);
2954 hrtimer_cancel(&to->timer);
2955 destroy_hrtimer_on_stack(&to->timer);
2961 static long futex_wait_restart(struct restart_block *restart)
2963 u32 __user *uaddr = restart->futex.uaddr;
2964 ktime_t t, *tp = NULL;
2966 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2967 t = restart->futex.time;
2970 restart->fn = do_no_restart_syscall;
2972 return (long)futex_wait(uaddr, restart->futex.flags,
2973 restart->futex.val, tp, restart->futex.bitset);
2978 * Userspace tried a 0 -> TID atomic transition of the futex value
2979 * and failed. The kernel side here does the whole locking operation:
2980 * if there are waiters then it will block as a consequence of relying
2981 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2982 * a 0 value of the futex too.).
2984 * Also serves as futex trylock_pi()'ing, and due semantics.
2986 static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
2987 ktime_t *time, int trylock)
2989 struct hrtimer_sleeper timeout, *to;
2990 struct task_struct *exiting = NULL;
2991 struct rt_mutex_waiter rt_waiter;
2992 struct futex_hash_bucket *hb;
2993 struct futex_q q = futex_q_init;
2996 if (!IS_ENABLED(CONFIG_FUTEX_PI))
2999 if (refill_pi_state_cache())
3002 to = futex_setup_timer(time, &timeout, flags, 0);
3005 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, FUTEX_WRITE);
3006 if (unlikely(ret != 0))
3010 hb = queue_lock(&q);
3012 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
3014 if (unlikely(ret)) {
3016 * Atomic work succeeded and we got the lock,
3017 * or failed. Either way, we do _not_ block.
3021 /* We got the lock. */
3023 goto out_unlock_put_key;
3029 * Two reasons for this:
3030 * - EBUSY: Task is exiting and we just wait for the
3032 * - EAGAIN: The user space value changed.
3036 * Handle the case where the owner is in the middle of
3037 * exiting. Wait for the exit to complete otherwise
3038 * this task might loop forever, aka. live lock.
3040 wait_for_owner_exiting(ret, exiting);
3044 goto out_unlock_put_key;
3048 WARN_ON(!q.pi_state);
3051 * Only actually queue now that the atomic ops are done:
3056 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
3057 /* Fixup the trylock return value: */
3058 ret = ret ? 0 : -EWOULDBLOCK;
3062 rt_mutex_init_waiter(&rt_waiter);
3065 * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
3066 * hold it while doing rt_mutex_start_proxy(), because then it will
3067 * include hb->lock in the blocking chain, even through we'll not in
3068 * fact hold it while blocking. This will lead it to report -EDEADLK
3069 * and BUG when futex_unlock_pi() interleaves with this.
3071 * Therefore acquire wait_lock while holding hb->lock, but drop the
3072 * latter before calling __rt_mutex_start_proxy_lock(). This
3073 * interleaves with futex_unlock_pi() -- which does a similar lock
3074 * handoff -- such that the latter can observe the futex_q::pi_state
3075 * before __rt_mutex_start_proxy_lock() is done.
3077 raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
3078 spin_unlock(q.lock_ptr);
3080 * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
3081 * such that futex_unlock_pi() is guaranteed to observe the waiter when
3082 * it sees the futex_q::pi_state.
3084 ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
3085 raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
3094 hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
3096 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
3099 spin_lock(q.lock_ptr);
3101 * If we failed to acquire the lock (deadlock/signal/timeout), we must
3102 * first acquire the hb->lock before removing the lock from the
3103 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
3106 * In particular; it is important that futex_unlock_pi() can not
3107 * observe this inconsistency.
3109 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
3114 * Fixup the pi_state owner and possibly acquire the lock if we
3117 res = fixup_owner(uaddr, &q, !ret);
3119 * If fixup_owner() returned an error, propagate that. If it acquired
3120 * the lock, clear our -ETIMEDOUT or -EINTR.
3123 ret = (res < 0) ? res : 0;
3126 spin_unlock(q.lock_ptr);
3134 hrtimer_cancel(&to->timer);
3135 destroy_hrtimer_on_stack(&to->timer);
3137 return ret != -EINTR ? ret : -ERESTARTNOINTR;
3142 ret = fault_in_user_writeable(uaddr);
3146 if (!(flags & FLAGS_SHARED))
3153 * Userspace attempted a TID -> 0 atomic transition, and failed.
3154 * This is the in-kernel slowpath: we look up the PI state (if any),
3155 * and do the rt-mutex unlock.
3157 static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
3159 u32 curval, uval, vpid = task_pid_vnr(current);
3160 union futex_key key = FUTEX_KEY_INIT;
3161 struct futex_hash_bucket *hb;
3162 struct futex_q *top_waiter;
3165 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3169 if (get_user(uval, uaddr))
3172 * We release only a lock we actually own:
3174 if ((uval & FUTEX_TID_MASK) != vpid)
3177 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_WRITE);
3181 hb = hash_futex(&key);
3182 spin_lock(&hb->lock);
3185 * Check waiters first. We do not trust user space values at
3186 * all and we at least want to know if user space fiddled
3187 * with the futex value instead of blindly unlocking.
3189 top_waiter = futex_top_waiter(hb, &key);
3191 struct futex_pi_state *pi_state = top_waiter->pi_state;
3198 * If current does not own the pi_state then the futex is
3199 * inconsistent and user space fiddled with the futex value.
3201 if (pi_state->owner != current)
3204 get_pi_state(pi_state);
3206 * By taking wait_lock while still holding hb->lock, we ensure
3207 * there is no point where we hold neither; and therefore
3208 * wake_futex_pi() must observe a state consistent with what we
3211 * In particular; this forces __rt_mutex_start_proxy() to
3212 * complete such that we're guaranteed to observe the
3213 * rt_waiter. Also see the WARN in wake_futex_pi().
3215 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
3216 spin_unlock(&hb->lock);
3218 /* drops pi_state->pi_mutex.wait_lock */
3219 ret = wake_futex_pi(uaddr, uval, pi_state);
3221 put_pi_state(pi_state);
3224 * Success, we're done! No tricky corner cases.
3229 * The atomic access to the futex value generated a
3230 * pagefault, so retry the user-access and the wakeup:
3235 * A unconditional UNLOCK_PI op raced against a waiter
3236 * setting the FUTEX_WAITERS bit. Try again.
3241 * wake_futex_pi has detected invalid state. Tell user
3248 * We have no kernel internal state, i.e. no waiters in the
3249 * kernel. Waiters which are about to queue themselves are stuck
3250 * on hb->lock. So we can safely ignore them. We do neither
3251 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3254 if ((ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))) {
3255 spin_unlock(&hb->lock);
3270 * If uval has changed, let user space handle it.
3272 ret = (curval == uval) ? 0 : -EAGAIN;
3275 spin_unlock(&hb->lock);
3284 ret = fault_in_user_writeable(uaddr);
3292 * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex
3293 * @hb: the hash_bucket futex_q was original enqueued on
3294 * @q: the futex_q woken while waiting to be requeued
3295 * @timeout: the timeout associated with the wait (NULL if none)
3297 * Determine the cause for the early wakeup.
3300 * -EWOULDBLOCK or -ETIMEDOUT or -ERESTARTNOINTR
3303 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
3305 struct hrtimer_sleeper *timeout)
3310 * With the hb lock held, we avoid races while we process the wakeup.
3311 * We only need to hold hb (and not hb2) to ensure atomicity as the
3312 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
3313 * It can't be requeued from uaddr2 to something else since we don't
3314 * support a PI aware source futex for requeue.
3316 WARN_ON_ONCE(&hb->lock != q->lock_ptr);
3319 * We were woken prior to requeue by a timeout or a signal.
3320 * Unqueue the futex_q and determine which it was.
3322 plist_del(&q->list, &hb->chain);
3325 /* Handle spurious wakeups gracefully */
3327 if (timeout && !timeout->task)
3329 else if (signal_pending(current))
3330 ret = -ERESTARTNOINTR;
3335 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
3336 * @uaddr: the futex we initially wait on (non-pi)
3337 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
3338 * the same type, no requeueing from private to shared, etc.
3339 * @val: the expected value of uaddr
3340 * @abs_time: absolute timeout
3341 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
3342 * @uaddr2: the pi futex we will take prior to returning to user-space
3344 * The caller will wait on uaddr and will be requeued by futex_requeue() to
3345 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
3346 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
3347 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
3348 * without one, the pi logic would not know which task to boost/deboost, if
3349 * there was a need to.
3351 * We call schedule in futex_wait_queue_me() when we enqueue and return there
3352 * via the following--
3353 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
3354 * 2) wakeup on uaddr2 after a requeue
3358 * If 3, cleanup and return -ERESTARTNOINTR.
3360 * If 2, we may then block on trying to take the rt_mutex and return via:
3361 * 5) successful lock
3364 * 8) other lock acquisition failure
3366 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
3368 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
3374 static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
3375 u32 val, ktime_t *abs_time, u32 bitset,
3378 struct hrtimer_sleeper timeout, *to;
3379 struct rt_mutex_waiter rt_waiter;
3380 struct futex_hash_bucket *hb;
3381 union futex_key key2 = FUTEX_KEY_INIT;
3382 struct futex_q q = futex_q_init;
3383 struct rt_mutex_base *pi_mutex;
3386 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3389 if (uaddr == uaddr2)
3395 to = futex_setup_timer(abs_time, &timeout, flags,
3396 current->timer_slack_ns);
3399 * The waiter is allocated on our stack, manipulated by the requeue
3400 * code while we sleep on uaddr.
3402 rt_mutex_init_waiter(&rt_waiter);
3404 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
3405 if (unlikely(ret != 0))
3409 q.rt_waiter = &rt_waiter;
3410 q.requeue_pi_key = &key2;
3413 * Prepare to wait on uaddr. On success, it holds hb->lock and q
3416 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
3421 * The check above which compares uaddrs is not sufficient for
3422 * shared futexes. We need to compare the keys:
3424 if (match_futex(&q.key, &key2)) {
3430 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
3431 futex_wait_queue_me(hb, &q, to);
3433 switch (futex_requeue_pi_wakeup_sync(&q)) {
3434 case Q_REQUEUE_PI_IGNORE:
3435 /* The waiter is still on uaddr1 */
3436 spin_lock(&hb->lock);
3437 ret = handle_early_requeue_pi_wakeup(hb, &q, to);
3438 spin_unlock(&hb->lock);
3441 case Q_REQUEUE_PI_LOCKED:
3442 /* The requeue acquired the lock */
3443 if (q.pi_state && (q.pi_state->owner != current)) {
3444 spin_lock(q.lock_ptr);
3445 ret = fixup_owner(uaddr2, &q, true);
3447 * Drop the reference to the pi state which the
3448 * requeue_pi() code acquired for us.
3450 put_pi_state(q.pi_state);
3451 spin_unlock(q.lock_ptr);
3453 * Adjust the return value. It's either -EFAULT or
3454 * success (1) but the caller expects 0 for success.
3456 ret = ret < 0 ? ret : 0;
3460 case Q_REQUEUE_PI_DONE:
3461 /* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
3462 pi_mutex = &q.pi_state->pi_mutex;
3463 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
3465 /* Current is not longer pi_blocked_on */
3466 spin_lock(q.lock_ptr);
3467 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
3470 debug_rt_mutex_free_waiter(&rt_waiter);
3472 * Fixup the pi_state owner and possibly acquire the lock if we
3475 res = fixup_owner(uaddr2, &q, !ret);
3477 * If fixup_owner() returned an error, propagate that. If it
3478 * acquired the lock, clear -ETIMEDOUT or -EINTR.
3481 ret = (res < 0) ? res : 0;
3484 spin_unlock(q.lock_ptr);
3486 if (ret == -EINTR) {
3488 * We've already been requeued, but cannot restart
3489 * by calling futex_lock_pi() directly. We could
3490 * restart this syscall, but it would detect that
3491 * the user space "val" changed and return
3492 * -EWOULDBLOCK. Save the overhead of the restart
3493 * and return -EWOULDBLOCK directly.
3504 hrtimer_cancel(&to->timer);
3505 destroy_hrtimer_on_stack(&to->timer);
3511 * Support for robust futexes: the kernel cleans up held futexes at
3514 * Implementation: user-space maintains a per-thread list of locks it
3515 * is holding. Upon do_exit(), the kernel carefully walks this list,
3516 * and marks all locks that are owned by this thread with the
3517 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
3518 * always manipulated with the lock held, so the list is private and
3519 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
3520 * field, to allow the kernel to clean up if the thread dies after
3521 * acquiring the lock, but just before it could have added itself to
3522 * the list. There can only be one such pending lock.
3526 * sys_set_robust_list() - Set the robust-futex list head of a task
3527 * @head: pointer to the list-head
3528 * @len: length of the list-head, as userspace expects
3530 SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
3533 if (!futex_cmpxchg_enabled)
3536 * The kernel knows only one size for now:
3538 if (unlikely(len != sizeof(*head)))
3541 current->robust_list = head;
3547 * sys_get_robust_list() - Get the robust-futex list head of a task
3548 * @pid: pid of the process [zero for current task]
3549 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
3550 * @len_ptr: pointer to a length field, the kernel fills in the header size
3552 SYSCALL_DEFINE3(get_robust_list, int, pid,
3553 struct robust_list_head __user * __user *, head_ptr,
3554 size_t __user *, len_ptr)
3556 struct robust_list_head __user *head;
3558 struct task_struct *p;
3560 if (!futex_cmpxchg_enabled)
3569 p = find_task_by_vpid(pid);
3575 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
3578 head = p->robust_list;
3581 if (put_user(sizeof(*head), len_ptr))
3583 return put_user(head, head_ptr);
3591 /* Constants for the pending_op argument of handle_futex_death */
3592 #define HANDLE_DEATH_PENDING true
3593 #define HANDLE_DEATH_LIST false
3596 * Process a futex-list entry, check whether it's owned by the
3597 * dying task, and do notification if so:
3599 static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
3600 bool pi, bool pending_op)
3602 u32 uval, nval, mval;
3605 /* Futex address must be 32bit aligned */
3606 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3610 if (get_user(uval, uaddr))
3614 * Special case for regular (non PI) futexes. The unlock path in
3615 * user space has two race scenarios:
3617 * 1. The unlock path releases the user space futex value and
3618 * before it can execute the futex() syscall to wake up
3619 * waiters it is killed.
3621 * 2. A woken up waiter is killed before it can acquire the
3622 * futex in user space.
3624 * In both cases the TID validation below prevents a wakeup of
3625 * potential waiters which can cause these waiters to block
3628 * In both cases the following conditions are met:
3630 * 1) task->robust_list->list_op_pending != NULL
3631 * @pending_op == true
3632 * 2) User space futex value == 0
3633 * 3) Regular futex: @pi == false
3635 * If these conditions are met, it is safe to attempt waking up a
3636 * potential waiter without touching the user space futex value and
3637 * trying to set the OWNER_DIED bit. The user space futex value is
3638 * uncontended and the rest of the user space mutex state is
3639 * consistent, so a woken waiter will just take over the
3640 * uncontended futex. Setting the OWNER_DIED bit would create
3641 * inconsistent state and malfunction of the user space owner died
3644 if (pending_op && !pi && !uval) {
3645 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3649 if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
3653 * Ok, this dying thread is truly holding a futex
3654 * of interest. Set the OWNER_DIED bit atomically
3655 * via cmpxchg, and if the value had FUTEX_WAITERS
3656 * set, wake up a waiter (if any). (We have to do a
3657 * futex_wake() even if OWNER_DIED is already set -
3658 * to handle the rare but possible case of recursive
3659 * thread-death.) The rest of the cleanup is done in
3662 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3665 * We are not holding a lock here, but we want to have
3666 * the pagefault_disable/enable() protection because
3667 * we want to handle the fault gracefully. If the
3668 * access fails we try to fault in the futex with R/W
3669 * verification via get_user_pages. get_user() above
3670 * does not guarantee R/W access. If that fails we
3671 * give up and leave the futex locked.
3673 if ((err = cmpxchg_futex_value_locked(&nval, uaddr, uval, mval))) {
3676 if (fault_in_user_writeable(uaddr))
3694 * Wake robust non-PI futexes here. The wakeup of
3695 * PI futexes happens in exit_pi_state():
3697 if (!pi && (uval & FUTEX_WAITERS))
3698 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3704 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3706 static inline int fetch_robust_entry(struct robust_list __user **entry,
3707 struct robust_list __user * __user *head,
3710 unsigned long uentry;
3712 if (get_user(uentry, (unsigned long __user *)head))
3715 *entry = (void __user *)(uentry & ~1UL);
3722 * Walk curr->robust_list (very carefully, it's a userspace list!)
3723 * and mark any locks found there dead, and notify any waiters.
3725 * We silently return on any sign of list-walking problem.
3727 static void exit_robust_list(struct task_struct *curr)
3729 struct robust_list_head __user *head = curr->robust_list;
3730 struct robust_list __user *entry, *next_entry, *pending;
3731 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3732 unsigned int next_pi;
3733 unsigned long futex_offset;
3736 if (!futex_cmpxchg_enabled)
3740 * Fetch the list head (which was registered earlier, via
3741 * sys_set_robust_list()):
3743 if (fetch_robust_entry(&entry, &head->list.next, &pi))
3746 * Fetch the relative futex offset:
3748 if (get_user(futex_offset, &head->futex_offset))
3751 * Fetch any possibly pending lock-add first, and handle it
3754 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
3757 next_entry = NULL; /* avoid warning with gcc */
3758 while (entry != &head->list) {
3760 * Fetch the next entry in the list before calling
3761 * handle_futex_death:
3763 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
3765 * A pending lock might already be on the list, so
3766 * don't process it twice:
3768 if (entry != pending) {
3769 if (handle_futex_death((void __user *)entry + futex_offset,
3770 curr, pi, HANDLE_DEATH_LIST))
3778 * Avoid excessively long or circular lists:
3787 handle_futex_death((void __user *)pending + futex_offset,
3788 curr, pip, HANDLE_DEATH_PENDING);
3792 static void futex_cleanup(struct task_struct *tsk)
3794 if (unlikely(tsk->robust_list)) {
3795 exit_robust_list(tsk);
3796 tsk->robust_list = NULL;
3799 #ifdef CONFIG_COMPAT
3800 if (unlikely(tsk->compat_robust_list)) {
3801 compat_exit_robust_list(tsk);
3802 tsk->compat_robust_list = NULL;
3806 if (unlikely(!list_empty(&tsk->pi_state_list)))
3807 exit_pi_state_list(tsk);
3811 * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
3812 * @tsk: task to set the state on
3814 * Set the futex exit state of the task lockless. The futex waiter code
3815 * observes that state when a task is exiting and loops until the task has
3816 * actually finished the futex cleanup. The worst case for this is that the
3817 * waiter runs through the wait loop until the state becomes visible.
3819 * This is called from the recursive fault handling path in do_exit().
3821 * This is best effort. Either the futex exit code has run already or
3822 * not. If the OWNER_DIED bit has been set on the futex then the waiter can
3823 * take it over. If not, the problem is pushed back to user space. If the
3824 * futex exit code did not run yet, then an already queued waiter might
3825 * block forever, but there is nothing which can be done about that.
3827 void futex_exit_recursive(struct task_struct *tsk)
3829 /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
3830 if (tsk->futex_state == FUTEX_STATE_EXITING)
3831 mutex_unlock(&tsk->futex_exit_mutex);
3832 tsk->futex_state = FUTEX_STATE_DEAD;
3835 static void futex_cleanup_begin(struct task_struct *tsk)
3838 * Prevent various race issues against a concurrent incoming waiter
3839 * including live locks by forcing the waiter to block on
3840 * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
3841 * attach_to_pi_owner().
3843 mutex_lock(&tsk->futex_exit_mutex);
3846 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
3848 * This ensures that all subsequent checks of tsk->futex_state in
3849 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
3850 * tsk->pi_lock held.
3852 * It guarantees also that a pi_state which was queued right before
3853 * the state change under tsk->pi_lock by a concurrent waiter must
3854 * be observed in exit_pi_state_list().
3856 raw_spin_lock_irq(&tsk->pi_lock);
3857 tsk->futex_state = FUTEX_STATE_EXITING;
3858 raw_spin_unlock_irq(&tsk->pi_lock);
3861 static void futex_cleanup_end(struct task_struct *tsk, int state)
3864 * Lockless store. The only side effect is that an observer might
3865 * take another loop until it becomes visible.
3867 tsk->futex_state = state;
3869 * Drop the exit protection. This unblocks waiters which observed
3870 * FUTEX_STATE_EXITING to reevaluate the state.
3872 mutex_unlock(&tsk->futex_exit_mutex);
3875 void futex_exec_release(struct task_struct *tsk)
3878 * The state handling is done for consistency, but in the case of
3879 * exec() there is no way to prevent further damage as the PID stays
3880 * the same. But for the unlikely and arguably buggy case that a
3881 * futex is held on exec(), this provides at least as much state
3882 * consistency protection which is possible.
3884 futex_cleanup_begin(tsk);
3887 * Reset the state to FUTEX_STATE_OK. The task is alive and about
3888 * exec a new binary.
3890 futex_cleanup_end(tsk, FUTEX_STATE_OK);
3893 void futex_exit_release(struct task_struct *tsk)
3895 futex_cleanup_begin(tsk);
3897 futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
3900 long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
3901 u32 __user *uaddr2, u32 val2, u32 val3)
3903 int cmd = op & FUTEX_CMD_MASK;
3904 unsigned int flags = 0;
3906 if (!(op & FUTEX_PRIVATE_FLAG))
3907 flags |= FLAGS_SHARED;
3909 if (op & FUTEX_CLOCK_REALTIME) {
3910 flags |= FLAGS_CLOCKRT;
3911 if (cmd != FUTEX_WAIT_BITSET && cmd != FUTEX_WAIT_REQUEUE_PI &&
3912 cmd != FUTEX_LOCK_PI2)
3918 case FUTEX_LOCK_PI2:
3919 case FUTEX_UNLOCK_PI:
3920 case FUTEX_TRYLOCK_PI:
3921 case FUTEX_WAIT_REQUEUE_PI:
3922 case FUTEX_CMP_REQUEUE_PI:
3923 if (!futex_cmpxchg_enabled)
3929 val3 = FUTEX_BITSET_MATCH_ANY;
3931 case FUTEX_WAIT_BITSET:
3932 return futex_wait(uaddr, flags, val, timeout, val3);
3934 val3 = FUTEX_BITSET_MATCH_ANY;
3936 case FUTEX_WAKE_BITSET:
3937 return futex_wake(uaddr, flags, val, val3);
3939 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
3940 case FUTEX_CMP_REQUEUE:
3941 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
3943 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
3945 flags |= FLAGS_CLOCKRT;
3947 case FUTEX_LOCK_PI2:
3948 return futex_lock_pi(uaddr, flags, timeout, 0);
3949 case FUTEX_UNLOCK_PI:
3950 return futex_unlock_pi(uaddr, flags);
3951 case FUTEX_TRYLOCK_PI:
3952 return futex_lock_pi(uaddr, flags, NULL, 1);
3953 case FUTEX_WAIT_REQUEUE_PI:
3954 val3 = FUTEX_BITSET_MATCH_ANY;
3955 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3957 case FUTEX_CMP_REQUEUE_PI:
3958 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
3963 static __always_inline bool futex_cmd_has_timeout(u32 cmd)
3968 case FUTEX_LOCK_PI2:
3969 case FUTEX_WAIT_BITSET:
3970 case FUTEX_WAIT_REQUEUE_PI:
3976 static __always_inline int
3977 futex_init_timeout(u32 cmd, u32 op, struct timespec64 *ts, ktime_t *t)
3979 if (!timespec64_valid(ts))
3982 *t = timespec64_to_ktime(*ts);
3983 if (cmd == FUTEX_WAIT)
3984 *t = ktime_add_safe(ktime_get(), *t);
3985 else if (cmd != FUTEX_LOCK_PI && !(op & FUTEX_CLOCK_REALTIME))
3986 *t = timens_ktime_to_host(CLOCK_MONOTONIC, *t);
3990 SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
3991 const struct __kernel_timespec __user *, utime,
3992 u32 __user *, uaddr2, u32, val3)
3994 int ret, cmd = op & FUTEX_CMD_MASK;
3995 ktime_t t, *tp = NULL;
3996 struct timespec64 ts;
3998 if (utime && futex_cmd_has_timeout(cmd)) {
3999 if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
4001 if (get_timespec64(&ts, utime))
4003 ret = futex_init_timeout(cmd, op, &ts, &t);
4009 return do_futex(uaddr, op, val, tp, uaddr2, (unsigned long)utime, val3);
4012 #ifdef CONFIG_COMPAT
4014 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
4017 compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
4018 compat_uptr_t __user *head, unsigned int *pi)
4020 if (get_user(*uentry, head))
4023 *entry = compat_ptr((*uentry) & ~1);
4024 *pi = (unsigned int)(*uentry) & 1;
4029 static void __user *futex_uaddr(struct robust_list __user *entry,
4030 compat_long_t futex_offset)
4032 compat_uptr_t base = ptr_to_compat(entry);
4033 void __user *uaddr = compat_ptr(base + futex_offset);
4039 * Walk curr->robust_list (very carefully, it's a userspace list!)
4040 * and mark any locks found there dead, and notify any waiters.
4042 * We silently return on any sign of list-walking problem.
4044 static void compat_exit_robust_list(struct task_struct *curr)
4046 struct compat_robust_list_head __user *head = curr->compat_robust_list;
4047 struct robust_list __user *entry, *next_entry, *pending;
4048 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
4049 unsigned int next_pi;
4050 compat_uptr_t uentry, next_uentry, upending;
4051 compat_long_t futex_offset;
4054 if (!futex_cmpxchg_enabled)
4058 * Fetch the list head (which was registered earlier, via
4059 * sys_set_robust_list()):
4061 if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
4064 * Fetch the relative futex offset:
4066 if (get_user(futex_offset, &head->futex_offset))
4069 * Fetch any possibly pending lock-add first, and handle it
4072 if (compat_fetch_robust_entry(&upending, &pending,
4073 &head->list_op_pending, &pip))
4076 next_entry = NULL; /* avoid warning with gcc */
4077 while (entry != (struct robust_list __user *) &head->list) {
4079 * Fetch the next entry in the list before calling
4080 * handle_futex_death:
4082 rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
4083 (compat_uptr_t __user *)&entry->next, &next_pi);
4085 * A pending lock might already be on the list, so
4086 * dont process it twice:
4088 if (entry != pending) {
4089 void __user *uaddr = futex_uaddr(entry, futex_offset);
4091 if (handle_futex_death(uaddr, curr, pi,
4097 uentry = next_uentry;
4101 * Avoid excessively long or circular lists:
4109 void __user *uaddr = futex_uaddr(pending, futex_offset);
4111 handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
4115 COMPAT_SYSCALL_DEFINE2(set_robust_list,
4116 struct compat_robust_list_head __user *, head,
4119 if (!futex_cmpxchg_enabled)
4122 if (unlikely(len != sizeof(*head)))
4125 current->compat_robust_list = head;
4130 COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
4131 compat_uptr_t __user *, head_ptr,
4132 compat_size_t __user *, len_ptr)
4134 struct compat_robust_list_head __user *head;
4136 struct task_struct *p;
4138 if (!futex_cmpxchg_enabled)
4147 p = find_task_by_vpid(pid);
4153 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
4156 head = p->compat_robust_list;
4159 if (put_user(sizeof(*head), len_ptr))
4161 return put_user(ptr_to_compat(head), head_ptr);
4168 #endif /* CONFIG_COMPAT */
4170 #ifdef CONFIG_COMPAT_32BIT_TIME
4171 SYSCALL_DEFINE6(futex_time32, u32 __user *, uaddr, int, op, u32, val,
4172 const struct old_timespec32 __user *, utime, u32 __user *, uaddr2,
4175 int ret, cmd = op & FUTEX_CMD_MASK;
4176 ktime_t t, *tp = NULL;
4177 struct timespec64 ts;
4179 if (utime && futex_cmd_has_timeout(cmd)) {
4180 if (get_old_timespec32(&ts, utime))
4182 ret = futex_init_timeout(cmd, op, &ts, &t);
4188 return do_futex(uaddr, op, val, tp, uaddr2, (unsigned long)utime, val3);
4190 #endif /* CONFIG_COMPAT_32BIT_TIME */
4192 static void __init futex_detect_cmpxchg(void)
4194 #ifndef CONFIG_HAVE_FUTEX_CMPXCHG
4198 * This will fail and we want it. Some arch implementations do
4199 * runtime detection of the futex_atomic_cmpxchg_inatomic()
4200 * functionality. We want to know that before we call in any
4201 * of the complex code paths. Also we want to prevent
4202 * registration of robust lists in that case. NULL is
4203 * guaranteed to fault and we get -EFAULT on functional
4204 * implementation, the non-functional ones will return
4207 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
4208 futex_cmpxchg_enabled = 1;
4212 static int __init futex_init(void)
4214 unsigned int futex_shift;
4217 #if CONFIG_BASE_SMALL
4218 futex_hashsize = 16;
4220 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
4223 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
4225 futex_hashsize < 256 ? HASH_SMALL : 0,
4227 futex_hashsize, futex_hashsize);
4228 futex_hashsize = 1UL << futex_shift;
4230 futex_detect_cmpxchg();
4232 for (i = 0; i < futex_hashsize; i++) {
4233 atomic_set(&futex_queues[i].waiters, 0);
4234 plist_head_init(&futex_queues[i].chain);
4235 spin_lock_init(&futex_queues[i].lock);
4240 core_initcall(futex_init);