1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Slab allocator functions that are independent of the allocator strategy 4 * 5 * (C) 2012 Christoph Lameter <cl@gentwo.org> 6 */ 7 #include <linux/slab.h> 8 9 #include <linux/mm.h> 10 #include <linux/poison.h> 11 #include <linux/interrupt.h> 12 #include <linux/memory.h> 13 #include <linux/cache.h> 14 #include <linux/compiler.h> 15 #include <linux/kfence.h> 16 #include <linux/module.h> 17 #include <linux/cpu.h> 18 #include <linux/uaccess.h> 19 #include <linux/seq_file.h> 20 #include <linux/dma-mapping.h> 21 #include <linux/swiotlb.h> 22 #include <linux/proc_fs.h> 23 #include <linux/debugfs.h> 24 #include <linux/kmemleak.h> 25 #include <linux/kasan.h> 26 #include <asm/cacheflush.h> 27 #include <asm/tlbflush.h> 28 #include <asm/page.h> 29 #include <linux/memcontrol.h> 30 #include <linux/stackdepot.h> 31 #include <trace/events/rcu.h> 32 33 #include "../kernel/rcu/rcu.h" 34 #include "internal.h" 35 #include "slab.h" 36 37 #define CREATE_TRACE_POINTS 38 #include <trace/events/kmem.h> 39 40 enum slab_state slab_state; 41 LIST_HEAD(slab_caches); 42 DEFINE_MUTEX(slab_mutex); 43 struct kmem_cache *kmem_cache; 44 45 /* 46 * Set of flags that will prevent slab merging. 47 * Any flag that adds per-object metadata should be included, 48 * since slab merging can update s->inuse that affects the metadata layout. 49 */ 50 #define SLAB_NEVER_MERGE (SLAB_DEBUG_FLAGS | SLAB_TYPESAFE_BY_RCU | \ 51 SLAB_NOLEAKTRACE | SLAB_FAILSLAB | SLAB_NO_MERGE | \ 52 SLAB_OBJ_EXT_IN_OBJ) 53 54 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \ 55 SLAB_CACHE_DMA32 | SLAB_ACCOUNT) 56 57 /* 58 * Merge control. If this is set then no merging of slab caches will occur. 59 */ 60 static bool slab_nomerge = !IS_ENABLED(CONFIG_SLAB_MERGE_DEFAULT); 61 62 static int __init setup_slab_nomerge(char *str) 63 { 64 slab_nomerge = true; 65 return 1; 66 } 67 68 static int __init setup_slab_merge(char *str) 69 { 70 slab_nomerge = false; 71 return 1; 72 } 73 74 __setup_param("slub_nomerge", slub_nomerge, setup_slab_nomerge, 0); 75 __setup_param("slub_merge", slub_merge, setup_slab_merge, 0); 76 77 __setup("slab_nomerge", setup_slab_nomerge); 78 __setup("slab_merge", setup_slab_merge); 79 80 /* 81 * Determine the size of a slab object 82 */ 83 unsigned int kmem_cache_size(struct kmem_cache *s) 84 { 85 return s->object_size; 86 } 87 EXPORT_SYMBOL(kmem_cache_size); 88 89 #ifdef CONFIG_DEBUG_VM 90 91 static bool kmem_cache_is_duplicate_name(const char *name) 92 { 93 struct kmem_cache *s; 94 95 list_for_each_entry(s, &slab_caches, list) { 96 if (!strcmp(s->name, name)) 97 return true; 98 } 99 100 return false; 101 } 102 103 static int kmem_cache_sanity_check(const char *name, unsigned int size) 104 { 105 if (!name || in_interrupt() || size > KMALLOC_MAX_SIZE) { 106 pr_err("kmem_cache_create(%s) integrity check failed\n", name); 107 return -EINVAL; 108 } 109 110 /* Duplicate names will confuse slabtop, et al */ 111 WARN(kmem_cache_is_duplicate_name(name), 112 "kmem_cache of name '%s' already exists\n", name); 113 114 WARN_ON(strchr(name, ' ')); /* It confuses parsers */ 115 return 0; 116 } 117 #else 118 static inline int kmem_cache_sanity_check(const char *name, unsigned int size) 119 { 120 return 0; 121 } 122 #endif 123 124 /* 125 * Figure out what the alignment of the objects will be given a set of 126 * flags, a user specified alignment and the size of the objects. 127 */ 128 static unsigned int calculate_alignment(slab_flags_t flags, 129 unsigned int align, unsigned int size) 130 { 131 /* 132 * If the user wants hardware cache aligned objects then follow that 133 * suggestion if the object is sufficiently large. 134 * 135 * The hardware cache alignment cannot override the specified 136 * alignment though. If that is greater then use it. 137 */ 138 if (flags & SLAB_HWCACHE_ALIGN) { 139 unsigned int ralign; 140 141 ralign = cache_line_size(); 142 while (size <= ralign / 2) 143 ralign /= 2; 144 align = max(align, ralign); 145 } 146 147 align = max(align, arch_slab_minalign()); 148 149 return ALIGN(align, sizeof(void *)); 150 } 151 152 /* 153 * Find a mergeable slab cache 154 */ 155 int slab_unmergeable(struct kmem_cache *s) 156 { 157 if (slab_nomerge || (s->flags & SLAB_NEVER_MERGE)) 158 return 1; 159 160 if (s->ctor) 161 return 1; 162 163 #ifdef CONFIG_HARDENED_USERCOPY 164 if (s->usersize) 165 return 1; 166 #endif 167 168 /* 169 * We may have set a slab to be unmergeable during bootstrap. 170 */ 171 if (s->refcount < 0) 172 return 1; 173 174 return 0; 175 } 176 177 bool slab_args_unmergeable(struct kmem_cache_args *args, slab_flags_t flags) 178 { 179 if (slab_nomerge) 180 return true; 181 182 if (args->ctor) 183 return true; 184 185 if (IS_ENABLED(CONFIG_HARDENED_USERCOPY) && args->usersize) 186 return true; 187 188 if (flags & SLAB_NEVER_MERGE) 189 return true; 190 191 return false; 192 } 193 194 static struct kmem_cache *find_mergeable(unsigned int size, slab_flags_t flags, 195 const char *name, struct kmem_cache_args *args) 196 { 197 struct kmem_cache *s; 198 unsigned int align; 199 200 flags = kmem_cache_flags(flags, name); 201 if (slab_args_unmergeable(args, flags)) 202 return NULL; 203 204 size = ALIGN(size, sizeof(void *)); 205 align = calculate_alignment(flags, args->align, size); 206 size = ALIGN(size, align); 207 208 list_for_each_entry_reverse(s, &slab_caches, list) { 209 if (slab_unmergeable(s)) 210 continue; 211 212 if (size > s->size) 213 continue; 214 215 if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME)) 216 continue; 217 /* 218 * Check if alignment is compatible. 219 * Courtesy of Adrian Drzewiecki 220 */ 221 if ((s->size & ~(align - 1)) != s->size) 222 continue; 223 224 if (s->size - size >= sizeof(void *)) 225 continue; 226 227 return s; 228 } 229 return NULL; 230 } 231 232 static struct kmem_cache *create_cache(const char *name, 233 unsigned int object_size, 234 struct kmem_cache_args *args, 235 slab_flags_t flags) 236 { 237 struct kmem_cache *s; 238 int err; 239 240 /* If a custom freelist pointer is requested make sure it's sane. */ 241 err = -EINVAL; 242 if (args->use_freeptr_offset && 243 (args->freeptr_offset >= object_size || 244 (!(flags & SLAB_TYPESAFE_BY_RCU) && !args->ctor) || 245 !IS_ALIGNED(args->freeptr_offset, __alignof__(freeptr_t)))) 246 goto out; 247 248 err = -ENOMEM; 249 s = kmem_cache_zalloc(kmem_cache, GFP_KERNEL); 250 if (!s) 251 goto out; 252 err = do_kmem_cache_create(s, name, object_size, args, flags); 253 if (err) 254 goto out_free_cache; 255 256 s->refcount = 1; 257 list_add(&s->list, &slab_caches); 258 return s; 259 260 out_free_cache: 261 kmem_cache_free(kmem_cache, s); 262 out: 263 return ERR_PTR(err); 264 } 265 266 static struct kmem_cache * 267 __kmem_cache_alias(const char *name, unsigned int size, slab_flags_t flags, 268 struct kmem_cache_args *args) 269 { 270 struct kmem_cache *s; 271 272 s = find_mergeable(size, flags, name, args); 273 if (s) { 274 if (sysfs_slab_alias(s, name)) 275 pr_err("SLUB: Unable to add cache alias %s to sysfs\n", 276 name); 277 278 s->refcount++; 279 280 /* 281 * Adjust the object sizes so that we clear 282 * the complete object on kzalloc. 283 */ 284 s->object_size = max(s->object_size, size); 285 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *))); 286 } 287 288 return s; 289 } 290 291 /** 292 * __kmem_cache_create_args - Create a kmem cache. 293 * @name: A string which is used in /proc/slabinfo to identify this cache. 294 * @object_size: The size of objects to be created in this cache. 295 * @args: Additional arguments for the cache creation (see 296 * &struct kmem_cache_args). 297 * @flags: See the descriptions of individual flags. The common ones are listed 298 * in the description below. 299 * 300 * Not to be called directly, use the kmem_cache_create() wrapper with the same 301 * parameters. 302 * 303 * Commonly used @flags: 304 * 305 * &SLAB_ACCOUNT - Account allocations to memcg. 306 * 307 * &SLAB_HWCACHE_ALIGN - Align objects on cache line boundaries. 308 * 309 * &SLAB_RECLAIM_ACCOUNT - Objects are reclaimable. 310 * 311 * &SLAB_TYPESAFE_BY_RCU - Slab page (not individual objects) freeing delayed 312 * by a grace period - see the full description before using. 313 * 314 * Context: Cannot be called within a interrupt, but can be interrupted. 315 * 316 * Return: a pointer to the cache on success, NULL on failure. 317 */ 318 struct kmem_cache *__kmem_cache_create_args(const char *name, 319 unsigned int object_size, 320 struct kmem_cache_args *args, 321 slab_flags_t flags) 322 { 323 struct kmem_cache *s = NULL; 324 const char *cache_name; 325 int err; 326 327 #ifdef CONFIG_SLUB_DEBUG 328 /* 329 * If no slab_debug was enabled globally, the static key is not yet 330 * enabled by setup_slub_debug(). Enable it if the cache is being 331 * created with any of the debugging flags passed explicitly. 332 * It's also possible that this is the first cache created with 333 * SLAB_STORE_USER and we should init stack_depot for it. 334 */ 335 if (flags & SLAB_DEBUG_FLAGS) 336 static_branch_enable(&slub_debug_enabled); 337 if (flags & SLAB_STORE_USER) 338 stack_depot_init(); 339 #else 340 flags &= ~SLAB_DEBUG_FLAGS; 341 #endif 342 343 /* 344 * Caches with specific capacity are special enough. It's simpler to 345 * make them unmergeable. 346 */ 347 if (args->sheaf_capacity) 348 flags |= SLAB_NO_MERGE; 349 350 mutex_lock(&slab_mutex); 351 352 err = kmem_cache_sanity_check(name, object_size); 353 if (err) { 354 goto out_unlock; 355 } 356 357 if (flags & ~SLAB_FLAGS_PERMITTED) { 358 err = -EINVAL; 359 goto out_unlock; 360 } 361 362 /* Fail closed on bad usersize of useroffset values. */ 363 if (!IS_ENABLED(CONFIG_HARDENED_USERCOPY) || 364 WARN_ON(!args->usersize && args->useroffset) || 365 WARN_ON(object_size < args->usersize || 366 object_size - args->usersize < args->useroffset)) 367 args->usersize = args->useroffset = 0; 368 369 s = __kmem_cache_alias(name, object_size, flags, args); 370 if (s) 371 goto out_unlock; 372 373 cache_name = kstrdup_const(name, GFP_KERNEL); 374 if (!cache_name) { 375 err = -ENOMEM; 376 goto out_unlock; 377 } 378 379 args->align = calculate_alignment(flags, args->align, object_size); 380 s = create_cache(cache_name, object_size, args, flags); 381 if (IS_ERR(s)) { 382 err = PTR_ERR(s); 383 kfree_const(cache_name); 384 } 385 386 out_unlock: 387 mutex_unlock(&slab_mutex); 388 389 if (err) { 390 if (flags & SLAB_PANIC) 391 panic("%s: Failed to create slab '%s'. Error %d\n", 392 __func__, name, err); 393 else { 394 pr_warn("%s(%s) failed with error %d\n", 395 __func__, name, err); 396 dump_stack(); 397 } 398 return NULL; 399 } 400 return s; 401 } 402 EXPORT_SYMBOL(__kmem_cache_create_args); 403 404 static struct kmem_cache *kmem_buckets_cache __ro_after_init; 405 406 /** 407 * kmem_buckets_create - Create a set of caches that handle dynamic sized 408 * allocations via kmem_buckets_alloc() 409 * @name: A prefix string which is used in /proc/slabinfo to identify this 410 * cache. The individual caches with have their sizes as the suffix. 411 * @flags: SLAB flags (see kmem_cache_create() for details). 412 * @useroffset: Starting offset within an allocation that may be copied 413 * to/from userspace. 414 * @usersize: How many bytes, starting at @useroffset, may be copied 415 * to/from userspace. 416 * @ctor: A constructor for the objects, run when new allocations are made. 417 * 418 * Cannot be called within an interrupt, but can be interrupted. 419 * 420 * Return: a pointer to the cache on success, NULL on failure. When 421 * CONFIG_SLAB_BUCKETS is not enabled, ZERO_SIZE_PTR is returned, and 422 * subsequent calls to kmem_buckets_alloc() will fall back to kmalloc(). 423 * (i.e. callers only need to check for NULL on failure.) 424 */ 425 kmem_buckets *kmem_buckets_create(const char *name, slab_flags_t flags, 426 unsigned int useroffset, 427 unsigned int usersize, 428 void (*ctor)(void *)) 429 { 430 unsigned long mask = 0; 431 unsigned int idx; 432 kmem_buckets *b; 433 434 BUILD_BUG_ON(ARRAY_SIZE(kmalloc_caches[KMALLOC_NORMAL]) > BITS_PER_LONG); 435 436 /* 437 * When the separate buckets API is not built in, just return 438 * a non-NULL value for the kmem_buckets pointer, which will be 439 * unused when performing allocations. 440 */ 441 if (!IS_ENABLED(CONFIG_SLAB_BUCKETS)) 442 return ZERO_SIZE_PTR; 443 444 if (WARN_ON(!kmem_buckets_cache)) 445 return NULL; 446 447 b = kmem_cache_alloc(kmem_buckets_cache, GFP_KERNEL|__GFP_ZERO); 448 if (WARN_ON(!b)) 449 return NULL; 450 451 flags |= SLAB_NO_MERGE; 452 453 for (idx = 0; idx < ARRAY_SIZE(kmalloc_caches[KMALLOC_NORMAL]); idx++) { 454 char *short_size, *cache_name; 455 unsigned int cache_useroffset, cache_usersize; 456 unsigned int size, aligned_idx; 457 458 if (!kmalloc_caches[KMALLOC_NORMAL][idx]) 459 continue; 460 461 size = kmalloc_caches[KMALLOC_NORMAL][idx]->object_size; 462 if (!size) 463 continue; 464 465 short_size = strchr(kmalloc_caches[KMALLOC_NORMAL][idx]->name, '-'); 466 if (WARN_ON(!short_size)) 467 goto fail; 468 469 if (useroffset >= size) { 470 cache_useroffset = 0; 471 cache_usersize = 0; 472 } else { 473 cache_useroffset = useroffset; 474 cache_usersize = min(size - cache_useroffset, usersize); 475 } 476 477 aligned_idx = __kmalloc_index(size, false); 478 if (!(*b)[aligned_idx]) { 479 cache_name = kasprintf(GFP_KERNEL, "%s-%s", name, short_size + 1); 480 if (WARN_ON(!cache_name)) 481 goto fail; 482 (*b)[aligned_idx] = kmem_cache_create_usercopy(cache_name, size, 483 0, flags, cache_useroffset, 484 cache_usersize, ctor); 485 kfree(cache_name); 486 if (WARN_ON(!(*b)[aligned_idx])) 487 goto fail; 488 set_bit(aligned_idx, &mask); 489 } 490 if (idx != aligned_idx) 491 (*b)[idx] = (*b)[aligned_idx]; 492 } 493 494 return b; 495 496 fail: 497 for_each_set_bit(idx, &mask, ARRAY_SIZE(kmalloc_caches[KMALLOC_NORMAL])) 498 kmem_cache_destroy((*b)[idx]); 499 kmem_cache_free(kmem_buckets_cache, b); 500 501 return NULL; 502 } 503 EXPORT_SYMBOL(kmem_buckets_create); 504 505 /* 506 * For a given kmem_cache, kmem_cache_destroy() should only be called 507 * once or there will be a use-after-free problem. The actual deletion 508 * and release of the kobject does not need slab_mutex or cpu_hotplug_lock 509 * protection. So they are now done without holding those locks. 510 */ 511 static void kmem_cache_release(struct kmem_cache *s) 512 { 513 kfence_shutdown_cache(s); 514 if (__is_defined(SLAB_SUPPORTS_SYSFS) && slab_state >= FULL) 515 sysfs_slab_release(s); 516 else 517 slab_kmem_cache_release(s); 518 } 519 520 void slab_kmem_cache_release(struct kmem_cache *s) 521 { 522 __kmem_cache_release(s); 523 kfree_const(s->name); 524 kmem_cache_free(kmem_cache, s); 525 } 526 527 void kmem_cache_destroy(struct kmem_cache *s) 528 { 529 int err; 530 531 if (unlikely(!s) || !kasan_check_byte(s)) 532 return; 533 534 /* in-flight kfree_rcu()'s may include objects from our cache */ 535 kvfree_rcu_barrier_on_cache(s); 536 537 if (IS_ENABLED(CONFIG_SLUB_RCU_DEBUG) && 538 (s->flags & SLAB_TYPESAFE_BY_RCU)) { 539 /* 540 * Under CONFIG_SLUB_RCU_DEBUG, when objects in a 541 * SLAB_TYPESAFE_BY_RCU slab are freed, SLUB will internally 542 * defer their freeing with call_rcu(). 543 * Wait for such call_rcu() invocations here before actually 544 * destroying the cache. 545 * 546 * It doesn't matter that we haven't looked at the slab refcount 547 * yet - slabs with SLAB_TYPESAFE_BY_RCU can't be merged, so 548 * the refcount should be 1 here. 549 */ 550 rcu_barrier(); 551 } 552 553 /* Wait for deferred work from kmalloc/kfree_nolock() */ 554 defer_free_barrier(); 555 556 cpus_read_lock(); 557 mutex_lock(&slab_mutex); 558 559 s->refcount--; 560 if (s->refcount) { 561 mutex_unlock(&slab_mutex); 562 cpus_read_unlock(); 563 return; 564 } 565 566 /* free asan quarantined objects */ 567 kasan_cache_shutdown(s); 568 569 err = __kmem_cache_shutdown(s); 570 if (!slab_in_kunit_test()) 571 WARN(err, "%s %s: Slab cache still has objects when called from %pS", 572 __func__, s->name, (void *)_RET_IP_); 573 574 list_del(&s->list); 575 576 mutex_unlock(&slab_mutex); 577 cpus_read_unlock(); 578 579 if (slab_state >= FULL) 580 sysfs_slab_unlink(s); 581 debugfs_slab_release(s); 582 583 if (err) 584 return; 585 586 if (s->flags & SLAB_TYPESAFE_BY_RCU) 587 rcu_barrier(); 588 589 kmem_cache_release(s); 590 } 591 EXPORT_SYMBOL(kmem_cache_destroy); 592 593 /** 594 * kmem_cache_shrink - Shrink a cache. 595 * @cachep: The cache to shrink. 596 * 597 * Releases as many slabs as possible for a cache. 598 * To help debugging, a zero exit status indicates all slabs were released. 599 * 600 * Return: %0 if all slabs were released, non-zero otherwise 601 */ 602 int kmem_cache_shrink(struct kmem_cache *cachep) 603 { 604 kasan_cache_shrink(cachep); 605 606 return __kmem_cache_shrink(cachep); 607 } 608 EXPORT_SYMBOL(kmem_cache_shrink); 609 610 bool slab_is_available(void) 611 { 612 return slab_state >= UP; 613 } 614 615 #ifdef CONFIG_PRINTK 616 static void kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab) 617 { 618 if (__kfence_obj_info(kpp, object, slab)) 619 return; 620 __kmem_obj_info(kpp, object, slab); 621 } 622 623 /** 624 * kmem_dump_obj - Print available slab provenance information 625 * @object: slab object for which to find provenance information. 626 * 627 * This function uses pr_cont(), so that the caller is expected to have 628 * printed out whatever preamble is appropriate. The provenance information 629 * depends on the type of object and on how much debugging is enabled. 630 * For a slab-cache object, the fact that it is a slab object is printed, 631 * and, if available, the slab name, return address, and stack trace from 632 * the allocation and last free path of that object. 633 * 634 * Return: %true if the pointer is to a not-yet-freed object from 635 * kmalloc() or kmem_cache_alloc(), either %true or %false if the pointer 636 * is to an already-freed object, and %false otherwise. 637 */ 638 bool kmem_dump_obj(void *object) 639 { 640 char *cp = IS_ENABLED(CONFIG_MMU) ? "" : "/vmalloc"; 641 int i; 642 struct slab *slab; 643 unsigned long ptroffset; 644 struct kmem_obj_info kp = { }; 645 646 /* Some arches consider ZERO_SIZE_PTR to be a valid address. */ 647 if (object < (void *)PAGE_SIZE || !virt_addr_valid(object)) 648 return false; 649 slab = virt_to_slab(object); 650 if (!slab) 651 return false; 652 653 kmem_obj_info(&kp, object, slab); 654 if (kp.kp_slab_cache) 655 pr_cont(" slab%s %s", cp, kp.kp_slab_cache->name); 656 else 657 pr_cont(" slab%s", cp); 658 if (is_kfence_address(object)) 659 pr_cont(" (kfence)"); 660 if (kp.kp_objp) 661 pr_cont(" start %px", kp.kp_objp); 662 if (kp.kp_data_offset) 663 pr_cont(" data offset %lu", kp.kp_data_offset); 664 if (kp.kp_objp) { 665 ptroffset = ((char *)object - (char *)kp.kp_objp) - kp.kp_data_offset; 666 pr_cont(" pointer offset %lu", ptroffset); 667 } 668 if (kp.kp_slab_cache && kp.kp_slab_cache->object_size) 669 pr_cont(" size %u", kp.kp_slab_cache->object_size); 670 if (kp.kp_ret) 671 pr_cont(" allocated at %pS\n", kp.kp_ret); 672 else 673 pr_cont("\n"); 674 for (i = 0; i < ARRAY_SIZE(kp.kp_stack); i++) { 675 if (!kp.kp_stack[i]) 676 break; 677 pr_info(" %pS\n", kp.kp_stack[i]); 678 } 679 680 if (kp.kp_free_stack[0]) 681 pr_cont(" Free path:\n"); 682 683 for (i = 0; i < ARRAY_SIZE(kp.kp_free_stack); i++) { 684 if (!kp.kp_free_stack[i]) 685 break; 686 pr_info(" %pS\n", kp.kp_free_stack[i]); 687 } 688 689 return true; 690 } 691 EXPORT_SYMBOL_GPL(kmem_dump_obj); 692 #endif 693 694 /* Create a cache during boot when no slab services are available yet */ 695 void __init create_boot_cache(struct kmem_cache *s, const char *name, 696 unsigned int size, slab_flags_t flags, 697 unsigned int useroffset, unsigned int usersize) 698 { 699 int err; 700 unsigned int align = ARCH_KMALLOC_MINALIGN; 701 struct kmem_cache_args kmem_args = {}; 702 703 /* 704 * kmalloc caches guarantee alignment of at least the largest 705 * power-of-two divisor of the size. For power-of-two sizes, 706 * it is the size itself. 707 */ 708 if (flags & SLAB_KMALLOC) 709 align = max(align, 1U << (ffs(size) - 1)); 710 kmem_args.align = calculate_alignment(flags, align, size); 711 712 #ifdef CONFIG_HARDENED_USERCOPY 713 kmem_args.useroffset = useroffset; 714 kmem_args.usersize = usersize; 715 #endif 716 717 err = do_kmem_cache_create(s, name, size, &kmem_args, flags); 718 719 if (err) 720 panic("Creation of kmalloc slab %s size=%u failed. Reason %d\n", 721 name, size, err); 722 723 s->refcount = -1; /* Exempt from merging for now */ 724 } 725 726 static struct kmem_cache *__init create_kmalloc_cache(const char *name, 727 unsigned int size, 728 slab_flags_t flags) 729 { 730 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT); 731 732 if (!s) 733 panic("Out of memory when creating slab %s\n", name); 734 735 create_boot_cache(s, name, size, flags | SLAB_KMALLOC, 0, size); 736 list_add(&s->list, &slab_caches); 737 s->refcount = 1; 738 return s; 739 } 740 741 kmem_buckets kmalloc_caches[NR_KMALLOC_TYPES] __ro_after_init = 742 { /* initialization for https://llvm.org/pr42570 */ }; 743 EXPORT_SYMBOL(kmalloc_caches); 744 745 #ifdef CONFIG_KMALLOC_PARTITION_RANDOM 746 unsigned long random_kmalloc_seed __ro_after_init; 747 EXPORT_SYMBOL(random_kmalloc_seed); 748 #endif 749 750 /* 751 * Conversion table for small slabs sizes / 8 to the index in the 752 * kmalloc array. This is necessary for slabs < 192 since we have non power 753 * of two cache sizes there. The size of larger slabs can be determined using 754 * fls. 755 */ 756 u8 kmalloc_size_index[24] __ro_after_init = { 757 3, /* 8 */ 758 4, /* 16 */ 759 5, /* 24 */ 760 5, /* 32 */ 761 6, /* 40 */ 762 6, /* 48 */ 763 6, /* 56 */ 764 6, /* 64 */ 765 1, /* 72 */ 766 1, /* 80 */ 767 1, /* 88 */ 768 1, /* 96 */ 769 7, /* 104 */ 770 7, /* 112 */ 771 7, /* 120 */ 772 7, /* 128 */ 773 2, /* 136 */ 774 2, /* 144 */ 775 2, /* 152 */ 776 2, /* 160 */ 777 2, /* 168 */ 778 2, /* 176 */ 779 2, /* 184 */ 780 2 /* 192 */ 781 }; 782 783 size_t kmalloc_size_roundup(size_t size) 784 { 785 if (size && size <= KMALLOC_MAX_CACHE_SIZE) { 786 struct kmem_cache *s; 787 788 /* 789 * The flags don't matter since size_index is common to all. 790 * Neither does the caller for just getting ->object_size. 791 */ 792 s = kmalloc_slab(size, NULL, GFP_KERNEL, __kmalloc_token(0), 793 SLAB_ALLOC_DEFAULT); 794 return s->object_size; 795 } 796 797 /* Above the smaller buckets, size is a multiple of page size. */ 798 if (size && size <= KMALLOC_MAX_SIZE) 799 return PAGE_SIZE << get_order(size); 800 801 /* 802 * Return 'size' for 0 - kmalloc() returns ZERO_SIZE_PTR 803 * and very large size - kmalloc() may fail. 804 */ 805 return size; 806 807 } 808 EXPORT_SYMBOL(kmalloc_size_roundup); 809 810 #ifdef CONFIG_ZONE_DMA 811 #define KMALLOC_DMA_NAME(sz) .name[KMALLOC_DMA] = "dma-kmalloc-" #sz, 812 #else 813 #define KMALLOC_DMA_NAME(sz) 814 #endif 815 816 #ifdef CONFIG_MEMCG 817 #define KMALLOC_CGROUP_NAME(sz) .name[KMALLOC_CGROUP] = "kmalloc-cg-" #sz, 818 #else 819 #define KMALLOC_CGROUP_NAME(sz) 820 #endif 821 822 #ifndef CONFIG_SLUB_TINY 823 #define KMALLOC_RCL_NAME(sz) .name[KMALLOC_RECLAIM] = "kmalloc-rcl-" #sz, 824 #else 825 #define KMALLOC_RCL_NAME(sz) 826 #endif 827 828 #ifdef CONFIG_KMALLOC_PARTITION_CACHES 829 #define __KMALLOC_PARTITION_CONCAT(a, b) a ## b 830 #define KMALLOC_PARTITION_NAME(N, sz) __KMALLOC_PARTITION_CONCAT(KMA_PART_, N)(sz) 831 #define KMA_PART_1(sz) .name[KMALLOC_PARTITION_START + 1] = "kmalloc-part-01-" #sz, 832 #define KMA_PART_2(sz) KMA_PART_1(sz) .name[KMALLOC_PARTITION_START + 2] = "kmalloc-part-02-" #sz, 833 #define KMA_PART_3(sz) KMA_PART_2(sz) .name[KMALLOC_PARTITION_START + 3] = "kmalloc-part-03-" #sz, 834 #define KMA_PART_4(sz) KMA_PART_3(sz) .name[KMALLOC_PARTITION_START + 4] = "kmalloc-part-04-" #sz, 835 #define KMA_PART_5(sz) KMA_PART_4(sz) .name[KMALLOC_PARTITION_START + 5] = "kmalloc-part-05-" #sz, 836 #define KMA_PART_6(sz) KMA_PART_5(sz) .name[KMALLOC_PARTITION_START + 6] = "kmalloc-part-06-" #sz, 837 #define KMA_PART_7(sz) KMA_PART_6(sz) .name[KMALLOC_PARTITION_START + 7] = "kmalloc-part-07-" #sz, 838 #define KMA_PART_8(sz) KMA_PART_7(sz) .name[KMALLOC_PARTITION_START + 8] = "kmalloc-part-08-" #sz, 839 #define KMA_PART_9(sz) KMA_PART_8(sz) .name[KMALLOC_PARTITION_START + 9] = "kmalloc-part-09-" #sz, 840 #define KMA_PART_10(sz) KMA_PART_9(sz) .name[KMALLOC_PARTITION_START + 10] = "kmalloc-part-10-" #sz, 841 #define KMA_PART_11(sz) KMA_PART_10(sz) .name[KMALLOC_PARTITION_START + 11] = "kmalloc-part-11-" #sz, 842 #define KMA_PART_12(sz) KMA_PART_11(sz) .name[KMALLOC_PARTITION_START + 12] = "kmalloc-part-12-" #sz, 843 #define KMA_PART_13(sz) KMA_PART_12(sz) .name[KMALLOC_PARTITION_START + 13] = "kmalloc-part-13-" #sz, 844 #define KMA_PART_14(sz) KMA_PART_13(sz) .name[KMALLOC_PARTITION_START + 14] = "kmalloc-part-14-" #sz, 845 #define KMA_PART_15(sz) KMA_PART_14(sz) .name[KMALLOC_PARTITION_START + 15] = "kmalloc-part-15-" #sz, 846 #else // CONFIG_KMALLOC_PARTITION_CACHES 847 #define KMALLOC_PARTITION_NAME(N, sz) 848 #endif 849 850 #ifdef CONFIG_SLAB_OBJ_EXT 851 #define KMALLOC_NO_OBJ_EXT_NAME(sz) .name[KMALLOC_NO_OBJ_EXT] = "kmalloc-no-objext-" #sz, 852 #else 853 #define KMALLOC_NO_OBJ_EXT_NAME(sz) 854 #endif 855 856 #define INIT_KMALLOC_INFO(__size, __short_size) \ 857 { \ 858 .name[KMALLOC_NORMAL] = "kmalloc-" #__short_size, \ 859 KMALLOC_RCL_NAME(__short_size) \ 860 KMALLOC_CGROUP_NAME(__short_size) \ 861 KMALLOC_DMA_NAME(__short_size) \ 862 KMALLOC_PARTITION_NAME(KMALLOC_PARTITION_CACHES_NR, __short_size) \ 863 KMALLOC_NO_OBJ_EXT_NAME(__short_size) \ 864 .size = __size, \ 865 } 866 867 /* 868 * kmalloc_info[] is to make slab_debug=,kmalloc-xx option work at boot time. 869 * kmalloc_index() supports up to 2^21=2MB, so the final entry of the table is 870 * kmalloc-2M. 871 */ 872 const struct kmalloc_info_struct kmalloc_info[] __initconst = { 873 INIT_KMALLOC_INFO(0, 0), 874 INIT_KMALLOC_INFO(96, 96), 875 INIT_KMALLOC_INFO(192, 192), 876 INIT_KMALLOC_INFO(8, 8), 877 INIT_KMALLOC_INFO(16, 16), 878 INIT_KMALLOC_INFO(32, 32), 879 INIT_KMALLOC_INFO(64, 64), 880 INIT_KMALLOC_INFO(128, 128), 881 INIT_KMALLOC_INFO(256, 256), 882 INIT_KMALLOC_INFO(512, 512), 883 INIT_KMALLOC_INFO(1024, 1k), 884 INIT_KMALLOC_INFO(2048, 2k), 885 INIT_KMALLOC_INFO(4096, 4k), 886 INIT_KMALLOC_INFO(8192, 8k), 887 INIT_KMALLOC_INFO(16384, 16k), 888 INIT_KMALLOC_INFO(32768, 32k), 889 INIT_KMALLOC_INFO(65536, 64k), 890 INIT_KMALLOC_INFO(131072, 128k), 891 INIT_KMALLOC_INFO(262144, 256k), 892 INIT_KMALLOC_INFO(524288, 512k), 893 INIT_KMALLOC_INFO(1048576, 1M), 894 INIT_KMALLOC_INFO(2097152, 2M) 895 }; 896 897 /* 898 * Patch up the size_index table if we have strange large alignment 899 * requirements for the kmalloc array. This is only the case for 900 * MIPS it seems. The standard arches will not generate any code here. 901 * 902 * Largest permitted alignment is 256 bytes due to the way we 903 * handle the index determination for the smaller caches. 904 * 905 * Make sure that nothing crazy happens if someone starts tinkering 906 * around with ARCH_KMALLOC_MINALIGN 907 */ 908 void __init setup_kmalloc_cache_index_table(void) 909 { 910 unsigned int i; 911 912 BUILD_BUG_ON(KMALLOC_MIN_SIZE > 256 || 913 !is_power_of_2(KMALLOC_MIN_SIZE)); 914 915 for (i = 8; i < KMALLOC_MIN_SIZE; i += 8) { 916 unsigned int elem = size_index_elem(i); 917 918 if (elem >= ARRAY_SIZE(kmalloc_size_index)) 919 break; 920 kmalloc_size_index[elem] = KMALLOC_SHIFT_LOW; 921 } 922 923 if (KMALLOC_MIN_SIZE >= 64) { 924 /* 925 * The 96 byte sized cache is not used if the alignment 926 * is 64 byte. 927 */ 928 for (i = 64 + 8; i <= 96; i += 8) 929 kmalloc_size_index[size_index_elem(i)] = 7; 930 931 } 932 933 if (KMALLOC_MIN_SIZE >= 128) { 934 /* 935 * The 192 byte sized cache is not used if the alignment 936 * is 128 byte. Redirect kmalloc to use the 256 byte cache 937 * instead. 938 */ 939 for (i = 128 + 8; i <= 192; i += 8) 940 kmalloc_size_index[size_index_elem(i)] = 8; 941 } 942 } 943 944 static unsigned int __kmalloc_minalign(void) 945 { 946 unsigned int minalign = dma_get_cache_alignment(); 947 948 if (IS_ENABLED(CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC) && 949 is_swiotlb_allocated()) 950 minalign = ARCH_KMALLOC_MINALIGN; 951 952 return max(minalign, arch_slab_minalign()); 953 } 954 955 static void __init 956 new_kmalloc_cache(int idx, enum kmalloc_cache_type type) 957 { 958 slab_flags_t flags = 0; 959 unsigned int minalign = __kmalloc_minalign(); 960 unsigned int aligned_size = kmalloc_info[idx].size; 961 int aligned_idx = idx; 962 963 if ((KMALLOC_RECLAIM != KMALLOC_NORMAL) && (type == KMALLOC_RECLAIM)) { 964 flags |= SLAB_RECLAIM_ACCOUNT; 965 } else if (IS_ENABLED(CONFIG_MEMCG) && (type == KMALLOC_CGROUP)) { 966 if (mem_cgroup_kmem_disabled()) { 967 kmalloc_caches[type][idx] = kmalloc_caches[KMALLOC_NORMAL][idx]; 968 return; 969 } 970 flags |= SLAB_ACCOUNT; 971 } else if (IS_ENABLED(CONFIG_SLAB_OBJ_EXT) && type == KMALLOC_NO_OBJ_EXT) { 972 if (!need_kmalloc_no_objext()) { 973 kmalloc_caches[type][idx] = kmalloc_caches[KMALLOC_NORMAL][idx]; 974 return; 975 } 976 flags |= SLAB_NO_OBJ_EXT | SLAB_NO_MERGE; 977 } else if (IS_ENABLED(CONFIG_ZONE_DMA) && (type == KMALLOC_DMA)) { 978 flags |= SLAB_CACHE_DMA; 979 } 980 981 #ifdef CONFIG_KMALLOC_PARTITION_CACHES 982 if (type >= KMALLOC_PARTITION_START && type <= KMALLOC_PARTITION_END) 983 flags |= SLAB_NO_MERGE; 984 #endif 985 986 /* 987 * If CONFIG_MEMCG is enabled, disable cache merging for 988 * KMALLOC_NORMAL caches. 989 */ 990 if (IS_ENABLED(CONFIG_MEMCG) && (type == KMALLOC_NORMAL)) 991 flags |= SLAB_NO_MERGE; 992 993 if (minalign > ARCH_KMALLOC_MINALIGN) { 994 aligned_size = ALIGN(aligned_size, minalign); 995 aligned_idx = __kmalloc_index(aligned_size, false); 996 } 997 998 if (!kmalloc_caches[type][aligned_idx]) 999 kmalloc_caches[type][aligned_idx] = create_kmalloc_cache( 1000 kmalloc_info[aligned_idx].name[type], 1001 aligned_size, flags); 1002 if (idx != aligned_idx) 1003 kmalloc_caches[type][idx] = kmalloc_caches[type][aligned_idx]; 1004 } 1005 1006 /* 1007 * Create the kmalloc array. Some of the regular kmalloc arrays 1008 * may already have been created because they were needed to 1009 * enable allocations for slab creation. 1010 */ 1011 void __init create_kmalloc_caches(void) 1012 { 1013 int i; 1014 enum kmalloc_cache_type type; 1015 1016 /* 1017 * Including KMALLOC_CGROUP if CONFIG_MEMCG defined 1018 */ 1019 for (type = KMALLOC_NORMAL; type < NR_KMALLOC_TYPES; type++) { 1020 /* Caches that are NOT of the two-to-the-power-of size. */ 1021 if (KMALLOC_MIN_SIZE <= 32) 1022 new_kmalloc_cache(1, type); 1023 if (KMALLOC_MIN_SIZE <= 64) 1024 new_kmalloc_cache(2, type); 1025 1026 /* Caches that are of the two-to-the-power-of size. */ 1027 for (i = KMALLOC_SHIFT_LOW; i <= KMALLOC_SHIFT_HIGH; i++) 1028 new_kmalloc_cache(i, type); 1029 } 1030 #ifdef CONFIG_KMALLOC_PARTITION_RANDOM 1031 random_kmalloc_seed = get_random_u64(); 1032 #endif 1033 1034 /* Kmalloc array is now usable */ 1035 slab_state = UP; 1036 1037 if (IS_ENABLED(CONFIG_SLAB_BUCKETS)) 1038 kmem_buckets_cache = kmem_cache_create("kmalloc_buckets", 1039 sizeof(kmem_buckets), 1040 0, SLAB_NO_MERGE, NULL); 1041 } 1042 1043 gfp_t kmalloc_fix_flags(gfp_t flags) 1044 { 1045 gfp_t invalid_mask = flags & GFP_SLAB_BUG_MASK; 1046 1047 flags &= ~GFP_SLAB_BUG_MASK; 1048 pr_warn("Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n", 1049 invalid_mask, &invalid_mask, flags, &flags); 1050 dump_stack(); 1051 1052 return flags; 1053 } 1054 1055 #ifdef CONFIG_SLAB_FREELIST_RANDOM 1056 /* Randomize a generic freelist */ 1057 static void freelist_randomize(unsigned int *list, 1058 unsigned int count) 1059 { 1060 unsigned int rand; 1061 unsigned int i; 1062 1063 for (i = 0; i < count; i++) 1064 list[i] = i; 1065 1066 /* Fisher-Yates shuffle */ 1067 for (i = count - 1; i > 0; i--) { 1068 rand = get_random_u32_below(i + 1); 1069 swap(list[i], list[rand]); 1070 } 1071 } 1072 1073 /* Create a random sequence per cache */ 1074 int cache_random_seq_create(struct kmem_cache *cachep, unsigned int count, 1075 gfp_t gfp) 1076 { 1077 1078 if (count < 2 || cachep->random_seq) 1079 return 0; 1080 1081 cachep->random_seq = kcalloc(count, sizeof(unsigned int), gfp); 1082 if (!cachep->random_seq) 1083 return -ENOMEM; 1084 1085 freelist_randomize(cachep->random_seq, count); 1086 return 0; 1087 } 1088 1089 /* Destroy the per-cache random freelist sequence */ 1090 void cache_random_seq_destroy(struct kmem_cache *cachep) 1091 { 1092 kfree(cachep->random_seq); 1093 cachep->random_seq = NULL; 1094 } 1095 #endif /* CONFIG_SLAB_FREELIST_RANDOM */ 1096 1097 #ifdef CONFIG_SLUB_DEBUG 1098 #define SLABINFO_RIGHTS (0400) 1099 1100 static void print_slabinfo_header(struct seq_file *m) 1101 { 1102 /* 1103 * Output format version, so at least we can change it 1104 * without _too_ many complaints. 1105 */ 1106 seq_puts(m, "slabinfo - version: 2.1\n"); 1107 seq_puts(m, "# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab>"); 1108 seq_puts(m, " : tunables <limit> <batchcount> <sharedfactor>"); 1109 seq_puts(m, " : slabdata <active_slabs> <num_slabs> <sharedavail>"); 1110 seq_putc(m, '\n'); 1111 } 1112 1113 static void *slab_start(struct seq_file *m, loff_t *pos) 1114 { 1115 mutex_lock(&slab_mutex); 1116 return seq_list_start(&slab_caches, *pos); 1117 } 1118 1119 static void *slab_next(struct seq_file *m, void *p, loff_t *pos) 1120 { 1121 return seq_list_next(p, &slab_caches, pos); 1122 } 1123 1124 static void slab_stop(struct seq_file *m, void *p) 1125 { 1126 mutex_unlock(&slab_mutex); 1127 } 1128 1129 static void cache_show(struct kmem_cache *s, struct seq_file *m) 1130 { 1131 struct slabinfo sinfo; 1132 1133 memset(&sinfo, 0, sizeof(sinfo)); 1134 get_slabinfo(s, &sinfo); 1135 1136 seq_printf(m, "%-17s %6lu %6lu %6u %4u %4d", 1137 s->name, sinfo.active_objs, sinfo.num_objs, s->size, 1138 sinfo.objects_per_slab, (1 << sinfo.cache_order)); 1139 1140 seq_printf(m, " : tunables %4u %4u %4u", 1141 sinfo.limit, sinfo.batchcount, sinfo.shared); 1142 seq_printf(m, " : slabdata %6lu %6lu %6lu", 1143 sinfo.active_slabs, sinfo.num_slabs, sinfo.shared_avail); 1144 seq_putc(m, '\n'); 1145 } 1146 1147 static int slab_show(struct seq_file *m, void *p) 1148 { 1149 struct kmem_cache *s = list_entry(p, struct kmem_cache, list); 1150 1151 if (p == slab_caches.next) 1152 print_slabinfo_header(m); 1153 cache_show(s, m); 1154 return 0; 1155 } 1156 1157 void dump_unreclaimable_slab(void) 1158 { 1159 struct kmem_cache *s; 1160 struct slabinfo sinfo; 1161 1162 /* 1163 * Here acquiring slab_mutex is risky since we don't prefer to get 1164 * sleep in oom path. But, without mutex hold, it may introduce a 1165 * risk of crash. 1166 * Use mutex_trylock to protect the list traverse, dump nothing 1167 * without acquiring the mutex. 1168 */ 1169 if (!mutex_trylock(&slab_mutex)) { 1170 pr_warn("excessive unreclaimable slab but cannot dump stats\n"); 1171 return; 1172 } 1173 1174 pr_info("Unreclaimable slab info:\n"); 1175 pr_info("Name Used Total\n"); 1176 1177 list_for_each_entry(s, &slab_caches, list) { 1178 if (s->flags & SLAB_RECLAIM_ACCOUNT) 1179 continue; 1180 1181 get_slabinfo(s, &sinfo); 1182 1183 if (sinfo.num_objs > 0) 1184 pr_info("%-17s %10luKB %10luKB\n", s->name, 1185 (sinfo.active_objs * s->size) / 1024, 1186 (sinfo.num_objs * s->size) / 1024); 1187 } 1188 mutex_unlock(&slab_mutex); 1189 } 1190 1191 /* 1192 * slabinfo_op - iterator that generates /proc/slabinfo 1193 * 1194 * Output layout: 1195 * cache-name 1196 * num-active-objs 1197 * total-objs 1198 * object size 1199 * num-active-slabs 1200 * total-slabs 1201 * num-pages-per-slab 1202 * + further values on SMP and with statistics enabled 1203 */ 1204 static const struct seq_operations slabinfo_op = { 1205 .start = slab_start, 1206 .next = slab_next, 1207 .stop = slab_stop, 1208 .show = slab_show, 1209 }; 1210 1211 static int slabinfo_open(struct inode *inode, struct file *file) 1212 { 1213 return seq_open(file, &slabinfo_op); 1214 } 1215 1216 static const struct proc_ops slabinfo_proc_ops = { 1217 .proc_flags = PROC_ENTRY_PERMANENT, 1218 .proc_open = slabinfo_open, 1219 .proc_read = seq_read, 1220 .proc_lseek = seq_lseek, 1221 .proc_release = seq_release, 1222 }; 1223 1224 static int __init slab_proc_init(void) 1225 { 1226 proc_create("slabinfo", SLABINFO_RIGHTS, NULL, &slabinfo_proc_ops); 1227 return 0; 1228 } 1229 module_init(slab_proc_init); 1230 1231 #endif /* CONFIG_SLUB_DEBUG */ 1232 1233 /** 1234 * kfree_sensitive - Clear sensitive information in memory before freeing 1235 * @p: object to free memory of 1236 * 1237 * The memory of the object @p points to is zeroed before freed. 1238 * If @p is %NULL, kfree_sensitive() does nothing. 1239 * 1240 * Note: this function zeroes the whole allocated buffer which can be a good 1241 * deal bigger than the requested buffer size passed to kmalloc(). So be 1242 * careful when using this function in performance sensitive code. 1243 */ 1244 void kfree_sensitive(const void *p) 1245 { 1246 size_t ks; 1247 void *mem = (void *)p; 1248 1249 ks = ksize(mem); 1250 if (ks) { 1251 kasan_unpoison_range(mem, ks); 1252 memzero_explicit(mem, ks); 1253 } 1254 kfree(mem); 1255 } 1256 EXPORT_SYMBOL(kfree_sensitive); 1257 1258 #ifdef CONFIG_BPF_SYSCALL 1259 #include <linux/btf.h> 1260 1261 __bpf_kfunc_start_defs(); 1262 1263 __bpf_kfunc struct kmem_cache *bpf_get_kmem_cache(u64 addr) 1264 { 1265 struct slab *slab; 1266 1267 if (!virt_addr_valid((void *)(long)addr)) 1268 return NULL; 1269 1270 slab = virt_to_slab((void *)(long)addr); 1271 return slab ? slab->slab_cache : NULL; 1272 } 1273 1274 __bpf_kfunc_end_defs(); 1275 #endif /* CONFIG_BPF_SYSCALL */ 1276 1277 /* Tracepoints definitions. */ 1278 EXPORT_TRACEPOINT_SYMBOL(kmalloc); 1279 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_alloc); 1280 EXPORT_TRACEPOINT_SYMBOL(kfree); 1281 EXPORT_TRACEPOINT_SYMBOL(kmem_cache_free); 1282 1283 #ifndef CONFIG_KVFREE_RCU_BATCHED 1284 1285 void kvfree_call_rcu(struct rcu_head *head, void *ptr) 1286 { 1287 if (head) { 1288 kasan_record_aux_stack(ptr); 1289 call_rcu(head, kvfree_rcu_cb); 1290 return; 1291 } 1292 1293 // kvfree_rcu(one_arg) call. 1294 might_sleep(); 1295 synchronize_rcu(); 1296 kvfree(ptr); 1297 } 1298 EXPORT_SYMBOL_GPL(kvfree_call_rcu); 1299 1300 void __init kvfree_rcu_init(void) 1301 { 1302 } 1303 1304 #else /* CONFIG_KVFREE_RCU_BATCHED */ 1305 1306 /* 1307 * This rcu parameter is runtime-read-only. It reflects 1308 * a minimum allowed number of objects which can be cached 1309 * per-CPU. Object size is equal to one page. This value 1310 * can be changed at boot time. 1311 */ 1312 static int rcu_min_cached_objs = 5; 1313 module_param(rcu_min_cached_objs, int, 0444); 1314 1315 // A page shrinker can ask for pages to be freed to make them 1316 // available for other parts of the system. This usually happens 1317 // under low memory conditions, and in that case we should also 1318 // defer page-cache filling for a short time period. 1319 // 1320 // The default value is 5 seconds, which is long enough to reduce 1321 // interference with the shrinker while it asks other systems to 1322 // drain their caches. 1323 static int rcu_delay_page_cache_fill_msec = 5000; 1324 module_param(rcu_delay_page_cache_fill_msec, int, 0444); 1325 1326 static struct workqueue_struct *rcu_reclaim_wq; 1327 1328 /* Maximum number of jiffies to wait before draining a batch. */ 1329 #define KFREE_DRAIN_JIFFIES (5 * HZ) 1330 #define KFREE_N_BATCHES 2 1331 #define FREE_N_CHANNELS 2 1332 1333 /** 1334 * struct kvfree_rcu_bulk_data - single block to store kvfree_rcu() pointers 1335 * @list: List node. All blocks are linked between each other 1336 * @gp_snap: Snapshot of RCU state for objects placed to this bulk 1337 * @nr_records: Number of active pointers in the array 1338 * @records: Array of the kvfree_rcu() pointers 1339 */ 1340 struct kvfree_rcu_bulk_data { 1341 struct list_head list; 1342 struct rcu_gp_oldstate gp_snap; 1343 unsigned long nr_records; 1344 void *records[] __counted_by(nr_records); 1345 }; 1346 1347 /* 1348 * This macro defines how many entries the "records" array 1349 * will contain. It is based on the fact that the size of 1350 * kvfree_rcu_bulk_data structure becomes exactly one page. 1351 */ 1352 #define KVFREE_BULK_MAX_ENTR \ 1353 ((PAGE_SIZE - sizeof(struct kvfree_rcu_bulk_data)) / sizeof(void *)) 1354 1355 /** 1356 * struct kfree_rcu_cpu_work - single batch of kfree_rcu() requests 1357 * @rcu_work: Let queue_rcu_work() invoke workqueue handler after grace period 1358 * @head_free: List of kfree_rcu() objects waiting for a grace period 1359 * @head_free_gp_snap: Grace-period snapshot to check for attempted premature frees. 1360 * @bulk_head_free: Bulk-List of kvfree_rcu() objects waiting for a grace period 1361 * @krcp: Pointer to @kfree_rcu_cpu structure 1362 */ 1363 1364 struct kfree_rcu_cpu_work { 1365 struct rcu_work rcu_work; 1366 struct rcu_head *head_free; 1367 struct rcu_gp_oldstate head_free_gp_snap; 1368 struct list_head bulk_head_free[FREE_N_CHANNELS]; 1369 struct kfree_rcu_cpu *krcp; 1370 }; 1371 1372 /** 1373 * struct kfree_rcu_cpu - batch up kfree_rcu() requests for RCU grace period 1374 * @head: List of kfree_rcu() objects not yet waiting for a grace period 1375 * @head_gp_snap: Snapshot of RCU state for objects placed to "@head" 1376 * @bulk_head: Bulk-List of kvfree_rcu() objects not yet waiting for a grace period 1377 * @krw_arr: Array of batches of kfree_rcu() objects waiting for a grace period 1378 * @lock: Synchronize access to this structure 1379 * @monitor_work: Promote @head to @head_free after KFREE_DRAIN_JIFFIES 1380 * @initialized: The @rcu_work fields have been initialized 1381 * @head_count: Number of objects in rcu_head singular list 1382 * @bulk_count: Number of objects in bulk-list 1383 * @bkvcache: 1384 * A simple cache list that contains objects for reuse purpose. 1385 * In order to save some per-cpu space the list is singular. 1386 * Even though it is lockless an access has to be protected by the 1387 * per-cpu lock. 1388 * @page_cache_work: A work to refill the cache when it is empty 1389 * @backoff_page_cache_fill: Delay cache refills 1390 * @work_in_progress: Indicates that page_cache_work is running 1391 * @hrtimer: A hrtimer for scheduling a page_cache_work 1392 * @nr_bkv_objs: number of allocated objects at @bkvcache. 1393 * 1394 * This is a per-CPU structure. The reason that it is not included in 1395 * the rcu_data structure is to permit this code to be extracted from 1396 * the RCU files. Such extraction could allow further optimization of 1397 * the interactions with the slab allocators. 1398 */ 1399 struct kfree_rcu_cpu { 1400 // Objects queued on a linked list 1401 // through their rcu_head structures. 1402 struct rcu_head *head; 1403 unsigned long head_gp_snap; 1404 atomic_t head_count; 1405 1406 // Objects queued on a bulk-list. 1407 struct list_head bulk_head[FREE_N_CHANNELS]; 1408 atomic_t bulk_count[FREE_N_CHANNELS]; 1409 1410 struct kfree_rcu_cpu_work krw_arr[KFREE_N_BATCHES]; 1411 raw_spinlock_t lock; 1412 struct delayed_work monitor_work; 1413 bool initialized; 1414 1415 struct delayed_work page_cache_work; 1416 atomic_t backoff_page_cache_fill; 1417 atomic_t work_in_progress; 1418 struct hrtimer hrtimer; 1419 1420 struct llist_head bkvcache; 1421 int nr_bkv_objs; 1422 }; 1423 1424 static DEFINE_PER_CPU(struct kfree_rcu_cpu, krc) = { 1425 .lock = __RAW_SPIN_LOCK_UNLOCKED(krc.lock), 1426 }; 1427 1428 static __always_inline void 1429 debug_rcu_bhead_unqueue(struct kvfree_rcu_bulk_data *bhead) 1430 { 1431 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD 1432 int i; 1433 1434 for (i = 0; i < bhead->nr_records; i++) 1435 debug_rcu_head_unqueue((struct rcu_head *)(bhead->records[i])); 1436 #endif 1437 } 1438 1439 static inline struct kfree_rcu_cpu * 1440 krc_this_cpu_lock(unsigned long *flags) 1441 { 1442 struct kfree_rcu_cpu *krcp; 1443 1444 local_irq_save(*flags); // For safely calling this_cpu_ptr(). 1445 krcp = this_cpu_ptr(&krc); 1446 raw_spin_lock(&krcp->lock); 1447 1448 return krcp; 1449 } 1450 1451 static inline void 1452 krc_this_cpu_unlock(struct kfree_rcu_cpu *krcp, unsigned long flags) 1453 { 1454 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1455 } 1456 1457 static inline struct kvfree_rcu_bulk_data * 1458 get_cached_bnode(struct kfree_rcu_cpu *krcp) 1459 { 1460 if (!krcp->nr_bkv_objs) 1461 return NULL; 1462 1463 WRITE_ONCE(krcp->nr_bkv_objs, krcp->nr_bkv_objs - 1); 1464 return (struct kvfree_rcu_bulk_data *) 1465 llist_del_first(&krcp->bkvcache); 1466 } 1467 1468 static inline bool 1469 put_cached_bnode(struct kfree_rcu_cpu *krcp, 1470 struct kvfree_rcu_bulk_data *bnode) 1471 { 1472 // Check the limit. 1473 if (krcp->nr_bkv_objs >= rcu_min_cached_objs) 1474 return false; 1475 1476 llist_add((struct llist_node *) bnode, &krcp->bkvcache); 1477 WRITE_ONCE(krcp->nr_bkv_objs, krcp->nr_bkv_objs + 1); 1478 return true; 1479 } 1480 1481 static int 1482 drain_page_cache(struct kfree_rcu_cpu *krcp) 1483 { 1484 unsigned long flags; 1485 struct llist_node *page_list, *pos, *n; 1486 int freed = 0; 1487 1488 if (!rcu_min_cached_objs) 1489 return 0; 1490 1491 raw_spin_lock_irqsave(&krcp->lock, flags); 1492 page_list = llist_del_all(&krcp->bkvcache); 1493 WRITE_ONCE(krcp->nr_bkv_objs, 0); 1494 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1495 1496 llist_for_each_safe(pos, n, page_list) { 1497 free_page((unsigned long)pos); 1498 freed++; 1499 } 1500 1501 return freed; 1502 } 1503 1504 static void 1505 kvfree_rcu_bulk(struct kfree_rcu_cpu *krcp, 1506 struct kvfree_rcu_bulk_data *bnode, int idx) 1507 { 1508 unsigned long flags; 1509 int i; 1510 1511 if (!WARN_ON_ONCE(!poll_state_synchronize_rcu_full(&bnode->gp_snap))) { 1512 debug_rcu_bhead_unqueue(bnode); 1513 rcu_lock_acquire(&rcu_callback_map); 1514 if (idx == 0) { // kmalloc() / kfree(). 1515 trace_rcu_invoke_kfree_bulk_callback( 1516 "slab", bnode->nr_records, 1517 bnode->records); 1518 1519 kfree_bulk(bnode->nr_records, bnode->records); 1520 } else { // vmalloc() / vfree(). 1521 for (i = 0; i < bnode->nr_records; i++) { 1522 trace_rcu_invoke_kvfree_callback( 1523 "slab", bnode->records[i], 0); 1524 1525 vfree(bnode->records[i]); 1526 } 1527 } 1528 rcu_lock_release(&rcu_callback_map); 1529 } 1530 1531 raw_spin_lock_irqsave(&krcp->lock, flags); 1532 if (put_cached_bnode(krcp, bnode)) 1533 bnode = NULL; 1534 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1535 1536 if (bnode) 1537 free_page((unsigned long) bnode); 1538 1539 cond_resched_tasks_rcu_qs(); 1540 } 1541 1542 static void 1543 kvfree_rcu_list(struct rcu_head *head) 1544 { 1545 struct rcu_head *next; 1546 1547 for (; head; head = next) { 1548 void *ptr = (void *) head->func; 1549 unsigned long offset = (void *) head - ptr; 1550 1551 next = head->next; 1552 debug_rcu_head_unqueue((struct rcu_head *)ptr); 1553 rcu_lock_acquire(&rcu_callback_map); 1554 trace_rcu_invoke_kvfree_callback("slab", head, offset); 1555 1556 kvfree(ptr); 1557 1558 rcu_lock_release(&rcu_callback_map); 1559 cond_resched_tasks_rcu_qs(); 1560 } 1561 } 1562 1563 /* 1564 * This function is invoked in workqueue context after a grace period. 1565 * It frees all the objects queued on ->bulk_head_free or ->head_free. 1566 */ 1567 static void kfree_rcu_work(struct work_struct *work) 1568 { 1569 unsigned long flags; 1570 struct kvfree_rcu_bulk_data *bnode, *n; 1571 struct list_head bulk_head[FREE_N_CHANNELS]; 1572 struct rcu_head *head; 1573 struct kfree_rcu_cpu *krcp; 1574 struct kfree_rcu_cpu_work *krwp; 1575 struct rcu_gp_oldstate head_gp_snap; 1576 int i; 1577 1578 krwp = container_of(to_rcu_work(work), 1579 struct kfree_rcu_cpu_work, rcu_work); 1580 krcp = krwp->krcp; 1581 1582 raw_spin_lock_irqsave(&krcp->lock, flags); 1583 // Channels 1 and 2. 1584 for (i = 0; i < FREE_N_CHANNELS; i++) 1585 list_replace_init(&krwp->bulk_head_free[i], &bulk_head[i]); 1586 1587 // Channel 3. 1588 head = krwp->head_free; 1589 krwp->head_free = NULL; 1590 head_gp_snap = krwp->head_free_gp_snap; 1591 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1592 1593 // Handle the first two channels. 1594 for (i = 0; i < FREE_N_CHANNELS; i++) { 1595 // Start from the tail page, so a GP is likely passed for it. 1596 list_for_each_entry_safe(bnode, n, &bulk_head[i], list) 1597 kvfree_rcu_bulk(krcp, bnode, i); 1598 } 1599 1600 /* 1601 * This is used when the "bulk" path can not be used for the 1602 * double-argument of kvfree_rcu(). This happens when the 1603 * page-cache is empty, which means that objects are instead 1604 * queued on a linked list through their rcu_head structures. 1605 * This list is named "Channel 3". 1606 */ 1607 if (head && !WARN_ON_ONCE(!poll_state_synchronize_rcu_full(&head_gp_snap))) 1608 kvfree_rcu_list(head); 1609 } 1610 1611 static bool kfree_rcu_sheaf(void *obj) 1612 { 1613 struct kmem_cache *s; 1614 struct slab *slab; 1615 1616 if (is_vmalloc_addr(obj)) 1617 return false; 1618 1619 slab = virt_to_slab(obj); 1620 if (unlikely(!slab)) 1621 return false; 1622 1623 s = slab->slab_cache; 1624 if (likely(!IS_ENABLED(CONFIG_NUMA) || slab_nid(slab) == numa_mem_id())) 1625 return __kfree_rcu_sheaf(s, obj); 1626 1627 return false; 1628 } 1629 1630 static bool 1631 need_offload_krc(struct kfree_rcu_cpu *krcp) 1632 { 1633 int i; 1634 1635 for (i = 0; i < FREE_N_CHANNELS; i++) 1636 if (!list_empty(&krcp->bulk_head[i])) 1637 return true; 1638 1639 return !!READ_ONCE(krcp->head); 1640 } 1641 1642 static bool 1643 need_wait_for_krwp_work(struct kfree_rcu_cpu_work *krwp) 1644 { 1645 int i; 1646 1647 for (i = 0; i < FREE_N_CHANNELS; i++) 1648 if (!list_empty(&krwp->bulk_head_free[i])) 1649 return true; 1650 1651 return !!krwp->head_free; 1652 } 1653 1654 static int krc_count(struct kfree_rcu_cpu *krcp) 1655 { 1656 int sum = atomic_read(&krcp->head_count); 1657 int i; 1658 1659 for (i = 0; i < FREE_N_CHANNELS; i++) 1660 sum += atomic_read(&krcp->bulk_count[i]); 1661 1662 return sum; 1663 } 1664 1665 static void 1666 __schedule_delayed_monitor_work(struct kfree_rcu_cpu *krcp) 1667 { 1668 long delay, delay_left; 1669 1670 delay = krc_count(krcp) >= KVFREE_BULK_MAX_ENTR ? 1:KFREE_DRAIN_JIFFIES; 1671 if (delayed_work_pending(&krcp->monitor_work)) { 1672 delay_left = krcp->monitor_work.timer.expires - jiffies; 1673 if (delay < delay_left) 1674 mod_delayed_work(rcu_reclaim_wq, &krcp->monitor_work, delay); 1675 return; 1676 } 1677 queue_delayed_work(rcu_reclaim_wq, &krcp->monitor_work, delay); 1678 } 1679 1680 static void 1681 schedule_delayed_monitor_work(struct kfree_rcu_cpu *krcp) 1682 { 1683 unsigned long flags; 1684 1685 raw_spin_lock_irqsave(&krcp->lock, flags); 1686 __schedule_delayed_monitor_work(krcp); 1687 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1688 } 1689 1690 static void 1691 kvfree_rcu_drain_ready(struct kfree_rcu_cpu *krcp) 1692 { 1693 struct list_head bulk_ready[FREE_N_CHANNELS]; 1694 struct kvfree_rcu_bulk_data *bnode, *n; 1695 struct rcu_head *head_ready = NULL; 1696 unsigned long flags; 1697 int i; 1698 1699 raw_spin_lock_irqsave(&krcp->lock, flags); 1700 for (i = 0; i < FREE_N_CHANNELS; i++) { 1701 INIT_LIST_HEAD(&bulk_ready[i]); 1702 1703 list_for_each_entry_safe_reverse(bnode, n, &krcp->bulk_head[i], list) { 1704 if (!poll_state_synchronize_rcu_full(&bnode->gp_snap)) 1705 break; 1706 1707 atomic_sub(bnode->nr_records, &krcp->bulk_count[i]); 1708 list_move(&bnode->list, &bulk_ready[i]); 1709 } 1710 } 1711 1712 if (krcp->head && poll_state_synchronize_rcu(krcp->head_gp_snap)) { 1713 head_ready = krcp->head; 1714 atomic_set(&krcp->head_count, 0); 1715 WRITE_ONCE(krcp->head, NULL); 1716 } 1717 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1718 1719 for (i = 0; i < FREE_N_CHANNELS; i++) { 1720 list_for_each_entry_safe(bnode, n, &bulk_ready[i], list) 1721 kvfree_rcu_bulk(krcp, bnode, i); 1722 } 1723 1724 if (head_ready) 1725 kvfree_rcu_list(head_ready); 1726 } 1727 1728 /* 1729 * Return: %true if a work is queued, %false otherwise. 1730 */ 1731 static bool 1732 kvfree_rcu_queue_batch(struct kfree_rcu_cpu *krcp) 1733 { 1734 unsigned long flags; 1735 bool queued = false; 1736 int i, j; 1737 1738 raw_spin_lock_irqsave(&krcp->lock, flags); 1739 1740 // Attempt to start a new batch. 1741 for (i = 0; i < KFREE_N_BATCHES; i++) { 1742 struct kfree_rcu_cpu_work *krwp = &(krcp->krw_arr[i]); 1743 1744 // Try to detach bulk_head or head and attach it, only when 1745 // all channels are free. Any channel is not free means at krwp 1746 // there is on-going rcu work to handle krwp's free business. 1747 if (need_wait_for_krwp_work(krwp)) 1748 continue; 1749 1750 // kvfree_rcu_drain_ready() might handle this krcp, if so give up. 1751 if (need_offload_krc(krcp)) { 1752 // Channel 1 corresponds to the SLAB-pointer bulk path. 1753 // Channel 2 corresponds to vmalloc-pointer bulk path. 1754 for (j = 0; j < FREE_N_CHANNELS; j++) { 1755 if (list_empty(&krwp->bulk_head_free[j])) { 1756 atomic_set(&krcp->bulk_count[j], 0); 1757 list_replace_init(&krcp->bulk_head[j], 1758 &krwp->bulk_head_free[j]); 1759 } 1760 } 1761 1762 // Channel 3 corresponds to both SLAB and vmalloc 1763 // objects queued on the linked list. 1764 if (!krwp->head_free) { 1765 krwp->head_free = krcp->head; 1766 get_state_synchronize_rcu_full(&krwp->head_free_gp_snap); 1767 atomic_set(&krcp->head_count, 0); 1768 WRITE_ONCE(krcp->head, NULL); 1769 } 1770 1771 // One work is per one batch, so there are three 1772 // "free channels", the batch can handle. Break 1773 // the loop since it is done with this CPU thus 1774 // queuing an RCU work is _always_ success here. 1775 queued = queue_rcu_work(rcu_reclaim_wq, &krwp->rcu_work); 1776 WARN_ON_ONCE(!queued); 1777 break; 1778 } 1779 } 1780 1781 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1782 return queued; 1783 } 1784 1785 /* 1786 * This function is invoked after the KFREE_DRAIN_JIFFIES timeout. 1787 */ 1788 static void kfree_rcu_monitor(struct work_struct *work) 1789 { 1790 struct kfree_rcu_cpu *krcp = container_of(work, 1791 struct kfree_rcu_cpu, monitor_work.work); 1792 1793 // Drain ready for reclaim. 1794 kvfree_rcu_drain_ready(krcp); 1795 1796 // Queue a batch for a rest. 1797 kvfree_rcu_queue_batch(krcp); 1798 1799 // If there is nothing to detach, it means that our job is 1800 // successfully done here. In case of having at least one 1801 // of the channels that is still busy we should rearm the 1802 // work to repeat an attempt. Because previous batches are 1803 // still in progress. 1804 if (need_offload_krc(krcp)) 1805 schedule_delayed_monitor_work(krcp); 1806 } 1807 1808 static void fill_page_cache_func(struct work_struct *work) 1809 { 1810 struct kvfree_rcu_bulk_data *bnode; 1811 struct kfree_rcu_cpu *krcp = 1812 container_of(work, struct kfree_rcu_cpu, 1813 page_cache_work.work); 1814 unsigned long flags; 1815 int nr_pages; 1816 bool pushed; 1817 int i; 1818 1819 nr_pages = atomic_read(&krcp->backoff_page_cache_fill) ? 1820 1 : rcu_min_cached_objs; 1821 1822 for (i = READ_ONCE(krcp->nr_bkv_objs); i < nr_pages; i++) { 1823 bnode = (struct kvfree_rcu_bulk_data *) 1824 __get_free_page(GFP_KERNEL | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN); 1825 1826 if (!bnode) 1827 break; 1828 1829 raw_spin_lock_irqsave(&krcp->lock, flags); 1830 pushed = put_cached_bnode(krcp, bnode); 1831 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1832 1833 if (!pushed) { 1834 free_page((unsigned long) bnode); 1835 break; 1836 } 1837 } 1838 1839 atomic_set(&krcp->work_in_progress, 0); 1840 atomic_set(&krcp->backoff_page_cache_fill, 0); 1841 } 1842 1843 // Record ptr in a page managed by krcp, with the pre-krc_this_cpu_lock() 1844 // state specified by flags. If can_alloc is true, the caller must 1845 // be schedulable and not be holding any locks or mutexes that might be 1846 // acquired by the memory allocator or anything that it might invoke. 1847 // Returns true if ptr was successfully recorded, else the caller must 1848 // use a fallback. 1849 static inline bool 1850 add_ptr_to_bulk_krc_lock(struct kfree_rcu_cpu **krcp, 1851 unsigned long *flags, void *ptr, bool can_alloc) 1852 { 1853 struct kvfree_rcu_bulk_data *bnode; 1854 int idx; 1855 1856 *krcp = krc_this_cpu_lock(flags); 1857 if (unlikely(!(*krcp)->initialized)) 1858 return false; 1859 1860 idx = !!is_vmalloc_addr(ptr); 1861 bnode = list_first_entry_or_null(&(*krcp)->bulk_head[idx], 1862 struct kvfree_rcu_bulk_data, list); 1863 1864 /* Check if a new block is required. */ 1865 if (!bnode || bnode->nr_records == KVFREE_BULK_MAX_ENTR) { 1866 bnode = get_cached_bnode(*krcp); 1867 if (!bnode && can_alloc) { 1868 krc_this_cpu_unlock(*krcp, *flags); 1869 1870 // __GFP_NORETRY - allows a light-weight direct reclaim 1871 // what is OK from minimizing of fallback hitting point of 1872 // view. Apart of that it forbids any OOM invoking what is 1873 // also beneficial since we are about to release memory soon. 1874 // 1875 // __GFP_NOMEMALLOC - prevents from consuming of all the 1876 // memory reserves. Please note we have a fallback path. 1877 // 1878 // __GFP_NOWARN - it is supposed that an allocation can 1879 // be failed under low memory or high memory pressure 1880 // scenarios. 1881 bnode = (struct kvfree_rcu_bulk_data *) 1882 __get_free_page(GFP_KERNEL | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN); 1883 raw_spin_lock_irqsave(&(*krcp)->lock, *flags); 1884 } 1885 1886 if (!bnode) 1887 return false; 1888 1889 // Initialize the new block and attach it. 1890 bnode->nr_records = 0; 1891 list_add(&bnode->list, &(*krcp)->bulk_head[idx]); 1892 } 1893 1894 // Finally insert and update the GP for this page. 1895 bnode->nr_records++; 1896 bnode->records[bnode->nr_records - 1] = ptr; 1897 get_state_synchronize_rcu_full(&bnode->gp_snap); 1898 atomic_inc(&(*krcp)->bulk_count[idx]); 1899 1900 return true; 1901 } 1902 1903 static enum hrtimer_restart 1904 schedule_page_work_fn(struct hrtimer *t) 1905 { 1906 struct kfree_rcu_cpu *krcp = 1907 container_of(t, struct kfree_rcu_cpu, hrtimer); 1908 1909 queue_delayed_work(system_highpri_wq, &krcp->page_cache_work, 0); 1910 return HRTIMER_NORESTART; 1911 } 1912 1913 static void 1914 run_page_cache_worker(struct kfree_rcu_cpu *krcp) 1915 { 1916 // If cache disabled, bail out. 1917 if (!rcu_min_cached_objs) 1918 return; 1919 1920 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING && 1921 !atomic_xchg(&krcp->work_in_progress, 1)) { 1922 if (atomic_read(&krcp->backoff_page_cache_fill)) { 1923 queue_delayed_work(rcu_reclaim_wq, 1924 &krcp->page_cache_work, 1925 msecs_to_jiffies(rcu_delay_page_cache_fill_msec)); 1926 } else { 1927 hrtimer_setup(&krcp->hrtimer, schedule_page_work_fn, CLOCK_MONOTONIC, 1928 HRTIMER_MODE_REL); 1929 hrtimer_start(&krcp->hrtimer, 0, HRTIMER_MODE_REL); 1930 } 1931 } 1932 } 1933 1934 void __init kfree_rcu_scheduler_running(void) 1935 { 1936 int cpu; 1937 1938 for_each_possible_cpu(cpu) { 1939 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 1940 1941 if (need_offload_krc(krcp)) 1942 schedule_delayed_monitor_work(krcp); 1943 } 1944 } 1945 1946 /* 1947 * Queue a request for lazy invocation of the appropriate free routine 1948 * after a grace period. Please note that three paths are maintained, 1949 * two for the common case using arrays of pointers and a third one that 1950 * is used only when the main paths cannot be used, for example, due to 1951 * memory pressure. 1952 * 1953 * Each kvfree_call_rcu() request is added to a batch. The batch will be drained 1954 * every KFREE_DRAIN_JIFFIES number of jiffies. All the objects in the batch will 1955 * be free'd in workqueue context. This allows us to: batch requests together to 1956 * reduce the number of grace periods during heavy kfree_rcu()/kvfree_rcu() load. 1957 */ 1958 void kvfree_call_rcu(struct rcu_head *head, void *ptr) 1959 { 1960 unsigned long flags; 1961 struct kfree_rcu_cpu *krcp; 1962 bool success; 1963 1964 /* 1965 * Please note there is a limitation for the head-less 1966 * variant, that is why there is a clear rule for such 1967 * objects: it can be used from might_sleep() context 1968 * only. For other places please embed an rcu_head to 1969 * your data. 1970 */ 1971 if (!head) 1972 might_sleep(); 1973 1974 if (!IS_ENABLED(CONFIG_PREEMPT_RT) && kfree_rcu_sheaf(ptr)) 1975 return; 1976 1977 // Queue the object but don't yet schedule the batch. 1978 if (debug_rcu_head_queue(ptr)) { 1979 // Probable double kfree_rcu(), just leak. 1980 WARN_ONCE(1, "%s(): Double-freed call. rcu_head %p\n", 1981 __func__, head); 1982 1983 // Mark as success and leave. 1984 return; 1985 } 1986 1987 kasan_record_aux_stack(ptr); 1988 success = add_ptr_to_bulk_krc_lock(&krcp, &flags, ptr, !head); 1989 if (!success) { 1990 run_page_cache_worker(krcp); 1991 1992 if (head == NULL) 1993 // Inline if kvfree_rcu(one_arg) call. 1994 goto unlock_return; 1995 1996 head->func = ptr; 1997 head->next = krcp->head; 1998 WRITE_ONCE(krcp->head, head); 1999 atomic_inc(&krcp->head_count); 2000 2001 // Take a snapshot for this krcp. 2002 krcp->head_gp_snap = get_state_synchronize_rcu(); 2003 success = true; 2004 } 2005 2006 /* 2007 * The kvfree_rcu() caller considers the pointer freed at this point 2008 * and likely removes any references to it. Since the actual slab 2009 * freeing (and kmemleak_free()) is deferred, tell kmemleak to ignore 2010 * this object (no scanning or false positives reporting). 2011 */ 2012 kmemleak_ignore(ptr); 2013 2014 // Set timer to drain after KFREE_DRAIN_JIFFIES. 2015 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING) 2016 __schedule_delayed_monitor_work(krcp); 2017 2018 unlock_return: 2019 krc_this_cpu_unlock(krcp, flags); 2020 2021 /* 2022 * Inline kvfree() after synchronize_rcu(). We can do 2023 * it from might_sleep() context only, so the current 2024 * CPU can pass the QS state. 2025 */ 2026 if (!success) { 2027 debug_rcu_head_unqueue((struct rcu_head *) ptr); 2028 synchronize_rcu(); 2029 kvfree(ptr); 2030 } 2031 } 2032 EXPORT_SYMBOL_GPL(kvfree_call_rcu); 2033 2034 static inline void __kvfree_rcu_barrier(void) 2035 { 2036 struct kfree_rcu_cpu_work *krwp; 2037 struct kfree_rcu_cpu *krcp; 2038 bool queued; 2039 int i, cpu; 2040 2041 /* 2042 * Firstly we detach objects and queue them over an RCU-batch 2043 * for all CPUs. Finally queued works are flushed for each CPU. 2044 * 2045 * Please note. If there are outstanding batches for a particular 2046 * CPU, those have to be finished first following by queuing a new. 2047 */ 2048 for_each_possible_cpu(cpu) { 2049 krcp = per_cpu_ptr(&krc, cpu); 2050 2051 /* 2052 * Check if this CPU has any objects which have been queued for a 2053 * new GP completion. If not(means nothing to detach), we are done 2054 * with it. If any batch is pending/running for this "krcp", below 2055 * per-cpu flush_rcu_work() waits its completion(see last step). 2056 */ 2057 if (!need_offload_krc(krcp)) 2058 continue; 2059 2060 while (1) { 2061 /* 2062 * If we are not able to queue a new RCU work it means: 2063 * - batches for this CPU are still in flight which should 2064 * be flushed first and then repeat; 2065 * - no objects to detach, because of concurrency. 2066 */ 2067 queued = kvfree_rcu_queue_batch(krcp); 2068 2069 /* 2070 * Bail out, if there is no need to offload this "krcp" 2071 * anymore. As noted earlier it can run concurrently. 2072 */ 2073 if (queued || !need_offload_krc(krcp)) 2074 break; 2075 2076 /* There are ongoing batches. */ 2077 for (i = 0; i < KFREE_N_BATCHES; i++) { 2078 krwp = &(krcp->krw_arr[i]); 2079 flush_rcu_work(&krwp->rcu_work); 2080 } 2081 } 2082 } 2083 2084 /* 2085 * Now we guarantee that all objects are flushed. 2086 */ 2087 for_each_possible_cpu(cpu) { 2088 krcp = per_cpu_ptr(&krc, cpu); 2089 2090 /* 2091 * A monitor work can drain ready to reclaim objects 2092 * directly. Wait its completion if running or pending. 2093 */ 2094 cancel_delayed_work_sync(&krcp->monitor_work); 2095 2096 for (i = 0; i < KFREE_N_BATCHES; i++) { 2097 krwp = &(krcp->krw_arr[i]); 2098 flush_rcu_work(&krwp->rcu_work); 2099 } 2100 } 2101 } 2102 2103 /** 2104 * kvfree_rcu_barrier - Wait until all in-flight kvfree_rcu() complete. 2105 * 2106 * Note that a single argument of kvfree_rcu() call has a slow path that 2107 * triggers synchronize_rcu() following by freeing a pointer. It is done 2108 * before the return from the function. Therefore for any single-argument 2109 * call that will result in a kfree() to a cache that is to be destroyed 2110 * during module exit, it is developer's responsibility to ensure that all 2111 * such calls have returned before the call to kmem_cache_destroy(). 2112 */ 2113 void kvfree_rcu_barrier(void) 2114 { 2115 flush_all_rcu_sheaves(); 2116 __kvfree_rcu_barrier(); 2117 } 2118 EXPORT_SYMBOL_GPL(kvfree_rcu_barrier); 2119 2120 /** 2121 * kvfree_rcu_barrier_on_cache - Wait for in-flight kvfree_rcu() calls on a 2122 * specific slab cache. 2123 * @s: slab cache to wait for 2124 * 2125 * See the description of kvfree_rcu_barrier() for details. 2126 */ 2127 void kvfree_rcu_barrier_on_cache(struct kmem_cache *s) 2128 { 2129 if (cache_has_sheaves(s)) { 2130 cpus_read_lock(); 2131 flush_rcu_sheaves_on_cache(s); 2132 cpus_read_unlock(); 2133 rcu_barrier(); 2134 } 2135 2136 /* 2137 * TODO: Introduce a version of __kvfree_rcu_barrier() that works 2138 * on a specific slab cache. 2139 */ 2140 __kvfree_rcu_barrier(); 2141 } 2142 EXPORT_SYMBOL_GPL(kvfree_rcu_barrier_on_cache); 2143 2144 static unsigned long 2145 kfree_rcu_shrink_count(struct shrinker *shrink, struct shrink_control *sc) 2146 { 2147 int cpu; 2148 unsigned long count = 0; 2149 2150 /* Snapshot count of all CPUs */ 2151 for_each_possible_cpu(cpu) { 2152 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2153 2154 count += krc_count(krcp); 2155 count += READ_ONCE(krcp->nr_bkv_objs); 2156 atomic_set(&krcp->backoff_page_cache_fill, 1); 2157 } 2158 2159 return count == 0 ? SHRINK_EMPTY : count; 2160 } 2161 2162 static unsigned long 2163 kfree_rcu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) 2164 { 2165 int cpu, freed = 0; 2166 2167 for_each_possible_cpu(cpu) { 2168 int count; 2169 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2170 2171 count = krc_count(krcp); 2172 count += drain_page_cache(krcp); 2173 kfree_rcu_monitor(&krcp->monitor_work.work); 2174 2175 sc->nr_to_scan -= count; 2176 freed += count; 2177 2178 if (sc->nr_to_scan <= 0) 2179 break; 2180 } 2181 2182 return freed == 0 ? SHRINK_STOP : freed; 2183 } 2184 2185 void __init kvfree_rcu_init(void) 2186 { 2187 int cpu; 2188 int i, j; 2189 struct shrinker *kfree_rcu_shrinker; 2190 2191 rcu_reclaim_wq = alloc_workqueue("kvfree_rcu_reclaim", 2192 WQ_UNBOUND | WQ_MEM_RECLAIM, 0); 2193 WARN_ON(!rcu_reclaim_wq); 2194 2195 /* Clamp it to [0:100] seconds interval. */ 2196 if (rcu_delay_page_cache_fill_msec < 0 || 2197 rcu_delay_page_cache_fill_msec > 100 * MSEC_PER_SEC) { 2198 2199 rcu_delay_page_cache_fill_msec = 2200 clamp(rcu_delay_page_cache_fill_msec, 0, 2201 (int) (100 * MSEC_PER_SEC)); 2202 2203 pr_info("Adjusting rcutree.rcu_delay_page_cache_fill_msec to %d ms.\n", 2204 rcu_delay_page_cache_fill_msec); 2205 } 2206 2207 for_each_possible_cpu(cpu) { 2208 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2209 2210 for (i = 0; i < KFREE_N_BATCHES; i++) { 2211 INIT_RCU_WORK(&krcp->krw_arr[i].rcu_work, kfree_rcu_work); 2212 krcp->krw_arr[i].krcp = krcp; 2213 2214 for (j = 0; j < FREE_N_CHANNELS; j++) 2215 INIT_LIST_HEAD(&krcp->krw_arr[i].bulk_head_free[j]); 2216 } 2217 2218 for (i = 0; i < FREE_N_CHANNELS; i++) 2219 INIT_LIST_HEAD(&krcp->bulk_head[i]); 2220 2221 INIT_DELAYED_WORK(&krcp->monitor_work, kfree_rcu_monitor); 2222 INIT_DELAYED_WORK(&krcp->page_cache_work, fill_page_cache_func); 2223 krcp->initialized = true; 2224 } 2225 2226 kfree_rcu_shrinker = shrinker_alloc(0, "slab-kvfree-rcu"); 2227 if (!kfree_rcu_shrinker) { 2228 pr_err("Failed to allocate kfree_rcu() shrinker!\n"); 2229 return; 2230 } 2231 2232 kfree_rcu_shrinker->count_objects = kfree_rcu_shrink_count; 2233 kfree_rcu_shrinker->scan_objects = kfree_rcu_shrink_scan; 2234 2235 shrinker_register(kfree_rcu_shrinker); 2236 } 2237 2238 #endif /* CONFIG_KVFREE_RCU_BATCHED */ 2239