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