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>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
81 #include <sys/taskqueue.h>
82 #include <sys/vmmeter.h>
85 #include <vm/vm_domainset.h>
86 #include <vm/vm_object.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_pageout.h>
89 #include <vm/vm_param.h>
90 #include <vm/vm_phys.h>
91 #include <vm/vm_pagequeue.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_extern.h>
96 #include <vm/uma_int.h>
97 #include <vm/uma_dbg.h>
101 #ifdef DEBUG_MEMGUARD
102 #include <vm/memguard.h>
105 #include <machine/md_var.h>
108 #define UMA_ALWAYS_CTORDTOR 1
110 #define UMA_ALWAYS_CTORDTOR 0
114 * This is the zone and keg from which all zones are spawned.
116 static uma_zone_t kegs;
117 static uma_zone_t zones;
120 * On INVARIANTS builds, the slab contains a second bitset of the same size,
121 * "dbg_bits", which is laid out immediately after us_free.
124 #define SLAB_BITSETS 2
126 #define SLAB_BITSETS 1
130 * These are the two zones from which all offpage uma_slab_ts are allocated.
132 * One zone is for slab headers that can represent a larger number of items,
133 * making the slabs themselves more efficient, and the other zone is for
134 * headers that are smaller and represent fewer items, making the headers more
137 #define SLABZONE_SIZE(setsize) \
138 (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
139 #define SLABZONE0_SETSIZE (PAGE_SIZE / 16)
140 #define SLABZONE1_SETSIZE SLAB_MAX_SETSIZE
141 #define SLABZONE0_SIZE SLABZONE_SIZE(SLABZONE0_SETSIZE)
142 #define SLABZONE1_SIZE SLABZONE_SIZE(SLABZONE1_SETSIZE)
143 static uma_zone_t slabzones[2];
146 * The initial hash tables come out of this zone so they can be allocated
147 * prior to malloc coming up.
149 static uma_zone_t hashzone;
151 /* The boot-time adjusted value for cache line alignment. */
152 int uma_align_cache = 64 - 1;
154 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
155 static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
158 * Are we allowed to allocate buckets?
160 static int bucketdisable = 1;
162 /* Linked list of all kegs in the system */
163 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
165 /* Linked list of all cache-only zones in the system */
166 static LIST_HEAD(,uma_zone) uma_cachezones =
167 LIST_HEAD_INITIALIZER(uma_cachezones);
169 /* This RW lock protects the keg list */
170 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
173 * First available virual address for boot time allocations.
175 static vm_offset_t bootstart;
176 static vm_offset_t bootmem;
178 static struct sx uma_reclaim_lock;
181 * kmem soft limit, initialized by uma_set_limit(). Ensure that early
182 * allocations don't trigger a wakeup of the reclaim thread.
184 unsigned long uma_kmem_limit = LONG_MAX;
185 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
186 "UMA kernel memory soft limit");
187 unsigned long uma_kmem_total;
188 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
189 "UMA kernel memory usage");
191 /* Is the VM done starting up? */
198 } booted = BOOT_COLD;
201 * This is the handle used to schedule events that need to happen
202 * outside of the allocation fast path.
204 static struct callout uma_callout;
205 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
208 * This structure is passed as the zone ctor arg so that I don't have to create
209 * a special allocation function just for zones.
211 struct uma_zctor_args {
226 struct uma_kctor_args {
235 struct uma_bucket_zone {
237 const char *ubz_name;
238 int ubz_entries; /* Number of items it can hold. */
239 int ubz_maxsize; /* Maximum allocation size per-item. */
243 * Compute the actual number of bucket entries to pack them in power
244 * of two sizes for more efficient space utilization.
246 #define BUCKET_SIZE(n) \
247 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
249 #define BUCKET_MAX BUCKET_SIZE(256)
252 struct uma_bucket_zone bucket_zones[] = {
253 /* Literal bucket sizes. */
254 { NULL, "2 Bucket", 2, 4096 },
255 { NULL, "4 Bucket", 4, 3072 },
256 { NULL, "8 Bucket", 8, 2048 },
257 { NULL, "16 Bucket", 16, 1024 },
258 /* Rounded down power of 2 sizes for efficiency. */
259 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
260 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
261 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
262 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
267 * Flags and enumerations to be passed to internal functions.
271 SKIP_CNT = 0x00000001,
272 SKIP_DTOR = 0x00010000,
273 SKIP_FINI = 0x00020000,
278 void uma_startup1(vm_offset_t);
279 void uma_startup2(void);
281 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
282 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
283 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
284 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
285 static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
286 static void page_free(void *, vm_size_t, uint8_t);
287 static void pcpu_page_free(void *, vm_size_t, uint8_t);
288 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
289 static void cache_drain(uma_zone_t);
290 static void bucket_drain(uma_zone_t, uma_bucket_t);
291 static void bucket_cache_reclaim(uma_zone_t zone, bool);
292 static int keg_ctor(void *, int, void *, int);
293 static void keg_dtor(void *, int, void *);
294 static int zone_ctor(void *, int, void *, int);
295 static void zone_dtor(void *, int, void *);
296 static inline void item_dtor(uma_zone_t zone, void *item, int size,
297 void *udata, enum zfreeskip skip);
298 static int zero_init(void *, int, int);
299 static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
300 int itemdomain, bool ws);
301 static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
302 static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
303 static void zone_timeout(uma_zone_t zone, void *);
304 static int hash_alloc(struct uma_hash *, u_int);
305 static int hash_expand(struct uma_hash *, struct uma_hash *);
306 static void hash_free(struct uma_hash *hash);
307 static void uma_timeout(void *);
308 static void uma_shutdown(void);
309 static void *zone_alloc_item(uma_zone_t, void *, int, int);
310 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
311 static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
312 static void zone_free_limit(uma_zone_t zone, int count);
313 static void bucket_enable(void);
314 static void bucket_init(void);
315 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
316 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
317 static void bucket_zone_drain(void);
318 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
319 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
320 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
321 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
322 uma_fini fini, int align, uint32_t flags);
323 static int zone_import(void *, void **, int, int, int);
324 static void zone_release(void *, void **, int);
325 static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
326 static bool cache_free(uma_zone_t, uma_cache_t, void *, void *, int);
328 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
329 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
330 static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
331 static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
332 static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
333 static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
334 static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
336 static uint64_t uma_zone_get_allocs(uma_zone_t zone);
338 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
339 "Memory allocation debugging");
342 static uint64_t uma_keg_get_allocs(uma_keg_t zone);
343 static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
345 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
346 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
347 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
348 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
350 static u_int dbg_divisor = 1;
351 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
352 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
353 "Debug & thrash every this item in memory allocator");
355 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
356 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
357 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
358 &uma_dbg_cnt, "memory items debugged");
359 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
360 &uma_skip_cnt, "memory items skipped, not debugged");
363 SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
364 "Universal Memory Allocator");
366 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
367 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
369 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
370 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
372 static int zone_warnings = 1;
373 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
374 "Warn when UMA zones becomes full");
376 static int multipage_slabs = 1;
377 TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
378 SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
379 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
380 "UMA may choose larger slab sizes for better efficiency");
383 * Select the slab zone for an offpage slab with the given maximum item count.
385 static inline uma_zone_t
389 return (slabzones[ipers > SLABZONE0_SETSIZE]);
393 * This routine checks to see whether or not it's safe to enable buckets.
399 KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
400 bucketdisable = vm_page_count_min();
404 * Initialize bucket_zones, the array of zones of buckets of various sizes.
406 * For each zone, calculate the memory required for each bucket, consisting
407 * of the header and an array of pointers.
412 struct uma_bucket_zone *ubz;
415 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
416 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
417 size += sizeof(void *) * ubz->ubz_entries;
418 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
419 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
420 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
421 UMA_ZONE_FIRSTTOUCH);
426 * Given a desired number of entries for a bucket, return the zone from which
427 * to allocate the bucket.
429 static struct uma_bucket_zone *
430 bucket_zone_lookup(int entries)
432 struct uma_bucket_zone *ubz;
434 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
435 if (ubz->ubz_entries >= entries)
441 static struct uma_bucket_zone *
442 bucket_zone_max(uma_zone_t zone, int nitems)
444 struct uma_bucket_zone *ubz;
448 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
449 /* Count the cross-domain bucket. */
452 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
453 if (ubz->ubz_entries * bpcpu * mp_ncpus > nitems)
455 if (ubz == &bucket_zones[0])
463 bucket_select(int size)
465 struct uma_bucket_zone *ubz;
467 ubz = &bucket_zones[0];
468 if (size > ubz->ubz_maxsize)
469 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
471 for (; ubz->ubz_entries != 0; ubz++)
472 if (ubz->ubz_maxsize < size)
475 return (ubz->ubz_entries);
479 bucket_alloc(uma_zone_t zone, void *udata, int flags)
481 struct uma_bucket_zone *ubz;
485 * Don't allocate buckets early in boot.
487 if (__predict_false(booted < BOOT_KVA))
491 * To limit bucket recursion we store the original zone flags
492 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
493 * NOVM flag to persist even through deep recursions. We also
494 * store ZFLAG_BUCKET once we have recursed attempting to allocate
495 * a bucket for a bucket zone so we do not allow infinite bucket
496 * recursion. This cookie will even persist to frees of unused
497 * buckets via the allocation path or bucket allocations in the
500 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
501 udata = (void *)(uintptr_t)zone->uz_flags;
503 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
505 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
507 if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
509 ubz = bucket_zone_lookup(zone->uz_bucket_size);
510 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
512 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
515 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
518 bucket->ub_entries = ubz->ubz_entries;
519 bucket->ub_seq = SMR_SEQ_INVALID;
520 CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
521 zone->uz_name, zone, bucket);
528 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
530 struct uma_bucket_zone *ubz;
532 if (bucket->ub_cnt != 0)
533 bucket_drain(zone, bucket);
535 KASSERT(bucket->ub_cnt == 0,
536 ("bucket_free: Freeing a non free bucket."));
537 KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
538 ("bucket_free: Freeing an SMR bucket."));
539 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
540 udata = (void *)(uintptr_t)zone->uz_flags;
541 ubz = bucket_zone_lookup(bucket->ub_entries);
542 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
546 bucket_zone_drain(void)
548 struct uma_bucket_zone *ubz;
550 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
551 uma_zone_reclaim(ubz->ubz_zone, UMA_RECLAIM_DRAIN);
555 * Acquire the domain lock and record contention.
557 static uma_zone_domain_t
558 zone_domain_lock(uma_zone_t zone, int domain)
560 uma_zone_domain_t zdom;
563 zdom = ZDOM_GET(zone, domain);
565 if (ZDOM_OWNED(zdom))
568 /* This is unsynchronized. The counter does not need to be precise. */
569 if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
570 zone->uz_bucket_size++;
575 * Search for the domain with the least cached items and return it if it
576 * is out of balance with the preferred domain.
578 static __noinline int
579 zone_domain_lowest(uma_zone_t zone, int pref)
581 long least, nitems, prefitems;
585 prefitems = least = LONG_MAX;
587 for (i = 0; i < vm_ndomains; i++) {
588 nitems = ZDOM_GET(zone, i)->uzd_nitems;
589 if (nitems < least) {
596 if (prefitems < least * 2)
603 * Search for the domain with the most cached items and return it or the
604 * preferred domain if it has enough to proceed.
606 static __noinline int
607 zone_domain_highest(uma_zone_t zone, int pref)
613 if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
618 for (i = 0; i < vm_ndomains; i++) {
619 nitems = ZDOM_GET(zone, i)->uzd_nitems;
630 * Safely subtract cnt from imax.
633 zone_domain_imax_sub(uma_zone_domain_t zdom, int cnt)
638 old = zdom->uzd_imax;
644 } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, new) == 0);
648 * Set the maximum imax value.
651 zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
655 old = zdom->uzd_imax;
659 } while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
663 * Attempt to satisfy an allocation by retrieving a full bucket from one of the
664 * zone's caches. If a bucket is found the zone is not locked on return.
667 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
673 ZDOM_LOCK_ASSERT(zdom);
675 if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
678 /* SMR Buckets can not be re-used until readers expire. */
679 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
680 bucket->ub_seq != SMR_SEQ_INVALID) {
681 if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
683 bucket->ub_seq = SMR_SEQ_INVALID;
684 dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
685 if (STAILQ_NEXT(bucket, ub_link) != NULL)
686 zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
688 STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
690 KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
691 ("%s: item count underflow (%ld, %d)",
692 __func__, zdom->uzd_nitems, bucket->ub_cnt));
693 KASSERT(bucket->ub_cnt > 0,
694 ("%s: empty bucket in bucket cache", __func__));
695 zdom->uzd_nitems -= bucket->ub_cnt;
698 * Shift the bounds of the current WSS interval to avoid
699 * perturbing the estimate.
702 zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
703 zone_domain_imax_sub(zdom, bucket->ub_cnt);
704 } else if (zdom->uzd_imin > zdom->uzd_nitems)
705 zdom->uzd_imin = zdom->uzd_nitems;
709 for (i = 0; i < bucket->ub_cnt; i++)
710 item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
717 * Insert a full bucket into the specified cache. The "ws" parameter indicates
718 * whether the bucket's contents should be counted as part of the zone's working
719 * set. The bucket may be freed if it exceeds the bucket limit.
722 zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
725 uma_zone_domain_t zdom;
727 /* We don't cache empty buckets. This can happen after a reclaim. */
728 if (bucket->ub_cnt == 0)
730 zdom = zone_domain_lock(zone, domain);
733 * Conditionally set the maximum number of items.
735 zdom->uzd_nitems += bucket->ub_cnt;
736 if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
738 zone_domain_imax_set(zdom, zdom->uzd_nitems);
739 if (STAILQ_EMPTY(&zdom->uzd_buckets))
740 zdom->uzd_seq = bucket->ub_seq;
743 * Try to promote reuse of recently used items. For items
744 * protected by SMR, try to defer reuse to minimize polling.
746 if (bucket->ub_seq == SMR_SEQ_INVALID)
747 STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
749 STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
753 zdom->uzd_nitems -= bucket->ub_cnt;
756 bucket_free(zone, bucket, udata);
759 /* Pops an item out of a per-cpu cache bucket. */
761 cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
765 CRITICAL_ASSERT(curthread);
768 item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
770 bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
771 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
778 /* Pushes an item into a per-cpu cache bucket. */
780 cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
783 CRITICAL_ASSERT(curthread);
784 KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
785 ("uma_zfree: Freeing to non free bucket index."));
787 bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
793 * Unload a UMA bucket from a per-cpu cache.
795 static inline uma_bucket_t
796 cache_bucket_unload(uma_cache_bucket_t bucket)
800 b = bucket->ucb_bucket;
802 MPASS(b->ub_entries == bucket->ucb_entries);
803 b->ub_cnt = bucket->ucb_cnt;
804 bucket->ucb_bucket = NULL;
805 bucket->ucb_entries = bucket->ucb_cnt = 0;
811 static inline uma_bucket_t
812 cache_bucket_unload_alloc(uma_cache_t cache)
815 return (cache_bucket_unload(&cache->uc_allocbucket));
818 static inline uma_bucket_t
819 cache_bucket_unload_free(uma_cache_t cache)
822 return (cache_bucket_unload(&cache->uc_freebucket));
825 static inline uma_bucket_t
826 cache_bucket_unload_cross(uma_cache_t cache)
829 return (cache_bucket_unload(&cache->uc_crossbucket));
833 * Load a bucket into a per-cpu cache bucket.
836 cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
839 CRITICAL_ASSERT(curthread);
840 MPASS(bucket->ucb_bucket == NULL);
841 MPASS(b->ub_seq == SMR_SEQ_INVALID);
843 bucket->ucb_bucket = b;
844 bucket->ucb_cnt = b->ub_cnt;
845 bucket->ucb_entries = b->ub_entries;
849 cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
852 cache_bucket_load(&cache->uc_allocbucket, b);
856 cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
859 cache_bucket_load(&cache->uc_freebucket, b);
864 cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
867 cache_bucket_load(&cache->uc_crossbucket, b);
872 * Copy and preserve ucb_spare.
875 cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
878 b1->ucb_bucket = b2->ucb_bucket;
879 b1->ucb_entries = b2->ucb_entries;
880 b1->ucb_cnt = b2->ucb_cnt;
884 * Swap two cache buckets.
887 cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
889 struct uma_cache_bucket b3;
891 CRITICAL_ASSERT(curthread);
893 cache_bucket_copy(&b3, b1);
894 cache_bucket_copy(b1, b2);
895 cache_bucket_copy(b2, &b3);
899 * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
902 cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
904 uma_zone_domain_t zdom;
908 * Avoid the lock if possible.
910 zdom = ZDOM_GET(zone, domain);
911 if (zdom->uzd_nitems == 0)
914 if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
915 !smr_poll(zone->uz_smr, zdom->uzd_seq, false))
919 * Check the zone's cache of buckets.
921 zdom = zone_domain_lock(zone, domain);
922 if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
930 zone_log_warning(uma_zone_t zone)
932 static const struct timeval warninterval = { 300, 0 };
934 if (!zone_warnings || zone->uz_warning == NULL)
937 if (ratecheck(&zone->uz_ratecheck, &warninterval))
938 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
942 zone_maxaction(uma_zone_t zone)
945 if (zone->uz_maxaction.ta_func != NULL)
946 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
950 * Routine called by timeout which is used to fire off some time interval
951 * based calculations. (stats, hash size, etc.)
960 uma_timeout(void *unused)
963 zone_foreach(zone_timeout, NULL);
965 /* Reschedule this event */
966 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
970 * Update the working set size estimate for the zone's bucket cache.
971 * The constants chosen here are somewhat arbitrary. With an update period of
972 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
976 zone_domain_update_wss(uma_zone_domain_t zdom)
981 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
982 wss = zdom->uzd_imax - zdom->uzd_imin;
983 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
984 zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
989 * Routine to perform timeout driven calculations. This expands the
990 * hashes and does per cpu statistics aggregation.
995 zone_timeout(uma_zone_t zone, void *unused)
1000 if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
1006 * Hash zones are non-numa by definition so the first domain
1007 * is the only one present.
1010 pages = keg->uk_domain[0].ud_pages;
1013 * Expand the keg hash table.
1015 * This is done if the number of slabs is larger than the hash size.
1016 * What I'm trying to do here is completely reduce collisions. This
1017 * may be a little aggressive. Should I allow for two collisions max?
1019 if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
1020 struct uma_hash newhash;
1021 struct uma_hash oldhash;
1025 * This is so involved because allocating and freeing
1026 * while the keg lock is held will lead to deadlock.
1027 * I have to do everything in stages and check for
1031 ret = hash_alloc(&newhash, 1 << fls(slabs));
1034 if (hash_expand(&keg->uk_hash, &newhash)) {
1035 oldhash = keg->uk_hash;
1036 keg->uk_hash = newhash;
1041 hash_free(&oldhash);
1048 for (int i = 0; i < vm_ndomains; i++)
1049 zone_domain_update_wss(ZDOM_GET(zone, i));
1053 * Allocate and zero fill the next sized hash table from the appropriate
1057 * hash A new hash structure with the old hash size in uh_hashsize
1060 * 1 on success and 0 on failure.
1063 hash_alloc(struct uma_hash *hash, u_int size)
1067 KASSERT(powerof2(size), ("hash size must be power of 2"));
1068 if (size > UMA_HASH_SIZE_INIT) {
1069 hash->uh_hashsize = size;
1070 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
1071 hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
1073 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
1074 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
1075 UMA_ANYDOMAIN, M_WAITOK);
1076 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
1078 if (hash->uh_slab_hash) {
1079 bzero(hash->uh_slab_hash, alloc);
1080 hash->uh_hashmask = hash->uh_hashsize - 1;
1088 * Expands the hash table for HASH zones. This is done from zone_timeout
1089 * to reduce collisions. This must not be done in the regular allocation
1090 * path, otherwise, we can recurse on the vm while allocating pages.
1093 * oldhash The hash you want to expand
1094 * newhash The hash structure for the new table
1102 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
1104 uma_hash_slab_t slab;
1108 if (!newhash->uh_slab_hash)
1111 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
1115 * I need to investigate hash algorithms for resizing without a
1119 for (idx = 0; idx < oldhash->uh_hashsize; idx++)
1120 while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
1121 slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
1122 LIST_REMOVE(slab, uhs_hlink);
1123 hval = UMA_HASH(newhash, slab->uhs_data);
1124 LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
1132 * Free the hash bucket to the appropriate backing store.
1135 * slab_hash The hash bucket we're freeing
1136 * hashsize The number of entries in that hash bucket
1142 hash_free(struct uma_hash *hash)
1144 if (hash->uh_slab_hash == NULL)
1146 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
1147 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
1149 free(hash->uh_slab_hash, M_UMAHASH);
1153 * Frees all outstanding items in a bucket
1156 * zone The zone to free to, must be unlocked.
1157 * bucket The free/alloc bucket with items.
1163 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
1167 if (bucket->ub_cnt == 0)
1170 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
1171 bucket->ub_seq != SMR_SEQ_INVALID) {
1172 smr_wait(zone->uz_smr, bucket->ub_seq);
1173 bucket->ub_seq = SMR_SEQ_INVALID;
1174 for (i = 0; i < bucket->ub_cnt; i++)
1175 item_dtor(zone, bucket->ub_bucket[i],
1176 zone->uz_size, NULL, SKIP_NONE);
1179 for (i = 0; i < bucket->ub_cnt; i++)
1180 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
1181 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
1182 if (zone->uz_max_items > 0)
1183 zone_free_limit(zone, bucket->ub_cnt);
1185 bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
1191 * Drains the per cpu caches for a zone.
1193 * NOTE: This may only be called while the zone is being torn down, and not
1194 * during normal operation. This is necessary in order that we do not have
1195 * to migrate CPUs to drain the per-CPU caches.
1198 * zone The zone to drain, must be unlocked.
1204 cache_drain(uma_zone_t zone)
1207 uma_bucket_t bucket;
1212 * XXX: It is safe to not lock the per-CPU caches, because we're
1213 * tearing down the zone anyway. I.e., there will be no further use
1214 * of the caches at this point.
1216 * XXX: It would good to be able to assert that the zone is being
1217 * torn down to prevent improper use of cache_drain().
1219 seq = SMR_SEQ_INVALID;
1220 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
1221 seq = smr_advance(zone->uz_smr);
1223 cache = &zone->uz_cpu[cpu];
1224 bucket = cache_bucket_unload_alloc(cache);
1226 bucket_free(zone, bucket, NULL);
1227 bucket = cache_bucket_unload_free(cache);
1228 if (bucket != NULL) {
1229 bucket->ub_seq = seq;
1230 bucket_free(zone, bucket, NULL);
1232 bucket = cache_bucket_unload_cross(cache);
1233 if (bucket != NULL) {
1234 bucket->ub_seq = seq;
1235 bucket_free(zone, bucket, NULL);
1238 bucket_cache_reclaim(zone, true);
1242 cache_shrink(uma_zone_t zone, void *unused)
1245 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1248 zone->uz_bucket_size =
1249 (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
1253 cache_drain_safe_cpu(uma_zone_t zone, void *unused)
1256 uma_bucket_t b1, b2, b3;
1259 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1262 b1 = b2 = b3 = NULL;
1264 cache = &zone->uz_cpu[curcpu];
1265 domain = PCPU_GET(domain);
1266 b1 = cache_bucket_unload_alloc(cache);
1269 * Don't flush SMR zone buckets. This leaves the zone without a
1270 * bucket and forces every free to synchronize().
1272 if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
1273 b2 = cache_bucket_unload_free(cache);
1274 b3 = cache_bucket_unload_cross(cache);
1279 zone_free_bucket(zone, b1, NULL, domain, false);
1281 zone_free_bucket(zone, b2, NULL, domain, false);
1283 /* Adjust the domain so it goes to zone_free_cross. */
1284 domain = (domain + 1) % vm_ndomains;
1285 zone_free_bucket(zone, b3, NULL, domain, false);
1290 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
1291 * This is an expensive call because it needs to bind to all CPUs
1292 * one by one and enter a critical section on each of them in order
1293 * to safely access their cache buckets.
1294 * Zone lock must not be held on call this function.
1297 pcpu_cache_drain_safe(uma_zone_t zone)
1302 * Polite bucket sizes shrinking was not enough, shrink aggressively.
1305 cache_shrink(zone, NULL);
1307 zone_foreach(cache_shrink, NULL);
1310 thread_lock(curthread);
1311 sched_bind(curthread, cpu);
1312 thread_unlock(curthread);
1315 cache_drain_safe_cpu(zone, NULL);
1317 zone_foreach(cache_drain_safe_cpu, NULL);
1319 thread_lock(curthread);
1320 sched_unbind(curthread);
1321 thread_unlock(curthread);
1325 * Reclaim cached buckets from a zone. All buckets are reclaimed if the caller
1326 * requested a drain, otherwise the per-domain caches are trimmed to either
1327 * estimated working set size.
1330 bucket_cache_reclaim(uma_zone_t zone, bool drain)
1332 uma_zone_domain_t zdom;
1333 uma_bucket_t bucket;
1338 * Shrink the zone bucket size to ensure that the per-CPU caches
1339 * don't grow too large.
1341 if (zone->uz_bucket_size > zone->uz_bucket_size_min)
1342 zone->uz_bucket_size--;
1344 for (i = 0; i < vm_ndomains; i++) {
1346 * The cross bucket is partially filled and not part of
1347 * the item count. Reclaim it individually here.
1349 zdom = ZDOM_GET(zone, i);
1350 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
1351 ZONE_CROSS_LOCK(zone);
1352 bucket = zdom->uzd_cross;
1353 zdom->uzd_cross = NULL;
1354 ZONE_CROSS_UNLOCK(zone);
1356 bucket_free(zone, bucket, NULL);
1360 * If we were asked to drain the zone, we are done only once
1361 * this bucket cache is empty. Otherwise, we reclaim items in
1362 * excess of the zone's estimated working set size. If the
1363 * difference nitems - imin is larger than the WSS estimate,
1364 * then the estimate will grow at the end of this interval and
1365 * we ignore the historical average.
1368 target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
1370 while (zdom->uzd_nitems > target) {
1371 bucket = zone_fetch_bucket(zone, zdom, true);
1374 bucket_free(zone, bucket, NULL);
1382 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
1388 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
1389 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
1391 mem = slab_data(slab, keg);
1392 flags = slab->us_flags;
1394 if (keg->uk_fini != NULL) {
1395 for (i--; i > -1; i--)
1398 * trash_fini implies that dtor was trash_dtor. trash_fini
1399 * would check that memory hasn't been modified since free,
1400 * which executed trash_dtor.
1401 * That's why we need to run uma_dbg_kskip() check here,
1402 * albeit we don't make skip check for other init/fini
1405 if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
1406 keg->uk_fini != trash_fini)
1408 keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
1410 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1411 zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
1413 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
1414 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
1418 * Frees pages from a keg back to the system. This is done on demand from
1419 * the pageout daemon.
1424 keg_drain(uma_keg_t keg)
1426 struct slabhead freeslabs;
1428 uma_slab_t slab, tmp;
1431 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
1434 for (i = 0; i < vm_ndomains; i++) {
1435 CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1436 keg->uk_name, keg, i, dom->ud_free_items);
1437 dom = &keg->uk_domain[i];
1438 LIST_INIT(&freeslabs);
1441 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1442 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
1443 UMA_HASH_REMOVE(&keg->uk_hash, slab);
1445 n = dom->ud_free_slabs;
1446 LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1447 dom->ud_free_slabs = 0;
1448 dom->ud_free_items -= n * keg->uk_ipers;
1449 dom->ud_pages -= n * keg->uk_ppera;
1452 LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1453 keg_free_slab(keg, slab, keg->uk_ipers);
1458 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1462 * Set draining to interlock with zone_dtor() so we can release our
1463 * locks as we go. Only dtor() should do a WAITOK call since it
1464 * is the only call that knows the structure will still be available
1468 while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1469 if (waitok == M_NOWAIT)
1471 msleep(zone, &ZDOM_GET(zone, 0)->uzd_lock, PVM, "zonedrain",
1474 zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1476 bucket_cache_reclaim(zone, drain);
1479 * The DRAINING flag protects us from being freed while
1480 * we're running. Normally the uma_rwlock would protect us but we
1481 * must be able to release and acquire the right lock for each keg.
1483 if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1484 keg_drain(zone->uz_keg);
1486 zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1493 zone_drain(uma_zone_t zone, void *unused)
1496 zone_reclaim(zone, M_NOWAIT, true);
1500 zone_trim(uma_zone_t zone, void *unused)
1503 zone_reclaim(zone, M_NOWAIT, false);
1507 * Allocate a new slab for a keg and inserts it into the partial slab list.
1508 * The keg should be unlocked on entry. If the allocation succeeds it will
1509 * be locked on return.
1512 * flags Wait flags for the item initialization routine
1513 * aflags Wait flags for the slab allocation
1516 * The slab that was allocated or NULL if there is no memory and the
1517 * caller specified M_NOWAIT.
1520 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1531 KASSERT(domain >= 0 && domain < vm_ndomains,
1532 ("keg_alloc_slab: domain %d out of range", domain));
1534 allocf = keg->uk_allocf;
1537 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1538 uma_hash_slab_t hslab;
1539 hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1543 slab = &hslab->uhs_slab;
1547 * This reproduces the old vm_zone behavior of zero filling pages the
1548 * first time they are added to a zone.
1550 * Malloced items are zeroed in uma_zalloc.
1553 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1558 if (keg->uk_flags & UMA_ZONE_NODUMP)
1561 /* zone is passed for legacy reasons. */
1562 size = keg->uk_ppera * PAGE_SIZE;
1563 mem = allocf(zone, size, domain, &sflags, aflags);
1565 if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1566 zone_free_item(slabzone(keg->uk_ipers),
1567 slab_tohashslab(slab), NULL, SKIP_NONE);
1570 uma_total_inc(size);
1572 /* For HASH zones all pages go to the same uma_domain. */
1573 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1576 /* Point the slab into the allocated memory */
1577 if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1578 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1580 slab_tohashslab(slab)->uhs_data = mem;
1582 if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1583 for (i = 0; i < keg->uk_ppera; i++)
1584 vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1587 slab->us_freecount = keg->uk_ipers;
1588 slab->us_flags = sflags;
1589 slab->us_domain = domain;
1591 BIT_FILL(keg->uk_ipers, &slab->us_free);
1593 BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1596 if (keg->uk_init != NULL) {
1597 for (i = 0; i < keg->uk_ipers; i++)
1598 if (keg->uk_init(slab_item(slab, keg, i),
1599 keg->uk_size, flags) != 0)
1601 if (i != keg->uk_ipers) {
1602 keg_free_slab(keg, slab, i);
1606 KEG_LOCK(keg, domain);
1608 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1609 slab, keg->uk_name, keg);
1611 if (keg->uk_flags & UMA_ZFLAG_HASH)
1612 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1615 * If we got a slab here it's safe to mark it partially used
1616 * and return. We assume that the caller is going to remove
1617 * at least one item.
1619 dom = &keg->uk_domain[domain];
1620 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1621 dom->ud_pages += keg->uk_ppera;
1622 dom->ud_free_items += keg->uk_ipers;
1631 * This function is intended to be used early on in place of page_alloc() so
1632 * that we may use the boot time page cache to satisfy allocations before
1636 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1645 pages = howmany(bytes, PAGE_SIZE);
1646 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1648 *pflag = UMA_SLAB_BOOT;
1649 m = vm_page_alloc_contig_domain(NULL, 0, domain,
1650 malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages,
1651 (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1655 pa = VM_PAGE_TO_PHYS(m);
1656 for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1657 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1658 defined(__riscv) || defined(__powerpc64__)
1659 if ((wait & M_NODUMP) == 0)
1663 /* Allocate KVA and indirectly advance bootmem. */
1664 mem = (void *)pmap_map(&bootmem, m->phys_addr,
1665 m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1666 if ((wait & M_ZERO) != 0)
1667 bzero(mem, pages * PAGE_SIZE);
1673 startup_free(void *mem, vm_size_t bytes)
1678 va = (vm_offset_t)mem;
1679 m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1680 pmap_remove(kernel_pmap, va, va + bytes);
1681 for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1682 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1683 defined(__riscv) || defined(__powerpc64__)
1684 dump_drop_page(VM_PAGE_TO_PHYS(m));
1686 vm_page_unwire_noq(m);
1692 * Allocates a number of pages from the system
1695 * bytes The number of bytes requested
1696 * wait Shall we wait?
1699 * A pointer to the alloced memory or possibly
1700 * NULL if M_NOWAIT is set.
1703 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1706 void *p; /* Returned page */
1708 *pflag = UMA_SLAB_KERNEL;
1709 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1715 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1718 struct pglist alloctail;
1719 vm_offset_t addr, zkva;
1721 vm_page_t p, p_next;
1726 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1728 TAILQ_INIT(&alloctail);
1729 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1730 malloc2vm_flags(wait);
1731 *pflag = UMA_SLAB_KERNEL;
1732 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1733 if (CPU_ABSENT(cpu)) {
1734 p = vm_page_alloc(NULL, 0, flags);
1737 p = vm_page_alloc(NULL, 0, flags);
1739 pc = pcpu_find(cpu);
1740 if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1743 p = vm_page_alloc_domain(NULL, 0,
1744 pc->pc_domain, flags);
1745 if (__predict_false(p == NULL))
1746 p = vm_page_alloc(NULL, 0, flags);
1749 if (__predict_false(p == NULL))
1751 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1753 if ((addr = kva_alloc(bytes)) == 0)
1756 TAILQ_FOREACH(p, &alloctail, listq) {
1757 pmap_qenter(zkva, &p, 1);
1760 return ((void*)addr);
1762 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1763 vm_page_unwire_noq(p);
1770 * Allocates a number of pages from within an object
1773 * bytes The number of bytes requested
1774 * wait Shall we wait?
1777 * A pointer to the alloced memory or possibly
1778 * NULL if M_NOWAIT is set.
1781 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1784 TAILQ_HEAD(, vm_page) alloctail;
1786 vm_offset_t retkva, zkva;
1787 vm_page_t p, p_next;
1790 TAILQ_INIT(&alloctail);
1793 npages = howmany(bytes, PAGE_SIZE);
1794 while (npages > 0) {
1795 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1796 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1797 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1801 * Since the page does not belong to an object, its
1804 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1809 * Page allocation failed, free intermediate pages and
1812 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1813 vm_page_unwire_noq(p);
1818 *flags = UMA_SLAB_PRIV;
1819 zkva = keg->uk_kva +
1820 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1822 TAILQ_FOREACH(p, &alloctail, listq) {
1823 pmap_qenter(zkva, &p, 1);
1827 return ((void *)retkva);
1831 * Allocate physically contiguous pages.
1834 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1838 *pflag = UMA_SLAB_KERNEL;
1839 return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1840 bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1844 * Frees a number of pages to the system
1847 * mem A pointer to the memory to be freed
1848 * size The size of the memory being freed
1849 * flags The original p->us_flags field
1855 page_free(void *mem, vm_size_t size, uint8_t flags)
1858 if ((flags & UMA_SLAB_BOOT) != 0) {
1859 startup_free(mem, size);
1863 KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1864 ("UMA: page_free used with invalid flags %x", flags));
1866 kmem_free((vm_offset_t)mem, size);
1870 * Frees pcpu zone allocations
1873 * mem A pointer to the memory to be freed
1874 * size The size of the memory being freed
1875 * flags The original p->us_flags field
1881 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1883 vm_offset_t sva, curva;
1887 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1889 if ((flags & UMA_SLAB_BOOT) != 0) {
1890 startup_free(mem, size);
1894 sva = (vm_offset_t)mem;
1895 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1896 paddr = pmap_kextract(curva);
1897 m = PHYS_TO_VM_PAGE(paddr);
1898 vm_page_unwire_noq(m);
1901 pmap_qremove(sva, size >> PAGE_SHIFT);
1902 kva_free(sva, size);
1906 * Zero fill initializer
1908 * Arguments/Returns follow uma_init specifications
1911 zero_init(void *mem, int size, int flags)
1918 static struct noslabbits *
1919 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
1922 return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
1927 * Actual size of embedded struct slab (!OFFPAGE).
1930 slab_sizeof(int nitems)
1934 s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
1935 return (roundup(s, UMA_ALIGN_PTR + 1));
1938 #define UMA_FIXPT_SHIFT 31
1939 #define UMA_FRAC_FIXPT(n, d) \
1940 ((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
1941 #define UMA_FIXPT_PCT(f) \
1942 ((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
1943 #define UMA_PCT_FIXPT(pct) UMA_FRAC_FIXPT((pct), 100)
1944 #define UMA_MIN_EFF UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
1947 * Compute the number of items that will fit in a slab. If hdr is true, the
1948 * item count may be limited to provide space in the slab for an inline slab
1949 * header. Otherwise, all slab space will be provided for item storage.
1952 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
1957 /* The padding between items is not needed after the last item. */
1958 padpi = rsize - size;
1962 * Start with the maximum item count and remove items until
1963 * the slab header first alongside the allocatable memory.
1965 for (ipers = MIN(SLAB_MAX_SETSIZE,
1966 (slabsize + padpi - slab_sizeof(1)) / rsize);
1968 ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
1972 ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
1978 struct keg_layout_result {
1986 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
1987 struct keg_layout_result *kl)
1992 kl->slabsize = slabsize;
1994 /* Handle INTERNAL as inline with an extra page. */
1995 if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
1996 kl->format &= ~UMA_ZFLAG_INTERNAL;
1997 kl->slabsize += PAGE_SIZE;
2000 kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2001 (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2003 /* Account for memory used by an offpage slab header. */
2004 total = kl->slabsize;
2005 if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2006 total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2008 kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2012 * Determine the format of a uma keg. This determines where the slab header
2013 * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2016 * keg The zone we should initialize
2022 keg_layout(uma_keg_t keg)
2024 struct keg_layout_result kl = {}, kl_tmp;
2033 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2034 (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2035 (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2036 ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2037 __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2039 KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2040 (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2041 ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2044 alignsize = keg->uk_align + 1;
2047 * Calculate the size of each allocation (rsize) according to
2048 * alignment. If the requested size is smaller than we have
2049 * allocation bits for we round it up.
2051 rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2052 rsize = roundup2(rsize, alignsize);
2054 if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2056 * We want one item to start on every align boundary in a page.
2057 * To do this we will span pages. We will also extend the item
2058 * by the size of align if it is an even multiple of align.
2059 * Otherwise, it would fall on the same boundary every time.
2061 if ((rsize & alignsize) == 0)
2063 slabsize = rsize * (PAGE_SIZE / alignsize);
2064 slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2065 slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2066 slabsize = round_page(slabsize);
2069 * Start with a slab size of as many pages as it takes to
2070 * represent a single item. We will try to fit as many
2071 * additional items into the slab as possible.
2073 slabsize = round_page(keg->uk_size);
2076 /* Build a list of all of the available formats for this keg. */
2079 /* Evaluate an inline slab layout. */
2080 if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2083 /* TODO: vm_page-embedded slab. */
2086 * We can't do OFFPAGE if we're internal or if we've been
2087 * asked to not go to the VM for buckets. If we do this we
2088 * may end up going to the VM for slabs which we do not want
2089 * to do if we're UMA_ZONE_VM, which clearly forbids it.
2090 * In those cases, evaluate a pseudo-format called INTERNAL
2091 * which has an inline slab header and one extra page to
2092 * guarantee that it fits.
2094 * Otherwise, see if using an OFFPAGE slab will improve our
2097 if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2098 fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2100 fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2103 * Choose a slab size and format which satisfy the minimum efficiency.
2104 * Prefer the smallest slab size that meets the constraints.
2106 * Start with a minimum slab size, to accommodate CACHESPREAD. Then,
2107 * for small items (up to PAGE_SIZE), the iteration increment is one
2108 * page; and for large items, the increment is one item.
2110 i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2111 KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2112 keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2115 slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2116 round_page(rsize * (i - 1) + keg->uk_size);
2118 for (j = 0; j < nfmt; j++) {
2119 /* Only if we have no viable format yet. */
2120 if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2124 keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2125 if (kl_tmp.eff <= kl.eff)
2130 CTR6(KTR_UMA, "keg %s layout: format %#x "
2131 "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2132 keg->uk_name, kl.format, kl.ipers, rsize,
2133 kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2135 /* Stop when we reach the minimum efficiency. */
2136 if (kl.eff >= UMA_MIN_EFF)
2140 if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2141 slabsize >= SLAB_MAX_SETSIZE * rsize ||
2142 (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2146 pages = atop(kl.slabsize);
2147 if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2148 pages *= mp_maxid + 1;
2150 keg->uk_rsize = rsize;
2151 keg->uk_ipers = kl.ipers;
2152 keg->uk_ppera = pages;
2153 keg->uk_flags |= kl.format;
2156 * How do we find the slab header if it is offpage or if not all item
2157 * start addresses are in the same page? We could solve the latter
2158 * case with vaddr alignment, but we don't.
2160 if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2161 (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2162 if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2163 keg->uk_flags |= UMA_ZFLAG_HASH;
2165 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2168 CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2169 __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2171 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2172 ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2173 keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2174 keg->uk_ipers, pages));
2178 * Keg header ctor. This initializes all fields, locks, etc. And inserts
2179 * the keg onto the global keg list.
2181 * Arguments/Returns follow uma_ctor specifications
2182 * udata Actually uma_kctor_args
2185 keg_ctor(void *mem, int size, void *udata, int flags)
2187 struct uma_kctor_args *arg = udata;
2188 uma_keg_t keg = mem;
2193 keg->uk_size = arg->size;
2194 keg->uk_init = arg->uminit;
2195 keg->uk_fini = arg->fini;
2196 keg->uk_align = arg->align;
2197 keg->uk_reserve = 0;
2198 keg->uk_flags = arg->flags;
2201 * We use a global round-robin policy by default. Zones with
2202 * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2203 * case the iterator is never run.
2205 keg->uk_dr.dr_policy = DOMAINSET_RR();
2206 keg->uk_dr.dr_iter = 0;
2209 * The primary zone is passed to us at keg-creation time.
2212 keg->uk_name = zone->uz_name;
2214 if (arg->flags & UMA_ZONE_ZINIT)
2215 keg->uk_init = zero_init;
2217 if (arg->flags & UMA_ZONE_MALLOC)
2218 keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2221 keg->uk_flags &= ~UMA_ZONE_PCPU;
2227 * Use a first-touch NUMA policy for kegs that pmap_extract() will
2228 * work on. Use round-robin for everything else.
2230 * Zones may override the default by specifying either.
2233 if ((keg->uk_flags &
2234 (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2235 keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2236 else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2237 keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2241 * If we haven't booted yet we need allocations to go through the
2242 * startup cache until the vm is ready.
2244 #ifdef UMA_MD_SMALL_ALLOC
2245 if (keg->uk_ppera == 1)
2246 keg->uk_allocf = uma_small_alloc;
2249 if (booted < BOOT_KVA)
2250 keg->uk_allocf = startup_alloc;
2251 else if (keg->uk_flags & UMA_ZONE_PCPU)
2252 keg->uk_allocf = pcpu_page_alloc;
2253 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2254 keg->uk_allocf = contig_alloc;
2256 keg->uk_allocf = page_alloc;
2257 #ifdef UMA_MD_SMALL_ALLOC
2258 if (keg->uk_ppera == 1)
2259 keg->uk_freef = uma_small_free;
2262 if (keg->uk_flags & UMA_ZONE_PCPU)
2263 keg->uk_freef = pcpu_page_free;
2265 keg->uk_freef = page_free;
2268 * Initialize keg's locks.
2270 for (i = 0; i < vm_ndomains; i++)
2271 KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2274 * If we're putting the slab header in the actual page we need to
2275 * figure out where in each page it goes. See slab_sizeof
2278 if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2281 shsize = slab_sizeof(keg->uk_ipers);
2282 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2284 * The only way the following is possible is if with our
2285 * UMA_ALIGN_PTR adjustments we are now bigger than
2286 * UMA_SLAB_SIZE. I haven't checked whether this is
2287 * mathematically possible for all cases, so we make
2290 KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2291 ("zone %s ipers %d rsize %d size %d slab won't fit",
2292 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2295 if (keg->uk_flags & UMA_ZFLAG_HASH)
2296 hash_alloc(&keg->uk_hash, 0);
2298 CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2300 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2302 rw_wlock(&uma_rwlock);
2303 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2304 rw_wunlock(&uma_rwlock);
2309 zone_kva_available(uma_zone_t zone, void *unused)
2313 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2317 if (keg->uk_allocf == startup_alloc) {
2318 /* Switch to the real allocator. */
2319 if (keg->uk_flags & UMA_ZONE_PCPU)
2320 keg->uk_allocf = pcpu_page_alloc;
2321 else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2323 keg->uk_allocf = contig_alloc;
2325 keg->uk_allocf = page_alloc;
2330 zone_alloc_counters(uma_zone_t zone, void *unused)
2333 zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2334 zone->uz_frees = counter_u64_alloc(M_WAITOK);
2335 zone->uz_fails = counter_u64_alloc(M_WAITOK);
2336 zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2340 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2342 uma_zone_domain_t zdom;
2345 struct sysctl_oid *oid, *domainoid;
2346 int domains, i, cnt;
2347 static const char *nokeg = "cache zone";
2351 * Make a sysctl safe copy of the zone name by removing
2352 * any special characters and handling dups by appending
2355 if (zone->uz_namecnt != 0) {
2356 /* Count the number of decimal digits and '_' separator. */
2357 for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2359 zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2361 sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2364 zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2365 for (c = zone->uz_ctlname; *c != '\0'; c++)
2366 if (strchr("./\\ -", *c) != NULL)
2370 * Basic parameters at the root.
2372 zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2373 OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2375 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2376 "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2377 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2378 "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2379 zone, 0, sysctl_handle_uma_zone_flags, "A",
2380 "Allocator configuration flags");
2381 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2382 "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2383 "Desired per-cpu cache size");
2384 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2385 "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2386 "Maximum allowed per-cpu cache size");
2391 if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2392 domains = vm_ndomains;
2395 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2396 "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2398 if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2399 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2400 "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2401 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2402 "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2403 "Real object size with alignment");
2404 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2405 "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2406 "pages per-slab allocation");
2407 SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2408 "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2409 "items available per-slab");
2410 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2411 "align", CTLFLAG_RD, &keg->uk_align, 0,
2412 "item alignment mask");
2413 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2414 "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2415 keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2416 "Slab utilization (100 - internal fragmentation %)");
2417 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2418 OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2419 for (i = 0; i < domains; i++) {
2420 dom = &keg->uk_domain[i];
2421 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2422 OID_AUTO, VM_DOMAIN(i)->vmd_name,
2423 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2424 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2425 "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2426 "Total pages currently allocated from VM");
2427 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2428 "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2429 "items free in the slab layer");
2432 SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2433 "name", CTLFLAG_RD, nokeg, "Keg name");
2436 * Information about zone limits.
2438 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2439 "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2440 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2441 "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2442 zone, 0, sysctl_handle_uma_zone_items, "QU",
2443 "current number of allocated items if limit is set");
2444 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2445 "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2446 "Maximum number of cached items");
2447 SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2448 "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2449 "Number of threads sleeping at limit");
2450 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2451 "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2452 "Total zone limit sleeps");
2453 SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2454 "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2455 "Maximum number of items in each domain's bucket cache");
2458 * Per-domain zone information.
2460 domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2461 OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2462 for (i = 0; i < domains; i++) {
2463 zdom = ZDOM_GET(zone, i);
2464 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2465 OID_AUTO, VM_DOMAIN(i)->vmd_name,
2466 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2467 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2468 "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2469 "number of items in this domain");
2470 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2471 "imax", CTLFLAG_RD, &zdom->uzd_imax,
2472 "maximum item count in this period");
2473 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2474 "imin", CTLFLAG_RD, &zdom->uzd_imin,
2475 "minimum item count in this period");
2476 SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2477 "wss", CTLFLAG_RD, &zdom->uzd_wss,
2478 "Working set size");
2482 * General statistics.
2484 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2485 "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2486 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2487 "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2488 zone, 1, sysctl_handle_uma_zone_cur, "I",
2489 "Current number of allocated items");
2490 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2491 "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2492 zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2493 "Total allocation calls");
2494 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2495 "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2496 zone, 0, sysctl_handle_uma_zone_frees, "QU",
2497 "Total free calls");
2498 SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2499 "fails", CTLFLAG_RD, &zone->uz_fails,
2500 "Number of allocation failures");
2501 SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2502 "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2503 "Free calls from the wrong domain");
2506 struct uma_zone_count {
2512 zone_count(uma_zone_t zone, void *arg)
2514 struct uma_zone_count *cnt;
2518 * Some zones are rapidly created with identical names and
2519 * destroyed out of order. This can lead to gaps in the count.
2520 * Use one greater than the maximum observed for this name.
2522 if (strcmp(zone->uz_name, cnt->name) == 0)
2523 cnt->count = MAX(cnt->count,
2524 zone->uz_namecnt + 1);
2528 zone_update_caches(uma_zone_t zone)
2532 for (i = 0; i <= mp_maxid; i++) {
2533 cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2534 cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2539 * Zone header ctor. This initializes all fields, locks, etc.
2541 * Arguments/Returns follow uma_ctor specifications
2542 * udata Actually uma_zctor_args
2545 zone_ctor(void *mem, int size, void *udata, int flags)
2547 struct uma_zone_count cnt;
2548 struct uma_zctor_args *arg = udata;
2549 uma_zone_domain_t zdom;
2550 uma_zone_t zone = mem;
2556 zone->uz_name = arg->name;
2557 zone->uz_ctor = arg->ctor;
2558 zone->uz_dtor = arg->dtor;
2559 zone->uz_init = NULL;
2560 zone->uz_fini = NULL;
2561 zone->uz_sleeps = 0;
2562 zone->uz_bucket_size = 0;
2563 zone->uz_bucket_size_min = 0;
2564 zone->uz_bucket_size_max = BUCKET_MAX;
2565 zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2566 zone->uz_warning = NULL;
2567 /* The domain structures follow the cpu structures. */
2568 zone->uz_bucket_max = ULONG_MAX;
2569 timevalclear(&zone->uz_ratecheck);
2571 /* Count the number of duplicate names. */
2572 cnt.name = arg->name;
2574 zone_foreach(zone_count, &cnt);
2575 zone->uz_namecnt = cnt.count;
2576 ZONE_CROSS_LOCK_INIT(zone);
2578 for (i = 0; i < vm_ndomains; i++) {
2579 zdom = ZDOM_GET(zone, i);
2580 ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2581 STAILQ_INIT(&zdom->uzd_buckets);
2585 if (arg->uminit == trash_init && arg->fini == trash_fini)
2586 zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2590 * This is a pure cache zone, no kegs.
2593 KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2594 ("zone_ctor: Import specified for non-cache zone."));
2595 zone->uz_flags = arg->flags;
2596 zone->uz_size = arg->size;
2597 zone->uz_import = arg->import;
2598 zone->uz_release = arg->release;
2599 zone->uz_arg = arg->arg;
2602 * Cache zones are round-robin unless a policy is
2603 * specified because they may have incompatible
2606 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2607 zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2609 rw_wlock(&uma_rwlock);
2610 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2611 rw_wunlock(&uma_rwlock);
2616 * Use the regular zone/keg/slab allocator.
2618 zone->uz_import = zone_import;
2619 zone->uz_release = zone_release;
2620 zone->uz_arg = zone;
2623 if (arg->flags & UMA_ZONE_SECONDARY) {
2624 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2625 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2626 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2627 zone->uz_init = arg->uminit;
2628 zone->uz_fini = arg->fini;
2629 zone->uz_flags |= UMA_ZONE_SECONDARY;
2630 rw_wlock(&uma_rwlock);
2632 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2633 if (LIST_NEXT(z, uz_link) == NULL) {
2634 LIST_INSERT_AFTER(z, zone, uz_link);
2639 rw_wunlock(&uma_rwlock);
2640 } else if (keg == NULL) {
2641 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2642 arg->align, arg->flags)) == NULL)
2645 struct uma_kctor_args karg;
2648 /* We should only be here from uma_startup() */
2649 karg.size = arg->size;
2650 karg.uminit = arg->uminit;
2651 karg.fini = arg->fini;
2652 karg.align = arg->align;
2653 karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2655 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2661 /* Inherit properties from the keg. */
2663 zone->uz_size = keg->uk_size;
2664 zone->uz_flags |= (keg->uk_flags &
2665 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2668 if (booted >= BOOT_PCPU) {
2669 zone_alloc_counters(zone, NULL);
2670 if (booted >= BOOT_RUNNING)
2671 zone_alloc_sysctl(zone, NULL);
2673 zone->uz_allocs = EARLY_COUNTER;
2674 zone->uz_frees = EARLY_COUNTER;
2675 zone->uz_fails = EARLY_COUNTER;
2678 /* Caller requests a private SMR context. */
2679 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2680 zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2682 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2683 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2684 ("Invalid zone flag combination"));
2685 if (arg->flags & UMA_ZFLAG_INTERNAL)
2686 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2687 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2688 zone->uz_bucket_size = BUCKET_MAX;
2689 else if ((arg->flags & UMA_ZONE_MINBUCKET) != 0)
2690 zone->uz_bucket_size_max = zone->uz_bucket_size = BUCKET_MIN;
2691 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2692 zone->uz_bucket_size = 0;
2694 zone->uz_bucket_size = bucket_select(zone->uz_size);
2695 zone->uz_bucket_size_min = zone->uz_bucket_size;
2696 if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2697 zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2698 zone_update_caches(zone);
2704 * Keg header dtor. This frees all data, destroys locks, frees the hash
2705 * table and removes the keg from the global list.
2707 * Arguments/Returns follow uma_dtor specifications
2711 keg_dtor(void *arg, int size, void *udata)
2714 uint32_t free, pages;
2717 keg = (uma_keg_t)arg;
2719 for (i = 0; i < vm_ndomains; i++) {
2720 free += keg->uk_domain[i].ud_free_items;
2721 pages += keg->uk_domain[i].ud_pages;
2722 KEG_LOCK_FINI(keg, i);
2725 printf("Freed UMA keg (%s) was not empty (%u items). "
2726 " Lost %u pages of memory.\n",
2727 keg->uk_name ? keg->uk_name : "",
2728 pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2730 hash_free(&keg->uk_hash);
2736 * Arguments/Returns follow uma_dtor specifications
2740 zone_dtor(void *arg, int size, void *udata)
2746 zone = (uma_zone_t)arg;
2748 sysctl_remove_oid(zone->uz_oid, 1, 1);
2750 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2753 rw_wlock(&uma_rwlock);
2754 LIST_REMOVE(zone, uz_link);
2755 rw_wunlock(&uma_rwlock);
2756 zone_reclaim(zone, M_WAITOK, true);
2759 * We only destroy kegs from non secondary/non cache zones.
2761 if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2763 rw_wlock(&uma_rwlock);
2764 LIST_REMOVE(keg, uk_link);
2765 rw_wunlock(&uma_rwlock);
2766 zone_free_item(kegs, keg, NULL, SKIP_NONE);
2768 counter_u64_free(zone->uz_allocs);
2769 counter_u64_free(zone->uz_frees);
2770 counter_u64_free(zone->uz_fails);
2771 counter_u64_free(zone->uz_xdomain);
2772 free(zone->uz_ctlname, M_UMA);
2773 for (i = 0; i < vm_ndomains; i++)
2774 ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2775 ZONE_CROSS_LOCK_FINI(zone);
2779 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2784 LIST_FOREACH(keg, &uma_kegs, uk_link) {
2785 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2788 LIST_FOREACH(zone, &uma_cachezones, uz_link)
2793 * Traverses every zone in the system and calls a callback
2796 * zfunc A pointer to a function which accepts a zone
2803 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2806 rw_rlock(&uma_rwlock);
2807 zone_foreach_unlocked(zfunc, arg);
2808 rw_runlock(&uma_rwlock);
2812 * Initialize the kernel memory allocator. This is done after pages can be
2813 * allocated but before general KVA is available.
2816 uma_startup1(vm_offset_t virtual_avail)
2818 struct uma_zctor_args args;
2819 size_t ksize, zsize, size;
2820 uma_keg_t primarykeg;
2825 bootstart = bootmem = virtual_avail;
2827 rw_init(&uma_rwlock, "UMA lock");
2828 sx_init(&uma_reclaim_lock, "umareclaim");
2830 ksize = sizeof(struct uma_keg) +
2831 (sizeof(struct uma_domain) * vm_ndomains);
2832 ksize = roundup(ksize, UMA_SUPER_ALIGN);
2833 zsize = sizeof(struct uma_zone) +
2834 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2835 (sizeof(struct uma_zone_domain) * vm_ndomains);
2836 zsize = roundup(zsize, UMA_SUPER_ALIGN);
2838 /* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2839 size = (zsize * 2) + ksize;
2840 for (domain = 0; domain < vm_ndomains; domain++) {
2841 m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2846 zones = (uma_zone_t)m;
2848 kegs = (uma_zone_t)m;
2850 primarykeg = (uma_keg_t)m;
2852 /* "manually" create the initial zone */
2853 memset(&args, 0, sizeof(args));
2854 args.name = "UMA Kegs";
2856 args.ctor = keg_ctor;
2857 args.dtor = keg_dtor;
2858 args.uminit = zero_init;
2860 args.keg = primarykeg;
2861 args.align = UMA_SUPER_ALIGN - 1;
2862 args.flags = UMA_ZFLAG_INTERNAL;
2863 zone_ctor(kegs, zsize, &args, M_WAITOK);
2865 args.name = "UMA Zones";
2867 args.ctor = zone_ctor;
2868 args.dtor = zone_dtor;
2869 args.uminit = zero_init;
2872 args.align = UMA_SUPER_ALIGN - 1;
2873 args.flags = UMA_ZFLAG_INTERNAL;
2874 zone_ctor(zones, zsize, &args, M_WAITOK);
2876 /* Now make zones for slab headers */
2877 slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
2878 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2879 slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
2880 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2882 hashzone = uma_zcreate("UMA Hash",
2883 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2884 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2890 #ifndef UMA_MD_SMALL_ALLOC
2891 extern void vm_radix_reserve_kva(void);
2895 * Advertise the availability of normal kva allocations and switch to
2896 * the default back-end allocator. Marks the KVA we consumed on startup
2897 * as used in the map.
2903 if (bootstart != bootmem) {
2904 vm_map_lock(kernel_map);
2905 (void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
2906 VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2907 vm_map_unlock(kernel_map);
2910 #ifndef UMA_MD_SMALL_ALLOC
2911 /* Set up radix zone to use noobj_alloc. */
2912 vm_radix_reserve_kva();
2916 zone_foreach_unlocked(zone_kva_available, NULL);
2921 * Allocate counters as early as possible so that boot-time allocations are
2922 * accounted more precisely.
2925 uma_startup_pcpu(void *arg __unused)
2928 zone_foreach_unlocked(zone_alloc_counters, NULL);
2931 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
2934 * Finish our initialization steps.
2937 uma_startup3(void *arg __unused)
2941 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2942 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2943 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2945 zone_foreach_unlocked(zone_alloc_sysctl, NULL);
2946 callout_init(&uma_callout, 1);
2947 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2948 booted = BOOT_RUNNING;
2950 EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
2951 EVENTHANDLER_PRI_FIRST);
2953 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
2959 booted = BOOT_SHUTDOWN;
2963 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2964 int align, uint32_t flags)
2966 struct uma_kctor_args args;
2969 args.uminit = uminit;
2971 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2974 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2977 /* Public functions */
2980 uma_set_align(int align)
2983 if (align != UMA_ALIGN_CACHE)
2984 uma_align_cache = align;
2989 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2990 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2993 struct uma_zctor_args args;
2996 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2999 /* This stuff is essential for the zone ctor */
3000 memset(&args, 0, sizeof(args));
3005 args.uminit = uminit;
3009 * Inject procedures which check for memory use after free if we are
3010 * allowed to scramble the memory while it is not allocated. This
3011 * requires that: UMA is actually able to access the memory, no init
3012 * or fini procedures, no dependency on the initial value of the
3013 * memory, and no (legitimate) use of the memory after free. Note,
3014 * the ctor and dtor do not need to be empty.
3016 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3017 UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3018 args.uminit = trash_init;
3019 args.fini = trash_fini;
3026 sx_slock(&uma_reclaim_lock);
3027 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3028 sx_sunlock(&uma_reclaim_lock);
3035 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3036 uma_init zinit, uma_fini zfini, uma_zone_t primary)
3038 struct uma_zctor_args args;
3042 keg = primary->uz_keg;
3043 memset(&args, 0, sizeof(args));
3045 args.size = keg->uk_size;
3048 args.uminit = zinit;
3050 args.align = keg->uk_align;
3051 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3054 sx_slock(&uma_reclaim_lock);
3055 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3056 sx_sunlock(&uma_reclaim_lock);
3063 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3064 uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3065 void *arg, int flags)
3067 struct uma_zctor_args args;
3069 memset(&args, 0, sizeof(args));
3074 args.uminit = zinit;
3076 args.import = zimport;
3077 args.release = zrelease;
3080 args.flags = flags | UMA_ZFLAG_CACHE;
3082 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3087 uma_zdestroy(uma_zone_t zone)
3091 * Large slabs are expensive to reclaim, so don't bother doing
3092 * unnecessary work if we're shutting down.
3094 if (booted == BOOT_SHUTDOWN &&
3095 zone->uz_fini == NULL && zone->uz_release == zone_release)
3097 sx_slock(&uma_reclaim_lock);
3098 zone_free_item(zones, zone, NULL, SKIP_NONE);
3099 sx_sunlock(&uma_reclaim_lock);
3103 uma_zwait(uma_zone_t zone)
3106 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3107 uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3108 else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3109 uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3111 uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3115 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3117 void *item, *pcpu_item;
3121 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3123 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3126 pcpu_item = zpcpu_base_to_offset(item);
3127 if (flags & M_ZERO) {
3129 for (i = 0; i <= mp_maxid; i++)
3130 bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3132 bzero(item, zone->uz_size);
3139 * A stub while both regular and pcpu cases are identical.
3142 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3147 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3149 item = zpcpu_offset_to_base(pcpu_item);
3150 uma_zfree_arg(zone, item, udata);
3153 static inline void *
3154 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3160 skipdbg = uma_dbg_zskip(zone, item);
3161 if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3162 zone->uz_ctor != trash_ctor)
3163 trash_ctor(item, size, udata, flags);
3165 /* Check flags before loading ctor pointer. */
3166 if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3167 __predict_false(zone->uz_ctor != NULL) &&
3168 zone->uz_ctor(item, size, udata, flags) != 0) {
3169 counter_u64_add(zone->uz_fails, 1);
3170 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3175 uma_dbg_alloc(zone, NULL, item);
3177 if (__predict_false(flags & M_ZERO))
3178 return (memset(item, 0, size));
3184 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3185 enum zfreeskip skip)
3190 skipdbg = uma_dbg_zskip(zone, item);
3191 if (skip == SKIP_NONE && !skipdbg) {
3192 if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3193 uma_dbg_free(zone, udata, item);
3195 uma_dbg_free(zone, NULL, item);
3198 if (__predict_true(skip < SKIP_DTOR)) {
3199 if (zone->uz_dtor != NULL)
3200 zone->uz_dtor(item, size, udata);
3202 if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3203 zone->uz_dtor != trash_dtor)
3204 trash_dtor(item, size, udata);
3211 item_domain(void *item)
3215 domain = _vm_phys_domain(vtophys(item));
3216 KASSERT(domain >= 0 && domain < vm_ndomains,
3217 ("%s: unknown domain for item %p", __func__, item));
3222 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3223 #define UMA_ZALLOC_DEBUG
3225 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3231 if (flags & M_WAITOK) {
3232 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3233 "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3238 KASSERT((flags & M_EXEC) == 0,
3239 ("uma_zalloc_debug: called with M_EXEC"));
3240 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3241 ("uma_zalloc_debug: called within spinlock or critical section"));
3242 KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3243 ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3246 #ifdef DEBUG_MEMGUARD
3247 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3249 item = memguard_alloc(zone->uz_size, flags);
3251 error = EJUSTRETURN;
3252 if (zone->uz_init != NULL &&
3253 zone->uz_init(item, zone->uz_size, flags) != 0) {
3257 if (zone->uz_ctor != NULL &&
3258 zone->uz_ctor(item, zone->uz_size, udata,
3260 counter_u64_add(zone->uz_fails, 1);
3261 zone->uz_fini(item, zone->uz_size);
3268 /* This is unfortunate but should not be fatal. */
3275 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3277 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3278 ("uma_zfree_debug: called with spinlock or critical section held"));
3280 #ifdef DEBUG_MEMGUARD
3281 if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3282 if (zone->uz_dtor != NULL)
3283 zone->uz_dtor(item, zone->uz_size, udata);
3284 if (zone->uz_fini != NULL)
3285 zone->uz_fini(item, zone->uz_size);
3286 memguard_free(item);
3287 return (EJUSTRETURN);
3294 static inline void *
3295 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3296 void *udata, int flags)
3301 item = cache_bucket_pop(cache, bucket);
3302 size = cache_uz_size(cache);
3303 uz_flags = cache_uz_flags(cache);
3305 return (item_ctor(zone, uz_flags, size, udata, flags, item));
3308 static __noinline void *
3309 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3311 uma_cache_bucket_t bucket;
3314 while (cache_alloc(zone, cache, udata, flags)) {
3315 cache = &zone->uz_cpu[curcpu];
3316 bucket = &cache->uc_allocbucket;
3317 if (__predict_false(bucket->ucb_cnt == 0))
3319 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3324 * We can not get a bucket so try to return a single item.
3326 if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3327 domain = PCPU_GET(domain);
3329 domain = UMA_ANYDOMAIN;
3330 return (zone_alloc_item(zone, udata, domain, flags));
3335 uma_zalloc_smr(uma_zone_t zone, int flags)
3337 uma_cache_bucket_t bucket;
3340 #ifdef UMA_ZALLOC_DEBUG
3343 KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3344 ("uma_zalloc_arg: called with non-SMR zone."));
3345 if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3350 cache = &zone->uz_cpu[curcpu];
3351 bucket = &cache->uc_allocbucket;
3352 if (__predict_false(bucket->ucb_cnt == 0))
3353 return (cache_alloc_retry(zone, cache, NULL, flags));
3354 return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3359 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3361 uma_cache_bucket_t bucket;
3364 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3365 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3367 /* This is the fast path allocation */
3368 CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3371 #ifdef UMA_ZALLOC_DEBUG
3374 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3375 ("uma_zalloc_arg: called with SMR zone."));
3376 if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3381 * If possible, allocate from the per-CPU cache. There are two
3382 * requirements for safe access to the per-CPU cache: (1) the thread
3383 * accessing the cache must not be preempted or yield during access,
3384 * and (2) the thread must not migrate CPUs without switching which
3385 * cache it accesses. We rely on a critical section to prevent
3386 * preemption and migration. We release the critical section in
3387 * order to acquire the zone mutex if we are unable to allocate from
3388 * the current cache; when we re-acquire the critical section, we
3389 * must detect and handle migration if it has occurred.
3392 cache = &zone->uz_cpu[curcpu];
3393 bucket = &cache->uc_allocbucket;
3394 if (__predict_false(bucket->ucb_cnt == 0))
3395 return (cache_alloc_retry(zone, cache, udata, flags));
3396 return (cache_alloc_item(zone, cache, bucket, udata, flags));
3400 * Replenish an alloc bucket and possibly restore an old one. Called in
3401 * a critical section. Returns in a critical section.
3403 * A false return value indicates an allocation failure.
3404 * A true return value indicates success and the caller should retry.
3406 static __noinline bool
3407 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3409 uma_bucket_t bucket;
3410 int curdomain, domain;
3413 CRITICAL_ASSERT(curthread);
3416 * If we have run out of items in our alloc bucket see
3417 * if we can switch with the free bucket.
3419 * SMR Zones can't re-use the free bucket until the sequence has
3422 if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3423 cache->uc_freebucket.ucb_cnt != 0) {
3424 cache_bucket_swap(&cache->uc_freebucket,
3425 &cache->uc_allocbucket);
3430 * Discard any empty allocation bucket while we hold no locks.
3432 bucket = cache_bucket_unload_alloc(cache);
3435 if (bucket != NULL) {
3436 KASSERT(bucket->ub_cnt == 0,
3437 ("cache_alloc: Entered with non-empty alloc bucket."));
3438 bucket_free(zone, bucket, udata);
3442 * Attempt to retrieve the item from the per-CPU cache has failed, so
3443 * we must go back to the zone. This requires the zdom lock, so we
3444 * must drop the critical section, then re-acquire it when we go back
3445 * to the cache. Since the critical section is released, we may be
3446 * preempted or migrate. As such, make sure not to maintain any
3447 * thread-local state specific to the cache from prior to releasing
3448 * the critical section.
3450 domain = PCPU_GET(domain);
3451 if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3452 VM_DOMAIN_EMPTY(domain))
3453 domain = zone_domain_highest(zone, domain);
3454 bucket = cache_fetch_bucket(zone, cache, domain);
3455 if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3456 bucket = zone_alloc_bucket(zone, udata, domain, flags);
3462 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3463 zone->uz_name, zone, bucket);
3464 if (bucket == NULL) {
3470 * See if we lost the race or were migrated. Cache the
3471 * initialized bucket to make this less likely or claim
3472 * the memory directly.
3475 cache = &zone->uz_cpu[curcpu];
3476 if (cache->uc_allocbucket.ucb_bucket == NULL &&
3477 ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3478 (curdomain = PCPU_GET(domain)) == domain ||
3479 VM_DOMAIN_EMPTY(curdomain))) {
3481 atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3483 cache_bucket_load_alloc(cache, bucket);
3488 * We lost the race, release this bucket and start over.
3491 zone_put_bucket(zone, domain, bucket, udata, false);
3498 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3501 uma_bucket_t bucket;
3502 uma_zone_domain_t zdom;
3506 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3507 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3509 /* This is the fast path allocation */
3510 CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3511 zone->uz_name, zone, domain, flags);
3513 if (flags & M_WAITOK) {
3514 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3515 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3517 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3518 ("uma_zalloc_domain: called with spinlock or critical section held"));
3519 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3520 ("uma_zalloc_domain: called with SMR zone."));
3522 KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3523 ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3525 if (vm_ndomains == 1)
3526 return (uma_zalloc_arg(zone, udata, flags));
3529 * Try to allocate from the bucket cache before falling back to the keg.
3530 * We could try harder and attempt to allocate from per-CPU caches or
3531 * the per-domain cross-domain buckets, but the complexity is probably
3532 * not worth it. It is more important that frees of previous
3533 * cross-domain allocations do not blow up the cache.
3535 zdom = zone_domain_lock(zone, domain);
3536 if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3537 item = bucket->ub_bucket[bucket->ub_cnt - 1];
3539 bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3542 zone_put_bucket(zone, domain, bucket, udata, true);
3543 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3546 KASSERT(item_domain(item) == domain,
3547 ("%s: bucket cache item %p from wrong domain",
3549 counter_u64_add(zone->uz_allocs, 1);
3554 return (zone_alloc_item(zone, udata, domain, flags));
3556 return (uma_zalloc_arg(zone, udata, flags));
3561 * Find a slab with some space. Prefer slabs that are partially used over those
3562 * that are totally full. This helps to reduce fragmentation.
3564 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
3568 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3574 KASSERT(domain >= 0 && domain < vm_ndomains,
3575 ("keg_first_slab: domain %d out of range", domain));
3576 KEG_LOCK_ASSERT(keg, domain);
3581 dom = &keg->uk_domain[domain];
3582 if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3584 if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3585 LIST_REMOVE(slab, us_link);
3586 dom->ud_free_slabs--;
3587 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3591 domain = (domain + 1) % vm_ndomains;
3592 } while (domain != start);
3598 * Fetch an existing slab from a free or partial list. Returns with the
3599 * keg domain lock held if a slab was found or unlocked if not.
3602 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3607 /* HASH has a single free list. */
3608 if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3611 KEG_LOCK(keg, domain);
3612 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3613 if (keg->uk_domain[domain].ud_free_items <= reserve ||
3614 (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3615 KEG_UNLOCK(keg, domain);
3622 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3624 struct vm_domainset_iter di;
3631 * Use the keg's policy if upper layers haven't already specified a
3632 * domain (as happens with first-touch zones).
3634 * To avoid races we run the iterator with the keg lock held, but that
3635 * means that we cannot allow the vm_domainset layer to sleep. Thus,
3636 * clear M_WAITOK and handle low memory conditions locally.
3638 rr = rdomain == UMA_ANYDOMAIN;
3640 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3641 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3649 slab = keg_fetch_free_slab(keg, domain, rr, flags);
3654 * M_NOVM means don't ask at all!
3659 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3662 if (!rr && (flags & M_WAITOK) == 0)
3664 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3665 if ((flags & M_WAITOK) != 0) {
3666 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3674 * We might not have been able to get a slab but another cpu
3675 * could have while we were unlocked. Check again before we
3678 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3685 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3691 KEG_LOCK_ASSERT(keg, slab->us_domain);
3693 dom = &keg->uk_domain[slab->us_domain];
3694 freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3695 BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3696 item = slab_item(slab, keg, freei);
3697 slab->us_freecount--;
3698 dom->ud_free_items--;
3701 * Move this slab to the full list. It must be on the partial list, so
3702 * we do not need to update the free slab count. In particular,
3703 * keg_fetch_slab() always returns slabs on the partial list.
3705 if (slab->us_freecount == 0) {
3706 LIST_REMOVE(slab, us_link);
3707 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3714 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3728 /* Try to keep the buckets totally full */
3729 for (i = 0; i < max; ) {
3730 if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3733 stripe = howmany(max, vm_ndomains);
3735 dom = &keg->uk_domain[slab->us_domain];
3736 while (slab->us_freecount && i < max) {
3737 bucket[i++] = slab_alloc_item(keg, slab);
3738 if (dom->ud_free_items <= keg->uk_reserve)
3742 * If the zone is striped we pick a new slab for every
3743 * N allocations. Eliminating this conditional will
3744 * instead pick a new domain for each bucket rather
3745 * than stripe within each bucket. The current option
3746 * produces more fragmentation and requires more cpu
3747 * time but yields better distribution.
3749 if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3750 vm_ndomains > 1 && --stripe == 0)
3754 KEG_UNLOCK(keg, slab->us_domain);
3755 /* Don't block if we allocated any successfully. */
3764 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3766 uint64_t old, new, total, max;
3769 * The hard case. We're going to sleep because there were existing
3770 * sleepers or because we ran out of items. This routine enforces
3771 * fairness by keeping fifo order.
3773 * First release our ill gotten gains and make some noise.
3776 zone_free_limit(zone, count);
3777 zone_log_warning(zone);
3778 zone_maxaction(zone);
3779 if (flags & M_NOWAIT)
3783 * We need to allocate an item or set ourself as a sleeper
3784 * while the sleepq lock is held to avoid wakeup races. This
3785 * is essentially a home rolled semaphore.
3787 sleepq_lock(&zone->uz_max_items);
3788 old = zone->uz_items;
3790 MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3791 /* Cache the max since we will evaluate twice. */
3792 max = zone->uz_max_items;
3793 if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3794 UZ_ITEMS_COUNT(old) >= max)
3795 new = old + UZ_ITEMS_SLEEPER;
3797 new = old + MIN(count, max - old);
3798 } while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3800 /* We may have successfully allocated under the sleepq lock. */
3801 if (UZ_ITEMS_SLEEPERS(new) == 0) {
3802 sleepq_release(&zone->uz_max_items);
3807 * This is in a different cacheline from uz_items so that we
3808 * don't constantly invalidate the fastpath cacheline when we
3809 * adjust item counts. This could be limited to toggling on
3812 atomic_add_32(&zone->uz_sleepers, 1);
3813 atomic_add_64(&zone->uz_sleeps, 1);
3816 * We have added ourselves as a sleeper. The sleepq lock
3817 * protects us from wakeup races. Sleep now and then retry.
3819 sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3820 sleepq_wait(&zone->uz_max_items, PVM);
3823 * After wakeup, remove ourselves as a sleeper and try
3824 * again. We no longer have the sleepq lock for protection.
3826 * Subract ourselves as a sleeper while attempting to add
3829 atomic_subtract_32(&zone->uz_sleepers, 1);
3830 old = atomic_fetchadd_64(&zone->uz_items,
3831 -(UZ_ITEMS_SLEEPER - count));
3832 /* We're no longer a sleeper. */
3833 old -= UZ_ITEMS_SLEEPER;
3836 * If we're still at the limit, restart. Notably do not
3837 * block on other sleepers. Cache the max value to protect
3838 * against changes via sysctl.
3840 total = UZ_ITEMS_COUNT(old);
3841 max = zone->uz_max_items;
3844 /* Truncate if necessary, otherwise wake other sleepers. */
3845 if (total + count > max) {
3846 zone_free_limit(zone, total + count - max);
3847 count = max - total;
3848 } else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
3849 wakeup_one(&zone->uz_max_items);
3856 * Allocate 'count' items from our max_items limit. Returns the number
3857 * available. If M_NOWAIT is not specified it will sleep until at least
3858 * one item can be allocated.
3861 zone_alloc_limit(uma_zone_t zone, int count, int flags)
3866 max = zone->uz_max_items;
3870 * We expect normal allocations to succeed with a simple
3873 old = atomic_fetchadd_64(&zone->uz_items, count);
3874 if (__predict_true(old + count <= max))
3878 * If we had some items and no sleepers just return the
3879 * truncated value. We have to release the excess space
3880 * though because that may wake sleepers who weren't woken
3881 * because we were temporarily over the limit.
3884 zone_free_limit(zone, (old + count) - max);
3887 return (zone_alloc_limit_hard(zone, count, flags));
3891 * Free a number of items back to the limit.
3894 zone_free_limit(uma_zone_t zone, int count)
3901 * In the common case we either have no sleepers or
3902 * are still over the limit and can just return.
3904 old = atomic_fetchadd_64(&zone->uz_items, -count);
3905 if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
3906 UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
3910 * Moderate the rate of wakeups. Sleepers will continue
3911 * to generate wakeups if necessary.
3913 wakeup_one(&zone->uz_max_items);
3917 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
3919 uma_bucket_t bucket;
3922 CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
3925 /* Avoid allocs targeting empty domains. */
3926 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
3927 domain = UMA_ANYDOMAIN;
3928 else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
3929 domain = UMA_ANYDOMAIN;
3931 if (zone->uz_max_items > 0)
3932 maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
3935 maxbucket = zone->uz_bucket_size;
3939 /* Don't wait for buckets, preserve caller's NOVM setting. */
3940 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
3941 if (bucket == NULL) {
3946 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
3947 MIN(maxbucket, bucket->ub_entries), domain, flags);
3950 * Initialize the memory if necessary.
3952 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
3955 for (i = 0; i < bucket->ub_cnt; i++)
3956 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
3960 * If we couldn't initialize the whole bucket, put the
3961 * rest back onto the freelist.
3963 if (i != bucket->ub_cnt) {
3964 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
3965 bucket->ub_cnt - i);
3967 bzero(&bucket->ub_bucket[i],
3968 sizeof(void *) * (bucket->ub_cnt - i));
3974 cnt = bucket->ub_cnt;
3975 if (bucket->ub_cnt == 0) {
3976 bucket_free(zone, bucket, udata);
3977 counter_u64_add(zone->uz_fails, 1);
3981 if (zone->uz_max_items > 0 && cnt < maxbucket)
3982 zone_free_limit(zone, maxbucket - cnt);
3988 * Allocates a single item from a zone.
3991 * zone The zone to alloc for.
3992 * udata The data to be passed to the constructor.
3993 * domain The domain to allocate from or UMA_ANYDOMAIN.
3994 * flags M_WAITOK, M_NOWAIT, M_ZERO.
3997 * NULL if there is no memory and M_NOWAIT is set
3998 * An item if successful
4002 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4006 if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4007 counter_u64_add(zone->uz_fails, 1);
4011 /* Avoid allocs targeting empty domains. */
4012 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4013 domain = UMA_ANYDOMAIN;
4015 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4019 * We have to call both the zone's init (not the keg's init)
4020 * and the zone's ctor. This is because the item is going from
4021 * a keg slab directly to the user, and the user is expecting it
4022 * to be both zone-init'd as well as zone-ctor'd.
4024 if (zone->uz_init != NULL) {
4025 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
4026 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4030 item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4035 counter_u64_add(zone->uz_allocs, 1);
4036 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4037 zone->uz_name, zone);
4042 counter_u64_add(zone->uz_fails, 1);
4044 if (zone->uz_max_items > 0)
4045 zone_free_limit(zone, 1);
4046 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4047 zone->uz_name, zone);
4054 uma_zfree_smr(uma_zone_t zone, void *item)
4057 uma_cache_bucket_t bucket;
4058 int itemdomain, uz_flags;
4060 #ifdef UMA_ZALLOC_DEBUG
4061 KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4062 ("uma_zfree_smr: called with non-SMR zone."));
4063 KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4064 SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4065 if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4068 cache = &zone->uz_cpu[curcpu];
4069 uz_flags = cache_uz_flags(cache);
4072 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4073 itemdomain = item_domain(item);
4077 cache = &zone->uz_cpu[curcpu];
4078 /* SMR Zones must free to the free bucket. */
4079 bucket = &cache->uc_freebucket;
4081 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4082 PCPU_GET(domain) != itemdomain) {
4083 bucket = &cache->uc_crossbucket;
4086 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4087 cache_bucket_push(cache, bucket, item);
4091 } while (cache_free(zone, cache, NULL, item, itemdomain));
4095 * If nothing else caught this, we'll just do an internal free.
4097 zone_free_item(zone, item, NULL, SKIP_NONE);
4102 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4105 uma_cache_bucket_t bucket;
4106 int itemdomain, uz_flags;
4108 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4109 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4111 CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4113 #ifdef UMA_ZALLOC_DEBUG
4114 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4115 ("uma_zfree_arg: called with SMR zone."));
4116 if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4119 /* uma_zfree(..., NULL) does nothing, to match free(9). */
4124 * We are accessing the per-cpu cache without a critical section to
4125 * fetch size and flags. This is acceptable, if we are preempted we
4126 * will simply read another cpu's line.
4128 cache = &zone->uz_cpu[curcpu];
4129 uz_flags = cache_uz_flags(cache);
4130 if (UMA_ALWAYS_CTORDTOR ||
4131 __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4132 item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4135 * The race here is acceptable. If we miss it we'll just have to wait
4136 * a little longer for the limits to be reset.
4138 if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4139 if (zone->uz_sleepers > 0)
4144 * If possible, free to the per-CPU cache. There are two
4145 * requirements for safe access to the per-CPU cache: (1) the thread
4146 * accessing the cache must not be preempted or yield during access,
4147 * and (2) the thread must not migrate CPUs without switching which
4148 * cache it accesses. We rely on a critical section to prevent
4149 * preemption and migration. We release the critical section in
4150 * order to acquire the zone mutex if we are unable to free to the
4151 * current cache; when we re-acquire the critical section, we must
4152 * detect and handle migration if it has occurred.
4156 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4157 itemdomain = item_domain(item);
4161 cache = &zone->uz_cpu[curcpu];
4163 * Try to free into the allocbucket first to give LIFO
4164 * ordering for cache-hot datastructures. Spill over
4165 * into the freebucket if necessary. Alloc will swap
4166 * them if one runs dry.
4168 bucket = &cache->uc_allocbucket;
4170 if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4171 PCPU_GET(domain) != itemdomain) {
4172 bucket = &cache->uc_crossbucket;
4175 if (bucket->ucb_cnt == bucket->ucb_entries &&
4176 cache->uc_freebucket.ucb_cnt <
4177 cache->uc_freebucket.ucb_entries)
4178 cache_bucket_swap(&cache->uc_freebucket,
4179 &cache->uc_allocbucket);
4180 if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4181 cache_bucket_push(cache, bucket, item);
4185 } while (cache_free(zone, cache, udata, item, itemdomain));
4189 * If nothing else caught this, we'll just do an internal free.
4192 zone_free_item(zone, item, udata, SKIP_DTOR);
4197 * sort crossdomain free buckets to domain correct buckets and cache
4201 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4203 struct uma_bucketlist fullbuckets;
4204 uma_zone_domain_t zdom;
4211 "uma_zfree: zone %s(%p) draining cross bucket %p",
4212 zone->uz_name, zone, bucket);
4215 * It is possible for buckets to arrive here out of order so we fetch
4216 * the current smr seq rather than accepting the bucket's.
4218 seq = SMR_SEQ_INVALID;
4219 if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4220 seq = smr_advance(zone->uz_smr);
4223 * To avoid having ndomain * ndomain buckets for sorting we have a
4224 * lock on the current crossfree bucket. A full matrix with
4225 * per-domain locking could be used if necessary.
4227 STAILQ_INIT(&fullbuckets);
4228 ZONE_CROSS_LOCK(zone);
4229 while (bucket->ub_cnt > 0) {
4230 item = bucket->ub_bucket[bucket->ub_cnt - 1];
4231 domain = item_domain(item);
4232 zdom = ZDOM_GET(zone, domain);
4233 if (zdom->uzd_cross == NULL) {
4234 zdom->uzd_cross = bucket_alloc(zone, udata, M_NOWAIT);
4235 if (zdom->uzd_cross == NULL)
4238 b = zdom->uzd_cross;
4239 b->ub_bucket[b->ub_cnt++] = item;
4241 if (b->ub_cnt == b->ub_entries) {
4242 STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4243 zdom->uzd_cross = NULL;
4247 ZONE_CROSS_UNLOCK(zone);
4248 if (bucket->ub_cnt == 0)
4249 bucket->ub_seq = SMR_SEQ_INVALID;
4250 bucket_free(zone, bucket, udata);
4252 while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4253 STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4254 domain = item_domain(b->ub_bucket[0]);
4255 zone_put_bucket(zone, domain, b, udata, true);
4261 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4262 int itemdomain, bool ws)
4267 * Buckets coming from the wrong domain will be entirely for the
4268 * only other domain on two domain systems. In this case we can
4269 * simply cache them. Otherwise we need to sort them back to
4272 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4273 vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4274 zone_free_cross(zone, bucket, udata);
4280 * Attempt to save the bucket in the zone's domain bucket cache.
4283 "uma_zfree: zone %s(%p) putting bucket %p on free list",
4284 zone->uz_name, zone, bucket);
4285 /* ub_cnt is pointing to the last free item */
4286 if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4287 itemdomain = zone_domain_lowest(zone, itemdomain);
4288 zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4292 * Populate a free or cross bucket for the current cpu cache. Free any
4293 * existing full bucket either to the zone cache or back to the slab layer.
4295 * Enters and returns in a critical section. false return indicates that
4296 * we can not satisfy this free in the cache layer. true indicates that
4297 * the caller should retry.
4299 static __noinline bool
4300 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4303 uma_cache_bucket_t cbucket;
4304 uma_bucket_t newbucket, bucket;
4306 CRITICAL_ASSERT(curthread);
4308 if (zone->uz_bucket_size == 0)
4311 cache = &zone->uz_cpu[curcpu];
4315 * FIRSTTOUCH domains need to free to the correct zdom. When
4316 * enabled this is the zdom of the item. The bucket is the
4317 * cross bucket if the current domain and itemdomain do not match.
4319 cbucket = &cache->uc_freebucket;
4321 if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4322 if (PCPU_GET(domain) != itemdomain) {
4323 cbucket = &cache->uc_crossbucket;
4324 if (cbucket->ucb_cnt != 0)
4325 counter_u64_add(zone->uz_xdomain,
4330 bucket = cache_bucket_unload(cbucket);
4331 KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4332 ("cache_free: Entered with non-full free bucket."));
4334 /* We are no longer associated with this CPU. */
4338 * Don't let SMR zones operate without a free bucket. Force
4339 * a synchronize and re-use this one. We will only degrade
4340 * to a synchronize every bucket_size items rather than every
4341 * item if we fail to allocate a bucket.
4343 if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4345 bucket->ub_seq = smr_advance(zone->uz_smr);
4346 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4347 if (newbucket == NULL && bucket != NULL) {
4348 bucket_drain(zone, bucket);
4352 } else if (!bucketdisable)
4353 newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4356 zone_free_bucket(zone, bucket, udata, itemdomain, true);
4359 if ((bucket = newbucket) == NULL)
4361 cache = &zone->uz_cpu[curcpu];
4364 * Check to see if we should be populating the cross bucket. If it
4365 * is already populated we will fall through and attempt to populate
4368 if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4369 if (PCPU_GET(domain) != itemdomain &&
4370 cache->uc_crossbucket.ucb_bucket == NULL) {
4371 cache_bucket_load_cross(cache, bucket);
4377 * We may have lost the race to fill the bucket or switched CPUs.
4379 if (cache->uc_freebucket.ucb_bucket != NULL) {
4381 bucket_free(zone, bucket, udata);
4384 cache_bucket_load_free(cache, bucket);
4390 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4397 KEG_LOCK_ASSERT(keg, slab->us_domain);
4399 /* Do we need to remove from any lists? */
4400 dom = &keg->uk_domain[slab->us_domain];
4401 if (slab->us_freecount + 1 == keg->uk_ipers) {
4402 LIST_REMOVE(slab, us_link);
4403 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4404 dom->ud_free_slabs++;
4405 } else if (slab->us_freecount == 0) {
4406 LIST_REMOVE(slab, us_link);
4407 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4410 /* Slab management. */
4411 freei = slab_item_index(slab, keg, item);
4412 BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4413 slab->us_freecount++;
4415 /* Keg statistics. */
4416 dom->ud_free_items++;
4420 zone_release(void *arg, void **bucket, int cnt)
4433 if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4434 lock = KEG_LOCK(keg, 0);
4435 for (i = 0; i < cnt; i++) {
4437 if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4438 slab = vtoslab((vm_offset_t)item);
4440 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4441 if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4442 slab = hash_sfind(&keg->uk_hash, mem);
4444 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4446 if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4449 lock = KEG_LOCK(keg, slab->us_domain);
4451 slab_free_item(zone, slab, item);
4458 * Frees a single item to any zone.
4461 * zone The zone to free to
4462 * item The item we're freeing
4463 * udata User supplied data for the dtor
4464 * skip Skip dtors and finis
4466 static __noinline void
4467 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4471 * If a free is sent directly to an SMR zone we have to
4472 * synchronize immediately because the item can instantly
4473 * be reallocated. This should only happen in degenerate
4474 * cases when no memory is available for per-cpu caches.
4476 if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4477 smr_synchronize(zone->uz_smr);
4479 item_dtor(zone, item, zone->uz_size, udata, skip);
4481 if (skip < SKIP_FINI && zone->uz_fini)
4482 zone->uz_fini(item, zone->uz_size);
4484 zone->uz_release(zone->uz_arg, &item, 1);
4486 if (skip & SKIP_CNT)
4489 counter_u64_add(zone->uz_frees, 1);
4491 if (zone->uz_max_items > 0)
4492 zone_free_limit(zone, 1);
4497 uma_zone_set_max(uma_zone_t zone, int nitems)
4499 struct uma_bucket_zone *ubz;
4503 * XXX This can misbehave if the zone has any allocations with
4504 * no limit and a limit is imposed. There is currently no
4505 * way to clear a limit.
4508 ubz = bucket_zone_max(zone, nitems);
4509 count = ubz != NULL ? ubz->ubz_entries : 0;
4510 zone->uz_bucket_size_max = zone->uz_bucket_size = count;
4511 if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4512 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4513 zone->uz_max_items = nitems;
4514 zone->uz_flags |= UMA_ZFLAG_LIMIT;
4515 zone_update_caches(zone);
4516 /* We may need to wake waiters. */
4517 wakeup(&zone->uz_max_items);
4525 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4527 struct uma_bucket_zone *ubz;
4531 ubz = bucket_zone_max(zone, nitems);
4534 if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4535 /* Count the cross-domain bucket. */
4537 nitems -= ubz->ubz_entries * bpcpu * mp_ncpus;
4538 zone->uz_bucket_size_max = ubz->ubz_entries;
4540 zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
4542 if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4543 zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4544 zone->uz_bucket_max = nitems / vm_ndomains;
4550 uma_zone_get_max(uma_zone_t zone)
4554 nitems = atomic_load_64(&zone->uz_max_items);
4561 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4564 ZONE_ASSERT_COLD(zone);
4565 zone->uz_warning = warning;
4570 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4573 ZONE_ASSERT_COLD(zone);
4574 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4579 uma_zone_get_cur(uma_zone_t zone)
4585 if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4586 nitems = counter_u64_fetch(zone->uz_allocs) -
4587 counter_u64_fetch(zone->uz_frees);
4589 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4590 atomic_load_64(&zone->uz_cpu[i].uc_frees);
4592 return (nitems < 0 ? 0 : nitems);
4596 uma_zone_get_allocs(uma_zone_t zone)
4602 if (zone->uz_allocs != EARLY_COUNTER)
4603 nitems = counter_u64_fetch(zone->uz_allocs);
4605 nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4611 uma_zone_get_frees(uma_zone_t zone)
4617 if (zone->uz_frees != EARLY_COUNTER)
4618 nitems = counter_u64_fetch(zone->uz_frees);
4620 nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4626 /* Used only for KEG_ASSERT_COLD(). */
4628 uma_keg_get_allocs(uma_keg_t keg)
4634 LIST_FOREACH(z, &keg->uk_zones, uz_link)
4635 nitems += uma_zone_get_allocs(z);
4643 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4648 KEG_ASSERT_COLD(keg);
4649 keg->uk_init = uminit;
4654 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4659 KEG_ASSERT_COLD(keg);
4660 keg->uk_fini = fini;
4665 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4668 ZONE_ASSERT_COLD(zone);
4669 zone->uz_init = zinit;
4674 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4677 ZONE_ASSERT_COLD(zone);
4678 zone->uz_fini = zfini;
4683 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4688 KEG_ASSERT_COLD(keg);
4689 keg->uk_freef = freef;
4694 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4699 KEG_ASSERT_COLD(keg);
4700 keg->uk_allocf = allocf;
4705 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4708 ZONE_ASSERT_COLD(zone);
4710 KASSERT(smr != NULL, ("Got NULL smr"));
4711 KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4712 ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4713 zone->uz_flags |= UMA_ZONE_SMR;
4715 zone_update_caches(zone);
4719 uma_zone_get_smr(uma_zone_t zone)
4722 return (zone->uz_smr);
4727 uma_zone_reserve(uma_zone_t zone, int items)
4732 KEG_ASSERT_COLD(keg);
4733 keg->uk_reserve = items;
4738 uma_zone_reserve_kva(uma_zone_t zone, int count)
4745 KEG_ASSERT_COLD(keg);
4746 ZONE_ASSERT_COLD(zone);
4748 pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4750 #ifdef UMA_MD_SMALL_ALLOC
4751 if (keg->uk_ppera > 1) {
4755 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4761 MPASS(keg->uk_kva == 0);
4764 zone->uz_max_items = pages * keg->uk_ipers;
4765 #ifdef UMA_MD_SMALL_ALLOC
4766 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4768 keg->uk_allocf = noobj_alloc;
4770 keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4771 zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4772 zone_update_caches(zone);
4779 uma_prealloc(uma_zone_t zone, int items)
4781 struct vm_domainset_iter di;
4785 int aflags, domain, slabs;
4788 slabs = howmany(items, keg->uk_ipers);
4789 while (slabs-- > 0) {
4791 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
4794 slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
4797 dom = &keg->uk_domain[slab->us_domain];
4799 * keg_alloc_slab() always returns a slab on the
4802 LIST_REMOVE(slab, us_link);
4803 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
4805 dom->ud_free_slabs++;
4806 KEG_UNLOCK(keg, slab->us_domain);
4809 if (vm_domainset_iter_policy(&di, &domain) != 0)
4810 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
4816 * Returns a snapshot of memory consumption in bytes.
4819 uma_zone_memory(uma_zone_t zone)
4825 if (zone->uz_flags & UMA_ZFLAG_CACHE) {
4826 for (i = 0; i < vm_ndomains; i++)
4827 sz += ZDOM_GET(zone, i)->uzd_nitems;
4828 return (sz * zone->uz_size);
4830 for (i = 0; i < vm_ndomains; i++)
4831 sz += zone->uz_keg->uk_domain[i].ud_pages;
4833 return (sz * PAGE_SIZE);
4838 uma_reclaim(int req)
4841 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
4842 sx_xlock(&uma_reclaim_lock);
4846 case UMA_RECLAIM_TRIM:
4847 zone_foreach(zone_trim, NULL);
4849 case UMA_RECLAIM_DRAIN:
4850 case UMA_RECLAIM_DRAIN_CPU:
4851 zone_foreach(zone_drain, NULL);
4852 if (req == UMA_RECLAIM_DRAIN_CPU) {
4853 pcpu_cache_drain_safe(NULL);
4854 zone_foreach(zone_drain, NULL);
4858 panic("unhandled reclamation request %d", req);
4862 * Some slabs may have been freed but this zone will be visited early
4863 * we visit again so that we can free pages that are empty once other
4864 * zones are drained. We have to do the same for buckets.
4866 zone_drain(slabzones[0], NULL);
4867 zone_drain(slabzones[1], NULL);
4868 bucket_zone_drain();
4869 sx_xunlock(&uma_reclaim_lock);
4872 static volatile int uma_reclaim_needed;
4875 uma_reclaim_wakeup(void)
4878 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
4879 wakeup(uma_reclaim);
4883 uma_reclaim_worker(void *arg __unused)
4887 sx_xlock(&uma_reclaim_lock);
4888 while (atomic_load_int(&uma_reclaim_needed) == 0)
4889 sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
4891 sx_xunlock(&uma_reclaim_lock);
4892 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
4893 uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
4894 atomic_store_int(&uma_reclaim_needed, 0);
4895 /* Don't fire more than once per-second. */
4896 pause("umarclslp", hz);
4902 uma_zone_reclaim(uma_zone_t zone, int req)
4906 case UMA_RECLAIM_TRIM:
4907 zone_trim(zone, NULL);
4909 case UMA_RECLAIM_DRAIN:
4910 zone_drain(zone, NULL);
4912 case UMA_RECLAIM_DRAIN_CPU:
4913 pcpu_cache_drain_safe(zone);
4914 zone_drain(zone, NULL);
4917 panic("unhandled reclamation request %d", req);
4923 uma_zone_exhausted(uma_zone_t zone)
4926 return (atomic_load_32(&zone->uz_sleepers) > 0);
4933 return (uma_kmem_limit);
4937 uma_set_limit(unsigned long limit)
4940 uma_kmem_limit = limit;
4947 return (atomic_load_long(&uma_kmem_total));
4954 return (uma_kmem_limit - uma_size());
4959 * Generate statistics across both the zone and its per-cpu cache's. Return
4960 * desired statistics if the pointer is non-NULL for that statistic.
4962 * Note: does not update the zone statistics, as it can't safely clear the
4963 * per-CPU cache statistic.
4967 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
4968 uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
4971 uint64_t allocs, frees, sleeps, xdomain;
4974 allocs = frees = sleeps = xdomain = 0;
4977 cache = &z->uz_cpu[cpu];
4978 cachefree += cache->uc_allocbucket.ucb_cnt;
4979 cachefree += cache->uc_freebucket.ucb_cnt;
4980 xdomain += cache->uc_crossbucket.ucb_cnt;
4981 cachefree += cache->uc_crossbucket.ucb_cnt;
4982 allocs += cache->uc_allocs;
4983 frees += cache->uc_frees;
4985 allocs += counter_u64_fetch(z->uz_allocs);
4986 frees += counter_u64_fetch(z->uz_frees);
4987 xdomain += counter_u64_fetch(z->uz_xdomain);
4988 sleeps += z->uz_sleeps;
4989 if (cachefreep != NULL)
4990 *cachefreep = cachefree;
4991 if (allocsp != NULL)
4995 if (sleepsp != NULL)
4997 if (xdomainp != NULL)
4998 *xdomainp = xdomain;
5003 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5010 rw_rlock(&uma_rwlock);
5011 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5012 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5015 LIST_FOREACH(z, &uma_cachezones, uz_link)
5018 rw_runlock(&uma_rwlock);
5019 return (sysctl_handle_int(oidp, &count, 0, req));
5023 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5024 struct uma_percpu_stat *ups, bool internal)
5026 uma_zone_domain_t zdom;
5030 for (i = 0; i < vm_ndomains; i++) {
5031 zdom = ZDOM_GET(z, i);
5032 uth->uth_zone_free += zdom->uzd_nitems;
5034 uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5035 uth->uth_frees = counter_u64_fetch(z->uz_frees);
5036 uth->uth_fails = counter_u64_fetch(z->uz_fails);
5037 uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5038 uth->uth_sleeps = z->uz_sleeps;
5040 for (i = 0; i < mp_maxid + 1; i++) {
5041 bzero(&ups[i], sizeof(*ups));
5042 if (internal || CPU_ABSENT(i))
5044 cache = &z->uz_cpu[i];
5045 ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5046 ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5047 ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5048 ups[i].ups_allocs = cache->uc_allocs;
5049 ups[i].ups_frees = cache->uc_frees;
5054 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5056 struct uma_stream_header ush;
5057 struct uma_type_header uth;
5058 struct uma_percpu_stat *ups;
5063 uint32_t kfree, pages;
5064 int count, error, i;
5066 error = sysctl_wire_old_buffer(req, 0);
5069 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5070 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5071 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5074 rw_rlock(&uma_rwlock);
5075 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5076 LIST_FOREACH(z, &kz->uk_zones, uz_link)
5080 LIST_FOREACH(z, &uma_cachezones, uz_link)
5084 * Insert stream header.
5086 bzero(&ush, sizeof(ush));
5087 ush.ush_version = UMA_STREAM_VERSION;
5088 ush.ush_maxcpus = (mp_maxid + 1);
5089 ush.ush_count = count;
5090 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5092 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5094 for (i = 0; i < vm_ndomains; i++) {
5095 kfree += kz->uk_domain[i].ud_free_items;
5096 pages += kz->uk_domain[i].ud_pages;
5098 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5099 bzero(&uth, sizeof(uth));
5100 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5101 uth.uth_align = kz->uk_align;
5102 uth.uth_size = kz->uk_size;
5103 uth.uth_rsize = kz->uk_rsize;
5104 if (z->uz_max_items > 0) {
5105 items = UZ_ITEMS_COUNT(z->uz_items);
5106 uth.uth_pages = (items / kz->uk_ipers) *
5109 uth.uth_pages = pages;
5110 uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5112 uth.uth_limit = z->uz_max_items;
5113 uth.uth_keg_free = kfree;
5116 * A zone is secondary is it is not the first entry
5117 * on the keg's zone list.
5119 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5120 (LIST_FIRST(&kz->uk_zones) != z))
5121 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5122 uma_vm_zone_stats(&uth, z, &sbuf, ups,
5123 kz->uk_flags & UMA_ZFLAG_INTERNAL);
5124 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5125 for (i = 0; i < mp_maxid + 1; i++)
5126 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5129 LIST_FOREACH(z, &uma_cachezones, uz_link) {
5130 bzero(&uth, sizeof(uth));
5131 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5132 uth.uth_size = z->uz_size;
5133 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5134 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5135 for (i = 0; i < mp_maxid + 1; i++)
5136 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5139 rw_runlock(&uma_rwlock);
5140 error = sbuf_finish(&sbuf);
5147 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5149 uma_zone_t zone = *(uma_zone_t *)arg1;
5152 max = uma_zone_get_max(zone);
5153 error = sysctl_handle_int(oidp, &max, 0, req);
5154 if (error || !req->newptr)
5157 uma_zone_set_max(zone, max);
5163 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5169 * Some callers want to add sysctls for global zones that
5170 * may not yet exist so they pass a pointer to a pointer.
5173 zone = *(uma_zone_t *)arg1;
5176 cur = uma_zone_get_cur(zone);
5177 return (sysctl_handle_int(oidp, &cur, 0, req));
5181 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5183 uma_zone_t zone = arg1;
5186 cur = uma_zone_get_allocs(zone);
5187 return (sysctl_handle_64(oidp, &cur, 0, req));
5191 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5193 uma_zone_t zone = arg1;
5196 cur = uma_zone_get_frees(zone);
5197 return (sysctl_handle_64(oidp, &cur, 0, req));
5201 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5204 uma_zone_t zone = arg1;
5207 sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5208 if (zone->uz_flags != 0)
5209 sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5211 sbuf_printf(&sbuf, "0");
5212 error = sbuf_finish(&sbuf);
5219 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5221 uma_keg_t keg = arg1;
5222 int avail, effpct, total;
5224 total = keg->uk_ppera * PAGE_SIZE;
5225 if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5226 total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5228 * We consider the client's requested size and alignment here, not the
5229 * real size determination uk_rsize, because we also adjust the real
5230 * size for internal implementation reasons (max bitset size).
5232 avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5233 if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5234 avail *= mp_maxid + 1;
5235 effpct = 100 * avail / total;
5236 return (sysctl_handle_int(oidp, &effpct, 0, req));
5240 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5242 uma_zone_t zone = arg1;
5245 cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5246 return (sysctl_handle_64(oidp, &cur, 0, req));
5251 uma_dbg_getslab(uma_zone_t zone, void *item)
5258 * It is safe to return the slab here even though the
5259 * zone is unlocked because the item's allocation state
5260 * essentially holds a reference.
5262 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5263 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5265 if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5266 return (vtoslab((vm_offset_t)mem));
5268 if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5269 return ((uma_slab_t)(mem + keg->uk_pgoff));
5271 slab = hash_sfind(&keg->uk_hash, mem);
5278 uma_dbg_zskip(uma_zone_t zone, void *mem)
5281 if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5284 return (uma_dbg_kskip(zone->uz_keg, mem));
5288 uma_dbg_kskip(uma_keg_t keg, void *mem)
5292 if (dbg_divisor == 0)
5295 if (dbg_divisor == 1)
5298 idx = (uintptr_t)mem >> PAGE_SHIFT;
5299 if (keg->uk_ipers > 1) {
5300 idx *= keg->uk_ipers;
5301 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5304 if ((idx / dbg_divisor) * dbg_divisor != idx) {
5305 counter_u64_add(uma_skip_cnt, 1);
5308 counter_u64_add(uma_dbg_cnt, 1);
5314 * Set up the slab's freei data such that uma_dbg_free can function.
5318 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5324 slab = uma_dbg_getslab(zone, item);
5326 panic("uma: item %p did not belong to zone %s",
5327 item, zone->uz_name);
5330 freei = slab_item_index(slab, keg, item);
5332 if (BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5333 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5334 item, zone, zone->uz_name, slab, freei);
5335 BIT_SET_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5339 * Verifies freed addresses. Checks for alignment, valid slab membership
5340 * and duplicate frees.
5344 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5350 slab = uma_dbg_getslab(zone, item);
5352 panic("uma: Freed item %p did not belong to zone %s",
5353 item, zone->uz_name);
5356 freei = slab_item_index(slab, keg, item);
5358 if (freei >= keg->uk_ipers)
5359 panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5360 item, zone, zone->uz_name, slab, freei);
5362 if (slab_item(slab, keg, freei) != item)
5363 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5364 item, zone, zone->uz_name, slab, freei);
5366 if (!BIT_ISSET(keg->uk_ipers, freei, slab_dbg_bits(slab, keg)))
5367 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5368 item, zone, zone->uz_name, slab, freei);
5370 BIT_CLR_ATOMIC(keg->uk_ipers, freei, slab_dbg_bits(slab, keg));
5372 #endif /* INVARIANTS */
5376 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5377 uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5382 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5383 *allocs = counter_u64_fetch(z->uz_allocs);
5384 frees = counter_u64_fetch(z->uz_frees);
5385 *sleeps = z->uz_sleeps;
5389 uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5391 for (i = 0; i < vm_ndomains; i++) {
5392 *cachefree += ZDOM_GET(z, i)->uzd_nitems;
5393 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5394 (LIST_FIRST(&kz->uk_zones) != z)))
5395 *cachefree += kz->uk_domain[i].ud_free_items;
5397 *used = *allocs - frees;
5398 return (((int64_t)*used + *cachefree) * kz->uk_size);
5401 DB_SHOW_COMMAND(uma, db_show_uma)
5403 const char *fmt_hdr, *fmt_entry;
5406 uint64_t allocs, used, sleeps, xdomain;
5408 /* variables for sorting */
5410 uma_zone_t cur_zone, last_zone;
5411 int64_t cur_size, last_size, size;
5414 /* /i option produces machine-parseable CSV output */
5415 if (modif[0] == 'i') {
5416 fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5417 fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5419 fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5420 fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5423 db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5424 "Sleeps", "Bucket", "Total Mem", "XFree");
5426 /* Sort the zones with largest size first. */
5428 last_size = INT64_MAX;
5433 LIST_FOREACH(kz, &uma_kegs, uk_link) {
5434 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5436 * In the case of size ties, print out zones
5437 * in the order they are encountered. That is,
5438 * when we encounter the most recently output
5439 * zone, we have already printed all preceding
5440 * ties, and we must print all following ties.
5442 if (z == last_zone) {
5446 size = get_uma_stats(kz, z, &allocs, &used,
5447 &sleeps, &cachefree, &xdomain);
5448 if (size > cur_size && size < last_size + ties)
5456 if (cur_zone == NULL)
5459 size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5460 &sleeps, &cachefree, &xdomain);
5461 db_printf(fmt_entry, cur_zone->uz_name,
5462 (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5463 (uintmax_t)allocs, (uintmax_t)sleeps,
5464 (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5469 last_zone = cur_zone;
5470 last_size = cur_size;
5474 DB_SHOW_COMMAND(umacache, db_show_umacache)
5477 uint64_t allocs, frees;
5481 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5482 "Requests", "Bucket");
5483 LIST_FOREACH(z, &uma_cachezones, uz_link) {
5484 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5485 for (i = 0; i < vm_ndomains; i++)
5486 cachefree += ZDOM_GET(z, i)->uzd_nitems;
5487 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5488 z->uz_name, (uintmax_t)z->uz_size,
5489 (intmax_t)(allocs - frees), cachefree,
5490 (uintmax_t)allocs, z->uz_bucket_size);