futex: Remove pointless mmgrap() + mmdrop()
[linux-block.git] / kernel / futex.c
CommitLineData
1a59d1b8 1// SPDX-License-Identifier: GPL-2.0-or-later
1da177e4
LT
2/*
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 *
0771dfef
IM
12 * Robust futex support started by Ingo Molnar
13 * (C) Copyright 2006 Red Hat Inc, All Rights Reserved
14 * Thanks to Thomas Gleixner for suggestions, analysis and fixes.
15 *
c87e2837
IM
16 * PI-futex support started by Ingo Molnar and Thomas Gleixner
17 * Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
18 * Copyright (C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
19 *
34f01cc1
ED
20 * PRIVATE futexes by Eric Dumazet
21 * Copyright (C) 2007 Eric Dumazet <dada1@cosmosbay.com>
22 *
52400ba9
DH
23 * Requeue-PI support by Darren Hart <dvhltc@us.ibm.com>
24 * Copyright (C) IBM Corporation, 2009
25 * Thanks to Thomas Gleixner for conceptual design and careful reviews.
26 *
1da177e4
LT
27 * Thanks to Ben LaHaise for yelling "hashed waitqueues" loudly
28 * enough at me, Linus for the original (flawed) idea, Matthew
29 * Kirkwood for proof-of-concept implementation.
30 *
31 * "The futexes are also cursed."
32 * "But they come in a choice of three flavours!"
1da177e4 33 */
04e7712f 34#include <linux/compat.h>
1da177e4
LT
35#include <linux/slab.h>
36#include <linux/poll.h>
37#include <linux/fs.h>
38#include <linux/file.h>
39#include <linux/jhash.h>
40#include <linux/init.h>
41#include <linux/futex.h>
42#include <linux/mount.h>
43#include <linux/pagemap.h>
44#include <linux/syscalls.h>
7ed20e1a 45#include <linux/signal.h>
9984de1a 46#include <linux/export.h>
fd5eea42 47#include <linux/magic.h>
b488893a
PE
48#include <linux/pid.h>
49#include <linux/nsproxy.h>
bdbb776f 50#include <linux/ptrace.h>
8bd75c77 51#include <linux/sched/rt.h>
84f001e1 52#include <linux/sched/wake_q.h>
6e84f315 53#include <linux/sched/mm.h>
13d60f4b 54#include <linux/hugetlb.h>
88c8004f 55#include <linux/freezer.h>
57c8a661 56#include <linux/memblock.h>
ab51fbab 57#include <linux/fault-inject.h>
49262de2 58#include <linux/refcount.h>
b488893a 59
4732efbe 60#include <asm/futex.h>
1da177e4 61
1696a8be 62#include "locking/rtmutex_common.h"
c87e2837 63
99b60ce6 64/*
d7e8af1a
DB
65 * READ this before attempting to hack on futexes!
66 *
67 * Basic futex operation and ordering guarantees
68 * =============================================
99b60ce6
TG
69 *
70 * The waiter reads the futex value in user space and calls
71 * futex_wait(). This function computes the hash bucket and acquires
72 * the hash bucket lock. After that it reads the futex user space value
b0c29f79
DB
73 * again and verifies that the data has not changed. If it has not changed
74 * it enqueues itself into the hash bucket, releases the hash bucket lock
75 * and schedules.
99b60ce6
TG
76 *
77 * The waker side modifies the user space value of the futex and calls
b0c29f79
DB
78 * futex_wake(). This function computes the hash bucket and acquires the
79 * hash bucket lock. Then it looks for waiters on that futex in the hash
80 * bucket and wakes them.
99b60ce6 81 *
b0c29f79
DB
82 * In futex wake up scenarios where no tasks are blocked on a futex, taking
83 * the hb spinlock can be avoided and simply return. In order for this
84 * optimization to work, ordering guarantees must exist so that the waiter
85 * being added to the list is acknowledged when the list is concurrently being
86 * checked by the waker, avoiding scenarios like the following:
99b60ce6
TG
87 *
88 * CPU 0 CPU 1
89 * val = *futex;
90 * sys_futex(WAIT, futex, val);
91 * futex_wait(futex, val);
92 * uval = *futex;
93 * *futex = newval;
94 * sys_futex(WAKE, futex);
95 * futex_wake(futex);
96 * if (queue_empty())
97 * return;
98 * if (uval == val)
99 * lock(hash_bucket(futex));
100 * queue();
101 * unlock(hash_bucket(futex));
102 * schedule();
103 *
104 * This would cause the waiter on CPU 0 to wait forever because it
105 * missed the transition of the user space value from val to newval
106 * and the waker did not find the waiter in the hash bucket queue.
99b60ce6 107 *
b0c29f79
DB
108 * The correct serialization ensures that a waiter either observes
109 * the changed user space value before blocking or is woken by a
110 * concurrent waker:
111 *
112 * CPU 0 CPU 1
99b60ce6
TG
113 * val = *futex;
114 * sys_futex(WAIT, futex, val);
115 * futex_wait(futex, val);
b0c29f79 116 *
d7e8af1a 117 * waiters++; (a)
8ad7b378
DB
118 * smp_mb(); (A) <-- paired with -.
119 * |
120 * lock(hash_bucket(futex)); |
121 * |
122 * uval = *futex; |
123 * | *futex = newval;
124 * | sys_futex(WAKE, futex);
125 * | futex_wake(futex);
126 * |
127 * `--------> smp_mb(); (B)
99b60ce6 128 * if (uval == val)
b0c29f79 129 * queue();
99b60ce6 130 * unlock(hash_bucket(futex));
b0c29f79
DB
131 * schedule(); if (waiters)
132 * lock(hash_bucket(futex));
d7e8af1a
DB
133 * else wake_waiters(futex);
134 * waiters--; (b) unlock(hash_bucket(futex));
b0c29f79 135 *
d7e8af1a
DB
136 * Where (A) orders the waiters increment and the futex value read through
137 * atomic operations (see hb_waiters_inc) and where (B) orders the write
993b2ff2
DB
138 * to futex and the waiters read -- this is done by the barriers for both
139 * shared and private futexes in get_futex_key_refs().
b0c29f79
DB
140 *
141 * This yields the following case (where X:=waiters, Y:=futex):
142 *
143 * X = Y = 0
144 *
145 * w[X]=1 w[Y]=1
146 * MB MB
147 * r[Y]=y r[X]=x
148 *
149 * Which guarantees that x==0 && y==0 is impossible; which translates back into
150 * the guarantee that we cannot both miss the futex variable change and the
151 * enqueue.
d7e8af1a
DB
152 *
153 * Note that a new waiter is accounted for in (a) even when it is possible that
154 * the wait call can return error, in which case we backtrack from it in (b).
155 * Refer to the comment in queue_lock().
156 *
157 * Similarly, in order to account for waiters being requeued on another
158 * address we always increment the waiters for the destination bucket before
159 * acquiring the lock. It then decrements them again after releasing it -
160 * the code that actually moves the futex(es) between hash buckets (requeue_futex)
161 * will do the additional required waiter count housekeeping. This is done for
162 * double_lock_hb() and double_unlock_hb(), respectively.
99b60ce6
TG
163 */
164
04e7712f
AB
165#ifdef CONFIG_HAVE_FUTEX_CMPXCHG
166#define futex_cmpxchg_enabled 1
167#else
168static int __read_mostly futex_cmpxchg_enabled;
03b8c7b6 169#endif
a0c1e907 170
b41277dc
DH
171/*
172 * Futex flags used to encode options to functions and preserve them across
173 * restarts.
174 */
784bdf3b
TG
175#ifdef CONFIG_MMU
176# define FLAGS_SHARED 0x01
177#else
178/*
179 * NOMMU does not have per process address space. Let the compiler optimize
180 * code away.
181 */
182# define FLAGS_SHARED 0x00
183#endif
b41277dc
DH
184#define FLAGS_CLOCKRT 0x02
185#define FLAGS_HAS_TIMEOUT 0x04
186
c87e2837
IM
187/*
188 * Priority Inheritance state:
189 */
190struct futex_pi_state {
191 /*
192 * list of 'owned' pi_state instances - these have to be
193 * cleaned up in do_exit() if the task exits prematurely:
194 */
195 struct list_head list;
196
197 /*
198 * The PI object:
199 */
200 struct rt_mutex pi_mutex;
201
202 struct task_struct *owner;
49262de2 203 refcount_t refcount;
c87e2837
IM
204
205 union futex_key key;
3859a271 206} __randomize_layout;
c87e2837 207
d8d88fbb
DH
208/**
209 * struct futex_q - The hashed futex queue entry, one per waiting task
fb62db2b 210 * @list: priority-sorted list of tasks waiting on this futex
d8d88fbb
DH
211 * @task: the task waiting on the futex
212 * @lock_ptr: the hash bucket lock
213 * @key: the key the futex is hashed on
214 * @pi_state: optional priority inheritance state
215 * @rt_waiter: rt_waiter storage for use with requeue_pi
216 * @requeue_pi_key: the requeue_pi target futex key
217 * @bitset: bitset for the optional bitmasked wakeup
218 *
ac6424b9 219 * We use this hashed waitqueue, instead of a normal wait_queue_entry_t, so
1da177e4
LT
220 * we can wake only the relevant ones (hashed queues may be shared).
221 *
222 * A futex_q has a woken state, just like tasks have TASK_RUNNING.
ec92d082 223 * It is considered woken when plist_node_empty(&q->list) || q->lock_ptr == 0.
fb62db2b 224 * The order of wakeup is always to make the first condition true, then
d8d88fbb
DH
225 * the second.
226 *
227 * PI futexes are typically woken before they are removed from the hash list via
228 * the rt_mutex code. See unqueue_me_pi().
1da177e4
LT
229 */
230struct futex_q {
ec92d082 231 struct plist_node list;
1da177e4 232
d8d88fbb 233 struct task_struct *task;
1da177e4 234 spinlock_t *lock_ptr;
1da177e4 235 union futex_key key;
c87e2837 236 struct futex_pi_state *pi_state;
52400ba9 237 struct rt_mutex_waiter *rt_waiter;
84bc4af5 238 union futex_key *requeue_pi_key;
cd689985 239 u32 bitset;
3859a271 240} __randomize_layout;
1da177e4 241
5bdb05f9
DH
242static const struct futex_q futex_q_init = {
243 /* list gets initialized in queue_me()*/
244 .key = FUTEX_KEY_INIT,
245 .bitset = FUTEX_BITSET_MATCH_ANY
246};
247
1da177e4 248/*
b2d0994b
DH
249 * Hash buckets are shared by all the futex_keys that hash to the same
250 * location. Each key may have multiple futex_q structures, one for each task
251 * waiting on a futex.
1da177e4
LT
252 */
253struct futex_hash_bucket {
11d4616b 254 atomic_t waiters;
ec92d082
PP
255 spinlock_t lock;
256 struct plist_head chain;
a52b89eb 257} ____cacheline_aligned_in_smp;
1da177e4 258
ac742d37
RV
259/*
260 * The base of the bucket array and its size are always used together
261 * (after initialization only in hash_futex()), so ensure that they
262 * reside in the same cacheline.
263 */
264static struct {
265 struct futex_hash_bucket *queues;
266 unsigned long hashsize;
267} __futex_data __read_mostly __aligned(2*sizeof(long));
268#define futex_queues (__futex_data.queues)
269#define futex_hashsize (__futex_data.hashsize)
a52b89eb 270
1da177e4 271
ab51fbab
DB
272/*
273 * Fault injections for futexes.
274 */
275#ifdef CONFIG_FAIL_FUTEX
276
277static struct {
278 struct fault_attr attr;
279
621a5f7a 280 bool ignore_private;
ab51fbab
DB
281} fail_futex = {
282 .attr = FAULT_ATTR_INITIALIZER,
621a5f7a 283 .ignore_private = false,
ab51fbab
DB
284};
285
286static int __init setup_fail_futex(char *str)
287{
288 return setup_fault_attr(&fail_futex.attr, str);
289}
290__setup("fail_futex=", setup_fail_futex);
291
5d285a7f 292static bool should_fail_futex(bool fshared)
ab51fbab
DB
293{
294 if (fail_futex.ignore_private && !fshared)
295 return false;
296
297 return should_fail(&fail_futex.attr, 1);
298}
299
300#ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
301
302static int __init fail_futex_debugfs(void)
303{
304 umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
305 struct dentry *dir;
306
307 dir = fault_create_debugfs_attr("fail_futex", NULL,
308 &fail_futex.attr);
309 if (IS_ERR(dir))
310 return PTR_ERR(dir);
311
0365aeba
GKH
312 debugfs_create_bool("ignore-private", mode, dir,
313 &fail_futex.ignore_private);
ab51fbab
DB
314 return 0;
315}
316
317late_initcall(fail_futex_debugfs);
318
319#endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
320
321#else
322static inline bool should_fail_futex(bool fshared)
323{
324 return false;
325}
326#endif /* CONFIG_FAIL_FUTEX */
327
ba31c1a4
TG
328#ifdef CONFIG_COMPAT
329static void compat_exit_robust_list(struct task_struct *curr);
330#else
331static inline void compat_exit_robust_list(struct task_struct *curr) { }
332#endif
333
11d4616b
LT
334/*
335 * Reflects a new waiter being added to the waitqueue.
336 */
337static inline void hb_waiters_inc(struct futex_hash_bucket *hb)
b0c29f79
DB
338{
339#ifdef CONFIG_SMP
11d4616b 340 atomic_inc(&hb->waiters);
b0c29f79 341 /*
11d4616b 342 * Full barrier (A), see the ordering comment above.
b0c29f79 343 */
4e857c58 344 smp_mb__after_atomic();
11d4616b
LT
345#endif
346}
347
348/*
349 * Reflects a waiter being removed from the waitqueue by wakeup
350 * paths.
351 */
352static inline void hb_waiters_dec(struct futex_hash_bucket *hb)
353{
354#ifdef CONFIG_SMP
355 atomic_dec(&hb->waiters);
356#endif
357}
b0c29f79 358
11d4616b
LT
359static inline int hb_waiters_pending(struct futex_hash_bucket *hb)
360{
361#ifdef CONFIG_SMP
362 return atomic_read(&hb->waiters);
b0c29f79 363#else
11d4616b 364 return 1;
b0c29f79
DB
365#endif
366}
367
e8b61b3f
TG
368/**
369 * hash_futex - Return the hash bucket in the global hash
370 * @key: Pointer to the futex key for which the hash is calculated
371 *
372 * We hash on the keys returned from get_futex_key (see below) and return the
373 * corresponding hash bucket in the global hash.
1da177e4
LT
374 */
375static struct futex_hash_bucket *hash_futex(union futex_key *key)
376{
377 u32 hash = jhash2((u32*)&key->both.word,
378 (sizeof(key->both.word)+sizeof(key->both.ptr))/4,
379 key->both.offset);
a52b89eb 380 return &futex_queues[hash & (futex_hashsize - 1)];
1da177e4
LT
381}
382
e8b61b3f
TG
383
384/**
385 * match_futex - Check whether two futex keys are equal
386 * @key1: Pointer to key1
387 * @key2: Pointer to key2
388 *
1da177e4
LT
389 * Return 1 if two futex_keys are equal, 0 otherwise.
390 */
391static inline int match_futex(union futex_key *key1, union futex_key *key2)
392{
2bc87203
DH
393 return (key1 && key2
394 && key1->both.word == key2->both.word
1da177e4
LT
395 && key1->both.ptr == key2->both.ptr
396 && key1->both.offset == key2->both.offset);
397}
398
38d47c1b
PZ
399/*
400 * Take a reference to the resource addressed by a key.
401 * Can be called while holding spinlocks.
402 *
403 */
404static void get_futex_key_refs(union futex_key *key)
405{
406 if (!key->both.ptr)
407 return;
408
784bdf3b
TG
409 /*
410 * On MMU less systems futexes are always "private" as there is no per
411 * process address space. We need the smp wmb nevertheless - yes,
412 * arch/blackfin has MMU less SMP ...
413 */
414 if (!IS_ENABLED(CONFIG_MMU)) {
415 smp_mb(); /* explicit smp_mb(); (B) */
416 return;
417 }
418
38d47c1b
PZ
419 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
420 case FUT_OFF_INODE:
8019ad13 421 smp_mb(); /* explicit smp_mb(); (B) */
38d47c1b
PZ
422 break;
423 case FUT_OFF_MMSHARED:
22299339 424 smp_mb(); /* explicit smp_mb(); (B) */
38d47c1b 425 break;
76835b0e 426 default:
993b2ff2
DB
427 /*
428 * Private futexes do not hold reference on an inode or
429 * mm, therefore the only purpose of calling get_futex_key_refs
430 * is because we need the barrier for the lockless waiter check.
431 */
8ad7b378 432 smp_mb(); /* explicit smp_mb(); (B) */
38d47c1b
PZ
433 }
434}
435
436/*
437 * Drop a reference to the resource addressed by a key.
993b2ff2
DB
438 * The hash bucket spinlock must not be held. This is
439 * a no-op for private futexes, see comment in the get
440 * counterpart.
38d47c1b
PZ
441 */
442static void drop_futex_key_refs(union futex_key *key)
443{
90621c40
DH
444 if (!key->both.ptr) {
445 /* If we're here then we tried to put a key we failed to get */
446 WARN_ON_ONCE(1);
38d47c1b 447 return;
90621c40 448 }
38d47c1b 449
784bdf3b
TG
450 if (!IS_ENABLED(CONFIG_MMU))
451 return;
452
38d47c1b
PZ
453 switch (key->both.offset & (FUT_OFF_INODE|FUT_OFF_MMSHARED)) {
454 case FUT_OFF_INODE:
38d47c1b
PZ
455 break;
456 case FUT_OFF_MMSHARED:
38d47c1b
PZ
457 break;
458 }
459}
460
96d4f267
LT
461enum futex_access {
462 FUTEX_READ,
463 FUTEX_WRITE
464};
465
5ca584d9
WL
466/**
467 * futex_setup_timer - set up the sleeping hrtimer.
468 * @time: ptr to the given timeout value
469 * @timeout: the hrtimer_sleeper structure to be set up
470 * @flags: futex flags
471 * @range_ns: optional range in ns
472 *
473 * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
474 * value given
475 */
476static inline struct hrtimer_sleeper *
477futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
478 int flags, u64 range_ns)
479{
480 if (!time)
481 return NULL;
482
dbc1625f
SAS
483 hrtimer_init_sleeper_on_stack(timeout, (flags & FLAGS_CLOCKRT) ?
484 CLOCK_REALTIME : CLOCK_MONOTONIC,
485 HRTIMER_MODE_ABS);
5ca584d9
WL
486 /*
487 * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
488 * effectively the same as calling hrtimer_set_expires().
489 */
490 hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
491
492 return timeout;
493}
494
8019ad13
PZ
495/*
496 * Generate a machine wide unique identifier for this inode.
497 *
498 * This relies on u64 not wrapping in the life-time of the machine; which with
499 * 1ns resolution means almost 585 years.
500 *
501 * This further relies on the fact that a well formed program will not unmap
502 * the file while it has a (shared) futex waiting on it. This mapping will have
503 * a file reference which pins the mount and inode.
504 *
505 * If for some reason an inode gets evicted and read back in again, it will get
506 * a new sequence number and will _NOT_ match, even though it is the exact same
507 * file.
508 *
509 * It is important that match_futex() will never have a false-positive, esp.
510 * for PI futexes that can mess up the state. The above argues that false-negatives
511 * are only possible for malformed programs.
512 */
513static u64 get_inode_sequence_number(struct inode *inode)
514{
515 static atomic64_t i_seq;
516 u64 old;
517
518 /* Does the inode already have a sequence number? */
519 old = atomic64_read(&inode->i_sequence);
520 if (likely(old))
521 return old;
522
523 for (;;) {
524 u64 new = atomic64_add_return(1, &i_seq);
525 if (WARN_ON_ONCE(!new))
526 continue;
527
528 old = atomic64_cmpxchg_relaxed(&inode->i_sequence, 0, new);
529 if (old)
530 return old;
531 return new;
532 }
533}
534
34f01cc1 535/**
d96ee56c
DH
536 * get_futex_key() - Get parameters which are the keys for a futex
537 * @uaddr: virtual address of the futex
538 * @fshared: 0 for a PROCESS_PRIVATE futex, 1 for PROCESS_SHARED
539 * @key: address where result is stored.
96d4f267
LT
540 * @rw: mapping needs to be read/write (values: FUTEX_READ,
541 * FUTEX_WRITE)
34f01cc1 542 *
6c23cbbd
RD
543 * Return: a negative error code or 0
544 *
7b4ff1ad 545 * The key words are stored in @key on success.
1da177e4 546 *
8019ad13
PZ
547 * For shared mappings (when @fshared), the key is:
548 * ( inode->i_sequence, page->index, offset_within_page )
549 * [ also see get_inode_sequence_number() ]
550 *
551 * For private mappings (or when !@fshared), the key is:
552 * ( current->mm, address, 0 )
553 *
554 * This allows (cross process, where applicable) identification of the futex
555 * without keeping the page pinned for the duration of the FUTEX_WAIT.
1da177e4 556 *
b2d0994b 557 * lock_page() might sleep, the caller should not hold a spinlock.
1da177e4 558 */
64d1304a 559static int
96d4f267 560get_futex_key(u32 __user *uaddr, int fshared, union futex_key *key, enum futex_access rw)
1da177e4 561{
e2970f2f 562 unsigned long address = (unsigned long)uaddr;
1da177e4 563 struct mm_struct *mm = current->mm;
077fa7ae 564 struct page *page, *tail;
14d27abd 565 struct address_space *mapping;
9ea71503 566 int err, ro = 0;
1da177e4
LT
567
568 /*
569 * The futex address must be "naturally" aligned.
570 */
e2970f2f 571 key->both.offset = address % PAGE_SIZE;
34f01cc1 572 if (unlikely((address % sizeof(u32)) != 0))
1da177e4 573 return -EINVAL;
e2970f2f 574 address -= key->both.offset;
1da177e4 575
96d4f267 576 if (unlikely(!access_ok(uaddr, sizeof(u32))))
5cdec2d8
LT
577 return -EFAULT;
578
ab51fbab
DB
579 if (unlikely(should_fail_futex(fshared)))
580 return -EFAULT;
581
34f01cc1
ED
582 /*
583 * PROCESS_PRIVATE futexes are fast.
584 * As the mm cannot disappear under us and the 'key' only needs
585 * virtual address, we dont even have to find the underlying vma.
586 * Note : We do have to check 'uaddr' is a valid user address,
587 * but access_ok() should be faster than find_vma()
588 */
589 if (!fshared) {
34f01cc1
ED
590 key->private.mm = mm;
591 key->private.address = address;
8ad7b378 592 get_futex_key_refs(key); /* implies smp_mb(); (B) */
34f01cc1
ED
593 return 0;
594 }
1da177e4 595
38d47c1b 596again:
ab51fbab
DB
597 /* Ignore any VERIFY_READ mapping (futex common case) */
598 if (unlikely(should_fail_futex(fshared)))
599 return -EFAULT;
600
73b0140b 601 err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
9ea71503
SB
602 /*
603 * If write access is not required (eg. FUTEX_WAIT), try
604 * and get read-only access.
605 */
96d4f267 606 if (err == -EFAULT && rw == FUTEX_READ) {
9ea71503
SB
607 err = get_user_pages_fast(address, 1, 0, &page);
608 ro = 1;
609 }
38d47c1b
PZ
610 if (err < 0)
611 return err;
9ea71503
SB
612 else
613 err = 0;
38d47c1b 614
65d8fc77
MG
615 /*
616 * The treatment of mapping from this point on is critical. The page
617 * lock protects many things but in this context the page lock
618 * stabilizes mapping, prevents inode freeing in the shared
619 * file-backed region case and guards against movement to swap cache.
620 *
621 * Strictly speaking the page lock is not needed in all cases being
622 * considered here and page lock forces unnecessarily serialization
623 * From this point on, mapping will be re-verified if necessary and
624 * page lock will be acquired only if it is unavoidable
077fa7ae
MG
625 *
626 * Mapping checks require the head page for any compound page so the
627 * head page and mapping is looked up now. For anonymous pages, it
628 * does not matter if the page splits in the future as the key is
629 * based on the address. For filesystem-backed pages, the tail is
630 * required as the index of the page determines the key. For
631 * base pages, there is no tail page and tail == page.
65d8fc77 632 */
077fa7ae 633 tail = page;
65d8fc77
MG
634 page = compound_head(page);
635 mapping = READ_ONCE(page->mapping);
636
e6780f72 637 /*
14d27abd 638 * If page->mapping is NULL, then it cannot be a PageAnon
e6780f72
HD
639 * page; but it might be the ZERO_PAGE or in the gate area or
640 * in a special mapping (all cases which we are happy to fail);
641 * or it may have been a good file page when get_user_pages_fast
642 * found it, but truncated or holepunched or subjected to
643 * invalidate_complete_page2 before we got the page lock (also
644 * cases which we are happy to fail). And we hold a reference,
645 * so refcount care in invalidate_complete_page's remove_mapping
646 * prevents drop_caches from setting mapping to NULL beneath us.
647 *
648 * The case we do have to guard against is when memory pressure made
649 * shmem_writepage move it from filecache to swapcache beneath us:
14d27abd 650 * an unlikely race, but we do need to retry for page->mapping.
e6780f72 651 */
65d8fc77
MG
652 if (unlikely(!mapping)) {
653 int shmem_swizzled;
654
655 /*
656 * Page lock is required to identify which special case above
657 * applies. If this is really a shmem page then the page lock
658 * will prevent unexpected transitions.
659 */
660 lock_page(page);
661 shmem_swizzled = PageSwapCache(page) || page->mapping;
14d27abd
KS
662 unlock_page(page);
663 put_page(page);
65d8fc77 664
e6780f72
HD
665 if (shmem_swizzled)
666 goto again;
65d8fc77 667
e6780f72 668 return -EFAULT;
38d47c1b 669 }
1da177e4
LT
670
671 /*
672 * Private mappings are handled in a simple way.
673 *
65d8fc77
MG
674 * If the futex key is stored on an anonymous page, then the associated
675 * object is the mm which is implicitly pinned by the calling process.
676 *
1da177e4
LT
677 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
678 * it's a read-only handle, it's expected that futexes attach to
38d47c1b 679 * the object not the particular process.
1da177e4 680 */
14d27abd 681 if (PageAnon(page)) {
9ea71503
SB
682 /*
683 * A RO anonymous page will never change and thus doesn't make
684 * sense for futex operations.
685 */
ab51fbab 686 if (unlikely(should_fail_futex(fshared)) || ro) {
9ea71503
SB
687 err = -EFAULT;
688 goto out;
689 }
690
38d47c1b 691 key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
1da177e4 692 key->private.mm = mm;
e2970f2f 693 key->private.address = address;
65d8fc77 694
38d47c1b 695 } else {
65d8fc77
MG
696 struct inode *inode;
697
698 /*
699 * The associated futex object in this case is the inode and
700 * the page->mapping must be traversed. Ordinarily this should
701 * be stabilised under page lock but it's not strictly
702 * necessary in this case as we just want to pin the inode, not
703 * update the radix tree or anything like that.
704 *
705 * The RCU read lock is taken as the inode is finally freed
706 * under RCU. If the mapping still matches expectations then the
707 * mapping->host can be safely accessed as being a valid inode.
708 */
709 rcu_read_lock();
710
711 if (READ_ONCE(page->mapping) != mapping) {
712 rcu_read_unlock();
713 put_page(page);
714
715 goto again;
716 }
717
718 inode = READ_ONCE(mapping->host);
719 if (!inode) {
720 rcu_read_unlock();
721 put_page(page);
722
723 goto again;
724 }
725
38d47c1b 726 key->both.offset |= FUT_OFF_INODE; /* inode-based key */
8019ad13 727 key->shared.i_seq = get_inode_sequence_number(inode);
077fa7ae 728 key->shared.pgoff = basepage_index(tail);
65d8fc77 729 rcu_read_unlock();
1da177e4
LT
730 }
731
8019ad13
PZ
732 get_futex_key_refs(key); /* implies smp_mb(); (B) */
733
9ea71503 734out:
14d27abd 735 put_page(page);
9ea71503 736 return err;
1da177e4
LT
737}
738
ae791a2d 739static inline void put_futex_key(union futex_key *key)
1da177e4 740{
38d47c1b 741 drop_futex_key_refs(key);
1da177e4
LT
742}
743
d96ee56c
DH
744/**
745 * fault_in_user_writeable() - Fault in user address and verify RW access
d0725992
TG
746 * @uaddr: pointer to faulting user space address
747 *
748 * Slow path to fixup the fault we just took in the atomic write
749 * access to @uaddr.
750 *
fb62db2b 751 * We have no generic implementation of a non-destructive write to the
d0725992
TG
752 * user address. We know that we faulted in the atomic pagefault
753 * disabled section so we can as well avoid the #PF overhead by
754 * calling get_user_pages() right away.
755 */
756static int fault_in_user_writeable(u32 __user *uaddr)
757{
722d0172
AK
758 struct mm_struct *mm = current->mm;
759 int ret;
760
761 down_read(&mm->mmap_sem);
2efaca92 762 ret = fixup_user_fault(current, mm, (unsigned long)uaddr,
4a9e1cda 763 FAULT_FLAG_WRITE, NULL);
722d0172
AK
764 up_read(&mm->mmap_sem);
765
d0725992
TG
766 return ret < 0 ? ret : 0;
767}
768
4b1c486b
DH
769/**
770 * futex_top_waiter() - Return the highest priority waiter on a futex
d96ee56c
DH
771 * @hb: the hash bucket the futex_q's reside in
772 * @key: the futex key (to distinguish it from other futex futex_q's)
4b1c486b
DH
773 *
774 * Must be called with the hb lock held.
775 */
776static struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb,
777 union futex_key *key)
778{
779 struct futex_q *this;
780
781 plist_for_each_entry(this, &hb->chain, list) {
782 if (match_futex(&this->key, key))
783 return this;
784 }
785 return NULL;
786}
787
37a9d912
ML
788static int cmpxchg_futex_value_locked(u32 *curval, u32 __user *uaddr,
789 u32 uval, u32 newval)
36cf3b5c 790{
37a9d912 791 int ret;
36cf3b5c
TG
792
793 pagefault_disable();
37a9d912 794 ret = futex_atomic_cmpxchg_inatomic(curval, uaddr, uval, newval);
36cf3b5c
TG
795 pagefault_enable();
796
37a9d912 797 return ret;
36cf3b5c
TG
798}
799
800static int get_futex_value_locked(u32 *dest, u32 __user *from)
1da177e4
LT
801{
802 int ret;
803
a866374a 804 pagefault_disable();
bd28b145 805 ret = __get_user(*dest, from);
a866374a 806 pagefault_enable();
1da177e4
LT
807
808 return ret ? -EFAULT : 0;
809}
810
c87e2837
IM
811
812/*
813 * PI code:
814 */
815static int refill_pi_state_cache(void)
816{
817 struct futex_pi_state *pi_state;
818
819 if (likely(current->pi_state_cache))
820 return 0;
821
4668edc3 822 pi_state = kzalloc(sizeof(*pi_state), GFP_KERNEL);
c87e2837
IM
823
824 if (!pi_state)
825 return -ENOMEM;
826
c87e2837
IM
827 INIT_LIST_HEAD(&pi_state->list);
828 /* pi_mutex gets initialized later */
829 pi_state->owner = NULL;
49262de2 830 refcount_set(&pi_state->refcount, 1);
38d47c1b 831 pi_state->key = FUTEX_KEY_INIT;
c87e2837
IM
832
833 current->pi_state_cache = pi_state;
834
835 return 0;
836}
837
bf92cf3a 838static struct futex_pi_state *alloc_pi_state(void)
c87e2837
IM
839{
840 struct futex_pi_state *pi_state = current->pi_state_cache;
841
842 WARN_ON(!pi_state);
843 current->pi_state_cache = NULL;
844
845 return pi_state;
846}
847
bf92cf3a
PZ
848static void get_pi_state(struct futex_pi_state *pi_state)
849{
49262de2 850 WARN_ON_ONCE(!refcount_inc_not_zero(&pi_state->refcount));
bf92cf3a
PZ
851}
852
30a6b803 853/*
29e9ee5d
TG
854 * Drops a reference to the pi_state object and frees or caches it
855 * when the last reference is gone.
30a6b803 856 */
29e9ee5d 857static void put_pi_state(struct futex_pi_state *pi_state)
c87e2837 858{
30a6b803
BS
859 if (!pi_state)
860 return;
861
49262de2 862 if (!refcount_dec_and_test(&pi_state->refcount))
c87e2837
IM
863 return;
864
865 /*
866 * If pi_state->owner is NULL, the owner is most probably dying
867 * and has cleaned up the pi_state already
868 */
869 if (pi_state->owner) {
c74aef2d 870 struct task_struct *owner;
c87e2837 871
c74aef2d
PZ
872 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
873 owner = pi_state->owner;
874 if (owner) {
875 raw_spin_lock(&owner->pi_lock);
876 list_del_init(&pi_state->list);
877 raw_spin_unlock(&owner->pi_lock);
878 }
879 rt_mutex_proxy_unlock(&pi_state->pi_mutex, owner);
880 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
c87e2837
IM
881 }
882
c74aef2d 883 if (current->pi_state_cache) {
c87e2837 884 kfree(pi_state);
c74aef2d 885 } else {
c87e2837
IM
886 /*
887 * pi_state->list is already empty.
888 * clear pi_state->owner.
889 * refcount is at 0 - put it back to 1.
890 */
891 pi_state->owner = NULL;
49262de2 892 refcount_set(&pi_state->refcount, 1);
c87e2837
IM
893 current->pi_state_cache = pi_state;
894 }
895}
896
bc2eecd7
NP
897#ifdef CONFIG_FUTEX_PI
898
c87e2837
IM
899/*
900 * This task is holding PI mutexes at exit time => bad.
901 * Kernel cleans up PI-state, but userspace is likely hosed.
902 * (Robust-futex cleanup is separate and might save the day for userspace.)
903 */
ba31c1a4 904static void exit_pi_state_list(struct task_struct *curr)
c87e2837 905{
c87e2837
IM
906 struct list_head *next, *head = &curr->pi_state_list;
907 struct futex_pi_state *pi_state;
627371d7 908 struct futex_hash_bucket *hb;
38d47c1b 909 union futex_key key = FUTEX_KEY_INIT;
c87e2837 910
a0c1e907
TG
911 if (!futex_cmpxchg_enabled)
912 return;
c87e2837
IM
913 /*
914 * We are a ZOMBIE and nobody can enqueue itself on
915 * pi_state_list anymore, but we have to be careful
627371d7 916 * versus waiters unqueueing themselves:
c87e2837 917 */
1d615482 918 raw_spin_lock_irq(&curr->pi_lock);
c87e2837 919 while (!list_empty(head)) {
c87e2837
IM
920 next = head->next;
921 pi_state = list_entry(next, struct futex_pi_state, list);
922 key = pi_state->key;
627371d7 923 hb = hash_futex(&key);
153fbd12
PZ
924
925 /*
926 * We can race against put_pi_state() removing itself from the
927 * list (a waiter going away). put_pi_state() will first
928 * decrement the reference count and then modify the list, so
929 * its possible to see the list entry but fail this reference
930 * acquire.
931 *
932 * In that case; drop the locks to let put_pi_state() make
933 * progress and retry the loop.
934 */
49262de2 935 if (!refcount_inc_not_zero(&pi_state->refcount)) {
153fbd12
PZ
936 raw_spin_unlock_irq(&curr->pi_lock);
937 cpu_relax();
938 raw_spin_lock_irq(&curr->pi_lock);
939 continue;
940 }
1d615482 941 raw_spin_unlock_irq(&curr->pi_lock);
c87e2837 942
c87e2837 943 spin_lock(&hb->lock);
c74aef2d
PZ
944 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
945 raw_spin_lock(&curr->pi_lock);
627371d7
IM
946 /*
947 * We dropped the pi-lock, so re-check whether this
948 * task still owns the PI-state:
949 */
c87e2837 950 if (head->next != next) {
153fbd12 951 /* retain curr->pi_lock for the loop invariant */
c74aef2d 952 raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
c87e2837 953 spin_unlock(&hb->lock);
153fbd12 954 put_pi_state(pi_state);
c87e2837
IM
955 continue;
956 }
957
c87e2837 958 WARN_ON(pi_state->owner != curr);
627371d7
IM
959 WARN_ON(list_empty(&pi_state->list));
960 list_del_init(&pi_state->list);
c87e2837 961 pi_state->owner = NULL;
c87e2837 962
153fbd12 963 raw_spin_unlock(&curr->pi_lock);
c74aef2d 964 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
c87e2837
IM
965 spin_unlock(&hb->lock);
966
16ffa12d
PZ
967 rt_mutex_futex_unlock(&pi_state->pi_mutex);
968 put_pi_state(pi_state);
969
1d615482 970 raw_spin_lock_irq(&curr->pi_lock);
c87e2837 971 }
1d615482 972 raw_spin_unlock_irq(&curr->pi_lock);
c87e2837 973}
ba31c1a4
TG
974#else
975static inline void exit_pi_state_list(struct task_struct *curr) { }
bc2eecd7
NP
976#endif
977
54a21788
TG
978/*
979 * We need to check the following states:
980 *
981 * Waiter | pi_state | pi->owner | uTID | uODIED | ?
982 *
983 * [1] NULL | --- | --- | 0 | 0/1 | Valid
984 * [2] NULL | --- | --- | >0 | 0/1 | Valid
985 *
986 * [3] Found | NULL | -- | Any | 0/1 | Invalid
987 *
988 * [4] Found | Found | NULL | 0 | 1 | Valid
989 * [5] Found | Found | NULL | >0 | 1 | Invalid
990 *
991 * [6] Found | Found | task | 0 | 1 | Valid
992 *
993 * [7] Found | Found | NULL | Any | 0 | Invalid
994 *
995 * [8] Found | Found | task | ==taskTID | 0/1 | Valid
996 * [9] Found | Found | task | 0 | 0 | Invalid
997 * [10] Found | Found | task | !=taskTID | 0/1 | Invalid
998 *
999 * [1] Indicates that the kernel can acquire the futex atomically. We
1000 * came came here due to a stale FUTEX_WAITERS/FUTEX_OWNER_DIED bit.
1001 *
1002 * [2] Valid, if TID does not belong to a kernel thread. If no matching
1003 * thread is found then it indicates that the owner TID has died.
1004 *
1005 * [3] Invalid. The waiter is queued on a non PI futex
1006 *
1007 * [4] Valid state after exit_robust_list(), which sets the user space
1008 * value to FUTEX_WAITERS | FUTEX_OWNER_DIED.
1009 *
1010 * [5] The user space value got manipulated between exit_robust_list()
1011 * and exit_pi_state_list()
1012 *
1013 * [6] Valid state after exit_pi_state_list() which sets the new owner in
1014 * the pi_state but cannot access the user space value.
1015 *
1016 * [7] pi_state->owner can only be NULL when the OWNER_DIED bit is set.
1017 *
1018 * [8] Owner and user space value match
1019 *
1020 * [9] There is no transient state which sets the user space TID to 0
1021 * except exit_robust_list(), but this is indicated by the
1022 * FUTEX_OWNER_DIED bit. See [4]
1023 *
1024 * [10] There is no transient state which leaves owner and user space
1025 * TID out of sync.
734009e9
PZ
1026 *
1027 *
1028 * Serialization and lifetime rules:
1029 *
1030 * hb->lock:
1031 *
1032 * hb -> futex_q, relation
1033 * futex_q -> pi_state, relation
1034 *
1035 * (cannot be raw because hb can contain arbitrary amount
1036 * of futex_q's)
1037 *
1038 * pi_mutex->wait_lock:
1039 *
1040 * {uval, pi_state}
1041 *
1042 * (and pi_mutex 'obviously')
1043 *
1044 * p->pi_lock:
1045 *
1046 * p->pi_state_list -> pi_state->list, relation
1047 *
1048 * pi_state->refcount:
1049 *
1050 * pi_state lifetime
1051 *
1052 *
1053 * Lock order:
1054 *
1055 * hb->lock
1056 * pi_mutex->wait_lock
1057 * p->pi_lock
1058 *
54a21788 1059 */
e60cbc5c
TG
1060
1061/*
1062 * Validate that the existing waiter has a pi_state and sanity check
1063 * the pi_state against the user space value. If correct, attach to
1064 * it.
1065 */
734009e9
PZ
1066static int attach_to_pi_state(u32 __user *uaddr, u32 uval,
1067 struct futex_pi_state *pi_state,
e60cbc5c 1068 struct futex_pi_state **ps)
c87e2837 1069{
778e9a9c 1070 pid_t pid = uval & FUTEX_TID_MASK;
94ffac5d
PZ
1071 u32 uval2;
1072 int ret;
c87e2837 1073
e60cbc5c
TG
1074 /*
1075 * Userspace might have messed up non-PI and PI futexes [3]
1076 */
1077 if (unlikely(!pi_state))
1078 return -EINVAL;
06a9ec29 1079
734009e9
PZ
1080 /*
1081 * We get here with hb->lock held, and having found a
1082 * futex_top_waiter(). This means that futex_lock_pi() of said futex_q
1083 * has dropped the hb->lock in between queue_me() and unqueue_me_pi(),
1084 * which in turn means that futex_lock_pi() still has a reference on
1085 * our pi_state.
16ffa12d
PZ
1086 *
1087 * The waiter holding a reference on @pi_state also protects against
1088 * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi()
1089 * and futex_wait_requeue_pi() as it cannot go to 0 and consequently
1090 * free pi_state before we can take a reference ourselves.
734009e9 1091 */
49262de2 1092 WARN_ON(!refcount_read(&pi_state->refcount));
59647b6a 1093
734009e9
PZ
1094 /*
1095 * Now that we have a pi_state, we can acquire wait_lock
1096 * and do the state validation.
1097 */
1098 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1099
1100 /*
1101 * Since {uval, pi_state} is serialized by wait_lock, and our current
1102 * uval was read without holding it, it can have changed. Verify it
1103 * still is what we expect it to be, otherwise retry the entire
1104 * operation.
1105 */
1106 if (get_futex_value_locked(&uval2, uaddr))
1107 goto out_efault;
1108
1109 if (uval != uval2)
1110 goto out_eagain;
1111
e60cbc5c
TG
1112 /*
1113 * Handle the owner died case:
1114 */
1115 if (uval & FUTEX_OWNER_DIED) {
bd1dbcc6 1116 /*
e60cbc5c
TG
1117 * exit_pi_state_list sets owner to NULL and wakes the
1118 * topmost waiter. The task which acquires the
1119 * pi_state->rt_mutex will fixup owner.
bd1dbcc6 1120 */
e60cbc5c 1121 if (!pi_state->owner) {
59647b6a 1122 /*
e60cbc5c
TG
1123 * No pi state owner, but the user space TID
1124 * is not 0. Inconsistent state. [5]
59647b6a 1125 */
e60cbc5c 1126 if (pid)
734009e9 1127 goto out_einval;
bd1dbcc6 1128 /*
e60cbc5c 1129 * Take a ref on the state and return success. [4]
866293ee 1130 */
734009e9 1131 goto out_attach;
c87e2837 1132 }
bd1dbcc6
TG
1133
1134 /*
e60cbc5c
TG
1135 * If TID is 0, then either the dying owner has not
1136 * yet executed exit_pi_state_list() or some waiter
1137 * acquired the rtmutex in the pi state, but did not
1138 * yet fixup the TID in user space.
1139 *
1140 * Take a ref on the state and return success. [6]
1141 */
1142 if (!pid)
734009e9 1143 goto out_attach;
e60cbc5c
TG
1144 } else {
1145 /*
1146 * If the owner died bit is not set, then the pi_state
1147 * must have an owner. [7]
bd1dbcc6 1148 */
e60cbc5c 1149 if (!pi_state->owner)
734009e9 1150 goto out_einval;
c87e2837
IM
1151 }
1152
e60cbc5c
TG
1153 /*
1154 * Bail out if user space manipulated the futex value. If pi
1155 * state exists then the owner TID must be the same as the
1156 * user space TID. [9/10]
1157 */
1158 if (pid != task_pid_vnr(pi_state->owner))
734009e9
PZ
1159 goto out_einval;
1160
1161out_attach:
bf92cf3a 1162 get_pi_state(pi_state);
734009e9 1163 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
e60cbc5c
TG
1164 *ps = pi_state;
1165 return 0;
734009e9
PZ
1166
1167out_einval:
1168 ret = -EINVAL;
1169 goto out_error;
1170
1171out_eagain:
1172 ret = -EAGAIN;
1173 goto out_error;
1174
1175out_efault:
1176 ret = -EFAULT;
1177 goto out_error;
1178
1179out_error:
1180 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1181 return ret;
e60cbc5c
TG
1182}
1183
3ef240ea
TG
1184/**
1185 * wait_for_owner_exiting - Block until the owner has exited
51bfb1d1 1186 * @ret: owner's current futex lock status
3ef240ea
TG
1187 * @exiting: Pointer to the exiting task
1188 *
1189 * Caller must hold a refcount on @exiting.
1190 */
1191static void wait_for_owner_exiting(int ret, struct task_struct *exiting)
1192{
1193 if (ret != -EBUSY) {
1194 WARN_ON_ONCE(exiting);
1195 return;
1196 }
1197
1198 if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
1199 return;
1200
1201 mutex_lock(&exiting->futex_exit_mutex);
1202 /*
1203 * No point in doing state checking here. If the waiter got here
1204 * while the task was in exec()->exec_futex_release() then it can
1205 * have any FUTEX_STATE_* value when the waiter has acquired the
1206 * mutex. OK, if running, EXITING or DEAD if it reached exit()
1207 * already. Highly unlikely and not a problem. Just one more round
1208 * through the futex maze.
1209 */
1210 mutex_unlock(&exiting->futex_exit_mutex);
1211
1212 put_task_struct(exiting);
1213}
1214
da791a66
TG
1215static int handle_exit_race(u32 __user *uaddr, u32 uval,
1216 struct task_struct *tsk)
1217{
1218 u32 uval2;
1219
1220 /*
ac31c7ff
TG
1221 * If the futex exit state is not yet FUTEX_STATE_DEAD, tell the
1222 * caller that the alleged owner is busy.
da791a66 1223 */
3d4775df 1224 if (tsk && tsk->futex_state != FUTEX_STATE_DEAD)
ac31c7ff 1225 return -EBUSY;
da791a66
TG
1226
1227 /*
1228 * Reread the user space value to handle the following situation:
1229 *
1230 * CPU0 CPU1
1231 *
1232 * sys_exit() sys_futex()
1233 * do_exit() futex_lock_pi()
1234 * futex_lock_pi_atomic()
1235 * exit_signals(tsk) No waiters:
1236 * tsk->flags |= PF_EXITING; *uaddr == 0x00000PID
1237 * mm_release(tsk) Set waiter bit
1238 * exit_robust_list(tsk) { *uaddr = 0x80000PID;
1239 * Set owner died attach_to_pi_owner() {
1240 * *uaddr = 0xC0000000; tsk = get_task(PID);
1241 * } if (!tsk->flags & PF_EXITING) {
1242 * ... attach();
3d4775df
TG
1243 * tsk->futex_state = } else {
1244 * FUTEX_STATE_DEAD; if (tsk->futex_state !=
1245 * FUTEX_STATE_DEAD)
da791a66
TG
1246 * return -EAGAIN;
1247 * return -ESRCH; <--- FAIL
1248 * }
1249 *
1250 * Returning ESRCH unconditionally is wrong here because the
1251 * user space value has been changed by the exiting task.
1252 *
1253 * The same logic applies to the case where the exiting task is
1254 * already gone.
1255 */
1256 if (get_futex_value_locked(&uval2, uaddr))
1257 return -EFAULT;
1258
1259 /* If the user space value has changed, try again. */
1260 if (uval2 != uval)
1261 return -EAGAIN;
1262
1263 /*
1264 * The exiting task did not have a robust list, the robust list was
1265 * corrupted or the user space value in *uaddr is simply bogus.
1266 * Give up and tell user space.
1267 */
1268 return -ESRCH;
1269}
1270
04e1b2e5
TG
1271/*
1272 * Lookup the task for the TID provided from user space and attach to
1273 * it after doing proper sanity checks.
1274 */
da791a66 1275static int attach_to_pi_owner(u32 __user *uaddr, u32 uval, union futex_key *key,
3ef240ea
TG
1276 struct futex_pi_state **ps,
1277 struct task_struct **exiting)
e60cbc5c 1278{
e60cbc5c 1279 pid_t pid = uval & FUTEX_TID_MASK;
04e1b2e5
TG
1280 struct futex_pi_state *pi_state;
1281 struct task_struct *p;
e60cbc5c 1282
c87e2837 1283 /*
e3f2ddea 1284 * We are the first waiter - try to look up the real owner and attach
54a21788 1285 * the new pi_state to it, but bail out when TID = 0 [1]
da791a66
TG
1286 *
1287 * The !pid check is paranoid. None of the call sites should end up
1288 * with pid == 0, but better safe than sorry. Let the caller retry
c87e2837 1289 */
778e9a9c 1290 if (!pid)
da791a66 1291 return -EAGAIN;
2ee08260 1292 p = find_get_task_by_vpid(pid);
7a0ea09a 1293 if (!p)
da791a66 1294 return handle_exit_race(uaddr, uval, NULL);
778e9a9c 1295
a2129464 1296 if (unlikely(p->flags & PF_KTHREAD)) {
f0d71b3d
TG
1297 put_task_struct(p);
1298 return -EPERM;
1299 }
1300
778e9a9c 1301 /*
3d4775df
TG
1302 * We need to look at the task state to figure out, whether the
1303 * task is exiting. To protect against the change of the task state
1304 * in futex_exit_release(), we do this protected by p->pi_lock:
778e9a9c 1305 */
1d615482 1306 raw_spin_lock_irq(&p->pi_lock);
3d4775df 1307 if (unlikely(p->futex_state != FUTEX_STATE_OK)) {
778e9a9c 1308 /*
3d4775df
TG
1309 * The task is on the way out. When the futex state is
1310 * FUTEX_STATE_DEAD, we know that the task has finished
1311 * the cleanup:
778e9a9c 1312 */
da791a66 1313 int ret = handle_exit_race(uaddr, uval, p);
778e9a9c 1314
1d615482 1315 raw_spin_unlock_irq(&p->pi_lock);
3ef240ea
TG
1316 /*
1317 * If the owner task is between FUTEX_STATE_EXITING and
1318 * FUTEX_STATE_DEAD then store the task pointer and keep
1319 * the reference on the task struct. The calling code will
1320 * drop all locks, wait for the task to reach
1321 * FUTEX_STATE_DEAD and then drop the refcount. This is
1322 * required to prevent a live lock when the current task
1323 * preempted the exiting task between the two states.
1324 */
1325 if (ret == -EBUSY)
1326 *exiting = p;
1327 else
1328 put_task_struct(p);
778e9a9c
AK
1329 return ret;
1330 }
c87e2837 1331
54a21788
TG
1332 /*
1333 * No existing pi state. First waiter. [2]
734009e9
PZ
1334 *
1335 * This creates pi_state, we have hb->lock held, this means nothing can
1336 * observe this state, wait_lock is irrelevant.
54a21788 1337 */
c87e2837
IM
1338 pi_state = alloc_pi_state();
1339
1340 /*
04e1b2e5 1341 * Initialize the pi_mutex in locked state and make @p
c87e2837
IM
1342 * the owner of it:
1343 */
1344 rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p);
1345
1346 /* Store the key for possible exit cleanups: */
d0aa7a70 1347 pi_state->key = *key;
c87e2837 1348
627371d7 1349 WARN_ON(!list_empty(&pi_state->list));
c87e2837 1350 list_add(&pi_state->list, &p->pi_state_list);
c74aef2d
PZ
1351 /*
1352 * Assignment without holding pi_state->pi_mutex.wait_lock is safe
1353 * because there is no concurrency as the object is not published yet.
1354 */
c87e2837 1355 pi_state->owner = p;
1d615482 1356 raw_spin_unlock_irq(&p->pi_lock);
c87e2837
IM
1357
1358 put_task_struct(p);
1359
d0aa7a70 1360 *ps = pi_state;
c87e2837
IM
1361
1362 return 0;
1363}
1364
734009e9
PZ
1365static int lookup_pi_state(u32 __user *uaddr, u32 uval,
1366 struct futex_hash_bucket *hb,
3ef240ea
TG
1367 union futex_key *key, struct futex_pi_state **ps,
1368 struct task_struct **exiting)
04e1b2e5 1369{
499f5aca 1370 struct futex_q *top_waiter = futex_top_waiter(hb, key);
04e1b2e5
TG
1371
1372 /*
1373 * If there is a waiter on that futex, validate it and
1374 * attach to the pi_state when the validation succeeds.
1375 */
499f5aca 1376 if (top_waiter)
734009e9 1377 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
04e1b2e5
TG
1378
1379 /*
1380 * We are the first waiter - try to look up the owner based on
1381 * @uval and attach to it.
1382 */
3ef240ea 1383 return attach_to_pi_owner(uaddr, uval, key, ps, exiting);
04e1b2e5
TG
1384}
1385
af54d6a1
TG
1386static int lock_pi_update_atomic(u32 __user *uaddr, u32 uval, u32 newval)
1387{
6b4f4bc9 1388 int err;
af54d6a1
TG
1389 u32 uninitialized_var(curval);
1390
ab51fbab
DB
1391 if (unlikely(should_fail_futex(true)))
1392 return -EFAULT;
1393
6b4f4bc9
WD
1394 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1395 if (unlikely(err))
1396 return err;
af54d6a1 1397
734009e9 1398 /* If user space value changed, let the caller retry */
af54d6a1
TG
1399 return curval != uval ? -EAGAIN : 0;
1400}
1401
1a52084d 1402/**
d96ee56c 1403 * futex_lock_pi_atomic() - Atomic work required to acquire a pi aware futex
bab5bc9e
DH
1404 * @uaddr: the pi futex user address
1405 * @hb: the pi futex hash bucket
1406 * @key: the futex key associated with uaddr and hb
1407 * @ps: the pi_state pointer where we store the result of the
1408 * lookup
1409 * @task: the task to perform the atomic lock work for. This will
1410 * be "current" except in the case of requeue pi.
3ef240ea
TG
1411 * @exiting: Pointer to store the task pointer of the owner task
1412 * which is in the middle of exiting
bab5bc9e 1413 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
1a52084d 1414 *
6c23cbbd 1415 * Return:
7b4ff1ad
MCC
1416 * - 0 - ready to wait;
1417 * - 1 - acquired the lock;
1418 * - <0 - error
1a52084d
DH
1419 *
1420 * The hb->lock and futex_key refs shall be held by the caller.
3ef240ea
TG
1421 *
1422 * @exiting is only set when the return value is -EBUSY. If so, this holds
1423 * a refcount on the exiting task on return and the caller needs to drop it
1424 * after waiting for the exit to complete.
1a52084d
DH
1425 */
1426static int futex_lock_pi_atomic(u32 __user *uaddr, struct futex_hash_bucket *hb,
1427 union futex_key *key,
1428 struct futex_pi_state **ps,
3ef240ea
TG
1429 struct task_struct *task,
1430 struct task_struct **exiting,
1431 int set_waiters)
1a52084d 1432{
af54d6a1 1433 u32 uval, newval, vpid = task_pid_vnr(task);
499f5aca 1434 struct futex_q *top_waiter;
af54d6a1 1435 int ret;
1a52084d
DH
1436
1437 /*
af54d6a1
TG
1438 * Read the user space value first so we can validate a few
1439 * things before proceeding further.
1a52084d 1440 */
af54d6a1 1441 if (get_futex_value_locked(&uval, uaddr))
1a52084d
DH
1442 return -EFAULT;
1443
ab51fbab
DB
1444 if (unlikely(should_fail_futex(true)))
1445 return -EFAULT;
1446
1a52084d
DH
1447 /*
1448 * Detect deadlocks.
1449 */
af54d6a1 1450 if ((unlikely((uval & FUTEX_TID_MASK) == vpid)))
1a52084d
DH
1451 return -EDEADLK;
1452
ab51fbab
DB
1453 if ((unlikely(should_fail_futex(true))))
1454 return -EDEADLK;
1455
1a52084d 1456 /*
af54d6a1
TG
1457 * Lookup existing state first. If it exists, try to attach to
1458 * its pi_state.
1a52084d 1459 */
499f5aca
PZ
1460 top_waiter = futex_top_waiter(hb, key);
1461 if (top_waiter)
734009e9 1462 return attach_to_pi_state(uaddr, uval, top_waiter->pi_state, ps);
1a52084d
DH
1463
1464 /*
af54d6a1
TG
1465 * No waiter and user TID is 0. We are here because the
1466 * waiters or the owner died bit is set or called from
1467 * requeue_cmp_pi or for whatever reason something took the
1468 * syscall.
1a52084d 1469 */
af54d6a1 1470 if (!(uval & FUTEX_TID_MASK)) {
59fa6245 1471 /*
af54d6a1
TG
1472 * We take over the futex. No other waiters and the user space
1473 * TID is 0. We preserve the owner died bit.
59fa6245 1474 */
af54d6a1
TG
1475 newval = uval & FUTEX_OWNER_DIED;
1476 newval |= vpid;
1a52084d 1477
af54d6a1
TG
1478 /* The futex requeue_pi code can enforce the waiters bit */
1479 if (set_waiters)
1480 newval |= FUTEX_WAITERS;
1481
1482 ret = lock_pi_update_atomic(uaddr, uval, newval);
1483 /* If the take over worked, return 1 */
1484 return ret < 0 ? ret : 1;
1485 }
1a52084d
DH
1486
1487 /*
af54d6a1
TG
1488 * First waiter. Set the waiters bit before attaching ourself to
1489 * the owner. If owner tries to unlock, it will be forced into
1490 * the kernel and blocked on hb->lock.
1a52084d 1491 */
af54d6a1
TG
1492 newval = uval | FUTEX_WAITERS;
1493 ret = lock_pi_update_atomic(uaddr, uval, newval);
1494 if (ret)
1495 return ret;
1a52084d 1496 /*
af54d6a1
TG
1497 * If the update of the user space value succeeded, we try to
1498 * attach to the owner. If that fails, no harm done, we only
1499 * set the FUTEX_WAITERS bit in the user space variable.
1a52084d 1500 */
3ef240ea 1501 return attach_to_pi_owner(uaddr, newval, key, ps, exiting);
1a52084d
DH
1502}
1503
2e12978a
LJ
1504/**
1505 * __unqueue_futex() - Remove the futex_q from its futex_hash_bucket
1506 * @q: The futex_q to unqueue
1507 *
1508 * The q->lock_ptr must not be NULL and must be held by the caller.
1509 */
1510static void __unqueue_futex(struct futex_q *q)
1511{
1512 struct futex_hash_bucket *hb;
1513
4de1a293 1514 if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
2e12978a 1515 return;
4de1a293 1516 lockdep_assert_held(q->lock_ptr);
2e12978a
LJ
1517
1518 hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
1519 plist_del(&q->list, &hb->chain);
11d4616b 1520 hb_waiters_dec(hb);
2e12978a
LJ
1521}
1522
1da177e4
LT
1523/*
1524 * The hash bucket lock must be held when this is called.
1d0dcb3a
DB
1525 * Afterwards, the futex_q must not be accessed. Callers
1526 * must ensure to later call wake_up_q() for the actual
1527 * wakeups to occur.
1da177e4 1528 */
1d0dcb3a 1529static void mark_wake_futex(struct wake_q_head *wake_q, struct futex_q *q)
1da177e4 1530{
f1a11e05
TG
1531 struct task_struct *p = q->task;
1532
aa10990e
DH
1533 if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
1534 return;
1535
b061c38b 1536 get_task_struct(p);
2e12978a 1537 __unqueue_futex(q);
1da177e4 1538 /*
38fcd06e
DHV
1539 * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
1540 * is written, without taking any locks. This is possible in the event
1541 * of a spurious wakeup, for example. A memory barrier is required here
1542 * to prevent the following store to lock_ptr from getting ahead of the
1543 * plist_del in __unqueue_futex().
1da177e4 1544 */
1b367ece 1545 smp_store_release(&q->lock_ptr, NULL);
b061c38b
PZ
1546
1547 /*
1548 * Queue the task for later wakeup for after we've released
75145904 1549 * the hb->lock.
b061c38b 1550 */
07879c6a 1551 wake_q_add_safe(wake_q, p);
1da177e4
LT
1552}
1553
16ffa12d
PZ
1554/*
1555 * Caller must hold a reference on @pi_state.
1556 */
1557static int wake_futex_pi(u32 __user *uaddr, u32 uval, struct futex_pi_state *pi_state)
c87e2837 1558{
7cfdaf38 1559 u32 uninitialized_var(curval), newval;
16ffa12d 1560 struct task_struct *new_owner;
aa2bfe55 1561 bool postunlock = false;
194a6b5b 1562 DEFINE_WAKE_Q(wake_q);
13fbca4c 1563 int ret = 0;
c87e2837 1564
c87e2837 1565 new_owner = rt_mutex_next_owner(&pi_state->pi_mutex);
bebe5b51 1566 if (WARN_ON_ONCE(!new_owner)) {
16ffa12d 1567 /*
bebe5b51 1568 * As per the comment in futex_unlock_pi() this should not happen.
16ffa12d
PZ
1569 *
1570 * When this happens, give up our locks and try again, giving
1571 * the futex_lock_pi() instance time to complete, either by
1572 * waiting on the rtmutex or removing itself from the futex
1573 * queue.
1574 */
1575 ret = -EAGAIN;
1576 goto out_unlock;
73d786bd 1577 }
c87e2837
IM
1578
1579 /*
16ffa12d
PZ
1580 * We pass it to the next owner. The WAITERS bit is always kept
1581 * enabled while there is PI state around. We cleanup the owner
1582 * died bit, because we are the owner.
c87e2837 1583 */
13fbca4c 1584 newval = FUTEX_WAITERS | task_pid_vnr(new_owner);
e3f2ddea 1585
ab51fbab
DB
1586 if (unlikely(should_fail_futex(true)))
1587 ret = -EFAULT;
1588
6b4f4bc9
WD
1589 ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
1590 if (!ret && (curval != uval)) {
89e9e66b
SAS
1591 /*
1592 * If a unconditional UNLOCK_PI operation (user space did not
1593 * try the TID->0 transition) raced with a waiter setting the
1594 * FUTEX_WAITERS flag between get_user() and locking the hash
1595 * bucket lock, retry the operation.
1596 */
1597 if ((FUTEX_TID_MASK & curval) == uval)
1598 ret = -EAGAIN;
1599 else
1600 ret = -EINVAL;
1601 }
734009e9 1602
16ffa12d
PZ
1603 if (ret)
1604 goto out_unlock;
c87e2837 1605
94ffac5d
PZ
1606 /*
1607 * This is a point of no return; once we modify the uval there is no
1608 * going back and subsequent operations must not fail.
1609 */
1610
b4abf910 1611 raw_spin_lock(&pi_state->owner->pi_lock);
627371d7
IM
1612 WARN_ON(list_empty(&pi_state->list));
1613 list_del_init(&pi_state->list);
b4abf910 1614 raw_spin_unlock(&pi_state->owner->pi_lock);
627371d7 1615
b4abf910 1616 raw_spin_lock(&new_owner->pi_lock);
627371d7 1617 WARN_ON(!list_empty(&pi_state->list));
c87e2837
IM
1618 list_add(&pi_state->list, &new_owner->pi_state_list);
1619 pi_state->owner = new_owner;
b4abf910 1620 raw_spin_unlock(&new_owner->pi_lock);
627371d7 1621
aa2bfe55 1622 postunlock = __rt_mutex_futex_unlock(&pi_state->pi_mutex, &wake_q);
5293c2ef 1623
16ffa12d 1624out_unlock:
5293c2ef 1625 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
5293c2ef 1626
aa2bfe55
PZ
1627 if (postunlock)
1628 rt_mutex_postunlock(&wake_q);
c87e2837 1629
16ffa12d 1630 return ret;
c87e2837
IM
1631}
1632
8b8f319f
IM
1633/*
1634 * Express the locking dependencies for lockdep:
1635 */
1636static inline void
1637double_lock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1638{
1639 if (hb1 <= hb2) {
1640 spin_lock(&hb1->lock);
1641 if (hb1 < hb2)
1642 spin_lock_nested(&hb2->lock, SINGLE_DEPTH_NESTING);
1643 } else { /* hb1 > hb2 */
1644 spin_lock(&hb2->lock);
1645 spin_lock_nested(&hb1->lock, SINGLE_DEPTH_NESTING);
1646 }
1647}
1648
5eb3dc62
DH
1649static inline void
1650double_unlock_hb(struct futex_hash_bucket *hb1, struct futex_hash_bucket *hb2)
1651{
f061d351 1652 spin_unlock(&hb1->lock);
88f502fe
IM
1653 if (hb1 != hb2)
1654 spin_unlock(&hb2->lock);
5eb3dc62
DH
1655}
1656
1da177e4 1657/*
b2d0994b 1658 * Wake up waiters matching bitset queued on this futex (uaddr).
1da177e4 1659 */
b41277dc
DH
1660static int
1661futex_wake(u32 __user *uaddr, unsigned int flags, int nr_wake, u32 bitset)
1da177e4 1662{
e2970f2f 1663 struct futex_hash_bucket *hb;
1da177e4 1664 struct futex_q *this, *next;
38d47c1b 1665 union futex_key key = FUTEX_KEY_INIT;
1da177e4 1666 int ret;
194a6b5b 1667 DEFINE_WAKE_Q(wake_q);
1da177e4 1668
cd689985
TG
1669 if (!bitset)
1670 return -EINVAL;
1671
96d4f267 1672 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_READ);
1da177e4
LT
1673 if (unlikely(ret != 0))
1674 goto out;
1675
e2970f2f 1676 hb = hash_futex(&key);
b0c29f79
DB
1677
1678 /* Make sure we really have tasks to wakeup */
1679 if (!hb_waiters_pending(hb))
1680 goto out_put_key;
1681
e2970f2f 1682 spin_lock(&hb->lock);
1da177e4 1683
0d00c7b2 1684 plist_for_each_entry_safe(this, next, &hb->chain, list) {
1da177e4 1685 if (match_futex (&this->key, &key)) {
52400ba9 1686 if (this->pi_state || this->rt_waiter) {
ed6f7b10
IM
1687 ret = -EINVAL;
1688 break;
1689 }
cd689985
TG
1690
1691 /* Check if one of the bits is set in both bitsets */
1692 if (!(this->bitset & bitset))
1693 continue;
1694
1d0dcb3a 1695 mark_wake_futex(&wake_q, this);
1da177e4
LT
1696 if (++ret >= nr_wake)
1697 break;
1698 }
1699 }
1700
e2970f2f 1701 spin_unlock(&hb->lock);
1d0dcb3a 1702 wake_up_q(&wake_q);
b0c29f79 1703out_put_key:
ae791a2d 1704 put_futex_key(&key);
42d35d48 1705out:
1da177e4
LT
1706 return ret;
1707}
1708
30d6e0a4
JS
1709static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
1710{
1711 unsigned int op = (encoded_op & 0x70000000) >> 28;
1712 unsigned int cmp = (encoded_op & 0x0f000000) >> 24;
d70ef228
JS
1713 int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
1714 int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
30d6e0a4
JS
1715 int oldval, ret;
1716
1717 if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
e78c38f6
JS
1718 if (oparg < 0 || oparg > 31) {
1719 char comm[sizeof(current->comm)];
1720 /*
1721 * kill this print and return -EINVAL when userspace
1722 * is sane again
1723 */
1724 pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
1725 get_task_comm(comm, current), oparg);
1726 oparg &= 31;
1727 }
30d6e0a4
JS
1728 oparg = 1 << oparg;
1729 }
1730
96d4f267 1731 if (!access_ok(uaddr, sizeof(u32)))
30d6e0a4
JS
1732 return -EFAULT;
1733
1734 ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
1735 if (ret)
1736 return ret;
1737
1738 switch (cmp) {
1739 case FUTEX_OP_CMP_EQ:
1740 return oldval == cmparg;
1741 case FUTEX_OP_CMP_NE:
1742 return oldval != cmparg;
1743 case FUTEX_OP_CMP_LT:
1744 return oldval < cmparg;
1745 case FUTEX_OP_CMP_GE:
1746 return oldval >= cmparg;
1747 case FUTEX_OP_CMP_LE:
1748 return oldval <= cmparg;
1749 case FUTEX_OP_CMP_GT:
1750 return oldval > cmparg;
1751 default:
1752 return -ENOSYS;
1753 }
1754}
1755
4732efbe
JJ
1756/*
1757 * Wake up all waiters hashed on the physical page that is mapped
1758 * to this virtual address:
1759 */
e2970f2f 1760static int
b41277dc 1761futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
e2970f2f 1762 int nr_wake, int nr_wake2, int op)
4732efbe 1763{
38d47c1b 1764 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
e2970f2f 1765 struct futex_hash_bucket *hb1, *hb2;
4732efbe 1766 struct futex_q *this, *next;
e4dc5b7a 1767 int ret, op_ret;
194a6b5b 1768 DEFINE_WAKE_Q(wake_q);
4732efbe 1769
e4dc5b7a 1770retry:
96d4f267 1771 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
4732efbe
JJ
1772 if (unlikely(ret != 0))
1773 goto out;
96d4f267 1774 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
4732efbe 1775 if (unlikely(ret != 0))
42d35d48 1776 goto out_put_key1;
4732efbe 1777
e2970f2f
IM
1778 hb1 = hash_futex(&key1);
1779 hb2 = hash_futex(&key2);
4732efbe 1780
e4dc5b7a 1781retry_private:
eaaea803 1782 double_lock_hb(hb1, hb2);
e2970f2f 1783 op_ret = futex_atomic_op_inuser(op, uaddr2);
4732efbe 1784 if (unlikely(op_ret < 0)) {
5eb3dc62 1785 double_unlock_hb(hb1, hb2);
4732efbe 1786
6b4f4bc9
WD
1787 if (!IS_ENABLED(CONFIG_MMU) ||
1788 unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
1789 /*
1790 * we don't get EFAULT from MMU faults if we don't have
1791 * an MMU, but we might get them from range checking
1792 */
796f8d9b 1793 ret = op_ret;
42d35d48 1794 goto out_put_keys;
796f8d9b
DG
1795 }
1796
6b4f4bc9
WD
1797 if (op_ret == -EFAULT) {
1798 ret = fault_in_user_writeable(uaddr2);
1799 if (ret)
1800 goto out_put_keys;
1801 }
4732efbe 1802
6b4f4bc9
WD
1803 if (!(flags & FLAGS_SHARED)) {
1804 cond_resched();
e4dc5b7a 1805 goto retry_private;
6b4f4bc9 1806 }
e4dc5b7a 1807
ae791a2d
TG
1808 put_futex_key(&key2);
1809 put_futex_key(&key1);
6b4f4bc9 1810 cond_resched();
e4dc5b7a 1811 goto retry;
4732efbe
JJ
1812 }
1813
0d00c7b2 1814 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
4732efbe 1815 if (match_futex (&this->key, &key1)) {
aa10990e
DH
1816 if (this->pi_state || this->rt_waiter) {
1817 ret = -EINVAL;
1818 goto out_unlock;
1819 }
1d0dcb3a 1820 mark_wake_futex(&wake_q, this);
4732efbe
JJ
1821 if (++ret >= nr_wake)
1822 break;
1823 }
1824 }
1825
1826 if (op_ret > 0) {
4732efbe 1827 op_ret = 0;
0d00c7b2 1828 plist_for_each_entry_safe(this, next, &hb2->chain, list) {
4732efbe 1829 if (match_futex (&this->key, &key2)) {
aa10990e
DH
1830 if (this->pi_state || this->rt_waiter) {
1831 ret = -EINVAL;
1832 goto out_unlock;
1833 }
1d0dcb3a 1834 mark_wake_futex(&wake_q, this);
4732efbe
JJ
1835 if (++op_ret >= nr_wake2)
1836 break;
1837 }
1838 }
1839 ret += op_ret;
1840 }
1841
aa10990e 1842out_unlock:
5eb3dc62 1843 double_unlock_hb(hb1, hb2);
1d0dcb3a 1844 wake_up_q(&wake_q);
42d35d48 1845out_put_keys:
ae791a2d 1846 put_futex_key(&key2);
42d35d48 1847out_put_key1:
ae791a2d 1848 put_futex_key(&key1);
42d35d48 1849out:
4732efbe
JJ
1850 return ret;
1851}
1852
9121e478
DH
1853/**
1854 * requeue_futex() - Requeue a futex_q from one hb to another
1855 * @q: the futex_q to requeue
1856 * @hb1: the source hash_bucket
1857 * @hb2: the target hash_bucket
1858 * @key2: the new key for the requeued futex_q
1859 */
1860static inline
1861void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
1862 struct futex_hash_bucket *hb2, union futex_key *key2)
1863{
1864
1865 /*
1866 * If key1 and key2 hash to the same bucket, no need to
1867 * requeue.
1868 */
1869 if (likely(&hb1->chain != &hb2->chain)) {
1870 plist_del(&q->list, &hb1->chain);
11d4616b 1871 hb_waiters_dec(hb1);
11d4616b 1872 hb_waiters_inc(hb2);
fe1bce9e 1873 plist_add(&q->list, &hb2->chain);
9121e478 1874 q->lock_ptr = &hb2->lock;
9121e478
DH
1875 }
1876 get_futex_key_refs(key2);
1877 q->key = *key2;
1878}
1879
52400ba9
DH
1880/**
1881 * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
d96ee56c
DH
1882 * @q: the futex_q
1883 * @key: the key of the requeue target futex
1884 * @hb: the hash_bucket of the requeue target futex
52400ba9
DH
1885 *
1886 * During futex_requeue, with requeue_pi=1, it is possible to acquire the
1887 * target futex if it is uncontended or via a lock steal. Set the futex_q key
1888 * to the requeue target futex so the waiter can detect the wakeup on the right
1889 * futex, but remove it from the hb and NULL the rt_waiter so it can detect
beda2c7e
DH
1890 * atomic lock acquisition. Set the q->lock_ptr to the requeue target hb->lock
1891 * to protect access to the pi_state to fixup the owner later. Must be called
1892 * with both q->lock_ptr and hb->lock held.
52400ba9
DH
1893 */
1894static inline
beda2c7e
DH
1895void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
1896 struct futex_hash_bucket *hb)
52400ba9 1897{
52400ba9
DH
1898 get_futex_key_refs(key);
1899 q->key = *key;
1900
2e12978a 1901 __unqueue_futex(q);
52400ba9
DH
1902
1903 WARN_ON(!q->rt_waiter);
1904 q->rt_waiter = NULL;
1905
beda2c7e 1906 q->lock_ptr = &hb->lock;
beda2c7e 1907
f1a11e05 1908 wake_up_state(q->task, TASK_NORMAL);
52400ba9
DH
1909}
1910
1911/**
1912 * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
bab5bc9e
DH
1913 * @pifutex: the user address of the to futex
1914 * @hb1: the from futex hash bucket, must be locked by the caller
1915 * @hb2: the to futex hash bucket, must be locked by the caller
1916 * @key1: the from futex key
1917 * @key2: the to futex key
1918 * @ps: address to store the pi_state pointer
3ef240ea
TG
1919 * @exiting: Pointer to store the task pointer of the owner task
1920 * which is in the middle of exiting
bab5bc9e 1921 * @set_waiters: force setting the FUTEX_WAITERS bit (1) or not (0)
52400ba9
DH
1922 *
1923 * Try and get the lock on behalf of the top waiter if we can do it atomically.
bab5bc9e
DH
1924 * Wake the top waiter if we succeed. If the caller specified set_waiters,
1925 * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
1926 * hb1 and hb2 must be held by the caller.
52400ba9 1927 *
3ef240ea
TG
1928 * @exiting is only set when the return value is -EBUSY. If so, this holds
1929 * a refcount on the exiting task on return and the caller needs to drop it
1930 * after waiting for the exit to complete.
1931 *
6c23cbbd 1932 * Return:
7b4ff1ad
MCC
1933 * - 0 - failed to acquire the lock atomically;
1934 * - >0 - acquired the lock, return value is vpid of the top_waiter
1935 * - <0 - error
52400ba9 1936 */
3ef240ea
TG
1937static int
1938futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
1939 struct futex_hash_bucket *hb2, union futex_key *key1,
1940 union futex_key *key2, struct futex_pi_state **ps,
1941 struct task_struct **exiting, int set_waiters)
52400ba9 1942{
bab5bc9e 1943 struct futex_q *top_waiter = NULL;
52400ba9 1944 u32 curval;
866293ee 1945 int ret, vpid;
52400ba9
DH
1946
1947 if (get_futex_value_locked(&curval, pifutex))
1948 return -EFAULT;
1949
ab51fbab
DB
1950 if (unlikely(should_fail_futex(true)))
1951 return -EFAULT;
1952
bab5bc9e
DH
1953 /*
1954 * Find the top_waiter and determine if there are additional waiters.
1955 * If the caller intends to requeue more than 1 waiter to pifutex,
1956 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
1957 * as we have means to handle the possible fault. If not, don't set
1958 * the bit unecessarily as it will force the subsequent unlock to enter
1959 * the kernel.
1960 */
52400ba9
DH
1961 top_waiter = futex_top_waiter(hb1, key1);
1962
1963 /* There are no waiters, nothing for us to do. */
1964 if (!top_waiter)
1965 return 0;
1966
84bc4af5
DH
1967 /* Ensure we requeue to the expected futex. */
1968 if (!match_futex(top_waiter->requeue_pi_key, key2))
1969 return -EINVAL;
1970
52400ba9 1971 /*
bab5bc9e
DH
1972 * Try to take the lock for top_waiter. Set the FUTEX_WAITERS bit in
1973 * the contended case or if set_waiters is 1. The pi_state is returned
1974 * in ps in contended cases.
52400ba9 1975 */
866293ee 1976 vpid = task_pid_vnr(top_waiter->task);
bab5bc9e 1977 ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
3ef240ea 1978 exiting, set_waiters);
866293ee 1979 if (ret == 1) {
beda2c7e 1980 requeue_pi_wake_futex(top_waiter, key2, hb2);
866293ee
TG
1981 return vpid;
1982 }
52400ba9
DH
1983 return ret;
1984}
1985
1986/**
1987 * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
fb62db2b 1988 * @uaddr1: source futex user address
b41277dc 1989 * @flags: futex flags (FLAGS_SHARED, etc.)
fb62db2b
RD
1990 * @uaddr2: target futex user address
1991 * @nr_wake: number of waiters to wake (must be 1 for requeue_pi)
1992 * @nr_requeue: number of waiters to requeue (0-INT_MAX)
1993 * @cmpval: @uaddr1 expected value (or %NULL)
1994 * @requeue_pi: if we are attempting to requeue from a non-pi futex to a
b41277dc 1995 * pi futex (pi to pi requeue is not supported)
52400ba9
DH
1996 *
1997 * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
1998 * uaddr2 atomically on behalf of the top waiter.
1999 *
6c23cbbd 2000 * Return:
7b4ff1ad
MCC
2001 * - >=0 - on success, the number of tasks requeued or woken;
2002 * - <0 - on error
1da177e4 2003 */
b41277dc
DH
2004static int futex_requeue(u32 __user *uaddr1, unsigned int flags,
2005 u32 __user *uaddr2, int nr_wake, int nr_requeue,
2006 u32 *cmpval, int requeue_pi)
1da177e4 2007{
38d47c1b 2008 union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
52400ba9
DH
2009 int drop_count = 0, task_count = 0, ret;
2010 struct futex_pi_state *pi_state = NULL;
e2970f2f 2011 struct futex_hash_bucket *hb1, *hb2;
1da177e4 2012 struct futex_q *this, *next;
194a6b5b 2013 DEFINE_WAKE_Q(wake_q);
52400ba9 2014
fbe0e839
LJ
2015 if (nr_wake < 0 || nr_requeue < 0)
2016 return -EINVAL;
2017
bc2eecd7
NP
2018 /*
2019 * When PI not supported: return -ENOSYS if requeue_pi is true,
2020 * consequently the compiler knows requeue_pi is always false past
2021 * this point which will optimize away all the conditional code
2022 * further down.
2023 */
2024 if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
2025 return -ENOSYS;
2026
52400ba9 2027 if (requeue_pi) {
e9c243a5
TG
2028 /*
2029 * Requeue PI only works on two distinct uaddrs. This
2030 * check is only valid for private futexes. See below.
2031 */
2032 if (uaddr1 == uaddr2)
2033 return -EINVAL;
2034
52400ba9
DH
2035 /*
2036 * requeue_pi requires a pi_state, try to allocate it now
2037 * without any locks in case it fails.
2038 */
2039 if (refill_pi_state_cache())
2040 return -ENOMEM;
2041 /*
2042 * requeue_pi must wake as many tasks as it can, up to nr_wake
2043 * + nr_requeue, since it acquires the rt_mutex prior to
2044 * returning to userspace, so as to not leave the rt_mutex with
2045 * waiters and no owner. However, second and third wake-ups
2046 * cannot be predicted as they involve race conditions with the
2047 * first wake and a fault while looking up the pi_state. Both
2048 * pthread_cond_signal() and pthread_cond_broadcast() should
2049 * use nr_wake=1.
2050 */
2051 if (nr_wake != 1)
2052 return -EINVAL;
2053 }
1da177e4 2054
42d35d48 2055retry:
96d4f267 2056 ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, FUTEX_READ);
1da177e4
LT
2057 if (unlikely(ret != 0))
2058 goto out;
9ea71503 2059 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2,
96d4f267 2060 requeue_pi ? FUTEX_WRITE : FUTEX_READ);
1da177e4 2061 if (unlikely(ret != 0))
42d35d48 2062 goto out_put_key1;
1da177e4 2063
e9c243a5
TG
2064 /*
2065 * The check above which compares uaddrs is not sufficient for
2066 * shared futexes. We need to compare the keys:
2067 */
2068 if (requeue_pi && match_futex(&key1, &key2)) {
2069 ret = -EINVAL;
2070 goto out_put_keys;
2071 }
2072
e2970f2f
IM
2073 hb1 = hash_futex(&key1);
2074 hb2 = hash_futex(&key2);
1da177e4 2075
e4dc5b7a 2076retry_private:
69cd9eba 2077 hb_waiters_inc(hb2);
8b8f319f 2078 double_lock_hb(hb1, hb2);
1da177e4 2079
e2970f2f
IM
2080 if (likely(cmpval != NULL)) {
2081 u32 curval;
1da177e4 2082
e2970f2f 2083 ret = get_futex_value_locked(&curval, uaddr1);
1da177e4
LT
2084
2085 if (unlikely(ret)) {
5eb3dc62 2086 double_unlock_hb(hb1, hb2);
69cd9eba 2087 hb_waiters_dec(hb2);
1da177e4 2088
e2970f2f 2089 ret = get_user(curval, uaddr1);
e4dc5b7a
DH
2090 if (ret)
2091 goto out_put_keys;
1da177e4 2092
b41277dc 2093 if (!(flags & FLAGS_SHARED))
e4dc5b7a 2094 goto retry_private;
1da177e4 2095
ae791a2d
TG
2096 put_futex_key(&key2);
2097 put_futex_key(&key1);
e4dc5b7a 2098 goto retry;
1da177e4 2099 }
e2970f2f 2100 if (curval != *cmpval) {
1da177e4
LT
2101 ret = -EAGAIN;
2102 goto out_unlock;
2103 }
2104 }
2105
52400ba9 2106 if (requeue_pi && (task_count - nr_wake < nr_requeue)) {
3ef240ea
TG
2107 struct task_struct *exiting = NULL;
2108
bab5bc9e
DH
2109 /*
2110 * Attempt to acquire uaddr2 and wake the top waiter. If we
2111 * intend to requeue waiters, force setting the FUTEX_WAITERS
2112 * bit. We force this here where we are able to easily handle
2113 * faults rather in the requeue loop below.
2114 */
52400ba9 2115 ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
3ef240ea
TG
2116 &key2, &pi_state,
2117 &exiting, nr_requeue);
52400ba9
DH
2118
2119 /*
2120 * At this point the top_waiter has either taken uaddr2 or is
2121 * waiting on it. If the former, then the pi_state will not
2122 * exist yet, look it up one more time to ensure we have a
866293ee
TG
2123 * reference to it. If the lock was taken, ret contains the
2124 * vpid of the top waiter task.
ecb38b78
TG
2125 * If the lock was not taken, we have pi_state and an initial
2126 * refcount on it. In case of an error we have nothing.
52400ba9 2127 */
866293ee 2128 if (ret > 0) {
52400ba9 2129 WARN_ON(pi_state);
89061d3d 2130 drop_count++;
52400ba9 2131 task_count++;
866293ee 2132 /*
ecb38b78
TG
2133 * If we acquired the lock, then the user space value
2134 * of uaddr2 should be vpid. It cannot be changed by
2135 * the top waiter as it is blocked on hb2 lock if it
2136 * tries to do so. If something fiddled with it behind
2137 * our back the pi state lookup might unearth it. So
2138 * we rather use the known value than rereading and
2139 * handing potential crap to lookup_pi_state.
2140 *
2141 * If that call succeeds then we have pi_state and an
2142 * initial refcount on it.
866293ee 2143 */
3ef240ea
TG
2144 ret = lookup_pi_state(uaddr2, ret, hb2, &key2,
2145 &pi_state, &exiting);
52400ba9
DH
2146 }
2147
2148 switch (ret) {
2149 case 0:
ecb38b78 2150 /* We hold a reference on the pi state. */
52400ba9 2151 break;
4959f2de
TG
2152
2153 /* If the above failed, then pi_state is NULL */
52400ba9
DH
2154 case -EFAULT:
2155 double_unlock_hb(hb1, hb2);
69cd9eba 2156 hb_waiters_dec(hb2);
ae791a2d
TG
2157 put_futex_key(&key2);
2158 put_futex_key(&key1);
d0725992 2159 ret = fault_in_user_writeable(uaddr2);
52400ba9
DH
2160 if (!ret)
2161 goto retry;
2162 goto out;
ac31c7ff 2163 case -EBUSY:
52400ba9 2164 case -EAGAIN:
af54d6a1
TG
2165 /*
2166 * Two reasons for this:
ac31c7ff 2167 * - EBUSY: Owner is exiting and we just wait for the
af54d6a1 2168 * exit to complete.
ac31c7ff 2169 * - EAGAIN: The user space value changed.
af54d6a1 2170 */
52400ba9 2171 double_unlock_hb(hb1, hb2);
69cd9eba 2172 hb_waiters_dec(hb2);
ae791a2d
TG
2173 put_futex_key(&key2);
2174 put_futex_key(&key1);
3ef240ea
TG
2175 /*
2176 * Handle the case where the owner is in the middle of
2177 * exiting. Wait for the exit to complete otherwise
2178 * this task might loop forever, aka. live lock.
2179 */
2180 wait_for_owner_exiting(ret, exiting);
52400ba9
DH
2181 cond_resched();
2182 goto retry;
2183 default:
2184 goto out_unlock;
2185 }
2186 }
2187
0d00c7b2 2188 plist_for_each_entry_safe(this, next, &hb1->chain, list) {
52400ba9
DH
2189 if (task_count - nr_wake >= nr_requeue)
2190 break;
2191
2192 if (!match_futex(&this->key, &key1))
1da177e4 2193 continue;
52400ba9 2194
392741e0
DH
2195 /*
2196 * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always
2197 * be paired with each other and no other futex ops.
aa10990e
DH
2198 *
2199 * We should never be requeueing a futex_q with a pi_state,
2200 * which is awaiting a futex_unlock_pi().
392741e0
DH
2201 */
2202 if ((requeue_pi && !this->rt_waiter) ||
aa10990e
DH
2203 (!requeue_pi && this->rt_waiter) ||
2204 this->pi_state) {
392741e0
DH
2205 ret = -EINVAL;
2206 break;
2207 }
52400ba9
DH
2208
2209 /*
2210 * Wake nr_wake waiters. For requeue_pi, if we acquired the
2211 * lock, we already woke the top_waiter. If not, it will be
2212 * woken by futex_unlock_pi().
2213 */
2214 if (++task_count <= nr_wake && !requeue_pi) {
1d0dcb3a 2215 mark_wake_futex(&wake_q, this);
52400ba9
DH
2216 continue;
2217 }
1da177e4 2218
84bc4af5
DH
2219 /* Ensure we requeue to the expected futex for requeue_pi. */
2220 if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) {
2221 ret = -EINVAL;
2222 break;
2223 }
2224
52400ba9
DH
2225 /*
2226 * Requeue nr_requeue waiters and possibly one more in the case
2227 * of requeue_pi if we couldn't acquire the lock atomically.
2228 */
2229 if (requeue_pi) {
ecb38b78
TG
2230 /*
2231 * Prepare the waiter to take the rt_mutex. Take a
2232 * refcount on the pi_state and store the pointer in
2233 * the futex_q object of the waiter.
2234 */
bf92cf3a 2235 get_pi_state(pi_state);
52400ba9
DH
2236 this->pi_state = pi_state;
2237 ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
2238 this->rt_waiter,
c051b21f 2239 this->task);
52400ba9 2240 if (ret == 1) {
ecb38b78
TG
2241 /*
2242 * We got the lock. We do neither drop the
2243 * refcount on pi_state nor clear
2244 * this->pi_state because the waiter needs the
2245 * pi_state for cleaning up the user space
2246 * value. It will drop the refcount after
2247 * doing so.
2248 */
beda2c7e 2249 requeue_pi_wake_futex(this, &key2, hb2);
89061d3d 2250 drop_count++;
52400ba9
DH
2251 continue;
2252 } else if (ret) {
ecb38b78
TG
2253 /*
2254 * rt_mutex_start_proxy_lock() detected a
2255 * potential deadlock when we tried to queue
2256 * that waiter. Drop the pi_state reference
2257 * which we took above and remove the pointer
2258 * to the state from the waiters futex_q
2259 * object.
2260 */
52400ba9 2261 this->pi_state = NULL;
29e9ee5d 2262 put_pi_state(pi_state);
885c2cb7
TG
2263 /*
2264 * We stop queueing more waiters and let user
2265 * space deal with the mess.
2266 */
2267 break;
52400ba9 2268 }
1da177e4 2269 }
52400ba9
DH
2270 requeue_futex(this, hb1, hb2, &key2);
2271 drop_count++;
1da177e4
LT
2272 }
2273
ecb38b78
TG
2274 /*
2275 * We took an extra initial reference to the pi_state either
2276 * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We
2277 * need to drop it here again.
2278 */
29e9ee5d 2279 put_pi_state(pi_state);
885c2cb7
TG
2280
2281out_unlock:
5eb3dc62 2282 double_unlock_hb(hb1, hb2);
1d0dcb3a 2283 wake_up_q(&wake_q);
69cd9eba 2284 hb_waiters_dec(hb2);
1da177e4 2285
cd84a42f
DH
2286 /*
2287 * drop_futex_key_refs() must be called outside the spinlocks. During
2288 * the requeue we moved futex_q's from the hash bucket at key1 to the
2289 * one at key2 and updated their key pointer. We no longer need to
2290 * hold the references to key1.
2291 */
1da177e4 2292 while (--drop_count >= 0)
9adef58b 2293 drop_futex_key_refs(&key1);
1da177e4 2294
42d35d48 2295out_put_keys:
ae791a2d 2296 put_futex_key(&key2);
42d35d48 2297out_put_key1:
ae791a2d 2298 put_futex_key(&key1);
42d35d48 2299out:
52400ba9 2300 return ret ? ret : task_count;
1da177e4
LT
2301}
2302
2303/* The key must be already stored in q->key. */
82af7aca 2304static inline struct futex_hash_bucket *queue_lock(struct futex_q *q)
15e408cd 2305 __acquires(&hb->lock)
1da177e4 2306{
e2970f2f 2307 struct futex_hash_bucket *hb;
1da177e4 2308
e2970f2f 2309 hb = hash_futex(&q->key);
11d4616b
LT
2310
2311 /*
2312 * Increment the counter before taking the lock so that
2313 * a potential waker won't miss a to-be-slept task that is
2314 * waiting for the spinlock. This is safe as all queue_lock()
2315 * users end up calling queue_me(). Similarly, for housekeeping,
2316 * decrement the counter at queue_unlock() when some error has
2317 * occurred and we don't end up adding the task to the list.
2318 */
6f568ebe 2319 hb_waiters_inc(hb); /* implies smp_mb(); (A) */
11d4616b 2320
e2970f2f 2321 q->lock_ptr = &hb->lock;
1da177e4 2322
6f568ebe 2323 spin_lock(&hb->lock);
e2970f2f 2324 return hb;
1da177e4
LT
2325}
2326
d40d65c8 2327static inline void
0d00c7b2 2328queue_unlock(struct futex_hash_bucket *hb)
15e408cd 2329 __releases(&hb->lock)
d40d65c8
DH
2330{
2331 spin_unlock(&hb->lock);
11d4616b 2332 hb_waiters_dec(hb);
d40d65c8
DH
2333}
2334
cfafcd11 2335static inline void __queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
1da177e4 2336{
ec92d082
PP
2337 int prio;
2338
2339 /*
2340 * The priority used to register this element is
2341 * - either the real thread-priority for the real-time threads
2342 * (i.e. threads with a priority lower than MAX_RT_PRIO)
2343 * - or MAX_RT_PRIO for non-RT threads.
2344 * Thus, all RT-threads are woken first in priority order, and
2345 * the others are woken last, in FIFO order.
2346 */
2347 prio = min(current->normal_prio, MAX_RT_PRIO);
2348
2349 plist_node_init(&q->list, prio);
ec92d082 2350 plist_add(&q->list, &hb->chain);
c87e2837 2351 q->task = current;
cfafcd11
PZ
2352}
2353
2354/**
2355 * queue_me() - Enqueue the futex_q on the futex_hash_bucket
2356 * @q: The futex_q to enqueue
2357 * @hb: The destination hash bucket
2358 *
2359 * The hb->lock must be held by the caller, and is released here. A call to
2360 * queue_me() is typically paired with exactly one call to unqueue_me(). The
2361 * exceptions involve the PI related operations, which may use unqueue_me_pi()
2362 * or nothing if the unqueue is done as part of the wake process and the unqueue
2363 * state is implicit in the state of woken task (see futex_wait_requeue_pi() for
2364 * an example).
2365 */
2366static inline void queue_me(struct futex_q *q, struct futex_hash_bucket *hb)
2367 __releases(&hb->lock)
2368{
2369 __queue_me(q, hb);
e2970f2f 2370 spin_unlock(&hb->lock);
1da177e4
LT
2371}
2372
d40d65c8
DH
2373/**
2374 * unqueue_me() - Remove the futex_q from its futex_hash_bucket
2375 * @q: The futex_q to unqueue
2376 *
2377 * The q->lock_ptr must not be held by the caller. A call to unqueue_me() must
2378 * be paired with exactly one earlier call to queue_me().
2379 *
6c23cbbd 2380 * Return:
7b4ff1ad
MCC
2381 * - 1 - if the futex_q was still queued (and we removed unqueued it);
2382 * - 0 - if the futex_q was already removed by the waking thread
1da177e4 2383 */
1da177e4
LT
2384static int unqueue_me(struct futex_q *q)
2385{
1da177e4 2386 spinlock_t *lock_ptr;
e2970f2f 2387 int ret = 0;
1da177e4
LT
2388
2389 /* In the common case we don't take the spinlock, which is nice. */
42d35d48 2390retry:
29b75eb2
JZ
2391 /*
2392 * q->lock_ptr can change between this read and the following spin_lock.
2393 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
2394 * optimizing lock_ptr out of the logic below.
2395 */
2396 lock_ptr = READ_ONCE(q->lock_ptr);
c80544dc 2397 if (lock_ptr != NULL) {
1da177e4
LT
2398 spin_lock(lock_ptr);
2399 /*
2400 * q->lock_ptr can change between reading it and
2401 * spin_lock(), causing us to take the wrong lock. This
2402 * corrects the race condition.
2403 *
2404 * Reasoning goes like this: if we have the wrong lock,
2405 * q->lock_ptr must have changed (maybe several times)
2406 * between reading it and the spin_lock(). It can
2407 * change again after the spin_lock() but only if it was
2408 * already changed before the spin_lock(). It cannot,
2409 * however, change back to the original value. Therefore
2410 * we can detect whether we acquired the correct lock.
2411 */
2412 if (unlikely(lock_ptr != q->lock_ptr)) {
2413 spin_unlock(lock_ptr);
2414 goto retry;
2415 }
2e12978a 2416 __unqueue_futex(q);
c87e2837
IM
2417
2418 BUG_ON(q->pi_state);
2419
1da177e4
LT
2420 spin_unlock(lock_ptr);
2421 ret = 1;
2422 }
2423
9adef58b 2424 drop_futex_key_refs(&q->key);
1da177e4
LT
2425 return ret;
2426}
2427
c87e2837
IM
2428/*
2429 * PI futexes can not be requeued and must remove themself from the
d0aa7a70
PP
2430 * hash bucket. The hash bucket lock (i.e. lock_ptr) is held on entry
2431 * and dropped here.
c87e2837 2432 */
d0aa7a70 2433static void unqueue_me_pi(struct futex_q *q)
15e408cd 2434 __releases(q->lock_ptr)
c87e2837 2435{
2e12978a 2436 __unqueue_futex(q);
c87e2837
IM
2437
2438 BUG_ON(!q->pi_state);
29e9ee5d 2439 put_pi_state(q->pi_state);
c87e2837
IM
2440 q->pi_state = NULL;
2441
d0aa7a70 2442 spin_unlock(q->lock_ptr);
c87e2837
IM
2443}
2444
778e9a9c 2445static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
c1e2f0ea 2446 struct task_struct *argowner)
d0aa7a70 2447{
d0aa7a70 2448 struct futex_pi_state *pi_state = q->pi_state;
7cfdaf38 2449 u32 uval, uninitialized_var(curval), newval;
c1e2f0ea
PZ
2450 struct task_struct *oldowner, *newowner;
2451 u32 newtid;
6b4f4bc9 2452 int ret, err = 0;
d0aa7a70 2453
c1e2f0ea
PZ
2454 lockdep_assert_held(q->lock_ptr);
2455
734009e9
PZ
2456 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
2457
2458 oldowner = pi_state->owner;
1b7558e4
TG
2459
2460 /*
c1e2f0ea 2461 * We are here because either:
16ffa12d 2462 *
c1e2f0ea
PZ
2463 * - we stole the lock and pi_state->owner needs updating to reflect
2464 * that (@argowner == current),
2465 *
2466 * or:
2467 *
2468 * - someone stole our lock and we need to fix things to point to the
2469 * new owner (@argowner == NULL).
2470 *
2471 * Either way, we have to replace the TID in the user space variable.
8161239a 2472 * This must be atomic as we have to preserve the owner died bit here.
1b7558e4 2473 *
b2d0994b
DH
2474 * Note: We write the user space value _before_ changing the pi_state
2475 * because we can fault here. Imagine swapped out pages or a fork
2476 * that marked all the anonymous memory readonly for cow.
1b7558e4 2477 *
734009e9
PZ
2478 * Modifying pi_state _before_ the user space value would leave the
2479 * pi_state in an inconsistent state when we fault here, because we
2480 * need to drop the locks to handle the fault. This might be observed
2481 * in the PID check in lookup_pi_state.
1b7558e4
TG
2482 */
2483retry:
c1e2f0ea
PZ
2484 if (!argowner) {
2485 if (oldowner != current) {
2486 /*
2487 * We raced against a concurrent self; things are
2488 * already fixed up. Nothing to do.
2489 */
2490 ret = 0;
2491 goto out_unlock;
2492 }
2493
2494 if (__rt_mutex_futex_trylock(&pi_state->pi_mutex)) {
2495 /* We got the lock after all, nothing to fix. */
2496 ret = 0;
2497 goto out_unlock;
2498 }
2499
2500 /*
2501 * Since we just failed the trylock; there must be an owner.
2502 */
2503 newowner = rt_mutex_owner(&pi_state->pi_mutex);
2504 BUG_ON(!newowner);
2505 } else {
2506 WARN_ON_ONCE(argowner != current);
2507 if (oldowner == current) {
2508 /*
2509 * We raced against a concurrent self; things are
2510 * already fixed up. Nothing to do.
2511 */
2512 ret = 0;
2513 goto out_unlock;
2514 }
2515 newowner = argowner;
2516 }
2517
2518 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
a97cb0e7
PZ
2519 /* Owner died? */
2520 if (!pi_state->owner)
2521 newtid |= FUTEX_OWNER_DIED;
c1e2f0ea 2522
6b4f4bc9
WD
2523 err = get_futex_value_locked(&uval, uaddr);
2524 if (err)
2525 goto handle_err;
1b7558e4 2526
16ffa12d 2527 for (;;) {
1b7558e4
TG
2528 newval = (uval & FUTEX_OWNER_DIED) | newtid;
2529
6b4f4bc9
WD
2530 err = cmpxchg_futex_value_locked(&curval, uaddr, uval, newval);
2531 if (err)
2532 goto handle_err;
2533
1b7558e4
TG
2534 if (curval == uval)
2535 break;
2536 uval = curval;
2537 }
2538
2539 /*
2540 * We fixed up user space. Now we need to fix the pi_state
2541 * itself.
2542 */
d0aa7a70 2543 if (pi_state->owner != NULL) {
734009e9 2544 raw_spin_lock(&pi_state->owner->pi_lock);
d0aa7a70
PP
2545 WARN_ON(list_empty(&pi_state->list));
2546 list_del_init(&pi_state->list);
734009e9 2547 raw_spin_unlock(&pi_state->owner->pi_lock);
1b7558e4 2548 }
d0aa7a70 2549
cdf71a10 2550 pi_state->owner = newowner;
d0aa7a70 2551
734009e9 2552 raw_spin_lock(&newowner->pi_lock);
d0aa7a70 2553 WARN_ON(!list_empty(&pi_state->list));
cdf71a10 2554 list_add(&pi_state->list, &newowner->pi_state_list);
734009e9
PZ
2555 raw_spin_unlock(&newowner->pi_lock);
2556 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2557
1b7558e4 2558 return 0;
d0aa7a70 2559
d0aa7a70 2560 /*
6b4f4bc9
WD
2561 * In order to reschedule or handle a page fault, we need to drop the
2562 * locks here. In the case of a fault, this gives the other task
2563 * (either the highest priority waiter itself or the task which stole
2564 * the rtmutex) the chance to try the fixup of the pi_state. So once we
2565 * are back from handling the fault we need to check the pi_state after
2566 * reacquiring the locks and before trying to do another fixup. When
2567 * the fixup has been done already we simply return.
734009e9
PZ
2568 *
2569 * Note: we hold both hb->lock and pi_mutex->wait_lock. We can safely
2570 * drop hb->lock since the caller owns the hb -> futex_q relation.
2571 * Dropping the pi_mutex->wait_lock requires the state revalidate.
d0aa7a70 2572 */
6b4f4bc9 2573handle_err:
734009e9 2574 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1b7558e4 2575 spin_unlock(q->lock_ptr);
778e9a9c 2576
6b4f4bc9
WD
2577 switch (err) {
2578 case -EFAULT:
2579 ret = fault_in_user_writeable(uaddr);
2580 break;
2581
2582 case -EAGAIN:
2583 cond_resched();
2584 ret = 0;
2585 break;
2586
2587 default:
2588 WARN_ON_ONCE(1);
2589 ret = err;
2590 break;
2591 }
778e9a9c 2592
1b7558e4 2593 spin_lock(q->lock_ptr);
734009e9 2594 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
778e9a9c 2595
1b7558e4
TG
2596 /*
2597 * Check if someone else fixed it for us:
2598 */
734009e9
PZ
2599 if (pi_state->owner != oldowner) {
2600 ret = 0;
2601 goto out_unlock;
2602 }
1b7558e4
TG
2603
2604 if (ret)
734009e9 2605 goto out_unlock;
1b7558e4
TG
2606
2607 goto retry;
734009e9
PZ
2608
2609out_unlock:
2610 raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
2611 return ret;
d0aa7a70
PP
2612}
2613
72c1bbf3 2614static long futex_wait_restart(struct restart_block *restart);
36cf3b5c 2615
dd973998
DH
2616/**
2617 * fixup_owner() - Post lock pi_state and corner case management
2618 * @uaddr: user address of the futex
dd973998
DH
2619 * @q: futex_q (contains pi_state and access to the rt_mutex)
2620 * @locked: if the attempt to take the rt_mutex succeeded (1) or not (0)
2621 *
2622 * After attempting to lock an rt_mutex, this function is called to cleanup
2623 * the pi_state owner as well as handle race conditions that may allow us to
2624 * acquire the lock. Must be called with the hb lock held.
2625 *
6c23cbbd 2626 * Return:
7b4ff1ad
MCC
2627 * - 1 - success, lock taken;
2628 * - 0 - success, lock not taken;
2629 * - <0 - on error (-EFAULT)
dd973998 2630 */
ae791a2d 2631static int fixup_owner(u32 __user *uaddr, struct futex_q *q, int locked)
dd973998 2632{
dd973998
DH
2633 int ret = 0;
2634
2635 if (locked) {
2636 /*
2637 * Got the lock. We might not be the anticipated owner if we
2638 * did a lock-steal - fix up the PI-state in that case:
16ffa12d 2639 *
c1e2f0ea
PZ
2640 * Speculative pi_state->owner read (we don't hold wait_lock);
2641 * since we own the lock pi_state->owner == current is the
2642 * stable state, anything else needs more attention.
dd973998
DH
2643 */
2644 if (q->pi_state->owner != current)
ae791a2d 2645 ret = fixup_pi_state_owner(uaddr, q, current);
dd973998
DH
2646 goto out;
2647 }
2648
c1e2f0ea
PZ
2649 /*
2650 * If we didn't get the lock; check if anybody stole it from us. In
2651 * that case, we need to fix up the uval to point to them instead of
2652 * us, otherwise bad things happen. [10]
2653 *
2654 * Another speculative read; pi_state->owner == current is unstable
2655 * but needs our attention.
2656 */
2657 if (q->pi_state->owner == current) {
2658 ret = fixup_pi_state_owner(uaddr, q, NULL);
2659 goto out;
2660 }
2661
dd973998
DH
2662 /*
2663 * Paranoia check. If we did not take the lock, then we should not be
8161239a 2664 * the owner of the rt_mutex.
dd973998 2665 */
73d786bd 2666 if (rt_mutex_owner(&q->pi_state->pi_mutex) == current) {
dd973998
DH
2667 printk(KERN_ERR "fixup_owner: ret = %d pi-mutex: %p "
2668 "pi-state %p\n", ret,
2669 q->pi_state->pi_mutex.owner,
2670 q->pi_state->owner);
73d786bd 2671 }
dd973998
DH
2672
2673out:
2674 return ret ? ret : locked;
2675}
2676
ca5f9524
DH
2677/**
2678 * futex_wait_queue_me() - queue_me() and wait for wakeup, timeout, or signal
2679 * @hb: the futex hash bucket, must be locked by the caller
2680 * @q: the futex_q to queue up on
2681 * @timeout: the prepared hrtimer_sleeper, or null for no timeout
ca5f9524
DH
2682 */
2683static void futex_wait_queue_me(struct futex_hash_bucket *hb, struct futex_q *q,
f1a11e05 2684 struct hrtimer_sleeper *timeout)
ca5f9524 2685{
9beba3c5
DH
2686 /*
2687 * The task state is guaranteed to be set before another task can
b92b8b35 2688 * wake it. set_current_state() is implemented using smp_store_mb() and
9beba3c5
DH
2689 * queue_me() calls spin_unlock() upon completion, both serializing
2690 * access to the hash list and forcing another memory barrier.
2691 */
f1a11e05 2692 set_current_state(TASK_INTERRUPTIBLE);
0729e196 2693 queue_me(q, hb);
ca5f9524
DH
2694
2695 /* Arm the timer */
2e4b0d3f 2696 if (timeout)
9dd8813e 2697 hrtimer_sleeper_start_expires(timeout, HRTIMER_MODE_ABS);
ca5f9524
DH
2698
2699 /*
0729e196
DH
2700 * If we have been removed from the hash list, then another task
2701 * has tried to wake us, and we can skip the call to schedule().
ca5f9524
DH
2702 */
2703 if (likely(!plist_node_empty(&q->list))) {
2704 /*
2705 * If the timer has already expired, current will already be
2706 * flagged for rescheduling. Only call schedule if there
2707 * is no timeout, or if it has yet to expire.
2708 */
2709 if (!timeout || timeout->task)
88c8004f 2710 freezable_schedule();
ca5f9524
DH
2711 }
2712 __set_current_state(TASK_RUNNING);
2713}
2714
f801073f
DH
2715/**
2716 * futex_wait_setup() - Prepare to wait on a futex
2717 * @uaddr: the futex userspace address
2718 * @val: the expected value
b41277dc 2719 * @flags: futex flags (FLAGS_SHARED, etc.)
f801073f
DH
2720 * @q: the associated futex_q
2721 * @hb: storage for hash_bucket pointer to be returned to caller
2722 *
2723 * Setup the futex_q and locate the hash_bucket. Get the futex value and
2724 * compare it with the expected value. Handle atomic faults internally.
2725 * Return with the hb lock held and a q.key reference on success, and unlocked
2726 * with no q.key reference on failure.
2727 *
6c23cbbd 2728 * Return:
7b4ff1ad
MCC
2729 * - 0 - uaddr contains val and hb has been locked;
2730 * - <1 - -EFAULT or -EWOULDBLOCK (uaddr does not contain val) and hb is unlocked
f801073f 2731 */
b41277dc 2732static int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
f801073f 2733 struct futex_q *q, struct futex_hash_bucket **hb)
1da177e4 2734{
e2970f2f
IM
2735 u32 uval;
2736 int ret;
1da177e4 2737
1da177e4 2738 /*
b2d0994b 2739 * Access the page AFTER the hash-bucket is locked.
1da177e4
LT
2740 * Order is important:
2741 *
2742 * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
2743 * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); }
2744 *
2745 * The basic logical guarantee of a futex is that it blocks ONLY
2746 * if cond(var) is known to be true at the time of blocking, for
8fe8f545
ML
2747 * any cond. If we locked the hash-bucket after testing *uaddr, that
2748 * would open a race condition where we could block indefinitely with
1da177e4
LT
2749 * cond(var) false, which would violate the guarantee.
2750 *
8fe8f545
ML
2751 * On the other hand, we insert q and release the hash-bucket only
2752 * after testing *uaddr. This guarantees that futex_wait() will NOT
2753 * absorb a wakeup if *uaddr does not match the desired values
2754 * while the syscall executes.
1da177e4 2755 */
f801073f 2756retry:
96d4f267 2757 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q->key, FUTEX_READ);
f801073f 2758 if (unlikely(ret != 0))
a5a2a0c7 2759 return ret;
f801073f
DH
2760
2761retry_private:
2762 *hb = queue_lock(q);
2763
e2970f2f 2764 ret = get_futex_value_locked(&uval, uaddr);
1da177e4 2765
f801073f 2766 if (ret) {
0d00c7b2 2767 queue_unlock(*hb);
1da177e4 2768
e2970f2f 2769 ret = get_user(uval, uaddr);
e4dc5b7a 2770 if (ret)
f801073f 2771 goto out;
1da177e4 2772
b41277dc 2773 if (!(flags & FLAGS_SHARED))
e4dc5b7a
DH
2774 goto retry_private;
2775
ae791a2d 2776 put_futex_key(&q->key);
e4dc5b7a 2777 goto retry;
1da177e4 2778 }
ca5f9524 2779
f801073f 2780 if (uval != val) {
0d00c7b2 2781 queue_unlock(*hb);
f801073f 2782 ret = -EWOULDBLOCK;
2fff78c7 2783 }
1da177e4 2784
f801073f
DH
2785out:
2786 if (ret)
ae791a2d 2787 put_futex_key(&q->key);
f801073f
DH
2788 return ret;
2789}
2790
b41277dc
DH
2791static int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
2792 ktime_t *abs_time, u32 bitset)
f801073f 2793{
5ca584d9 2794 struct hrtimer_sleeper timeout, *to;
f801073f
DH
2795 struct restart_block *restart;
2796 struct futex_hash_bucket *hb;
5bdb05f9 2797 struct futex_q q = futex_q_init;
f801073f
DH
2798 int ret;
2799
2800 if (!bitset)
2801 return -EINVAL;
f801073f
DH
2802 q.bitset = bitset;
2803
5ca584d9
WL
2804 to = futex_setup_timer(abs_time, &timeout, flags,
2805 current->timer_slack_ns);
d58e6576 2806retry:
7ada876a
DH
2807 /*
2808 * Prepare to wait on uaddr. On success, holds hb lock and increments
2809 * q.key refs.
2810 */
b41277dc 2811 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
f801073f
DH
2812 if (ret)
2813 goto out;
2814
ca5f9524 2815 /* queue_me and wait for wakeup, timeout, or a signal. */
f1a11e05 2816 futex_wait_queue_me(hb, &q, to);
1da177e4
LT
2817
2818 /* If we were woken (and unqueued), we succeeded, whatever. */
2fff78c7 2819 ret = 0;
7ada876a 2820 /* unqueue_me() drops q.key ref */
1da177e4 2821 if (!unqueue_me(&q))
7ada876a 2822 goto out;
2fff78c7 2823 ret = -ETIMEDOUT;
ca5f9524 2824 if (to && !to->task)
7ada876a 2825 goto out;
72c1bbf3 2826
e2970f2f 2827 /*
d58e6576
TG
2828 * We expect signal_pending(current), but we might be the
2829 * victim of a spurious wakeup as well.
e2970f2f 2830 */
7ada876a 2831 if (!signal_pending(current))
d58e6576 2832 goto retry;
d58e6576 2833
2fff78c7 2834 ret = -ERESTARTSYS;
c19384b5 2835 if (!abs_time)
7ada876a 2836 goto out;
1da177e4 2837
f56141e3 2838 restart = &current->restart_block;
2fff78c7 2839 restart->fn = futex_wait_restart;
a3c74c52 2840 restart->futex.uaddr = uaddr;
2fff78c7 2841 restart->futex.val = val;
2456e855 2842 restart->futex.time = *abs_time;
2fff78c7 2843 restart->futex.bitset = bitset;
0cd9c649 2844 restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
42d35d48 2845
2fff78c7
PZ
2846 ret = -ERESTART_RESTARTBLOCK;
2847
42d35d48 2848out:
ca5f9524
DH
2849 if (to) {
2850 hrtimer_cancel(&to->timer);
2851 destroy_hrtimer_on_stack(&to->timer);
2852 }
c87e2837
IM
2853 return ret;
2854}
2855
72c1bbf3
NP
2856
2857static long futex_wait_restart(struct restart_block *restart)
2858{
a3c74c52 2859 u32 __user *uaddr = restart->futex.uaddr;
a72188d8 2860 ktime_t t, *tp = NULL;
72c1bbf3 2861
a72188d8 2862 if (restart->futex.flags & FLAGS_HAS_TIMEOUT) {
2456e855 2863 t = restart->futex.time;
a72188d8
DH
2864 tp = &t;
2865 }
72c1bbf3 2866 restart->fn = do_no_restart_syscall;
b41277dc
DH
2867
2868 return (long)futex_wait(uaddr, restart->futex.flags,
2869 restart->futex.val, tp, restart->futex.bitset);
72c1bbf3
NP
2870}
2871
2872
c87e2837
IM
2873/*
2874 * Userspace tried a 0 -> TID atomic transition of the futex value
2875 * and failed. The kernel side here does the whole locking operation:
767f509c
DB
2876 * if there are waiters then it will block as a consequence of relying
2877 * on rt-mutexes, it does PI, etc. (Due to races the kernel might see
2878 * a 0 value of the futex too.).
2879 *
2880 * Also serves as futex trylock_pi()'ing, and due semantics.
c87e2837 2881 */
996636dd 2882static int futex_lock_pi(u32 __user *uaddr, unsigned int flags,
b41277dc 2883 ktime_t *time, int trylock)
c87e2837 2884{
5ca584d9 2885 struct hrtimer_sleeper timeout, *to;
16ffa12d 2886 struct futex_pi_state *pi_state = NULL;
3ef240ea 2887 struct task_struct *exiting = NULL;
cfafcd11 2888 struct rt_mutex_waiter rt_waiter;
c87e2837 2889 struct futex_hash_bucket *hb;
5bdb05f9 2890 struct futex_q q = futex_q_init;
dd973998 2891 int res, ret;
c87e2837 2892
bc2eecd7
NP
2893 if (!IS_ENABLED(CONFIG_FUTEX_PI))
2894 return -ENOSYS;
2895
c87e2837
IM
2896 if (refill_pi_state_cache())
2897 return -ENOMEM;
2898
5ca584d9 2899 to = futex_setup_timer(time, &timeout, FLAGS_CLOCKRT, 0);
c5780e97 2900
42d35d48 2901retry:
96d4f267 2902 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &q.key, FUTEX_WRITE);
c87e2837 2903 if (unlikely(ret != 0))
42d35d48 2904 goto out;
c87e2837 2905
e4dc5b7a 2906retry_private:
82af7aca 2907 hb = queue_lock(&q);
c87e2837 2908
3ef240ea
TG
2909 ret = futex_lock_pi_atomic(uaddr, hb, &q.key, &q.pi_state, current,
2910 &exiting, 0);
c87e2837 2911 if (unlikely(ret)) {
767f509c
DB
2912 /*
2913 * Atomic work succeeded and we got the lock,
2914 * or failed. Either way, we do _not_ block.
2915 */
778e9a9c 2916 switch (ret) {
1a52084d
DH
2917 case 1:
2918 /* We got the lock. */
2919 ret = 0;
2920 goto out_unlock_put_key;
2921 case -EFAULT:
2922 goto uaddr_faulted;
ac31c7ff 2923 case -EBUSY:
778e9a9c
AK
2924 case -EAGAIN:
2925 /*
af54d6a1 2926 * Two reasons for this:
ac31c7ff 2927 * - EBUSY: Task is exiting and we just wait for the
af54d6a1 2928 * exit to complete.
ac31c7ff 2929 * - EAGAIN: The user space value changed.
778e9a9c 2930 */
0d00c7b2 2931 queue_unlock(hb);
ae791a2d 2932 put_futex_key(&q.key);
3ef240ea
TG
2933 /*
2934 * Handle the case where the owner is in the middle of
2935 * exiting. Wait for the exit to complete otherwise
2936 * this task might loop forever, aka. live lock.
2937 */
2938 wait_for_owner_exiting(ret, exiting);
778e9a9c
AK
2939 cond_resched();
2940 goto retry;
778e9a9c 2941 default:
42d35d48 2942 goto out_unlock_put_key;
c87e2837 2943 }
c87e2837
IM
2944 }
2945
cfafcd11
PZ
2946 WARN_ON(!q.pi_state);
2947
c87e2837
IM
2948 /*
2949 * Only actually queue now that the atomic ops are done:
2950 */
cfafcd11 2951 __queue_me(&q, hb);
c87e2837 2952
cfafcd11 2953 if (trylock) {
5293c2ef 2954 ret = rt_mutex_futex_trylock(&q.pi_state->pi_mutex);
c87e2837
IM
2955 /* Fixup the trylock return value: */
2956 ret = ret ? 0 : -EWOULDBLOCK;
cfafcd11 2957 goto no_block;
c87e2837
IM
2958 }
2959
56222b21
PZ
2960 rt_mutex_init_waiter(&rt_waiter);
2961
cfafcd11 2962 /*
56222b21
PZ
2963 * On PREEMPT_RT_FULL, when hb->lock becomes an rt_mutex, we must not
2964 * hold it while doing rt_mutex_start_proxy(), because then it will
2965 * include hb->lock in the blocking chain, even through we'll not in
2966 * fact hold it while blocking. This will lead it to report -EDEADLK
2967 * and BUG when futex_unlock_pi() interleaves with this.
2968 *
2969 * Therefore acquire wait_lock while holding hb->lock, but drop the
1a1fb985
TG
2970 * latter before calling __rt_mutex_start_proxy_lock(). This
2971 * interleaves with futex_unlock_pi() -- which does a similar lock
2972 * handoff -- such that the latter can observe the futex_q::pi_state
2973 * before __rt_mutex_start_proxy_lock() is done.
cfafcd11 2974 */
56222b21
PZ
2975 raw_spin_lock_irq(&q.pi_state->pi_mutex.wait_lock);
2976 spin_unlock(q.lock_ptr);
1a1fb985
TG
2977 /*
2978 * __rt_mutex_start_proxy_lock() unconditionally enqueues the @rt_waiter
2979 * such that futex_unlock_pi() is guaranteed to observe the waiter when
2980 * it sees the futex_q::pi_state.
2981 */
56222b21
PZ
2982 ret = __rt_mutex_start_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter, current);
2983 raw_spin_unlock_irq(&q.pi_state->pi_mutex.wait_lock);
2984
cfafcd11
PZ
2985 if (ret) {
2986 if (ret == 1)
2987 ret = 0;
1a1fb985 2988 goto cleanup;
cfafcd11
PZ
2989 }
2990
cfafcd11 2991 if (unlikely(to))
9dd8813e 2992 hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
cfafcd11
PZ
2993
2994 ret = rt_mutex_wait_proxy_lock(&q.pi_state->pi_mutex, to, &rt_waiter);
2995
1a1fb985 2996cleanup:
a99e4e41 2997 spin_lock(q.lock_ptr);
cfafcd11 2998 /*
1a1fb985 2999 * If we failed to acquire the lock (deadlock/signal/timeout), we must
cfafcd11 3000 * first acquire the hb->lock before removing the lock from the
1a1fb985
TG
3001 * rt_mutex waitqueue, such that we can keep the hb and rt_mutex wait
3002 * lists consistent.
56222b21
PZ
3003 *
3004 * In particular; it is important that futex_unlock_pi() can not
3005 * observe this inconsistency.
cfafcd11
PZ
3006 */
3007 if (ret && !rt_mutex_cleanup_proxy_lock(&q.pi_state->pi_mutex, &rt_waiter))
3008 ret = 0;
3009
3010no_block:
dd973998
DH
3011 /*
3012 * Fixup the pi_state owner and possibly acquire the lock if we
3013 * haven't already.
3014 */
ae791a2d 3015 res = fixup_owner(uaddr, &q, !ret);
dd973998
DH
3016 /*
3017 * If fixup_owner() returned an error, proprogate that. If it acquired
3018 * the lock, clear our -ETIMEDOUT or -EINTR.
3019 */
3020 if (res)
3021 ret = (res < 0) ? res : 0;
c87e2837 3022
e8f6386c 3023 /*
dd973998
DH
3024 * If fixup_owner() faulted and was unable to handle the fault, unlock
3025 * it and return the fault to userspace.
e8f6386c 3026 */
16ffa12d
PZ
3027 if (ret && (rt_mutex_owner(&q.pi_state->pi_mutex) == current)) {
3028 pi_state = q.pi_state;
3029 get_pi_state(pi_state);
3030 }
e8f6386c 3031
778e9a9c
AK
3032 /* Unqueue and drop the lock */
3033 unqueue_me_pi(&q);
c87e2837 3034
16ffa12d
PZ
3035 if (pi_state) {
3036 rt_mutex_futex_unlock(&pi_state->pi_mutex);
3037 put_pi_state(pi_state);
3038 }
3039
5ecb01cf 3040 goto out_put_key;
c87e2837 3041
42d35d48 3042out_unlock_put_key:
0d00c7b2 3043 queue_unlock(hb);
c87e2837 3044
42d35d48 3045out_put_key:
ae791a2d 3046 put_futex_key(&q.key);
42d35d48 3047out:
97181f9b
TG
3048 if (to) {
3049 hrtimer_cancel(&to->timer);
237fc6e7 3050 destroy_hrtimer_on_stack(&to->timer);
97181f9b 3051 }
dd973998 3052 return ret != -EINTR ? ret : -ERESTARTNOINTR;
c87e2837 3053
42d35d48 3054uaddr_faulted:
0d00c7b2 3055 queue_unlock(hb);
778e9a9c 3056
d0725992 3057 ret = fault_in_user_writeable(uaddr);
e4dc5b7a
DH
3058 if (ret)
3059 goto out_put_key;
c87e2837 3060
b41277dc 3061 if (!(flags & FLAGS_SHARED))
e4dc5b7a
DH
3062 goto retry_private;
3063
ae791a2d 3064 put_futex_key(&q.key);
e4dc5b7a 3065 goto retry;
c87e2837
IM
3066}
3067
c87e2837
IM
3068/*
3069 * Userspace attempted a TID -> 0 atomic transition, and failed.
3070 * This is the in-kernel slowpath: we look up the PI state (if any),
3071 * and do the rt-mutex unlock.
3072 */
b41277dc 3073static int futex_unlock_pi(u32 __user *uaddr, unsigned int flags)
c87e2837 3074{
ccf9e6a8 3075 u32 uninitialized_var(curval), uval, vpid = task_pid_vnr(current);
38d47c1b 3076 union futex_key key = FUTEX_KEY_INIT;
ccf9e6a8 3077 struct futex_hash_bucket *hb;
499f5aca 3078 struct futex_q *top_waiter;
e4dc5b7a 3079 int ret;
c87e2837 3080
bc2eecd7
NP
3081 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3082 return -ENOSYS;
3083
c87e2837
IM
3084retry:
3085 if (get_user(uval, uaddr))
3086 return -EFAULT;
3087 /*
3088 * We release only a lock we actually own:
3089 */
c0c9ed15 3090 if ((uval & FUTEX_TID_MASK) != vpid)
c87e2837 3091 return -EPERM;
c87e2837 3092
96d4f267 3093 ret = get_futex_key(uaddr, flags & FLAGS_SHARED, &key, FUTEX_WRITE);
ccf9e6a8
TG
3094 if (ret)
3095 return ret;
c87e2837
IM
3096
3097 hb = hash_futex(&key);
3098 spin_lock(&hb->lock);
3099
c87e2837 3100 /*
ccf9e6a8
TG
3101 * Check waiters first. We do not trust user space values at
3102 * all and we at least want to know if user space fiddled
3103 * with the futex value instead of blindly unlocking.
c87e2837 3104 */
499f5aca
PZ
3105 top_waiter = futex_top_waiter(hb, &key);
3106 if (top_waiter) {
16ffa12d
PZ
3107 struct futex_pi_state *pi_state = top_waiter->pi_state;
3108
3109 ret = -EINVAL;
3110 if (!pi_state)
3111 goto out_unlock;
3112
3113 /*
3114 * If current does not own the pi_state then the futex is
3115 * inconsistent and user space fiddled with the futex value.
3116 */
3117 if (pi_state->owner != current)
3118 goto out_unlock;
3119
bebe5b51 3120 get_pi_state(pi_state);
802ab58d 3121 /*
bebe5b51
PZ
3122 * By taking wait_lock while still holding hb->lock, we ensure
3123 * there is no point where we hold neither; and therefore
3124 * wake_futex_pi() must observe a state consistent with what we
3125 * observed.
1a1fb985
TG
3126 *
3127 * In particular; this forces __rt_mutex_start_proxy() to
3128 * complete such that we're guaranteed to observe the
3129 * rt_waiter. Also see the WARN in wake_futex_pi().
16ffa12d 3130 */
bebe5b51 3131 raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
16ffa12d
PZ
3132 spin_unlock(&hb->lock);
3133
c74aef2d 3134 /* drops pi_state->pi_mutex.wait_lock */
16ffa12d
PZ
3135 ret = wake_futex_pi(uaddr, uval, pi_state);
3136
3137 put_pi_state(pi_state);
3138
3139 /*
3140 * Success, we're done! No tricky corner cases.
802ab58d
SAS
3141 */
3142 if (!ret)
3143 goto out_putkey;
c87e2837 3144 /*
ccf9e6a8
TG
3145 * The atomic access to the futex value generated a
3146 * pagefault, so retry the user-access and the wakeup:
c87e2837
IM
3147 */
3148 if (ret == -EFAULT)
3149 goto pi_faulted;
89e9e66b
SAS
3150 /*
3151 * A unconditional UNLOCK_PI op raced against a waiter
3152 * setting the FUTEX_WAITERS bit. Try again.
3153 */
6b4f4bc9
WD
3154 if (ret == -EAGAIN)
3155 goto pi_retry;
802ab58d
SAS
3156 /*
3157 * wake_futex_pi has detected invalid state. Tell user
3158 * space.
3159 */
16ffa12d 3160 goto out_putkey;
c87e2837 3161 }
ccf9e6a8 3162
c87e2837 3163 /*
ccf9e6a8
TG
3164 * We have no kernel internal state, i.e. no waiters in the
3165 * kernel. Waiters which are about to queue themselves are stuck
3166 * on hb->lock. So we can safely ignore them. We do neither
3167 * preserve the WAITERS bit not the OWNER_DIED one. We are the
3168 * owner.
c87e2837 3169 */
6b4f4bc9 3170 if ((ret = cmpxchg_futex_value_locked(&curval, uaddr, uval, 0))) {
16ffa12d 3171 spin_unlock(&hb->lock);
6b4f4bc9
WD
3172 switch (ret) {
3173 case -EFAULT:
3174 goto pi_faulted;
3175
3176 case -EAGAIN:
3177 goto pi_retry;
3178
3179 default:
3180 WARN_ON_ONCE(1);
3181 goto out_putkey;
3182 }
16ffa12d 3183 }
c87e2837 3184
ccf9e6a8
TG
3185 /*
3186 * If uval has changed, let user space handle it.
3187 */
3188 ret = (curval == uval) ? 0 : -EAGAIN;
3189
c87e2837
IM
3190out_unlock:
3191 spin_unlock(&hb->lock);
802ab58d 3192out_putkey:
ae791a2d 3193 put_futex_key(&key);
c87e2837
IM
3194 return ret;
3195
6b4f4bc9
WD
3196pi_retry:
3197 put_futex_key(&key);
3198 cond_resched();
3199 goto retry;
3200
c87e2837 3201pi_faulted:
ae791a2d 3202 put_futex_key(&key);
c87e2837 3203
d0725992 3204 ret = fault_in_user_writeable(uaddr);
b5686363 3205 if (!ret)
c87e2837
IM
3206 goto retry;
3207
1da177e4
LT
3208 return ret;
3209}
3210
52400ba9
DH
3211/**
3212 * handle_early_requeue_pi_wakeup() - Detect early wakeup on the initial futex
3213 * @hb: the hash_bucket futex_q was original enqueued on
3214 * @q: the futex_q woken while waiting to be requeued
3215 * @key2: the futex_key of the requeue target futex
3216 * @timeout: the timeout associated with the wait (NULL if none)
3217 *
3218 * Detect if the task was woken on the initial futex as opposed to the requeue
3219 * target futex. If so, determine if it was a timeout or a signal that caused
3220 * the wakeup and return the appropriate error code to the caller. Must be
3221 * called with the hb lock held.
3222 *
6c23cbbd 3223 * Return:
7b4ff1ad
MCC
3224 * - 0 = no early wakeup detected;
3225 * - <0 = -ETIMEDOUT or -ERESTARTNOINTR
52400ba9
DH
3226 */
3227static inline
3228int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
3229 struct futex_q *q, union futex_key *key2,
3230 struct hrtimer_sleeper *timeout)
3231{
3232 int ret = 0;
3233
3234 /*
3235 * With the hb lock held, we avoid races while we process the wakeup.
3236 * We only need to hold hb (and not hb2) to ensure atomicity as the
3237 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
3238 * It can't be requeued from uaddr2 to something else since we don't
3239 * support a PI aware source futex for requeue.
3240 */
3241 if (!match_futex(&q->key, key2)) {
3242 WARN_ON(q->lock_ptr && (&hb->lock != q->lock_ptr));
3243 /*
3244 * We were woken prior to requeue by a timeout or a signal.
3245 * Unqueue the futex_q and determine which it was.
3246 */
2e12978a 3247 plist_del(&q->list, &hb->chain);
11d4616b 3248 hb_waiters_dec(hb);
52400ba9 3249
d58e6576 3250 /* Handle spurious wakeups gracefully */
11df6ddd 3251 ret = -EWOULDBLOCK;
52400ba9
DH
3252 if (timeout && !timeout->task)
3253 ret = -ETIMEDOUT;
d58e6576 3254 else if (signal_pending(current))
1c840c14 3255 ret = -ERESTARTNOINTR;
52400ba9
DH
3256 }
3257 return ret;
3258}
3259
3260/**
3261 * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
56ec1607 3262 * @uaddr: the futex we initially wait on (non-pi)
b41277dc 3263 * @flags: futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
ab51fbab 3264 * the same type, no requeueing from private to shared, etc.
52400ba9
DH
3265 * @val: the expected value of uaddr
3266 * @abs_time: absolute timeout
56ec1607 3267 * @bitset: 32 bit wakeup bitset set by userspace, defaults to all
52400ba9
DH
3268 * @uaddr2: the pi futex we will take prior to returning to user-space
3269 *
3270 * The caller will wait on uaddr and will be requeued by futex_requeue() to
6f7b0a2a
DH
3271 * uaddr2 which must be PI aware and unique from uaddr. Normal wakeup will wake
3272 * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
3273 * userspace. This ensures the rt_mutex maintains an owner when it has waiters;
3274 * without one, the pi logic would not know which task to boost/deboost, if
3275 * there was a need to.
52400ba9
DH
3276 *
3277 * We call schedule in futex_wait_queue_me() when we enqueue and return there
6c23cbbd 3278 * via the following--
52400ba9 3279 * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
cc6db4e6
DH
3280 * 2) wakeup on uaddr2 after a requeue
3281 * 3) signal
3282 * 4) timeout
52400ba9 3283 *
cc6db4e6 3284 * If 3, cleanup and return -ERESTARTNOINTR.
52400ba9
DH
3285 *
3286 * If 2, we may then block on trying to take the rt_mutex and return via:
3287 * 5) successful lock
3288 * 6) signal
3289 * 7) timeout
3290 * 8) other lock acquisition failure
3291 *
cc6db4e6 3292 * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
52400ba9
DH
3293 *
3294 * If 4 or 7, we cleanup and return with -ETIMEDOUT.
3295 *
6c23cbbd 3296 * Return:
7b4ff1ad
MCC
3297 * - 0 - On success;
3298 * - <0 - On error
52400ba9 3299 */
b41277dc 3300static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
52400ba9 3301 u32 val, ktime_t *abs_time, u32 bitset,
b41277dc 3302 u32 __user *uaddr2)
52400ba9 3303{
5ca584d9 3304 struct hrtimer_sleeper timeout, *to;
16ffa12d 3305 struct futex_pi_state *pi_state = NULL;
52400ba9 3306 struct rt_mutex_waiter rt_waiter;
52400ba9 3307 struct futex_hash_bucket *hb;
5bdb05f9
DH
3308 union futex_key key2 = FUTEX_KEY_INIT;
3309 struct futex_q q = futex_q_init;
52400ba9 3310 int res, ret;
52400ba9 3311
bc2eecd7
NP
3312 if (!IS_ENABLED(CONFIG_FUTEX_PI))
3313 return -ENOSYS;
3314
6f7b0a2a
DH
3315 if (uaddr == uaddr2)
3316 return -EINVAL;
3317
52400ba9
DH
3318 if (!bitset)
3319 return -EINVAL;
3320
5ca584d9
WL
3321 to = futex_setup_timer(abs_time, &timeout, flags,
3322 current->timer_slack_ns);
52400ba9
DH
3323
3324 /*
3325 * The waiter is allocated on our stack, manipulated by the requeue
3326 * code while we sleep on uaddr.
3327 */
50809358 3328 rt_mutex_init_waiter(&rt_waiter);
52400ba9 3329
96d4f267 3330 ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, FUTEX_WRITE);
52400ba9
DH
3331 if (unlikely(ret != 0))
3332 goto out;
3333
84bc4af5
DH
3334 q.bitset = bitset;
3335 q.rt_waiter = &rt_waiter;
3336 q.requeue_pi_key = &key2;
3337
7ada876a
DH
3338 /*
3339 * Prepare to wait on uaddr. On success, increments q.key (key1) ref
3340 * count.
3341 */
b41277dc 3342 ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
c8b15a70
TG
3343 if (ret)
3344 goto out_key2;
52400ba9 3345
e9c243a5
TG
3346 /*
3347 * The check above which compares uaddrs is not sufficient for
3348 * shared futexes. We need to compare the keys:
3349 */
3350 if (match_futex(&q.key, &key2)) {
13c42c2f 3351 queue_unlock(hb);
e9c243a5
TG
3352 ret = -EINVAL;
3353 goto out_put_keys;
3354 }
3355
52400ba9 3356 /* Queue the futex_q, drop the hb lock, wait for wakeup. */
f1a11e05 3357 futex_wait_queue_me(hb, &q, to);
52400ba9
DH
3358
3359 spin_lock(&hb->lock);
3360 ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to);
3361 spin_unlock(&hb->lock);
3362 if (ret)
3363 goto out_put_keys;
3364
3365 /*
3366 * In order for us to be here, we know our q.key == key2, and since
3367 * we took the hb->lock above, we also know that futex_requeue() has
3368 * completed and we no longer have to concern ourselves with a wakeup
7ada876a
DH
3369 * race with the atomic proxy lock acquisition by the requeue code. The
3370 * futex_requeue dropped our key1 reference and incremented our key2
3371 * reference count.
52400ba9
DH
3372 */
3373
3374 /* Check if the requeue code acquired the second futex for us. */
3375 if (!q.rt_waiter) {
3376 /*
3377 * Got the lock. We might not be the anticipated owner if we
3378 * did a lock-steal - fix up the PI-state in that case.
3379 */
3380 if (q.pi_state && (q.pi_state->owner != current)) {
3381 spin_lock(q.lock_ptr);
ae791a2d 3382 ret = fixup_pi_state_owner(uaddr2, &q, current);
16ffa12d
PZ
3383 if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current) {
3384 pi_state = q.pi_state;
3385 get_pi_state(pi_state);
3386 }
fb75a428
TG
3387 /*
3388 * Drop the reference to the pi state which
3389 * the requeue_pi() code acquired for us.
3390 */
29e9ee5d 3391 put_pi_state(q.pi_state);
52400ba9
DH
3392 spin_unlock(q.lock_ptr);
3393 }
3394 } else {
c236c8e9
PZ
3395 struct rt_mutex *pi_mutex;
3396
52400ba9
DH
3397 /*
3398 * We have been woken up by futex_unlock_pi(), a timeout, or a
3399 * signal. futex_unlock_pi() will not destroy the lock_ptr nor
3400 * the pi_state.
3401 */
f27071cb 3402 WARN_ON(!q.pi_state);
52400ba9 3403 pi_mutex = &q.pi_state->pi_mutex;
38d589f2 3404 ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
52400ba9
DH
3405
3406 spin_lock(q.lock_ptr);
38d589f2
PZ
3407 if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
3408 ret = 0;
3409
3410 debug_rt_mutex_free_waiter(&rt_waiter);
52400ba9
DH
3411 /*
3412 * Fixup the pi_state owner and possibly acquire the lock if we
3413 * haven't already.
3414 */
ae791a2d 3415 res = fixup_owner(uaddr2, &q, !ret);
52400ba9
DH
3416 /*
3417 * If fixup_owner() returned an error, proprogate that. If it
56ec1607 3418 * acquired the lock, clear -ETIMEDOUT or -EINTR.
52400ba9
DH
3419 */
3420 if (res)
3421 ret = (res < 0) ? res : 0;
3422
c236c8e9
PZ
3423 /*
3424 * If fixup_pi_state_owner() faulted and was unable to handle
3425 * the fault, unlock the rt_mutex and return the fault to
3426 * userspace.
3427 */
16ffa12d
PZ
3428 if (ret && rt_mutex_owner(&q.pi_state->pi_mutex) == current) {
3429 pi_state = q.pi_state;
3430 get_pi_state(pi_state);
3431 }
c236c8e9 3432
52400ba9
DH
3433 /* Unqueue and drop the lock. */
3434 unqueue_me_pi(&q);
3435 }
3436
16ffa12d
PZ
3437 if (pi_state) {
3438 rt_mutex_futex_unlock(&pi_state->pi_mutex);
3439 put_pi_state(pi_state);
3440 }
3441
c236c8e9 3442 if (ret == -EINTR) {
52400ba9 3443 /*
cc6db4e6
DH
3444 * We've already been requeued, but cannot restart by calling
3445 * futex_lock_pi() directly. We could restart this syscall, but
3446 * it would detect that the user space "val" changed and return
3447 * -EWOULDBLOCK. Save the overhead of the restart and return
3448 * -EWOULDBLOCK directly.
52400ba9 3449 */
2070887f 3450 ret = -EWOULDBLOCK;
52400ba9
DH
3451 }
3452
3453out_put_keys:
ae791a2d 3454 put_futex_key(&q.key);
c8b15a70 3455out_key2:
ae791a2d 3456 put_futex_key(&key2);
52400ba9
DH
3457
3458out:
3459 if (to) {
3460 hrtimer_cancel(&to->timer);
3461 destroy_hrtimer_on_stack(&to->timer);
3462 }
3463 return ret;
3464}
3465
0771dfef
IM
3466/*
3467 * Support for robust futexes: the kernel cleans up held futexes at
3468 * thread exit time.
3469 *
3470 * Implementation: user-space maintains a per-thread list of locks it
3471 * is holding. Upon do_exit(), the kernel carefully walks this list,
3472 * and marks all locks that are owned by this thread with the
c87e2837 3473 * FUTEX_OWNER_DIED bit, and wakes up a waiter (if any). The list is
0771dfef
IM
3474 * always manipulated with the lock held, so the list is private and
3475 * per-thread. Userspace also maintains a per-thread 'list_op_pending'
3476 * field, to allow the kernel to clean up if the thread dies after
3477 * acquiring the lock, but just before it could have added itself to
3478 * the list. There can only be one such pending lock.
3479 */
3480
3481/**
d96ee56c
DH
3482 * sys_set_robust_list() - Set the robust-futex list head of a task
3483 * @head: pointer to the list-head
3484 * @len: length of the list-head, as userspace expects
0771dfef 3485 */
836f92ad
HC
3486SYSCALL_DEFINE2(set_robust_list, struct robust_list_head __user *, head,
3487 size_t, len)
0771dfef 3488{
a0c1e907
TG
3489 if (!futex_cmpxchg_enabled)
3490 return -ENOSYS;
0771dfef
IM
3491 /*
3492 * The kernel knows only one size for now:
3493 */
3494 if (unlikely(len != sizeof(*head)))
3495 return -EINVAL;
3496
3497 current->robust_list = head;
3498
3499 return 0;
3500}
3501
3502/**
d96ee56c
DH
3503 * sys_get_robust_list() - Get the robust-futex list head of a task
3504 * @pid: pid of the process [zero for current task]
3505 * @head_ptr: pointer to a list-head pointer, the kernel fills it in
3506 * @len_ptr: pointer to a length field, the kernel fills in the header size
0771dfef 3507 */
836f92ad
HC
3508SYSCALL_DEFINE3(get_robust_list, int, pid,
3509 struct robust_list_head __user * __user *, head_ptr,
3510 size_t __user *, len_ptr)
0771dfef 3511{
ba46df98 3512 struct robust_list_head __user *head;
0771dfef 3513 unsigned long ret;
bdbb776f 3514 struct task_struct *p;
0771dfef 3515
a0c1e907
TG
3516 if (!futex_cmpxchg_enabled)
3517 return -ENOSYS;
3518
bdbb776f
KC
3519 rcu_read_lock();
3520
3521 ret = -ESRCH;
0771dfef 3522 if (!pid)
bdbb776f 3523 p = current;
0771dfef 3524 else {
228ebcbe 3525 p = find_task_by_vpid(pid);
0771dfef
IM
3526 if (!p)
3527 goto err_unlock;
0771dfef
IM
3528 }
3529
bdbb776f 3530 ret = -EPERM;
caaee623 3531 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
bdbb776f
KC
3532 goto err_unlock;
3533
3534 head = p->robust_list;
3535 rcu_read_unlock();
3536
0771dfef
IM
3537 if (put_user(sizeof(*head), len_ptr))
3538 return -EFAULT;
3539 return put_user(head, head_ptr);
3540
3541err_unlock:
aaa2a97e 3542 rcu_read_unlock();
0771dfef
IM
3543
3544 return ret;
3545}
3546
ca16d5be
YT
3547/* Constants for the pending_op argument of handle_futex_death */
3548#define HANDLE_DEATH_PENDING true
3549#define HANDLE_DEATH_LIST false
3550
0771dfef
IM
3551/*
3552 * Process a futex-list entry, check whether it's owned by the
3553 * dying task, and do notification if so:
3554 */
ca16d5be
YT
3555static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
3556 bool pi, bool pending_op)
0771dfef 3557{
7cfdaf38 3558 u32 uval, uninitialized_var(nval), mval;
6b4f4bc9 3559 int err;
0771dfef 3560
5a07168d
CJ
3561 /* Futex address must be 32bit aligned */
3562 if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
3563 return -1;
3564
8f17d3a5
IM
3565retry:
3566 if (get_user(uval, uaddr))
0771dfef
IM
3567 return -1;
3568
ca16d5be
YT
3569 /*
3570 * Special case for regular (non PI) futexes. The unlock path in
3571 * user space has two race scenarios:
3572 *
3573 * 1. The unlock path releases the user space futex value and
3574 * before it can execute the futex() syscall to wake up
3575 * waiters it is killed.
3576 *
3577 * 2. A woken up waiter is killed before it can acquire the
3578 * futex in user space.
3579 *
3580 * In both cases the TID validation below prevents a wakeup of
3581 * potential waiters which can cause these waiters to block
3582 * forever.
3583 *
3584 * In both cases the following conditions are met:
3585 *
3586 * 1) task->robust_list->list_op_pending != NULL
3587 * @pending_op == true
3588 * 2) User space futex value == 0
3589 * 3) Regular futex: @pi == false
3590 *
3591 * If these conditions are met, it is safe to attempt waking up a
3592 * potential waiter without touching the user space futex value and
3593 * trying to set the OWNER_DIED bit. The user space futex value is
3594 * uncontended and the rest of the user space mutex state is
3595 * consistent, so a woken waiter will just take over the
3596 * uncontended futex. Setting the OWNER_DIED bit would create
3597 * inconsistent state and malfunction of the user space owner died
3598 * handling.
3599 */
3600 if (pending_op && !pi && !uval) {
3601 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3602 return 0;
3603 }
3604
6b4f4bc9
WD
3605 if ((uval & FUTEX_TID_MASK) != task_pid_vnr(curr))
3606 return 0;
3607
3608 /*
3609 * Ok, this dying thread is truly holding a futex
3610 * of interest. Set the OWNER_DIED bit atomically
3611 * via cmpxchg, and if the value had FUTEX_WAITERS
3612 * set, wake up a waiter (if any). (We have to do a
3613 * futex_wake() even if OWNER_DIED is already set -
3614 * to handle the rare but possible case of recursive
3615 * thread-death.) The rest of the cleanup is done in
3616 * userspace.
3617 */
3618 mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
3619
3620 /*
3621 * We are not holding a lock here, but we want to have
3622 * the pagefault_disable/enable() protection because
3623 * we want to handle the fault gracefully. If the
3624 * access fails we try to fault in the futex with R/W
3625 * verification via get_user_pages. get_user() above
3626 * does not guarantee R/W access. If that fails we
3627 * give up and leave the futex locked.
3628 */
3629 if ((err = cmpxchg_futex_value_locked(&nval, uaddr, uval, mval))) {
3630 switch (err) {
3631 case -EFAULT:
6e0aa9f8
TG
3632 if (fault_in_user_writeable(uaddr))
3633 return -1;
3634 goto retry;
6b4f4bc9
WD
3635
3636 case -EAGAIN:
3637 cond_resched();
8f17d3a5 3638 goto retry;
0771dfef 3639
6b4f4bc9
WD
3640 default:
3641 WARN_ON_ONCE(1);
3642 return err;
3643 }
0771dfef 3644 }
6b4f4bc9
WD
3645
3646 if (nval != uval)
3647 goto retry;
3648
3649 /*
3650 * Wake robust non-PI futexes here. The wakeup of
3651 * PI futexes happens in exit_pi_state():
3652 */
3653 if (!pi && (uval & FUTEX_WAITERS))
3654 futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
3655
0771dfef
IM
3656 return 0;
3657}
3658
e3f2ddea
IM
3659/*
3660 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3661 */
3662static inline int fetch_robust_entry(struct robust_list __user **entry,
ba46df98 3663 struct robust_list __user * __user *head,
1dcc41bb 3664 unsigned int *pi)
e3f2ddea
IM
3665{
3666 unsigned long uentry;
3667
ba46df98 3668 if (get_user(uentry, (unsigned long __user *)head))
e3f2ddea
IM
3669 return -EFAULT;
3670
ba46df98 3671 *entry = (void __user *)(uentry & ~1UL);
e3f2ddea
IM
3672 *pi = uentry & 1;
3673
3674 return 0;
3675}
3676
0771dfef
IM
3677/*
3678 * Walk curr->robust_list (very carefully, it's a userspace list!)
3679 * and mark any locks found there dead, and notify any waiters.
3680 *
3681 * We silently return on any sign of list-walking problem.
3682 */
ba31c1a4 3683static void exit_robust_list(struct task_struct *curr)
0771dfef
IM
3684{
3685 struct robust_list_head __user *head = curr->robust_list;
9f96cb1e 3686 struct robust_list __user *entry, *next_entry, *pending;
4c115e95
DH
3687 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3688 unsigned int uninitialized_var(next_pi);
0771dfef 3689 unsigned long futex_offset;
9f96cb1e 3690 int rc;
0771dfef 3691
a0c1e907
TG
3692 if (!futex_cmpxchg_enabled)
3693 return;
3694
0771dfef
IM
3695 /*
3696 * Fetch the list head (which was registered earlier, via
3697 * sys_set_robust_list()):
3698 */
e3f2ddea 3699 if (fetch_robust_entry(&entry, &head->list.next, &pi))
0771dfef
IM
3700 return;
3701 /*
3702 * Fetch the relative futex offset:
3703 */
3704 if (get_user(futex_offset, &head->futex_offset))
3705 return;
3706 /*
3707 * Fetch any possibly pending lock-add first, and handle it
3708 * if it exists:
3709 */
e3f2ddea 3710 if (fetch_robust_entry(&pending, &head->list_op_pending, &pip))
0771dfef 3711 return;
e3f2ddea 3712
9f96cb1e 3713 next_entry = NULL; /* avoid warning with gcc */
0771dfef 3714 while (entry != &head->list) {
9f96cb1e
MS
3715 /*
3716 * Fetch the next entry in the list before calling
3717 * handle_futex_death:
3718 */
3719 rc = fetch_robust_entry(&next_entry, &entry->next, &next_pi);
0771dfef
IM
3720 /*
3721 * A pending lock might already be on the list, so
c87e2837 3722 * don't process it twice:
0771dfef 3723 */
ca16d5be 3724 if (entry != pending) {
ba46df98 3725 if (handle_futex_death((void __user *)entry + futex_offset,
ca16d5be 3726 curr, pi, HANDLE_DEATH_LIST))
0771dfef 3727 return;
ca16d5be 3728 }
9f96cb1e 3729 if (rc)
0771dfef 3730 return;
9f96cb1e
MS
3731 entry = next_entry;
3732 pi = next_pi;
0771dfef
IM
3733 /*
3734 * Avoid excessively long or circular lists:
3735 */
3736 if (!--limit)
3737 break;
3738
3739 cond_resched();
3740 }
9f96cb1e 3741
ca16d5be 3742 if (pending) {
9f96cb1e 3743 handle_futex_death((void __user *)pending + futex_offset,
ca16d5be
YT
3744 curr, pip, HANDLE_DEATH_PENDING);
3745 }
0771dfef
IM
3746}
3747
af8cbda2 3748static void futex_cleanup(struct task_struct *tsk)
ba31c1a4
TG
3749{
3750 if (unlikely(tsk->robust_list)) {
3751 exit_robust_list(tsk);
3752 tsk->robust_list = NULL;
3753 }
3754
3755#ifdef CONFIG_COMPAT
3756 if (unlikely(tsk->compat_robust_list)) {
3757 compat_exit_robust_list(tsk);
3758 tsk->compat_robust_list = NULL;
3759 }
3760#endif
3761
3762 if (unlikely(!list_empty(&tsk->pi_state_list)))
3763 exit_pi_state_list(tsk);
3764}
3765
18f69438
TG
3766/**
3767 * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
3768 * @tsk: task to set the state on
3769 *
3770 * Set the futex exit state of the task lockless. The futex waiter code
3771 * observes that state when a task is exiting and loops until the task has
3772 * actually finished the futex cleanup. The worst case for this is that the
3773 * waiter runs through the wait loop until the state becomes visible.
3774 *
3775 * This is called from the recursive fault handling path in do_exit().
3776 *
3777 * This is best effort. Either the futex exit code has run already or
3778 * not. If the OWNER_DIED bit has been set on the futex then the waiter can
3779 * take it over. If not, the problem is pushed back to user space. If the
3780 * futex exit code did not run yet, then an already queued waiter might
3781 * block forever, but there is nothing which can be done about that.
3782 */
3783void futex_exit_recursive(struct task_struct *tsk)
3784{
3f186d97
TG
3785 /* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
3786 if (tsk->futex_state == FUTEX_STATE_EXITING)
3787 mutex_unlock(&tsk->futex_exit_mutex);
18f69438
TG
3788 tsk->futex_state = FUTEX_STATE_DEAD;
3789}
3790
af8cbda2 3791static void futex_cleanup_begin(struct task_struct *tsk)
150d7158 3792{
3f186d97
TG
3793 /*
3794 * Prevent various race issues against a concurrent incoming waiter
3795 * including live locks by forcing the waiter to block on
3796 * tsk->futex_exit_mutex when it observes FUTEX_STATE_EXITING in
3797 * attach_to_pi_owner().
3798 */
3799 mutex_lock(&tsk->futex_exit_mutex);
3800
18f69438 3801 /*
4a8e991b
TG
3802 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
3803 *
3804 * This ensures that all subsequent checks of tsk->futex_state in
3805 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
3806 * tsk->pi_lock held.
3807 *
3808 * It guarantees also that a pi_state which was queued right before
3809 * the state change under tsk->pi_lock by a concurrent waiter must
3810 * be observed in exit_pi_state_list().
18f69438
TG
3811 */
3812 raw_spin_lock_irq(&tsk->pi_lock);
4a8e991b 3813 tsk->futex_state = FUTEX_STATE_EXITING;
18f69438 3814 raw_spin_unlock_irq(&tsk->pi_lock);
af8cbda2 3815}
18f69438 3816
af8cbda2
TG
3817static void futex_cleanup_end(struct task_struct *tsk, int state)
3818{
3819 /*
3820 * Lockless store. The only side effect is that an observer might
3821 * take another loop until it becomes visible.
3822 */
3823 tsk->futex_state = state;
3f186d97
TG
3824 /*
3825 * Drop the exit protection. This unblocks waiters which observed
3826 * FUTEX_STATE_EXITING to reevaluate the state.
3827 */
3828 mutex_unlock(&tsk->futex_exit_mutex);
af8cbda2 3829}
18f69438 3830
af8cbda2
TG
3831void futex_exec_release(struct task_struct *tsk)
3832{
3833 /*
3834 * The state handling is done for consistency, but in the case of
3835 * exec() there is no way to prevent futher damage as the PID stays
3836 * the same. But for the unlikely and arguably buggy case that a
3837 * futex is held on exec(), this provides at least as much state
3838 * consistency protection which is possible.
3839 */
3840 futex_cleanup_begin(tsk);
3841 futex_cleanup(tsk);
3842 /*
3843 * Reset the state to FUTEX_STATE_OK. The task is alive and about
3844 * exec a new binary.
3845 */
3846 futex_cleanup_end(tsk, FUTEX_STATE_OK);
3847}
3848
3849void futex_exit_release(struct task_struct *tsk)
3850{
3851 futex_cleanup_begin(tsk);
3852 futex_cleanup(tsk);
3853 futex_cleanup_end(tsk, FUTEX_STATE_DEAD);
150d7158
TG
3854}
3855
c19384b5 3856long do_futex(u32 __user *uaddr, int op, u32 val, ktime_t *timeout,
e2970f2f 3857 u32 __user *uaddr2, u32 val2, u32 val3)
1da177e4 3858{
81b40539 3859 int cmd = op & FUTEX_CMD_MASK;
b41277dc 3860 unsigned int flags = 0;
34f01cc1
ED
3861
3862 if (!(op & FUTEX_PRIVATE_FLAG))
b41277dc 3863 flags |= FLAGS_SHARED;
1da177e4 3864
b41277dc
DH
3865 if (op & FUTEX_CLOCK_REALTIME) {
3866 flags |= FLAGS_CLOCKRT;
337f1304
DH
3867 if (cmd != FUTEX_WAIT && cmd != FUTEX_WAIT_BITSET && \
3868 cmd != FUTEX_WAIT_REQUEUE_PI)
b41277dc
DH
3869 return -ENOSYS;
3870 }
1da177e4 3871
59263b51
TG
3872 switch (cmd) {
3873 case FUTEX_LOCK_PI:
3874 case FUTEX_UNLOCK_PI:
3875 case FUTEX_TRYLOCK_PI:
3876 case FUTEX_WAIT_REQUEUE_PI:
3877 case FUTEX_CMP_REQUEUE_PI:
3878 if (!futex_cmpxchg_enabled)
3879 return -ENOSYS;
3880 }
3881
34f01cc1 3882 switch (cmd) {
1da177e4 3883 case FUTEX_WAIT:
cd689985 3884 val3 = FUTEX_BITSET_MATCH_ANY;
b639186f 3885 /* fall through */
cd689985 3886 case FUTEX_WAIT_BITSET:
81b40539 3887 return futex_wait(uaddr, flags, val, timeout, val3);
1da177e4 3888 case FUTEX_WAKE:
cd689985 3889 val3 = FUTEX_BITSET_MATCH_ANY;
b639186f 3890 /* fall through */
cd689985 3891 case FUTEX_WAKE_BITSET:
81b40539 3892 return futex_wake(uaddr, flags, val, val3);
1da177e4 3893 case FUTEX_REQUEUE:
81b40539 3894 return futex_requeue(uaddr, flags, uaddr2, val, val2, NULL, 0);
1da177e4 3895 case FUTEX_CMP_REQUEUE:
81b40539 3896 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 0);
4732efbe 3897 case FUTEX_WAKE_OP:
81b40539 3898 return futex_wake_op(uaddr, flags, uaddr2, val, val2, val3);
c87e2837 3899 case FUTEX_LOCK_PI:
996636dd 3900 return futex_lock_pi(uaddr, flags, timeout, 0);
c87e2837 3901 case FUTEX_UNLOCK_PI:
81b40539 3902 return futex_unlock_pi(uaddr, flags);
c87e2837 3903 case FUTEX_TRYLOCK_PI:
996636dd 3904 return futex_lock_pi(uaddr, flags, NULL, 1);
52400ba9
DH
3905 case FUTEX_WAIT_REQUEUE_PI:
3906 val3 = FUTEX_BITSET_MATCH_ANY;
81b40539
TG
3907 return futex_wait_requeue_pi(uaddr, flags, val, timeout, val3,
3908 uaddr2);
52400ba9 3909 case FUTEX_CMP_REQUEUE_PI:
81b40539 3910 return futex_requeue(uaddr, flags, uaddr2, val, val2, &val3, 1);
1da177e4 3911 }
81b40539 3912 return -ENOSYS;
1da177e4
LT
3913}
3914
3915
17da2bd9 3916SYSCALL_DEFINE6(futex, u32 __user *, uaddr, int, op, u32, val,
bec2f7cb 3917 struct __kernel_timespec __user *, utime, u32 __user *, uaddr2,
17da2bd9 3918 u32, val3)
1da177e4 3919{
bec2f7cb 3920 struct timespec64 ts;
c19384b5 3921 ktime_t t, *tp = NULL;
e2970f2f 3922 u32 val2 = 0;
34f01cc1 3923 int cmd = op & FUTEX_CMD_MASK;
1da177e4 3924
cd689985 3925 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
52400ba9
DH
3926 cmd == FUTEX_WAIT_BITSET ||
3927 cmd == FUTEX_WAIT_REQUEUE_PI)) {
ab51fbab
DB
3928 if (unlikely(should_fail_futex(!(op & FUTEX_PRIVATE_FLAG))))
3929 return -EFAULT;
bec2f7cb 3930 if (get_timespec64(&ts, utime))
1da177e4 3931 return -EFAULT;
bec2f7cb 3932 if (!timespec64_valid(&ts))
9741ef96 3933 return -EINVAL;
c19384b5 3934
bec2f7cb 3935 t = timespec64_to_ktime(ts);
34f01cc1 3936 if (cmd == FUTEX_WAIT)
5a7780e7 3937 t = ktime_add_safe(ktime_get(), t);
c19384b5 3938 tp = &t;
1da177e4
LT
3939 }
3940 /*
52400ba9 3941 * requeue parameter in 'utime' if cmd == FUTEX_*_REQUEUE_*.
f54f0986 3942 * number of waiters to wake in 'utime' if cmd == FUTEX_WAKE_OP.
1da177e4 3943 */
f54f0986 3944 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
ba9c22f2 3945 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
e2970f2f 3946 val2 = (u32) (unsigned long) utime;
1da177e4 3947
c19384b5 3948 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
1da177e4
LT
3949}
3950
04e7712f
AB
3951#ifdef CONFIG_COMPAT
3952/*
3953 * Fetch a robust-list pointer. Bit 0 signals PI futexes:
3954 */
3955static inline int
3956compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
3957 compat_uptr_t __user *head, unsigned int *pi)
3958{
3959 if (get_user(*uentry, head))
3960 return -EFAULT;
3961
3962 *entry = compat_ptr((*uentry) & ~1);
3963 *pi = (unsigned int)(*uentry) & 1;
3964
3965 return 0;
3966}
3967
3968static void __user *futex_uaddr(struct robust_list __user *entry,
3969 compat_long_t futex_offset)
3970{
3971 compat_uptr_t base = ptr_to_compat(entry);
3972 void __user *uaddr = compat_ptr(base + futex_offset);
3973
3974 return uaddr;
3975}
3976
3977/*
3978 * Walk curr->robust_list (very carefully, it's a userspace list!)
3979 * and mark any locks found there dead, and notify any waiters.
3980 *
3981 * We silently return on any sign of list-walking problem.
3982 */
ba31c1a4 3983static void compat_exit_robust_list(struct task_struct *curr)
04e7712f
AB
3984{
3985 struct compat_robust_list_head __user *head = curr->compat_robust_list;
3986 struct robust_list __user *entry, *next_entry, *pending;
3987 unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
3988 unsigned int uninitialized_var(next_pi);
3989 compat_uptr_t uentry, next_uentry, upending;
3990 compat_long_t futex_offset;
3991 int rc;
3992
3993 if (!futex_cmpxchg_enabled)
3994 return;
3995
3996 /*
3997 * Fetch the list head (which was registered earlier, via
3998 * sys_set_robust_list()):
3999 */
4000 if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &pi))
4001 return;
4002 /*
4003 * Fetch the relative futex offset:
4004 */
4005 if (get_user(futex_offset, &head->futex_offset))
4006 return;
4007 /*
4008 * Fetch any possibly pending lock-add first, and handle it
4009 * if it exists:
4010 */
4011 if (compat_fetch_robust_entry(&upending, &pending,
4012 &head->list_op_pending, &pip))
4013 return;
4014
4015 next_entry = NULL; /* avoid warning with gcc */
4016 while (entry != (struct robust_list __user *) &head->list) {
4017 /*
4018 * Fetch the next entry in the list before calling
4019 * handle_futex_death:
4020 */
4021 rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
4022 (compat_uptr_t __user *)&entry->next, &next_pi);
4023 /*
4024 * A pending lock might already be on the list, so
4025 * dont process it twice:
4026 */
4027 if (entry != pending) {
4028 void __user *uaddr = futex_uaddr(entry, futex_offset);
4029
ca16d5be
YT
4030 if (handle_futex_death(uaddr, curr, pi,
4031 HANDLE_DEATH_LIST))
04e7712f
AB
4032 return;
4033 }
4034 if (rc)
4035 return;
4036 uentry = next_uentry;
4037 entry = next_entry;
4038 pi = next_pi;
4039 /*
4040 * Avoid excessively long or circular lists:
4041 */
4042 if (!--limit)
4043 break;
4044
4045 cond_resched();
4046 }
4047 if (pending) {
4048 void __user *uaddr = futex_uaddr(pending, futex_offset);
4049
ca16d5be 4050 handle_futex_death(uaddr, curr, pip, HANDLE_DEATH_PENDING);
04e7712f
AB
4051 }
4052}
4053
4054COMPAT_SYSCALL_DEFINE2(set_robust_list,
4055 struct compat_robust_list_head __user *, head,
4056 compat_size_t, len)
4057{
4058 if (!futex_cmpxchg_enabled)
4059 return -ENOSYS;
4060
4061 if (unlikely(len != sizeof(*head)))
4062 return -EINVAL;
4063
4064 current->compat_robust_list = head;
4065
4066 return 0;
4067}
4068
4069COMPAT_SYSCALL_DEFINE3(get_robust_list, int, pid,
4070 compat_uptr_t __user *, head_ptr,
4071 compat_size_t __user *, len_ptr)
4072{
4073 struct compat_robust_list_head __user *head;
4074 unsigned long ret;
4075 struct task_struct *p;
4076
4077 if (!futex_cmpxchg_enabled)
4078 return -ENOSYS;
4079
4080 rcu_read_lock();
4081
4082 ret = -ESRCH;
4083 if (!pid)
4084 p = current;
4085 else {
4086 p = find_task_by_vpid(pid);
4087 if (!p)
4088 goto err_unlock;
4089 }
4090
4091 ret = -EPERM;
4092 if (!ptrace_may_access(p, PTRACE_MODE_READ_REALCREDS))
4093 goto err_unlock;
4094
4095 head = p->compat_robust_list;
4096 rcu_read_unlock();
4097
4098 if (put_user(sizeof(*head), len_ptr))
4099 return -EFAULT;
4100 return put_user(ptr_to_compat(head), head_ptr);
4101
4102err_unlock:
4103 rcu_read_unlock();
4104
4105 return ret;
4106}
bec2f7cb 4107#endif /* CONFIG_COMPAT */
04e7712f 4108
bec2f7cb 4109#ifdef CONFIG_COMPAT_32BIT_TIME
8dabe724 4110SYSCALL_DEFINE6(futex_time32, u32 __user *, uaddr, int, op, u32, val,
04e7712f
AB
4111 struct old_timespec32 __user *, utime, u32 __user *, uaddr2,
4112 u32, val3)
4113{
bec2f7cb 4114 struct timespec64 ts;
04e7712f
AB
4115 ktime_t t, *tp = NULL;
4116 int val2 = 0;
4117 int cmd = op & FUTEX_CMD_MASK;
4118
4119 if (utime && (cmd == FUTEX_WAIT || cmd == FUTEX_LOCK_PI ||
4120 cmd == FUTEX_WAIT_BITSET ||
4121 cmd == FUTEX_WAIT_REQUEUE_PI)) {
bec2f7cb 4122 if (get_old_timespec32(&ts, utime))
04e7712f 4123 return -EFAULT;
bec2f7cb 4124 if (!timespec64_valid(&ts))
04e7712f
AB
4125 return -EINVAL;
4126
bec2f7cb 4127 t = timespec64_to_ktime(ts);
04e7712f
AB
4128 if (cmd == FUTEX_WAIT)
4129 t = ktime_add_safe(ktime_get(), t);
4130 tp = &t;
4131 }
4132 if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
4133 cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
4134 val2 = (int) (unsigned long) utime;
4135
4136 return do_futex(uaddr, op, val, tp, uaddr2, val2, val3);
4137}
bec2f7cb 4138#endif /* CONFIG_COMPAT_32BIT_TIME */
04e7712f 4139
03b8c7b6 4140static void __init futex_detect_cmpxchg(void)
1da177e4 4141{
03b8c7b6 4142#ifndef CONFIG_HAVE_FUTEX_CMPXCHG
a0c1e907 4143 u32 curval;
03b8c7b6
HC
4144
4145 /*
4146 * This will fail and we want it. Some arch implementations do
4147 * runtime detection of the futex_atomic_cmpxchg_inatomic()
4148 * functionality. We want to know that before we call in any
4149 * of the complex code paths. Also we want to prevent
4150 * registration of robust lists in that case. NULL is
4151 * guaranteed to fault and we get -EFAULT on functional
4152 * implementation, the non-functional ones will return
4153 * -ENOSYS.
4154 */
4155 if (cmpxchg_futex_value_locked(&curval, NULL, 0, 0) == -EFAULT)
4156 futex_cmpxchg_enabled = 1;
4157#endif
4158}
4159
4160static int __init futex_init(void)
4161{
63b1a816 4162 unsigned int futex_shift;
a52b89eb
DB
4163 unsigned long i;
4164
4165#if CONFIG_BASE_SMALL
4166 futex_hashsize = 16;
4167#else
4168 futex_hashsize = roundup_pow_of_two(256 * num_possible_cpus());
4169#endif
4170
4171 futex_queues = alloc_large_system_hash("futex", sizeof(*futex_queues),
4172 futex_hashsize, 0,
4173 futex_hashsize < 256 ? HASH_SMALL : 0,
63b1a816
HC
4174 &futex_shift, NULL,
4175 futex_hashsize, futex_hashsize);
4176 futex_hashsize = 1UL << futex_shift;
03b8c7b6
HC
4177
4178 futex_detect_cmpxchg();
a0c1e907 4179
a52b89eb 4180 for (i = 0; i < futex_hashsize; i++) {
11d4616b 4181 atomic_set(&futex_queues[i].waiters, 0);
732375c6 4182 plist_head_init(&futex_queues[i].chain);
3e4ab747
TG
4183 spin_lock_init(&futex_queues[i].lock);
4184 }
4185
1da177e4
LT
4186 return 0;
4187}
25f71d1c 4188core_initcall(futex_init);