1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * SLUB: A slab allocator that limits cache line use instead of queuing 4 * objects in per cpu and per node lists. 5 * 6 * The allocator synchronizes using per slab locks or atomic operations 7 * and only uses a centralized lock to manage a pool of partial slabs. 8 * 9 * (C) 2007 SGI, Christoph Lameter 10 * (C) 2011 Linux Foundation, Christoph Lameter 11 */ 12 13 #include <linux/mm.h> 14 #include <linux/swap.h> /* mm_account_reclaimed_pages() */ 15 #include <linux/module.h> 16 #include <linux/bit_spinlock.h> 17 #include <linux/interrupt.h> 18 #include <linux/swab.h> 19 #include <linux/bitops.h> 20 #include <linux/slab.h> 21 #include "slab.h" 22 #include <linux/vmalloc.h> 23 #include <linux/proc_fs.h> 24 #include <linux/seq_file.h> 25 #include <linux/kasan.h> 26 #include <linux/kmsan.h> 27 #include <linux/cpu.h> 28 #include <linux/cpuset.h> 29 #include <linux/mempolicy.h> 30 #include <linux/ctype.h> 31 #include <linux/stackdepot.h> 32 #include <linux/debugobjects.h> 33 #include <linux/kallsyms.h> 34 #include <linux/kfence.h> 35 #include <linux/memory.h> 36 #include <linux/math64.h> 37 #include <linux/fault-inject.h> 38 #include <linux/kmemleak.h> 39 #include <linux/stacktrace.h> 40 #include <linux/prefetch.h> 41 #include <linux/memcontrol.h> 42 #include <linux/random.h> 43 #include <kunit/test.h> 44 #include <kunit/test-bug.h> 45 #include <linux/sort.h> 46 47 #include <linux/debugfs.h> 48 #include <trace/events/kmem.h> 49 50 #include "internal.h" 51 52 /* 53 * Lock order: 54 * 1. slab_mutex (Global Mutex) 55 * 2. node->list_lock (Spinlock) 56 * 3. kmem_cache->cpu_slab->lock (Local lock) 57 * 4. slab_lock(slab) (Only on some arches) 58 * 5. object_map_lock (Only for debugging) 59 * 60 * slab_mutex 61 * 62 * The role of the slab_mutex is to protect the list of all the slabs 63 * and to synchronize major metadata changes to slab cache structures. 64 * Also synchronizes memory hotplug callbacks. 65 * 66 * slab_lock 67 * 68 * The slab_lock is a wrapper around the page lock, thus it is a bit 69 * spinlock. 70 * 71 * The slab_lock is only used on arches that do not have the ability 72 * to do a cmpxchg_double. It only protects: 73 * 74 * A. slab->freelist -> List of free objects in a slab 75 * B. slab->inuse -> Number of objects in use 76 * C. slab->objects -> Number of objects in slab 77 * D. slab->frozen -> frozen state 78 * 79 * Frozen slabs 80 * 81 * If a slab is frozen then it is exempt from list management. It is 82 * the cpu slab which is actively allocated from by the processor that 83 * froze it and it is not on any list. The processor that froze the 84 * slab is the one who can perform list operations on the slab. Other 85 * processors may put objects onto the freelist but the processor that 86 * froze the slab is the only one that can retrieve the objects from the 87 * slab's freelist. 88 * 89 * CPU partial slabs 90 * 91 * The partially empty slabs cached on the CPU partial list are used 92 * for performance reasons, which speeds up the allocation process. 93 * These slabs are not frozen, but are also exempt from list management, 94 * by clearing the SL_partial flag when moving out of the node 95 * partial list. Please see __slab_free() for more details. 96 * 97 * To sum up, the current scheme is: 98 * - node partial slab: SL_partial && !frozen 99 * - cpu partial slab: !SL_partial && !frozen 100 * - cpu slab: !SL_partial && frozen 101 * - full slab: !SL_partial && !frozen 102 * 103 * list_lock 104 * 105 * The list_lock protects the partial and full list on each node and 106 * the partial slab counter. If taken then no new slabs may be added or 107 * removed from the lists nor make the number of partial slabs be modified. 108 * (Note that the total number of slabs is an atomic value that may be 109 * modified without taking the list lock). 110 * 111 * The list_lock is a centralized lock and thus we avoid taking it as 112 * much as possible. As long as SLUB does not have to handle partial 113 * slabs, operations can continue without any centralized lock. F.e. 114 * allocating a long series of objects that fill up slabs does not require 115 * the list lock. 116 * 117 * For debug caches, all allocations are forced to go through a list_lock 118 * protected region to serialize against concurrent validation. 119 * 120 * cpu_slab->lock local lock 121 * 122 * This locks protect slowpath manipulation of all kmem_cache_cpu fields 123 * except the stat counters. This is a percpu structure manipulated only by 124 * the local cpu, so the lock protects against being preempted or interrupted 125 * by an irq. Fast path operations rely on lockless operations instead. 126 * 127 * On PREEMPT_RT, the local lock neither disables interrupts nor preemption 128 * which means the lockless fastpath cannot be used as it might interfere with 129 * an in-progress slow path operations. In this case the local lock is always 130 * taken but it still utilizes the freelist for the common operations. 131 * 132 * lockless fastpaths 133 * 134 * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free()) 135 * are fully lockless when satisfied from the percpu slab (and when 136 * cmpxchg_double is possible to use, otherwise slab_lock is taken). 137 * They also don't disable preemption or migration or irqs. They rely on 138 * the transaction id (tid) field to detect being preempted or moved to 139 * another cpu. 140 * 141 * irq, preemption, migration considerations 142 * 143 * Interrupts are disabled as part of list_lock or local_lock operations, or 144 * around the slab_lock operation, in order to make the slab allocator safe 145 * to use in the context of an irq. 146 * 147 * In addition, preemption (or migration on PREEMPT_RT) is disabled in the 148 * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the 149 * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer 150 * doesn't have to be revalidated in each section protected by the local lock. 151 * 152 * SLUB assigns one slab for allocation to each processor. 153 * Allocations only occur from these slabs called cpu slabs. 154 * 155 * Slabs with free elements are kept on a partial list and during regular 156 * operations no list for full slabs is used. If an object in a full slab is 157 * freed then the slab will show up again on the partial lists. 158 * We track full slabs for debugging purposes though because otherwise we 159 * cannot scan all objects. 160 * 161 * Slabs are freed when they become empty. Teardown and setup is 162 * minimal so we rely on the page allocators per cpu caches for 163 * fast frees and allocs. 164 * 165 * slab->frozen The slab is frozen and exempt from list processing. 166 * This means that the slab is dedicated to a purpose 167 * such as satisfying allocations for a specific 168 * processor. Objects may be freed in the slab while 169 * it is frozen but slab_free will then skip the usual 170 * list operations. It is up to the processor holding 171 * the slab to integrate the slab into the slab lists 172 * when the slab is no longer needed. 173 * 174 * One use of this flag is to mark slabs that are 175 * used for allocations. Then such a slab becomes a cpu 176 * slab. The cpu slab may be equipped with an additional 177 * freelist that allows lockless access to 178 * free objects in addition to the regular freelist 179 * that requires the slab lock. 180 * 181 * SLAB_DEBUG_FLAGS Slab requires special handling due to debug 182 * options set. This moves slab handling out of 183 * the fast path and disables lockless freelists. 184 */ 185 186 /** 187 * enum slab_flags - How the slab flags bits are used. 188 * @SL_locked: Is locked with slab_lock() 189 * @SL_partial: On the per-node partial list 190 * @SL_pfmemalloc: Was allocated from PF_MEMALLOC reserves 191 * 192 * The slab flags share space with the page flags but some bits have 193 * different interpretations. The high bits are used for information 194 * like zone/node/section. 195 */ 196 enum slab_flags { 197 SL_locked = PG_locked, 198 SL_partial = PG_workingset, /* Historical reasons for this bit */ 199 SL_pfmemalloc = PG_active, /* Historical reasons for this bit */ 200 }; 201 202 /* 203 * We could simply use migrate_disable()/enable() but as long as it's a 204 * function call even on !PREEMPT_RT, use inline preempt_disable() there. 205 */ 206 #ifndef CONFIG_PREEMPT_RT 207 #define slub_get_cpu_ptr(var) get_cpu_ptr(var) 208 #define slub_put_cpu_ptr(var) put_cpu_ptr(var) 209 #define USE_LOCKLESS_FAST_PATH() (true) 210 #else 211 #define slub_get_cpu_ptr(var) \ 212 ({ \ 213 migrate_disable(); \ 214 this_cpu_ptr(var); \ 215 }) 216 #define slub_put_cpu_ptr(var) \ 217 do { \ 218 (void)(var); \ 219 migrate_enable(); \ 220 } while (0) 221 #define USE_LOCKLESS_FAST_PATH() (false) 222 #endif 223 224 #ifndef CONFIG_SLUB_TINY 225 #define __fastpath_inline __always_inline 226 #else 227 #define __fastpath_inline 228 #endif 229 230 #ifdef CONFIG_SLUB_DEBUG 231 #ifdef CONFIG_SLUB_DEBUG_ON 232 DEFINE_STATIC_KEY_TRUE(slub_debug_enabled); 233 #else 234 DEFINE_STATIC_KEY_FALSE(slub_debug_enabled); 235 #endif 236 #endif /* CONFIG_SLUB_DEBUG */ 237 238 #ifdef CONFIG_NUMA 239 static DEFINE_STATIC_KEY_FALSE(strict_numa); 240 #endif 241 242 /* Structure holding parameters for get_partial() call chain */ 243 struct partial_context { 244 gfp_t flags; 245 unsigned int orig_size; 246 void *object; 247 }; 248 249 static inline bool kmem_cache_debug(struct kmem_cache *s) 250 { 251 return kmem_cache_debug_flags(s, SLAB_DEBUG_FLAGS); 252 } 253 254 void *fixup_red_left(struct kmem_cache *s, void *p) 255 { 256 if (kmem_cache_debug_flags(s, SLAB_RED_ZONE)) 257 p += s->red_left_pad; 258 259 return p; 260 } 261 262 static inline bool kmem_cache_has_cpu_partial(struct kmem_cache *s) 263 { 264 #ifdef CONFIG_SLUB_CPU_PARTIAL 265 return !kmem_cache_debug(s); 266 #else 267 return false; 268 #endif 269 } 270 271 /* 272 * Issues still to be resolved: 273 * 274 * - Support PAGE_ALLOC_DEBUG. Should be easy to do. 275 * 276 * - Variable sizing of the per node arrays 277 */ 278 279 /* Enable to log cmpxchg failures */ 280 #undef SLUB_DEBUG_CMPXCHG 281 282 #ifndef CONFIG_SLUB_TINY 283 /* 284 * Minimum number of partial slabs. These will be left on the partial 285 * lists even if they are empty. kmem_cache_shrink may reclaim them. 286 */ 287 #define MIN_PARTIAL 5 288 289 /* 290 * Maximum number of desirable partial slabs. 291 * The existence of more partial slabs makes kmem_cache_shrink 292 * sort the partial list by the number of objects in use. 293 */ 294 #define MAX_PARTIAL 10 295 #else 296 #define MIN_PARTIAL 0 297 #define MAX_PARTIAL 0 298 #endif 299 300 #define DEBUG_DEFAULT_FLAGS (SLAB_CONSISTENCY_CHECKS | SLAB_RED_ZONE | \ 301 SLAB_POISON | SLAB_STORE_USER) 302 303 /* 304 * These debug flags cannot use CMPXCHG because there might be consistency 305 * issues when checking or reading debug information 306 */ 307 #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \ 308 SLAB_TRACE) 309 310 311 /* 312 * Debugging flags that require metadata to be stored in the slab. These get 313 * disabled when slab_debug=O is used and a cache's min order increases with 314 * metadata. 315 */ 316 #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER) 317 318 #define OO_SHIFT 16 319 #define OO_MASK ((1 << OO_SHIFT) - 1) 320 #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */ 321 322 /* Internal SLUB flags */ 323 /* Poison object */ 324 #define __OBJECT_POISON __SLAB_FLAG_BIT(_SLAB_OBJECT_POISON) 325 /* Use cmpxchg_double */ 326 327 #ifdef system_has_freelist_aba 328 #define __CMPXCHG_DOUBLE __SLAB_FLAG_BIT(_SLAB_CMPXCHG_DOUBLE) 329 #else 330 #define __CMPXCHG_DOUBLE __SLAB_FLAG_UNUSED 331 #endif 332 333 /* 334 * Tracking user of a slab. 335 */ 336 #define TRACK_ADDRS_COUNT 16 337 struct track { 338 unsigned long addr; /* Called from address */ 339 #ifdef CONFIG_STACKDEPOT 340 depot_stack_handle_t handle; 341 #endif 342 int cpu; /* Was running on cpu */ 343 int pid; /* Pid context */ 344 unsigned long when; /* When did the operation occur */ 345 }; 346 347 enum track_item { TRACK_ALLOC, TRACK_FREE }; 348 349 #ifdef SLAB_SUPPORTS_SYSFS 350 static int sysfs_slab_add(struct kmem_cache *); 351 static int sysfs_slab_alias(struct kmem_cache *, const char *); 352 #else 353 static inline int sysfs_slab_add(struct kmem_cache *s) { return 0; } 354 static inline int sysfs_slab_alias(struct kmem_cache *s, const char *p) 355 { return 0; } 356 #endif 357 358 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_SLUB_DEBUG) 359 static void debugfs_slab_add(struct kmem_cache *); 360 #else 361 static inline void debugfs_slab_add(struct kmem_cache *s) { } 362 #endif 363 364 enum stat_item { 365 ALLOC_FASTPATH, /* Allocation from cpu slab */ 366 ALLOC_SLOWPATH, /* Allocation by getting a new cpu slab */ 367 FREE_FASTPATH, /* Free to cpu slab */ 368 FREE_SLOWPATH, /* Freeing not to cpu slab */ 369 FREE_FROZEN, /* Freeing to frozen slab */ 370 FREE_ADD_PARTIAL, /* Freeing moves slab to partial list */ 371 FREE_REMOVE_PARTIAL, /* Freeing removes last object */ 372 ALLOC_FROM_PARTIAL, /* Cpu slab acquired from node partial list */ 373 ALLOC_SLAB, /* Cpu slab acquired from page allocator */ 374 ALLOC_REFILL, /* Refill cpu slab from slab freelist */ 375 ALLOC_NODE_MISMATCH, /* Switching cpu slab */ 376 FREE_SLAB, /* Slab freed to the page allocator */ 377 CPUSLAB_FLUSH, /* Abandoning of the cpu slab */ 378 DEACTIVATE_FULL, /* Cpu slab was full when deactivated */ 379 DEACTIVATE_EMPTY, /* Cpu slab was empty when deactivated */ 380 DEACTIVATE_TO_HEAD, /* Cpu slab was moved to the head of partials */ 381 DEACTIVATE_TO_TAIL, /* Cpu slab was moved to the tail of partials */ 382 DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */ 383 DEACTIVATE_BYPASS, /* Implicit deactivation */ 384 ORDER_FALLBACK, /* Number of times fallback was necessary */ 385 CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */ 386 CMPXCHG_DOUBLE_FAIL, /* Failures of slab freelist update */ 387 CPU_PARTIAL_ALLOC, /* Used cpu partial on alloc */ 388 CPU_PARTIAL_FREE, /* Refill cpu partial on free */ 389 CPU_PARTIAL_NODE, /* Refill cpu partial from node partial */ 390 CPU_PARTIAL_DRAIN, /* Drain cpu partial to node partial */ 391 NR_SLUB_STAT_ITEMS 392 }; 393 394 #ifndef CONFIG_SLUB_TINY 395 /* 396 * When changing the layout, make sure freelist and tid are still compatible 397 * with this_cpu_cmpxchg_double() alignment requirements. 398 */ 399 struct kmem_cache_cpu { 400 union { 401 struct { 402 void **freelist; /* Pointer to next available object */ 403 unsigned long tid; /* Globally unique transaction id */ 404 }; 405 freelist_aba_t freelist_tid; 406 }; 407 struct slab *slab; /* The slab from which we are allocating */ 408 #ifdef CONFIG_SLUB_CPU_PARTIAL 409 struct slab *partial; /* Partially allocated slabs */ 410 #endif 411 local_lock_t lock; /* Protects the fields above */ 412 #ifdef CONFIG_SLUB_STATS 413 unsigned int stat[NR_SLUB_STAT_ITEMS]; 414 #endif 415 }; 416 #endif /* CONFIG_SLUB_TINY */ 417 418 static inline void stat(const struct kmem_cache *s, enum stat_item si) 419 { 420 #ifdef CONFIG_SLUB_STATS 421 /* 422 * The rmw is racy on a preemptible kernel but this is acceptable, so 423 * avoid this_cpu_add()'s irq-disable overhead. 424 */ 425 raw_cpu_inc(s->cpu_slab->stat[si]); 426 #endif 427 } 428 429 static inline 430 void stat_add(const struct kmem_cache *s, enum stat_item si, int v) 431 { 432 #ifdef CONFIG_SLUB_STATS 433 raw_cpu_add(s->cpu_slab->stat[si], v); 434 #endif 435 } 436 437 /* 438 * The slab lists for all objects. 439 */ 440 struct kmem_cache_node { 441 spinlock_t list_lock; 442 unsigned long nr_partial; 443 struct list_head partial; 444 #ifdef CONFIG_SLUB_DEBUG 445 atomic_long_t nr_slabs; 446 atomic_long_t total_objects; 447 struct list_head full; 448 #endif 449 }; 450 451 static inline struct kmem_cache_node *get_node(struct kmem_cache *s, int node) 452 { 453 return s->node[node]; 454 } 455 456 /* 457 * Iterator over all nodes. The body will be executed for each node that has 458 * a kmem_cache_node structure allocated (which is true for all online nodes) 459 */ 460 #define for_each_kmem_cache_node(__s, __node, __n) \ 461 for (__node = 0; __node < nr_node_ids; __node++) \ 462 if ((__n = get_node(__s, __node))) 463 464 /* 465 * Tracks for which NUMA nodes we have kmem_cache_nodes allocated. 466 * Corresponds to node_state[N_NORMAL_MEMORY], but can temporarily 467 * differ during memory hotplug/hotremove operations. 468 * Protected by slab_mutex. 469 */ 470 static nodemask_t slab_nodes; 471 472 #ifndef CONFIG_SLUB_TINY 473 /* 474 * Workqueue used for flush_cpu_slab(). 475 */ 476 static struct workqueue_struct *flushwq; 477 #endif 478 479 /******************************************************************** 480 * Core slab cache functions 481 *******************************************************************/ 482 483 /* 484 * Returns freelist pointer (ptr). With hardening, this is obfuscated 485 * with an XOR of the address where the pointer is held and a per-cache 486 * random number. 487 */ 488 static inline freeptr_t freelist_ptr_encode(const struct kmem_cache *s, 489 void *ptr, unsigned long ptr_addr) 490 { 491 unsigned long encoded; 492 493 #ifdef CONFIG_SLAB_FREELIST_HARDENED 494 encoded = (unsigned long)ptr ^ s->random ^ swab(ptr_addr); 495 #else 496 encoded = (unsigned long)ptr; 497 #endif 498 return (freeptr_t){.v = encoded}; 499 } 500 501 static inline void *freelist_ptr_decode(const struct kmem_cache *s, 502 freeptr_t ptr, unsigned long ptr_addr) 503 { 504 void *decoded; 505 506 #ifdef CONFIG_SLAB_FREELIST_HARDENED 507 decoded = (void *)(ptr.v ^ s->random ^ swab(ptr_addr)); 508 #else 509 decoded = (void *)ptr.v; 510 #endif 511 return decoded; 512 } 513 514 static inline void *get_freepointer(struct kmem_cache *s, void *object) 515 { 516 unsigned long ptr_addr; 517 freeptr_t p; 518 519 object = kasan_reset_tag(object); 520 ptr_addr = (unsigned long)object + s->offset; 521 p = *(freeptr_t *)(ptr_addr); 522 return freelist_ptr_decode(s, p, ptr_addr); 523 } 524 525 #ifndef CONFIG_SLUB_TINY 526 static void prefetch_freepointer(const struct kmem_cache *s, void *object) 527 { 528 prefetchw(object + s->offset); 529 } 530 #endif 531 532 /* 533 * When running under KMSAN, get_freepointer_safe() may return an uninitialized 534 * pointer value in the case the current thread loses the race for the next 535 * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in 536 * slab_alloc_node() will fail, so the uninitialized value won't be used, but 537 * KMSAN will still check all arguments of cmpxchg because of imperfect 538 * handling of inline assembly. 539 * To work around this problem, we apply __no_kmsan_checks to ensure that 540 * get_freepointer_safe() returns initialized memory. 541 */ 542 __no_kmsan_checks 543 static inline void *get_freepointer_safe(struct kmem_cache *s, void *object) 544 { 545 unsigned long freepointer_addr; 546 freeptr_t p; 547 548 if (!debug_pagealloc_enabled_static()) 549 return get_freepointer(s, object); 550 551 object = kasan_reset_tag(object); 552 freepointer_addr = (unsigned long)object + s->offset; 553 copy_from_kernel_nofault(&p, (freeptr_t *)freepointer_addr, sizeof(p)); 554 return freelist_ptr_decode(s, p, freepointer_addr); 555 } 556 557 static inline void set_freepointer(struct kmem_cache *s, void *object, void *fp) 558 { 559 unsigned long freeptr_addr = (unsigned long)object + s->offset; 560 561 #ifdef CONFIG_SLAB_FREELIST_HARDENED 562 BUG_ON(object == fp); /* naive detection of double free or corruption */ 563 #endif 564 565 freeptr_addr = (unsigned long)kasan_reset_tag((void *)freeptr_addr); 566 *(freeptr_t *)freeptr_addr = freelist_ptr_encode(s, fp, freeptr_addr); 567 } 568 569 /* 570 * See comment in calculate_sizes(). 571 */ 572 static inline bool freeptr_outside_object(struct kmem_cache *s) 573 { 574 return s->offset >= s->inuse; 575 } 576 577 /* 578 * Return offset of the end of info block which is inuse + free pointer if 579 * not overlapping with object. 580 */ 581 static inline unsigned int get_info_end(struct kmem_cache *s) 582 { 583 if (freeptr_outside_object(s)) 584 return s->inuse + sizeof(void *); 585 else 586 return s->inuse; 587 } 588 589 /* Loop over all objects in a slab */ 590 #define for_each_object(__p, __s, __addr, __objects) \ 591 for (__p = fixup_red_left(__s, __addr); \ 592 __p < (__addr) + (__objects) * (__s)->size; \ 593 __p += (__s)->size) 594 595 static inline unsigned int order_objects(unsigned int order, unsigned int size) 596 { 597 return ((unsigned int)PAGE_SIZE << order) / size; 598 } 599 600 static inline struct kmem_cache_order_objects oo_make(unsigned int order, 601 unsigned int size) 602 { 603 struct kmem_cache_order_objects x = { 604 (order << OO_SHIFT) + order_objects(order, size) 605 }; 606 607 return x; 608 } 609 610 static inline unsigned int oo_order(struct kmem_cache_order_objects x) 611 { 612 return x.x >> OO_SHIFT; 613 } 614 615 static inline unsigned int oo_objects(struct kmem_cache_order_objects x) 616 { 617 return x.x & OO_MASK; 618 } 619 620 #ifdef CONFIG_SLUB_CPU_PARTIAL 621 static void slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects) 622 { 623 unsigned int nr_slabs; 624 625 s->cpu_partial = nr_objects; 626 627 /* 628 * We take the number of objects but actually limit the number of 629 * slabs on the per cpu partial list, in order to limit excessive 630 * growth of the list. For simplicity we assume that the slabs will 631 * be half-full. 632 */ 633 nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo)); 634 s->cpu_partial_slabs = nr_slabs; 635 } 636 637 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s) 638 { 639 return s->cpu_partial_slabs; 640 } 641 #else 642 static inline void 643 slub_set_cpu_partial(struct kmem_cache *s, unsigned int nr_objects) 644 { 645 } 646 647 static inline unsigned int slub_get_cpu_partial(struct kmem_cache *s) 648 { 649 return 0; 650 } 651 #endif /* CONFIG_SLUB_CPU_PARTIAL */ 652 653 /* 654 * If network-based swap is enabled, slub must keep track of whether memory 655 * were allocated from pfmemalloc reserves. 656 */ 657 static inline bool slab_test_pfmemalloc(const struct slab *slab) 658 { 659 return test_bit(SL_pfmemalloc, &slab->flags); 660 } 661 662 static inline void slab_set_pfmemalloc(struct slab *slab) 663 { 664 set_bit(SL_pfmemalloc, &slab->flags); 665 } 666 667 static inline void __slab_clear_pfmemalloc(struct slab *slab) 668 { 669 __clear_bit(SL_pfmemalloc, &slab->flags); 670 } 671 672 /* 673 * Per slab locking using the pagelock 674 */ 675 static __always_inline void slab_lock(struct slab *slab) 676 { 677 bit_spin_lock(SL_locked, &slab->flags); 678 } 679 680 static __always_inline void slab_unlock(struct slab *slab) 681 { 682 bit_spin_unlock(SL_locked, &slab->flags); 683 } 684 685 static inline bool 686 __update_freelist_fast(struct slab *slab, 687 void *freelist_old, unsigned long counters_old, 688 void *freelist_new, unsigned long counters_new) 689 { 690 #ifdef system_has_freelist_aba 691 freelist_aba_t old = { .freelist = freelist_old, .counter = counters_old }; 692 freelist_aba_t new = { .freelist = freelist_new, .counter = counters_new }; 693 694 return try_cmpxchg_freelist(&slab->freelist_counter.full, &old.full, new.full); 695 #else 696 return false; 697 #endif 698 } 699 700 static inline bool 701 __update_freelist_slow(struct slab *slab, 702 void *freelist_old, unsigned long counters_old, 703 void *freelist_new, unsigned long counters_new) 704 { 705 bool ret = false; 706 707 slab_lock(slab); 708 if (slab->freelist == freelist_old && 709 slab->counters == counters_old) { 710 slab->freelist = freelist_new; 711 slab->counters = counters_new; 712 ret = true; 713 } 714 slab_unlock(slab); 715 716 return ret; 717 } 718 719 /* 720 * Interrupts must be disabled (for the fallback code to work right), typically 721 * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is 722 * part of bit_spin_lock(), is sufficient because the policy is not to allow any 723 * allocation/ free operation in hardirq context. Therefore nothing can 724 * interrupt the operation. 725 */ 726 static inline bool __slab_update_freelist(struct kmem_cache *s, struct slab *slab, 727 void *freelist_old, unsigned long counters_old, 728 void *freelist_new, unsigned long counters_new, 729 const char *n) 730 { 731 bool ret; 732 733 if (USE_LOCKLESS_FAST_PATH()) 734 lockdep_assert_irqs_disabled(); 735 736 if (s->flags & __CMPXCHG_DOUBLE) { 737 ret = __update_freelist_fast(slab, freelist_old, counters_old, 738 freelist_new, counters_new); 739 } else { 740 ret = __update_freelist_slow(slab, freelist_old, counters_old, 741 freelist_new, counters_new); 742 } 743 if (likely(ret)) 744 return true; 745 746 cpu_relax(); 747 stat(s, CMPXCHG_DOUBLE_FAIL); 748 749 #ifdef SLUB_DEBUG_CMPXCHG 750 pr_info("%s %s: cmpxchg double redo ", n, s->name); 751 #endif 752 753 return false; 754 } 755 756 static inline bool slab_update_freelist(struct kmem_cache *s, struct slab *slab, 757 void *freelist_old, unsigned long counters_old, 758 void *freelist_new, unsigned long counters_new, 759 const char *n) 760 { 761 bool ret; 762 763 if (s->flags & __CMPXCHG_DOUBLE) { 764 ret = __update_freelist_fast(slab, freelist_old, counters_old, 765 freelist_new, counters_new); 766 } else { 767 unsigned long flags; 768 769 local_irq_save(flags); 770 ret = __update_freelist_slow(slab, freelist_old, counters_old, 771 freelist_new, counters_new); 772 local_irq_restore(flags); 773 } 774 if (likely(ret)) 775 return true; 776 777 cpu_relax(); 778 stat(s, CMPXCHG_DOUBLE_FAIL); 779 780 #ifdef SLUB_DEBUG_CMPXCHG 781 pr_info("%s %s: cmpxchg double redo ", n, s->name); 782 #endif 783 784 return false; 785 } 786 787 /* 788 * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API 789 * family will round up the real request size to these fixed ones, so 790 * there could be an extra area than what is requested. Save the original 791 * request size in the meta data area, for better debug and sanity check. 792 */ 793 static inline void set_orig_size(struct kmem_cache *s, 794 void *object, unsigned int orig_size) 795 { 796 void *p = kasan_reset_tag(object); 797 798 if (!slub_debug_orig_size(s)) 799 return; 800 801 p += get_info_end(s); 802 p += sizeof(struct track) * 2; 803 804 *(unsigned int *)p = orig_size; 805 } 806 807 static inline unsigned int get_orig_size(struct kmem_cache *s, void *object) 808 { 809 void *p = kasan_reset_tag(object); 810 811 if (is_kfence_address(object)) 812 return kfence_ksize(object); 813 814 if (!slub_debug_orig_size(s)) 815 return s->object_size; 816 817 p += get_info_end(s); 818 p += sizeof(struct track) * 2; 819 820 return *(unsigned int *)p; 821 } 822 823 #ifdef CONFIG_SLUB_DEBUG 824 static unsigned long object_map[BITS_TO_LONGS(MAX_OBJS_PER_PAGE)]; 825 static DEFINE_SPINLOCK(object_map_lock); 826 827 static void __fill_map(unsigned long *obj_map, struct kmem_cache *s, 828 struct slab *slab) 829 { 830 void *addr = slab_address(slab); 831 void *p; 832 833 bitmap_zero(obj_map, slab->objects); 834 835 for (p = slab->freelist; p; p = get_freepointer(s, p)) 836 set_bit(__obj_to_index(s, addr, p), obj_map); 837 } 838 839 #if IS_ENABLED(CONFIG_KUNIT) 840 static bool slab_add_kunit_errors(void) 841 { 842 struct kunit_resource *resource; 843 844 if (!kunit_get_current_test()) 845 return false; 846 847 resource = kunit_find_named_resource(current->kunit_test, "slab_errors"); 848 if (!resource) 849 return false; 850 851 (*(int *)resource->data)++; 852 kunit_put_resource(resource); 853 return true; 854 } 855 856 bool slab_in_kunit_test(void) 857 { 858 struct kunit_resource *resource; 859 860 if (!kunit_get_current_test()) 861 return false; 862 863 resource = kunit_find_named_resource(current->kunit_test, "slab_errors"); 864 if (!resource) 865 return false; 866 867 kunit_put_resource(resource); 868 return true; 869 } 870 #else 871 static inline bool slab_add_kunit_errors(void) { return false; } 872 #endif 873 874 static inline unsigned int size_from_object(struct kmem_cache *s) 875 { 876 if (s->flags & SLAB_RED_ZONE) 877 return s->size - s->red_left_pad; 878 879 return s->size; 880 } 881 882 static inline void *restore_red_left(struct kmem_cache *s, void *p) 883 { 884 if (s->flags & SLAB_RED_ZONE) 885 p -= s->red_left_pad; 886 887 return p; 888 } 889 890 /* 891 * Debug settings: 892 */ 893 #if defined(CONFIG_SLUB_DEBUG_ON) 894 static slab_flags_t slub_debug = DEBUG_DEFAULT_FLAGS; 895 #else 896 static slab_flags_t slub_debug; 897 #endif 898 899 static char *slub_debug_string; 900 static int disable_higher_order_debug; 901 902 /* 903 * slub is about to manipulate internal object metadata. This memory lies 904 * outside the range of the allocated object, so accessing it would normally 905 * be reported by kasan as a bounds error. metadata_access_enable() is used 906 * to tell kasan that these accesses are OK. 907 */ 908 static inline void metadata_access_enable(void) 909 { 910 kasan_disable_current(); 911 kmsan_disable_current(); 912 } 913 914 static inline void metadata_access_disable(void) 915 { 916 kmsan_enable_current(); 917 kasan_enable_current(); 918 } 919 920 /* 921 * Object debugging 922 */ 923 924 /* Verify that a pointer has an address that is valid within a slab page */ 925 static inline int check_valid_pointer(struct kmem_cache *s, 926 struct slab *slab, void *object) 927 { 928 void *base; 929 930 if (!object) 931 return 1; 932 933 base = slab_address(slab); 934 object = kasan_reset_tag(object); 935 object = restore_red_left(s, object); 936 if (object < base || object >= base + slab->objects * s->size || 937 (object - base) % s->size) { 938 return 0; 939 } 940 941 return 1; 942 } 943 944 static void print_section(char *level, char *text, u8 *addr, 945 unsigned int length) 946 { 947 metadata_access_enable(); 948 print_hex_dump(level, text, DUMP_PREFIX_ADDRESS, 949 16, 1, kasan_reset_tag((void *)addr), length, 1); 950 metadata_access_disable(); 951 } 952 953 static struct track *get_track(struct kmem_cache *s, void *object, 954 enum track_item alloc) 955 { 956 struct track *p; 957 958 p = object + get_info_end(s); 959 960 return kasan_reset_tag(p + alloc); 961 } 962 963 #ifdef CONFIG_STACKDEPOT 964 static noinline depot_stack_handle_t set_track_prepare(void) 965 { 966 depot_stack_handle_t handle; 967 unsigned long entries[TRACK_ADDRS_COUNT]; 968 unsigned int nr_entries; 969 970 nr_entries = stack_trace_save(entries, ARRAY_SIZE(entries), 3); 971 handle = stack_depot_save(entries, nr_entries, GFP_NOWAIT); 972 973 return handle; 974 } 975 #else 976 static inline depot_stack_handle_t set_track_prepare(void) 977 { 978 return 0; 979 } 980 #endif 981 982 static void set_track_update(struct kmem_cache *s, void *object, 983 enum track_item alloc, unsigned long addr, 984 depot_stack_handle_t handle) 985 { 986 struct track *p = get_track(s, object, alloc); 987 988 #ifdef CONFIG_STACKDEPOT 989 p->handle = handle; 990 #endif 991 p->addr = addr; 992 p->cpu = smp_processor_id(); 993 p->pid = current->pid; 994 p->when = jiffies; 995 } 996 997 static __always_inline void set_track(struct kmem_cache *s, void *object, 998 enum track_item alloc, unsigned long addr) 999 { 1000 depot_stack_handle_t handle = set_track_prepare(); 1001 1002 set_track_update(s, object, alloc, addr, handle); 1003 } 1004 1005 static void init_tracking(struct kmem_cache *s, void *object) 1006 { 1007 struct track *p; 1008 1009 if (!(s->flags & SLAB_STORE_USER)) 1010 return; 1011 1012 p = get_track(s, object, TRACK_ALLOC); 1013 memset(p, 0, 2*sizeof(struct track)); 1014 } 1015 1016 static void print_track(const char *s, struct track *t, unsigned long pr_time) 1017 { 1018 depot_stack_handle_t handle __maybe_unused; 1019 1020 if (!t->addr) 1021 return; 1022 1023 pr_err("%s in %pS age=%lu cpu=%u pid=%d\n", 1024 s, (void *)t->addr, pr_time - t->when, t->cpu, t->pid); 1025 #ifdef CONFIG_STACKDEPOT 1026 handle = READ_ONCE(t->handle); 1027 if (handle) 1028 stack_depot_print(handle); 1029 else 1030 pr_err("object allocation/free stack trace missing\n"); 1031 #endif 1032 } 1033 1034 void print_tracking(struct kmem_cache *s, void *object) 1035 { 1036 unsigned long pr_time = jiffies; 1037 if (!(s->flags & SLAB_STORE_USER)) 1038 return; 1039 1040 print_track("Allocated", get_track(s, object, TRACK_ALLOC), pr_time); 1041 print_track("Freed", get_track(s, object, TRACK_FREE), pr_time); 1042 } 1043 1044 static void print_slab_info(const struct slab *slab) 1045 { 1046 pr_err("Slab 0x%p objects=%u used=%u fp=0x%p flags=%pGp\n", 1047 slab, slab->objects, slab->inuse, slab->freelist, 1048 &slab->flags); 1049 } 1050 1051 void skip_orig_size_check(struct kmem_cache *s, const void *object) 1052 { 1053 set_orig_size(s, (void *)object, s->object_size); 1054 } 1055 1056 static void __slab_bug(struct kmem_cache *s, const char *fmt, va_list argsp) 1057 { 1058 struct va_format vaf; 1059 va_list args; 1060 1061 va_copy(args, argsp); 1062 vaf.fmt = fmt; 1063 vaf.va = &args; 1064 pr_err("=============================================================================\n"); 1065 pr_err("BUG %s (%s): %pV\n", s ? s->name : "<unknown>", print_tainted(), &vaf); 1066 pr_err("-----------------------------------------------------------------------------\n\n"); 1067 va_end(args); 1068 } 1069 1070 static void slab_bug(struct kmem_cache *s, const char *fmt, ...) 1071 { 1072 va_list args; 1073 1074 va_start(args, fmt); 1075 __slab_bug(s, fmt, args); 1076 va_end(args); 1077 } 1078 1079 __printf(2, 3) 1080 static void slab_fix(struct kmem_cache *s, const char *fmt, ...) 1081 { 1082 struct va_format vaf; 1083 va_list args; 1084 1085 if (slab_add_kunit_errors()) 1086 return; 1087 1088 va_start(args, fmt); 1089 vaf.fmt = fmt; 1090 vaf.va = &args; 1091 pr_err("FIX %s: %pV\n", s->name, &vaf); 1092 va_end(args); 1093 } 1094 1095 static void print_trailer(struct kmem_cache *s, struct slab *slab, u8 *p) 1096 { 1097 unsigned int off; /* Offset of last byte */ 1098 u8 *addr = slab_address(slab); 1099 1100 print_tracking(s, p); 1101 1102 print_slab_info(slab); 1103 1104 pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n", 1105 p, p - addr, get_freepointer(s, p)); 1106 1107 if (s->flags & SLAB_RED_ZONE) 1108 print_section(KERN_ERR, "Redzone ", p - s->red_left_pad, 1109 s->red_left_pad); 1110 else if (p > addr + 16) 1111 print_section(KERN_ERR, "Bytes b4 ", p - 16, 16); 1112 1113 print_section(KERN_ERR, "Object ", p, 1114 min_t(unsigned int, s->object_size, PAGE_SIZE)); 1115 if (s->flags & SLAB_RED_ZONE) 1116 print_section(KERN_ERR, "Redzone ", p + s->object_size, 1117 s->inuse - s->object_size); 1118 1119 off = get_info_end(s); 1120 1121 if (s->flags & SLAB_STORE_USER) 1122 off += 2 * sizeof(struct track); 1123 1124 if (slub_debug_orig_size(s)) 1125 off += sizeof(unsigned int); 1126 1127 off += kasan_metadata_size(s, false); 1128 1129 if (off != size_from_object(s)) 1130 /* Beginning of the filler is the free pointer */ 1131 print_section(KERN_ERR, "Padding ", p + off, 1132 size_from_object(s) - off); 1133 } 1134 1135 static void object_err(struct kmem_cache *s, struct slab *slab, 1136 u8 *object, const char *reason) 1137 { 1138 if (slab_add_kunit_errors()) 1139 return; 1140 1141 slab_bug(s, reason); 1142 print_trailer(s, slab, object); 1143 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 1144 1145 WARN_ON(1); 1146 } 1147 1148 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab, 1149 void **freelist, void *nextfree) 1150 { 1151 if ((s->flags & SLAB_CONSISTENCY_CHECKS) && 1152 !check_valid_pointer(s, slab, nextfree) && freelist) { 1153 object_err(s, slab, *freelist, "Freechain corrupt"); 1154 *freelist = NULL; 1155 slab_fix(s, "Isolate corrupted freechain"); 1156 return true; 1157 } 1158 1159 return false; 1160 } 1161 1162 static void __slab_err(struct slab *slab) 1163 { 1164 if (slab_in_kunit_test()) 1165 return; 1166 1167 print_slab_info(slab); 1168 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 1169 1170 WARN_ON(1); 1171 } 1172 1173 static __printf(3, 4) void slab_err(struct kmem_cache *s, struct slab *slab, 1174 const char *fmt, ...) 1175 { 1176 va_list args; 1177 1178 if (slab_add_kunit_errors()) 1179 return; 1180 1181 va_start(args, fmt); 1182 __slab_bug(s, fmt, args); 1183 va_end(args); 1184 1185 __slab_err(slab); 1186 } 1187 1188 static void init_object(struct kmem_cache *s, void *object, u8 val) 1189 { 1190 u8 *p = kasan_reset_tag(object); 1191 unsigned int poison_size = s->object_size; 1192 1193 if (s->flags & SLAB_RED_ZONE) { 1194 /* 1195 * Here and below, avoid overwriting the KMSAN shadow. Keeping 1196 * the shadow makes it possible to distinguish uninit-value 1197 * from use-after-free. 1198 */ 1199 memset_no_sanitize_memory(p - s->red_left_pad, val, 1200 s->red_left_pad); 1201 1202 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) { 1203 /* 1204 * Redzone the extra allocated space by kmalloc than 1205 * requested, and the poison size will be limited to 1206 * the original request size accordingly. 1207 */ 1208 poison_size = get_orig_size(s, object); 1209 } 1210 } 1211 1212 if (s->flags & __OBJECT_POISON) { 1213 memset_no_sanitize_memory(p, POISON_FREE, poison_size - 1); 1214 memset_no_sanitize_memory(p + poison_size - 1, POISON_END, 1); 1215 } 1216 1217 if (s->flags & SLAB_RED_ZONE) 1218 memset_no_sanitize_memory(p + poison_size, val, 1219 s->inuse - poison_size); 1220 } 1221 1222 static void restore_bytes(struct kmem_cache *s, const char *message, u8 data, 1223 void *from, void *to) 1224 { 1225 slab_fix(s, "Restoring %s 0x%p-0x%p=0x%x", message, from, to - 1, data); 1226 memset(from, data, to - from); 1227 } 1228 1229 #ifdef CONFIG_KMSAN 1230 #define pad_check_attributes noinline __no_kmsan_checks 1231 #else 1232 #define pad_check_attributes 1233 #endif 1234 1235 static pad_check_attributes int 1236 check_bytes_and_report(struct kmem_cache *s, struct slab *slab, 1237 u8 *object, const char *what, u8 *start, unsigned int value, 1238 unsigned int bytes, bool slab_obj_print) 1239 { 1240 u8 *fault; 1241 u8 *end; 1242 u8 *addr = slab_address(slab); 1243 1244 metadata_access_enable(); 1245 fault = memchr_inv(kasan_reset_tag(start), value, bytes); 1246 metadata_access_disable(); 1247 if (!fault) 1248 return 1; 1249 1250 end = start + bytes; 1251 while (end > fault && end[-1] == value) 1252 end--; 1253 1254 if (slab_add_kunit_errors()) 1255 goto skip_bug_print; 1256 1257 pr_err("[%s overwritten] 0x%p-0x%p @offset=%tu. First byte 0x%x instead of 0x%x\n", 1258 what, fault, end - 1, fault - addr, fault[0], value); 1259 1260 if (slab_obj_print) 1261 object_err(s, slab, object, "Object corrupt"); 1262 1263 skip_bug_print: 1264 restore_bytes(s, what, value, fault, end); 1265 return 0; 1266 } 1267 1268 /* 1269 * Object layout: 1270 * 1271 * object address 1272 * Bytes of the object to be managed. 1273 * If the freepointer may overlay the object then the free 1274 * pointer is at the middle of the object. 1275 * 1276 * Poisoning uses 0x6b (POISON_FREE) and the last byte is 1277 * 0xa5 (POISON_END) 1278 * 1279 * object + s->object_size 1280 * Padding to reach word boundary. This is also used for Redzoning. 1281 * Padding is extended by another word if Redzoning is enabled and 1282 * object_size == inuse. 1283 * 1284 * We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with 1285 * 0xcc (SLUB_RED_ACTIVE) for objects in use. 1286 * 1287 * object + s->inuse 1288 * Meta data starts here. 1289 * 1290 * A. Free pointer (if we cannot overwrite object on free) 1291 * B. Tracking data for SLAB_STORE_USER 1292 * C. Original request size for kmalloc object (SLAB_STORE_USER enabled) 1293 * D. Padding to reach required alignment boundary or at minimum 1294 * one word if debugging is on to be able to detect writes 1295 * before the word boundary. 1296 * 1297 * Padding is done using 0x5a (POISON_INUSE) 1298 * 1299 * object + s->size 1300 * Nothing is used beyond s->size. 1301 * 1302 * If slabcaches are merged then the object_size and inuse boundaries are mostly 1303 * ignored. And therefore no slab options that rely on these boundaries 1304 * may be used with merged slabcaches. 1305 */ 1306 1307 static int check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p) 1308 { 1309 unsigned long off = get_info_end(s); /* The end of info */ 1310 1311 if (s->flags & SLAB_STORE_USER) { 1312 /* We also have user information there */ 1313 off += 2 * sizeof(struct track); 1314 1315 if (s->flags & SLAB_KMALLOC) 1316 off += sizeof(unsigned int); 1317 } 1318 1319 off += kasan_metadata_size(s, false); 1320 1321 if (size_from_object(s) == off) 1322 return 1; 1323 1324 return check_bytes_and_report(s, slab, p, "Object padding", 1325 p + off, POISON_INUSE, size_from_object(s) - off, true); 1326 } 1327 1328 /* Check the pad bytes at the end of a slab page */ 1329 static pad_check_attributes void 1330 slab_pad_check(struct kmem_cache *s, struct slab *slab) 1331 { 1332 u8 *start; 1333 u8 *fault; 1334 u8 *end; 1335 u8 *pad; 1336 int length; 1337 int remainder; 1338 1339 if (!(s->flags & SLAB_POISON)) 1340 return; 1341 1342 start = slab_address(slab); 1343 length = slab_size(slab); 1344 end = start + length; 1345 remainder = length % s->size; 1346 if (!remainder) 1347 return; 1348 1349 pad = end - remainder; 1350 metadata_access_enable(); 1351 fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder); 1352 metadata_access_disable(); 1353 if (!fault) 1354 return; 1355 while (end > fault && end[-1] == POISON_INUSE) 1356 end--; 1357 1358 slab_bug(s, "Padding overwritten. 0x%p-0x%p @offset=%tu", 1359 fault, end - 1, fault - start); 1360 print_section(KERN_ERR, "Padding ", pad, remainder); 1361 __slab_err(slab); 1362 1363 restore_bytes(s, "slab padding", POISON_INUSE, fault, end); 1364 } 1365 1366 static int check_object(struct kmem_cache *s, struct slab *slab, 1367 void *object, u8 val) 1368 { 1369 u8 *p = object; 1370 u8 *endobject = object + s->object_size; 1371 unsigned int orig_size, kasan_meta_size; 1372 int ret = 1; 1373 1374 if (s->flags & SLAB_RED_ZONE) { 1375 if (!check_bytes_and_report(s, slab, object, "Left Redzone", 1376 object - s->red_left_pad, val, s->red_left_pad, ret)) 1377 ret = 0; 1378 1379 if (!check_bytes_and_report(s, slab, object, "Right Redzone", 1380 endobject, val, s->inuse - s->object_size, ret)) 1381 ret = 0; 1382 1383 if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) { 1384 orig_size = get_orig_size(s, object); 1385 1386 if (s->object_size > orig_size && 1387 !check_bytes_and_report(s, slab, object, 1388 "kmalloc Redzone", p + orig_size, 1389 val, s->object_size - orig_size, ret)) { 1390 ret = 0; 1391 } 1392 } 1393 } else { 1394 if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) { 1395 if (!check_bytes_and_report(s, slab, p, "Alignment padding", 1396 endobject, POISON_INUSE, 1397 s->inuse - s->object_size, ret)) 1398 ret = 0; 1399 } 1400 } 1401 1402 if (s->flags & SLAB_POISON) { 1403 if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) { 1404 /* 1405 * KASAN can save its free meta data inside of the 1406 * object at offset 0. Thus, skip checking the part of 1407 * the redzone that overlaps with the meta data. 1408 */ 1409 kasan_meta_size = kasan_metadata_size(s, true); 1410 if (kasan_meta_size < s->object_size - 1 && 1411 !check_bytes_and_report(s, slab, p, "Poison", 1412 p + kasan_meta_size, POISON_FREE, 1413 s->object_size - kasan_meta_size - 1, ret)) 1414 ret = 0; 1415 if (kasan_meta_size < s->object_size && 1416 !check_bytes_and_report(s, slab, p, "End Poison", 1417 p + s->object_size - 1, POISON_END, 1, ret)) 1418 ret = 0; 1419 } 1420 /* 1421 * check_pad_bytes cleans up on its own. 1422 */ 1423 if (!check_pad_bytes(s, slab, p)) 1424 ret = 0; 1425 } 1426 1427 /* 1428 * Cannot check freepointer while object is allocated if 1429 * object and freepointer overlap. 1430 */ 1431 if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) && 1432 !check_valid_pointer(s, slab, get_freepointer(s, p))) { 1433 object_err(s, slab, p, "Freepointer corrupt"); 1434 /* 1435 * No choice but to zap it and thus lose the remainder 1436 * of the free objects in this slab. May cause 1437 * another error because the object count is now wrong. 1438 */ 1439 set_freepointer(s, p, NULL); 1440 ret = 0; 1441 } 1442 1443 return ret; 1444 } 1445 1446 static int check_slab(struct kmem_cache *s, struct slab *slab) 1447 { 1448 int maxobj; 1449 1450 if (!folio_test_slab(slab_folio(slab))) { 1451 slab_err(s, slab, "Not a valid slab page"); 1452 return 0; 1453 } 1454 1455 maxobj = order_objects(slab_order(slab), s->size); 1456 if (slab->objects > maxobj) { 1457 slab_err(s, slab, "objects %u > max %u", 1458 slab->objects, maxobj); 1459 return 0; 1460 } 1461 if (slab->inuse > slab->objects) { 1462 slab_err(s, slab, "inuse %u > max %u", 1463 slab->inuse, slab->objects); 1464 return 0; 1465 } 1466 if (slab->frozen) { 1467 slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed"); 1468 return 0; 1469 } 1470 1471 /* Slab_pad_check fixes things up after itself */ 1472 slab_pad_check(s, slab); 1473 return 1; 1474 } 1475 1476 /* 1477 * Determine if a certain object in a slab is on the freelist. Must hold the 1478 * slab lock to guarantee that the chains are in a consistent state. 1479 */ 1480 static bool on_freelist(struct kmem_cache *s, struct slab *slab, void *search) 1481 { 1482 int nr = 0; 1483 void *fp; 1484 void *object = NULL; 1485 int max_objects; 1486 1487 fp = slab->freelist; 1488 while (fp && nr <= slab->objects) { 1489 if (fp == search) 1490 return true; 1491 if (!check_valid_pointer(s, slab, fp)) { 1492 if (object) { 1493 object_err(s, slab, object, 1494 "Freechain corrupt"); 1495 set_freepointer(s, object, NULL); 1496 break; 1497 } else { 1498 slab_err(s, slab, "Freepointer corrupt"); 1499 slab->freelist = NULL; 1500 slab->inuse = slab->objects; 1501 slab_fix(s, "Freelist cleared"); 1502 return false; 1503 } 1504 } 1505 object = fp; 1506 fp = get_freepointer(s, object); 1507 nr++; 1508 } 1509 1510 if (nr > slab->objects) { 1511 slab_err(s, slab, "Freelist cycle detected"); 1512 slab->freelist = NULL; 1513 slab->inuse = slab->objects; 1514 slab_fix(s, "Freelist cleared"); 1515 return false; 1516 } 1517 1518 max_objects = order_objects(slab_order(slab), s->size); 1519 if (max_objects > MAX_OBJS_PER_PAGE) 1520 max_objects = MAX_OBJS_PER_PAGE; 1521 1522 if (slab->objects != max_objects) { 1523 slab_err(s, slab, "Wrong number of objects. Found %d but should be %d", 1524 slab->objects, max_objects); 1525 slab->objects = max_objects; 1526 slab_fix(s, "Number of objects adjusted"); 1527 } 1528 if (slab->inuse != slab->objects - nr) { 1529 slab_err(s, slab, "Wrong object count. Counter is %d but counted were %d", 1530 slab->inuse, slab->objects - nr); 1531 slab->inuse = slab->objects - nr; 1532 slab_fix(s, "Object count adjusted"); 1533 } 1534 return search == NULL; 1535 } 1536 1537 static void trace(struct kmem_cache *s, struct slab *slab, void *object, 1538 int alloc) 1539 { 1540 if (s->flags & SLAB_TRACE) { 1541 pr_info("TRACE %s %s 0x%p inuse=%d fp=0x%p\n", 1542 s->name, 1543 alloc ? "alloc" : "free", 1544 object, slab->inuse, 1545 slab->freelist); 1546 1547 if (!alloc) 1548 print_section(KERN_INFO, "Object ", (void *)object, 1549 s->object_size); 1550 1551 dump_stack(); 1552 } 1553 } 1554 1555 /* 1556 * Tracking of fully allocated slabs for debugging purposes. 1557 */ 1558 static void add_full(struct kmem_cache *s, 1559 struct kmem_cache_node *n, struct slab *slab) 1560 { 1561 if (!(s->flags & SLAB_STORE_USER)) 1562 return; 1563 1564 lockdep_assert_held(&n->list_lock); 1565 list_add(&slab->slab_list, &n->full); 1566 } 1567 1568 static void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab) 1569 { 1570 if (!(s->flags & SLAB_STORE_USER)) 1571 return; 1572 1573 lockdep_assert_held(&n->list_lock); 1574 list_del(&slab->slab_list); 1575 } 1576 1577 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n) 1578 { 1579 return atomic_long_read(&n->nr_slabs); 1580 } 1581 1582 static inline void inc_slabs_node(struct kmem_cache *s, int node, int objects) 1583 { 1584 struct kmem_cache_node *n = get_node(s, node); 1585 1586 atomic_long_inc(&n->nr_slabs); 1587 atomic_long_add(objects, &n->total_objects); 1588 } 1589 static inline void dec_slabs_node(struct kmem_cache *s, int node, int objects) 1590 { 1591 struct kmem_cache_node *n = get_node(s, node); 1592 1593 atomic_long_dec(&n->nr_slabs); 1594 atomic_long_sub(objects, &n->total_objects); 1595 } 1596 1597 /* Object debug checks for alloc/free paths */ 1598 static void setup_object_debug(struct kmem_cache *s, void *object) 1599 { 1600 if (!kmem_cache_debug_flags(s, SLAB_STORE_USER|SLAB_RED_ZONE|__OBJECT_POISON)) 1601 return; 1602 1603 init_object(s, object, SLUB_RED_INACTIVE); 1604 init_tracking(s, object); 1605 } 1606 1607 static 1608 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) 1609 { 1610 if (!kmem_cache_debug_flags(s, SLAB_POISON)) 1611 return; 1612 1613 metadata_access_enable(); 1614 memset(kasan_reset_tag(addr), POISON_INUSE, slab_size(slab)); 1615 metadata_access_disable(); 1616 } 1617 1618 static inline int alloc_consistency_checks(struct kmem_cache *s, 1619 struct slab *slab, void *object) 1620 { 1621 if (!check_slab(s, slab)) 1622 return 0; 1623 1624 if (!check_valid_pointer(s, slab, object)) { 1625 object_err(s, slab, object, "Freelist Pointer check fails"); 1626 return 0; 1627 } 1628 1629 if (!check_object(s, slab, object, SLUB_RED_INACTIVE)) 1630 return 0; 1631 1632 return 1; 1633 } 1634 1635 static noinline bool alloc_debug_processing(struct kmem_cache *s, 1636 struct slab *slab, void *object, int orig_size) 1637 { 1638 if (s->flags & SLAB_CONSISTENCY_CHECKS) { 1639 if (!alloc_consistency_checks(s, slab, object)) 1640 goto bad; 1641 } 1642 1643 /* Success. Perform special debug activities for allocs */ 1644 trace(s, slab, object, 1); 1645 set_orig_size(s, object, orig_size); 1646 init_object(s, object, SLUB_RED_ACTIVE); 1647 return true; 1648 1649 bad: 1650 if (folio_test_slab(slab_folio(slab))) { 1651 /* 1652 * If this is a slab page then lets do the best we can 1653 * to avoid issues in the future. Marking all objects 1654 * as used avoids touching the remaining objects. 1655 */ 1656 slab_fix(s, "Marking all objects used"); 1657 slab->inuse = slab->objects; 1658 slab->freelist = NULL; 1659 slab->frozen = 1; /* mark consistency-failed slab as frozen */ 1660 } 1661 return false; 1662 } 1663 1664 static inline int free_consistency_checks(struct kmem_cache *s, 1665 struct slab *slab, void *object, unsigned long addr) 1666 { 1667 if (!check_valid_pointer(s, slab, object)) { 1668 slab_err(s, slab, "Invalid object pointer 0x%p", object); 1669 return 0; 1670 } 1671 1672 if (on_freelist(s, slab, object)) { 1673 object_err(s, slab, object, "Object already free"); 1674 return 0; 1675 } 1676 1677 if (!check_object(s, slab, object, SLUB_RED_ACTIVE)) 1678 return 0; 1679 1680 if (unlikely(s != slab->slab_cache)) { 1681 if (!folio_test_slab(slab_folio(slab))) { 1682 slab_err(s, slab, "Attempt to free object(0x%p) outside of slab", 1683 object); 1684 } else if (!slab->slab_cache) { 1685 slab_err(NULL, slab, "No slab cache for object 0x%p", 1686 object); 1687 } else { 1688 object_err(s, slab, object, 1689 "page slab pointer corrupt."); 1690 } 1691 return 0; 1692 } 1693 return 1; 1694 } 1695 1696 /* 1697 * Parse a block of slab_debug options. Blocks are delimited by ';' 1698 * 1699 * @str: start of block 1700 * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified 1701 * @slabs: return start of list of slabs, or NULL when there's no list 1702 * @init: assume this is initial parsing and not per-kmem-create parsing 1703 * 1704 * returns the start of next block if there's any, or NULL 1705 */ 1706 static char * 1707 parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init) 1708 { 1709 bool higher_order_disable = false; 1710 1711 /* Skip any completely empty blocks */ 1712 while (*str && *str == ';') 1713 str++; 1714 1715 if (*str == ',') { 1716 /* 1717 * No options but restriction on slabs. This means full 1718 * debugging for slabs matching a pattern. 1719 */ 1720 *flags = DEBUG_DEFAULT_FLAGS; 1721 goto check_slabs; 1722 } 1723 *flags = 0; 1724 1725 /* Determine which debug features should be switched on */ 1726 for (; *str && *str != ',' && *str != ';'; str++) { 1727 switch (tolower(*str)) { 1728 case '-': 1729 *flags = 0; 1730 break; 1731 case 'f': 1732 *flags |= SLAB_CONSISTENCY_CHECKS; 1733 break; 1734 case 'z': 1735 *flags |= SLAB_RED_ZONE; 1736 break; 1737 case 'p': 1738 *flags |= SLAB_POISON; 1739 break; 1740 case 'u': 1741 *flags |= SLAB_STORE_USER; 1742 break; 1743 case 't': 1744 *flags |= SLAB_TRACE; 1745 break; 1746 case 'a': 1747 *flags |= SLAB_FAILSLAB; 1748 break; 1749 case 'o': 1750 /* 1751 * Avoid enabling debugging on caches if its minimum 1752 * order would increase as a result. 1753 */ 1754 higher_order_disable = true; 1755 break; 1756 default: 1757 if (init) 1758 pr_err("slab_debug option '%c' unknown. skipped\n", *str); 1759 } 1760 } 1761 check_slabs: 1762 if (*str == ',') 1763 *slabs = ++str; 1764 else 1765 *slabs = NULL; 1766 1767 /* Skip over the slab list */ 1768 while (*str && *str != ';') 1769 str++; 1770 1771 /* Skip any completely empty blocks */ 1772 while (*str && *str == ';') 1773 str++; 1774 1775 if (init && higher_order_disable) 1776 disable_higher_order_debug = 1; 1777 1778 if (*str) 1779 return str; 1780 else 1781 return NULL; 1782 } 1783 1784 static int __init setup_slub_debug(char *str) 1785 { 1786 slab_flags_t flags; 1787 slab_flags_t global_flags; 1788 char *saved_str; 1789 char *slab_list; 1790 bool global_slub_debug_changed = false; 1791 bool slab_list_specified = false; 1792 1793 global_flags = DEBUG_DEFAULT_FLAGS; 1794 if (*str++ != '=' || !*str) 1795 /* 1796 * No options specified. Switch on full debugging. 1797 */ 1798 goto out; 1799 1800 saved_str = str; 1801 while (str) { 1802 str = parse_slub_debug_flags(str, &flags, &slab_list, true); 1803 1804 if (!slab_list) { 1805 global_flags = flags; 1806 global_slub_debug_changed = true; 1807 } else { 1808 slab_list_specified = true; 1809 if (flags & SLAB_STORE_USER) 1810 stack_depot_request_early_init(); 1811 } 1812 } 1813 1814 /* 1815 * For backwards compatibility, a single list of flags with list of 1816 * slabs means debugging is only changed for those slabs, so the global 1817 * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending 1818 * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as 1819 * long as there is no option specifying flags without a slab list. 1820 */ 1821 if (slab_list_specified) { 1822 if (!global_slub_debug_changed) 1823 global_flags = slub_debug; 1824 slub_debug_string = saved_str; 1825 } 1826 out: 1827 slub_debug = global_flags; 1828 if (slub_debug & SLAB_STORE_USER) 1829 stack_depot_request_early_init(); 1830 if (slub_debug != 0 || slub_debug_string) 1831 static_branch_enable(&slub_debug_enabled); 1832 else 1833 static_branch_disable(&slub_debug_enabled); 1834 if ((static_branch_unlikely(&init_on_alloc) || 1835 static_branch_unlikely(&init_on_free)) && 1836 (slub_debug & SLAB_POISON)) 1837 pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n"); 1838 return 1; 1839 } 1840 1841 __setup("slab_debug", setup_slub_debug); 1842 __setup_param("slub_debug", slub_debug, setup_slub_debug, 0); 1843 1844 /* 1845 * kmem_cache_flags - apply debugging options to the cache 1846 * @flags: flags to set 1847 * @name: name of the cache 1848 * 1849 * Debug option(s) are applied to @flags. In addition to the debug 1850 * option(s), if a slab name (or multiple) is specified i.e. 1851 * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ... 1852 * then only the select slabs will receive the debug option(s). 1853 */ 1854 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name) 1855 { 1856 char *iter; 1857 size_t len; 1858 char *next_block; 1859 slab_flags_t block_flags; 1860 slab_flags_t slub_debug_local = slub_debug; 1861 1862 if (flags & SLAB_NO_USER_FLAGS) 1863 return flags; 1864 1865 /* 1866 * If the slab cache is for debugging (e.g. kmemleak) then 1867 * don't store user (stack trace) information by default, 1868 * but let the user enable it via the command line below. 1869 */ 1870 if (flags & SLAB_NOLEAKTRACE) 1871 slub_debug_local &= ~SLAB_STORE_USER; 1872 1873 len = strlen(name); 1874 next_block = slub_debug_string; 1875 /* Go through all blocks of debug options, see if any matches our slab's name */ 1876 while (next_block) { 1877 next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false); 1878 if (!iter) 1879 continue; 1880 /* Found a block that has a slab list, search it */ 1881 while (*iter) { 1882 char *end, *glob; 1883 size_t cmplen; 1884 1885 end = strchrnul(iter, ','); 1886 if (next_block && next_block < end) 1887 end = next_block - 1; 1888 1889 glob = strnchr(iter, end - iter, '*'); 1890 if (glob) 1891 cmplen = glob - iter; 1892 else 1893 cmplen = max_t(size_t, len, (end - iter)); 1894 1895 if (!strncmp(name, iter, cmplen)) { 1896 flags |= block_flags; 1897 return flags; 1898 } 1899 1900 if (!*end || *end == ';') 1901 break; 1902 iter = end + 1; 1903 } 1904 } 1905 1906 return flags | slub_debug_local; 1907 } 1908 #else /* !CONFIG_SLUB_DEBUG */ 1909 static inline void setup_object_debug(struct kmem_cache *s, void *object) {} 1910 static inline 1911 void setup_slab_debug(struct kmem_cache *s, struct slab *slab, void *addr) {} 1912 1913 static inline bool alloc_debug_processing(struct kmem_cache *s, 1914 struct slab *slab, void *object, int orig_size) { return true; } 1915 1916 static inline bool free_debug_processing(struct kmem_cache *s, 1917 struct slab *slab, void *head, void *tail, int *bulk_cnt, 1918 unsigned long addr, depot_stack_handle_t handle) { return true; } 1919 1920 static inline void slab_pad_check(struct kmem_cache *s, struct slab *slab) {} 1921 static inline int check_object(struct kmem_cache *s, struct slab *slab, 1922 void *object, u8 val) { return 1; } 1923 static inline depot_stack_handle_t set_track_prepare(void) { return 0; } 1924 static inline void set_track(struct kmem_cache *s, void *object, 1925 enum track_item alloc, unsigned long addr) {} 1926 static inline void add_full(struct kmem_cache *s, struct kmem_cache_node *n, 1927 struct slab *slab) {} 1928 static inline void remove_full(struct kmem_cache *s, struct kmem_cache_node *n, 1929 struct slab *slab) {} 1930 slab_flags_t kmem_cache_flags(slab_flags_t flags, const char *name) 1931 { 1932 return flags; 1933 } 1934 #define slub_debug 0 1935 1936 #define disable_higher_order_debug 0 1937 1938 static inline unsigned long node_nr_slabs(struct kmem_cache_node *n) 1939 { return 0; } 1940 static inline void inc_slabs_node(struct kmem_cache *s, int node, 1941 int objects) {} 1942 static inline void dec_slabs_node(struct kmem_cache *s, int node, 1943 int objects) {} 1944 #ifndef CONFIG_SLUB_TINY 1945 static bool freelist_corrupted(struct kmem_cache *s, struct slab *slab, 1946 void **freelist, void *nextfree) 1947 { 1948 return false; 1949 } 1950 #endif 1951 #endif /* CONFIG_SLUB_DEBUG */ 1952 1953 #ifdef CONFIG_SLAB_OBJ_EXT 1954 1955 #ifdef CONFIG_MEM_ALLOC_PROFILING_DEBUG 1956 1957 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) 1958 { 1959 struct slabobj_ext *slab_exts; 1960 struct slab *obj_exts_slab; 1961 1962 obj_exts_slab = virt_to_slab(obj_exts); 1963 slab_exts = slab_obj_exts(obj_exts_slab); 1964 if (slab_exts) { 1965 unsigned int offs = obj_to_index(obj_exts_slab->slab_cache, 1966 obj_exts_slab, obj_exts); 1967 /* codetag should be NULL */ 1968 WARN_ON(slab_exts[offs].ref.ct); 1969 set_codetag_empty(&slab_exts[offs].ref); 1970 } 1971 } 1972 1973 static inline void mark_failed_objexts_alloc(struct slab *slab) 1974 { 1975 slab->obj_exts = OBJEXTS_ALLOC_FAIL; 1976 } 1977 1978 static inline void handle_failed_objexts_alloc(unsigned long obj_exts, 1979 struct slabobj_ext *vec, unsigned int objects) 1980 { 1981 /* 1982 * If vector previously failed to allocate then we have live 1983 * objects with no tag reference. Mark all references in this 1984 * vector as empty to avoid warnings later on. 1985 */ 1986 if (obj_exts & OBJEXTS_ALLOC_FAIL) { 1987 unsigned int i; 1988 1989 for (i = 0; i < objects; i++) 1990 set_codetag_empty(&vec[i].ref); 1991 } 1992 } 1993 1994 #else /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */ 1995 1996 static inline void mark_objexts_empty(struct slabobj_ext *obj_exts) {} 1997 static inline void mark_failed_objexts_alloc(struct slab *slab) {} 1998 static inline void handle_failed_objexts_alloc(unsigned long obj_exts, 1999 struct slabobj_ext *vec, unsigned int objects) {} 2000 2001 #endif /* CONFIG_MEM_ALLOC_PROFILING_DEBUG */ 2002 2003 /* 2004 * The allocated objcg pointers array is not accounted directly. 2005 * Moreover, it should not come from DMA buffer and is not readily 2006 * reclaimable. So those GFP bits should be masked off. 2007 */ 2008 #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \ 2009 __GFP_ACCOUNT | __GFP_NOFAIL) 2010 2011 static inline void init_slab_obj_exts(struct slab *slab) 2012 { 2013 slab->obj_exts = 0; 2014 } 2015 2016 int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s, 2017 gfp_t gfp, bool new_slab) 2018 { 2019 unsigned int objects = objs_per_slab(s, slab); 2020 unsigned long new_exts; 2021 unsigned long old_exts; 2022 struct slabobj_ext *vec; 2023 2024 gfp &= ~OBJCGS_CLEAR_MASK; 2025 /* Prevent recursive extension vector allocation */ 2026 gfp |= __GFP_NO_OBJ_EXT; 2027 vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp, 2028 slab_nid(slab)); 2029 if (!vec) { 2030 /* Mark vectors which failed to allocate */ 2031 if (new_slab) 2032 mark_failed_objexts_alloc(slab); 2033 2034 return -ENOMEM; 2035 } 2036 2037 new_exts = (unsigned long)vec; 2038 #ifdef CONFIG_MEMCG 2039 new_exts |= MEMCG_DATA_OBJEXTS; 2040 #endif 2041 old_exts = READ_ONCE(slab->obj_exts); 2042 handle_failed_objexts_alloc(old_exts, vec, objects); 2043 if (new_slab) { 2044 /* 2045 * If the slab is brand new and nobody can yet access its 2046 * obj_exts, no synchronization is required and obj_exts can 2047 * be simply assigned. 2048 */ 2049 slab->obj_exts = new_exts; 2050 } else if ((old_exts & ~OBJEXTS_FLAGS_MASK) || 2051 cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) { 2052 /* 2053 * If the slab is already in use, somebody can allocate and 2054 * assign slabobj_exts in parallel. In this case the existing 2055 * objcg vector should be reused. 2056 */ 2057 mark_objexts_empty(vec); 2058 kfree(vec); 2059 return 0; 2060 } 2061 2062 kmemleak_not_leak(vec); 2063 return 0; 2064 } 2065 2066 static inline void free_slab_obj_exts(struct slab *slab) 2067 { 2068 struct slabobj_ext *obj_exts; 2069 2070 obj_exts = slab_obj_exts(slab); 2071 if (!obj_exts) 2072 return; 2073 2074 /* 2075 * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its 2076 * corresponding extension will be NULL. alloc_tag_sub() will throw a 2077 * warning if slab has extensions but the extension of an object is 2078 * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that 2079 * the extension for obj_exts is expected to be NULL. 2080 */ 2081 mark_objexts_empty(obj_exts); 2082 kfree(obj_exts); 2083 slab->obj_exts = 0; 2084 } 2085 2086 #else /* CONFIG_SLAB_OBJ_EXT */ 2087 2088 static inline void init_slab_obj_exts(struct slab *slab) 2089 { 2090 } 2091 2092 static int alloc_slab_obj_exts(struct slab *slab, struct kmem_cache *s, 2093 gfp_t gfp, bool new_slab) 2094 { 2095 return 0; 2096 } 2097 2098 static inline void free_slab_obj_exts(struct slab *slab) 2099 { 2100 } 2101 2102 #endif /* CONFIG_SLAB_OBJ_EXT */ 2103 2104 #ifdef CONFIG_MEM_ALLOC_PROFILING 2105 2106 static inline struct slabobj_ext * 2107 prepare_slab_obj_exts_hook(struct kmem_cache *s, gfp_t flags, void *p) 2108 { 2109 struct slab *slab; 2110 2111 if (!p) 2112 return NULL; 2113 2114 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE)) 2115 return NULL; 2116 2117 if (flags & __GFP_NO_OBJ_EXT) 2118 return NULL; 2119 2120 slab = virt_to_slab(p); 2121 if (!slab_obj_exts(slab) && 2122 alloc_slab_obj_exts(slab, s, flags, false)) { 2123 pr_warn_once("%s, %s: Failed to create slab extension vector!\n", 2124 __func__, s->name); 2125 return NULL; 2126 } 2127 2128 return slab_obj_exts(slab) + obj_to_index(s, slab, p); 2129 } 2130 2131 /* Should be called only if mem_alloc_profiling_enabled() */ 2132 static noinline void 2133 __alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags) 2134 { 2135 struct slabobj_ext *obj_exts; 2136 2137 obj_exts = prepare_slab_obj_exts_hook(s, flags, object); 2138 /* 2139 * Currently obj_exts is used only for allocation profiling. 2140 * If other users appear then mem_alloc_profiling_enabled() 2141 * check should be added before alloc_tag_add(). 2142 */ 2143 if (likely(obj_exts)) 2144 alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size); 2145 } 2146 2147 static inline void 2148 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags) 2149 { 2150 if (mem_alloc_profiling_enabled()) 2151 __alloc_tagging_slab_alloc_hook(s, object, flags); 2152 } 2153 2154 /* Should be called only if mem_alloc_profiling_enabled() */ 2155 static noinline void 2156 __alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, 2157 int objects) 2158 { 2159 struct slabobj_ext *obj_exts; 2160 int i; 2161 2162 /* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */ 2163 if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE)) 2164 return; 2165 2166 obj_exts = slab_obj_exts(slab); 2167 if (!obj_exts) 2168 return; 2169 2170 for (i = 0; i < objects; i++) { 2171 unsigned int off = obj_to_index(s, slab, p[i]); 2172 2173 alloc_tag_sub(&obj_exts[off].ref, s->size); 2174 } 2175 } 2176 2177 static inline void 2178 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, 2179 int objects) 2180 { 2181 if (mem_alloc_profiling_enabled()) 2182 __alloc_tagging_slab_free_hook(s, slab, p, objects); 2183 } 2184 2185 #else /* CONFIG_MEM_ALLOC_PROFILING */ 2186 2187 static inline void 2188 alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags) 2189 { 2190 } 2191 2192 static inline void 2193 alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, 2194 int objects) 2195 { 2196 } 2197 2198 #endif /* CONFIG_MEM_ALLOC_PROFILING */ 2199 2200 2201 #ifdef CONFIG_MEMCG 2202 2203 static void memcg_alloc_abort_single(struct kmem_cache *s, void *object); 2204 2205 static __fastpath_inline 2206 bool memcg_slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru, 2207 gfp_t flags, size_t size, void **p) 2208 { 2209 if (likely(!memcg_kmem_online())) 2210 return true; 2211 2212 if (likely(!(flags & __GFP_ACCOUNT) && !(s->flags & SLAB_ACCOUNT))) 2213 return true; 2214 2215 if (likely(__memcg_slab_post_alloc_hook(s, lru, flags, size, p))) 2216 return true; 2217 2218 if (likely(size == 1)) { 2219 memcg_alloc_abort_single(s, *p); 2220 *p = NULL; 2221 } else { 2222 kmem_cache_free_bulk(s, size, p); 2223 } 2224 2225 return false; 2226 } 2227 2228 static __fastpath_inline 2229 void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, 2230 int objects) 2231 { 2232 struct slabobj_ext *obj_exts; 2233 2234 if (!memcg_kmem_online()) 2235 return; 2236 2237 obj_exts = slab_obj_exts(slab); 2238 if (likely(!obj_exts)) 2239 return; 2240 2241 __memcg_slab_free_hook(s, slab, p, objects, obj_exts); 2242 } 2243 2244 static __fastpath_inline 2245 bool memcg_slab_post_charge(void *p, gfp_t flags) 2246 { 2247 struct slabobj_ext *slab_exts; 2248 struct kmem_cache *s; 2249 struct folio *folio; 2250 struct slab *slab; 2251 unsigned long off; 2252 2253 folio = virt_to_folio(p); 2254 if (!folio_test_slab(folio)) { 2255 int size; 2256 2257 if (folio_memcg_kmem(folio)) 2258 return true; 2259 2260 if (__memcg_kmem_charge_page(folio_page(folio, 0), flags, 2261 folio_order(folio))) 2262 return false; 2263 2264 /* 2265 * This folio has already been accounted in the global stats but 2266 * not in the memcg stats. So, subtract from the global and use 2267 * the interface which adds to both global and memcg stats. 2268 */ 2269 size = folio_size(folio); 2270 node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size); 2271 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size); 2272 return true; 2273 } 2274 2275 slab = folio_slab(folio); 2276 s = slab->slab_cache; 2277 2278 /* 2279 * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency 2280 * of slab_obj_exts being allocated from the same slab and thus the slab 2281 * becoming effectively unfreeable. 2282 */ 2283 if (is_kmalloc_normal(s)) 2284 return true; 2285 2286 /* Ignore already charged objects. */ 2287 slab_exts = slab_obj_exts(slab); 2288 if (slab_exts) { 2289 off = obj_to_index(s, slab, p); 2290 if (unlikely(slab_exts[off].objcg)) 2291 return true; 2292 } 2293 2294 return __memcg_slab_post_alloc_hook(s, NULL, flags, 1, &p); 2295 } 2296 2297 #else /* CONFIG_MEMCG */ 2298 static inline bool memcg_slab_post_alloc_hook(struct kmem_cache *s, 2299 struct list_lru *lru, 2300 gfp_t flags, size_t size, 2301 void **p) 2302 { 2303 return true; 2304 } 2305 2306 static inline void memcg_slab_free_hook(struct kmem_cache *s, struct slab *slab, 2307 void **p, int objects) 2308 { 2309 } 2310 2311 static inline bool memcg_slab_post_charge(void *p, gfp_t flags) 2312 { 2313 return true; 2314 } 2315 #endif /* CONFIG_MEMCG */ 2316 2317 #ifdef CONFIG_SLUB_RCU_DEBUG 2318 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head); 2319 2320 struct rcu_delayed_free { 2321 struct rcu_head head; 2322 void *object; 2323 }; 2324 #endif 2325 2326 /* 2327 * Hooks for other subsystems that check memory allocations. In a typical 2328 * production configuration these hooks all should produce no code at all. 2329 * 2330 * Returns true if freeing of the object can proceed, false if its reuse 2331 * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned 2332 * to KFENCE. 2333 */ 2334 static __always_inline 2335 bool slab_free_hook(struct kmem_cache *s, void *x, bool init, 2336 bool after_rcu_delay) 2337 { 2338 /* Are the object contents still accessible? */ 2339 bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay; 2340 2341 kmemleak_free_recursive(x, s->flags); 2342 kmsan_slab_free(s, x); 2343 2344 debug_check_no_locks_freed(x, s->object_size); 2345 2346 if (!(s->flags & SLAB_DEBUG_OBJECTS)) 2347 debug_check_no_obj_freed(x, s->object_size); 2348 2349 /* Use KCSAN to help debug racy use-after-free. */ 2350 if (!still_accessible) 2351 __kcsan_check_access(x, s->object_size, 2352 KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT); 2353 2354 if (kfence_free(x)) 2355 return false; 2356 2357 /* 2358 * Give KASAN a chance to notice an invalid free operation before we 2359 * modify the object. 2360 */ 2361 if (kasan_slab_pre_free(s, x)) 2362 return false; 2363 2364 #ifdef CONFIG_SLUB_RCU_DEBUG 2365 if (still_accessible) { 2366 struct rcu_delayed_free *delayed_free; 2367 2368 delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT); 2369 if (delayed_free) { 2370 /* 2371 * Let KASAN track our call stack as a "related work 2372 * creation", just like if the object had been freed 2373 * normally via kfree_rcu(). 2374 * We have to do this manually because the rcu_head is 2375 * not located inside the object. 2376 */ 2377 kasan_record_aux_stack(x); 2378 2379 delayed_free->object = x; 2380 call_rcu(&delayed_free->head, slab_free_after_rcu_debug); 2381 return false; 2382 } 2383 } 2384 #endif /* CONFIG_SLUB_RCU_DEBUG */ 2385 2386 /* 2387 * As memory initialization might be integrated into KASAN, 2388 * kasan_slab_free and initialization memset's must be 2389 * kept together to avoid discrepancies in behavior. 2390 * 2391 * The initialization memset's clear the object and the metadata, 2392 * but don't touch the SLAB redzone. 2393 * 2394 * The object's freepointer is also avoided if stored outside the 2395 * object. 2396 */ 2397 if (unlikely(init)) { 2398 int rsize; 2399 unsigned int inuse, orig_size; 2400 2401 inuse = get_info_end(s); 2402 orig_size = get_orig_size(s, x); 2403 if (!kasan_has_integrated_init()) 2404 memset(kasan_reset_tag(x), 0, orig_size); 2405 rsize = (s->flags & SLAB_RED_ZONE) ? s->red_left_pad : 0; 2406 memset((char *)kasan_reset_tag(x) + inuse, 0, 2407 s->size - inuse - rsize); 2408 /* 2409 * Restore orig_size, otherwize kmalloc redzone overwritten 2410 * would be reported 2411 */ 2412 set_orig_size(s, x, orig_size); 2413 2414 } 2415 /* KASAN might put x into memory quarantine, delaying its reuse. */ 2416 return !kasan_slab_free(s, x, init, still_accessible); 2417 } 2418 2419 static __fastpath_inline 2420 bool slab_free_freelist_hook(struct kmem_cache *s, void **head, void **tail, 2421 int *cnt) 2422 { 2423 2424 void *object; 2425 void *next = *head; 2426 void *old_tail = *tail; 2427 bool init; 2428 2429 if (is_kfence_address(next)) { 2430 slab_free_hook(s, next, false, false); 2431 return false; 2432 } 2433 2434 /* Head and tail of the reconstructed freelist */ 2435 *head = NULL; 2436 *tail = NULL; 2437 2438 init = slab_want_init_on_free(s); 2439 2440 do { 2441 object = next; 2442 next = get_freepointer(s, object); 2443 2444 /* If object's reuse doesn't have to be delayed */ 2445 if (likely(slab_free_hook(s, object, init, false))) { 2446 /* Move object to the new freelist */ 2447 set_freepointer(s, object, *head); 2448 *head = object; 2449 if (!*tail) 2450 *tail = object; 2451 } else { 2452 /* 2453 * Adjust the reconstructed freelist depth 2454 * accordingly if object's reuse is delayed. 2455 */ 2456 --(*cnt); 2457 } 2458 } while (object != old_tail); 2459 2460 return *head != NULL; 2461 } 2462 2463 static void *setup_object(struct kmem_cache *s, void *object) 2464 { 2465 setup_object_debug(s, object); 2466 object = kasan_init_slab_obj(s, object); 2467 if (unlikely(s->ctor)) { 2468 kasan_unpoison_new_object(s, object); 2469 s->ctor(object); 2470 kasan_poison_new_object(s, object); 2471 } 2472 return object; 2473 } 2474 2475 /* 2476 * Slab allocation and freeing 2477 */ 2478 static inline struct slab *alloc_slab_page(gfp_t flags, int node, 2479 struct kmem_cache_order_objects oo) 2480 { 2481 struct folio *folio; 2482 struct slab *slab; 2483 unsigned int order = oo_order(oo); 2484 2485 if (node == NUMA_NO_NODE) 2486 folio = (struct folio *)alloc_frozen_pages(flags, order); 2487 else 2488 folio = (struct folio *)__alloc_frozen_pages(flags, order, node, NULL); 2489 2490 if (!folio) 2491 return NULL; 2492 2493 slab = folio_slab(folio); 2494 __folio_set_slab(folio); 2495 if (folio_is_pfmemalloc(folio)) 2496 slab_set_pfmemalloc(slab); 2497 2498 return slab; 2499 } 2500 2501 #ifdef CONFIG_SLAB_FREELIST_RANDOM 2502 /* Pre-initialize the random sequence cache */ 2503 static int init_cache_random_seq(struct kmem_cache *s) 2504 { 2505 unsigned int count = oo_objects(s->oo); 2506 int err; 2507 2508 /* Bailout if already initialised */ 2509 if (s->random_seq) 2510 return 0; 2511 2512 err = cache_random_seq_create(s, count, GFP_KERNEL); 2513 if (err) { 2514 pr_err("SLUB: Unable to initialize free list for %s\n", 2515 s->name); 2516 return err; 2517 } 2518 2519 /* Transform to an offset on the set of pages */ 2520 if (s->random_seq) { 2521 unsigned int i; 2522 2523 for (i = 0; i < count; i++) 2524 s->random_seq[i] *= s->size; 2525 } 2526 return 0; 2527 } 2528 2529 /* Initialize each random sequence freelist per cache */ 2530 static void __init init_freelist_randomization(void) 2531 { 2532 struct kmem_cache *s; 2533 2534 mutex_lock(&slab_mutex); 2535 2536 list_for_each_entry(s, &slab_caches, list) 2537 init_cache_random_seq(s); 2538 2539 mutex_unlock(&slab_mutex); 2540 } 2541 2542 /* Get the next entry on the pre-computed freelist randomized */ 2543 static void *next_freelist_entry(struct kmem_cache *s, 2544 unsigned long *pos, void *start, 2545 unsigned long page_limit, 2546 unsigned long freelist_count) 2547 { 2548 unsigned int idx; 2549 2550 /* 2551 * If the target page allocation failed, the number of objects on the 2552 * page might be smaller than the usual size defined by the cache. 2553 */ 2554 do { 2555 idx = s->random_seq[*pos]; 2556 *pos += 1; 2557 if (*pos >= freelist_count) 2558 *pos = 0; 2559 } while (unlikely(idx >= page_limit)); 2560 2561 return (char *)start + idx; 2562 } 2563 2564 /* Shuffle the single linked freelist based on a random pre-computed sequence */ 2565 static bool shuffle_freelist(struct kmem_cache *s, struct slab *slab) 2566 { 2567 void *start; 2568 void *cur; 2569 void *next; 2570 unsigned long idx, pos, page_limit, freelist_count; 2571 2572 if (slab->objects < 2 || !s->random_seq) 2573 return false; 2574 2575 freelist_count = oo_objects(s->oo); 2576 pos = get_random_u32_below(freelist_count); 2577 2578 page_limit = slab->objects * s->size; 2579 start = fixup_red_left(s, slab_address(slab)); 2580 2581 /* First entry is used as the base of the freelist */ 2582 cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count); 2583 cur = setup_object(s, cur); 2584 slab->freelist = cur; 2585 2586 for (idx = 1; idx < slab->objects; idx++) { 2587 next = next_freelist_entry(s, &pos, start, page_limit, 2588 freelist_count); 2589 next = setup_object(s, next); 2590 set_freepointer(s, cur, next); 2591 cur = next; 2592 } 2593 set_freepointer(s, cur, NULL); 2594 2595 return true; 2596 } 2597 #else 2598 static inline int init_cache_random_seq(struct kmem_cache *s) 2599 { 2600 return 0; 2601 } 2602 static inline void init_freelist_randomization(void) { } 2603 static inline bool shuffle_freelist(struct kmem_cache *s, struct slab *slab) 2604 { 2605 return false; 2606 } 2607 #endif /* CONFIG_SLAB_FREELIST_RANDOM */ 2608 2609 static __always_inline void account_slab(struct slab *slab, int order, 2610 struct kmem_cache *s, gfp_t gfp) 2611 { 2612 if (memcg_kmem_online() && (s->flags & SLAB_ACCOUNT)) 2613 alloc_slab_obj_exts(slab, s, gfp, true); 2614 2615 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s), 2616 PAGE_SIZE << order); 2617 } 2618 2619 static __always_inline void unaccount_slab(struct slab *slab, int order, 2620 struct kmem_cache *s) 2621 { 2622 /* 2623 * The slab object extensions should now be freed regardless of 2624 * whether mem_alloc_profiling_enabled() or not because profiling 2625 * might have been disabled after slab->obj_exts got allocated. 2626 */ 2627 free_slab_obj_exts(slab); 2628 2629 mod_node_page_state(slab_pgdat(slab), cache_vmstat_idx(s), 2630 -(PAGE_SIZE << order)); 2631 } 2632 2633 static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags, int node) 2634 { 2635 struct slab *slab; 2636 struct kmem_cache_order_objects oo = s->oo; 2637 gfp_t alloc_gfp; 2638 void *start, *p, *next; 2639 int idx; 2640 bool shuffle; 2641 2642 flags &= gfp_allowed_mask; 2643 2644 flags |= s->allocflags; 2645 2646 /* 2647 * Let the initial higher-order allocation fail under memory pressure 2648 * so we fall-back to the minimum order allocation. 2649 */ 2650 alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL; 2651 if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min)) 2652 alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM; 2653 2654 slab = alloc_slab_page(alloc_gfp, node, oo); 2655 if (unlikely(!slab)) { 2656 oo = s->min; 2657 alloc_gfp = flags; 2658 /* 2659 * Allocation may have failed due to fragmentation. 2660 * Try a lower order alloc if possible 2661 */ 2662 slab = alloc_slab_page(alloc_gfp, node, oo); 2663 if (unlikely(!slab)) 2664 return NULL; 2665 stat(s, ORDER_FALLBACK); 2666 } 2667 2668 slab->objects = oo_objects(oo); 2669 slab->inuse = 0; 2670 slab->frozen = 0; 2671 init_slab_obj_exts(slab); 2672 2673 account_slab(slab, oo_order(oo), s, flags); 2674 2675 slab->slab_cache = s; 2676 2677 kasan_poison_slab(slab); 2678 2679 start = slab_address(slab); 2680 2681 setup_slab_debug(s, slab, start); 2682 2683 shuffle = shuffle_freelist(s, slab); 2684 2685 if (!shuffle) { 2686 start = fixup_red_left(s, start); 2687 start = setup_object(s, start); 2688 slab->freelist = start; 2689 for (idx = 0, p = start; idx < slab->objects - 1; idx++) { 2690 next = p + s->size; 2691 next = setup_object(s, next); 2692 set_freepointer(s, p, next); 2693 p = next; 2694 } 2695 set_freepointer(s, p, NULL); 2696 } 2697 2698 return slab; 2699 } 2700 2701 static struct slab *new_slab(struct kmem_cache *s, gfp_t flags, int node) 2702 { 2703 if (unlikely(flags & GFP_SLAB_BUG_MASK)) 2704 flags = kmalloc_fix_flags(flags); 2705 2706 WARN_ON_ONCE(s->ctor && (flags & __GFP_ZERO)); 2707 2708 return allocate_slab(s, 2709 flags & (GFP_RECLAIM_MASK | GFP_CONSTRAINT_MASK), node); 2710 } 2711 2712 static void __free_slab(struct kmem_cache *s, struct slab *slab) 2713 { 2714 struct folio *folio = slab_folio(slab); 2715 int order = folio_order(folio); 2716 int pages = 1 << order; 2717 2718 __slab_clear_pfmemalloc(slab); 2719 folio->mapping = NULL; 2720 __folio_clear_slab(folio); 2721 mm_account_reclaimed_pages(pages); 2722 unaccount_slab(slab, order, s); 2723 free_frozen_pages(&folio->page, order); 2724 } 2725 2726 static void rcu_free_slab(struct rcu_head *h) 2727 { 2728 struct slab *slab = container_of(h, struct slab, rcu_head); 2729 2730 __free_slab(slab->slab_cache, slab); 2731 } 2732 2733 static void free_slab(struct kmem_cache *s, struct slab *slab) 2734 { 2735 if (kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) { 2736 void *p; 2737 2738 slab_pad_check(s, slab); 2739 for_each_object(p, s, slab_address(slab), slab->objects) 2740 check_object(s, slab, p, SLUB_RED_INACTIVE); 2741 } 2742 2743 if (unlikely(s->flags & SLAB_TYPESAFE_BY_RCU)) 2744 call_rcu(&slab->rcu_head, rcu_free_slab); 2745 else 2746 __free_slab(s, slab); 2747 } 2748 2749 static void discard_slab(struct kmem_cache *s, struct slab *slab) 2750 { 2751 dec_slabs_node(s, slab_nid(slab), slab->objects); 2752 free_slab(s, slab); 2753 } 2754 2755 static inline bool slab_test_node_partial(const struct slab *slab) 2756 { 2757 return test_bit(SL_partial, &slab->flags); 2758 } 2759 2760 static inline void slab_set_node_partial(struct slab *slab) 2761 { 2762 set_bit(SL_partial, &slab->flags); 2763 } 2764 2765 static inline void slab_clear_node_partial(struct slab *slab) 2766 { 2767 clear_bit(SL_partial, &slab->flags); 2768 } 2769 2770 /* 2771 * Management of partially allocated slabs. 2772 */ 2773 static inline void 2774 __add_partial(struct kmem_cache_node *n, struct slab *slab, int tail) 2775 { 2776 n->nr_partial++; 2777 if (tail == DEACTIVATE_TO_TAIL) 2778 list_add_tail(&slab->slab_list, &n->partial); 2779 else 2780 list_add(&slab->slab_list, &n->partial); 2781 slab_set_node_partial(slab); 2782 } 2783 2784 static inline void add_partial(struct kmem_cache_node *n, 2785 struct slab *slab, int tail) 2786 { 2787 lockdep_assert_held(&n->list_lock); 2788 __add_partial(n, slab, tail); 2789 } 2790 2791 static inline void remove_partial(struct kmem_cache_node *n, 2792 struct slab *slab) 2793 { 2794 lockdep_assert_held(&n->list_lock); 2795 list_del(&slab->slab_list); 2796 slab_clear_node_partial(slab); 2797 n->nr_partial--; 2798 } 2799 2800 /* 2801 * Called only for kmem_cache_debug() caches instead of remove_partial(), with a 2802 * slab from the n->partial list. Remove only a single object from the slab, do 2803 * the alloc_debug_processing() checks and leave the slab on the list, or move 2804 * it to full list if it was the last free object. 2805 */ 2806 static void *alloc_single_from_partial(struct kmem_cache *s, 2807 struct kmem_cache_node *n, struct slab *slab, int orig_size) 2808 { 2809 void *object; 2810 2811 lockdep_assert_held(&n->list_lock); 2812 2813 object = slab->freelist; 2814 slab->freelist = get_freepointer(s, object); 2815 slab->inuse++; 2816 2817 if (!alloc_debug_processing(s, slab, object, orig_size)) { 2818 if (folio_test_slab(slab_folio(slab))) 2819 remove_partial(n, slab); 2820 return NULL; 2821 } 2822 2823 if (slab->inuse == slab->objects) { 2824 remove_partial(n, slab); 2825 add_full(s, n, slab); 2826 } 2827 2828 return object; 2829 } 2830 2831 /* 2832 * Called only for kmem_cache_debug() caches to allocate from a freshly 2833 * allocated slab. Allocate a single object instead of whole freelist 2834 * and put the slab to the partial (or full) list. 2835 */ 2836 static void *alloc_single_from_new_slab(struct kmem_cache *s, 2837 struct slab *slab, int orig_size) 2838 { 2839 int nid = slab_nid(slab); 2840 struct kmem_cache_node *n = get_node(s, nid); 2841 unsigned long flags; 2842 void *object; 2843 2844 2845 object = slab->freelist; 2846 slab->freelist = get_freepointer(s, object); 2847 slab->inuse = 1; 2848 2849 if (!alloc_debug_processing(s, slab, object, orig_size)) 2850 /* 2851 * It's not really expected that this would fail on a 2852 * freshly allocated slab, but a concurrent memory 2853 * corruption in theory could cause that. 2854 */ 2855 return NULL; 2856 2857 spin_lock_irqsave(&n->list_lock, flags); 2858 2859 if (slab->inuse == slab->objects) 2860 add_full(s, n, slab); 2861 else 2862 add_partial(n, slab, DEACTIVATE_TO_HEAD); 2863 2864 inc_slabs_node(s, nid, slab->objects); 2865 spin_unlock_irqrestore(&n->list_lock, flags); 2866 2867 return object; 2868 } 2869 2870 #ifdef CONFIG_SLUB_CPU_PARTIAL 2871 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain); 2872 #else 2873 static inline void put_cpu_partial(struct kmem_cache *s, struct slab *slab, 2874 int drain) { } 2875 #endif 2876 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags); 2877 2878 /* 2879 * Try to allocate a partial slab from a specific node. 2880 */ 2881 static struct slab *get_partial_node(struct kmem_cache *s, 2882 struct kmem_cache_node *n, 2883 struct partial_context *pc) 2884 { 2885 struct slab *slab, *slab2, *partial = NULL; 2886 unsigned long flags; 2887 unsigned int partial_slabs = 0; 2888 2889 /* 2890 * Racy check. If we mistakenly see no partial slabs then we 2891 * just allocate an empty slab. If we mistakenly try to get a 2892 * partial slab and there is none available then get_partial() 2893 * will return NULL. 2894 */ 2895 if (!n || !n->nr_partial) 2896 return NULL; 2897 2898 spin_lock_irqsave(&n->list_lock, flags); 2899 list_for_each_entry_safe(slab, slab2, &n->partial, slab_list) { 2900 if (!pfmemalloc_match(slab, pc->flags)) 2901 continue; 2902 2903 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) { 2904 void *object = alloc_single_from_partial(s, n, slab, 2905 pc->orig_size); 2906 if (object) { 2907 partial = slab; 2908 pc->object = object; 2909 break; 2910 } 2911 continue; 2912 } 2913 2914 remove_partial(n, slab); 2915 2916 if (!partial) { 2917 partial = slab; 2918 stat(s, ALLOC_FROM_PARTIAL); 2919 2920 if ((slub_get_cpu_partial(s) == 0)) { 2921 break; 2922 } 2923 } else { 2924 put_cpu_partial(s, slab, 0); 2925 stat(s, CPU_PARTIAL_NODE); 2926 2927 if (++partial_slabs > slub_get_cpu_partial(s) / 2) { 2928 break; 2929 } 2930 } 2931 } 2932 spin_unlock_irqrestore(&n->list_lock, flags); 2933 return partial; 2934 } 2935 2936 /* 2937 * Get a slab from somewhere. Search in increasing NUMA distances. 2938 */ 2939 static struct slab *get_any_partial(struct kmem_cache *s, 2940 struct partial_context *pc) 2941 { 2942 #ifdef CONFIG_NUMA 2943 struct zonelist *zonelist; 2944 struct zoneref *z; 2945 struct zone *zone; 2946 enum zone_type highest_zoneidx = gfp_zone(pc->flags); 2947 struct slab *slab; 2948 unsigned int cpuset_mems_cookie; 2949 2950 /* 2951 * The defrag ratio allows a configuration of the tradeoffs between 2952 * inter node defragmentation and node local allocations. A lower 2953 * defrag_ratio increases the tendency to do local allocations 2954 * instead of attempting to obtain partial slabs from other nodes. 2955 * 2956 * If the defrag_ratio is set to 0 then kmalloc() always 2957 * returns node local objects. If the ratio is higher then kmalloc() 2958 * may return off node objects because partial slabs are obtained 2959 * from other nodes and filled up. 2960 * 2961 * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100 2962 * (which makes defrag_ratio = 1000) then every (well almost) 2963 * allocation will first attempt to defrag slab caches on other nodes. 2964 * This means scanning over all nodes to look for partial slabs which 2965 * may be expensive if we do it every time we are trying to find a slab 2966 * with available objects. 2967 */ 2968 if (!s->remote_node_defrag_ratio || 2969 get_cycles() % 1024 > s->remote_node_defrag_ratio) 2970 return NULL; 2971 2972 do { 2973 cpuset_mems_cookie = read_mems_allowed_begin(); 2974 zonelist = node_zonelist(mempolicy_slab_node(), pc->flags); 2975 for_each_zone_zonelist(zone, z, zonelist, highest_zoneidx) { 2976 struct kmem_cache_node *n; 2977 2978 n = get_node(s, zone_to_nid(zone)); 2979 2980 if (n && cpuset_zone_allowed(zone, pc->flags) && 2981 n->nr_partial > s->min_partial) { 2982 slab = get_partial_node(s, n, pc); 2983 if (slab) { 2984 /* 2985 * Don't check read_mems_allowed_retry() 2986 * here - if mems_allowed was updated in 2987 * parallel, that was a harmless race 2988 * between allocation and the cpuset 2989 * update 2990 */ 2991 return slab; 2992 } 2993 } 2994 } 2995 } while (read_mems_allowed_retry(cpuset_mems_cookie)); 2996 #endif /* CONFIG_NUMA */ 2997 return NULL; 2998 } 2999 3000 /* 3001 * Get a partial slab, lock it and return it. 3002 */ 3003 static struct slab *get_partial(struct kmem_cache *s, int node, 3004 struct partial_context *pc) 3005 { 3006 struct slab *slab; 3007 int searchnode = node; 3008 3009 if (node == NUMA_NO_NODE) 3010 searchnode = numa_mem_id(); 3011 3012 slab = get_partial_node(s, get_node(s, searchnode), pc); 3013 if (slab || (node != NUMA_NO_NODE && (pc->flags & __GFP_THISNODE))) 3014 return slab; 3015 3016 return get_any_partial(s, pc); 3017 } 3018 3019 #ifndef CONFIG_SLUB_TINY 3020 3021 #ifdef CONFIG_PREEMPTION 3022 /* 3023 * Calculate the next globally unique transaction for disambiguation 3024 * during cmpxchg. The transactions start with the cpu number and are then 3025 * incremented by CONFIG_NR_CPUS. 3026 */ 3027 #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS) 3028 #else 3029 /* 3030 * No preemption supported therefore also no need to check for 3031 * different cpus. 3032 */ 3033 #define TID_STEP 1 3034 #endif /* CONFIG_PREEMPTION */ 3035 3036 static inline unsigned long next_tid(unsigned long tid) 3037 { 3038 return tid + TID_STEP; 3039 } 3040 3041 #ifdef SLUB_DEBUG_CMPXCHG 3042 static inline unsigned int tid_to_cpu(unsigned long tid) 3043 { 3044 return tid % TID_STEP; 3045 } 3046 3047 static inline unsigned long tid_to_event(unsigned long tid) 3048 { 3049 return tid / TID_STEP; 3050 } 3051 #endif 3052 3053 static inline unsigned int init_tid(int cpu) 3054 { 3055 return cpu; 3056 } 3057 3058 static inline void note_cmpxchg_failure(const char *n, 3059 const struct kmem_cache *s, unsigned long tid) 3060 { 3061 #ifdef SLUB_DEBUG_CMPXCHG 3062 unsigned long actual_tid = __this_cpu_read(s->cpu_slab->tid); 3063 3064 pr_info("%s %s: cmpxchg redo ", n, s->name); 3065 3066 #ifdef CONFIG_PREEMPTION 3067 if (tid_to_cpu(tid) != tid_to_cpu(actual_tid)) 3068 pr_warn("due to cpu change %d -> %d\n", 3069 tid_to_cpu(tid), tid_to_cpu(actual_tid)); 3070 else 3071 #endif 3072 if (tid_to_event(tid) != tid_to_event(actual_tid)) 3073 pr_warn("due to cpu running other code. Event %ld->%ld\n", 3074 tid_to_event(tid), tid_to_event(actual_tid)); 3075 else 3076 pr_warn("for unknown reason: actual=%lx was=%lx target=%lx\n", 3077 actual_tid, tid, next_tid(tid)); 3078 #endif 3079 stat(s, CMPXCHG_DOUBLE_CPU_FAIL); 3080 } 3081 3082 static void init_kmem_cache_cpus(struct kmem_cache *s) 3083 { 3084 int cpu; 3085 struct kmem_cache_cpu *c; 3086 3087 for_each_possible_cpu(cpu) { 3088 c = per_cpu_ptr(s->cpu_slab, cpu); 3089 local_lock_init(&c->lock); 3090 c->tid = init_tid(cpu); 3091 } 3092 } 3093 3094 /* 3095 * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist, 3096 * unfreezes the slabs and puts it on the proper list. 3097 * Assumes the slab has been already safely taken away from kmem_cache_cpu 3098 * by the caller. 3099 */ 3100 static void deactivate_slab(struct kmem_cache *s, struct slab *slab, 3101 void *freelist) 3102 { 3103 struct kmem_cache_node *n = get_node(s, slab_nid(slab)); 3104 int free_delta = 0; 3105 void *nextfree, *freelist_iter, *freelist_tail; 3106 int tail = DEACTIVATE_TO_HEAD; 3107 unsigned long flags = 0; 3108 struct slab new; 3109 struct slab old; 3110 3111 if (READ_ONCE(slab->freelist)) { 3112 stat(s, DEACTIVATE_REMOTE_FREES); 3113 tail = DEACTIVATE_TO_TAIL; 3114 } 3115 3116 /* 3117 * Stage one: Count the objects on cpu's freelist as free_delta and 3118 * remember the last object in freelist_tail for later splicing. 3119 */ 3120 freelist_tail = NULL; 3121 freelist_iter = freelist; 3122 while (freelist_iter) { 3123 nextfree = get_freepointer(s, freelist_iter); 3124 3125 /* 3126 * If 'nextfree' is invalid, it is possible that the object at 3127 * 'freelist_iter' is already corrupted. So isolate all objects 3128 * starting at 'freelist_iter' by skipping them. 3129 */ 3130 if (freelist_corrupted(s, slab, &freelist_iter, nextfree)) 3131 break; 3132 3133 freelist_tail = freelist_iter; 3134 free_delta++; 3135 3136 freelist_iter = nextfree; 3137 } 3138 3139 /* 3140 * Stage two: Unfreeze the slab while splicing the per-cpu 3141 * freelist to the head of slab's freelist. 3142 */ 3143 do { 3144 old.freelist = READ_ONCE(slab->freelist); 3145 old.counters = READ_ONCE(slab->counters); 3146 VM_BUG_ON(!old.frozen); 3147 3148 /* Determine target state of the slab */ 3149 new.counters = old.counters; 3150 new.frozen = 0; 3151 if (freelist_tail) { 3152 new.inuse -= free_delta; 3153 set_freepointer(s, freelist_tail, old.freelist); 3154 new.freelist = freelist; 3155 } else { 3156 new.freelist = old.freelist; 3157 } 3158 } while (!slab_update_freelist(s, slab, 3159 old.freelist, old.counters, 3160 new.freelist, new.counters, 3161 "unfreezing slab")); 3162 3163 /* 3164 * Stage three: Manipulate the slab list based on the updated state. 3165 */ 3166 if (!new.inuse && n->nr_partial >= s->min_partial) { 3167 stat(s, DEACTIVATE_EMPTY); 3168 discard_slab(s, slab); 3169 stat(s, FREE_SLAB); 3170 } else if (new.freelist) { 3171 spin_lock_irqsave(&n->list_lock, flags); 3172 add_partial(n, slab, tail); 3173 spin_unlock_irqrestore(&n->list_lock, flags); 3174 stat(s, tail); 3175 } else { 3176 stat(s, DEACTIVATE_FULL); 3177 } 3178 } 3179 3180 #ifdef CONFIG_SLUB_CPU_PARTIAL 3181 static void __put_partials(struct kmem_cache *s, struct slab *partial_slab) 3182 { 3183 struct kmem_cache_node *n = NULL, *n2 = NULL; 3184 struct slab *slab, *slab_to_discard = NULL; 3185 unsigned long flags = 0; 3186 3187 while (partial_slab) { 3188 slab = partial_slab; 3189 partial_slab = slab->next; 3190 3191 n2 = get_node(s, slab_nid(slab)); 3192 if (n != n2) { 3193 if (n) 3194 spin_unlock_irqrestore(&n->list_lock, flags); 3195 3196 n = n2; 3197 spin_lock_irqsave(&n->list_lock, flags); 3198 } 3199 3200 if (unlikely(!slab->inuse && n->nr_partial >= s->min_partial)) { 3201 slab->next = slab_to_discard; 3202 slab_to_discard = slab; 3203 } else { 3204 add_partial(n, slab, DEACTIVATE_TO_TAIL); 3205 stat(s, FREE_ADD_PARTIAL); 3206 } 3207 } 3208 3209 if (n) 3210 spin_unlock_irqrestore(&n->list_lock, flags); 3211 3212 while (slab_to_discard) { 3213 slab = slab_to_discard; 3214 slab_to_discard = slab_to_discard->next; 3215 3216 stat(s, DEACTIVATE_EMPTY); 3217 discard_slab(s, slab); 3218 stat(s, FREE_SLAB); 3219 } 3220 } 3221 3222 /* 3223 * Put all the cpu partial slabs to the node partial list. 3224 */ 3225 static void put_partials(struct kmem_cache *s) 3226 { 3227 struct slab *partial_slab; 3228 unsigned long flags; 3229 3230 local_lock_irqsave(&s->cpu_slab->lock, flags); 3231 partial_slab = this_cpu_read(s->cpu_slab->partial); 3232 this_cpu_write(s->cpu_slab->partial, NULL); 3233 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3234 3235 if (partial_slab) 3236 __put_partials(s, partial_slab); 3237 } 3238 3239 static void put_partials_cpu(struct kmem_cache *s, 3240 struct kmem_cache_cpu *c) 3241 { 3242 struct slab *partial_slab; 3243 3244 partial_slab = slub_percpu_partial(c); 3245 c->partial = NULL; 3246 3247 if (partial_slab) 3248 __put_partials(s, partial_slab); 3249 } 3250 3251 /* 3252 * Put a slab into a partial slab slot if available. 3253 * 3254 * If we did not find a slot then simply move all the partials to the 3255 * per node partial list. 3256 */ 3257 static void put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain) 3258 { 3259 struct slab *oldslab; 3260 struct slab *slab_to_put = NULL; 3261 unsigned long flags; 3262 int slabs = 0; 3263 3264 local_lock_irqsave(&s->cpu_slab->lock, flags); 3265 3266 oldslab = this_cpu_read(s->cpu_slab->partial); 3267 3268 if (oldslab) { 3269 if (drain && oldslab->slabs >= s->cpu_partial_slabs) { 3270 /* 3271 * Partial array is full. Move the existing set to the 3272 * per node partial list. Postpone the actual unfreezing 3273 * outside of the critical section. 3274 */ 3275 slab_to_put = oldslab; 3276 oldslab = NULL; 3277 } else { 3278 slabs = oldslab->slabs; 3279 } 3280 } 3281 3282 slabs++; 3283 3284 slab->slabs = slabs; 3285 slab->next = oldslab; 3286 3287 this_cpu_write(s->cpu_slab->partial, slab); 3288 3289 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3290 3291 if (slab_to_put) { 3292 __put_partials(s, slab_to_put); 3293 stat(s, CPU_PARTIAL_DRAIN); 3294 } 3295 } 3296 3297 #else /* CONFIG_SLUB_CPU_PARTIAL */ 3298 3299 static inline void put_partials(struct kmem_cache *s) { } 3300 static inline void put_partials_cpu(struct kmem_cache *s, 3301 struct kmem_cache_cpu *c) { } 3302 3303 #endif /* CONFIG_SLUB_CPU_PARTIAL */ 3304 3305 static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c) 3306 { 3307 unsigned long flags; 3308 struct slab *slab; 3309 void *freelist; 3310 3311 local_lock_irqsave(&s->cpu_slab->lock, flags); 3312 3313 slab = c->slab; 3314 freelist = c->freelist; 3315 3316 c->slab = NULL; 3317 c->freelist = NULL; 3318 c->tid = next_tid(c->tid); 3319 3320 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3321 3322 if (slab) { 3323 deactivate_slab(s, slab, freelist); 3324 stat(s, CPUSLAB_FLUSH); 3325 } 3326 } 3327 3328 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) 3329 { 3330 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu); 3331 void *freelist = c->freelist; 3332 struct slab *slab = c->slab; 3333 3334 c->slab = NULL; 3335 c->freelist = NULL; 3336 c->tid = next_tid(c->tid); 3337 3338 if (slab) { 3339 deactivate_slab(s, slab, freelist); 3340 stat(s, CPUSLAB_FLUSH); 3341 } 3342 3343 put_partials_cpu(s, c); 3344 } 3345 3346 struct slub_flush_work { 3347 struct work_struct work; 3348 struct kmem_cache *s; 3349 bool skip; 3350 }; 3351 3352 /* 3353 * Flush cpu slab. 3354 * 3355 * Called from CPU work handler with migration disabled. 3356 */ 3357 static void flush_cpu_slab(struct work_struct *w) 3358 { 3359 struct kmem_cache *s; 3360 struct kmem_cache_cpu *c; 3361 struct slub_flush_work *sfw; 3362 3363 sfw = container_of(w, struct slub_flush_work, work); 3364 3365 s = sfw->s; 3366 c = this_cpu_ptr(s->cpu_slab); 3367 3368 if (c->slab) 3369 flush_slab(s, c); 3370 3371 put_partials(s); 3372 } 3373 3374 static bool has_cpu_slab(int cpu, struct kmem_cache *s) 3375 { 3376 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, cpu); 3377 3378 return c->slab || slub_percpu_partial(c); 3379 } 3380 3381 static DEFINE_MUTEX(flush_lock); 3382 static DEFINE_PER_CPU(struct slub_flush_work, slub_flush); 3383 3384 static void flush_all_cpus_locked(struct kmem_cache *s) 3385 { 3386 struct slub_flush_work *sfw; 3387 unsigned int cpu; 3388 3389 lockdep_assert_cpus_held(); 3390 mutex_lock(&flush_lock); 3391 3392 for_each_online_cpu(cpu) { 3393 sfw = &per_cpu(slub_flush, cpu); 3394 if (!has_cpu_slab(cpu, s)) { 3395 sfw->skip = true; 3396 continue; 3397 } 3398 INIT_WORK(&sfw->work, flush_cpu_slab); 3399 sfw->skip = false; 3400 sfw->s = s; 3401 queue_work_on(cpu, flushwq, &sfw->work); 3402 } 3403 3404 for_each_online_cpu(cpu) { 3405 sfw = &per_cpu(slub_flush, cpu); 3406 if (sfw->skip) 3407 continue; 3408 flush_work(&sfw->work); 3409 } 3410 3411 mutex_unlock(&flush_lock); 3412 } 3413 3414 static void flush_all(struct kmem_cache *s) 3415 { 3416 cpus_read_lock(); 3417 flush_all_cpus_locked(s); 3418 cpus_read_unlock(); 3419 } 3420 3421 /* 3422 * Use the cpu notifier to insure that the cpu slabs are flushed when 3423 * necessary. 3424 */ 3425 static int slub_cpu_dead(unsigned int cpu) 3426 { 3427 struct kmem_cache *s; 3428 3429 mutex_lock(&slab_mutex); 3430 list_for_each_entry(s, &slab_caches, list) 3431 __flush_cpu_slab(s, cpu); 3432 mutex_unlock(&slab_mutex); 3433 return 0; 3434 } 3435 3436 #else /* CONFIG_SLUB_TINY */ 3437 static inline void flush_all_cpus_locked(struct kmem_cache *s) { } 3438 static inline void flush_all(struct kmem_cache *s) { } 3439 static inline void __flush_cpu_slab(struct kmem_cache *s, int cpu) { } 3440 static inline int slub_cpu_dead(unsigned int cpu) { return 0; } 3441 #endif /* CONFIG_SLUB_TINY */ 3442 3443 /* 3444 * Check if the objects in a per cpu structure fit numa 3445 * locality expectations. 3446 */ 3447 static inline int node_match(struct slab *slab, int node) 3448 { 3449 #ifdef CONFIG_NUMA 3450 if (node != NUMA_NO_NODE && slab_nid(slab) != node) 3451 return 0; 3452 #endif 3453 return 1; 3454 } 3455 3456 #ifdef CONFIG_SLUB_DEBUG 3457 static int count_free(struct slab *slab) 3458 { 3459 return slab->objects - slab->inuse; 3460 } 3461 3462 static inline unsigned long node_nr_objs(struct kmem_cache_node *n) 3463 { 3464 return atomic_long_read(&n->total_objects); 3465 } 3466 3467 /* Supports checking bulk free of a constructed freelist */ 3468 static inline bool free_debug_processing(struct kmem_cache *s, 3469 struct slab *slab, void *head, void *tail, int *bulk_cnt, 3470 unsigned long addr, depot_stack_handle_t handle) 3471 { 3472 bool checks_ok = false; 3473 void *object = head; 3474 int cnt = 0; 3475 3476 if (s->flags & SLAB_CONSISTENCY_CHECKS) { 3477 if (!check_slab(s, slab)) 3478 goto out; 3479 } 3480 3481 if (slab->inuse < *bulk_cnt) { 3482 slab_err(s, slab, "Slab has %d allocated objects but %d are to be freed\n", 3483 slab->inuse, *bulk_cnt); 3484 goto out; 3485 } 3486 3487 next_object: 3488 3489 if (++cnt > *bulk_cnt) 3490 goto out_cnt; 3491 3492 if (s->flags & SLAB_CONSISTENCY_CHECKS) { 3493 if (!free_consistency_checks(s, slab, object, addr)) 3494 goto out; 3495 } 3496 3497 if (s->flags & SLAB_STORE_USER) 3498 set_track_update(s, object, TRACK_FREE, addr, handle); 3499 trace(s, slab, object, 0); 3500 /* Freepointer not overwritten by init_object(), SLAB_POISON moved it */ 3501 init_object(s, object, SLUB_RED_INACTIVE); 3502 3503 /* Reached end of constructed freelist yet? */ 3504 if (object != tail) { 3505 object = get_freepointer(s, object); 3506 goto next_object; 3507 } 3508 checks_ok = true; 3509 3510 out_cnt: 3511 if (cnt != *bulk_cnt) { 3512 slab_err(s, slab, "Bulk free expected %d objects but found %d\n", 3513 *bulk_cnt, cnt); 3514 *bulk_cnt = cnt; 3515 } 3516 3517 out: 3518 3519 if (!checks_ok) 3520 slab_fix(s, "Object at 0x%p not freed", object); 3521 3522 return checks_ok; 3523 } 3524 #endif /* CONFIG_SLUB_DEBUG */ 3525 3526 #if defined(CONFIG_SLUB_DEBUG) || defined(SLAB_SUPPORTS_SYSFS) 3527 static unsigned long count_partial(struct kmem_cache_node *n, 3528 int (*get_count)(struct slab *)) 3529 { 3530 unsigned long flags; 3531 unsigned long x = 0; 3532 struct slab *slab; 3533 3534 spin_lock_irqsave(&n->list_lock, flags); 3535 list_for_each_entry(slab, &n->partial, slab_list) 3536 x += get_count(slab); 3537 spin_unlock_irqrestore(&n->list_lock, flags); 3538 return x; 3539 } 3540 #endif /* CONFIG_SLUB_DEBUG || SLAB_SUPPORTS_SYSFS */ 3541 3542 #ifdef CONFIG_SLUB_DEBUG 3543 #define MAX_PARTIAL_TO_SCAN 10000 3544 3545 static unsigned long count_partial_free_approx(struct kmem_cache_node *n) 3546 { 3547 unsigned long flags; 3548 unsigned long x = 0; 3549 struct slab *slab; 3550 3551 spin_lock_irqsave(&n->list_lock, flags); 3552 if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) { 3553 list_for_each_entry(slab, &n->partial, slab_list) 3554 x += slab->objects - slab->inuse; 3555 } else { 3556 /* 3557 * For a long list, approximate the total count of objects in 3558 * it to meet the limit on the number of slabs to scan. 3559 * Scan from both the list's head and tail for better accuracy. 3560 */ 3561 unsigned long scanned = 0; 3562 3563 list_for_each_entry(slab, &n->partial, slab_list) { 3564 x += slab->objects - slab->inuse; 3565 if (++scanned == MAX_PARTIAL_TO_SCAN / 2) 3566 break; 3567 } 3568 list_for_each_entry_reverse(slab, &n->partial, slab_list) { 3569 x += slab->objects - slab->inuse; 3570 if (++scanned == MAX_PARTIAL_TO_SCAN) 3571 break; 3572 } 3573 x = mult_frac(x, n->nr_partial, scanned); 3574 x = min(x, node_nr_objs(n)); 3575 } 3576 spin_unlock_irqrestore(&n->list_lock, flags); 3577 return x; 3578 } 3579 3580 static noinline void 3581 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) 3582 { 3583 static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL, 3584 DEFAULT_RATELIMIT_BURST); 3585 int cpu = raw_smp_processor_id(); 3586 int node; 3587 struct kmem_cache_node *n; 3588 3589 if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs)) 3590 return; 3591 3592 pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n", 3593 cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags); 3594 pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n", 3595 s->name, s->object_size, s->size, oo_order(s->oo), 3596 oo_order(s->min)); 3597 3598 if (oo_order(s->min) > get_order(s->object_size)) 3599 pr_warn(" %s debugging increased min order, use slab_debug=O to disable.\n", 3600 s->name); 3601 3602 for_each_kmem_cache_node(s, node, n) { 3603 unsigned long nr_slabs; 3604 unsigned long nr_objs; 3605 unsigned long nr_free; 3606 3607 nr_free = count_partial_free_approx(n); 3608 nr_slabs = node_nr_slabs(n); 3609 nr_objs = node_nr_objs(n); 3610 3611 pr_warn(" node %d: slabs: %ld, objs: %ld, free: %ld\n", 3612 node, nr_slabs, nr_objs, nr_free); 3613 } 3614 } 3615 #else /* CONFIG_SLUB_DEBUG */ 3616 static inline void 3617 slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid) { } 3618 #endif 3619 3620 static inline bool pfmemalloc_match(struct slab *slab, gfp_t gfpflags) 3621 { 3622 if (unlikely(slab_test_pfmemalloc(slab))) 3623 return gfp_pfmemalloc_allowed(gfpflags); 3624 3625 return true; 3626 } 3627 3628 #ifndef CONFIG_SLUB_TINY 3629 static inline bool 3630 __update_cpu_freelist_fast(struct kmem_cache *s, 3631 void *freelist_old, void *freelist_new, 3632 unsigned long tid) 3633 { 3634 freelist_aba_t old = { .freelist = freelist_old, .counter = tid }; 3635 freelist_aba_t new = { .freelist = freelist_new, .counter = next_tid(tid) }; 3636 3637 return this_cpu_try_cmpxchg_freelist(s->cpu_slab->freelist_tid.full, 3638 &old.full, new.full); 3639 } 3640 3641 /* 3642 * Check the slab->freelist and either transfer the freelist to the 3643 * per cpu freelist or deactivate the slab. 3644 * 3645 * The slab is still frozen if the return value is not NULL. 3646 * 3647 * If this function returns NULL then the slab has been unfrozen. 3648 */ 3649 static inline void *get_freelist(struct kmem_cache *s, struct slab *slab) 3650 { 3651 struct slab new; 3652 unsigned long counters; 3653 void *freelist; 3654 3655 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock)); 3656 3657 do { 3658 freelist = slab->freelist; 3659 counters = slab->counters; 3660 3661 new.counters = counters; 3662 3663 new.inuse = slab->objects; 3664 new.frozen = freelist != NULL; 3665 3666 } while (!__slab_update_freelist(s, slab, 3667 freelist, counters, 3668 NULL, new.counters, 3669 "get_freelist")); 3670 3671 return freelist; 3672 } 3673 3674 /* 3675 * Freeze the partial slab and return the pointer to the freelist. 3676 */ 3677 static inline void *freeze_slab(struct kmem_cache *s, struct slab *slab) 3678 { 3679 struct slab new; 3680 unsigned long counters; 3681 void *freelist; 3682 3683 do { 3684 freelist = slab->freelist; 3685 counters = slab->counters; 3686 3687 new.counters = counters; 3688 VM_BUG_ON(new.frozen); 3689 3690 new.inuse = slab->objects; 3691 new.frozen = 1; 3692 3693 } while (!slab_update_freelist(s, slab, 3694 freelist, counters, 3695 NULL, new.counters, 3696 "freeze_slab")); 3697 3698 return freelist; 3699 } 3700 3701 /* 3702 * Slow path. The lockless freelist is empty or we need to perform 3703 * debugging duties. 3704 * 3705 * Processing is still very fast if new objects have been freed to the 3706 * regular freelist. In that case we simply take over the regular freelist 3707 * as the lockless freelist and zap the regular freelist. 3708 * 3709 * If that is not working then we fall back to the partial lists. We take the 3710 * first element of the freelist as the object to allocate now and move the 3711 * rest of the freelist to the lockless freelist. 3712 * 3713 * And if we were unable to get a new slab from the partial slab lists then 3714 * we need to allocate a new slab. This is the slowest path since it involves 3715 * a call to the page allocator and the setup of a new slab. 3716 * 3717 * Version of __slab_alloc to use when we know that preemption is 3718 * already disabled (which is the case for bulk allocation). 3719 */ 3720 static void *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, 3721 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size) 3722 { 3723 void *freelist; 3724 struct slab *slab; 3725 unsigned long flags; 3726 struct partial_context pc; 3727 bool try_thisnode = true; 3728 3729 stat(s, ALLOC_SLOWPATH); 3730 3731 reread_slab: 3732 3733 slab = READ_ONCE(c->slab); 3734 if (!slab) { 3735 /* 3736 * if the node is not online or has no normal memory, just 3737 * ignore the node constraint 3738 */ 3739 if (unlikely(node != NUMA_NO_NODE && 3740 !node_isset(node, slab_nodes))) 3741 node = NUMA_NO_NODE; 3742 goto new_slab; 3743 } 3744 3745 if (unlikely(!node_match(slab, node))) { 3746 /* 3747 * same as above but node_match() being false already 3748 * implies node != NUMA_NO_NODE 3749 */ 3750 if (!node_isset(node, slab_nodes)) { 3751 node = NUMA_NO_NODE; 3752 } else { 3753 stat(s, ALLOC_NODE_MISMATCH); 3754 goto deactivate_slab; 3755 } 3756 } 3757 3758 /* 3759 * By rights, we should be searching for a slab page that was 3760 * PFMEMALLOC but right now, we are losing the pfmemalloc 3761 * information when the page leaves the per-cpu allocator 3762 */ 3763 if (unlikely(!pfmemalloc_match(slab, gfpflags))) 3764 goto deactivate_slab; 3765 3766 /* must check again c->slab in case we got preempted and it changed */ 3767 local_lock_irqsave(&s->cpu_slab->lock, flags); 3768 if (unlikely(slab != c->slab)) { 3769 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3770 goto reread_slab; 3771 } 3772 freelist = c->freelist; 3773 if (freelist) 3774 goto load_freelist; 3775 3776 freelist = get_freelist(s, slab); 3777 3778 if (!freelist) { 3779 c->slab = NULL; 3780 c->tid = next_tid(c->tid); 3781 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3782 stat(s, DEACTIVATE_BYPASS); 3783 goto new_slab; 3784 } 3785 3786 stat(s, ALLOC_REFILL); 3787 3788 load_freelist: 3789 3790 lockdep_assert_held(this_cpu_ptr(&s->cpu_slab->lock)); 3791 3792 /* 3793 * freelist is pointing to the list of objects to be used. 3794 * slab is pointing to the slab from which the objects are obtained. 3795 * That slab must be frozen for per cpu allocations to work. 3796 */ 3797 VM_BUG_ON(!c->slab->frozen); 3798 c->freelist = get_freepointer(s, freelist); 3799 c->tid = next_tid(c->tid); 3800 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3801 return freelist; 3802 3803 deactivate_slab: 3804 3805 local_lock_irqsave(&s->cpu_slab->lock, flags); 3806 if (slab != c->slab) { 3807 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3808 goto reread_slab; 3809 } 3810 freelist = c->freelist; 3811 c->slab = NULL; 3812 c->freelist = NULL; 3813 c->tid = next_tid(c->tid); 3814 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3815 deactivate_slab(s, slab, freelist); 3816 3817 new_slab: 3818 3819 #ifdef CONFIG_SLUB_CPU_PARTIAL 3820 while (slub_percpu_partial(c)) { 3821 local_lock_irqsave(&s->cpu_slab->lock, flags); 3822 if (unlikely(c->slab)) { 3823 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3824 goto reread_slab; 3825 } 3826 if (unlikely(!slub_percpu_partial(c))) { 3827 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3828 /* we were preempted and partial list got empty */ 3829 goto new_objects; 3830 } 3831 3832 slab = slub_percpu_partial(c); 3833 slub_set_percpu_partial(c, slab); 3834 3835 if (likely(node_match(slab, node) && 3836 pfmemalloc_match(slab, gfpflags))) { 3837 c->slab = slab; 3838 freelist = get_freelist(s, slab); 3839 VM_BUG_ON(!freelist); 3840 stat(s, CPU_PARTIAL_ALLOC); 3841 goto load_freelist; 3842 } 3843 3844 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3845 3846 slab->next = NULL; 3847 __put_partials(s, slab); 3848 } 3849 #endif 3850 3851 new_objects: 3852 3853 pc.flags = gfpflags; 3854 /* 3855 * When a preferred node is indicated but no __GFP_THISNODE 3856 * 3857 * 1) try to get a partial slab from target node only by having 3858 * __GFP_THISNODE in pc.flags for get_partial() 3859 * 2) if 1) failed, try to allocate a new slab from target node with 3860 * GPF_NOWAIT | __GFP_THISNODE opportunistically 3861 * 3) if 2) failed, retry with original gfpflags which will allow 3862 * get_partial() try partial lists of other nodes before potentially 3863 * allocating new page from other nodes 3864 */ 3865 if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE) 3866 && try_thisnode)) 3867 pc.flags = GFP_NOWAIT | __GFP_THISNODE; 3868 3869 pc.orig_size = orig_size; 3870 slab = get_partial(s, node, &pc); 3871 if (slab) { 3872 if (kmem_cache_debug(s)) { 3873 freelist = pc.object; 3874 /* 3875 * For debug caches here we had to go through 3876 * alloc_single_from_partial() so just store the 3877 * tracking info and return the object. 3878 */ 3879 if (s->flags & SLAB_STORE_USER) 3880 set_track(s, freelist, TRACK_ALLOC, addr); 3881 3882 return freelist; 3883 } 3884 3885 freelist = freeze_slab(s, slab); 3886 goto retry_load_slab; 3887 } 3888 3889 slub_put_cpu_ptr(s->cpu_slab); 3890 slab = new_slab(s, pc.flags, node); 3891 c = slub_get_cpu_ptr(s->cpu_slab); 3892 3893 if (unlikely(!slab)) { 3894 if (node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE) 3895 && try_thisnode) { 3896 try_thisnode = false; 3897 goto new_objects; 3898 } 3899 slab_out_of_memory(s, gfpflags, node); 3900 return NULL; 3901 } 3902 3903 stat(s, ALLOC_SLAB); 3904 3905 if (kmem_cache_debug(s)) { 3906 freelist = alloc_single_from_new_slab(s, slab, orig_size); 3907 3908 if (unlikely(!freelist)) 3909 goto new_objects; 3910 3911 if (s->flags & SLAB_STORE_USER) 3912 set_track(s, freelist, TRACK_ALLOC, addr); 3913 3914 return freelist; 3915 } 3916 3917 /* 3918 * No other reference to the slab yet so we can 3919 * muck around with it freely without cmpxchg 3920 */ 3921 freelist = slab->freelist; 3922 slab->freelist = NULL; 3923 slab->inuse = slab->objects; 3924 slab->frozen = 1; 3925 3926 inc_slabs_node(s, slab_nid(slab), slab->objects); 3927 3928 if (unlikely(!pfmemalloc_match(slab, gfpflags))) { 3929 /* 3930 * For !pfmemalloc_match() case we don't load freelist so that 3931 * we don't make further mismatched allocations easier. 3932 */ 3933 deactivate_slab(s, slab, get_freepointer(s, freelist)); 3934 return freelist; 3935 } 3936 3937 retry_load_slab: 3938 3939 local_lock_irqsave(&s->cpu_slab->lock, flags); 3940 if (unlikely(c->slab)) { 3941 void *flush_freelist = c->freelist; 3942 struct slab *flush_slab = c->slab; 3943 3944 c->slab = NULL; 3945 c->freelist = NULL; 3946 c->tid = next_tid(c->tid); 3947 3948 local_unlock_irqrestore(&s->cpu_slab->lock, flags); 3949 3950 deactivate_slab(s, flush_slab, flush_freelist); 3951 3952 stat(s, CPUSLAB_FLUSH); 3953 3954 goto retry_load_slab; 3955 } 3956 c->slab = slab; 3957 3958 goto load_freelist; 3959 } 3960 3961 /* 3962 * A wrapper for ___slab_alloc() for contexts where preemption is not yet 3963 * disabled. Compensates for possible cpu changes by refetching the per cpu area 3964 * pointer. 3965 */ 3966 static void *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, 3967 unsigned long addr, struct kmem_cache_cpu *c, unsigned int orig_size) 3968 { 3969 void *p; 3970 3971 #ifdef CONFIG_PREEMPT_COUNT 3972 /* 3973 * We may have been preempted and rescheduled on a different 3974 * cpu before disabling preemption. Need to reload cpu area 3975 * pointer. 3976 */ 3977 c = slub_get_cpu_ptr(s->cpu_slab); 3978 #endif 3979 3980 p = ___slab_alloc(s, gfpflags, node, addr, c, orig_size); 3981 #ifdef CONFIG_PREEMPT_COUNT 3982 slub_put_cpu_ptr(s->cpu_slab); 3983 #endif 3984 return p; 3985 } 3986 3987 static __always_inline void *__slab_alloc_node(struct kmem_cache *s, 3988 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size) 3989 { 3990 struct kmem_cache_cpu *c; 3991 struct slab *slab; 3992 unsigned long tid; 3993 void *object; 3994 3995 redo: 3996 /* 3997 * Must read kmem_cache cpu data via this cpu ptr. Preemption is 3998 * enabled. We may switch back and forth between cpus while 3999 * reading from one cpu area. That does not matter as long 4000 * as we end up on the original cpu again when doing the cmpxchg. 4001 * 4002 * We must guarantee that tid and kmem_cache_cpu are retrieved on the 4003 * same cpu. We read first the kmem_cache_cpu pointer and use it to read 4004 * the tid. If we are preempted and switched to another cpu between the 4005 * two reads, it's OK as the two are still associated with the same cpu 4006 * and cmpxchg later will validate the cpu. 4007 */ 4008 c = raw_cpu_ptr(s->cpu_slab); 4009 tid = READ_ONCE(c->tid); 4010 4011 /* 4012 * Irqless object alloc/free algorithm used here depends on sequence 4013 * of fetching cpu_slab's data. tid should be fetched before anything 4014 * on c to guarantee that object and slab associated with previous tid 4015 * won't be used with current tid. If we fetch tid first, object and 4016 * slab could be one associated with next tid and our alloc/free 4017 * request will be failed. In this case, we will retry. So, no problem. 4018 */ 4019 barrier(); 4020 4021 /* 4022 * The transaction ids are globally unique per cpu and per operation on 4023 * a per cpu queue. Thus they can be guarantee that the cmpxchg_double 4024 * occurs on the right processor and that there was no operation on the 4025 * linked list in between. 4026 */ 4027 4028 object = c->freelist; 4029 slab = c->slab; 4030 4031 #ifdef CONFIG_NUMA 4032 if (static_branch_unlikely(&strict_numa) && 4033 node == NUMA_NO_NODE) { 4034 4035 struct mempolicy *mpol = current->mempolicy; 4036 4037 if (mpol) { 4038 /* 4039 * Special BIND rule support. If existing slab 4040 * is in permitted set then do not redirect 4041 * to a particular node. 4042 * Otherwise we apply the memory policy to get 4043 * the node we need to allocate on. 4044 */ 4045 if (mpol->mode != MPOL_BIND || !slab || 4046 !node_isset(slab_nid(slab), mpol->nodes)) 4047 4048 node = mempolicy_slab_node(); 4049 } 4050 } 4051 #endif 4052 4053 if (!USE_LOCKLESS_FAST_PATH() || 4054 unlikely(!object || !slab || !node_match(slab, node))) { 4055 object = __slab_alloc(s, gfpflags, node, addr, c, orig_size); 4056 } else { 4057 void *next_object = get_freepointer_safe(s, object); 4058 4059 /* 4060 * The cmpxchg will only match if there was no additional 4061 * operation and if we are on the right processor. 4062 * 4063 * The cmpxchg does the following atomically (without lock 4064 * semantics!) 4065 * 1. Relocate first pointer to the current per cpu area. 4066 * 2. Verify that tid and freelist have not been changed 4067 * 3. If they were not changed replace tid and freelist 4068 * 4069 * Since this is without lock semantics the protection is only 4070 * against code executing on this cpu *not* from access by 4071 * other cpus. 4072 */ 4073 if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) { 4074 note_cmpxchg_failure("slab_alloc", s, tid); 4075 goto redo; 4076 } 4077 prefetch_freepointer(s, next_object); 4078 stat(s, ALLOC_FASTPATH); 4079 } 4080 4081 return object; 4082 } 4083 #else /* CONFIG_SLUB_TINY */ 4084 static void *__slab_alloc_node(struct kmem_cache *s, 4085 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size) 4086 { 4087 struct partial_context pc; 4088 struct slab *slab; 4089 void *object; 4090 4091 pc.flags = gfpflags; 4092 pc.orig_size = orig_size; 4093 slab = get_partial(s, node, &pc); 4094 4095 if (slab) 4096 return pc.object; 4097 4098 slab = new_slab(s, gfpflags, node); 4099 if (unlikely(!slab)) { 4100 slab_out_of_memory(s, gfpflags, node); 4101 return NULL; 4102 } 4103 4104 object = alloc_single_from_new_slab(s, slab, orig_size); 4105 4106 return object; 4107 } 4108 #endif /* CONFIG_SLUB_TINY */ 4109 4110 /* 4111 * If the object has been wiped upon free, make sure it's fully initialized by 4112 * zeroing out freelist pointer. 4113 * 4114 * Note that we also wipe custom freelist pointers. 4115 */ 4116 static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s, 4117 void *obj) 4118 { 4119 if (unlikely(slab_want_init_on_free(s)) && obj && 4120 !freeptr_outside_object(s)) 4121 memset((void *)((char *)kasan_reset_tag(obj) + s->offset), 4122 0, sizeof(void *)); 4123 } 4124 4125 static __fastpath_inline 4126 struct kmem_cache *slab_pre_alloc_hook(struct kmem_cache *s, gfp_t flags) 4127 { 4128 flags &= gfp_allowed_mask; 4129 4130 might_alloc(flags); 4131 4132 if (unlikely(should_failslab(s, flags))) 4133 return NULL; 4134 4135 return s; 4136 } 4137 4138 static __fastpath_inline 4139 bool slab_post_alloc_hook(struct kmem_cache *s, struct list_lru *lru, 4140 gfp_t flags, size_t size, void **p, bool init, 4141 unsigned int orig_size) 4142 { 4143 unsigned int zero_size = s->object_size; 4144 bool kasan_init = init; 4145 size_t i; 4146 gfp_t init_flags = flags & gfp_allowed_mask; 4147 4148 /* 4149 * For kmalloc object, the allocated memory size(object_size) is likely 4150 * larger than the requested size(orig_size). If redzone check is 4151 * enabled for the extra space, don't zero it, as it will be redzoned 4152 * soon. The redzone operation for this extra space could be seen as a 4153 * replacement of current poisoning under certain debug option, and 4154 * won't break other sanity checks. 4155 */ 4156 if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) && 4157 (s->flags & SLAB_KMALLOC)) 4158 zero_size = orig_size; 4159 4160 /* 4161 * When slab_debug is enabled, avoid memory initialization integrated 4162 * into KASAN and instead zero out the memory via the memset below with 4163 * the proper size. Otherwise, KASAN might overwrite SLUB redzones and 4164 * cause false-positive reports. This does not lead to a performance 4165 * penalty on production builds, as slab_debug is not intended to be 4166 * enabled there. 4167 */ 4168 if (__slub_debug_enabled()) 4169 kasan_init = false; 4170 4171 /* 4172 * As memory initialization might be integrated into KASAN, 4173 * kasan_slab_alloc and initialization memset must be 4174 * kept together to avoid discrepancies in behavior. 4175 * 4176 * As p[i] might get tagged, memset and kmemleak hook come after KASAN. 4177 */ 4178 for (i = 0; i < size; i++) { 4179 p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init); 4180 if (p[i] && init && (!kasan_init || 4181 !kasan_has_integrated_init())) 4182 memset(p[i], 0, zero_size); 4183 kmemleak_alloc_recursive(p[i], s->object_size, 1, 4184 s->flags, init_flags); 4185 kmsan_slab_alloc(s, p[i], init_flags); 4186 alloc_tagging_slab_alloc_hook(s, p[i], flags); 4187 } 4188 4189 return memcg_slab_post_alloc_hook(s, lru, flags, size, p); 4190 } 4191 4192 /* 4193 * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc) 4194 * have the fastpath folded into their functions. So no function call 4195 * overhead for requests that can be satisfied on the fastpath. 4196 * 4197 * The fastpath works by first checking if the lockless freelist can be used. 4198 * If not then __slab_alloc is called for slow processing. 4199 * 4200 * Otherwise we can simply pick the next object from the lockless free list. 4201 */ 4202 static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru, 4203 gfp_t gfpflags, int node, unsigned long addr, size_t orig_size) 4204 { 4205 void *object; 4206 bool init = false; 4207 4208 s = slab_pre_alloc_hook(s, gfpflags); 4209 if (unlikely(!s)) 4210 return NULL; 4211 4212 object = kfence_alloc(s, orig_size, gfpflags); 4213 if (unlikely(object)) 4214 goto out; 4215 4216 object = __slab_alloc_node(s, gfpflags, node, addr, orig_size); 4217 4218 maybe_wipe_obj_freeptr(s, object); 4219 init = slab_want_init_on_alloc(gfpflags, s); 4220 4221 out: 4222 /* 4223 * When init equals 'true', like for kzalloc() family, only 4224 * @orig_size bytes might be zeroed instead of s->object_size 4225 * In case this fails due to memcg_slab_post_alloc_hook(), 4226 * object is set to NULL 4227 */ 4228 slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size); 4229 4230 return object; 4231 } 4232 4233 void *kmem_cache_alloc_noprof(struct kmem_cache *s, gfp_t gfpflags) 4234 { 4235 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, _RET_IP_, 4236 s->object_size); 4237 4238 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE); 4239 4240 return ret; 4241 } 4242 EXPORT_SYMBOL(kmem_cache_alloc_noprof); 4243 4244 void *kmem_cache_alloc_lru_noprof(struct kmem_cache *s, struct list_lru *lru, 4245 gfp_t gfpflags) 4246 { 4247 void *ret = slab_alloc_node(s, lru, gfpflags, NUMA_NO_NODE, _RET_IP_, 4248 s->object_size); 4249 4250 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, NUMA_NO_NODE); 4251 4252 return ret; 4253 } 4254 EXPORT_SYMBOL(kmem_cache_alloc_lru_noprof); 4255 4256 bool kmem_cache_charge(void *objp, gfp_t gfpflags) 4257 { 4258 if (!memcg_kmem_online()) 4259 return true; 4260 4261 return memcg_slab_post_charge(objp, gfpflags); 4262 } 4263 EXPORT_SYMBOL(kmem_cache_charge); 4264 4265 /** 4266 * kmem_cache_alloc_node - Allocate an object on the specified node 4267 * @s: The cache to allocate from. 4268 * @gfpflags: See kmalloc(). 4269 * @node: node number of the target node. 4270 * 4271 * Identical to kmem_cache_alloc but it will allocate memory on the given 4272 * node, which can improve the performance for cpu bound structures. 4273 * 4274 * Fallback to other node is possible if __GFP_THISNODE is not set. 4275 * 4276 * Return: pointer to the new object or %NULL in case of error 4277 */ 4278 void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node) 4279 { 4280 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size); 4281 4282 trace_kmem_cache_alloc(_RET_IP_, ret, s, gfpflags, node); 4283 4284 return ret; 4285 } 4286 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof); 4287 4288 /* 4289 * To avoid unnecessary overhead, we pass through large allocation requests 4290 * directly to the page allocator. We use __GFP_COMP, because we will need to 4291 * know the allocation order to free the pages properly in kfree. 4292 */ 4293 static void *___kmalloc_large_node(size_t size, gfp_t flags, int node) 4294 { 4295 struct folio *folio; 4296 void *ptr = NULL; 4297 unsigned int order = get_order(size); 4298 4299 if (unlikely(flags & GFP_SLAB_BUG_MASK)) 4300 flags = kmalloc_fix_flags(flags); 4301 4302 flags |= __GFP_COMP; 4303 4304 if (node == NUMA_NO_NODE) 4305 folio = (struct folio *)alloc_frozen_pages_noprof(flags, order); 4306 else 4307 folio = (struct folio *)__alloc_frozen_pages_noprof(flags, order, node, NULL); 4308 4309 if (folio) { 4310 ptr = folio_address(folio); 4311 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, 4312 PAGE_SIZE << order); 4313 __folio_set_large_kmalloc(folio); 4314 } 4315 4316 ptr = kasan_kmalloc_large(ptr, size, flags); 4317 /* As ptr might get tagged, call kmemleak hook after KASAN. */ 4318 kmemleak_alloc(ptr, size, 1, flags); 4319 kmsan_kmalloc_large(ptr, size, flags); 4320 4321 return ptr; 4322 } 4323 4324 void *__kmalloc_large_noprof(size_t size, gfp_t flags) 4325 { 4326 void *ret = ___kmalloc_large_node(size, flags, NUMA_NO_NODE); 4327 4328 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size), 4329 flags, NUMA_NO_NODE); 4330 return ret; 4331 } 4332 EXPORT_SYMBOL(__kmalloc_large_noprof); 4333 4334 void *__kmalloc_large_node_noprof(size_t size, gfp_t flags, int node) 4335 { 4336 void *ret = ___kmalloc_large_node(size, flags, node); 4337 4338 trace_kmalloc(_RET_IP_, ret, size, PAGE_SIZE << get_order(size), 4339 flags, node); 4340 return ret; 4341 } 4342 EXPORT_SYMBOL(__kmalloc_large_node_noprof); 4343 4344 static __always_inline 4345 void *__do_kmalloc_node(size_t size, kmem_buckets *b, gfp_t flags, int node, 4346 unsigned long caller) 4347 { 4348 struct kmem_cache *s; 4349 void *ret; 4350 4351 if (unlikely(size > KMALLOC_MAX_CACHE_SIZE)) { 4352 ret = __kmalloc_large_node_noprof(size, flags, node); 4353 trace_kmalloc(caller, ret, size, 4354 PAGE_SIZE << get_order(size), flags, node); 4355 return ret; 4356 } 4357 4358 if (unlikely(!size)) 4359 return ZERO_SIZE_PTR; 4360 4361 s = kmalloc_slab(size, b, flags, caller); 4362 4363 ret = slab_alloc_node(s, NULL, flags, node, caller, size); 4364 ret = kasan_kmalloc(s, ret, size, flags); 4365 trace_kmalloc(caller, ret, size, s->size, flags, node); 4366 return ret; 4367 } 4368 void *__kmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node) 4369 { 4370 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, _RET_IP_); 4371 } 4372 EXPORT_SYMBOL(__kmalloc_node_noprof); 4373 4374 void *__kmalloc_noprof(size_t size, gfp_t flags) 4375 { 4376 return __do_kmalloc_node(size, NULL, flags, NUMA_NO_NODE, _RET_IP_); 4377 } 4378 EXPORT_SYMBOL(__kmalloc_noprof); 4379 4380 void *__kmalloc_node_track_caller_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, 4381 int node, unsigned long caller) 4382 { 4383 return __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), flags, node, caller); 4384 4385 } 4386 EXPORT_SYMBOL(__kmalloc_node_track_caller_noprof); 4387 4388 void *__kmalloc_cache_noprof(struct kmem_cache *s, gfp_t gfpflags, size_t size) 4389 { 4390 void *ret = slab_alloc_node(s, NULL, gfpflags, NUMA_NO_NODE, 4391 _RET_IP_, size); 4392 4393 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, NUMA_NO_NODE); 4394 4395 ret = kasan_kmalloc(s, ret, size, gfpflags); 4396 return ret; 4397 } 4398 EXPORT_SYMBOL(__kmalloc_cache_noprof); 4399 4400 void *__kmalloc_cache_node_noprof(struct kmem_cache *s, gfp_t gfpflags, 4401 int node, size_t size) 4402 { 4403 void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, size); 4404 4405 trace_kmalloc(_RET_IP_, ret, size, s->size, gfpflags, node); 4406 4407 ret = kasan_kmalloc(s, ret, size, gfpflags); 4408 return ret; 4409 } 4410 EXPORT_SYMBOL(__kmalloc_cache_node_noprof); 4411 4412 static noinline void free_to_partial_list( 4413 struct kmem_cache *s, struct slab *slab, 4414 void *head, void *tail, int bulk_cnt, 4415 unsigned long addr) 4416 { 4417 struct kmem_cache_node *n = get_node(s, slab_nid(slab)); 4418 struct slab *slab_free = NULL; 4419 int cnt = bulk_cnt; 4420 unsigned long flags; 4421 depot_stack_handle_t handle = 0; 4422 4423 if (s->flags & SLAB_STORE_USER) 4424 handle = set_track_prepare(); 4425 4426 spin_lock_irqsave(&n->list_lock, flags); 4427 4428 if (free_debug_processing(s, slab, head, tail, &cnt, addr, handle)) { 4429 void *prior = slab->freelist; 4430 4431 /* Perform the actual freeing while we still hold the locks */ 4432 slab->inuse -= cnt; 4433 set_freepointer(s, tail, prior); 4434 slab->freelist = head; 4435 4436 /* 4437 * If the slab is empty, and node's partial list is full, 4438 * it should be discarded anyway no matter it's on full or 4439 * partial list. 4440 */ 4441 if (slab->inuse == 0 && n->nr_partial >= s->min_partial) 4442 slab_free = slab; 4443 4444 if (!prior) { 4445 /* was on full list */ 4446 remove_full(s, n, slab); 4447 if (!slab_free) { 4448 add_partial(n, slab, DEACTIVATE_TO_TAIL); 4449 stat(s, FREE_ADD_PARTIAL); 4450 } 4451 } else if (slab_free) { 4452 remove_partial(n, slab); 4453 stat(s, FREE_REMOVE_PARTIAL); 4454 } 4455 } 4456 4457 if (slab_free) { 4458 /* 4459 * Update the counters while still holding n->list_lock to 4460 * prevent spurious validation warnings 4461 */ 4462 dec_slabs_node(s, slab_nid(slab_free), slab_free->objects); 4463 } 4464 4465 spin_unlock_irqrestore(&n->list_lock, flags); 4466 4467 if (slab_free) { 4468 stat(s, FREE_SLAB); 4469 free_slab(s, slab_free); 4470 } 4471 } 4472 4473 /* 4474 * Slow path handling. This may still be called frequently since objects 4475 * have a longer lifetime than the cpu slabs in most processing loads. 4476 * 4477 * So we still attempt to reduce cache line usage. Just take the slab 4478 * lock and free the item. If there is no additional partial slab 4479 * handling required then we can return immediately. 4480 */ 4481 static void __slab_free(struct kmem_cache *s, struct slab *slab, 4482 void *head, void *tail, int cnt, 4483 unsigned long addr) 4484 4485 { 4486 void *prior; 4487 int was_frozen; 4488 struct slab new; 4489 unsigned long counters; 4490 struct kmem_cache_node *n = NULL; 4491 unsigned long flags; 4492 bool on_node_partial; 4493 4494 stat(s, FREE_SLOWPATH); 4495 4496 if (IS_ENABLED(CONFIG_SLUB_TINY) || kmem_cache_debug(s)) { 4497 free_to_partial_list(s, slab, head, tail, cnt, addr); 4498 return; 4499 } 4500 4501 do { 4502 if (unlikely(n)) { 4503 spin_unlock_irqrestore(&n->list_lock, flags); 4504 n = NULL; 4505 } 4506 prior = slab->freelist; 4507 counters = slab->counters; 4508 set_freepointer(s, tail, prior); 4509 new.counters = counters; 4510 was_frozen = new.frozen; 4511 new.inuse -= cnt; 4512 if ((!new.inuse || !prior) && !was_frozen) { 4513 /* Needs to be taken off a list */ 4514 if (!kmem_cache_has_cpu_partial(s) || prior) { 4515 4516 n = get_node(s, slab_nid(slab)); 4517 /* 4518 * Speculatively acquire the list_lock. 4519 * If the cmpxchg does not succeed then we may 4520 * drop the list_lock without any processing. 4521 * 4522 * Otherwise the list_lock will synchronize with 4523 * other processors updating the list of slabs. 4524 */ 4525 spin_lock_irqsave(&n->list_lock, flags); 4526 4527 on_node_partial = slab_test_node_partial(slab); 4528 } 4529 } 4530 4531 } while (!slab_update_freelist(s, slab, 4532 prior, counters, 4533 head, new.counters, 4534 "__slab_free")); 4535 4536 if (likely(!n)) { 4537 4538 if (likely(was_frozen)) { 4539 /* 4540 * The list lock was not taken therefore no list 4541 * activity can be necessary. 4542 */ 4543 stat(s, FREE_FROZEN); 4544 } else if (kmem_cache_has_cpu_partial(s) && !prior) { 4545 /* 4546 * If we started with a full slab then put it onto the 4547 * per cpu partial list. 4548 */ 4549 put_cpu_partial(s, slab, 1); 4550 stat(s, CPU_PARTIAL_FREE); 4551 } 4552 4553 return; 4554 } 4555 4556 /* 4557 * This slab was partially empty but not on the per-node partial list, 4558 * in which case we shouldn't manipulate its list, just return. 4559 */ 4560 if (prior && !on_node_partial) { 4561 spin_unlock_irqrestore(&n->list_lock, flags); 4562 return; 4563 } 4564 4565 if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) 4566 goto slab_empty; 4567 4568 /* 4569 * Objects left in the slab. If it was not on the partial list before 4570 * then add it. 4571 */ 4572 if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) { 4573 add_partial(n, slab, DEACTIVATE_TO_TAIL); 4574 stat(s, FREE_ADD_PARTIAL); 4575 } 4576 spin_unlock_irqrestore(&n->list_lock, flags); 4577 return; 4578 4579 slab_empty: 4580 if (prior) { 4581 /* 4582 * Slab on the partial list. 4583 */ 4584 remove_partial(n, slab); 4585 stat(s, FREE_REMOVE_PARTIAL); 4586 } 4587 4588 spin_unlock_irqrestore(&n->list_lock, flags); 4589 stat(s, FREE_SLAB); 4590 discard_slab(s, slab); 4591 } 4592 4593 #ifndef CONFIG_SLUB_TINY 4594 /* 4595 * Fastpath with forced inlining to produce a kfree and kmem_cache_free that 4596 * can perform fastpath freeing without additional function calls. 4597 * 4598 * The fastpath is only possible if we are freeing to the current cpu slab 4599 * of this processor. This typically the case if we have just allocated 4600 * the item before. 4601 * 4602 * If fastpath is not possible then fall back to __slab_free where we deal 4603 * with all sorts of special processing. 4604 * 4605 * Bulk free of a freelist with several objects (all pointing to the 4606 * same slab) possible by specifying head and tail ptr, plus objects 4607 * count (cnt). Bulk free indicated by tail pointer being set. 4608 */ 4609 static __always_inline void do_slab_free(struct kmem_cache *s, 4610 struct slab *slab, void *head, void *tail, 4611 int cnt, unsigned long addr) 4612 { 4613 struct kmem_cache_cpu *c; 4614 unsigned long tid; 4615 void **freelist; 4616 4617 redo: 4618 /* 4619 * Determine the currently cpus per cpu slab. 4620 * The cpu may change afterward. However that does not matter since 4621 * data is retrieved via this pointer. If we are on the same cpu 4622 * during the cmpxchg then the free will succeed. 4623 */ 4624 c = raw_cpu_ptr(s->cpu_slab); 4625 tid = READ_ONCE(c->tid); 4626 4627 /* Same with comment on barrier() in __slab_alloc_node() */ 4628 barrier(); 4629 4630 if (unlikely(slab != c->slab)) { 4631 __slab_free(s, slab, head, tail, cnt, addr); 4632 return; 4633 } 4634 4635 if (USE_LOCKLESS_FAST_PATH()) { 4636 freelist = READ_ONCE(c->freelist); 4637 4638 set_freepointer(s, tail, freelist); 4639 4640 if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) { 4641 note_cmpxchg_failure("slab_free", s, tid); 4642 goto redo; 4643 } 4644 } else { 4645 /* Update the free list under the local lock */ 4646 local_lock(&s->cpu_slab->lock); 4647 c = this_cpu_ptr(s->cpu_slab); 4648 if (unlikely(slab != c->slab)) { 4649 local_unlock(&s->cpu_slab->lock); 4650 goto redo; 4651 } 4652 tid = c->tid; 4653 freelist = c->freelist; 4654 4655 set_freepointer(s, tail, freelist); 4656 c->freelist = head; 4657 c->tid = next_tid(tid); 4658 4659 local_unlock(&s->cpu_slab->lock); 4660 } 4661 stat_add(s, FREE_FASTPATH, cnt); 4662 } 4663 #else /* CONFIG_SLUB_TINY */ 4664 static void do_slab_free(struct kmem_cache *s, 4665 struct slab *slab, void *head, void *tail, 4666 int cnt, unsigned long addr) 4667 { 4668 __slab_free(s, slab, head, tail, cnt, addr); 4669 } 4670 #endif /* CONFIG_SLUB_TINY */ 4671 4672 static __fastpath_inline 4673 void slab_free(struct kmem_cache *s, struct slab *slab, void *object, 4674 unsigned long addr) 4675 { 4676 memcg_slab_free_hook(s, slab, &object, 1); 4677 alloc_tagging_slab_free_hook(s, slab, &object, 1); 4678 4679 if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false))) 4680 do_slab_free(s, slab, object, object, 1, addr); 4681 } 4682 4683 #ifdef CONFIG_MEMCG 4684 /* Do not inline the rare memcg charging failed path into the allocation path */ 4685 static noinline 4686 void memcg_alloc_abort_single(struct kmem_cache *s, void *object) 4687 { 4688 if (likely(slab_free_hook(s, object, slab_want_init_on_free(s), false))) 4689 do_slab_free(s, virt_to_slab(object), object, object, 1, _RET_IP_); 4690 } 4691 #endif 4692 4693 static __fastpath_inline 4694 void slab_free_bulk(struct kmem_cache *s, struct slab *slab, void *head, 4695 void *tail, void **p, int cnt, unsigned long addr) 4696 { 4697 memcg_slab_free_hook(s, slab, p, cnt); 4698 alloc_tagging_slab_free_hook(s, slab, p, cnt); 4699 /* 4700 * With KASAN enabled slab_free_freelist_hook modifies the freelist 4701 * to remove objects, whose reuse must be delayed. 4702 */ 4703 if (likely(slab_free_freelist_hook(s, &head, &tail, &cnt))) 4704 do_slab_free(s, slab, head, tail, cnt, addr); 4705 } 4706 4707 #ifdef CONFIG_SLUB_RCU_DEBUG 4708 static void slab_free_after_rcu_debug(struct rcu_head *rcu_head) 4709 { 4710 struct rcu_delayed_free *delayed_free = 4711 container_of(rcu_head, struct rcu_delayed_free, head); 4712 void *object = delayed_free->object; 4713 struct slab *slab = virt_to_slab(object); 4714 struct kmem_cache *s; 4715 4716 kfree(delayed_free); 4717 4718 if (WARN_ON(is_kfence_address(object))) 4719 return; 4720 4721 /* find the object and the cache again */ 4722 if (WARN_ON(!slab)) 4723 return; 4724 s = slab->slab_cache; 4725 if (WARN_ON(!(s->flags & SLAB_TYPESAFE_BY_RCU))) 4726 return; 4727 4728 /* resume freeing */ 4729 if (slab_free_hook(s, object, slab_want_init_on_free(s), true)) 4730 do_slab_free(s, slab, object, object, 1, _THIS_IP_); 4731 } 4732 #endif /* CONFIG_SLUB_RCU_DEBUG */ 4733 4734 #ifdef CONFIG_KASAN_GENERIC 4735 void ___cache_free(struct kmem_cache *cache, void *x, unsigned long addr) 4736 { 4737 do_slab_free(cache, virt_to_slab(x), x, x, 1, addr); 4738 } 4739 #endif 4740 4741 static inline struct kmem_cache *virt_to_cache(const void *obj) 4742 { 4743 struct slab *slab; 4744 4745 slab = virt_to_slab(obj); 4746 if (WARN_ONCE(!slab, "%s: Object is not a Slab page!\n", __func__)) 4747 return NULL; 4748 return slab->slab_cache; 4749 } 4750 4751 static inline struct kmem_cache *cache_from_obj(struct kmem_cache *s, void *x) 4752 { 4753 struct kmem_cache *cachep; 4754 4755 if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) && 4756 !kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) 4757 return s; 4758 4759 cachep = virt_to_cache(x); 4760 if (WARN(cachep && cachep != s, 4761 "%s: Wrong slab cache. %s but object is from %s\n", 4762 __func__, s->name, cachep->name)) 4763 print_tracking(cachep, x); 4764 return cachep; 4765 } 4766 4767 /** 4768 * kmem_cache_free - Deallocate an object 4769 * @s: The cache the allocation was from. 4770 * @x: The previously allocated object. 4771 * 4772 * Free an object which was previously allocated from this 4773 * cache. 4774 */ 4775 void kmem_cache_free(struct kmem_cache *s, void *x) 4776 { 4777 s = cache_from_obj(s, x); 4778 if (!s) 4779 return; 4780 trace_kmem_cache_free(_RET_IP_, x, s); 4781 slab_free(s, virt_to_slab(x), x, _RET_IP_); 4782 } 4783 EXPORT_SYMBOL(kmem_cache_free); 4784 4785 static void free_large_kmalloc(struct folio *folio, void *object) 4786 { 4787 unsigned int order = folio_order(folio); 4788 4789 if (WARN_ON_ONCE(!folio_test_large_kmalloc(folio))) { 4790 dump_page(&folio->page, "Not a kmalloc allocation"); 4791 return; 4792 } 4793 4794 if (WARN_ON_ONCE(order == 0)) 4795 pr_warn_once("object pointer: 0x%p\n", object); 4796 4797 kmemleak_free(object); 4798 kasan_kfree_large(object); 4799 kmsan_kfree_large(object); 4800 4801 lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, 4802 -(PAGE_SIZE << order)); 4803 __folio_clear_large_kmalloc(folio); 4804 free_frozen_pages(&folio->page, order); 4805 } 4806 4807 /* 4808 * Given an rcu_head embedded within an object obtained from kvmalloc at an 4809 * offset < 4k, free the object in question. 4810 */ 4811 void kvfree_rcu_cb(struct rcu_head *head) 4812 { 4813 void *obj = head; 4814 struct folio *folio; 4815 struct slab *slab; 4816 struct kmem_cache *s; 4817 void *slab_addr; 4818 4819 if (is_vmalloc_addr(obj)) { 4820 obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj); 4821 vfree(obj); 4822 return; 4823 } 4824 4825 folio = virt_to_folio(obj); 4826 if (!folio_test_slab(folio)) { 4827 /* 4828 * rcu_head offset can be only less than page size so no need to 4829 * consider folio order 4830 */ 4831 obj = (void *) PAGE_ALIGN_DOWN((unsigned long)obj); 4832 free_large_kmalloc(folio, obj); 4833 return; 4834 } 4835 4836 slab = folio_slab(folio); 4837 s = slab->slab_cache; 4838 slab_addr = folio_address(folio); 4839 4840 if (is_kfence_address(obj)) { 4841 obj = kfence_object_start(obj); 4842 } else { 4843 unsigned int idx = __obj_to_index(s, slab_addr, obj); 4844 4845 obj = slab_addr + s->size * idx; 4846 obj = fixup_red_left(s, obj); 4847 } 4848 4849 slab_free(s, slab, obj, _RET_IP_); 4850 } 4851 4852 /** 4853 * kfree - free previously allocated memory 4854 * @object: pointer returned by kmalloc() or kmem_cache_alloc() 4855 * 4856 * If @object is NULL, no operation is performed. 4857 */ 4858 void kfree(const void *object) 4859 { 4860 struct folio *folio; 4861 struct slab *slab; 4862 struct kmem_cache *s; 4863 void *x = (void *)object; 4864 4865 trace_kfree(_RET_IP_, object); 4866 4867 if (unlikely(ZERO_OR_NULL_PTR(object))) 4868 return; 4869 4870 folio = virt_to_folio(object); 4871 if (unlikely(!folio_test_slab(folio))) { 4872 free_large_kmalloc(folio, (void *)object); 4873 return; 4874 } 4875 4876 slab = folio_slab(folio); 4877 s = slab->slab_cache; 4878 slab_free(s, slab, x, _RET_IP_); 4879 } 4880 EXPORT_SYMBOL(kfree); 4881 4882 static __always_inline __realloc_size(2) void * 4883 __do_krealloc(const void *p, size_t new_size, gfp_t flags) 4884 { 4885 void *ret; 4886 size_t ks = 0; 4887 int orig_size = 0; 4888 struct kmem_cache *s = NULL; 4889 4890 if (unlikely(ZERO_OR_NULL_PTR(p))) 4891 goto alloc_new; 4892 4893 /* Check for double-free. */ 4894 if (!kasan_check_byte(p)) 4895 return NULL; 4896 4897 if (is_kfence_address(p)) { 4898 ks = orig_size = kfence_ksize(p); 4899 } else { 4900 struct folio *folio; 4901 4902 folio = virt_to_folio(p); 4903 if (unlikely(!folio_test_slab(folio))) { 4904 /* Big kmalloc object */ 4905 WARN_ON(folio_size(folio) <= KMALLOC_MAX_CACHE_SIZE); 4906 WARN_ON(p != folio_address(folio)); 4907 ks = folio_size(folio); 4908 } else { 4909 s = folio_slab(folio)->slab_cache; 4910 orig_size = get_orig_size(s, (void *)p); 4911 ks = s->object_size; 4912 } 4913 } 4914 4915 /* If the old object doesn't fit, allocate a bigger one */ 4916 if (new_size > ks) 4917 goto alloc_new; 4918 4919 /* Zero out spare memory. */ 4920 if (want_init_on_alloc(flags)) { 4921 kasan_disable_current(); 4922 if (orig_size && orig_size < new_size) 4923 memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size); 4924 else 4925 memset(kasan_reset_tag(p) + new_size, 0, ks - new_size); 4926 kasan_enable_current(); 4927 } 4928 4929 /* Setup kmalloc redzone when needed */ 4930 if (s && slub_debug_orig_size(s)) { 4931 set_orig_size(s, (void *)p, new_size); 4932 if (s->flags & SLAB_RED_ZONE && new_size < ks) 4933 memset_no_sanitize_memory(kasan_reset_tag(p) + new_size, 4934 SLUB_RED_ACTIVE, ks - new_size); 4935 } 4936 4937 p = kasan_krealloc(p, new_size, flags); 4938 return (void *)p; 4939 4940 alloc_new: 4941 ret = kmalloc_node_track_caller_noprof(new_size, flags, NUMA_NO_NODE, _RET_IP_); 4942 if (ret && p) { 4943 /* Disable KASAN checks as the object's redzone is accessed. */ 4944 kasan_disable_current(); 4945 memcpy(ret, kasan_reset_tag(p), orig_size ?: ks); 4946 kasan_enable_current(); 4947 } 4948 4949 return ret; 4950 } 4951 4952 /** 4953 * krealloc - reallocate memory. The contents will remain unchanged. 4954 * @p: object to reallocate memory for. 4955 * @new_size: how many bytes of memory are required. 4956 * @flags: the type of memory to allocate. 4957 * 4958 * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size 4959 * is 0 and @p is not a %NULL pointer, the object pointed to is freed. 4960 * 4961 * If __GFP_ZERO logic is requested, callers must ensure that, starting with the 4962 * initial memory allocation, every subsequent call to this API for the same 4963 * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that 4964 * __GFP_ZERO is not fully honored by this API. 4965 * 4966 * When slub_debug_orig_size() is off, krealloc() only knows about the bucket 4967 * size of an allocation (but not the exact size it was allocated with) and 4968 * hence implements the following semantics for shrinking and growing buffers 4969 * with __GFP_ZERO:: 4970 * 4971 * new bucket 4972 * 0 size size 4973 * |--------|----------------| 4974 * | keep | zero | 4975 * 4976 * Otherwise, the original allocation size 'orig_size' could be used to 4977 * precisely clear the requested size, and the new size will also be stored 4978 * as the new 'orig_size'. 4979 * 4980 * In any case, the contents of the object pointed to are preserved up to the 4981 * lesser of the new and old sizes. 4982 * 4983 * Return: pointer to the allocated memory or %NULL in case of error 4984 */ 4985 void *krealloc_noprof(const void *p, size_t new_size, gfp_t flags) 4986 { 4987 void *ret; 4988 4989 if (unlikely(!new_size)) { 4990 kfree(p); 4991 return ZERO_SIZE_PTR; 4992 } 4993 4994 ret = __do_krealloc(p, new_size, flags); 4995 if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret)) 4996 kfree(p); 4997 4998 return ret; 4999 } 5000 EXPORT_SYMBOL(krealloc_noprof); 5001 5002 static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size) 5003 { 5004 /* 5005 * We want to attempt a large physically contiguous block first because 5006 * it is less likely to fragment multiple larger blocks and therefore 5007 * contribute to a long term fragmentation less than vmalloc fallback. 5008 * However make sure that larger requests are not too disruptive - i.e. 5009 * do not direct reclaim unless physically continuous memory is preferred 5010 * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to 5011 * start working in the background 5012 */ 5013 if (size > PAGE_SIZE) { 5014 flags |= __GFP_NOWARN; 5015 5016 if (!(flags & __GFP_RETRY_MAYFAIL)) 5017 flags &= ~__GFP_DIRECT_RECLAIM; 5018 5019 /* nofail semantic is implemented by the vmalloc fallback */ 5020 flags &= ~__GFP_NOFAIL; 5021 } 5022 5023 return flags; 5024 } 5025 5026 /** 5027 * __kvmalloc_node - attempt to allocate physically contiguous memory, but upon 5028 * failure, fall back to non-contiguous (vmalloc) allocation. 5029 * @size: size of the request. 5030 * @b: which set of kmalloc buckets to allocate from. 5031 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL. 5032 * @node: numa node to allocate from 5033 * 5034 * Uses kmalloc to get the memory but if the allocation fails then falls back 5035 * to the vmalloc allocator. Use kvfree for freeing the memory. 5036 * 5037 * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier. 5038 * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is 5039 * preferable to the vmalloc fallback, due to visible performance drawbacks. 5040 * 5041 * Return: pointer to the allocated memory of %NULL in case of failure 5042 */ 5043 void *__kvmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node) 5044 { 5045 void *ret; 5046 5047 /* 5048 * It doesn't really make sense to fallback to vmalloc for sub page 5049 * requests 5050 */ 5051 ret = __do_kmalloc_node(size, PASS_BUCKET_PARAM(b), 5052 kmalloc_gfp_adjust(flags, size), 5053 node, _RET_IP_); 5054 if (ret || size <= PAGE_SIZE) 5055 return ret; 5056 5057 /* non-sleeping allocations are not supported by vmalloc */ 5058 if (!gfpflags_allow_blocking(flags)) 5059 return NULL; 5060 5061 /* Don't even allow crazy sizes */ 5062 if (unlikely(size > INT_MAX)) { 5063 WARN_ON_ONCE(!(flags & __GFP_NOWARN)); 5064 return NULL; 5065 } 5066 5067 /* 5068 * kvmalloc() can always use VM_ALLOW_HUGE_VMAP, 5069 * since the callers already cannot assume anything 5070 * about the resulting pointer, and cannot play 5071 * protection games. 5072 */ 5073 return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END, 5074 flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP, 5075 node, __builtin_return_address(0)); 5076 } 5077 EXPORT_SYMBOL(__kvmalloc_node_noprof); 5078 5079 /** 5080 * kvfree() - Free memory. 5081 * @addr: Pointer to allocated memory. 5082 * 5083 * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc(). 5084 * It is slightly more efficient to use kfree() or vfree() if you are certain 5085 * that you know which one to use. 5086 * 5087 * Context: Either preemptible task context or not-NMI interrupt. 5088 */ 5089 void kvfree(const void *addr) 5090 { 5091 if (is_vmalloc_addr(addr)) 5092 vfree(addr); 5093 else 5094 kfree(addr); 5095 } 5096 EXPORT_SYMBOL(kvfree); 5097 5098 /** 5099 * kvfree_sensitive - Free a data object containing sensitive information. 5100 * @addr: address of the data object to be freed. 5101 * @len: length of the data object. 5102 * 5103 * Use the special memzero_explicit() function to clear the content of a 5104 * kvmalloc'ed object containing sensitive data to make sure that the 5105 * compiler won't optimize out the data clearing. 5106 */ 5107 void kvfree_sensitive(const void *addr, size_t len) 5108 { 5109 if (likely(!ZERO_OR_NULL_PTR(addr))) { 5110 memzero_explicit((void *)addr, len); 5111 kvfree(addr); 5112 } 5113 } 5114 EXPORT_SYMBOL(kvfree_sensitive); 5115 5116 /** 5117 * kvrealloc - reallocate memory; contents remain unchanged 5118 * @p: object to reallocate memory for 5119 * @size: the size to reallocate 5120 * @flags: the flags for the page level allocator 5121 * 5122 * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0 5123 * and @p is not a %NULL pointer, the object pointed to is freed. 5124 * 5125 * If __GFP_ZERO logic is requested, callers must ensure that, starting with the 5126 * initial memory allocation, every subsequent call to this API for the same 5127 * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that 5128 * __GFP_ZERO is not fully honored by this API. 5129 * 5130 * In any case, the contents of the object pointed to are preserved up to the 5131 * lesser of the new and old sizes. 5132 * 5133 * This function must not be called concurrently with itself or kvfree() for the 5134 * same memory allocation. 5135 * 5136 * Return: pointer to the allocated memory or %NULL in case of error 5137 */ 5138 void *kvrealloc_noprof(const void *p, size_t size, gfp_t flags) 5139 { 5140 void *n; 5141 5142 if (is_vmalloc_addr(p)) 5143 return vrealloc_noprof(p, size, flags); 5144 5145 n = krealloc_noprof(p, size, kmalloc_gfp_adjust(flags, size)); 5146 if (!n) { 5147 /* We failed to krealloc(), fall back to kvmalloc(). */ 5148 n = kvmalloc_noprof(size, flags); 5149 if (!n) 5150 return NULL; 5151 5152 if (p) { 5153 /* We already know that `p` is not a vmalloc address. */ 5154 kasan_disable_current(); 5155 memcpy(n, kasan_reset_tag(p), ksize(p)); 5156 kasan_enable_current(); 5157 5158 kfree(p); 5159 } 5160 } 5161 5162 return n; 5163 } 5164 EXPORT_SYMBOL(kvrealloc_noprof); 5165 5166 struct detached_freelist { 5167 struct slab *slab; 5168 void *tail; 5169 void *freelist; 5170 int cnt; 5171 struct kmem_cache *s; 5172 }; 5173 5174 /* 5175 * This function progressively scans the array with free objects (with 5176 * a limited look ahead) and extract objects belonging to the same 5177 * slab. It builds a detached freelist directly within the given 5178 * slab/objects. This can happen without any need for 5179 * synchronization, because the objects are owned by running process. 5180 * The freelist is build up as a single linked list in the objects. 5181 * The idea is, that this detached freelist can then be bulk 5182 * transferred to the real freelist(s), but only requiring a single 5183 * synchronization primitive. Look ahead in the array is limited due 5184 * to performance reasons. 5185 */ 5186 static inline 5187 int build_detached_freelist(struct kmem_cache *s, size_t size, 5188 void **p, struct detached_freelist *df) 5189 { 5190 int lookahead = 3; 5191 void *object; 5192 struct folio *folio; 5193 size_t same; 5194 5195 object = p[--size]; 5196 folio = virt_to_folio(object); 5197 if (!s) { 5198 /* Handle kalloc'ed objects */ 5199 if (unlikely(!folio_test_slab(folio))) { 5200 free_large_kmalloc(folio, object); 5201 df->slab = NULL; 5202 return size; 5203 } 5204 /* Derive kmem_cache from object */ 5205 df->slab = folio_slab(folio); 5206 df->s = df->slab->slab_cache; 5207 } else { 5208 df->slab = folio_slab(folio); 5209 df->s = cache_from_obj(s, object); /* Support for memcg */ 5210 } 5211 5212 /* Start new detached freelist */ 5213 df->tail = object; 5214 df->freelist = object; 5215 df->cnt = 1; 5216 5217 if (is_kfence_address(object)) 5218 return size; 5219 5220 set_freepointer(df->s, object, NULL); 5221 5222 same = size; 5223 while (size) { 5224 object = p[--size]; 5225 /* df->slab is always set at this point */ 5226 if (df->slab == virt_to_slab(object)) { 5227 /* Opportunity build freelist */ 5228 set_freepointer(df->s, object, df->freelist); 5229 df->freelist = object; 5230 df->cnt++; 5231 same--; 5232 if (size != same) 5233 swap(p[size], p[same]); 5234 continue; 5235 } 5236 5237 /* Limit look ahead search */ 5238 if (!--lookahead) 5239 break; 5240 } 5241 5242 return same; 5243 } 5244 5245 /* 5246 * Internal bulk free of objects that were not initialised by the post alloc 5247 * hooks and thus should not be processed by the free hooks 5248 */ 5249 static void __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p) 5250 { 5251 if (!size) 5252 return; 5253 5254 do { 5255 struct detached_freelist df; 5256 5257 size = build_detached_freelist(s, size, p, &df); 5258 if (!df.slab) 5259 continue; 5260 5261 if (kfence_free(df.freelist)) 5262 continue; 5263 5264 do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt, 5265 _RET_IP_); 5266 } while (likely(size)); 5267 } 5268 5269 /* Note that interrupts must be enabled when calling this function. */ 5270 void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p) 5271 { 5272 if (!size) 5273 return; 5274 5275 do { 5276 struct detached_freelist df; 5277 5278 size = build_detached_freelist(s, size, p, &df); 5279 if (!df.slab) 5280 continue; 5281 5282 slab_free_bulk(df.s, df.slab, df.freelist, df.tail, &p[size], 5283 df.cnt, _RET_IP_); 5284 } while (likely(size)); 5285 } 5286 EXPORT_SYMBOL(kmem_cache_free_bulk); 5287 5288 #ifndef CONFIG_SLUB_TINY 5289 static inline 5290 int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, size_t size, 5291 void **p) 5292 { 5293 struct kmem_cache_cpu *c; 5294 unsigned long irqflags; 5295 int i; 5296 5297 /* 5298 * Drain objects in the per cpu slab, while disabling local 5299 * IRQs, which protects against PREEMPT and interrupts 5300 * handlers invoking normal fastpath. 5301 */ 5302 c = slub_get_cpu_ptr(s->cpu_slab); 5303 local_lock_irqsave(&s->cpu_slab->lock, irqflags); 5304 5305 for (i = 0; i < size; i++) { 5306 void *object = kfence_alloc(s, s->object_size, flags); 5307 5308 if (unlikely(object)) { 5309 p[i] = object; 5310 continue; 5311 } 5312 5313 object = c->freelist; 5314 if (unlikely(!object)) { 5315 /* 5316 * We may have removed an object from c->freelist using 5317 * the fastpath in the previous iteration; in that case, 5318 * c->tid has not been bumped yet. 5319 * Since ___slab_alloc() may reenable interrupts while 5320 * allocating memory, we should bump c->tid now. 5321 */ 5322 c->tid = next_tid(c->tid); 5323 5324 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags); 5325 5326 /* 5327 * Invoking slow path likely have side-effect 5328 * of re-populating per CPU c->freelist 5329 */ 5330 p[i] = ___slab_alloc(s, flags, NUMA_NO_NODE, 5331 _RET_IP_, c, s->object_size); 5332 if (unlikely(!p[i])) 5333 goto error; 5334 5335 c = this_cpu_ptr(s->cpu_slab); 5336 maybe_wipe_obj_freeptr(s, p[i]); 5337 5338 local_lock_irqsave(&s->cpu_slab->lock, irqflags); 5339 5340 continue; /* goto for-loop */ 5341 } 5342 c->freelist = get_freepointer(s, object); 5343 p[i] = object; 5344 maybe_wipe_obj_freeptr(s, p[i]); 5345 stat(s, ALLOC_FASTPATH); 5346 } 5347 c->tid = next_tid(c->tid); 5348 local_unlock_irqrestore(&s->cpu_slab->lock, irqflags); 5349 slub_put_cpu_ptr(s->cpu_slab); 5350 5351 return i; 5352 5353 error: 5354 slub_put_cpu_ptr(s->cpu_slab); 5355 __kmem_cache_free_bulk(s, i, p); 5356 return 0; 5357 5358 } 5359 #else /* CONFIG_SLUB_TINY */ 5360 static int __kmem_cache_alloc_bulk(struct kmem_cache *s, gfp_t flags, 5361 size_t size, void **p) 5362 { 5363 int i; 5364 5365 for (i = 0; i < size; i++) { 5366 void *object = kfence_alloc(s, s->object_size, flags); 5367 5368 if (unlikely(object)) { 5369 p[i] = object; 5370 continue; 5371 } 5372 5373 p[i] = __slab_alloc_node(s, flags, NUMA_NO_NODE, 5374 _RET_IP_, s->object_size); 5375 if (unlikely(!p[i])) 5376 goto error; 5377 5378 maybe_wipe_obj_freeptr(s, p[i]); 5379 } 5380 5381 return i; 5382 5383 error: 5384 __kmem_cache_free_bulk(s, i, p); 5385 return 0; 5386 } 5387 #endif /* CONFIG_SLUB_TINY */ 5388 5389 /* Note that interrupts must be enabled when calling this function. */ 5390 int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size, 5391 void **p) 5392 { 5393 int i; 5394 5395 if (!size) 5396 return 0; 5397 5398 s = slab_pre_alloc_hook(s, flags); 5399 if (unlikely(!s)) 5400 return 0; 5401 5402 i = __kmem_cache_alloc_bulk(s, flags, size, p); 5403 if (unlikely(i == 0)) 5404 return 0; 5405 5406 /* 5407 * memcg and kmem_cache debug support and memory initialization. 5408 * Done outside of the IRQ disabled fastpath loop. 5409 */ 5410 if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p, 5411 slab_want_init_on_alloc(flags, s), s->object_size))) { 5412 return 0; 5413 } 5414 return i; 5415 } 5416 EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof); 5417 5418 5419 /* 5420 * Object placement in a slab is made very easy because we always start at 5421 * offset 0. If we tune the size of the object to the alignment then we can 5422 * get the required alignment by putting one properly sized object after 5423 * another. 5424 * 5425 * Notice that the allocation order determines the sizes of the per cpu 5426 * caches. Each processor has always one slab available for allocations. 5427 * Increasing the allocation order reduces the number of times that slabs 5428 * must be moved on and off the partial lists and is therefore a factor in 5429 * locking overhead. 5430 */ 5431 5432 /* 5433 * Minimum / Maximum order of slab pages. This influences locking overhead 5434 * and slab fragmentation. A higher order reduces the number of partial slabs 5435 * and increases the number of allocations possible without having to 5436 * take the list_lock. 5437 */ 5438 static unsigned int slub_min_order; 5439 static unsigned int slub_max_order = 5440 IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER; 5441 static unsigned int slub_min_objects; 5442 5443 /* 5444 * Calculate the order of allocation given an slab object size. 5445 * 5446 * The order of allocation has significant impact on performance and other 5447 * system components. Generally order 0 allocations should be preferred since 5448 * order 0 does not cause fragmentation in the page allocator. Larger objects 5449 * be problematic to put into order 0 slabs because there may be too much 5450 * unused space left. We go to a higher order if more than 1/16th of the slab 5451 * would be wasted. 5452 * 5453 * In order to reach satisfactory performance we must ensure that a minimum 5454 * number of objects is in one slab. Otherwise we may generate too much 5455 * activity on the partial lists which requires taking the list_lock. This is 5456 * less a concern for large slabs though which are rarely used. 5457 * 5458 * slab_max_order specifies the order where we begin to stop considering the 5459 * number of objects in a slab as critical. If we reach slab_max_order then 5460 * we try to keep the page order as low as possible. So we accept more waste 5461 * of space in favor of a small page order. 5462 * 5463 * Higher order allocations also allow the placement of more objects in a 5464 * slab and thereby reduce object handling overhead. If the user has 5465 * requested a higher minimum order then we start with that one instead of 5466 * the smallest order which will fit the object. 5467 */ 5468 static inline unsigned int calc_slab_order(unsigned int size, 5469 unsigned int min_order, unsigned int max_order, 5470 unsigned int fract_leftover) 5471 { 5472 unsigned int order; 5473 5474 for (order = min_order; order <= max_order; order++) { 5475 5476 unsigned int slab_size = (unsigned int)PAGE_SIZE << order; 5477 unsigned int rem; 5478 5479 rem = slab_size % size; 5480 5481 if (rem <= slab_size / fract_leftover) 5482 break; 5483 } 5484 5485 return order; 5486 } 5487 5488 static inline int calculate_order(unsigned int size) 5489 { 5490 unsigned int order; 5491 unsigned int min_objects; 5492 unsigned int max_objects; 5493 unsigned int min_order; 5494 5495 min_objects = slub_min_objects; 5496 if (!min_objects) { 5497 /* 5498 * Some architectures will only update present cpus when 5499 * onlining them, so don't trust the number if it's just 1. But 5500 * we also don't want to use nr_cpu_ids always, as on some other 5501 * architectures, there can be many possible cpus, but never 5502 * onlined. Here we compromise between trying to avoid too high 5503 * order on systems that appear larger than they are, and too 5504 * low order on systems that appear smaller than they are. 5505 */ 5506 unsigned int nr_cpus = num_present_cpus(); 5507 if (nr_cpus <= 1) 5508 nr_cpus = nr_cpu_ids; 5509 min_objects = 4 * (fls(nr_cpus) + 1); 5510 } 5511 /* min_objects can't be 0 because get_order(0) is undefined */ 5512 max_objects = max(order_objects(slub_max_order, size), 1U); 5513 min_objects = min(min_objects, max_objects); 5514 5515 min_order = max_t(unsigned int, slub_min_order, 5516 get_order(min_objects * size)); 5517 if (order_objects(min_order, size) > MAX_OBJS_PER_PAGE) 5518 return get_order(size * MAX_OBJS_PER_PAGE) - 1; 5519 5520 /* 5521 * Attempt to find best configuration for a slab. This works by first 5522 * attempting to generate a layout with the best possible configuration 5523 * and backing off gradually. 5524 * 5525 * We start with accepting at most 1/16 waste and try to find the 5526 * smallest order from min_objects-derived/slab_min_order up to 5527 * slab_max_order that will satisfy the constraint. Note that increasing 5528 * the order can only result in same or less fractional waste, not more. 5529 * 5530 * If that fails, we increase the acceptable fraction of waste and try 5531 * again. The last iteration with fraction of 1/2 would effectively 5532 * accept any waste and give us the order determined by min_objects, as 5533 * long as at least single object fits within slab_max_order. 5534 */ 5535 for (unsigned int fraction = 16; fraction > 1; fraction /= 2) { 5536 order = calc_slab_order(size, min_order, slub_max_order, 5537 fraction); 5538 if (order <= slub_max_order) 5539 return order; 5540 } 5541 5542 /* 5543 * Doh this slab cannot be placed using slab_max_order. 5544 */ 5545 order = get_order(size); 5546 if (order <= MAX_PAGE_ORDER) 5547 return order; 5548 return -ENOSYS; 5549 } 5550 5551 static void 5552 init_kmem_cache_node(struct kmem_cache_node *n) 5553 { 5554 n->nr_partial = 0; 5555 spin_lock_init(&n->list_lock); 5556 INIT_LIST_HEAD(&n->partial); 5557 #ifdef CONFIG_SLUB_DEBUG 5558 atomic_long_set(&n->nr_slabs, 0); 5559 atomic_long_set(&n->total_objects, 0); 5560 INIT_LIST_HEAD(&n->full); 5561 #endif 5562 } 5563 5564 #ifndef CONFIG_SLUB_TINY 5565 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s) 5566 { 5567 BUILD_BUG_ON(PERCPU_DYNAMIC_EARLY_SIZE < 5568 NR_KMALLOC_TYPES * KMALLOC_SHIFT_HIGH * 5569 sizeof(struct kmem_cache_cpu)); 5570 5571 /* 5572 * Must align to double word boundary for the double cmpxchg 5573 * instructions to work; see __pcpu_double_call_return_bool(). 5574 */ 5575 s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu), 5576 2 * sizeof(void *)); 5577 5578 if (!s->cpu_slab) 5579 return 0; 5580 5581 init_kmem_cache_cpus(s); 5582 5583 return 1; 5584 } 5585 #else 5586 static inline int alloc_kmem_cache_cpus(struct kmem_cache *s) 5587 { 5588 return 1; 5589 } 5590 #endif /* CONFIG_SLUB_TINY */ 5591 5592 static struct kmem_cache *kmem_cache_node; 5593 5594 /* 5595 * No kmalloc_node yet so do it by hand. We know that this is the first 5596 * slab on the node for this slabcache. There are no concurrent accesses 5597 * possible. 5598 * 5599 * Note that this function only works on the kmem_cache_node 5600 * when allocating for the kmem_cache_node. This is used for bootstrapping 5601 * memory on a fresh node that has no slab structures yet. 5602 */ 5603 static void early_kmem_cache_node_alloc(int node) 5604 { 5605 struct slab *slab; 5606 struct kmem_cache_node *n; 5607 5608 BUG_ON(kmem_cache_node->size < sizeof(struct kmem_cache_node)); 5609 5610 slab = new_slab(kmem_cache_node, GFP_NOWAIT, node); 5611 5612 BUG_ON(!slab); 5613 if (slab_nid(slab) != node) { 5614 pr_err("SLUB: Unable to allocate memory from node %d\n", node); 5615 pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n"); 5616 } 5617 5618 n = slab->freelist; 5619 BUG_ON(!n); 5620 #ifdef CONFIG_SLUB_DEBUG 5621 init_object(kmem_cache_node, n, SLUB_RED_ACTIVE); 5622 #endif 5623 n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false); 5624 slab->freelist = get_freepointer(kmem_cache_node, n); 5625 slab->inuse = 1; 5626 kmem_cache_node->node[node] = n; 5627 init_kmem_cache_node(n); 5628 inc_slabs_node(kmem_cache_node, node, slab->objects); 5629 5630 /* 5631 * No locks need to be taken here as it has just been 5632 * initialized and there is no concurrent access. 5633 */ 5634 __add_partial(n, slab, DEACTIVATE_TO_HEAD); 5635 } 5636 5637 static void free_kmem_cache_nodes(struct kmem_cache *s) 5638 { 5639 int node; 5640 struct kmem_cache_node *n; 5641 5642 for_each_kmem_cache_node(s, node, n) { 5643 s->node[node] = NULL; 5644 kmem_cache_free(kmem_cache_node, n); 5645 } 5646 } 5647 5648 void __kmem_cache_release(struct kmem_cache *s) 5649 { 5650 cache_random_seq_destroy(s); 5651 #ifndef CONFIG_SLUB_TINY 5652 free_percpu(s->cpu_slab); 5653 #endif 5654 free_kmem_cache_nodes(s); 5655 } 5656 5657 static int init_kmem_cache_nodes(struct kmem_cache *s) 5658 { 5659 int node; 5660 5661 for_each_node_mask(node, slab_nodes) { 5662 struct kmem_cache_node *n; 5663 5664 if (slab_state == DOWN) { 5665 early_kmem_cache_node_alloc(node); 5666 continue; 5667 } 5668 n = kmem_cache_alloc_node(kmem_cache_node, 5669 GFP_KERNEL, node); 5670 5671 if (!n) { 5672 free_kmem_cache_nodes(s); 5673 return 0; 5674 } 5675 5676 init_kmem_cache_node(n); 5677 s->node[node] = n; 5678 } 5679 return 1; 5680 } 5681 5682 static void set_cpu_partial(struct kmem_cache *s) 5683 { 5684 #ifdef CONFIG_SLUB_CPU_PARTIAL 5685 unsigned int nr_objects; 5686 5687 /* 5688 * cpu_partial determined the maximum number of objects kept in the 5689 * per cpu partial lists of a processor. 5690 * 5691 * Per cpu partial lists mainly contain slabs that just have one 5692 * object freed. If they are used for allocation then they can be 5693 * filled up again with minimal effort. The slab will never hit the 5694 * per node partial lists and therefore no locking will be required. 5695 * 5696 * For backwards compatibility reasons, this is determined as number 5697 * of objects, even though we now limit maximum number of pages, see 5698 * slub_set_cpu_partial() 5699 */ 5700 if (!kmem_cache_has_cpu_partial(s)) 5701 nr_objects = 0; 5702 else if (s->size >= PAGE_SIZE) 5703 nr_objects = 6; 5704 else if (s->size >= 1024) 5705 nr_objects = 24; 5706 else if (s->size >= 256) 5707 nr_objects = 52; 5708 else 5709 nr_objects = 120; 5710 5711 slub_set_cpu_partial(s, nr_objects); 5712 #endif 5713 } 5714 5715 /* 5716 * calculate_sizes() determines the order and the distribution of data within 5717 * a slab object. 5718 */ 5719 static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s) 5720 { 5721 slab_flags_t flags = s->flags; 5722 unsigned int size = s->object_size; 5723 unsigned int order; 5724 5725 /* 5726 * Round up object size to the next word boundary. We can only 5727 * place the free pointer at word boundaries and this determines 5728 * the possible location of the free pointer. 5729 */ 5730 size = ALIGN(size, sizeof(void *)); 5731 5732 #ifdef CONFIG_SLUB_DEBUG 5733 /* 5734 * Determine if we can poison the object itself. If the user of 5735 * the slab may touch the object after free or before allocation 5736 * then we should never poison the object itself. 5737 */ 5738 if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) && 5739 !s->ctor) 5740 s->flags |= __OBJECT_POISON; 5741 else 5742 s->flags &= ~__OBJECT_POISON; 5743 5744 5745 /* 5746 * If we are Redzoning then check if there is some space between the 5747 * end of the object and the free pointer. If not then add an 5748 * additional word to have some bytes to store Redzone information. 5749 */ 5750 if ((flags & SLAB_RED_ZONE) && size == s->object_size) 5751 size += sizeof(void *); 5752 #endif 5753 5754 /* 5755 * With that we have determined the number of bytes in actual use 5756 * by the object and redzoning. 5757 */ 5758 s->inuse = size; 5759 5760 if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) || 5761 (flags & SLAB_POISON) || s->ctor || 5762 ((flags & SLAB_RED_ZONE) && 5763 (s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) { 5764 /* 5765 * Relocate free pointer after the object if it is not 5766 * permitted to overwrite the first word of the object on 5767 * kmem_cache_free. 5768 * 5769 * This is the case if we do RCU, have a constructor or 5770 * destructor, are poisoning the objects, or are 5771 * redzoning an object smaller than sizeof(void *) or are 5772 * redzoning an object with slub_debug_orig_size() enabled, 5773 * in which case the right redzone may be extended. 5774 * 5775 * The assumption that s->offset >= s->inuse means free 5776 * pointer is outside of the object is used in the 5777 * freeptr_outside_object() function. If that is no 5778 * longer true, the function needs to be modified. 5779 */ 5780 s->offset = size; 5781 size += sizeof(void *); 5782 } else if ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) { 5783 s->offset = args->freeptr_offset; 5784 } else { 5785 /* 5786 * Store freelist pointer near middle of object to keep 5787 * it away from the edges of the object to avoid small 5788 * sized over/underflows from neighboring allocations. 5789 */ 5790 s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *)); 5791 } 5792 5793 #ifdef CONFIG_SLUB_DEBUG 5794 if (flags & SLAB_STORE_USER) { 5795 /* 5796 * Need to store information about allocs and frees after 5797 * the object. 5798 */ 5799 size += 2 * sizeof(struct track); 5800 5801 /* Save the original kmalloc request size */ 5802 if (flags & SLAB_KMALLOC) 5803 size += sizeof(unsigned int); 5804 } 5805 #endif 5806 5807 kasan_cache_create(s, &size, &s->flags); 5808 #ifdef CONFIG_SLUB_DEBUG 5809 if (flags & SLAB_RED_ZONE) { 5810 /* 5811 * Add some empty padding so that we can catch 5812 * overwrites from earlier objects rather than let 5813 * tracking information or the free pointer be 5814 * corrupted if a user writes before the start 5815 * of the object. 5816 */ 5817 size += sizeof(void *); 5818 5819 s->red_left_pad = sizeof(void *); 5820 s->red_left_pad = ALIGN(s->red_left_pad, s->align); 5821 size += s->red_left_pad; 5822 } 5823 #endif 5824 5825 /* 5826 * SLUB stores one object immediately after another beginning from 5827 * offset 0. In order to align the objects we have to simply size 5828 * each object to conform to the alignment. 5829 */ 5830 size = ALIGN(size, s->align); 5831 s->size = size; 5832 s->reciprocal_size = reciprocal_value(size); 5833 order = calculate_order(size); 5834 5835 if ((int)order < 0) 5836 return 0; 5837 5838 s->allocflags = __GFP_COMP; 5839 5840 if (s->flags & SLAB_CACHE_DMA) 5841 s->allocflags |= GFP_DMA; 5842 5843 if (s->flags & SLAB_CACHE_DMA32) 5844 s->allocflags |= GFP_DMA32; 5845 5846 if (s->flags & SLAB_RECLAIM_ACCOUNT) 5847 s->allocflags |= __GFP_RECLAIMABLE; 5848 5849 /* 5850 * Determine the number of objects per slab 5851 */ 5852 s->oo = oo_make(order, size); 5853 s->min = oo_make(get_order(size), size); 5854 5855 return !!oo_objects(s->oo); 5856 } 5857 5858 static void list_slab_objects(struct kmem_cache *s, struct slab *slab) 5859 { 5860 #ifdef CONFIG_SLUB_DEBUG 5861 void *addr = slab_address(slab); 5862 void *p; 5863 5864 if (!slab_add_kunit_errors()) 5865 slab_bug(s, "Objects remaining on __kmem_cache_shutdown()"); 5866 5867 spin_lock(&object_map_lock); 5868 __fill_map(object_map, s, slab); 5869 5870 for_each_object(p, s, addr, slab->objects) { 5871 5872 if (!test_bit(__obj_to_index(s, addr, p), object_map)) { 5873 if (slab_add_kunit_errors()) 5874 continue; 5875 pr_err("Object 0x%p @offset=%tu\n", p, p - addr); 5876 print_tracking(s, p); 5877 } 5878 } 5879 spin_unlock(&object_map_lock); 5880 5881 __slab_err(slab); 5882 #endif 5883 } 5884 5885 /* 5886 * Attempt to free all partial slabs on a node. 5887 * This is called from __kmem_cache_shutdown(). We must take list_lock 5888 * because sysfs file might still access partial list after the shutdowning. 5889 */ 5890 static void free_partial(struct kmem_cache *s, struct kmem_cache_node *n) 5891 { 5892 LIST_HEAD(discard); 5893 struct slab *slab, *h; 5894 5895 BUG_ON(irqs_disabled()); 5896 spin_lock_irq(&n->list_lock); 5897 list_for_each_entry_safe(slab, h, &n->partial, slab_list) { 5898 if (!slab->inuse) { 5899 remove_partial(n, slab); 5900 list_add(&slab->slab_list, &discard); 5901 } else { 5902 list_slab_objects(s, slab); 5903 } 5904 } 5905 spin_unlock_irq(&n->list_lock); 5906 5907 list_for_each_entry_safe(slab, h, &discard, slab_list) 5908 discard_slab(s, slab); 5909 } 5910 5911 bool __kmem_cache_empty(struct kmem_cache *s) 5912 { 5913 int node; 5914 struct kmem_cache_node *n; 5915 5916 for_each_kmem_cache_node(s, node, n) 5917 if (n->nr_partial || node_nr_slabs(n)) 5918 return false; 5919 return true; 5920 } 5921 5922 /* 5923 * Release all resources used by a slab cache. 5924 */ 5925 int __kmem_cache_shutdown(struct kmem_cache *s) 5926 { 5927 int node; 5928 struct kmem_cache_node *n; 5929 5930 flush_all_cpus_locked(s); 5931 /* Attempt to free all objects */ 5932 for_each_kmem_cache_node(s, node, n) { 5933 free_partial(s, n); 5934 if (n->nr_partial || node_nr_slabs(n)) 5935 return 1; 5936 } 5937 return 0; 5938 } 5939 5940 #ifdef CONFIG_PRINTK 5941 void __kmem_obj_info(struct kmem_obj_info *kpp, void *object, struct slab *slab) 5942 { 5943 void *base; 5944 int __maybe_unused i; 5945 unsigned int objnr; 5946 void *objp; 5947 void *objp0; 5948 struct kmem_cache *s = slab->slab_cache; 5949 struct track __maybe_unused *trackp; 5950 5951 kpp->kp_ptr = object; 5952 kpp->kp_slab = slab; 5953 kpp->kp_slab_cache = s; 5954 base = slab_address(slab); 5955 objp0 = kasan_reset_tag(object); 5956 #ifdef CONFIG_SLUB_DEBUG 5957 objp = restore_red_left(s, objp0); 5958 #else 5959 objp = objp0; 5960 #endif 5961 objnr = obj_to_index(s, slab, objp); 5962 kpp->kp_data_offset = (unsigned long)((char *)objp0 - (char *)objp); 5963 objp = base + s->size * objnr; 5964 kpp->kp_objp = objp; 5965 if (WARN_ON_ONCE(objp < base || objp >= base + slab->objects * s->size 5966 || (objp - base) % s->size) || 5967 !(s->flags & SLAB_STORE_USER)) 5968 return; 5969 #ifdef CONFIG_SLUB_DEBUG 5970 objp = fixup_red_left(s, objp); 5971 trackp = get_track(s, objp, TRACK_ALLOC); 5972 kpp->kp_ret = (void *)trackp->addr; 5973 #ifdef CONFIG_STACKDEPOT 5974 { 5975 depot_stack_handle_t handle; 5976 unsigned long *entries; 5977 unsigned int nr_entries; 5978 5979 handle = READ_ONCE(trackp->handle); 5980 if (handle) { 5981 nr_entries = stack_depot_fetch(handle, &entries); 5982 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++) 5983 kpp->kp_stack[i] = (void *)entries[i]; 5984 } 5985 5986 trackp = get_track(s, objp, TRACK_FREE); 5987 handle = READ_ONCE(trackp->handle); 5988 if (handle) { 5989 nr_entries = stack_depot_fetch(handle, &entries); 5990 for (i = 0; i < KS_ADDRS_COUNT && i < nr_entries; i++) 5991 kpp->kp_free_stack[i] = (void *)entries[i]; 5992 } 5993 } 5994 #endif 5995 #endif 5996 } 5997 #endif 5998 5999 /******************************************************************** 6000 * Kmalloc subsystem 6001 *******************************************************************/ 6002 6003 static int __init setup_slub_min_order(char *str) 6004 { 6005 get_option(&str, (int *)&slub_min_order); 6006 6007 if (slub_min_order > slub_max_order) 6008 slub_max_order = slub_min_order; 6009 6010 return 1; 6011 } 6012 6013 __setup("slab_min_order=", setup_slub_min_order); 6014 __setup_param("slub_min_order=", slub_min_order, setup_slub_min_order, 0); 6015 6016 6017 static int __init setup_slub_max_order(char *str) 6018 { 6019 get_option(&str, (int *)&slub_max_order); 6020 slub_max_order = min_t(unsigned int, slub_max_order, MAX_PAGE_ORDER); 6021 6022 if (slub_min_order > slub_max_order) 6023 slub_min_order = slub_max_order; 6024 6025 return 1; 6026 } 6027 6028 __setup("slab_max_order=", setup_slub_max_order); 6029 __setup_param("slub_max_order=", slub_max_order, setup_slub_max_order, 0); 6030 6031 static int __init setup_slub_min_objects(char *str) 6032 { 6033 get_option(&str, (int *)&slub_min_objects); 6034 6035 return 1; 6036 } 6037 6038 __setup("slab_min_objects=", setup_slub_min_objects); 6039 __setup_param("slub_min_objects=", slub_min_objects, setup_slub_min_objects, 0); 6040 6041 #ifdef CONFIG_NUMA 6042 static int __init setup_slab_strict_numa(char *str) 6043 { 6044 if (nr_node_ids > 1) { 6045 static_branch_enable(&strict_numa); 6046 pr_info("SLUB: Strict NUMA enabled.\n"); 6047 } else { 6048 pr_warn("slab_strict_numa parameter set on non NUMA system.\n"); 6049 } 6050 6051 return 1; 6052 } 6053 6054 __setup("slab_strict_numa", setup_slab_strict_numa); 6055 #endif 6056 6057 6058 #ifdef CONFIG_HARDENED_USERCOPY 6059 /* 6060 * Rejects incorrectly sized objects and objects that are to be copied 6061 * to/from userspace but do not fall entirely within the containing slab 6062 * cache's usercopy region. 6063 * 6064 * Returns NULL if check passes, otherwise const char * to name of cache 6065 * to indicate an error. 6066 */ 6067 void __check_heap_object(const void *ptr, unsigned long n, 6068 const struct slab *slab, bool to_user) 6069 { 6070 struct kmem_cache *s; 6071 unsigned int offset; 6072 bool is_kfence = is_kfence_address(ptr); 6073 6074 ptr = kasan_reset_tag(ptr); 6075 6076 /* Find object and usable object size. */ 6077 s = slab->slab_cache; 6078 6079 /* Reject impossible pointers. */ 6080 if (ptr < slab_address(slab)) 6081 usercopy_abort("SLUB object not in SLUB page?!", NULL, 6082 to_user, 0, n); 6083 6084 /* Find offset within object. */ 6085 if (is_kfence) 6086 offset = ptr - kfence_object_start(ptr); 6087 else 6088 offset = (ptr - slab_address(slab)) % s->size; 6089 6090 /* Adjust for redzone and reject if within the redzone. */ 6091 if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) { 6092 if (offset < s->red_left_pad) 6093 usercopy_abort("SLUB object in left red zone", 6094 s->name, to_user, offset, n); 6095 offset -= s->red_left_pad; 6096 } 6097 6098 /* Allow address range falling entirely within usercopy region. */ 6099 if (offset >= s->useroffset && 6100 offset - s->useroffset <= s->usersize && 6101 n <= s->useroffset - offset + s->usersize) 6102 return; 6103 6104 usercopy_abort("SLUB object", s->name, to_user, offset, n); 6105 } 6106 #endif /* CONFIG_HARDENED_USERCOPY */ 6107 6108 #define SHRINK_PROMOTE_MAX 32 6109 6110 /* 6111 * kmem_cache_shrink discards empty slabs and promotes the slabs filled 6112 * up most to the head of the partial lists. New allocations will then 6113 * fill those up and thus they can be removed from the partial lists. 6114 * 6115 * The slabs with the least items are placed last. This results in them 6116 * being allocated from last increasing the chance that the last objects 6117 * are freed in them. 6118 */ 6119 static int __kmem_cache_do_shrink(struct kmem_cache *s) 6120 { 6121 int node; 6122 int i; 6123 struct kmem_cache_node *n; 6124 struct slab *slab; 6125 struct slab *t; 6126 struct list_head discard; 6127 struct list_head promote[SHRINK_PROMOTE_MAX]; 6128 unsigned long flags; 6129 int ret = 0; 6130 6131 for_each_kmem_cache_node(s, node, n) { 6132 INIT_LIST_HEAD(&discard); 6133 for (i = 0; i < SHRINK_PROMOTE_MAX; i++) 6134 INIT_LIST_HEAD(promote + i); 6135 6136 spin_lock_irqsave(&n->list_lock, flags); 6137 6138 /* 6139 * Build lists of slabs to discard or promote. 6140 * 6141 * Note that concurrent frees may occur while we hold the 6142 * list_lock. slab->inuse here is the upper limit. 6143 */ 6144 list_for_each_entry_safe(slab, t, &n->partial, slab_list) { 6145 int free = slab->objects - slab->inuse; 6146 6147 /* Do not reread slab->inuse */ 6148 barrier(); 6149 6150 /* We do not keep full slabs on the list */ 6151 BUG_ON(free <= 0); 6152 6153 if (free == slab->objects) { 6154 list_move(&slab->slab_list, &discard); 6155 slab_clear_node_partial(slab); 6156 n->nr_partial--; 6157 dec_slabs_node(s, node, slab->objects); 6158 } else if (free <= SHRINK_PROMOTE_MAX) 6159 list_move(&slab->slab_list, promote + free - 1); 6160 } 6161 6162 /* 6163 * Promote the slabs filled up most to the head of the 6164 * partial list. 6165 */ 6166 for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--) 6167 list_splice(promote + i, &n->partial); 6168 6169 spin_unlock_irqrestore(&n->list_lock, flags); 6170 6171 /* Release empty slabs */ 6172 list_for_each_entry_safe(slab, t, &discard, slab_list) 6173 free_slab(s, slab); 6174 6175 if (node_nr_slabs(n)) 6176 ret = 1; 6177 } 6178 6179 return ret; 6180 } 6181 6182 int __kmem_cache_shrink(struct kmem_cache *s) 6183 { 6184 flush_all(s); 6185 return __kmem_cache_do_shrink(s); 6186 } 6187 6188 static int slab_mem_going_offline_callback(void *arg) 6189 { 6190 struct kmem_cache *s; 6191 6192 mutex_lock(&slab_mutex); 6193 list_for_each_entry(s, &slab_caches, list) { 6194 flush_all_cpus_locked(s); 6195 __kmem_cache_do_shrink(s); 6196 } 6197 mutex_unlock(&slab_mutex); 6198 6199 return 0; 6200 } 6201 6202 static void slab_mem_offline_callback(void *arg) 6203 { 6204 struct memory_notify *marg = arg; 6205 int offline_node; 6206 6207 offline_node = marg->status_change_nid_normal; 6208 6209 /* 6210 * If the node still has available memory. we need kmem_cache_node 6211 * for it yet. 6212 */ 6213 if (offline_node < 0) 6214 return; 6215 6216 mutex_lock(&slab_mutex); 6217 node_clear(offline_node, slab_nodes); 6218 /* 6219 * We no longer free kmem_cache_node structures here, as it would be 6220 * racy with all get_node() users, and infeasible to protect them with 6221 * slab_mutex. 6222 */ 6223 mutex_unlock(&slab_mutex); 6224 } 6225 6226 static int slab_mem_going_online_callback(void *arg) 6227 { 6228 struct kmem_cache_node *n; 6229 struct kmem_cache *s; 6230 struct memory_notify *marg = arg; 6231 int nid = marg->status_change_nid_normal; 6232 int ret = 0; 6233 6234 /* 6235 * If the node's memory is already available, then kmem_cache_node is 6236 * already created. Nothing to do. 6237 */ 6238 if (nid < 0) 6239 return 0; 6240 6241 /* 6242 * We are bringing a node online. No memory is available yet. We must 6243 * allocate a kmem_cache_node structure in order to bring the node 6244 * online. 6245 */ 6246 mutex_lock(&slab_mutex); 6247 list_for_each_entry(s, &slab_caches, list) { 6248 /* 6249 * The structure may already exist if the node was previously 6250 * onlined and offlined. 6251 */ 6252 if (get_node(s, nid)) 6253 continue; 6254 /* 6255 * XXX: kmem_cache_alloc_node will fallback to other nodes 6256 * since memory is not yet available from the node that 6257 * is brought up. 6258 */ 6259 n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL); 6260 if (!n) { 6261 ret = -ENOMEM; 6262 goto out; 6263 } 6264 init_kmem_cache_node(n); 6265 s->node[nid] = n; 6266 } 6267 /* 6268 * Any cache created after this point will also have kmem_cache_node 6269 * initialized for the new node. 6270 */ 6271 node_set(nid, slab_nodes); 6272 out: 6273 mutex_unlock(&slab_mutex); 6274 return ret; 6275 } 6276 6277 static int slab_memory_callback(struct notifier_block *self, 6278 unsigned long action, void *arg) 6279 { 6280 int ret = 0; 6281 6282 switch (action) { 6283 case MEM_GOING_ONLINE: 6284 ret = slab_mem_going_online_callback(arg); 6285 break; 6286 case MEM_GOING_OFFLINE: 6287 ret = slab_mem_going_offline_callback(arg); 6288 break; 6289 case MEM_OFFLINE: 6290 case MEM_CANCEL_ONLINE: 6291 slab_mem_offline_callback(arg); 6292 break; 6293 case MEM_ONLINE: 6294 case MEM_CANCEL_OFFLINE: 6295 break; 6296 } 6297 if (ret) 6298 ret = notifier_from_errno(ret); 6299 else 6300 ret = NOTIFY_OK; 6301 return ret; 6302 } 6303 6304 /******************************************************************** 6305 * Basic setup of slabs 6306 *******************************************************************/ 6307 6308 /* 6309 * Used for early kmem_cache structures that were allocated using 6310 * the page allocator. Allocate them properly then fix up the pointers 6311 * that may be pointing to the wrong kmem_cache structure. 6312 */ 6313 6314 static struct kmem_cache * __init bootstrap(struct kmem_cache *static_cache) 6315 { 6316 int node; 6317 struct kmem_cache *s = kmem_cache_zalloc(kmem_cache, GFP_NOWAIT); 6318 struct kmem_cache_node *n; 6319 6320 memcpy(s, static_cache, kmem_cache->object_size); 6321 6322 /* 6323 * This runs very early, and only the boot processor is supposed to be 6324 * up. Even if it weren't true, IRQs are not up so we couldn't fire 6325 * IPIs around. 6326 */ 6327 __flush_cpu_slab(s, smp_processor_id()); 6328 for_each_kmem_cache_node(s, node, n) { 6329 struct slab *p; 6330 6331 list_for_each_entry(p, &n->partial, slab_list) 6332 p->slab_cache = s; 6333 6334 #ifdef CONFIG_SLUB_DEBUG 6335 list_for_each_entry(p, &n->full, slab_list) 6336 p->slab_cache = s; 6337 #endif 6338 } 6339 list_add(&s->list, &slab_caches); 6340 return s; 6341 } 6342 6343 void __init kmem_cache_init(void) 6344 { 6345 static __initdata struct kmem_cache boot_kmem_cache, 6346 boot_kmem_cache_node; 6347 int node; 6348 6349 if (debug_guardpage_minorder()) 6350 slub_max_order = 0; 6351 6352 /* Print slub debugging pointers without hashing */ 6353 if (__slub_debug_enabled()) 6354 no_hash_pointers_enable(NULL); 6355 6356 kmem_cache_node = &boot_kmem_cache_node; 6357 kmem_cache = &boot_kmem_cache; 6358 6359 /* 6360 * Initialize the nodemask for which we will allocate per node 6361 * structures. Here we don't need taking slab_mutex yet. 6362 */ 6363 for_each_node_state(node, N_NORMAL_MEMORY) 6364 node_set(node, slab_nodes); 6365 6366 create_boot_cache(kmem_cache_node, "kmem_cache_node", 6367 sizeof(struct kmem_cache_node), 6368 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0); 6369 6370 hotplug_memory_notifier(slab_memory_callback, SLAB_CALLBACK_PRI); 6371 6372 /* Able to allocate the per node structures */ 6373 slab_state = PARTIAL; 6374 6375 create_boot_cache(kmem_cache, "kmem_cache", 6376 offsetof(struct kmem_cache, node) + 6377 nr_node_ids * sizeof(struct kmem_cache_node *), 6378 SLAB_HWCACHE_ALIGN | SLAB_NO_OBJ_EXT, 0, 0); 6379 6380 kmem_cache = bootstrap(&boot_kmem_cache); 6381 kmem_cache_node = bootstrap(&boot_kmem_cache_node); 6382 6383 /* Now we can use the kmem_cache to allocate kmalloc slabs */ 6384 setup_kmalloc_cache_index_table(); 6385 create_kmalloc_caches(); 6386 6387 /* Setup random freelists for each cache */ 6388 init_freelist_randomization(); 6389 6390 cpuhp_setup_state_nocalls(CPUHP_SLUB_DEAD, "slub:dead", NULL, 6391 slub_cpu_dead); 6392 6393 pr_info("SLUB: HWalign=%d, Order=%u-%u, MinObjects=%u, CPUs=%u, Nodes=%u\n", 6394 cache_line_size(), 6395 slub_min_order, slub_max_order, slub_min_objects, 6396 nr_cpu_ids, nr_node_ids); 6397 } 6398 6399 void __init kmem_cache_init_late(void) 6400 { 6401 #ifndef CONFIG_SLUB_TINY 6402 flushwq = alloc_workqueue("slub_flushwq", WQ_MEM_RECLAIM, 0); 6403 WARN_ON(!flushwq); 6404 #endif 6405 } 6406 6407 struct kmem_cache * 6408 __kmem_cache_alias(const char *name, unsigned int size, unsigned int align, 6409 slab_flags_t flags, void (*ctor)(void *)) 6410 { 6411 struct kmem_cache *s; 6412 6413 s = find_mergeable(size, align, flags, name, ctor); 6414 if (s) { 6415 if (sysfs_slab_alias(s, name)) 6416 pr_err("SLUB: Unable to add cache alias %s to sysfs\n", 6417 name); 6418 6419 s->refcount++; 6420 6421 /* 6422 * Adjust the object sizes so that we clear 6423 * the complete object on kzalloc. 6424 */ 6425 s->object_size = max(s->object_size, size); 6426 s->inuse = max(s->inuse, ALIGN(size, sizeof(void *))); 6427 } 6428 6429 return s; 6430 } 6431 6432 int do_kmem_cache_create(struct kmem_cache *s, const char *name, 6433 unsigned int size, struct kmem_cache_args *args, 6434 slab_flags_t flags) 6435 { 6436 int err = -EINVAL; 6437 6438 s->name = name; 6439 s->size = s->object_size = size; 6440 6441 s->flags = kmem_cache_flags(flags, s->name); 6442 #ifdef CONFIG_SLAB_FREELIST_HARDENED 6443 s->random = get_random_long(); 6444 #endif 6445 s->align = args->align; 6446 s->ctor = args->ctor; 6447 #ifdef CONFIG_HARDENED_USERCOPY 6448 s->useroffset = args->useroffset; 6449 s->usersize = args->usersize; 6450 #endif 6451 6452 if (!calculate_sizes(args, s)) 6453 goto out; 6454 if (disable_higher_order_debug) { 6455 /* 6456 * Disable debugging flags that store metadata if the min slab 6457 * order increased. 6458 */ 6459 if (get_order(s->size) > get_order(s->object_size)) { 6460 s->flags &= ~DEBUG_METADATA_FLAGS; 6461 s->offset = 0; 6462 if (!calculate_sizes(args, s)) 6463 goto out; 6464 } 6465 } 6466 6467 #ifdef system_has_freelist_aba 6468 if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) { 6469 /* Enable fast mode */ 6470 s->flags |= __CMPXCHG_DOUBLE; 6471 } 6472 #endif 6473 6474 /* 6475 * The larger the object size is, the more slabs we want on the partial 6476 * list to avoid pounding the page allocator excessively. 6477 */ 6478 s->min_partial = min_t(unsigned long, MAX_PARTIAL, ilog2(s->size) / 2); 6479 s->min_partial = max_t(unsigned long, MIN_PARTIAL, s->min_partial); 6480 6481 set_cpu_partial(s); 6482 6483 #ifdef CONFIG_NUMA 6484 s->remote_node_defrag_ratio = 1000; 6485 #endif 6486 6487 /* Initialize the pre-computed randomized freelist if slab is up */ 6488 if (slab_state >= UP) { 6489 if (init_cache_random_seq(s)) 6490 goto out; 6491 } 6492 6493 if (!init_kmem_cache_nodes(s)) 6494 goto out; 6495 6496 if (!alloc_kmem_cache_cpus(s)) 6497 goto out; 6498 6499 err = 0; 6500 6501 /* Mutex is not taken during early boot */ 6502 if (slab_state <= UP) 6503 goto out; 6504 6505 /* 6506 * Failing to create sysfs files is not critical to SLUB functionality. 6507 * If it fails, proceed with cache creation without these files. 6508 */ 6509 if (sysfs_slab_add(s)) 6510 pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name); 6511 6512 if (s->flags & SLAB_STORE_USER) 6513 debugfs_slab_add(s); 6514 6515 out: 6516 if (err) 6517 __kmem_cache_release(s); 6518 return err; 6519 } 6520 6521 #ifdef SLAB_SUPPORTS_SYSFS 6522 static int count_inuse(struct slab *slab) 6523 { 6524 return slab->inuse; 6525 } 6526 6527 static int count_total(struct slab *slab) 6528 { 6529 return slab->objects; 6530 } 6531 #endif 6532 6533 #ifdef CONFIG_SLUB_DEBUG 6534 static void validate_slab(struct kmem_cache *s, struct slab *slab, 6535 unsigned long *obj_map) 6536 { 6537 void *p; 6538 void *addr = slab_address(slab); 6539 6540 if (!check_slab(s, slab) || !on_freelist(s, slab, NULL)) 6541 return; 6542 6543 /* Now we know that a valid freelist exists */ 6544 __fill_map(obj_map, s, slab); 6545 for_each_object(p, s, addr, slab->objects) { 6546 u8 val = test_bit(__obj_to_index(s, addr, p), obj_map) ? 6547 SLUB_RED_INACTIVE : SLUB_RED_ACTIVE; 6548 6549 if (!check_object(s, slab, p, val)) 6550 break; 6551 } 6552 } 6553 6554 static int validate_slab_node(struct kmem_cache *s, 6555 struct kmem_cache_node *n, unsigned long *obj_map) 6556 { 6557 unsigned long count = 0; 6558 struct slab *slab; 6559 unsigned long flags; 6560 6561 spin_lock_irqsave(&n->list_lock, flags); 6562 6563 list_for_each_entry(slab, &n->partial, slab_list) { 6564 validate_slab(s, slab, obj_map); 6565 count++; 6566 } 6567 if (count != n->nr_partial) { 6568 pr_err("SLUB %s: %ld partial slabs counted but counter=%ld\n", 6569 s->name, count, n->nr_partial); 6570 slab_add_kunit_errors(); 6571 } 6572 6573 if (!(s->flags & SLAB_STORE_USER)) 6574 goto out; 6575 6576 list_for_each_entry(slab, &n->full, slab_list) { 6577 validate_slab(s, slab, obj_map); 6578 count++; 6579 } 6580 if (count != node_nr_slabs(n)) { 6581 pr_err("SLUB: %s %ld slabs counted but counter=%ld\n", 6582 s->name, count, node_nr_slabs(n)); 6583 slab_add_kunit_errors(); 6584 } 6585 6586 out: 6587 spin_unlock_irqrestore(&n->list_lock, flags); 6588 return count; 6589 } 6590 6591 long validate_slab_cache(struct kmem_cache *s) 6592 { 6593 int node; 6594 unsigned long count = 0; 6595 struct kmem_cache_node *n; 6596 unsigned long *obj_map; 6597 6598 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL); 6599 if (!obj_map) 6600 return -ENOMEM; 6601 6602 flush_all(s); 6603 for_each_kmem_cache_node(s, node, n) 6604 count += validate_slab_node(s, n, obj_map); 6605 6606 bitmap_free(obj_map); 6607 6608 return count; 6609 } 6610 EXPORT_SYMBOL(validate_slab_cache); 6611 6612 #ifdef CONFIG_DEBUG_FS 6613 /* 6614 * Generate lists of code addresses where slabcache objects are allocated 6615 * and freed. 6616 */ 6617 6618 struct location { 6619 depot_stack_handle_t handle; 6620 unsigned long count; 6621 unsigned long addr; 6622 unsigned long waste; 6623 long long sum_time; 6624 long min_time; 6625 long max_time; 6626 long min_pid; 6627 long max_pid; 6628 DECLARE_BITMAP(cpus, NR_CPUS); 6629 nodemask_t nodes; 6630 }; 6631 6632 struct loc_track { 6633 unsigned long max; 6634 unsigned long count; 6635 struct location *loc; 6636 loff_t idx; 6637 }; 6638 6639 static struct dentry *slab_debugfs_root; 6640 6641 static void free_loc_track(struct loc_track *t) 6642 { 6643 if (t->max) 6644 free_pages((unsigned long)t->loc, 6645 get_order(sizeof(struct location) * t->max)); 6646 } 6647 6648 static int alloc_loc_track(struct loc_track *t, unsigned long max, gfp_t flags) 6649 { 6650 struct location *l; 6651 int order; 6652 6653 order = get_order(sizeof(struct location) * max); 6654 6655 l = (void *)__get_free_pages(flags, order); 6656 if (!l) 6657 return 0; 6658 6659 if (t->count) { 6660 memcpy(l, t->loc, sizeof(struct location) * t->count); 6661 free_loc_track(t); 6662 } 6663 t->max = max; 6664 t->loc = l; 6665 return 1; 6666 } 6667 6668 static int add_location(struct loc_track *t, struct kmem_cache *s, 6669 const struct track *track, 6670 unsigned int orig_size) 6671 { 6672 long start, end, pos; 6673 struct location *l; 6674 unsigned long caddr, chandle, cwaste; 6675 unsigned long age = jiffies - track->when; 6676 depot_stack_handle_t handle = 0; 6677 unsigned int waste = s->object_size - orig_size; 6678 6679 #ifdef CONFIG_STACKDEPOT 6680 handle = READ_ONCE(track->handle); 6681 #endif 6682 start = -1; 6683 end = t->count; 6684 6685 for ( ; ; ) { 6686 pos = start + (end - start + 1) / 2; 6687 6688 /* 6689 * There is nothing at "end". If we end up there 6690 * we need to add something to before end. 6691 */ 6692 if (pos == end) 6693 break; 6694 6695 l = &t->loc[pos]; 6696 caddr = l->addr; 6697 chandle = l->handle; 6698 cwaste = l->waste; 6699 if ((track->addr == caddr) && (handle == chandle) && 6700 (waste == cwaste)) { 6701 6702 l->count++; 6703 if (track->when) { 6704 l->sum_time += age; 6705 if (age < l->min_time) 6706 l->min_time = age; 6707 if (age > l->max_time) 6708 l->max_time = age; 6709 6710 if (track->pid < l->min_pid) 6711 l->min_pid = track->pid; 6712 if (track->pid > l->max_pid) 6713 l->max_pid = track->pid; 6714 6715 cpumask_set_cpu(track->cpu, 6716 to_cpumask(l->cpus)); 6717 } 6718 node_set(page_to_nid(virt_to_page(track)), l->nodes); 6719 return 1; 6720 } 6721 6722 if (track->addr < caddr) 6723 end = pos; 6724 else if (track->addr == caddr && handle < chandle) 6725 end = pos; 6726 else if (track->addr == caddr && handle == chandle && 6727 waste < cwaste) 6728 end = pos; 6729 else 6730 start = pos; 6731 } 6732 6733 /* 6734 * Not found. Insert new tracking element. 6735 */ 6736 if (t->count >= t->max && !alloc_loc_track(t, 2 * t->max, GFP_ATOMIC)) 6737 return 0; 6738 6739 l = t->loc + pos; 6740 if (pos < t->count) 6741 memmove(l + 1, l, 6742 (t->count - pos) * sizeof(struct location)); 6743 t->count++; 6744 l->count = 1; 6745 l->addr = track->addr; 6746 l->sum_time = age; 6747 l->min_time = age; 6748 l->max_time = age; 6749 l->min_pid = track->pid; 6750 l->max_pid = track->pid; 6751 l->handle = handle; 6752 l->waste = waste; 6753 cpumask_clear(to_cpumask(l->cpus)); 6754 cpumask_set_cpu(track->cpu, to_cpumask(l->cpus)); 6755 nodes_clear(l->nodes); 6756 node_set(page_to_nid(virt_to_page(track)), l->nodes); 6757 return 1; 6758 } 6759 6760 static void process_slab(struct loc_track *t, struct kmem_cache *s, 6761 struct slab *slab, enum track_item alloc, 6762 unsigned long *obj_map) 6763 { 6764 void *addr = slab_address(slab); 6765 bool is_alloc = (alloc == TRACK_ALLOC); 6766 void *p; 6767 6768 __fill_map(obj_map, s, slab); 6769 6770 for_each_object(p, s, addr, slab->objects) 6771 if (!test_bit(__obj_to_index(s, addr, p), obj_map)) 6772 add_location(t, s, get_track(s, p, alloc), 6773 is_alloc ? get_orig_size(s, p) : 6774 s->object_size); 6775 } 6776 #endif /* CONFIG_DEBUG_FS */ 6777 #endif /* CONFIG_SLUB_DEBUG */ 6778 6779 #ifdef SLAB_SUPPORTS_SYSFS 6780 enum slab_stat_type { 6781 SL_ALL, /* All slabs */ 6782 SL_PARTIAL, /* Only partially allocated slabs */ 6783 SL_CPU, /* Only slabs used for cpu caches */ 6784 SL_OBJECTS, /* Determine allocated objects not slabs */ 6785 SL_TOTAL /* Determine object capacity not slabs */ 6786 }; 6787 6788 #define SO_ALL (1 << SL_ALL) 6789 #define SO_PARTIAL (1 << SL_PARTIAL) 6790 #define SO_CPU (1 << SL_CPU) 6791 #define SO_OBJECTS (1 << SL_OBJECTS) 6792 #define SO_TOTAL (1 << SL_TOTAL) 6793 6794 static ssize_t show_slab_objects(struct kmem_cache *s, 6795 char *buf, unsigned long flags) 6796 { 6797 unsigned long total = 0; 6798 int node; 6799 int x; 6800 unsigned long *nodes; 6801 int len = 0; 6802 6803 nodes = kcalloc(nr_node_ids, sizeof(unsigned long), GFP_KERNEL); 6804 if (!nodes) 6805 return -ENOMEM; 6806 6807 if (flags & SO_CPU) { 6808 int cpu; 6809 6810 for_each_possible_cpu(cpu) { 6811 struct kmem_cache_cpu *c = per_cpu_ptr(s->cpu_slab, 6812 cpu); 6813 int node; 6814 struct slab *slab; 6815 6816 slab = READ_ONCE(c->slab); 6817 if (!slab) 6818 continue; 6819 6820 node = slab_nid(slab); 6821 if (flags & SO_TOTAL) 6822 x = slab->objects; 6823 else if (flags & SO_OBJECTS) 6824 x = slab->inuse; 6825 else 6826 x = 1; 6827 6828 total += x; 6829 nodes[node] += x; 6830 6831 #ifdef CONFIG_SLUB_CPU_PARTIAL 6832 slab = slub_percpu_partial_read_once(c); 6833 if (slab) { 6834 node = slab_nid(slab); 6835 if (flags & SO_TOTAL) 6836 WARN_ON_ONCE(1); 6837 else if (flags & SO_OBJECTS) 6838 WARN_ON_ONCE(1); 6839 else 6840 x = data_race(slab->slabs); 6841 total += x; 6842 nodes[node] += x; 6843 } 6844 #endif 6845 } 6846 } 6847 6848 /* 6849 * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex" 6850 * already held which will conflict with an existing lock order: 6851 * 6852 * mem_hotplug_lock->slab_mutex->kernfs_mutex 6853 * 6854 * We don't really need mem_hotplug_lock (to hold off 6855 * slab_mem_going_offline_callback) here because slab's memory hot 6856 * unplug code doesn't destroy the kmem_cache->node[] data. 6857 */ 6858 6859 #ifdef CONFIG_SLUB_DEBUG 6860 if (flags & SO_ALL) { 6861 struct kmem_cache_node *n; 6862 6863 for_each_kmem_cache_node(s, node, n) { 6864 6865 if (flags & SO_TOTAL) 6866 x = node_nr_objs(n); 6867 else if (flags & SO_OBJECTS) 6868 x = node_nr_objs(n) - count_partial(n, count_free); 6869 else 6870 x = node_nr_slabs(n); 6871 total += x; 6872 nodes[node] += x; 6873 } 6874 6875 } else 6876 #endif 6877 if (flags & SO_PARTIAL) { 6878 struct kmem_cache_node *n; 6879 6880 for_each_kmem_cache_node(s, node, n) { 6881 if (flags & SO_TOTAL) 6882 x = count_partial(n, count_total); 6883 else if (flags & SO_OBJECTS) 6884 x = count_partial(n, count_inuse); 6885 else 6886 x = n->nr_partial; 6887 total += x; 6888 nodes[node] += x; 6889 } 6890 } 6891 6892 len += sysfs_emit_at(buf, len, "%lu", total); 6893 #ifdef CONFIG_NUMA 6894 for (node = 0; node < nr_node_ids; node++) { 6895 if (nodes[node]) 6896 len += sysfs_emit_at(buf, len, " N%d=%lu", 6897 node, nodes[node]); 6898 } 6899 #endif 6900 len += sysfs_emit_at(buf, len, "\n"); 6901 kfree(nodes); 6902 6903 return len; 6904 } 6905 6906 #define to_slab_attr(n) container_of(n, struct slab_attribute, attr) 6907 #define to_slab(n) container_of(n, struct kmem_cache, kobj) 6908 6909 struct slab_attribute { 6910 struct attribute attr; 6911 ssize_t (*show)(struct kmem_cache *s, char *buf); 6912 ssize_t (*store)(struct kmem_cache *s, const char *x, size_t count); 6913 }; 6914 6915 #define SLAB_ATTR_RO(_name) \ 6916 static struct slab_attribute _name##_attr = __ATTR_RO_MODE(_name, 0400) 6917 6918 #define SLAB_ATTR(_name) \ 6919 static struct slab_attribute _name##_attr = __ATTR_RW_MODE(_name, 0600) 6920 6921 static ssize_t slab_size_show(struct kmem_cache *s, char *buf) 6922 { 6923 return sysfs_emit(buf, "%u\n", s->size); 6924 } 6925 SLAB_ATTR_RO(slab_size); 6926 6927 static ssize_t align_show(struct kmem_cache *s, char *buf) 6928 { 6929 return sysfs_emit(buf, "%u\n", s->align); 6930 } 6931 SLAB_ATTR_RO(align); 6932 6933 static ssize_t object_size_show(struct kmem_cache *s, char *buf) 6934 { 6935 return sysfs_emit(buf, "%u\n", s->object_size); 6936 } 6937 SLAB_ATTR_RO(object_size); 6938 6939 static ssize_t objs_per_slab_show(struct kmem_cache *s, char *buf) 6940 { 6941 return sysfs_emit(buf, "%u\n", oo_objects(s->oo)); 6942 } 6943 SLAB_ATTR_RO(objs_per_slab); 6944 6945 static ssize_t order_show(struct kmem_cache *s, char *buf) 6946 { 6947 return sysfs_emit(buf, "%u\n", oo_order(s->oo)); 6948 } 6949 SLAB_ATTR_RO(order); 6950 6951 static ssize_t min_partial_show(struct kmem_cache *s, char *buf) 6952 { 6953 return sysfs_emit(buf, "%lu\n", s->min_partial); 6954 } 6955 6956 static ssize_t min_partial_store(struct kmem_cache *s, const char *buf, 6957 size_t length) 6958 { 6959 unsigned long min; 6960 int err; 6961 6962 err = kstrtoul(buf, 10, &min); 6963 if (err) 6964 return err; 6965 6966 s->min_partial = min; 6967 return length; 6968 } 6969 SLAB_ATTR(min_partial); 6970 6971 static ssize_t cpu_partial_show(struct kmem_cache *s, char *buf) 6972 { 6973 unsigned int nr_partial = 0; 6974 #ifdef CONFIG_SLUB_CPU_PARTIAL 6975 nr_partial = s->cpu_partial; 6976 #endif 6977 6978 return sysfs_emit(buf, "%u\n", nr_partial); 6979 } 6980 6981 static ssize_t cpu_partial_store(struct kmem_cache *s, const char *buf, 6982 size_t length) 6983 { 6984 unsigned int objects; 6985 int err; 6986 6987 err = kstrtouint(buf, 10, &objects); 6988 if (err) 6989 return err; 6990 if (objects && !kmem_cache_has_cpu_partial(s)) 6991 return -EINVAL; 6992 6993 slub_set_cpu_partial(s, objects); 6994 flush_all(s); 6995 return length; 6996 } 6997 SLAB_ATTR(cpu_partial); 6998 6999 static ssize_t ctor_show(struct kmem_cache *s, char *buf) 7000 { 7001 if (!s->ctor) 7002 return 0; 7003 return sysfs_emit(buf, "%pS\n", s->ctor); 7004 } 7005 SLAB_ATTR_RO(ctor); 7006 7007 static ssize_t aliases_show(struct kmem_cache *s, char *buf) 7008 { 7009 return sysfs_emit(buf, "%d\n", s->refcount < 0 ? 0 : s->refcount - 1); 7010 } 7011 SLAB_ATTR_RO(aliases); 7012 7013 static ssize_t partial_show(struct kmem_cache *s, char *buf) 7014 { 7015 return show_slab_objects(s, buf, SO_PARTIAL); 7016 } 7017 SLAB_ATTR_RO(partial); 7018 7019 static ssize_t cpu_slabs_show(struct kmem_cache *s, char *buf) 7020 { 7021 return show_slab_objects(s, buf, SO_CPU); 7022 } 7023 SLAB_ATTR_RO(cpu_slabs); 7024 7025 static ssize_t objects_partial_show(struct kmem_cache *s, char *buf) 7026 { 7027 return show_slab_objects(s, buf, SO_PARTIAL|SO_OBJECTS); 7028 } 7029 SLAB_ATTR_RO(objects_partial); 7030 7031 static ssize_t slabs_cpu_partial_show(struct kmem_cache *s, char *buf) 7032 { 7033 int objects = 0; 7034 int slabs = 0; 7035 int cpu __maybe_unused; 7036 int len = 0; 7037 7038 #ifdef CONFIG_SLUB_CPU_PARTIAL 7039 for_each_online_cpu(cpu) { 7040 struct slab *slab; 7041 7042 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu)); 7043 7044 if (slab) 7045 slabs += data_race(slab->slabs); 7046 } 7047 #endif 7048 7049 /* Approximate half-full slabs, see slub_set_cpu_partial() */ 7050 objects = (slabs * oo_objects(s->oo)) / 2; 7051 len += sysfs_emit_at(buf, len, "%d(%d)", objects, slabs); 7052 7053 #ifdef CONFIG_SLUB_CPU_PARTIAL 7054 for_each_online_cpu(cpu) { 7055 struct slab *slab; 7056 7057 slab = slub_percpu_partial(per_cpu_ptr(s->cpu_slab, cpu)); 7058 if (slab) { 7059 slabs = data_race(slab->slabs); 7060 objects = (slabs * oo_objects(s->oo)) / 2; 7061 len += sysfs_emit_at(buf, len, " C%d=%d(%d)", 7062 cpu, objects, slabs); 7063 } 7064 } 7065 #endif 7066 len += sysfs_emit_at(buf, len, "\n"); 7067 7068 return len; 7069 } 7070 SLAB_ATTR_RO(slabs_cpu_partial); 7071 7072 static ssize_t reclaim_account_show(struct kmem_cache *s, char *buf) 7073 { 7074 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RECLAIM_ACCOUNT)); 7075 } 7076 SLAB_ATTR_RO(reclaim_account); 7077 7078 static ssize_t hwcache_align_show(struct kmem_cache *s, char *buf) 7079 { 7080 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_HWCACHE_ALIGN)); 7081 } 7082 SLAB_ATTR_RO(hwcache_align); 7083 7084 #ifdef CONFIG_ZONE_DMA 7085 static ssize_t cache_dma_show(struct kmem_cache *s, char *buf) 7086 { 7087 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CACHE_DMA)); 7088 } 7089 SLAB_ATTR_RO(cache_dma); 7090 #endif 7091 7092 #ifdef CONFIG_HARDENED_USERCOPY 7093 static ssize_t usersize_show(struct kmem_cache *s, char *buf) 7094 { 7095 return sysfs_emit(buf, "%u\n", s->usersize); 7096 } 7097 SLAB_ATTR_RO(usersize); 7098 #endif 7099 7100 static ssize_t destroy_by_rcu_show(struct kmem_cache *s, char *buf) 7101 { 7102 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TYPESAFE_BY_RCU)); 7103 } 7104 SLAB_ATTR_RO(destroy_by_rcu); 7105 7106 #ifdef CONFIG_SLUB_DEBUG 7107 static ssize_t slabs_show(struct kmem_cache *s, char *buf) 7108 { 7109 return show_slab_objects(s, buf, SO_ALL); 7110 } 7111 SLAB_ATTR_RO(slabs); 7112 7113 static ssize_t total_objects_show(struct kmem_cache *s, char *buf) 7114 { 7115 return show_slab_objects(s, buf, SO_ALL|SO_TOTAL); 7116 } 7117 SLAB_ATTR_RO(total_objects); 7118 7119 static ssize_t objects_show(struct kmem_cache *s, char *buf) 7120 { 7121 return show_slab_objects(s, buf, SO_ALL|SO_OBJECTS); 7122 } 7123 SLAB_ATTR_RO(objects); 7124 7125 static ssize_t sanity_checks_show(struct kmem_cache *s, char *buf) 7126 { 7127 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_CONSISTENCY_CHECKS)); 7128 } 7129 SLAB_ATTR_RO(sanity_checks); 7130 7131 static ssize_t trace_show(struct kmem_cache *s, char *buf) 7132 { 7133 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_TRACE)); 7134 } 7135 SLAB_ATTR_RO(trace); 7136 7137 static ssize_t red_zone_show(struct kmem_cache *s, char *buf) 7138 { 7139 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_RED_ZONE)); 7140 } 7141 7142 SLAB_ATTR_RO(red_zone); 7143 7144 static ssize_t poison_show(struct kmem_cache *s, char *buf) 7145 { 7146 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_POISON)); 7147 } 7148 7149 SLAB_ATTR_RO(poison); 7150 7151 static ssize_t store_user_show(struct kmem_cache *s, char *buf) 7152 { 7153 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_STORE_USER)); 7154 } 7155 7156 SLAB_ATTR_RO(store_user); 7157 7158 static ssize_t validate_show(struct kmem_cache *s, char *buf) 7159 { 7160 return 0; 7161 } 7162 7163 static ssize_t validate_store(struct kmem_cache *s, 7164 const char *buf, size_t length) 7165 { 7166 int ret = -EINVAL; 7167 7168 if (buf[0] == '1' && kmem_cache_debug(s)) { 7169 ret = validate_slab_cache(s); 7170 if (ret >= 0) 7171 ret = length; 7172 } 7173 return ret; 7174 } 7175 SLAB_ATTR(validate); 7176 7177 #endif /* CONFIG_SLUB_DEBUG */ 7178 7179 #ifdef CONFIG_FAILSLAB 7180 static ssize_t failslab_show(struct kmem_cache *s, char *buf) 7181 { 7182 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_FAILSLAB)); 7183 } 7184 7185 static ssize_t failslab_store(struct kmem_cache *s, const char *buf, 7186 size_t length) 7187 { 7188 if (s->refcount > 1) 7189 return -EINVAL; 7190 7191 if (buf[0] == '1') 7192 WRITE_ONCE(s->flags, s->flags | SLAB_FAILSLAB); 7193 else 7194 WRITE_ONCE(s->flags, s->flags & ~SLAB_FAILSLAB); 7195 7196 return length; 7197 } 7198 SLAB_ATTR(failslab); 7199 #endif 7200 7201 static ssize_t shrink_show(struct kmem_cache *s, char *buf) 7202 { 7203 return 0; 7204 } 7205 7206 static ssize_t shrink_store(struct kmem_cache *s, 7207 const char *buf, size_t length) 7208 { 7209 if (buf[0] == '1') 7210 kmem_cache_shrink(s); 7211 else 7212 return -EINVAL; 7213 return length; 7214 } 7215 SLAB_ATTR(shrink); 7216 7217 #ifdef CONFIG_NUMA 7218 static ssize_t remote_node_defrag_ratio_show(struct kmem_cache *s, char *buf) 7219 { 7220 return sysfs_emit(buf, "%u\n", s->remote_node_defrag_ratio / 10); 7221 } 7222 7223 static ssize_t remote_node_defrag_ratio_store(struct kmem_cache *s, 7224 const char *buf, size_t length) 7225 { 7226 unsigned int ratio; 7227 int err; 7228 7229 err = kstrtouint(buf, 10, &ratio); 7230 if (err) 7231 return err; 7232 if (ratio > 100) 7233 return -ERANGE; 7234 7235 s->remote_node_defrag_ratio = ratio * 10; 7236 7237 return length; 7238 } 7239 SLAB_ATTR(remote_node_defrag_ratio); 7240 #endif 7241 7242 #ifdef CONFIG_SLUB_STATS 7243 static int show_stat(struct kmem_cache *s, char *buf, enum stat_item si) 7244 { 7245 unsigned long sum = 0; 7246 int cpu; 7247 int len = 0; 7248 int *data = kmalloc_array(nr_cpu_ids, sizeof(int), GFP_KERNEL); 7249 7250 if (!data) 7251 return -ENOMEM; 7252 7253 for_each_online_cpu(cpu) { 7254 unsigned x = per_cpu_ptr(s->cpu_slab, cpu)->stat[si]; 7255 7256 data[cpu] = x; 7257 sum += x; 7258 } 7259 7260 len += sysfs_emit_at(buf, len, "%lu", sum); 7261 7262 #ifdef CONFIG_SMP 7263 for_each_online_cpu(cpu) { 7264 if (data[cpu]) 7265 len += sysfs_emit_at(buf, len, " C%d=%u", 7266 cpu, data[cpu]); 7267 } 7268 #endif 7269 kfree(data); 7270 len += sysfs_emit_at(buf, len, "\n"); 7271 7272 return len; 7273 } 7274 7275 static void clear_stat(struct kmem_cache *s, enum stat_item si) 7276 { 7277 int cpu; 7278 7279 for_each_online_cpu(cpu) 7280 per_cpu_ptr(s->cpu_slab, cpu)->stat[si] = 0; 7281 } 7282 7283 #define STAT_ATTR(si, text) \ 7284 static ssize_t text##_show(struct kmem_cache *s, char *buf) \ 7285 { \ 7286 return show_stat(s, buf, si); \ 7287 } \ 7288 static ssize_t text##_store(struct kmem_cache *s, \ 7289 const char *buf, size_t length) \ 7290 { \ 7291 if (buf[0] != '0') \ 7292 return -EINVAL; \ 7293 clear_stat(s, si); \ 7294 return length; \ 7295 } \ 7296 SLAB_ATTR(text); \ 7297 7298 STAT_ATTR(ALLOC_FASTPATH, alloc_fastpath); 7299 STAT_ATTR(ALLOC_SLOWPATH, alloc_slowpath); 7300 STAT_ATTR(FREE_FASTPATH, free_fastpath); 7301 STAT_ATTR(FREE_SLOWPATH, free_slowpath); 7302 STAT_ATTR(FREE_FROZEN, free_frozen); 7303 STAT_ATTR(FREE_ADD_PARTIAL, free_add_partial); 7304 STAT_ATTR(FREE_REMOVE_PARTIAL, free_remove_partial); 7305 STAT_ATTR(ALLOC_FROM_PARTIAL, alloc_from_partial); 7306 STAT_ATTR(ALLOC_SLAB, alloc_slab); 7307 STAT_ATTR(ALLOC_REFILL, alloc_refill); 7308 STAT_ATTR(ALLOC_NODE_MISMATCH, alloc_node_mismatch); 7309 STAT_ATTR(FREE_SLAB, free_slab); 7310 STAT_ATTR(CPUSLAB_FLUSH, cpuslab_flush); 7311 STAT_ATTR(DEACTIVATE_FULL, deactivate_full); 7312 STAT_ATTR(DEACTIVATE_EMPTY, deactivate_empty); 7313 STAT_ATTR(DEACTIVATE_TO_HEAD, deactivate_to_head); 7314 STAT_ATTR(DEACTIVATE_TO_TAIL, deactivate_to_tail); 7315 STAT_ATTR(DEACTIVATE_REMOTE_FREES, deactivate_remote_frees); 7316 STAT_ATTR(DEACTIVATE_BYPASS, deactivate_bypass); 7317 STAT_ATTR(ORDER_FALLBACK, order_fallback); 7318 STAT_ATTR(CMPXCHG_DOUBLE_CPU_FAIL, cmpxchg_double_cpu_fail); 7319 STAT_ATTR(CMPXCHG_DOUBLE_FAIL, cmpxchg_double_fail); 7320 STAT_ATTR(CPU_PARTIAL_ALLOC, cpu_partial_alloc); 7321 STAT_ATTR(CPU_PARTIAL_FREE, cpu_partial_free); 7322 STAT_ATTR(CPU_PARTIAL_NODE, cpu_partial_node); 7323 STAT_ATTR(CPU_PARTIAL_DRAIN, cpu_partial_drain); 7324 #endif /* CONFIG_SLUB_STATS */ 7325 7326 #ifdef CONFIG_KFENCE 7327 static ssize_t skip_kfence_show(struct kmem_cache *s, char *buf) 7328 { 7329 return sysfs_emit(buf, "%d\n", !!(s->flags & SLAB_SKIP_KFENCE)); 7330 } 7331 7332 static ssize_t skip_kfence_store(struct kmem_cache *s, 7333 const char *buf, size_t length) 7334 { 7335 int ret = length; 7336 7337 if (buf[0] == '0') 7338 s->flags &= ~SLAB_SKIP_KFENCE; 7339 else if (buf[0] == '1') 7340 s->flags |= SLAB_SKIP_KFENCE; 7341 else 7342 ret = -EINVAL; 7343 7344 return ret; 7345 } 7346 SLAB_ATTR(skip_kfence); 7347 #endif 7348 7349 static struct attribute *slab_attrs[] = { 7350 &slab_size_attr.attr, 7351 &object_size_attr.attr, 7352 &objs_per_slab_attr.attr, 7353 &order_attr.attr, 7354 &min_partial_attr.attr, 7355 &cpu_partial_attr.attr, 7356 &objects_partial_attr.attr, 7357 &partial_attr.attr, 7358 &cpu_slabs_attr.attr, 7359 &ctor_attr.attr, 7360 &aliases_attr.attr, 7361 &align_attr.attr, 7362 &hwcache_align_attr.attr, 7363 &reclaim_account_attr.attr, 7364 &destroy_by_rcu_attr.attr, 7365 &shrink_attr.attr, 7366 &slabs_cpu_partial_attr.attr, 7367 #ifdef CONFIG_SLUB_DEBUG 7368 &total_objects_attr.attr, 7369 &objects_attr.attr, 7370 &slabs_attr.attr, 7371 &sanity_checks_attr.attr, 7372 &trace_attr.attr, 7373 &red_zone_attr.attr, 7374 &poison_attr.attr, 7375 &store_user_attr.attr, 7376 &validate_attr.attr, 7377 #endif 7378 #ifdef CONFIG_ZONE_DMA 7379 &cache_dma_attr.attr, 7380 #endif 7381 #ifdef CONFIG_NUMA 7382 &remote_node_defrag_ratio_attr.attr, 7383 #endif 7384 #ifdef CONFIG_SLUB_STATS 7385 &alloc_fastpath_attr.attr, 7386 &alloc_slowpath_attr.attr, 7387 &free_fastpath_attr.attr, 7388 &free_slowpath_attr.attr, 7389 &free_frozen_attr.attr, 7390 &free_add_partial_attr.attr, 7391 &free_remove_partial_attr.attr, 7392 &alloc_from_partial_attr.attr, 7393 &alloc_slab_attr.attr, 7394 &alloc_refill_attr.attr, 7395 &alloc_node_mismatch_attr.attr, 7396 &free_slab_attr.attr, 7397 &cpuslab_flush_attr.attr, 7398 &deactivate_full_attr.attr, 7399 &deactivate_empty_attr.attr, 7400 &deactivate_to_head_attr.attr, 7401 &deactivate_to_tail_attr.attr, 7402 &deactivate_remote_frees_attr.attr, 7403 &deactivate_bypass_attr.attr, 7404 &order_fallback_attr.attr, 7405 &cmpxchg_double_fail_attr.attr, 7406 &cmpxchg_double_cpu_fail_attr.attr, 7407 &cpu_partial_alloc_attr.attr, 7408 &cpu_partial_free_attr.attr, 7409 &cpu_partial_node_attr.attr, 7410 &cpu_partial_drain_attr.attr, 7411 #endif 7412 #ifdef CONFIG_FAILSLAB 7413 &failslab_attr.attr, 7414 #endif 7415 #ifdef CONFIG_HARDENED_USERCOPY 7416 &usersize_attr.attr, 7417 #endif 7418 #ifdef CONFIG_KFENCE 7419 &skip_kfence_attr.attr, 7420 #endif 7421 7422 NULL 7423 }; 7424 7425 static const struct attribute_group slab_attr_group = { 7426 .attrs = slab_attrs, 7427 }; 7428 7429 static ssize_t slab_attr_show(struct kobject *kobj, 7430 struct attribute *attr, 7431 char *buf) 7432 { 7433 struct slab_attribute *attribute; 7434 struct kmem_cache *s; 7435 7436 attribute = to_slab_attr(attr); 7437 s = to_slab(kobj); 7438 7439 if (!attribute->show) 7440 return -EIO; 7441 7442 return attribute->show(s, buf); 7443 } 7444 7445 static ssize_t slab_attr_store(struct kobject *kobj, 7446 struct attribute *attr, 7447 const char *buf, size_t len) 7448 { 7449 struct slab_attribute *attribute; 7450 struct kmem_cache *s; 7451 7452 attribute = to_slab_attr(attr); 7453 s = to_slab(kobj); 7454 7455 if (!attribute->store) 7456 return -EIO; 7457 7458 return attribute->store(s, buf, len); 7459 } 7460 7461 static void kmem_cache_release(struct kobject *k) 7462 { 7463 slab_kmem_cache_release(to_slab(k)); 7464 } 7465 7466 static const struct sysfs_ops slab_sysfs_ops = { 7467 .show = slab_attr_show, 7468 .store = slab_attr_store, 7469 }; 7470 7471 static const struct kobj_type slab_ktype = { 7472 .sysfs_ops = &slab_sysfs_ops, 7473 .release = kmem_cache_release, 7474 }; 7475 7476 static struct kset *slab_kset; 7477 7478 static inline struct kset *cache_kset(struct kmem_cache *s) 7479 { 7480 return slab_kset; 7481 } 7482 7483 #define ID_STR_LENGTH 32 7484 7485 /* Create a unique string id for a slab cache: 7486 * 7487 * Format :[flags-]size 7488 */ 7489 static char *create_unique_id(struct kmem_cache *s) 7490 { 7491 char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL); 7492 char *p = name; 7493 7494 if (!name) 7495 return ERR_PTR(-ENOMEM); 7496 7497 *p++ = ':'; 7498 /* 7499 * First flags affecting slabcache operations. We will only 7500 * get here for aliasable slabs so we do not need to support 7501 * too many flags. The flags here must cover all flags that 7502 * are matched during merging to guarantee that the id is 7503 * unique. 7504 */ 7505 if (s->flags & SLAB_CACHE_DMA) 7506 *p++ = 'd'; 7507 if (s->flags & SLAB_CACHE_DMA32) 7508 *p++ = 'D'; 7509 if (s->flags & SLAB_RECLAIM_ACCOUNT) 7510 *p++ = 'a'; 7511 if (s->flags & SLAB_CONSISTENCY_CHECKS) 7512 *p++ = 'F'; 7513 if (s->flags & SLAB_ACCOUNT) 7514 *p++ = 'A'; 7515 if (p != name + 1) 7516 *p++ = '-'; 7517 p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size); 7518 7519 if (WARN_ON(p > name + ID_STR_LENGTH - 1)) { 7520 kfree(name); 7521 return ERR_PTR(-EINVAL); 7522 } 7523 kmsan_unpoison_memory(name, p - name); 7524 return name; 7525 } 7526 7527 static int sysfs_slab_add(struct kmem_cache *s) 7528 { 7529 int err; 7530 const char *name; 7531 struct kset *kset = cache_kset(s); 7532 int unmergeable = slab_unmergeable(s); 7533 7534 if (!unmergeable && disable_higher_order_debug && 7535 (slub_debug & DEBUG_METADATA_FLAGS)) 7536 unmergeable = 1; 7537 7538 if (unmergeable) { 7539 /* 7540 * Slabcache can never be merged so we can use the name proper. 7541 * This is typically the case for debug situations. In that 7542 * case we can catch duplicate names easily. 7543 */ 7544 sysfs_remove_link(&slab_kset->kobj, s->name); 7545 name = s->name; 7546 } else { 7547 /* 7548 * Create a unique name for the slab as a target 7549 * for the symlinks. 7550 */ 7551 name = create_unique_id(s); 7552 if (IS_ERR(name)) 7553 return PTR_ERR(name); 7554 } 7555 7556 s->kobj.kset = kset; 7557 err = kobject_init_and_add(&s->kobj, &slab_ktype, NULL, "%s", name); 7558 if (err) 7559 goto out; 7560 7561 err = sysfs_create_group(&s->kobj, &slab_attr_group); 7562 if (err) 7563 goto out_del_kobj; 7564 7565 if (!unmergeable) { 7566 /* Setup first alias */ 7567 sysfs_slab_alias(s, s->name); 7568 } 7569 out: 7570 if (!unmergeable) 7571 kfree(name); 7572 return err; 7573 out_del_kobj: 7574 kobject_del(&s->kobj); 7575 goto out; 7576 } 7577 7578 void sysfs_slab_unlink(struct kmem_cache *s) 7579 { 7580 if (s->kobj.state_in_sysfs) 7581 kobject_del(&s->kobj); 7582 } 7583 7584 void sysfs_slab_release(struct kmem_cache *s) 7585 { 7586 kobject_put(&s->kobj); 7587 } 7588 7589 /* 7590 * Need to buffer aliases during bootup until sysfs becomes 7591 * available lest we lose that information. 7592 */ 7593 struct saved_alias { 7594 struct kmem_cache *s; 7595 const char *name; 7596 struct saved_alias *next; 7597 }; 7598 7599 static struct saved_alias *alias_list; 7600 7601 static int sysfs_slab_alias(struct kmem_cache *s, const char *name) 7602 { 7603 struct saved_alias *al; 7604 7605 if (slab_state == FULL) { 7606 /* 7607 * If we have a leftover link then remove it. 7608 */ 7609 sysfs_remove_link(&slab_kset->kobj, name); 7610 /* 7611 * The original cache may have failed to generate sysfs file. 7612 * In that case, sysfs_create_link() returns -ENOENT and 7613 * symbolic link creation is skipped. 7614 */ 7615 return sysfs_create_link(&slab_kset->kobj, &s->kobj, name); 7616 } 7617 7618 al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL); 7619 if (!al) 7620 return -ENOMEM; 7621 7622 al->s = s; 7623 al->name = name; 7624 al->next = alias_list; 7625 alias_list = al; 7626 kmsan_unpoison_memory(al, sizeof(*al)); 7627 return 0; 7628 } 7629 7630 static int __init slab_sysfs_init(void) 7631 { 7632 struct kmem_cache *s; 7633 int err; 7634 7635 mutex_lock(&slab_mutex); 7636 7637 slab_kset = kset_create_and_add("slab", NULL, kernel_kobj); 7638 if (!slab_kset) { 7639 mutex_unlock(&slab_mutex); 7640 pr_err("Cannot register slab subsystem.\n"); 7641 return -ENOMEM; 7642 } 7643 7644 slab_state = FULL; 7645 7646 list_for_each_entry(s, &slab_caches, list) { 7647 err = sysfs_slab_add(s); 7648 if (err) 7649 pr_err("SLUB: Unable to add boot slab %s to sysfs\n", 7650 s->name); 7651 } 7652 7653 while (alias_list) { 7654 struct saved_alias *al = alias_list; 7655 7656 alias_list = alias_list->next; 7657 err = sysfs_slab_alias(al->s, al->name); 7658 if (err) 7659 pr_err("SLUB: Unable to add boot slab alias %s to sysfs\n", 7660 al->name); 7661 kfree(al); 7662 } 7663 7664 mutex_unlock(&slab_mutex); 7665 return 0; 7666 } 7667 late_initcall(slab_sysfs_init); 7668 #endif /* SLAB_SUPPORTS_SYSFS */ 7669 7670 #if defined(CONFIG_SLUB_DEBUG) && defined(CONFIG_DEBUG_FS) 7671 static int slab_debugfs_show(struct seq_file *seq, void *v) 7672 { 7673 struct loc_track *t = seq->private; 7674 struct location *l; 7675 unsigned long idx; 7676 7677 idx = (unsigned long) t->idx; 7678 if (idx < t->count) { 7679 l = &t->loc[idx]; 7680 7681 seq_printf(seq, "%7ld ", l->count); 7682 7683 if (l->addr) 7684 seq_printf(seq, "%pS", (void *)l->addr); 7685 else 7686 seq_puts(seq, "<not-available>"); 7687 7688 if (l->waste) 7689 seq_printf(seq, " waste=%lu/%lu", 7690 l->count * l->waste, l->waste); 7691 7692 if (l->sum_time != l->min_time) { 7693 seq_printf(seq, " age=%ld/%llu/%ld", 7694 l->min_time, div_u64(l->sum_time, l->count), 7695 l->max_time); 7696 } else 7697 seq_printf(seq, " age=%ld", l->min_time); 7698 7699 if (l->min_pid != l->max_pid) 7700 seq_printf(seq, " pid=%ld-%ld", l->min_pid, l->max_pid); 7701 else 7702 seq_printf(seq, " pid=%ld", 7703 l->min_pid); 7704 7705 if (num_online_cpus() > 1 && !cpumask_empty(to_cpumask(l->cpus))) 7706 seq_printf(seq, " cpus=%*pbl", 7707 cpumask_pr_args(to_cpumask(l->cpus))); 7708 7709 if (nr_online_nodes > 1 && !nodes_empty(l->nodes)) 7710 seq_printf(seq, " nodes=%*pbl", 7711 nodemask_pr_args(&l->nodes)); 7712 7713 #ifdef CONFIG_STACKDEPOT 7714 { 7715 depot_stack_handle_t handle; 7716 unsigned long *entries; 7717 unsigned int nr_entries, j; 7718 7719 handle = READ_ONCE(l->handle); 7720 if (handle) { 7721 nr_entries = stack_depot_fetch(handle, &entries); 7722 seq_puts(seq, "\n"); 7723 for (j = 0; j < nr_entries; j++) 7724 seq_printf(seq, " %pS\n", (void *)entries[j]); 7725 } 7726 } 7727 #endif 7728 seq_puts(seq, "\n"); 7729 } 7730 7731 if (!idx && !t->count) 7732 seq_puts(seq, "No data\n"); 7733 7734 return 0; 7735 } 7736 7737 static void slab_debugfs_stop(struct seq_file *seq, void *v) 7738 { 7739 } 7740 7741 static void *slab_debugfs_next(struct seq_file *seq, void *v, loff_t *ppos) 7742 { 7743 struct loc_track *t = seq->private; 7744 7745 t->idx = ++(*ppos); 7746 if (*ppos <= t->count) 7747 return ppos; 7748 7749 return NULL; 7750 } 7751 7752 static int cmp_loc_by_count(const void *a, const void *b, const void *data) 7753 { 7754 struct location *loc1 = (struct location *)a; 7755 struct location *loc2 = (struct location *)b; 7756 7757 if (loc1->count > loc2->count) 7758 return -1; 7759 else 7760 return 1; 7761 } 7762 7763 static void *slab_debugfs_start(struct seq_file *seq, loff_t *ppos) 7764 { 7765 struct loc_track *t = seq->private; 7766 7767 t->idx = *ppos; 7768 return ppos; 7769 } 7770 7771 static const struct seq_operations slab_debugfs_sops = { 7772 .start = slab_debugfs_start, 7773 .next = slab_debugfs_next, 7774 .stop = slab_debugfs_stop, 7775 .show = slab_debugfs_show, 7776 }; 7777 7778 static int slab_debug_trace_open(struct inode *inode, struct file *filep) 7779 { 7780 7781 struct kmem_cache_node *n; 7782 enum track_item alloc; 7783 int node; 7784 struct loc_track *t = __seq_open_private(filep, &slab_debugfs_sops, 7785 sizeof(struct loc_track)); 7786 struct kmem_cache *s = file_inode(filep)->i_private; 7787 unsigned long *obj_map; 7788 7789 if (!t) 7790 return -ENOMEM; 7791 7792 obj_map = bitmap_alloc(oo_objects(s->oo), GFP_KERNEL); 7793 if (!obj_map) { 7794 seq_release_private(inode, filep); 7795 return -ENOMEM; 7796 } 7797 7798 alloc = debugfs_get_aux_num(filep); 7799 7800 if (!alloc_loc_track(t, PAGE_SIZE / sizeof(struct location), GFP_KERNEL)) { 7801 bitmap_free(obj_map); 7802 seq_release_private(inode, filep); 7803 return -ENOMEM; 7804 } 7805 7806 for_each_kmem_cache_node(s, node, n) { 7807 unsigned long flags; 7808 struct slab *slab; 7809 7810 if (!node_nr_slabs(n)) 7811 continue; 7812 7813 spin_lock_irqsave(&n->list_lock, flags); 7814 list_for_each_entry(slab, &n->partial, slab_list) 7815 process_slab(t, s, slab, alloc, obj_map); 7816 list_for_each_entry(slab, &n->full, slab_list) 7817 process_slab(t, s, slab, alloc, obj_map); 7818 spin_unlock_irqrestore(&n->list_lock, flags); 7819 } 7820 7821 /* Sort locations by count */ 7822 sort_r(t->loc, t->count, sizeof(struct location), 7823 cmp_loc_by_count, NULL, NULL); 7824 7825 bitmap_free(obj_map); 7826 return 0; 7827 } 7828 7829 static int slab_debug_trace_release(struct inode *inode, struct file *file) 7830 { 7831 struct seq_file *seq = file->private_data; 7832 struct loc_track *t = seq->private; 7833 7834 free_loc_track(t); 7835 return seq_release_private(inode, file); 7836 } 7837 7838 static const struct file_operations slab_debugfs_fops = { 7839 .open = slab_debug_trace_open, 7840 .read = seq_read, 7841 .llseek = seq_lseek, 7842 .release = slab_debug_trace_release, 7843 }; 7844 7845 static void debugfs_slab_add(struct kmem_cache *s) 7846 { 7847 struct dentry *slab_cache_dir; 7848 7849 if (unlikely(!slab_debugfs_root)) 7850 return; 7851 7852 slab_cache_dir = debugfs_create_dir(s->name, slab_debugfs_root); 7853 7854 debugfs_create_file_aux_num("alloc_traces", 0400, slab_cache_dir, s, 7855 TRACK_ALLOC, &slab_debugfs_fops); 7856 7857 debugfs_create_file_aux_num("free_traces", 0400, slab_cache_dir, s, 7858 TRACK_FREE, &slab_debugfs_fops); 7859 } 7860 7861 void debugfs_slab_release(struct kmem_cache *s) 7862 { 7863 debugfs_lookup_and_remove(s->name, slab_debugfs_root); 7864 } 7865 7866 static int __init slab_debugfs_init(void) 7867 { 7868 struct kmem_cache *s; 7869 7870 slab_debugfs_root = debugfs_create_dir("slab", NULL); 7871 7872 list_for_each_entry(s, &slab_caches, list) 7873 if (s->flags & SLAB_STORE_USER) 7874 debugfs_slab_add(s); 7875 7876 return 0; 7877 7878 } 7879 __initcall(slab_debugfs_init); 7880 #endif 7881 /* 7882 * The /proc/slabinfo ABI 7883 */ 7884 #ifdef CONFIG_SLUB_DEBUG 7885 void get_slabinfo(struct kmem_cache *s, struct slabinfo *sinfo) 7886 { 7887 unsigned long nr_slabs = 0; 7888 unsigned long nr_objs = 0; 7889 unsigned long nr_free = 0; 7890 int node; 7891 struct kmem_cache_node *n; 7892 7893 for_each_kmem_cache_node(s, node, n) { 7894 nr_slabs += node_nr_slabs(n); 7895 nr_objs += node_nr_objs(n); 7896 nr_free += count_partial_free_approx(n); 7897 } 7898 7899 sinfo->active_objs = nr_objs - nr_free; 7900 sinfo->num_objs = nr_objs; 7901 sinfo->active_slabs = nr_slabs; 7902 sinfo->num_slabs = nr_slabs; 7903 sinfo->objects_per_slab = oo_objects(s->oo); 7904 sinfo->cache_order = oo_order(s->oo); 7905 } 7906 #endif /* CONFIG_SLUB_DEBUG */ 7907