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