2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2005, 2009, 2013 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>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
100 #include <vm/memguard.h>
104 * This is the zone and keg from which all zones are spawned.
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
113 * The initial hash tables come out of this zone so they can be allocated
114 * prior to malloc coming up.
116 static uma_zone_t hashzone;
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
124 * Are we allowed to allocate buckets?
126 static int bucketdisable = 1;
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133 LIST_HEAD_INITIALIZER(uma_cachezones);
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
139 * Pointer and counter to pool of pages, that is preallocated at
140 * startup to bootstrap UMA.
142 static char *bootmem;
143 static int boot_pages;
145 static struct sx uma_reclaim_lock;
148 * kmem soft limit, initialized by uma_set_limit(). Ensure that early
149 * allocations don't trigger a wakeup of the reclaim thread.
151 static unsigned long uma_kmem_limit = LONG_MAX;
152 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
153 "UMA kernel memory soft limit");
154 static unsigned long uma_kmem_total;
155 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
156 "UMA kernel memory usage");
158 /* Is the VM done starting up? */
159 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
160 BOOT_RUNNING } booted = BOOT_COLD;
163 * This is the handle used to schedule events that need to happen
164 * outside of the allocation fast path.
166 static struct callout uma_callout;
167 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
170 * This structure is passed as the zone ctor arg so that I don't have to create
171 * a special allocation function just for zones.
173 struct uma_zctor_args {
188 struct uma_kctor_args {
197 struct uma_bucket_zone {
200 int ubz_entries; /* Number of items it can hold. */
201 int ubz_maxsize; /* Maximum allocation size per-item. */
205 * Compute the actual number of bucket entries to pack them in power
206 * of two sizes for more efficient space utilization.
208 #define BUCKET_SIZE(n) \
209 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
211 #define BUCKET_MAX BUCKET_SIZE(256)
212 #define BUCKET_MIN BUCKET_SIZE(4)
214 struct uma_bucket_zone bucket_zones[] = {
215 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
216 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
217 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
218 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
219 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
220 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
221 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
222 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
223 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
228 * Flags and enumerations to be passed to internal functions.
232 SKIP_CNT = 0x00000001,
233 SKIP_DTOR = 0x00010000,
234 SKIP_FINI = 0x00020000,
239 int uma_startup_count(int);
240 void uma_startup(void *, int);
241 void uma_startup1(void);
242 void uma_startup2(void);
244 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
245 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
246 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
247 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
248 static void page_free(void *, vm_size_t, uint8_t);
249 static void pcpu_page_free(void *, vm_size_t, uint8_t);
250 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
251 static void cache_drain(uma_zone_t);
252 static void bucket_drain(uma_zone_t, uma_bucket_t);
253 static void bucket_cache_reclaim(uma_zone_t zone, bool);
254 static int keg_ctor(void *, int, void *, int);
255 static void keg_dtor(void *, int, void *);
256 static int zone_ctor(void *, int, void *, int);
257 static void zone_dtor(void *, int, void *);
258 static int zero_init(void *, int, int);
259 static void keg_small_init(uma_keg_t keg);
260 static void keg_large_init(uma_keg_t keg);
261 static void zone_foreach(void (*zfunc)(uma_zone_t));
262 static void zone_timeout(uma_zone_t zone);
263 static int hash_alloc(struct uma_hash *, u_int);
264 static int hash_expand(struct uma_hash *, struct uma_hash *);
265 static void hash_free(struct uma_hash *hash);
266 static void uma_timeout(void *);
267 static void uma_startup3(void);
268 static void *zone_alloc_item(uma_zone_t, void *, int, int);
269 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
270 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
271 static void bucket_enable(void);
272 static void bucket_init(void);
273 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
274 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
275 static void bucket_zone_drain(void);
276 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
277 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
278 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
279 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
280 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
281 uma_fini fini, int align, uint32_t flags);
282 static int zone_import(uma_zone_t, void **, int, int, int);
283 static void zone_release(uma_zone_t, void **, int);
284 static void uma_zero_item(void *, uma_zone_t);
286 void uma_print_zone(uma_zone_t);
287 void uma_print_stats(void);
288 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
289 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
292 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
293 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
294 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
295 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
297 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
298 "Memory allocation debugging");
300 static u_int dbg_divisor = 1;
301 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
302 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
303 "Debug & thrash every this item in memory allocator");
305 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
306 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
307 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
308 &uma_dbg_cnt, "memory items debugged");
309 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
310 &uma_skip_cnt, "memory items skipped, not debugged");
313 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
315 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
316 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
318 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
319 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
321 static int zone_warnings = 1;
322 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
323 "Warn when UMA zones becomes full");
325 /* Adjust bytes under management by UMA. */
327 uma_total_dec(unsigned long size)
330 atomic_subtract_long(&uma_kmem_total, size);
334 uma_total_inc(unsigned long size)
337 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
338 uma_reclaim_wakeup();
342 * This routine checks to see whether or not it's safe to enable buckets.
347 bucketdisable = vm_page_count_min();
351 * Initialize bucket_zones, the array of zones of buckets of various sizes.
353 * For each zone, calculate the memory required for each bucket, consisting
354 * of the header and an array of pointers.
359 struct uma_bucket_zone *ubz;
362 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
363 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
364 size += sizeof(void *) * ubz->ubz_entries;
365 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
366 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
367 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
372 * Given a desired number of entries for a bucket, return the zone from which
373 * to allocate the bucket.
375 static struct uma_bucket_zone *
376 bucket_zone_lookup(int entries)
378 struct uma_bucket_zone *ubz;
380 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
381 if (ubz->ubz_entries >= entries)
388 bucket_select(int size)
390 struct uma_bucket_zone *ubz;
392 ubz = &bucket_zones[0];
393 if (size > ubz->ubz_maxsize)
394 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
396 for (; ubz->ubz_entries != 0; ubz++)
397 if (ubz->ubz_maxsize < size)
400 return (ubz->ubz_entries);
404 bucket_alloc(uma_zone_t zone, void *udata, int flags)
406 struct uma_bucket_zone *ubz;
410 * This is to stop us from allocating per cpu buckets while we're
411 * running out of vm.boot_pages. Otherwise, we would exhaust the
412 * boot pages. This also prevents us from allocating buckets in
413 * low memory situations.
418 * To limit bucket recursion we store the original zone flags
419 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
420 * NOVM flag to persist even through deep recursions. We also
421 * store ZFLAG_BUCKET once we have recursed attempting to allocate
422 * a bucket for a bucket zone so we do not allow infinite bucket
423 * recursion. This cookie will even persist to frees of unused
424 * buckets via the allocation path or bucket allocations in the
427 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
428 udata = (void *)(uintptr_t)zone->uz_flags;
430 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
432 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
434 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
436 ubz = bucket_zone_lookup(zone->uz_count);
437 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
439 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
442 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
445 bucket->ub_entries = ubz->ubz_entries;
452 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
454 struct uma_bucket_zone *ubz;
456 KASSERT(bucket->ub_cnt == 0,
457 ("bucket_free: Freeing a non free bucket."));
458 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
459 udata = (void *)(uintptr_t)zone->uz_flags;
460 ubz = bucket_zone_lookup(bucket->ub_entries);
461 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
465 bucket_zone_drain(void)
467 struct uma_bucket_zone *ubz;
469 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
470 uma_zone_reclaim(ubz->ubz_zone, UMA_RECLAIM_DRAIN);
474 * Attempt to satisfy an allocation by retrieving a full bucket from one of the
478 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom)
482 ZONE_LOCK_ASSERT(zone);
484 if ((bucket = TAILQ_FIRST(&zdom->uzd_buckets)) != NULL) {
485 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
486 TAILQ_REMOVE(&zdom->uzd_buckets, bucket, ub_link);
487 zdom->uzd_nitems -= bucket->ub_cnt;
488 if (zdom->uzd_imin > zdom->uzd_nitems)
489 zdom->uzd_imin = zdom->uzd_nitems;
490 zone->uz_bkt_count -= bucket->ub_cnt;
496 * Insert a full bucket into the specified cache. The "ws" parameter indicates
497 * whether the bucket's contents should be counted as part of the zone's working
501 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
505 ZONE_LOCK_ASSERT(zone);
506 KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
510 TAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
512 TAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
513 zdom->uzd_nitems += bucket->ub_cnt;
514 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
515 zdom->uzd_imax = zdom->uzd_nitems;
516 zone->uz_bkt_count += bucket->ub_cnt;
520 zone_log_warning(uma_zone_t zone)
522 static const struct timeval warninterval = { 300, 0 };
524 if (!zone_warnings || zone->uz_warning == NULL)
527 if (ratecheck(&zone->uz_ratecheck, &warninterval))
528 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
532 zone_maxaction(uma_zone_t zone)
535 if (zone->uz_maxaction.ta_func != NULL)
536 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
540 * Routine called by timeout which is used to fire off some time interval
541 * based calculations. (stats, hash size, etc.)
550 uma_timeout(void *unused)
553 zone_foreach(zone_timeout);
555 /* Reschedule this event */
556 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
560 * Update the working set size estimate for the zone's bucket cache.
561 * The constants chosen here are somewhat arbitrary. With an update period of
562 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
566 zone_domain_update_wss(uma_zone_domain_t zdom)
570 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
571 wss = zdom->uzd_imax - zdom->uzd_imin;
572 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
573 zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
577 * Routine to perform timeout driven calculations. This expands the
578 * hashes and does per cpu statistics aggregation.
583 zone_timeout(uma_zone_t zone)
585 uma_keg_t keg = zone->uz_keg;
590 * Expand the keg hash table.
592 * This is done if the number of slabs is larger than the hash size.
593 * What I'm trying to do here is completely reduce collisions. This
594 * may be a little aggressive. Should I allow for two collisions max?
596 if (keg->uk_flags & UMA_ZONE_HASH &&
597 (slabs = keg->uk_pages / keg->uk_ppera) >
598 keg->uk_hash.uh_hashsize) {
599 struct uma_hash newhash;
600 struct uma_hash oldhash;
604 * This is so involved because allocating and freeing
605 * while the keg lock is held will lead to deadlock.
606 * I have to do everything in stages and check for
610 ret = hash_alloc(&newhash, 1 << fls(slabs));
613 if (hash_expand(&keg->uk_hash, &newhash)) {
614 oldhash = keg->uk_hash;
615 keg->uk_hash = newhash;
627 for (int i = 0; i < vm_ndomains; i++)
628 zone_domain_update_wss(&zone->uz_domain[i]);
633 * Allocate and zero fill the next sized hash table from the appropriate
637 * hash A new hash structure with the old hash size in uh_hashsize
640 * 1 on success and 0 on failure.
643 hash_alloc(struct uma_hash *hash, u_int size)
647 KASSERT(powerof2(size), ("hash size must be power of 2"));
648 if (size > UMA_HASH_SIZE_INIT) {
649 hash->uh_hashsize = size;
650 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
651 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
652 M_UMAHASH, M_NOWAIT);
654 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
655 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
656 UMA_ANYDOMAIN, M_WAITOK);
657 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
659 if (hash->uh_slab_hash) {
660 bzero(hash->uh_slab_hash, alloc);
661 hash->uh_hashmask = hash->uh_hashsize - 1;
669 * Expands the hash table for HASH zones. This is done from zone_timeout
670 * to reduce collisions. This must not be done in the regular allocation
671 * path, otherwise, we can recurse on the vm while allocating pages.
674 * oldhash The hash you want to expand
675 * newhash The hash structure for the new table
683 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
689 if (!newhash->uh_slab_hash)
692 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
696 * I need to investigate hash algorithms for resizing without a
700 for (idx = 0; idx < oldhash->uh_hashsize; idx++)
701 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
702 slab = SLIST_FIRST(&oldhash->uh_slab_hash[idx]);
703 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[idx], us_hlink);
704 hval = UMA_HASH(newhash, slab->us_data);
705 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
713 * Free the hash bucket to the appropriate backing store.
716 * slab_hash The hash bucket we're freeing
717 * hashsize The number of entries in that hash bucket
723 hash_free(struct uma_hash *hash)
725 if (hash->uh_slab_hash == NULL)
727 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
728 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
730 free(hash->uh_slab_hash, M_UMAHASH);
734 * Frees all outstanding items in a bucket
737 * zone The zone to free to, must be unlocked.
738 * bucket The free/alloc bucket with items, cpu queue must be locked.
745 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
753 for (i = 0; i < bucket->ub_cnt; i++)
754 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
755 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
756 if (zone->uz_max_items > 0) {
758 zone->uz_items -= bucket->ub_cnt;
759 if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
767 * Drains the per cpu caches for a zone.
769 * NOTE: This may only be called while the zone is being turn down, and not
770 * during normal operation. This is necessary in order that we do not have
771 * to migrate CPUs to drain the per-CPU caches.
774 * zone The zone to drain, must be unlocked.
780 cache_drain(uma_zone_t zone)
786 * XXX: It is safe to not lock the per-CPU caches, because we're
787 * tearing down the zone anyway. I.e., there will be no further use
788 * of the caches at this point.
790 * XXX: It would good to be able to assert that the zone is being
791 * torn down to prevent improper use of cache_drain().
793 * XXX: We lock the zone before passing into bucket_cache_reclaim() as
794 * it is used elsewhere. Should the tear-down path be made special
795 * there in some form?
798 cache = &zone->uz_cpu[cpu];
799 bucket_drain(zone, cache->uc_allocbucket);
800 if (cache->uc_allocbucket != NULL)
801 bucket_free(zone, cache->uc_allocbucket, NULL);
802 cache->uc_allocbucket = NULL;
803 bucket_drain(zone, cache->uc_freebucket);
804 if (cache->uc_freebucket != NULL)
805 bucket_free(zone, cache->uc_freebucket, NULL);
806 cache->uc_freebucket = NULL;
807 bucket_drain(zone, cache->uc_crossbucket);
808 if (cache->uc_crossbucket != NULL)
809 bucket_free(zone, cache->uc_crossbucket, NULL);
810 cache->uc_crossbucket = NULL;
813 bucket_cache_reclaim(zone, true);
818 cache_shrink(uma_zone_t zone)
821 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
825 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
830 cache_drain_safe_cpu(uma_zone_t zone)
833 uma_bucket_t b1, b2, b3;
836 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
842 if (zone->uz_flags & UMA_ZONE_NUMA)
843 domain = PCPU_GET(domain);
846 cache = &zone->uz_cpu[curcpu];
847 if (cache->uc_allocbucket) {
848 if (cache->uc_allocbucket->ub_cnt != 0)
849 zone_put_bucket(zone, &zone->uz_domain[domain],
850 cache->uc_allocbucket, false);
852 b1 = cache->uc_allocbucket;
853 cache->uc_allocbucket = NULL;
855 if (cache->uc_freebucket) {
856 if (cache->uc_freebucket->ub_cnt != 0)
857 zone_put_bucket(zone, &zone->uz_domain[domain],
858 cache->uc_freebucket, false);
860 b2 = cache->uc_freebucket;
861 cache->uc_freebucket = NULL;
863 b3 = cache->uc_crossbucket;
864 cache->uc_crossbucket = NULL;
868 bucket_free(zone, b1, NULL);
870 bucket_free(zone, b2, NULL);
872 bucket_drain(zone, b3);
873 bucket_free(zone, b3, NULL);
878 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
879 * This is an expensive call because it needs to bind to all CPUs
880 * one by one and enter a critical section on each of them in order
881 * to safely access their cache buckets.
882 * Zone lock must not be held on call this function.
885 pcpu_cache_drain_safe(uma_zone_t zone)
890 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
895 zone_foreach(cache_shrink);
898 thread_lock(curthread);
899 sched_bind(curthread, cpu);
900 thread_unlock(curthread);
903 cache_drain_safe_cpu(zone);
905 zone_foreach(cache_drain_safe_cpu);
907 thread_lock(curthread);
908 sched_unbind(curthread);
909 thread_unlock(curthread);
913 * Reclaim cached buckets from a zone. All buckets are reclaimed if the caller
914 * requested a drain, otherwise the per-domain caches are trimmed to either
915 * estimated working set size.
918 bucket_cache_reclaim(uma_zone_t zone, bool drain)
920 uma_zone_domain_t zdom;
925 for (i = 0; i < vm_ndomains; i++) {
926 zdom = &zone->uz_domain[i];
929 * If we were asked to drain the zone, we are done only once
930 * this bucket cache is empty. Otherwise, we reclaim items in
931 * excess of the zone's estimated working set size. If the
932 * difference nitems - imin is larger than the WSS estimate,
933 * then the estimate will grow at the end of this interval and
934 * we ignore the historical average.
936 target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
938 while (zdom->uzd_nitems > target) {
939 bucket = TAILQ_LAST(&zdom->uzd_buckets, uma_bucketlist);
942 tofree = bucket->ub_cnt;
943 TAILQ_REMOVE(&zdom->uzd_buckets, bucket, ub_link);
944 zdom->uzd_nitems -= tofree;
947 * Shift the bounds of the current WSS interval to avoid
948 * perturbing the estimate.
950 zdom->uzd_imax -= lmin(zdom->uzd_imax, tofree);
951 zdom->uzd_imin -= lmin(zdom->uzd_imin, tofree);
954 bucket_drain(zone, bucket);
955 bucket_free(zone, bucket, NULL);
961 * Shrink the zone bucket size to ensure that the per-CPU caches
962 * don't grow too large.
964 if (zone->uz_count > zone->uz_count_min)
969 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
975 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
976 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
979 flags = slab->us_flags;
981 if (keg->uk_fini != NULL) {
982 for (i--; i > -1; i--)
985 * trash_fini implies that dtor was trash_dtor. trash_fini
986 * would check that memory hasn't been modified since free,
987 * which executed trash_dtor.
988 * That's why we need to run uma_dbg_kskip() check here,
989 * albeit we don't make skip check for other init/fini
992 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
993 keg->uk_fini != trash_fini)
995 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
998 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
999 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1000 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
1001 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
1005 * Frees pages from a keg back to the system. This is done on demand from
1006 * the pageout daemon.
1011 keg_drain(uma_keg_t keg)
1013 struct slabhead freeslabs = { 0 };
1015 uma_slab_t slab, tmp;
1019 * We don't want to take pages from statically allocated kegs at this
1022 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
1025 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
1026 keg->uk_name, keg, keg->uk_free);
1028 if (keg->uk_free == 0)
1031 for (i = 0; i < vm_ndomains; i++) {
1032 dom = &keg->uk_domain[i];
1033 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
1034 /* We have nowhere to free these to. */
1035 if (slab->us_flags & UMA_SLAB_BOOT)
1038 LIST_REMOVE(slab, us_link);
1039 keg->uk_pages -= keg->uk_ppera;
1040 keg->uk_free -= keg->uk_ipers;
1042 if (keg->uk_flags & UMA_ZONE_HASH)
1043 UMA_HASH_REMOVE(&keg->uk_hash, slab,
1046 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1053 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1054 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1055 keg_free_slab(keg, slab, keg->uk_ipers);
1060 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1064 * Set draining to interlock with zone_dtor() so we can release our
1065 * locks as we go. Only dtor() should do a WAITOK call since it
1066 * is the only call that knows the structure will still be available
1070 while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1071 if (waitok == M_NOWAIT)
1073 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1075 zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1076 bucket_cache_reclaim(zone, drain);
1080 * The DRAINING flag protects us from being freed while
1081 * we're running. Normally the uma_rwlock would protect us but we
1082 * must be able to release and acquire the right lock for each keg.
1084 keg_drain(zone->uz_keg);
1086 zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1093 zone_drain(uma_zone_t zone)
1096 zone_reclaim(zone, M_NOWAIT, true);
1100 zone_trim(uma_zone_t zone)
1103 zone_reclaim(zone, M_NOWAIT, false);
1107 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1108 * If the allocation was successful, the keg lock will be held upon return,
1109 * otherwise the keg will be left unlocked.
1112 * flags Wait flags for the item initialization routine
1113 * aflags Wait flags for the slab allocation
1116 * The slab that was allocated or NULL if there is no memory and the
1117 * caller specified M_NOWAIT.
1120 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1130 KASSERT(domain >= 0 && domain < vm_ndomains,
1131 ("keg_alloc_slab: domain %d out of range", domain));
1132 KEG_LOCK_ASSERT(keg);
1133 MPASS(zone->uz_lockptr == &keg->uk_lock);
1135 allocf = keg->uk_allocf;
1140 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1141 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, aflags);
1147 * This reproduces the old vm_zone behavior of zero filling pages the
1148 * first time they are added to a zone.
1150 * Malloced items are zeroed in uma_zalloc.
1153 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1158 if (keg->uk_flags & UMA_ZONE_NODUMP)
1161 /* zone is passed for legacy reasons. */
1162 size = keg->uk_ppera * PAGE_SIZE;
1163 mem = allocf(zone, size, domain, &sflags, aflags);
1165 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1166 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1170 uma_total_inc(size);
1172 /* Point the slab into the allocated memory */
1173 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1174 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1176 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1177 for (i = 0; i < keg->uk_ppera; i++)
1178 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1181 slab->us_data = mem;
1182 slab->us_freecount = keg->uk_ipers;
1183 slab->us_flags = sflags;
1184 slab->us_domain = domain;
1185 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1187 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1190 if (keg->uk_init != NULL) {
1191 for (i = 0; i < keg->uk_ipers; i++)
1192 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1193 keg->uk_size, flags) != 0)
1195 if (i != keg->uk_ipers) {
1196 keg_free_slab(keg, slab, i);
1203 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1204 slab, keg->uk_name, keg);
1206 if (keg->uk_flags & UMA_ZONE_HASH)
1207 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1209 keg->uk_pages += keg->uk_ppera;
1210 keg->uk_free += keg->uk_ipers;
1217 * This function is intended to be used early on in place of page_alloc() so
1218 * that we may use the boot time page cache to satisfy allocations before
1222 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1231 * If we are in BOOT_BUCKETS or higher, than switch to real
1232 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1238 case BOOT_PAGEALLOC:
1239 if (keg->uk_ppera > 1)
1243 #ifdef UMA_MD_SMALL_ALLOC
1244 keg->uk_allocf = (keg->uk_ppera > 1) ?
1245 page_alloc : uma_small_alloc;
1247 keg->uk_allocf = page_alloc;
1249 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1253 * Check our small startup cache to see if it has pages remaining.
1255 pages = howmany(bytes, PAGE_SIZE);
1256 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1257 if (pages > boot_pages)
1258 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1260 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1264 boot_pages -= pages;
1265 bootmem += pages * PAGE_SIZE;
1266 *pflag = UMA_SLAB_BOOT;
1272 * Allocates a number of pages from the system
1275 * bytes The number of bytes requested
1276 * wait Shall we wait?
1279 * A pointer to the alloced memory or possibly
1280 * NULL if M_NOWAIT is set.
1283 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1286 void *p; /* Returned page */
1288 *pflag = UMA_SLAB_KERNEL;
1289 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1295 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1298 struct pglist alloctail;
1299 vm_offset_t addr, zkva;
1301 vm_page_t p, p_next;
1306 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1308 TAILQ_INIT(&alloctail);
1309 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1310 malloc2vm_flags(wait);
1311 *pflag = UMA_SLAB_KERNEL;
1312 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1313 if (CPU_ABSENT(cpu)) {
1314 p = vm_page_alloc(NULL, 0, flags);
1317 p = vm_page_alloc(NULL, 0, flags);
1319 pc = pcpu_find(cpu);
1320 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1321 if (__predict_false(p == NULL))
1322 p = vm_page_alloc(NULL, 0, flags);
1325 if (__predict_false(p == NULL))
1327 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1329 if ((addr = kva_alloc(bytes)) == 0)
1332 TAILQ_FOREACH(p, &alloctail, listq) {
1333 pmap_qenter(zkva, &p, 1);
1336 return ((void*)addr);
1338 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1339 vm_page_unwire_noq(p);
1346 * Allocates a number of pages from within an object
1349 * bytes The number of bytes requested
1350 * wait Shall we wait?
1353 * A pointer to the alloced memory or possibly
1354 * NULL if M_NOWAIT is set.
1357 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1360 TAILQ_HEAD(, vm_page) alloctail;
1362 vm_offset_t retkva, zkva;
1363 vm_page_t p, p_next;
1366 TAILQ_INIT(&alloctail);
1369 npages = howmany(bytes, PAGE_SIZE);
1370 while (npages > 0) {
1371 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1372 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1373 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1377 * Since the page does not belong to an object, its
1380 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1385 * Page allocation failed, free intermediate pages and
1388 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1389 vm_page_unwire_noq(p);
1394 *flags = UMA_SLAB_PRIV;
1395 zkva = keg->uk_kva +
1396 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1398 TAILQ_FOREACH(p, &alloctail, listq) {
1399 pmap_qenter(zkva, &p, 1);
1403 return ((void *)retkva);
1407 * Frees a number of pages to the system
1410 * mem A pointer to the memory to be freed
1411 * size The size of the memory being freed
1412 * flags The original p->us_flags field
1418 page_free(void *mem, vm_size_t size, uint8_t flags)
1421 if ((flags & UMA_SLAB_KERNEL) == 0)
1422 panic("UMA: page_free used with invalid flags %x", flags);
1424 kmem_free((vm_offset_t)mem, size);
1428 * Frees pcpu zone allocations
1431 * mem A pointer to the memory to be freed
1432 * size The size of the memory being freed
1433 * flags The original p->us_flags field
1439 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1441 vm_offset_t sva, curva;
1445 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1446 sva = (vm_offset_t)mem;
1447 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1448 paddr = pmap_kextract(curva);
1449 m = PHYS_TO_VM_PAGE(paddr);
1450 vm_page_unwire_noq(m);
1453 pmap_qremove(sva, size >> PAGE_SHIFT);
1454 kva_free(sva, size);
1459 * Zero fill initializer
1461 * Arguments/Returns follow uma_init specifications
1464 zero_init(void *mem, int size, int flags)
1471 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1474 * keg The zone we should initialize
1480 keg_small_init(uma_keg_t keg)
1488 if (keg->uk_flags & UMA_ZONE_PCPU) {
1489 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1491 slabsize = UMA_PCPU_ALLOC_SIZE;
1492 keg->uk_ppera = ncpus;
1494 slabsize = UMA_SLAB_SIZE;
1499 * Calculate the size of each allocation (rsize) according to
1500 * alignment. If the requested size is smaller than we have
1501 * allocation bits for we round it up.
1503 rsize = keg->uk_size;
1504 if (rsize < slabsize / SLAB_SETSIZE)
1505 rsize = slabsize / SLAB_SETSIZE;
1506 if (rsize & keg->uk_align)
1507 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1508 keg->uk_rsize = rsize;
1510 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1511 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1512 ("%s: size %u too large", __func__, keg->uk_rsize));
1514 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1517 shsize = SIZEOF_UMA_SLAB;
1519 if (rsize <= slabsize - shsize)
1520 keg->uk_ipers = (slabsize - shsize) / rsize;
1522 /* Handle special case when we have 1 item per slab, so
1523 * alignment requirement can be relaxed. */
1524 KASSERT(keg->uk_size <= slabsize - shsize,
1525 ("%s: size %u greater than slab", __func__, keg->uk_size));
1528 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1529 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1531 memused = keg->uk_ipers * rsize + shsize;
1532 wastedspace = slabsize - memused;
1535 * We can't do OFFPAGE if we're internal or if we've been
1536 * asked to not go to the VM for buckets. If we do this we
1537 * may end up going to the VM for slabs which we do not
1538 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1539 * of UMA_ZONE_VM, which clearly forbids it.
1541 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1542 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1546 * See if using an OFFPAGE slab will limit our waste. Only do
1547 * this if it permits more items per-slab.
1549 * XXX We could try growing slabsize to limit max waste as well.
1550 * Historically this was not done because the VM could not
1551 * efficiently handle contiguous allocations.
1553 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1554 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1555 keg->uk_ipers = slabsize / keg->uk_rsize;
1556 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1557 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1558 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1559 "keg: %s(%p), calculated wastedspace = %d, "
1560 "maximum wasted space allowed = %d, "
1561 "calculated ipers = %d, "
1562 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1563 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1564 slabsize - keg->uk_ipers * keg->uk_rsize);
1565 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1568 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1569 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1570 keg->uk_flags |= UMA_ZONE_HASH;
1574 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1575 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1579 * keg The keg we should initialize
1585 keg_large_init(uma_keg_t keg)
1588 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1589 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1590 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1592 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1594 keg->uk_rsize = keg->uk_size;
1596 /* Check whether we have enough space to not do OFFPAGE. */
1597 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1598 PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1600 * We can't do OFFPAGE if we're internal, in which case
1601 * we need an extra page per allocation to contain the
1604 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1605 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1610 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1611 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1612 keg->uk_flags |= UMA_ZONE_HASH;
1616 keg_cachespread_init(uma_keg_t keg)
1623 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1624 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1626 alignsize = keg->uk_align + 1;
1627 rsize = keg->uk_size;
1629 * We want one item to start on every align boundary in a page. To
1630 * do this we will span pages. We will also extend the item by the
1631 * size of align if it is an even multiple of align. Otherwise, it
1632 * would fall on the same boundary every time.
1634 if (rsize & keg->uk_align)
1635 rsize = (rsize & ~keg->uk_align) + alignsize;
1636 if ((rsize & alignsize) == 0)
1638 trailer = rsize - keg->uk_size;
1639 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1640 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1641 keg->uk_rsize = rsize;
1642 keg->uk_ppera = pages;
1643 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1644 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1645 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1646 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1651 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1652 * the keg onto the global keg list.
1654 * Arguments/Returns follow uma_ctor specifications
1655 * udata Actually uma_kctor_args
1658 keg_ctor(void *mem, int size, void *udata, int flags)
1660 struct uma_kctor_args *arg = udata;
1661 uma_keg_t keg = mem;
1665 keg->uk_size = arg->size;
1666 keg->uk_init = arg->uminit;
1667 keg->uk_fini = arg->fini;
1668 keg->uk_align = arg->align;
1670 keg->uk_reserve = 0;
1672 keg->uk_flags = arg->flags;
1673 keg->uk_slabzone = NULL;
1676 * We use a global round-robin policy by default. Zones with
1677 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1678 * iterator is never run.
1680 keg->uk_dr.dr_policy = DOMAINSET_RR();
1681 keg->uk_dr.dr_iter = 0;
1684 * The master zone is passed to us at keg-creation time.
1687 keg->uk_name = zone->uz_name;
1689 if (arg->flags & UMA_ZONE_VM)
1690 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1692 if (arg->flags & UMA_ZONE_ZINIT)
1693 keg->uk_init = zero_init;
1695 if (arg->flags & UMA_ZONE_MALLOC)
1696 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1698 if (arg->flags & UMA_ZONE_PCPU)
1700 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1702 keg->uk_flags &= ~UMA_ZONE_PCPU;
1705 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1706 keg_cachespread_init(keg);
1708 if (keg->uk_size > UMA_SLAB_SPACE)
1709 keg_large_init(keg);
1711 keg_small_init(keg);
1714 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1715 keg->uk_slabzone = slabzone;
1718 * If we haven't booted yet we need allocations to go through the
1719 * startup cache until the vm is ready.
1721 if (booted < BOOT_PAGEALLOC)
1722 keg->uk_allocf = startup_alloc;
1723 #ifdef UMA_MD_SMALL_ALLOC
1724 else if (keg->uk_ppera == 1)
1725 keg->uk_allocf = uma_small_alloc;
1727 else if (keg->uk_flags & UMA_ZONE_PCPU)
1728 keg->uk_allocf = pcpu_page_alloc;
1730 keg->uk_allocf = page_alloc;
1731 #ifdef UMA_MD_SMALL_ALLOC
1732 if (keg->uk_ppera == 1)
1733 keg->uk_freef = uma_small_free;
1736 if (keg->uk_flags & UMA_ZONE_PCPU)
1737 keg->uk_freef = pcpu_page_free;
1739 keg->uk_freef = page_free;
1742 * Initialize keg's lock
1744 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1747 * If we're putting the slab header in the actual page we need to
1748 * figure out where in each page it goes. See SIZEOF_UMA_SLAB
1751 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1752 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1754 * The only way the following is possible is if with our
1755 * UMA_ALIGN_PTR adjustments we are now bigger than
1756 * UMA_SLAB_SIZE. I haven't checked whether this is
1757 * mathematically possible for all cases, so we make
1760 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1761 PAGE_SIZE * keg->uk_ppera,
1762 ("zone %s ipers %d rsize %d size %d slab won't fit",
1763 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1766 if (keg->uk_flags & UMA_ZONE_HASH)
1767 hash_alloc(&keg->uk_hash, 0);
1769 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1770 keg, zone->uz_name, zone,
1771 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1774 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1776 rw_wlock(&uma_rwlock);
1777 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1778 rw_wunlock(&uma_rwlock);
1783 zone_alloc_counters(uma_zone_t zone)
1786 zone->uz_allocs = counter_u64_alloc(M_WAITOK);
1787 zone->uz_frees = counter_u64_alloc(M_WAITOK);
1788 zone->uz_fails = counter_u64_alloc(M_WAITOK);
1792 * Zone header ctor. This initializes all fields, locks, etc.
1794 * Arguments/Returns follow uma_ctor specifications
1795 * udata Actually uma_zctor_args
1798 zone_ctor(void *mem, int size, void *udata, int flags)
1800 struct uma_zctor_args *arg = udata;
1801 uma_zone_t zone = mem;
1807 zone->uz_name = arg->name;
1808 zone->uz_ctor = arg->ctor;
1809 zone->uz_dtor = arg->dtor;
1810 zone->uz_init = NULL;
1811 zone->uz_fini = NULL;
1812 zone->uz_sleeps = 0;
1813 zone->uz_xdomain = 0;
1815 zone->uz_count_min = 0;
1816 zone->uz_count_max = BUCKET_MAX;
1818 zone->uz_warning = NULL;
1819 /* The domain structures follow the cpu structures. */
1820 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1821 zone->uz_bkt_max = ULONG_MAX;
1822 timevalclear(&zone->uz_ratecheck);
1824 if (__predict_true(booted == BOOT_RUNNING))
1825 zone_alloc_counters(zone);
1827 zone->uz_allocs = EARLY_COUNTER;
1828 zone->uz_frees = EARLY_COUNTER;
1829 zone->uz_fails = EARLY_COUNTER;
1832 for (i = 0; i < vm_ndomains; i++)
1833 TAILQ_INIT(&zone->uz_domain[i].uzd_buckets);
1836 * This is a pure cache zone, no kegs.
1839 if (arg->flags & UMA_ZONE_VM)
1840 arg->flags |= UMA_ZFLAG_CACHEONLY;
1841 zone->uz_flags = arg->flags;
1842 zone->uz_size = arg->size;
1843 zone->uz_import = arg->import;
1844 zone->uz_release = arg->release;
1845 zone->uz_arg = arg->arg;
1846 zone->uz_lockptr = &zone->uz_lock;
1847 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1848 rw_wlock(&uma_rwlock);
1849 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1850 rw_wunlock(&uma_rwlock);
1855 * Use the regular zone/keg/slab allocator.
1857 zone->uz_import = (uma_import)zone_import;
1858 zone->uz_release = (uma_release)zone_release;
1859 zone->uz_arg = zone;
1862 if (arg->flags & UMA_ZONE_SECONDARY) {
1863 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1864 zone->uz_init = arg->uminit;
1865 zone->uz_fini = arg->fini;
1866 zone->uz_lockptr = &keg->uk_lock;
1867 zone->uz_flags |= UMA_ZONE_SECONDARY;
1868 rw_wlock(&uma_rwlock);
1870 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1871 if (LIST_NEXT(z, uz_link) == NULL) {
1872 LIST_INSERT_AFTER(z, zone, uz_link);
1877 rw_wunlock(&uma_rwlock);
1878 } else if (keg == NULL) {
1879 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1880 arg->align, arg->flags)) == NULL)
1883 struct uma_kctor_args karg;
1886 /* We should only be here from uma_startup() */
1887 karg.size = arg->size;
1888 karg.uminit = arg->uminit;
1889 karg.fini = arg->fini;
1890 karg.align = arg->align;
1891 karg.flags = arg->flags;
1893 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1900 zone->uz_size = keg->uk_size;
1901 zone->uz_flags |= (keg->uk_flags &
1902 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1905 * Some internal zones don't have room allocated for the per cpu
1906 * caches. If we're internal, bail out here.
1908 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1909 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1910 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1915 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1916 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1917 ("Invalid zone flag combination"));
1918 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0) {
1919 zone->uz_count = BUCKET_MAX;
1920 } else if ((arg->flags & UMA_ZONE_MINBUCKET) != 0) {
1921 zone->uz_count = BUCKET_MIN;
1922 zone->uz_count_max = BUCKET_MIN;
1923 } else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1926 zone->uz_count = bucket_select(zone->uz_size);
1927 zone->uz_count_min = zone->uz_count;
1933 * Keg header dtor. This frees all data, destroys locks, frees the hash
1934 * table and removes the keg from the global list.
1936 * Arguments/Returns follow uma_dtor specifications
1940 keg_dtor(void *arg, int size, void *udata)
1944 keg = (uma_keg_t)arg;
1946 if (keg->uk_free != 0) {
1947 printf("Freed UMA keg (%s) was not empty (%d items). "
1948 " Lost %d pages of memory.\n",
1949 keg->uk_name ? keg->uk_name : "",
1950 keg->uk_free, keg->uk_pages);
1954 hash_free(&keg->uk_hash);
1962 * Arguments/Returns follow uma_dtor specifications
1966 zone_dtor(void *arg, int size, void *udata)
1971 zone = (uma_zone_t)arg;
1973 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1976 rw_wlock(&uma_rwlock);
1977 LIST_REMOVE(zone, uz_link);
1978 rw_wunlock(&uma_rwlock);
1980 * XXX there are some races here where
1981 * the zone can be drained but zone lock
1982 * released and then refilled before we
1983 * remove it... we dont care for now
1985 zone_reclaim(zone, M_WAITOK, true);
1987 * We only destroy kegs from non secondary/non cache zones.
1989 if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
1991 rw_wlock(&uma_rwlock);
1992 LIST_REMOVE(keg, uk_link);
1993 rw_wunlock(&uma_rwlock);
1994 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1996 counter_u64_free(zone->uz_allocs);
1997 counter_u64_free(zone->uz_frees);
1998 counter_u64_free(zone->uz_fails);
1999 if (zone->uz_lockptr == &zone->uz_lock)
2000 ZONE_LOCK_FINI(zone);
2004 * Traverses every zone in the system and calls a callback
2007 * zfunc A pointer to a function which accepts a zone
2014 zone_foreach(void (*zfunc)(uma_zone_t))
2020 * Before BOOT_RUNNING we are guaranteed to be single
2021 * threaded, so locking isn't needed. Startup functions
2022 * are allowed to use M_WAITOK.
2024 if (__predict_true(booted == BOOT_RUNNING))
2025 rw_rlock(&uma_rwlock);
2026 LIST_FOREACH(keg, &uma_kegs, uk_link) {
2027 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2030 if (__predict_true(booted == BOOT_RUNNING))
2031 rw_runlock(&uma_rwlock);
2035 * Count how many pages do we need to bootstrap. VM supplies
2036 * its need in early zones in the argument, we add up our zones,
2037 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
2038 * zone of zones and zone of kegs are accounted separately.
2040 #define UMA_BOOT_ZONES 11
2041 /* Zone of zones and zone of kegs have arbitrary alignment. */
2042 #define UMA_BOOT_ALIGN 32
2043 static int zsize, ksize;
2045 uma_startup_count(int vm_zones)
2049 ksize = sizeof(struct uma_keg) +
2050 (sizeof(struct uma_domain) * vm_ndomains);
2051 zsize = sizeof(struct uma_zone) +
2052 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2053 (sizeof(struct uma_zone_domain) * vm_ndomains);
2056 * Memory for the zone of kegs and its keg,
2057 * and for zone of zones.
2059 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
2060 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
2062 #ifdef UMA_MD_SMALL_ALLOC
2063 zones = UMA_BOOT_ZONES;
2065 zones = UMA_BOOT_ZONES + vm_zones;
2069 /* Memory for the rest of startup zones, UMA and VM, ... */
2070 if (zsize > UMA_SLAB_SPACE) {
2071 /* See keg_large_init(). */
2074 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
2075 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2078 pages += (zones + vm_zones) * ppera;
2079 } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2080 /* See keg_small_init() special case for uk_ppera = 1. */
2083 pages += howmany(zones,
2084 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2086 /* ... and their kegs. Note that zone of zones allocates a keg! */
2087 pages += howmany(zones + 1,
2088 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2091 * Most of startup zones are not going to be offpages, that's
2092 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2093 * calculations. Some large bucket zones will be offpage, and
2094 * thus will allocate hashes. We take conservative approach
2095 * and assume that all zones may allocate hash. This may give
2096 * us some positive inaccuracy, usually an extra single page.
2098 pages += howmany(zones, UMA_SLAB_SPACE /
2099 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2105 uma_startup(void *mem, int npages)
2107 struct uma_zctor_args args;
2108 uma_keg_t masterkeg;
2112 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2115 rw_init(&uma_rwlock, "UMA lock");
2117 /* Use bootpages memory for the zone of zones and zone of kegs. */
2119 zones = (uma_zone_t)m;
2120 m += roundup(zsize, CACHE_LINE_SIZE);
2121 kegs = (uma_zone_t)m;
2122 m += roundup(zsize, CACHE_LINE_SIZE);
2123 masterkeg = (uma_keg_t)m;
2124 m += roundup(ksize, CACHE_LINE_SIZE);
2125 m = roundup(m, PAGE_SIZE);
2126 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2129 /* "manually" create the initial zone */
2130 memset(&args, 0, sizeof(args));
2131 args.name = "UMA Kegs";
2133 args.ctor = keg_ctor;
2134 args.dtor = keg_dtor;
2135 args.uminit = zero_init;
2137 args.keg = masterkeg;
2138 args.align = UMA_BOOT_ALIGN - 1;
2139 args.flags = UMA_ZFLAG_INTERNAL;
2140 zone_ctor(kegs, zsize, &args, M_WAITOK);
2143 boot_pages = npages;
2145 args.name = "UMA Zones";
2147 args.ctor = zone_ctor;
2148 args.dtor = zone_dtor;
2149 args.uminit = zero_init;
2152 args.align = UMA_BOOT_ALIGN - 1;
2153 args.flags = UMA_ZFLAG_INTERNAL;
2154 zone_ctor(zones, zsize, &args, M_WAITOK);
2156 /* Now make a zone for slab headers */
2157 slabzone = uma_zcreate("UMA Slabs",
2158 sizeof(struct uma_slab),
2159 NULL, NULL, NULL, NULL,
2160 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2162 hashzone = uma_zcreate("UMA Hash",
2163 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2164 NULL, NULL, NULL, NULL,
2165 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2169 booted = BOOT_STRAPPED;
2177 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2179 booted = BOOT_PAGEALLOC;
2187 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2189 booted = BOOT_BUCKETS;
2190 sx_init(&uma_reclaim_lock, "umareclaim");
2195 * Initialize our callout handle
2203 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2204 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2205 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2207 zone_foreach(zone_alloc_counters);
2208 callout_init(&uma_callout, 1);
2209 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2210 booted = BOOT_RUNNING;
2214 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2215 int align, uint32_t flags)
2217 struct uma_kctor_args args;
2220 args.uminit = uminit;
2222 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2225 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2228 /* Public functions */
2231 uma_set_align(int align)
2234 if (align != UMA_ALIGN_CACHE)
2235 uma_align_cache = align;
2240 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2241 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2244 struct uma_zctor_args args;
2248 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2251 /* Sets all zones to a first-touch domain policy. */
2252 #ifdef UMA_FIRSTTOUCH
2253 flags |= UMA_ZONE_NUMA;
2256 /* This stuff is essential for the zone ctor */
2257 memset(&args, 0, sizeof(args));
2262 args.uminit = uminit;
2266 * If a zone is being created with an empty constructor and
2267 * destructor, pass UMA constructor/destructor which checks for
2268 * memory use after free.
2270 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2271 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2272 args.ctor = trash_ctor;
2273 args.dtor = trash_dtor;
2274 args.uminit = trash_init;
2275 args.fini = trash_fini;
2282 if (booted < BOOT_BUCKETS) {
2285 sx_slock(&uma_reclaim_lock);
2288 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2290 sx_sunlock(&uma_reclaim_lock);
2296 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2297 uma_init zinit, uma_fini zfini, uma_zone_t master)
2299 struct uma_zctor_args args;
2304 keg = master->uz_keg;
2305 memset(&args, 0, sizeof(args));
2307 args.size = keg->uk_size;
2310 args.uminit = zinit;
2312 args.align = keg->uk_align;
2313 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2316 if (booted < BOOT_BUCKETS) {
2319 sx_slock(&uma_reclaim_lock);
2322 /* XXX Attaches only one keg of potentially many. */
2323 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2325 sx_sunlock(&uma_reclaim_lock);
2331 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2332 uma_init zinit, uma_fini zfini, uma_import zimport,
2333 uma_release zrelease, void *arg, int flags)
2335 struct uma_zctor_args args;
2337 memset(&args, 0, sizeof(args));
2342 args.uminit = zinit;
2344 args.import = zimport;
2345 args.release = zrelease;
2348 args.flags = flags | UMA_ZFLAG_CACHE;
2350 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2355 uma_zdestroy(uma_zone_t zone)
2358 sx_slock(&uma_reclaim_lock);
2359 zone_free_item(zones, zone, NULL, SKIP_NONE);
2360 sx_sunlock(&uma_reclaim_lock);
2364 uma_zwait(uma_zone_t zone)
2368 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2369 uma_zfree(zone, item);
2373 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2379 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2381 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2382 if (item != NULL && (flags & M_ZERO)) {
2384 for (i = 0; i <= mp_maxid; i++)
2385 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2387 bzero(item, zone->uz_size);
2394 * A stub while both regular and pcpu cases are identical.
2397 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2401 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2403 uma_zfree_arg(zone, item, udata);
2408 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2410 uma_zone_domain_t zdom;
2411 uma_bucket_t bucket;
2414 int cpu, domain, lockfail, maxbucket;
2419 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2420 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2422 /* This is the fast path allocation */
2423 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2424 curthread, zone->uz_name, zone, flags);
2426 if (flags & M_WAITOK) {
2427 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2428 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2430 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2431 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2432 ("uma_zalloc_arg: called with spinlock or critical section held"));
2433 if (zone->uz_flags & UMA_ZONE_PCPU)
2434 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2435 "with M_ZERO passed"));
2437 #ifdef DEBUG_MEMGUARD
2438 if (memguard_cmp_zone(zone)) {
2439 item = memguard_alloc(zone->uz_size, flags);
2441 if (zone->uz_init != NULL &&
2442 zone->uz_init(item, zone->uz_size, flags) != 0)
2444 if (zone->uz_ctor != NULL &&
2445 zone->uz_ctor(item, zone->uz_size, udata,
2447 zone->uz_fini(item, zone->uz_size);
2452 /* This is unfortunate but should not be fatal. */
2456 * If possible, allocate from the per-CPU cache. There are two
2457 * requirements for safe access to the per-CPU cache: (1) the thread
2458 * accessing the cache must not be preempted or yield during access,
2459 * and (2) the thread must not migrate CPUs without switching which
2460 * cache it accesses. We rely on a critical section to prevent
2461 * preemption and migration. We release the critical section in
2462 * order to acquire the zone mutex if we are unable to allocate from
2463 * the current cache; when we re-acquire the critical section, we
2464 * must detect and handle migration if it has occurred.
2469 cache = &zone->uz_cpu[cpu];
2472 bucket = cache->uc_allocbucket;
2473 if (bucket != NULL && bucket->ub_cnt > 0) {
2475 item = bucket->ub_bucket[bucket->ub_cnt];
2477 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2479 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2483 skipdbg = uma_dbg_zskip(zone, item);
2485 if (zone->uz_ctor != NULL &&
2487 (!skipdbg || zone->uz_ctor != trash_ctor ||
2488 zone->uz_dtor != trash_dtor) &&
2490 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2491 counter_u64_add(zone->uz_fails, 1);
2492 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2497 uma_dbg_alloc(zone, NULL, item);
2500 uma_zero_item(item, zone);
2505 * We have run out of items in our alloc bucket.
2506 * See if we can switch with our free bucket.
2508 bucket = cache->uc_freebucket;
2509 if (bucket != NULL && bucket->ub_cnt > 0) {
2511 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2512 zone->uz_name, zone);
2513 cache->uc_freebucket = cache->uc_allocbucket;
2514 cache->uc_allocbucket = bucket;
2519 * Discard any empty allocation bucket while we hold no locks.
2521 bucket = cache->uc_allocbucket;
2522 cache->uc_allocbucket = NULL;
2525 bucket_free(zone, bucket, udata);
2527 /* Short-circuit for zones without buckets and low memory. */
2528 if (zone->uz_count == 0 || bucketdisable) {
2530 if (zone->uz_flags & UMA_ZONE_NUMA)
2531 domain = PCPU_GET(domain);
2533 domain = UMA_ANYDOMAIN;
2538 * Attempt to retrieve the item from the per-CPU cache has failed, so
2539 * we must go back to the zone. This requires the zone lock, so we
2540 * must drop the critical section, then re-acquire it when we go back
2541 * to the cache. Since the critical section is released, we may be
2542 * preempted or migrate. As such, make sure not to maintain any
2543 * thread-local state specific to the cache from prior to releasing
2544 * the critical section.
2547 if (ZONE_TRYLOCK(zone) == 0) {
2548 /* Record contention to size the buckets. */
2554 cache = &zone->uz_cpu[cpu];
2556 /* See if we lost the race to fill the cache. */
2557 if (cache->uc_allocbucket != NULL) {
2563 * Check the zone's cache of buckets.
2565 if (zone->uz_flags & UMA_ZONE_NUMA) {
2566 domain = PCPU_GET(domain);
2567 zdom = &zone->uz_domain[domain];
2569 domain = UMA_ANYDOMAIN;
2570 zdom = &zone->uz_domain[0];
2573 if ((bucket = zone_fetch_bucket(zone, zdom)) != NULL) {
2574 KASSERT(bucket->ub_cnt != 0,
2575 ("uma_zalloc_arg: Returning an empty bucket."));
2576 cache->uc_allocbucket = bucket;
2580 /* We are no longer associated with this CPU. */
2584 * We bump the uz count when the cache size is insufficient to
2585 * handle the working set.
2587 if (lockfail && zone->uz_count < zone->uz_count_max)
2590 if (zone->uz_max_items > 0) {
2591 if (zone->uz_items >= zone->uz_max_items)
2593 maxbucket = MIN(zone->uz_count,
2594 zone->uz_max_items - zone->uz_items);
2595 zone->uz_items += maxbucket;
2597 maxbucket = zone->uz_count;
2601 * Now lets just fill a bucket and put it on the free list. If that
2602 * works we'll restart the allocation from the beginning and it
2603 * will use the just filled bucket.
2605 bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2606 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2607 zone->uz_name, zone, bucket);
2609 if (bucket != NULL) {
2610 if (zone->uz_max_items > 0 && bucket->ub_cnt < maxbucket) {
2611 MPASS(zone->uz_items >= maxbucket - bucket->ub_cnt);
2612 zone->uz_items -= maxbucket - bucket->ub_cnt;
2613 if (zone->uz_sleepers > 0 &&
2614 zone->uz_items < zone->uz_max_items)
2619 cache = &zone->uz_cpu[cpu];
2622 * See if we lost the race or were migrated. Cache the
2623 * initialized bucket to make this less likely or claim
2624 * the memory directly.
2626 if (cache->uc_allocbucket == NULL &&
2627 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2628 domain == PCPU_GET(domain))) {
2629 cache->uc_allocbucket = bucket;
2630 zdom->uzd_imax += bucket->ub_cnt;
2631 } else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2634 bucket_drain(zone, bucket);
2635 bucket_free(zone, bucket, udata);
2636 goto zalloc_restart;
2638 zone_put_bucket(zone, zdom, bucket, false);
2641 } else if (zone->uz_max_items > 0) {
2642 zone->uz_items -= maxbucket;
2643 if (zone->uz_sleepers > 0 &&
2644 zone->uz_items + 1 < zone->uz_max_items)
2649 * We may not be able to get a bucket so return an actual item.
2652 item = zone_alloc_item_locked(zone, udata, domain, flags);
2658 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2661 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2662 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2664 /* This is the fast path allocation */
2666 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2667 curthread, zone->uz_name, zone, domain, flags);
2669 if (flags & M_WAITOK) {
2670 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2671 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2673 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2674 ("uma_zalloc_domain: called with spinlock or critical section held"));
2676 return (zone_alloc_item(zone, udata, domain, flags));
2680 * Find a slab with some space. Prefer slabs that are partially used over those
2681 * that are totally full. This helps to reduce fragmentation.
2683 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2687 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2693 KASSERT(domain >= 0 && domain < vm_ndomains,
2694 ("keg_first_slab: domain %d out of range", domain));
2695 KEG_LOCK_ASSERT(keg);
2700 dom = &keg->uk_domain[domain];
2701 if (!LIST_EMPTY(&dom->ud_part_slab))
2702 return (LIST_FIRST(&dom->ud_part_slab));
2703 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2704 slab = LIST_FIRST(&dom->ud_free_slab);
2705 LIST_REMOVE(slab, us_link);
2706 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2710 domain = (domain + 1) % vm_ndomains;
2711 } while (domain != start);
2717 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2721 KEG_LOCK_ASSERT(keg);
2723 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2724 if (keg->uk_free <= reserve)
2726 return (keg_first_slab(keg, domain, rr));
2730 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2732 struct vm_domainset_iter di;
2739 KEG_LOCK_ASSERT(keg);
2742 * Use the keg's policy if upper layers haven't already specified a
2743 * domain (as happens with first-touch zones).
2745 * To avoid races we run the iterator with the keg lock held, but that
2746 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2747 * clear M_WAITOK and handle low memory conditions locally.
2749 rr = rdomain == UMA_ANYDOMAIN;
2751 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2752 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2760 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2762 MPASS(slab->us_keg == keg);
2767 * M_NOVM means don't ask at all!
2772 KASSERT(zone->uz_max_items == 0 ||
2773 zone->uz_items <= zone->uz_max_items,
2774 ("%s: zone %p overflow", __func__, zone));
2776 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
2778 * If we got a slab here it's safe to mark it partially used
2779 * and return. We assume that the caller is going to remove
2780 * at least one item.
2783 MPASS(slab->us_keg == keg);
2784 dom = &keg->uk_domain[slab->us_domain];
2785 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2789 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2790 if ((flags & M_WAITOK) != 0) {
2792 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2801 * We might not have been able to get a slab but another cpu
2802 * could have while we were unlocked. Check again before we
2805 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2806 MPASS(slab->us_keg == keg);
2813 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2823 slab = keg_fetch_slab(keg, zone, domain, flags);
2826 if (flags & (M_NOWAIT | M_NOVM))
2834 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2840 MPASS(keg == slab->us_keg);
2841 KEG_LOCK_ASSERT(keg);
2843 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2844 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2845 item = slab->us_data + (keg->uk_rsize * freei);
2846 slab->us_freecount--;
2849 /* Move this slab to the full list */
2850 if (slab->us_freecount == 0) {
2851 LIST_REMOVE(slab, us_link);
2852 dom = &keg->uk_domain[slab->us_domain];
2853 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2860 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2871 /* Try to keep the buckets totally full */
2872 for (i = 0; i < max; ) {
2873 if ((slab = zone_fetch_slab(zone, keg, domain, flags)) == NULL)
2877 stripe = howmany(max, vm_ndomains);
2879 while (slab->us_freecount && i < max) {
2880 bucket[i++] = slab_alloc_item(keg, slab);
2881 if (keg->uk_free <= keg->uk_reserve)
2885 * If the zone is striped we pick a new slab for every
2886 * N allocations. Eliminating this conditional will
2887 * instead pick a new domain for each bucket rather
2888 * than stripe within each bucket. The current option
2889 * produces more fragmentation and requires more cpu
2890 * time but yields better distribution.
2892 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2893 vm_ndomains > 1 && --stripe == 0)
2897 /* Don't block if we allocated any successfully. */
2908 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2910 uma_bucket_t bucket;
2912 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2914 /* Avoid allocs targeting empty domains. */
2915 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
2916 domain = UMA_ANYDOMAIN;
2918 /* Don't wait for buckets, preserve caller's NOVM setting. */
2919 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2923 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2924 MIN(max, bucket->ub_entries), domain, flags);
2927 * Initialize the memory if necessary.
2929 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2932 for (i = 0; i < bucket->ub_cnt; i++)
2933 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2937 * If we couldn't initialize the whole bucket, put the
2938 * rest back onto the freelist.
2940 if (i != bucket->ub_cnt) {
2941 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2942 bucket->ub_cnt - i);
2944 bzero(&bucket->ub_bucket[i],
2945 sizeof(void *) * (bucket->ub_cnt - i));
2951 if (bucket->ub_cnt == 0) {
2952 bucket_free(zone, bucket, udata);
2953 counter_u64_add(zone->uz_fails, 1);
2961 * Allocates a single item from a zone.
2964 * zone The zone to alloc for.
2965 * udata The data to be passed to the constructor.
2966 * domain The domain to allocate from or UMA_ANYDOMAIN.
2967 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2970 * NULL if there is no memory and M_NOWAIT is set
2971 * An item if successful
2975 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2979 return (zone_alloc_item_locked(zone, udata, domain, flags));
2983 * Returns with zone unlocked.
2986 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2993 ZONE_LOCK_ASSERT(zone);
2995 if (zone->uz_max_items > 0) {
2996 if (zone->uz_items >= zone->uz_max_items) {
2997 zone_log_warning(zone);
2998 zone_maxaction(zone);
2999 if (flags & M_NOWAIT) {
3004 zone->uz_sleepers++;
3005 while (zone->uz_items >= zone->uz_max_items)
3006 mtx_sleep(zone, zone->uz_lockptr, PVM,
3008 zone->uz_sleepers--;
3009 if (zone->uz_sleepers > 0 &&
3010 zone->uz_items + 1 < zone->uz_max_items)
3017 /* Avoid allocs targeting empty domains. */
3018 if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
3019 domain = UMA_ANYDOMAIN;
3021 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
3025 skipdbg = uma_dbg_zskip(zone, item);
3028 * We have to call both the zone's init (not the keg's init)
3029 * and the zone's ctor. This is because the item is going from
3030 * a keg slab directly to the user, and the user is expecting it
3031 * to be both zone-init'd as well as zone-ctor'd.
3033 if (zone->uz_init != NULL) {
3034 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
3035 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
3039 if (zone->uz_ctor != NULL &&
3041 (!skipdbg || zone->uz_ctor != trash_ctor ||
3042 zone->uz_dtor != trash_dtor) &&
3044 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
3045 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3050 uma_dbg_alloc(zone, NULL, item);
3053 uma_zero_item(item, zone);
3055 counter_u64_add(zone->uz_allocs, 1);
3056 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3057 zone->uz_name, zone);
3062 if (zone->uz_max_items > 0) {
3067 counter_u64_add(zone->uz_fails, 1);
3068 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3069 zone->uz_name, zone);
3075 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3078 uma_bucket_t bucket;
3079 uma_zone_domain_t zdom;
3089 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3090 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3092 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3095 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3096 ("uma_zfree_arg: called with spinlock or critical section held"));
3098 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3101 #ifdef DEBUG_MEMGUARD
3102 if (is_memguard_addr(item)) {
3103 if (zone->uz_dtor != NULL)
3104 zone->uz_dtor(item, zone->uz_size, udata);
3105 if (zone->uz_fini != NULL)
3106 zone->uz_fini(item, zone->uz_size);
3107 memguard_free(item);
3112 skipdbg = uma_dbg_zskip(zone, item);
3113 if (skipdbg == false) {
3114 if (zone->uz_flags & UMA_ZONE_MALLOC)
3115 uma_dbg_free(zone, udata, item);
3117 uma_dbg_free(zone, NULL, item);
3119 if (zone->uz_dtor != NULL && (!skipdbg ||
3120 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3122 if (zone->uz_dtor != NULL)
3124 zone->uz_dtor(item, zone->uz_size, udata);
3127 * The race here is acceptable. If we miss it we'll just have to wait
3128 * a little longer for the limits to be reset.
3130 if (zone->uz_sleepers > 0)
3134 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0)
3135 itemdomain = _vm_phys_domain(pmap_kextract((vm_offset_t)item));
3139 * If possible, free to the per-CPU cache. There are two
3140 * requirements for safe access to the per-CPU cache: (1) the thread
3141 * accessing the cache must not be preempted or yield during access,
3142 * and (2) the thread must not migrate CPUs without switching which
3143 * cache it accesses. We rely on a critical section to prevent
3144 * preemption and migration. We release the critical section in
3145 * order to acquire the zone mutex if we are unable to free to the
3146 * current cache; when we re-acquire the critical section, we must
3147 * detect and handle migration if it has occurred.
3152 cache = &zone->uz_cpu[cpu];
3155 domain = PCPU_GET(domain);
3157 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0)
3158 itemdomain = domain;
3161 * Try to free into the allocbucket first to give LIFO ordering
3162 * for cache-hot datastructures. Spill over into the freebucket
3163 * if necessary. Alloc will swap them if one runs dry.
3166 if (domain != itemdomain) {
3167 bucket = cache->uc_crossbucket;
3171 bucket = cache->uc_allocbucket;
3172 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3173 bucket = cache->uc_freebucket;
3175 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3176 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3177 ("uma_zfree: Freeing to non free bucket index."));
3178 bucket->ub_bucket[bucket->ub_cnt] = item;
3186 * We must go back the zone, which requires acquiring the zone lock,
3187 * which in turn means we must release and re-acquire the critical
3188 * section. Since the critical section is released, we may be
3189 * preempted or migrate. As such, make sure not to maintain any
3190 * thread-local state specific to the cache from prior to releasing
3191 * the critical section.
3194 if (zone->uz_count == 0 || bucketdisable)
3198 if (ZONE_TRYLOCK(zone) == 0) {
3199 /* Record contention to size the buckets. */
3205 domain = PCPU_GET(domain);
3206 cache = &zone->uz_cpu[cpu];
3209 if (domain != itemdomain)
3210 bucket = cache->uc_crossbucket;
3213 bucket = cache->uc_freebucket;
3214 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3219 if (domain != itemdomain)
3220 cache->uc_crossbucket = NULL;
3223 cache->uc_freebucket = NULL;
3224 /* We are no longer associated with this CPU. */
3228 if (domain != itemdomain) {
3229 if (bucket != NULL) {
3230 zone->uz_xdomain += bucket->ub_cnt;
3231 if (vm_ndomains > 2 ||
3232 zone->uz_bkt_count >= zone->uz_bkt_max) {
3234 bucket_drain(zone, bucket);
3235 bucket_free(zone, bucket, udata);
3237 zdom = &zone->uz_domain[itemdomain];
3238 zone_put_bucket(zone, zdom, bucket, true);
3243 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3248 cache = &zone->uz_cpu[cpu];
3249 if (cache->uc_crossbucket == NULL) {
3250 cache->uc_crossbucket = bucket;
3254 bucket_free(zone, bucket, udata);
3259 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3260 zdom = &zone->uz_domain[domain];
3263 zdom = &zone->uz_domain[0];
3266 /* Can we throw this on the zone full list? */
3267 if (bucket != NULL) {
3269 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3270 zone->uz_name, zone, bucket);
3271 /* ub_cnt is pointing to the last free item */
3272 KASSERT(bucket->ub_cnt == bucket->ub_entries,
3273 ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3274 if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3276 bucket_drain(zone, bucket);
3277 bucket_free(zone, bucket, udata);
3280 zone_put_bucket(zone, zdom, bucket, true);
3284 * We bump the uz count when the cache size is insufficient to
3285 * handle the working set.
3287 if (lockfail && zone->uz_count < zone->uz_count_max)
3291 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3292 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3293 zone->uz_name, zone, bucket);
3297 cache = &zone->uz_cpu[cpu];
3298 if (cache->uc_freebucket == NULL &&
3299 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3300 domain == PCPU_GET(domain))) {
3301 cache->uc_freebucket = bucket;
3305 * We lost the race, start over. We have to drop our
3306 * critical section to free the bucket.
3309 bucket_free(zone, bucket, udata);
3314 * If nothing else caught this, we'll just do an internal free.
3317 zone_free_item(zone, item, udata, SKIP_DTOR);
3321 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3324 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3325 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3327 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3330 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3331 ("uma_zfree_domain: called with spinlock or critical section held"));
3333 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3336 zone_free_item(zone, item, udata, SKIP_NONE);
3340 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3347 MPASS(zone->uz_lockptr == &keg->uk_lock);
3348 KEG_LOCK_ASSERT(keg);
3349 MPASS(keg == slab->us_keg);
3351 dom = &keg->uk_domain[slab->us_domain];
3353 /* Do we need to remove from any lists? */
3354 if (slab->us_freecount+1 == keg->uk_ipers) {
3355 LIST_REMOVE(slab, us_link);
3356 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3357 } else if (slab->us_freecount == 0) {
3358 LIST_REMOVE(slab, us_link);
3359 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3362 /* Slab management. */
3363 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3364 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3365 slab->us_freecount++;
3367 /* Keg statistics. */
3372 zone_release(uma_zone_t zone, void **bucket, int cnt)
3382 for (i = 0; i < cnt; i++) {
3384 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3385 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3386 if (zone->uz_flags & UMA_ZONE_HASH) {
3387 slab = hash_sfind(&keg->uk_hash, mem);
3389 mem += keg->uk_pgoff;
3390 slab = (uma_slab_t)mem;
3393 slab = vtoslab((vm_offset_t)item);
3394 MPASS(slab->us_keg == keg);
3396 slab_free_item(zone, slab, item);
3402 * Frees a single item to any zone.
3405 * zone The zone to free to
3406 * item The item we're freeing
3407 * udata User supplied data for the dtor
3408 * skip Skip dtors and finis
3411 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3416 skipdbg = uma_dbg_zskip(zone, item);
3417 if (skip == SKIP_NONE && !skipdbg) {
3418 if (zone->uz_flags & UMA_ZONE_MALLOC)
3419 uma_dbg_free(zone, udata, item);
3421 uma_dbg_free(zone, NULL, item);
3424 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3425 (!skipdbg || zone->uz_dtor != trash_dtor ||
3426 zone->uz_ctor != trash_ctor))
3428 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3430 zone->uz_dtor(item, zone->uz_size, udata);
3432 if (skip < SKIP_FINI && zone->uz_fini)
3433 zone->uz_fini(item, zone->uz_size);
3435 zone->uz_release(zone->uz_arg, &item, 1);
3437 if (skip & SKIP_CNT)
3440 counter_u64_add(zone->uz_frees, 1);
3442 if (zone->uz_max_items > 0) {
3445 if (zone->uz_sleepers > 0 &&
3446 zone->uz_items < zone->uz_max_items)
3454 uma_zone_set_max(uma_zone_t zone, int nitems)
3456 struct uma_bucket_zone *ubz;
3459 * If limit is very low we may need to limit how
3460 * much items are allowed in CPU caches.
3462 ubz = &bucket_zones[0];
3463 for (; ubz->ubz_entries != 0; ubz++)
3464 if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3466 if (ubz == &bucket_zones[0])
3467 nitems = ubz->ubz_entries * 2 * mp_ncpus;
3472 zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3473 if (zone->uz_count_min > zone->uz_count_max)
3474 zone->uz_count_min = zone->uz_count_max;
3475 zone->uz_max_items = nitems;
3483 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3487 zone->uz_bkt_max = nitems;
3495 uma_zone_get_max(uma_zone_t zone)
3500 nitems = zone->uz_max_items;
3508 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3512 zone->uz_warning = warning;
3518 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3522 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3528 uma_zone_get_cur(uma_zone_t zone)
3534 nitems = counter_u64_fetch(zone->uz_allocs) -
3535 counter_u64_fetch(zone->uz_frees);
3538 * See the comment in uma_vm_zone_stats() regarding the
3539 * safety of accessing the per-cpu caches. With the zone lock
3540 * held, it is safe, but can potentially result in stale data.
3542 nitems += zone->uz_cpu[i].uc_allocs -
3543 zone->uz_cpu[i].uc_frees;
3547 return (nitems < 0 ? 0 : nitems);
3552 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3558 KASSERT(keg->uk_pages == 0,
3559 ("uma_zone_set_init on non-empty keg"));
3560 keg->uk_init = uminit;
3566 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3572 KASSERT(keg->uk_pages == 0,
3573 ("uma_zone_set_fini on non-empty keg"));
3574 keg->uk_fini = fini;
3580 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3584 KASSERT(zone->uz_keg->uk_pages == 0,
3585 ("uma_zone_set_zinit on non-empty keg"));
3586 zone->uz_init = zinit;
3592 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3596 KASSERT(zone->uz_keg->uk_pages == 0,
3597 ("uma_zone_set_zfini on non-empty keg"));
3598 zone->uz_fini = zfini;
3603 /* XXX uk_freef is not actually used with the zone locked */
3605 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3610 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3612 keg->uk_freef = freef;
3617 /* XXX uk_allocf is not actually used with the zone locked */
3619 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3625 keg->uk_allocf = allocf;
3631 uma_zone_reserve(uma_zone_t zone, int items)
3637 keg->uk_reserve = items;
3643 uma_zone_reserve_kva(uma_zone_t zone, int count)
3651 pages = count / keg->uk_ipers;
3652 if (pages * keg->uk_ipers < count)
3654 pages *= keg->uk_ppera;
3656 #ifdef UMA_MD_SMALL_ALLOC
3657 if (keg->uk_ppera > 1) {
3661 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3668 MPASS(keg->uk_kva == 0);
3671 zone->uz_max_items = pages * keg->uk_ipers;
3672 #ifdef UMA_MD_SMALL_ALLOC
3673 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3675 keg->uk_allocf = noobj_alloc;
3677 keg->uk_flags |= UMA_ZONE_NOFREE;
3685 uma_prealloc(uma_zone_t zone, int items)
3687 struct vm_domainset_iter di;
3691 int aflags, domain, slabs;
3695 slabs = items / keg->uk_ipers;
3696 if (slabs * keg->uk_ipers < items)
3698 while (slabs-- > 0) {
3700 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3703 slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
3706 MPASS(slab->us_keg == keg);
3707 dom = &keg->uk_domain[slab->us_domain];
3708 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
3713 if (vm_domainset_iter_policy(&di, &domain) != 0) {
3715 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
3725 uma_reclaim(int req)
3728 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3729 sx_xlock(&uma_reclaim_lock);
3733 case UMA_RECLAIM_TRIM:
3734 zone_foreach(zone_trim);
3736 case UMA_RECLAIM_DRAIN:
3737 case UMA_RECLAIM_DRAIN_CPU:
3738 zone_foreach(zone_drain);
3739 if (req == UMA_RECLAIM_DRAIN_CPU) {
3740 pcpu_cache_drain_safe(NULL);
3741 zone_foreach(zone_drain);
3745 panic("unhandled reclamation request %d", req);
3749 * Some slabs may have been freed but this zone will be visited early
3750 * we visit again so that we can free pages that are empty once other
3751 * zones are drained. We have to do the same for buckets.
3753 zone_drain(slabzone);
3754 bucket_zone_drain();
3755 sx_xunlock(&uma_reclaim_lock);
3758 static volatile int uma_reclaim_needed;
3761 uma_reclaim_wakeup(void)
3764 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3765 wakeup(uma_reclaim);
3769 uma_reclaim_worker(void *arg __unused)
3773 sx_xlock(&uma_reclaim_lock);
3774 while (atomic_load_int(&uma_reclaim_needed) == 0)
3775 sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
3777 sx_xunlock(&uma_reclaim_lock);
3778 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3779 uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
3780 atomic_store_int(&uma_reclaim_needed, 0);
3781 /* Don't fire more than once per-second. */
3782 pause("umarclslp", hz);
3788 uma_zone_reclaim(uma_zone_t zone, int req)
3792 case UMA_RECLAIM_TRIM:
3795 case UMA_RECLAIM_DRAIN:
3798 case UMA_RECLAIM_DRAIN_CPU:
3799 pcpu_cache_drain_safe(zone);
3803 panic("unhandled reclamation request %d", req);
3809 uma_zone_exhausted(uma_zone_t zone)
3814 full = zone->uz_sleepers > 0;
3820 uma_zone_exhausted_nolock(uma_zone_t zone)
3822 return (zone->uz_sleepers > 0);
3826 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3828 struct domainset *policy;
3832 if (domain != UMA_ANYDOMAIN) {
3833 /* avoid allocs targeting empty domains */
3834 if (VM_DOMAIN_EMPTY(domain))
3835 domain = UMA_ANYDOMAIN;
3837 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3840 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3841 DOMAINSET_FIXED(domain);
3842 addr = kmem_malloc_domainset(policy, size, wait);
3844 vsetslab(addr, slab);
3845 slab->us_data = (void *)addr;
3846 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3847 slab->us_size = size;
3848 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3849 pmap_kextract(addr)));
3850 uma_total_inc(size);
3852 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3855 return ((void *)addr);
3859 uma_large_malloc(vm_size_t size, int wait)
3862 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3866 uma_large_free(uma_slab_t slab)
3869 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3870 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3871 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3872 uma_total_dec(slab->us_size);
3873 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3877 uma_zero_item(void *item, uma_zone_t zone)
3880 bzero(item, zone->uz_size);
3887 return (uma_kmem_limit);
3891 uma_set_limit(unsigned long limit)
3894 uma_kmem_limit = limit;
3901 return (atomic_load_long(&uma_kmem_total));
3908 return (uma_kmem_limit - uma_size());
3912 uma_print_stats(void)
3914 zone_foreach(uma_print_zone);
3918 slab_print(uma_slab_t slab)
3920 printf("slab: keg %p, data %p, freecount %d\n",
3921 slab->us_keg, slab->us_data, slab->us_freecount);
3925 cache_print(uma_cache_t cache)
3927 printf("alloc: %p(%d), free: %p(%d), cross: %p(%d)j\n",
3928 cache->uc_allocbucket,
3929 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3930 cache->uc_freebucket,
3931 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0,
3932 cache->uc_crossbucket,
3933 cache->uc_crossbucket?cache->uc_crossbucket->ub_cnt:0);
3937 uma_print_keg(uma_keg_t keg)
3943 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3945 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3946 keg->uk_ipers, keg->uk_ppera,
3947 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3949 for (i = 0; i < vm_ndomains; i++) {
3950 dom = &keg->uk_domain[i];
3951 printf("Part slabs:\n");
3952 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3954 printf("Free slabs:\n");
3955 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3957 printf("Full slabs:\n");
3958 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3964 uma_print_zone(uma_zone_t zone)
3969 printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3970 zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3972 if (zone->uz_lockptr != &zone->uz_lock)
3973 uma_print_keg(zone->uz_keg);
3975 cache = &zone->uz_cpu[i];
3976 printf("CPU %d Cache:\n", i);
3983 * Generate statistics across both the zone and its per-cpu cache's. Return
3984 * desired statistics if the pointer is non-NULL for that statistic.
3986 * Note: does not update the zone statistics, as it can't safely clear the
3987 * per-CPU cache statistic.
3989 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3990 * safe from off-CPU; we should modify the caches to track this information
3991 * directly so that we don't have to.
3994 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3995 uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
3998 uint64_t allocs, frees, sleeps, xdomain;
4001 allocs = frees = sleeps = xdomain = 0;
4004 cache = &z->uz_cpu[cpu];
4005 if (cache->uc_allocbucket != NULL)
4006 cachefree += cache->uc_allocbucket->ub_cnt;
4007 if (cache->uc_freebucket != NULL)
4008 cachefree += cache->uc_freebucket->ub_cnt;
4009 if (cache->uc_crossbucket != NULL) {
4010 xdomain += cache->uc_crossbucket->ub_cnt;
4011 cachefree += cache->uc_crossbucket->ub_cnt;
4013 allocs += cache->uc_allocs;
4014 frees += cache->uc_frees;
4016 allocs += counter_u64_fetch(z->uz_allocs);
4017 frees += counter_u64_fetch(z->uz_frees);
4018 sleeps += z->uz_sleeps;
4019 xdomain += z->uz_xdomain;
4020 if (cachefreep != NULL)
4021 *cachefreep = cachefree;
4022 if (allocsp != NULL)
4026 if (sleepsp != NULL)
4028 if (xdomainp != NULL)
4029 *xdomainp = xdomain;
4034 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
4041 rw_rlock(&uma_rwlock);
4042 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4043 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4046 LIST_FOREACH(z, &uma_cachezones, uz_link)
4049 rw_runlock(&uma_rwlock);
4050 return (sysctl_handle_int(oidp, &count, 0, req));
4054 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
4055 struct uma_percpu_stat *ups, bool internal)
4057 uma_zone_domain_t zdom;
4062 for (i = 0; i < vm_ndomains; i++) {
4063 zdom = &z->uz_domain[i];
4064 uth->uth_zone_free += zdom->uzd_nitems;
4066 uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
4067 uth->uth_frees = counter_u64_fetch(z->uz_frees);
4068 uth->uth_fails = counter_u64_fetch(z->uz_fails);
4069 uth->uth_sleeps = z->uz_sleeps;
4070 uth->uth_xdomain = z->uz_xdomain;
4072 * While it is not normally safe to access the cache
4073 * bucket pointers while not on the CPU that owns the
4074 * cache, we only allow the pointers to be exchanged
4075 * without the zone lock held, not invalidated, so
4076 * accept the possible race associated with bucket
4077 * exchange during monitoring.
4079 for (i = 0; i < mp_maxid + 1; i++) {
4080 bzero(&ups[i], sizeof(*ups));
4081 if (internal || CPU_ABSENT(i))
4083 cache = &z->uz_cpu[i];
4084 if (cache->uc_allocbucket != NULL)
4085 ups[i].ups_cache_free +=
4086 cache->uc_allocbucket->ub_cnt;
4087 if (cache->uc_freebucket != NULL)
4088 ups[i].ups_cache_free +=
4089 cache->uc_freebucket->ub_cnt;
4090 if (cache->uc_crossbucket != NULL)
4091 ups[i].ups_cache_free +=
4092 cache->uc_crossbucket->ub_cnt;
4093 ups[i].ups_allocs = cache->uc_allocs;
4094 ups[i].ups_frees = cache->uc_frees;
4099 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
4101 struct uma_stream_header ush;
4102 struct uma_type_header uth;
4103 struct uma_percpu_stat *ups;
4107 int count, error, i;
4109 error = sysctl_wire_old_buffer(req, 0);
4112 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
4113 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
4114 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
4117 rw_rlock(&uma_rwlock);
4118 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4119 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4123 LIST_FOREACH(z, &uma_cachezones, uz_link)
4127 * Insert stream header.
4129 bzero(&ush, sizeof(ush));
4130 ush.ush_version = UMA_STREAM_VERSION;
4131 ush.ush_maxcpus = (mp_maxid + 1);
4132 ush.ush_count = count;
4133 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
4135 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4136 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4137 bzero(&uth, sizeof(uth));
4139 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4140 uth.uth_align = kz->uk_align;
4141 uth.uth_size = kz->uk_size;
4142 uth.uth_rsize = kz->uk_rsize;
4143 if (z->uz_max_items > 0)
4144 uth.uth_pages = (z->uz_items / kz->uk_ipers) *
4147 uth.uth_pages = kz->uk_pages;
4148 uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
4150 uth.uth_limit = z->uz_max_items;
4151 uth.uth_keg_free = z->uz_keg->uk_free;
4154 * A zone is secondary is it is not the first entry
4155 * on the keg's zone list.
4157 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
4158 (LIST_FIRST(&kz->uk_zones) != z))
4159 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
4160 uma_vm_zone_stats(&uth, z, &sbuf, ups,
4161 kz->uk_flags & UMA_ZFLAG_INTERNAL);
4163 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4164 for (i = 0; i < mp_maxid + 1; i++)
4165 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4168 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4169 bzero(&uth, sizeof(uth));
4171 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4172 uth.uth_size = z->uz_size;
4173 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
4175 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4176 for (i = 0; i < mp_maxid + 1; i++)
4177 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4180 rw_runlock(&uma_rwlock);
4181 error = sbuf_finish(&sbuf);
4188 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4190 uma_zone_t zone = *(uma_zone_t *)arg1;
4193 max = uma_zone_get_max(zone);
4194 error = sysctl_handle_int(oidp, &max, 0, req);
4195 if (error || !req->newptr)
4198 uma_zone_set_max(zone, max);
4204 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4206 uma_zone_t zone = *(uma_zone_t *)arg1;
4209 cur = uma_zone_get_cur(zone);
4210 return (sysctl_handle_int(oidp, &cur, 0, req));
4215 uma_dbg_getslab(uma_zone_t zone, void *item)
4221 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4222 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4223 slab = vtoslab((vm_offset_t)mem);
4226 * It is safe to return the slab here even though the
4227 * zone is unlocked because the item's allocation state
4228 * essentially holds a reference.
4230 if (zone->uz_lockptr == &zone->uz_lock)
4234 if (keg->uk_flags & UMA_ZONE_HASH)
4235 slab = hash_sfind(&keg->uk_hash, mem);
4237 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4245 uma_dbg_zskip(uma_zone_t zone, void *mem)
4248 if (zone->uz_lockptr == &zone->uz_lock)
4251 return (uma_dbg_kskip(zone->uz_keg, mem));
4255 uma_dbg_kskip(uma_keg_t keg, void *mem)
4259 if (dbg_divisor == 0)
4262 if (dbg_divisor == 1)
4265 idx = (uintptr_t)mem >> PAGE_SHIFT;
4266 if (keg->uk_ipers > 1) {
4267 idx *= keg->uk_ipers;
4268 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4271 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4272 counter_u64_add(uma_skip_cnt, 1);
4275 counter_u64_add(uma_dbg_cnt, 1);
4281 * Set up the slab's freei data such that uma_dbg_free can function.
4285 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4291 slab = uma_dbg_getslab(zone, item);
4293 panic("uma: item %p did not belong to zone %s\n",
4294 item, zone->uz_name);
4297 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4299 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4300 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4301 item, zone, zone->uz_name, slab, freei);
4302 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4308 * Verifies freed addresses. Checks for alignment, valid slab membership
4309 * and duplicate frees.
4313 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4319 slab = uma_dbg_getslab(zone, item);
4321 panic("uma: Freed item %p did not belong to zone %s\n",
4322 item, zone->uz_name);
4325 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4327 if (freei >= keg->uk_ipers)
4328 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4329 item, zone, zone->uz_name, slab, freei);
4331 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4332 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4333 item, zone, zone->uz_name, slab, freei);
4335 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4336 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4337 item, zone, zone->uz_name, slab, freei);
4339 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4341 #endif /* INVARIANTS */
4344 DB_SHOW_COMMAND(uma, db_show_uma)
4348 uint64_t allocs, frees, sleeps, xdomain;
4352 db_printf("%18s %8s %8s %8s %12s %8s %8s %8s\n", "Zone", "Size", "Used",
4353 "Free", "Requests", "Sleeps", "Bucket", "XFree");
4354 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4355 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4356 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4357 allocs = counter_u64_fetch(z->uz_allocs);
4358 frees = counter_u64_fetch(z->uz_frees);
4359 sleeps = z->uz_sleeps;
4362 uma_zone_sumstat(z, &cachefree, &allocs,
4363 &frees, &sleeps, &xdomain);
4364 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4365 (LIST_FIRST(&kz->uk_zones) != z)))
4366 cachefree += kz->uk_free;
4367 for (i = 0; i < vm_ndomains; i++)
4368 cachefree += z->uz_domain[i].uzd_nitems;
4370 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u %8ju\n",
4371 z->uz_name, (uintmax_t)kz->uk_size,
4372 (intmax_t)(allocs - frees), cachefree,
4373 (uintmax_t)allocs, sleeps, z->uz_count, xdomain);
4380 DB_SHOW_COMMAND(umacache, db_show_umacache)
4383 uint64_t allocs, frees;
4387 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4388 "Requests", "Bucket");
4389 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4390 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
4391 for (i = 0; i < vm_ndomains; i++)
4392 cachefree += z->uz_domain[i].uzd_nitems;
4393 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4394 z->uz_name, (uintmax_t)z->uz_size,
4395 (intmax_t)(allocs - frees), cachefree,
4396 (uintmax_t)allocs, z->uz_count);