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