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