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