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