blob: 69d98929f2f53364039369026c8248b2d7439ed9 [file] [log] [blame]
Thomas Gleixner1a59d1b82019-05-27 08:55:05 +02001// SPDX-License-Identifier: GPL-2.0-or-later
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
3 * Fast Userspace Mutexes (which I call "Futexes!").
4 * (C) Rusty Russell, IBM 2002
5 *
6 * Generalized futexes, futex requeueing, misc fixes by Ingo Molnar
7 * (C) Copyright 2003 Red Hat Inc, All Rights Reserved
8 *
9 * Removed page pinning, fix privately mapped COW pages and other cleanups
10 * (C) Copyright 2003, 2004 Jamie Lokier
11 *
Ingo Molnar0771dfe2006-03-27 01:16:22 -080012 * 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.
15 *
Ingo Molnarc87e2832006-06-27 02:54:58 -070016 * 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>
19 *
Eric Dumazet34f01cc2007-05-09 02:35:04 -070020 * PRIVATE futexes by Eric Dumazet
21 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
22 *
Darren Hart52400ba2009-04-03 13:40:49 -070023 * 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.
26 *
Linus Torvalds1da177e2005-04-16 15:20:36 -070027 * 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.
30 *
31 * "The futexes are also cursed."
32 * "But they come in a choice of three flavours!"
Linus Torvalds1da177e2005-04-16 15:20:36 -070033 */
Arnd Bergmann04e77122018-04-17 16:31:07 +020034#include <linux/compat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070035#include <linux/jhash.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070036#include <linux/pagemap.h>
Colin Cross88c80042013-05-01 18:35:05 -070037#include <linux/freezer.h>
Mike Rapoport57c8a662018-10-30 15:09:49 -070038#include <linux/memblock.h>
Davidlohr Buesoab51fba2015-06-29 23:26:02 -070039#include <linux/fault-inject.h>
Peter Zijlstraaf8cc962021-09-23 14:10:51 -030040#include <linux/slab.h>
Pavel Emelyanovb4888932007-10-18 23:40:14 -070041
Peter Zijlstraaf8cc962021-09-23 14:10:51 -030042#include "futex.h"
Peter Zijlstra77e52ae2021-09-23 14:10:50 -030043#include "../locking/rtmutex_common.h"
Ingo Molnarc87e2832006-06-27 02:54:58 -070044
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080045/*
Davidlohr Buesod7e8af12014-04-09 11:55:07 -070046 * READ this before attempting to hack on futexes!
47 *
48 * Basic futex operation and ordering guarantees
49 * =============================================
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080050 *
51 * The waiter reads the futex value in user space and calls
52 * futex_wait(). This function computes the hash bucket and acquires
53 * the hash bucket lock. After that it reads the futex user space value
Davidlohr Buesob0c29f72014-01-12 15:31:25 -080054 * again and verifies that the data has not changed. If it has not changed
55 * it enqueues itself into the hash bucket, releases the hash bucket lock
56 * and schedules.
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080057 *
58 * The waker side modifies the user space value of the futex and calls
Davidlohr Buesob0c29f72014-01-12 15:31:25 -080059 * futex_wake(). This function computes the hash bucket and acquires the
60 * hash bucket lock. Then it looks for waiters on that futex in the hash
61 * bucket and wakes them.
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080062 *
Davidlohr Buesob0c29f72014-01-12 15:31:25 -080063 * In futex wake up scenarios where no tasks are blocked on a futex, taking
64 * the hb spinlock can be avoided and simply return. In order for this
65 * optimization to work, ordering guarantees must exist so that the waiter
66 * being added to the list is acknowledged when the list is concurrently being
67 * checked by the waker, avoiding scenarios like the following:
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080068 *
69 * CPU 0 CPU 1
70 * val = *futex;
71 * sys_futex(WAIT, futex, val);
72 * futex_wait(futex, val);
73 * uval = *futex;
74 * *futex = newval;
75 * sys_futex(WAKE, futex);
76 * futex_wake(futex);
77 * if (queue_empty())
78 * return;
79 * if (uval == val)
80 * lock(hash_bucket(futex));
81 * queue();
82 * unlock(hash_bucket(futex));
83 * schedule();
84 *
85 * This would cause the waiter on CPU 0 to wait forever because it
86 * missed the transition of the user space value from val to newval
87 * and the waker did not find the waiter in the hash bucket queue.
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080088 *
Davidlohr Buesob0c29f72014-01-12 15:31:25 -080089 * The correct serialization ensures that a waiter either observes
90 * the changed user space value before blocking or is woken by a
91 * concurrent waker:
92 *
93 * CPU 0 CPU 1
Thomas Gleixner99b60ce2014-01-12 15:31:24 -080094 * val = *futex;
95 * sys_futex(WAIT, futex, val);
96 * futex_wait(futex, val);
Davidlohr Buesob0c29f72014-01-12 15:31:25 -080097 *
Davidlohr Buesod7e8af12014-04-09 11:55:07 -070098 * waiters++; (a)
Davidlohr Bueso8ad7b372016-02-09 11:15:13 -080099 * smp_mb(); (A) <-- paired with -.
100 * |
101 * lock(hash_bucket(futex)); |
102 * |
103 * uval = *futex; |
104 * | *futex = newval;
105 * | sys_futex(WAKE, futex);
106 * | futex_wake(futex);
107 * |
108 * `--------> smp_mb(); (B)
Thomas Gleixner99b60ce2014-01-12 15:31:24 -0800109 * if (uval == val)
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800110 * queue();
Thomas Gleixner99b60ce2014-01-12 15:31:24 -0800111 * unlock(hash_bucket(futex));
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800112 * schedule(); if (waiters)
113 * lock(hash_bucket(futex));
Davidlohr Buesod7e8af12014-04-09 11:55:07 -0700114 * else wake_waiters(futex);
115 * waiters--; (b) unlock(hash_bucket(futex));
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800116 *
Davidlohr Buesod7e8af12014-04-09 11:55:07 -0700117 * Where (A) orders the waiters increment and the futex value read through
118 * atomic operations (see hb_waiters_inc) and where (B) orders the write
Peter Zijlstra4b39f992020-03-04 13:24:24 +0100119 * to futex and the waiters read (see hb_waiters_pending()).
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800120 *
121 * This yields the following case (where X:=waiters, Y:=futex):
122 *
123 * X = Y = 0
124 *
125 * w[X]=1 w[Y]=1
126 * MB MB
127 * r[Y]=y r[X]=x
128 *
129 * Which guarantees that x==0 && y==0 is impossible; which translates back into
130 * the guarantee that we cannot both miss the futex variable change and the
131 * enqueue.
Davidlohr Buesod7e8af12014-04-09 11:55:07 -0700132 *
133 * Note that a new waiter is accounted for in (a) even when it is possible that
134 * the wait call can return error, in which case we backtrack from it in (b).
135 * Refer to the comment in queue_lock().
136 *
137 * Similarly, in order to account for waiters being requeued on another
138 * address we always increment the waiters for the destination bucket before
139 * acquiring the lock. It then decrements them again after releasing it -
140 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
141 * will do the additional required waiter count housekeeping. This is done for
142 * double_lock_hb() and double_unlock_hb(), respectively.
Thomas Gleixner99b60ce2014-01-12 15:31:24 -0800143 */
144
Peter Zijlstraaf8cc962021-09-23 14:10:51 -0300145#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
146int __read_mostly futex_cmpxchg_enabled;
Heiko Carstens03b8c7b2014-03-02 13:09:47 +0100147#endif
Thomas Gleixnera0c1e902008-02-23 15:23:57 -0800148
Darren Hartb41277d2010-11-08 13:10:09 -0800149
150/*
Ingo Molnarc87e2832006-06-27 02:54:58 -0700151 * Priority Inheritance state:
152 */
153struct futex_pi_state {
154 /*
155 * list of 'owned' pi_state instances - these have to be
156 * cleaned up in do_exit() if the task exits prematurely:
157 */
158 struct list_head list;
159
160 /*
161 * The PI object:
162 */
Peter Zijlstra830e6ac2021-08-15 23:27:58 +0200163 struct rt_mutex_base pi_mutex;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700164
165 struct task_struct *owner;
Elena Reshetova49262de2019-02-05 14:24:27 +0200166 refcount_t refcount;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700167
168 union futex_key key;
Kees Cook3859a272016-10-28 01:22:25 -0700169} __randomize_layout;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700170
Darren Hartd8d88fb2009-09-21 22:30:30 -0700171/**
172 * struct futex_q - The hashed futex queue entry, one per waiting task
Randy Dunlapfb62db22010-10-13 11:02:34 -0700173 * @list: priority-sorted list of tasks waiting on this futex
Darren Hartd8d88fb2009-09-21 22:30:30 -0700174 * @task: the task waiting on the futex
175 * @lock_ptr: the hash bucket lock
176 * @key: the key the futex is hashed on
177 * @pi_state: optional priority inheritance state
178 * @rt_waiter: rt_waiter storage for use with requeue_pi
179 * @requeue_pi_key: the requeue_pi target futex key
180 * @bitset: bitset for the optional bitmasked wakeup
Thomas Gleixner07d91ef52021-08-15 23:29:18 +0200181 * @requeue_state: State field for futex_requeue_pi()
182 * @requeue_wait: RCU wait for futex_requeue_pi() (RT only)
Darren Hartd8d88fb2009-09-21 22:30:30 -0700183 *
Ingo Molnarac6424b2017-06-20 12:06:13 +0200184 * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
Linus Torvalds1da177e2005-04-16 15:20:36 -0700185 * we can wake only the relevant ones (hashed queues may be shared).
186 *
187 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
Pierre Peifferec92d082007-05-09 02:35:00 -0700188 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
Randy Dunlapfb62db22010-10-13 11:02:34 -0700189 * The order of wakeup is always to make the first condition true, then
Darren Hartd8d88fb2009-09-21 22:30:30 -0700190 * the second.
191 *
192 * PI futexes are typically woken before they are removed from the hash list via
193 * the rt_mutex code. See unqueue_me_pi().
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194 */
195struct futex_q {
Pierre Peifferec92d082007-05-09 02:35:00 -0700196 struct plist_node list;
Darren Hartd8d88fb2009-09-21 22:30:30 -0700197
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +0200198 struct task_struct *task;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700199 spinlock_t *lock_ptr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700200 union futex_key key;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700201 struct futex_pi_state *pi_state;
Darren Hart52400ba2009-04-03 13:40:49 -0700202 struct rt_mutex_waiter *rt_waiter;
Darren Hart84bc4af2009-08-13 17:36:53 -0700203 union futex_key *requeue_pi_key;
Thomas Gleixnercd689982008-02-01 17:45:14 +0100204 u32 bitset;
Thomas Gleixner07d91ef52021-08-15 23:29:18 +0200205 atomic_t requeue_state;
206#ifdef CONFIG_PREEMPT_RT
207 struct rcuwait requeue_wait;
208#endif
Kees Cook3859a272016-10-28 01:22:25 -0700209} __randomize_layout;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700210
Thomas Gleixner07d91ef52021-08-15 23:29:18 +0200211/*
212 * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an
213 * underlying rtmutex. The task which is about to be requeued could have
214 * just woken up (timeout, signal). After the wake up the task has to
215 * acquire hash bucket lock, which is held by the requeue code. As a task
216 * can only be blocked on _ONE_ rtmutex at a time, the proxy lock blocking
217 * and the hash bucket lock blocking would collide and corrupt state.
218 *
219 * On !PREEMPT_RT this is not a problem and everything could be serialized
220 * on hash bucket lock, but aside of having the benefit of common code,
221 * this allows to avoid doing the requeue when the task is already on the
222 * way out and taking the hash bucket lock of the original uaddr1 when the
223 * requeue has been completed.
224 *
225 * The following state transitions are valid:
226 *
227 * On the waiter side:
228 * Q_REQUEUE_PI_NONE -> Q_REQUEUE_PI_IGNORE
229 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_WAIT
230 *
231 * On the requeue side:
232 * Q_REQUEUE_PI_NONE -> Q_REQUEUE_PI_INPROGRESS
233 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_DONE/LOCKED
234 * Q_REQUEUE_PI_IN_PROGRESS -> Q_REQUEUE_PI_NONE (requeue failed)
235 * Q_REQUEUE_PI_WAIT -> Q_REQUEUE_PI_DONE/LOCKED
236 * Q_REQUEUE_PI_WAIT -> Q_REQUEUE_PI_IGNORE (requeue failed)
237 *
238 * The requeue side ignores a waiter with state Q_REQUEUE_PI_IGNORE as this
239 * signals that the waiter is already on the way out. It also means that
240 * the waiter is still on the 'wait' futex, i.e. uaddr1.
241 *
242 * The waiter side signals early wakeup to the requeue side either through
243 * setting state to Q_REQUEUE_PI_IGNORE or to Q_REQUEUE_PI_WAIT depending
244 * on the current state. In case of Q_REQUEUE_PI_IGNORE it can immediately
245 * proceed to take the hash bucket lock of uaddr1. If it set state to WAIT,
246 * which means the wakeup is interleaving with a requeue in progress it has
247 * to wait for the requeue side to change the state. Either to DONE/LOCKED
248 * or to IGNORE. DONE/LOCKED means the waiter q is now on the uaddr2 futex
249 * and either blocked (DONE) or has acquired it (LOCKED). IGNORE is set by
250 * the requeue side when the requeue attempt failed via deadlock detection
251 * and therefore the waiter q is still on the uaddr1 futex.
252 */
253enum {
254 Q_REQUEUE_PI_NONE = 0,
255 Q_REQUEUE_PI_IGNORE,
256 Q_REQUEUE_PI_IN_PROGRESS,
257 Q_REQUEUE_PI_WAIT,
258 Q_REQUEUE_PI_DONE,
259 Q_REQUEUE_PI_LOCKED,
260};
261
Darren Hart5bdb05f2010-11-08 13:40:28 -0800262static const struct futex_q futex_q_init = {
263 /* list gets initialized in queue_me()*/
Thomas Gleixner07d91ef52021-08-15 23:29:18 +0200264 .key = FUTEX_KEY_INIT,
265 .bitset = FUTEX_BITSET_MATCH_ANY,
266 .requeue_state = ATOMIC_INIT(Q_REQUEUE_PI_NONE),
Darren Hart5bdb05f2010-11-08 13:40:28 -0800267};
268
Linus Torvalds1da177e2005-04-16 15:20:36 -0700269/*
Darren Hartb2d09942009-03-12 00:55:37 -0700270 * Hash buckets are shared by all the futex_keys that hash to the same
271 * location. Each key may have multiple futex_q structures, one for each task
272 * waiting on a futex.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700273 */
274struct futex_hash_bucket {
Linus Torvalds11d46162014-03-20 22:11:17 -0700275 atomic_t waiters;
Pierre Peifferec92d082007-05-09 02:35:00 -0700276 spinlock_t lock;
277 struct plist_head chain;
Davidlohr Buesoa52b89e2014-01-12 15:31:23 -0800278} ____cacheline_aligned_in_smp;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700279
Rasmus Villemoesac742d32015-09-09 23:36:40 +0200280/*
281 * The base of the bucket array and its size are always used together
282 * (after initialization only in hash_futex()), so ensure that they
283 * reside in the same cacheline.
284 */
285static struct {
286 struct futex_hash_bucket *queues;
287 unsigned long hashsize;
288} __futex_data __read_mostly __aligned(2*sizeof(long));
289#define futex_queues (__futex_data.queues)
290#define futex_hashsize (__futex_data.hashsize)
Davidlohr Buesoa52b89e2014-01-12 15:31:23 -0800291
Linus Torvalds1da177e2005-04-16 15:20:36 -0700292
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700293/*
294 * Fault injections for futexes.
295 */
296#ifdef CONFIG_FAIL_FUTEX
297
298static struct {
299 struct fault_attr attr;
300
Viresh Kumar621a5f72015-09-26 15:04:07 -0700301 bool ignore_private;
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700302} fail_futex = {
303 .attr = FAULT_ATTR_INITIALIZER,
Viresh Kumar621a5f72015-09-26 15:04:07 -0700304 .ignore_private = false,
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700305};
306
307static int __init setup_fail_futex(char *str)
308{
309 return setup_fault_attr(&fail_futex.attr, str);
310}
311__setup("fail_futex=", setup_fail_futex);
312
Peter Zijlstraaf8cc962021-09-23 14:10:51 -0300313bool should_fail_futex(bool fshared)
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700314{
315 if (fail_futex.ignore_private && !fshared)
316 return false;
317
318 return should_fail(&fail_futex.attr, 1);
319}
320
321#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
322
323static int __init fail_futex_debugfs(void)
324{
325 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
326 struct dentry *dir;
327
328 dir = fault_create_debugfs_attr("fail_futex", NULL,
329 &fail_futex.attr);
330 if (IS_ERR(dir))
331 return PTR_ERR(dir);
332
Greg Kroah-Hartman0365aeb2019-01-22 16:21:39 +0100333 debugfs_create_bool("ignore-private", mode, dir,
334 &fail_futex.ignore_private);
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700335 return 0;
336}
337
338late_initcall(fail_futex_debugfs);
339
340#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
341
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700342#endif /* CONFIG_FAIL_FUTEX */
343
Linus Torvalds11d46162014-03-20 22:11:17 -0700344/*
345 * Reflects a new waiter being added to the waitqueue.
346 */
347static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800348{
349#ifdef CONFIG_SMP
Linus Torvalds11d46162014-03-20 22:11:17 -0700350 atomic_inc(&hb->waiters);
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800351 /*
Linus Torvalds11d46162014-03-20 22:11:17 -0700352 * Full barrier (A), see the ordering comment above.
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800353 */
Peter Zijlstra4e857c52014-03-17 18:06:10 +0100354 smp_mb__after_atomic();
Linus Torvalds11d46162014-03-20 22:11:17 -0700355#endif
356}
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800357
Linus Torvalds11d46162014-03-20 22:11:17 -0700358/*
359 * Reflects a waiter being removed from the waitqueue by wakeup
360 * paths.
361 */
362static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
363{
364#ifdef CONFIG_SMP
365 atomic_dec(&hb->waiters);
366#endif
367}
368
369static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
370{
371#ifdef CONFIG_SMP
Peter Zijlstra4b39f992020-03-04 13:24:24 +0100372 /*
373 * Full barrier (B), see the ordering comment above.
374 */
375 smp_mb();
Linus Torvalds11d46162014-03-20 22:11:17 -0700376 return atomic_read(&hb->waiters);
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800377#else
Linus Torvalds11d46162014-03-20 22:11:17 -0700378 return 1;
Davidlohr Buesob0c29f72014-01-12 15:31:25 -0800379#endif
380}
381
Thomas Gleixnere8b61b32016-06-01 10:43:29 +0200382/**
383 * hash_futex - Return the hash bucket in the global hash
384 * @key: Pointer to the futex key for which the hash is calculated
385 *
386 * We hash on the keys returned from get_futex_key (see below) and return the
387 * corresponding hash bucket in the global hash.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700388 */
389static struct futex_hash_bucket *hash_futex(union futex_key *key)
390{
Thomas Gleixner8d677432020-03-08 19:07:17 +0100391 u32 hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / 4,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700392 key->both.offset);
Thomas Gleixner8d677432020-03-08 19:07:17 +0100393
Davidlohr Buesoa52b89e2014-01-12 15:31:23 -0800394 return &futex_queues[hash & (futex_hashsize - 1)];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700395}
396
Thomas Gleixnere8b61b32016-06-01 10:43:29 +0200397
398/**
399 * match_futex - Check whether two futex keys are equal
400 * @key1: Pointer to key1
401 * @key2: Pointer to key2
402 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700403 * Return 1 if two futex_keys are equal, 0 otherwise.
404 */
405static inline int match_futex(union futex_key *key1, union futex_key *key2)
406{
Darren Hart2bc87202009-10-14 10:12:39 -0700407 return (key1 && key2
408 && key1->both.word == key2->both.word
Linus Torvalds1da177e2005-04-16 15:20:36 -0700409 && key1->both.ptr == key2->both.ptr
410 && key1->both.offset == key2->both.offset);
411}
412
Linus Torvalds96d4f262019-01-03 18:57:57 -0800413enum futex_access {
414 FUTEX_READ,
415 FUTEX_WRITE
416};
417
Eric Dumazet34f01cc2007-05-09 02:35:04 -0700418/**
Waiman Long5ca584d2019-05-28 12:03:45 -0400419 * futex_setup_timer - set up the sleeping hrtimer.
420 * @time: ptr to the given timeout value
421 * @timeout: the hrtimer_sleeper structure to be set up
422 * @flags: futex flags
423 * @range_ns: optional range in ns
424 *
425 * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
426 * value given
427 */
428static inline struct hrtimer_sleeper *
429futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
430 int flags, u64 range_ns)
431{
432 if (!time)
433 return NULL;
434
Sebastian Andrzej Siewiordbc16252019-07-26 20:30:50 +0200435 hrtimer_init_sleeper_on_stack(timeout, (flags & FLAGS_CLOCKRT) ?
436 CLOCK_REALTIME : CLOCK_MONOTONIC,
437 HRTIMER_MODE_ABS);
Waiman Long5ca584d2019-05-28 12:03:45 -0400438 /*
439 * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
440 * effectively the same as calling hrtimer_set_expires().
441 */
442 hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
443
444 return timeout;
445}
446
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100447/*
448 * Generate a machine wide unique identifier for this inode.
449 *
450 * This relies on u64 not wrapping in the life-time of the machine; which with
451 * 1ns resolution means almost 585 years.
452 *
453 * This further relies on the fact that a well formed program will not unmap
454 * the file while it has a (shared) futex waiting on it. This mapping will have
455 * a file reference which pins the mount and inode.
456 *
457 * If for some reason an inode gets evicted and read back in again, it will get
458 * a new sequence number and will _NOT_ match, even though it is the exact same
459 * file.
460 *
461 * It is important that match_futex() will never have a false-positive, esp.
462 * for PI futexes that can mess up the state. The above argues that false-negatives
463 * are only possible for malformed programs.
464 */
465static u64 get_inode_sequence_number(struct inode *inode)
466{
467 static atomic64_t i_seq;
468 u64 old;
469
470 /* Does the inode already have a sequence number? */
471 old = atomic64_read(&inode->i_sequence);
472 if (likely(old))
473 return old;
474
475 for (;;) {
476 u64 new = atomic64_add_return(1, &i_seq);
477 if (WARN_ON_ONCE(!new))
478 continue;
479
480 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
481 if (old)
482 return old;
483 return new;
484 }
485}
486
Waiman Long5ca584d2019-05-28 12:03:45 -0400487/**
Darren Hartd96ee562009-09-21 22:30:22 -0700488 * get_futex_key() - Get parameters which are the keys for a futex
489 * @uaddr: virtual address of the futex
André Almeida92613082020-07-02 17:28:43 -0300490 * @fshared: false for a PROCESS_PRIVATE futex, true for PROCESS_SHARED
Darren Hartd96ee562009-09-21 22:30:22 -0700491 * @key: address where result is stored.
Linus Torvalds96d4f262019-01-03 18:57:57 -0800492 * @rw: mapping needs to be read/write (values: FUTEX_READ,
493 * FUTEX_WRITE)
Eric Dumazet34f01cc2007-05-09 02:35:04 -0700494 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -0800495 * Return: a negative error code or 0
496 *
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -0300497 * The key words are stored in @key on success.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700498 *
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100499 * For shared mappings (when @fshared), the key is:
Mauro Carvalho Chehab03c109d2020-04-14 18:48:58 +0200500 *
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100501 * ( inode->i_sequence, page->index, offset_within_page )
Mauro Carvalho Chehab03c109d2020-04-14 18:48:58 +0200502 *
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100503 * [ also see get_inode_sequence_number() ]
504 *
505 * For private mappings (or when !@fshared), the key is:
Mauro Carvalho Chehab03c109d2020-04-14 18:48:58 +0200506 *
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100507 * ( current->mm, address, 0 )
508 *
509 * This allows (cross process, where applicable) identification of the futex
510 * without keeping the page pinned for the duration of the FUTEX_WAIT.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700511 *
Darren Hartb2d09942009-03-12 00:55:37 -0700512 * lock_page() might sleep, the caller should not hold a spinlock.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700513 */
André Almeida92613082020-07-02 17:28:43 -0300514static int get_futex_key(u32 __user *uaddr, bool fshared, union futex_key *key,
515 enum futex_access rw)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700516{
Ingo Molnare2970f22006-06-27 02:54:47 -0700517 unsigned long address = (unsigned long)uaddr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700518 struct mm_struct *mm = current->mm;
Mel Gorman077fa7a2016-06-08 14:25:22 +0100519 struct page *page, *tail;
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800520 struct address_space *mapping;
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500521 int err, ro = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522
523 /*
524 * The futex address must be "naturally" aligned.
525 */
Ingo Molnare2970f22006-06-27 02:54:47 -0700526 key->both.offset = address % PAGE_SIZE;
Eric Dumazet34f01cc2007-05-09 02:35:04 -0700527 if (unlikely((address % sizeof(u32)) != 0))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700528 return -EINVAL;
Ingo Molnare2970f22006-06-27 02:54:47 -0700529 address -= key->both.offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700530
Linus Torvalds96d4f262019-01-03 18:57:57 -0800531 if (unlikely(!access_ok(uaddr, sizeof(u32))))
Linus Torvalds5cdec2d2013-12-12 09:53:51 -0800532 return -EFAULT;
533
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700534 if (unlikely(should_fail_futex(fshared)))
535 return -EFAULT;
536
Linus Torvalds1da177e2005-04-16 15:20:36 -0700537 /*
Eric Dumazet34f01cc2007-05-09 02:35:04 -0700538 * PROCESS_PRIVATE futexes are fast.
539 * As the mm cannot disappear under us and the 'key' only needs
540 * virtual address, we dont even have to find the underlying vma.
541 * Note : We do have to check 'uaddr' is a valid user address,
542 * but access_ok() should be faster than find_vma()
543 */
544 if (!fshared) {
Eric Dumazet34f01cc2007-05-09 02:35:04 -0700545 key->private.mm = mm;
546 key->private.address = address;
547 return 0;
548 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700549
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200550again:
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700551 /* Ignore any VERIFY_READ mapping (futex common case) */
André Almeida92613082020-07-02 17:28:43 -0300552 if (unlikely(should_fail_futex(true)))
Davidlohr Buesoab51fba2015-06-29 23:26:02 -0700553 return -EFAULT;
554
Ira Weiny73b01402019-05-13 17:17:11 -0700555 err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500556 /*
557 * If write access is not required (eg. FUTEX_WAIT), try
558 * and get read-only access.
559 */
Linus Torvalds96d4f262019-01-03 18:57:57 -0800560 if (err == -EFAULT && rw == FUTEX_READ) {
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500561 err = get_user_pages_fast(address, 1, 0, &page);
562 ro = 1;
563 }
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200564 if (err < 0)
565 return err;
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500566 else
567 err = 0;
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200568
Mel Gorman65d8fc72016-02-09 11:15:14 -0800569 /*
570 * The treatment of mapping from this point on is critical. The page
571 * lock protects many things but in this context the page lock
572 * stabilizes mapping, prevents inode freeing in the shared
573 * file-backed region case and guards against movement to swap cache.
574 *
575 * Strictly speaking the page lock is not needed in all cases being
576 * considered here and page lock forces unnecessarily serialization
577 * From this point on, mapping will be re-verified if necessary and
578 * page lock will be acquired only if it is unavoidable
Mel Gorman077fa7a2016-06-08 14:25:22 +0100579 *
580 * Mapping checks require the head page for any compound page so the
581 * head page and mapping is looked up now. For anonymous pages, it
582 * does not matter if the page splits in the future as the key is
583 * based on the address. For filesystem-backed pages, the tail is
584 * required as the index of the page determines the key. For
585 * base pages, there is no tail page and tail == page.
Mel Gorman65d8fc72016-02-09 11:15:14 -0800586 */
Mel Gorman077fa7a2016-06-08 14:25:22 +0100587 tail = page;
Mel Gorman65d8fc72016-02-09 11:15:14 -0800588 page = compound_head(page);
589 mapping = READ_ONCE(page->mapping);
590
Hugh Dickinse6780f72011-12-31 11:44:01 -0800591 /*
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800592 * If page->mapping is NULL, then it cannot be a PageAnon
Hugh Dickinse6780f72011-12-31 11:44:01 -0800593 * page; but it might be the ZERO_PAGE or in the gate area or
594 * in a special mapping (all cases which we are happy to fail);
595 * or it may have been a good file page when get_user_pages_fast
596 * found it, but truncated or holepunched or subjected to
597 * invalidate_complete_page2 before we got the page lock (also
598 * cases which we are happy to fail). And we hold a reference,
599 * so refcount care in invalidate_complete_page's remove_mapping
600 * prevents drop_caches from setting mapping to NULL beneath us.
601 *
602 * The case we do have to guard against is when memory pressure made
603 * shmem_writepage move it from filecache to swapcache beneath us:
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800604 * an unlikely race, but we do need to retry for page->mapping.
Hugh Dickinse6780f72011-12-31 11:44:01 -0800605 */
Mel Gorman65d8fc72016-02-09 11:15:14 -0800606 if (unlikely(!mapping)) {
607 int shmem_swizzled;
608
609 /*
610 * Page lock is required to identify which special case above
611 * applies. If this is really a shmem page then the page lock
612 * will prevent unexpected transitions.
613 */
614 lock_page(page);
615 shmem_swizzled = PageSwapCache(page) || page->mapping;
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800616 unlock_page(page);
617 put_page(page);
Mel Gorman65d8fc72016-02-09 11:15:14 -0800618
Hugh Dickinse6780f72011-12-31 11:44:01 -0800619 if (shmem_swizzled)
620 goto again;
Mel Gorman65d8fc72016-02-09 11:15:14 -0800621
Hugh Dickinse6780f72011-12-31 11:44:01 -0800622 return -EFAULT;
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200623 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624
625 /*
626 * Private mappings are handled in a simple way.
627 *
Mel Gorman65d8fc72016-02-09 11:15:14 -0800628 * If the futex key is stored on an anonymous page, then the associated
629 * object is the mm which is implicitly pinned by the calling process.
630 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700631 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
632 * it's a read-only handle, it's expected that futexes attach to
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200633 * the object not the particular process.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700634 */
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800635 if (PageAnon(page)) {
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500636 /*
637 * A RO anonymous page will never change and thus doesn't make
638 * sense for futex operations.
639 */
André Almeida92613082020-07-02 17:28:43 -0300640 if (unlikely(should_fail_futex(true)) || ro) {
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500641 err = -EFAULT;
642 goto out;
643 }
644
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200645 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700646 key->private.mm = mm;
Ingo Molnare2970f22006-06-27 02:54:47 -0700647 key->private.address = address;
Mel Gorman65d8fc72016-02-09 11:15:14 -0800648
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200649 } else {
Mel Gorman65d8fc72016-02-09 11:15:14 -0800650 struct inode *inode;
651
652 /*
653 * The associated futex object in this case is the inode and
654 * the page->mapping must be traversed. Ordinarily this should
655 * be stabilised under page lock but it's not strictly
656 * necessary in this case as we just want to pin the inode, not
657 * update the radix tree or anything like that.
658 *
659 * The RCU read lock is taken as the inode is finally freed
660 * under RCU. If the mapping still matches expectations then the
661 * mapping->host can be safely accessed as being a valid inode.
662 */
663 rcu_read_lock();
664
665 if (READ_ONCE(page->mapping) != mapping) {
666 rcu_read_unlock();
667 put_page(page);
668
669 goto again;
670 }
671
672 inode = READ_ONCE(mapping->host);
673 if (!inode) {
674 rcu_read_unlock();
675 put_page(page);
676
677 goto again;
678 }
679
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200680 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
Peter Zijlstra8019ad12020-03-04 11:28:31 +0100681 key->shared.i_seq = get_inode_sequence_number(inode);
Hugh Dickinsfe19bd32021-06-24 18:39:52 -0700682 key->shared.pgoff = page_to_pgoff(tail);
Mel Gorman65d8fc72016-02-09 11:15:14 -0800683 rcu_read_unlock();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700684 }
685
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500686out:
Kirill A. Shutemov14d27ab2016-01-15 16:53:00 -0800687 put_page(page);
Shawn Bohrer9ea71502011-06-30 11:21:32 -0500688 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700689}
690
Darren Hartd96ee562009-09-21 22:30:22 -0700691/**
692 * fault_in_user_writeable() - Fault in user address and verify RW access
Thomas Gleixnerd0725992009-06-11 23:15:43 +0200693 * @uaddr: pointer to faulting user space address
694 *
695 * Slow path to fixup the fault we just took in the atomic write
696 * access to @uaddr.
697 *
Randy Dunlapfb62db22010-10-13 11:02:34 -0700698 * We have no generic implementation of a non-destructive write to the
Thomas Gleixnerd0725992009-06-11 23:15:43 +0200699 * user address. We know that we faulted in the atomic pagefault
700 * disabled section so we can as well avoid the #PF overhead by
701 * calling get_user_pages() right away.
702 */
703static int fault_in_user_writeable(u32 __user *uaddr)
704{
Andi Kleen722d0172009-12-08 13:19:42 +0100705 struct mm_struct *mm = current->mm;
706 int ret;
707
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700708 mmap_read_lock(mm);
Peter Xu64019a22020-08-11 18:39:01 -0700709 ret = fixup_user_fault(mm, (unsigned long)uaddr,
Dominik Dingel4a9e1cd2016-01-15 16:57:04 -0800710 FAULT_FLAG_WRITE, NULL);
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700711 mmap_read_unlock(mm);
Andi Kleen722d0172009-12-08 13:19:42 +0100712
Thomas Gleixnerd0725992009-06-11 23:15:43 +0200713 return ret < 0 ? ret : 0;
714}
715
Darren Hart4b1c4862009-04-03 13:39:42 -0700716/**
717 * futex_top_waiter() - Return the highest priority waiter on a futex
Darren Hartd96ee562009-09-21 22:30:22 -0700718 * @hb: the hash bucket the futex_q's reside in
719 * @key: the futex key (to distinguish it from other futex futex_q's)
Darren Hart4b1c4862009-04-03 13:39:42 -0700720 *
721 * Must be called with the hb lock held.
722 */
723static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
724 union futex_key *key)
725{
726 struct futex_q *this;
727
728 plist_for_each_entry(this, &hb->chain, list) {
729 if (match_futex(&this->key, key))
730 return this;
731 }
732 return NULL;
733}
734
Michel Lespinasse37a9d912011-03-10 18:48:51 -0800735static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
736 u32 uval, u32 newval)
Thomas Gleixner36cf3b52007-07-15 23:41:20 -0700737{
Michel Lespinasse37a9d912011-03-10 18:48:51 -0800738 int ret;
Thomas Gleixner36cf3b52007-07-15 23:41:20 -0700739
740 pagefault_disable();
Michel Lespinasse37a9d912011-03-10 18:48:51 -0800741 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
Thomas Gleixner36cf3b52007-07-15 23:41:20 -0700742 pagefault_enable();
743
Michel Lespinasse37a9d912011-03-10 18:48:51 -0800744 return ret;
Thomas Gleixner36cf3b52007-07-15 23:41:20 -0700745}
746
747static int get_futex_value_locked(u32 *dest, u32 __user *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700748{
749 int ret;
750
Peter Zijlstraa8663742006-12-06 20:32:20 -0800751 pagefault_disable();
Linus Torvaldsbd28b142016-05-22 17:21:27 -0700752 ret = __get_user(*dest, from);
Peter Zijlstraa8663742006-12-06 20:32:20 -0800753 pagefault_enable();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700754
755 return ret ? -EFAULT : 0;
756}
757
Ingo Molnarc87e2832006-06-27 02:54:58 -0700758
759/*
760 * PI code:
761 */
762static int refill_pi_state_cache(void)
763{
764 struct futex_pi_state *pi_state;
765
766 if (likely(current->pi_state_cache))
767 return 0;
768
Burman Yan4668edc2006-12-06 20:38:51 -0800769 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700770
771 if (!pi_state)
772 return -ENOMEM;
773
Ingo Molnarc87e2832006-06-27 02:54:58 -0700774 INIT_LIST_HEAD(&pi_state->list);
775 /* pi_mutex gets initialized later */
776 pi_state->owner = NULL;
Elena Reshetova49262de2019-02-05 14:24:27 +0200777 refcount_set(&pi_state->refcount, 1);
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200778 pi_state->key = FUTEX_KEY_INIT;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700779
780 current->pi_state_cache = pi_state;
781
782 return 0;
783}
784
Peter Zijlstrabf92cf32017-03-22 11:35:53 +0100785static struct futex_pi_state *alloc_pi_state(void)
Ingo Molnarc87e2832006-06-27 02:54:58 -0700786{
787 struct futex_pi_state *pi_state = current->pi_state_cache;
788
789 WARN_ON(!pi_state);
790 current->pi_state_cache = NULL;
791
792 return pi_state;
793}
794
Thomas Gleixnerc5cade22021-01-19 15:21:35 +0100795static void pi_state_update_owner(struct futex_pi_state *pi_state,
796 struct task_struct *new_owner)
797{
798 struct task_struct *old_owner = pi_state->owner;
799
800 lockdep_assert_held(&pi_state->pi_mutex.wait_lock);
801
802 if (old_owner) {
803 raw_spin_lock(&old_owner->pi_lock);
804 WARN_ON(list_empty(&pi_state->list));
805 list_del_init(&pi_state->list);
806 raw_spin_unlock(&old_owner->pi_lock);
807 }
808
809 if (new_owner) {
810 raw_spin_lock(&new_owner->pi_lock);
811 WARN_ON(!list_empty(&pi_state->list));
812 list_add(&pi_state->list, &new_owner->pi_state_list);
813 pi_state->owner = new_owner;
814 raw_spin_unlock(&new_owner->pi_lock);
815 }
816}
817
Peter Zijlstrabf92cf32017-03-22 11:35:53 +0100818static void get_pi_state(struct futex_pi_state *pi_state)
819{
Elena Reshetova49262de2019-02-05 14:24:27 +0200820 WARN_ON_ONCE(!refcount_inc_not_zero(&pi_state->refcount));
Peter Zijlstrabf92cf32017-03-22 11:35:53 +0100821}
822
Brian Silverman30a6b802014-10-25 20:20:37 -0400823/*
Thomas Gleixner29e9ee52015-12-19 20:07:39 +0000824 * Drops a reference to the pi_state object and frees or caches it
825 * when the last reference is gone.
Brian Silverman30a6b802014-10-25 20:20:37 -0400826 */
Thomas Gleixner29e9ee52015-12-19 20:07:39 +0000827static void put_pi_state(struct futex_pi_state *pi_state)
Ingo Molnarc87e2832006-06-27 02:54:58 -0700828{
Brian Silverman30a6b802014-10-25 20:20:37 -0400829 if (!pi_state)
830 return;
831
Elena Reshetova49262de2019-02-05 14:24:27 +0200832 if (!refcount_dec_and_test(&pi_state->refcount))
Ingo Molnarc87e2832006-06-27 02:54:58 -0700833 return;
834
835 /*
836 * If pi_state->owner is NULL, the owner is most probably dying
837 * and has cleaned up the pi_state already
838 */
839 if (pi_state->owner) {
Dan Carpenter1e106aa2020-11-06 11:52:05 +0300840 unsigned long flags;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700841
Dan Carpenter1e106aa2020-11-06 11:52:05 +0300842 raw_spin_lock_irqsave(&pi_state->pi_mutex.wait_lock, flags);
Thomas Gleixner6ccc84f2021-01-20 11:35:19 +0100843 pi_state_update_owner(pi_state, NULL);
Thomas Gleixner2156ac12021-01-20 11:32:07 +0100844 rt_mutex_proxy_unlock(&pi_state->pi_mutex);
Dan Carpenter1e106aa2020-11-06 11:52:05 +0300845 raw_spin_unlock_irqrestore(&pi_state->pi_mutex.wait_lock, flags);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700846 }
847
Peter Zijlstrac74aef22017-09-22 17:48:06 +0200848 if (current->pi_state_cache) {
Ingo Molnarc87e2832006-06-27 02:54:58 -0700849 kfree(pi_state);
Peter Zijlstrac74aef22017-09-22 17:48:06 +0200850 } else {
Ingo Molnarc87e2832006-06-27 02:54:58 -0700851 /*
852 * pi_state->list is already empty.
853 * clear pi_state->owner.
854 * refcount is at 0 - put it back to 1.
855 */
856 pi_state->owner = NULL;
Elena Reshetova49262de2019-02-05 14:24:27 +0200857 refcount_set(&pi_state->refcount, 1);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700858 current->pi_state_cache = pi_state;
859 }
860}
861
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -0400862#ifdef CONFIG_FUTEX_PI
863
Ingo Molnarc87e2832006-06-27 02:54:58 -0700864/*
865 * This task is holding PI mutexes at exit time => bad.
866 * Kernel cleans up PI-state, but userspace is likely hosed.
867 * (Robust-futex cleanup is separate and might save the day for userspace.)
868 */
Thomas Gleixnerba31c1a42019-11-06 22:55:36 +0100869static void exit_pi_state_list(struct task_struct *curr)
Ingo Molnarc87e2832006-06-27 02:54:58 -0700870{
Ingo Molnarc87e2832006-06-27 02:54:58 -0700871 struct list_head *next, *head = &curr->pi_state_list;
872 struct futex_pi_state *pi_state;
Ingo Molnar627371d2006-07-29 05:16:20 +0200873 struct futex_hash_bucket *hb;
Peter Zijlstra38d47c12008-09-26 19:32:20 +0200874 union futex_key key = FUTEX_KEY_INIT;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700875
Thomas Gleixnera0c1e902008-02-23 15:23:57 -0800876 if (!futex_cmpxchg_enabled)
877 return;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700878 /*
879 * We are a ZOMBIE and nobody can enqueue itself on
880 * pi_state_list anymore, but we have to be careful
Ingo Molnar627371d2006-07-29 05:16:20 +0200881 * versus waiters unqueueing themselves:
Ingo Molnarc87e2832006-06-27 02:54:58 -0700882 */
Thomas Gleixner1d615482009-11-17 14:54:03 +0100883 raw_spin_lock_irq(&curr->pi_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700884 while (!list_empty(head)) {
Ingo Molnarc87e2832006-06-27 02:54:58 -0700885 next = head->next;
886 pi_state = list_entry(next, struct futex_pi_state, list);
887 key = pi_state->key;
Ingo Molnar627371d2006-07-29 05:16:20 +0200888 hb = hash_futex(&key);
Peter Zijlstra153fbd12017-10-31 11:18:53 +0100889
890 /*
891 * We can race against put_pi_state() removing itself from the
892 * list (a waiter going away). put_pi_state() will first
893 * decrement the reference count and then modify the list, so
894 * its possible to see the list entry but fail this reference
895 * acquire.
896 *
897 * In that case; drop the locks to let put_pi_state() make
898 * progress and retry the loop.
899 */
Elena Reshetova49262de2019-02-05 14:24:27 +0200900 if (!refcount_inc_not_zero(&pi_state->refcount)) {
Peter Zijlstra153fbd12017-10-31 11:18:53 +0100901 raw_spin_unlock_irq(&curr->pi_lock);
902 cpu_relax();
903 raw_spin_lock_irq(&curr->pi_lock);
904 continue;
905 }
Thomas Gleixner1d615482009-11-17 14:54:03 +0100906 raw_spin_unlock_irq(&curr->pi_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700907
Ingo Molnarc87e2832006-06-27 02:54:58 -0700908 spin_lock(&hb->lock);
Peter Zijlstrac74aef22017-09-22 17:48:06 +0200909 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
910 raw_spin_lock(&curr->pi_lock);
Ingo Molnar627371d2006-07-29 05:16:20 +0200911 /*
912 * We dropped the pi-lock, so re-check whether this
913 * task still owns the PI-state:
914 */
Ingo Molnarc87e2832006-06-27 02:54:58 -0700915 if (head->next != next) {
Peter Zijlstra153fbd12017-10-31 11:18:53 +0100916 /* retain curr->pi_lock for the loop invariant */
Peter Zijlstrac74aef22017-09-22 17:48:06 +0200917 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700918 spin_unlock(&hb->lock);
Peter Zijlstra153fbd12017-10-31 11:18:53 +0100919 put_pi_state(pi_state);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700920 continue;
921 }
922
Ingo Molnarc87e2832006-06-27 02:54:58 -0700923 WARN_ON(pi_state->owner != curr);
Ingo Molnar627371d2006-07-29 05:16:20 +0200924 WARN_ON(list_empty(&pi_state->list));
925 list_del_init(&pi_state->list);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700926 pi_state->owner = NULL;
Ingo Molnarc87e2832006-06-27 02:54:58 -0700927
Peter Zijlstra153fbd12017-10-31 11:18:53 +0100928 raw_spin_unlock(&curr->pi_lock);
Peter Zijlstrac74aef22017-09-22 17:48:06 +0200929 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700930 spin_unlock(&hb->lock);
931
Peter Zijlstra16ffa122017-03-22 11:35:55 +0100932 rt_mutex_futex_unlock(&pi_state->pi_mutex);
933 put_pi_state(pi_state);
934
Thomas Gleixner1d615482009-11-17 14:54:03 +0100935 raw_spin_lock_irq(&curr->pi_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700936 }
Thomas Gleixner1d615482009-11-17 14:54:03 +0100937 raw_spin_unlock_irq(&curr->pi_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -0700938}
Thomas Gleixnerba31c1a42019-11-06 22:55:36 +0100939#else
940static inline void exit_pi_state_list(struct task_struct *curr) { }
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -0400941#endif
942
Thomas Gleixner54a21782014-06-03 12:27:08 +0000943/*
944 * We need to check the following states:
945 *
946 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
947 *
948 * [1] NULL | --- | --- | 0 | 0/1 | Valid
949 * [2] NULL | --- | --- | >0 | 0/1 | Valid
950 *
951 * [3] Found | NULL | -- | Any | 0/1 | Invalid
952 *
953 * [4] Found | Found | NULL | 0 | 1 | Valid
954 * [5] Found | Found | NULL | >0 | 1 | Invalid
955 *
956 * [6] Found | Found | task | 0 | 1 | Valid
957 *
958 * [7] Found | Found | NULL | Any | 0 | Invalid
959 *
960 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
961 * [9] Found | Found | task | 0 | 0 | Invalid
962 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
963 *
964 * [1] Indicates that the kernel can acquire the futex atomically. We
Randy Dunlap7b7b8a22020-10-15 20:10:28 -0700965 * came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
Thomas Gleixner54a21782014-06-03 12:27:08 +0000966 *
967 * [2] Valid, if TID does not belong to a kernel thread. If no matching
968 * thread is found then it indicates that the owner TID has died.
969 *
970 * [3] Invalid. The waiter is queued on a non PI futex
971 *
972 * [4] Valid state after exit_robust_list(), which sets the user space
973 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
974 *
975 * [5] The user space value got manipulated between exit_robust_list()
976 * and exit_pi_state_list()
977 *
978 * [6] Valid state after exit_pi_state_list() which sets the new owner in
979 * the pi_state but cannot access the user space value.
980 *
981 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
982 *
983 * [8] Owner and user space value match
984 *
985 * [9] There is no transient state which sets the user space TID to 0
986 * except exit_robust_list(), but this is indicated by the
987 * FUTEX_OWNER_DIED bit. See [4]
988 *
989 * [10] There is no transient state which leaves owner and user space
Thomas Gleixner34b1a1c2021-01-18 19:01:21 +0100990 * TID out of sync. Except one error case where the kernel is denied
991 * write access to the user address, see fixup_pi_state_owner().
Peter Zijlstra734009e2017-03-22 11:35:52 +0100992 *
993 *
994 * Serialization and lifetime rules:
995 *
996 * hb->lock:
997 *
998 * hb -> futex_q, relation
999 * futex_q -> pi_state, relation
1000 *
1001 * (cannot be raw because hb can contain arbitrary amount
1002 * of futex_q's)
1003 *
1004 * pi_mutex->wait_lock:
1005 *
1006 * {uval, pi_state}
1007 *
1008 * (and pi_mutex 'obviously')
1009 *
1010 * p->pi_lock:
1011 *
1012 * p->pi_state_list -> pi_state->list, relation
Davidlohr Buesoc2e4bfe2021-02-26 09:50:29 -08001013 * pi_mutex->owner -> pi_state->owner, relation
Peter Zijlstra734009e2017-03-22 11:35:52 +01001014 *
1015 * pi_state->refcount:
1016 *
1017 * pi_state lifetime
1018 *
1019 *
1020 * Lock order:
1021 *
1022 * hb->lock
1023 * pi_mutex->wait_lock
1024 * p->pi_lock
1025 *
Thomas Gleixner54a21782014-06-03 12:27:08 +00001026 */
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001027
1028/*
1029 * Validate that the existing waiter has a pi_state and sanity check
1030 * the pi_state against the user space value. If correct, attach to
1031 * it.
1032 */
Peter Zijlstra734009e2017-03-22 11:35:52 +01001033static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1034 struct futex_pi_state *pi_state,
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001035 struct futex_pi_state **ps)
1036{
1037 pid_t pid = uval & FUTEX_TID_MASK;
Peter Zijlstra94ffac52017-04-07 09:04:07 +02001038 u32 uval2;
1039 int ret;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001040
1041 /*
1042 * Userspace might have messed up non-PI and PI futexes [3]
1043 */
1044 if (unlikely(!pi_state))
1045 return -EINVAL;
1046
Peter Zijlstra734009e2017-03-22 11:35:52 +01001047 /*
1048 * We get here with hb->lock held, and having found a
1049 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1050 * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
1051 * which in turn means that futex_lock_pi() still has a reference on
1052 * our pi_state.
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001053 *
1054 * The waiter holding a reference on @pi_state also protects against
1055 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1056 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1057 * free pi_state before we can take a reference ourselves.
Peter Zijlstra734009e2017-03-22 11:35:52 +01001058 */
Elena Reshetova49262de2019-02-05 14:24:27 +02001059 WARN_ON(!refcount_read(&pi_state->refcount));
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001060
1061 /*
Peter Zijlstra734009e2017-03-22 11:35:52 +01001062 * Now that we have a pi_state, we can acquire wait_lock
1063 * and do the state validation.
1064 */
1065 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1066
1067 /*
1068 * Since {uval, pi_state} is serialized by wait_lock, and our current
1069 * uval was read without holding it, it can have changed. Verify it
1070 * still is what we expect it to be, otherwise retry the entire
1071 * operation.
1072 */
1073 if (get_futex_value_locked(&uval2, uaddr))
1074 goto out_efault;
1075
1076 if (uval != uval2)
1077 goto out_eagain;
1078
1079 /*
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001080 * Handle the owner died case:
1081 */
1082 if (uval & FUTEX_OWNER_DIED) {
1083 /*
1084 * exit_pi_state_list sets owner to NULL and wakes the
1085 * topmost waiter. The task which acquires the
1086 * pi_state->rt_mutex will fixup owner.
1087 */
1088 if (!pi_state->owner) {
1089 /*
1090 * No pi state owner, but the user space TID
1091 * is not 0. Inconsistent state. [5]
1092 */
1093 if (pid)
Peter Zijlstra734009e2017-03-22 11:35:52 +01001094 goto out_einval;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001095 /*
1096 * Take a ref on the state and return success. [4]
1097 */
Peter Zijlstra734009e2017-03-22 11:35:52 +01001098 goto out_attach;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001099 }
1100
1101 /*
1102 * If TID is 0, then either the dying owner has not
1103 * yet executed exit_pi_state_list() or some waiter
1104 * acquired the rtmutex in the pi state, but did not
1105 * yet fixup the TID in user space.
1106 *
1107 * Take a ref on the state and return success. [6]
1108 */
1109 if (!pid)
Peter Zijlstra734009e2017-03-22 11:35:52 +01001110 goto out_attach;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001111 } else {
1112 /*
1113 * If the owner died bit is not set, then the pi_state
1114 * must have an owner. [7]
1115 */
1116 if (!pi_state->owner)
Peter Zijlstra734009e2017-03-22 11:35:52 +01001117 goto out_einval;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001118 }
1119
1120 /*
1121 * Bail out if user space manipulated the futex value. If pi
1122 * state exists then the owner TID must be the same as the
1123 * user space TID. [9/10]
1124 */
1125 if (pid != task_pid_vnr(pi_state->owner))
Peter Zijlstra734009e2017-03-22 11:35:52 +01001126 goto out_einval;
1127
1128out_attach:
Peter Zijlstrabf92cf32017-03-22 11:35:53 +01001129 get_pi_state(pi_state);
Peter Zijlstra734009e2017-03-22 11:35:52 +01001130 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001131 *ps = pi_state;
1132 return 0;
Peter Zijlstra734009e2017-03-22 11:35:52 +01001133
1134out_einval:
1135 ret = -EINVAL;
1136 goto out_error;
1137
1138out_eagain:
1139 ret = -EAGAIN;
1140 goto out_error;
1141
1142out_efault:
1143 ret = -EFAULT;
1144 goto out_error;
1145
1146out_error:
1147 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1148 return ret;
Thomas Gleixnere60cbc52014-06-11 20:45:39 +00001149}
1150
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001151/**
1152 * wait_for_owner_exiting - Block until the owner has exited
Randy Dunlap51bfb1d2019-12-08 20:26:55 -08001153 * @ret: owner's current futex lock status
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001154 * @exiting: Pointer to the exiting task
1155 *
1156 * Caller must hold a refcount on @exiting.
1157 */
1158static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1159{
1160 if (ret != -EBUSY) {
1161 WARN_ON_ONCE(exiting);
1162 return;
1163 }
1164
1165 if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
1166 return;
1167
1168 mutex_lock(&exiting->futex_exit_mutex);
1169 /*
1170 * No point in doing state checking here. If the waiter got here
1171 * while the task was in exec()->exec_futex_release() then it can
1172 * have any FUTEX_STATE_* value when the waiter has acquired the
1173 * mutex. OK, if running, EXITING or DEAD if it reached exit()
1174 * already. Highly unlikely and not a problem. Just one more round
1175 * through the futex maze.
1176 */
1177 mutex_unlock(&exiting->futex_exit_mutex);
1178
1179 put_task_struct(exiting);
1180}
1181
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001182static int handle_exit_race(u32 __user *uaddr, u32 uval,
1183 struct task_struct *tsk)
1184{
1185 u32 uval2;
1186
1187 /*
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01001188 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1189 * caller that the alleged owner is busy.
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001190 */
Thomas Gleixner3d4775d2019-11-06 22:55:37 +01001191 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01001192 return -EBUSY;
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001193
1194 /*
1195 * Reread the user space value to handle the following situation:
1196 *
1197 * CPU0 CPU1
1198 *
1199 * sys_exit() sys_futex()
1200 * do_exit() futex_lock_pi()
1201 * futex_lock_pi_atomic()
1202 * exit_signals(tsk) No waiters:
1203 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1204 * mm_release(tsk) Set waiter bit
1205 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1206 * Set owner died attach_to_pi_owner() {
1207 * *uaddr = 0xC0000000; tsk = get_task(PID);
1208 * } if (!tsk->flags & PF_EXITING) {
1209 * ... attach();
Thomas Gleixner3d4775d2019-11-06 22:55:37 +01001210 * tsk->futex_state = } else {
1211 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1212 * FUTEX_STATE_DEAD)
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001213 * return -EAGAIN;
1214 * return -ESRCH; <--- FAIL
1215 * }
1216 *
1217 * Returning ESRCH unconditionally is wrong here because the
1218 * user space value has been changed by the exiting task.
1219 *
1220 * The same logic applies to the case where the exiting task is
1221 * already gone.
1222 */
1223 if (get_futex_value_locked(&uval2, uaddr))
1224 return -EFAULT;
1225
1226 /* If the user space value has changed, try again. */
1227 if (uval2 != uval)
1228 return -EAGAIN;
1229
1230 /*
1231 * The exiting task did not have a robust list, the robust list was
1232 * corrupted or the user space value in *uaddr is simply bogus.
1233 * Give up and tell user space.
1234 */
1235 return -ESRCH;
1236}
1237
Thomas Gleixner34057652021-09-02 11:48:51 +02001238static void __attach_to_pi_owner(struct task_struct *p, union futex_key *key,
1239 struct futex_pi_state **ps)
1240{
1241 /*
1242 * No existing pi state. First waiter. [2]
1243 *
1244 * This creates pi_state, we have hb->lock held, this means nothing can
1245 * observe this state, wait_lock is irrelevant.
1246 */
1247 struct futex_pi_state *pi_state = alloc_pi_state();
1248
1249 /*
1250 * Initialize the pi_mutex in locked state and make @p
1251 * the owner of it:
1252 */
1253 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1254
1255 /* Store the key for possible exit cleanups: */
1256 pi_state->key = *key;
1257
1258 WARN_ON(!list_empty(&pi_state->list));
1259 list_add(&pi_state->list, &p->pi_state_list);
1260 /*
1261 * Assignment without holding pi_state->pi_mutex.wait_lock is safe
1262 * because there is no concurrency as the object is not published yet.
1263 */
1264 pi_state->owner = p;
1265
1266 *ps = pi_state;
1267}
Thomas Gleixner04e1b2e2014-06-11 20:45:40 +00001268/*
1269 * Lookup the task for the TID provided from user space and attach to
1270 * it after doing proper sanity checks.
1271 */
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001272static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001273 struct futex_pi_state **ps,
1274 struct task_struct **exiting)
Ingo Molnarc87e2832006-06-27 02:54:58 -07001275{
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001276 pid_t pid = uval & FUTEX_TID_MASK;
Thomas Gleixner04e1b2e2014-06-11 20:45:40 +00001277 struct task_struct *p;
Ingo Molnarc87e2832006-06-27 02:54:58 -07001278
1279 /*
Ingo Molnare3f2dde2006-07-29 05:17:57 +02001280 * We are the first waiter - try to look up the real owner and attach
Thomas Gleixner54a21782014-06-03 12:27:08 +00001281 * the new pi_state to it, but bail out when TID = 0 [1]
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001282 *
1283 * The !pid check is paranoid. None of the call sites should end up
1284 * with pid == 0, but better safe than sorry. Let the caller retry
Ingo Molnarc87e2832006-06-27 02:54:58 -07001285 */
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001286 if (!pid)
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001287 return -EAGAIN;
Mike Rapoport2ee08262018-02-06 15:40:17 -08001288 p = find_get_task_by_vpid(pid);
Michal Hocko7a0ea092010-06-30 09:51:19 +02001289 if (!p)
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001290 return handle_exit_race(uaddr, uval, NULL);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001291
Oleg Nesterova2129462015-02-02 15:05:36 +01001292 if (unlikely(p->flags & PF_KTHREAD)) {
Thomas Gleixnerf0d71b32014-05-12 20:45:35 +00001293 put_task_struct(p);
1294 return -EPERM;
1295 }
1296
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001297 /*
Thomas Gleixner3d4775d2019-11-06 22:55:37 +01001298 * We need to look at the task state to figure out, whether the
1299 * task is exiting. To protect against the change of the task state
1300 * in futex_exit_release(), we do this protected by p->pi_lock:
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001301 */
Thomas Gleixner1d615482009-11-17 14:54:03 +01001302 raw_spin_lock_irq(&p->pi_lock);
Thomas Gleixner3d4775d2019-11-06 22:55:37 +01001303 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001304 /*
Thomas Gleixner3d4775d2019-11-06 22:55:37 +01001305 * The task is on the way out. When the futex state is
1306 * FUTEX_STATE_DEAD, we know that the task has finished
1307 * the cleanup:
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001308 */
Thomas Gleixnerda791a62018-12-10 14:35:14 +01001309 int ret = handle_exit_race(uaddr, uval, p);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001310
Thomas Gleixner1d615482009-11-17 14:54:03 +01001311 raw_spin_unlock_irq(&p->pi_lock);
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001312 /*
1313 * If the owner task is between FUTEX_STATE_EXITING and
1314 * FUTEX_STATE_DEAD then store the task pointer and keep
1315 * the reference on the task struct. The calling code will
1316 * drop all locks, wait for the task to reach
1317 * FUTEX_STATE_DEAD and then drop the refcount. This is
1318 * required to prevent a live lock when the current task
1319 * preempted the exiting task between the two states.
1320 */
1321 if (ret == -EBUSY)
1322 *exiting = p;
1323 else
1324 put_task_struct(p);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001325 return ret;
1326 }
Ingo Molnarc87e2832006-06-27 02:54:58 -07001327
Thomas Gleixner34057652021-09-02 11:48:51 +02001328 __attach_to_pi_owner(p, key, ps);
Thomas Gleixner1d615482009-11-17 14:54:03 +01001329 raw_spin_unlock_irq(&p->pi_lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -07001330
1331 put_task_struct(p);
1332
Ingo Molnarc87e2832006-06-27 02:54:58 -07001333 return 0;
1334}
1335
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001336static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1337{
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001338 int err;
Kees Cook3f649ab2020-06-03 13:09:38 -07001339 u32 curval;
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001340
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07001341 if (unlikely(should_fail_futex(true)))
1342 return -EFAULT;
1343
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001344 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1345 if (unlikely(err))
1346 return err;
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001347
Peter Zijlstra734009e2017-03-22 11:35:52 +01001348 /* If user space value changed, let the caller retry */
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001349 return curval != uval ? -EAGAIN : 0;
1350}
1351
Darren Hart1a520842009-04-03 13:39:52 -07001352/**
Darren Hartd96ee562009-09-21 22:30:22 -07001353 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
Darren Hartbab5bc92009-04-07 23:23:50 -07001354 * @uaddr: the pi futex user address
1355 * @hb: the pi futex hash bucket
1356 * @key: the futex key associated with uaddr and hb
1357 * @ps: the pi_state pointer where we store the result of the
1358 * lookup
1359 * @task: the task to perform the atomic lock work for. This will
1360 * be "current" except in the case of requeue pi.
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001361 * @exiting: Pointer to store the task pointer of the owner task
1362 * which is in the middle of exiting
Darren Hartbab5bc92009-04-07 23:23:50 -07001363 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
Darren Hart1a520842009-04-03 13:39:52 -07001364 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08001365 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03001366 * - 0 - ready to wait;
1367 * - 1 - acquired the lock;
1368 * - <0 - error
Darren Hart1a520842009-04-03 13:39:52 -07001369 *
Thomas Gleixnerc363b7e2021-08-15 23:29:06 +02001370 * The hb->lock must be held by the caller.
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001371 *
1372 * @exiting is only set when the return value is -EBUSY. If so, this holds
1373 * a refcount on the exiting task on return and the caller needs to drop it
1374 * after waiting for the exit to complete.
Darren Hart1a520842009-04-03 13:39:52 -07001375 */
1376static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1377 union futex_key *key,
1378 struct futex_pi_state **ps,
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001379 struct task_struct *task,
1380 struct task_struct **exiting,
1381 int set_waiters)
Darren Hart1a520842009-04-03 13:39:52 -07001382{
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001383 u32 uval, newval, vpid = task_pid_vnr(task);
Peter Zijlstra499f5ac2017-03-22 11:35:48 +01001384 struct futex_q *top_waiter;
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001385 int ret;
Darren Hart1a520842009-04-03 13:39:52 -07001386
1387 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001388 * Read the user space value first so we can validate a few
1389 * things before proceeding further.
Darren Hart1a520842009-04-03 13:39:52 -07001390 */
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001391 if (get_futex_value_locked(&uval, uaddr))
Darren Hart1a520842009-04-03 13:39:52 -07001392 return -EFAULT;
1393
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07001394 if (unlikely(should_fail_futex(true)))
1395 return -EFAULT;
1396
Darren Hart1a520842009-04-03 13:39:52 -07001397 /*
1398 * Detect deadlocks.
1399 */
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001400 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
Darren Hart1a520842009-04-03 13:39:52 -07001401 return -EDEADLK;
1402
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07001403 if ((unlikely(should_fail_futex(true))))
1404 return -EDEADLK;
1405
Darren Hart1a520842009-04-03 13:39:52 -07001406 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001407 * Lookup existing state first. If it exists, try to attach to
1408 * its pi_state.
Darren Hart1a520842009-04-03 13:39:52 -07001409 */
Peter Zijlstra499f5ac2017-03-22 11:35:48 +01001410 top_waiter = futex_top_waiter(hb, key);
1411 if (top_waiter)
Peter Zijlstra734009e2017-03-22 11:35:52 +01001412 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001413
1414 /*
1415 * No waiter and user TID is 0. We are here because the
1416 * waiters or the owner died bit is set or called from
1417 * requeue_cmp_pi or for whatever reason something took the
1418 * syscall.
1419 */
1420 if (!(uval & FUTEX_TID_MASK)) {
Thomas Gleixnerb3eaa9f2014-06-03 12:27:06 +00001421 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001422 * We take over the futex. No other waiters and the user space
1423 * TID is 0. We preserve the owner died bit.
Thomas Gleixnerb3eaa9f2014-06-03 12:27:06 +00001424 */
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001425 newval = uval & FUTEX_OWNER_DIED;
1426 newval |= vpid;
1427
1428 /* The futex requeue_pi code can enforce the waiters bit */
1429 if (set_waiters)
1430 newval |= FUTEX_WAITERS;
1431
1432 ret = lock_pi_update_atomic(uaddr, uval, newval);
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02001433 if (ret)
1434 return ret;
1435
1436 /*
1437 * If the waiter bit was requested the caller also needs PI
1438 * state attached to the new owner of the user space futex.
1439 *
1440 * @task is guaranteed to be alive and it cannot be exiting
1441 * because it is either sleeping or waiting in
1442 * futex_requeue_pi_wakeup_sync().
Thomas Gleixner34057652021-09-02 11:48:51 +02001443 *
1444 * No need to do the full attach_to_pi_owner() exercise
1445 * because @task is known and valid.
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02001446 */
1447 if (set_waiters) {
Thomas Gleixner34057652021-09-02 11:48:51 +02001448 raw_spin_lock_irq(&task->pi_lock);
1449 __attach_to_pi_owner(task, key, ps);
1450 raw_spin_unlock_irq(&task->pi_lock);
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02001451 }
1452 return 1;
Thomas Gleixnerb3eaa9f2014-06-03 12:27:06 +00001453 }
Darren Hart1a520842009-04-03 13:39:52 -07001454
Darren Hart1a520842009-04-03 13:39:52 -07001455 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001456 * First waiter. Set the waiters bit before attaching ourself to
1457 * the owner. If owner tries to unlock, it will be forced into
1458 * the kernel and blocked on hb->lock.
Darren Hart1a520842009-04-03 13:39:52 -07001459 */
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001460 newval = uval | FUTEX_WAITERS;
1461 ret = lock_pi_update_atomic(uaddr, uval, newval);
1462 if (ret)
1463 return ret;
Darren Hart1a520842009-04-03 13:39:52 -07001464 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00001465 * If the update of the user space value succeeded, we try to
1466 * attach to the owner. If that fails, no harm done, we only
1467 * set the FUTEX_WAITERS bit in the user space variable.
Darren Hart1a520842009-04-03 13:39:52 -07001468 */
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001469 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
Darren Hart1a520842009-04-03 13:39:52 -07001470}
1471
Lai Jiangshan2e129782010-12-22 14:18:50 +08001472/**
1473 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1474 * @q: The futex_q to unqueue
1475 *
1476 * The q->lock_ptr must not be NULL and must be held by the caller.
1477 */
1478static void __unqueue_futex(struct futex_q *q)
1479{
1480 struct futex_hash_bucket *hb;
1481
Lance Roy4de1a292018-10-02 22:38:57 -07001482 if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
Lai Jiangshan2e129782010-12-22 14:18:50 +08001483 return;
Lance Roy4de1a292018-10-02 22:38:57 -07001484 lockdep_assert_held(q->lock_ptr);
Lai Jiangshan2e129782010-12-22 14:18:50 +08001485
1486 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1487 plist_del(&q->list, &hb->chain);
Linus Torvalds11d46162014-03-20 22:11:17 -07001488 hb_waiters_dec(hb);
Lai Jiangshan2e129782010-12-22 14:18:50 +08001489}
1490
Ingo Molnarc87e2832006-06-27 02:54:58 -07001491/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001492 * The hash bucket lock must be held when this is called.
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001493 * Afterwards, the futex_q must not be accessed. Callers
1494 * must ensure to later call wake_up_q() for the actual
1495 * wakeups to occur.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001496 */
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001497static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001498{
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02001499 struct task_struct *p = q->task;
1500
Darren Hartaa109902012-11-26 16:29:56 -08001501 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1502 return;
1503
Peter Zijlstrab061c382018-11-29 14:44:49 +01001504 get_task_struct(p);
Lai Jiangshan2e129782010-12-22 14:18:50 +08001505 __unqueue_futex(q);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001506 /*
Darren Hart (VMware)38fcd062017-04-14 15:31:38 -07001507 * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
1508 * is written, without taking any locks. This is possible in the event
1509 * of a spurious wakeup, for example. A memory barrier is required here
1510 * to prevent the following store to lock_ptr from getting ahead of the
1511 * plist_del in __unqueue_futex().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001512 */
Peter Zijlstra1b367ec2017-03-22 11:35:49 +01001513 smp_store_release(&q->lock_ptr, NULL);
Peter Zijlstrab061c382018-11-29 14:44:49 +01001514
1515 /*
1516 * Queue the task for later wakeup for after we've released
Davidlohr Bueso75145902019-10-22 20:34:50 -07001517 * the hb->lock.
Peter Zijlstrab061c382018-11-29 14:44:49 +01001518 */
Davidlohr Bueso07879c62018-12-18 11:53:52 -08001519 wake_q_add_safe(wake_q, p);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520}
1521
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001522/*
1523 * Caller must hold a reference on @pi_state.
1524 */
1525static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
Ingo Molnarc87e2832006-06-27 02:54:58 -07001526{
Davidlohr Bueso9a4b99f2021-02-26 09:50:26 -08001527 struct rt_mutex_waiter *top_waiter;
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001528 struct task_struct *new_owner;
Peter Zijlstraaa2bfe52017-03-23 15:56:10 +01001529 bool postunlock = false;
Thomas Gleixner7980aa32021-08-15 23:28:09 +02001530 DEFINE_RT_WAKE_Q(wqh);
1531 u32 curval, newval;
Thomas Gleixner13fbca42014-06-03 12:27:07 +00001532 int ret = 0;
Ingo Molnarc87e2832006-06-27 02:54:58 -07001533
Davidlohr Bueso9a4b99f2021-02-26 09:50:26 -08001534 top_waiter = rt_mutex_top_waiter(&pi_state->pi_mutex);
1535 if (WARN_ON_ONCE(!top_waiter)) {
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001536 /*
Peter Zijlstrabebe5b52017-03-22 11:35:59 +01001537 * As per the comment in futex_unlock_pi() this should not happen.
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001538 *
1539 * When this happens, give up our locks and try again, giving
1540 * the futex_lock_pi() instance time to complete, either by
1541 * waiting on the rtmutex or removing itself from the futex
1542 * queue.
1543 */
1544 ret = -EAGAIN;
1545 goto out_unlock;
Peter Zijlstra73d786b2017-03-22 11:35:54 +01001546 }
Ingo Molnarc87e2832006-06-27 02:54:58 -07001547
Davidlohr Bueso9a4b99f2021-02-26 09:50:26 -08001548 new_owner = top_waiter->task;
1549
Ingo Molnarc87e2832006-06-27 02:54:58 -07001550 /*
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001551 * We pass it to the next owner. The WAITERS bit is always kept
1552 * enabled while there is PI state around. We cleanup the owner
1553 * died bit, because we are the owner.
Ingo Molnarc87e2832006-06-27 02:54:58 -07001554 */
Thomas Gleixner13fbca42014-06-03 12:27:07 +00001555 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07001556
Mateusz Nosek921c7eb2020-09-27 02:08:58 +02001557 if (unlikely(should_fail_futex(true))) {
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07001558 ret = -EFAULT;
Mateusz Nosek921c7eb2020-09-27 02:08:58 +02001559 goto out_unlock;
1560 }
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07001561
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001562 ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1563 if (!ret && (curval != uval)) {
Sebastian Andrzej Siewior89e9e662016-04-15 14:35:39 +02001564 /*
1565 * If a unconditional UNLOCK_PI operation (user space did not
1566 * try the TID->0 transition) raced with a waiter setting the
1567 * FUTEX_WAITERS flag between get_user() and locking the hash
1568 * bucket lock, retry the operation.
1569 */
1570 if ((FUTEX_TID_MASK & curval) == uval)
1571 ret = -EAGAIN;
1572 else
1573 ret = -EINVAL;
1574 }
Peter Zijlstra734009e2017-03-22 11:35:52 +01001575
Thomas Gleixnerc5cade22021-01-19 15:21:35 +01001576 if (!ret) {
1577 /*
1578 * This is a point of no return; once we modified the uval
1579 * there is no going back and subsequent operations must
1580 * not fail.
1581 */
1582 pi_state_update_owner(pi_state, new_owner);
Thomas Gleixner7980aa32021-08-15 23:28:09 +02001583 postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wqh);
Thomas Gleixnerc5cade22021-01-19 15:21:35 +01001584 }
Peter Zijlstra5293c2e2017-03-22 11:35:51 +01001585
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001586out_unlock:
Peter Zijlstra5293c2e2017-03-22 11:35:51 +01001587 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
Peter Zijlstra5293c2e2017-03-22 11:35:51 +01001588
Peter Zijlstraaa2bfe52017-03-23 15:56:10 +01001589 if (postunlock)
Thomas Gleixner7980aa32021-08-15 23:28:09 +02001590 rt_mutex_postunlock(&wqh);
Ingo Molnarc87e2832006-06-27 02:54:58 -07001591
Peter Zijlstra16ffa122017-03-22 11:35:55 +01001592 return ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07001593}
1594
Linus Torvalds1da177e2005-04-16 15:20:36 -07001595/*
Ingo Molnar8b8f3192006-07-03 00:25:05 -07001596 * Express the locking dependencies for lockdep:
1597 */
1598static inline void
1599double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1600{
1601 if (hb1 <= hb2) {
1602 spin_lock(&hb1->lock);
1603 if (hb1 < hb2)
1604 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1605 } else { /* hb1 > hb2 */
1606 spin_lock(&hb2->lock);
1607 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1608 }
1609}
1610
Darren Hart5eb3dc62009-03-12 00:55:52 -07001611static inline void
1612double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1613{
Darren Hartf061d352009-03-12 15:11:18 -07001614 spin_unlock(&hb1->lock);
Ingo Molnar88f502f2009-03-13 10:32:07 +01001615 if (hb1 != hb2)
1616 spin_unlock(&hb2->lock);
Darren Hart5eb3dc62009-03-12 00:55:52 -07001617}
1618
Ingo Molnar8b8f3192006-07-03 00:25:05 -07001619/*
Darren Hartb2d09942009-03-12 00:55:37 -07001620 * Wake up waiters matching bitset queued on this futex (uaddr).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001621 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03001622int futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001623{
Ingo Molnare2970f22006-06-27 02:54:47 -07001624 struct futex_hash_bucket *hb;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 struct futex_q *this, *next;
Peter Zijlstra38d47c12008-09-26 19:32:20 +02001626 union futex_key key = FUTEX_KEY_INIT;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001627 int ret;
Waiman Long194a6b52016-11-17 11:46:38 -05001628 DEFINE_WAKE_Q(wake_q);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629
Thomas Gleixnercd689982008-02-01 17:45:14 +01001630 if (!bitset)
1631 return -EINVAL;
1632
Linus Torvalds96d4f262019-01-03 18:57:57 -08001633 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_READ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001634 if (unlikely(ret != 0))
André Almeidad7c5ed72020-07-02 17:28:41 -03001635 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001636
Ingo Molnare2970f22006-06-27 02:54:47 -07001637 hb = hash_futex(&key);
Davidlohr Buesob0c29f72014-01-12 15:31:25 -08001638
1639 /* Make sure we really have tasks to wakeup */
1640 if (!hb_waiters_pending(hb))
André Almeidad7c5ed72020-07-02 17:28:41 -03001641 return ret;
Davidlohr Buesob0c29f72014-01-12 15:31:25 -08001642
Ingo Molnare2970f22006-06-27 02:54:47 -07001643 spin_lock(&hb->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001644
Jason Low0d00c7b2014-01-12 15:31:22 -08001645 plist_for_each_entry_safe(this, next, &hb->chain, list) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646 if (match_futex (&this->key, &key)) {
Darren Hart52400ba2009-04-03 13:40:49 -07001647 if (this->pi_state || this->rt_waiter) {
Ingo Molnared6f7b12006-07-01 04:35:46 -07001648 ret = -EINVAL;
1649 break;
1650 }
Thomas Gleixnercd689982008-02-01 17:45:14 +01001651
1652 /* Check if one of the bits is set in both bitsets */
1653 if (!(this->bitset & bitset))
1654 continue;
1655
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001656 mark_wake_futex(&wake_q, this);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001657 if (++ret >= nr_wake)
1658 break;
1659 }
1660 }
1661
Ingo Molnare2970f22006-06-27 02:54:47 -07001662 spin_unlock(&hb->lock);
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001663 wake_up_q(&wake_q);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001664 return ret;
1665}
1666
Jiri Slaby30d6e0a2017-08-24 09:31:05 +02001667static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1668{
1669 unsigned int op = (encoded_op & 0x70000000) >> 28;
1670 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
Jiri Slabyd70ef222017-11-30 15:35:44 +01001671 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1672 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
Jiri Slaby30d6e0a2017-08-24 09:31:05 +02001673 int oldval, ret;
1674
1675 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
Jiri Slabye78c38f62017-10-23 13:41:51 +02001676 if (oparg < 0 || oparg > 31) {
1677 char comm[sizeof(current->comm)];
1678 /*
1679 * kill this print and return -EINVAL when userspace
1680 * is sane again
1681 */
1682 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1683 get_task_comm(comm, current), oparg);
1684 oparg &= 31;
1685 }
Jiri Slaby30d6e0a2017-08-24 09:31:05 +02001686 oparg = 1 << oparg;
1687 }
1688
Al Viroa08971e2020-02-16 10:17:27 -05001689 pagefault_disable();
Jiri Slaby30d6e0a2017-08-24 09:31:05 +02001690 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
Al Viroa08971e2020-02-16 10:17:27 -05001691 pagefault_enable();
Jiri Slaby30d6e0a2017-08-24 09:31:05 +02001692 if (ret)
1693 return ret;
1694
1695 switch (cmp) {
1696 case FUTEX_OP_CMP_EQ:
1697 return oldval == cmparg;
1698 case FUTEX_OP_CMP_NE:
1699 return oldval != cmparg;
1700 case FUTEX_OP_CMP_LT:
1701 return oldval < cmparg;
1702 case FUTEX_OP_CMP_GE:
1703 return oldval >= cmparg;
1704 case FUTEX_OP_CMP_LE:
1705 return oldval <= cmparg;
1706 case FUTEX_OP_CMP_GT:
1707 return oldval > cmparg;
1708 default:
1709 return -ENOSYS;
1710 }
1711}
1712
Linus Torvalds1da177e2005-04-16 15:20:36 -07001713/*
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001714 * Wake up all waiters hashed on the physical page that is mapped
1715 * to this virtual address:
1716 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03001717int futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
1718 int nr_wake, int nr_wake2, int op)
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001719{
Peter Zijlstra38d47c12008-09-26 19:32:20 +02001720 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
Ingo Molnare2970f22006-06-27 02:54:47 -07001721 struct futex_hash_bucket *hb1, *hb2;
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001722 struct futex_q *this, *next;
Darren Harte4dc5b72009-03-12 00:56:13 -07001723 int ret, op_ret;
Waiman Long194a6b52016-11-17 11:46:38 -05001724 DEFINE_WAKE_Q(wake_q);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001725
Darren Harte4dc5b72009-03-12 00:56:13 -07001726retry:
Linus Torvalds96d4f262019-01-03 18:57:57 -08001727 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001728 if (unlikely(ret != 0))
André Almeidad7c5ed72020-07-02 17:28:41 -03001729 return ret;
Linus Torvalds96d4f262019-01-03 18:57:57 -08001730 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001731 if (unlikely(ret != 0))
André Almeidad7c5ed72020-07-02 17:28:41 -03001732 return ret;
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001733
Ingo Molnare2970f22006-06-27 02:54:47 -07001734 hb1 = hash_futex(&key1);
1735 hb2 = hash_futex(&key2);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001736
Darren Harte4dc5b72009-03-12 00:56:13 -07001737retry_private:
Thomas Gleixnereaaea802009-10-04 09:34:17 +02001738 double_lock_hb(hb1, hb2);
Ingo Molnare2970f22006-06-27 02:54:47 -07001739 op_ret = futex_atomic_op_inuser(op, uaddr2);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001740 if (unlikely(op_ret < 0)) {
Darren Hart5eb3dc62009-03-12 00:55:52 -07001741 double_unlock_hb(hb1, hb2);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001742
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001743 if (!IS_ENABLED(CONFIG_MMU) ||
1744 unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
1745 /*
1746 * we don't get EFAULT from MMU faults if we don't have
1747 * an MMU, but we might get them from range checking
1748 */
David Gibson796f8d92005-11-07 00:59:33 -08001749 ret = op_ret;
André Almeidad7c5ed72020-07-02 17:28:41 -03001750 return ret;
David Gibson796f8d92005-11-07 00:59:33 -08001751 }
1752
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001753 if (op_ret == -EFAULT) {
1754 ret = fault_in_user_writeable(uaddr2);
1755 if (ret)
André Almeidad7c5ed72020-07-02 17:28:41 -03001756 return ret;
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001757 }
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001758
Will Deacon6b4f4bc2019-02-28 11:58:08 +00001759 cond_resched();
Pavel Begunkova82adc72021-05-17 14:30:12 +01001760 if (!(flags & FLAGS_SHARED))
1761 goto retry_private;
Darren Harte4dc5b72009-03-12 00:56:13 -07001762 goto retry;
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001763 }
1764
Jason Low0d00c7b2014-01-12 15:31:22 -08001765 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001766 if (match_futex (&this->key, &key1)) {
Darren Hartaa109902012-11-26 16:29:56 -08001767 if (this->pi_state || this->rt_waiter) {
1768 ret = -EINVAL;
1769 goto out_unlock;
1770 }
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001771 mark_wake_futex(&wake_q, this);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001772 if (++ret >= nr_wake)
1773 break;
1774 }
1775 }
1776
1777 if (op_ret > 0) {
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001778 op_ret = 0;
Jason Low0d00c7b2014-01-12 15:31:22 -08001779 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001780 if (match_futex (&this->key, &key2)) {
Darren Hartaa109902012-11-26 16:29:56 -08001781 if (this->pi_state || this->rt_waiter) {
1782 ret = -EINVAL;
1783 goto out_unlock;
1784 }
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001785 mark_wake_futex(&wake_q, this);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001786 if (++op_ret >= nr_wake2)
1787 break;
1788 }
1789 }
1790 ret += op_ret;
1791 }
1792
Darren Hartaa109902012-11-26 16:29:56 -08001793out_unlock:
Darren Hart5eb3dc62009-03-12 00:55:52 -07001794 double_unlock_hb(hb1, hb2);
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07001795 wake_up_q(&wake_q);
Jakub Jelinek4732efbe2005-09-06 15:16:25 -07001796 return ret;
1797}
1798
Darren Hart9121e472009-04-03 13:40:31 -07001799/**
1800 * requeue_futex() - Requeue a futex_q from one hb to another
1801 * @q: the futex_q to requeue
1802 * @hb1: the source hash_bucket
1803 * @hb2: the target hash_bucket
1804 * @key2: the new key for the requeued futex_q
1805 */
1806static inline
1807void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1808 struct futex_hash_bucket *hb2, union futex_key *key2)
1809{
1810
1811 /*
1812 * If key1 and key2 hash to the same bucket, no need to
1813 * requeue.
1814 */
1815 if (likely(&hb1->chain != &hb2->chain)) {
1816 plist_del(&q->list, &hb1->chain);
Linus Torvalds11d46162014-03-20 22:11:17 -07001817 hb_waiters_dec(hb1);
Linus Torvalds11d46162014-03-20 22:11:17 -07001818 hb_waiters_inc(hb2);
Davidlohr Buesofe1bce92016-04-20 20:09:24 -07001819 plist_add(&q->list, &hb2->chain);
Darren Hart9121e472009-04-03 13:40:31 -07001820 q->lock_ptr = &hb2->lock;
Darren Hart9121e472009-04-03 13:40:31 -07001821 }
Darren Hart9121e472009-04-03 13:40:31 -07001822 q->key = *key2;
1823}
1824
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02001825static inline bool futex_requeue_pi_prepare(struct futex_q *q,
1826 struct futex_pi_state *pi_state)
1827{
1828 int old, new;
1829
1830 /*
1831 * Set state to Q_REQUEUE_PI_IN_PROGRESS unless an early wakeup has
1832 * already set Q_REQUEUE_PI_IGNORE to signal that requeue should
1833 * ignore the waiter.
1834 */
1835 old = atomic_read_acquire(&q->requeue_state);
1836 do {
1837 if (old == Q_REQUEUE_PI_IGNORE)
1838 return false;
1839
1840 /*
1841 * futex_proxy_trylock_atomic() might have set it to
1842 * IN_PROGRESS and a interleaved early wake to WAIT.
1843 *
1844 * It was considered to have an extra state for that
1845 * trylock, but that would just add more conditionals
1846 * all over the place for a dubious value.
1847 */
1848 if (old != Q_REQUEUE_PI_NONE)
1849 break;
1850
1851 new = Q_REQUEUE_PI_IN_PROGRESS;
1852 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1853
1854 q->pi_state = pi_state;
1855 return true;
1856}
1857
1858static inline void futex_requeue_pi_complete(struct futex_q *q, int locked)
1859{
1860 int old, new;
1861
1862 old = atomic_read_acquire(&q->requeue_state);
1863 do {
1864 if (old == Q_REQUEUE_PI_IGNORE)
1865 return;
1866
1867 if (locked >= 0) {
1868 /* Requeue succeeded. Set DONE or LOCKED */
1869 WARN_ON_ONCE(old != Q_REQUEUE_PI_IN_PROGRESS &&
1870 old != Q_REQUEUE_PI_WAIT);
1871 new = Q_REQUEUE_PI_DONE + locked;
1872 } else if (old == Q_REQUEUE_PI_IN_PROGRESS) {
1873 /* Deadlock, no early wakeup interleave */
1874 new = Q_REQUEUE_PI_NONE;
1875 } else {
1876 /* Deadlock, early wakeup interleave. */
1877 WARN_ON_ONCE(old != Q_REQUEUE_PI_WAIT);
1878 new = Q_REQUEUE_PI_IGNORE;
1879 }
1880 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1881
1882#ifdef CONFIG_PREEMPT_RT
1883 /* If the waiter interleaved with the requeue let it know */
1884 if (unlikely(old == Q_REQUEUE_PI_WAIT))
1885 rcuwait_wake_up(&q->requeue_wait);
1886#endif
1887}
1888
1889static inline int futex_requeue_pi_wakeup_sync(struct futex_q *q)
1890{
1891 int old, new;
1892
1893 old = atomic_read_acquire(&q->requeue_state);
1894 do {
1895 /* Is requeue done already? */
1896 if (old >= Q_REQUEUE_PI_DONE)
1897 return old;
1898
1899 /*
1900 * If not done, then tell the requeue code to either ignore
1901 * the waiter or to wake it up once the requeue is done.
1902 */
1903 new = Q_REQUEUE_PI_WAIT;
1904 if (old == Q_REQUEUE_PI_NONE)
1905 new = Q_REQUEUE_PI_IGNORE;
1906 } while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
1907
1908 /* If the requeue was in progress, wait for it to complete */
1909 if (old == Q_REQUEUE_PI_IN_PROGRESS) {
1910#ifdef CONFIG_PREEMPT_RT
1911 rcuwait_wait_event(&q->requeue_wait,
1912 atomic_read(&q->requeue_state) != Q_REQUEUE_PI_WAIT,
1913 TASK_UNINTERRUPTIBLE);
1914#else
1915 (void)atomic_cond_read_relaxed(&q->requeue_state, VAL != Q_REQUEUE_PI_WAIT);
1916#endif
1917 }
1918
1919 /*
1920 * Requeue is now either prohibited or complete. Reread state
1921 * because during the wait above it might have changed. Nothing
1922 * will modify q->requeue_state after this point.
1923 */
1924 return atomic_read(&q->requeue_state);
1925}
1926
Darren Hart52400ba2009-04-03 13:40:49 -07001927/**
1928 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
Darren Hartd96ee562009-09-21 22:30:22 -07001929 * @q: the futex_q
1930 * @key: the key of the requeue target futex
1931 * @hb: the hash_bucket of the requeue target futex
Darren Hart52400ba2009-04-03 13:40:49 -07001932 *
1933 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
Thomas Gleixner249955e2021-09-02 11:48:50 +02001934 * target futex if it is uncontended or via a lock steal.
1935 *
1936 * 1) Set @q::key to the requeue target futex key so the waiter can detect
1937 * the wakeup on the right futex.
1938 *
1939 * 2) Dequeue @q from the hash bucket.
1940 *
1941 * 3) Set @q::rt_waiter to NULL so the woken up task can detect atomic lock
1942 * acquisition.
1943 *
1944 * 4) Set the q->lock_ptr to the requeue target hb->lock for the case that
1945 * the waiter has to fixup the pi state.
1946 *
1947 * 5) Complete the requeue state so the waiter can make progress. After
1948 * this point the waiter task can return from the syscall immediately in
1949 * case that the pi state does not have to be fixed up.
1950 *
1951 * 6) Wake the waiter task.
1952 *
1953 * Must be called with both q->lock_ptr and hb->lock held.
Darren Hart52400ba2009-04-03 13:40:49 -07001954 */
1955static inline
Darren Hartbeda2c72009-08-09 15:34:39 -07001956void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1957 struct futex_hash_bucket *hb)
Darren Hart52400ba2009-04-03 13:40:49 -07001958{
Darren Hart52400ba2009-04-03 13:40:49 -07001959 q->key = *key;
1960
Lai Jiangshan2e129782010-12-22 14:18:50 +08001961 __unqueue_futex(q);
Darren Hart52400ba2009-04-03 13:40:49 -07001962
1963 WARN_ON(!q->rt_waiter);
1964 q->rt_waiter = NULL;
1965
Darren Hartbeda2c72009-08-09 15:34:39 -07001966 q->lock_ptr = &hb->lock;
Darren Hartbeda2c72009-08-09 15:34:39 -07001967
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02001968 /* Signal locked state to the waiter */
1969 futex_requeue_pi_complete(q, 1);
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02001970 wake_up_state(q->task, TASK_NORMAL);
Darren Hart52400ba2009-04-03 13:40:49 -07001971}
1972
1973/**
1974 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
Darren Hartbab5bc92009-04-07 23:23:50 -07001975 * @pifutex: the user address of the to futex
1976 * @hb1: the from futex hash bucket, must be locked by the caller
1977 * @hb2: the to futex hash bucket, must be locked by the caller
1978 * @key1: the from futex key
1979 * @key2: the to futex key
1980 * @ps: address to store the pi_state pointer
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001981 * @exiting: Pointer to store the task pointer of the owner task
1982 * which is in the middle of exiting
Darren Hartbab5bc92009-04-07 23:23:50 -07001983 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
Darren Hart52400ba2009-04-03 13:40:49 -07001984 *
1985 * Try and get the lock on behalf of the top waiter if we can do it atomically.
Darren Hartbab5bc92009-04-07 23:23:50 -07001986 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1987 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1988 * hb1 and hb2 must be held by the caller.
Darren Hart52400ba2009-04-03 13:40:49 -07001989 *
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001990 * @exiting is only set when the return value is -EBUSY. If so, this holds
1991 * a refcount on the exiting task on return and the caller needs to drop it
1992 * after waiting for the exit to complete.
1993 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08001994 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03001995 * - 0 - failed to acquire the lock atomically;
1996 * - >0 - acquired the lock, return value is vpid of the top_waiter
1997 * - <0 - error
Darren Hart52400ba2009-04-03 13:40:49 -07001998 */
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01001999static int
2000futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
2001 struct futex_hash_bucket *hb2, union futex_key *key1,
2002 union futex_key *key2, struct futex_pi_state **ps,
2003 struct task_struct **exiting, int set_waiters)
Darren Hart52400ba2009-04-03 13:40:49 -07002004{
Darren Hartbab5bc92009-04-07 23:23:50 -07002005 struct futex_q *top_waiter = NULL;
Darren Hart52400ba2009-04-03 13:40:49 -07002006 u32 curval;
Thomas Gleixnerd66e3ed2021-09-03 22:47:06 +02002007 int ret;
Darren Hart52400ba2009-04-03 13:40:49 -07002008
2009 if (get_futex_value_locked(&curval, pifutex))
2010 return -EFAULT;
2011
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07002012 if (unlikely(should_fail_futex(true)))
2013 return -EFAULT;
2014
Darren Hartbab5bc92009-04-07 23:23:50 -07002015 /*
2016 * Find the top_waiter and determine if there are additional waiters.
2017 * If the caller intends to requeue more than 1 waiter to pifutex,
2018 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
2019 * as we have means to handle the possible fault. If not, don't set
Ingo Molnar93d09552021-05-12 20:04:28 +02002020 * the bit unnecessarily as it will force the subsequent unlock to enter
Darren Hartbab5bc92009-04-07 23:23:50 -07002021 * the kernel.
2022 */
Darren Hart52400ba2009-04-03 13:40:49 -07002023 top_waiter = futex_top_waiter(hb1, key1);
2024
2025 /* There are no waiters, nothing for us to do. */
2026 if (!top_waiter)
2027 return 0;
2028
Thomas Gleixnerdc7109a2021-08-15 23:29:04 +02002029 /*
2030 * Ensure that this is a waiter sitting in futex_wait_requeue_pi()
2031 * and waiting on the 'waitqueue' futex which is always !PI.
2032 */
2033 if (!top_waiter->rt_waiter || top_waiter->pi_state)
Colin Ian Kinga974b542021-08-18 14:18:40 +01002034 return -EINVAL;
Thomas Gleixnerdc7109a2021-08-15 23:29:04 +02002035
Darren Hart84bc4af2009-08-13 17:36:53 -07002036 /* Ensure we requeue to the expected futex. */
2037 if (!match_futex(top_waiter->requeue_pi_key, key2))
2038 return -EINVAL;
2039
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002040 /* Ensure that this does not race against an early wakeup */
2041 if (!futex_requeue_pi_prepare(top_waiter, NULL))
2042 return -EAGAIN;
2043
Darren Hart52400ba2009-04-03 13:40:49 -07002044 /*
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002045 * Try to take the lock for top_waiter and set the FUTEX_WAITERS bit
2046 * in the contended case or if @set_waiters is true.
2047 *
2048 * In the contended case PI state is attached to the lock owner. If
2049 * the user space lock can be acquired then PI state is attached to
2050 * the new owner (@top_waiter->task) when @set_waiters is true.
Darren Hart52400ba2009-04-03 13:40:49 -07002051 */
Darren Hartbab5bc92009-04-07 23:23:50 -07002052 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01002053 exiting, set_waiters);
Thomas Gleixner866293e2014-05-12 20:45:34 +00002054 if (ret == 1) {
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002055 /*
2056 * Lock was acquired in user space and PI state was
2057 * attached to @top_waiter->task. That means state is fully
2058 * consistent and the waiter can return to user space
2059 * immediately after the wakeup.
2060 */
Darren Hartbeda2c72009-08-09 15:34:39 -07002061 requeue_pi_wake_futex(top_waiter, key2, hb2);
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002062 } else if (ret < 0) {
2063 /* Rewind top_waiter::requeue_state */
2064 futex_requeue_pi_complete(top_waiter, ret);
2065 } else {
2066 /*
2067 * futex_lock_pi_atomic() did not acquire the user space
2068 * futex, but managed to establish the proxy lock and pi
2069 * state. top_waiter::requeue_state cannot be fixed up here
2070 * because the waiter is not enqueued on the rtmutex
2071 * yet. This is handled at the callsite depending on the
2072 * result of rt_mutex_start_proxy_lock() which is
2073 * guaranteed to be reached with this function returning 0.
2074 */
Thomas Gleixner866293e2014-05-12 20:45:34 +00002075 }
Darren Hart52400ba2009-04-03 13:40:49 -07002076 return ret;
2077}
2078
2079/**
2080 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
Randy Dunlapfb62db22010-10-13 11:02:34 -07002081 * @uaddr1: source futex user address
Darren Hartb41277d2010-11-08 13:10:09 -08002082 * @flags: futex flags (FLAGS_SHARED, etc.)
Randy Dunlapfb62db22010-10-13 11:02:34 -07002083 * @uaddr2: target futex user address
2084 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
2085 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
2086 * @cmpval: @uaddr1 expected value (or %NULL)
2087 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
Darren Hartb41277d2010-11-08 13:10:09 -08002088 * pi futex (pi to pi requeue is not supported)
Darren Hart52400ba2009-04-03 13:40:49 -07002089 *
2090 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
2091 * uaddr2 atomically on behalf of the top waiter.
2092 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08002093 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03002094 * - >=0 - on success, the number of tasks requeued or woken;
2095 * - <0 - on error
Linus Torvalds1da177e2005-04-16 15:20:36 -07002096 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03002097int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
2098 int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002099{
Peter Zijlstra38d47c12008-09-26 19:32:20 +02002100 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
Peter Zijlstra4b39f992020-03-04 13:24:24 +01002101 int task_count = 0, ret;
Darren Hart52400ba2009-04-03 13:40:49 -07002102 struct futex_pi_state *pi_state = NULL;
Ingo Molnare2970f22006-06-27 02:54:47 -07002103 struct futex_hash_bucket *hb1, *hb2;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002104 struct futex_q *this, *next;
Waiman Long194a6b52016-11-17 11:46:38 -05002105 DEFINE_WAKE_Q(wake_q);
Darren Hart52400ba2009-04-03 13:40:49 -07002106
Li Jinyuefbe0e832017-12-14 17:04:54 +08002107 if (nr_wake < 0 || nr_requeue < 0)
2108 return -EINVAL;
2109
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -04002110 /*
2111 * When PI not supported: return -ENOSYS if requeue_pi is true,
2112 * consequently the compiler knows requeue_pi is always false past
2113 * this point which will optimize away all the conditional code
2114 * further down.
2115 */
2116 if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
2117 return -ENOSYS;
2118
Darren Hart52400ba2009-04-03 13:40:49 -07002119 if (requeue_pi) {
2120 /*
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00002121 * Requeue PI only works on two distinct uaddrs. This
2122 * check is only valid for private futexes. See below.
2123 */
2124 if (uaddr1 == uaddr2)
2125 return -EINVAL;
2126
2127 /*
Thomas Gleixnerc18eaa32021-08-15 23:29:14 +02002128 * futex_requeue() allows the caller to define the number
2129 * of waiters to wake up via the @nr_wake argument. With
2130 * REQUEUE_PI, waking up more than one waiter is creating
2131 * more problems than it solves. Waking up a waiter makes
2132 * only sense if the PI futex @uaddr2 is uncontended as
2133 * this allows the requeue code to acquire the futex
2134 * @uaddr2 before waking the waiter. The waiter can then
2135 * return to user space without further action. A secondary
2136 * wakeup would just make the futex_wait_requeue_pi()
2137 * handling more complex, because that code would have to
2138 * look up pi_state and do more or less all the handling
2139 * which the requeue code has to do for the to be requeued
2140 * waiters. So restrict the number of waiters to wake to
2141 * one, and only wake it up when the PI futex is
2142 * uncontended. Otherwise requeue it and let the unlock of
2143 * the PI futex handle the wakeup.
2144 *
2145 * All REQUEUE_PI users, e.g. pthread_cond_signal() and
2146 * pthread_cond_broadcast() must use nr_wake=1.
Darren Hart52400ba2009-04-03 13:40:49 -07002147 */
2148 if (nr_wake != 1)
2149 return -EINVAL;
Thomas Gleixnerd69cba52021-08-15 23:29:15 +02002150
2151 /*
2152 * requeue_pi requires a pi_state, try to allocate it now
2153 * without any locks in case it fails.
2154 */
2155 if (refill_pi_state_cache())
2156 return -ENOMEM;
Darren Hart52400ba2009-04-03 13:40:49 -07002157 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002158
Darren Hart42d35d42008-12-29 15:49:53 -08002159retry:
Linus Torvalds96d4f262019-01-03 18:57:57 -08002160 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002161 if (unlikely(ret != 0))
André Almeidad7c5ed72020-07-02 17:28:41 -03002162 return ret;
Shawn Bohrer9ea71502011-06-30 11:21:32 -05002163 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
Linus Torvalds96d4f262019-01-03 18:57:57 -08002164 requeue_pi ? FUTEX_WRITE : FUTEX_READ);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002165 if (unlikely(ret != 0))
André Almeidad7c5ed72020-07-02 17:28:41 -03002166 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002167
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00002168 /*
2169 * The check above which compares uaddrs is not sufficient for
2170 * shared futexes. We need to compare the keys:
2171 */
André Almeidad7c5ed72020-07-02 17:28:41 -03002172 if (requeue_pi && match_futex(&key1, &key2))
2173 return -EINVAL;
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00002174
Ingo Molnare2970f22006-06-27 02:54:47 -07002175 hb1 = hash_futex(&key1);
2176 hb2 = hash_futex(&key2);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002177
Darren Harte4dc5b72009-03-12 00:56:13 -07002178retry_private:
Linus Torvalds69cd9eb2014-04-08 15:30:07 -07002179 hb_waiters_inc(hb2);
Ingo Molnar8b8f3192006-07-03 00:25:05 -07002180 double_lock_hb(hb1, hb2);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002181
Ingo Molnare2970f22006-06-27 02:54:47 -07002182 if (likely(cmpval != NULL)) {
2183 u32 curval;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002184
Ingo Molnare2970f22006-06-27 02:54:47 -07002185 ret = get_futex_value_locked(&curval, uaddr1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002186
2187 if (unlikely(ret)) {
Darren Hart5eb3dc62009-03-12 00:55:52 -07002188 double_unlock_hb(hb1, hb2);
Linus Torvalds69cd9eb2014-04-08 15:30:07 -07002189 hb_waiters_dec(hb2);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002190
Darren Harte4dc5b72009-03-12 00:56:13 -07002191 ret = get_user(curval, uaddr1);
2192 if (ret)
André Almeidad7c5ed72020-07-02 17:28:41 -03002193 return ret;
Darren Harte4dc5b72009-03-12 00:56:13 -07002194
Darren Hartb41277d2010-11-08 13:10:09 -08002195 if (!(flags & FLAGS_SHARED))
Darren Harte4dc5b72009-03-12 00:56:13 -07002196 goto retry_private;
2197
Darren Harte4dc5b72009-03-12 00:56:13 -07002198 goto retry;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002199 }
Ingo Molnare2970f22006-06-27 02:54:47 -07002200 if (curval != *cmpval) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002201 ret = -EAGAIN;
2202 goto out_unlock;
2203 }
2204 }
2205
Thomas Gleixner8e746332021-08-15 23:29:09 +02002206 if (requeue_pi) {
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01002207 struct task_struct *exiting = NULL;
2208
Darren Hartbab5bc92009-04-07 23:23:50 -07002209 /*
2210 * Attempt to acquire uaddr2 and wake the top waiter. If we
2211 * intend to requeue waiters, force setting the FUTEX_WAITERS
2212 * bit. We force this here where we are able to easily handle
2213 * faults rather in the requeue loop below.
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002214 *
2215 * Updates topwaiter::requeue_state if a top waiter exists.
Darren Hartbab5bc92009-04-07 23:23:50 -07002216 */
Darren Hart52400ba2009-04-03 13:40:49 -07002217 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01002218 &key2, &pi_state,
2219 &exiting, nr_requeue);
Darren Hart52400ba2009-04-03 13:40:49 -07002220
2221 /*
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002222 * At this point the top_waiter has either taken uaddr2 or
2223 * is waiting on it. In both cases pi_state has been
2224 * established and an initial refcount on it. In case of an
2225 * error there's nothing.
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002226 *
2227 * The top waiter's requeue_state is up to date:
2228 *
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002229 * - If the lock was acquired atomically (ret == 1), then
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002230 * the state is Q_REQUEUE_PI_LOCKED.
2231 *
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002232 * The top waiter has been dequeued and woken up and can
2233 * return to user space immediately. The kernel/user
2234 * space state is consistent. In case that there must be
2235 * more waiters requeued the WAITERS bit in the user
2236 * space futex is set so the top waiter task has to go
2237 * into the syscall slowpath to unlock the futex. This
2238 * will block until this requeue operation has been
2239 * completed and the hash bucket locks have been
2240 * dropped.
2241 *
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002242 * - If the trylock failed with an error (ret < 0) then
2243 * the state is either Q_REQUEUE_PI_NONE, i.e. "nothing
2244 * happened", or Q_REQUEUE_PI_IGNORE when there was an
2245 * interleaved early wakeup.
2246 *
2247 * - If the trylock did not succeed (ret == 0) then the
2248 * state is either Q_REQUEUE_PI_IN_PROGRESS or
2249 * Q_REQUEUE_PI_WAIT if an early wakeup interleaved.
2250 * This will be cleaned up in the loop below, which
2251 * cannot fail because futex_proxy_trylock_atomic() did
2252 * the same sanity checks for requeue_pi as the loop
2253 * below does.
Darren Hart52400ba2009-04-03 13:40:49 -07002254 */
Darren Hart52400ba2009-04-03 13:40:49 -07002255 switch (ret) {
2256 case 0:
Thomas Gleixnerecb38b72015-12-19 20:07:39 +00002257 /* We hold a reference on the pi state. */
Darren Hart52400ba2009-04-03 13:40:49 -07002258 break;
Thomas Gleixner4959f2d2015-12-19 20:07:40 +00002259
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002260 case 1:
2261 /*
2262 * futex_proxy_trylock_atomic() acquired the user space
2263 * futex. Adjust task_count.
2264 */
2265 task_count++;
2266 ret = 0;
2267 break;
2268
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002269 /*
2270 * If the above failed, then pi_state is NULL and
2271 * waiter::requeue_state is correct.
2272 */
Darren Hart52400ba2009-04-03 13:40:49 -07002273 case -EFAULT:
2274 double_unlock_hb(hb1, hb2);
Linus Torvalds69cd9eb2014-04-08 15:30:07 -07002275 hb_waiters_dec(hb2);
Thomas Gleixnerd0725992009-06-11 23:15:43 +02002276 ret = fault_in_user_writeable(uaddr2);
Darren Hart52400ba2009-04-03 13:40:49 -07002277 if (!ret)
2278 goto retry;
André Almeidad7c5ed72020-07-02 17:28:41 -03002279 return ret;
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01002280 case -EBUSY:
Darren Hart52400ba2009-04-03 13:40:49 -07002281 case -EAGAIN:
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00002282 /*
2283 * Two reasons for this:
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01002284 * - EBUSY: Owner is exiting and we just wait for the
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00002285 * exit to complete.
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01002286 * - EAGAIN: The user space value changed.
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00002287 */
Darren Hart52400ba2009-04-03 13:40:49 -07002288 double_unlock_hb(hb1, hb2);
Linus Torvalds69cd9eb2014-04-08 15:30:07 -07002289 hb_waiters_dec(hb2);
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01002290 /*
2291 * Handle the case where the owner is in the middle of
2292 * exiting. Wait for the exit to complete otherwise
2293 * this task might loop forever, aka. live lock.
2294 */
2295 wait_for_owner_exiting(ret, exiting);
Darren Hart52400ba2009-04-03 13:40:49 -07002296 cond_resched();
2297 goto retry;
2298 default:
2299 goto out_unlock;
2300 }
2301 }
2302
Jason Low0d00c7b2014-01-12 15:31:22 -08002303 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
Darren Hart52400ba2009-04-03 13:40:49 -07002304 if (task_count - nr_wake >= nr_requeue)
2305 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002306
Darren Hart52400ba2009-04-03 13:40:49 -07002307 if (!match_futex(&this->key, &key1))
2308 continue;
2309
Darren Hart392741e2009-08-07 15:20:48 -07002310 /*
Ingo Molnar93d09552021-05-12 20:04:28 +02002311 * FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI should always
Darren Hart392741e2009-08-07 15:20:48 -07002312 * be paired with each other and no other futex ops.
Darren Hartaa109902012-11-26 16:29:56 -08002313 *
2314 * We should never be requeueing a futex_q with a pi_state,
2315 * which is awaiting a futex_unlock_pi().
Darren Hart392741e2009-08-07 15:20:48 -07002316 */
2317 if ((requeue_pi && !this->rt_waiter) ||
Darren Hartaa109902012-11-26 16:29:56 -08002318 (!requeue_pi && this->rt_waiter) ||
2319 this->pi_state) {
Darren Hart392741e2009-08-07 15:20:48 -07002320 ret = -EINVAL;
2321 break;
2322 }
Darren Hart52400ba2009-04-03 13:40:49 -07002323
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002324 /* Plain futexes just wake or requeue and are done */
2325 if (!requeue_pi) {
2326 if (++task_count <= nr_wake)
2327 mark_wake_futex(&wake_q, this);
2328 else
2329 requeue_futex(this, hb1, hb2, &key2);
Darren Hart52400ba2009-04-03 13:40:49 -07002330 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002331 }
Darren Hart52400ba2009-04-03 13:40:49 -07002332
Darren Hart84bc4af2009-08-13 17:36:53 -07002333 /* Ensure we requeue to the expected futex for requeue_pi. */
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002334 if (!match_futex(this->requeue_pi_key, &key2)) {
Darren Hart84bc4af2009-08-13 17:36:53 -07002335 ret = -EINVAL;
2336 break;
2337 }
2338
Darren Hart52400ba2009-04-03 13:40:49 -07002339 /*
2340 * Requeue nr_requeue waiters and possibly one more in the case
2341 * of requeue_pi if we couldn't acquire the lock atomically.
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002342 *
2343 * Prepare the waiter to take the rt_mutex. Take a refcount
2344 * on the pi_state and store the pointer in the futex_q
2345 * object of the waiter.
Darren Hart52400ba2009-04-03 13:40:49 -07002346 */
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002347 get_pi_state(pi_state);
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002348
2349 /* Don't requeue when the waiter is already on the way out. */
2350 if (!futex_requeue_pi_prepare(this, pi_state)) {
2351 /*
2352 * Early woken waiter signaled that it is on the
2353 * way out. Drop the pi_state reference and try the
2354 * next waiter. @this->pi_state is still NULL.
2355 */
2356 put_pi_state(pi_state);
2357 continue;
2358 }
2359
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002360 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002361 this->rt_waiter,
2362 this->task);
2363
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002364 if (ret == 1) {
Thomas Gleixnerecb38b72015-12-19 20:07:39 +00002365 /*
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002366 * We got the lock. We do neither drop the refcount
2367 * on pi_state nor clear this->pi_state because the
2368 * waiter needs the pi_state for cleaning up the
2369 * user space value. It will drop the refcount
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002370 * after doing so. this::requeue_state is updated
2371 * in the wakeup as well.
Thomas Gleixnerecb38b72015-12-19 20:07:39 +00002372 */
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002373 requeue_pi_wake_futex(this, &key2, hb2);
2374 task_count++;
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002375 } else if (!ret) {
2376 /* Waiter is queued, move it to hb2 */
2377 requeue_futex(this, hb1, hb2, &key2);
2378 futex_requeue_pi_complete(this, 0);
2379 task_count++;
2380 } else {
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002381 /*
2382 * rt_mutex_start_proxy_lock() detected a potential
2383 * deadlock when we tried to queue that waiter.
2384 * Drop the pi_state reference which we took above
2385 * and remove the pointer to the state from the
2386 * waiters futex_q object.
2387 */
2388 this->pi_state = NULL;
2389 put_pi_state(pi_state);
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02002390 futex_requeue_pi_complete(this, ret);
Thomas Gleixner64b7b712021-08-15 23:29:12 +02002391 /*
2392 * We stop queueing more waiters and let user space
2393 * deal with the mess.
2394 */
2395 break;
Darren Hart52400ba2009-04-03 13:40:49 -07002396 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002397 }
2398
Thomas Gleixnerecb38b72015-12-19 20:07:39 +00002399 /*
Thomas Gleixner4f07ec02021-09-02 11:48:48 +02002400 * We took an extra initial reference to the pi_state in
2401 * futex_proxy_trylock_atomic(). We need to drop it here again.
Thomas Gleixnerecb38b72015-12-19 20:07:39 +00002402 */
Thomas Gleixner29e9ee52015-12-19 20:07:39 +00002403 put_pi_state(pi_state);
Thomas Gleixner885c2cb2015-12-19 20:07:41 +00002404
2405out_unlock:
Darren Hart5eb3dc62009-03-12 00:55:52 -07002406 double_unlock_hb(hb1, hb2);
Davidlohr Bueso1d0dcb32015-05-01 08:27:51 -07002407 wake_up_q(&wake_q);
Linus Torvalds69cd9eb2014-04-08 15:30:07 -07002408 hb_waiters_dec(hb2);
Darren Hart52400ba2009-04-03 13:40:49 -07002409 return ret ? ret : task_count;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002410}
2411
2412/* The key must be already stored in q->key. */
Eric Sesterhenn82af7ac2008-01-25 10:40:46 +01002413static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
Namhyung Kim15e408c2010-09-14 21:43:48 +09002414 __acquires(&hb->lock)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002415{
Ingo Molnare2970f22006-06-27 02:54:47 -07002416 struct futex_hash_bucket *hb;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002417
Ingo Molnare2970f22006-06-27 02:54:47 -07002418 hb = hash_futex(&q->key);
Linus Torvalds11d46162014-03-20 22:11:17 -07002419
2420 /*
2421 * Increment the counter before taking the lock so that
2422 * a potential waker won't miss a to-be-slept task that is
2423 * waiting for the spinlock. This is safe as all queue_lock()
2424 * users end up calling queue_me(). Similarly, for housekeeping,
2425 * decrement the counter at queue_unlock() when some error has
2426 * occurred and we don't end up adding the task to the list.
2427 */
Davidlohr Bueso6f568eb2019-02-06 10:56:02 -08002428 hb_waiters_inc(hb); /* implies smp_mb(); (A) */
Linus Torvalds11d46162014-03-20 22:11:17 -07002429
Ingo Molnare2970f22006-06-27 02:54:47 -07002430 q->lock_ptr = &hb->lock;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002431
Davidlohr Bueso6f568eb2019-02-06 10:56:02 -08002432 spin_lock(&hb->lock);
Ingo Molnare2970f22006-06-27 02:54:47 -07002433 return hb;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002434}
2435
Darren Hartd40d65c2009-09-21 22:30:15 -07002436static inline void
Jason Low0d00c7b2014-01-12 15:31:22 -08002437queue_unlock(struct futex_hash_bucket *hb)
Namhyung Kim15e408c2010-09-14 21:43:48 +09002438 __releases(&hb->lock)
Darren Hartd40d65c2009-09-21 22:30:15 -07002439{
2440 spin_unlock(&hb->lock);
Linus Torvalds11d46162014-03-20 22:11:17 -07002441 hb_waiters_dec(hb);
Darren Hartd40d65c2009-09-21 22:30:15 -07002442}
2443
Peter Zijlstracfafcd12017-03-22 11:35:58 +01002444static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002445{
Pierre Peifferec92d082007-05-09 02:35:00 -07002446 int prio;
2447
2448 /*
2449 * The priority used to register this element is
2450 * - either the real thread-priority for the real-time threads
2451 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2452 * - or MAX_RT_PRIO for non-RT threads.
2453 * Thus, all RT-threads are woken first in priority order, and
2454 * the others are woken last, in FIFO order.
2455 */
2456 prio = min(current->normal_prio, MAX_RT_PRIO);
2457
2458 plist_node_init(&q->list, prio);
Pierre Peifferec92d082007-05-09 02:35:00 -07002459 plist_add(&q->list, &hb->chain);
Ingo Molnarc87e2832006-06-27 02:54:58 -07002460 q->task = current;
Peter Zijlstracfafcd12017-03-22 11:35:58 +01002461}
2462
2463/**
2464 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2465 * @q: The futex_q to enqueue
2466 * @hb: The destination hash bucket
2467 *
2468 * The hb->lock must be held by the caller, and is released here. A call to
2469 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2470 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2471 * or nothing if the unqueue is done as part of the wake process and the unqueue
2472 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2473 * an example).
2474 */
2475static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2476 __releases(&hb->lock)
2477{
2478 __queue_me(q, hb);
Ingo Molnare2970f22006-06-27 02:54:47 -07002479 spin_unlock(&hb->lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002480}
2481
Darren Hartd40d65c2009-09-21 22:30:15 -07002482/**
2483 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2484 * @q: The futex_q to unqueue
2485 *
2486 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2487 * be paired with exactly one earlier call to queue_me().
2488 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08002489 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03002490 * - 1 - if the futex_q was still queued (and we removed unqueued it);
2491 * - 0 - if the futex_q was already removed by the waking thread
Linus Torvalds1da177e2005-04-16 15:20:36 -07002492 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002493static int unqueue_me(struct futex_q *q)
2494{
Linus Torvalds1da177e2005-04-16 15:20:36 -07002495 spinlock_t *lock_ptr;
Ingo Molnare2970f22006-06-27 02:54:47 -07002496 int ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002497
2498 /* In the common case we don't take the spinlock, which is nice. */
Darren Hart42d35d42008-12-29 15:49:53 -08002499retry:
Jianyu Zhan29b75eb2016-03-07 09:32:24 +08002500 /*
2501 * q->lock_ptr can change between this read and the following spin_lock.
2502 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2503 * optimizing lock_ptr out of the logic below.
2504 */
2505 lock_ptr = READ_ONCE(q->lock_ptr);
Stephen Hemmingerc80544d2007-10-18 03:07:05 -07002506 if (lock_ptr != NULL) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002507 spin_lock(lock_ptr);
2508 /*
2509 * q->lock_ptr can change between reading it and
2510 * spin_lock(), causing us to take the wrong lock. This
2511 * corrects the race condition.
2512 *
2513 * Reasoning goes like this: if we have the wrong lock,
2514 * q->lock_ptr must have changed (maybe several times)
2515 * between reading it and the spin_lock(). It can
2516 * change again after the spin_lock() but only if it was
2517 * already changed before the spin_lock(). It cannot,
2518 * however, change back to the original value. Therefore
2519 * we can detect whether we acquired the correct lock.
2520 */
2521 if (unlikely(lock_ptr != q->lock_ptr)) {
2522 spin_unlock(lock_ptr);
2523 goto retry;
2524 }
Lai Jiangshan2e129782010-12-22 14:18:50 +08002525 __unqueue_futex(q);
Ingo Molnarc87e2832006-06-27 02:54:58 -07002526
2527 BUG_ON(q->pi_state);
2528
Linus Torvalds1da177e2005-04-16 15:20:36 -07002529 spin_unlock(lock_ptr);
2530 ret = 1;
2531 }
2532
Linus Torvalds1da177e2005-04-16 15:20:36 -07002533 return ret;
2534}
2535
Ingo Molnarc87e2832006-06-27 02:54:58 -07002536/*
Ingo Molnar93d09552021-05-12 20:04:28 +02002537 * PI futexes can not be requeued and must remove themselves from the
Davidlohr Buesoa3f24282021-02-26 09:50:28 -08002538 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held.
Ingo Molnarc87e2832006-06-27 02:54:58 -07002539 */
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002540static void unqueue_me_pi(struct futex_q *q)
Ingo Molnarc87e2832006-06-27 02:54:58 -07002541{
Lai Jiangshan2e129782010-12-22 14:18:50 +08002542 __unqueue_futex(q);
Ingo Molnarc87e2832006-06-27 02:54:58 -07002543
2544 BUG_ON(!q->pi_state);
Thomas Gleixner29e9ee52015-12-19 20:07:39 +00002545 put_pi_state(q->pi_state);
Ingo Molnarc87e2832006-06-27 02:54:58 -07002546 q->pi_state = NULL;
Ingo Molnarc87e2832006-06-27 02:54:58 -07002547}
2548
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002549static int __fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2550 struct task_struct *argowner)
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002551{
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002552 struct futex_pi_state *pi_state = q->pi_state;
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002553 struct task_struct *oldowner, *newowner;
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002554 u32 uval, curval, newval, newtid;
2555 int err = 0;
Peter Zijlstra734009e2017-03-22 11:35:52 +01002556
2557 oldowner = pi_state->owner;
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002558
2559 /*
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002560 * We are here because either:
Peter Zijlstra16ffa122017-03-22 11:35:55 +01002561 *
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002562 * - we stole the lock and pi_state->owner needs updating to reflect
2563 * that (@argowner == current),
2564 *
2565 * or:
2566 *
2567 * - someone stole our lock and we need to fix things to point to the
2568 * new owner (@argowner == NULL).
2569 *
2570 * Either way, we have to replace the TID in the user space variable.
Lai Jiangshan81612392011-01-14 17:09:41 +08002571 * This must be atomic as we have to preserve the owner died bit here.
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002572 *
Darren Hartb2d09942009-03-12 00:55:37 -07002573 * Note: We write the user space value _before_ changing the pi_state
2574 * because we can fault here. Imagine swapped out pages or a fork
2575 * that marked all the anonymous memory readonly for cow.
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002576 *
Peter Zijlstra734009e2017-03-22 11:35:52 +01002577 * Modifying pi_state _before_ the user space value would leave the
2578 * pi_state in an inconsistent state when we fault here, because we
2579 * need to drop the locks to handle the fault. This might be observed
Thomas Gleixnerf6f4ec02021-08-15 23:29:07 +02002580 * in the PID checks when attaching to PI state .
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002581 */
2582retry:
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002583 if (!argowner) {
2584 if (oldowner != current) {
2585 /*
2586 * We raced against a concurrent self; things are
2587 * already fixed up. Nothing to do.
2588 */
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002589 return 0;
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002590 }
2591
2592 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01002593 /* We got the lock. pi_state is correct. Tell caller. */
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002594 return 1;
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002595 }
2596
2597 /*
Mike Galbraith9f5d1c32020-11-04 16:12:44 +01002598 * The trylock just failed, so either there is an owner or
2599 * there is a higher priority waiter than this one.
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002600 */
2601 newowner = rt_mutex_owner(&pi_state->pi_mutex);
Mike Galbraith9f5d1c32020-11-04 16:12:44 +01002602 /*
2603 * If the higher priority waiter has not yet taken over the
2604 * rtmutex then newowner is NULL. We can't return here with
2605 * that state because it's inconsistent vs. the user space
2606 * state. So drop the locks and try again. It's a valid
2607 * situation and not any different from the other retry
2608 * conditions.
2609 */
2610 if (unlikely(!newowner)) {
2611 err = -EAGAIN;
2612 goto handle_err;
2613 }
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002614 } else {
2615 WARN_ON_ONCE(argowner != current);
2616 if (oldowner == current) {
2617 /*
2618 * We raced against a concurrent self; things are
2619 * already fixed up. Nothing to do.
2620 */
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002621 return 1;
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002622 }
2623 newowner = argowner;
2624 }
2625
2626 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
Peter Zijlstraa97cb0e2018-01-22 11:39:47 +01002627 /* Owner died? */
2628 if (!pi_state->owner)
2629 newtid |= FUTEX_OWNER_DIED;
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002630
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002631 err = get_futex_value_locked(&uval, uaddr);
2632 if (err)
2633 goto handle_err;
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002634
Peter Zijlstra16ffa122017-03-22 11:35:55 +01002635 for (;;) {
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002636 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2637
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002638 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
2639 if (err)
2640 goto handle_err;
2641
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002642 if (curval == uval)
2643 break;
2644 uval = curval;
2645 }
2646
2647 /*
2648 * We fixed up user space. Now we need to fix the pi_state
2649 * itself.
2650 */
Thomas Gleixnerc5cade22021-01-19 15:21:35 +01002651 pi_state_update_owner(pi_state, newowner);
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002652
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01002653 return argowner == current;
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002654
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002655 /*
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002656 * In order to reschedule or handle a page fault, we need to drop the
2657 * locks here. In the case of a fault, this gives the other task
2658 * (either the highest priority waiter itself or the task which stole
2659 * the rtmutex) the chance to try the fixup of the pi_state. So once we
2660 * are back from handling the fault we need to check the pi_state after
2661 * reacquiring the locks and before trying to do another fixup. When
2662 * the fixup has been done already we simply return.
Peter Zijlstra734009e2017-03-22 11:35:52 +01002663 *
2664 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2665 * drop hb->lock since the caller owns the hb -> futex_q relation.
2666 * Dropping the pi_mutex->wait_lock requires the state revalidate.
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002667 */
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002668handle_err:
Peter Zijlstra734009e2017-03-22 11:35:52 +01002669 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002670 spin_unlock(q->lock_ptr);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07002671
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002672 switch (err) {
2673 case -EFAULT:
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002674 err = fault_in_user_writeable(uaddr);
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002675 break;
2676
2677 case -EAGAIN:
2678 cond_resched();
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002679 err = 0;
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002680 break;
2681
2682 default:
2683 WARN_ON_ONCE(1);
Will Deacon6b4f4bc2019-02-28 11:58:08 +00002684 break;
2685 }
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07002686
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002687 spin_lock(q->lock_ptr);
Peter Zijlstra734009e2017-03-22 11:35:52 +01002688 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07002689
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002690 /*
2691 * Check if someone else fixed it for us:
2692 */
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002693 if (pi_state->owner != oldowner)
2694 return argowner == current;
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002695
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002696 /* Retry if err was -EAGAIN or the fault in succeeded */
2697 if (!err)
2698 goto retry;
Thomas Gleixner1b7558e2008-06-23 11:21:58 +02002699
Thomas Gleixner34b1a1c2021-01-18 19:01:21 +01002700 /*
2701 * fault_in_user_writeable() failed so user state is immutable. At
2702 * best we can make the kernel state consistent but user state will
2703 * be most likely hosed and any subsequent unlock operation will be
2704 * rejected due to PI futex rule [10].
2705 *
2706 * Ensure that the rtmutex owner is also the pi_state owner despite
2707 * the user space value claiming something different. There is no
2708 * point in unlocking the rtmutex if current is the owner as it
2709 * would need to wait until the next waiter has taken the rtmutex
2710 * to guarantee consistent state. Keep it simple. Userspace asked
2711 * for this wreckaged state.
2712 *
2713 * The rtmutex has an owner - either current or some other
2714 * task. See the EAGAIN loop above.
2715 */
2716 pi_state_update_owner(pi_state, rt_mutex_owner(&pi_state->pi_mutex));
Peter Zijlstra734009e2017-03-22 11:35:52 +01002717
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002718 return err;
2719}
Peter Zijlstra734009e2017-03-22 11:35:52 +01002720
Thomas Gleixnerf2dac392021-01-19 16:26:38 +01002721static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
2722 struct task_struct *argowner)
2723{
2724 struct futex_pi_state *pi_state = q->pi_state;
2725 int ret;
2726
2727 lockdep_assert_held(q->lock_ptr);
2728
2729 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2730 ret = __fixup_pi_state_owner(uaddr, q, argowner);
Peter Zijlstra734009e2017-03-22 11:35:52 +01002731 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2732 return ret;
Pierre Peifferd0aa7a72007-05-09 02:35:02 -07002733}
2734
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002735static long futex_wait_restart(struct restart_block *restart);
Thomas Gleixner36cf3b52007-07-15 23:41:20 -07002736
Darren Hartca5f9522009-04-03 13:39:33 -07002737/**
Darren Hartdd973992009-04-03 13:40:02 -07002738 * fixup_owner() - Post lock pi_state and corner case management
2739 * @uaddr: user address of the futex
Darren Hartdd973992009-04-03 13:40:02 -07002740 * @q: futex_q (contains pi_state and access to the rt_mutex)
2741 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2742 *
2743 * After attempting to lock an rt_mutex, this function is called to cleanup
2744 * the pi_state owner as well as handle race conditions that may allow us to
2745 * acquire the lock. Must be called with the hb lock held.
2746 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08002747 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03002748 * - 1 - success, lock taken;
2749 * - 0 - success, lock not taken;
2750 * - <0 - on error (-EFAULT)
Darren Hartdd973992009-04-03 13:40:02 -07002751 */
Thomas Gleixnerae791a22010-11-10 13:30:36 +01002752static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
Darren Hartdd973992009-04-03 13:40:02 -07002753{
Darren Hartdd973992009-04-03 13:40:02 -07002754 if (locked) {
2755 /*
2756 * Got the lock. We might not be the anticipated owner if we
2757 * did a lock-steal - fix up the PI-state in that case:
Peter Zijlstra16ffa122017-03-22 11:35:55 +01002758 *
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002759 * Speculative pi_state->owner read (we don't hold wait_lock);
2760 * since we own the lock pi_state->owner == current is the
2761 * stable state, anything else needs more attention.
Darren Hartdd973992009-04-03 13:40:02 -07002762 */
2763 if (q->pi_state->owner != current)
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01002764 return fixup_pi_state_owner(uaddr, q, current);
2765 return 1;
Darren Hartdd973992009-04-03 13:40:02 -07002766 }
2767
2768 /*
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002769 * If we didn't get the lock; check if anybody stole it from us. In
2770 * that case, we need to fix up the uval to point to them instead of
2771 * us, otherwise bad things happen. [10]
2772 *
2773 * Another speculative read; pi_state->owner == current is unstable
2774 * but needs our attention.
2775 */
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01002776 if (q->pi_state->owner == current)
2777 return fixup_pi_state_owner(uaddr, q, NULL);
Peter Zijlstrac1e2f0e2017-12-08 13:49:39 +01002778
2779 /*
Darren Hartdd973992009-04-03 13:40:02 -07002780 * Paranoia check. If we did not take the lock, then we should not be
Thomas Gleixner04b79c52021-01-19 16:06:10 +01002781 * the owner of the rt_mutex. Warn and establish consistent state.
Darren Hartdd973992009-04-03 13:40:02 -07002782 */
Thomas Gleixner04b79c52021-01-19 16:06:10 +01002783 if (WARN_ON_ONCE(rt_mutex_owner(&q->pi_state->pi_mutex) == current))
2784 return fixup_pi_state_owner(uaddr, q, current);
Darren Hartdd973992009-04-03 13:40:02 -07002785
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01002786 return 0;
Darren Hartdd973992009-04-03 13:40:02 -07002787}
2788
2789/**
Darren Hartca5f9522009-04-03 13:39:33 -07002790 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2791 * @hb: the futex hash bucket, must be locked by the caller
2792 * @q: the futex_q to queue up on
2793 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
Darren Hartca5f9522009-04-03 13:39:33 -07002794 */
2795static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02002796 struct hrtimer_sleeper *timeout)
Darren Hartca5f9522009-04-03 13:39:33 -07002797{
Darren Hart9beba3c2009-09-24 11:54:47 -07002798 /*
2799 * The task state is guaranteed to be set before another task can
Peter Zijlstrab92b8b32015-05-12 10:51:55 +02002800 * wake it. set_current_state() is implemented using smp_store_mb() and
Darren Hart9beba3c2009-09-24 11:54:47 -07002801 * queue_me() calls spin_unlock() upon completion, both serializing
2802 * access to the hash list and forcing another memory barrier.
2803 */
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02002804 set_current_state(TASK_INTERRUPTIBLE);
Darren Hart0729e192009-09-21 22:30:38 -07002805 queue_me(q, hb);
Darren Hartca5f9522009-04-03 13:39:33 -07002806
2807 /* Arm the timer */
Thomas Gleixner2e4b0d32015-04-14 21:09:13 +00002808 if (timeout)
Thomas Gleixner9dd88132019-07-30 21:16:55 +02002809 hrtimer_sleeper_start_expires(timeout, HRTIMER_MODE_ABS);
Darren Hartca5f9522009-04-03 13:39:33 -07002810
2811 /*
Darren Hart0729e192009-09-21 22:30:38 -07002812 * If we have been removed from the hash list, then another task
2813 * has tried to wake us, and we can skip the call to schedule().
Darren Hartca5f9522009-04-03 13:39:33 -07002814 */
2815 if (likely(!plist_node_empty(&q->list))) {
2816 /*
2817 * If the timer has already expired, current will already be
2818 * flagged for rescheduling. Only call schedule if there
2819 * is no timeout, or if it has yet to expire.
2820 */
2821 if (!timeout || timeout->task)
Colin Cross88c80042013-05-01 18:35:05 -07002822 freezable_schedule();
Darren Hartca5f9522009-04-03 13:39:33 -07002823 }
2824 __set_current_state(TASK_RUNNING);
2825}
2826
Darren Hartf8010732009-04-03 13:40:40 -07002827/**
2828 * futex_wait_setup() - Prepare to wait on a futex
2829 * @uaddr: the futex userspace address
2830 * @val: the expected value
Darren Hartb41277d2010-11-08 13:10:09 -08002831 * @flags: futex flags (FLAGS_SHARED, etc.)
Darren Hartf8010732009-04-03 13:40:40 -07002832 * @q: the associated futex_q
2833 * @hb: storage for hash_bucket pointer to be returned to caller
2834 *
2835 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2836 * compare it with the expected value. Handle atomic faults internally.
Thomas Gleixnerc363b7e2021-08-15 23:29:06 +02002837 * Return with the hb lock held on success, and unlocked on failure.
Darren Hartf8010732009-04-03 13:40:40 -07002838 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08002839 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03002840 * - 0 - uaddr contains val and hb has been locked;
2841 * - <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
Darren Hartf8010732009-04-03 13:40:40 -07002842 */
Darren Hartb41277d2010-11-08 13:10:09 -08002843static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
Darren Hartf8010732009-04-03 13:40:40 -07002844 struct futex_q *q, struct futex_hash_bucket **hb)
2845{
2846 u32 uval;
2847 int ret;
2848
2849 /*
2850 * Access the page AFTER the hash-bucket is locked.
2851 * Order is important:
2852 *
2853 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2854 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2855 *
2856 * The basic logical guarantee of a futex is that it blocks ONLY
2857 * if cond(var) is known to be true at the time of blocking, for
Michel Lespinasse8fe8f542011-03-06 18:07:50 -08002858 * any cond. If we locked the hash-bucket after testing *uaddr, that
2859 * would open a race condition where we could block indefinitely with
Darren Hartf8010732009-04-03 13:40:40 -07002860 * cond(var) false, which would violate the guarantee.
2861 *
Michel Lespinasse8fe8f542011-03-06 18:07:50 -08002862 * On the other hand, we insert q and release the hash-bucket only
2863 * after testing *uaddr. This guarantees that futex_wait() will NOT
2864 * absorb a wakeup if *uaddr does not match the desired values
2865 * while the syscall executes.
Darren Hartf8010732009-04-03 13:40:40 -07002866 */
2867retry:
Linus Torvalds96d4f262019-01-03 18:57:57 -08002868 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, FUTEX_READ);
Darren Hartf8010732009-04-03 13:40:40 -07002869 if (unlikely(ret != 0))
Darren Harta5a2a0c2009-04-10 09:50:05 -07002870 return ret;
Darren Hartf8010732009-04-03 13:40:40 -07002871
2872retry_private:
2873 *hb = queue_lock(q);
2874
2875 ret = get_futex_value_locked(&uval, uaddr);
2876
2877 if (ret) {
Jason Low0d00c7b2014-01-12 15:31:22 -08002878 queue_unlock(*hb);
Darren Hartf8010732009-04-03 13:40:40 -07002879
2880 ret = get_user(uval, uaddr);
2881 if (ret)
André Almeidad7c5ed72020-07-02 17:28:41 -03002882 return ret;
Darren Hartf8010732009-04-03 13:40:40 -07002883
Darren Hartb41277d2010-11-08 13:10:09 -08002884 if (!(flags & FLAGS_SHARED))
Darren Hartf8010732009-04-03 13:40:40 -07002885 goto retry_private;
2886
Darren Hartf8010732009-04-03 13:40:40 -07002887 goto retry;
2888 }
2889
2890 if (uval != val) {
Jason Low0d00c7b2014-01-12 15:31:22 -08002891 queue_unlock(*hb);
Darren Hartf8010732009-04-03 13:40:40 -07002892 ret = -EWOULDBLOCK;
2893 }
2894
Darren Hartf8010732009-04-03 13:40:40 -07002895 return ret;
2896}
2897
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03002898int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002899{
Waiman Long5ca584d2019-05-28 12:03:45 -04002900 struct hrtimer_sleeper timeout, *to;
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002901 struct restart_block *restart;
Ingo Molnare2970f22006-06-27 02:54:47 -07002902 struct futex_hash_bucket *hb;
Darren Hart5bdb05f2010-11-08 13:40:28 -08002903 struct futex_q q = futex_q_init;
Ingo Molnare2970f22006-06-27 02:54:47 -07002904 int ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002905
Thomas Gleixnercd689982008-02-01 17:45:14 +01002906 if (!bitset)
2907 return -EINVAL;
Thomas Gleixnercd689982008-02-01 17:45:14 +01002908 q.bitset = bitset;
Darren Hartca5f9522009-04-03 13:39:33 -07002909
Waiman Long5ca584d2019-05-28 12:03:45 -04002910 to = futex_setup_timer(abs_time, &timeout, flags,
2911 current->timer_slack_ns);
Thomas Gleixnerd58e6572009-10-13 20:40:43 +02002912retry:
Darren Hart7ada8762010-10-17 08:35:04 -07002913 /*
Thomas Gleixnerc363b7e2021-08-15 23:29:06 +02002914 * Prepare to wait on uaddr. On success, it holds hb->lock and q
2915 * is initialized.
Darren Hart7ada8762010-10-17 08:35:04 -07002916 */
Darren Hartb41277d2010-11-08 13:10:09 -08002917 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
Darren Hartf8010732009-04-03 13:40:40 -07002918 if (ret)
Darren Hart42d35d42008-12-29 15:49:53 -08002919 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002920
Darren Hartca5f9522009-04-03 13:39:33 -07002921 /* queue_me and wait for wakeup, timeout, or a signal. */
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02002922 futex_wait_queue_me(hb, &q, to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002923
2924 /* If we were woken (and unqueued), we succeeded, whatever. */
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002925 ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002926 if (!unqueue_me(&q))
Darren Hart7ada8762010-10-17 08:35:04 -07002927 goto out;
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002928 ret = -ETIMEDOUT;
Darren Hartca5f9522009-04-03 13:39:33 -07002929 if (to && !to->task)
Darren Hart7ada8762010-10-17 08:35:04 -07002930 goto out;
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002931
Ingo Molnare2970f22006-06-27 02:54:47 -07002932 /*
Thomas Gleixnerd58e6572009-10-13 20:40:43 +02002933 * We expect signal_pending(current), but we might be the
2934 * victim of a spurious wakeup as well.
Ingo Molnare2970f22006-06-27 02:54:47 -07002935 */
Darren Hart7ada8762010-10-17 08:35:04 -07002936 if (!signal_pending(current))
Thomas Gleixnerd58e6572009-10-13 20:40:43 +02002937 goto retry;
Thomas Gleixnerd58e6572009-10-13 20:40:43 +02002938
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002939 ret = -ERESTARTSYS;
Pierre Peifferc19384b2007-05-09 02:35:02 -07002940 if (!abs_time)
Darren Hart7ada8762010-10-17 08:35:04 -07002941 goto out;
Steven Rostedtce6bd422007-12-05 15:46:09 +01002942
Andy Lutomirskif56141e2015-02-12 15:01:14 -08002943 restart = &current->restart_block;
Namhyung Kima3c74c52010-09-14 21:43:47 +09002944 restart->futex.uaddr = uaddr;
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002945 restart->futex.val = val;
Thomas Gleixner2456e852016-12-25 11:38:40 +01002946 restart->futex.time = *abs_time;
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002947 restart->futex.bitset = bitset;
Darren Hart0cd9c642011-04-14 15:41:57 -07002948 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002949
Oleg Nesterov5abbe512021-02-01 18:46:41 +01002950 ret = set_restart_fn(restart, futex_wait_restart);
Peter Zijlstra2fff78c2009-02-11 18:10:10 +01002951
Darren Hart42d35d42008-12-29 15:49:53 -08002952out:
Darren Hartca5f9522009-04-03 13:39:33 -07002953 if (to) {
2954 hrtimer_cancel(&to->timer);
2955 destroy_hrtimer_on_stack(&to->timer);
2956 }
Ingo Molnarc87e2832006-06-27 02:54:58 -07002957 return ret;
2958}
2959
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002960
2961static long futex_wait_restart(struct restart_block *restart)
2962{
Namhyung Kima3c74c52010-09-14 21:43:47 +09002963 u32 __user *uaddr = restart->futex.uaddr;
Darren Harta72188d2009-04-03 13:40:22 -07002964 ktime_t t, *tp = NULL;
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002965
Darren Harta72188d2009-04-03 13:40:22 -07002966 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
Thomas Gleixner2456e852016-12-25 11:38:40 +01002967 t = restart->futex.time;
Darren Harta72188d2009-04-03 13:40:22 -07002968 tp = &t;
2969 }
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002970 restart->fn = do_no_restart_syscall;
Darren Hartb41277d2010-11-08 13:10:09 -08002971
2972 return (long)futex_wait(uaddr, restart->futex.flags,
2973 restart->futex.val, tp, restart->futex.bitset);
Nick Piggin72c1bbf2007-05-08 00:26:43 -07002974}
2975
2976
Ingo Molnarc87e2832006-06-27 02:54:58 -07002977/*
2978 * Userspace tried a 0 -> TID atomic transition of the futex value
2979 * and failed. The kernel side here does the whole locking operation:
Davidlohr Bueso767f5092015-06-29 23:26:01 -07002980 * 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.).
2983 *
2984 * Also serves as futex trylock_pi()'ing, and due semantics.
Ingo Molnarc87e2832006-06-27 02:54:58 -07002985 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03002986int futex_lock_pi(u32 __user *uaddr, unsigned int flags, ktime_t *time, int trylock)
Ingo Molnarc87e2832006-06-27 02:54:58 -07002987{
Waiman Long5ca584d2019-05-28 12:03:45 -04002988 struct hrtimer_sleeper timeout, *to;
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01002989 struct task_struct *exiting = NULL;
Peter Zijlstracfafcd12017-03-22 11:35:58 +01002990 struct rt_mutex_waiter rt_waiter;
Ingo Molnarc87e2832006-06-27 02:54:58 -07002991 struct futex_hash_bucket *hb;
Darren Hart5bdb05f2010-11-08 13:40:28 -08002992 struct futex_q q = futex_q_init;
Darren Hartdd973992009-04-03 13:40:02 -07002993 int res, ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07002994
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -04002995 if (!IS_ENABLED(CONFIG_FUTEX_PI))
2996 return -ENOSYS;
2997
Ingo Molnarc87e2832006-06-27 02:54:58 -07002998 if (refill_pi_state_cache())
2999 return -ENOMEM;
3000
Thomas Gleixnere112c412021-04-22 21:44:22 +02003001 to = futex_setup_timer(time, &timeout, flags, 0);
Thomas Gleixnerc5780e92006-09-08 09:47:15 -07003002
Darren Hart42d35d42008-12-29 15:49:53 -08003003retry:
Linus Torvalds96d4f262019-01-03 18:57:57 -08003004 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, FUTEX_WRITE);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003005 if (unlikely(ret != 0))
Darren Hart42d35d42008-12-29 15:49:53 -08003006 goto out;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003007
Darren Harte4dc5b72009-03-12 00:56:13 -07003008retry_private:
Eric Sesterhenn82af7ac2008-01-25 10:40:46 +01003009 hb = queue_lock(&q);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003010
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01003011 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
3012 &exiting, 0);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003013 if (unlikely(ret)) {
Davidlohr Bueso767f5092015-06-29 23:26:01 -07003014 /*
3015 * Atomic work succeeded and we got the lock,
3016 * or failed. Either way, we do _not_ block.
3017 */
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003018 switch (ret) {
Darren Hart1a520842009-04-03 13:39:52 -07003019 case 1:
3020 /* We got the lock. */
3021 ret = 0;
3022 goto out_unlock_put_key;
3023 case -EFAULT:
3024 goto uaddr_faulted;
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01003025 case -EBUSY:
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003026 case -EAGAIN:
3027 /*
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00003028 * Two reasons for this:
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01003029 * - EBUSY: Task is exiting and we just wait for the
Thomas Gleixneraf54d6a2014-06-11 20:45:41 +00003030 * exit to complete.
Thomas Gleixnerac31c7f2019-11-06 22:55:45 +01003031 * - EAGAIN: The user space value changed.
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003032 */
Jason Low0d00c7b2014-01-12 15:31:22 -08003033 queue_unlock(hb);
Thomas Gleixner3ef240e2019-11-06 22:55:46 +01003034 /*
3035 * Handle the case where the owner is in the middle of
3036 * exiting. Wait for the exit to complete otherwise
3037 * this task might loop forever, aka. live lock.
3038 */
3039 wait_for_owner_exiting(ret, exiting);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003040 cond_resched();
3041 goto retry;
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003042 default:
Darren Hart42d35d42008-12-29 15:49:53 -08003043 goto out_unlock_put_key;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003044 }
Ingo Molnarc87e2832006-06-27 02:54:58 -07003045 }
3046
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003047 WARN_ON(!q.pi_state);
3048
Ingo Molnarc87e2832006-06-27 02:54:58 -07003049 /*
3050 * Only actually queue now that the atomic ops are done:
3051 */
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003052 __queue_me(&q, hb);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003053
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003054 if (trylock) {
Peter Zijlstra5293c2e2017-03-22 11:35:51 +01003055 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003056 /* Fixup the trylock return value: */
3057 ret = ret ? 0 : -EWOULDBLOCK;
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003058 goto no_block;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003059 }
3060
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003061 rt_mutex_init_waiter(&rt_waiter);
Peter Zijlstra56222b22017-03-22 11:36:00 +01003062
3063 /*
3064 * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
3065 * hold it while doing rt_mutex_start_proxy(), because then it will
3066 * include hb->lock in the blocking chain, even through we'll not in
3067 * fact hold it while blocking. This will lead it to report -EDEADLK
3068 * and BUG when futex_unlock_pi() interleaves with this.
3069 *
3070 * Therefore acquire wait_lock while holding hb->lock, but drop the
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003071 * latter before calling __rt_mutex_start_proxy_lock(). This
3072 * interleaves with futex_unlock_pi() -- which does a similar lock
3073 * handoff -- such that the latter can observe the futex_q::pi_state
3074 * before __rt_mutex_start_proxy_lock() is done.
Peter Zijlstra56222b22017-03-22 11:36:00 +01003075 */
3076 raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
3077 spin_unlock(q.lock_ptr);
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003078 /*
3079 * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
3080 * such that futex_unlock_pi() is guaranteed to observe the waiter when
3081 * it sees the futex_q::pi_state.
3082 */
Peter Zijlstra56222b22017-03-22 11:36:00 +01003083 ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
3084 raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
3085
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003086 if (ret) {
3087 if (ret == 1)
3088 ret = 0;
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003089 goto cleanup;
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003090 }
3091
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003092 if (unlikely(to))
Thomas Gleixner9dd88132019-07-30 21:16:55 +02003093 hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003094
3095 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
3096
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003097cleanup:
Vernon Mauerya99e4e42006-07-01 04:35:42 -07003098 spin_lock(q.lock_ptr);
Darren Hartdd973992009-04-03 13:40:02 -07003099 /*
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003100 * If we failed to acquire the lock (deadlock/signal/timeout), we must
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003101 * first acquire the hb->lock before removing the lock from the
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003102 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
3103 * lists consistent.
Peter Zijlstra56222b22017-03-22 11:36:00 +01003104 *
3105 * In particular; it is important that futex_unlock_pi() can not
3106 * observe this inconsistency.
Peter Zijlstracfafcd12017-03-22 11:35:58 +01003107 */
3108 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
3109 ret = 0;
3110
3111no_block:
3112 /*
Darren Hartdd973992009-04-03 13:40:02 -07003113 * Fixup the pi_state owner and possibly acquire the lock if we
3114 * haven't already.
3115 */
Thomas Gleixnerae791a22010-11-10 13:30:36 +01003116 res = fixup_owner(uaddr, &q, !ret);
Darren Hartdd973992009-04-03 13:40:02 -07003117 /*
Ingo Molnar93d09552021-05-12 20:04:28 +02003118 * If fixup_owner() returned an error, propagate that. If it acquired
Darren Hartdd973992009-04-03 13:40:02 -07003119 * the lock, clear our -ETIMEDOUT or -EINTR.
3120 */
3121 if (res)
3122 ret = (res < 0) ? res : 0;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003123
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003124 unqueue_me_pi(&q);
Davidlohr Buesoa3f24282021-02-26 09:50:28 -08003125 spin_unlock(q.lock_ptr);
André Almeida9180bd42020-07-02 17:28:40 -03003126 goto out;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003127
Darren Hart42d35d42008-12-29 15:49:53 -08003128out_unlock_put_key:
Jason Low0d00c7b2014-01-12 15:31:22 -08003129 queue_unlock(hb);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003130
Darren Hart42d35d42008-12-29 15:49:53 -08003131out:
Thomas Gleixner97181f92017-04-10 18:03:36 +02003132 if (to) {
3133 hrtimer_cancel(&to->timer);
Thomas Gleixner237fc6e2008-04-30 00:55:04 -07003134 destroy_hrtimer_on_stack(&to->timer);
Thomas Gleixner97181f92017-04-10 18:03:36 +02003135 }
Darren Hartdd973992009-04-03 13:40:02 -07003136 return ret != -EINTR ? ret : -ERESTARTNOINTR;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003137
Darren Hart42d35d42008-12-29 15:49:53 -08003138uaddr_faulted:
Jason Low0d00c7b2014-01-12 15:31:22 -08003139 queue_unlock(hb);
Alexey Kuznetsov778e9a92007-06-08 13:47:00 -07003140
Thomas Gleixnerd0725992009-06-11 23:15:43 +02003141 ret = fault_in_user_writeable(uaddr);
Darren Harte4dc5b72009-03-12 00:56:13 -07003142 if (ret)
André Almeida9180bd42020-07-02 17:28:40 -03003143 goto out;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003144
Darren Hartb41277d2010-11-08 13:10:09 -08003145 if (!(flags & FLAGS_SHARED))
Darren Harte4dc5b72009-03-12 00:56:13 -07003146 goto retry_private;
3147
Darren Harte4dc5b72009-03-12 00:56:13 -07003148 goto retry;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003149}
3150
3151/*
Ingo Molnarc87e2832006-06-27 02:54:58 -07003152 * Userspace attempted a TID -> 0 atomic transition, and failed.
3153 * This is the in-kernel slowpath: we look up the PI state (if any),
3154 * and do the rt-mutex unlock.
3155 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03003156int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
Ingo Molnarc87e2832006-06-27 02:54:58 -07003157{
Kees Cook3f649ab2020-06-03 13:09:38 -07003158 u32 curval, uval, vpid = task_pid_vnr(current);
Peter Zijlstra38d47c12008-09-26 19:32:20 +02003159 union futex_key key = FUTEX_KEY_INIT;
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003160 struct futex_hash_bucket *hb;
Peter Zijlstra499f5ac2017-03-22 11:35:48 +01003161 struct futex_q *top_waiter;
Darren Harte4dc5b72009-03-12 00:56:13 -07003162 int ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003163
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -04003164 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3165 return -ENOSYS;
3166
Ingo Molnarc87e2832006-06-27 02:54:58 -07003167retry:
3168 if (get_user(uval, uaddr))
3169 return -EFAULT;
3170 /*
3171 * We release only a lock we actually own:
3172 */
Thomas Gleixnerc0c9ed12011-03-11 11:51:22 +01003173 if ((uval & FUTEX_TID_MASK) != vpid)
Ingo Molnarc87e2832006-06-27 02:54:58 -07003174 return -EPERM;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003175
Linus Torvalds96d4f262019-01-03 18:57:57 -08003176 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_WRITE);
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003177 if (ret)
3178 return ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003179
3180 hb = hash_futex(&key);
3181 spin_lock(&hb->lock);
3182
Ingo Molnarc87e2832006-06-27 02:54:58 -07003183 /*
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003184 * Check waiters first. We do not trust user space values at
3185 * all and we at least want to know if user space fiddled
3186 * with the futex value instead of blindly unlocking.
Ingo Molnarc87e2832006-06-27 02:54:58 -07003187 */
Peter Zijlstra499f5ac2017-03-22 11:35:48 +01003188 top_waiter = futex_top_waiter(hb, &key);
3189 if (top_waiter) {
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003190 struct futex_pi_state *pi_state = top_waiter->pi_state;
3191
3192 ret = -EINVAL;
3193 if (!pi_state)
3194 goto out_unlock;
3195
Sebastian Andrzej Siewior802ab582015-06-17 10:33:50 +02003196 /*
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003197 * If current does not own the pi_state then the futex is
3198 * inconsistent and user space fiddled with the futex value.
3199 */
3200 if (pi_state->owner != current)
3201 goto out_unlock;
3202
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003203 get_pi_state(pi_state);
Peter Zijlstrabebe5b52017-03-22 11:35:59 +01003204 /*
Peter Zijlstrabebe5b52017-03-22 11:35:59 +01003205 * By taking wait_lock while still holding hb->lock, we ensure
3206 * there is no point where we hold neither; and therefore
3207 * wake_futex_pi() must observe a state consistent with what we
3208 * observed.
Thomas Gleixner1a1fb982019-01-29 23:15:12 +01003209 *
3210 * In particular; this forces __rt_mutex_start_proxy() to
3211 * complete such that we're guaranteed to observe the
3212 * rt_waiter. Also see the WARN in wake_futex_pi().
Peter Zijlstrabebe5b52017-03-22 11:35:59 +01003213 */
3214 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003215 spin_unlock(&hb->lock);
3216
Peter Zijlstrac74aef22017-09-22 17:48:06 +02003217 /* drops pi_state->pi_mutex.wait_lock */
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003218 ret = wake_futex_pi(uaddr, uval, pi_state);
3219
3220 put_pi_state(pi_state);
3221
3222 /*
3223 * Success, we're done! No tricky corner cases.
Sebastian Andrzej Siewior802ab582015-06-17 10:33:50 +02003224 */
3225 if (!ret)
Jangwoong Kim0f9438502020-12-30 21:29:53 +09003226 return ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003227 /*
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003228 * The atomic access to the futex value generated a
3229 * pagefault, so retry the user-access and the wakeup:
Ingo Molnarc87e2832006-06-27 02:54:58 -07003230 */
3231 if (ret == -EFAULT)
3232 goto pi_faulted;
Sebastian Andrzej Siewior802ab582015-06-17 10:33:50 +02003233 /*
Sebastian Andrzej Siewior89e9e662016-04-15 14:35:39 +02003234 * A unconditional UNLOCK_PI op raced against a waiter
3235 * setting the FUTEX_WAITERS bit. Try again.
3236 */
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003237 if (ret == -EAGAIN)
3238 goto pi_retry;
Sebastian Andrzej Siewior89e9e662016-04-15 14:35:39 +02003239 /*
Sebastian Andrzej Siewior802ab582015-06-17 10:33:50 +02003240 * wake_futex_pi has detected invalid state. Tell user
3241 * space.
3242 */
Jangwoong Kim0f9438502020-12-30 21:29:53 +09003243 return ret;
Ingo Molnarc87e2832006-06-27 02:54:58 -07003244 }
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003245
Ingo Molnarc87e2832006-06-27 02:54:58 -07003246 /*
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003247 * We have no kernel internal state, i.e. no waiters in the
3248 * kernel. Waiters which are about to queue themselves are stuck
3249 * on hb->lock. So we can safely ignore them. We do neither
3250 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3251 * owner.
Ingo Molnarc87e2832006-06-27 02:54:58 -07003252 */
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003253 if ((ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))) {
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003254 spin_unlock(&hb->lock);
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003255 switch (ret) {
3256 case -EFAULT:
3257 goto pi_faulted;
3258
3259 case -EAGAIN:
3260 goto pi_retry;
3261
3262 default:
3263 WARN_ON_ONCE(1);
Jangwoong Kim0f9438502020-12-30 21:29:53 +09003264 return ret;
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003265 }
Peter Zijlstra16ffa122017-03-22 11:35:55 +01003266 }
Ingo Molnarc87e2832006-06-27 02:54:58 -07003267
Thomas Gleixnerccf9e6a2014-06-11 20:45:38 +00003268 /*
3269 * If uval has changed, let user space handle it.
3270 */
3271 ret = (curval == uval) ? 0 : -EAGAIN;
3272
Ingo Molnarc87e2832006-06-27 02:54:58 -07003273out_unlock:
3274 spin_unlock(&hb->lock);
Ingo Molnarc87e2832006-06-27 02:54:58 -07003275 return ret;
3276
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003277pi_retry:
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003278 cond_resched();
3279 goto retry;
3280
Ingo Molnarc87e2832006-06-27 02:54:58 -07003281pi_faulted:
Ingo Molnarc87e2832006-06-27 02:54:58 -07003282
Thomas Gleixnerd0725992009-06-11 23:15:43 +02003283 ret = fault_in_user_writeable(uaddr);
Darren Hartb5686362008-12-18 15:06:34 -08003284 if (!ret)
Ingo Molnarc87e2832006-06-27 02:54:58 -07003285 goto retry;
3286
Linus Torvalds1da177e2005-04-16 15:20:36 -07003287 return ret;
3288}
3289
Darren Hart52400ba2009-04-03 13:40:49 -07003290/**
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003291 * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex
Darren Hart52400ba2009-04-03 13:40:49 -07003292 * @hb: the hash_bucket futex_q was original enqueued on
3293 * @q: the futex_q woken while waiting to be requeued
Darren Hart52400ba2009-04-03 13:40:49 -07003294 * @timeout: the timeout associated with the wait (NULL if none)
3295 *
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003296 * Determine the cause for the early wakeup.
Darren Hart52400ba2009-04-03 13:40:49 -07003297 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08003298 * Return:
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003299 * -EWOULDBLOCK or -ETIMEDOUT or -ERESTARTNOINTR
Darren Hart52400ba2009-04-03 13:40:49 -07003300 */
3301static inline
3302int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003303 struct futex_q *q,
Darren Hart52400ba2009-04-03 13:40:49 -07003304 struct hrtimer_sleeper *timeout)
3305{
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003306 int ret;
Darren Hart52400ba2009-04-03 13:40:49 -07003307
3308 /*
3309 * With the hb lock held, we avoid races while we process the wakeup.
3310 * We only need to hold hb (and not hb2) to ensure atomicity as the
3311 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
3312 * It can't be requeued from uaddr2 to something else since we don't
3313 * support a PI aware source futex for requeue.
3314 */
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003315 WARN_ON_ONCE(&hb->lock != q->lock_ptr);
Darren Hart52400ba2009-04-03 13:40:49 -07003316
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003317 /*
3318 * We were woken prior to requeue by a timeout or a signal.
3319 * Unqueue the futex_q and determine which it was.
3320 */
3321 plist_del(&q->list, &hb->chain);
3322 hb_waiters_dec(hb);
3323
3324 /* Handle spurious wakeups gracefully */
3325 ret = -EWOULDBLOCK;
3326 if (timeout && !timeout->task)
3327 ret = -ETIMEDOUT;
3328 else if (signal_pending(current))
3329 ret = -ERESTARTNOINTR;
Darren Hart52400ba2009-04-03 13:40:49 -07003330 return ret;
3331}
3332
3333/**
3334 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
Darren Hart56ec1602009-09-21 22:29:59 -07003335 * @uaddr: the futex we initially wait on (non-pi)
Darren Hartb41277d2010-11-08 13:10:09 -08003336 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
Davidlohr Buesoab51fba2015-06-29 23:26:02 -07003337 * the same type, no requeueing from private to shared, etc.
Darren Hart52400ba2009-04-03 13:40:49 -07003338 * @val: the expected value of uaddr
3339 * @abs_time: absolute timeout
Darren Hart56ec1602009-09-21 22:29:59 -07003340 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
Darren Hart52400ba2009-04-03 13:40:49 -07003341 * @uaddr2: the pi futex we will take prior to returning to user-space
3342 *
3343 * The caller will wait on uaddr and will be requeued by futex_requeue() to
Darren Hart6f7b0a22012-07-20 11:53:31 -07003344 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
3345 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
3346 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
3347 * without one, the pi logic would not know which task to boost/deboost, if
3348 * there was a need to.
Darren Hart52400ba2009-04-03 13:40:49 -07003349 *
3350 * We call schedule in futex_wait_queue_me() when we enqueue and return there
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08003351 * via the following--
Darren Hart52400ba2009-04-03 13:40:49 -07003352 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
Darren Hartcc6db4e2009-07-31 16:20:10 -07003353 * 2) wakeup on uaddr2 after a requeue
3354 * 3) signal
3355 * 4) timeout
Darren Hart52400ba2009-04-03 13:40:49 -07003356 *
Darren Hartcc6db4e2009-07-31 16:20:10 -07003357 * If 3, cleanup and return -ERESTARTNOINTR.
Darren Hart52400ba2009-04-03 13:40:49 -07003358 *
3359 * If 2, we may then block on trying to take the rt_mutex and return via:
3360 * 5) successful lock
3361 * 6) signal
3362 * 7) timeout
3363 * 8) other lock acquisition failure
3364 *
Darren Hartcc6db4e2009-07-31 16:20:10 -07003365 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
Darren Hart52400ba2009-04-03 13:40:49 -07003366 *
3367 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
3368 *
Randy Dunlap6c23cbb2013-03-05 10:00:24 -08003369 * Return:
Mauro Carvalho Chehab7b4ff1a2017-05-11 10:17:45 -03003370 * - 0 - On success;
3371 * - <0 - On error
Darren Hart52400ba2009-04-03 13:40:49 -07003372 */
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03003373int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
3374 u32 val, ktime_t *abs_time, u32 bitset,
3375 u32 __user *uaddr2)
Darren Hart52400ba2009-04-03 13:40:49 -07003376{
Waiman Long5ca584d2019-05-28 12:03:45 -04003377 struct hrtimer_sleeper timeout, *to;
Darren Hart52400ba2009-04-03 13:40:49 -07003378 struct rt_mutex_waiter rt_waiter;
Darren Hart52400ba2009-04-03 13:40:49 -07003379 struct futex_hash_bucket *hb;
Darren Hart5bdb05f2010-11-08 13:40:28 -08003380 union futex_key key2 = FUTEX_KEY_INIT;
3381 struct futex_q q = futex_q_init;
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003382 struct rt_mutex_base *pi_mutex;
Darren Hart52400ba2009-04-03 13:40:49 -07003383 int res, ret;
Darren Hart52400ba2009-04-03 13:40:49 -07003384
Nicolas Pitrebc2eecd2017-08-01 00:31:32 -04003385 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3386 return -ENOSYS;
3387
Darren Hart6f7b0a22012-07-20 11:53:31 -07003388 if (uaddr == uaddr2)
3389 return -EINVAL;
3390
Darren Hart52400ba2009-04-03 13:40:49 -07003391 if (!bitset)
3392 return -EINVAL;
3393
Waiman Long5ca584d2019-05-28 12:03:45 -04003394 to = futex_setup_timer(abs_time, &timeout, flags,
3395 current->timer_slack_ns);
Darren Hart52400ba2009-04-03 13:40:49 -07003396
3397 /*
3398 * The waiter is allocated on our stack, manipulated by the requeue
3399 * code while we sleep on uaddr.
3400 */
Peter Zijlstra50809352017-03-22 11:35:56 +01003401 rt_mutex_init_waiter(&rt_waiter);
Darren Hart52400ba2009-04-03 13:40:49 -07003402
Linus Torvalds96d4f262019-01-03 18:57:57 -08003403 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
Darren Hart52400ba2009-04-03 13:40:49 -07003404 if (unlikely(ret != 0))
3405 goto out;
3406
Darren Hart84bc4af2009-08-13 17:36:53 -07003407 q.bitset = bitset;
3408 q.rt_waiter = &rt_waiter;
3409 q.requeue_pi_key = &key2;
3410
Darren Hart7ada8762010-10-17 08:35:04 -07003411 /*
Thomas Gleixnerc363b7e2021-08-15 23:29:06 +02003412 * Prepare to wait on uaddr. On success, it holds hb->lock and q
3413 * is initialized.
Darren Hart7ada8762010-10-17 08:35:04 -07003414 */
Darren Hartb41277d2010-11-08 13:10:09 -08003415 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
Thomas Gleixnerc8b15a72009-05-20 09:18:50 +02003416 if (ret)
André Almeida9180bd42020-07-02 17:28:40 -03003417 goto out;
Darren Hart52400ba2009-04-03 13:40:49 -07003418
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00003419 /*
3420 * The check above which compares uaddrs is not sufficient for
3421 * shared futexes. We need to compare the keys:
3422 */
3423 if (match_futex(&q.key, &key2)) {
Thomas Gleixner13c42c22014-09-11 23:44:35 +02003424 queue_unlock(hb);
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00003425 ret = -EINVAL;
André Almeida9180bd42020-07-02 17:28:40 -03003426 goto out;
Thomas Gleixnere9c243a2014-06-03 12:27:06 +00003427 }
3428
Darren Hart52400ba2009-04-03 13:40:49 -07003429 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
Thomas Gleixnerf1a11e02009-05-05 19:21:40 +02003430 futex_wait_queue_me(hb, &q, to);
Darren Hart52400ba2009-04-03 13:40:49 -07003431
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003432 switch (futex_requeue_pi_wakeup_sync(&q)) {
3433 case Q_REQUEUE_PI_IGNORE:
3434 /* The waiter is still on uaddr1 */
3435 spin_lock(&hb->lock);
Thomas Gleixner6231acb2021-08-15 23:29:17 +02003436 ret = handle_early_requeue_pi_wakeup(hb, &q, to);
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003437 spin_unlock(&hb->lock);
3438 break;
Darren Hart52400ba2009-04-03 13:40:49 -07003439
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003440 case Q_REQUEUE_PI_LOCKED:
3441 /* The requeue acquired the lock */
Darren Hart52400ba2009-04-03 13:40:49 -07003442 if (q.pi_state && (q.pi_state->owner != current)) {
3443 spin_lock(q.lock_ptr);
Davidlohr Buesoa1565aa2021-02-26 09:50:27 -08003444 ret = fixup_owner(uaddr2, &q, true);
Thomas Gleixnerfb75a422015-12-19 20:07:38 +00003445 /*
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003446 * Drop the reference to the pi state which the
3447 * requeue_pi() code acquired for us.
Thomas Gleixnerfb75a422015-12-19 20:07:38 +00003448 */
Thomas Gleixner29e9ee52015-12-19 20:07:39 +00003449 put_pi_state(q.pi_state);
Darren Hart52400ba2009-04-03 13:40:49 -07003450 spin_unlock(q.lock_ptr);
Thomas Gleixner12bb3f72021-01-20 16:00:24 +01003451 /*
3452 * Adjust the return value. It's either -EFAULT or
3453 * success (1) but the caller expects 0 for success.
3454 */
3455 ret = ret < 0 ? ret : 0;
Darren Hart52400ba2009-04-03 13:40:49 -07003456 }
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003457 break;
Peter Zijlstrac236c8e2017-03-04 10:27:18 +01003458
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003459 case Q_REQUEUE_PI_DONE:
3460 /* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
Darren Hart52400ba2009-04-03 13:40:49 -07003461 pi_mutex = &q.pi_state->pi_mutex;
Peter Zijlstra38d589f2017-03-22 11:35:57 +01003462 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
Darren Hart52400ba2009-04-03 13:40:49 -07003463
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003464 /* Current is not longer pi_blocked_on */
Darren Hart52400ba2009-04-03 13:40:49 -07003465 spin_lock(q.lock_ptr);
Peter Zijlstra38d589f2017-03-22 11:35:57 +01003466 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
3467 ret = 0;
3468
3469 debug_rt_mutex_free_waiter(&rt_waiter);
Darren Hart52400ba2009-04-03 13:40:49 -07003470 /*
3471 * Fixup the pi_state owner and possibly acquire the lock if we
3472 * haven't already.
3473 */
Thomas Gleixnerae791a22010-11-10 13:30:36 +01003474 res = fixup_owner(uaddr2, &q, !ret);
Darren Hart52400ba2009-04-03 13:40:49 -07003475 /*
Ingo Molnar93d09552021-05-12 20:04:28 +02003476 * If fixup_owner() returned an error, propagate that. If it
Darren Hart56ec1602009-09-21 22:29:59 -07003477 * acquired the lock, clear -ETIMEDOUT or -EINTR.
Darren Hart52400ba2009-04-03 13:40:49 -07003478 */
3479 if (res)
3480 ret = (res < 0) ? res : 0;
3481
Darren Hart52400ba2009-04-03 13:40:49 -07003482 unqueue_me_pi(&q);
Davidlohr Buesoa3f24282021-02-26 09:50:28 -08003483 spin_unlock(q.lock_ptr);
Darren Hart52400ba2009-04-03 13:40:49 -07003484
Thomas Gleixner07d91ef52021-08-15 23:29:18 +02003485 if (ret == -EINTR) {
3486 /*
3487 * We've already been requeued, but cannot restart
3488 * by calling futex_lock_pi() directly. We could
3489 * restart this syscall, but it would detect that
3490 * the user space "val" changed and return
3491 * -EWOULDBLOCK. Save the overhead of the restart
3492 * and return -EWOULDBLOCK directly.
3493 */
3494 ret = -EWOULDBLOCK;
3495 }
3496 break;
3497 default:
3498 BUG();
Darren Hart52400ba2009-04-03 13:40:49 -07003499 }
3500
Darren Hart52400ba2009-04-03 13:40:49 -07003501out:
3502 if (to) {
3503 hrtimer_cancel(&to->timer);
3504 destroy_hrtimer_on_stack(&to->timer);
3505 }
3506 return ret;
3507}
3508
Yang Taoca16d5b2019-11-06 22:55:35 +01003509/* Constants for the pending_op argument of handle_futex_death */
3510#define HANDLE_DEATH_PENDING true
3511#define HANDLE_DEATH_LIST false
3512
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003513/*
3514 * Process a futex-list entry, check whether it's owned by the
3515 * dying task, and do notification if so:
3516 */
Yang Taoca16d5b2019-11-06 22:55:35 +01003517static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
3518 bool pi, bool pending_op)
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003519{
Kees Cook3f649ab2020-06-03 13:09:38 -07003520 u32 uval, nval, mval;
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003521 int err;
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003522
Chen Jie5a071682019-03-15 03:44:38 +00003523 /* Futex address must be 32bit aligned */
3524 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3525 return -1;
3526
Ingo Molnar8f17d3a2006-03-27 01:16:27 -08003527retry:
3528 if (get_user(uval, uaddr))
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003529 return -1;
3530
Yang Taoca16d5b2019-11-06 22:55:35 +01003531 /*
3532 * Special case for regular (non PI) futexes. The unlock path in
3533 * user space has two race scenarios:
3534 *
3535 * 1. The unlock path releases the user space futex value and
3536 * before it can execute the futex() syscall to wake up
3537 * waiters it is killed.
3538 *
3539 * 2. A woken up waiter is killed before it can acquire the
3540 * futex in user space.
3541 *
3542 * In both cases the TID validation below prevents a wakeup of
3543 * potential waiters which can cause these waiters to block
3544 * forever.
3545 *
3546 * In both cases the following conditions are met:
3547 *
3548 * 1) task->robust_list->list_op_pending != NULL
3549 * @pending_op == true
3550 * 2) User space futex value == 0
3551 * 3) Regular futex: @pi == false
3552 *
3553 * If these conditions are met, it is safe to attempt waking up a
3554 * potential waiter without touching the user space futex value and
3555 * trying to set the OWNER_DIED bit. The user space futex value is
3556 * uncontended and the rest of the user space mutex state is
3557 * consistent, so a woken waiter will just take over the
3558 * uncontended futex. Setting the OWNER_DIED bit would create
3559 * inconsistent state and malfunction of the user space owner died
3560 * handling.
3561 */
3562 if (pending_op && !pi && !uval) {
3563 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3564 return 0;
3565 }
3566
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003567 if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
3568 return 0;
3569
3570 /*
3571 * Ok, this dying thread is truly holding a futex
3572 * of interest. Set the OWNER_DIED bit atomically
3573 * via cmpxchg, and if the value had FUTEX_WAITERS
3574 * set, wake up a waiter (if any). (We have to do a
3575 * futex_wake() even if OWNER_DIED is already set -
3576 * to handle the rare but possible case of recursive
3577 * thread-death.) The rest of the cleanup is done in
3578 * userspace.
3579 */
3580 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3581
3582 /*
3583 * We are not holding a lock here, but we want to have
3584 * the pagefault_disable/enable() protection because
3585 * we want to handle the fault gracefully. If the
3586 * access fails we try to fault in the futex with R/W
3587 * verification via get_user_pages. get_user() above
3588 * does not guarantee R/W access. If that fails we
3589 * give up and leave the futex locked.
3590 */
3591 if ((err = cmpxchg_futex_value_locked(&nval, uaddr, uval, mval))) {
3592 switch (err) {
3593 case -EFAULT:
Thomas Gleixner6e0aa9f2011-03-14 10:34:35 +01003594 if (fault_in_user_writeable(uaddr))
3595 return -1;
3596 goto retry;
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003597
3598 case -EAGAIN:
3599 cond_resched();
Ingo Molnar8f17d3a2006-03-27 01:16:27 -08003600 goto retry;
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003601
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003602 default:
3603 WARN_ON_ONCE(1);
3604 return err;
3605 }
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003606 }
Will Deacon6b4f4bc2019-02-28 11:58:08 +00003607
3608 if (nval != uval)
3609 goto retry;
3610
3611 /*
3612 * Wake robust non-PI futexes here. The wakeup of
3613 * PI futexes happens in exit_pi_state():
3614 */
3615 if (!pi && (uval & FUTEX_WAITERS))
3616 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3617
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003618 return 0;
3619}
3620
3621/*
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003622 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3623 */
3624static inline int fetch_robust_entry(struct robust_list __user **entry,
Al Viroba46df92006-10-10 22:46:07 +01003625 struct robust_list __user * __user *head,
Namhyung Kim1dcc41b2010-09-14 21:43:46 +09003626 unsigned int *pi)
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003627{
3628 unsigned long uentry;
3629
Al Viroba46df92006-10-10 22:46:07 +01003630 if (get_user(uentry, (unsigned long __user *)head))
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003631 return -EFAULT;
3632
Al Viroba46df92006-10-10 22:46:07 +01003633 *entry = (void __user *)(uentry & ~1UL);
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003634 *pi = uentry & 1;
3635
3636 return 0;
3637}
3638
3639/*
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003640 * Walk curr->robust_list (very carefully, it's a userspace list!)
3641 * and mark any locks found there dead, and notify any waiters.
3642 *
3643 * We silently return on any sign of list-walking problem.
3644 */
Thomas Gleixnerba31c1a42019-11-06 22:55:36 +01003645static void exit_robust_list(struct task_struct *curr)
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003646{
3647 struct robust_list_head __user *head = curr->robust_list;
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003648 struct robust_list __user *entry, *next_entry, *pending;
Darren Hart4c115e92010-11-04 15:00:00 -04003649 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
Kees Cook3f649ab2020-06-03 13:09:38 -07003650 unsigned int next_pi;
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003651 unsigned long futex_offset;
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003652 int rc;
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003653
Thomas Gleixnera0c1e902008-02-23 15:23:57 -08003654 if (!futex_cmpxchg_enabled)
3655 return;
3656
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003657 /*
3658 * Fetch the list head (which was registered earlier, via
3659 * sys_set_robust_list()):
3660 */
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003661 if (fetch_robust_entry(&entry, &head->list.next, &pi))
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003662 return;
3663 /*
3664 * Fetch the relative futex offset:
3665 */
3666 if (get_user(futex_offset, &head->futex_offset))
3667 return;
3668 /*
3669 * Fetch any possibly pending lock-add first, and handle it
3670 * if it exists:
3671 */
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003672 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003673 return;
Ingo Molnare3f2dde2006-07-29 05:17:57 +02003674
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003675 next_entry = NULL; /* avoid warning with gcc */
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003676 while (entry != &head->list) {
3677 /*
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003678 * Fetch the next entry in the list before calling
3679 * handle_futex_death:
3680 */
3681 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
3682 /*
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003683 * A pending lock might already be on the list, so
Ingo Molnarc87e2832006-06-27 02:54:58 -07003684 * don't process it twice:
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003685 */
Yang Taoca16d5b2019-11-06 22:55:35 +01003686 if (entry != pending) {
Al Viroba46df92006-10-10 22:46:07 +01003687 if (handle_futex_death((void __user *)entry + futex_offset,
Yang Taoca16d5b2019-11-06 22:55:35 +01003688 curr, pi, HANDLE_DEATH_LIST))
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003689 return;
Yang Taoca16d5b2019-11-06 22:55:35 +01003690 }
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003691 if (rc)
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003692 return;
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003693 entry = next_entry;
3694 pi = next_pi;
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003695 /*
3696 * Avoid excessively long or circular lists:
3697 */
3698 if (!--limit)
3699 break;
3700
3701 cond_resched();
3702 }
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003703
Yang Taoca16d5b2019-11-06 22:55:35 +01003704 if (pending) {
Martin Schwidefsky9f96cb12007-10-01 01:20:13 -07003705 handle_futex_death((void __user *)pending + futex_offset,
Yang Taoca16d5b2019-11-06 22:55:35 +01003706 curr, pip, HANDLE_DEATH_PENDING);
3707 }
Ingo Molnar0771dfe2006-03-27 01:16:22 -08003708}
3709
Peter Zijlstraaf8cc962021-09-23 14:10:51 -03003710#ifdef CONFIG_COMPAT
3711static void __user *futex_uaddr(struct robust_list __user *entry,
3712 compat_long_t futex_offset)
3713{
3714 compat_uptr_t base = ptr_to_compat(entry);
3715 void __user *uaddr = compat_ptr(base + futex_offset);
3716
3717 return uaddr;
3718}
3719
3720/*
3721 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3722 */
3723static inline int
3724compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
3725 compat_uptr_t __user *head, unsigned int *pi)
3726{
3727 if (get_user(*uentry, head))
3728 return -EFAULT;
3729
3730 *entry = compat_ptr((*uentry) & ~1);
3731 *pi = (unsigned int)(*uentry) & 1;
3732
3733 return 0;
3734}
3735
3736/*
3737 * Walk curr->robust_list (very carefully, it's a userspace list!)
3738 * and mark any locks found there dead, and notify any waiters.
3739 *
3740 * We silently return on any sign of list-walking problem.
3741 */
3742static void compat_exit_robust_list(struct task_struct *curr)
3743{
3744 struct compat_robust_list_head __user *head = curr->compat_robust_list;
3745 struct robust_list __user *entry, *next_entry, *pending;
3746 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3747 unsigned int next_pi;
3748 compat_uptr_t uentry, next_uentry, upending;
3749 compat_long_t futex_offset;
3750 int rc;
3751
3752 if (!futex_cmpxchg_enabled)
3753 return;
3754
3755 /*
3756 * Fetch the list head (which was registered earlier, via
3757 * sys_set_robust_list()):
3758 */
3759 if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
3760 return;
3761 /*
3762 * Fetch the relative futex offset:
3763 */
3764 if (get_user(futex_offset, &head->futex_offset))
3765 return;
3766 /*
3767 * Fetch any possibly pending lock-add first, and handle it
3768 * if it exists:
3769 */
3770 if (compat_fetch_robust_entry(&upending, &pending,
3771 &head->list_op_pending, &pip))
3772 return;
3773
3774 next_entry = NULL; /* avoid warning with gcc */
3775 while (entry != (struct robust_list __user *) &head->list) {
3776 /*
3777 * Fetch the next entry in the list before calling
3778 * handle_futex_death:
3779 */
3780 rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
3781 (compat_uptr_t __user *)&entry->next, &next_pi);
3782 /*
3783 * A pending lock might already be on the list, so
3784 * dont process it twice:
3785 */
3786 if (entry != pending) {
3787 void __user *uaddr = futex_uaddr(entry, futex_offset);
3788
3789 if (handle_futex_death(uaddr, curr, pi,
3790 HANDLE_DEATH_LIST))
3791 return;
3792 }
3793 if (rc)
3794 return;
3795 uentry = next_uentry;
3796 entry = next_entry;
3797 pi = next_pi;
3798 /*
3799 * Avoid excessively long or circular lists:
3800 */
3801 if (!--limit)
3802 break;
3803
3804 cond_resched();
3805 }
3806 if (pending) {
3807 void __user *uaddr = futex_uaddr(pending, futex_offset);
3808
3809 handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
3810 }
3811}
3812#endif
3813
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003814static void futex_cleanup(struct task_struct *tsk)
Thomas Gleixnerba31c1a42019-11-06 22:55:36 +01003815{
3816 if (unlikely(tsk->robust_list)) {
3817 exit_robust_list(tsk);
3818 tsk->robust_list = NULL;
3819 }
3820
3821#ifdef CONFIG_COMPAT
3822 if (unlikely(tsk->compat_robust_list)) {
3823 compat_exit_robust_list(tsk);
3824 tsk->compat_robust_list = NULL;
3825 }
3826#endif
3827
3828 if (unlikely(!list_empty(&tsk->pi_state_list)))
3829 exit_pi_state_list(tsk);
3830}
3831
Thomas Gleixner18f69432019-11-06 22:55:41 +01003832/**
3833 * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
3834 * @tsk: task to set the state on
3835 *
3836 * Set the futex exit state of the task lockless. The futex waiter code
3837 * observes that state when a task is exiting and loops until the task has
3838 * actually finished the futex cleanup. The worst case for this is that the
3839 * waiter runs through the wait loop until the state becomes visible.
3840 *
3841 * This is called from the recursive fault handling path in do_exit().
3842 *
3843 * This is best effort. Either the futex exit code has run already or
3844 * not. If the OWNER_DIED bit has been set on the futex then the waiter can
3845 * take it over. If not, the problem is pushed back to user space. If the
3846 * futex exit code did not run yet, then an already queued waiter might
3847 * block forever, but there is nothing which can be done about that.
3848 */
3849void futex_exit_recursive(struct task_struct *tsk)
3850{
Thomas Gleixner3f186d92019-11-06 22:55:44 +01003851 /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
3852 if (tsk->futex_state == FUTEX_STATE_EXITING)
3853 mutex_unlock(&tsk->futex_exit_mutex);
Thomas Gleixner18f69432019-11-06 22:55:41 +01003854 tsk->futex_state = FUTEX_STATE_DEAD;
3855}
3856
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003857static void futex_cleanup_begin(struct task_struct *tsk)
Thomas Gleixner150d7152019-11-06 22:55:39 +01003858{
Thomas Gleixner18f69432019-11-06 22:55:41 +01003859 /*
Thomas Gleixner3f186d92019-11-06 22:55:44 +01003860 * Prevent various race issues against a concurrent incoming waiter
3861 * including live locks by forcing the waiter to block on
3862 * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
3863 * attach_to_pi_owner().
3864 */
3865 mutex_lock(&tsk->futex_exit_mutex);
3866
3867 /*
Thomas Gleixner4a8e9912019-11-06 22:55:42 +01003868 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
3869 *
3870 * This ensures that all subsequent checks of tsk->futex_state in
3871 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
3872 * tsk->pi_lock held.
3873 *
3874 * It guarantees also that a pi_state which was queued right before
3875 * the state change under tsk->pi_lock by a concurrent waiter must
3876 * be observed in exit_pi_state_list().
Thomas Gleixner18f69432019-11-06 22:55:41 +01003877 */
3878 raw_spin_lock_irq(&tsk->pi_lock);
Thomas Gleixner4a8e9912019-11-06 22:55:42 +01003879 tsk->futex_state = FUTEX_STATE_EXITING;
Thomas Gleixner18f69432019-11-06 22:55:41 +01003880 raw_spin_unlock_irq(&tsk->pi_lock);
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003881}
Thomas Gleixner18f69432019-11-06 22:55:41 +01003882
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003883static void futex_cleanup_end(struct task_struct *tsk, int state)
3884{
3885 /*
3886 * Lockless store. The only side effect is that an observer might
3887 * take another loop until it becomes visible.
3888 */
3889 tsk->futex_state = state;
Thomas Gleixner3f186d92019-11-06 22:55:44 +01003890 /*
3891 * Drop the exit protection. This unblocks waiters which observed
3892 * FUTEX_STATE_EXITING to reevaluate the state.
3893 */
3894 mutex_unlock(&tsk->futex_exit_mutex);
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003895}
Thomas Gleixner18f69432019-11-06 22:55:41 +01003896
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003897void futex_exec_release(struct task_struct *tsk)
3898{
3899 /*
3900 * The state handling is done for consistency, but in the case of
Ingo Molnar93d09552021-05-12 20:04:28 +02003901 * exec() there is no way to prevent further damage as the PID stays
Thomas Gleixneraf8cbda2019-11-06 22:55:43 +01003902 * the same. But for the unlikely and arguably buggy case that a
3903 * futex is held on exec(), this provides at least as much state
3904 * consistency protection which is possible.
3905 */
3906 futex_cleanup_begin(tsk);
3907 futex_cleanup(tsk);
3908 /*
3909 * Reset the state to FUTEX_STATE_OK. The task is alive and about
3910 * exec a new binary.
3911 */
3912 futex_cleanup_end(tsk, FUTEX_STATE_OK);
3913}
3914
3915void futex_exit_release(struct task_struct *tsk)
3916{
3917 futex_cleanup_begin(tsk);
3918 futex_cleanup(tsk);
3919 futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
Thomas Gleixner150d7152019-11-06 22:55:39 +01003920}
3921
Heiko Carstens03b8c7b2014-03-02 13:09:47 +01003922static void __init futex_detect_cmpxchg(void)
3923{
3924#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
3925 u32 curval;
3926
3927 /*
3928 * This will fail and we want it. Some arch implementations do
3929 * runtime detection of the futex_atomic_cmpxchg_inatomic()
3930 * functionality. We want to know that before we call in any
3931 * of the complex code paths. Also we want to prevent
3932 * registration of robust lists in that case. NULL is
3933 * guaranteed to fault and we get -EFAULT on functional
3934 * implementation, the non-functional ones will return
3935 * -ENOSYS.
3936 */
3937 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
3938 futex_cmpxchg_enabled = 1;
3939#endif
3940}
3941
Benjamin Herrenschmidtf6d107f2008-03-27 14:52:15 +11003942static int __init futex_init(void)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003943{
Heiko Carstens63b1a812014-01-16 14:54:50 +01003944 unsigned int futex_shift;
Davidlohr Buesoa52b89e2014-01-12 15:31:23 -08003945 unsigned long i;
3946
3947#if CONFIG_BASE_SMALL
3948 futex_hashsize = 16;
3949#else
3950 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
3951#endif
3952
3953 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
3954 futex_hashsize, 0,
3955 futex_hashsize < 256 ? HASH_SMALL : 0,
Heiko Carstens63b1a812014-01-16 14:54:50 +01003956 &futex_shift, NULL,
3957 futex_hashsize, futex_hashsize);
3958 futex_hashsize = 1UL << futex_shift;
Heiko Carstens03b8c7b2014-03-02 13:09:47 +01003959
3960 futex_detect_cmpxchg();
Thomas Gleixnera0c1e902008-02-23 15:23:57 -08003961
Davidlohr Buesoa52b89e2014-01-12 15:31:23 -08003962 for (i = 0; i < futex_hashsize; i++) {
Linus Torvalds11d46162014-03-20 22:11:17 -07003963 atomic_set(&futex_queues[i].waiters, 0);
Dima Zavin732375c2011-07-07 17:27:59 -07003964 plist_head_init(&futex_queues[i].chain);
Thomas Gleixner3e4ab742008-02-23 15:23:55 -08003965 spin_lock_init(&futex_queues[i].lock);
3966 }
3967
Linus Torvalds1da177e2005-04-16 15:20:36 -07003968 return 0;
3969}
Yang Yang25f71d12016-12-30 16:17:55 +08003970core_initcall(futex_init);