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