// SPDX-License-Identifier: GPL-2.0 /* * SLUB: A slab allocator that limits cache line use instead of queuing * objects in per cpu and per node lists. * * The allocator synchronizes using per slab locks or atomic operations * and only uses a centralized lock to manage a pool of partial slabs. * * (C) 2007 SGI, Christoph Lameter * (C) 2011 Linux Foundation, Christoph Lameter
*/
/* * Lock order: * 1. slab_mutex (Global Mutex) * 2. node->list_lock (Spinlock) * 3. kmem_cache->cpu_slab->lock (Local lock) * 4. slab_lock(slab) (Only on some arches) * 5. object_map_lock (Only for debugging) * * slab_mutex * * The role of the slab_mutex is to protect the list of all the slabs * and to synchronize major metadata changes to slab cache structures. * Also synchronizes memory hotplug callbacks. * * slab_lock * * The slab_lock is a wrapper around the page lock, thus it is a bit * spinlock. * * The slab_lock is only used on arches that do not have the ability * to do a cmpxchg_double. It only protects: * * A. slab->freelist -> List of free objects in a slab * B. slab->inuse -> Number of objects in use * C. slab->objects -> Number of objects in slab * D. slab->frozen -> frozen state * * Frozen slabs * * If a slab is frozen then it is exempt from list management. It is * the cpu slab which is actively allocated from by the processor that * froze it and it is not on any list. The processor that froze the * slab is the one who can perform list operations on the slab. Other * processors may put objects onto the freelist but the processor that * froze the slab is the only one that can retrieve the objects from the * slab's freelist. * * CPU partial slabs * * The partially empty slabs cached on the CPU partial list are used * for performance reasons, which speeds up the allocation process. * These slabs are not frozen, but are also exempt from list management, * by clearing the SL_partial flag when moving out of the node * partial list. Please see __slab_free() for more details. * * To sum up, the current scheme is: * - node partial slab: SL_partial && !frozen * - cpu partial slab: !SL_partial && !frozen * - cpu slab: !SL_partial && frozen * - full slab: !SL_partial && !frozen * * list_lock * * The list_lock protects the partial and full list on each node and * the partial slab counter. If taken then no new slabs may be added or * removed from the lists nor make the number of partial slabs be modified. * (Note that the total number of slabs is an atomic value that may be * modified without taking the list lock). * * The list_lock is a centralized lock and thus we avoid taking it as * much as possible. As long as SLUB does not have to handle partial * slabs, operations can continue without any centralized lock. F.e. * allocating a long series of objects that fill up slabs does not require * the list lock. * * For debug caches, all allocations are forced to go through a list_lock * protected region to serialize against concurrent validation. * * cpu_slab->lock local lock * * This locks protect slowpath manipulation of all kmem_cache_cpu fields * except the stat counters. This is a percpu structure manipulated only by * the local cpu, so the lock protects against being preempted or interrupted * by an irq. Fast path operations rely on lockless operations instead. * * On PREEMPT_RT, the local lock neither disables interrupts nor preemption * which means the lockless fastpath cannot be used as it might interfere with * an in-progress slow path operations. In this case the local lock is always * taken but it still utilizes the freelist for the common operations. * * lockless fastpaths * * The fast path allocation (slab_alloc_node()) and freeing (do_slab_free()) * are fully lockless when satisfied from the percpu slab (and when * cmpxchg_double is possible to use, otherwise slab_lock is taken). * They also don't disable preemption or migration or irqs. They rely on * the transaction id (tid) field to detect being preempted or moved to * another cpu. * * irq, preemption, migration considerations * * Interrupts are disabled as part of list_lock or local_lock operations, or * around the slab_lock operation, in order to make the slab allocator safe * to use in the context of an irq. * * In addition, preemption (or migration on PREEMPT_RT) is disabled in the * allocation slowpath, bulk allocation, and put_cpu_partial(), so that the * local cpu doesn't change in the process and e.g. the kmem_cache_cpu pointer * doesn't have to be revalidated in each section protected by the local lock. * * SLUB assigns one slab for allocation to each processor. * Allocations only occur from these slabs called cpu slabs. * * Slabs with free elements are kept on a partial list and during regular * operations no list for full slabs is used. If an object in a full slab is * freed then the slab will show up again on the partial lists. * We track full slabs for debugging purposes though because otherwise we * cannot scan all objects. * * Slabs are freed when they become empty. Teardown and setup is * minimal so we rely on the page allocators per cpu caches for * fast frees and allocs. * * slab->frozen The slab is frozen and exempt from list processing. * This means that the slab is dedicated to a purpose * such as satisfying allocations for a specific * processor. Objects may be freed in the slab while * it is frozen but slab_free will then skip the usual * list operations. It is up to the processor holding * the slab to integrate the slab into the slab lists * when the slab is no longer needed. * * One use of this flag is to mark slabs that are * used for allocations. Then such a slab becomes a cpu * slab. The cpu slab may be equipped with an additional * freelist that allows lockless access to * free objects in addition to the regular freelist * that requires the slab lock. * * SLAB_DEBUG_FLAGS Slab requires special handling due to debug * options set. This moves slab handling out of * the fast path and disables lockless freelists.
*/
/** * enum slab_flags - How the slab flags bits are used. * @SL_locked: Is locked with slab_lock() * @SL_partial: On the per-node partial list * @SL_pfmemalloc: Was allocated from PF_MEMALLOC reserves * * The slab flags share space with the page flags but some bits have * different interpretations. The high bits are used for information * like zone/node/section.
*/ enum slab_flags {
SL_locked = PG_locked,
SL_partial = PG_workingset, /* Historical reasons for this bit */
SL_pfmemalloc = PG_active, /* Historical reasons for this bit */
};
/* * We could simply use migrate_disable()/enable() but as long as it's a * function call even on !PREEMPT_RT, use inline preempt_disable() there.
*/ #ifndef CONFIG_PREEMPT_RT #define slub_get_cpu_ptr(var) get_cpu_ptr(var) #define slub_put_cpu_ptr(var) put_cpu_ptr(var) #define USE_LOCKLESS_FAST_PATH() (true) #else #define slub_get_cpu_ptr(var) \
({ \
migrate_disable(); \
this_cpu_ptr(var); \
}) #define slub_put_cpu_ptr(var) \ do { \
(void)(var); \
migrate_enable(); \
} while (0) #define USE_LOCKLESS_FAST_PATH() (false) #endif
/* * Issues still to be resolved: * * - Support PAGE_ALLOC_DEBUG. Should be easy to do. * * - Variable sizing of the per node arrays
*/
/* Enable to log cmpxchg failures */ #undef SLUB_DEBUG_CMPXCHG
#ifndef CONFIG_SLUB_TINY /* * Minimum number of partial slabs. These will be left on the partial * lists even if they are empty. kmem_cache_shrink may reclaim them.
*/ #define MIN_PARTIAL 5
/* * Maximum number of desirable partial slabs. * The existence of more partial slabs makes kmem_cache_shrink * sort the partial list by the number of objects in use.
*/ #define MAX_PARTIAL 10 #else #define MIN_PARTIAL 0 #define MAX_PARTIAL 0 #endif
/* * These debug flags cannot use CMPXCHG because there might be consistency * issues when checking or reading debug information
*/ #define SLAB_NO_CMPXCHG (SLAB_CONSISTENCY_CHECKS | SLAB_STORE_USER | \
SLAB_TRACE)
/* * Debugging flags that require metadata to be stored in the slab. These get * disabled when slab_debug=O is used and a cache's min order increases with * metadata.
*/ #define DEBUG_METADATA_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER)
#define OO_SHIFT 16 #define OO_MASK ((1 << OO_SHIFT) - 1) #define MAX_OBJS_PER_PAGE 32767 /* since slab.objects is u15 */
/* * Tracking user of a slab.
*/ #define TRACK_ADDRS_COUNT 16 struct track { unsignedlong addr; /* Called from address */ #ifdef CONFIG_STACKDEPOT
depot_stack_handle_t handle; #endif int cpu; /* Was running on cpu */ int pid; /* Pid context */ unsignedlong when; /* When did the operation occur */
};
enum stat_item {
ALLOC_FASTPATH, /* Allocation from cpu slab */
ALLOC_SLOWPATH, /* Allocation by getting a new cpu slab */
FREE_FASTPATH, /* Free to cpu slab */
FREE_SLOWPATH, /* Freeing not to cpu slab */
FREE_FROZEN, /* Freeing to frozen slab */
FREE_ADD_PARTIAL, /* Freeing moves slab to partial list */
FREE_REMOVE_PARTIAL, /* Freeing removes last object */
ALLOC_FROM_PARTIAL, /* Cpu slab acquired from node partial list */
ALLOC_SLAB, /* Cpu slab acquired from page allocator */
ALLOC_REFILL, /* Refill cpu slab from slab freelist */
ALLOC_NODE_MISMATCH, /* Switching cpu slab */
FREE_SLAB, /* Slab freed to the page allocator */
CPUSLAB_FLUSH, /* Abandoning of the cpu slab */
DEACTIVATE_FULL, /* Cpu slab was full when deactivated */
DEACTIVATE_EMPTY, /* Cpu slab was empty when deactivated */
DEACTIVATE_TO_HEAD, /* Cpu slab was moved to the head of partials */
DEACTIVATE_TO_TAIL, /* Cpu slab was moved to the tail of partials */
DEACTIVATE_REMOTE_FREES,/* Slab contained remotely freed objects */
DEACTIVATE_BYPASS, /* Implicit deactivation */
ORDER_FALLBACK, /* Number of times fallback was necessary */
CMPXCHG_DOUBLE_CPU_FAIL,/* Failures of this_cpu_cmpxchg_double */
CMPXCHG_DOUBLE_FAIL, /* Failures of slab freelist update */
CPU_PARTIAL_ALLOC, /* Used cpu partial on alloc */
CPU_PARTIAL_FREE, /* Refill cpu partial on free */
CPU_PARTIAL_NODE, /* Refill cpu partial from node partial */
CPU_PARTIAL_DRAIN, /* Drain cpu partial to node partial */
NR_SLUB_STAT_ITEMS
};
#ifndef CONFIG_SLUB_TINY /* * When changing the layout, make sure freelist and tid are still compatible * with this_cpu_cmpxchg_double() alignment requirements.
*/ struct kmem_cache_cpu { union { struct { void **freelist; /* Pointer to next available object */ unsignedlong tid; /* Globally unique transaction id */
};
freelist_aba_t freelist_tid;
}; struct slab *slab; /* The slab from which we are allocating */ #ifdef CONFIG_SLUB_CPU_PARTIAL struct slab *partial; /* Partially allocated slabs */ #endif
local_lock_t lock; /* Protects the fields above */ #ifdef CONFIG_SLUB_STATS unsignedint stat[NR_SLUB_STAT_ITEMS]; #endif
}; #endif/* CONFIG_SLUB_TINY */
staticinlinevoid stat(conststruct kmem_cache *s, enum stat_item si)
{ #ifdef CONFIG_SLUB_STATS /* * The rmw is racy on a preemptible kernel but this is acceptable, so * avoid this_cpu_add()'s irq-disable overhead.
*/
raw_cpu_inc(s->cpu_slab->stat[si]); #endif
}
/* * Iterator over all nodes. The body will be executed for each node that has * a kmem_cache_node structure allocated (which is true for all online nodes)
*/ #define for_each_kmem_cache_node(__s, __node, __n) \ for (__node = 0; __node < nr_node_ids; __node++) \ if ((__n = get_node(__s, __node)))
/* * Tracks for which NUMA nodes we have kmem_cache_nodes allocated. * Corresponds to node_state[N_MEMORY], but can temporarily * differ during memory hotplug/hotremove operations. * Protected by slab_mutex.
*/ static nodemask_t slab_nodes;
#ifndef CONFIG_SLUB_TINY /* * Workqueue used for flush_cpu_slab().
*/ staticstruct workqueue_struct *flushwq; #endif
/* * Returns freelist pointer (ptr). With hardening, this is obfuscated * with an XOR of the address where the pointer is held and a per-cache * random number.
*/ staticinline freeptr_t freelist_ptr_encode(conststruct kmem_cache *s, void *ptr, unsignedlong ptr_addr)
{ unsignedlong encoded;
/* * When running under KMSAN, get_freepointer_safe() may return an uninitialized * pointer value in the case the current thread loses the race for the next * memory chunk in the freelist. In that case this_cpu_cmpxchg_double() in * slab_alloc_node() will fail, so the uninitialized value won't be used, but * KMSAN will still check all arguments of cmpxchg because of imperfect * handling of inline assembly. * To work around this problem, we apply __no_kmsan_checks to ensure that * get_freepointer_safe() returns initialized memory.
*/
__no_kmsan_checks staticinlinevoid *get_freepointer_safe(struct kmem_cache *s, void *object)
{ unsignedlong freepointer_addr;
freeptr_t p;
if (!debug_pagealloc_enabled_static()) return get_freepointer(s, object);
/* * See comment in calculate_sizes().
*/ staticinlinebool freeptr_outside_object(struct kmem_cache *s)
{ return s->offset >= s->inuse;
}
/* * Return offset of the end of info block which is inuse + free pointer if * not overlapping with object.
*/ staticinlineunsignedint get_info_end(struct kmem_cache *s)
{ if (freeptr_outside_object(s)) return s->inuse + sizeof(void *); else return s->inuse;
}
/* Loop over all objects in a slab */ #define for_each_object(__p, __s, __addr, __objects) \ for (__p = fixup_red_left(__s, __addr); \
__p < (__addr) + (__objects) * (__s)->size; \
__p += (__s)->size)
/* * We take the number of objects but actually limit the number of * slabs on the per cpu partial list, in order to limit excessive * growth of the list. For simplicity we assume that the slabs will * be half-full.
*/
nr_slabs = DIV_ROUND_UP(nr_objects * 2, oo_objects(s->oo));
s->cpu_partial_slabs = nr_slabs;
}
/* * If network-based swap is enabled, slub must keep track of whether memory * were allocated from pfmemalloc reserves.
*/ staticinlinebool slab_test_pfmemalloc(conststruct slab *slab)
{ return test_bit(SL_pfmemalloc, &slab->flags);
}
/* * Interrupts must be disabled (for the fallback code to work right), typically * by an _irqsave() lock variant. On PREEMPT_RT the preempt_disable(), which is * part of bit_spin_lock(), is sufficient because the policy is not to allow any * allocation/ free operation in hardirq context. Therefore nothing can * interrupt the operation.
*/ staticinlinebool __slab_update_freelist(struct kmem_cache *s, struct slab *slab, void *freelist_old, unsignedlong counters_old, void *freelist_new, unsignedlong counters_new, constchar *n)
{ bool ret;
if (USE_LOCKLESS_FAST_PATH())
lockdep_assert_irqs_disabled();
if (s->flags & __CMPXCHG_DOUBLE) {
ret = __update_freelist_fast(slab, freelist_old, counters_old,
freelist_new, counters_new);
} else {
ret = __update_freelist_slow(slab, freelist_old, counters_old,
freelist_new, counters_new);
} if (likely(ret)) returntrue;
/* * kmalloc caches has fixed sizes (mostly power of 2), and kmalloc() API * family will round up the real request size to these fixed ones, so * there could be an extra area than what is requested. Save the original * request size in the meta data area, for better debug and sanity check.
*/ staticinlinevoid set_orig_size(struct kmem_cache *s, void *object, unsignedint orig_size)
{ void *p = kasan_reset_tag(object);
if (!slub_debug_orig_size(s)) return;
p += get_info_end(s);
p += sizeof(struct track) * 2;
/* * slub is about to manipulate internal object metadata. This memory lies * outside the range of the allocated object, so accessing it would normally * be reported by kasan as a bounds error. metadata_access_enable() is used * to tell kasan that these accesses are OK.
*/ staticinlinevoid metadata_access_enable(void)
{
kasan_disable_current();
kmsan_disable_current();
}
/* Verify that a pointer has an address that is valid within a slab page */ staticinlineint check_valid_pointer(struct kmem_cache *s, struct slab *slab, void *object)
{ void *base;
if (!object) return 1;
base = slab_address(slab);
object = kasan_reset_tag(object);
object = restore_red_left(s, object); if (object < base || object >= base + slab->objects * s->size ||
(object - base) % s->size) { return 0;
}
pr_err("Object 0x%p @offset=%tu fp=0x%p\n\n",
p, p - addr, get_freepointer(s, p));
if (s->flags & SLAB_RED_ZONE)
print_section(KERN_ERR, "Redzone ", p - s->red_left_pad,
s->red_left_pad); elseif (p > addr + 16)
print_section(KERN_ERR, "Bytes b4 ", p - 16, 16);
print_section(KERN_ERR, "Object ", p,
min_t(unsignedint, s->object_size, PAGE_SIZE)); if (s->flags & SLAB_RED_ZONE)
print_section(KERN_ERR, "Redzone ", p + s->object_size,
s->inuse - s->object_size);
off = get_info_end(s);
if (s->flags & SLAB_STORE_USER)
off += 2 * sizeof(struct track);
if (slub_debug_orig_size(s))
off += sizeof(unsignedint);
off += kasan_metadata_size(s, false);
if (off != size_from_object(s)) /* Beginning of the filler is the free pointer */
print_section(KERN_ERR, "Padding ", p + off,
size_from_object(s) - off);
}
if (s->flags & SLAB_RED_ZONE) { /* * Here and below, avoid overwriting the KMSAN shadow. Keeping * the shadow makes it possible to distinguish uninit-value * from use-after-free.
*/
memset_no_sanitize_memory(p - s->red_left_pad, val,
s->red_left_pad);
if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) { /* * Redzone the extra allocated space by kmalloc than * requested, and the poison size will be limited to * the original request size accordingly.
*/
poison_size = get_orig_size(s, object);
}
}
/* * Object layout: * * object address * Bytes of the object to be managed. * If the freepointer may overlay the object then the free * pointer is at the middle of the object. * * Poisoning uses 0x6b (POISON_FREE) and the last byte is * 0xa5 (POISON_END) * * object + s->object_size * Padding to reach word boundary. This is also used for Redzoning. * Padding is extended by another word if Redzoning is enabled and * object_size == inuse. * * We fill with 0xbb (SLUB_RED_INACTIVE) for inactive objects and with * 0xcc (SLUB_RED_ACTIVE) for objects in use. * * object + s->inuse * Meta data starts here. * * A. Free pointer (if we cannot overwrite object on free) * B. Tracking data for SLAB_STORE_USER * C. Original request size for kmalloc object (SLAB_STORE_USER enabled) * D. Padding to reach required alignment boundary or at minimum * one word if debugging is on to be able to detect writes * before the word boundary. * * Padding is done using 0x5a (POISON_INUSE) * * object + s->size * Nothing is used beyond s->size. * * If slabcaches are merged then the object_size and inuse boundaries are mostly * ignored. And therefore no slab options that rely on these boundaries * may be used with merged slabcaches.
*/
staticint check_pad_bytes(struct kmem_cache *s, struct slab *slab, u8 *p)
{ unsignedlong off = get_info_end(s); /* The end of info */
if (s->flags & SLAB_STORE_USER) { /* We also have user information there */
off += 2 * sizeof(struct track);
if (s->flags & SLAB_KMALLOC)
off += sizeof(unsignedint);
}
/* Check the pad bytes at the end of a slab page */ static pad_check_attributes void
slab_pad_check(struct kmem_cache *s, struct slab *slab)
{
u8 *start;
u8 *fault;
u8 *end;
u8 *pad; int length; int remainder;
if (!(s->flags & SLAB_POISON)) return;
start = slab_address(slab);
length = slab_size(slab);
end = start + length;
remainder = length % s->size; if (!remainder) return;
pad = end - remainder;
metadata_access_enable();
fault = memchr_inv(kasan_reset_tag(pad), POISON_INUSE, remainder);
metadata_access_disable(); if (!fault) return; while (end > fault && end[-1] == POISON_INUSE)
end--;
if (s->flags & SLAB_RED_ZONE) { if (!check_bytes_and_report(s, slab, object, "Left Redzone",
object - s->red_left_pad, val, s->red_left_pad, ret))
ret = 0;
if (!check_bytes_and_report(s, slab, object, "Right Redzone",
endobject, val, s->inuse - s->object_size, ret))
ret = 0;
if (slub_debug_orig_size(s) && val == SLUB_RED_ACTIVE) {
orig_size = get_orig_size(s, object);
if (s->object_size > orig_size &&
!check_bytes_and_report(s, slab, object, "kmalloc Redzone", p + orig_size,
val, s->object_size - orig_size, ret)) {
ret = 0;
}
}
} else { if ((s->flags & SLAB_POISON) && s->object_size < s->inuse) { if (!check_bytes_and_report(s, slab, p, "Alignment padding",
endobject, POISON_INUSE,
s->inuse - s->object_size, ret))
ret = 0;
}
}
if (s->flags & SLAB_POISON) { if (val != SLUB_RED_ACTIVE && (s->flags & __OBJECT_POISON)) { /* * KASAN can save its free meta data inside of the * object at offset 0. Thus, skip checking the part of * the redzone that overlaps with the meta data.
*/
kasan_meta_size = kasan_metadata_size(s, true); if (kasan_meta_size < s->object_size - 1 &&
!check_bytes_and_report(s, slab, p, "Poison",
p + kasan_meta_size, POISON_FREE,
s->object_size - kasan_meta_size - 1, ret))
ret = 0; if (kasan_meta_size < s->object_size &&
!check_bytes_and_report(s, slab, p, "End Poison",
p + s->object_size - 1, POISON_END, 1, ret))
ret = 0;
} /* * check_pad_bytes cleans up on its own.
*/ if (!check_pad_bytes(s, slab, p))
ret = 0;
}
/* * Cannot check freepointer while object is allocated if * object and freepointer overlap.
*/ if ((freeptr_outside_object(s) || val != SLUB_RED_ACTIVE) &&
!check_valid_pointer(s, slab, get_freepointer(s, p))) {
object_err(s, slab, p, "Freepointer corrupt"); /* * No choice but to zap it and thus lose the remainder * of the free objects in this slab. May cause * another error because the object count is now wrong.
*/
set_freepointer(s, p, NULL);
ret = 0;
}
return ret;
}
staticint check_slab(struct kmem_cache *s, struct slab *slab)
{ int maxobj;
if (!folio_test_slab(slab_folio(slab))) {
slab_err(s, slab, "Not a valid slab page"); return 0;
}
maxobj = order_objects(slab_order(slab), s->size); if (slab->objects > maxobj) {
slab_err(s, slab, "objects %u > max %u",
slab->objects, maxobj); return 0;
} if (slab->inuse > slab->objects) {
slab_err(s, slab, "inuse %u > max %u",
slab->inuse, slab->objects); return 0;
} if (slab->frozen) {
slab_err(s, slab, "Slab disabled since SLUB metadata consistency check failed"); return 0;
}
/* Slab_pad_check fixes things up after itself */
slab_pad_check(s, slab); return 1;
}
/* * Determine if a certain object in a slab is on the freelist. Must hold the * slab lock to guarantee that the chains are in a consistent state.
*/ staticbool on_freelist(struct kmem_cache *s, struct slab *slab, void *search)
{ int nr = 0; void *fp; void *object = NULL; int max_objects;
if (!check_object(s, slab, object, SLUB_RED_INACTIVE)) return 0;
return 1;
}
static noinline bool alloc_debug_processing(struct kmem_cache *s, struct slab *slab, void *object, int orig_size)
{ if (s->flags & SLAB_CONSISTENCY_CHECKS) { if (!alloc_consistency_checks(s, slab, object)) goto bad;
}
/* Success. Perform special debug activities for allocs */
trace(s, slab, object, 1);
set_orig_size(s, object, orig_size);
init_object(s, object, SLUB_RED_ACTIVE); returntrue;
bad: if (folio_test_slab(slab_folio(slab))) { /* * If this is a slab page then lets do the best we can * to avoid issues in the future. Marking all objects * as used avoids touching the remaining objects.
*/
slab_fix(s, "Marking all objects used");
slab->inuse = slab->objects;
slab->freelist = NULL;
slab->frozen = 1; /* mark consistency-failed slab as frozen */
} returnfalse;
}
if (!check_object(s, slab, object, SLUB_RED_ACTIVE)) return 0;
if (unlikely(s != slab->slab_cache)) { if (!folio_test_slab(slab_folio(slab))) {
slab_err(s, slab, "Attempt to free object(0x%p) outside of slab",
object);
} elseif (!slab->slab_cache) {
slab_err(NULL, slab, "No slab cache for object 0x%p",
object);
} else {
object_err(s, slab, object, "page slab pointer corrupt.");
} return 0;
} return 1;
}
/* * Parse a block of slab_debug options. Blocks are delimited by ';' * * @str: start of block * @flags: returns parsed flags, or DEBUG_DEFAULT_FLAGS if none specified * @slabs: return start of list of slabs, or NULL when there's no list * @init: assume this is initial parsing and not per-kmem-create parsing * * returns the start of next block if there's any, or NULL
*/ staticchar *
parse_slub_debug_flags(char *str, slab_flags_t *flags, char **slabs, bool init)
{ bool higher_order_disable = false;
/* Skip any completely empty blocks */ while (*str && *str == ';')
str++;
if (*str == ',') { /* * No options but restriction on slabs. This means full * debugging for slabs matching a pattern.
*/
*flags = DEBUG_DEFAULT_FLAGS; goto check_slabs;
}
*flags = 0;
/* Determine which debug features should be switched on */ for (; *str && *str != ',' && *str != ';'; str++) { switch (tolower(*str)) { case'-':
*flags = 0; break; case'f':
*flags |= SLAB_CONSISTENCY_CHECKS; break; case'z':
*flags |= SLAB_RED_ZONE; break; case'p':
*flags |= SLAB_POISON; break; case'u':
*flags |= SLAB_STORE_USER; break; case't':
*flags |= SLAB_TRACE; break; case'a':
*flags |= SLAB_FAILSLAB; break; case'o': /* * Avoid enabling debugging on caches if its minimum * order would increase as a result.
*/
higher_order_disable = true; break; default: if (init)
pr_err("slab_debug option '%c' unknown. skipped\n", *str);
}
}
check_slabs: if (*str == ',')
*slabs = ++str; else
*slabs = NULL;
/* Skip over the slab list */ while (*str && *str != ';')
str++;
/* Skip any completely empty blocks */ while (*str && *str == ';')
str++;
if (init && higher_order_disable)
disable_higher_order_debug = 1;
/* * For backwards compatibility, a single list of flags with list of * slabs means debugging is only changed for those slabs, so the global * slab_debug should be unchanged (0 or DEBUG_DEFAULT_FLAGS, depending * on CONFIG_SLUB_DEBUG_ON). We can extended that to multiple lists as * long as there is no option specifying flags without a slab list.
*/ if (slab_list_specified) { if (!global_slub_debug_changed)
global_flags = slub_debug;
slub_debug_string = saved_str;
}
out:
slub_debug = global_flags; if (slub_debug & SLAB_STORE_USER)
stack_depot_request_early_init(); if (slub_debug != 0 || slub_debug_string)
static_branch_enable(&slub_debug_enabled); else
static_branch_disable(&slub_debug_enabled); if ((static_branch_unlikely(&init_on_alloc) ||
static_branch_unlikely(&init_on_free)) &&
(slub_debug & SLAB_POISON))
pr_info("mem auto-init: SLAB_POISON will take precedence over init_on_alloc/init_on_free\n"); return 1;
}
/* * kmem_cache_flags - apply debugging options to the cache * @flags: flags to set * @name: name of the cache * * Debug option(s) are applied to @flags. In addition to the debug * option(s), if a slab name (or multiple) is specified i.e. * slab_debug=<Debug-Options>,<slab name1>,<slab name2> ... * then only the select slabs will receive the debug option(s).
*/
slab_flags_t kmem_cache_flags(slab_flags_t flags, constchar *name)
{ char *iter;
size_t len; char *next_block;
slab_flags_t block_flags;
slab_flags_t slub_debug_local = slub_debug;
if (flags & SLAB_NO_USER_FLAGS) return flags;
/* * If the slab cache is for debugging (e.g. kmemleak) then * don't store user (stack trace) information by default, * but let the user enable it via the command line below.
*/ if (flags & SLAB_NOLEAKTRACE)
slub_debug_local &= ~SLAB_STORE_USER;
len = strlen(name);
next_block = slub_debug_string; /* Go through all blocks of debug options, see if any matches our slab's name */ while (next_block) {
next_block = parse_slub_debug_flags(next_block, &block_flags, &iter, false); if (!iter) continue; /* Found a block that has a slab list, search it */ while (*iter) { char *end, *glob;
size_t cmplen;
end = strchrnul(iter, ','); if (next_block && next_block < end)
end = next_block - 1;
staticinlinevoid handle_failed_objexts_alloc(unsignedlong obj_exts, struct slabobj_ext *vec, unsignedint objects)
{ /* * If vector previously failed to allocate then we have live * objects with no tag reference. Mark all references in this * vector as empty to avoid warnings later on.
*/ if (obj_exts & OBJEXTS_ALLOC_FAIL) { unsignedint i;
for (i = 0; i < objects; i++)
set_codetag_empty(&vec[i].ref);
}
}
/* * The allocated objcg pointers array is not accounted directly. * Moreover, it should not come from DMA buffer and is not readily * reclaimable. So those GFP bits should be masked off.
*/ #define OBJCGS_CLEAR_MASK (__GFP_DMA | __GFP_RECLAIMABLE | \
__GFP_ACCOUNT | __GFP_NOFAIL)
gfp &= ~OBJCGS_CLEAR_MASK; /* Prevent recursive extension vector allocation */
gfp |= __GFP_NO_OBJ_EXT;
vec = kcalloc_node(objects, sizeof(struct slabobj_ext), gfp,
slab_nid(slab)); if (!vec) { /* * Try to mark vectors which failed to allocate. * If this operation fails, there may be a racing process * that has already completed the allocation.
*/ if (!mark_failed_objexts_alloc(slab) &&
slab_obj_exts(slab)) return 0;
return -ENOMEM;
}
new_exts = (unsignedlong)vec; #ifdef CONFIG_MEMCG
new_exts |= MEMCG_DATA_OBJEXTS; #endif
retry:
old_exts = READ_ONCE(slab->obj_exts);
handle_failed_objexts_alloc(old_exts, vec, objects); if (new_slab) { /* * If the slab is brand new and nobody can yet access its * obj_exts, no synchronization is required and obj_exts can * be simply assigned.
*/
slab->obj_exts = new_exts;
} elseif (old_exts & ~OBJEXTS_FLAGS_MASK) { /* * If the slab is already in use, somebody can allocate and * assign slabobj_exts in parallel. In this case the existing * objcg vector should be reused.
*/
mark_objexts_empty(vec);
kfree(vec); return 0;
} elseif (cmpxchg(&slab->obj_exts, old_exts, new_exts) != old_exts) { /* Retry if a racing thread changed slab->obj_exts from under us. */ goto retry;
}
obj_exts = slab_obj_exts(slab); if (!obj_exts) { /* * If obj_exts allocation failed, slab->obj_exts is set to * OBJEXTS_ALLOC_FAIL. In this case, we end up here and should * clear the flag.
*/
slab->obj_exts = 0; return;
}
/* * obj_exts was created with __GFP_NO_OBJ_EXT flag, therefore its * corresponding extension will be NULL. alloc_tag_sub() will throw a * warning if slab has extensions but the extension of an object is * NULL, therefore replace NULL with CODETAG_EMPTY to indicate that * the extension for obj_exts is expected to be NULL.
*/
mark_objexts_empty(obj_exts);
kfree(obj_exts);
slab->obj_exts = 0;
}
/* Should be called only if mem_alloc_profiling_enabled() */ static noinline void
__alloc_tagging_slab_alloc_hook(struct kmem_cache *s, void *object, gfp_t flags)
{ struct slabobj_ext *obj_exts;
obj_exts = prepare_slab_obj_exts_hook(s, flags, object); /* * Currently obj_exts is used only for allocation profiling. * If other users appear then mem_alloc_profiling_enabled() * check should be added before alloc_tag_add().
*/ if (likely(obj_exts))
alloc_tag_add(&obj_exts->ref, current->alloc_tag, s->size);
}
/* Should be called only if mem_alloc_profiling_enabled() */ static noinline void
__alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, int objects)
{ struct slabobj_ext *obj_exts; int i;
/* slab->obj_exts might not be NULL if it was created for MEMCG accounting. */ if (s->flags & (SLAB_NO_OBJ_EXT | SLAB_NOLEAKTRACE)) return;
obj_exts = slab_obj_exts(slab); if (!obj_exts) return;
for (i = 0; i < objects; i++) { unsignedint off = obj_to_index(s, slab, p[i]);
alloc_tag_sub(&obj_exts[off].ref, s->size);
}
}
staticinlinevoid
alloc_tagging_slab_free_hook(struct kmem_cache *s, struct slab *slab, void **p, int objects)
{ if (mem_alloc_profiling_enabled())
__alloc_tagging_slab_free_hook(s, slab, p, objects);
}
folio = virt_to_folio(p); if (!folio_test_slab(folio)) { int size;
if (folio_memcg_kmem(folio)) returntrue;
if (__memcg_kmem_charge_page(folio_page(folio, 0), flags,
folio_order(folio))) returnfalse;
/* * This folio has already been accounted in the global stats but * not in the memcg stats. So, subtract from the global and use * the interface which adds to both global and memcg stats.
*/
size = folio_size(folio);
node_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, -size);
lruvec_stat_mod_folio(folio, NR_SLAB_UNRECLAIMABLE_B, size); returntrue;
}
slab = folio_slab(folio);
s = slab->slab_cache;
/* * Ignore KMALLOC_NORMAL cache to avoid possible circular dependency * of slab_obj_exts being allocated from the same slab and thus the slab * becoming effectively unfreeable.
*/ if (is_kmalloc_normal(s)) returntrue;
/* Ignore already charged objects. */
slab_exts = slab_obj_exts(slab); if (slab_exts) {
off = obj_to_index(s, slab, p); if (unlikely(slab_exts[off].objcg)) returntrue;
}
/* * Hooks for other subsystems that check memory allocations. In a typical * production configuration these hooks all should produce no code at all. * * Returns true if freeing of the object can proceed, false if its reuse * was delayed by CONFIG_SLUB_RCU_DEBUG or KASAN quarantine, or it was returned * to KFENCE.
*/ static __always_inline bool slab_free_hook(struct kmem_cache *s, void *x, bool init, bool after_rcu_delay)
{ /* Are the object contents still accessible? */ bool still_accessible = (s->flags & SLAB_TYPESAFE_BY_RCU) && !after_rcu_delay;
if (!(s->flags & SLAB_DEBUG_OBJECTS))
debug_check_no_obj_freed(x, s->object_size);
/* Use KCSAN to help debug racy use-after-free. */ if (!still_accessible)
__kcsan_check_access(x, s->object_size,
KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ASSERT);
if (kfence_free(x)) returnfalse;
/* * Give KASAN a chance to notice an invalid free operation before we * modify the object.
*/ if (kasan_slab_pre_free(s, x)) returnfalse;
#ifdef CONFIG_SLUB_RCU_DEBUG if (still_accessible) { struct rcu_delayed_free *delayed_free;
delayed_free = kmalloc(sizeof(*delayed_free), GFP_NOWAIT); if (delayed_free) { /* * Let KASAN track our call stack as a "related work * creation", just like if the object had been freed * normally via kfree_rcu(). * We have to do this manually because the rcu_head is * not located inside the object.
*/
kasan_record_aux_stack(x);
/* * As memory initialization might be integrated into KASAN, * kasan_slab_free and initialization memset's must be * kept together to avoid discrepancies in behavior. * * The initialization memset's clear the object and the metadata, * but don't touch the SLAB redzone. * * The object's freepointer is also avoided if stored outside the * object.
*/ if (unlikely(init)) { int rsize; unsignedint inuse, orig_size;
if (is_kfence_address(next)) {
slab_free_hook(s, next, false, false); returnfalse;
}
/* Head and tail of the reconstructed freelist */
*head = NULL;
*tail = NULL;
init = slab_want_init_on_free(s);
do {
object = next;
next = get_freepointer(s, object);
/* If object's reuse doesn't have to be delayed */ if (likely(slab_free_hook(s, object, init, false))) { /* Move object to the new freelist */
set_freepointer(s, object, *head);
*head = object; if (!*tail)
*tail = object;
} else { /* * Adjust the reconstructed freelist depth * accordingly if object's reuse is delayed.
*/
--(*cnt);
}
} while (object != old_tail);
/* Get the next entry on the pre-computed freelist randomized */ staticvoid *next_freelist_entry(struct kmem_cache *s, unsignedlong *pos, void *start, unsignedlong page_limit, unsignedlong freelist_count)
{ unsignedint idx;
/* * If the target page allocation failed, the number of objects on the * page might be smaller than the usual size defined by the cache.
*/ do {
idx = s->random_seq[*pos];
*pos += 1; if (*pos >= freelist_count)
*pos = 0;
} while (unlikely(idx >= page_limit));
return (char *)start + idx;
}
/* Shuffle the single linked freelist based on a random pre-computed sequence */ staticbool shuffle_freelist(struct kmem_cache *s, struct slab *slab)
{ void *start; void *cur; void *next; unsignedlong idx, pos, page_limit, freelist_count;
if (slab->objects < 2 || !s->random_seq) returnfalse;
/* First entry is used as the base of the freelist */
cur = next_freelist_entry(s, &pos, start, page_limit, freelist_count);
cur = setup_object(s, cur);
slab->freelist = cur;
for (idx = 1; idx < slab->objects; idx++) {
next = next_freelist_entry(s, &pos, start, page_limit,
freelist_count);
next = setup_object(s, next);
set_freepointer(s, cur, next);
cur = next;
}
set_freepointer(s, cur, NULL);
static __always_inline void unaccount_slab(struct slab *slab, int order, struct kmem_cache *s)
{ /* * The slab object extensions should now be freed regardless of * whether mem_alloc_profiling_enabled() or not because profiling * might have been disabled after slab->obj_exts got allocated.
*/
free_slab_obj_exts(slab);
/* * Let the initial higher-order allocation fail under memory pressure * so we fall-back to the minimum order allocation.
*/
alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL; if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
slab = alloc_slab_page(alloc_gfp, node, oo); if (unlikely(!slab)) {
oo = s->min;
alloc_gfp = flags; /* * Allocation may have failed due to fragmentation. * Try a lower order alloc if possible
*/
slab = alloc_slab_page(alloc_gfp, node, oo); if (unlikely(!slab)) return NULL;
stat(s, ORDER_FALLBACK);
}
/* * Called only for kmem_cache_debug() caches instead of remove_partial(), with a * slab from the n->partial list. Remove only a single object from the slab, do * the alloc_debug_processing() checks and leave the slab on the list, or move * it to full list if it was the last free object.
*/ staticvoid *alloc_single_from_partial(struct kmem_cache *s, struct kmem_cache_node *n, struct slab *slab, int orig_size)
{ void *object;
if (!alloc_debug_processing(s, slab, object, orig_size)) { if (folio_test_slab(slab_folio(slab)))
remove_partial(n, slab); return NULL;
}
if (slab->inuse == slab->objects) {
remove_partial(n, slab);
add_full(s, n, slab);
}
return object;
}
/* * Called only for kmem_cache_debug() caches to allocate from a freshly * allocated slab. Allocate a single object instead of whole freelist * and put the slab to the partial (or full) list.
*/ staticvoid *alloc_single_from_new_slab(struct kmem_cache *s, struct slab *slab, int orig_size)
{ int nid = slab_nid(slab); struct kmem_cache_node *n = get_node(s, nid); unsignedlong flags; void *object;
if (!alloc_debug_processing(s, slab, object, orig_size)) /* * It's not really expected that this would fail on a * freshly allocated slab, but a concurrent memory * corruption in theory could cause that.
*/ return NULL;
spin_lock_irqsave(&n->list_lock, flags);
if (slab->inuse == slab->objects)
add_full(s, n, slab); else
add_partial(n, slab, DEACTIVATE_TO_HEAD);
/* * Try to allocate a partial slab from a specific node.
*/ staticstruct slab *get_partial_node(struct kmem_cache *s, struct kmem_cache_node *n, struct partial_context *pc)
{ struct slab *slab, *slab2, *partial = NULL; unsignedlong flags; unsignedint partial_slabs = 0;
/* * Racy check. If we mistakenly see no partial slabs then we * just allocate an empty slab. If we mistakenly try to get a * partial slab and there is none available then get_partial() * will return NULL.
*/ if (!n || !n->nr_partial) return NULL;
/* * Get a slab from somewhere. Search in increasing NUMA distances.
*/ staticstruct slab *get_any_partial(struct kmem_cache *s, struct partial_context *pc)
{ #ifdef CONFIG_NUMA struct zonelist *zonelist; struct zoneref *z; struct zone *zone; enum zone_type highest_zoneidx = gfp_zone(pc->flags); struct slab *slab; unsignedint cpuset_mems_cookie;
/* * The defrag ratio allows a configuration of the tradeoffs between * inter node defragmentation and node local allocations. A lower * defrag_ratio increases the tendency to do local allocations * instead of attempting to obtain partial slabs from other nodes. * * If the defrag_ratio is set to 0 then kmalloc() always * returns node local objects. If the ratio is higher then kmalloc() * may return off node objects because partial slabs are obtained * from other nodes and filled up. * * If /sys/kernel/slab/xx/remote_node_defrag_ratio is set to 100 * (which makes defrag_ratio = 1000) then every (well almost) * allocation will first attempt to defrag slab caches on other nodes. * This means scanning over all nodes to look for partial slabs which * may be expensive if we do it every time we are trying to find a slab * with available objects.
*/ if (!s->remote_node_defrag_ratio ||
get_cycles() % 1024 > s->remote_node_defrag_ratio) return NULL;
if (n && cpuset_zone_allowed(zone, pc->flags) &&
n->nr_partial > s->min_partial) {
slab = get_partial_node(s, n, pc); if (slab) { /* * Don't check read_mems_allowed_retry() * here - if mems_allowed was updated in * parallel, that was a harmless race * between allocation and the cpuset * update
*/ return slab;
}
}
}
} while (read_mems_allowed_retry(cpuset_mems_cookie)); #endif/* CONFIG_NUMA */ return NULL;
}
/* * Get a partial slab, lock it and return it.
*/ staticstruct slab *get_partial(struct kmem_cache *s, int node, struct partial_context *pc)
{ struct slab *slab; int searchnode = node;
if (node == NUMA_NO_NODE)
searchnode = numa_mem_id();
#ifdef CONFIG_PREEMPTION /* * Calculate the next globally unique transaction for disambiguation * during cmpxchg. The transactions start with the cpu number and are then * incremented by CONFIG_NR_CPUS.
*/ #define TID_STEP roundup_pow_of_two(CONFIG_NR_CPUS) #else /* * No preemption supported therefore also no need to check for * different cpus.
*/ #define TID_STEP 1 #endif/* CONFIG_PREEMPTION */
staticinlineunsignedlong next_tid(unsignedlong tid)
{ return tid + TID_STEP;
}
/* * Finishes removing the cpu slab. Merges cpu's freelist with slab's freelist, * unfreezes the slabs and puts it on the proper list. * Assumes the slab has been already safely taken away from kmem_cache_cpu * by the caller.
*/ staticvoid deactivate_slab(struct kmem_cache *s, struct slab *slab, void *freelist)
{ struct kmem_cache_node *n = get_node(s, slab_nid(slab)); int free_delta = 0; void *nextfree, *freelist_iter, *freelist_tail; int tail = DEACTIVATE_TO_HEAD; unsignedlong flags = 0; struct slab new; struct slab old;
if (READ_ONCE(slab->freelist)) {
stat(s, DEACTIVATE_REMOTE_FREES);
tail = DEACTIVATE_TO_TAIL;
}
/* * Stage one: Count the objects on cpu's freelist as free_delta and * remember the last object in freelist_tail for later splicing.
*/
freelist_tail = NULL;
freelist_iter = freelist; while (freelist_iter) {
nextfree = get_freepointer(s, freelist_iter);
/* * If 'nextfree' is invalid, it is possible that the object at * 'freelist_iter' is already corrupted. So isolate all objects * starting at 'freelist_iter' by skipping them.
*/ if (freelist_corrupted(s, slab, &freelist_iter, nextfree)) break;
freelist_tail = freelist_iter;
free_delta++;
freelist_iter = nextfree;
}
/* * Stage two: Unfreeze the slab while splicing the per-cpu * freelist to the head of slab's freelist.
*/ do {
old.freelist = READ_ONCE(slab->freelist);
old.counters = READ_ONCE(slab->counters);
VM_BUG_ON(!old.frozen);
/* Determine target state of the slab */ new.counters = old.counters; new.frozen = 0; if (freelist_tail) { new.inuse -= free_delta;
set_freepointer(s, freelist_tail, old.freelist); new.freelist = freelist;
} else { new.freelist = old.freelist;
}
} while (!slab_update_freelist(s, slab,
old.freelist, old.counters, new.freelist, new.counters, "unfreezing slab"));
/* * Stage three: Manipulate the slab list based on the updated state.
*/ if (!new.inuse && n->nr_partial >= s->min_partial) {
stat(s, DEACTIVATE_EMPTY);
discard_slab(s, slab);
stat(s, FREE_SLAB);
} elseif (new.freelist) {
spin_lock_irqsave(&n->list_lock, flags);
add_partial(n, slab, tail);
spin_unlock_irqrestore(&n->list_lock, flags);
stat(s, tail);
} else {
stat(s, DEACTIVATE_FULL);
}
}
/* * Put all the cpu partial slabs to the node partial list.
*/ staticvoid put_partials(struct kmem_cache *s)
{ struct slab *partial_slab; unsignedlong flags;
if (partial_slab)
__put_partials(s, partial_slab);
}
/* * Put a slab into a partial slab slot if available. * * If we did not find a slot then simply move all the partials to the * per node partial list.
*/ staticvoid put_cpu_partial(struct kmem_cache *s, struct slab *slab, int drain)
{ struct slab *oldslab; struct slab *slab_to_put = NULL; unsignedlong flags; int slabs = 0;
local_lock_irqsave(&s->cpu_slab->lock, flags);
oldslab = this_cpu_read(s->cpu_slab->partial);
if (oldslab) { if (drain && oldslab->slabs >= s->cpu_partial_slabs) { /* * Partial array is full. Move the existing set to the * per node partial list. Postpone the actual unfreezing * outside of the critical section.
*/
slab_to_put = oldslab;
oldslab = NULL;
} else {
slabs = oldslab->slabs;
}
}
/* * Flush cpu slab. * * Called from CPU work handler with migration disabled.
*/ staticvoid flush_cpu_slab(struct work_struct *w)
{ struct kmem_cache *s; struct kmem_cache_cpu *c; struct slub_flush_work *sfw;
/* * Use the cpu notifier to insure that the cpu slabs are flushed when * necessary.
*/ staticint slub_cpu_dead(unsignedint cpu)
{ struct kmem_cache *s;
/* * Check if the objects in a per cpu structure fit numa * locality expectations.
*/ staticinlineint node_match(struct slab *slab, int node)
{ #ifdef CONFIG_NUMA if (node != NUMA_NO_NODE && slab_nid(slab) != node) return 0; #endif return 1;
}
spin_lock_irqsave(&n->list_lock, flags); if (n->nr_partial <= MAX_PARTIAL_TO_SCAN) {
list_for_each_entry(slab, &n->partial, slab_list)
x += slab->objects - slab->inuse;
} else { /* * For a long list, approximate the total count of objects in * it to meet the limit on the number of slabs to scan. * Scan from both the list's head and tail for better accuracy.
*/ unsignedlong scanned = 0;
list_for_each_entry(slab, &n->partial, slab_list) {
x += slab->objects - slab->inuse; if (++scanned == MAX_PARTIAL_TO_SCAN / 2) break;
}
list_for_each_entry_reverse(slab, &n->partial, slab_list) {
x += slab->objects - slab->inuse; if (++scanned == MAX_PARTIAL_TO_SCAN) break;
}
x = mult_frac(x, n->nr_partial, scanned);
x = min(x, node_nr_objs(n));
}
spin_unlock_irqrestore(&n->list_lock, flags); return x;
}
static noinline void
slab_out_of_memory(struct kmem_cache *s, gfp_t gfpflags, int nid)
{ static DEFINE_RATELIMIT_STATE(slub_oom_rs, DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST); int cpu = raw_smp_processor_id(); int node; struct kmem_cache_node *n;
if ((gfpflags & __GFP_NOWARN) || !__ratelimit(&slub_oom_rs)) return;
pr_warn("SLUB: Unable to allocate memory on CPU %u (of node %d) on node %d, gfp=%#x(%pGg)\n",
cpu, cpu_to_node(cpu), nid, gfpflags, &gfpflags);
pr_warn(" cache: %s, object size: %u, buffer size: %u, default order: %u, min order: %u\n",
s->name, s->object_size, s->size, oo_order(s->oo),
oo_order(s->min));
if (oo_order(s->min) > get_order(s->object_size))
pr_warn(" %s debugging increased min order, use slab_debug=O to disable.\n",
s->name);
/* * Check the slab->freelist and either transfer the freelist to the * per cpu freelist or deactivate the slab. * * The slab is still frozen if the return value is not NULL. * * If this function returns NULL then the slab has been unfrozen.
*/ staticinlinevoid *get_freelist(struct kmem_cache *s, struct slab *slab)
{ struct slab new; unsignedlong counters; void *freelist;
} while (!__slab_update_freelist(s, slab,
freelist, counters,
NULL, new.counters, "get_freelist"));
return freelist;
}
/* * Freeze the partial slab and return the pointer to the freelist.
*/ staticinlinevoid *freeze_slab(struct kmem_cache *s, struct slab *slab)
{ struct slab new; unsignedlong counters; void *freelist;
do {
freelist = slab->freelist;
counters = slab->counters;
new.counters = counters;
VM_BUG_ON(new.frozen);
new.inuse = slab->objects; new.frozen = 1;
} while (!slab_update_freelist(s, slab,
freelist, counters,
NULL, new.counters, "freeze_slab"));
return freelist;
}
/* * Slow path. The lockless freelist is empty or we need to perform * debugging duties. * * Processing is still very fast if new objects have been freed to the * regular freelist. In that case we simply take over the regular freelist * as the lockless freelist and zap the regular freelist. * * If that is not working then we fall back to the partial lists. We take the * first element of the freelist as the object to allocate now and move the * rest of the freelist to the lockless freelist. * * And if we were unable to get a new slab from the partial slab lists then * we need to allocate a new slab. This is the slowest path since it involves * a call to the page allocator and the setup of a new slab. * * Version of __slab_alloc to use when we know that preemption is * already disabled (which is the case for bulk allocation).
*/ staticvoid *___slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, unsignedlong addr, struct kmem_cache_cpu *c, unsignedint orig_size)
{ void *freelist; struct slab *slab; unsignedlong flags; struct partial_context pc; bool try_thisnode = true;
stat(s, ALLOC_SLOWPATH);
reread_slab:
slab = READ_ONCE(c->slab); if (!slab) { /* * if the node is not online or has no normal memory, just * ignore the node constraint
*/ if (unlikely(node != NUMA_NO_NODE &&
!node_isset(node, slab_nodes)))
node = NUMA_NO_NODE; goto new_slab;
}
if (unlikely(!node_match(slab, node))) { /* * same as above but node_match() being false already * implies node != NUMA_NO_NODE
*/ if (!node_isset(node, slab_nodes)) {
node = NUMA_NO_NODE;
} else {
stat(s, ALLOC_NODE_MISMATCH); goto deactivate_slab;
}
}
/* * By rights, we should be searching for a slab page that was * PFMEMALLOC but right now, we are losing the pfmemalloc * information when the page leaves the per-cpu allocator
*/ if (unlikely(!pfmemalloc_match(slab, gfpflags))) goto deactivate_slab;
/* must check again c->slab in case we got preempted and it changed */
local_lock_irqsave(&s->cpu_slab->lock, flags); if (unlikely(slab != c->slab)) {
local_unlock_irqrestore(&s->cpu_slab->lock, flags); goto reread_slab;
}
freelist = c->freelist; if (freelist) goto load_freelist;
/* * freelist is pointing to the list of objects to be used. * slab is pointing to the slab from which the objects are obtained. * That slab must be frozen for per cpu allocations to work.
*/
VM_BUG_ON(!c->slab->frozen);
c->freelist = get_freepointer(s, freelist);
c->tid = next_tid(c->tid);
local_unlock_irqrestore(&s->cpu_slab->lock, flags); return freelist;
#ifdef CONFIG_SLUB_CPU_PARTIAL while (slub_percpu_partial(c)) {
local_lock_irqsave(&s->cpu_slab->lock, flags); if (unlikely(c->slab)) {
local_unlock_irqrestore(&s->cpu_slab->lock, flags); goto reread_slab;
} if (unlikely(!slub_percpu_partial(c))) {
local_unlock_irqrestore(&s->cpu_slab->lock, flags); /* we were preempted and partial list got empty */ goto new_objects;
}
pc.flags = gfpflags; /* * When a preferred node is indicated but no __GFP_THISNODE * * 1) try to get a partial slab from target node only by having * __GFP_THISNODE in pc.flags for get_partial() * 2) if 1) failed, try to allocate a new slab from target node with * GPF_NOWAIT | __GFP_THISNODE opportunistically * 3) if 2) failed, retry with original gfpflags which will allow * get_partial() try partial lists of other nodes before potentially * allocating new page from other nodes
*/ if (unlikely(node != NUMA_NO_NODE && !(gfpflags & __GFP_THISNODE)
&& try_thisnode))
pc.flags = GFP_NOWAIT | __GFP_THISNODE;
pc.orig_size = orig_size;
slab = get_partial(s, node, &pc); if (slab) { if (kmem_cache_debug(s)) {
freelist = pc.object; /* * For debug caches here we had to go through * alloc_single_from_partial() so just store the * tracking info and return the object. * * Due to disabled preemption we need to disallow * blocking. The flags are further adjusted by * gfp_nested_mask() in stack_depot itself.
*/ if (s->flags & SLAB_STORE_USER)
set_track(s, freelist, TRACK_ALLOC, addr,
gfpflags & ~(__GFP_DIRECT_RECLAIM));
/* * No other reference to the slab yet so we can * muck around with it freely without cmpxchg
*/
freelist = slab->freelist;
slab->freelist = NULL;
slab->inuse = slab->objects;
slab->frozen = 1;
inc_slabs_node(s, slab_nid(slab), slab->objects);
if (unlikely(!pfmemalloc_match(slab, gfpflags))) { /* * For !pfmemalloc_match() case we don't load freelist so that * we don't make further mismatched allocations easier.
*/
deactivate_slab(s, slab, get_freepointer(s, freelist)); return freelist;
}
/* * A wrapper for ___slab_alloc() for contexts where preemption is not yet * disabled. Compensates for possible cpu changes by refetching the per cpu area * pointer.
*/ staticvoid *__slab_alloc(struct kmem_cache *s, gfp_t gfpflags, int node, unsignedlong addr, struct kmem_cache_cpu *c, unsignedint orig_size)
{ void *p;
#ifdef CONFIG_PREEMPT_COUNT /* * We may have been preempted and rescheduled on a different * cpu before disabling preemption. Need to reload cpu area * pointer.
*/
c = slub_get_cpu_ptr(s->cpu_slab); #endif
redo: /* * Must read kmem_cache cpu data via this cpu ptr. Preemption is * enabled. We may switch back and forth between cpus while * reading from one cpu area. That does not matter as long * as we end up on the original cpu again when doing the cmpxchg. * * We must guarantee that tid and kmem_cache_cpu are retrieved on the * same cpu. We read first the kmem_cache_cpu pointer and use it to read * the tid. If we are preempted and switched to another cpu between the * two reads, it's OK as the two are still associated with the same cpu * and cmpxchg later will validate the cpu.
*/
c = raw_cpu_ptr(s->cpu_slab);
tid = READ_ONCE(c->tid);
/* * Irqless object alloc/free algorithm used here depends on sequence * of fetching cpu_slab's data. tid should be fetched before anything * on c to guarantee that object and slab associated with previous tid * won't be used with current tid. If we fetch tid first, object and * slab could be one associated with next tid and our alloc/free * request will be failed. In this case, we will retry. So, no problem.
*/
barrier();
/* * The transaction ids are globally unique per cpu and per operation on * a per cpu queue. Thus they can be guarantee that the cmpxchg_double * occurs on the right processor and that there was no operation on the * linked list in between.
*/
object = c->freelist;
slab = c->slab;
#ifdef CONFIG_NUMA if (static_branch_unlikely(&strict_numa) &&
node == NUMA_NO_NODE) {
struct mempolicy *mpol = current->mempolicy;
if (mpol) { /* * Special BIND rule support. If existing slab * is in permitted set then do not redirect * to a particular node. * Otherwise we apply the memory policy to get * the node we need to allocate on.
*/ if (mpol->mode != MPOL_BIND || !slab ||
!node_isset(slab_nid(slab), mpol->nodes))
/* * The cmpxchg will only match if there was no additional * operation and if we are on the right processor. * * The cmpxchg does the following atomically (without lock * semantics!) * 1. Relocate first pointer to the current per cpu area. * 2. Verify that tid and freelist have not been changed * 3. If they were not changed replace tid and freelist * * Since this is without lock semantics the protection is only * against code executing on this cpu *not* from access by * other cpus.
*/ if (unlikely(!__update_cpu_freelist_fast(s, object, next_object, tid))) {
note_cmpxchg_failure("slab_alloc", s, tid); goto redo;
}
prefetch_freepointer(s, next_object);
stat(s, ALLOC_FASTPATH);
}
/* * If the object has been wiped upon free, make sure it's fully initialized by * zeroing out freelist pointer. * * Note that we also wipe custom freelist pointers.
*/ static __always_inline void maybe_wipe_obj_freeptr(struct kmem_cache *s, void *obj)
{ if (unlikely(slab_want_init_on_free(s)) && obj &&
!freeptr_outside_object(s))
memset((void *)((char *)kasan_reset_tag(obj) + s->offset),
0, sizeof(void *));
}
/* * For kmalloc object, the allocated memory size(object_size) is likely * larger than the requested size(orig_size). If redzone check is * enabled for the extra space, don't zero it, as it will be redzoned * soon. The redzone operation for this extra space could be seen as a * replacement of current poisoning under certain debug option, and * won't break other sanity checks.
*/ if (kmem_cache_debug_flags(s, SLAB_STORE_USER | SLAB_RED_ZONE) &&
(s->flags & SLAB_KMALLOC))
zero_size = orig_size;
/* * When slab_debug is enabled, avoid memory initialization integrated * into KASAN and instead zero out the memory via the memset below with * the proper size. Otherwise, KASAN might overwrite SLUB redzones and * cause false-positive reports. This does not lead to a performance * penalty on production builds, as slab_debug is not intended to be * enabled there.
*/ if (__slub_debug_enabled())
kasan_init = false;
/* * As memory initialization might be integrated into KASAN, * kasan_slab_alloc and initialization memset must be * kept together to avoid discrepancies in behavior. * * As p[i] might get tagged, memset and kmemleak hook come after KASAN.
*/ for (i = 0; i < size; i++) {
p[i] = kasan_slab_alloc(s, p[i], init_flags, kasan_init); if (p[i] && init && (!kasan_init ||
!kasan_has_integrated_init()))
memset(p[i], 0, zero_size);
kmemleak_alloc_recursive(p[i], s->object_size, 1,
s->flags, init_flags);
kmsan_slab_alloc(s, p[i], init_flags);
alloc_tagging_slab_alloc_hook(s, p[i], flags);
}
/* * Inlined fastpath so that allocation functions (kmalloc, kmem_cache_alloc) * have the fastpath folded into their functions. So no function call * overhead for requests that can be satisfied on the fastpath. * * The fastpath works by first checking if the lockless freelist can be used. * If not then __slab_alloc is called for slow processing. * * Otherwise we can simply pick the next object from the lockless free list.
*/ static __fastpath_inline void *slab_alloc_node(struct kmem_cache *s, struct list_lru *lru,
gfp_t gfpflags, int node, unsignedlong addr, size_t orig_size)
{ void *object; bool init = false;
s = slab_pre_alloc_hook(s, gfpflags); if (unlikely(!s)) return NULL;
object = kfence_alloc(s, orig_size, gfpflags); if (unlikely(object)) goto out;
out: /* * When init equals 'true', like for kzalloc() family, only * @orig_size bytes might be zeroed instead of s->object_size * In case this fails due to memcg_slab_post_alloc_hook(), * object is set to NULL
*/
slab_post_alloc_hook(s, lru, gfpflags, 1, &object, init, orig_size);
/** * kmem_cache_alloc_node - Allocate an object on the specified node * @s: The cache to allocate from. * @gfpflags: See kmalloc(). * @node: node number of the target node. * * Identical to kmem_cache_alloc but it will allocate memory on the given * node, which can improve the performance for cpu bound structures. * * Fallback to other node is possible if __GFP_THISNODE is not set. * * Return: pointer to the new object or %NULL in case of error
*/ void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int node)
{ void *ret = slab_alloc_node(s, NULL, gfpflags, node, _RET_IP_, s->object_size);
/* * To avoid unnecessary overhead, we pass through large allocation requests * directly to the page allocator. We use __GFP_COMP, because we will need to * know the allocation order to free the pages properly in kfree.
*/ staticvoid *___kmalloc_large_node(size_t size, gfp_t flags, int node)
{ struct folio *folio; void *ptr = NULL; unsignedint order = get_order(size);
if (unlikely(flags & GFP_SLAB_BUG_MASK))
flags = kmalloc_fix_flags(flags);
/* * We cannot use GFP_NOWAIT as there are callsites where waking up * kswapd could deadlock
*/ if (s->flags & SLAB_STORE_USER)
handle = set_track_prepare(__GFP_NOWARN);
/* Perform the actual freeing while we still hold the locks */
slab->inuse -= cnt;
set_freepointer(s, tail, prior);
slab->freelist = head;
/* * If the slab is empty, and node's partial list is full, * it should be discarded anyway no matter it's on full or * partial list.
*/ if (slab->inuse == 0 && n->nr_partial >= s->min_partial)
slab_free = slab;
if (!prior) { /* was on full list */
remove_full(s, n, slab); if (!slab_free) {
add_partial(n, slab, DEACTIVATE_TO_TAIL);
stat(s, FREE_ADD_PARTIAL);
}
} elseif (slab_free) {
remove_partial(n, slab);
stat(s, FREE_REMOVE_PARTIAL);
}
}
if (slab_free) { /* * Update the counters while still holding n->list_lock to * prevent spurious validation warnings
*/
dec_slabs_node(s, slab_nid(slab_free), slab_free->objects);
}
spin_unlock_irqrestore(&n->list_lock, flags);
if (slab_free) {
stat(s, FREE_SLAB);
free_slab(s, slab_free);
}
}
/* * Slow path handling. This may still be called frequently since objects * have a longer lifetime than the cpu slabs in most processing loads. * * So we still attempt to reduce cache line usage. Just take the slab * lock and free the item. If there is no additional partial slab * handling required then we can return immediately.
*/ staticvoid __slab_free(struct kmem_cache *s, struct slab *slab, void *head, void *tail, int cnt, unsignedlong addr)
do { if (unlikely(n)) {
spin_unlock_irqrestore(&n->list_lock, flags);
n = NULL;
}
prior = slab->freelist;
counters = slab->counters;
set_freepointer(s, tail, prior); new.counters = counters;
was_frozen = new.frozen; new.inuse -= cnt; if ((!new.inuse || !prior) && !was_frozen) { /* Needs to be taken off a list */ if (!kmem_cache_has_cpu_partial(s) || prior) {
n = get_node(s, slab_nid(slab)); /* * Speculatively acquire the list_lock. * If the cmpxchg does not succeed then we may * drop the list_lock without any processing. * * Otherwise the list_lock will synchronize with * other processors updating the list of slabs.
*/
spin_lock_irqsave(&n->list_lock, flags);
} while (!slab_update_freelist(s, slab,
prior, counters,
head, new.counters, "__slab_free"));
if (likely(!n)) {
if (likely(was_frozen)) { /* * The list lock was not taken therefore no list * activity can be necessary.
*/
stat(s, FREE_FROZEN);
} elseif (kmem_cache_has_cpu_partial(s) && !prior) { /* * If we started with a full slab then put it onto the * per cpu partial list.
*/
put_cpu_partial(s, slab, 1);
stat(s, CPU_PARTIAL_FREE);
}
return;
}
/* * This slab was partially empty but not on the per-node partial list, * in which case we shouldn't manipulate its list, just return.
*/ if (prior && !on_node_partial) {
spin_unlock_irqrestore(&n->list_lock, flags); return;
}
if (unlikely(!new.inuse && n->nr_partial >= s->min_partial)) goto slab_empty;
/* * Objects left in the slab. If it was not on the partial list before * then add it.
*/ if (!kmem_cache_has_cpu_partial(s) && unlikely(!prior)) {
add_partial(n, slab, DEACTIVATE_TO_TAIL);
stat(s, FREE_ADD_PARTIAL);
}
spin_unlock_irqrestore(&n->list_lock, flags); return;
slab_empty: if (prior) { /* * Slab on the partial list.
*/
remove_partial(n, slab);
stat(s, FREE_REMOVE_PARTIAL);
}
#ifndef CONFIG_SLUB_TINY /* * Fastpath with forced inlining to produce a kfree and kmem_cache_free that * can perform fastpath freeing without additional function calls. * * The fastpath is only possible if we are freeing to the current cpu slab * of this processor. This typically the case if we have just allocated * the item before. * * If fastpath is not possible then fall back to __slab_free where we deal * with all sorts of special processing. * * Bulk free of a freelist with several objects (all pointing to the * same slab) possible by specifying head and tail ptr, plus objects * count (cnt). Bulk free indicated by tail pointer being set.
*/ static __always_inline void do_slab_free(struct kmem_cache *s, struct slab *slab, void *head, void *tail, int cnt, unsignedlong addr)
{ struct kmem_cache_cpu *c; unsignedlong tid; void **freelist;
redo: /* * Determine the currently cpus per cpu slab. * The cpu may change afterward. However that does not matter since * data is retrieved via this pointer. If we are on the same cpu * during the cmpxchg then the free will succeed.
*/
c = raw_cpu_ptr(s->cpu_slab);
tid = READ_ONCE(c->tid);
/* Same with comment on barrier() in __slab_alloc_node() */
barrier();
if (USE_LOCKLESS_FAST_PATH()) {
freelist = READ_ONCE(c->freelist);
set_freepointer(s, tail, freelist);
if (unlikely(!__update_cpu_freelist_fast(s, freelist, head, tid))) {
note_cmpxchg_failure("slab_free", s, tid); goto redo;
}
} else { /* Update the free list under the local lock */
local_lock(&s->cpu_slab->lock);
c = this_cpu_ptr(s->cpu_slab); if (unlikely(slab != c->slab)) {
local_unlock(&s->cpu_slab->lock); goto redo;
}
tid = c->tid;
freelist = c->freelist;
if (!IS_ENABLED(CONFIG_SLAB_FREELIST_HARDENED) &&
!kmem_cache_debug_flags(s, SLAB_CONSISTENCY_CHECKS)) return s;
cachep = virt_to_cache(x); if (WARN(cachep && cachep != s, "%s: Wrong slab cache. %s but object is from %s\n",
__func__, s->name, cachep->name))
print_tracking(cachep, x); return cachep;
}
/** * kmem_cache_free - Deallocate an object * @s: The cache the allocation was from. * @x: The previously allocated object. * * Free an object which was previously allocated from this * cache.
*/ void kmem_cache_free(struct kmem_cache *s, void *x)
{
s = cache_from_obj(s, x); if (!s) return;
trace_kmem_cache_free(_RET_IP_, x, s);
slab_free(s, virt_to_slab(x), x, _RET_IP_);
}
EXPORT_SYMBOL(kmem_cache_free);
/* * Given an rcu_head embedded within an object obtained from kvmalloc at an * offset < 4k, free the object in question.
*/ void kvfree_rcu_cb(struct rcu_head *head)
{ void *obj = head; struct folio *folio; struct slab *slab; struct kmem_cache *s; void *slab_addr;
folio = virt_to_folio(obj); if (!folio_test_slab(folio)) { /* * rcu_head offset can be only less than page size so no need to * consider folio order
*/
obj = (void *) PAGE_ALIGN_DOWN((unsignedlong)obj);
free_large_kmalloc(folio, obj); return;
}
slab = folio_slab(folio);
s = slab->slab_cache;
slab_addr = folio_address(folio);
/* If the old object doesn't fit, allocate a bigger one */ if (new_size > ks) goto alloc_new;
/* Zero out spare memory. */ if (want_init_on_alloc(flags)) {
kasan_disable_current(); if (orig_size && orig_size < new_size)
memset(kasan_reset_tag(p) + orig_size, 0, new_size - orig_size); else
memset(kasan_reset_tag(p) + new_size, 0, ks - new_size);
kasan_enable_current();
}
/* Setup kmalloc redzone when needed */ if (s && slub_debug_orig_size(s)) {
set_orig_size(s, (void *)p, new_size); if (s->flags & SLAB_RED_ZONE && new_size < ks)
memset_no_sanitize_memory(kasan_reset_tag(p) + new_size,
SLUB_RED_ACTIVE, ks - new_size);
}
p = kasan_krealloc(p, new_size, flags); return (void *)p;
alloc_new:
ret = kmalloc_node_track_caller_noprof(new_size, flags, NUMA_NO_NODE, _RET_IP_); if (ret && p) { /* Disable KASAN checks as the object's redzone is accessed. */
kasan_disable_current();
memcpy(ret, kasan_reset_tag(p), orig_size ?: ks);
kasan_enable_current();
}
return ret;
}
/** * krealloc - reallocate memory. The contents will remain unchanged. * @p: object to reallocate memory for. * @new_size: how many bytes of memory are required. * @flags: the type of memory to allocate. * * If @p is %NULL, krealloc() behaves exactly like kmalloc(). If @new_size * is 0 and @p is not a %NULL pointer, the object pointed to is freed. * * If __GFP_ZERO logic is requested, callers must ensure that, starting with the * initial memory allocation, every subsequent call to this API for the same * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that * __GFP_ZERO is not fully honored by this API. * * When slub_debug_orig_size() is off, krealloc() only knows about the bucket * size of an allocation (but not the exact size it was allocated with) and * hence implements the following semantics for shrinking and growing buffers * with __GFP_ZERO:: * * new bucket * 0 size size * |--------|----------------| * | keep | zero | * * Otherwise, the original allocation size 'orig_size' could be used to * precisely clear the requested size, and the new size will also be stored * as the new 'orig_size'. * * In any case, the contents of the object pointed to are preserved up to the * lesser of the new and old sizes. * * Return: pointer to the allocated memory or %NULL in case of error
*/ void *krealloc_noprof(constvoid *p, size_t new_size, gfp_t flags)
{ void *ret;
if (unlikely(!new_size)) {
kfree(p); return ZERO_SIZE_PTR;
}
ret = __do_krealloc(p, new_size, flags); if (ret && kasan_reset_tag(p) != kasan_reset_tag(ret))
kfree(p);
return ret;
}
EXPORT_SYMBOL(krealloc_noprof);
static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
{ /* * We want to attempt a large physically contiguous block first because * it is less likely to fragment multiple larger blocks and therefore * contribute to a long term fragmentation less than vmalloc fallback. * However make sure that larger requests are not too disruptive - i.e. * do not direct reclaim unless physically continuous memory is preferred * (__GFP_RETRY_MAYFAIL mode). We still kick in kswapd/kcompactd to * start working in the background
*/ if (size > PAGE_SIZE) {
flags |= __GFP_NOWARN;
if (!(flags & __GFP_RETRY_MAYFAIL))
flags &= ~__GFP_DIRECT_RECLAIM;
/* nofail semantic is implemented by the vmalloc fallback */
flags &= ~__GFP_NOFAIL;
}
return flags;
}
/** * __kvmalloc_node - attempt to allocate physically contiguous memory, but upon * failure, fall back to non-contiguous (vmalloc) allocation. * @size: size of the request. * @b: which set of kmalloc buckets to allocate from. * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL. * @node: numa node to allocate from * * Uses kmalloc to get the memory but if the allocation fails then falls back * to the vmalloc allocator. Use kvfree for freeing the memory. * * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier. * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is * preferable to the vmalloc fallback, due to visible performance drawbacks. * * Return: pointer to the allocated memory of %NULL in case of failure
*/ void *__kvmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
{ void *ret;
/* * It doesn't really make sense to fallback to vmalloc for sub page * requests
*/
ret = __do_kmalloc_node(size, PASS_BUCKET_PARAM(b),
kmalloc_gfp_adjust(flags, size),
node, _RET_IP_); if (ret || size <= PAGE_SIZE) return ret;
/* non-sleeping allocations are not supported by vmalloc */ if (!gfpflags_allow_blocking(flags)) return NULL;
/* Don't even allow crazy sizes */ if (unlikely(size > INT_MAX)) {
WARN_ON_ONCE(!(flags & __GFP_NOWARN)); return NULL;
}
/* * kvmalloc() can always use VM_ALLOW_HUGE_VMAP, * since the callers already cannot assume anything * about the resulting pointer, and cannot play * protection games.
*/ return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END,
flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
node, __builtin_return_address(0));
}
EXPORT_SYMBOL(__kvmalloc_node_noprof);
/** * kvfree() - Free memory. * @addr: Pointer to allocated memory. * * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc(). * It is slightly more efficient to use kfree() or vfree() if you are certain * that you know which one to use. * * Context: Either preemptible task context or not-NMI interrupt.
*/ void kvfree(constvoid *addr)
{ if (is_vmalloc_addr(addr))
vfree(addr); else
kfree(addr);
}
EXPORT_SYMBOL(kvfree);
/** * kvfree_sensitive - Free a data object containing sensitive information. * @addr: address of the data object to be freed. * @len: length of the data object. * * Use the special memzero_explicit() function to clear the content of a * kvmalloc'ed object containing sensitive data to make sure that the * compiler won't optimize out the data clearing.
*/ void kvfree_sensitive(constvoid *addr, size_t len)
{ if (likely(!ZERO_OR_NULL_PTR(addr))) {
memzero_explicit((void *)addr, len);
kvfree(addr);
}
}
EXPORT_SYMBOL(kvfree_sensitive);
/** * kvrealloc - reallocate memory; contents remain unchanged * @p: object to reallocate memory for * @size: the size to reallocate * @flags: the flags for the page level allocator * * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0 * and @p is not a %NULL pointer, the object pointed to is freed. * * If __GFP_ZERO logic is requested, callers must ensure that, starting with the * initial memory allocation, every subsequent call to this API for the same * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that * __GFP_ZERO is not fully honored by this API. * * In any case, the contents of the object pointed to are preserved up to the * lesser of the new and old sizes. * * This function must not be called concurrently with itself or kvfree() for the * same memory allocation. * * Return: pointer to the allocated memory or %NULL in case of error
*/ void *kvrealloc_noprof(constvoid *p, size_t size, gfp_t flags)
{ void *n;
if (is_vmalloc_addr(p)) return vrealloc_noprof(p, size, flags);
n = krealloc_noprof(p, size, kmalloc_gfp_adjust(flags, size)); if (!n) { /* We failed to krealloc(), fall back to kvmalloc(). */
n = kvmalloc_noprof(size, flags); if (!n) return NULL;
if (p) { /* We already know that `p` is not a vmalloc address. */
kasan_disable_current();
memcpy(n, kasan_reset_tag(p), ksize(p));
kasan_enable_current();
/* * This function progressively scans the array with free objects (with * a limited look ahead) and extract objects belonging to the same * slab. It builds a detached freelist directly within the given * slab/objects. This can happen without any need for * synchronization, because the objects are owned by running process. * The freelist is build up as a single linked list in the objects. * The idea is, that this detached freelist can then be bulk * transferred to the real freelist(s), but only requiring a single * synchronization primitive. Look ahead in the array is limited due * to performance reasons.
*/ staticinline int build_detached_freelist(struct kmem_cache *s, size_t size, void **p, struct detached_freelist *df)
{ int lookahead = 3; void *object; struct folio *folio;
size_t same;
same = size; while (size) {
object = p[--size]; /* df->slab is always set at this point */ if (df->slab == virt_to_slab(object)) { /* Opportunity build freelist */
set_freepointer(df->s, object, df->freelist);
df->freelist = object;
df->cnt++;
same--; if (size != same)
swap(p[size], p[same]); continue;
}
/* Limit look ahead search */ if (!--lookahead) break;
}
return same;
}
/* * Internal bulk free of objects that were not initialised by the post alloc * hooks and thus should not be processed by the free hooks
*/ staticvoid __kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
{ if (!size) return;
do { struct detached_freelist df;
size = build_detached_freelist(s, size, p, &df); if (!df.slab) continue;
if (kfence_free(df.freelist)) continue;
do_slab_free(df.s, df.slab, df.freelist, df.tail, df.cnt,
_RET_IP_);
} while (likely(size));
}
/* Note that interrupts must be enabled when calling this function. */ void kmem_cache_free_bulk(struct kmem_cache *s, size_t size, void **p)
{ if (!size) return;
do { struct detached_freelist df;
size = build_detached_freelist(s, size, p, &df); if (!df.slab) continue;
/* * Drain objects in the per cpu slab, while disabling local * IRQs, which protects against PREEMPT and interrupts * handlers invoking normal fastpath.
*/
c = slub_get_cpu_ptr(s->cpu_slab);
local_lock_irqsave(&s->cpu_slab->lock, irqflags);
for (i = 0; i < size; i++) { void *object = kfence_alloc(s, s->object_size, flags);
if (unlikely(object)) {
p[i] = object; continue;
}
object = c->freelist; if (unlikely(!object)) { /* * We may have removed an object from c->freelist using * the fastpath in the previous iteration; in that case, * c->tid has not been bumped yet. * Since ___slab_alloc() may reenable interrupts while * allocating memory, we should bump c->tid now.
*/
c->tid = next_tid(c->tid);
error:
__kmem_cache_free_bulk(s, i, p); return 0;
} #endif/* CONFIG_SLUB_TINY */
/* Note that interrupts must be enabled when calling this function. */ int kmem_cache_alloc_bulk_noprof(struct kmem_cache *s, gfp_t flags, size_t size, void **p)
{ int i;
if (!size) return 0;
s = slab_pre_alloc_hook(s, flags); if (unlikely(!s)) return 0;
i = __kmem_cache_alloc_bulk(s, flags, size, p); if (unlikely(i == 0)) return 0;
/* * memcg and kmem_cache debug support and memory initialization. * Done outside of the IRQ disabled fastpath loop.
*/ if (unlikely(!slab_post_alloc_hook(s, NULL, flags, size, p,
slab_want_init_on_alloc(flags, s), s->object_size))) { return 0;
} return i;
}
EXPORT_SYMBOL(kmem_cache_alloc_bulk_noprof);
/* * Object placement in a slab is made very easy because we always start at * offset 0. If we tune the size of the object to the alignment then we can * get the required alignment by putting one properly sized object after * another. * * Notice that the allocation order determines the sizes of the per cpu * caches. Each processor has always one slab available for allocations. * Increasing the allocation order reduces the number of times that slabs * must be moved on and off the partial lists and is therefore a factor in * locking overhead.
*/
/* * Minimum / Maximum order of slab pages. This influences locking overhead * and slab fragmentation. A higher order reduces the number of partial slabs * and increases the number of allocations possible without having to * take the list_lock.
*/ staticunsignedint slub_min_order; staticunsignedint slub_max_order =
IS_ENABLED(CONFIG_SLUB_TINY) ? 1 : PAGE_ALLOC_COSTLY_ORDER; staticunsignedint slub_min_objects;
/* * Calculate the order of allocation given an slab object size. * * The order of allocation has significant impact on performance and other * system components. Generally order 0 allocations should be preferred since * order 0 does not cause fragmentation in the page allocator. Larger objects * be problematic to put into order 0 slabs because there may be too much * unused space left. We go to a higher order if more than 1/16th of the slab * would be wasted. * * In order to reach satisfactory performance we must ensure that a minimum * number of objects is in one slab. Otherwise we may generate too much * activity on the partial lists which requires taking the list_lock. This is * less a concern for large slabs though which are rarely used. * * slab_max_order specifies the order where we begin to stop considering the * number of objects in a slab as critical. If we reach slab_max_order then * we try to keep the page order as low as possible. So we accept more waste * of space in favor of a small page order. * * Higher order allocations also allow the placement of more objects in a * slab and thereby reduce object handling overhead. If the user has * requested a higher minimum order then we start with that one instead of * the smallest order which will fit the object.
*/ staticinlineunsignedint calc_slab_order(unsignedint size, unsignedint min_order, unsignedint max_order, unsignedint fract_leftover)
{ unsignedint order;
for (order = min_order; order <= max_order; order++) {
min_objects = slub_min_objects; if (!min_objects) { /* * Some architectures will only update present cpus when * onlining them, so don't trust the number if it's just 1. But * we also don't want to use nr_cpu_ids always, as on some other * architectures, there can be many possible cpus, but never * onlined. Here we compromise between trying to avoid too high * order on systems that appear larger than they are, and too * low order on systems that appear smaller than they are.
*/ unsignedint nr_cpus = num_present_cpus(); if (nr_cpus <= 1)
nr_cpus = nr_cpu_ids;
min_objects = 4 * (fls(nr_cpus) + 1);
} /* min_objects can't be 0 because get_order(0) is undefined */
max_objects = max(order_objects(slub_max_order, size), 1U);
min_objects = min(min_objects, max_objects);
/* * Attempt to find best configuration for a slab. This works by first * attempting to generate a layout with the best possible configuration * and backing off gradually. * * We start with accepting at most 1/16 waste and try to find the * smallest order from min_objects-derived/slab_min_order up to * slab_max_order that will satisfy the constraint. Note that increasing * the order can only result in same or less fractional waste, not more. * * If that fails, we increase the acceptable fraction of waste and try * again. The last iteration with fraction of 1/2 would effectively * accept any waste and give us the order determined by min_objects, as * long as at least single object fits within slab_max_order.
*/ for (unsignedint fraction = 16; fraction > 1; fraction /= 2) {
order = calc_slab_order(size, min_order, slub_max_order,
fraction); if (order <= slub_max_order) return order;
}
/* * Doh this slab cannot be placed using slab_max_order.
*/
order = get_order(size); if (order <= MAX_PAGE_ORDER) return order; return -ENOSYS;
}
/* * Must align to double word boundary for the double cmpxchg * instructions to work; see __pcpu_double_call_return_bool().
*/
s->cpu_slab = __alloc_percpu(sizeof(struct kmem_cache_cpu),
2 * sizeof(void *));
/* * No kmalloc_node yet so do it by hand. We know that this is the first * slab on the node for this slabcache. There are no concurrent accesses * possible. * * Note that this function only works on the kmem_cache_node * when allocating for the kmem_cache_node. This is used for bootstrapping * memory on a fresh node that has no slab structures yet.
*/ staticvoid early_kmem_cache_node_alloc(int node)
{ struct slab *slab; struct kmem_cache_node *n;
BUG_ON(!slab); if (slab_nid(slab) != node) {
pr_err("SLUB: Unable to allocate memory from node %d\n", node);
pr_err("SLUB: Allocating a useless per node structure in order to be able to continue\n");
}
n = slab->freelist;
BUG_ON(!n); #ifdef CONFIG_SLUB_DEBUG
init_object(kmem_cache_node, n, SLUB_RED_ACTIVE); #endif
n = kasan_slab_alloc(kmem_cache_node, n, GFP_KERNEL, false);
slab->freelist = get_freepointer(kmem_cache_node, n);
slab->inuse = 1;
kmem_cache_node->node[node] = n;
init_kmem_cache_node(n);
inc_slabs_node(kmem_cache_node, node, slab->objects);
/* * No locks need to be taken here as it has just been * initialized and there is no concurrent access.
*/
__add_partial(n, slab, DEACTIVATE_TO_HEAD);
}
staticvoid free_kmem_cache_nodes(struct kmem_cache *s)
{ int node; struct kmem_cache_node *n;
/* * cpu_partial determined the maximum number of objects kept in the * per cpu partial lists of a processor. * * Per cpu partial lists mainly contain slabs that just have one * object freed. If they are used for allocation then they can be * filled up again with minimal effort. The slab will never hit the * per node partial lists and therefore no locking will be required. * * For backwards compatibility reasons, this is determined as number * of objects, even though we now limit maximum number of pages, see * slub_set_cpu_partial()
*/ if (!kmem_cache_has_cpu_partial(s))
nr_objects = 0; elseif (s->size >= PAGE_SIZE)
nr_objects = 6; elseif (s->size >= 1024)
nr_objects = 24; elseif (s->size >= 256)
nr_objects = 52; else
nr_objects = 120;
slub_set_cpu_partial(s, nr_objects); #endif
}
/* * calculate_sizes() determines the order and the distribution of data within * a slab object.
*/ staticint calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
{
slab_flags_t flags = s->flags; unsignedint size = s->object_size; unsignedint order;
/* * Round up object size to the next word boundary. We can only * place the free pointer at word boundaries and this determines * the possible location of the free pointer.
*/
size = ALIGN(size, sizeof(void *));
#ifdef CONFIG_SLUB_DEBUG /* * Determine if we can poison the object itself. If the user of * the slab may touch the object after free or before allocation * then we should never poison the object itself.
*/ if ((flags & SLAB_POISON) && !(flags & SLAB_TYPESAFE_BY_RCU) &&
!s->ctor)
s->flags |= __OBJECT_POISON; else
s->flags &= ~__OBJECT_POISON;
/* * If we are Redzoning then check if there is some space between the * end of the object and the free pointer. If not then add an * additional word to have some bytes to store Redzone information.
*/ if ((flags & SLAB_RED_ZONE) && size == s->object_size)
size += sizeof(void *); #endif
/* * With that we have determined the number of bytes in actual use * by the object and redzoning.
*/
s->inuse = size;
if (((flags & SLAB_TYPESAFE_BY_RCU) && !args->use_freeptr_offset) ||
(flags & SLAB_POISON) || s->ctor ||
((flags & SLAB_RED_ZONE) &&
(s->object_size < sizeof(void *) || slub_debug_orig_size(s)))) { /* * Relocate free pointer after the object if it is not * permitted to overwrite the first word of the object on * kmem_cache_free. * * This is the case if we do RCU, have a constructor or * destructor, are poisoning the objects, or are * redzoning an object smaller than sizeof(void *) or are * redzoning an object with slub_debug_orig_size() enabled, * in which case the right redzone may be extended. * * The assumption that s->offset >= s->inuse means free * pointer is outside of the object is used in the * freeptr_outside_object() function. If that is no * longer true, the function needs to be modified.
*/
s->offset = size;
size += sizeof(void *);
} elseif ((flags & SLAB_TYPESAFE_BY_RCU) && args->use_freeptr_offset) {
s->offset = args->freeptr_offset;
} else { /* * Store freelist pointer near middle of object to keep * it away from the edges of the object to avoid small * sized over/underflows from neighboring allocations.
*/
s->offset = ALIGN_DOWN(s->object_size / 2, sizeof(void *));
}
#ifdef CONFIG_SLUB_DEBUG if (flags & SLAB_STORE_USER) { /* * Need to store information about allocs and frees after * the object.
*/
size += 2 * sizeof(struct track);
/* Save the original kmalloc request size */ if (flags & SLAB_KMALLOC)
size += sizeof(unsignedint);
} #endif
kasan_cache_create(s, &size, &s->flags); #ifdef CONFIG_SLUB_DEBUG if (flags & SLAB_RED_ZONE) { /* * Add some empty padding so that we can catch * overwrites from earlier objects rather than let * tracking information or the free pointer be * corrupted if a user writes before the start * of the object.
*/
size += sizeof(void *);
/* * SLUB stores one object immediately after another beginning from * offset 0. In order to align the objects we have to simply size * each object to conform to the alignment.
*/
size = ALIGN(size, s->align);
s->size = size;
s->reciprocal_size = reciprocal_value(size);
order = calculate_order(size);
if ((int)order < 0) return 0;
s->allocflags = __GFP_COMP;
if (s->flags & SLAB_CACHE_DMA)
s->allocflags |= GFP_DMA;
if (s->flags & SLAB_CACHE_DMA32)
s->allocflags |= GFP_DMA32;
if (s->flags & SLAB_RECLAIM_ACCOUNT)
s->allocflags |= __GFP_RECLAIMABLE;
/* * Determine the number of objects per slab
*/
s->oo = oo_make(order, size);
s->min = oo_make(get_order(size), size);
if (!test_bit(__obj_to_index(s, addr, p), object_map)) { if (slab_add_kunit_errors()) continue;
pr_err("Object 0x%p @offset=%tu\n", p, p - addr);
print_tracking(s, p);
}
}
spin_unlock(&object_map_lock);
__slab_err(slab); #endif
}
/* * Attempt to free all partial slabs on a node. * This is called from __kmem_cache_shutdown(). We must take list_lock * because sysfs file might still access partial list after the shutdowning.
*/ staticvoid free_partial(struct kmem_cache *s, struct kmem_cache_node *n)
{
LIST_HEAD(discard); struct slab *slab, *h;
#ifdef CONFIG_NUMA staticint __init setup_slab_strict_numa(char *str)
{ if (nr_node_ids > 1) {
static_branch_enable(&strict_numa);
pr_info("SLUB: Strict NUMA enabled.\n");
} else {
pr_warn("slab_strict_numa parameter set on non NUMA system.\n");
}
#ifdef CONFIG_HARDENED_USERCOPY /* * Rejects incorrectly sized objects and objects that are to be copied * to/from userspace but do not fall entirely within the containing slab * cache's usercopy region. * * Returns NULL if check passes, otherwise const char * to name of cache * to indicate an error.
*/ void __check_heap_object(constvoid *ptr, unsignedlong n, conststruct slab *slab, bool to_user)
{ struct kmem_cache *s; unsignedint offset; bool is_kfence = is_kfence_address(ptr);
ptr = kasan_reset_tag(ptr);
/* Find object and usable object size. */
s = slab->slab_cache;
/* Reject impossible pointers. */ if (ptr < slab_address(slab))
usercopy_abort("SLUB object not in SLUB page?!", NULL,
to_user, 0, n);
/* Adjust for redzone and reject if within the redzone. */ if (!is_kfence && kmem_cache_debug_flags(s, SLAB_RED_ZONE)) { if (offset < s->red_left_pad)
usercopy_abort("SLUB object in left red zone",
s->name, to_user, offset, n);
offset -= s->red_left_pad;
}
/* Allow address range falling entirely within usercopy region. */ if (offset >= s->useroffset &&
offset - s->useroffset <= s->usersize &&
n <= s->useroffset - offset + s->usersize) return;
/* * kmem_cache_shrink discards empty slabs and promotes the slabs filled * up most to the head of the partial lists. New allocations will then * fill those up and thus they can be removed from the partial lists. * * The slabs with the least items are placed last. This results in them * being allocated from last increasing the chance that the last objects * are freed in them.
*/ staticint __kmem_cache_do_shrink(struct kmem_cache *s)
{ int node; int i; struct kmem_cache_node *n; struct slab *slab; struct slab *t; struct list_head discard; struct list_head promote[SHRINK_PROMOTE_MAX]; unsignedlong flags; int ret = 0;
for_each_kmem_cache_node(s, node, n) {
INIT_LIST_HEAD(&discard); for (i = 0; i < SHRINK_PROMOTE_MAX; i++)
INIT_LIST_HEAD(promote + i);
spin_lock_irqsave(&n->list_lock, flags);
/* * Build lists of slabs to discard or promote. * * Note that concurrent frees may occur while we hold the * list_lock. slab->inuse here is the upper limit.
*/
list_for_each_entry_safe(slab, t, &n->partial, slab_list) { int free = slab->objects - slab->inuse;
/* Do not reread slab->inuse */
barrier();
/* We do not keep full slabs on the list */
BUG_ON(free <= 0);
/* * Promote the slabs filled up most to the head of the * partial list.
*/ for (i = SHRINK_PROMOTE_MAX - 1; i >= 0; i--)
list_splice(promote + i, &n->partial);
staticint slab_mem_going_online_callback(int nid)
{ struct kmem_cache_node *n; struct kmem_cache *s; int ret = 0;
/* * We are bringing a node online. No memory is available yet. We must * allocate a kmem_cache_node structure in order to bring the node * online.
*/
mutex_lock(&slab_mutex);
list_for_each_entry(s, &slab_caches, list) { /* * The structure may already exist if the node was previously * onlined and offlined.
*/ if (get_node(s, nid)) continue; /* * XXX: kmem_cache_alloc_node will fallback to other nodes * since memory is not yet available from the node that * is brought up.
*/
n = kmem_cache_alloc(kmem_cache_node, GFP_KERNEL); if (!n) {
ret = -ENOMEM; goto out;
}
init_kmem_cache_node(n);
s->node[nid] = n;
} /* * Any cache created after this point will also have kmem_cache_node * initialized for the new node.
*/
node_set(nid, slab_nodes);
out:
mutex_unlock(&slab_mutex); return ret;
}
staticint slab_memory_callback(struct notifier_block *self, unsignedlong action, void *arg)
{ struct node_notify *nn = arg; int nid = nn->nid; int ret = 0;
switch (action) { case NODE_ADDING_FIRST_MEMORY:
ret = slab_mem_going_online_callback(nid); break; case NODE_REMOVING_LAST_MEMORY:
ret = slab_mem_going_offline_callback(); break;
} if (ret)
ret = notifier_from_errno(ret); else
ret = NOTIFY_OK; return ret;
}
/******************************************************************** * Basic setup of slabs
*******************************************************************/
/* * Used for early kmem_cache structures that were allocated using * the page allocator. Allocate them properly then fix up the pointers * that may be pointing to the wrong kmem_cache structure.
*/
/* * This runs very early, and only the boot processor is supposed to be * up. Even if it weren't true, IRQs are not up so we couldn't fire * IPIs around.
*/
__flush_cpu_slab(s, smp_processor_id());
for_each_kmem_cache_node(s, node, n) { struct slab *p;
/* * Initialize the nodemask for which we will allocate per node * structures. Here we don't need taking slab_mutex yet.
*/
for_each_node_state(node, N_MEMORY)
node_set(node, slab_nodes);
s = find_mergeable(size, align, flags, name, ctor); if (s) { if (sysfs_slab_alias(s, name))
pr_err("SLUB: Unable to add cache alias %s to sysfs\n",
name);
s->refcount++;
/* * Adjust the object sizes so that we clear * the complete object on kzalloc.
*/
s->object_size = max(s->object_size, size);
s->inuse = max(s->inuse, ALIGN(size, sizeof(void *)));
}
return s;
}
int do_kmem_cache_create(struct kmem_cache *s, constchar *name, unsignedint size, struct kmem_cache_args *args,
slab_flags_t flags)
{ int err = -EINVAL;
if (!calculate_sizes(args, s)) goto out; if (disable_higher_order_debug) { /* * Disable debugging flags that store metadata if the min slab * order increased.
*/ if (get_order(s->size) > get_order(s->object_size)) {
s->flags &= ~DEBUG_METADATA_FLAGS;
s->offset = 0; if (!calculate_sizes(args, s)) goto out;
}
}
#ifdef system_has_freelist_aba if (system_has_freelist_aba() && !(s->flags & SLAB_NO_CMPXCHG)) { /* Enable fast mode */
s->flags |= __CMPXCHG_DOUBLE;
} #endif
/* * The larger the object size is, the more slabs we want on the partial * list to avoid pounding the page allocator excessively.
*/
s->min_partial = min_t(unsignedlong, MAX_PARTIAL, ilog2(s->size) / 2);
s->min_partial = max_t(unsignedlong, MIN_PARTIAL, s->min_partial);
/* Initialize the pre-computed randomized freelist if slab is up */ if (slab_state >= UP) { if (init_cache_random_seq(s)) goto out;
}
if (!init_kmem_cache_nodes(s)) goto out;
if (!alloc_kmem_cache_cpus(s)) goto out;
err = 0;
/* Mutex is not taken during early boot */ if (slab_state <= UP) goto out;
/* * Failing to create sysfs files is not critical to SLUB functionality. * If it fails, proceed with cache creation without these files.
*/ if (sysfs_slab_add(s))
pr_err("SLUB: Unable to add cache %s to sysfs\n", s->name);
if (s->flags & SLAB_STORE_USER)
debugfs_slab_add(s);
out: if (err)
__kmem_cache_release(s); return err;
}
static ssize_t show_slab_objects(struct kmem_cache *s, char *buf, unsignedlong flags)
{ unsignedlong total = 0; int node; int x; unsignedlong *nodes; int len = 0;
nodes = kcalloc(nr_node_ids, sizeof(unsignedlong), GFP_KERNEL); if (!nodes) return -ENOMEM;
node = slab_nid(slab); if (flags & SO_TOTAL)
x = slab->objects; elseif (flags & SO_OBJECTS)
x = slab->inuse; else
x = 1;
total += x;
nodes[node] += x;
#ifdef CONFIG_SLUB_CPU_PARTIAL
slab = slub_percpu_partial_read_once(c); if (slab) {
node = slab_nid(slab); if (flags & SO_TOTAL)
WARN_ON_ONCE(1); elseif (flags & SO_OBJECTS)
WARN_ON_ONCE(1); else
x = data_race(slab->slabs);
total += x;
nodes[node] += x;
} #endif
}
}
/* * It is impossible to take "mem_hotplug_lock" here with "kernfs_mutex" * already held which will conflict with an existing lock order: * * mem_hotplug_lock->slab_mutex->kernfs_mutex * * We don't really need mem_hotplug_lock (to hold off * slab_mem_going_offline_callback) here because slab's memory hot * unplug code doesn't destroy the kmem_cache->node[] data.
*/
#ifdef CONFIG_SLUB_DEBUG if (flags & SO_ALL) { struct kmem_cache_node *n;
for_each_kmem_cache_node(s, node, n) {
if (flags & SO_TOTAL)
x = node_nr_objs(n); elseif (flags & SO_OBJECTS)
x = node_nr_objs(n) - count_partial(n, count_free); else
x = node_nr_slabs(n);
total += x;
nodes[node] += x;
}
/* Create a unique string id for a slab cache: * * Format :[flags-]size
*/ staticchar *create_unique_id(struct kmem_cache *s)
{ char *name = kmalloc(ID_STR_LENGTH, GFP_KERNEL); char *p = name;
if (!name) return ERR_PTR(-ENOMEM);
*p++ = ':'; /* * First flags affecting slabcache operations. We will only * get here for aliasable slabs so we do not need to support * too many flags. The flags here must cover all flags that * are matched during merging to guarantee that the id is * unique.
*/ if (s->flags & SLAB_CACHE_DMA)
*p++ = 'd'; if (s->flags & SLAB_CACHE_DMA32)
*p++ = 'D'; if (s->flags & SLAB_RECLAIM_ACCOUNT)
*p++ = 'a'; if (s->flags & SLAB_CONSISTENCY_CHECKS)
*p++ = 'F'; if (s->flags & SLAB_ACCOUNT)
*p++ = 'A'; if (p != name + 1)
*p++ = '-';
p += snprintf(p, ID_STR_LENGTH - (p - name), "%07u", s->size);
if (WARN_ON(p > name + ID_STR_LENGTH - 1)) {
kfree(name); return ERR_PTR(-EINVAL);
}
kmsan_unpoison_memory(name, p - name); return name;
}
staticint sysfs_slab_add(struct kmem_cache *s)
{ int err; constchar *name; struct kset *kset = cache_kset(s); int unmergeable = slab_unmergeable(s);
if (unmergeable) { /* * Slabcache can never be merged so we can use the name proper. * This is typically the case for debug situations. In that * case we can catch duplicate names easily.
*/
sysfs_remove_link(&slab_kset->kobj, s->name);
name = s->name;
} else { /* * Create a unique name for the slab as a target * for the symlinks.
*/
name = create_unique_id(s); if (IS_ERR(name)) return PTR_ERR(name);
}
/* * Need to buffer aliases during bootup until sysfs becomes * available lest we lose that information.
*/ struct saved_alias { struct kmem_cache *s; constchar *name; struct saved_alias *next;
};
if (slab_state == FULL) { /* * If we have a leftover link then remove it.
*/
sysfs_remove_link(&slab_kset->kobj, name); /* * The original cache may have failed to generate sysfs file. * In that case, sysfs_create_link() returns -ENOENT and * symbolic link creation is skipped.
*/ return sysfs_create_link(&slab_kset->kobj, &s->kobj, name);
}
al = kmalloc(sizeof(struct saved_alias), GFP_KERNEL); if (!al) return -ENOMEM;
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.