2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2019 Jeffrey Roberson <jeff@FreeBSD.org>
5 * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6 * Copyright (c) 2004-2006 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice unmodified, this list of conditions, and the following
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * uma_core.c Implementation of the Universal Memory allocator
34 * This allocator is intended to replace the multitude of similar object caches
35 * in the standard FreeBSD kernel. The intent is to be flexible as well as
36 * efficient. A primary design goal is to return unused memory to the rest of
37 * the system. This will make the system as a whole more flexible due to the
38 * ability to move memory to subsystems which most need it instead of leaving
39 * pools of reserved memory unused.
41 * The basic ideas stem from similar slab/zone based allocators whose algorithms
48 * - Improve memory usage for large allocations
49 * - Investigate cache size adjustments
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
56 #include "opt_param.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
62 #include <sys/bitset.h>
63 #include <sys/domainset.h>
64 #include <sys/eventhandler.h>
65 #include <sys/kernel.h>
66 #include <sys/types.h>
67 #include <sys/limits.h>
68 #include <sys/queue.h>
69 #include <sys/malloc.h>
72 #include <sys/sysctl.h>
73 #include <sys/mutex.h>
75 #include <sys/random.h>
76 #include <sys/rwlock.h>
78 #include <sys/sched.h>
79 #include <sys/sleepqueue.h>
82 #include <sys/taskqueue.h>
83 #include <sys/vmmeter.h>
86 #include <vm/vm_param.h>
87 #include <vm/vm_domainset.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_phys.h>
92 #include <vm/vm_pagequeue.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_kern.h>
95 #include <vm/vm_extern.h>
96 #include <vm/vm_dumpset.h>
98 #include <vm/uma_int.h>
99 #include <vm/uma_dbg.h>
103 #ifdef DEBUG_MEMGUARD
104 #include <vm/memguard.h>
107 #include <machine/md_var.h>
110 #define UMA_ALWAYS_CTORDTOR 1
112 #define UMA_ALWAYS_CTORDTOR 0
116 * This is the zone and keg from which all zones are spawned.
118 static uma_zone_t kegs;
119 static uma_zone_t zones;
122 * On INVARIANTS builds, the slab contains a second bitset of the same size,
123 * "dbg_bits", which is laid out immediately after us_free.
126 #define SLAB_BITSETS 2
128 #define SLAB_BITSETS 1
132 * These are the two zones from which all offpage uma_slab_ts are allocated.
134 * One zone is for slab headers that can represent a larger number of items,
135 * making the slabs themselves more efficient, and the other zone is for
136 * headers that are smaller and represent fewer items, making the headers more
139 #define SLABZONE_SIZE(setsize) \
140 (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
141 #define SLABZONE0_SETSIZE (PAGE_SIZE / 16)
142 #define SLABZONE1_SETSIZE SLAB_MAX_SETSIZE
143 #define SLABZONE0_SIZE SLABZONE_SIZE(SLABZONE0_SETSIZE)
144 #define SLABZONE1_SIZE SLABZONE_SIZE(SLABZONE1_SETSIZE)
145 static uma_zone_t slabzones[2];
148 * The initial hash tables come out of this zone so they can be allocated
149 * prior to malloc coming up.
151 static uma_zone_t hashzone;
153 /* The boot-time adjusted value for cache line alignment. */
154 int uma_align_cache = 64 - 1;
156 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
157 static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
160 * Are we allowed to allocate buckets?
162 static int bucketdisable = 1;
164 /* Linked list of all kegs in the system */
165 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
167 /* Linked list of all cache-only zones in the system */
168 static LIST_HEAD(,uma_zone) uma_cachezones =
169 LIST_HEAD_INITIALIZER(uma_cachezones);
171 /* This RW lock protects the keg list */
172 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
175 * First available virual address for boot time allocations.
177 static vm_offset_t bootstart;
178 static vm_offset_t bootmem;
180 static struct sx uma_reclaim_lock;
183 * kmem soft limit, initialized by uma_set_limit(). Ensure that early
184 * allocations don't trigger a wakeup of the reclaim thread.
186 unsigned long uma_kmem_limit = LONG_MAX;
187 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
188 "UMA kernel memory soft limit");
189 unsigned long uma_kmem_total;
190 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
191 "UMA kernel memory usage");
193 /* Is the VM done starting up? */
200 } booted = BOOT_COLD;
203 * This is the handle used to schedule events that need to happen
204 * outside of the allocation fast path.
206 static struct callout uma_callout;
207 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
210 * This structure is passed as the zone ctor arg so that I don't have to create
211 * a special allocation function just for zones.
213 struct uma_zctor_args {
228 struct uma_kctor_args {
237 struct uma_bucket_zone {
239 const char *ubz_name;
240 int ubz_entries; /* Number of items it can hold. */
241 int ubz_maxsize; /* Maximum allocation size per-item. */
245 * Compute the actual number of bucket entries to pack them in power
246 * of two sizes for more efficient space utilization.
248 #define BUCKET_SIZE(n) \
249 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
251 #define BUCKET_MAX BUCKET_SIZE(256)
253 struct uma_bucket_zone bucket_zones[] = {
254 /* Literal bucket sizes. */
255 { NULL, "2 Bucket", 2, 4096 },
256 { NULL, "4 Bucket", 4, 3072 },
257 { NULL, "8 Bucket", 8, 2048 },
258 { NULL, "16 Bucket", 16, 1024 },
259 /* Rounded down power of 2 sizes for efficiency. */
260 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
261 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
262 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
263 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
268 * Flags and enumerations to be passed to internal functions.
272 SKIP_CNT = 0x00000001,
273 SKIP_DTOR = 0x00010000,
274 SKIP_FINI = 0x00020000,
279 void uma_startup1(vm_offset_t);
280 void uma_startup2(void);
282 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
283 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
284 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
285 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
286 static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
287 static void page_free(void *, vm_size_t, uint8_t);
288 static void pcpu_page_free(void *, vm_size_t, uint8_t);
289 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
290 static void cache_drain(uma_zone_t);
291 static void bucket_drain(uma_zone_t, uma_bucket_t);
292 static void bucket_cache_reclaim(uma_zone_t zone, bool);
293 static int keg_ctor(void *, int, void *, int);
294 static void keg_dtor(void *, int, void *);
295 static int zone_ctor(void *, int, void *, int);
296 static void zone_dtor(void *, int, void *);
297 static inline void item_dtor(uma_zone_t zone, void *item, int size,
298 void *udata, enum zfreeskip skip);
299 static int zero_init(void *, int, int);
300 static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
301 int itemdomain, bool ws);
302 static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
303 static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
304 static void zone_timeout(uma_zone_t zone, void *);
305 static int hash_alloc(struct uma_hash *, u_int);
306 static int hash_expand(struct uma_hash *, struct uma_hash *);
307 static void hash_free(struct uma_hash *hash);
308 static void uma_timeout(void *);
309 static void uma_shutdown(void);
310 static void *zone_alloc_item(uma_zone_t, void *, int, int);
311 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
312 static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
313 static void zone_free_limit(uma_zone_t zone, int count);
314 static void bucket_enable(void);
315 static void bucket_init(void);
316 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
317 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
318 static void bucket_zone_drain(void);
319 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
320 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
321 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
322 static size_t slab_sizeof(int nitems);
323 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
324 uma_fini fini, int align, uint32_t flags);
325 static int zone_import(void *, void **, int, int, int);
326 static void zone_release(void *, void **, int);
327 static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
328 static bool cache_free(uma_zone_t, uma_cache_t, void *, void *, int);
330 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
331 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
332 static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
333 static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
334 static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
335 static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
336 static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
338 static uint64_t uma_zone_get_allocs(uma_zone_t zone);
340 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
341 "Memory allocation debugging");
344 static uint64_t uma_keg_get_allocs(uma_keg_t zone);
345 static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
347 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
348 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
349 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
350 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
352 static u_int dbg_divisor = 1;
353 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
354 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
355 "Debug & thrash every this item in memory allocator");
357 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
358 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
359 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
360 &uma_dbg_cnt, "memory items debugged");
361 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
362 &uma_skip_cnt, "memory items skipped, not debugged");
365 SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
366 "Universal Memory Allocator");
368 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
369 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
371 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
372 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
374 static int zone_warnings = 1;
375 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
376 "Warn when UMA zones becomes full");
378 static int multipage_slabs = 1;
379 TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
380 SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
381 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
382 "UMA may choose larger slab sizes for better efficiency");
385 * Select the slab zone for an offpage slab with the given maximum item count.
387 static inline uma_zone_t
391 return (slabzones[ipers > SLABZONE0_SETSIZE]);
395 * This routine checks to see whether or not it's safe to enable buckets.
401 KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
402 bucketdisable = vm_page_count_min();
406 * Initialize bucket_zones, the array of zones of buckets of various sizes.
408 * For each zone, calculate the memory required for each bucket, consisting
409 * of the header and an array of pointers.
414 struct uma_bucket_zone *ubz;
417 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
418 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
419 size += sizeof(void *) * ubz->ubz_entries;
420 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
421 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
422 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
423 UMA_ZONE_FIRSTTOUCH);
428 * Given a desired number of entries for a bucket, return the zone from which
429 * to allocate the bucket.
431 static struct uma_bucket_zone *
432 bucket_zone_lookup(int entries)
434 struct uma_bucket_zone *ubz;
436 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
437 if (ubz->ubz_entries >= entries)
444 bucket_select(int size)
446 struct uma_bucket_zone *ubz;
448 ubz = &bucket_zones[0];
449 if (size > ubz->ubz_maxsize)
450 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
452 for (; ubz->ubz_entries != 0; ubz++)
453 if (ubz->ubz_maxsize < size)
456 return (ubz->ubz_entries);
460 bucket_alloc(uma_zone_t zone, void *udata, int flags)
462 struct uma_bucket_zone *ubz;
466 * Don't allocate buckets early in boot.
468 if (__predict_false(booted < BOOT_KVA))
472 * To limit bucket recursion we store the original zone flags
473 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
474 * NOVM flag to persist even through deep recursions. We also
475 * store ZFLAG_BUCKET once we have recursed attempting to allocate
476 * a bucket for a bucket zone so we do not allow infinite bucket
477 * recursion. This cookie will even persist to frees of unused
478 * buckets via the allocation path or bucket allocations in the
481 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
482 udata = (void *)(uintptr_t)zone->uz_flags;
484 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
486 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
488 if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
490 ubz = bucket_zone_lookup(atomic_load_16(&zone->uz_bucket_size));
491 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
493 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
496 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
499 bucket->ub_entries = min(ubz->ubz_entries,
500 zone->uz_bucket_size_max);
501 bucket->ub_seq = SMR_SEQ_INVALID;
502 CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
503 zone->uz_name, zone, bucket);
510 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
512 struct uma_bucket_zone *ubz;
514 if (bucket->ub_cnt != 0)
515 bucket_drain(zone, bucket);
517 KASSERT(bucket->ub_cnt == 0,
518 ("bucket_free: Freeing a non free bucket."));
519 KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
520 ("bucket_free: Freeing an SMR bucket."));
521 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
522 udata = (void *)(uintptr_t)zone->uz_flags;
523 ubz = bucket_zone_lookup(bucket->ub_entries);
524 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
528 bucket_zone_drain(void)
530 struct uma_bucket_zone *ubz;
532 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
533 uma_zone_reclaim(ubz->ubz_zone, UMA_RECLAIM_DRAIN);
538 kasan_mark_item_valid(uma_zone_t zone, void *item)
544 if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
548 rsz = roundup2(sz, KASAN_SHADOW_SCALE);
549 if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
550 kasan_mark(item, sz, rsz, 0);
552 pcpu_item = zpcpu_base_to_offset(item);
553 for (i = 0; i <= mp_maxid; i++)
554 kasan_mark(zpcpu_get_cpu(pcpu_item, i), sz, rsz, 0);
559 kasan_mark_item_invalid(uma_zone_t zone, void *item)
565 if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
568 sz = roundup2(zone->uz_size, KASAN_SHADOW_SCALE);
569 if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
570 kasan_mark(item, 0, sz, KASAN_UMA_FREED);
572 pcpu_item = zpcpu_base_to_offset(item);
573 for (i = 0; i <= mp_maxid; i++)
574 kasan_mark(zpcpu_get_cpu(pcpu_item, i), 0, sz, 0);
579 kasan_mark_slab_valid(uma_keg_t keg, void *mem)
583 if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
584 sz = keg->uk_ppera * PAGE_SIZE;
585 kasan_mark(mem, sz, sz, 0);
590 kasan_mark_slab_invalid(uma_keg_t keg, void *mem)
594 if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
595 if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
596 sz = keg->uk_ppera * PAGE_SIZE;
599 kasan_mark(mem, 0, sz, KASAN_UMA_FREED);
604 kasan_mark_item_valid(uma_zone_t zone __unused, void *item __unused)
609 kasan_mark_item_invalid(uma_zone_t zone __unused, void *item __unused)
614 kasan_mark_slab_valid(uma_keg_t keg __unused, void *mem __unused)
619 kasan_mark_slab_invalid(uma_keg_t keg __unused, void *mem __unused)
625 * Acquire the domain lock and record contention.
627 static uma_zone_domain_t
628 zone_domain_lock(uma_zone_t zone, int domain)
630 uma_zone_domain_t zdom;
633 zdom = ZDOM_GET(zone, domain);
635 if (ZDOM_OWNED(zdom))
638 /* This is unsynchronized. The counter does not need to be precise. */
639 if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
640 zone->uz_bucket_size++;
645 * Search for the domain with the least cached items and return it if it
646 * is out of balance with the preferred domain.
648 static __noinline int
649 zone_domain_lowest(uma_zone_t zone, int pref)
651 long least, nitems, prefitems;
655 prefitems = least = LONG_MAX;
657 for (i = 0; i < vm_ndomains; i++) {
658 nitems = ZDOM_GET(zone, i)->uzd_nitems;
659 if (nitems < least) {
666 if (prefitems < least * 2)
673 * Search for the domain with the most cached items and return it or the
674 * preferred domain if it has enough to proceed.
676 static __noinline int
677 zone_domain_highest(uma_zone_t zone, int pref)
683 if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
688 for (i = 0; i < vm_ndomains; i++) {
689 nitems = ZDOM_GET(zone, i)->uzd_nitems;
700 * Safely subtract cnt from imax.
703 zone_domain_imax_sub(uma_zone_domain_t zdom, int cnt)
708 old = zdom->uzd_imax;
714 } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, new) == 0);
718 * Set the maximum imax value.
721 zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
725 old = zdom->uzd_imax;
729 } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
733 * Attempt to satisfy an allocation by retrieving a full bucket from one of the
734 * zone's caches. If a bucket is found the zone is not locked on return.
737 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
743 ZDOM_LOCK_ASSERT(zdom);
745 if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
748 /* SMR Buckets can not be re-used until readers expire. */
749 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
750 bucket->ub_seq != SMR_SEQ_INVALID) {
751 if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
753 bucket->ub_seq = SMR_SEQ_INVALID;
754 dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
755 if (STAILQ_NEXT(bucket, ub_link) != NULL)
756 zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
758 STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
760 KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
761 ("%s: item count underflow (%ld, %d)",
762 __func__, zdom->uzd_nitems, bucket->ub_cnt));
763 KASSERT(bucket->ub_cnt > 0,
764 ("%s: empty bucket in bucket cache", __func__));
765 zdom->uzd_nitems -= bucket->ub_cnt;
768 * Shift the bounds of the current WSS interval to avoid
769 * perturbing the estimate.
772 zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
773 zone_domain_imax_sub(zdom, bucket->ub_cnt);
774 } else if (zdom->uzd_imin > zdom->uzd_nitems)
775 zdom->uzd_imin = zdom->uzd_nitems;
779 for (i = 0; i < bucket->ub_cnt; i++)
780 item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
787 * Insert a full bucket into the specified cache. The "ws" parameter indicates
788 * whether the bucket's contents should be counted as part of the zone's working
789 * set. The bucket may be freed if it exceeds the bucket limit.
792 zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
795 uma_zone_domain_t zdom;
797 /* We don't cache empty buckets. This can happen after a reclaim. */
798 if (bucket->ub_cnt == 0)
800 zdom = zone_domain_lock(zone, domain);
803 * Conditionally set the maximum number of items.
805 zdom->uzd_nitems += bucket->ub_cnt;
806 if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
808 zone_domain_imax_set(zdom, zdom->uzd_nitems);
809 if (STAILQ_EMPTY(&zdom->uzd_buckets))
810 zdom->uzd_seq = bucket->ub_seq;
813 * Try to promote reuse of recently used items. For items
814 * protected by SMR, try to defer reuse to minimize polling.
816 if (bucket->ub_seq == SMR_SEQ_INVALID)
817 STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
819 STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
823 zdom->uzd_nitems -= bucket->ub_cnt;
826 bucket_free(zone, bucket, udata);
829 /* Pops an item out of a per-cpu cache bucket. */
831 cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
835 CRITICAL_ASSERT(curthread);
838 item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
840 bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
841 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
848 /* Pushes an item into a per-cpu cache bucket. */
850 cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
853 CRITICAL_ASSERT(curthread);
854 KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
855 ("uma_zfree: Freeing to non free bucket index."));
857 bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
863 * Unload a UMA bucket from a per-cpu cache.
865 static inline uma_bucket_t
866 cache_bucket_unload(uma_cache_bucket_t bucket)
870 b = bucket->ucb_bucket;
872 MPASS(b->ub_entries == bucket->ucb_entries);
873 b->ub_cnt = bucket->ucb_cnt;
874 bucket->ucb_bucket = NULL;
875 bucket->ucb_entries = bucket->ucb_cnt = 0;
881 static inline uma_bucket_t
882 cache_bucket_unload_alloc(uma_cache_t cache)
885 return (cache_bucket_unload(&cache->uc_allocbucket));
888 static inline uma_bucket_t
889 cache_bucket_unload_free(uma_cache_t cache)
892 return (cache_bucket_unload(&cache->uc_freebucket));
895 static inline uma_bucket_t
896 cache_bucket_unload_cross(uma_cache_t cache)
899 return (cache_bucket_unload(&cache->uc_crossbucket));
903 * Load a bucket into a per-cpu cache bucket.
906 cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
909 CRITICAL_ASSERT(curthread);
910 MPASS(bucket->ucb_bucket == NULL);
911 MPASS(b->ub_seq == SMR_SEQ_INVALID);
913 bucket->ucb_bucket = b;
914 bucket->ucb_cnt = b->ub_cnt;
915 bucket->ucb_entries = b->ub_entries;
919 cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
922 cache_bucket_load(&cache->uc_allocbucket, b);
926 cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
929 cache_bucket_load(&cache->uc_freebucket, b);
934 cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
937 cache_bucket_load(&cache->uc_crossbucket, b);
942 * Copy and preserve ucb_spare.
945 cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
948 b1->ucb_bucket = b2->ucb_bucket;
949 b1->ucb_entries = b2->ucb_entries;
950 b1->ucb_cnt = b2->ucb_cnt;
954 * Swap two cache buckets.
957 cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
959 struct uma_cache_bucket b3;
961 CRITICAL_ASSERT(curthread);
963 cache_bucket_copy(&b3, b1);
964 cache_bucket_copy(b1, b2);
965 cache_bucket_copy(b2, &b3);
969 * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
972 cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
974 uma_zone_domain_t zdom;
978 * Avoid the lock if possible.
980 zdom = ZDOM_GET(zone, domain);
981 if (zdom->uzd_nitems == 0)
984 if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
985 !smr_poll(zone->uz_smr, zdom->uzd_seq, false))
989 * Check the zone's cache of buckets.
991 zdom = zone_domain_lock(zone, domain);
992 if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
1000 zone_log_warning(uma_zone_t zone)
1002 static const struct timeval warninterval = { 300, 0 };
1004 if (!zone_warnings || zone->uz_warning == NULL)
1007 if (ratecheck(&zone->uz_ratecheck, &warninterval))
1008 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
1012 zone_maxaction(uma_zone_t zone)
1015 if (zone->uz_maxaction.ta_func != NULL)
1016 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
1020 * Routine called by timeout which is used to fire off some time interval
1021 * based calculations. (stats, hash size, etc.)
1030 uma_timeout(void *unused)
1033 zone_foreach(zone_timeout, NULL);
1035 /* Reschedule this event */
1036 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1040 * Update the working set size estimate for the zone's bucket cache.
1041 * The constants chosen here are somewhat arbitrary. With an update period of
1042 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
1046 zone_domain_update_wss(uma_zone_domain_t zdom)
1051 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
1052 wss = zdom->uzd_imax - zdom->uzd_imin;
1053 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
1054 zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
1059 * Routine to perform timeout driven calculations. This expands the
1060 * hashes and does per cpu statistics aggregation.
1065 zone_timeout(uma_zone_t zone, void *unused)
1070 if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
1076 * Hash zones are non-numa by definition so the first domain
1077 * is the only one present.
1080 pages = keg->uk_domain[0].ud_pages;
1083 * Expand the keg hash table.
1085 * This is done if the number of slabs is larger than the hash size.
1086 * What I'm trying to do here is completely reduce collisions. This
1087 * may be a little aggressive. Should I allow for two collisions max?
1089 if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
1090 struct uma_hash newhash;
1091 struct uma_hash oldhash;
1095 * This is so involved because allocating and freeing
1096 * while the keg lock is held will lead to deadlock.
1097 * I have to do everything in stages and check for
1101 ret = hash_alloc(&newhash, 1 << fls(slabs));
1104 if (hash_expand(&keg->uk_hash, &newhash)) {
1105 oldhash = keg->uk_hash;
1106 keg->uk_hash = newhash;
1111 hash_free(&oldhash);
1118 for (int i = 0; i < vm_ndomains; i++)
1119 zone_domain_update_wss(ZDOM_GET(zone, i));
1123 * Allocate and zero fill the next sized hash table from the appropriate
1127 * hash A new hash structure with the old hash size in uh_hashsize
1130 * 1 on success and 0 on failure.
1133 hash_alloc(struct uma_hash *hash, u_int size)
1137 KASSERT(powerof2(size), ("hash size must be power of 2"));
1138 if (size > UMA_HASH_SIZE_INIT) {
1139 hash->uh_hashsize = size;
1140 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
1141 hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
1143 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
1144 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
1145 UMA_ANYDOMAIN, M_WAITOK);
1146 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
1148 if (hash->uh_slab_hash) {
1149 bzero(hash->uh_slab_hash, alloc);
1150 hash->uh_hashmask = hash->uh_hashsize - 1;
1158 * Expands the hash table for HASH zones. This is done from zone_timeout
1159 * to reduce collisions. This must not be done in the regular allocation
1160 * path, otherwise, we can recurse on the vm while allocating pages.
1163 * oldhash The hash you want to expand
1164 * newhash The hash structure for the new table
1172 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
1174 uma_hash_slab_t slab;
1178 if (!newhash->uh_slab_hash)
1181 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
1185 * I need to investigate hash algorithms for resizing without a
1189 for (idx = 0; idx < oldhash->uh_hashsize; idx++)
1190 while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
1191 slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
1192 LIST_REMOVE(slab, uhs_hlink);
1193 hval = UMA_HASH(newhash, slab->uhs_data);
1194 LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
1202 * Free the hash bucket to the appropriate backing store.
1205 * slab_hash The hash bucket we're freeing
1206 * hashsize The number of entries in that hash bucket
1212 hash_free(struct uma_hash *hash)
1214 if (hash->uh_slab_hash == NULL)
1216 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
1217 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
1219 free(hash->uh_slab_hash, M_UMAHASH);
1223 * Frees all outstanding items in a bucket
1226 * zone The zone to free to, must be unlocked.
1227 * bucket The free/alloc bucket with items.
1233 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
1237 if (bucket->ub_cnt == 0)
1240 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
1241 bucket->ub_seq != SMR_SEQ_INVALID) {
1242 smr_wait(zone->uz_smr, bucket->ub_seq);
1243 bucket->ub_seq = SMR_SEQ_INVALID;
1244 for (i = 0; i < bucket->ub_cnt; i++)
1245 item_dtor(zone, bucket->ub_bucket[i],
1246 zone->uz_size, NULL, SKIP_NONE);
1249 for (i = 0; i < bucket->ub_cnt; i++) {
1250 kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
1251 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
1252 kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
1254 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
1255 if (zone->uz_max_items > 0)
1256 zone_free_limit(zone, bucket->ub_cnt);
1258 bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
1264 * Drains the per cpu caches for a zone.
1266 * NOTE: This may only be called while the zone is being torn down, and not
1267 * during normal operation. This is necessary in order that we do not have
1268 * to migrate CPUs to drain the per-CPU caches.
1271 * zone The zone to drain, must be unlocked.
1277 cache_drain(uma_zone_t zone)
1280 uma_bucket_t bucket;
1285 * XXX: It is safe to not lock the per-CPU caches, because we're
1286 * tearing down the zone anyway. I.e., there will be no further use
1287 * of the caches at this point.
1289 * XXX: It would good to be able to assert that the zone is being
1290 * torn down to prevent improper use of cache_drain().
1292 seq = SMR_SEQ_INVALID;
1293 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
1294 seq = smr_advance(zone->uz_smr);
1296 cache = &zone->uz_cpu[cpu];
1297 bucket = cache_bucket_unload_alloc(cache);
1299 bucket_free(zone, bucket, NULL);
1300 bucket = cache_bucket_unload_free(cache);
1301 if (bucket != NULL) {
1302 bucket->ub_seq = seq;
1303 bucket_free(zone, bucket, NULL);
1305 bucket = cache_bucket_unload_cross(cache);
1306 if (bucket != NULL) {
1307 bucket->ub_seq = seq;
1308 bucket_free(zone, bucket, NULL);
1311 bucket_cache_reclaim(zone, true);
1315 cache_shrink(uma_zone_t zone, void *unused)
1318 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1321 zone->uz_bucket_size =
1322 (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
1326 cache_drain_safe_cpu(uma_zone_t zone, void *unused)
1329 uma_bucket_t b1, b2, b3;
1332 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1335 b1 = b2 = b3 = NULL;
1337 cache = &zone->uz_cpu[curcpu];
1338 domain = PCPU_GET(domain);
1339 b1 = cache_bucket_unload_alloc(cache);
1342 * Don't flush SMR zone buckets. This leaves the zone without a
1343 * bucket and forces every free to synchronize().
1345 if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
1346 b2 = cache_bucket_unload_free(cache);
1347 b3 = cache_bucket_unload_cross(cache);
1352 zone_free_bucket(zone, b1, NULL, domain, false);
1354 zone_free_bucket(zone, b2, NULL, domain, false);
1356 /* Adjust the domain so it goes to zone_free_cross. */
1357 domain = (domain + 1) % vm_ndomains;
1358 zone_free_bucket(zone, b3, NULL, domain, false);
1363 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
1364 * This is an expensive call because it needs to bind to all CPUs
1365 * one by one and enter a critical section on each of them in order
1366 * to safely access their cache buckets.
1367 * Zone lock must not be held on call this function.
1370 pcpu_cache_drain_safe(uma_zone_t zone)
1375 * Polite bucket sizes shrinking was not enough, shrink aggressively.
1378 cache_shrink(zone, NULL);
1380 zone_foreach(cache_shrink, NULL);
1383 thread_lock(curthread);
1384 sched_bind(curthread, cpu);
1385 thread_unlock(curthread);
1388 cache_drain_safe_cpu(zone, NULL);
1390 zone_foreach(cache_drain_safe_cpu, NULL);
1392 thread_lock(curthread);
1393 sched_unbind(curthread);
1394 thread_unlock(curthread);
1398 * Reclaim cached buckets from a zone. All buckets are reclaimed if the caller
1399 * requested a drain, otherwise the per-domain caches are trimmed to either
1400 * estimated working set size.
1403 bucket_cache_reclaim(uma_zone_t zone, bool drain)
1405 uma_zone_domain_t zdom;
1406 uma_bucket_t bucket;
1411 * Shrink the zone bucket size to ensure that the per-CPU caches
1412 * don't grow too large.
1414 if (zone->uz_bucket_size > zone->uz_bucket_size_min)
1415 zone->uz_bucket_size--;
1417 for (i = 0; i < vm_ndomains; i++) {
1419 * The cross bucket is partially filled and not part of
1420 * the item count. Reclaim it individually here.
1422 zdom = ZDOM_GET(zone, i);
1423 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
1424 ZONE_CROSS_LOCK(zone);
1425 bucket = zdom->uzd_cross;
1426 zdom->uzd_cross = NULL;
1427 ZONE_CROSS_UNLOCK(zone);
1429 bucket_free(zone, bucket, NULL);
1433 * If we were asked to drain the zone, we are done only once
1434 * this bucket cache is empty. Otherwise, we reclaim items in
1435 * excess of the zone's estimated working set size. If the
1436 * difference nitems - imin is larger than the WSS estimate,
1437 * then the estimate will grow at the end of this interval and
1438 * we ignore the historical average.
1441 target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
1443 while (zdom->uzd_nitems > target) {
1444 bucket = zone_fetch_bucket(zone, zdom, true);
1447 bucket_free(zone, bucket, NULL);
1455 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
1462 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
1463 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
1465 mem = slab_data(slab, keg);
1466 size = PAGE_SIZE * keg->uk_ppera;
1468 kasan_mark_slab_valid(keg, mem);
1469 if (keg->uk_fini != NULL) {
1470 for (i = start - 1; i > -1; i--)
1473 * trash_fini implies that dtor was trash_dtor. trash_fini
1474 * would check that memory hasn't been modified since free,
1475 * which executed trash_dtor.
1476 * That's why we need to run uma_dbg_kskip() check here,
1477 * albeit we don't make skip check for other init/fini
1480 if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
1481 keg->uk_fini != trash_fini)
1483 keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
1485 flags = slab->us_flags;
1486 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1487 zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
1490 keg->uk_freef(mem, size, flags);
1491 uma_total_dec(size);
1495 keg_drain_domain(uma_keg_t keg, int domain)
1497 struct slabhead freeslabs;
1499 uma_slab_t slab, tmp;
1500 uint32_t i, stofree, stokeep, partial;
1502 dom = &keg->uk_domain[domain];
1503 LIST_INIT(&freeslabs);
1505 CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1506 keg->uk_name, keg, domain, dom->ud_free_items);
1508 KEG_LOCK(keg, domain);
1511 * Are the free items in partially allocated slabs sufficient to meet
1512 * the reserve? If not, compute the number of fully free slabs that must
1515 partial = dom->ud_free_items - dom->ud_free_slabs * keg->uk_ipers;
1516 if (partial < keg->uk_reserve) {
1517 stokeep = min(dom->ud_free_slabs,
1518 howmany(keg->uk_reserve - partial, keg->uk_ipers));
1522 stofree = dom->ud_free_slabs - stokeep;
1525 * Partition the free slabs into two sets: those that must be kept in
1526 * order to maintain the reserve, and those that may be released back to
1527 * the system. Since one set may be much larger than the other,
1528 * populate the smaller of the two sets and swap them if necessary.
1530 for (i = min(stofree, stokeep); i > 0; i--) {
1531 slab = LIST_FIRST(&dom->ud_free_slab);
1532 LIST_REMOVE(slab, us_link);
1533 LIST_INSERT_HEAD(&freeslabs, slab, us_link);
1535 if (stofree > stokeep)
1536 LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1538 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1539 LIST_FOREACH(slab, &freeslabs, us_link)
1540 UMA_HASH_REMOVE(&keg->uk_hash, slab);
1542 dom->ud_free_items -= stofree * keg->uk_ipers;
1543 dom->ud_free_slabs -= stofree;
1544 dom->ud_pages -= stofree * keg->uk_ppera;
1545 KEG_UNLOCK(keg, domain);
1547 LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1548 keg_free_slab(keg, slab, keg->uk_ipers);
1552 * Frees pages from a keg back to the system. This is done on demand from
1553 * the pageout daemon.
1558 keg_drain(uma_keg_t keg)
1562 if ((keg->uk_flags & UMA_ZONE_NOFREE) != 0)
1564 for (i = 0; i < vm_ndomains; i++)
1565 keg_drain_domain(keg, i);
1569 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1573 * Set draining to interlock with zone_dtor() so we can release our
1574 * locks as we go. Only dtor() should do a WAITOK call since it
1575 * is the only call that knows the structure will still be available
1579 while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1580 if (waitok == M_NOWAIT)
1582 msleep(zone, &ZDOM_GET(zone, 0)->uzd_lock, PVM, "zonedrain",
1585 zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1587 bucket_cache_reclaim(zone, drain);
1590 * The DRAINING flag protects us from being freed while
1591 * we're running. Normally the uma_rwlock would protect us but we
1592 * must be able to release and acquire the right lock for each keg.
1594 if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1595 keg_drain(zone->uz_keg);
1597 zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1604 zone_drain(uma_zone_t zone, void *unused)
1607 zone_reclaim(zone, M_NOWAIT, true);
1611 zone_trim(uma_zone_t zone, void *unused)
1614 zone_reclaim(zone, M_NOWAIT, false);
1618 * Allocate a new slab for a keg and inserts it into the partial slab list.
1619 * The keg should be unlocked on entry. If the allocation succeeds it will
1620 * be locked on return.
1623 * flags Wait flags for the item initialization routine
1624 * aflags Wait flags for the slab allocation
1627 * The slab that was allocated or NULL if there is no memory and the
1628 * caller specified M_NOWAIT.
1631 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1641 KASSERT(domain >= 0 && domain < vm_ndomains,
1642 ("keg_alloc_slab: domain %d out of range", domain));
1646 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1647 uma_hash_slab_t hslab;
1648 hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1652 slab = &hslab->uhs_slab;
1656 * This reproduces the old vm_zone behavior of zero filling pages the
1657 * first time they are added to a zone.
1659 * Malloced items are zeroed in uma_zalloc.
1662 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1667 if (keg->uk_flags & UMA_ZONE_NODUMP)
1670 /* zone is passed for legacy reasons. */
1671 size = keg->uk_ppera * PAGE_SIZE;
1672 mem = keg->uk_allocf(zone, size, domain, &sflags, aflags);
1674 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1675 zone_free_item(slabzone(keg->uk_ipers),
1676 slab_tohashslab(slab), NULL, SKIP_NONE);
1679 uma_total_inc(size);
1681 /* For HASH zones all pages go to the same uma_domain. */
1682 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1685 /* Point the slab into the allocated memory */
1686 if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1687 slab = (uma_slab_t)(mem + keg->uk_pgoff);
1689 slab_tohashslab(slab)->uhs_data = mem;
1691 if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1692 for (i = 0; i < keg->uk_ppera; i++)
1693 vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1696 slab->us_freecount = keg->uk_ipers;
1697 slab->us_flags = sflags;
1698 slab->us_domain = domain;
1700 BIT_FILL(keg->uk_ipers, &slab->us_free);
1702 BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1705 if (keg->uk_init != NULL) {
1706 for (i = 0; i < keg->uk_ipers; i++)
1707 if (keg->uk_init(slab_item(slab, keg, i),
1708 keg->uk_size, flags) != 0)
1710 if (i != keg->uk_ipers) {
1711 keg_free_slab(keg, slab, i);
1715 kasan_mark_slab_invalid(keg, mem);
1716 KEG_LOCK(keg, domain);
1718 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1719 slab, keg->uk_name, keg);
1721 if (keg->uk_flags & UMA_ZFLAG_HASH)
1722 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1725 * If we got a slab here it's safe to mark it partially used
1726 * and return. We assume that the caller is going to remove
1727 * at least one item.
1729 dom = &keg->uk_domain[domain];
1730 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1731 dom->ud_pages += keg->uk_ppera;
1732 dom->ud_free_items += keg->uk_ipers;
1741 * This function is intended to be used early on in place of page_alloc(). It
1742 * performs contiguous physical memory allocations and uses a bump allocator for
1743 * KVA, so is usable before the kernel map is initialized.
1746 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1755 pages = howmany(bytes, PAGE_SIZE);
1756 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1758 *pflag = UMA_SLAB_BOOT;
1759 m = vm_page_alloc_contig_domain(NULL, 0, domain,
1760 malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages,
1761 (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1765 pa = VM_PAGE_TO_PHYS(m);
1766 for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1767 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1768 defined(__riscv) || defined(__powerpc64__)
1769 if ((wait & M_NODUMP) == 0)
1773 /* Allocate KVA and indirectly advance bootmem. */
1774 mem = (void *)pmap_map(&bootmem, m->phys_addr,
1775 m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1776 if ((wait & M_ZERO) != 0)
1777 bzero(mem, pages * PAGE_SIZE);
1783 startup_free(void *mem, vm_size_t bytes)
1788 va = (vm_offset_t)mem;
1789 m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1792 * startup_alloc() returns direct-mapped slabs on some platforms. Avoid
1793 * unmapping ranges of the direct map.
1795 if (va >= bootstart && va + bytes <= bootmem)
1796 pmap_remove(kernel_pmap, va, va + bytes);
1797 for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1798 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1799 defined(__riscv) || defined(__powerpc64__)
1800 dump_drop_page(VM_PAGE_TO_PHYS(m));
1802 vm_page_unwire_noq(m);
1808 * Allocates a number of pages from the system
1811 * bytes The number of bytes requested
1812 * wait Shall we wait?
1815 * A pointer to the alloced memory or possibly
1816 * NULL if M_NOWAIT is set.
1819 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1822 void *p; /* Returned page */
1824 *pflag = UMA_SLAB_KERNEL;
1825 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1831 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1834 struct pglist alloctail;
1835 vm_offset_t addr, zkva;
1837 vm_page_t p, p_next;
1842 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1844 TAILQ_INIT(&alloctail);
1845 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1846 malloc2vm_flags(wait);
1847 *pflag = UMA_SLAB_KERNEL;
1848 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1849 if (CPU_ABSENT(cpu)) {
1850 p = vm_page_alloc(NULL, 0, flags);
1853 p = vm_page_alloc(NULL, 0, flags);
1855 pc = pcpu_find(cpu);
1856 if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1859 p = vm_page_alloc_domain(NULL, 0,
1860 pc->pc_domain, flags);
1861 if (__predict_false(p == NULL))
1862 p = vm_page_alloc(NULL, 0, flags);
1865 if (__predict_false(p == NULL))
1867 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1869 if ((addr = kva_alloc(bytes)) == 0)
1872 TAILQ_FOREACH(p, &alloctail, listq) {
1873 pmap_qenter(zkva, &p, 1);
1876 return ((void*)addr);
1878 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1879 vm_page_unwire_noq(p);
1886 * Allocates a number of pages from within an object
1889 * bytes The number of bytes requested
1890 * wait Shall we wait?
1893 * A pointer to the alloced memory or possibly
1894 * NULL if M_NOWAIT is set.
1897 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1900 TAILQ_HEAD(, vm_page) alloctail;
1902 vm_offset_t retkva, zkva;
1903 vm_page_t p, p_next;
1906 TAILQ_INIT(&alloctail);
1909 npages = howmany(bytes, PAGE_SIZE);
1910 while (npages > 0) {
1911 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1912 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1913 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1917 * Since the page does not belong to an object, its
1920 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1925 * Page allocation failed, free intermediate pages and
1928 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1929 vm_page_unwire_noq(p);
1934 *flags = UMA_SLAB_PRIV;
1935 zkva = keg->uk_kva +
1936 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1938 TAILQ_FOREACH(p, &alloctail, listq) {
1939 pmap_qenter(zkva, &p, 1);
1943 return ((void *)retkva);
1947 * Allocate physically contiguous pages.
1950 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1954 *pflag = UMA_SLAB_KERNEL;
1955 return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1956 bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1960 * Frees a number of pages to the system
1963 * mem A pointer to the memory to be freed
1964 * size The size of the memory being freed
1965 * flags The original p->us_flags field
1971 page_free(void *mem, vm_size_t size, uint8_t flags)
1974 if ((flags & UMA_SLAB_BOOT) != 0) {
1975 startup_free(mem, size);
1979 KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1980 ("UMA: page_free used with invalid flags %x", flags));
1982 kmem_free((vm_offset_t)mem, size);
1986 * Frees pcpu zone allocations
1989 * mem A pointer to the memory to be freed
1990 * size The size of the memory being freed
1991 * flags The original p->us_flags field
1997 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1999 vm_offset_t sva, curva;
2003 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
2005 if ((flags & UMA_SLAB_BOOT) != 0) {
2006 startup_free(mem, size);
2010 sva = (vm_offset_t)mem;
2011 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
2012 paddr = pmap_kextract(curva);
2013 m = PHYS_TO_VM_PAGE(paddr);
2014 vm_page_unwire_noq(m);
2017 pmap_qremove(sva, size >> PAGE_SHIFT);
2018 kva_free(sva, size);
2022 * Zero fill initializer
2024 * Arguments/Returns follow uma_init specifications
2027 zero_init(void *mem, int size, int flags)
2034 static struct noslabbits *
2035 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
2038 return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
2043 * Actual size of embedded struct slab (!OFFPAGE).
2046 slab_sizeof(int nitems)
2050 s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
2051 return (roundup(s, UMA_ALIGN_PTR + 1));
2054 #define UMA_FIXPT_SHIFT 31
2055 #define UMA_FRAC_FIXPT(n, d) \
2056 ((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
2057 #define UMA_FIXPT_PCT(f) \
2058 ((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
2059 #define UMA_PCT_FIXPT(pct) UMA_FRAC_FIXPT((pct), 100)
2060 #define UMA_MIN_EFF UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
2063 * Compute the number of items that will fit in a slab. If hdr is true, the
2064 * item count may be limited to provide space in the slab for an inline slab
2065 * header. Otherwise, all slab space will be provided for item storage.
2068 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
2073 /* The padding between items is not needed after the last item. */
2074 padpi = rsize - size;
2078 * Start with the maximum item count and remove items until
2079 * the slab header first alongside the allocatable memory.
2081 for (ipers = MIN(SLAB_MAX_SETSIZE,
2082 (slabsize + padpi - slab_sizeof(1)) / rsize);
2084 ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
2088 ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
2094 struct keg_layout_result {
2102 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
2103 struct keg_layout_result *kl)
2108 kl->slabsize = slabsize;
2110 /* Handle INTERNAL as inline with an extra page. */
2111 if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
2112 kl->format &= ~UMA_ZFLAG_INTERNAL;
2113 kl->slabsize += PAGE_SIZE;
2116 kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2117 (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2119 /* Account for memory used by an offpage slab header. */
2120 total = kl->slabsize;
2121 if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2122 total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2124 kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2128 * Determine the format of a uma keg. This determines where the slab header
2129 * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2132 * keg The zone we should initialize
2138 keg_layout(uma_keg_t keg)
2140 struct keg_layout_result kl = {}, kl_tmp;
2149 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2150 (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2151 (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2152 ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2153 __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2155 KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2156 (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2157 ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2160 alignsize = keg->uk_align + 1;
2163 * Calculate the size of each allocation (rsize) according to
2164 * alignment. If the requested size is smaller than we have
2165 * allocation bits for we round it up.
2167 rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2168 rsize = roundup2(rsize, alignsize);
2170 if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2172 * We want one item to start on every align boundary in a page.
2173 * To do this we will span pages. We will also extend the item
2174 * by the size of align if it is an even multiple of align.
2175 * Otherwise, it would fall on the same boundary every time.
2177 if ((rsize & alignsize) == 0)
2179 slabsize = rsize * (PAGE_SIZE / alignsize);
2180 slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2181 slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2182 slabsize = round_page(slabsize);
2185 * Start with a slab size of as many pages as it takes to
2186 * represent a single item. We will try to fit as many
2187 * additional items into the slab as possible.
2189 slabsize = round_page(keg->uk_size);
2192 /* Build a list of all of the available formats for this keg. */
2195 /* Evaluate an inline slab layout. */
2196 if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2199 /* TODO: vm_page-embedded slab. */
2202 * We can't do OFFPAGE if we're internal or if we've been
2203 * asked to not go to the VM for buckets. If we do this we
2204 * may end up going to the VM for slabs which we do not want
2205 * to do if we're UMA_ZONE_VM, which clearly forbids it.
2206 * In those cases, evaluate a pseudo-format called INTERNAL
2207 * which has an inline slab header and one extra page to
2208 * guarantee that it fits.
2210 * Otherwise, see if using an OFFPAGE slab will improve our
2213 if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2214 fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2216 fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2219 * Choose a slab size and format which satisfy the minimum efficiency.
2220 * Prefer the smallest slab size that meets the constraints.
2222 * Start with a minimum slab size, to accommodate CACHESPREAD. Then,
2223 * for small items (up to PAGE_SIZE), the iteration increment is one
2224 * page; and for large items, the increment is one item.
2226 i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2227 KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2228 keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2231 slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2232 round_page(rsize * (i - 1) + keg->uk_size);
2234 for (j = 0; j < nfmt; j++) {
2235 /* Only if we have no viable format yet. */
2236 if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2240 keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2241 if (kl_tmp.eff <= kl.eff)
2246 CTR6(KTR_UMA, "keg %s layout: format %#x "
2247 "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2248 keg->uk_name, kl.format, kl.ipers, rsize,
2249 kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2251 /* Stop when we reach the minimum efficiency. */
2252 if (kl.eff >= UMA_MIN_EFF)
2256 if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2257 slabsize >= SLAB_MAX_SETSIZE * rsize ||
2258 (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2262 pages = atop(kl.slabsize);
2263 if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2264 pages *= mp_maxid + 1;
2266 keg->uk_rsize = rsize;
2267 keg->uk_ipers = kl.ipers;
2268 keg->uk_ppera = pages;
2269 keg->uk_flags |= kl.format;
2272 * How do we find the slab header if it is offpage or if not all item
2273 * start addresses are in the same page? We could solve the latter
2274 * case with vaddr alignment, but we don't.
2276 if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2277 (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2278 if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2279 keg->uk_flags |= UMA_ZFLAG_HASH;
2281 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2284 CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2285 __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2287 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2288 ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2289 keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2290 keg->uk_ipers, pages));
2294 * Keg header ctor. This initializes all fields, locks, etc. And inserts
2295 * the keg onto the global keg list.
2297 * Arguments/Returns follow uma_ctor specifications
2298 * udata Actually uma_kctor_args
2301 keg_ctor(void *mem, int size, void *udata, int flags)
2303 struct uma_kctor_args *arg = udata;
2304 uma_keg_t keg = mem;
2309 keg->uk_size = arg->size;
2310 keg->uk_init = arg->uminit;
2311 keg->uk_fini = arg->fini;
2312 keg->uk_align = arg->align;
2313 keg->uk_reserve = 0;
2314 keg->uk_flags = arg->flags;
2317 * We use a global round-robin policy by default. Zones with
2318 * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2319 * case the iterator is never run.
2321 keg->uk_dr.dr_policy = DOMAINSET_RR();
2322 keg->uk_dr.dr_iter = 0;
2325 * The primary zone is passed to us at keg-creation time.
2328 keg->uk_name = zone->uz_name;
2330 if (arg->flags & UMA_ZONE_ZINIT)
2331 keg->uk_init = zero_init;
2333 if (arg->flags & UMA_ZONE_MALLOC)
2334 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2337 keg->uk_flags &= ~UMA_ZONE_PCPU;
2343 * Use a first-touch NUMA policy for kegs that pmap_extract() will
2344 * work on. Use round-robin for everything else.
2346 * Zones may override the default by specifying either.
2349 if ((keg->uk_flags &
2350 (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2351 keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2352 else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2353 keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2357 * If we haven't booted yet we need allocations to go through the
2358 * startup cache until the vm is ready.
2360 #ifdef UMA_MD_SMALL_ALLOC
2361 if (keg->uk_ppera == 1)
2362 keg->uk_allocf = uma_small_alloc;
2365 if (booted < BOOT_KVA)
2366 keg->uk_allocf = startup_alloc;
2367 else if (keg->uk_flags & UMA_ZONE_PCPU)
2368 keg->uk_allocf = pcpu_page_alloc;
2369 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2370 keg->uk_allocf = contig_alloc;
2372 keg->uk_allocf = page_alloc;
2373 #ifdef UMA_MD_SMALL_ALLOC
2374 if (keg->uk_ppera == 1)
2375 keg->uk_freef = uma_small_free;
2378 if (keg->uk_flags & UMA_ZONE_PCPU)
2379 keg->uk_freef = pcpu_page_free;
2381 keg->uk_freef = page_free;
2384 * Initialize keg's locks.
2386 for (i = 0; i < vm_ndomains; i++)
2387 KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2390 * If we're putting the slab header in the actual page we need to
2391 * figure out where in each page it goes. See slab_sizeof
2394 if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2397 shsize = slab_sizeof(keg->uk_ipers);
2398 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2400 * The only way the following is possible is if with our
2401 * UMA_ALIGN_PTR adjustments we are now bigger than
2402 * UMA_SLAB_SIZE. I haven't checked whether this is
2403 * mathematically possible for all cases, so we make
2406 KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2407 ("zone %s ipers %d rsize %d size %d slab won't fit",
2408 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2411 if (keg->uk_flags & UMA_ZFLAG_HASH)
2412 hash_alloc(&keg->uk_hash, 0);
2414 CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2416 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2418 rw_wlock(&uma_rwlock);
2419 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2420 rw_wunlock(&uma_rwlock);
2425 zone_kva_available(uma_zone_t zone, void *unused)
2429 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2433 if (keg->uk_allocf == startup_alloc) {
2434 /* Switch to the real allocator. */
2435 if (keg->uk_flags & UMA_ZONE_PCPU)
2436 keg->uk_allocf = pcpu_page_alloc;
2437 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2439 keg->uk_allocf = contig_alloc;
2441 keg->uk_allocf = page_alloc;
2446 zone_alloc_counters(uma_zone_t zone, void *unused)
2449 zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2450 zone->uz_frees = counter_u64_alloc(M_WAITOK);
2451 zone->uz_fails = counter_u64_alloc(M_WAITOK);
2452 zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2456 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2458 uma_zone_domain_t zdom;
2461 struct sysctl_oid *oid, *domainoid;
2462 int domains, i, cnt;
2463 static const char *nokeg = "cache zone";
2467 * Make a sysctl safe copy of the zone name by removing
2468 * any special characters and handling dups by appending
2471 if (zone->uz_namecnt != 0) {
2472 /* Count the number of decimal digits and '_' separator. */
2473 for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2475 zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2477 sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2480 zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2481 for (c = zone->uz_ctlname; *c != '\0'; c++)
2482 if (strchr("./\\ -", *c) != NULL)
2486 * Basic parameters at the root.
2488 zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2489 OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2491 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2492 "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2493 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2494 "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2495 zone, 0, sysctl_handle_uma_zone_flags, "A",
2496 "Allocator configuration flags");
2497 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2498 "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2499 "Desired per-cpu cache size");
2500 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2501 "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2502 "Maximum allowed per-cpu cache size");
2507 if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2508 domains = vm_ndomains;
2511 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2512 "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2514 if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2515 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2516 "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2517 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2518 "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2519 "Real object size with alignment");
2520 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2521 "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2522 "pages per-slab allocation");
2523 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2524 "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2525 "items available per-slab");
2526 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2527 "align", CTLFLAG_RD, &keg->uk_align, 0,
2528 "item alignment mask");
2529 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2530 "reserve", CTLFLAG_RD, &keg->uk_reserve, 0,
2531 "number of reserved items");
2532 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2533 "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2534 keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2535 "Slab utilization (100 - internal fragmentation %)");
2536 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2537 OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2538 for (i = 0; i < domains; i++) {
2539 dom = &keg->uk_domain[i];
2540 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2541 OID_AUTO, VM_DOMAIN(i)->vmd_name,
2542 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2543 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2544 "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2545 "Total pages currently allocated from VM");
2546 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2547 "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2548 "items free in the slab layer");
2551 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2552 "name", CTLFLAG_RD, nokeg, "Keg name");
2555 * Information about zone limits.
2557 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2558 "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2559 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2560 "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2561 zone, 0, sysctl_handle_uma_zone_items, "QU",
2562 "Current number of allocated items if limit is set");
2563 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2564 "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2565 "Maximum number of allocated and cached items");
2566 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2567 "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2568 "Number of threads sleeping at limit");
2569 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2570 "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2571 "Total zone limit sleeps");
2572 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2573 "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2574 "Maximum number of items in each domain's bucket cache");
2577 * Per-domain zone information.
2579 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2580 OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2581 for (i = 0; i < domains; i++) {
2582 zdom = ZDOM_GET(zone, i);
2583 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2584 OID_AUTO, VM_DOMAIN(i)->vmd_name,
2585 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2586 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2587 "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2588 "number of items in this domain");
2589 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2590 "imax", CTLFLAG_RD, &zdom->uzd_imax,
2591 "maximum item count in this period");
2592 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2593 "imin", CTLFLAG_RD, &zdom->uzd_imin,
2594 "minimum item count in this period");
2595 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2596 "wss", CTLFLAG_RD, &zdom->uzd_wss,
2597 "Working set size");
2601 * General statistics.
2603 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2604 "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2605 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2606 "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2607 zone, 1, sysctl_handle_uma_zone_cur, "I",
2608 "Current number of allocated items");
2609 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2610 "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2611 zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2612 "Total allocation calls");
2613 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2614 "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2615 zone, 0, sysctl_handle_uma_zone_frees, "QU",
2616 "Total free calls");
2617 SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2618 "fails", CTLFLAG_RD, &zone->uz_fails,
2619 "Number of allocation failures");
2620 SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2621 "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2622 "Free calls from the wrong domain");
2625 struct uma_zone_count {
2631 zone_count(uma_zone_t zone, void *arg)
2633 struct uma_zone_count *cnt;
2637 * Some zones are rapidly created with identical names and
2638 * destroyed out of order. This can lead to gaps in the count.
2639 * Use one greater than the maximum observed for this name.
2641 if (strcmp(zone->uz_name, cnt->name) == 0)
2642 cnt->count = MAX(cnt->count,
2643 zone->uz_namecnt + 1);
2647 zone_update_caches(uma_zone_t zone)
2651 for (i = 0; i <= mp_maxid; i++) {
2652 cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2653 cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2658 * Zone header ctor. This initializes all fields, locks, etc.
2660 * Arguments/Returns follow uma_ctor specifications
2661 * udata Actually uma_zctor_args
2664 zone_ctor(void *mem, int size, void *udata, int flags)
2666 struct uma_zone_count cnt;
2667 struct uma_zctor_args *arg = udata;
2668 uma_zone_domain_t zdom;
2669 uma_zone_t zone = mem;
2675 zone->uz_name = arg->name;
2676 zone->uz_ctor = arg->ctor;
2677 zone->uz_dtor = arg->dtor;
2678 zone->uz_init = NULL;
2679 zone->uz_fini = NULL;
2680 zone->uz_sleeps = 0;
2681 zone->uz_bucket_size = 0;
2682 zone->uz_bucket_size_min = 0;
2683 zone->uz_bucket_size_max = BUCKET_MAX;
2684 zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2685 zone->uz_warning = NULL;
2686 /* The domain structures follow the cpu structures. */
2687 zone->uz_bucket_max = ULONG_MAX;
2688 timevalclear(&zone->uz_ratecheck);
2690 /* Count the number of duplicate names. */
2691 cnt.name = arg->name;
2693 zone_foreach(zone_count, &cnt);
2694 zone->uz_namecnt = cnt.count;
2695 ZONE_CROSS_LOCK_INIT(zone);
2697 for (i = 0; i < vm_ndomains; i++) {
2698 zdom = ZDOM_GET(zone, i);
2699 ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2700 STAILQ_INIT(&zdom->uzd_buckets);
2703 #if defined(INVARIANTS) && !defined(KASAN)
2704 if (arg->uminit == trash_init && arg->fini == trash_fini)
2705 zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2706 #elif defined(KASAN)
2707 if ((arg->flags & (UMA_ZONE_NOFREE | UMA_ZFLAG_CACHE)) != 0)
2708 arg->flags |= UMA_ZONE_NOKASAN;
2712 * This is a pure cache zone, no kegs.
2715 KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2716 ("zone_ctor: Import specified for non-cache zone."));
2717 zone->uz_flags = arg->flags;
2718 zone->uz_size = arg->size;
2719 zone->uz_import = arg->import;
2720 zone->uz_release = arg->release;
2721 zone->uz_arg = arg->arg;
2724 * Cache zones are round-robin unless a policy is
2725 * specified because they may have incompatible
2728 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2729 zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2731 rw_wlock(&uma_rwlock);
2732 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2733 rw_wunlock(&uma_rwlock);
2738 * Use the regular zone/keg/slab allocator.
2740 zone->uz_import = zone_import;
2741 zone->uz_release = zone_release;
2742 zone->uz_arg = zone;
2745 if (arg->flags & UMA_ZONE_SECONDARY) {
2746 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2747 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2748 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2749 zone->uz_init = arg->uminit;
2750 zone->uz_fini = arg->fini;
2751 zone->uz_flags |= UMA_ZONE_SECONDARY;
2752 rw_wlock(&uma_rwlock);
2754 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2755 if (LIST_NEXT(z, uz_link) == NULL) {
2756 LIST_INSERT_AFTER(z, zone, uz_link);
2761 rw_wunlock(&uma_rwlock);
2762 } else if (keg == NULL) {
2763 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2764 arg->align, arg->flags)) == NULL)
2767 struct uma_kctor_args karg;
2770 /* We should only be here from uma_startup() */
2771 karg.size = arg->size;
2772 karg.uminit = arg->uminit;
2773 karg.fini = arg->fini;
2774 karg.align = arg->align;
2775 karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2777 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2783 /* Inherit properties from the keg. */
2785 zone->uz_size = keg->uk_size;
2786 zone->uz_flags |= (keg->uk_flags &
2787 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2790 if (booted >= BOOT_PCPU) {
2791 zone_alloc_counters(zone, NULL);
2792 if (booted >= BOOT_RUNNING)
2793 zone_alloc_sysctl(zone, NULL);
2795 zone->uz_allocs = EARLY_COUNTER;
2796 zone->uz_frees = EARLY_COUNTER;
2797 zone->uz_fails = EARLY_COUNTER;
2800 /* Caller requests a private SMR context. */
2801 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2802 zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2804 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2805 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2806 ("Invalid zone flag combination"));
2807 if (arg->flags & UMA_ZFLAG_INTERNAL)
2808 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2809 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2810 zone->uz_bucket_size = BUCKET_MAX;
2811 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2812 zone->uz_bucket_size = 0;
2814 zone->uz_bucket_size = bucket_select(zone->uz_size);
2815 zone->uz_bucket_size_min = zone->uz_bucket_size;
2816 if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2817 zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2818 zone_update_caches(zone);
2824 * Keg header dtor. This frees all data, destroys locks, frees the hash
2825 * table and removes the keg from the global list.
2827 * Arguments/Returns follow uma_dtor specifications
2831 keg_dtor(void *arg, int size, void *udata)
2834 uint32_t free, pages;
2837 keg = (uma_keg_t)arg;
2839 for (i = 0; i < vm_ndomains; i++) {
2840 free += keg->uk_domain[i].ud_free_items;
2841 pages += keg->uk_domain[i].ud_pages;
2842 KEG_LOCK_FINI(keg, i);
2845 printf("Freed UMA keg (%s) was not empty (%u items). "
2846 " Lost %u pages of memory.\n",
2847 keg->uk_name ? keg->uk_name : "",
2848 pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2850 hash_free(&keg->uk_hash);
2856 * Arguments/Returns follow uma_dtor specifications
2860 zone_dtor(void *arg, int size, void *udata)
2866 zone = (uma_zone_t)arg;
2868 sysctl_remove_oid(zone->uz_oid, 1, 1);
2870 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2873 rw_wlock(&uma_rwlock);
2874 LIST_REMOVE(zone, uz_link);
2875 rw_wunlock(&uma_rwlock);
2876 if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2878 keg->uk_reserve = 0;
2880 zone_reclaim(zone, M_WAITOK, true);
2883 * We only destroy kegs from non secondary/non cache zones.
2885 if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2887 rw_wlock(&uma_rwlock);
2888 LIST_REMOVE(keg, uk_link);
2889 rw_wunlock(&uma_rwlock);
2890 zone_free_item(kegs, keg, NULL, SKIP_NONE);
2892 counter_u64_free(zone->uz_allocs);
2893 counter_u64_free(zone->uz_frees);
2894 counter_u64_free(zone->uz_fails);
2895 counter_u64_free(zone->uz_xdomain);
2896 free(zone->uz_ctlname, M_UMA);
2897 for (i = 0; i < vm_ndomains; i++)
2898 ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2899 ZONE_CROSS_LOCK_FINI(zone);
2903 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2908 LIST_FOREACH(keg, &uma_kegs, uk_link) {
2909 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2912 LIST_FOREACH(zone, &uma_cachezones, uz_link)
2917 * Traverses every zone in the system and calls a callback
2920 * zfunc A pointer to a function which accepts a zone
2927 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2930 rw_rlock(&uma_rwlock);
2931 zone_foreach_unlocked(zfunc, arg);
2932 rw_runlock(&uma_rwlock);
2936 * Initialize the kernel memory allocator. This is done after pages can be
2937 * allocated but before general KVA is available.
2940 uma_startup1(vm_offset_t virtual_avail)
2942 struct uma_zctor_args args;
2943 size_t ksize, zsize, size;
2944 uma_keg_t primarykeg;
2949 bootstart = bootmem = virtual_avail;
2951 rw_init(&uma_rwlock, "UMA lock");
2952 sx_init(&uma_reclaim_lock, "umareclaim");
2954 ksize = sizeof(struct uma_keg) +
2955 (sizeof(struct uma_domain) * vm_ndomains);
2956 ksize = roundup(ksize, UMA_SUPER_ALIGN);
2957 zsize = sizeof(struct uma_zone) +
2958 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2959 (sizeof(struct uma_zone_domain) * vm_ndomains);
2960 zsize = roundup(zsize, UMA_SUPER_ALIGN);
2962 /* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2963 size = (zsize * 2) + ksize;
2964 for (domain = 0; domain < vm_ndomains; domain++) {
2965 m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2970 zones = (uma_zone_t)m;
2972 kegs = (uma_zone_t)m;
2974 primarykeg = (uma_keg_t)m;
2976 /* "manually" create the initial zone */
2977 memset(&args, 0, sizeof(args));
2978 args.name = "UMA Kegs";
2980 args.ctor = keg_ctor;
2981 args.dtor = keg_dtor;
2982 args.uminit = zero_init;
2984 args.keg = primarykeg;
2985 args.align = UMA_SUPER_ALIGN - 1;
2986 args.flags = UMA_ZFLAG_INTERNAL;
2987 zone_ctor(kegs, zsize, &args, M_WAITOK);
2989 args.name = "UMA Zones";
2991 args.ctor = zone_ctor;
2992 args.dtor = zone_dtor;
2993 args.uminit = zero_init;
2996 args.align = UMA_SUPER_ALIGN - 1;
2997 args.flags = UMA_ZFLAG_INTERNAL;
2998 zone_ctor(zones, zsize, &args, M_WAITOK);
3000 /* Now make zones for slab headers */
3001 slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
3002 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3003 slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
3004 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3006 hashzone = uma_zcreate("UMA Hash",
3007 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
3008 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3014 #ifndef UMA_MD_SMALL_ALLOC
3015 extern void vm_radix_reserve_kva(void);
3019 * Advertise the availability of normal kva allocations and switch to
3020 * the default back-end allocator. Marks the KVA we consumed on startup
3021 * as used in the map.
3027 if (bootstart != bootmem) {
3028 vm_map_lock(kernel_map);
3029 (void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
3030 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
3031 vm_map_unlock(kernel_map);
3034 #ifndef UMA_MD_SMALL_ALLOC
3035 /* Set up radix zone to use noobj_alloc. */
3036 vm_radix_reserve_kva();
3040 zone_foreach_unlocked(zone_kva_available, NULL);
3045 * Allocate counters as early as possible so that boot-time allocations are
3046 * accounted more precisely.
3049 uma_startup_pcpu(void *arg __unused)
3052 zone_foreach_unlocked(zone_alloc_counters, NULL);
3055 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
3058 * Finish our initialization steps.
3061 uma_startup3(void *arg __unused)
3065 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
3066 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
3067 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
3069 zone_foreach_unlocked(zone_alloc_sysctl, NULL);
3070 callout_init(&uma_callout, 1);
3071 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
3072 booted = BOOT_RUNNING;
3074 EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
3075 EVENTHANDLER_PRI_FIRST);
3077 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
3083 booted = BOOT_SHUTDOWN;
3087 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
3088 int align, uint32_t flags)
3090 struct uma_kctor_args args;
3093 args.uminit = uminit;
3095 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
3098 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
3101 /* Public functions */
3104 uma_set_align(int align)
3107 if (align != UMA_ALIGN_CACHE)
3108 uma_align_cache = align;
3113 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
3114 uma_init uminit, uma_fini fini, int align, uint32_t flags)
3117 struct uma_zctor_args args;
3120 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
3123 /* This stuff is essential for the zone ctor */
3124 memset(&args, 0, sizeof(args));
3129 args.uminit = uminit;
3131 #if defined(INVARIANTS) && !defined(KASAN)
3133 * Inject procedures which check for memory use after free if we are
3134 * allowed to scramble the memory while it is not allocated. This
3135 * requires that: UMA is actually able to access the memory, no init
3136 * or fini procedures, no dependency on the initial value of the
3137 * memory, and no (legitimate) use of the memory after free. Note,
3138 * the ctor and dtor do not need to be empty.
3140 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3141 UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3142 args.uminit = trash_init;
3143 args.fini = trash_fini;
3150 sx_slock(&uma_reclaim_lock);
3151 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3152 sx_sunlock(&uma_reclaim_lock);
3159 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3160 uma_init zinit, uma_fini zfini, uma_zone_t primary)
3162 struct uma_zctor_args args;
3166 keg = primary->uz_keg;
3167 memset(&args, 0, sizeof(args));
3169 args.size = keg->uk_size;
3172 args.uminit = zinit;
3174 args.align = keg->uk_align;
3175 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3178 sx_slock(&uma_reclaim_lock);
3179 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3180 sx_sunlock(&uma_reclaim_lock);
3187 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3188 uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3189 void *arg, int flags)
3191 struct uma_zctor_args args;
3193 memset(&args, 0, sizeof(args));
3198 args.uminit = zinit;
3200 args.import = zimport;
3201 args.release = zrelease;
3204 args.flags = flags | UMA_ZFLAG_CACHE;
3206 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3211 uma_zdestroy(uma_zone_t zone)
3215 * Large slabs are expensive to reclaim, so don't bother doing
3216 * unnecessary work if we're shutting down.
3218 if (booted == BOOT_SHUTDOWN &&
3219 zone->uz_fini == NULL && zone->uz_release == zone_release)
3221 sx_slock(&uma_reclaim_lock);
3222 zone_free_item(zones, zone, NULL, SKIP_NONE);
3223 sx_sunlock(&uma_reclaim_lock);
3227 uma_zwait(uma_zone_t zone)
3230 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3231 uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3232 else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3233 uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3235 uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3239 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3241 void *item, *pcpu_item;
3245 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3247 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3250 pcpu_item = zpcpu_base_to_offset(item);
3251 if (flags & M_ZERO) {
3253 for (i = 0; i <= mp_maxid; i++)
3254 bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3256 bzero(item, zone->uz_size);
3263 * A stub while both regular and pcpu cases are identical.
3266 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3271 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3274 /* uma_zfree_pcu_*(..., NULL) does nothing, to match free(9). */
3275 if (pcpu_item == NULL)
3278 item = zpcpu_offset_to_base(pcpu_item);
3279 uma_zfree_arg(zone, item, udata);
3282 static inline void *
3283 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3290 kasan_mark_item_valid(zone, item);
3293 skipdbg = uma_dbg_zskip(zone, item);
3294 if (!skipdbg && (uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3295 zone->uz_ctor != trash_ctor)
3296 trash_ctor(item, size, udata, flags);
3299 /* Check flags before loading ctor pointer. */
3300 if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3301 __predict_false(zone->uz_ctor != NULL) &&
3302 zone->uz_ctor(item, size, udata, flags) != 0) {
3303 counter_u64_add(zone->uz_fails, 1);
3304 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3309 uma_dbg_alloc(zone, NULL, item);
3311 if (__predict_false(flags & M_ZERO))
3312 return (memset(item, 0, size));
3318 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3319 enum zfreeskip skip)
3324 skipdbg = uma_dbg_zskip(zone, item);
3325 if (skip == SKIP_NONE && !skipdbg) {
3326 if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3327 uma_dbg_free(zone, udata, item);
3329 uma_dbg_free(zone, NULL, item);
3332 if (__predict_true(skip < SKIP_DTOR)) {
3333 if (zone->uz_dtor != NULL)
3334 zone->uz_dtor(item, size, udata);
3336 if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3337 zone->uz_dtor != trash_dtor)
3338 trash_dtor(item, size, udata);
3341 kasan_mark_item_invalid(zone, item);
3346 item_domain(void *item)
3350 domain = vm_phys_domain(vtophys(item));
3351 KASSERT(domain >= 0 && domain < vm_ndomains,
3352 ("%s: unknown domain for item %p", __func__, item));
3357 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3358 #define UMA_ZALLOC_DEBUG
3360 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3366 if (flags & M_WAITOK) {
3367 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3368 "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3373 KASSERT((flags & M_EXEC) == 0,
3374 ("uma_zalloc_debug: called with M_EXEC"));
3375 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3376 ("uma_zalloc_debug: called within spinlock or critical section"));
3377 KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3378 ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3381 #ifdef DEBUG_MEMGUARD
3382 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3384 item = memguard_alloc(zone->uz_size, flags);
3386 error = EJUSTRETURN;
3387 if (zone->uz_init != NULL &&
3388 zone->uz_init(item, zone->uz_size, flags) != 0) {
3392 if (zone->uz_ctor != NULL &&
3393 zone->uz_ctor(item, zone->uz_size, udata,
3395 counter_u64_add(zone->uz_fails, 1);
3396 zone->uz_fini(item, zone->uz_size);
3403 /* This is unfortunate but should not be fatal. */
3410 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3412 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3413 ("uma_zfree_debug: called with spinlock or critical section held"));
3415 #ifdef DEBUG_MEMGUARD
3416 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3417 if (zone->uz_dtor != NULL)
3418 zone->uz_dtor(item, zone->uz_size, udata);
3419 if (zone->uz_fini != NULL)
3420 zone->uz_fini(item, zone->uz_size);
3421 memguard_free(item);
3422 return (EJUSTRETURN);
3429 static inline void *
3430 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3431 void *udata, int flags)
3436 item = cache_bucket_pop(cache, bucket);
3437 size = cache_uz_size(cache);
3438 uz_flags = cache_uz_flags(cache);
3440 return (item_ctor(zone, uz_flags, size, udata, flags, item));
3443 static __noinline void *
3444 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3446 uma_cache_bucket_t bucket;
3449 while (cache_alloc(zone, cache, udata, flags)) {
3450 cache = &zone->uz_cpu[curcpu];
3451 bucket = &cache->uc_allocbucket;
3452 if (__predict_false(bucket->ucb_cnt == 0))
3454 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3459 * We can not get a bucket so try to return a single item.
3461 if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3462 domain = PCPU_GET(domain);
3464 domain = UMA_ANYDOMAIN;
3465 return (zone_alloc_item(zone, udata, domain, flags));
3470 uma_zalloc_smr(uma_zone_t zone, int flags)
3472 uma_cache_bucket_t bucket;
3475 #ifdef UMA_ZALLOC_DEBUG
3478 KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3479 ("uma_zalloc_arg: called with non-SMR zone."));
3480 if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3485 cache = &zone->uz_cpu[curcpu];
3486 bucket = &cache->uc_allocbucket;
3487 if (__predict_false(bucket->ucb_cnt == 0))
3488 return (cache_alloc_retry(zone, cache, NULL, flags));
3489 return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3494 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3496 uma_cache_bucket_t bucket;
3499 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3500 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3502 /* This is the fast path allocation */
3503 CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3506 #ifdef UMA_ZALLOC_DEBUG
3509 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3510 ("uma_zalloc_arg: called with SMR zone."));
3511 if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3516 * If possible, allocate from the per-CPU cache. There are two
3517 * requirements for safe access to the per-CPU cache: (1) the thread
3518 * accessing the cache must not be preempted or yield during access,
3519 * and (2) the thread must not migrate CPUs without switching which
3520 * cache it accesses. We rely on a critical section to prevent
3521 * preemption and migration. We release the critical section in
3522 * order to acquire the zone mutex if we are unable to allocate from
3523 * the current cache; when we re-acquire the critical section, we
3524 * must detect and handle migration if it has occurred.
3527 cache = &zone->uz_cpu[curcpu];
3528 bucket = &cache->uc_allocbucket;
3529 if (__predict_false(bucket->ucb_cnt == 0))
3530 return (cache_alloc_retry(zone, cache, udata, flags));
3531 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3535 * Replenish an alloc bucket and possibly restore an old one. Called in
3536 * a critical section. Returns in a critical section.
3538 * A false return value indicates an allocation failure.
3539 * A true return value indicates success and the caller should retry.
3541 static __noinline bool
3542 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3544 uma_bucket_t bucket;
3545 int curdomain, domain;
3548 CRITICAL_ASSERT(curthread);
3551 * If we have run out of items in our alloc bucket see
3552 * if we can switch with the free bucket.
3554 * SMR Zones can't re-use the free bucket until the sequence has
3557 if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3558 cache->uc_freebucket.ucb_cnt != 0) {
3559 cache_bucket_swap(&cache->uc_freebucket,
3560 &cache->uc_allocbucket);
3565 * Discard any empty allocation bucket while we hold no locks.
3567 bucket = cache_bucket_unload_alloc(cache);
3570 if (bucket != NULL) {
3571 KASSERT(bucket->ub_cnt == 0,
3572 ("cache_alloc: Entered with non-empty alloc bucket."));
3573 bucket_free(zone, bucket, udata);
3577 * Attempt to retrieve the item from the per-CPU cache has failed, so
3578 * we must go back to the zone. This requires the zdom lock, so we
3579 * must drop the critical section, then re-acquire it when we go back
3580 * to the cache. Since the critical section is released, we may be
3581 * preempted or migrate. As such, make sure not to maintain any
3582 * thread-local state specific to the cache from prior to releasing
3583 * the critical section.
3585 domain = PCPU_GET(domain);
3586 if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3587 VM_DOMAIN_EMPTY(domain))
3588 domain = zone_domain_highest(zone, domain);
3589 bucket = cache_fetch_bucket(zone, cache, domain);
3590 if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3591 bucket = zone_alloc_bucket(zone, udata, domain, flags);
3597 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3598 zone->uz_name, zone, bucket);
3599 if (bucket == NULL) {
3605 * See if we lost the race or were migrated. Cache the
3606 * initialized bucket to make this less likely or claim
3607 * the memory directly.
3610 cache = &zone->uz_cpu[curcpu];
3611 if (cache->uc_allocbucket.ucb_bucket == NULL &&
3612 ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3613 (curdomain = PCPU_GET(domain)) == domain ||
3614 VM_DOMAIN_EMPTY(curdomain))) {
3616 atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3618 cache_bucket_load_alloc(cache, bucket);
3623 * We lost the race, release this bucket and start over.
3626 zone_put_bucket(zone, domain, bucket, udata, false);
3633 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3636 uma_bucket_t bucket;
3637 uma_zone_domain_t zdom;
3641 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3642 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3644 /* This is the fast path allocation */
3645 CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3646 zone->uz_name, zone, domain, flags);
3648 if (flags & M_WAITOK) {
3649 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3650 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3652 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3653 ("uma_zalloc_domain: called with spinlock or critical section held"));
3654 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3655 ("uma_zalloc_domain: called with SMR zone."));
3657 KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3658 ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3660 if (vm_ndomains == 1)
3661 return (uma_zalloc_arg(zone, udata, flags));
3664 * Try to allocate from the bucket cache before falling back to the keg.
3665 * We could try harder and attempt to allocate from per-CPU caches or
3666 * the per-domain cross-domain buckets, but the complexity is probably
3667 * not worth it. It is more important that frees of previous
3668 * cross-domain allocations do not blow up the cache.
3670 zdom = zone_domain_lock(zone, domain);
3671 if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3672 item = bucket->ub_bucket[bucket->ub_cnt - 1];
3674 bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3677 zone_put_bucket(zone, domain, bucket, udata, true);
3678 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3681 KASSERT(item_domain(item) == domain,
3682 ("%s: bucket cache item %p from wrong domain",
3684 counter_u64_add(zone->uz_allocs, 1);
3689 return (zone_alloc_item(zone, udata, domain, flags));
3691 return (uma_zalloc_arg(zone, udata, flags));
3696 * Find a slab with some space. Prefer slabs that are partially used over those
3697 * that are totally full. This helps to reduce fragmentation.
3699 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
3703 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3709 KASSERT(domain >= 0 && domain < vm_ndomains,
3710 ("keg_first_slab: domain %d out of range", domain));
3711 KEG_LOCK_ASSERT(keg, domain);
3716 dom = &keg->uk_domain[domain];
3717 if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3719 if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3720 LIST_REMOVE(slab, us_link);
3721 dom->ud_free_slabs--;
3722 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3726 domain = (domain + 1) % vm_ndomains;
3727 } while (domain != start);
3733 * Fetch an existing slab from a free or partial list. Returns with the
3734 * keg domain lock held if a slab was found or unlocked if not.
3737 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3742 /* HASH has a single free list. */
3743 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3746 KEG_LOCK(keg, domain);
3747 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3748 if (keg->uk_domain[domain].ud_free_items <= reserve ||
3749 (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3750 KEG_UNLOCK(keg, domain);
3757 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3759 struct vm_domainset_iter di;
3766 * Use the keg's policy if upper layers haven't already specified a
3767 * domain (as happens with first-touch zones).
3769 * To avoid races we run the iterator with the keg lock held, but that
3770 * means that we cannot allow the vm_domainset layer to sleep. Thus,
3771 * clear M_WAITOK and handle low memory conditions locally.
3773 rr = rdomain == UMA_ANYDOMAIN;
3775 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3776 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3784 slab = keg_fetch_free_slab(keg, domain, rr, flags);
3789 * M_NOVM means don't ask at all!
3794 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3797 if (!rr && (flags & M_WAITOK) == 0)
3799 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3800 if ((flags & M_WAITOK) != 0) {
3801 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3809 * We might not have been able to get a slab but another cpu
3810 * could have while we were unlocked. Check again before we
3813 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3820 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3826 KEG_LOCK_ASSERT(keg, slab->us_domain);
3828 dom = &keg->uk_domain[slab->us_domain];
3829 freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3830 BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3831 item = slab_item(slab, keg, freei);
3832 slab->us_freecount--;
3833 dom->ud_free_items--;
3836 * Move this slab to the full list. It must be on the partial list, so
3837 * we do not need to update the free slab count. In particular,
3838 * keg_fetch_slab() always returns slabs on the partial list.
3840 if (slab->us_freecount == 0) {
3841 LIST_REMOVE(slab, us_link);
3842 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3849 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3863 /* Try to keep the buckets totally full */
3864 for (i = 0; i < max; ) {
3865 if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3868 stripe = howmany(max, vm_ndomains);
3870 dom = &keg->uk_domain[slab->us_domain];
3872 bucket[i++] = slab_alloc_item(keg, slab);
3873 if (dom->ud_free_items <= keg->uk_reserve) {
3875 * Avoid depleting the reserve after a
3876 * successful item allocation, even if
3877 * M_USE_RESERVE is specified.
3879 KEG_UNLOCK(keg, slab->us_domain);
3884 * If the zone is striped we pick a new slab for every
3885 * N allocations. Eliminating this conditional will
3886 * instead pick a new domain for each bucket rather
3887 * than stripe within each bucket. The current option
3888 * produces more fragmentation and requires more cpu
3889 * time but yields better distribution.
3891 if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3892 vm_ndomains > 1 && --stripe == 0)
3895 } while (slab->us_freecount != 0 && i < max);
3896 KEG_UNLOCK(keg, slab->us_domain);
3898 /* Don't block if we allocated any successfully. */
3907 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3909 uint64_t old, new, total, max;
3912 * The hard case. We're going to sleep because there were existing
3913 * sleepers or because we ran out of items. This routine enforces
3914 * fairness by keeping fifo order.
3916 * First release our ill gotten gains and make some noise.
3919 zone_free_limit(zone, count);
3920 zone_log_warning(zone);
3921 zone_maxaction(zone);
3922 if (flags & M_NOWAIT)
3926 * We need to allocate an item or set ourself as a sleeper
3927 * while the sleepq lock is held to avoid wakeup races. This
3928 * is essentially a home rolled semaphore.
3930 sleepq_lock(&zone->uz_max_items);
3931 old = zone->uz_items;
3933 MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3934 /* Cache the max since we will evaluate twice. */
3935 max = zone->uz_max_items;
3936 if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3937 UZ_ITEMS_COUNT(old) >= max)
3938 new = old + UZ_ITEMS_SLEEPER;
3940 new = old + MIN(count, max - old);
3941 } while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3943 /* We may have successfully allocated under the sleepq lock. */
3944 if (UZ_ITEMS_SLEEPERS(new) == 0) {
3945 sleepq_release(&zone->uz_max_items);
3950 * This is in a different cacheline from uz_items so that we
3951 * don't constantly invalidate the fastpath cacheline when we
3952 * adjust item counts. This could be limited to toggling on
3955 atomic_add_32(&zone->uz_sleepers, 1);
3956 atomic_add_64(&zone->uz_sleeps, 1);
3959 * We have added ourselves as a sleeper. The sleepq lock
3960 * protects us from wakeup races. Sleep now and then retry.
3962 sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3963 sleepq_wait(&zone->uz_max_items, PVM);
3966 * After wakeup, remove ourselves as a sleeper and try
3967 * again. We no longer have the sleepq lock for protection.
3969 * Subract ourselves as a sleeper while attempting to add
3972 atomic_subtract_32(&zone->uz_sleepers, 1);
3973 old = atomic_fetchadd_64(&zone->uz_items,
3974 -(UZ_ITEMS_SLEEPER - count));
3975 /* We're no longer a sleeper. */
3976 old -= UZ_ITEMS_SLEEPER;
3979 * If we're still at the limit, restart. Notably do not
3980 * block on other sleepers. Cache the max value to protect
3981 * against changes via sysctl.
3983 total = UZ_ITEMS_COUNT(old);
3984 max = zone->uz_max_items;
3987 /* Truncate if necessary, otherwise wake other sleepers. */
3988 if (total + count > max) {
3989 zone_free_limit(zone, total + count - max);
3990 count = max - total;
3991 } else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
3992 wakeup_one(&zone->uz_max_items);
3999 * Allocate 'count' items from our max_items limit. Returns the number
4000 * available. If M_NOWAIT is not specified it will sleep until at least
4001 * one item can be allocated.
4004 zone_alloc_limit(uma_zone_t zone, int count, int flags)
4009 max = zone->uz_max_items;
4013 * We expect normal allocations to succeed with a simple
4016 old = atomic_fetchadd_64(&zone->uz_items, count);
4017 if (__predict_true(old + count <= max))
4021 * If we had some items and no sleepers just return the
4022 * truncated value. We have to release the excess space
4023 * though because that may wake sleepers who weren't woken
4024 * because we were temporarily over the limit.
4027 zone_free_limit(zone, (old + count) - max);
4030 return (zone_alloc_limit_hard(zone, count, flags));
4034 * Free a number of items back to the limit.
4037 zone_free_limit(uma_zone_t zone, int count)
4044 * In the common case we either have no sleepers or
4045 * are still over the limit and can just return.
4047 old = atomic_fetchadd_64(&zone->uz_items, -count);
4048 if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
4049 UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
4053 * Moderate the rate of wakeups. Sleepers will continue
4054 * to generate wakeups if necessary.
4056 wakeup_one(&zone->uz_max_items);
4060 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
4062 uma_bucket_t bucket;
4063 int error, maxbucket, cnt;
4065 CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
4068 /* Avoid allocs targeting empty domains. */
4069 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4070 domain = UMA_ANYDOMAIN;
4071 else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4072 domain = UMA_ANYDOMAIN;
4074 if (zone->uz_max_items > 0)
4075 maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
4078 maxbucket = zone->uz_bucket_size;
4082 /* Don't wait for buckets, preserve caller's NOVM setting. */
4083 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
4084 if (bucket == NULL) {
4089 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
4090 MIN(maxbucket, bucket->ub_entries), domain, flags);
4093 * Initialize the memory if necessary.
4095 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
4098 for (i = 0; i < bucket->ub_cnt; i++) {
4099 kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
4100 error = zone->uz_init(bucket->ub_bucket[i],
4101 zone->uz_size, flags);
4102 kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
4108 * If we couldn't initialize the whole bucket, put the
4109 * rest back onto the freelist.
4111 if (i != bucket->ub_cnt) {
4112 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
4113 bucket->ub_cnt - i);
4115 bzero(&bucket->ub_bucket[i],
4116 sizeof(void *) * (bucket->ub_cnt - i));
4122 cnt = bucket->ub_cnt;
4123 if (bucket->ub_cnt == 0) {
4124 bucket_free(zone, bucket, udata);
4125 counter_u64_add(zone->uz_fails, 1);
4129 if (zone->uz_max_items > 0 && cnt < maxbucket)
4130 zone_free_limit(zone, maxbucket - cnt);
4136 * Allocates a single item from a zone.
4139 * zone The zone to alloc for.
4140 * udata The data to be passed to the constructor.
4141 * domain The domain to allocate from or UMA_ANYDOMAIN.
4142 * flags M_WAITOK, M_NOWAIT, M_ZERO.
4145 * NULL if there is no memory and M_NOWAIT is set
4146 * An item if successful
4150 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4154 if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4155 counter_u64_add(zone->uz_fails, 1);
4159 /* Avoid allocs targeting empty domains. */
4160 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4161 domain = UMA_ANYDOMAIN;
4163 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4167 * We have to call both the zone's init (not the keg's init)
4168 * and the zone's ctor. This is because the item is going from
4169 * a keg slab directly to the user, and the user is expecting it
4170 * to be both zone-init'd as well as zone-ctor'd.
4172 if (zone->uz_init != NULL) {
4175 kasan_mark_item_valid(zone, item);
4176 error = zone->uz_init(item, zone->uz_size, flags);
4177 kasan_mark_item_invalid(zone, item);
4179 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4183 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4188 counter_u64_add(zone->uz_allocs, 1);
4189 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4190 zone->uz_name, zone);
4195 counter_u64_add(zone->uz_fails, 1);
4197 if (zone->uz_max_items > 0)
4198 zone_free_limit(zone, 1);
4199 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4200 zone->uz_name, zone);
4207 uma_zfree_smr(uma_zone_t zone, void *item)
4210 uma_cache_bucket_t bucket;
4211 int itemdomain, uz_flags;
4213 #ifdef UMA_ZALLOC_DEBUG
4214 KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4215 ("uma_zfree_smr: called with non-SMR zone."));
4216 KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4217 SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4218 if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4221 cache = &zone->uz_cpu[curcpu];
4222 uz_flags = cache_uz_flags(cache);
4225 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4226 itemdomain = item_domain(item);
4230 cache = &zone->uz_cpu[curcpu];
4231 /* SMR Zones must free to the free bucket. */
4232 bucket = &cache->uc_freebucket;
4234 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4235 PCPU_GET(domain) != itemdomain) {
4236 bucket = &cache->uc_crossbucket;
4239 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4240 cache_bucket_push(cache, bucket, item);
4244 } while (cache_free(zone, cache, NULL, item, itemdomain));
4248 * If nothing else caught this, we'll just do an internal free.
4250 zone_free_item(zone, item, NULL, SKIP_NONE);
4255 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4258 uma_cache_bucket_t bucket;
4259 int itemdomain, uz_flags;
4261 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4262 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4264 CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4266 #ifdef UMA_ZALLOC_DEBUG
4267 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4268 ("uma_zfree_arg: called with SMR zone."));
4269 if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4272 /* uma_zfree(..., NULL) does nothing, to match free(9). */
4277 * We are accessing the per-cpu cache without a critical section to
4278 * fetch size and flags. This is acceptable, if we are preempted we
4279 * will simply read another cpu's line.
4281 cache = &zone->uz_cpu[curcpu];
4282 uz_flags = cache_uz_flags(cache);
4283 if (UMA_ALWAYS_CTORDTOR ||
4284 __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4285 item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4288 * The race here is acceptable. If we miss it we'll just have to wait
4289 * a little longer for the limits to be reset.
4291 if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4292 if (atomic_load_32(&zone->uz_sleepers) > 0)
4297 * If possible, free to the per-CPU cache. There are two
4298 * requirements for safe access to the per-CPU cache: (1) the thread
4299 * accessing the cache must not be preempted or yield during access,
4300 * and (2) the thread must not migrate CPUs without switching which
4301 * cache it accesses. We rely on a critical section to prevent
4302 * preemption and migration. We release the critical section in
4303 * order to acquire the zone mutex if we are unable to free to the
4304 * current cache; when we re-acquire the critical section, we must
4305 * detect and handle migration if it has occurred.
4309 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4310 itemdomain = item_domain(item);
4314 cache = &zone->uz_cpu[curcpu];
4316 * Try to free into the allocbucket first to give LIFO
4317 * ordering for cache-hot datastructures. Spill over
4318 * into the freebucket if necessary. Alloc will swap
4319 * them if one runs dry.
4321 bucket = &cache->uc_allocbucket;
4323 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4324 PCPU_GET(domain) != itemdomain) {
4325 bucket = &cache->uc_crossbucket;
4328 if (bucket->ucb_cnt == bucket->ucb_entries &&
4329 cache->uc_freebucket.ucb_cnt <
4330 cache->uc_freebucket.ucb_entries)
4331 cache_bucket_swap(&cache->uc_freebucket,
4332 &cache->uc_allocbucket);
4333 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4334 cache_bucket_push(cache, bucket, item);
4338 } while (cache_free(zone, cache, udata, item, itemdomain));
4342 * If nothing else caught this, we'll just do an internal free.
4345 zone_free_item(zone, item, udata, SKIP_DTOR);
4350 * sort crossdomain free buckets to domain correct buckets and cache
4354 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4356 struct uma_bucketlist emptybuckets, fullbuckets;
4357 uma_zone_domain_t zdom;
4364 "uma_zfree: zone %s(%p) draining cross bucket %p",
4365 zone->uz_name, zone, bucket);
4368 * It is possible for buckets to arrive here out of order so we fetch
4369 * the current smr seq rather than accepting the bucket's.
4371 seq = SMR_SEQ_INVALID;
4372 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4373 seq = smr_advance(zone->uz_smr);
4376 * To avoid having ndomain * ndomain buckets for sorting we have a
4377 * lock on the current crossfree bucket. A full matrix with
4378 * per-domain locking could be used if necessary.
4380 STAILQ_INIT(&emptybuckets);
4381 STAILQ_INIT(&fullbuckets);
4382 ZONE_CROSS_LOCK(zone);
4383 for (; bucket->ub_cnt > 0; bucket->ub_cnt--) {
4384 item = bucket->ub_bucket[bucket->ub_cnt - 1];
4385 domain = item_domain(item);
4386 zdom = ZDOM_GET(zone, domain);
4387 if (zdom->uzd_cross == NULL) {
4388 if ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4389 STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4390 zdom->uzd_cross = b;
4393 * Avoid allocating a bucket with the cross lock
4394 * held, since allocation can trigger a
4395 * cross-domain free and bucket zones may
4396 * allocate from each other.
4398 ZONE_CROSS_UNLOCK(zone);
4399 b = bucket_alloc(zone, udata, M_NOWAIT);
4402 ZONE_CROSS_LOCK(zone);
4403 if (zdom->uzd_cross != NULL) {
4404 STAILQ_INSERT_HEAD(&emptybuckets, b,
4407 zdom->uzd_cross = b;
4411 b = zdom->uzd_cross;
4412 b->ub_bucket[b->ub_cnt++] = item;
4414 if (b->ub_cnt == b->ub_entries) {
4415 STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4416 if ((b = STAILQ_FIRST(&emptybuckets)) != NULL)
4417 STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4418 zdom->uzd_cross = b;
4421 ZONE_CROSS_UNLOCK(zone);
4423 if (bucket->ub_cnt == 0)
4424 bucket->ub_seq = SMR_SEQ_INVALID;
4425 bucket_free(zone, bucket, udata);
4427 while ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4428 STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4429 bucket_free(zone, b, udata);
4431 while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4432 STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4433 domain = item_domain(b->ub_bucket[0]);
4434 zone_put_bucket(zone, domain, b, udata, true);
4440 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4441 int itemdomain, bool ws)
4446 * Buckets coming from the wrong domain will be entirely for the
4447 * only other domain on two domain systems. In this case we can
4448 * simply cache them. Otherwise we need to sort them back to
4451 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4452 vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4453 zone_free_cross(zone, bucket, udata);
4459 * Attempt to save the bucket in the zone's domain bucket cache.
4462 "uma_zfree: zone %s(%p) putting bucket %p on free list",
4463 zone->uz_name, zone, bucket);
4464 /* ub_cnt is pointing to the last free item */
4465 if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4466 itemdomain = zone_domain_lowest(zone, itemdomain);
4467 zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4471 * Populate a free or cross bucket for the current cpu cache. Free any
4472 * existing full bucket either to the zone cache or back to the slab layer.
4474 * Enters and returns in a critical section. false return indicates that
4475 * we can not satisfy this free in the cache layer. true indicates that
4476 * the caller should retry.
4478 static __noinline bool
4479 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4482 uma_cache_bucket_t cbucket;
4483 uma_bucket_t newbucket, bucket;
4485 CRITICAL_ASSERT(curthread);
4487 if (zone->uz_bucket_size == 0)
4490 cache = &zone->uz_cpu[curcpu];
4494 * FIRSTTOUCH domains need to free to the correct zdom. When
4495 * enabled this is the zdom of the item. The bucket is the
4496 * cross bucket if the current domain and itemdomain do not match.
4498 cbucket = &cache->uc_freebucket;
4500 if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4501 if (PCPU_GET(domain) != itemdomain) {
4502 cbucket = &cache->uc_crossbucket;
4503 if (cbucket->ucb_cnt != 0)
4504 counter_u64_add(zone->uz_xdomain,
4509 bucket = cache_bucket_unload(cbucket);
4510 KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4511 ("cache_free: Entered with non-full free bucket."));
4513 /* We are no longer associated with this CPU. */
4517 * Don't let SMR zones operate without a free bucket. Force
4518 * a synchronize and re-use this one. We will only degrade
4519 * to a synchronize every bucket_size items rather than every
4520 * item if we fail to allocate a bucket.
4522 if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4524 bucket->ub_seq = smr_advance(zone->uz_smr);
4525 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4526 if (newbucket == NULL && bucket != NULL) {
4527 bucket_drain(zone, bucket);
4531 } else if (!bucketdisable)
4532 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4535 zone_free_bucket(zone, bucket, udata, itemdomain, true);
4538 if ((bucket = newbucket) == NULL)
4540 cache = &zone->uz_cpu[curcpu];
4543 * Check to see if we should be populating the cross bucket. If it
4544 * is already populated we will fall through and attempt to populate
4547 if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4548 if (PCPU_GET(domain) != itemdomain &&
4549 cache->uc_crossbucket.ucb_bucket == NULL) {
4550 cache_bucket_load_cross(cache, bucket);
4556 * We may have lost the race to fill the bucket or switched CPUs.
4558 if (cache->uc_freebucket.ucb_bucket != NULL) {
4560 bucket_free(zone, bucket, udata);
4563 cache_bucket_load_free(cache, bucket);
4569 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4576 KEG_LOCK_ASSERT(keg, slab->us_domain);
4578 /* Do we need to remove from any lists? */
4579 dom = &keg->uk_domain[slab->us_domain];
4580 if (slab->us_freecount + 1 == keg->uk_ipers) {
4581 LIST_REMOVE(slab, us_link);
4582 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4583 dom->ud_free_slabs++;
4584 } else if (slab->us_freecount == 0) {
4585 LIST_REMOVE(slab, us_link);
4586 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4589 /* Slab management. */
4590 freei = slab_item_index(slab, keg, item);
4591 BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4592 slab->us_freecount++;
4594 /* Keg statistics. */
4595 dom->ud_free_items++;
4599 zone_release(void *arg, void **bucket, int cnt)
4612 if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4613 lock = KEG_LOCK(keg, 0);
4614 for (i = 0; i < cnt; i++) {
4616 if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4617 slab = vtoslab((vm_offset_t)item);
4619 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4620 if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4621 slab = hash_sfind(&keg->uk_hash, mem);
4623 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4625 if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4628 lock = KEG_LOCK(keg, slab->us_domain);
4630 slab_free_item(zone, slab, item);
4637 * Frees a single item to any zone.
4640 * zone The zone to free to
4641 * item The item we're freeing
4642 * udata User supplied data for the dtor
4643 * skip Skip dtors and finis
4645 static __noinline void
4646 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4650 * If a free is sent directly to an SMR zone we have to
4651 * synchronize immediately because the item can instantly
4652 * be reallocated. This should only happen in degenerate
4653 * cases when no memory is available for per-cpu caches.
4655 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4656 smr_synchronize(zone->uz_smr);
4658 item_dtor(zone, item, zone->uz_size, udata, skip);
4660 if (skip < SKIP_FINI && zone->uz_fini) {
4661 kasan_mark_item_valid(zone, item);
4662 zone->uz_fini(item, zone->uz_size);
4663 kasan_mark_item_invalid(zone, item);
4666 zone->uz_release(zone->uz_arg, &item, 1);
4668 if (skip & SKIP_CNT)
4671 counter_u64_add(zone->uz_frees, 1);
4673 if (zone->uz_max_items > 0)
4674 zone_free_limit(zone, 1);
4679 uma_zone_set_max(uma_zone_t zone, int nitems)
4683 * If the limit is small, we may need to constrain the maximum per-CPU
4684 * cache size, or disable caching entirely.
4686 uma_zone_set_maxcache(zone, nitems);
4689 * XXX This can misbehave if the zone has any allocations with
4690 * no limit and a limit is imposed. There is currently no
4691 * way to clear a limit.
4694 zone->uz_max_items = nitems;
4695 zone->uz_flags |= UMA_ZFLAG_LIMIT;
4696 zone_update_caches(zone);
4697 /* We may need to wake waiters. */
4698 wakeup(&zone->uz_max_items);
4706 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4708 int bpcpu, bpdom, bsize, nb;
4713 * Compute a lower bound on the number of items that may be cached in
4714 * the zone. Each CPU gets at least two buckets, and for cross-domain
4715 * frees we use an additional bucket per CPU and per domain. Select the
4716 * largest bucket size that does not exceed half of the requested limit,
4717 * with the left over space given to the full bucket cache.
4722 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 && vm_ndomains > 1) {
4727 nb = bpcpu * mp_ncpus + bpdom * vm_ndomains;
4728 bsize = nitems / nb / 2;
4729 if (bsize > BUCKET_MAX)
4731 else if (bsize == 0 && nitems / nb > 0)
4733 zone->uz_bucket_size_max = zone->uz_bucket_size = bsize;
4734 if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4735 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4736 zone->uz_bucket_max = nitems - nb * bsize;
4742 uma_zone_get_max(uma_zone_t zone)
4746 nitems = atomic_load_64(&zone->uz_max_items);
4753 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4756 ZONE_ASSERT_COLD(zone);
4757 zone->uz_warning = warning;
4762 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4765 ZONE_ASSERT_COLD(zone);
4766 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4771 uma_zone_get_cur(uma_zone_t zone)
4777 if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4778 nitems = counter_u64_fetch(zone->uz_allocs) -
4779 counter_u64_fetch(zone->uz_frees);
4781 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4782 atomic_load_64(&zone->uz_cpu[i].uc_frees);
4784 return (nitems < 0 ? 0 : nitems);
4788 uma_zone_get_allocs(uma_zone_t zone)
4794 if (zone->uz_allocs != EARLY_COUNTER)
4795 nitems = counter_u64_fetch(zone->uz_allocs);
4797 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4803 uma_zone_get_frees(uma_zone_t zone)
4809 if (zone->uz_frees != EARLY_COUNTER)
4810 nitems = counter_u64_fetch(zone->uz_frees);
4812 nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4818 /* Used only for KEG_ASSERT_COLD(). */
4820 uma_keg_get_allocs(uma_keg_t keg)
4826 LIST_FOREACH(z, &keg->uk_zones, uz_link)
4827 nitems += uma_zone_get_allocs(z);
4835 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4840 KEG_ASSERT_COLD(keg);
4841 keg->uk_init = uminit;
4846 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4851 KEG_ASSERT_COLD(keg);
4852 keg->uk_fini = fini;
4857 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4860 ZONE_ASSERT_COLD(zone);
4861 zone->uz_init = zinit;
4866 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4869 ZONE_ASSERT_COLD(zone);
4870 zone->uz_fini = zfini;
4875 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4880 KEG_ASSERT_COLD(keg);
4881 keg->uk_freef = freef;
4886 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4891 KEG_ASSERT_COLD(keg);
4892 keg->uk_allocf = allocf;
4897 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4900 ZONE_ASSERT_COLD(zone);
4902 KASSERT(smr != NULL, ("Got NULL smr"));
4903 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4904 ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4905 zone->uz_flags |= UMA_ZONE_SMR;
4907 zone_update_caches(zone);
4911 uma_zone_get_smr(uma_zone_t zone)
4914 return (zone->uz_smr);
4919 uma_zone_reserve(uma_zone_t zone, int items)
4924 KEG_ASSERT_COLD(keg);
4925 keg->uk_reserve = items;
4930 uma_zone_reserve_kva(uma_zone_t zone, int count)
4937 KEG_ASSERT_COLD(keg);
4938 ZONE_ASSERT_COLD(zone);
4940 pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4942 #ifdef UMA_MD_SMALL_ALLOC
4943 if (keg->uk_ppera > 1) {
4947 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4953 MPASS(keg->uk_kva == 0);
4956 zone->uz_max_items = pages * keg->uk_ipers;
4957 #ifdef UMA_MD_SMALL_ALLOC
4958 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4960 keg->uk_allocf = noobj_alloc;
4962 keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4963 zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4964 zone_update_caches(zone);
4971 uma_prealloc(uma_zone_t zone, int items)
4973 struct vm_domainset_iter di;
4977 int aflags, domain, slabs;
4980 slabs = howmany(items, keg->uk_ipers);
4981 while (slabs-- > 0) {
4983 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
4986 slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
4989 dom = &keg->uk_domain[slab->us_domain];
4991 * keg_alloc_slab() always returns a slab on the
4994 LIST_REMOVE(slab, us_link);
4995 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
4997 dom->ud_free_slabs++;
4998 KEG_UNLOCK(keg, slab->us_domain);
5001 if (vm_domainset_iter_policy(&di, &domain) != 0)
5002 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
5008 * Returns a snapshot of memory consumption in bytes.
5011 uma_zone_memory(uma_zone_t zone)
5017 if (zone->uz_flags & UMA_ZFLAG_CACHE) {
5018 for (i = 0; i < vm_ndomains; i++)
5019 sz += ZDOM_GET(zone, i)->uzd_nitems;
5020 return (sz * zone->uz_size);
5022 for (i = 0; i < vm_ndomains; i++)
5023 sz += zone->uz_keg->uk_domain[i].ud_pages;
5025 return (sz * PAGE_SIZE);
5030 uma_reclaim(int req)
5033 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
5034 sx_xlock(&uma_reclaim_lock);
5038 case UMA_RECLAIM_TRIM:
5039 zone_foreach(zone_trim, NULL);
5041 case UMA_RECLAIM_DRAIN:
5042 case UMA_RECLAIM_DRAIN_CPU:
5043 zone_foreach(zone_drain, NULL);
5044 if (req == UMA_RECLAIM_DRAIN_CPU) {
5045 pcpu_cache_drain_safe(NULL);
5046 zone_foreach(zone_drain, NULL);
5050 panic("unhandled reclamation request %d", req);
5054 * Some slabs may have been freed but this zone will be visited early
5055 * we visit again so that we can free pages that are empty once other
5056 * zones are drained. We have to do the same for buckets.
5058 zone_drain(slabzones[0], NULL);
5059 zone_drain(slabzones[1], NULL);
5060 bucket_zone_drain();
5061 sx_xunlock(&uma_reclaim_lock);
5064 static volatile int uma_reclaim_needed;
5067 uma_reclaim_wakeup(void)
5070 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
5071 wakeup(uma_reclaim);
5075 uma_reclaim_worker(void *arg __unused)
5079 sx_xlock(&uma_reclaim_lock);
5080 while (atomic_load_int(&uma_reclaim_needed) == 0)
5081 sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
5083 sx_xunlock(&uma_reclaim_lock);
5084 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
5085 uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
5086 atomic_store_int(&uma_reclaim_needed, 0);
5087 /* Don't fire more than once per-second. */
5088 pause("umarclslp", hz);
5094 uma_zone_reclaim(uma_zone_t zone, int req)
5098 case UMA_RECLAIM_TRIM:
5099 zone_trim(zone, NULL);
5101 case UMA_RECLAIM_DRAIN:
5102 zone_drain(zone, NULL);
5104 case UMA_RECLAIM_DRAIN_CPU:
5105 pcpu_cache_drain_safe(zone);
5106 zone_drain(zone, NULL);
5109 panic("unhandled reclamation request %d", req);
5115 uma_zone_exhausted(uma_zone_t zone)
5118 return (atomic_load_32(&zone->uz_sleepers) > 0);
5125 return (uma_kmem_limit);
5129 uma_set_limit(unsigned long limit)
5132 uma_kmem_limit = limit;
5139 return (atomic_load_long(&uma_kmem_total));
5146 return (uma_kmem_limit - uma_size());
5151 * Generate statistics across both the zone and its per-cpu cache's. Return
5152 * desired statistics if the pointer is non-NULL for that statistic.
5154 * Note: does not update the zone statistics, as it can't safely clear the
5155 * per-CPU cache statistic.
5159 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
5160 uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
5163 uint64_t allocs, frees, sleeps, xdomain;
5166 allocs = frees = sleeps = xdomain = 0;
5169 cache = &z->uz_cpu[cpu];
5170 cachefree += cache->uc_allocbucket.ucb_cnt;
5171 cachefree += cache->uc_freebucket.ucb_cnt;
5172 xdomain += cache->uc_crossbucket.ucb_cnt;
5173 cachefree += cache->uc_crossbucket.ucb_cnt;
5174 allocs += cache->uc_allocs;
5175 frees += cache->uc_frees;
5177 allocs += counter_u64_fetch(z->uz_allocs);
5178 frees += counter_u64_fetch(z->uz_frees);
5179 xdomain += counter_u64_fetch(z->uz_xdomain);
5180 sleeps += z->uz_sleeps;
5181 if (cachefreep != NULL)
5182 *cachefreep = cachefree;
5183 if (allocsp != NULL)
5187 if (sleepsp != NULL)
5189 if (xdomainp != NULL)
5190 *xdomainp = xdomain;
5195 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5202 rw_rlock(&uma_rwlock);
5203 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5204 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5207 LIST_FOREACH(z, &uma_cachezones, uz_link)
5210 rw_runlock(&uma_rwlock);
5211 return (sysctl_handle_int(oidp, &count, 0, req));
5215 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5216 struct uma_percpu_stat *ups, bool internal)
5218 uma_zone_domain_t zdom;
5222 for (i = 0; i < vm_ndomains; i++) {
5223 zdom = ZDOM_GET(z, i);
5224 uth->uth_zone_free += zdom->uzd_nitems;
5226 uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5227 uth->uth_frees = counter_u64_fetch(z->uz_frees);
5228 uth->uth_fails = counter_u64_fetch(z->uz_fails);
5229 uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5230 uth->uth_sleeps = z->uz_sleeps;
5232 for (i = 0; i < mp_maxid + 1; i++) {
5233 bzero(&ups[i], sizeof(*ups));
5234 if (internal || CPU_ABSENT(i))
5236 cache = &z->uz_cpu[i];
5237 ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5238 ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5239 ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5240 ups[i].ups_allocs = cache->uc_allocs;
5241 ups[i].ups_frees = cache->uc_frees;
5246 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5248 struct uma_stream_header ush;
5249 struct uma_type_header uth;
5250 struct uma_percpu_stat *ups;
5255 uint32_t kfree, pages;
5256 int count, error, i;
5258 error = sysctl_wire_old_buffer(req, 0);
5261 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5262 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5263 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5266 rw_rlock(&uma_rwlock);
5267 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5268 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5272 LIST_FOREACH(z, &uma_cachezones, uz_link)
5276 * Insert stream header.
5278 bzero(&ush, sizeof(ush));
5279 ush.ush_version = UMA_STREAM_VERSION;
5280 ush.ush_maxcpus = (mp_maxid + 1);
5281 ush.ush_count = count;
5282 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5284 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5286 for (i = 0; i < vm_ndomains; i++) {
5287 kfree += kz->uk_domain[i].ud_free_items;
5288 pages += kz->uk_domain[i].ud_pages;
5290 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5291 bzero(&uth, sizeof(uth));
5292 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5293 uth.uth_align = kz->uk_align;
5294 uth.uth_size = kz->uk_size;
5295 uth.uth_rsize = kz->uk_rsize;
5296 if (z->uz_max_items > 0) {
5297 items = UZ_ITEMS_COUNT(z->uz_items);
5298 uth.uth_pages = (items / kz->uk_ipers) *
5301 uth.uth_pages = pages;
5302 uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5304 uth.uth_limit = z->uz_max_items;
5305 uth.uth_keg_free = kfree;
5308 * A zone is secondary is it is not the first entry
5309 * on the keg's zone list.
5311 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5312 (LIST_FIRST(&kz->uk_zones) != z))
5313 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5314 uma_vm_zone_stats(&uth, z, &sbuf, ups,
5315 kz->uk_flags & UMA_ZFLAG_INTERNAL);
5316 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5317 for (i = 0; i < mp_maxid + 1; i++)
5318 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5321 LIST_FOREACH(z, &uma_cachezones, uz_link) {
5322 bzero(&uth, sizeof(uth));
5323 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5324 uth.uth_size = z->uz_size;
5325 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5326 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5327 for (i = 0; i < mp_maxid + 1; i++)
5328 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5331 rw_runlock(&uma_rwlock);
5332 error = sbuf_finish(&sbuf);
5339 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5341 uma_zone_t zone = *(uma_zone_t *)arg1;
5344 max = uma_zone_get_max(zone);
5345 error = sysctl_handle_int(oidp, &max, 0, req);
5346 if (error || !req->newptr)
5349 uma_zone_set_max(zone, max);
5355 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5361 * Some callers want to add sysctls for global zones that
5362 * may not yet exist so they pass a pointer to a pointer.
5365 zone = *(uma_zone_t *)arg1;
5368 cur = uma_zone_get_cur(zone);
5369 return (sysctl_handle_int(oidp, &cur, 0, req));
5373 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5375 uma_zone_t zone = arg1;
5378 cur = uma_zone_get_allocs(zone);
5379 return (sysctl_handle_64(oidp, &cur, 0, req));
5383 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5385 uma_zone_t zone = arg1;
5388 cur = uma_zone_get_frees(zone);
5389 return (sysctl_handle_64(oidp, &cur, 0, req));
5393 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5396 uma_zone_t zone = arg1;
5399 sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5400 if (zone->uz_flags != 0)
5401 sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5403 sbuf_printf(&sbuf, "0");
5404 error = sbuf_finish(&sbuf);
5411 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5413 uma_keg_t keg = arg1;
5414 int avail, effpct, total;
5416 total = keg->uk_ppera * PAGE_SIZE;
5417 if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5418 total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5420 * We consider the client's requested size and alignment here, not the
5421 * real size determination uk_rsize, because we also adjust the real
5422 * size for internal implementation reasons (max bitset size).
5424 avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5425 if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5426 avail *= mp_maxid + 1;
5427 effpct = 100 * avail / total;
5428 return (sysctl_handle_int(oidp, &effpct, 0, req));
5432 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5434 uma_zone_t zone = arg1;
5437 cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5438 return (sysctl_handle_64(oidp, &cur, 0, req));
5443 uma_dbg_getslab(uma_zone_t zone, void *item)
5450 * It is safe to return the slab here even though the
5451 * zone is unlocked because the item's allocation state
5452 * essentially holds a reference.
5454 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5455 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5457 if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5458 return (vtoslab((vm_offset_t)mem));
5460 if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5461 return ((uma_slab_t)(mem + keg->uk_pgoff));
5463 slab = hash_sfind(&keg->uk_hash, mem);
5470 uma_dbg_zskip(uma_zone_t zone, void *mem)
5473 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5476 return (uma_dbg_kskip(zone->uz_keg, mem));
5480 uma_dbg_kskip(uma_keg_t keg, void *mem)
5484 if (dbg_divisor == 0)
5487 if (dbg_divisor == 1)
5490 idx = (uintptr_t)mem >> PAGE_SHIFT;
5491 if (keg->uk_ipers > 1) {
5492 idx *= keg->uk_ipers;
5493 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5496 if ((idx / dbg_divisor) * dbg_divisor != idx) {
5497 counter_u64_add(uma_skip_cnt, 1);
5500 counter_u64_add(uma_dbg_cnt, 1);
5506 * Set up the slab's freei data such that uma_dbg_free can function.
5510 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5516 slab = uma_dbg_getslab(zone, item);
5518 panic("uma: item %p did not belong to zone %s",
5519 item, zone->uz_name);
5522 freei = slab_item_index(slab, keg, item);
5524 if (BIT_TEST_SET_ATOMIC(keg->uk_ipers, freei,
5525 slab_dbg_bits(slab, keg)))
5526 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5527 item, zone, zone->uz_name, slab, freei);
5531 * Verifies freed addresses. Checks for alignment, valid slab membership
5532 * and duplicate frees.
5536 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5542 slab = uma_dbg_getslab(zone, item);
5544 panic("uma: Freed item %p did not belong to zone %s",
5545 item, zone->uz_name);
5548 freei = slab_item_index(slab, keg, item);
5550 if (freei >= keg->uk_ipers)
5551 panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5552 item, zone, zone->uz_name, slab, freei);
5554 if (slab_item(slab, keg, freei) != item)
5555 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5556 item, zone, zone->uz_name, slab, freei);
5558 if (!BIT_TEST_CLR_ATOMIC(keg->uk_ipers, freei,
5559 slab_dbg_bits(slab, keg)))
5560 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5561 item, zone, zone->uz_name, slab, freei);
5563 #endif /* INVARIANTS */
5567 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5568 uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5573 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5574 *allocs = counter_u64_fetch(z->uz_allocs);
5575 frees = counter_u64_fetch(z->uz_frees);
5576 *sleeps = z->uz_sleeps;
5580 uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5582 for (i = 0; i < vm_ndomains; i++) {
5583 *cachefree += ZDOM_GET(z, i)->uzd_nitems;
5584 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5585 (LIST_FIRST(&kz->uk_zones) != z)))
5586 *cachefree += kz->uk_domain[i].ud_free_items;
5588 *used = *allocs - frees;
5589 return (((int64_t)*used + *cachefree) * kz->uk_size);
5592 DB_SHOW_COMMAND(uma, db_show_uma)
5594 const char *fmt_hdr, *fmt_entry;
5597 uint64_t allocs, used, sleeps, xdomain;
5599 /* variables for sorting */
5601 uma_zone_t cur_zone, last_zone;
5602 int64_t cur_size, last_size, size;
5605 /* /i option produces machine-parseable CSV output */
5606 if (modif[0] == 'i') {
5607 fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5608 fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5610 fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5611 fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5614 db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5615 "Sleeps", "Bucket", "Total Mem", "XFree");
5617 /* Sort the zones with largest size first. */
5619 last_size = INT64_MAX;
5624 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5625 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5627 * In the case of size ties, print out zones
5628 * in the order they are encountered. That is,
5629 * when we encounter the most recently output
5630 * zone, we have already printed all preceding
5631 * ties, and we must print all following ties.
5633 if (z == last_zone) {
5637 size = get_uma_stats(kz, z, &allocs, &used,
5638 &sleeps, &cachefree, &xdomain);
5639 if (size > cur_size && size < last_size + ties)
5647 if (cur_zone == NULL)
5650 size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5651 &sleeps, &cachefree, &xdomain);
5652 db_printf(fmt_entry, cur_zone->uz_name,
5653 (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5654 (uintmax_t)allocs, (uintmax_t)sleeps,
5655 (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5660 last_zone = cur_zone;
5661 last_size = cur_size;
5665 DB_SHOW_COMMAND(umacache, db_show_umacache)
5668 uint64_t allocs, frees;
5672 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5673 "Requests", "Bucket");
5674 LIST_FOREACH(z, &uma_cachezones, uz_link) {
5675 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5676 for (i = 0; i < vm_ndomains; i++)
5677 cachefree += ZDOM_GET(z, i)->uzd_nitems;
5678 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5679 z->uz_name, (uintmax_t)z->uz_size,
5680 (intmax_t)(allocs - frees), cachefree,
5681 (uintmax_t)allocs, z->uz_bucket_size);