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