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 = kzalloc_objs(unsigned int, count, 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 /* Keep the prefix inherited from RCU */ 1371 #undef MODULE_PARAM_PREFIX 1372 #define MODULE_PARAM_PREFIX "rcutree." 1373 1374 /* 1375 * This rcu parameter is runtime-read-only. It reflects 1376 * a minimum allowed number of objects which can be cached 1377 * per-CPU. Object size is equal to one page. This value 1378 * can be changed at boot time. 1379 */ 1380 static int rcu_min_cached_objs = 5; 1381 module_param(rcu_min_cached_objs, int, 0444); 1382 1383 // A page shrinker can ask for pages to be freed to make them 1384 // available for other parts of the system. This usually happens 1385 // under low memory conditions, and in that case we should also 1386 // defer page-cache filling for a short time period. 1387 // 1388 // The default value is 5 seconds, which is long enough to reduce 1389 // interference with the shrinker while it asks other systems to 1390 // drain their caches. 1391 static int rcu_delay_page_cache_fill_msec = 5000; 1392 module_param(rcu_delay_page_cache_fill_msec, int, 0444); 1393 1394 static struct workqueue_struct *rcu_reclaim_wq; 1395 1396 /* Maximum number of jiffies to wait before draining a batch. */ 1397 #define KFREE_DRAIN_JIFFIES (5 * HZ) 1398 #define KFREE_N_BATCHES 2 1399 #define FREE_N_CHANNELS 2 1400 1401 /** 1402 * struct kvfree_rcu_bulk_data - single block to store kvfree_rcu() pointers 1403 * @list: List node. All blocks are linked between each other 1404 * @gp_snap: Snapshot of RCU state for objects placed to this bulk 1405 * @nr_records: Number of active pointers in the array 1406 * @records: Array of the kvfree_rcu() pointers 1407 */ 1408 struct kvfree_rcu_bulk_data { 1409 struct list_head list; 1410 struct rcu_gp_seq gp_snap; 1411 unsigned long nr_records; 1412 void *records[] __counted_by(nr_records); 1413 }; 1414 1415 /* 1416 * This macro defines how many entries the "records" array 1417 * will contain. It is based on the fact that the size of 1418 * kvfree_rcu_bulk_data structure becomes exactly one page. 1419 */ 1420 #define KVFREE_BULK_MAX_ENTR \ 1421 ((PAGE_SIZE - sizeof(struct kvfree_rcu_bulk_data)) / sizeof(void *)) 1422 1423 /** 1424 * struct kfree_rcu_cpu_work - single batch of kfree_rcu() requests 1425 * @rcu_work: Let queue_rcu_work() invoke workqueue handler after grace period 1426 * @head_free: List of kfree_rcu() objects waiting for a grace period 1427 * @head_free_gp_snap: Grace-period snapshot to check for attempted premature frees. 1428 * @bulk_head_free: Bulk-List of kvfree_rcu() objects waiting for a grace period 1429 * @krcp: Pointer to @kfree_rcu_cpu structure 1430 */ 1431 1432 struct kfree_rcu_cpu_work { 1433 struct rcu_work rcu_work; 1434 struct kvfree_rcu_head *head_free; 1435 struct rcu_gp_seq head_free_gp_snap; 1436 struct list_head bulk_head_free[FREE_N_CHANNELS]; 1437 struct kfree_rcu_cpu *krcp; 1438 }; 1439 1440 /** 1441 * struct kfree_rcu_cpu - batch up kfree_rcu() requests for RCU grace period 1442 * @head: List of kfree_rcu() objects not yet waiting for a grace period 1443 * @head_gp_snap: Snapshot of RCU state for objects placed to "@head" 1444 * @bulk_head: Bulk-List of kvfree_rcu() objects not yet waiting for a grace period 1445 * @krw_arr: Array of batches of kfree_rcu() objects waiting for a grace period 1446 * @lock: Synchronize access to this structure 1447 * @monitor_work: Promote @head to @head_free after KFREE_DRAIN_JIFFIES 1448 * @initialized: The @rcu_work fields have been initialized 1449 * @head_count: Number of objects in rcu_head singular list 1450 * @bulk_count: Number of objects in bulk-list 1451 * @bkvcache: 1452 * A simple cache list that contains objects for reuse purpose. 1453 * In order to save some per-cpu space the list is singular. 1454 * Even though it is lockless an access has to be protected by the 1455 * per-cpu lock. 1456 * @page_cache_work: A work to refill the cache when it is empty 1457 * @backoff_page_cache_fill: Delay cache refills 1458 * @work_in_progress: Indicates that page_cache_work is running 1459 * @hrtimer: A hrtimer for scheduling a page_cache_work 1460 * @nr_bkv_objs: number of allocated objects at @bkvcache. 1461 * 1462 * This is a per-CPU structure. The reason that it is not included in 1463 * the rcu_data structure is to permit this code to be extracted from 1464 * the RCU files. Such extraction could allow further optimization of 1465 * the interactions with the slab allocators. 1466 */ 1467 struct kfree_rcu_cpu { 1468 // Objects queued on a linked list 1469 // through their rcu_head structures. 1470 struct kvfree_rcu_head *head; 1471 unsigned long head_gp_snap; 1472 atomic_t head_count; 1473 1474 // Objects queued on a bulk-list. 1475 struct list_head bulk_head[FREE_N_CHANNELS]; 1476 atomic_t bulk_count[FREE_N_CHANNELS]; 1477 1478 struct kfree_rcu_cpu_work krw_arr[KFREE_N_BATCHES]; 1479 raw_spinlock_t lock; 1480 struct delayed_work monitor_work; 1481 bool initialized; 1482 1483 struct delayed_work page_cache_work; 1484 atomic_t backoff_page_cache_fill; 1485 atomic_t work_in_progress; 1486 struct hrtimer hrtimer; 1487 1488 struct llist_head bkvcache; 1489 int nr_bkv_objs; 1490 }; 1491 1492 static DEFINE_PER_CPU(struct kfree_rcu_cpu, krc) = { 1493 .lock = __RAW_SPIN_LOCK_UNLOCKED(krc.lock), 1494 }; 1495 1496 static __always_inline void 1497 debug_rcu_bhead_unqueue(struct kvfree_rcu_bulk_data *bhead) 1498 { 1499 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD 1500 int i; 1501 1502 for (i = 0; i < bhead->nr_records; i++) 1503 debug_rcu_head_unqueue((struct rcu_head *)(bhead->records[i])); 1504 #endif 1505 } 1506 1507 static inline struct kfree_rcu_cpu * 1508 krc_this_cpu_lock(unsigned long *flags) 1509 { 1510 struct kfree_rcu_cpu *krcp; 1511 1512 local_irq_save(*flags); // For safely calling this_cpu_ptr(). 1513 krcp = this_cpu_ptr(&krc); 1514 raw_spin_lock(&krcp->lock); 1515 1516 return krcp; 1517 } 1518 1519 static inline void 1520 krc_this_cpu_unlock(struct kfree_rcu_cpu *krcp, unsigned long flags) 1521 { 1522 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1523 } 1524 1525 static inline struct kvfree_rcu_bulk_data * 1526 get_cached_bnode(struct kfree_rcu_cpu *krcp) 1527 { 1528 if (!krcp->nr_bkv_objs) 1529 return NULL; 1530 1531 WRITE_ONCE(krcp->nr_bkv_objs, krcp->nr_bkv_objs - 1); 1532 return (struct kvfree_rcu_bulk_data *) 1533 llist_del_first(&krcp->bkvcache); 1534 } 1535 1536 static inline bool 1537 put_cached_bnode(struct kfree_rcu_cpu *krcp, 1538 struct kvfree_rcu_bulk_data *bnode) 1539 { 1540 // Check the limit. 1541 if (krcp->nr_bkv_objs >= rcu_min_cached_objs) 1542 return false; 1543 1544 llist_add((struct llist_node *) bnode, &krcp->bkvcache); 1545 WRITE_ONCE(krcp->nr_bkv_objs, krcp->nr_bkv_objs + 1); 1546 return true; 1547 } 1548 1549 static int 1550 drain_page_cache(struct kfree_rcu_cpu *krcp) 1551 { 1552 unsigned long flags; 1553 struct llist_node *page_list, *pos, *n; 1554 int freed = 0; 1555 1556 if (!rcu_min_cached_objs) 1557 return 0; 1558 1559 raw_spin_lock_irqsave(&krcp->lock, flags); 1560 page_list = llist_del_all(&krcp->bkvcache); 1561 WRITE_ONCE(krcp->nr_bkv_objs, 0); 1562 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1563 1564 llist_for_each_safe(pos, n, page_list) { 1565 free_page((unsigned long)pos); 1566 freed++; 1567 } 1568 1569 return freed; 1570 } 1571 1572 static void 1573 kvfree_rcu_bulk(struct kfree_rcu_cpu *krcp, 1574 struct kvfree_rcu_bulk_data *bnode, int idx) 1575 { 1576 unsigned long flags; 1577 int i; 1578 1579 if (!WARN_ON_ONCE(!poll_state_synchronize_rcu_full(&bnode->gp_snap))) { 1580 debug_rcu_bhead_unqueue(bnode); 1581 rcu_lock_acquire(&rcu_callback_map); 1582 if (idx == 0) { // kmalloc() / kfree(). 1583 trace_rcu_invoke_kfree_bulk_callback( 1584 "slab", bnode->nr_records, 1585 bnode->records); 1586 1587 kfree_bulk(bnode->nr_records, bnode->records); 1588 } else { // vmalloc() / vfree(). 1589 for (i = 0; i < bnode->nr_records; i++) { 1590 trace_rcu_invoke_kvfree_callback( 1591 "slab", bnode->records[i], 0); 1592 1593 vfree(bnode->records[i]); 1594 } 1595 } 1596 rcu_lock_release(&rcu_callback_map); 1597 } 1598 1599 raw_spin_lock_irqsave(&krcp->lock, flags); 1600 if (put_cached_bnode(krcp, bnode)) 1601 bnode = NULL; 1602 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1603 1604 if (bnode) 1605 free_page((unsigned long) bnode); 1606 1607 cond_resched_tasks_rcu_qs(); 1608 } 1609 1610 static void 1611 kvfree_rcu_list(struct kvfree_rcu_head *head) 1612 { 1613 struct kvfree_rcu_head *next; 1614 1615 for (; head; head = next) { 1616 void *ptr = kvmalloc_obj_start_addr(head); 1617 unsigned long offset = (void *) head - ptr; 1618 1619 next = head->next; 1620 debug_rcu_head_unqueue((struct rcu_head *)ptr); 1621 rcu_lock_acquire(&rcu_callback_map); 1622 trace_rcu_invoke_kvfree_callback("slab", head, offset); 1623 1624 kvfree(ptr); 1625 1626 rcu_lock_release(&rcu_callback_map); 1627 cond_resched_tasks_rcu_qs(); 1628 } 1629 } 1630 1631 /* 1632 * This function is invoked in workqueue context after a grace period. 1633 * It frees all the objects queued on ->bulk_head_free or ->head_free. 1634 */ 1635 static void kfree_rcu_work(struct work_struct *work) 1636 { 1637 unsigned long flags; 1638 struct kvfree_rcu_bulk_data *bnode, *n; 1639 struct list_head bulk_head[FREE_N_CHANNELS]; 1640 struct kvfree_rcu_head *head; 1641 struct kfree_rcu_cpu *krcp; 1642 struct kfree_rcu_cpu_work *krwp; 1643 struct rcu_gp_seq head_gp_snap; 1644 int i; 1645 1646 krwp = container_of(to_rcu_work(work), 1647 struct kfree_rcu_cpu_work, rcu_work); 1648 krcp = krwp->krcp; 1649 1650 raw_spin_lock_irqsave(&krcp->lock, flags); 1651 // Channels 1 and 2. 1652 for (i = 0; i < FREE_N_CHANNELS; i++) 1653 list_replace_init(&krwp->bulk_head_free[i], &bulk_head[i]); 1654 1655 // Channel 3. 1656 head = krwp->head_free; 1657 krwp->head_free = NULL; 1658 head_gp_snap = krwp->head_free_gp_snap; 1659 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1660 1661 // Handle the first two channels. 1662 for (i = 0; i < FREE_N_CHANNELS; i++) { 1663 // Start from the tail page, so a GP is likely passed for it. 1664 list_for_each_entry_safe(bnode, n, &bulk_head[i], list) 1665 kvfree_rcu_bulk(krcp, bnode, i); 1666 } 1667 1668 /* 1669 * This is used when the "bulk" path can not be used for the 1670 * double-argument of kvfree_rcu(). This happens when the 1671 * page-cache is empty, which means that objects are instead 1672 * queued on a linked list through their rcu_head structures. 1673 * This list is named "Channel 3". 1674 */ 1675 if (head && !WARN_ON_ONCE(!poll_state_synchronize_rcu_full(&head_gp_snap))) 1676 kvfree_rcu_list(head); 1677 } 1678 1679 static bool kfree_rcu_sheaf(void *obj) 1680 { 1681 struct kmem_cache *s; 1682 struct slab *slab; 1683 1684 if (is_vmalloc_addr(obj)) 1685 return false; 1686 1687 slab = virt_to_slab(obj); 1688 if (unlikely(!slab)) 1689 return false; 1690 1691 s = slab->slab_cache; 1692 if (likely(!IS_ENABLED(CONFIG_NUMA) || slab_nid(slab) == numa_mem_id())) 1693 return __kfree_rcu_sheaf(s, obj, SLAB_FREE_DEFAULT); 1694 1695 return false; 1696 } 1697 1698 static bool 1699 need_offload_krc(struct kfree_rcu_cpu *krcp) 1700 { 1701 int i; 1702 1703 for (i = 0; i < FREE_N_CHANNELS; i++) 1704 if (!list_empty(&krcp->bulk_head[i])) 1705 return true; 1706 1707 return !!READ_ONCE(krcp->head); 1708 } 1709 1710 static bool 1711 need_wait_for_krwp_work(struct kfree_rcu_cpu_work *krwp) 1712 { 1713 int i; 1714 1715 for (i = 0; i < FREE_N_CHANNELS; i++) 1716 if (!list_empty(&krwp->bulk_head_free[i])) 1717 return true; 1718 1719 return !!krwp->head_free; 1720 } 1721 1722 static int krc_count(struct kfree_rcu_cpu *krcp) 1723 { 1724 int sum = atomic_read(&krcp->head_count); 1725 int i; 1726 1727 for (i = 0; i < FREE_N_CHANNELS; i++) 1728 sum += atomic_read(&krcp->bulk_count[i]); 1729 1730 return sum; 1731 } 1732 1733 static void 1734 __schedule_delayed_monitor_work(struct kfree_rcu_cpu *krcp) 1735 { 1736 long delay, delay_left; 1737 1738 delay = krc_count(krcp) >= KVFREE_BULK_MAX_ENTR ? 1:KFREE_DRAIN_JIFFIES; 1739 if (delayed_work_pending(&krcp->monitor_work)) { 1740 delay_left = krcp->monitor_work.timer.expires - jiffies; 1741 if (delay < delay_left) 1742 mod_delayed_work(rcu_reclaim_wq, &krcp->monitor_work, delay); 1743 return; 1744 } 1745 queue_delayed_work(rcu_reclaim_wq, &krcp->monitor_work, delay); 1746 } 1747 1748 static void 1749 schedule_delayed_monitor_work(struct kfree_rcu_cpu *krcp) 1750 { 1751 unsigned long flags; 1752 1753 raw_spin_lock_irqsave(&krcp->lock, flags); 1754 __schedule_delayed_monitor_work(krcp); 1755 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1756 } 1757 1758 static void 1759 kvfree_rcu_drain_ready(struct kfree_rcu_cpu *krcp) 1760 { 1761 struct list_head bulk_ready[FREE_N_CHANNELS]; 1762 struct kvfree_rcu_bulk_data *bnode, *n; 1763 struct kvfree_rcu_head *head_ready = NULL; 1764 unsigned long flags; 1765 int i; 1766 1767 raw_spin_lock_irqsave(&krcp->lock, flags); 1768 for (i = 0; i < FREE_N_CHANNELS; i++) { 1769 INIT_LIST_HEAD(&bulk_ready[i]); 1770 1771 list_for_each_entry_safe_reverse(bnode, n, &krcp->bulk_head[i], list) { 1772 if (!poll_state_synchronize_rcu_full(&bnode->gp_snap)) 1773 break; 1774 1775 atomic_sub(bnode->nr_records, &krcp->bulk_count[i]); 1776 list_move(&bnode->list, &bulk_ready[i]); 1777 } 1778 } 1779 1780 if (krcp->head && poll_state_synchronize_rcu(krcp->head_gp_snap)) { 1781 head_ready = krcp->head; 1782 atomic_set(&krcp->head_count, 0); 1783 WRITE_ONCE(krcp->head, NULL); 1784 } 1785 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1786 1787 for (i = 0; i < FREE_N_CHANNELS; i++) { 1788 list_for_each_entry_safe(bnode, n, &bulk_ready[i], list) 1789 kvfree_rcu_bulk(krcp, bnode, i); 1790 } 1791 1792 if (head_ready) 1793 kvfree_rcu_list(head_ready); 1794 } 1795 1796 /* 1797 * Return: %true if a work is queued, %false otherwise. 1798 */ 1799 static bool 1800 kvfree_rcu_queue_batch(struct kfree_rcu_cpu *krcp) 1801 { 1802 unsigned long flags; 1803 bool queued = false; 1804 int i, j; 1805 1806 raw_spin_lock_irqsave(&krcp->lock, flags); 1807 1808 // Attempt to start a new batch. 1809 for (i = 0; i < KFREE_N_BATCHES; i++) { 1810 struct kfree_rcu_cpu_work *krwp = &(krcp->krw_arr[i]); 1811 1812 // Try to detach bulk_head or head and attach it, only when 1813 // all channels are free. Any channel is not free means at krwp 1814 // there is on-going rcu work to handle krwp's free business. 1815 if (need_wait_for_krwp_work(krwp)) 1816 continue; 1817 1818 // kvfree_rcu_drain_ready() might handle this krcp, if so give up. 1819 if (need_offload_krc(krcp)) { 1820 // Channel 1 corresponds to the SLAB-pointer bulk path. 1821 // Channel 2 corresponds to vmalloc-pointer bulk path. 1822 for (j = 0; j < FREE_N_CHANNELS; j++) { 1823 if (list_empty(&krwp->bulk_head_free[j])) { 1824 atomic_set(&krcp->bulk_count[j], 0); 1825 list_replace_init(&krcp->bulk_head[j], 1826 &krwp->bulk_head_free[j]); 1827 } 1828 } 1829 1830 // Channel 3 corresponds to both SLAB and vmalloc 1831 // objects queued on the linked list. 1832 if (!krwp->head_free) { 1833 krwp->head_free = krcp->head; 1834 get_state_synchronize_rcu_full(&krwp->head_free_gp_snap); 1835 atomic_set(&krcp->head_count, 0); 1836 WRITE_ONCE(krcp->head, NULL); 1837 } 1838 1839 // One work is per one batch, so there are three 1840 // "free channels", the batch can handle. Break 1841 // the loop since it is done with this CPU thus 1842 // queuing an RCU work is _always_ success here. 1843 queued = queue_rcu_work(rcu_reclaim_wq, &krwp->rcu_work); 1844 WARN_ON_ONCE(!queued); 1845 break; 1846 } 1847 } 1848 1849 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1850 return queued; 1851 } 1852 1853 /* 1854 * This function is invoked after the KFREE_DRAIN_JIFFIES timeout. 1855 */ 1856 static void kfree_rcu_monitor(struct work_struct *work) 1857 { 1858 struct kfree_rcu_cpu *krcp = container_of(work, 1859 struct kfree_rcu_cpu, monitor_work.work); 1860 1861 // Drain ready for reclaim. 1862 kvfree_rcu_drain_ready(krcp); 1863 1864 // Queue a batch for a rest. 1865 kvfree_rcu_queue_batch(krcp); 1866 1867 // If there is nothing to detach, it means that our job is 1868 // successfully done here. In case of having at least one 1869 // of the channels that is still busy we should rearm the 1870 // work to repeat an attempt. Because previous batches are 1871 // still in progress. 1872 if (need_offload_krc(krcp)) 1873 schedule_delayed_monitor_work(krcp); 1874 } 1875 1876 static void fill_page_cache_func(struct work_struct *work) 1877 { 1878 struct kvfree_rcu_bulk_data *bnode; 1879 struct kfree_rcu_cpu *krcp = 1880 container_of(work, struct kfree_rcu_cpu, 1881 page_cache_work.work); 1882 unsigned long flags; 1883 int nr_pages; 1884 bool pushed; 1885 int i; 1886 1887 nr_pages = atomic_read(&krcp->backoff_page_cache_fill) ? 1888 1 : rcu_min_cached_objs; 1889 1890 for (i = READ_ONCE(krcp->nr_bkv_objs); i < nr_pages; i++) { 1891 bnode = (struct kvfree_rcu_bulk_data *) 1892 __get_free_page(GFP_KERNEL | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN); 1893 1894 if (!bnode) 1895 break; 1896 1897 raw_spin_lock_irqsave(&krcp->lock, flags); 1898 pushed = put_cached_bnode(krcp, bnode); 1899 raw_spin_unlock_irqrestore(&krcp->lock, flags); 1900 1901 if (!pushed) { 1902 free_page((unsigned long) bnode); 1903 break; 1904 } 1905 } 1906 1907 atomic_set(&krcp->work_in_progress, 0); 1908 atomic_set(&krcp->backoff_page_cache_fill, 0); 1909 } 1910 1911 // Record ptr in a page managed by krcp, with the pre-krc_this_cpu_lock() 1912 // state specified by flags. If can_alloc is true, the caller must 1913 // be schedulable and not be holding any locks or mutexes that might be 1914 // acquired by the memory allocator or anything that it might invoke. 1915 // Returns true if ptr was successfully recorded, else the caller must 1916 // use a fallback. 1917 static inline bool 1918 add_ptr_to_bulk_krc_lock(struct kfree_rcu_cpu **krcp, 1919 unsigned long *flags, void *ptr, bool can_alloc) 1920 { 1921 struct kvfree_rcu_bulk_data *bnode; 1922 int idx; 1923 1924 *krcp = krc_this_cpu_lock(flags); 1925 if (unlikely(!(*krcp)->initialized)) 1926 return false; 1927 1928 idx = !!is_vmalloc_addr(ptr); 1929 bnode = list_first_entry_or_null(&(*krcp)->bulk_head[idx], 1930 struct kvfree_rcu_bulk_data, list); 1931 1932 /* Check if a new block is required. */ 1933 if (!bnode || bnode->nr_records == KVFREE_BULK_MAX_ENTR) { 1934 bnode = get_cached_bnode(*krcp); 1935 if (!bnode && can_alloc) { 1936 krc_this_cpu_unlock(*krcp, *flags); 1937 1938 // __GFP_NORETRY - allows a light-weight direct reclaim 1939 // what is OK from minimizing of fallback hitting point of 1940 // view. Apart of that it forbids any OOM invoking what is 1941 // also beneficial since we are about to release memory soon. 1942 // 1943 // __GFP_NOMEMALLOC - prevents from consuming of all the 1944 // memory reserves. Please note we have a fallback path. 1945 // 1946 // __GFP_NOWARN - it is supposed that an allocation can 1947 // be failed under low memory or high memory pressure 1948 // scenarios. 1949 bnode = (struct kvfree_rcu_bulk_data *) 1950 __get_free_page(GFP_KERNEL | __GFP_NORETRY | __GFP_NOMEMALLOC | __GFP_NOWARN); 1951 raw_spin_lock_irqsave(&(*krcp)->lock, *flags); 1952 } 1953 1954 if (!bnode) 1955 return false; 1956 1957 // Initialize the new block and attach it. 1958 bnode->nr_records = 0; 1959 list_add(&bnode->list, &(*krcp)->bulk_head[idx]); 1960 } 1961 1962 // Finally insert and update the GP for this page. 1963 bnode->nr_records++; 1964 bnode->records[bnode->nr_records - 1] = ptr; 1965 get_state_synchronize_rcu_full(&bnode->gp_snap); 1966 atomic_inc(&(*krcp)->bulk_count[idx]); 1967 1968 return true; 1969 } 1970 1971 static enum hrtimer_restart 1972 schedule_page_work_fn(struct hrtimer *t) 1973 { 1974 struct kfree_rcu_cpu *krcp = 1975 container_of(t, struct kfree_rcu_cpu, hrtimer); 1976 1977 queue_delayed_work(system_highpri_wq, &krcp->page_cache_work, 0); 1978 return HRTIMER_NORESTART; 1979 } 1980 1981 static void 1982 run_page_cache_worker(struct kfree_rcu_cpu *krcp) 1983 { 1984 // If cache disabled, bail out. 1985 if (!rcu_min_cached_objs) 1986 return; 1987 1988 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING && 1989 !atomic_xchg(&krcp->work_in_progress, 1)) { 1990 if (atomic_read(&krcp->backoff_page_cache_fill)) { 1991 queue_delayed_work(rcu_reclaim_wq, 1992 &krcp->page_cache_work, 1993 msecs_to_jiffies(rcu_delay_page_cache_fill_msec)); 1994 } else { 1995 hrtimer_setup(&krcp->hrtimer, schedule_page_work_fn, CLOCK_MONOTONIC, 1996 HRTIMER_MODE_REL); 1997 hrtimer_start(&krcp->hrtimer, 0, HRTIMER_MODE_REL); 1998 } 1999 } 2000 } 2001 2002 void __init kfree_rcu_scheduler_running(void) 2003 { 2004 int cpu; 2005 2006 for_each_possible_cpu(cpu) { 2007 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2008 2009 if (need_offload_krc(krcp)) 2010 schedule_delayed_monitor_work(krcp); 2011 } 2012 } 2013 2014 /* 2015 * Queue a request for lazy invocation of the appropriate free routine 2016 * after a grace period. Please note that three paths are maintained, 2017 * two for the common case using arrays of pointers and a third one that 2018 * is used only when the main paths cannot be used, for example, due to 2019 * memory pressure. 2020 * 2021 * Each kvfree_call_rcu() request is added to a batch. The batch will be drained 2022 * every KFREE_DRAIN_JIFFIES number of jiffies. All the objects in the batch will 2023 * be free'd in workqueue context. This allows us to: batch requests together to 2024 * reduce the number of grace periods during heavy kfree_rcu()/kvfree_rcu() load. 2025 */ 2026 void kvfree_call_rcu(struct kvfree_rcu_head *head, void *ptr) 2027 { 2028 unsigned long flags; 2029 struct kfree_rcu_cpu *krcp; 2030 bool success; 2031 2032 /* 2033 * Please note there is a limitation for the head-less 2034 * variant, that is why there is a clear rule for such 2035 * objects: it can be used from might_sleep() context 2036 * only. For other places please embed an rcu_head to 2037 * your data. 2038 */ 2039 if (!head) 2040 might_sleep(); 2041 2042 /* 2043 * kvfree_rcu() is called by set_cpus_allowed_force() with 2044 * task_struct::pi_lock acquired. On PREEMPT_RT the local_trylock() 2045 * usage below will acquire the waitlock which must be avoided. 2046 * Therefore avoid it on PREEMPT_RT. 2047 */ 2048 if (!IS_ENABLED(CONFIG_PREEMPT_RT) && kfree_rcu_sheaf(ptr)) 2049 return; 2050 2051 // Queue the object but don't yet schedule the batch. 2052 if (debug_rcu_head_queue(ptr)) { 2053 // Probable double kfree_rcu(), just leak. 2054 WARN_ONCE(1, "%s(): Double-freed call. rcu_head %p\n", 2055 __func__, head); 2056 2057 // Mark as success and leave. 2058 return; 2059 } 2060 2061 kasan_record_aux_stack(ptr); 2062 success = add_ptr_to_bulk_krc_lock(&krcp, &flags, ptr, !head); 2063 if (!success) { 2064 run_page_cache_worker(krcp); 2065 2066 if (head == NULL) 2067 // Inline if kvfree_rcu(one_arg) call. 2068 goto unlock_return; 2069 2070 head->next = krcp->head; 2071 WRITE_ONCE(krcp->head, head); 2072 atomic_inc(&krcp->head_count); 2073 2074 // Take a snapshot for this krcp. 2075 krcp->head_gp_snap = get_state_synchronize_rcu(); 2076 success = true; 2077 } 2078 2079 /* 2080 * The kvfree_rcu() caller considers the pointer freed at this point 2081 * and likely removes any references to it. Since the actual slab 2082 * freeing (and kmemleak_free()) is deferred, tell kmemleak to ignore 2083 * this object (no scanning or false positives reporting). 2084 */ 2085 kmemleak_ignore(ptr); 2086 2087 // Set timer to drain after KFREE_DRAIN_JIFFIES. 2088 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING) 2089 __schedule_delayed_monitor_work(krcp); 2090 2091 unlock_return: 2092 krc_this_cpu_unlock(krcp, flags); 2093 2094 /* 2095 * Inline kvfree() after synchronize_rcu(). We can do 2096 * it from might_sleep() context only, so the current 2097 * CPU can pass the QS state. 2098 */ 2099 if (!success) { 2100 debug_rcu_head_unqueue((struct rcu_head *) ptr); 2101 synchronize_rcu(); 2102 kvfree(ptr); 2103 } 2104 } 2105 EXPORT_SYMBOL_GPL(kvfree_call_rcu); 2106 2107 static inline void __kvfree_rcu_barrier(void) 2108 { 2109 struct kfree_rcu_cpu_work *krwp; 2110 struct kfree_rcu_cpu *krcp; 2111 bool queued; 2112 int i, cpu; 2113 2114 /* 2115 * Firstly we detach objects and queue them over an RCU-batch 2116 * for all CPUs. Finally queued works are flushed for each CPU. 2117 * 2118 * Please note. If there are outstanding batches for a particular 2119 * CPU, those have to be finished first following by queuing a new. 2120 */ 2121 for_each_possible_cpu(cpu) { 2122 krcp = per_cpu_ptr(&krc, cpu); 2123 2124 /* 2125 * Check if this CPU has any objects which have been queued for a 2126 * new GP completion. If not(means nothing to detach), we are done 2127 * with it. If any batch is pending/running for this "krcp", below 2128 * per-cpu flush_rcu_work() waits its completion(see last step). 2129 */ 2130 if (!need_offload_krc(krcp)) 2131 continue; 2132 2133 while (1) { 2134 /* 2135 * If we are not able to queue a new RCU work it means: 2136 * - batches for this CPU are still in flight which should 2137 * be flushed first and then repeat; 2138 * - no objects to detach, because of concurrency. 2139 */ 2140 queued = kvfree_rcu_queue_batch(krcp); 2141 2142 /* 2143 * Bail out, if there is no need to offload this "krcp" 2144 * anymore. As noted earlier it can run concurrently. 2145 */ 2146 if (queued || !need_offload_krc(krcp)) 2147 break; 2148 2149 /* There are ongoing batches. */ 2150 for (i = 0; i < KFREE_N_BATCHES; i++) { 2151 krwp = &(krcp->krw_arr[i]); 2152 flush_rcu_work(&krwp->rcu_work); 2153 } 2154 } 2155 } 2156 2157 /* 2158 * Now we guarantee that all objects are flushed. 2159 */ 2160 for_each_possible_cpu(cpu) { 2161 krcp = per_cpu_ptr(&krc, cpu); 2162 2163 /* 2164 * A monitor work can drain ready to reclaim objects 2165 * directly. Wait its completion if running or pending. 2166 */ 2167 cancel_delayed_work_sync(&krcp->monitor_work); 2168 2169 for (i = 0; i < KFREE_N_BATCHES; i++) { 2170 krwp = &(krcp->krw_arr[i]); 2171 flush_rcu_work(&krwp->rcu_work); 2172 } 2173 } 2174 } 2175 2176 /** 2177 * kvfree_rcu_barrier - Wait until all in-flight kvfree_rcu() complete. 2178 * 2179 * Note that a single argument of kvfree_rcu() call has a slow path that 2180 * triggers synchronize_rcu() following by freeing a pointer. It is done 2181 * before the return from the function. Therefore for any single-argument 2182 * call that will result in a kfree() to a cache that is to be destroyed 2183 * during module exit, it is developer's responsibility to ensure that all 2184 * such calls have returned before the call to kmem_cache_destroy(). 2185 */ 2186 void kvfree_rcu_barrier(void) 2187 { 2188 flush_all_rcu_sheaves(); 2189 __kvfree_rcu_barrier(); 2190 } 2191 2192 /** 2193 * kvfree_rcu_barrier_on_cache - Wait for in-flight kvfree_rcu() calls on a 2194 * specific slab cache. 2195 * @s: slab cache to wait for 2196 * 2197 * See the description of kvfree_rcu_barrier() for details. 2198 */ 2199 void kvfree_rcu_barrier_on_cache(struct kmem_cache *s) 2200 { 2201 /* kfree_rcu_nolock() might have deferred frees even without sheaves */ 2202 deferred_work_barrier(); 2203 2204 if (cache_has_sheaves(s)) { 2205 cpus_read_lock(); 2206 flush_rcu_sheaves_on_cache(s); 2207 cpus_read_unlock(); 2208 } 2209 2210 rcu_barrier(); 2211 __kvfree_rcu_barrier(); 2212 } 2213 2214 static unsigned long 2215 kfree_rcu_shrink_count(struct shrinker *shrink, struct shrink_control *sc) 2216 { 2217 int cpu; 2218 unsigned long count = 0; 2219 2220 /* Snapshot count of all CPUs */ 2221 for_each_possible_cpu(cpu) { 2222 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2223 2224 count += krc_count(krcp); 2225 count += READ_ONCE(krcp->nr_bkv_objs); 2226 atomic_set(&krcp->backoff_page_cache_fill, 1); 2227 } 2228 2229 return count == 0 ? SHRINK_EMPTY : count; 2230 } 2231 2232 static unsigned long 2233 kfree_rcu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) 2234 { 2235 int cpu, freed = 0; 2236 2237 for_each_possible_cpu(cpu) { 2238 int count; 2239 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2240 2241 count = krc_count(krcp); 2242 count += drain_page_cache(krcp); 2243 kfree_rcu_monitor(&krcp->monitor_work.work); 2244 2245 sc->nr_to_scan -= count; 2246 freed += count; 2247 2248 if (sc->nr_to_scan <= 0) 2249 break; 2250 } 2251 2252 return freed == 0 ? SHRINK_STOP : freed; 2253 } 2254 2255 void __init kvfree_rcu_init(void) 2256 { 2257 int cpu; 2258 int i, j; 2259 struct shrinker *kfree_rcu_shrinker; 2260 2261 rcu_reclaim_wq = alloc_workqueue("kvfree_rcu_reclaim", 2262 WQ_UNBOUND | WQ_MEM_RECLAIM, 0); 2263 WARN_ON(!rcu_reclaim_wq); 2264 2265 /* Clamp it to [1:100000] milliseconds interval. */ 2266 if (rcu_delay_page_cache_fill_msec < 1 || 2267 rcu_delay_page_cache_fill_msec > 100 * MSEC_PER_SEC) { 2268 2269 rcu_delay_page_cache_fill_msec = 2270 clamp(rcu_delay_page_cache_fill_msec, 1, 2271 (int) (100 * MSEC_PER_SEC)); 2272 2273 pr_info("Adjusting rcutree.rcu_delay_page_cache_fill_msec to %d ms.\n", 2274 rcu_delay_page_cache_fill_msec); 2275 } 2276 2277 for_each_possible_cpu(cpu) { 2278 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu); 2279 2280 for (i = 0; i < KFREE_N_BATCHES; i++) { 2281 INIT_RCU_WORK(&krcp->krw_arr[i].rcu_work, kfree_rcu_work); 2282 krcp->krw_arr[i].krcp = krcp; 2283 2284 for (j = 0; j < FREE_N_CHANNELS; j++) 2285 INIT_LIST_HEAD(&krcp->krw_arr[i].bulk_head_free[j]); 2286 } 2287 2288 for (i = 0; i < FREE_N_CHANNELS; i++) 2289 INIT_LIST_HEAD(&krcp->bulk_head[i]); 2290 2291 INIT_DELAYED_WORK(&krcp->monitor_work, kfree_rcu_monitor); 2292 INIT_DELAYED_WORK(&krcp->page_cache_work, fill_page_cache_func); 2293 krcp->initialized = true; 2294 } 2295 2296 kfree_rcu_shrinker = shrinker_alloc(0, "slab-kvfree-rcu"); 2297 if (!kfree_rcu_shrinker) { 2298 pr_err("Failed to allocate kfree_rcu() shrinker!\n"); 2299 return; 2300 } 2301 2302 kfree_rcu_shrinker->count_objects = kfree_rcu_shrink_count; 2303 kfree_rcu_shrinker->scan_objects = kfree_rcu_shrink_scan; 2304 2305 shrinker_register(kfree_rcu_shrinker); 2306 } 2307 2308 #endif /* CONFIG_KVFREE_RCU_BATCHED */ 2309