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.
224 SKIP_CNT = 0x00000001,
225 SKIP_DTOR = 0x00010000,
226 SKIP_FINI = 0x00020000,
229 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
233 int uma_startup_count(int);
234 void uma_startup(void *, int);
235 void uma_startup1(void);
236 void uma_startup2(void);
238 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
239 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
240 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
241 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
242 static void page_free(void *, vm_size_t, uint8_t);
243 static void pcpu_page_free(void *, vm_size_t, uint8_t);
244 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
245 static void cache_drain(uma_zone_t);
246 static void bucket_drain(uma_zone_t, uma_bucket_t);
247 static void bucket_cache_drain(uma_zone_t zone);
248 static int keg_ctor(void *, int, void *, int);
249 static void keg_dtor(void *, int, void *);
250 static int zone_ctor(void *, int, void *, int);
251 static void zone_dtor(void *, int, void *);
252 static int zero_init(void *, int, int);
253 static void keg_small_init(uma_keg_t keg);
254 static void keg_large_init(uma_keg_t keg);
255 static void zone_foreach(void (*zfunc)(uma_zone_t));
256 static void zone_timeout(uma_zone_t zone);
257 static int hash_alloc(struct uma_hash *);
258 static int hash_expand(struct uma_hash *, struct uma_hash *);
259 static void hash_free(struct uma_hash *hash);
260 static void uma_timeout(void *);
261 static void uma_startup3(void);
262 static void *zone_alloc_item(uma_zone_t, void *, int, int);
263 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
264 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
265 static void bucket_enable(void);
266 static void bucket_init(void);
267 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
268 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
269 static void bucket_zone_drain(void);
270 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
271 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
272 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
273 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
274 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
275 uma_fini fini, int align, uint32_t flags);
276 static int zone_import(uma_zone_t, void **, int, int, int);
277 static void zone_release(uma_zone_t, void **, int);
278 static void uma_zero_item(void *, uma_zone_t);
280 void uma_print_zone(uma_zone_t);
281 void uma_print_stats(void);
282 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
283 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
286 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
287 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
288 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
289 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
291 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
292 "Memory allocation debugging");
294 static u_int dbg_divisor = 1;
295 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
296 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
297 "Debug & thrash every this item in memory allocator");
299 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
300 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
301 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
302 &uma_dbg_cnt, "memory items debugged");
303 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
304 &uma_skip_cnt, "memory items skipped, not debugged");
307 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
309 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
310 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
312 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
313 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
315 static int zone_warnings = 1;
316 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
317 "Warn when UMA zones becomes full");
319 /* Adjust bytes under management by UMA. */
321 uma_total_dec(unsigned long size)
324 atomic_subtract_long(&uma_kmem_total, size);
328 uma_total_inc(unsigned long size)
331 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
332 uma_reclaim_wakeup();
336 * This routine checks to see whether or not it's safe to enable buckets.
341 bucketdisable = vm_page_count_min();
345 * Initialize bucket_zones, the array of zones of buckets of various sizes.
347 * For each zone, calculate the memory required for each bucket, consisting
348 * of the header and an array of pointers.
353 struct uma_bucket_zone *ubz;
356 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
357 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
358 size += sizeof(void *) * ubz->ubz_entries;
359 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
360 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
361 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
366 * Given a desired number of entries for a bucket, return the zone from which
367 * to allocate the bucket.
369 static struct uma_bucket_zone *
370 bucket_zone_lookup(int entries)
372 struct uma_bucket_zone *ubz;
374 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
375 if (ubz->ubz_entries >= entries)
382 bucket_select(int size)
384 struct uma_bucket_zone *ubz;
386 ubz = &bucket_zones[0];
387 if (size > ubz->ubz_maxsize)
388 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
390 for (; ubz->ubz_entries != 0; ubz++)
391 if (ubz->ubz_maxsize < size)
394 return (ubz->ubz_entries);
398 bucket_alloc(uma_zone_t zone, void *udata, int flags)
400 struct uma_bucket_zone *ubz;
404 * This is to stop us from allocating per cpu buckets while we're
405 * running out of vm.boot_pages. Otherwise, we would exhaust the
406 * boot pages. This also prevents us from allocating buckets in
407 * low memory situations.
412 * To limit bucket recursion we store the original zone flags
413 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
414 * NOVM flag to persist even through deep recursions. We also
415 * store ZFLAG_BUCKET once we have recursed attempting to allocate
416 * a bucket for a bucket zone so we do not allow infinite bucket
417 * recursion. This cookie will even persist to frees of unused
418 * buckets via the allocation path or bucket allocations in the
421 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
422 udata = (void *)(uintptr_t)zone->uz_flags;
424 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
426 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
428 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
430 ubz = bucket_zone_lookup(zone->uz_count);
431 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
433 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
436 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
439 bucket->ub_entries = ubz->ubz_entries;
446 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
448 struct uma_bucket_zone *ubz;
450 KASSERT(bucket->ub_cnt == 0,
451 ("bucket_free: Freeing a non free bucket."));
452 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
453 udata = (void *)(uintptr_t)zone->uz_flags;
454 ubz = bucket_zone_lookup(bucket->ub_entries);
455 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
459 bucket_zone_drain(void)
461 struct uma_bucket_zone *ubz;
463 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
464 zone_drain(ubz->ubz_zone);
468 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
472 ZONE_LOCK_ASSERT(zone);
474 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
475 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
476 LIST_REMOVE(bucket, ub_link);
477 zdom->uzd_nitems -= bucket->ub_cnt;
478 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
479 zdom->uzd_imin = zdom->uzd_nitems;
480 zone->uz_bkt_count -= bucket->ub_cnt;
486 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
490 ZONE_LOCK_ASSERT(zone);
491 KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
494 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
495 zdom->uzd_nitems += bucket->ub_cnt;
496 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
497 zdom->uzd_imax = zdom->uzd_nitems;
498 zone->uz_bkt_count += bucket->ub_cnt;
502 zone_log_warning(uma_zone_t zone)
504 static const struct timeval warninterval = { 300, 0 };
506 if (!zone_warnings || zone->uz_warning == NULL)
509 if (ratecheck(&zone->uz_ratecheck, &warninterval))
510 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
514 zone_maxaction(uma_zone_t zone)
517 if (zone->uz_maxaction.ta_func != NULL)
518 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
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 zone_timeout(uma_zone_t zone)
567 uma_keg_t keg = zone->uz_keg;
571 * Expand the keg hash table.
573 * This is done if the number of slabs is larger than the hash size.
574 * What I'm trying to do here is completely reduce collisions. This
575 * may be a little aggressive. Should I allow for two collisions max?
577 if (keg->uk_flags & UMA_ZONE_HASH &&
578 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
579 struct uma_hash newhash;
580 struct uma_hash oldhash;
584 * This is so involved because allocating and freeing
585 * while the keg lock is held will lead to deadlock.
586 * I have to do everything in stages and check for
589 newhash = keg->uk_hash;
591 ret = hash_alloc(&newhash);
594 if (hash_expand(&keg->uk_hash, &newhash)) {
595 oldhash = keg->uk_hash;
596 keg->uk_hash = newhash;
606 for (int i = 0; i < vm_ndomains; i++)
607 zone_domain_update_wss(&zone->uz_domain[i]);
613 * Allocate and zero fill the next sized hash table from the appropriate
617 * hash A new hash structure with the old hash size in uh_hashsize
620 * 1 on success and 0 on failure.
623 hash_alloc(struct uma_hash *hash)
628 oldsize = hash->uh_hashsize;
630 /* We're just going to go to a power of two greater */
632 hash->uh_hashsize = oldsize * 2;
633 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
634 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
635 M_UMAHASH, M_NOWAIT);
637 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
638 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
639 UMA_ANYDOMAIN, M_WAITOK);
640 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
642 if (hash->uh_slab_hash) {
643 bzero(hash->uh_slab_hash, alloc);
644 hash->uh_hashmask = hash->uh_hashsize - 1;
652 * Expands the hash table for HASH zones. This is done from zone_timeout
653 * to reduce collisions. This must not be done in the regular allocation
654 * path, otherwise, we can recurse on the vm while allocating pages.
657 * oldhash The hash you want to expand
658 * newhash The hash structure for the new table
666 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
672 if (!newhash->uh_slab_hash)
675 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
679 * I need to investigate hash algorithms for resizing without a
683 for (idx = 0; idx < oldhash->uh_hashsize; idx++)
684 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
685 slab = SLIST_FIRST(&oldhash->uh_slab_hash[idx]);
686 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[idx], us_hlink);
687 hval = UMA_HASH(newhash, slab->us_data);
688 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
696 * Free the hash bucket to the appropriate backing store.
699 * slab_hash The hash bucket we're freeing
700 * hashsize The number of entries in that hash bucket
706 hash_free(struct uma_hash *hash)
708 if (hash->uh_slab_hash == NULL)
710 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
711 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
713 free(hash->uh_slab_hash, M_UMAHASH);
717 * Frees all outstanding items in a bucket
720 * zone The zone to free to, must be unlocked.
721 * bucket The free/alloc bucket with items, cpu queue must be locked.
728 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
736 for (i = 0; i < bucket->ub_cnt; i++)
737 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
738 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
739 if (zone->uz_max_items > 0) {
741 zone->uz_items -= bucket->ub_cnt;
742 if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
750 * Drains the per cpu caches for a zone.
752 * NOTE: This may only be called while the zone is being turn down, and not
753 * during normal operation. This is necessary in order that we do not have
754 * to migrate CPUs to drain the per-CPU caches.
757 * zone The zone to drain, must be unlocked.
763 cache_drain(uma_zone_t zone)
769 * XXX: It is safe to not lock the per-CPU caches, because we're
770 * tearing down the zone anyway. I.e., there will be no further use
771 * of the caches at this point.
773 * XXX: It would good to be able to assert that the zone is being
774 * torn down to prevent improper use of cache_drain().
776 * XXX: We lock the zone before passing into bucket_cache_drain() as
777 * it is used elsewhere. Should the tear-down path be made special
778 * there in some form?
781 cache = &zone->uz_cpu[cpu];
782 bucket_drain(zone, cache->uc_allocbucket);
783 bucket_drain(zone, cache->uc_freebucket);
784 if (cache->uc_allocbucket != NULL)
785 bucket_free(zone, cache->uc_allocbucket, NULL);
786 if (cache->uc_freebucket != NULL)
787 bucket_free(zone, cache->uc_freebucket, NULL);
788 cache->uc_allocbucket = cache->uc_freebucket = NULL;
791 bucket_cache_drain(zone);
796 cache_shrink(uma_zone_t zone)
799 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
803 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
808 cache_drain_safe_cpu(uma_zone_t zone)
814 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
820 if (zone->uz_flags & UMA_ZONE_NUMA)
821 domain = PCPU_GET(domain);
824 cache = &zone->uz_cpu[curcpu];
825 if (cache->uc_allocbucket) {
826 if (cache->uc_allocbucket->ub_cnt != 0)
827 zone_put_bucket(zone, &zone->uz_domain[domain],
828 cache->uc_allocbucket, false);
830 b1 = cache->uc_allocbucket;
831 cache->uc_allocbucket = NULL;
833 if (cache->uc_freebucket) {
834 if (cache->uc_freebucket->ub_cnt != 0)
835 zone_put_bucket(zone, &zone->uz_domain[domain],
836 cache->uc_freebucket, false);
838 b2 = cache->uc_freebucket;
839 cache->uc_freebucket = NULL;
844 bucket_free(zone, b1, NULL);
846 bucket_free(zone, b2, NULL);
850 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
851 * This is an expensive call because it needs to bind to all CPUs
852 * one by one and enter a critical section on each of them in order
853 * to safely access their cache buckets.
854 * Zone lock must not be held on call this function.
857 cache_drain_safe(uma_zone_t zone)
862 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
867 zone_foreach(cache_shrink);
870 thread_lock(curthread);
871 sched_bind(curthread, cpu);
872 thread_unlock(curthread);
875 cache_drain_safe_cpu(zone);
877 zone_foreach(cache_drain_safe_cpu);
879 thread_lock(curthread);
880 sched_unbind(curthread);
881 thread_unlock(curthread);
885 * Drain the cached buckets from a zone. Expects a locked zone on entry.
888 bucket_cache_drain(uma_zone_t zone)
890 uma_zone_domain_t zdom;
895 * Drain the bucket queues and free the buckets.
897 for (i = 0; i < vm_ndomains; i++) {
898 zdom = &zone->uz_domain[i];
899 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
902 bucket_drain(zone, bucket);
903 bucket_free(zone, bucket, NULL);
909 * Shrink further bucket sizes. Price of single zone lock collision
910 * is probably lower then price of global cache drain.
912 if (zone->uz_count > zone->uz_count_min)
917 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
923 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
924 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
927 flags = slab->us_flags;
929 if (keg->uk_fini != NULL) {
930 for (i--; i > -1; i--)
933 * trash_fini implies that dtor was trash_dtor. trash_fini
934 * would check that memory hasn't been modified since free,
935 * which executed trash_dtor.
936 * That's why we need to run uma_dbg_kskip() check here,
937 * albeit we don't make skip check for other init/fini
940 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
941 keg->uk_fini != trash_fini)
943 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
946 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
947 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
948 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
949 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
953 * Frees pages from a keg back to the system. This is done on demand from
954 * the pageout daemon.
959 keg_drain(uma_keg_t keg)
961 struct slabhead freeslabs = { 0 };
963 uma_slab_t slab, tmp;
967 * We don't want to take pages from statically allocated kegs at this
970 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
973 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
974 keg->uk_name, keg, keg->uk_free);
976 if (keg->uk_free == 0)
979 for (i = 0; i < vm_ndomains; i++) {
980 dom = &keg->uk_domain[i];
981 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
982 /* We have nowhere to free these to. */
983 if (slab->us_flags & UMA_SLAB_BOOT)
986 LIST_REMOVE(slab, us_link);
987 keg->uk_pages -= keg->uk_ppera;
988 keg->uk_free -= keg->uk_ipers;
990 if (keg->uk_flags & UMA_ZONE_HASH)
991 UMA_HASH_REMOVE(&keg->uk_hash, slab,
994 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1001 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1002 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1003 keg_free_slab(keg, slab, keg->uk_ipers);
1008 zone_drain_wait(uma_zone_t zone, int waitok)
1012 * Set draining to interlock with zone_dtor() so we can release our
1013 * locks as we go. Only dtor() should do a WAITOK call since it
1014 * is the only call that knows the structure will still be available
1018 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1019 if (waitok == M_NOWAIT)
1021 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1023 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1024 bucket_cache_drain(zone);
1027 * The DRAINING flag protects us from being freed while
1028 * we're running. Normally the uma_rwlock would protect us but we
1029 * must be able to release and acquire the right lock for each keg.
1031 keg_drain(zone->uz_keg);
1033 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1040 zone_drain(uma_zone_t zone)
1043 zone_drain_wait(zone, M_NOWAIT);
1047 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1048 * If the allocation was successful, the keg lock will be held upon return,
1049 * otherwise the keg will be left unlocked.
1052 * flags Wait flags for the item initialization routine
1053 * aflags Wait flags for the slab allocation
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 flags,
1070 KASSERT(domain >= 0 && domain < vm_ndomains,
1071 ("keg_alloc_slab: domain %d out of range", domain));
1072 KEG_LOCK_ASSERT(keg);
1073 MPASS(zone->uz_lockptr == &keg->uk_lock);
1075 allocf = keg->uk_allocf;
1080 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1081 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, aflags);
1087 * This reproduces the old vm_zone behavior of zero filling pages the
1088 * first time they are added to a zone.
1090 * Malloced items are zeroed in uma_zalloc.
1093 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1098 if (keg->uk_flags & UMA_ZONE_NODUMP)
1101 /* zone is passed for legacy reasons. */
1102 size = keg->uk_ppera * PAGE_SIZE;
1103 mem = allocf(zone, size, domain, &sflags, aflags);
1105 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1106 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1110 uma_total_inc(size);
1112 /* Point the slab into the allocated memory */
1113 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1114 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1116 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1117 for (i = 0; i < keg->uk_ppera; i++)
1118 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1121 slab->us_data = mem;
1122 slab->us_freecount = keg->uk_ipers;
1123 slab->us_flags = sflags;
1124 slab->us_domain = domain;
1125 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1127 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1130 if (keg->uk_init != NULL) {
1131 for (i = 0; i < keg->uk_ipers; i++)
1132 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1133 keg->uk_size, flags) != 0)
1135 if (i != keg->uk_ipers) {
1136 keg_free_slab(keg, slab, i);
1143 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1144 slab, keg->uk_name, keg);
1146 if (keg->uk_flags & UMA_ZONE_HASH)
1147 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1149 keg->uk_pages += keg->uk_ppera;
1150 keg->uk_free += keg->uk_ipers;
1157 * This function is intended to be used early on in place of page_alloc() so
1158 * that we may use the boot time page cache to satisfy allocations before
1162 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1171 * If we are in BOOT_BUCKETS or higher, than switch to real
1172 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1178 case BOOT_PAGEALLOC:
1179 if (keg->uk_ppera > 1)
1183 #ifdef UMA_MD_SMALL_ALLOC
1184 keg->uk_allocf = (keg->uk_ppera > 1) ?
1185 page_alloc : uma_small_alloc;
1187 keg->uk_allocf = page_alloc;
1189 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1193 * Check our small startup cache to see if it has pages remaining.
1195 pages = howmany(bytes, PAGE_SIZE);
1196 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1197 if (pages > boot_pages)
1198 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1200 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1204 boot_pages -= pages;
1205 bootmem += pages * PAGE_SIZE;
1206 *pflag = UMA_SLAB_BOOT;
1212 * Allocates a number of pages from the system
1215 * bytes The number of bytes requested
1216 * wait Shall we wait?
1219 * A pointer to the alloced memory or possibly
1220 * NULL if M_NOWAIT is set.
1223 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1226 void *p; /* Returned page */
1228 *pflag = UMA_SLAB_KERNEL;
1229 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1235 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1238 struct pglist alloctail;
1239 vm_offset_t addr, zkva;
1241 vm_page_t p, p_next;
1246 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1248 TAILQ_INIT(&alloctail);
1249 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1250 malloc2vm_flags(wait);
1251 *pflag = UMA_SLAB_KERNEL;
1252 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1253 if (CPU_ABSENT(cpu)) {
1254 p = vm_page_alloc(NULL, 0, flags);
1257 p = vm_page_alloc(NULL, 0, flags);
1259 pc = pcpu_find(cpu);
1260 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1261 if (__predict_false(p == NULL))
1262 p = vm_page_alloc(NULL, 0, flags);
1265 if (__predict_false(p == NULL))
1267 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1269 if ((addr = kva_alloc(bytes)) == 0)
1272 TAILQ_FOREACH(p, &alloctail, listq) {
1273 pmap_qenter(zkva, &p, 1);
1276 return ((void*)addr);
1278 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1279 vm_page_unwire(p, PQ_NONE);
1286 * Allocates a number of pages from within an object
1289 * bytes The number of bytes requested
1290 * wait Shall we wait?
1293 * A pointer to the alloced memory or possibly
1294 * NULL if M_NOWAIT is set.
1297 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1300 TAILQ_HEAD(, vm_page) alloctail;
1302 vm_offset_t retkva, zkva;
1303 vm_page_t p, p_next;
1306 TAILQ_INIT(&alloctail);
1309 npages = howmany(bytes, PAGE_SIZE);
1310 while (npages > 0) {
1311 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1312 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1313 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1317 * Since the page does not belong to an object, its
1320 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1325 * Page allocation failed, free intermediate pages and
1328 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1329 vm_page_unwire(p, PQ_NONE);
1334 *flags = UMA_SLAB_PRIV;
1335 zkva = keg->uk_kva +
1336 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1338 TAILQ_FOREACH(p, &alloctail, listq) {
1339 pmap_qenter(zkva, &p, 1);
1343 return ((void *)retkva);
1347 * Frees a number of pages to the system
1350 * mem A pointer to the memory to be freed
1351 * size The size of the memory being freed
1352 * flags The original p->us_flags field
1358 page_free(void *mem, vm_size_t size, uint8_t flags)
1361 if ((flags & UMA_SLAB_KERNEL) == 0)
1362 panic("UMA: page_free used with invalid flags %x", flags);
1364 kmem_free((vm_offset_t)mem, size);
1368 * Frees pcpu zone allocations
1371 * mem A pointer to the memory to be freed
1372 * size The size of the memory being freed
1373 * flags The original p->us_flags field
1379 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1381 vm_offset_t sva, curva;
1385 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1386 sva = (vm_offset_t)mem;
1387 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1388 paddr = pmap_kextract(curva);
1389 m = PHYS_TO_VM_PAGE(paddr);
1390 vm_page_unwire(m, PQ_NONE);
1393 pmap_qremove(sva, size >> PAGE_SHIFT);
1394 kva_free(sva, size);
1399 * Zero fill initializer
1401 * Arguments/Returns follow uma_init specifications
1404 zero_init(void *mem, int size, int flags)
1411 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1414 * keg The zone we should initialize
1420 keg_small_init(uma_keg_t keg)
1428 if (keg->uk_flags & UMA_ZONE_PCPU) {
1429 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1431 slabsize = UMA_PCPU_ALLOC_SIZE;
1432 keg->uk_ppera = ncpus;
1434 slabsize = UMA_SLAB_SIZE;
1439 * Calculate the size of each allocation (rsize) according to
1440 * alignment. If the requested size is smaller than we have
1441 * allocation bits for we round it up.
1443 rsize = keg->uk_size;
1444 if (rsize < slabsize / SLAB_SETSIZE)
1445 rsize = slabsize / SLAB_SETSIZE;
1446 if (rsize & keg->uk_align)
1447 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1448 keg->uk_rsize = rsize;
1450 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1451 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1452 ("%s: size %u too large", __func__, keg->uk_rsize));
1454 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1457 shsize = SIZEOF_UMA_SLAB;
1459 if (rsize <= slabsize - shsize)
1460 keg->uk_ipers = (slabsize - shsize) / rsize;
1462 /* Handle special case when we have 1 item per slab, so
1463 * alignment requirement can be relaxed. */
1464 KASSERT(keg->uk_size <= slabsize - shsize,
1465 ("%s: size %u greater than slab", __func__, keg->uk_size));
1468 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1469 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1471 memused = keg->uk_ipers * rsize + shsize;
1472 wastedspace = slabsize - memused;
1475 * We can't do OFFPAGE if we're internal or if we've been
1476 * asked to not go to the VM for buckets. If we do this we
1477 * may end up going to the VM for slabs which we do not
1478 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1479 * of UMA_ZONE_VM, which clearly forbids it.
1481 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1482 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1486 * See if using an OFFPAGE slab will limit our waste. Only do
1487 * this if it permits more items per-slab.
1489 * XXX We could try growing slabsize to limit max waste as well.
1490 * Historically this was not done because the VM could not
1491 * efficiently handle contiguous allocations.
1493 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1494 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1495 keg->uk_ipers = slabsize / keg->uk_rsize;
1496 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1497 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1498 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1499 "keg: %s(%p), calculated wastedspace = %d, "
1500 "maximum wasted space allowed = %d, "
1501 "calculated ipers = %d, "
1502 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1503 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1504 slabsize - keg->uk_ipers * keg->uk_rsize);
1505 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1508 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1509 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1510 keg->uk_flags |= UMA_ZONE_HASH;
1514 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1515 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1519 * keg The keg we should initialize
1525 keg_large_init(uma_keg_t keg)
1528 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1529 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1530 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1532 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1534 keg->uk_rsize = keg->uk_size;
1536 /* Check whether we have enough space to not do OFFPAGE. */
1537 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1538 PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1540 * We can't do OFFPAGE if we're internal, in which case
1541 * we need an extra page per allocation to contain the
1544 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1545 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1550 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1551 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1552 keg->uk_flags |= UMA_ZONE_HASH;
1556 keg_cachespread_init(uma_keg_t keg)
1563 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1564 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1566 alignsize = keg->uk_align + 1;
1567 rsize = keg->uk_size;
1569 * We want one item to start on every align boundary in a page. To
1570 * do this we will span pages. We will also extend the item by the
1571 * size of align if it is an even multiple of align. Otherwise, it
1572 * would fall on the same boundary every time.
1574 if (rsize & keg->uk_align)
1575 rsize = (rsize & ~keg->uk_align) + alignsize;
1576 if ((rsize & alignsize) == 0)
1578 trailer = rsize - keg->uk_size;
1579 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1580 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1581 keg->uk_rsize = rsize;
1582 keg->uk_ppera = pages;
1583 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1584 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1585 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1586 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1591 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1592 * the keg onto the global keg list.
1594 * Arguments/Returns follow uma_ctor specifications
1595 * udata Actually uma_kctor_args
1598 keg_ctor(void *mem, int size, void *udata, int flags)
1600 struct uma_kctor_args *arg = udata;
1601 uma_keg_t keg = mem;
1605 keg->uk_size = arg->size;
1606 keg->uk_init = arg->uminit;
1607 keg->uk_fini = arg->fini;
1608 keg->uk_align = arg->align;
1610 keg->uk_reserve = 0;
1612 keg->uk_flags = arg->flags;
1613 keg->uk_slabzone = NULL;
1616 * We use a global round-robin policy by default. Zones with
1617 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1618 * iterator is never run.
1620 keg->uk_dr.dr_policy = DOMAINSET_RR();
1621 keg->uk_dr.dr_iter = 0;
1624 * The master zone is passed to us at keg-creation time.
1627 keg->uk_name = zone->uz_name;
1629 if (arg->flags & UMA_ZONE_VM)
1630 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1632 if (arg->flags & UMA_ZONE_ZINIT)
1633 keg->uk_init = zero_init;
1635 if (arg->flags & UMA_ZONE_MALLOC)
1636 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1638 if (arg->flags & UMA_ZONE_PCPU)
1640 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1642 keg->uk_flags &= ~UMA_ZONE_PCPU;
1645 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1646 keg_cachespread_init(keg);
1648 if (keg->uk_size > UMA_SLAB_SPACE)
1649 keg_large_init(keg);
1651 keg_small_init(keg);
1654 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1655 keg->uk_slabzone = slabzone;
1658 * If we haven't booted yet we need allocations to go through the
1659 * startup cache until the vm is ready.
1661 if (booted < BOOT_PAGEALLOC)
1662 keg->uk_allocf = startup_alloc;
1663 #ifdef UMA_MD_SMALL_ALLOC
1664 else if (keg->uk_ppera == 1)
1665 keg->uk_allocf = uma_small_alloc;
1667 else if (keg->uk_flags & UMA_ZONE_PCPU)
1668 keg->uk_allocf = pcpu_page_alloc;
1670 keg->uk_allocf = page_alloc;
1671 #ifdef UMA_MD_SMALL_ALLOC
1672 if (keg->uk_ppera == 1)
1673 keg->uk_freef = uma_small_free;
1676 if (keg->uk_flags & UMA_ZONE_PCPU)
1677 keg->uk_freef = pcpu_page_free;
1679 keg->uk_freef = page_free;
1682 * Initialize keg's lock
1684 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1687 * If we're putting the slab header in the actual page we need to
1688 * figure out where in each page it goes. See SIZEOF_UMA_SLAB
1691 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1692 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1694 * The only way the following is possible is if with our
1695 * UMA_ALIGN_PTR adjustments we are now bigger than
1696 * UMA_SLAB_SIZE. I haven't checked whether this is
1697 * mathematically possible for all cases, so we make
1700 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1701 PAGE_SIZE * keg->uk_ppera,
1702 ("zone %s ipers %d rsize %d size %d slab won't fit",
1703 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1706 if (keg->uk_flags & UMA_ZONE_HASH)
1707 hash_alloc(&keg->uk_hash);
1709 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1710 keg, zone->uz_name, zone,
1711 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1714 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1716 rw_wlock(&uma_rwlock);
1717 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1718 rw_wunlock(&uma_rwlock);
1723 zone_alloc_counters(uma_zone_t zone)
1726 zone->uz_allocs = counter_u64_alloc(M_WAITOK);
1727 zone->uz_frees = counter_u64_alloc(M_WAITOK);
1728 zone->uz_fails = counter_u64_alloc(M_WAITOK);
1732 * Zone header ctor. This initializes all fields, locks, etc.
1734 * Arguments/Returns follow uma_ctor specifications
1735 * udata Actually uma_zctor_args
1738 zone_ctor(void *mem, int size, void *udata, int flags)
1740 struct uma_zctor_args *arg = udata;
1741 uma_zone_t zone = mem;
1746 zone->uz_name = arg->name;
1747 zone->uz_ctor = arg->ctor;
1748 zone->uz_dtor = arg->dtor;
1749 zone->uz_init = NULL;
1750 zone->uz_fini = NULL;
1751 zone->uz_sleeps = 0;
1753 zone->uz_count_min = 0;
1754 zone->uz_count_max = BUCKET_MAX;
1756 zone->uz_warning = NULL;
1757 /* The domain structures follow the cpu structures. */
1758 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1759 zone->uz_bkt_max = ULONG_MAX;
1760 timevalclear(&zone->uz_ratecheck);
1762 if (__predict_true(booted == BOOT_RUNNING))
1763 zone_alloc_counters(zone);
1765 zone->uz_allocs = EARLY_COUNTER;
1766 zone->uz_frees = EARLY_COUNTER;
1767 zone->uz_fails = EARLY_COUNTER;
1771 * This is a pure cache zone, no kegs.
1774 if (arg->flags & UMA_ZONE_VM)
1775 arg->flags |= UMA_ZFLAG_CACHEONLY;
1776 zone->uz_flags = arg->flags;
1777 zone->uz_size = arg->size;
1778 zone->uz_import = arg->import;
1779 zone->uz_release = arg->release;
1780 zone->uz_arg = arg->arg;
1781 zone->uz_lockptr = &zone->uz_lock;
1782 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1783 rw_wlock(&uma_rwlock);
1784 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1785 rw_wunlock(&uma_rwlock);
1790 * Use the regular zone/keg/slab allocator.
1792 zone->uz_import = (uma_import)zone_import;
1793 zone->uz_release = (uma_release)zone_release;
1794 zone->uz_arg = zone;
1797 if (arg->flags & UMA_ZONE_SECONDARY) {
1798 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1799 zone->uz_init = arg->uminit;
1800 zone->uz_fini = arg->fini;
1801 zone->uz_lockptr = &keg->uk_lock;
1802 zone->uz_flags |= UMA_ZONE_SECONDARY;
1803 rw_wlock(&uma_rwlock);
1805 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1806 if (LIST_NEXT(z, uz_link) == NULL) {
1807 LIST_INSERT_AFTER(z, zone, uz_link);
1812 rw_wunlock(&uma_rwlock);
1813 } else if (keg == NULL) {
1814 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1815 arg->align, arg->flags)) == NULL)
1818 struct uma_kctor_args karg;
1821 /* We should only be here from uma_startup() */
1822 karg.size = arg->size;
1823 karg.uminit = arg->uminit;
1824 karg.fini = arg->fini;
1825 karg.align = arg->align;
1826 karg.flags = arg->flags;
1828 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1835 zone->uz_size = keg->uk_size;
1836 zone->uz_flags |= (keg->uk_flags &
1837 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1840 * Some internal zones don't have room allocated for the per cpu
1841 * caches. If we're internal, bail out here.
1843 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1844 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1845 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1850 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1851 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1852 ("Invalid zone flag combination"));
1853 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1854 zone->uz_count = BUCKET_MAX;
1855 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1858 zone->uz_count = bucket_select(zone->uz_size);
1859 zone->uz_count_min = zone->uz_count;
1865 * Keg header dtor. This frees all data, destroys locks, frees the hash
1866 * table and removes the keg from the global list.
1868 * Arguments/Returns follow uma_dtor specifications
1872 keg_dtor(void *arg, int size, void *udata)
1876 keg = (uma_keg_t)arg;
1878 if (keg->uk_free != 0) {
1879 printf("Freed UMA keg (%s) was not empty (%d items). "
1880 " Lost %d pages of memory.\n",
1881 keg->uk_name ? keg->uk_name : "",
1882 keg->uk_free, keg->uk_pages);
1886 hash_free(&keg->uk_hash);
1894 * Arguments/Returns follow uma_dtor specifications
1898 zone_dtor(void *arg, int size, void *udata)
1903 zone = (uma_zone_t)arg;
1905 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1908 rw_wlock(&uma_rwlock);
1909 LIST_REMOVE(zone, uz_link);
1910 rw_wunlock(&uma_rwlock);
1912 * XXX there are some races here where
1913 * the zone can be drained but zone lock
1914 * released and then refilled before we
1915 * remove it... we dont care for now
1917 zone_drain_wait(zone, M_WAITOK);
1919 * We only destroy kegs from non secondary zones.
1921 if ((keg = zone->uz_keg) != NULL &&
1922 (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1923 rw_wlock(&uma_rwlock);
1924 LIST_REMOVE(keg, uk_link);
1925 rw_wunlock(&uma_rwlock);
1926 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1928 counter_u64_free(zone->uz_allocs);
1929 counter_u64_free(zone->uz_frees);
1930 counter_u64_free(zone->uz_fails);
1931 if (zone->uz_lockptr == &zone->uz_lock)
1932 ZONE_LOCK_FINI(zone);
1936 * Traverses every zone in the system and calls a callback
1939 * zfunc A pointer to a function which accepts a zone
1946 zone_foreach(void (*zfunc)(uma_zone_t))
1952 * Before BOOT_RUNNING we are guaranteed to be single
1953 * threaded, so locking isn't needed. Startup functions
1954 * are allowed to use M_WAITOK.
1956 if (__predict_true(booted == BOOT_RUNNING))
1957 rw_rlock(&uma_rwlock);
1958 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1959 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1962 if (__predict_true(booted == BOOT_RUNNING))
1963 rw_runlock(&uma_rwlock);
1967 * Count how many pages do we need to bootstrap. VM supplies
1968 * its need in early zones in the argument, we add up our zones,
1969 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1970 * zone of zones and zone of kegs are accounted separately.
1972 #define UMA_BOOT_ZONES 11
1973 /* Zone of zones and zone of kegs have arbitrary alignment. */
1974 #define UMA_BOOT_ALIGN 32
1975 static int zsize, ksize;
1977 uma_startup_count(int vm_zones)
1981 ksize = sizeof(struct uma_keg) +
1982 (sizeof(struct uma_domain) * vm_ndomains);
1983 zsize = sizeof(struct uma_zone) +
1984 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1985 (sizeof(struct uma_zone_domain) * vm_ndomains);
1988 * Memory for the zone of kegs and its keg,
1989 * and for zone of zones.
1991 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1992 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1994 #ifdef UMA_MD_SMALL_ALLOC
1995 zones = UMA_BOOT_ZONES;
1997 zones = UMA_BOOT_ZONES + vm_zones;
2001 /* Memory for the rest of startup zones, UMA and VM, ... */
2002 if (zsize > UMA_SLAB_SPACE) {
2003 /* See keg_large_init(). */
2006 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
2007 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2010 pages += (zones + vm_zones) * ppera;
2011 } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2012 /* See keg_small_init() special case for uk_ppera = 1. */
2015 pages += howmany(zones,
2016 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2018 /* ... and their kegs. Note that zone of zones allocates a keg! */
2019 pages += howmany(zones + 1,
2020 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2023 * Most of startup zones are not going to be offpages, that's
2024 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2025 * calculations. Some large bucket zones will be offpage, and
2026 * thus will allocate hashes. We take conservative approach
2027 * and assume that all zones may allocate hash. This may give
2028 * us some positive inaccuracy, usually an extra single page.
2030 pages += howmany(zones, UMA_SLAB_SPACE /
2031 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2037 uma_startup(void *mem, int npages)
2039 struct uma_zctor_args args;
2040 uma_keg_t masterkeg;
2044 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2047 rw_init(&uma_rwlock, "UMA lock");
2049 /* Use bootpages memory for the zone of zones and zone of kegs. */
2051 zones = (uma_zone_t)m;
2052 m += roundup(zsize, CACHE_LINE_SIZE);
2053 kegs = (uma_zone_t)m;
2054 m += roundup(zsize, CACHE_LINE_SIZE);
2055 masterkeg = (uma_keg_t)m;
2056 m += roundup(ksize, CACHE_LINE_SIZE);
2057 m = roundup(m, PAGE_SIZE);
2058 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2061 /* "manually" create the initial zone */
2062 memset(&args, 0, sizeof(args));
2063 args.name = "UMA Kegs";
2065 args.ctor = keg_ctor;
2066 args.dtor = keg_dtor;
2067 args.uminit = zero_init;
2069 args.keg = masterkeg;
2070 args.align = UMA_BOOT_ALIGN - 1;
2071 args.flags = UMA_ZFLAG_INTERNAL;
2072 zone_ctor(kegs, zsize, &args, M_WAITOK);
2075 boot_pages = npages;
2077 args.name = "UMA Zones";
2079 args.ctor = zone_ctor;
2080 args.dtor = zone_dtor;
2081 args.uminit = zero_init;
2084 args.align = UMA_BOOT_ALIGN - 1;
2085 args.flags = UMA_ZFLAG_INTERNAL;
2086 zone_ctor(zones, zsize, &args, M_WAITOK);
2088 /* Now make a zone for slab headers */
2089 slabzone = uma_zcreate("UMA Slabs",
2090 sizeof(struct uma_slab),
2091 NULL, NULL, NULL, NULL,
2092 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2094 hashzone = uma_zcreate("UMA Hash",
2095 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2096 NULL, NULL, NULL, NULL,
2097 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2101 booted = BOOT_STRAPPED;
2109 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2111 booted = BOOT_PAGEALLOC;
2119 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2121 booted = BOOT_BUCKETS;
2122 sx_init(&uma_drain_lock, "umadrain");
2127 * Initialize our callout handle
2135 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2136 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2137 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2139 zone_foreach(zone_alloc_counters);
2140 callout_init(&uma_callout, 1);
2141 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2142 booted = BOOT_RUNNING;
2146 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2147 int align, uint32_t flags)
2149 struct uma_kctor_args args;
2152 args.uminit = uminit;
2154 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2157 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2160 /* Public functions */
2163 uma_set_align(int align)
2166 if (align != UMA_ALIGN_CACHE)
2167 uma_align_cache = align;
2172 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2173 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2176 struct uma_zctor_args args;
2180 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2183 /* This stuff is essential for the zone ctor */
2184 memset(&args, 0, sizeof(args));
2189 args.uminit = uminit;
2193 * If a zone is being created with an empty constructor and
2194 * destructor, pass UMA constructor/destructor which checks for
2195 * memory use after free.
2197 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2198 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2199 args.ctor = trash_ctor;
2200 args.dtor = trash_dtor;
2201 args.uminit = trash_init;
2202 args.fini = trash_fini;
2209 if (booted < BOOT_BUCKETS) {
2212 sx_slock(&uma_drain_lock);
2215 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2217 sx_sunlock(&uma_drain_lock);
2223 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2224 uma_init zinit, uma_fini zfini, uma_zone_t master)
2226 struct uma_zctor_args args;
2231 keg = master->uz_keg;
2232 memset(&args, 0, sizeof(args));
2234 args.size = keg->uk_size;
2237 args.uminit = zinit;
2239 args.align = keg->uk_align;
2240 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2243 if (booted < BOOT_BUCKETS) {
2246 sx_slock(&uma_drain_lock);
2249 /* XXX Attaches only one keg of potentially many. */
2250 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2252 sx_sunlock(&uma_drain_lock);
2258 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2259 uma_init zinit, uma_fini zfini, uma_import zimport,
2260 uma_release zrelease, void *arg, int flags)
2262 struct uma_zctor_args args;
2264 memset(&args, 0, sizeof(args));
2269 args.uminit = zinit;
2271 args.import = zimport;
2272 args.release = zrelease;
2275 args.flags = flags | UMA_ZFLAG_CACHE;
2277 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2282 uma_zdestroy(uma_zone_t zone)
2285 sx_slock(&uma_drain_lock);
2286 zone_free_item(zones, zone, NULL, SKIP_NONE);
2287 sx_sunlock(&uma_drain_lock);
2291 uma_zwait(uma_zone_t zone)
2295 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2296 uma_zfree(zone, item);
2300 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2306 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2308 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2309 if (item != NULL && (flags & M_ZERO)) {
2311 for (i = 0; i <= mp_maxid; i++)
2312 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2314 bzero(item, zone->uz_size);
2321 * A stub while both regular and pcpu cases are identical.
2324 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2328 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2330 uma_zfree_arg(zone, item, udata);
2335 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2337 uma_zone_domain_t zdom;
2338 uma_bucket_t bucket;
2341 int cpu, domain, lockfail, maxbucket;
2346 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2347 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2349 /* This is the fast path allocation */
2350 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2351 curthread, zone->uz_name, zone, flags);
2353 if (flags & M_WAITOK) {
2354 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2355 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2357 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2358 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2359 ("uma_zalloc_arg: called with spinlock or critical section held"));
2360 if (zone->uz_flags & UMA_ZONE_PCPU)
2361 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2362 "with M_ZERO passed"));
2364 #ifdef DEBUG_MEMGUARD
2365 if (memguard_cmp_zone(zone)) {
2366 item = memguard_alloc(zone->uz_size, flags);
2368 if (zone->uz_init != NULL &&
2369 zone->uz_init(item, zone->uz_size, flags) != 0)
2371 if (zone->uz_ctor != NULL &&
2372 zone->uz_ctor(item, zone->uz_size, udata,
2374 zone->uz_fini(item, zone->uz_size);
2379 /* This is unfortunate but should not be fatal. */
2383 * If possible, allocate from the per-CPU cache. There are two
2384 * requirements for safe access to the per-CPU cache: (1) the thread
2385 * accessing the cache must not be preempted or yield during access,
2386 * and (2) the thread must not migrate CPUs without switching which
2387 * cache it accesses. We rely on a critical section to prevent
2388 * preemption and migration. We release the critical section in
2389 * order to acquire the zone mutex if we are unable to allocate from
2390 * the current cache; when we re-acquire the critical section, we
2391 * must detect and handle migration if it has occurred.
2396 cache = &zone->uz_cpu[cpu];
2399 bucket = cache->uc_allocbucket;
2400 if (bucket != NULL && bucket->ub_cnt > 0) {
2402 item = bucket->ub_bucket[bucket->ub_cnt];
2404 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2406 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2410 skipdbg = uma_dbg_zskip(zone, item);
2412 if (zone->uz_ctor != NULL &&
2414 (!skipdbg || zone->uz_ctor != trash_ctor ||
2415 zone->uz_dtor != trash_dtor) &&
2417 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2418 counter_u64_add(zone->uz_fails, 1);
2419 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2424 uma_dbg_alloc(zone, NULL, item);
2427 uma_zero_item(item, zone);
2432 * We have run out of items in our alloc bucket.
2433 * See if we can switch with our free bucket.
2435 bucket = cache->uc_freebucket;
2436 if (bucket != NULL && bucket->ub_cnt > 0) {
2438 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2439 zone->uz_name, zone);
2440 cache->uc_freebucket = cache->uc_allocbucket;
2441 cache->uc_allocbucket = bucket;
2446 * Discard any empty allocation bucket while we hold no locks.
2448 bucket = cache->uc_allocbucket;
2449 cache->uc_allocbucket = NULL;
2452 bucket_free(zone, bucket, udata);
2454 if (zone->uz_flags & UMA_ZONE_NUMA) {
2455 domain = PCPU_GET(domain);
2456 if (VM_DOMAIN_EMPTY(domain))
2457 domain = UMA_ANYDOMAIN;
2459 domain = UMA_ANYDOMAIN;
2461 /* Short-circuit for zones without buckets and low memory. */
2462 if (zone->uz_count == 0 || bucketdisable) {
2468 * Attempt to retrieve the item from the per-CPU cache has failed, so
2469 * we must go back to the zone. This requires the zone lock, so we
2470 * must drop the critical section, then re-acquire it when we go back
2471 * to the cache. Since the critical section is released, we may be
2472 * preempted or migrate. As such, make sure not to maintain any
2473 * thread-local state specific to the cache from prior to releasing
2474 * the critical section.
2477 if (ZONE_TRYLOCK(zone) == 0) {
2478 /* Record contention to size the buckets. */
2484 cache = &zone->uz_cpu[cpu];
2486 /* See if we lost the race to fill the cache. */
2487 if (cache->uc_allocbucket != NULL) {
2493 * Check the zone's cache of buckets.
2495 if (domain == UMA_ANYDOMAIN)
2496 zdom = &zone->uz_domain[0];
2498 zdom = &zone->uz_domain[domain];
2499 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2500 KASSERT(bucket->ub_cnt != 0,
2501 ("uma_zalloc_arg: Returning an empty bucket."));
2502 cache->uc_allocbucket = bucket;
2506 /* We are no longer associated with this CPU. */
2510 * We bump the uz count when the cache size is insufficient to
2511 * handle the working set.
2513 if (lockfail && zone->uz_count < zone->uz_count_max)
2516 if (zone->uz_max_items > 0) {
2517 if (zone->uz_items >= zone->uz_max_items)
2519 maxbucket = MIN(zone->uz_count,
2520 zone->uz_max_items - zone->uz_items);
2521 zone->uz_items += maxbucket;
2523 maxbucket = zone->uz_count;
2527 * Now lets just fill a bucket and put it on the free list. If that
2528 * works we'll restart the allocation from the beginning and it
2529 * will use the just filled bucket.
2531 bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2532 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2533 zone->uz_name, zone, bucket);
2535 if (bucket != NULL) {
2536 if (zone->uz_max_items > 0 && bucket->ub_cnt < maxbucket) {
2537 MPASS(zone->uz_items >= maxbucket - bucket->ub_cnt);
2538 zone->uz_items -= maxbucket - bucket->ub_cnt;
2539 if (zone->uz_sleepers > 0 &&
2540 zone->uz_items < zone->uz_max_items)
2545 cache = &zone->uz_cpu[cpu];
2548 * See if we lost the race or were migrated. Cache the
2549 * initialized bucket to make this less likely or claim
2550 * the memory directly.
2552 if (cache->uc_allocbucket == NULL &&
2553 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2554 domain == PCPU_GET(domain))) {
2555 cache->uc_allocbucket = bucket;
2556 zdom->uzd_imax += bucket->ub_cnt;
2557 } else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2560 bucket_drain(zone, bucket);
2561 bucket_free(zone, bucket, udata);
2562 goto zalloc_restart;
2564 zone_put_bucket(zone, zdom, bucket, false);
2567 } else if (zone->uz_max_items > 0) {
2568 zone->uz_items -= maxbucket;
2569 if (zone->uz_sleepers > 0 &&
2570 zone->uz_items + 1 < zone->uz_max_items)
2575 * We may not be able to get a bucket so return an actual item.
2578 item = zone_alloc_item_locked(zone, udata, domain, flags);
2584 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2587 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2588 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2590 /* This is the fast path allocation */
2592 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2593 curthread, zone->uz_name, zone, domain, flags);
2595 if (flags & M_WAITOK) {
2596 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2597 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2599 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2600 ("uma_zalloc_domain: called with spinlock or critical section held"));
2602 return (zone_alloc_item(zone, udata, domain, flags));
2606 * Find a slab with some space. Prefer slabs that are partially used over those
2607 * that are totally full. This helps to reduce fragmentation.
2609 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2613 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2619 KASSERT(domain >= 0 && domain < vm_ndomains,
2620 ("keg_first_slab: domain %d out of range", domain));
2621 KEG_LOCK_ASSERT(keg);
2626 dom = &keg->uk_domain[domain];
2627 if (!LIST_EMPTY(&dom->ud_part_slab))
2628 return (LIST_FIRST(&dom->ud_part_slab));
2629 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2630 slab = LIST_FIRST(&dom->ud_free_slab);
2631 LIST_REMOVE(slab, us_link);
2632 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2636 domain = (domain + 1) % vm_ndomains;
2637 } while (domain != start);
2643 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2647 KEG_LOCK_ASSERT(keg);
2649 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2650 if (keg->uk_free <= reserve)
2652 return (keg_first_slab(keg, domain, rr));
2656 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2658 struct vm_domainset_iter di;
2665 KEG_LOCK_ASSERT(keg);
2668 * Use the keg's policy if upper layers haven't already specified a
2669 * domain (as happens with first-touch zones).
2671 * To avoid races we run the iterator with the keg lock held, but that
2672 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2673 * clear M_WAITOK and handle low memory conditions locally.
2675 rr = rdomain == UMA_ANYDOMAIN;
2677 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2678 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2686 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2688 MPASS(slab->us_keg == keg);
2693 * M_NOVM means don't ask at all!
2698 KASSERT(zone->uz_max_items == 0 ||
2699 zone->uz_items <= zone->uz_max_items,
2700 ("%s: zone %p overflow", __func__, zone));
2702 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
2704 * If we got a slab here it's safe to mark it partially used
2705 * and return. We assume that the caller is going to remove
2706 * at least one item.
2709 MPASS(slab->us_keg == keg);
2710 dom = &keg->uk_domain[slab->us_domain];
2711 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2715 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2716 if ((flags & M_WAITOK) != 0) {
2718 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2727 * We might not have been able to get a slab but another cpu
2728 * could have while we were unlocked. Check again before we
2731 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2732 MPASS(slab->us_keg == keg);
2739 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2749 slab = keg_fetch_slab(keg, zone, domain, flags);
2752 if (flags & (M_NOWAIT | M_NOVM))
2760 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2766 MPASS(keg == slab->us_keg);
2767 KEG_LOCK_ASSERT(keg);
2769 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2770 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2771 item = slab->us_data + (keg->uk_rsize * freei);
2772 slab->us_freecount--;
2775 /* Move this slab to the full list */
2776 if (slab->us_freecount == 0) {
2777 LIST_REMOVE(slab, us_link);
2778 dom = &keg->uk_domain[slab->us_domain];
2779 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2786 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2797 /* Try to keep the buckets totally full */
2798 for (i = 0; i < max; ) {
2799 if ((slab = zone_fetch_slab(zone, keg, domain, flags)) == NULL)
2803 stripe = howmany(max, vm_ndomains);
2805 while (slab->us_freecount && i < max) {
2806 bucket[i++] = slab_alloc_item(keg, slab);
2807 if (keg->uk_free <= keg->uk_reserve)
2811 * If the zone is striped we pick a new slab for every
2812 * N allocations. Eliminating this conditional will
2813 * instead pick a new domain for each bucket rather
2814 * than stripe within each bucket. The current option
2815 * produces more fragmentation and requires more cpu
2816 * time but yields better distribution.
2818 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2819 vm_ndomains > 1 && --stripe == 0)
2823 /* Don't block if we allocated any successfully. */
2834 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2836 uma_bucket_t bucket;
2838 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2840 /* Don't wait for buckets, preserve caller's NOVM setting. */
2841 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2845 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2846 MIN(max, bucket->ub_entries), domain, flags);
2849 * Initialize the memory if necessary.
2851 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2854 for (i = 0; i < bucket->ub_cnt; i++)
2855 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2859 * If we couldn't initialize the whole bucket, put the
2860 * rest back onto the freelist.
2862 if (i != bucket->ub_cnt) {
2863 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2864 bucket->ub_cnt - i);
2866 bzero(&bucket->ub_bucket[i],
2867 sizeof(void *) * (bucket->ub_cnt - i));
2873 if (bucket->ub_cnt == 0) {
2874 bucket_free(zone, bucket, udata);
2875 counter_u64_add(zone->uz_fails, 1);
2883 * Allocates a single item from a zone.
2886 * zone The zone to alloc for.
2887 * udata The data to be passed to the constructor.
2888 * domain The domain to allocate from or UMA_ANYDOMAIN.
2889 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2892 * NULL if there is no memory and M_NOWAIT is set
2893 * An item if successful
2897 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2901 return (zone_alloc_item_locked(zone, udata, domain, flags));
2905 * Returns with zone unlocked.
2908 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2915 ZONE_LOCK_ASSERT(zone);
2917 if (zone->uz_max_items > 0) {
2918 if (zone->uz_items >= zone->uz_max_items) {
2919 zone_log_warning(zone);
2920 zone_maxaction(zone);
2921 if (flags & M_NOWAIT) {
2926 zone->uz_sleepers++;
2927 while (zone->uz_items >= zone->uz_max_items)
2928 mtx_sleep(zone, zone->uz_lockptr, PVM,
2930 zone->uz_sleepers--;
2931 if (zone->uz_sleepers > 0 &&
2932 zone->uz_items + 1 < zone->uz_max_items)
2939 if (domain != UMA_ANYDOMAIN) {
2940 /* avoid allocs targeting empty domains */
2941 if (VM_DOMAIN_EMPTY(domain))
2942 domain = UMA_ANYDOMAIN;
2944 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
2948 skipdbg = uma_dbg_zskip(zone, item);
2951 * We have to call both the zone's init (not the keg's init)
2952 * and the zone's ctor. This is because the item is going from
2953 * a keg slab directly to the user, and the user is expecting it
2954 * to be both zone-init'd as well as zone-ctor'd.
2956 if (zone->uz_init != NULL) {
2957 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2958 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
2962 if (zone->uz_ctor != NULL &&
2964 (!skipdbg || zone->uz_ctor != trash_ctor ||
2965 zone->uz_dtor != trash_dtor) &&
2967 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2968 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2973 uma_dbg_alloc(zone, NULL, item);
2976 uma_zero_item(item, zone);
2978 counter_u64_add(zone->uz_allocs, 1);
2979 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
2980 zone->uz_name, zone);
2985 if (zone->uz_max_items > 0) {
2990 counter_u64_add(zone->uz_fails, 1);
2991 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
2992 zone->uz_name, zone);
2998 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3001 uma_bucket_t bucket;
3002 uma_zone_domain_t zdom;
3009 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3010 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3012 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3015 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3016 ("uma_zfree_arg: called with spinlock or critical section held"));
3018 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3021 #ifdef DEBUG_MEMGUARD
3022 if (is_memguard_addr(item)) {
3023 if (zone->uz_dtor != NULL)
3024 zone->uz_dtor(item, zone->uz_size, udata);
3025 if (zone->uz_fini != NULL)
3026 zone->uz_fini(item, zone->uz_size);
3027 memguard_free(item);
3032 skipdbg = uma_dbg_zskip(zone, item);
3033 if (skipdbg == false) {
3034 if (zone->uz_flags & UMA_ZONE_MALLOC)
3035 uma_dbg_free(zone, udata, item);
3037 uma_dbg_free(zone, NULL, item);
3039 if (zone->uz_dtor != NULL && (!skipdbg ||
3040 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3042 if (zone->uz_dtor != NULL)
3044 zone->uz_dtor(item, zone->uz_size, udata);
3047 * The race here is acceptable. If we miss it we'll just have to wait
3048 * a little longer for the limits to be reset.
3050 if (zone->uz_sleepers > 0)
3054 * If possible, free to the per-CPU cache. There are two
3055 * requirements for safe access to the per-CPU cache: (1) the thread
3056 * accessing the cache must not be preempted or yield during access,
3057 * and (2) the thread must not migrate CPUs without switching which
3058 * cache it accesses. We rely on a critical section to prevent
3059 * preemption and migration. We release the critical section in
3060 * order to acquire the zone mutex if we are unable to free to the
3061 * current cache; when we re-acquire the critical section, we must
3062 * detect and handle migration if it has occurred.
3067 cache = &zone->uz_cpu[cpu];
3071 * Try to free into the allocbucket first to give LIFO ordering
3072 * for cache-hot datastructures. Spill over into the freebucket
3073 * if necessary. Alloc will swap them if one runs dry.
3075 bucket = cache->uc_allocbucket;
3076 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3077 bucket = cache->uc_freebucket;
3078 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3079 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3080 ("uma_zfree: Freeing to non free bucket index."));
3081 bucket->ub_bucket[bucket->ub_cnt] = item;
3089 * We must go back the zone, which requires acquiring the zone lock,
3090 * which in turn means we must release and re-acquire the critical
3091 * section. Since the critical section is released, we may be
3092 * preempted or migrate. As such, make sure not to maintain any
3093 * thread-local state specific to the cache from prior to releasing
3094 * the critical section.
3097 if (zone->uz_count == 0 || bucketdisable)
3101 if (ZONE_TRYLOCK(zone) == 0) {
3102 /* Record contention to size the buckets. */
3108 cache = &zone->uz_cpu[cpu];
3110 bucket = cache->uc_freebucket;
3111 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3115 cache->uc_freebucket = NULL;
3116 /* We are no longer associated with this CPU. */
3119 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3120 domain = PCPU_GET(domain);
3121 if (VM_DOMAIN_EMPTY(domain))
3122 domain = UMA_ANYDOMAIN;
3125 zdom = &zone->uz_domain[0];
3127 /* Can we throw this on the zone full list? */
3128 if (bucket != NULL) {
3130 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3131 zone->uz_name, zone, bucket);
3132 /* ub_cnt is pointing to the last free item */
3133 KASSERT(bucket->ub_cnt == bucket->ub_entries,
3134 ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3135 if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3137 bucket_drain(zone, bucket);
3138 bucket_free(zone, bucket, udata);
3141 zone_put_bucket(zone, zdom, bucket, true);
3145 * We bump the uz count when the cache size is insufficient to
3146 * handle the working set.
3148 if (lockfail && zone->uz_count < zone->uz_count_max)
3152 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3153 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3154 zone->uz_name, zone, bucket);
3158 cache = &zone->uz_cpu[cpu];
3159 if (cache->uc_freebucket == NULL &&
3160 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3161 domain == PCPU_GET(domain))) {
3162 cache->uc_freebucket = bucket;
3166 * We lost the race, start over. We have to drop our
3167 * critical section to free the bucket.
3170 bucket_free(zone, bucket, udata);
3175 * If nothing else caught this, we'll just do an internal free.
3178 zone_free_item(zone, item, udata, SKIP_DTOR);
3182 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3185 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3186 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3188 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3191 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3192 ("uma_zfree_domain: called with spinlock or critical section held"));
3194 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3197 zone_free_item(zone, item, udata, SKIP_NONE);
3201 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3208 MPASS(zone->uz_lockptr == &keg->uk_lock);
3209 KEG_LOCK_ASSERT(keg);
3210 MPASS(keg == slab->us_keg);
3212 dom = &keg->uk_domain[slab->us_domain];
3214 /* Do we need to remove from any lists? */
3215 if (slab->us_freecount+1 == keg->uk_ipers) {
3216 LIST_REMOVE(slab, us_link);
3217 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3218 } else if (slab->us_freecount == 0) {
3219 LIST_REMOVE(slab, us_link);
3220 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3223 /* Slab management. */
3224 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3225 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3226 slab->us_freecount++;
3228 /* Keg statistics. */
3233 zone_release(uma_zone_t zone, void **bucket, int cnt)
3243 for (i = 0; i < cnt; i++) {
3245 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3246 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3247 if (zone->uz_flags & UMA_ZONE_HASH) {
3248 slab = hash_sfind(&keg->uk_hash, mem);
3250 mem += keg->uk_pgoff;
3251 slab = (uma_slab_t)mem;
3254 slab = vtoslab((vm_offset_t)item);
3255 MPASS(slab->us_keg == keg);
3257 slab_free_item(zone, slab, item);
3263 * Frees a single item to any zone.
3266 * zone The zone to free to
3267 * item The item we're freeing
3268 * udata User supplied data for the dtor
3269 * skip Skip dtors and finis
3272 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3277 skipdbg = uma_dbg_zskip(zone, item);
3278 if (skip == SKIP_NONE && !skipdbg) {
3279 if (zone->uz_flags & UMA_ZONE_MALLOC)
3280 uma_dbg_free(zone, udata, item);
3282 uma_dbg_free(zone, NULL, item);
3285 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3286 (!skipdbg || zone->uz_dtor != trash_dtor ||
3287 zone->uz_ctor != trash_ctor))
3289 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3291 zone->uz_dtor(item, zone->uz_size, udata);
3293 if (skip < SKIP_FINI && zone->uz_fini)
3294 zone->uz_fini(item, zone->uz_size);
3296 zone->uz_release(zone->uz_arg, &item, 1);
3298 if (skip & SKIP_CNT)
3301 counter_u64_add(zone->uz_frees, 1);
3303 if (zone->uz_max_items > 0) {
3306 if (zone->uz_sleepers > 0 &&
3307 zone->uz_items < zone->uz_max_items)
3315 uma_zone_set_max(uma_zone_t zone, int nitems)
3317 struct uma_bucket_zone *ubz;
3320 * If limit is very low we may need to limit how
3321 * much items are allowed in CPU caches.
3323 ubz = &bucket_zones[0];
3324 for (; ubz->ubz_entries != 0; ubz++)
3325 if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3327 if (ubz == &bucket_zones[0])
3328 nitems = ubz->ubz_entries * 2 * mp_ncpus;
3333 zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3334 if (zone->uz_count_min > zone->uz_count_max)
3335 zone->uz_count_min = zone->uz_count_max;
3336 zone->uz_max_items = nitems;
3344 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3348 zone->uz_bkt_max = nitems;
3356 uma_zone_get_max(uma_zone_t zone)
3361 nitems = zone->uz_max_items;
3369 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3373 zone->uz_warning = warning;
3379 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3383 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3389 uma_zone_get_cur(uma_zone_t zone)
3395 nitems = counter_u64_fetch(zone->uz_allocs) -
3396 counter_u64_fetch(zone->uz_frees);
3399 * See the comment in sysctl_vm_zone_stats() regarding the
3400 * safety of accessing the per-cpu caches. With the zone lock
3401 * held, it is safe, but can potentially result in stale data.
3403 nitems += zone->uz_cpu[i].uc_allocs -
3404 zone->uz_cpu[i].uc_frees;
3408 return (nitems < 0 ? 0 : nitems);
3413 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3419 KASSERT(keg->uk_pages == 0,
3420 ("uma_zone_set_init on non-empty keg"));
3421 keg->uk_init = uminit;
3427 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3433 KASSERT(keg->uk_pages == 0,
3434 ("uma_zone_set_fini on non-empty keg"));
3435 keg->uk_fini = fini;
3441 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3445 KASSERT(zone->uz_keg->uk_pages == 0,
3446 ("uma_zone_set_zinit on non-empty keg"));
3447 zone->uz_init = zinit;
3453 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3457 KASSERT(zone->uz_keg->uk_pages == 0,
3458 ("uma_zone_set_zfini on non-empty keg"));
3459 zone->uz_fini = zfini;
3464 /* XXX uk_freef is not actually used with the zone locked */
3466 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3471 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3473 keg->uk_freef = freef;
3478 /* XXX uk_allocf is not actually used with the zone locked */
3480 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3486 keg->uk_allocf = allocf;
3492 uma_zone_reserve(uma_zone_t zone, int items)
3498 keg->uk_reserve = items;
3504 uma_zone_reserve_kva(uma_zone_t zone, int count)
3512 pages = count / keg->uk_ipers;
3513 if (pages * keg->uk_ipers < count)
3515 pages *= keg->uk_ppera;
3517 #ifdef UMA_MD_SMALL_ALLOC
3518 if (keg->uk_ppera > 1) {
3522 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3529 MPASS(keg->uk_kva == 0);
3532 zone->uz_max_items = pages * keg->uk_ipers;
3533 #ifdef UMA_MD_SMALL_ALLOC
3534 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3536 keg->uk_allocf = noobj_alloc;
3538 keg->uk_flags |= UMA_ZONE_NOFREE;
3546 uma_prealloc(uma_zone_t zone, int items)
3548 struct vm_domainset_iter di;
3552 int aflags, domain, slabs;
3556 slabs = items / keg->uk_ipers;
3557 if (slabs * keg->uk_ipers < items)
3559 while (slabs-- > 0) {
3561 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3564 slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
3567 MPASS(slab->us_keg == keg);
3568 dom = &keg->uk_domain[slab->us_domain];
3569 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
3574 if (vm_domainset_iter_policy(&di, &domain) != 0) {
3576 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
3586 uma_reclaim_locked(bool kmem_danger)
3589 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3590 sx_assert(&uma_drain_lock, SA_XLOCKED);
3592 zone_foreach(zone_drain);
3593 if (vm_page_count_min() || kmem_danger) {
3594 cache_drain_safe(NULL);
3595 zone_foreach(zone_drain);
3599 * Some slabs may have been freed but this zone will be visited early
3600 * we visit again so that we can free pages that are empty once other
3601 * zones are drained. We have to do the same for buckets.
3603 zone_drain(slabzone);
3604 bucket_zone_drain();
3611 sx_xlock(&uma_drain_lock);
3612 uma_reclaim_locked(false);
3613 sx_xunlock(&uma_drain_lock);
3616 static volatile int uma_reclaim_needed;
3619 uma_reclaim_wakeup(void)
3622 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3623 wakeup(uma_reclaim);
3627 uma_reclaim_worker(void *arg __unused)
3631 sx_xlock(&uma_drain_lock);
3632 while (atomic_load_int(&uma_reclaim_needed) == 0)
3633 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3635 sx_xunlock(&uma_drain_lock);
3636 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3637 sx_xlock(&uma_drain_lock);
3638 uma_reclaim_locked(true);
3639 atomic_store_int(&uma_reclaim_needed, 0);
3640 sx_xunlock(&uma_drain_lock);
3641 /* Don't fire more than once per-second. */
3642 pause("umarclslp", hz);
3648 uma_zone_exhausted(uma_zone_t zone)
3653 full = zone->uz_sleepers > 0;
3659 uma_zone_exhausted_nolock(uma_zone_t zone)
3661 return (zone->uz_sleepers > 0);
3665 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3667 struct domainset *policy;
3671 if (domain != UMA_ANYDOMAIN) {
3672 /* avoid allocs targeting empty domains */
3673 if (VM_DOMAIN_EMPTY(domain))
3674 domain = UMA_ANYDOMAIN;
3676 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3679 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3680 DOMAINSET_FIXED(domain);
3681 addr = kmem_malloc_domainset(policy, size, wait);
3683 vsetslab(addr, slab);
3684 slab->us_data = (void *)addr;
3685 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3686 slab->us_size = size;
3687 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3688 pmap_kextract(addr)));
3689 uma_total_inc(size);
3691 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3694 return ((void *)addr);
3698 uma_large_malloc(vm_size_t size, int wait)
3701 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3705 uma_large_free(uma_slab_t slab)
3708 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3709 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3710 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3711 uma_total_dec(slab->us_size);
3712 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3716 uma_zero_item(void *item, uma_zone_t zone)
3719 bzero(item, zone->uz_size);
3726 return (uma_kmem_limit);
3730 uma_set_limit(unsigned long limit)
3733 uma_kmem_limit = limit;
3740 return (uma_kmem_total);
3747 return (uma_kmem_limit - uma_kmem_total);
3751 uma_print_stats(void)
3753 zone_foreach(uma_print_zone);
3757 slab_print(uma_slab_t slab)
3759 printf("slab: keg %p, data %p, freecount %d\n",
3760 slab->us_keg, slab->us_data, slab->us_freecount);
3764 cache_print(uma_cache_t cache)
3766 printf("alloc: %p(%d), free: %p(%d)\n",
3767 cache->uc_allocbucket,
3768 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3769 cache->uc_freebucket,
3770 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3774 uma_print_keg(uma_keg_t keg)
3780 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3782 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3783 keg->uk_ipers, keg->uk_ppera,
3784 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3786 for (i = 0; i < vm_ndomains; i++) {
3787 dom = &keg->uk_domain[i];
3788 printf("Part slabs:\n");
3789 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3791 printf("Free slabs:\n");
3792 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3794 printf("Full slabs:\n");
3795 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3801 uma_print_zone(uma_zone_t zone)
3806 printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3807 zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3809 if (zone->uz_lockptr != &zone->uz_lock)
3810 uma_print_keg(zone->uz_keg);
3812 cache = &zone->uz_cpu[i];
3813 printf("CPU %d Cache:\n", i);
3820 * Generate statistics across both the zone and its per-cpu cache's. Return
3821 * desired statistics if the pointer is non-NULL for that statistic.
3823 * Note: does not update the zone statistics, as it can't safely clear the
3824 * per-CPU cache statistic.
3826 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3827 * safe from off-CPU; we should modify the caches to track this information
3828 * directly so that we don't have to.
3831 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3832 uint64_t *freesp, uint64_t *sleepsp)
3835 uint64_t allocs, frees, sleeps;
3838 allocs = frees = sleeps = 0;
3841 cache = &z->uz_cpu[cpu];
3842 if (cache->uc_allocbucket != NULL)
3843 cachefree += cache->uc_allocbucket->ub_cnt;
3844 if (cache->uc_freebucket != NULL)
3845 cachefree += cache->uc_freebucket->ub_cnt;
3846 allocs += cache->uc_allocs;
3847 frees += cache->uc_frees;
3849 allocs += counter_u64_fetch(z->uz_allocs);
3850 frees += counter_u64_fetch(z->uz_frees);
3851 sleeps += z->uz_sleeps;
3852 if (cachefreep != NULL)
3853 *cachefreep = cachefree;
3854 if (allocsp != NULL)
3858 if (sleepsp != NULL)
3864 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3871 rw_rlock(&uma_rwlock);
3872 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3873 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3876 LIST_FOREACH(z, &uma_cachezones, uz_link)
3879 rw_runlock(&uma_rwlock);
3880 return (sysctl_handle_int(oidp, &count, 0, req));
3884 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
3885 struct uma_percpu_stat *ups, bool internal)
3887 uma_zone_domain_t zdom;
3892 for (i = 0; i < vm_ndomains; i++) {
3893 zdom = &z->uz_domain[i];
3894 uth->uth_zone_free += zdom->uzd_nitems;
3896 uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
3897 uth->uth_frees = counter_u64_fetch(z->uz_frees);
3898 uth->uth_fails = counter_u64_fetch(z->uz_fails);
3899 uth->uth_sleeps = z->uz_sleeps;
3901 * While it is not normally safe to access the cache
3902 * bucket pointers while not on the CPU that owns the
3903 * cache, we only allow the pointers to be exchanged
3904 * without the zone lock held, not invalidated, so
3905 * accept the possible race associated with bucket
3906 * exchange during monitoring.
3908 for (i = 0; i < mp_maxid + 1; i++) {
3909 bzero(&ups[i], sizeof(*ups));
3910 if (internal || CPU_ABSENT(i))
3912 cache = &z->uz_cpu[i];
3913 if (cache->uc_allocbucket != NULL)
3914 ups[i].ups_cache_free +=
3915 cache->uc_allocbucket->ub_cnt;
3916 if (cache->uc_freebucket != NULL)
3917 ups[i].ups_cache_free +=
3918 cache->uc_freebucket->ub_cnt;
3919 ups[i].ups_allocs = cache->uc_allocs;
3920 ups[i].ups_frees = cache->uc_frees;
3925 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3927 struct uma_stream_header ush;
3928 struct uma_type_header uth;
3929 struct uma_percpu_stat *ups;
3933 int count, error, i;
3935 error = sysctl_wire_old_buffer(req, 0);
3938 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3939 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3940 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3943 rw_rlock(&uma_rwlock);
3944 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3945 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3949 LIST_FOREACH(z, &uma_cachezones, uz_link)
3953 * Insert stream header.
3955 bzero(&ush, sizeof(ush));
3956 ush.ush_version = UMA_STREAM_VERSION;
3957 ush.ush_maxcpus = (mp_maxid + 1);
3958 ush.ush_count = count;
3959 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3961 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3962 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3963 bzero(&uth, sizeof(uth));
3965 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3966 uth.uth_align = kz->uk_align;
3967 uth.uth_size = kz->uk_size;
3968 uth.uth_rsize = kz->uk_rsize;
3969 if (z->uz_max_items > 0)
3970 uth.uth_pages = (z->uz_items / kz->uk_ipers) *
3973 uth.uth_pages = kz->uk_pages;
3974 uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
3976 uth.uth_limit = z->uz_max_items;
3977 uth.uth_keg_free = z->uz_keg->uk_free;
3980 * A zone is secondary is it is not the first entry
3981 * on the keg's zone list.
3983 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3984 (LIST_FIRST(&kz->uk_zones) != z))
3985 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3986 uma_vm_zone_stats(&uth, z, &sbuf, ups,
3987 kz->uk_flags & UMA_ZFLAG_INTERNAL);
3989 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3990 for (i = 0; i < mp_maxid + 1; i++)
3991 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
3994 LIST_FOREACH(z, &uma_cachezones, uz_link) {
3995 bzero(&uth, sizeof(uth));
3997 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3998 uth.uth_size = z->uz_size;
3999 uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
4001 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4002 for (i = 0; i < mp_maxid + 1; i++)
4003 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4006 rw_runlock(&uma_rwlock);
4007 error = sbuf_finish(&sbuf);
4014 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4016 uma_zone_t zone = *(uma_zone_t *)arg1;
4019 max = uma_zone_get_max(zone);
4020 error = sysctl_handle_int(oidp, &max, 0, req);
4021 if (error || !req->newptr)
4024 uma_zone_set_max(zone, max);
4030 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4032 uma_zone_t zone = *(uma_zone_t *)arg1;
4035 cur = uma_zone_get_cur(zone);
4036 return (sysctl_handle_int(oidp, &cur, 0, req));
4041 uma_dbg_getslab(uma_zone_t zone, void *item)
4047 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4048 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4049 slab = vtoslab((vm_offset_t)mem);
4052 * It is safe to return the slab here even though the
4053 * zone is unlocked because the item's allocation state
4054 * essentially holds a reference.
4056 if (zone->uz_lockptr == &zone->uz_lock)
4060 if (keg->uk_flags & UMA_ZONE_HASH)
4061 slab = hash_sfind(&keg->uk_hash, mem);
4063 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4071 uma_dbg_zskip(uma_zone_t zone, void *mem)
4074 if (zone->uz_lockptr == &zone->uz_lock)
4077 return (uma_dbg_kskip(zone->uz_keg, mem));
4081 uma_dbg_kskip(uma_keg_t keg, void *mem)
4085 if (dbg_divisor == 0)
4088 if (dbg_divisor == 1)
4091 idx = (uintptr_t)mem >> PAGE_SHIFT;
4092 if (keg->uk_ipers > 1) {
4093 idx *= keg->uk_ipers;
4094 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4097 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4098 counter_u64_add(uma_skip_cnt, 1);
4101 counter_u64_add(uma_dbg_cnt, 1);
4107 * Set up the slab's freei data such that uma_dbg_free can function.
4111 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4117 slab = uma_dbg_getslab(zone, item);
4119 panic("uma: item %p did not belong to zone %s\n",
4120 item, zone->uz_name);
4123 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4125 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4126 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4127 item, zone, zone->uz_name, slab, freei);
4128 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4134 * Verifies freed addresses. Checks for alignment, valid slab membership
4135 * and duplicate frees.
4139 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4145 slab = uma_dbg_getslab(zone, item);
4147 panic("uma: Freed item %p did not belong to zone %s\n",
4148 item, zone->uz_name);
4151 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4153 if (freei >= keg->uk_ipers)
4154 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4155 item, zone, zone->uz_name, slab, freei);
4157 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4158 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4159 item, zone, zone->uz_name, slab, freei);
4161 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4162 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4163 item, zone, zone->uz_name, slab, freei);
4165 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4167 #endif /* INVARIANTS */
4170 DB_SHOW_COMMAND(uma, db_show_uma)
4174 uint64_t allocs, frees, sleeps;
4178 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4179 "Free", "Requests", "Sleeps", "Bucket");
4180 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4181 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4182 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4183 allocs = counter_u64_fetch(z->uz_allocs);
4184 frees = counter_u64_fetch(z->uz_frees);
4185 sleeps = z->uz_sleeps;
4188 uma_zone_sumstat(z, &cachefree, &allocs,
4190 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4191 (LIST_FIRST(&kz->uk_zones) != z)))
4192 cachefree += kz->uk_free;
4193 for (i = 0; i < vm_ndomains; i++)
4194 cachefree += z->uz_domain[i].uzd_nitems;
4196 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4197 z->uz_name, (uintmax_t)kz->uk_size,
4198 (intmax_t)(allocs - frees), cachefree,
4199 (uintmax_t)allocs, sleeps, z->uz_count);
4206 DB_SHOW_COMMAND(umacache, db_show_umacache)
4209 uint64_t allocs, frees;
4213 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4214 "Requests", "Bucket");
4215 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4216 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4217 for (i = 0; i < vm_ndomains; i++)
4218 cachefree += z->uz_domain[i].uzd_nitems;
4219 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4220 z->uz_name, (uintmax_t)z->uz_size,
4221 (intmax_t)(allocs - frees), cachefree,
4222 (uintmax_t)allocs, z->uz_count);