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