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