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