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