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_drain_lock;
147 /* kmem soft limit. */
148 static unsigned long uma_kmem_limit = LONG_MAX;
149 static volatile unsigned long uma_kmem_total;
151 /* Is the VM done starting up? */
152 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
153 BOOT_RUNNING } booted = BOOT_COLD;
156 * This is the handle used to schedule events that need to happen
157 * outside of the allocation fast path.
159 static struct callout uma_callout;
160 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
163 * This structure is passed as the zone ctor arg so that I don't have to create
164 * a special allocation function just for zones.
166 struct uma_zctor_args {
181 struct uma_kctor_args {
190 struct uma_bucket_zone {
193 int ubz_entries; /* Number of items it can hold. */
194 int ubz_maxsize; /* Maximum allocation size per-item. */
198 * Compute the actual number of bucket entries to pack them in power
199 * of two sizes for more efficient space utilization.
201 #define BUCKET_SIZE(n) \
202 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
204 #define BUCKET_MAX BUCKET_SIZE(256)
206 struct uma_bucket_zone bucket_zones[] = {
207 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
208 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
209 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
210 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
211 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
212 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
213 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
214 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
215 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
220 * Flags and enumerations to be passed to internal functions.
222 enum zfreeskip { SKIP_NONE = 0, SKIP_DTOR, SKIP_FINI };
224 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
228 int uma_startup_count(int);
229 void uma_startup(void *, int);
230 void uma_startup1(void);
231 void uma_startup2(void);
233 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
234 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
235 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
236 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
237 static void page_free(void *, vm_size_t, uint8_t);
238 static void pcpu_page_free(void *, vm_size_t, uint8_t);
239 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int);
240 static void cache_drain(uma_zone_t);
241 static void bucket_drain(uma_zone_t, uma_bucket_t);
242 static void bucket_cache_drain(uma_zone_t zone);
243 static int keg_ctor(void *, int, void *, int);
244 static void keg_dtor(void *, int, void *);
245 static int zone_ctor(void *, int, void *, int);
246 static void zone_dtor(void *, int, void *);
247 static int zero_init(void *, int, int);
248 static void keg_small_init(uma_keg_t keg);
249 static void keg_large_init(uma_keg_t keg);
250 static void zone_foreach(void (*zfunc)(uma_zone_t));
251 static void zone_timeout(uma_zone_t zone);
252 static int hash_alloc(struct uma_hash *);
253 static int hash_expand(struct uma_hash *, struct uma_hash *);
254 static void hash_free(struct uma_hash *hash);
255 static void uma_timeout(void *);
256 static void uma_startup3(void);
257 static void *zone_alloc_item(uma_zone_t, void *, int, int);
258 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
259 static void bucket_enable(void);
260 static void bucket_init(void);
261 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
262 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
263 static void bucket_zone_drain(void);
264 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
265 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
266 static uma_slab_t zone_fetch_slab_multi(uma_zone_t, uma_keg_t, int, int);
267 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
268 static void slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item);
269 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
270 uma_fini fini, int align, uint32_t flags);
271 static int zone_import(uma_zone_t, void **, int, int, int);
272 static void zone_release(uma_zone_t, void **, int);
273 static void uma_zero_item(void *, uma_zone_t);
275 void uma_print_zone(uma_zone_t);
276 void uma_print_stats(void);
277 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
278 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
281 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
282 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
283 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
284 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
286 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
287 "Memory allocation debugging");
289 static u_int dbg_divisor = 1;
290 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
291 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
292 "Debug & thrash every this item in memory allocator");
294 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
295 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
296 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
297 &uma_dbg_cnt, "memory items debugged");
298 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
299 &uma_skip_cnt, "memory items skipped, not debugged");
302 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
304 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
305 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
307 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
308 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
310 static int zone_warnings = 1;
311 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
312 "Warn when UMA zones becomes full");
314 /* Adjust bytes under management by UMA. */
316 uma_total_dec(unsigned long size)
319 atomic_subtract_long(&uma_kmem_total, size);
323 uma_total_inc(unsigned long size)
326 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
327 uma_reclaim_wakeup();
331 * This routine checks to see whether or not it's safe to enable buckets.
336 bucketdisable = vm_page_count_min();
340 * Initialize bucket_zones, the array of zones of buckets of various sizes.
342 * For each zone, calculate the memory required for each bucket, consisting
343 * of the header and an array of pointers.
348 struct uma_bucket_zone *ubz;
351 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
352 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
353 size += sizeof(void *) * ubz->ubz_entries;
354 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
355 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
356 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
361 * Given a desired number of entries for a bucket, return the zone from which
362 * to allocate the bucket.
364 static struct uma_bucket_zone *
365 bucket_zone_lookup(int entries)
367 struct uma_bucket_zone *ubz;
369 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
370 if (ubz->ubz_entries >= entries)
377 bucket_select(int size)
379 struct uma_bucket_zone *ubz;
381 ubz = &bucket_zones[0];
382 if (size > ubz->ubz_maxsize)
383 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
385 for (; ubz->ubz_entries != 0; ubz++)
386 if (ubz->ubz_maxsize < size)
389 return (ubz->ubz_entries);
393 bucket_alloc(uma_zone_t zone, void *udata, int flags)
395 struct uma_bucket_zone *ubz;
399 * This is to stop us from allocating per cpu buckets while we're
400 * running out of vm.boot_pages. Otherwise, we would exhaust the
401 * boot pages. This also prevents us from allocating buckets in
402 * low memory situations.
407 * To limit bucket recursion we store the original zone flags
408 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
409 * NOVM flag to persist even through deep recursions. We also
410 * store ZFLAG_BUCKET once we have recursed attempting to allocate
411 * a bucket for a bucket zone so we do not allow infinite bucket
412 * recursion. This cookie will even persist to frees of unused
413 * buckets via the allocation path or bucket allocations in the
416 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
417 udata = (void *)(uintptr_t)zone->uz_flags;
419 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
421 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
423 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
425 ubz = bucket_zone_lookup(zone->uz_count);
426 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
428 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
431 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
434 bucket->ub_entries = ubz->ubz_entries;
441 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
443 struct uma_bucket_zone *ubz;
445 KASSERT(bucket->ub_cnt == 0,
446 ("bucket_free: Freeing a non free bucket."));
447 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
448 udata = (void *)(uintptr_t)zone->uz_flags;
449 ubz = bucket_zone_lookup(bucket->ub_entries);
450 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
454 bucket_zone_drain(void)
456 struct uma_bucket_zone *ubz;
458 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
459 zone_drain(ubz->ubz_zone);
463 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
467 ZONE_LOCK_ASSERT(zone);
469 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
470 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
471 LIST_REMOVE(bucket, ub_link);
472 zdom->uzd_nitems -= bucket->ub_cnt;
473 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
474 zdom->uzd_imin = zdom->uzd_nitems;
480 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
484 ZONE_LOCK_ASSERT(zone);
486 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
487 zdom->uzd_nitems += bucket->ub_cnt;
488 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
489 zdom->uzd_imax = zdom->uzd_nitems;
493 zone_log_warning(uma_zone_t zone)
495 static const struct timeval warninterval = { 300, 0 };
497 if (!zone_warnings || zone->uz_warning == NULL)
500 if (ratecheck(&zone->uz_ratecheck, &warninterval))
501 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
505 zone_maxaction(uma_zone_t zone)
508 if (zone->uz_maxaction.ta_func != NULL)
509 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
513 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
517 LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
518 kegfn(klink->kl_keg);
522 * Routine called by timeout which is used to fire off some time interval
523 * based calculations. (stats, hash size, etc.)
532 uma_timeout(void *unused)
535 zone_foreach(zone_timeout);
537 /* Reschedule this event */
538 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
542 * Update the working set size estimate for the zone's bucket cache.
543 * The constants chosen here are somewhat arbitrary. With an update period of
544 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
548 zone_domain_update_wss(uma_zone_domain_t zdom)
552 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
553 wss = zdom->uzd_imax - zdom->uzd_imin;
554 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
555 zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
559 * Routine to perform timeout driven calculations. This expands the
560 * hashes and does per cpu statistics aggregation.
565 keg_timeout(uma_keg_t keg)
570 * Expand the keg hash table.
572 * This is done if the number of slabs is larger than the hash size.
573 * What I'm trying to do here is completely reduce collisions. This
574 * may be a little aggressive. Should I allow for two collisions max?
576 if (keg->uk_flags & UMA_ZONE_HASH &&
577 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
578 struct uma_hash newhash;
579 struct uma_hash oldhash;
583 * This is so involved because allocating and freeing
584 * while the keg lock is held will lead to deadlock.
585 * I have to do everything in stages and check for
588 newhash = keg->uk_hash;
590 ret = hash_alloc(&newhash);
593 if (hash_expand(&keg->uk_hash, &newhash)) {
594 oldhash = keg->uk_hash;
595 keg->uk_hash = newhash;
608 zone_timeout(uma_zone_t zone)
612 zone_foreach_keg(zone, &keg_timeout);
615 for (i = 0; i < vm_ndomains; i++)
616 zone_domain_update_wss(&zone->uz_domain[i]);
621 * Allocate and zero fill the next sized hash table from the appropriate
625 * hash A new hash structure with the old hash size in uh_hashsize
628 * 1 on success and 0 on failure.
631 hash_alloc(struct uma_hash *hash)
636 oldsize = hash->uh_hashsize;
638 /* We're just going to go to a power of two greater */
640 hash->uh_hashsize = oldsize * 2;
641 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
642 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
643 M_UMAHASH, M_NOWAIT);
645 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
646 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
647 UMA_ANYDOMAIN, M_WAITOK);
648 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
650 if (hash->uh_slab_hash) {
651 bzero(hash->uh_slab_hash, alloc);
652 hash->uh_hashmask = hash->uh_hashsize - 1;
660 * Expands the hash table for HASH zones. This is done from zone_timeout
661 * to reduce collisions. This must not be done in the regular allocation
662 * path, otherwise, we can recurse on the vm while allocating pages.
665 * oldhash The hash you want to expand
666 * newhash The hash structure for the new table
674 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
680 if (!newhash->uh_slab_hash)
683 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
687 * I need to investigate hash algorithms for resizing without a
691 for (i = 0; i < oldhash->uh_hashsize; i++)
692 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
693 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
694 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
695 hval = UMA_HASH(newhash, slab->us_data);
696 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
704 * Free the hash bucket to the appropriate backing store.
707 * slab_hash The hash bucket we're freeing
708 * hashsize The number of entries in that hash bucket
714 hash_free(struct uma_hash *hash)
716 if (hash->uh_slab_hash == NULL)
718 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
719 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
721 free(hash->uh_slab_hash, M_UMAHASH);
725 * Frees all outstanding items in a bucket
728 * zone The zone to free to, must be unlocked.
729 * bucket The free/alloc bucket with items, cpu queue must be locked.
736 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
744 for (i = 0; i < bucket->ub_cnt; i++)
745 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
746 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
751 * Drains the per cpu caches for a zone.
753 * NOTE: This may only be called while the zone is being turn down, and not
754 * during normal operation. This is necessary in order that we do not have
755 * to migrate CPUs to drain the per-CPU caches.
758 * zone The zone to drain, must be unlocked.
764 cache_drain(uma_zone_t zone)
770 * XXX: It is safe to not lock the per-CPU caches, because we're
771 * tearing down the zone anyway. I.e., there will be no further use
772 * of the caches at this point.
774 * XXX: It would good to be able to assert that the zone is being
775 * torn down to prevent improper use of cache_drain().
777 * XXX: We lock the zone before passing into bucket_cache_drain() as
778 * it is used elsewhere. Should the tear-down path be made special
779 * there in some form?
782 cache = &zone->uz_cpu[cpu];
783 bucket_drain(zone, cache->uc_allocbucket);
784 bucket_drain(zone, cache->uc_freebucket);
785 if (cache->uc_allocbucket != NULL)
786 bucket_free(zone, cache->uc_allocbucket, NULL);
787 if (cache->uc_freebucket != NULL)
788 bucket_free(zone, cache->uc_freebucket, NULL);
789 cache->uc_allocbucket = cache->uc_freebucket = NULL;
792 bucket_cache_drain(zone);
797 cache_shrink(uma_zone_t zone)
800 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
804 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
809 cache_drain_safe_cpu(uma_zone_t zone)
815 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
821 if (zone->uz_flags & UMA_ZONE_NUMA)
822 domain = PCPU_GET(domain);
825 cache = &zone->uz_cpu[curcpu];
826 if (cache->uc_allocbucket) {
827 if (cache->uc_allocbucket->ub_cnt != 0)
828 zone_put_bucket(zone, &zone->uz_domain[domain],
829 cache->uc_allocbucket, false);
831 b1 = cache->uc_allocbucket;
832 cache->uc_allocbucket = NULL;
834 if (cache->uc_freebucket) {
835 if (cache->uc_freebucket->ub_cnt != 0)
836 zone_put_bucket(zone, &zone->uz_domain[domain],
837 cache->uc_freebucket, false);
839 b2 = cache->uc_freebucket;
840 cache->uc_freebucket = NULL;
845 bucket_free(zone, b1, NULL);
847 bucket_free(zone, b2, NULL);
851 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
852 * This is an expensive call because it needs to bind to all CPUs
853 * one by one and enter a critical section on each of them in order
854 * to safely access their cache buckets.
855 * Zone lock must not be held on call this function.
858 cache_drain_safe(uma_zone_t zone)
863 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
868 zone_foreach(cache_shrink);
871 thread_lock(curthread);
872 sched_bind(curthread, cpu);
873 thread_unlock(curthread);
876 cache_drain_safe_cpu(zone);
878 zone_foreach(cache_drain_safe_cpu);
880 thread_lock(curthread);
881 sched_unbind(curthread);
882 thread_unlock(curthread);
886 * Drain the cached buckets from a zone. Expects a locked zone on entry.
889 bucket_cache_drain(uma_zone_t zone)
891 uma_zone_domain_t zdom;
896 * Drain the bucket queues and free the buckets.
898 for (i = 0; i < vm_ndomains; i++) {
899 zdom = &zone->uz_domain[i];
900 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
903 bucket_drain(zone, bucket);
904 bucket_free(zone, bucket, NULL);
910 * Shrink further bucket sizes. Price of single zone lock collision
911 * is probably lower then price of global cache drain.
913 if (zone->uz_count > zone->uz_count_min)
918 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
924 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
925 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
928 flags = slab->us_flags;
930 if (keg->uk_fini != NULL) {
931 for (i--; i > -1; i--)
934 * trash_fini implies that dtor was trash_dtor. trash_fini
935 * would check that memory hasn't been modified since free,
936 * which executed trash_dtor.
937 * That's why we need to run uma_dbg_kskip() check here,
938 * albeit we don't make skip check for other init/fini
941 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
942 keg->uk_fini != trash_fini)
944 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
947 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
948 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
949 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
950 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
954 * Frees pages from a keg back to the system. This is done on demand from
955 * the pageout daemon.
960 keg_drain(uma_keg_t keg)
962 struct slabhead freeslabs = { 0 };
964 uma_slab_t slab, tmp;
968 * We don't want to take pages from statically allocated kegs at this
971 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
974 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
975 keg->uk_name, keg, keg->uk_free);
977 if (keg->uk_free == 0)
980 for (i = 0; i < vm_ndomains; i++) {
981 dom = &keg->uk_domain[i];
982 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
983 /* We have nowhere to free these to. */
984 if (slab->us_flags & UMA_SLAB_BOOT)
987 LIST_REMOVE(slab, us_link);
988 keg->uk_pages -= keg->uk_ppera;
989 keg->uk_free -= keg->uk_ipers;
991 if (keg->uk_flags & UMA_ZONE_HASH)
992 UMA_HASH_REMOVE(&keg->uk_hash, slab,
995 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1002 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1003 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1004 keg_free_slab(keg, slab, keg->uk_ipers);
1009 zone_drain_wait(uma_zone_t zone, int waitok)
1013 * Set draining to interlock with zone_dtor() so we can release our
1014 * locks as we go. Only dtor() should do a WAITOK call since it
1015 * is the only call that knows the structure will still be available
1019 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1020 if (waitok == M_NOWAIT)
1022 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1024 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1025 bucket_cache_drain(zone);
1028 * The DRAINING flag protects us from being freed while
1029 * we're running. Normally the uma_rwlock would protect us but we
1030 * must be able to release and acquire the right lock for each keg.
1032 zone_foreach_keg(zone, &keg_drain);
1034 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1041 zone_drain(uma_zone_t zone)
1044 zone_drain_wait(zone, M_NOWAIT);
1048 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1049 * If the allocation was successful, the keg lock will be held upon return,
1050 * otherwise the keg will be left unlocked.
1053 * wait Shall we wait?
1056 * The slab that was allocated or NULL if there is no memory and the
1057 * caller specified M_NOWAIT.
1060 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int wait)
1069 KASSERT(domain >= 0 && domain < vm_ndomains,
1070 ("keg_alloc_slab: domain %d out of range", domain));
1071 mtx_assert(&keg->uk_lock, MA_OWNED);
1073 allocf = keg->uk_allocf;
1078 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1079 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, wait);
1085 * This reproduces the old vm_zone behavior of zero filling pages the
1086 * first time they are added to a zone.
1088 * Malloced items are zeroed in uma_zalloc.
1091 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1096 if (keg->uk_flags & UMA_ZONE_NODUMP)
1099 /* zone is passed for legacy reasons. */
1100 size = keg->uk_ppera * PAGE_SIZE;
1101 mem = allocf(zone, size, domain, &flags, wait);
1103 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1104 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1108 uma_total_inc(size);
1110 /* Point the slab into the allocated memory */
1111 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1112 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1114 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1115 for (i = 0; i < keg->uk_ppera; i++)
1116 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1119 slab->us_data = mem;
1120 slab->us_freecount = keg->uk_ipers;
1121 slab->us_flags = flags;
1122 slab->us_domain = domain;
1123 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1125 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1128 if (keg->uk_init != NULL) {
1129 for (i = 0; i < keg->uk_ipers; i++)
1130 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1131 keg->uk_size, wait) != 0)
1133 if (i != keg->uk_ipers) {
1134 keg_free_slab(keg, slab, i);
1141 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1142 slab, keg->uk_name, keg);
1144 if (keg->uk_flags & UMA_ZONE_HASH)
1145 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1147 keg->uk_pages += keg->uk_ppera;
1148 keg->uk_free += keg->uk_ipers;
1155 * This function is intended to be used early on in place of page_alloc() so
1156 * that we may use the boot time page cache to satisfy allocations before
1160 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1167 keg = zone_first_keg(zone);
1170 * If we are in BOOT_BUCKETS or higher, than switch to real
1171 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1177 case BOOT_PAGEALLOC:
1178 if (keg->uk_ppera > 1)
1182 #ifdef UMA_MD_SMALL_ALLOC
1183 keg->uk_allocf = (keg->uk_ppera > 1) ?
1184 page_alloc : uma_small_alloc;
1186 keg->uk_allocf = page_alloc;
1188 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1192 * Check our small startup cache to see if it has pages remaining.
1194 pages = howmany(bytes, PAGE_SIZE);
1195 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1196 if (pages > boot_pages)
1197 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1199 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1203 boot_pages -= pages;
1204 bootmem += pages * PAGE_SIZE;
1205 *pflag = UMA_SLAB_BOOT;
1211 * Allocates a number of pages from the system
1214 * bytes The number of bytes requested
1215 * wait Shall we wait?
1218 * A pointer to the alloced memory or possibly
1219 * NULL if M_NOWAIT is set.
1222 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1225 void *p; /* Returned page */
1227 *pflag = UMA_SLAB_KERNEL;
1228 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1234 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1237 struct pglist alloctail;
1238 vm_offset_t addr, zkva;
1240 vm_page_t p, p_next;
1245 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1247 TAILQ_INIT(&alloctail);
1248 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1249 malloc2vm_flags(wait);
1250 *pflag = UMA_SLAB_KERNEL;
1251 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1252 if (CPU_ABSENT(cpu)) {
1253 p = vm_page_alloc(NULL, 0, flags);
1256 p = vm_page_alloc(NULL, 0, flags);
1258 pc = pcpu_find(cpu);
1259 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1260 if (__predict_false(p == NULL))
1261 p = vm_page_alloc(NULL, 0, flags);
1264 if (__predict_false(p == NULL))
1266 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1268 if ((addr = kva_alloc(bytes)) == 0)
1271 TAILQ_FOREACH(p, &alloctail, listq) {
1272 pmap_qenter(zkva, &p, 1);
1275 return ((void*)addr);
1277 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1278 vm_page_unwire(p, PQ_NONE);
1285 * Allocates a number of pages from within an object
1288 * bytes The number of bytes requested
1289 * wait Shall we wait?
1292 * A pointer to the alloced memory or possibly
1293 * NULL if M_NOWAIT is set.
1296 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1299 TAILQ_HEAD(, vm_page) alloctail;
1301 vm_offset_t retkva, zkva;
1302 vm_page_t p, p_next;
1305 TAILQ_INIT(&alloctail);
1306 keg = zone_first_keg(zone);
1308 npages = howmany(bytes, PAGE_SIZE);
1309 while (npages > 0) {
1310 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1311 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1312 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1316 * Since the page does not belong to an object, its
1319 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1324 * Page allocation failed, free intermediate pages and
1327 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1328 vm_page_unwire(p, PQ_NONE);
1333 *flags = UMA_SLAB_PRIV;
1334 zkva = keg->uk_kva +
1335 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1337 TAILQ_FOREACH(p, &alloctail, listq) {
1338 pmap_qenter(zkva, &p, 1);
1342 return ((void *)retkva);
1346 * Frees a number of pages to the system
1349 * mem A pointer to the memory to be freed
1350 * size The size of the memory being freed
1351 * flags The original p->us_flags field
1357 page_free(void *mem, vm_size_t size, uint8_t flags)
1360 if ((flags & UMA_SLAB_KERNEL) == 0)
1361 panic("UMA: page_free used with invalid flags %x", flags);
1363 kmem_free((vm_offset_t)mem, size);
1367 * Frees pcpu zone allocations
1370 * mem A pointer to the memory to be freed
1371 * size The size of the memory being freed
1372 * flags The original p->us_flags field
1378 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1380 vm_offset_t sva, curva;
1384 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1385 sva = (vm_offset_t)mem;
1386 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1387 paddr = pmap_kextract(curva);
1388 m = PHYS_TO_VM_PAGE(paddr);
1389 vm_page_unwire(m, PQ_NONE);
1392 pmap_qremove(sva, size >> PAGE_SHIFT);
1393 kva_free(sva, size);
1398 * Zero fill initializer
1400 * Arguments/Returns follow uma_init specifications
1403 zero_init(void *mem, int size, int flags)
1410 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1413 * keg The zone we should initialize
1419 keg_small_init(uma_keg_t keg)
1427 if (keg->uk_flags & UMA_ZONE_PCPU) {
1428 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1430 slabsize = UMA_PCPU_ALLOC_SIZE;
1431 keg->uk_ppera = ncpus;
1433 slabsize = UMA_SLAB_SIZE;
1438 * Calculate the size of each allocation (rsize) according to
1439 * alignment. If the requested size is smaller than we have
1440 * allocation bits for we round it up.
1442 rsize = keg->uk_size;
1443 if (rsize < slabsize / SLAB_SETSIZE)
1444 rsize = slabsize / SLAB_SETSIZE;
1445 if (rsize & keg->uk_align)
1446 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1447 keg->uk_rsize = rsize;
1449 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1450 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1451 ("%s: size %u too large", __func__, keg->uk_rsize));
1453 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1456 shsize = SIZEOF_UMA_SLAB;
1458 if (rsize <= slabsize - shsize)
1459 keg->uk_ipers = (slabsize - shsize) / rsize;
1461 /* Handle special case when we have 1 item per slab, so
1462 * alignment requirement can be relaxed. */
1463 KASSERT(keg->uk_size <= slabsize - shsize,
1464 ("%s: size %u greater than slab", __func__, keg->uk_size));
1467 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1468 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1470 memused = keg->uk_ipers * rsize + shsize;
1471 wastedspace = slabsize - memused;
1474 * We can't do OFFPAGE if we're internal or if we've been
1475 * asked to not go to the VM for buckets. If we do this we
1476 * may end up going to the VM for slabs which we do not
1477 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1478 * of UMA_ZONE_VM, which clearly forbids it.
1480 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1481 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1485 * See if using an OFFPAGE slab will limit our waste. Only do
1486 * this if it permits more items per-slab.
1488 * XXX We could try growing slabsize to limit max waste as well.
1489 * Historically this was not done because the VM could not
1490 * efficiently handle contiguous allocations.
1492 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1493 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1494 keg->uk_ipers = slabsize / keg->uk_rsize;
1495 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1496 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1497 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1498 "keg: %s(%p), calculated wastedspace = %d, "
1499 "maximum wasted space allowed = %d, "
1500 "calculated ipers = %d, "
1501 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1502 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1503 slabsize - keg->uk_ipers * keg->uk_rsize);
1504 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1507 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1508 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1509 keg->uk_flags |= UMA_ZONE_HASH;
1513 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1514 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1518 * keg The keg we should initialize
1524 keg_large_init(uma_keg_t keg)
1527 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1528 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1529 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1530 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1531 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1533 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1535 keg->uk_rsize = keg->uk_size;
1537 /* Check whether we have enough space to not do OFFPAGE. */
1538 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1539 PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1541 * We can't do OFFPAGE if we're internal, in which case
1542 * we need an extra page per allocation to contain the
1545 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1546 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1551 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1552 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1553 keg->uk_flags |= UMA_ZONE_HASH;
1557 keg_cachespread_init(uma_keg_t keg)
1564 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1565 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1567 alignsize = keg->uk_align + 1;
1568 rsize = keg->uk_size;
1570 * We want one item to start on every align boundary in a page. To
1571 * do this we will span pages. We will also extend the item by the
1572 * size of align if it is an even multiple of align. Otherwise, it
1573 * would fall on the same boundary every time.
1575 if (rsize & keg->uk_align)
1576 rsize = (rsize & ~keg->uk_align) + alignsize;
1577 if ((rsize & alignsize) == 0)
1579 trailer = rsize - keg->uk_size;
1580 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1581 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1582 keg->uk_rsize = rsize;
1583 keg->uk_ppera = pages;
1584 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1585 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1586 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1587 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1592 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1593 * the keg onto the global keg list.
1595 * Arguments/Returns follow uma_ctor specifications
1596 * udata Actually uma_kctor_args
1599 keg_ctor(void *mem, int size, void *udata, int flags)
1601 struct uma_kctor_args *arg = udata;
1602 uma_keg_t keg = mem;
1606 keg->uk_size = arg->size;
1607 keg->uk_init = arg->uminit;
1608 keg->uk_fini = arg->fini;
1609 keg->uk_align = arg->align;
1611 keg->uk_reserve = 0;
1613 keg->uk_flags = arg->flags;
1614 keg->uk_slabzone = NULL;
1617 * We use a global round-robin policy by default. Zones with
1618 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1619 * iterator is never run.
1621 keg->uk_dr.dr_policy = DOMAINSET_RR();
1622 keg->uk_dr.dr_iter = 0;
1625 * The master zone is passed to us at keg-creation time.
1628 keg->uk_name = zone->uz_name;
1630 if (arg->flags & UMA_ZONE_VM)
1631 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1633 if (arg->flags & UMA_ZONE_ZINIT)
1634 keg->uk_init = zero_init;
1636 if (arg->flags & UMA_ZONE_MALLOC)
1637 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1639 if (arg->flags & UMA_ZONE_PCPU)
1641 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1643 keg->uk_flags &= ~UMA_ZONE_PCPU;
1646 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1647 keg_cachespread_init(keg);
1649 if (keg->uk_size > UMA_SLAB_SPACE)
1650 keg_large_init(keg);
1652 keg_small_init(keg);
1655 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1656 keg->uk_slabzone = slabzone;
1659 * If we haven't booted yet we need allocations to go through the
1660 * startup cache until the vm is ready.
1662 if (booted < BOOT_PAGEALLOC)
1663 keg->uk_allocf = startup_alloc;
1664 #ifdef UMA_MD_SMALL_ALLOC
1665 else if (keg->uk_ppera == 1)
1666 keg->uk_allocf = uma_small_alloc;
1668 else if (keg->uk_flags & UMA_ZONE_PCPU)
1669 keg->uk_allocf = pcpu_page_alloc;
1671 keg->uk_allocf = page_alloc;
1672 #ifdef UMA_MD_SMALL_ALLOC
1673 if (keg->uk_ppera == 1)
1674 keg->uk_freef = uma_small_free;
1677 if (keg->uk_flags & UMA_ZONE_PCPU)
1678 keg->uk_freef = pcpu_page_free;
1680 keg->uk_freef = page_free;
1683 * Initialize keg's lock
1685 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1688 * If we're putting the slab header in the actual page we need to
1689 * figure out where in each page it goes. See SIZEOF_UMA_SLAB
1692 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1693 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1695 * The only way the following is possible is if with our
1696 * UMA_ALIGN_PTR adjustments we are now bigger than
1697 * UMA_SLAB_SIZE. I haven't checked whether this is
1698 * mathematically possible for all cases, so we make
1701 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1702 PAGE_SIZE * keg->uk_ppera,
1703 ("zone %s ipers %d rsize %d size %d slab won't fit",
1704 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1707 if (keg->uk_flags & UMA_ZONE_HASH)
1708 hash_alloc(&keg->uk_hash);
1710 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1711 keg, zone->uz_name, zone,
1712 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1715 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1717 rw_wlock(&uma_rwlock);
1718 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1719 rw_wunlock(&uma_rwlock);
1724 * Zone header ctor. This initializes all fields, locks, etc.
1726 * Arguments/Returns follow uma_ctor specifications
1727 * udata Actually uma_zctor_args
1730 zone_ctor(void *mem, int size, void *udata, int flags)
1732 struct uma_zctor_args *arg = udata;
1733 uma_zone_t zone = mem;
1738 zone->uz_name = arg->name;
1739 zone->uz_ctor = arg->ctor;
1740 zone->uz_dtor = arg->dtor;
1741 zone->uz_slab = zone_fetch_slab;
1742 zone->uz_init = NULL;
1743 zone->uz_fini = NULL;
1744 zone->uz_allocs = 0;
1747 zone->uz_sleeps = 0;
1749 zone->uz_count_min = 0;
1751 zone->uz_warning = NULL;
1752 /* The domain structures follow the cpu structures. */
1753 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1754 timevalclear(&zone->uz_ratecheck);
1757 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1760 * This is a pure cache zone, no kegs.
1763 if (arg->flags & UMA_ZONE_VM)
1764 arg->flags |= UMA_ZFLAG_CACHEONLY;
1765 zone->uz_flags = arg->flags;
1766 zone->uz_size = arg->size;
1767 zone->uz_import = arg->import;
1768 zone->uz_release = arg->release;
1769 zone->uz_arg = arg->arg;
1770 zone->uz_lockptr = &zone->uz_lock;
1771 rw_wlock(&uma_rwlock);
1772 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1773 rw_wunlock(&uma_rwlock);
1778 * Use the regular zone/keg/slab allocator.
1780 zone->uz_import = (uma_import)zone_import;
1781 zone->uz_release = (uma_release)zone_release;
1782 zone->uz_arg = zone;
1784 if (arg->flags & UMA_ZONE_SECONDARY) {
1785 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1786 zone->uz_init = arg->uminit;
1787 zone->uz_fini = arg->fini;
1788 zone->uz_lockptr = &keg->uk_lock;
1789 zone->uz_flags |= UMA_ZONE_SECONDARY;
1790 rw_wlock(&uma_rwlock);
1792 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1793 if (LIST_NEXT(z, uz_link) == NULL) {
1794 LIST_INSERT_AFTER(z, zone, uz_link);
1799 rw_wunlock(&uma_rwlock);
1800 } else if (keg == NULL) {
1801 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1802 arg->align, arg->flags)) == NULL)
1805 struct uma_kctor_args karg;
1808 /* We should only be here from uma_startup() */
1809 karg.size = arg->size;
1810 karg.uminit = arg->uminit;
1811 karg.fini = arg->fini;
1812 karg.align = arg->align;
1813 karg.flags = arg->flags;
1815 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1822 * Link in the first keg.
1824 zone->uz_klink.kl_keg = keg;
1825 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1826 zone->uz_lockptr = &keg->uk_lock;
1827 zone->uz_size = keg->uk_size;
1828 zone->uz_flags |= (keg->uk_flags &
1829 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1832 * Some internal zones don't have room allocated for the per cpu
1833 * caches. If we're internal, bail out here.
1835 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1836 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1837 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1842 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1843 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1844 ("Invalid zone flag combination"));
1845 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1846 zone->uz_count = BUCKET_MAX;
1847 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1850 zone->uz_count = bucket_select(zone->uz_size);
1851 zone->uz_count_min = zone->uz_count;
1857 * Keg header dtor. This frees all data, destroys locks, frees the hash
1858 * table and removes the keg from the global list.
1860 * Arguments/Returns follow uma_dtor specifications
1864 keg_dtor(void *arg, int size, void *udata)
1868 keg = (uma_keg_t)arg;
1870 if (keg->uk_free != 0) {
1871 printf("Freed UMA keg (%s) was not empty (%d items). "
1872 " Lost %d pages of memory.\n",
1873 keg->uk_name ? keg->uk_name : "",
1874 keg->uk_free, keg->uk_pages);
1878 hash_free(&keg->uk_hash);
1886 * Arguments/Returns follow uma_dtor specifications
1890 zone_dtor(void *arg, int size, void *udata)
1896 zone = (uma_zone_t)arg;
1897 keg = zone_first_keg(zone);
1899 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1902 rw_wlock(&uma_rwlock);
1903 LIST_REMOVE(zone, uz_link);
1904 rw_wunlock(&uma_rwlock);
1906 * XXX there are some races here where
1907 * the zone can be drained but zone lock
1908 * released and then refilled before we
1909 * remove it... we dont care for now
1911 zone_drain_wait(zone, M_WAITOK);
1913 * Unlink all of our kegs.
1915 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1916 klink->kl_keg = NULL;
1917 LIST_REMOVE(klink, kl_link);
1918 if (klink == &zone->uz_klink)
1920 free(klink, M_TEMP);
1923 * We only destroy kegs from non secondary zones.
1925 if (keg != NULL && (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1926 rw_wlock(&uma_rwlock);
1927 LIST_REMOVE(keg, uk_link);
1928 rw_wunlock(&uma_rwlock);
1929 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1931 ZONE_LOCK_FINI(zone);
1935 * Traverses every zone in the system and calls a callback
1938 * zfunc A pointer to a function which accepts a zone
1945 zone_foreach(void (*zfunc)(uma_zone_t))
1950 rw_rlock(&uma_rwlock);
1951 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1952 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1955 rw_runlock(&uma_rwlock);
1959 * Count how many pages do we need to bootstrap. VM supplies
1960 * its need in early zones in the argument, we add up our zones,
1961 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1962 * zone of zones and zone of kegs are accounted separately.
1964 #define UMA_BOOT_ZONES 11
1965 /* Zone of zones and zone of kegs have arbitrary alignment. */
1966 #define UMA_BOOT_ALIGN 32
1967 static int zsize, ksize;
1969 uma_startup_count(int vm_zones)
1973 ksize = sizeof(struct uma_keg) +
1974 (sizeof(struct uma_domain) * vm_ndomains);
1975 zsize = sizeof(struct uma_zone) +
1976 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1977 (sizeof(struct uma_zone_domain) * vm_ndomains);
1980 * Memory for the zone of kegs and its keg,
1981 * and for zone of zones.
1983 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1984 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1986 #ifdef UMA_MD_SMALL_ALLOC
1987 zones = UMA_BOOT_ZONES;
1989 zones = UMA_BOOT_ZONES + vm_zones;
1993 /* Memory for the rest of startup zones, UMA and VM, ... */
1994 if (zsize > UMA_SLAB_SPACE) {
1995 /* See keg_large_init(). */
1998 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
1999 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2002 pages += (zones + vm_zones) * ppera;
2003 } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2004 /* See keg_small_init() special case for uk_ppera = 1. */
2007 pages += howmany(zones,
2008 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2010 /* ... and their kegs. Note that zone of zones allocates a keg! */
2011 pages += howmany(zones + 1,
2012 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2015 * Most of startup zones are not going to be offpages, that's
2016 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2017 * calculations. Some large bucket zones will be offpage, and
2018 * thus will allocate hashes. We take conservative approach
2019 * and assume that all zones may allocate hash. This may give
2020 * us some positive inaccuracy, usually an extra single page.
2022 pages += howmany(zones, UMA_SLAB_SPACE /
2023 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2029 uma_startup(void *mem, int npages)
2031 struct uma_zctor_args args;
2032 uma_keg_t masterkeg;
2036 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2039 rw_init(&uma_rwlock, "UMA lock");
2041 /* Use bootpages memory for the zone of zones and zone of kegs. */
2043 zones = (uma_zone_t)m;
2044 m += roundup(zsize, CACHE_LINE_SIZE);
2045 kegs = (uma_zone_t)m;
2046 m += roundup(zsize, CACHE_LINE_SIZE);
2047 masterkeg = (uma_keg_t)m;
2048 m += roundup(ksize, CACHE_LINE_SIZE);
2049 m = roundup(m, PAGE_SIZE);
2050 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2053 /* "manually" create the initial zone */
2054 memset(&args, 0, sizeof(args));
2055 args.name = "UMA Kegs";
2057 args.ctor = keg_ctor;
2058 args.dtor = keg_dtor;
2059 args.uminit = zero_init;
2061 args.keg = masterkeg;
2062 args.align = UMA_BOOT_ALIGN - 1;
2063 args.flags = UMA_ZFLAG_INTERNAL;
2064 zone_ctor(kegs, zsize, &args, M_WAITOK);
2067 boot_pages = npages;
2069 args.name = "UMA Zones";
2071 args.ctor = zone_ctor;
2072 args.dtor = zone_dtor;
2073 args.uminit = zero_init;
2076 args.align = UMA_BOOT_ALIGN - 1;
2077 args.flags = UMA_ZFLAG_INTERNAL;
2078 zone_ctor(zones, zsize, &args, M_WAITOK);
2080 /* Now make a zone for slab headers */
2081 slabzone = uma_zcreate("UMA Slabs",
2082 sizeof(struct uma_slab),
2083 NULL, NULL, NULL, NULL,
2084 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2086 hashzone = uma_zcreate("UMA Hash",
2087 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2088 NULL, NULL, NULL, NULL,
2089 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2093 booted = BOOT_STRAPPED;
2101 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2103 booted = BOOT_PAGEALLOC;
2111 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2113 booted = BOOT_BUCKETS;
2114 sx_init(&uma_drain_lock, "umadrain");
2119 * Initialize our callout handle
2127 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2128 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2129 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2131 callout_init(&uma_callout, 1);
2132 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2133 booted = BOOT_RUNNING;
2137 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2138 int align, uint32_t flags)
2140 struct uma_kctor_args args;
2143 args.uminit = uminit;
2145 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2148 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2151 /* Public functions */
2154 uma_set_align(int align)
2157 if (align != UMA_ALIGN_CACHE)
2158 uma_align_cache = align;
2163 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2164 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2167 struct uma_zctor_args args;
2171 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2174 /* This stuff is essential for the zone ctor */
2175 memset(&args, 0, sizeof(args));
2180 args.uminit = uminit;
2184 * If a zone is being created with an empty constructor and
2185 * destructor, pass UMA constructor/destructor which checks for
2186 * memory use after free.
2188 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2189 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2190 args.ctor = trash_ctor;
2191 args.dtor = trash_dtor;
2192 args.uminit = trash_init;
2193 args.fini = trash_fini;
2200 if (booted < BOOT_BUCKETS) {
2203 sx_slock(&uma_drain_lock);
2206 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2208 sx_sunlock(&uma_drain_lock);
2214 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2215 uma_init zinit, uma_fini zfini, uma_zone_t master)
2217 struct uma_zctor_args args;
2222 keg = zone_first_keg(master);
2223 memset(&args, 0, sizeof(args));
2225 args.size = keg->uk_size;
2228 args.uminit = zinit;
2230 args.align = keg->uk_align;
2231 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2234 if (booted < BOOT_BUCKETS) {
2237 sx_slock(&uma_drain_lock);
2240 /* XXX Attaches only one keg of potentially many. */
2241 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2243 sx_sunlock(&uma_drain_lock);
2249 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2250 uma_init zinit, uma_fini zfini, uma_import zimport,
2251 uma_release zrelease, void *arg, int flags)
2253 struct uma_zctor_args args;
2255 memset(&args, 0, sizeof(args));
2260 args.uminit = zinit;
2262 args.import = zimport;
2263 args.release = zrelease;
2268 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2272 zone_lock_pair(uma_zone_t a, uma_zone_t b)
2276 mtx_lock_flags(b->uz_lockptr, MTX_DUPOK);
2279 mtx_lock_flags(a->uz_lockptr, MTX_DUPOK);
2284 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
2292 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
2299 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
2301 zone_lock_pair(zone, master);
2303 * zone must use vtoslab() to resolve objects and must already be
2306 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
2307 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
2312 * The new master must also use vtoslab().
2314 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
2320 * The underlying object must be the same size. rsize
2323 if (master->uz_size != zone->uz_size) {
2328 * Put it at the end of the list.
2330 klink->kl_keg = zone_first_keg(master);
2331 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
2332 if (LIST_NEXT(kl, kl_link) == NULL) {
2333 LIST_INSERT_AFTER(kl, klink, kl_link);
2338 zone->uz_flags |= UMA_ZFLAG_MULTI;
2339 zone->uz_slab = zone_fetch_slab_multi;
2342 zone_unlock_pair(zone, master);
2344 free(klink, M_TEMP);
2352 uma_zdestroy(uma_zone_t zone)
2355 sx_slock(&uma_drain_lock);
2356 zone_free_item(zones, zone, NULL, SKIP_NONE);
2357 sx_sunlock(&uma_drain_lock);
2361 uma_zwait(uma_zone_t zone)
2365 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2366 uma_zfree(zone, item);
2370 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2376 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2378 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2379 if (item != NULL && (flags & M_ZERO)) {
2381 for (i = 0; i <= mp_maxid; i++)
2382 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2384 bzero(item, zone->uz_size);
2391 * A stub while both regular and pcpu cases are identical.
2394 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2398 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2400 uma_zfree_arg(zone, item, udata);
2405 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2407 uma_zone_domain_t zdom;
2408 uma_bucket_t bucket;
2411 int cpu, domain, lockfail;
2416 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2417 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2419 /* This is the fast path allocation */
2420 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2421 curthread, zone->uz_name, zone, flags);
2423 if (flags & M_WAITOK) {
2424 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2425 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2427 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2428 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2429 ("uma_zalloc_arg: called with spinlock or critical section held"));
2430 if (zone->uz_flags & UMA_ZONE_PCPU)
2431 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2432 "with M_ZERO passed"));
2434 #ifdef DEBUG_MEMGUARD
2435 if (memguard_cmp_zone(zone)) {
2436 item = memguard_alloc(zone->uz_size, flags);
2438 if (zone->uz_init != NULL &&
2439 zone->uz_init(item, zone->uz_size, flags) != 0)
2441 if (zone->uz_ctor != NULL &&
2442 zone->uz_ctor(item, zone->uz_size, udata,
2444 zone->uz_fini(item, zone->uz_size);
2449 /* This is unfortunate but should not be fatal. */
2453 * If possible, allocate from the per-CPU cache. There are two
2454 * requirements for safe access to the per-CPU cache: (1) the thread
2455 * accessing the cache must not be preempted or yield during access,
2456 * and (2) the thread must not migrate CPUs without switching which
2457 * cache it accesses. We rely on a critical section to prevent
2458 * preemption and migration. We release the critical section in
2459 * order to acquire the zone mutex if we are unable to allocate from
2460 * the current cache; when we re-acquire the critical section, we
2461 * must detect and handle migration if it has occurred.
2466 cache = &zone->uz_cpu[cpu];
2469 bucket = cache->uc_allocbucket;
2470 if (bucket != NULL && bucket->ub_cnt > 0) {
2472 item = bucket->ub_bucket[bucket->ub_cnt];
2474 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2476 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2480 skipdbg = uma_dbg_zskip(zone, item);
2482 if (zone->uz_ctor != NULL &&
2484 (!skipdbg || zone->uz_ctor != trash_ctor ||
2485 zone->uz_dtor != trash_dtor) &&
2487 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2488 atomic_add_long(&zone->uz_fails, 1);
2489 zone_free_item(zone, item, udata, SKIP_DTOR);
2494 uma_dbg_alloc(zone, NULL, item);
2497 uma_zero_item(item, zone);
2502 * We have run out of items in our alloc bucket.
2503 * See if we can switch with our free bucket.
2505 bucket = cache->uc_freebucket;
2506 if (bucket != NULL && bucket->ub_cnt > 0) {
2508 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2509 zone->uz_name, zone);
2510 cache->uc_freebucket = cache->uc_allocbucket;
2511 cache->uc_allocbucket = bucket;
2516 * Discard any empty allocation bucket while we hold no locks.
2518 bucket = cache->uc_allocbucket;
2519 cache->uc_allocbucket = NULL;
2522 bucket_free(zone, bucket, udata);
2524 if (zone->uz_flags & UMA_ZONE_NUMA) {
2525 domain = PCPU_GET(domain);
2526 if (VM_DOMAIN_EMPTY(domain))
2527 domain = UMA_ANYDOMAIN;
2529 domain = UMA_ANYDOMAIN;
2531 /* Short-circuit for zones without buckets and low memory. */
2532 if (zone->uz_count == 0 || bucketdisable)
2536 * Attempt to retrieve the item from the per-CPU cache has failed, so
2537 * we must go back to the zone. This requires the zone lock, so we
2538 * must drop the critical section, then re-acquire it when we go back
2539 * to the cache. Since the critical section is released, we may be
2540 * preempted or migrate. As such, make sure not to maintain any
2541 * thread-local state specific to the cache from prior to releasing
2542 * the critical section.
2545 if (ZONE_TRYLOCK(zone) == 0) {
2546 /* Record contention to size the buckets. */
2552 cache = &zone->uz_cpu[cpu];
2554 /* See if we lost the race to fill the cache. */
2555 if (cache->uc_allocbucket != NULL) {
2561 * Check the zone's cache of buckets.
2563 if (domain == UMA_ANYDOMAIN)
2564 zdom = &zone->uz_domain[0];
2566 zdom = &zone->uz_domain[domain];
2567 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2568 KASSERT(bucket->ub_cnt != 0,
2569 ("uma_zalloc_arg: Returning an empty bucket."));
2570 cache->uc_allocbucket = bucket;
2574 /* We are no longer associated with this CPU. */
2578 * We bump the uz count when the cache size is insufficient to
2579 * handle the working set.
2581 if (lockfail && zone->uz_count < BUCKET_MAX)
2586 * Now lets just fill a bucket and put it on the free list. If that
2587 * works we'll restart the allocation from the beginning and it
2588 * will use the just filled bucket.
2590 bucket = zone_alloc_bucket(zone, udata, domain, flags);
2591 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2592 zone->uz_name, zone, bucket);
2593 if (bucket != NULL) {
2597 cache = &zone->uz_cpu[cpu];
2600 * See if we lost the race or were migrated. Cache the
2601 * initialized bucket to make this less likely or claim
2602 * the memory directly.
2604 if (cache->uc_allocbucket == NULL &&
2605 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2606 domain == PCPU_GET(domain))) {
2607 cache->uc_allocbucket = bucket;
2608 zdom->uzd_imax += bucket->ub_cnt;
2609 } else if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
2612 bucket_drain(zone, bucket);
2613 bucket_free(zone, bucket, udata);
2614 goto zalloc_restart;
2616 zone_put_bucket(zone, zdom, bucket, false);
2622 * We may not be able to get a bucket so return an actual item.
2625 item = zone_alloc_item(zone, udata, domain, flags);
2631 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2634 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2635 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2637 /* This is the fast path allocation */
2639 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2640 curthread, zone->uz_name, zone, domain, flags);
2642 if (flags & M_WAITOK) {
2643 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2644 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2646 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2647 ("uma_zalloc_domain: called with spinlock or critical section held"));
2649 return (zone_alloc_item(zone, udata, domain, flags));
2653 * Find a slab with some space. Prefer slabs that are partially used over those
2654 * that are totally full. This helps to reduce fragmentation.
2656 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2660 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2666 KASSERT(domain >= 0 && domain < vm_ndomains,
2667 ("keg_first_slab: domain %d out of range", domain));
2672 dom = &keg->uk_domain[domain];
2673 if (!LIST_EMPTY(&dom->ud_part_slab))
2674 return (LIST_FIRST(&dom->ud_part_slab));
2675 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2676 slab = LIST_FIRST(&dom->ud_free_slab);
2677 LIST_REMOVE(slab, us_link);
2678 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2682 domain = (domain + 1) % vm_ndomains;
2683 } while (domain != start);
2689 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2693 mtx_assert(&keg->uk_lock, MA_OWNED);
2695 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2696 if (keg->uk_free <= reserve)
2698 return (keg_first_slab(keg, domain, rr));
2702 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2704 struct vm_domainset_iter di;
2711 mtx_assert(&keg->uk_lock, MA_OWNED);
2714 * Use the keg's policy if upper layers haven't already specified a
2715 * domain (as happens with first-touch zones).
2717 * To avoid races we run the iterator with the keg lock held, but that
2718 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2719 * clear M_WAITOK and handle low memory conditions locally.
2721 rr = rdomain == UMA_ANYDOMAIN;
2723 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2724 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2732 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2734 MPASS(slab->us_keg == keg);
2739 * M_NOVM means don't ask at all!
2744 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2745 keg->uk_flags |= UMA_ZFLAG_FULL;
2747 * If this is not a multi-zone, set the FULL bit.
2748 * Otherwise slab_multi() takes care of it.
2750 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2751 zone->uz_flags |= UMA_ZFLAG_FULL;
2752 zone_log_warning(zone);
2753 zone_maxaction(zone);
2755 if (flags & M_NOWAIT)
2758 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2761 slab = keg_alloc_slab(keg, zone, domain, aflags);
2763 * If we got a slab here it's safe to mark it partially used
2764 * and return. We assume that the caller is going to remove
2765 * at least one item.
2768 MPASS(slab->us_keg == keg);
2769 dom = &keg->uk_domain[slab->us_domain];
2770 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2774 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2775 if ((flags & M_WAITOK) != 0) {
2777 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2786 * We might not have been able to get a slab but another cpu
2787 * could have while we were unlocked. Check again before we
2790 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2791 MPASS(slab->us_keg == keg);
2798 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2803 keg = zone_first_keg(zone);
2808 slab = keg_fetch_slab(keg, zone, domain, flags);
2811 if (flags & (M_NOWAIT | M_NOVM))
2819 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2820 * with the keg locked. On NULL no lock is held.
2822 * The last pointer is used to seed the search. It is not required.
2825 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int domain, int rflags)
2835 * Don't wait on the first pass. This will skip limit tests
2836 * as well. We don't want to block if we can find a provider
2839 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2841 * Use the last slab allocated as a hint for where to start
2845 slab = keg_fetch_slab(last, zone, domain, flags);
2851 * Loop until we have a slab incase of transient failures
2852 * while M_WAITOK is specified. I'm not sure this is 100%
2853 * required but we've done it for so long now.
2859 * Search the available kegs for slabs. Be careful to hold the
2860 * correct lock while calling into the keg layer.
2862 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2863 keg = klink->kl_keg;
2865 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2866 slab = keg_fetch_slab(keg, zone, domain, flags);
2870 if (keg->uk_flags & UMA_ZFLAG_FULL)
2876 if (rflags & (M_NOWAIT | M_NOVM))
2880 * All kegs are full. XXX We can't atomically check all kegs
2881 * and sleep so just sleep for a short period and retry.
2883 if (full && !empty) {
2885 zone->uz_flags |= UMA_ZFLAG_FULL;
2887 zone_log_warning(zone);
2888 zone_maxaction(zone);
2889 msleep(zone, zone->uz_lockptr, PVM,
2890 "zonelimit", hz/100);
2891 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2900 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2906 MPASS(keg == slab->us_keg);
2907 mtx_assert(&keg->uk_lock, MA_OWNED);
2909 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2910 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2911 item = slab->us_data + (keg->uk_rsize * freei);
2912 slab->us_freecount--;
2915 /* Move this slab to the full list */
2916 if (slab->us_freecount == 0) {
2917 LIST_REMOVE(slab, us_link);
2918 dom = &keg->uk_domain[slab->us_domain];
2919 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2926 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2937 /* Try to keep the buckets totally full */
2938 for (i = 0; i < max; ) {
2939 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2943 stripe = howmany(max, vm_ndomains);
2945 while (slab->us_freecount && i < max) {
2946 bucket[i++] = slab_alloc_item(keg, slab);
2947 if (keg->uk_free <= keg->uk_reserve)
2951 * If the zone is striped we pick a new slab for every
2952 * N allocations. Eliminating this conditional will
2953 * instead pick a new domain for each bucket rather
2954 * than stripe within each bucket. The current option
2955 * produces more fragmentation and requires more cpu
2956 * time but yields better distribution.
2958 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2959 vm_ndomains > 1 && --stripe == 0)
2963 /* Don't block if we allocated any successfully. */
2974 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
2976 uma_bucket_t bucket;
2979 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2981 /* Don't wait for buckets, preserve caller's NOVM setting. */
2982 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2986 max = MIN(bucket->ub_entries, zone->uz_count);
2987 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2988 max, domain, flags);
2991 * Initialize the memory if necessary.
2993 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2996 for (i = 0; i < bucket->ub_cnt; i++)
2997 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
3001 * If we couldn't initialize the whole bucket, put the
3002 * rest back onto the freelist.
3004 if (i != bucket->ub_cnt) {
3005 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
3006 bucket->ub_cnt - i);
3008 bzero(&bucket->ub_bucket[i],
3009 sizeof(void *) * (bucket->ub_cnt - i));
3015 if (bucket->ub_cnt == 0) {
3016 bucket_free(zone, bucket, udata);
3017 atomic_add_long(&zone->uz_fails, 1);
3025 * Allocates a single item from a zone.
3028 * zone The zone to alloc for.
3029 * udata The data to be passed to the constructor.
3030 * domain The domain to allocate from or UMA_ANYDOMAIN.
3031 * flags M_WAITOK, M_NOWAIT, M_ZERO.
3034 * NULL if there is no memory and M_NOWAIT is set
3035 * An item if successful
3039 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
3048 if (domain != UMA_ANYDOMAIN) {
3049 /* avoid allocs targeting empty domains */
3050 if (VM_DOMAIN_EMPTY(domain))
3051 domain = UMA_ANYDOMAIN;
3053 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
3055 atomic_add_long(&zone->uz_allocs, 1);
3058 skipdbg = uma_dbg_zskip(zone, item);
3061 * We have to call both the zone's init (not the keg's init)
3062 * and the zone's ctor. This is because the item is going from
3063 * a keg slab directly to the user, and the user is expecting it
3064 * to be both zone-init'd as well as zone-ctor'd.
3066 if (zone->uz_init != NULL) {
3067 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
3068 zone_free_item(zone, item, udata, SKIP_FINI);
3072 if (zone->uz_ctor != NULL &&
3074 (!skipdbg || zone->uz_ctor != trash_ctor ||
3075 zone->uz_dtor != trash_dtor) &&
3077 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
3078 zone_free_item(zone, item, udata, SKIP_DTOR);
3083 uma_dbg_alloc(zone, NULL, item);
3086 uma_zero_item(item, zone);
3088 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3089 zone->uz_name, zone);
3094 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3095 zone->uz_name, zone);
3096 atomic_add_long(&zone->uz_fails, 1);
3102 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3105 uma_bucket_t bucket;
3106 uma_zone_domain_t zdom;
3107 int cpu, domain, lockfail;
3112 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3113 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3115 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3118 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3119 ("uma_zfree_arg: called with spinlock or critical section held"));
3121 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3124 #ifdef DEBUG_MEMGUARD
3125 if (is_memguard_addr(item)) {
3126 if (zone->uz_dtor != NULL)
3127 zone->uz_dtor(item, zone->uz_size, udata);
3128 if (zone->uz_fini != NULL)
3129 zone->uz_fini(item, zone->uz_size);
3130 memguard_free(item);
3135 skipdbg = uma_dbg_zskip(zone, item);
3136 if (skipdbg == false) {
3137 if (zone->uz_flags & UMA_ZONE_MALLOC)
3138 uma_dbg_free(zone, udata, item);
3140 uma_dbg_free(zone, NULL, item);
3142 if (zone->uz_dtor != NULL && (!skipdbg ||
3143 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3145 if (zone->uz_dtor != NULL)
3147 zone->uz_dtor(item, zone->uz_size, udata);
3150 * The race here is acceptable. If we miss it we'll just have to wait
3151 * a little longer for the limits to be reset.
3153 if (zone->uz_flags & UMA_ZFLAG_FULL)
3157 * If possible, free to the per-CPU cache. There are two
3158 * requirements for safe access to the per-CPU cache: (1) the thread
3159 * accessing the cache must not be preempted or yield during access,
3160 * and (2) the thread must not migrate CPUs without switching which
3161 * cache it accesses. We rely on a critical section to prevent
3162 * preemption and migration. We release the critical section in
3163 * order to acquire the zone mutex if we are unable to free to the
3164 * current cache; when we re-acquire the critical section, we must
3165 * detect and handle migration if it has occurred.
3170 cache = &zone->uz_cpu[cpu];
3174 * Try to free into the allocbucket first to give LIFO ordering
3175 * for cache-hot datastructures. Spill over into the freebucket
3176 * if necessary. Alloc will swap them if one runs dry.
3178 bucket = cache->uc_allocbucket;
3179 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3180 bucket = cache->uc_freebucket;
3181 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3182 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3183 ("uma_zfree: Freeing to non free bucket index."));
3184 bucket->ub_bucket[bucket->ub_cnt] = item;
3192 * We must go back the zone, which requires acquiring the zone lock,
3193 * which in turn means we must release and re-acquire the critical
3194 * section. Since the critical section is released, we may be
3195 * preempted or migrate. As such, make sure not to maintain any
3196 * thread-local state specific to the cache from prior to releasing
3197 * the critical section.
3200 if (zone->uz_count == 0 || bucketdisable)
3204 if (ZONE_TRYLOCK(zone) == 0) {
3205 /* Record contention to size the buckets. */
3211 cache = &zone->uz_cpu[cpu];
3213 bucket = cache->uc_freebucket;
3214 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3218 cache->uc_freebucket = NULL;
3219 /* We are no longer associated with this CPU. */
3222 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3223 domain = PCPU_GET(domain);
3224 if (VM_DOMAIN_EMPTY(domain))
3225 domain = UMA_ANYDOMAIN;
3228 zdom = &zone->uz_domain[0];
3230 /* Can we throw this on the zone full list? */
3231 if (bucket != NULL) {
3233 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3234 zone->uz_name, zone, bucket);
3235 /* ub_cnt is pointing to the last free item */
3236 KASSERT(bucket->ub_cnt != 0,
3237 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
3238 if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
3240 bucket_drain(zone, bucket);
3241 bucket_free(zone, bucket, udata);
3244 zone_put_bucket(zone, zdom, bucket, true);
3248 * We bump the uz count when the cache size is insufficient to
3249 * handle the working set.
3251 if (lockfail && zone->uz_count < BUCKET_MAX)
3255 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3256 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3257 zone->uz_name, zone, bucket);
3261 cache = &zone->uz_cpu[cpu];
3262 if (cache->uc_freebucket == NULL &&
3263 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3264 domain == PCPU_GET(domain))) {
3265 cache->uc_freebucket = bucket;
3269 * We lost the race, start over. We have to drop our
3270 * critical section to free the bucket.
3273 bucket_free(zone, bucket, udata);
3278 * If nothing else caught this, we'll just do an internal free.
3281 zone_free_item(zone, item, udata, SKIP_DTOR);
3287 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3290 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3291 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3293 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3296 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3297 ("uma_zfree_domain: called with spinlock or critical section held"));
3299 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3302 zone_free_item(zone, item, udata, SKIP_NONE);
3306 slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item)
3311 mtx_assert(&keg->uk_lock, MA_OWNED);
3312 MPASS(keg == slab->us_keg);
3314 dom = &keg->uk_domain[slab->us_domain];
3316 /* Do we need to remove from any lists? */
3317 if (slab->us_freecount+1 == keg->uk_ipers) {
3318 LIST_REMOVE(slab, us_link);
3319 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3320 } else if (slab->us_freecount == 0) {
3321 LIST_REMOVE(slab, us_link);
3322 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3325 /* Slab management. */
3326 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3327 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3328 slab->us_freecount++;
3330 /* Keg statistics. */
3335 zone_release(uma_zone_t zone, void **bucket, int cnt)
3345 keg = zone_first_keg(zone);
3347 for (i = 0; i < cnt; i++) {
3349 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3350 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3351 if (zone->uz_flags & UMA_ZONE_HASH) {
3352 slab = hash_sfind(&keg->uk_hash, mem);
3354 mem += keg->uk_pgoff;
3355 slab = (uma_slab_t)mem;
3358 slab = vtoslab((vm_offset_t)item);
3359 if (slab->us_keg != keg) {
3365 slab_free_item(keg, slab, item);
3366 if (keg->uk_flags & UMA_ZFLAG_FULL) {
3367 if (keg->uk_pages < keg->uk_maxpages) {
3368 keg->uk_flags &= ~UMA_ZFLAG_FULL;
3373 * We can handle one more allocation. Since we're
3374 * clearing ZFLAG_FULL, wake up all procs blocked
3375 * on pages. This should be uncommon, so keeping this
3376 * simple for now (rather than adding count of blocked
3385 zone->uz_flags &= ~UMA_ZFLAG_FULL;
3393 * Frees a single item to any zone.
3396 * zone The zone to free to
3397 * item The item we're freeing
3398 * udata User supplied data for the dtor
3399 * skip Skip dtors and finis
3402 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3407 skipdbg = uma_dbg_zskip(zone, item);
3408 if (skip == SKIP_NONE && !skipdbg) {
3409 if (zone->uz_flags & UMA_ZONE_MALLOC)
3410 uma_dbg_free(zone, udata, item);
3412 uma_dbg_free(zone, NULL, item);
3415 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3416 (!skipdbg || zone->uz_dtor != trash_dtor ||
3417 zone->uz_ctor != trash_ctor))
3419 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3421 zone->uz_dtor(item, zone->uz_size, udata);
3423 if (skip < SKIP_FINI && zone->uz_fini)
3424 zone->uz_fini(item, zone->uz_size);
3426 atomic_add_long(&zone->uz_frees, 1);
3427 zone->uz_release(zone->uz_arg, &item, 1);
3432 uma_zone_set_max(uma_zone_t zone, int nitems)
3436 keg = zone_first_keg(zone);
3440 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
3441 if (keg->uk_maxpages * keg->uk_ipers < nitems)
3442 keg->uk_maxpages += keg->uk_ppera;
3443 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3451 uma_zone_get_max(uma_zone_t zone)
3456 keg = zone_first_keg(zone);
3460 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3468 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3472 zone->uz_warning = warning;
3478 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3482 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3488 uma_zone_get_cur(uma_zone_t zone)
3494 nitems = zone->uz_allocs - zone->uz_frees;
3497 * See the comment in sysctl_vm_zone_stats() regarding the
3498 * safety of accessing the per-cpu caches. With the zone lock
3499 * held, it is safe, but can potentially result in stale data.
3501 nitems += zone->uz_cpu[i].uc_allocs -
3502 zone->uz_cpu[i].uc_frees;
3506 return (nitems < 0 ? 0 : nitems);
3511 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3515 keg = zone_first_keg(zone);
3516 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
3518 KASSERT(keg->uk_pages == 0,
3519 ("uma_zone_set_init on non-empty keg"));
3520 keg->uk_init = uminit;
3526 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3530 keg = zone_first_keg(zone);
3531 KASSERT(keg != NULL, ("uma_zone_set_fini: Invalid zone type"));
3533 KASSERT(keg->uk_pages == 0,
3534 ("uma_zone_set_fini on non-empty keg"));
3535 keg->uk_fini = fini;
3541 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3545 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3546 ("uma_zone_set_zinit on non-empty keg"));
3547 zone->uz_init = zinit;
3553 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3557 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3558 ("uma_zone_set_zfini on non-empty keg"));
3559 zone->uz_fini = zfini;
3564 /* XXX uk_freef is not actually used with the zone locked */
3566 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3570 keg = zone_first_keg(zone);
3571 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3573 keg->uk_freef = freef;
3578 /* XXX uk_allocf is not actually used with the zone locked */
3580 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3584 keg = zone_first_keg(zone);
3586 keg->uk_allocf = allocf;
3592 uma_zone_reserve(uma_zone_t zone, int items)
3596 keg = zone_first_keg(zone);
3600 keg->uk_reserve = items;
3608 uma_zone_reserve_kva(uma_zone_t zone, int count)
3614 keg = zone_first_keg(zone);
3617 pages = count / keg->uk_ipers;
3619 if (pages * keg->uk_ipers < count)
3621 pages *= keg->uk_ppera;
3623 #ifdef UMA_MD_SMALL_ALLOC
3624 if (keg->uk_ppera > 1) {
3628 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3636 keg->uk_maxpages = pages;
3637 #ifdef UMA_MD_SMALL_ALLOC
3638 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3640 keg->uk_allocf = noobj_alloc;
3642 keg->uk_flags |= UMA_ZONE_NOFREE;
3650 uma_prealloc(uma_zone_t zone, int items)
3652 struct vm_domainset_iter di;
3656 int domain, flags, slabs;
3658 keg = zone_first_keg(zone);
3662 slabs = items / keg->uk_ipers;
3663 if (slabs * keg->uk_ipers < items)
3666 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain, &flags);
3667 while (slabs-- > 0) {
3668 slab = keg_alloc_slab(keg, zone, domain, flags);
3671 MPASS(slab->us_keg == keg);
3672 dom = &keg->uk_domain[slab->us_domain];
3673 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3674 if (vm_domainset_iter_policy(&di, &domain) != 0)
3682 uma_reclaim_locked(bool kmem_danger)
3685 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3686 sx_assert(&uma_drain_lock, SA_XLOCKED);
3688 zone_foreach(zone_drain);
3689 if (vm_page_count_min() || kmem_danger) {
3690 cache_drain_safe(NULL);
3691 zone_foreach(zone_drain);
3695 * Some slabs may have been freed but this zone will be visited early
3696 * we visit again so that we can free pages that are empty once other
3697 * zones are drained. We have to do the same for buckets.
3699 zone_drain(slabzone);
3700 bucket_zone_drain();
3707 sx_xlock(&uma_drain_lock);
3708 uma_reclaim_locked(false);
3709 sx_xunlock(&uma_drain_lock);
3712 static volatile int uma_reclaim_needed;
3715 uma_reclaim_wakeup(void)
3718 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3719 wakeup(uma_reclaim);
3723 uma_reclaim_worker(void *arg __unused)
3727 sx_xlock(&uma_drain_lock);
3728 while (atomic_load_int(&uma_reclaim_needed) == 0)
3729 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3731 sx_xunlock(&uma_drain_lock);
3732 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3733 sx_xlock(&uma_drain_lock);
3734 uma_reclaim_locked(true);
3735 atomic_store_int(&uma_reclaim_needed, 0);
3736 sx_xunlock(&uma_drain_lock);
3737 /* Don't fire more than once per-second. */
3738 pause("umarclslp", hz);
3744 uma_zone_exhausted(uma_zone_t zone)
3749 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3755 uma_zone_exhausted_nolock(uma_zone_t zone)
3757 return (zone->uz_flags & UMA_ZFLAG_FULL);
3761 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3763 struct domainset *policy;
3767 if (domain != UMA_ANYDOMAIN) {
3768 /* avoid allocs targeting empty domains */
3769 if (VM_DOMAIN_EMPTY(domain))
3770 domain = UMA_ANYDOMAIN;
3772 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3775 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3776 DOMAINSET_FIXED(domain);
3777 addr = kmem_malloc_domainset(policy, size, wait);
3779 vsetslab(addr, slab);
3780 slab->us_data = (void *)addr;
3781 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3782 slab->us_size = size;
3783 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3784 pmap_kextract(addr)));
3785 uma_total_inc(size);
3787 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3790 return ((void *)addr);
3794 uma_large_malloc(vm_size_t size, int wait)
3797 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3801 uma_large_free(uma_slab_t slab)
3804 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3805 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3806 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3807 uma_total_dec(slab->us_size);
3808 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3812 uma_zero_item(void *item, uma_zone_t zone)
3815 bzero(item, zone->uz_size);
3822 return (uma_kmem_limit);
3826 uma_set_limit(unsigned long limit)
3829 uma_kmem_limit = limit;
3836 return (uma_kmem_total);
3843 return (uma_kmem_limit - uma_kmem_total);
3847 uma_print_stats(void)
3849 zone_foreach(uma_print_zone);
3853 slab_print(uma_slab_t slab)
3855 printf("slab: keg %p, data %p, freecount %d\n",
3856 slab->us_keg, slab->us_data, slab->us_freecount);
3860 cache_print(uma_cache_t cache)
3862 printf("alloc: %p(%d), free: %p(%d)\n",
3863 cache->uc_allocbucket,
3864 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3865 cache->uc_freebucket,
3866 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3870 uma_print_keg(uma_keg_t keg)
3876 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3877 "out %d free %d limit %d\n",
3878 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3879 keg->uk_ipers, keg->uk_ppera,
3880 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3881 keg->uk_free, (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3882 for (i = 0; i < vm_ndomains; i++) {
3883 dom = &keg->uk_domain[i];
3884 printf("Part slabs:\n");
3885 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3887 printf("Free slabs:\n");
3888 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3890 printf("Full slabs:\n");
3891 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3897 uma_print_zone(uma_zone_t zone)
3903 printf("zone: %s(%p) size %d flags %#x\n",
3904 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3905 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3906 uma_print_keg(kl->kl_keg);
3908 cache = &zone->uz_cpu[i];
3909 printf("CPU %d Cache:\n", i);
3916 * Generate statistics across both the zone and its per-cpu cache's. Return
3917 * desired statistics if the pointer is non-NULL for that statistic.
3919 * Note: does not update the zone statistics, as it can't safely clear the
3920 * per-CPU cache statistic.
3922 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3923 * safe from off-CPU; we should modify the caches to track this information
3924 * directly so that we don't have to.
3927 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3928 uint64_t *freesp, uint64_t *sleepsp)
3931 uint64_t allocs, frees, sleeps;
3934 allocs = frees = sleeps = 0;
3937 cache = &z->uz_cpu[cpu];
3938 if (cache->uc_allocbucket != NULL)
3939 cachefree += cache->uc_allocbucket->ub_cnt;
3940 if (cache->uc_freebucket != NULL)
3941 cachefree += cache->uc_freebucket->ub_cnt;
3942 allocs += cache->uc_allocs;
3943 frees += cache->uc_frees;
3945 allocs += z->uz_allocs;
3946 frees += z->uz_frees;
3947 sleeps += z->uz_sleeps;
3948 if (cachefreep != NULL)
3949 *cachefreep = cachefree;
3950 if (allocsp != NULL)
3954 if (sleepsp != NULL)
3960 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3967 rw_rlock(&uma_rwlock);
3968 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3969 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3972 rw_runlock(&uma_rwlock);
3973 return (sysctl_handle_int(oidp, &count, 0, req));
3977 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3979 struct uma_stream_header ush;
3980 struct uma_type_header uth;
3981 struct uma_percpu_stat *ups;
3982 uma_zone_domain_t zdom;
3989 int count, error, i;
3991 error = sysctl_wire_old_buffer(req, 0);
3994 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3995 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3996 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3999 rw_rlock(&uma_rwlock);
4000 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4001 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4006 * Insert stream header.
4008 bzero(&ush, sizeof(ush));
4009 ush.ush_version = UMA_STREAM_VERSION;
4010 ush.ush_maxcpus = (mp_maxid + 1);
4011 ush.ush_count = count;
4012 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
4014 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4015 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4016 bzero(&uth, sizeof(uth));
4018 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4019 uth.uth_align = kz->uk_align;
4020 uth.uth_size = kz->uk_size;
4021 uth.uth_rsize = kz->uk_rsize;
4022 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
4024 uth.uth_maxpages += k->uk_maxpages;
4025 uth.uth_pages += k->uk_pages;
4026 uth.uth_keg_free += k->uk_free;
4027 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
4032 * A zone is secondary is it is not the first entry
4033 * on the keg's zone list.
4035 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
4036 (LIST_FIRST(&kz->uk_zones) != z))
4037 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
4039 for (i = 0; i < vm_ndomains; i++) {
4040 zdom = &z->uz_domain[i];
4041 uth.uth_zone_free += zdom->uzd_nitems;
4043 uth.uth_allocs = z->uz_allocs;
4044 uth.uth_frees = z->uz_frees;
4045 uth.uth_fails = z->uz_fails;
4046 uth.uth_sleeps = z->uz_sleeps;
4048 * While it is not normally safe to access the cache
4049 * bucket pointers while not on the CPU that owns the
4050 * cache, we only allow the pointers to be exchanged
4051 * without the zone lock held, not invalidated, so
4052 * accept the possible race associated with bucket
4053 * exchange during monitoring.
4055 for (i = 0; i < mp_maxid + 1; i++) {
4056 bzero(&ups[i], sizeof(*ups));
4057 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
4060 cache = &z->uz_cpu[i];
4061 if (cache->uc_allocbucket != NULL)
4062 ups[i].ups_cache_free +=
4063 cache->uc_allocbucket->ub_cnt;
4064 if (cache->uc_freebucket != NULL)
4065 ups[i].ups_cache_free +=
4066 cache->uc_freebucket->ub_cnt;
4067 ups[i].ups_allocs = cache->uc_allocs;
4068 ups[i].ups_frees = cache->uc_frees;
4071 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4072 for (i = 0; i < mp_maxid + 1; i++)
4073 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4076 rw_runlock(&uma_rwlock);
4077 error = sbuf_finish(&sbuf);
4084 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4086 uma_zone_t zone = *(uma_zone_t *)arg1;
4089 max = uma_zone_get_max(zone);
4090 error = sysctl_handle_int(oidp, &max, 0, req);
4091 if (error || !req->newptr)
4094 uma_zone_set_max(zone, max);
4100 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4102 uma_zone_t zone = *(uma_zone_t *)arg1;
4105 cur = uma_zone_get_cur(zone);
4106 return (sysctl_handle_int(oidp, &cur, 0, req));
4111 uma_dbg_getslab(uma_zone_t zone, void *item)
4117 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4118 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4119 slab = vtoslab((vm_offset_t)mem);
4122 * It is safe to return the slab here even though the
4123 * zone is unlocked because the item's allocation state
4124 * essentially holds a reference.
4127 keg = LIST_FIRST(&zone->uz_kegs)->kl_keg;
4128 if (keg->uk_flags & UMA_ZONE_HASH)
4129 slab = hash_sfind(&keg->uk_hash, mem);
4131 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4139 uma_dbg_zskip(uma_zone_t zone, void *mem)
4143 if ((keg = zone_first_keg(zone)) == NULL)
4146 return (uma_dbg_kskip(keg, mem));
4150 uma_dbg_kskip(uma_keg_t keg, void *mem)
4154 if (dbg_divisor == 0)
4157 if (dbg_divisor == 1)
4160 idx = (uintptr_t)mem >> PAGE_SHIFT;
4161 if (keg->uk_ipers > 1) {
4162 idx *= keg->uk_ipers;
4163 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4166 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4167 counter_u64_add(uma_skip_cnt, 1);
4170 counter_u64_add(uma_dbg_cnt, 1);
4176 * Set up the slab's freei data such that uma_dbg_free can function.
4180 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4186 slab = uma_dbg_getslab(zone, item);
4188 panic("uma: item %p did not belong to zone %s\n",
4189 item, zone->uz_name);
4192 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4194 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4195 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4196 item, zone, zone->uz_name, slab, freei);
4197 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4203 * Verifies freed addresses. Checks for alignment, valid slab membership
4204 * and duplicate frees.
4208 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4214 slab = uma_dbg_getslab(zone, item);
4216 panic("uma: Freed item %p did not belong to zone %s\n",
4217 item, zone->uz_name);
4220 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4222 if (freei >= keg->uk_ipers)
4223 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4224 item, zone, zone->uz_name, slab, freei);
4226 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4227 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4228 item, zone, zone->uz_name, slab, freei);
4230 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4231 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4232 item, zone, zone->uz_name, slab, freei);
4234 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4236 #endif /* INVARIANTS */
4239 DB_SHOW_COMMAND(uma, db_show_uma)
4243 uint64_t allocs, frees, sleeps;
4247 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4248 "Free", "Requests", "Sleeps", "Bucket");
4249 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4250 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4251 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4252 allocs = z->uz_allocs;
4253 frees = z->uz_frees;
4254 sleeps = z->uz_sleeps;
4257 uma_zone_sumstat(z, &cachefree, &allocs,
4259 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4260 (LIST_FIRST(&kz->uk_zones) != z)))
4261 cachefree += kz->uk_free;
4262 for (i = 0; i < vm_ndomains; i++)
4263 cachefree += z->uz_domain[i].uzd_nitems;
4265 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4266 z->uz_name, (uintmax_t)kz->uk_size,
4267 (intmax_t)(allocs - frees), cachefree,
4268 (uintmax_t)allocs, sleeps, z->uz_count);
4275 DB_SHOW_COMMAND(umacache, db_show_umacache)
4278 uint64_t allocs, frees;
4282 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4283 "Requests", "Bucket");
4284 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4285 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4286 for (i = 0; i < vm_ndomains; i++)
4287 cachefree += z->uz_domain[i].uzd_nitems;
4288 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4289 z->uz_name, (uintmax_t)z->uz_size,
4290 (intmax_t)(allocs - frees), cachefree,
4291 (uintmax_t)allocs, z->uz_count);