xref: /linux/kernel/futex/core.c (revision 1fc5a74b108fc90951890ec513ac81869f5eaff1)
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/debugfs.h>
36 #include <linux/fault-inject.h>
37 #include <linux/gfp.h>
38 #include <linux/jhash.h>
39 #include <linux/memblock.h>
40 #include <linux/mempolicy.h>
41 #include <linux/mmap_lock.h>
42 #include <linux/pagemap.h>
43 #include <linux/plist.h>
44 #include <linux/prctl.h>
45 #include <linux/rseq.h>
46 #include <linux/slab.h>
47 #include <linux/vmalloc.h>
48 #include <linux/kmemleak.h>
49 #include <linux/wait_bit.h>
50 
51 #include <vdso/futex.h>
52 
53 #include <asm/runtime-const.h>
54 
55 #include "futex.h"
56 #include "../locking/rtmutex_common.h"
57 
58 static u32 __futex_mask __ro_after_init;
59 static u32 __futex_shift __ro_after_init;
60 static struct futex_hash_bucket **__futex_queues __ro_after_init;
61 
futex_queues(void)62 static __always_inline struct futex_hash_bucket **futex_queues(void)
63 {
64 	return runtime_const_ptr(__futex_queues);
65 }
66 
67 struct futex_private_hash {
68 	int		state;
69 	unsigned int	hash_mask;
70 	struct rcu_head	rcu;
71 	void		*mm;
72 	bool		custom;
73 	struct futex_hash_bucket queues[];
74 };
75 
76 /*
77  * Fault injections for futexes.
78  */
79 #ifdef CONFIG_FAIL_FUTEX
80 
81 static struct {
82 	struct fault_attr attr;
83 
84 	bool ignore_private;
85 } fail_futex = {
86 	.attr = FAULT_ATTR_INITIALIZER,
87 	.ignore_private = false,
88 };
89 
setup_fail_futex(char * str)90 static int __init setup_fail_futex(char *str)
91 {
92 	return setup_fault_attr(&fail_futex.attr, str);
93 }
94 __setup("fail_futex=", setup_fail_futex);
95 
should_fail_futex(bool fshared)96 bool should_fail_futex(bool fshared)
97 {
98 	if (fail_futex.ignore_private && !fshared)
99 		return false;
100 
101 	return should_fail(&fail_futex.attr, 1);
102 }
103 
104 #ifdef CONFIG_FAULT_INJECTION_DEBUG_FS
105 
fail_futex_debugfs(void)106 static int __init fail_futex_debugfs(void)
107 {
108 	umode_t mode = S_IFREG | S_IRUSR | S_IWUSR;
109 	struct dentry *dir;
110 
111 	dir = fault_create_debugfs_attr("fail_futex", NULL,
112 					&fail_futex.attr);
113 	if (IS_ERR(dir))
114 		return PTR_ERR(dir);
115 
116 	debugfs_create_bool("ignore-private", mode, dir,
117 			    &fail_futex.ignore_private);
118 	return 0;
119 }
120 
121 late_initcall(fail_futex_debugfs);
122 
123 #endif /* CONFIG_FAULT_INJECTION_DEBUG_FS */
124 
125 #endif /* CONFIG_FAIL_FUTEX */
126 
127 static struct futex_hash_bucket *
128 __futex_hash(union futex_key *key, struct futex_private_hash *fph, struct futex_private_hash **fph_p);
129 
130 #ifdef CONFIG_FUTEX_PRIVATE_HASH
131 static bool futex_ref_get(struct futex_private_hash *fph);
132 static bool futex_ref_put(struct futex_private_hash *fph);
133 static bool futex_ref_is_dead(struct futex_private_hash *fph);
134 
135 enum { FR_PERCPU = 0, FR_ATOMIC };
136 
futex_private_hash_get(struct futex_private_hash * fph)137 static bool futex_private_hash_get(struct futex_private_hash *fph)
138 {
139 	return futex_ref_get(fph);
140 }
141 
futex_private_hash_put(struct futex_private_hash * fph)142 void futex_private_hash_put(struct futex_private_hash *fph)
143 {
144 	struct mm_struct *mm;
145 
146 	if (!fph)
147 		return;
148 
149 	mm = fph->mm;
150 	if (futex_ref_put(fph))
151 		wake_up_var(mm);
152 }
153 
154 static struct futex_hash_bucket *
__futex_hash_private(union futex_key * key,struct futex_private_hash * fph)155 __futex_hash_private(union futex_key *key, struct futex_private_hash *fph)
156 {
157 	u32 hash;
158 
159 	hash = jhash2((void *)&key->private.address, sizeof(key->private.address) / 4,
160 		      key->both.offset);
161 
162 	return &fph->queues[hash & fph->hash_mask];
163 }
164 
futex_rehash_private(struct futex_private_hash * old,struct futex_private_hash * new)165 static void futex_rehash_private(struct futex_private_hash *old,
166 				 struct futex_private_hash *new)
167 {
168 	struct futex_hash_bucket *hb_old, *hb_new;
169 	unsigned int slots = old->hash_mask + 1;
170 	unsigned int i;
171 
172 	for (i = 0; i < slots; i++) {
173 		struct futex_q *this, *tmp;
174 
175 		hb_old = &old->queues[i];
176 
177 		spin_lock(&hb_old->lock);
178 		plist_for_each_entry_safe(this, tmp, &hb_old->chain, list) {
179 			plist_del(&this->list, &hb_old->chain);
180 			futex_hb_waiters_dec(hb_old);
181 
182 			WARN_ON_ONCE(this->lock_ptr != &hb_old->lock);
183 
184 			hb_new = __futex_hash(&this->key, new, NULL);
185 			futex_hb_waiters_inc(hb_new);
186 			/*
187 			 * The new pointer isn't published yet but an already
188 			 * moved user can be unqueued due to timeout or signal.
189 			 */
190 			spin_lock_nested(&hb_new->lock, SINGLE_DEPTH_NESTING);
191 			plist_add(&this->list, &hb_new->chain);
192 			this->lock_ptr = &hb_new->lock;
193 			spin_unlock(&hb_new->lock);
194 		}
195 		spin_unlock(&hb_old->lock);
196 	}
197 }
198 
__futex_pivot_hash(struct mm_struct * mm,struct futex_private_hash * new)199 static bool __futex_pivot_hash(struct mm_struct *mm, struct futex_private_hash *new)
200 {
201 	struct futex_mm_phash *mmph = &mm->futex.phash;
202 	struct futex_private_hash *fph;
203 
204 	WARN_ON_ONCE(mmph->hash_new);
205 
206 	fph = rcu_dereference_protected(mmph->hash, lockdep_is_held(&mmph->lock));
207 	if (fph) {
208 		if (!futex_ref_is_dead(fph)) {
209 			mmph->hash_new = new;
210 			return false;
211 		}
212 
213 		futex_rehash_private(fph, new);
214 	}
215 	new->state = FR_PERCPU;
216 	scoped_guard(rcu) {
217 		mmph->batches = get_state_synchronize_rcu();
218 		rcu_assign_pointer(mmph->hash, new);
219 	}
220 	kvfree_rcu(fph, rcu);
221 	return true;
222 }
223 
futex_pivot_hash(struct mm_struct * mm)224 static void futex_pivot_hash(struct mm_struct *mm)
225 {
226 	scoped_guard(mutex, &mm->futex.phash.lock) {
227 		struct futex_private_hash *fph;
228 
229 		fph = mm->futex.phash.hash_new;
230 		if (fph) {
231 			mm->futex.phash.hash_new = NULL;
232 			__futex_pivot_hash(mm, fph);
233 		}
234 	}
235 }
236 
futex_private_hash(struct mm_struct * mm)237 struct futex_private_hash *futex_private_hash(struct mm_struct *mm)
238 {
239 	/*
240 	 * Ideally we don't loop. If there is a replacement in progress
241 	 * then a new private hash is already prepared and a reference can't be
242 	 * obtained once the last user dropped it's.
243 	 * In that case we block on mm_struct::futex_hash_lock and either have
244 	 * to perform the replacement or wait while someone else is doing the
245 	 * job. Eitherway, on the second iteration we acquire a reference on the
246 	 * new private hash or loop again because a new replacement has been
247 	 * requested.
248 	 */
249 again:
250 	scoped_guard(rcu) {
251 		struct futex_private_hash *fph;
252 
253 		fph = rcu_dereference(mm->futex.phash.hash);
254 		if (!fph)
255 			return NULL;
256 
257 		if (futex_private_hash_get(fph))
258 			return fph;
259 	}
260 	futex_pivot_hash(mm);
261 	goto again;
262 }
263 
futex_hash(union futex_key * key)264 struct futex_bucket_ref futex_hash(union futex_key *key)
265 {
266 again:
267 	scoped_guard(rcu) {
268 		struct futex_private_hash *fph = NULL;
269 		struct futex_hash_bucket *hb;
270 
271 		hb = __futex_hash(key, NULL, &fph);
272 
273 		if (!fph || futex_private_hash_get(fph))
274 			return (struct futex_bucket_ref){ .hb = hb, .fph = fph };
275 	}
276 	futex_pivot_hash(key->private.mm);
277 	goto again;
278 }
279 
280 #else /* !CONFIG_FUTEX_PRIVATE_HASH */
281 
futex_hash(union futex_key * key)282 struct futex_bucket_ref futex_hash(union futex_key *key)
283 {
284 	return (struct futex_bucket_ref){ .hb = __futex_hash(key, NULL, NULL), .fph = NULL };
285 }
286 
287 #endif /* CONFIG_FUTEX_PRIVATE_HASH */
288 
289 #ifdef CONFIG_FUTEX_MPOL
290 
__futex_key_to_node(struct mm_struct * mm,unsigned long addr)291 static int __futex_key_to_node(struct mm_struct *mm, unsigned long addr)
292 {
293 	struct vm_area_struct *vma = vma_lookup(mm, addr);
294 	struct mempolicy *mpol;
295 	int node = FUTEX_NO_NODE;
296 
297 	if (!vma)
298 		return FUTEX_NO_NODE;
299 
300 	mpol = READ_ONCE(vma->vm_policy);
301 	if (!mpol)
302 		return FUTEX_NO_NODE;
303 
304 	switch (mpol->mode) {
305 	case MPOL_PREFERRED:
306 		node = first_node(mpol->nodes);
307 		break;
308 	case MPOL_PREFERRED_MANY:
309 	case MPOL_BIND:
310 		if (mpol->home_node != NUMA_NO_NODE)
311 			node = mpol->home_node;
312 		break;
313 	default:
314 		break;
315 	}
316 
317 	return node;
318 }
319 
futex_key_to_node_opt(struct mm_struct * mm,unsigned long addr)320 static int futex_key_to_node_opt(struct mm_struct *mm, unsigned long addr)
321 {
322 	int seq, node;
323 
324 	guard(rcu)();
325 
326 	if (!mmap_lock_speculate_try_begin(mm, &seq))
327 		return -EBUSY;
328 
329 	node = __futex_key_to_node(mm, addr);
330 
331 	if (mmap_lock_speculate_retry(mm, seq))
332 		return -EAGAIN;
333 
334 	return node;
335 }
336 
futex_mpol(struct mm_struct * mm,unsigned long addr)337 static int futex_mpol(struct mm_struct *mm, unsigned long addr)
338 {
339 	int node;
340 
341 	node = futex_key_to_node_opt(mm, addr);
342 	if (node >= FUTEX_NO_NODE)
343 		return node;
344 
345 	guard(mmap_read_lock)(mm);
346 	return __futex_key_to_node(mm, addr);
347 }
348 
349 #else /* !CONFIG_FUTEX_MPOL */
350 
futex_mpol(struct mm_struct * mm,unsigned long addr)351 static int futex_mpol(struct mm_struct *mm, unsigned long addr)
352 {
353 	return FUTEX_NO_NODE;
354 }
355 
356 #endif /* CONFIG_FUTEX_MPOL */
357 
358 /**
359  * __futex_hash - Return the hash bucket
360  * @key:	Pointer to the futex key for which the hash is calculated
361  * @fph:	Pointer to private hash if known
362  * @fph_p:	Pointer to a private hash pointer; output for the private hash
363  *              used when set.
364  *
365  * We hash on the keys returned from get_futex_key (see below) and return the
366  * corresponding hash bucket.
367  * If the FUTEX is PROCESS_PRIVATE then a per-process hash bucket (from the
368  * private hash) is returned if existing. Otherwise a hash bucket from the
369  * global hash is returned.
370  */
371 static struct futex_hash_bucket *
__futex_hash(union futex_key * key,struct futex_private_hash * fph,struct futex_private_hash ** fph_p)372 __futex_hash(union futex_key *key, struct futex_private_hash *fph, struct futex_private_hash **fph_p)
373 {
374 	int node = key->both.node;
375 	u32 hash;
376 
377 #ifdef CONFIG_FUTEX_PRIVATE_HASH
378 	if (node == FUTEX_NO_NODE && futex_key_is_private(key)) {
379 		if (!fph)
380 			fph = rcu_dereference(key->private.mm->futex.phash.hash);
381 		if (fph && fph->hash_mask) {
382 			if (fph_p)
383 				*fph_p = fph;
384 			return __futex_hash_private(key, fph);
385 		}
386 	}
387 #endif
388 
389 	hash = jhash2((u32 *)key, offsetof(typeof(*key), both.offset) / sizeof(u32),
390 		      key->both.offset);
391 
392 	if (node == FUTEX_NO_NODE) {
393 		/*
394 		 * In case of !FLAGS_NUMA, use some unused hash bits to pick a
395 		 * node -- this ensures regular futexes are interleaved across
396 		 * the nodes and avoids having to allocate multiple
397 		 * hash-tables.
398 		 *
399 		 * NOTE: this isn't perfectly uniform, but it is fast and
400 		 * handles sparse node masks.
401 		 */
402 		node = runtime_const_shift_right_32(hash, __futex_shift) % nr_node_ids;
403 		if (!node_possible(node)) {
404 			node = find_next_bit_wrap(node_possible_map.bits, nr_node_ids, node);
405 		}
406 	}
407 
408 	return &futex_queues()[node][runtime_const_mask_32(hash, __futex_mask)];
409 }
410 
411 /**
412  * futex_setup_timer - set up the sleeping hrtimer.
413  * @time:	ptr to the given timeout value
414  * @timeout:	the hrtimer_sleeper structure to be set up
415  * @flags:	futex flags
416  * @range_ns:	optional range in ns
417  *
418  * Return: Initialized hrtimer_sleeper structure or NULL if no timeout
419  *	   value given
420  */
futex_setup_timer(ktime_t * time,struct hrtimer_sleeper * timeout,int flags,u64 range_ns)421 struct hrtimer_sleeper *futex_setup_timer(ktime_t *time, struct hrtimer_sleeper *timeout,
422 					  int flags, u64 range_ns)
423 {
424 	if (!time)
425 		return NULL;
426 
427 	hrtimer_setup_sleeper_on_stack(timeout,
428 				       (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC,
429 				       HRTIMER_MODE_ABS);
430 	/*
431 	 * If range_ns is 0, calling hrtimer_set_expires_range_ns() is
432 	 * effectively the same as calling hrtimer_set_expires().
433 	 */
434 	hrtimer_set_expires_range_ns(&timeout->timer, *time, range_ns);
435 
436 	return timeout;
437 }
438 
439 /*
440  * Generate a machine wide unique identifier for this inode.
441  *
442  * This relies on u64 not wrapping in the life-time of the machine; which with
443  * 1ns resolution means almost 585 years.
444  *
445  * This further relies on the fact that a well formed program will not unmap
446  * the file while it has a (shared) futex waiting on it. This mapping will have
447  * a file reference which pins the mount and inode.
448  *
449  * If for some reason an inode gets evicted and read back in again, it will get
450  * a new sequence number and will _NOT_ match, even though it is the exact same
451  * file.
452  *
453  * It is important that futex_match() will never have a false-positive, esp.
454  * for PI futexes that can mess up the state. The above argues that false-negatives
455  * are only possible for malformed programs.
456  */
get_inode_sequence_number(struct inode * inode)457 static u64 get_inode_sequence_number(struct inode *inode)
458 {
459 	static atomic64_t i_seq;
460 	u64 old;
461 
462 	/* Does the inode already have a sequence number? */
463 	old = atomic64_read(&inode->i_sequence);
464 	if (likely(old))
465 		return old;
466 
467 	for (;;) {
468 		u64 new = atomic64_inc_return(&i_seq);
469 		if (WARN_ON_ONCE(!new))
470 			continue;
471 
472 		old = 0;
473 		if (!atomic64_try_cmpxchg_relaxed(&inode->i_sequence, &old, new))
474 			return old;
475 		return new;
476 	}
477 }
478 
479 /**
480  * get_futex_key() - Get parameters which are the keys for a futex
481  * @uaddr:	virtual address of the futex
482  * @flags:	FLAGS_*
483  * @key:	address where result is stored.
484  * @rw:		mapping needs to be read/write (values: FUTEX_READ,
485  *              FUTEX_WRITE)
486  *
487  * Return: a negative error code or 0
488  *
489  * The key words are stored in @key on success.
490  *
491  * For shared mappings (when @fshared), the key is:
492  *
493  *   ( inode->i_sequence, page offset within mapping, offset_within_page )
494  *
495  * [ also see get_inode_sequence_number() ]
496  *
497  * For private mappings (or when !@fshared), the key is:
498  *
499  *   ( current->mm, address, 0 )
500  *
501  * This allows (cross process, where applicable) identification of the futex
502  * without keeping the page pinned for the duration of the FUTEX_WAIT.
503  *
504  * lock_page() might sleep, the caller should not hold a spinlock.
505  */
get_futex_key(u32 __user * uaddr,unsigned int flags,union futex_key * key,enum futex_access rw)506 int get_futex_key(u32 __user *uaddr, unsigned int flags, union futex_key *key,
507 		  enum futex_access rw)
508 {
509 	unsigned long address = (unsigned long)uaddr;
510 	struct mm_struct *mm = current->mm;
511 	struct page *page;
512 	struct folio *folio;
513 	struct address_space *mapping;
514 	int node, err, size, ro = 0;
515 	bool node_updated = false;
516 	bool fshared;
517 
518 	fshared = flags & FLAGS_SHARED;
519 	size = futex_size(flags);
520 	if (flags & FLAGS_NUMA)
521 		size *= 2;
522 
523 	/*
524 	 * The futex address must be "naturally" aligned.
525 	 */
526 	key->both.offset = address % PAGE_SIZE;
527 	if (unlikely((address & (size-1)) != 0))
528 		return -EINVAL;
529 	address -= key->both.offset;
530 
531 	if (unlikely(!access_ok(uaddr, size)))
532 		return -EFAULT;
533 
534 	if (unlikely(should_fail_futex(fshared)))
535 		return -EFAULT;
536 
537 	node = FUTEX_NO_NODE;
538 
539 	if (flags & FLAGS_NUMA) {
540 		u32 __user *naddr = (void *)uaddr + size / 2;
541 
542 		if (get_user_inline(node, naddr))
543 			return -EFAULT;
544 
545 		if ((node != FUTEX_NO_NODE) &&
546 		    ((unsigned int)node >= MAX_NUMNODES || !node_possible(node)))
547 			return -EINVAL;
548 	}
549 
550 	if (node == FUTEX_NO_NODE && (flags & FLAGS_MPOL)) {
551 		node = futex_mpol(mm, address);
552 		node_updated = true;
553 	}
554 
555 	if (flags & FLAGS_NUMA) {
556 		u32 __user *naddr = (void *)uaddr + size / 2;
557 
558 		if (node == FUTEX_NO_NODE) {
559 			node = numa_node_id();
560 			node_updated = true;
561 		}
562 		if (node_updated && put_user_inline(node, naddr))
563 			return -EFAULT;
564 	}
565 
566 	key->both.node = node;
567 
568 	/*
569 	 * PROCESS_PRIVATE futexes are fast.
570 	 * As the mm cannot disappear under us and the 'key' only needs
571 	 * virtual address, we dont even have to find the underlying vma.
572 	 * Note : We do have to check 'uaddr' is a valid user address,
573 	 *        but access_ok() should be faster than find_vma()
574 	 */
575 	if (!fshared) {
576 		/*
577 		 * On no-MMU, shared futexes are treated as private, therefore
578 		 * we must not include the current process in the key. Since
579 		 * there is only one address space, the address is a unique key
580 		 * on its own.
581 		 */
582 		if (IS_ENABLED(CONFIG_MMU))
583 			key->private.mm = mm;
584 		else
585 			key->private.mm = NULL;
586 
587 		key->private.address = address;
588 		return 0;
589 	}
590 
591 again:
592 	/* Ignore any VERIFY_READ mapping (futex common case) */
593 	if (unlikely(should_fail_futex(true)))
594 		return -EFAULT;
595 
596 	err = get_user_pages_fast(address, 1, FOLL_WRITE, &page);
597 	/*
598 	 * If write access is not required (eg. FUTEX_WAIT), try
599 	 * and get read-only access.
600 	 */
601 	if (err == -EFAULT && rw == FUTEX_READ) {
602 		err = get_user_pages_fast(address, 1, 0, &page);
603 		ro = 1;
604 	}
605 	if (err < 0)
606 		return err;
607 	else
608 		err = 0;
609 
610 	/*
611 	 * The treatment of mapping from this point on is critical. The folio
612 	 * lock protects many things but in this context the folio lock
613 	 * stabilizes mapping, prevents inode freeing in the shared
614 	 * file-backed region case and guards against movement to swap cache.
615 	 *
616 	 * Strictly speaking the folio lock is not needed in all cases being
617 	 * considered here and folio lock forces unnecessarily serialization.
618 	 * From this point on, mapping will be re-verified if necessary and
619 	 * folio lock will be acquired only if it is unavoidable
620 	 *
621 	 * Mapping checks require the folio so it is looked up now. For
622 	 * anonymous pages, it does not matter if the folio is split
623 	 * in the future as the key is based on the address. For
624 	 * filesystem-backed pages, the precise page is required as the
625 	 * index of the page determines the key.
626 	 */
627 	folio = page_folio(page);
628 	mapping = READ_ONCE(folio->mapping);
629 
630 	/*
631 	 * If folio->mapping is NULL, then it cannot be an anonymous
632 	 * page; but it might be the ZERO_PAGE or in the gate area or
633 	 * in a special mapping (all cases which we are happy to fail);
634 	 * or it may have been a good file page when get_user_pages_fast
635 	 * found it, but truncated or holepunched or subjected to
636 	 * invalidate_complete_page2 before we got the folio lock (also
637 	 * cases which we are happy to fail).  And we hold a reference,
638 	 * so refcount care in invalidate_inode_page's remove_mapping
639 	 * prevents drop_caches from setting mapping to NULL beneath us.
640 	 *
641 	 * The case we do have to guard against is when memory pressure made
642 	 * shmem_writepage move it from filecache to swapcache beneath us:
643 	 * an unlikely race, but we do need to retry for folio->mapping.
644 	 */
645 	if (unlikely(!mapping)) {
646 		int shmem_swizzled;
647 
648 		/*
649 		 * Folio lock is required to identify which special case above
650 		 * applies. If this is really a shmem page then the folio lock
651 		 * will prevent unexpected transitions.
652 		 */
653 		folio_lock(folio);
654 		shmem_swizzled = folio_test_swapcache(folio) || folio->mapping;
655 		folio_unlock(folio);
656 		folio_put(folio);
657 
658 		if (shmem_swizzled)
659 			goto again;
660 
661 		return -EFAULT;
662 	}
663 
664 	/*
665 	 * Private mappings are handled in a simple way.
666 	 *
667 	 * If the futex key is stored in anonymous memory, then the associated
668 	 * object is the mm which is implicitly pinned by the calling process.
669 	 *
670 	 * NOTE: When userspace waits on a MAP_SHARED mapping, even if
671 	 * it's a read-only handle, it's expected that futexes attach to
672 	 * the object not the particular process.
673 	 */
674 	if (folio_test_anon(folio)) {
675 		/*
676 		 * A RO anonymous page will never change and thus doesn't make
677 		 * sense for futex operations.
678 		 */
679 		if (unlikely(should_fail_futex(true)) || ro) {
680 			err = -EFAULT;
681 			goto out;
682 		}
683 
684 		key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
685 		key->private.mm = mm;
686 		key->private.address = address;
687 
688 	} else {
689 		struct inode *inode;
690 
691 		/*
692 		 * The associated futex object in this case is the inode and
693 		 * the folio->mapping must be traversed. Ordinarily this should
694 		 * be stabilised under folio lock but it's not strictly
695 		 * necessary in this case as we just want to pin the inode, not
696 		 * update i_pages or anything like that.
697 		 *
698 		 * The RCU read lock is taken as the inode is finally freed
699 		 * under RCU. If the mapping still matches expectations then the
700 		 * mapping->host can be safely accessed as being a valid inode.
701 		 */
702 		rcu_read_lock();
703 
704 		if (READ_ONCE(folio->mapping) != mapping) {
705 			rcu_read_unlock();
706 			folio_put(folio);
707 
708 			goto again;
709 		}
710 
711 		inode = READ_ONCE(mapping->host);
712 		if (!inode) {
713 			rcu_read_unlock();
714 			folio_put(folio);
715 
716 			goto again;
717 		}
718 
719 		key->both.offset |= FUT_OFF_INODE; /* inode-based key */
720 		key->shared.i_seq = get_inode_sequence_number(inode);
721 		key->shared.pgoff = page_pgoff(folio, page);
722 		rcu_read_unlock();
723 	}
724 
725 out:
726 	folio_put(folio);
727 	return err;
728 }
729 
730 /**
731  * fault_in_user_writeable() - Fault in user address and verify RW access
732  * @uaddr:	pointer to faulting user space address
733  *
734  * Slow path to fixup the fault we just took in the atomic write
735  * access to @uaddr.
736  *
737  * We have no generic implementation of a non-destructive write to the
738  * user address. We know that we faulted in the atomic pagefault
739  * disabled section so we can as well avoid the #PF overhead by
740  * calling get_user_pages() right away.
741  */
fault_in_user_writeable(u32 __user * uaddr)742 int fault_in_user_writeable(u32 __user *uaddr)
743 {
744 	struct mm_struct *mm = current->mm;
745 	int ret;
746 
747 	mmap_read_lock(mm);
748 	ret = fixup_user_fault(mm, (unsigned long)uaddr,
749 			       FAULT_FLAG_WRITE, NULL);
750 	mmap_read_unlock(mm);
751 
752 	return ret < 0 ? ret : 0;
753 }
754 
755 /**
756  * futex_top_waiter() - Return the highest priority waiter on a futex
757  * @hb:		the hash bucket the futex_q's reside in
758  * @key:	the futex key (to distinguish it from other futex futex_q's)
759  *
760  * Must be called with the hb lock held.
761  */
futex_top_waiter(struct futex_hash_bucket * hb,union futex_key * key)762 struct futex_q *futex_top_waiter(struct futex_hash_bucket *hb, union futex_key *key)
763 {
764 	struct futex_q *this;
765 
766 	plist_for_each_entry(this, &hb->chain, list) {
767 		if (futex_match(&this->key, key))
768 			return this;
769 	}
770 	return NULL;
771 }
772 
773 /**
774  * wait_for_owner_exiting - Block until the owner has exited
775  * @ret: owner's current futex lock status
776  * @exiting:	Pointer to the exiting task
777  *
778  * Caller must hold a refcount on @exiting.
779  */
wait_for_owner_exiting(int ret,struct task_struct * exiting)780 void wait_for_owner_exiting(int ret, struct task_struct *exiting)
781 {
782 	if (ret != -EBUSY) {
783 		WARN_ON_ONCE(exiting);
784 		return;
785 	}
786 
787 	if (WARN_ON_ONCE(ret == -EBUSY && !exiting))
788 		return;
789 
790 	mutex_lock(&exiting->futex.exit_mutex);
791 	/*
792 	 * No point in doing state checking here. If the waiter got here
793 	 * while the task was in exec()->exec_futex_release() then it can
794 	 * have any FUTEX_STATE_* value when the waiter has acquired the
795 	 * mutex. OK, if running, EXITING or DEAD if it reached exit()
796 	 * already. Highly unlikely and not a problem. Just one more round
797 	 * through the futex maze.
798 	 */
799 	mutex_unlock(&exiting->futex.exit_mutex);
800 
801 	put_task_struct(exiting);
802 }
803 
804 /**
805  * __futex_unqueue() - Remove the futex_q from its futex_hash_bucket
806  * @q:	The futex_q to unqueue
807  *
808  * The q->lock_ptr must not be NULL and must be held by the caller.
809  */
__futex_unqueue(struct futex_q * q)810 void __futex_unqueue(struct futex_q *q)
811 {
812 	struct futex_hash_bucket *hb;
813 
814 	if (WARN_ON_SMP(!q->lock_ptr) || WARN_ON(plist_node_empty(&q->list)))
815 		return;
816 	lockdep_assert_held(q->lock_ptr);
817 
818 	hb = container_of(q->lock_ptr, struct futex_hash_bucket, lock);
819 	plist_del(&q->list, &hb->chain);
820 	futex_hb_waiters_dec(hb);
821 }
822 
823 /* The key must be already stored in q->key. */
futex_q_lock(struct futex_q * q,struct futex_hash_bucket * hb)824 void futex_q_lock(struct futex_q *q, struct futex_hash_bucket *hb)
825 {
826 	/*
827 	 * Increment the counter before taking the lock so that
828 	 * a potential waker won't miss a to-be-slept task that is
829 	 * waiting for the spinlock. This is safe as all futex_q_lock()
830 	 * users end up calling futex_queue(). Similarly, for housekeeping,
831 	 * decrement the counter at futex_q_unlock() when some error has
832 	 * occurred and we don't end up adding the task to the list.
833 	 */
834 	futex_hb_waiters_inc(hb); /* implies smp_mb(); (A) */
835 
836 	q->lock_ptr = &hb->lock;
837 
838 	spin_lock(&hb->lock);
839 	__acquire(q->lock_ptr);
840 }
841 
futex_q_unlock(struct futex_hash_bucket * hb)842 void futex_q_unlock(struct futex_hash_bucket *hb)
843 {
844 	futex_hb_waiters_dec(hb);
845 	spin_unlock(&hb->lock);
846 }
847 
__futex_queue(struct futex_q * q,struct futex_hash_bucket * hb,struct task_struct * task)848 void __futex_queue(struct futex_q *q, struct futex_hash_bucket *hb,
849 		   struct task_struct *task)
850 {
851 	int prio;
852 
853 	/*
854 	 * The priority used to register this element is
855 	 * - either the real thread-priority for the real-time threads
856 	 * (i.e. threads with a priority lower than MAX_RT_PRIO)
857 	 * - or MAX_RT_PRIO for non-RT threads.
858 	 * Thus, all RT-threads are woken first in priority order, and
859 	 * the others are woken last, in FIFO order.
860 	 */
861 	prio = min(current->normal_prio, MAX_RT_PRIO);
862 
863 	plist_node_init(&q->list, prio);
864 	plist_add(&q->list, &hb->chain);
865 	q->task = task;
866 }
867 
868 /**
869  * futex_unqueue() - Remove the futex_q from its futex_hash_bucket
870  * @q:	The futex_q to unqueue
871  *
872  * The q->lock_ptr must not be held by the caller. A call to futex_unqueue() must
873  * be paired with exactly one earlier call to futex_queue().
874  *
875  * Return:
876  *  - 1 - if the futex_q was still queued (and we removed unqueued it);
877  *  - 0 - if the futex_q was already removed by the waking thread
878  */
futex_unqueue(struct futex_q * q)879 int futex_unqueue(struct futex_q *q)
880 {
881 	spinlock_t *lock_ptr;
882 	int ret = 0;
883 
884 	/* RCU so lock_ptr is not going away during locking. */
885 	guard(rcu)();
886 	/* In the common case we don't take the spinlock, which is nice. */
887 retry:
888 	/*
889 	 * q->lock_ptr can change between this read and the following spin_lock.
890 	 * Use READ_ONCE to forbid the compiler from reloading q->lock_ptr and
891 	 * optimizing lock_ptr out of the logic below.
892 	 */
893 	lock_ptr = READ_ONCE(q->lock_ptr);
894 	if (lock_ptr != NULL) {
895 		spin_lock(lock_ptr);
896 		/*
897 		 * q->lock_ptr can change between reading it and
898 		 * spin_lock(), causing us to take the wrong lock.  This
899 		 * corrects the race condition.
900 		 *
901 		 * Reasoning goes like this: if we have the wrong lock,
902 		 * q->lock_ptr must have changed (maybe several times)
903 		 * between reading it and the spin_lock().  It can
904 		 * change again after the spin_lock() but only if it was
905 		 * already changed before the spin_lock().  It cannot,
906 		 * however, change back to the original value.  Therefore
907 		 * we can detect whether we acquired the correct lock.
908 		 */
909 		if (unlikely(lock_ptr != q->lock_ptr)) {
910 			spin_unlock(lock_ptr);
911 			goto retry;
912 		}
913 		__futex_unqueue(q);
914 
915 		BUG_ON(q->pi_state);
916 
917 		spin_unlock(lock_ptr);
918 		ret = 1;
919 	}
920 
921 	return ret;
922 }
923 
futex_q_lockptr_lock(struct futex_q * q)924 void futex_q_lockptr_lock(struct futex_q *q)
925 {
926 	spinlock_t *lock_ptr;
927 
928 	/*
929 	 * See futex_unqueue() why lock_ptr can change.
930 	 */
931 	guard(rcu)();
932 retry:
933 	lock_ptr = READ_ONCE(q->lock_ptr);
934 	spin_lock(lock_ptr);
935 
936 	if (unlikely(lock_ptr != q->lock_ptr)) {
937 		spin_unlock(lock_ptr);
938 		goto retry;
939 	}
940 }
941 
942 /*
943  * PI futexes can not be requeued and must remove themselves from the hash
944  * bucket. The hash bucket lock (i.e. lock_ptr) is held.
945  */
futex_unqueue_pi(struct futex_q * q)946 void futex_unqueue_pi(struct futex_q *q)
947 {
948 	/*
949 	 * If the lock was not acquired (due to timeout or signal) then the
950 	 * rt_waiter is removed before futex_q is. If this is observed by
951 	 * an unlocker after dropping the rtmutex wait lock and before
952 	 * acquiring the hash bucket lock, then the unlocker dequeues the
953 	 * futex_q from the hash bucket list to guarantee consistent state
954 	 * vs. userspace. Therefore the dequeue here must be conditional.
955 	 */
956 	if (!plist_node_empty(&q->list))
957 		__futex_unqueue(q);
958 
959 	BUG_ON(!q->pi_state);
960 	put_pi_state(q->pi_state);
961 	q->pi_state = NULL;
962 }
963 
964 /* Constants for the pending_op argument of handle_futex_death */
965 #define HANDLE_DEATH_PENDING	true
966 #define HANDLE_DEATH_LIST	false
967 
968 /*
969  * Process a futex-list entry, check whether it's owned by the
970  * dying task, and do notification if so:
971  */
handle_futex_death(u32 __user * uaddr,struct task_struct * curr,unsigned int mod,bool pending_op)972 static int handle_futex_death(u32 __user *uaddr, struct task_struct *curr,
973 			      unsigned int mod, bool pending_op)
974 {
975 	bool pi = !!(mod & FUTEX_ROBUST_MOD_PI);
976 	u32 uval, nval, mval;
977 	pid_t owner;
978 	int err;
979 
980 	/* Futex address must be 32bit aligned */
981 	if ((((unsigned long)uaddr) % sizeof(*uaddr)) != 0)
982 		return -1;
983 
984 retry:
985 	if (get_user(uval, uaddr))
986 		return -1;
987 
988 	/*
989 	 * Special case for regular (non PI) futexes. Ordinarily, we do
990 	 * not perform any processing here unless the current thread was
991 	 * the owner of the futex (by the TID check below).
992 	 *
993 	 * However, the unlock path has three race scenarios:
994 	 *
995 	 * 1. The unlock path releases the user space futex value and
996 	 *    before it can execute the futex() syscall to wake up
997 	 *    waiters it is killed.
998 	 *
999 	 * 2. A woken up waiter is killed before it can acquire the
1000 	 *    futex in user space.
1001 	 *
1002 	 * 3. A woken up waiter is killed in user space after another
1003 	 *    thread has acquired the futex, but before it can set
1004 	 *    FUTEX_WAITERS.
1005 	 *
1006 	 * Note that, if userspace uses the FUTEX_ROBUST_UNLOCK flag, we
1007 	 * will not see case 1 here.
1008 	 *
1009 	 * In the second and third case, the wake up notification could
1010 	 * be generated from any of:
1011 	 *
1012 	 *    i.   An ordinary futex wakeup after unlock (with or
1013 	 *         without FUTEX_ROBUST_UNLOCK)
1014 	 *    ii.  A robust wakeup from another thread's death
1015 	 *    iii. A previous round through this special case
1016 	 *
1017 	 * As a result, the futex world will be in one of four states:
1018 	 *
1019 	 *    A. The futex word is 0 (unlocked)
1020 	 *    B. The futex word is owned by another thread
1021 	 *       (FUTEX_WAITERS is not set)
1022 	 *    C. The futex word is owned by another thread
1023 	 *       (FUTEX_WAITERS set)
1024 	 *    D. The futex's owner died and OWNER_DIED is set
1025 	 *       (the owner part of the word is 0)
1026 	 *
1027 	 * The key issue is that the kernel usually (at least from
1028 	 * sources ii. and iii. or when so requested by userspace from
1029 	 * source i.) only ever wakes *one* waiter at a time. If this
1030 	 * waiter dies before acquiring the futex (or setting the
1031 	 * FUTEX_WAITERS bit), the kernel *must* still wake the next
1032 	 * waiter down the line to uphold the futex invariants and
1033 	 * avoid lost wakeups. Note we do not need to handle state C,
1034 	 * as it does not matter to us whether *we* successfully set
1035 	 * the bit or a third thread did so in the meantime.
1036 	 *
1037 	 * Therefore, in these cases we must issue an additional
1038 	 * futex_wake(). Note however that we *must not* set OWNER_DIED
1039 	 * here. Our thread is *not* the owner of the futex.
1040 	 *
1041 	 * Thus to summarize, the conditions for needing the additional
1042 	 * futex_wake() are:
1043 	 *
1044 	 *	1) @pending_op == true (the thread has not finished the
1045 	 *	   mutex operation)
1046 	 *	2) The futex word is in one of the states A, B or D
1047 	 *	3) Regular futex: @pi == false
1048 	 *
1049 	 * Note in particular that in all of the states A-D the owner
1050 	 * portion of the futex word differs from our thread's TID
1051 	 * (unless the actual owner has the same TID in another PID
1052 	 * namespace, but we cannot currently distinguish that
1053 	 * scenario), so this can be a special-case wakeup in the bail
1054 	 * path of the ordinary TID check.
1055 	 */
1056 	owner = uval & FUTEX_TID_MASK;
1057 
1058 	if (owner != task_pid_vnr(curr)) {
1059 		if (pending_op && !pi && (!owner || !(uval & FUTEX_WAITERS))) {
1060 			futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, NULL, 1,
1061 				   FUTEX_BITSET_MATCH_ANY);
1062 		}
1063 		return 0;
1064 	}
1065 
1066 	/*
1067 	 * Ok, this dying thread is truly holding a futex
1068 	 * of interest. Set the OWNER_DIED bit atomically
1069 	 * via cmpxchg, and if the value had FUTEX_WAITERS
1070 	 * set, wake up a waiter (if any). (We have to do a
1071 	 * futex_wake() even if OWNER_DIED is already set -
1072 	 * to handle the rare but possible case of recursive
1073 	 * thread-death.) The rest of the cleanup is done in
1074 	 * userspace.
1075 	 */
1076 	mval = (uval & FUTEX_WAITERS) | FUTEX_OWNER_DIED;
1077 
1078 	/*
1079 	 * We are not holding a lock here, but we want to have
1080 	 * the pagefault_disable/enable() protection because
1081 	 * we want to handle the fault gracefully. If the
1082 	 * access fails we try to fault in the futex with R/W
1083 	 * verification via get_user_pages. get_user() above
1084 	 * does not guarantee R/W access. If that fails we
1085 	 * give up and leave the futex locked.
1086 	 */
1087 	if ((err = futex_cmpxchg_value_locked(&nval, uaddr, uval, mval))) {
1088 		switch (err) {
1089 		case -EFAULT:
1090 			if (fault_in_user_writeable(uaddr))
1091 				return -1;
1092 			goto retry;
1093 
1094 		case -EAGAIN:
1095 			cond_resched();
1096 			goto retry;
1097 
1098 		default:
1099 			WARN_ON_ONCE(1);
1100 			return err;
1101 		}
1102 	}
1103 
1104 	if (nval != uval)
1105 		goto retry;
1106 
1107 	/*
1108 	 * Wake robust non-PI futexes here. The wakeup of
1109 	 * PI futexes happens in exit_pi_state():
1110 	 */
1111 	if (!pi && (uval & FUTEX_WAITERS)) {
1112 		futex_wake(uaddr, FLAGS_SIZE_32 | FLAGS_SHARED, NULL, 1,
1113 			   FUTEX_BITSET_MATCH_ANY);
1114 	}
1115 
1116 	return 0;
1117 }
1118 
1119 /*
1120  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
1121  */
fetch_robust_entry(struct robust_list __user ** entry,struct robust_list __user * __user * head,unsigned int * mod)1122 static inline int fetch_robust_entry(struct robust_list __user **entry,
1123 				     struct robust_list __user * __user *head,
1124 				     unsigned int *mod)
1125 {
1126 	unsigned long uentry;
1127 
1128 	if (get_user(uentry, (unsigned long __user *)head))
1129 		return -EFAULT;
1130 
1131 	*entry = (void __user *)(uentry & ~FUTEX_ROBUST_MOD_MASK);
1132 	*mod = uentry & FUTEX_ROBUST_MOD_MASK;
1133 
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Walk curr->futex.robust_list (very carefully, it's a userspace list!)
1139  * and mark any locks found there dead, and notify any waiters.
1140  *
1141  * We silently return on any sign of list-walking problem.
1142  */
exit_robust_list(struct task_struct * curr)1143 static void exit_robust_list(struct task_struct *curr)
1144 {
1145 	struct robust_list_head __user *head = curr->futex.robust_list;
1146 	unsigned int limit = ROBUST_LIST_LIMIT, cur_mod, next_mod, pend_mod;
1147 	struct robust_list __user *entry, *next_entry, *pending;
1148 	unsigned long futex_offset;
1149 	int rc;
1150 
1151 	/*
1152 	 * Fetch the list head (which was registered earlier, via
1153 	 * sys_set_robust_list()):
1154 	 */
1155 	if (fetch_robust_entry(&entry, &head->list.next, &cur_mod))
1156 		return;
1157 	/*
1158 	 * Fetch the relative futex offset:
1159 	 */
1160 	if (get_user(futex_offset, &head->futex_offset))
1161 		return;
1162 	/*
1163 	 * Fetch any possibly pending lock-add first, and handle it
1164 	 * if it exists:
1165 	 */
1166 	if (fetch_robust_entry(&pending, &head->list_op_pending, &pend_mod))
1167 		return;
1168 
1169 	next_entry = NULL;	/* avoid warning with gcc */
1170 	while (entry != &head->list) {
1171 		/*
1172 		 * Fetch the next entry in the list before calling
1173 		 * handle_futex_death:
1174 		 */
1175 		rc = fetch_robust_entry(&next_entry, &entry->next, &next_mod);
1176 		/*
1177 		 * A pending lock might already be on the list, so
1178 		 * don't process it twice:
1179 		 */
1180 		if (entry != pending) {
1181 			if (handle_futex_death((void __user *)entry + futex_offset,
1182 						curr, cur_mod, HANDLE_DEATH_LIST))
1183 				return;
1184 		}
1185 		if (rc)
1186 			return;
1187 		entry = next_entry;
1188 		cur_mod = next_mod;
1189 		/*
1190 		 * Avoid excessively long or circular lists:
1191 		 */
1192 		if (!--limit)
1193 			break;
1194 
1195 		cond_resched();
1196 	}
1197 
1198 	if (pending) {
1199 		handle_futex_death((void __user *)pending + futex_offset,
1200 				   curr, pend_mod, HANDLE_DEATH_PENDING);
1201 	}
1202 }
1203 
robust_list_clear_pending(unsigned long __user * pop)1204 static bool robust_list_clear_pending(unsigned long __user *pop)
1205 {
1206 	struct robust_list_head __user *head = current->futex.robust_list;
1207 
1208 	if (!put_user(0UL, pop))
1209 		return true;
1210 
1211 	/*
1212 	 * Just give up. The robust list head is usually part of TLS, so the
1213 	 * chance that this gets resolved is close to zero.
1214 	 *
1215 	 * If @pop_addr is the robust_list_head::list_op_pending pointer then
1216 	 * clear the robust list head pointer to prevent further damage when the
1217 	 * task exits.  Better a few stale futexes than corrupted memory. But
1218 	 * that's mostly an academic exercise.
1219 	 */
1220 	if (pop == (unsigned long __user *)&head->list_op_pending)
1221 		current->futex.robust_list = NULL;
1222 	return false;
1223 }
1224 
1225 #ifdef CONFIG_COMPAT
futex_uaddr(struct robust_list __user * entry,compat_long_t futex_offset)1226 static void __user *futex_uaddr(struct robust_list __user *entry,
1227 				compat_long_t futex_offset)
1228 {
1229 	compat_uptr_t base = ptr_to_compat(entry);
1230 	void __user *uaddr = compat_ptr(base + futex_offset);
1231 
1232 	return uaddr;
1233 }
1234 
1235 /*
1236  * Fetch a robust-list pointer. Bit 0 signals PI futexes:
1237  */
1238 static inline int
compat_fetch_robust_entry(compat_uptr_t * uentry,struct robust_list __user ** entry,compat_uptr_t __user * head,unsigned int * pflags)1239 compat_fetch_robust_entry(compat_uptr_t *uentry, struct robust_list __user **entry,
1240 		   compat_uptr_t __user *head, unsigned int *pflags)
1241 {
1242 	if (get_user(*uentry, head))
1243 		return -EFAULT;
1244 
1245 	*entry = compat_ptr((*uentry) & ~FUTEX_ROBUST_MOD_MASK);
1246 	*pflags = (unsigned int)(*uentry) & FUTEX_ROBUST_MOD_MASK;
1247 
1248 	return 0;
1249 }
1250 
1251 /*
1252  * Walk curr->futex.robust_list (very carefully, it's a userspace list!)
1253  * and mark any locks found there dead, and notify any waiters.
1254  *
1255  * We silently return on any sign of list-walking problem.
1256  */
compat_exit_robust_list(struct task_struct * curr)1257 static void compat_exit_robust_list(struct task_struct *curr)
1258 {
1259 	struct compat_robust_list_head __user *head = current->futex.compat_robust_list;
1260 	unsigned int limit = ROBUST_LIST_LIMIT, cur_mod, next_mod, pend_mod;
1261 	struct robust_list __user *entry, *next_entry, *pending;
1262 	compat_uptr_t uentry, next_uentry, upending;
1263 	compat_long_t futex_offset;
1264 	int rc;
1265 
1266 	/*
1267 	 * Fetch the list head (which was registered earlier, via
1268 	 * sys_set_robust_list()):
1269 	 */
1270 	if (compat_fetch_robust_entry(&uentry, &entry, &head->list.next, &cur_mod))
1271 		return;
1272 	/*
1273 	 * Fetch the relative futex offset:
1274 	 */
1275 	if (get_user(futex_offset, &head->futex_offset))
1276 		return;
1277 	/*
1278 	 * Fetch any possibly pending lock-add first, and handle it
1279 	 * if it exists:
1280 	 */
1281 	if (compat_fetch_robust_entry(&upending, &pending, &head->list_op_pending, &pend_mod))
1282 		return;
1283 
1284 	next_entry = NULL;	/* avoid warning with gcc */
1285 	while (entry != (struct robust_list __user *) &head->list) {
1286 		/*
1287 		 * Fetch the next entry in the list before calling
1288 		 * handle_futex_death:
1289 		 */
1290 		rc = compat_fetch_robust_entry(&next_uentry, &next_entry,
1291 			(compat_uptr_t __user *)&entry->next, &next_mod);
1292 		/*
1293 		 * A pending lock might already be on the list, so
1294 		 * dont process it twice:
1295 		 */
1296 		if (entry != pending) {
1297 			void __user *uaddr = futex_uaddr(entry, futex_offset);
1298 
1299 			if (handle_futex_death(uaddr, curr, cur_mod, HANDLE_DEATH_LIST))
1300 				return;
1301 		}
1302 		if (rc)
1303 			return;
1304 		uentry = next_uentry;
1305 		entry = next_entry;
1306 		cur_mod = next_mod;
1307 		/*
1308 		 * Avoid excessively long or circular lists:
1309 		 */
1310 		if (!--limit)
1311 			break;
1312 
1313 		cond_resched();
1314 	}
1315 	if (pending) {
1316 		void __user *uaddr = futex_uaddr(pending, futex_offset);
1317 
1318 		handle_futex_death(uaddr, curr, pend_mod, HANDLE_DEATH_PENDING);
1319 	}
1320 }
1321 
compat_robust_list_clear_pending(u32 __user * pop)1322 static bool compat_robust_list_clear_pending(u32 __user *pop)
1323 {
1324 	struct compat_robust_list_head __user *head = current->futex.compat_robust_list;
1325 
1326 	if (!put_user(0U, pop))
1327 		return true;
1328 
1329 	/* See comment in robust_list_clear_pending(). */
1330 	if (pop == &head->list_op_pending)
1331 		current->futex.compat_robust_list = NULL;
1332 	return false;
1333 }
1334 #else
compat_robust_list_clear_pending(u32 __user * pop_addr)1335 static bool compat_robust_list_clear_pending(u32 __user *pop_addr) { return false; }
1336 #endif
1337 
1338 #ifdef CONFIG_FUTEX_PI
1339 
1340 /*
1341  * This task is holding PI mutexes at exit time => bad.
1342  * Kernel cleans up PI-state, but userspace is likely hosed.
1343  * (Robust-futex cleanup is separate and might save the day for userspace.)
1344  */
exit_pi_state_list(struct task_struct * curr)1345 static void exit_pi_state_list(struct task_struct *curr)
1346 {
1347 	struct list_head *next, *head = &curr->futex.pi_state_list;
1348 	struct futex_pi_state *pi_state;
1349 	union futex_key key = FUTEX_KEY_INIT;
1350 
1351 	/*
1352 	 * The mutex mm_struct::futex_hash_lock might be acquired.
1353 	 */
1354 	might_sleep();
1355 	/*
1356 	 * Ensure the hash remains stable (no resize) during the while loop
1357 	 * below. The hb pointer is acquired under the pi_lock so we can't block
1358 	 * on the mutex.
1359 	 */
1360 	WARN_ON(curr != current);
1361 	guard(private_hash)(current->mm);
1362 	/*
1363 	 * We are a ZOMBIE and nobody can enqueue itself on
1364 	 * pi_state_list anymore, but we have to be careful
1365 	 * versus waiters unqueueing themselves:
1366 	 */
1367 	raw_spin_lock_irq(&curr->pi_lock);
1368 	while (!list_empty(head)) {
1369 		next = head->next;
1370 		pi_state = list_entry(next, struct futex_pi_state, list);
1371 		key = pi_state->key;
1372 		if (1) {
1373 			CLASS(hbr, hbr)(&key);
1374 			auto hb = hbr.hb;
1375 
1376 			/*
1377 			 * We can race against put_pi_state() removing itself from the
1378 			 * list (a waiter going away). put_pi_state() will first
1379 			 * decrement the reference count and then modify the list, so
1380 			 * its possible to see the list entry but fail this reference
1381 			 * acquire.
1382 			 *
1383 			 * In that case; drop the locks to let put_pi_state() make
1384 			 * progress and retry the loop.
1385 			 */
1386 			if (!refcount_inc_not_zero(&pi_state->refcount)) {
1387 				raw_spin_unlock_irq(&curr->pi_lock);
1388 				cpu_relax();
1389 				raw_spin_lock_irq(&curr->pi_lock);
1390 				continue;
1391 			}
1392 			raw_spin_unlock_irq(&curr->pi_lock);
1393 
1394 			spin_lock(&hb->lock);
1395 			raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock);
1396 			raw_spin_lock(&curr->pi_lock);
1397 			/*
1398 			 * We dropped the pi-lock, so re-check whether this
1399 			 * task still owns the PI-state:
1400 			 */
1401 			if (head->next != next) {
1402 				/* retain curr->pi_lock for the loop invariant */
1403 				raw_spin_unlock(&pi_state->pi_mutex.wait_lock);
1404 				spin_unlock(&hb->lock);
1405 				put_pi_state(pi_state);
1406 				continue;
1407 			}
1408 
1409 			WARN_ON(pi_state->owner != curr);
1410 			WARN_ON(list_empty(&pi_state->list));
1411 			list_del_init(&pi_state->list);
1412 			pi_state->owner = NULL;
1413 
1414 			raw_spin_unlock(&curr->pi_lock);
1415 			raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock);
1416 			spin_unlock(&hb->lock);
1417 		}
1418 
1419 		rt_mutex_futex_unlock(&pi_state->pi_mutex);
1420 		put_pi_state(pi_state);
1421 
1422 		raw_spin_lock_irq(&curr->pi_lock);
1423 	}
1424 	raw_spin_unlock_irq(&curr->pi_lock);
1425 }
1426 #else
exit_pi_state_list(struct task_struct * curr)1427 static inline void exit_pi_state_list(struct task_struct *curr) { }
1428 #endif
1429 
futex_robust_list_clear_pending(void __user * pop,unsigned int flags)1430 bool futex_robust_list_clear_pending(void __user *pop, unsigned int flags)
1431 {
1432 	bool size32bit = !!(flags & FLAGS_ROBUST_LIST32);
1433 
1434 	if (!IS_ENABLED(CONFIG_64BIT) && !size32bit)
1435 		return false;
1436 
1437 	if (IS_ENABLED(CONFIG_64BIT) && size32bit)
1438 		return compat_robust_list_clear_pending(pop);
1439 
1440 	return robust_list_clear_pending(pop);
1441 }
1442 
1443 #ifdef CONFIG_FUTEX_ROBUST_UNLOCK
__futex_fixup_robust_unlock(struct pt_regs * regs,struct futex_unlock_cs_range * csr)1444 void __futex_fixup_robust_unlock(struct pt_regs *regs, struct futex_unlock_cs_range *csr)
1445 {
1446 	/*
1447 	 * arch_futex_robust_unlock_get_pop() returns the list pending op pointer from
1448 	 * @regs if the try_cmpxchg() succeeded.
1449 	 */
1450 	void __user *pop = arch_futex_robust_unlock_get_pop(regs);
1451 
1452 	if (!pop)
1453 		return;
1454 
1455 	futex_robust_list_clear_pending(pop, csr->pop_size32 ? FLAGS_ROBUST_LIST32 : 0);
1456 }
1457 #endif /* CONFIG_FUTEX_ROBUST_UNLOCK */
1458 
futex_cleanup(struct task_struct * tsk)1459 static void futex_cleanup(struct task_struct *tsk)
1460 {
1461 	if (unlikely(tsk->futex.robust_list)) {
1462 		exit_robust_list(tsk);
1463 		tsk->futex.robust_list = NULL;
1464 	}
1465 
1466 #ifdef CONFIG_COMPAT
1467 	if (unlikely(tsk->futex.compat_robust_list)) {
1468 		compat_exit_robust_list(tsk);
1469 		tsk->futex.compat_robust_list = NULL;
1470 	}
1471 #endif
1472 
1473 	if (unlikely(!list_empty(&tsk->futex.pi_state_list)))
1474 		exit_pi_state_list(tsk);
1475 }
1476 
1477 /**
1478  * futex_exit_recursive - Set the tasks futex state to FUTEX_STATE_DEAD
1479  * @tsk:	task to set the state on
1480  *
1481  * Set the futex exit state of the task lockless. The futex waiter code
1482  * observes that state when a task is exiting and loops until the task has
1483  * actually finished the futex cleanup. The worst case for this is that the
1484  * waiter runs through the wait loop until the state becomes visible.
1485  *
1486  * This is called from the recursive fault handling path in make_task_dead().
1487  *
1488  * This is best effort. Either the futex exit code has run already or
1489  * not. If the OWNER_DIED bit has been set on the futex then the waiter can
1490  * take it over. If not, the problem is pushed back to user space. If the
1491  * futex exit code did not run yet, then an already queued waiter might
1492  * block forever, but there is nothing which can be done about that.
1493  */
futex_exit_recursive(struct task_struct * tsk)1494 void futex_exit_recursive(struct task_struct *tsk)
1495 {
1496 	/* If the state is FUTEX_STATE_EXITING then futex_exit_mutex is held */
1497 	if (tsk->futex.state == FUTEX_STATE_EXITING) {
1498 		__assume_ctx_lock(&tsk->futex.exit_mutex);
1499 		mutex_unlock(&tsk->futex.exit_mutex);
1500 	}
1501 	tsk->futex.state = FUTEX_STATE_DEAD;
1502 }
1503 
futex_cleanup_begin(struct task_struct * tsk)1504 static void futex_cleanup_begin(struct task_struct *tsk)
1505 	__acquires(&tsk->futex.exit_mutex)
1506 {
1507 	/*
1508 	 * Prevent various race issues against a concurrent incoming waiter
1509 	 * including live locks by forcing the waiter to block on
1510 	 * tsk->futex.exit_mutex when it observes FUTEX_STATE_EXITING in
1511 	 * attach_to_pi_owner().
1512 	 */
1513 	mutex_lock(&tsk->futex.exit_mutex);
1514 
1515 	/*
1516 	 * Switch the state to FUTEX_STATE_EXITING under tsk->pi_lock.
1517 	 *
1518 	 * This ensures that all subsequent checks of tsk->futex_state in
1519 	 * attach_to_pi_owner() must observe FUTEX_STATE_EXITING with
1520 	 * tsk->pi_lock held.
1521 	 *
1522 	 * It guarantees also that a pi_state which was queued right before
1523 	 * the state change under tsk->pi_lock by a concurrent waiter must
1524 	 * be observed in exit_pi_state_list().
1525 	 */
1526 	raw_spin_lock_irq(&tsk->pi_lock);
1527 	tsk->futex.state = FUTEX_STATE_EXITING;
1528 	raw_spin_unlock_irq(&tsk->pi_lock);
1529 }
1530 
futex_cleanup_end(struct task_struct * tsk)1531 static void futex_cleanup_end(struct task_struct *tsk)
1532 	__releases(&tsk->futex.exit_mutex)
1533 {
1534 	scoped_guard(raw_spinlock_irq, &tsk->pi_lock)
1535 		tsk->futex.state = FUTEX_STATE_DEAD;
1536 
1537 	/*
1538 	 * Drop the exit protection. This unblocks waiters which observed
1539 	 * FUTEX_STATE_EXITING to reevaluate the state.
1540 	 */
1541 	mutex_unlock(&tsk->futex.exit_mutex);
1542 }
1543 
1544 /*
1545  * Invoked from mm_exit_exec_release() to cleanup the robust lists and pi state
1546  * of the outgoing task.
1547  *
1548  * exec() makes it interesting for futexes because the TID of the task stays the
1549  * same, but from a futex perspective the task has to be treated like an exiting
1550  * task. This is especially important for the sanity check for private futexes
1551  * in attach_to_pi_owner() which compares the owner's mm with the waiter's mm.
1552  *
1553  * That check would give the wrong answer if futex_cleanup_end() would
1554  * set the state to FUTEX_STATE_OK as long as the task still has the old
1555  * mm.
1556  *
1557  * After the task has switched to the new mm it sets it to
1558  * FUTEX_STATE_OK again in futex_exec_done().
1559  */
futex_exit_exec_release(struct task_struct * tsk)1560 void futex_exit_exec_release(struct task_struct *tsk)
1561 {
1562 	futex_cleanup_begin(tsk);
1563 	futex_cleanup(tsk);
1564 	futex_cleanup_end(tsk);
1565 }
1566 
1567 /*
1568  * exec() has switched to the new mm. Futex operations are safe again.
1569  */
futex_exec_done(struct task_struct * tsk)1570 void futex_exec_done(struct task_struct *tsk)
1571 {
1572 	/*
1573 	 * This store does not have to take tsk::futex::exit_mutex because the
1574 	 * phase where waiters block on it during state FUTEX_STATE_EXITING has
1575 	 * been finished when futex_cleanup_end() set the state to
1576 	 * FUTEX_STATE_DEAD.
1577 	 *
1578 	 * This transitions back from FUTEX_STATE_DEAD to FUTEX_STATE_OK. The
1579 	 * ordering guarantee required here is that the previous store to
1580 	 * tsk::mm in the calling code cannot be reordered against this store.
1581 	 */
1582 	guard(raw_spinlock_irq)(&tsk->pi_lock);
1583 	tsk->futex.state = FUTEX_STATE_OK;
1584 }
1585 
futex_hash_bucket_init(struct futex_hash_bucket * fhb)1586 static void futex_hash_bucket_init(struct futex_hash_bucket *fhb)
1587 {
1588 	atomic_set(&fhb->waiters, 0);
1589 	plist_head_init(&fhb->chain);
1590 	spin_lock_init(&fhb->lock);
1591 }
1592 
1593 #define FH_CUSTOM	0x01
1594 
1595 #ifdef CONFIG_FUTEX_PRIVATE_HASH
1596 
1597 /*
1598  * futex-ref
1599  *
1600  * Heavily inspired by percpu-rwsem/percpu-refcount; not reusing any of that
1601  * code because it just doesn't fit right.
1602  *
1603  * Dual counter, per-cpu / atomic approach like percpu-refcount, except it
1604  * re-initializes the state automatically, such that the fph swizzle is also a
1605  * transition back to per-cpu.
1606  */
1607 
1608 static void futex_ref_rcu(struct rcu_head *head);
1609 
__futex_ref_atomic_begin(struct futex_private_hash * fph)1610 static void __futex_ref_atomic_begin(struct futex_private_hash *fph)
1611 {
1612 	struct mm_struct *mm = fph->mm;
1613 
1614 	/*
1615 	 * The counter we're about to switch to must have fully switched;
1616 	 * otherwise it would be impossible for it to have reported success
1617 	 * from futex_ref_is_dead().
1618 	 */
1619 	WARN_ON_ONCE(atomic_long_read(&mm->futex.phash.atomic) != 0);
1620 
1621 	/*
1622 	 * Set the atomic to the bias value such that futex_ref_{get,put}()
1623 	 * will never observe 0. Will be fixed up in __futex_ref_atomic_end()
1624 	 * when folding in the percpu count.
1625 	 */
1626 	atomic_long_set(&mm->futex.phash.atomic, LONG_MAX);
1627 	smp_store_release(&fph->state, FR_ATOMIC);
1628 
1629 	call_rcu_hurry(&mm->futex.phash.rcu, futex_ref_rcu);
1630 }
1631 
__futex_ref_atomic_end(struct futex_private_hash * fph)1632 static void __futex_ref_atomic_end(struct futex_private_hash *fph)
1633 {
1634 	struct mm_struct *mm = fph->mm;
1635 	unsigned int count = 0;
1636 	long ret;
1637 	int cpu;
1638 
1639 	/*
1640 	 * Per __futex_ref_atomic_begin() the state of the fph must be ATOMIC
1641 	 * and per this RCU callback, everybody must now observe this state and
1642 	 * use the atomic variable.
1643 	 */
1644 	WARN_ON_ONCE(fph->state != FR_ATOMIC);
1645 
1646 	/*
1647 	 * Therefore the per-cpu counter is now stable, sum and reset.
1648 	 */
1649 	for_each_possible_cpu(cpu) {
1650 		unsigned int *ptr = per_cpu_ptr(mm->futex.phash.ref, cpu);
1651 		count += *ptr;
1652 		*ptr = 0;
1653 	}
1654 
1655 	/*
1656 	 * Re-init for the next cycle.
1657 	 */
1658 	this_cpu_inc(*mm->futex.phash.ref); /* 0 -> 1 */
1659 
1660 	/*
1661 	 * Add actual count, subtract bias and initial refcount.
1662 	 *
1663 	 * The moment this atomic operation happens, futex_ref_is_dead() can
1664 	 * become true.
1665 	 */
1666 	ret = atomic_long_add_return(count - LONG_MAX - 1, &mm->futex.phash.atomic);
1667 	if (!ret)
1668 		wake_up_var(mm);
1669 
1670 	WARN_ON_ONCE(ret < 0);
1671 	mmput_async(mm);
1672 }
1673 
futex_ref_rcu(struct rcu_head * head)1674 static void futex_ref_rcu(struct rcu_head *head)
1675 {
1676 	struct mm_struct *mm = container_of(head, struct mm_struct, futex.phash.rcu);
1677 	struct futex_private_hash *fph = rcu_dereference_raw(mm->futex.phash.hash);
1678 
1679 	if (fph->state == FR_PERCPU) {
1680 		/*
1681 		 * Per this extra grace-period, everybody must now observe
1682 		 * fph as the current fph and no previously observed fph's
1683 		 * are in-flight.
1684 		 *
1685 		 * Notably, nobody will now rely on the atomic
1686 		 * futex_ref_is_dead() state anymore so we can begin the
1687 		 * migration of the per-cpu counter into the atomic.
1688 		 */
1689 		__futex_ref_atomic_begin(fph);
1690 		return;
1691 	}
1692 
1693 	__futex_ref_atomic_end(fph);
1694 }
1695 
1696 /*
1697  * Drop the initial refcount and transition to atomics.
1698  */
futex_ref_drop(struct futex_private_hash * fph)1699 static void futex_ref_drop(struct futex_private_hash *fph)
1700 {
1701 	struct mm_struct *mm = fph->mm;
1702 
1703 	/*
1704 	 * Can only transition the current fph;
1705 	 */
1706 	WARN_ON_ONCE(rcu_dereference_raw(mm->futex.phash.hash) != fph);
1707 	/*
1708 	 * We enqueue at least one RCU callback. Ensure mm stays if the task
1709 	 * exits before the transition is completed.
1710 	 */
1711 	mmget(mm);
1712 
1713 	/*
1714 	 * In order to avoid the following scenario:
1715 	 *
1716 	 * futex_hash()			__futex_pivot_hash()
1717 	 *   guard(rcu);		  guard(mm->futex.phash.lock);
1718 	 *   fph = mm->futex.phash.hash;
1719 	 *				  rcu_assign_pointer(&mm->futex.phash.hash, new);
1720 	 *				futex_hash_allocate()
1721 	 *				  futex_ref_drop()
1722 	 *				    fph->state = FR_ATOMIC;
1723 	 *				    atomic_set(, BIAS);
1724 	 *
1725 	 *   futex_private_hash_get(fph); // OOPS
1726 	 *
1727 	 * Where an old fph (which is FR_ATOMIC) and should fail on
1728 	 * inc_not_zero, will succeed because a new transition is started and
1729 	 * the atomic is bias'ed away from 0.
1730 	 *
1731 	 * There must be at least one full grace-period between publishing a
1732 	 * new fph and trying to replace it.
1733 	 */
1734 	if (poll_state_synchronize_rcu(mm->futex.phash.batches)) {
1735 		/*
1736 		 * There was a grace-period, we can begin now.
1737 		 */
1738 		__futex_ref_atomic_begin(fph);
1739 		return;
1740 	}
1741 
1742 	call_rcu_hurry(&mm->futex.phash.rcu, futex_ref_rcu);
1743 }
1744 
futex_ref_get(struct futex_private_hash * fph)1745 static bool futex_ref_get(struct futex_private_hash *fph)
1746 {
1747 	struct mm_struct *mm = fph->mm;
1748 
1749 	guard(preempt)();
1750 
1751 	if (READ_ONCE(fph->state) == FR_PERCPU) {
1752 		__this_cpu_inc(*mm->futex.phash.ref);
1753 		return true;
1754 	}
1755 
1756 	return atomic_long_inc_not_zero(&mm->futex.phash.atomic);
1757 }
1758 
futex_ref_put(struct futex_private_hash * fph)1759 static bool futex_ref_put(struct futex_private_hash *fph)
1760 {
1761 	struct mm_struct *mm = fph->mm;
1762 
1763 	guard(preempt)();
1764 
1765 	if (READ_ONCE(fph->state) == FR_PERCPU) {
1766 		__this_cpu_dec(*mm->futex.phash.ref);
1767 		return false;
1768 	}
1769 
1770 	return atomic_long_dec_and_test(&mm->futex.phash.atomic);
1771 }
1772 
futex_ref_is_dead(struct futex_private_hash * fph)1773 static bool futex_ref_is_dead(struct futex_private_hash *fph)
1774 {
1775 	struct mm_struct *mm = fph->mm;
1776 
1777 	guard(rcu)();
1778 
1779 	if (smp_load_acquire(&fph->state) == FR_PERCPU)
1780 		return false;
1781 
1782 	return atomic_long_read(&mm->futex.phash.atomic) == 0;
1783 }
1784 
futex_hash_init_mm(struct futex_mm_data * fd)1785 static void futex_hash_init_mm(struct futex_mm_data *fd)
1786 {
1787 	memset(&fd->phash, 0, sizeof(fd->phash));
1788 	mutex_init(&fd->phash.lock);
1789 	fd->phash.batches = get_state_synchronize_rcu();
1790 }
1791 
futex_hash_free(struct mm_struct * mm)1792 void futex_hash_free(struct mm_struct *mm)
1793 {
1794 	struct futex_private_hash *fph;
1795 
1796 	free_percpu(mm->futex.phash.ref);
1797 	kvfree(mm->futex.phash.hash_new);
1798 	fph = rcu_dereference_raw(mm->futex.phash.hash);
1799 	kvfree(fph);
1800 }
1801 
futex_pivot_pending(struct mm_struct * mm)1802 static bool futex_pivot_pending(struct mm_struct *mm)
1803 {
1804 	struct futex_mm_phash *mmph = &mm->futex.phash;
1805 	struct futex_private_hash *fph;
1806 
1807 	guard(mutex)(&mmph->lock);
1808 
1809 	if (!mmph->hash_new)
1810 		return true;
1811 
1812 	fph = rcu_dereference_raw(mmph->hash);
1813 	return futex_ref_is_dead(fph);
1814 }
1815 
futex_hash_less(struct futex_private_hash * a,struct futex_private_hash * b)1816 static bool futex_hash_less(struct futex_private_hash *a,
1817 			    struct futex_private_hash *b)
1818 {
1819 	/* user provided always wins */
1820 	if (!a->custom && b->custom)
1821 		return true;
1822 	if (a->custom && !b->custom)
1823 		return false;
1824 
1825 	/* zero-sized hash wins */
1826 	if (!b->hash_mask)
1827 		return true;
1828 	if (!a->hash_mask)
1829 		return false;
1830 
1831 	/* keep the biggest */
1832 	if (a->hash_mask < b->hash_mask)
1833 		return true;
1834 	if (a->hash_mask > b->hash_mask)
1835 		return false;
1836 
1837 	return false; /* equal */
1838 }
1839 
futex_hash_allocate(unsigned int hash_slots,unsigned int flags)1840 static int futex_hash_allocate(unsigned int hash_slots, unsigned int flags)
1841 {
1842 	struct mm_struct *mm = current->mm;
1843 	struct futex_private_hash *fph;
1844 	bool custom = flags & FH_CUSTOM;
1845 	int i;
1846 
1847 	if (hash_slots && (hash_slots == 1 || !is_power_of_2(hash_slots)))
1848 		return -EINVAL;
1849 
1850 	/*
1851 	 * Once we've disabled the global hash there is no way back.
1852 	 */
1853 	scoped_guard(rcu) {
1854 		fph = rcu_dereference(mm->futex.phash.hash);
1855 		if (fph && !fph->hash_mask) {
1856 			if (custom)
1857 				return -EBUSY;
1858 			return 0;
1859 		}
1860 	}
1861 
1862 	if (!mm->futex.phash.ref) {
1863 		unsigned int __percpu *ref = alloc_percpu(unsigned int);
1864 
1865 		if (!ref)
1866 			return -ENOMEM;
1867 
1868 		/*
1869 		 * Tasks sharing the mm can run this concurrently, so take the
1870 		 * initial reference before publishing the counter.
1871 		 */
1872 		this_cpu_inc(*ref); /* 0 -> 1 */
1873 		if (cmpxchg(&mm->futex.phash.ref, NULL, ref))
1874 			free_percpu(ref);
1875 	}
1876 
1877 	fph = kvzalloc_flex(*fph, queues, hash_slots,
1878 			    GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
1879 	if (!fph)
1880 		return -ENOMEM;
1881 
1882 	fph->hash_mask = hash_slots ? hash_slots - 1 : 0;
1883 	fph->custom = custom;
1884 	fph->mm = mm;
1885 
1886 	for (i = 0; i < hash_slots; i++)
1887 		futex_hash_bucket_init(&fph->queues[i]);
1888 
1889 	if (custom) {
1890 		struct wait_bit_queue_entry __wbq_entry;
1891 		struct wait_queue_head *__wq_head;
1892 
1893 		/*
1894 		 * Only let prctl() wait / retry; don't unduly delay clone().
1895 		 */
1896 again:
1897 		__wq_head = __var_waitqueue(mm);
1898 		init_wait_var_entry(&__wbq_entry, mm, 0);
1899 		__wbq_entry.wq_entry.func = woken_wake_bit_function;
1900 		add_wait_queue(__wq_head, &__wbq_entry.wq_entry);
1901 
1902 		/*
1903 		 * add_wait_queue()		futex_ref_put()
1904 		 * MB (this)			MB (implied)
1905 		 * futex_pivot_pending()	wake_up_var()
1906 		 *                                waitqueue_active()
1907 		 *
1908 		 * Notably, it must not be possible to see
1909 		 * !futex_pivot_pending() && !waitqueue_active().
1910 		 */
1911 		smp_mb();
1912 
1913 		while (!futex_pivot_pending(mm) &&
1914 		       wait_woken(&__wbq_entry.wq_entry, TASK_UNINTERRUPTIBLE,
1915 				  MAX_SCHEDULE_TIMEOUT))
1916 			/* empty */;
1917 
1918 		remove_wait_queue(__wq_head, &__wbq_entry.wq_entry);
1919 	}
1920 
1921 	scoped_guard(mutex, &mm->futex.phash.lock) {
1922 		struct futex_private_hash *free __free(kvfree) = NULL;
1923 		struct futex_private_hash *cur, *new;
1924 
1925 		cur = rcu_dereference_protected(mm->futex.phash.hash,
1926 						lockdep_is_held(&mm->futex.phash.lock));
1927 		new = mm->futex.phash.hash_new;
1928 		mm->futex.phash.hash_new = NULL;
1929 
1930 		if (fph) {
1931 			if (cur && !cur->hash_mask) {
1932 				/*
1933 				 * If two threads simultaneously request the global
1934 				 * hash then the first one performs the switch,
1935 				 * the second one returns here.
1936 				 */
1937 				free = fph;
1938 				mm->futex.phash.hash_new = new;
1939 				return -EBUSY;
1940 			}
1941 			if (cur && !new) {
1942 				/*
1943 				 * If we have an existing hash, but do not yet have
1944 				 * allocated a replacement hash, drop the initial
1945 				 * reference on the existing hash.
1946 				 */
1947 				futex_ref_drop(cur);
1948 			}
1949 
1950 			if (new) {
1951 				/*
1952 				 * Two updates raced; throw out the lesser one.
1953 				 */
1954 				if (futex_hash_less(new, fph)) {
1955 					free = new;
1956 					new = fph;
1957 				} else {
1958 					free = fph;
1959 				}
1960 			} else {
1961 				new = fph;
1962 			}
1963 			fph = NULL;
1964 		}
1965 
1966 		if (new) {
1967 			/*
1968 			 * Will set mm->futex.phash.new_hash on failure;
1969 			 * futex_private_hash_get() will try again.
1970 			 */
1971 			if (!__futex_pivot_hash(mm, new) && custom)
1972 				goto again;
1973 		}
1974 	}
1975 	return 0;
1976 }
1977 
futex_hash_allocate_default(void)1978 int futex_hash_allocate_default(void)
1979 {
1980 	unsigned int threads, buckets, current_buckets = 0;
1981 	struct futex_private_hash *fph;
1982 
1983 	if (!current->mm)
1984 		return 0;
1985 
1986 	scoped_guard(rcu) {
1987 		threads = min_t(unsigned int, get_nr_threads(current), num_online_cpus());
1988 
1989 		fph = rcu_dereference(current->mm->futex.phash.hash);
1990 		if (fph) {
1991 			if (fph->custom)
1992 				return 0;
1993 
1994 			current_buckets = fph->hash_mask + 1;
1995 		}
1996 	}
1997 
1998 	/*
1999 	 * The default allocation will remain within
2000 	 *   16 <= threads * 4 <= global hash size
2001 	 */
2002 	buckets = roundup_pow_of_two(4 * threads);
2003 	buckets = clamp(buckets, 16, __futex_mask + 1);
2004 
2005 	if (current_buckets >= buckets)
2006 		return 0;
2007 
2008 	return futex_hash_allocate(buckets, 0);
2009 }
2010 
futex_hash_get_slots(void)2011 static int futex_hash_get_slots(void)
2012 {
2013 	struct futex_private_hash *fph;
2014 
2015 	guard(rcu)();
2016 	fph = rcu_dereference(current->mm->futex.phash.hash);
2017 	if (fph && fph->hash_mask)
2018 		return fph->hash_mask + 1;
2019 	return 0;
2020 }
2021 #else  /* CONFIG_FUTEX_PRIVATE_HASH */
futex_hash_allocate(unsigned int hslots,unsigned int flags)2022 static inline int futex_hash_allocate(unsigned int hslots, unsigned int flags) { return -EINVAL; }
futex_hash_get_slots(void)2023 static inline int futex_hash_get_slots(void) { return 0; }
futex_hash_init_mm(struct futex_mm_data * fd)2024 static inline void futex_hash_init_mm(struct futex_mm_data *fd) { }
2025 #endif /* !CONFIG_FUTEX_PRIVATE_HASH */
2026 
2027 #ifdef CONFIG_FUTEX_ROBUST_UNLOCK
futex_invalidate_cs_ranges(struct futex_mm_data * fd)2028 static void futex_invalidate_cs_ranges(struct futex_mm_data *fd)
2029 {
2030 	/*
2031 	 * Invalidate start_ip so that the quick check fails for ip >= start_ip
2032 	 * if VDSO is not mapped or the second slot is not available for compat
2033 	 * tasks as they use VDSO32 which does not provide the 64-bit pointer
2034 	 * variant.
2035 	 */
2036 	for (int i = 0; i < FUTEX_ROBUST_MAX_CS_RANGES; i++)
2037 		fd->unlock.cs_ranges[i].start_ip = ~0UL;
2038 }
2039 
futex_reset_cs_ranges(struct futex_mm_data * fd)2040 void futex_reset_cs_ranges(struct futex_mm_data *fd)
2041 {
2042 	memset(fd->unlock.cs_ranges, 0, sizeof(fd->unlock.cs_ranges));
2043 	futex_invalidate_cs_ranges(fd);
2044 }
2045 
futex_robust_unlock_init_mm(struct futex_mm_data * fd)2046 static void futex_robust_unlock_init_mm(struct futex_mm_data *fd)
2047 {
2048 	/* mm_dup() preserves the range, mm_alloc() clears it */
2049 	if (!fd->unlock.cs_ranges[0].start_ip)
2050 		futex_invalidate_cs_ranges(fd);
2051 }
2052 #else  /* CONFIG_FUTEX_ROBUST_UNLOCK */
futex_robust_unlock_init_mm(struct futex_mm_data * fd)2053 static inline void futex_robust_unlock_init_mm(struct futex_mm_data *fd) { }
2054 #endif /* !CONFIG_FUTEX_ROBUST_UNLOCK */
2055 
2056 #if defined(CONFIG_FUTEX_PRIVATE_HASH) || defined(CONFIG_FUTEX_ROBUST_UNLOCK)
futex_mm_init(struct mm_struct * mm)2057 void futex_mm_init(struct mm_struct *mm)
2058 {
2059 	futex_hash_init_mm(&mm->futex);
2060 	futex_robust_unlock_init_mm(&mm->futex);
2061 }
2062 #endif
2063 
futex_hash_prctl(unsigned long arg2,unsigned long arg3,unsigned long arg4)2064 int futex_hash_prctl(unsigned long arg2, unsigned long arg3, unsigned long arg4)
2065 {
2066 	unsigned int flags = FH_CUSTOM;
2067 	int ret;
2068 
2069 	switch (arg2) {
2070 	case PR_FUTEX_HASH_SET_SLOTS:
2071 		if (arg4)
2072 			return -EINVAL;
2073 		ret = futex_hash_allocate(arg3, flags);
2074 		break;
2075 
2076 	case PR_FUTEX_HASH_GET_SLOTS:
2077 		ret = futex_hash_get_slots();
2078 		break;
2079 
2080 	default:
2081 		ret = -EINVAL;
2082 		break;
2083 	}
2084 	return ret;
2085 }
2086 
futex_init(void)2087 static int __init futex_init(void)
2088 {
2089 	unsigned long hashsize, i;
2090 	unsigned int order, n;
2091 	unsigned long size;
2092 
2093 #ifdef CONFIG_BASE_SMALL
2094 	hashsize = 16;
2095 #else
2096 	hashsize = 256 * num_possible_cpus();
2097 	hashsize /= num_possible_nodes();
2098 	hashsize = max(4, hashsize);
2099 	hashsize = roundup_pow_of_two(hashsize);
2100 #endif
2101 	__futex_mask = hashsize - 1;
2102 	__futex_shift = ilog2(hashsize);
2103 	size = sizeof(struct futex_hash_bucket) * hashsize;
2104 	order = get_order(size);
2105 
2106 	__futex_queues = kzalloc_objs(*__futex_queues, nr_node_ids);
2107 	kmemleak_not_leak(__futex_queues);
2108 
2109 	runtime_const_init(shift, __futex_shift);
2110 	runtime_const_init(mask,  __futex_mask);
2111 	runtime_const_init(ptr,   __futex_queues);
2112 
2113 	barrier();
2114 
2115 	BUG_ON(!futex_queues());
2116 
2117 	for_each_node(n) {
2118 		struct futex_hash_bucket *table;
2119 
2120 		if (order > MAX_PAGE_ORDER)
2121 			table = vmalloc_huge_node(size, GFP_KERNEL, n);
2122 		else
2123 			table = alloc_pages_exact_nid(n, size, GFP_KERNEL);
2124 
2125 		BUG_ON(!table);
2126 
2127 		for (i = 0; i < hashsize; i++)
2128 			futex_hash_bucket_init(&table[i]);
2129 
2130 		futex_queues()[n] = table;
2131 	}
2132 
2133 	pr_info("futex hash table entries: %lu (%lu bytes on %d NUMA nodes, total %lu KiB, %s).\n",
2134 		hashsize, size, num_possible_nodes(), size * num_possible_nodes() / 1024,
2135 		order > MAX_PAGE_ORDER ? "vmalloc" : "linear");
2136 	return 0;
2137 }
2138 core_initcall(futex_init);
2139