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