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;
148 * kmem soft limit, initialized by uma_set_limit(). Ensure that early
149 * allocations don't trigger a wakeup of the reclaim thread.
151 static unsigned long uma_kmem_limit = LONG_MAX;
152 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
153 "UMA kernel memory soft limit");
154 static unsigned long uma_kmem_total;
155 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
156 "UMA kernel memory usage");
158 /* Is the VM done starting up? */
159 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
160 BOOT_RUNNING } booted = BOOT_COLD;
163 * This is the handle used to schedule events that need to happen
164 * outside of the allocation fast path.
166 static struct callout uma_callout;
167 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
170 * This structure is passed as the zone ctor arg so that I don't have to create
171 * a special allocation function just for zones.
173 struct uma_zctor_args {
188 struct uma_kctor_args {
197 struct uma_bucket_zone {
200 int ubz_entries; /* Number of items it can hold. */
201 int ubz_maxsize; /* Maximum allocation size per-item. */
205 * Compute the actual number of bucket entries to pack them in power
206 * of two sizes for more efficient space utilization.
208 #define BUCKET_SIZE(n) \
209 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
211 #define BUCKET_MAX BUCKET_SIZE(256)
213 struct uma_bucket_zone bucket_zones[] = {
214 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
215 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
216 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
217 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
218 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
219 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
220 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
221 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
222 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
227 * Flags and enumerations to be passed to internal functions.
229 enum zfreeskip { SKIP_NONE = 0, SKIP_DTOR, SKIP_FINI };
231 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
235 int uma_startup_count(int);
236 void uma_startup(void *, int);
237 void uma_startup1(void);
238 void uma_startup2(void);
240 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
241 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
242 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
243 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
244 static void page_free(void *, vm_size_t, uint8_t);
245 static void pcpu_page_free(void *, vm_size_t, uint8_t);
246 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
247 static void cache_drain(uma_zone_t);
248 static void bucket_drain(uma_zone_t, uma_bucket_t);
249 static void bucket_cache_drain(uma_zone_t zone);
250 static int keg_ctor(void *, int, void *, int);
251 static void keg_dtor(void *, int, void *);
252 static int zone_ctor(void *, int, void *, int);
253 static void zone_dtor(void *, int, void *);
254 static int zero_init(void *, int, int);
255 static void keg_small_init(uma_keg_t keg);
256 static void keg_large_init(uma_keg_t keg);
257 static void zone_foreach(void (*zfunc)(uma_zone_t));
258 static void zone_timeout(uma_zone_t zone);
259 static int hash_alloc(struct uma_hash *, u_int);
260 static int hash_expand(struct uma_hash *, struct uma_hash *);
261 static void hash_free(struct uma_hash *hash);
262 static void uma_timeout(void *);
263 static void uma_startup3(void);
264 static void *zone_alloc_item(uma_zone_t, void *, int, int);
265 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
266 static void bucket_enable(void);
267 static void bucket_init(void);
268 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
269 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
270 static void bucket_zone_drain(void);
271 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
272 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
273 static uma_slab_t zone_fetch_slab_multi(uma_zone_t, uma_keg_t, int, int);
274 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
275 static void slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item);
276 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
277 uma_fini fini, int align, uint32_t flags);
278 static int zone_import(uma_zone_t, void **, int, int, int);
279 static void zone_release(uma_zone_t, void **, int);
280 static void uma_zero_item(void *, uma_zone_t);
282 void uma_print_zone(uma_zone_t);
283 void uma_print_stats(void);
284 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
285 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
288 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
289 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
290 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
291 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
293 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
294 "Memory allocation debugging");
296 static u_int dbg_divisor = 1;
297 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
298 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
299 "Debug & thrash every this item in memory allocator");
301 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
302 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
303 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
304 &uma_dbg_cnt, "memory items debugged");
305 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
306 &uma_skip_cnt, "memory items skipped, not debugged");
309 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
311 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
312 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
314 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
315 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
317 static int zone_warnings = 1;
318 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
319 "Warn when UMA zones becomes full");
321 /* Adjust bytes under management by UMA. */
323 uma_total_dec(unsigned long size)
326 atomic_subtract_long(&uma_kmem_total, size);
330 uma_total_inc(unsigned long size)
333 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
334 uma_reclaim_wakeup();
338 * This routine checks to see whether or not it's safe to enable buckets.
343 bucketdisable = vm_page_count_min();
347 * Initialize bucket_zones, the array of zones of buckets of various sizes.
349 * For each zone, calculate the memory required for each bucket, consisting
350 * of the header and an array of pointers.
355 struct uma_bucket_zone *ubz;
358 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
359 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
360 size += sizeof(void *) * ubz->ubz_entries;
361 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
362 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
363 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
368 * Given a desired number of entries for a bucket, return the zone from which
369 * to allocate the bucket.
371 static struct uma_bucket_zone *
372 bucket_zone_lookup(int entries)
374 struct uma_bucket_zone *ubz;
376 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
377 if (ubz->ubz_entries >= entries)
384 bucket_select(int size)
386 struct uma_bucket_zone *ubz;
388 ubz = &bucket_zones[0];
389 if (size > ubz->ubz_maxsize)
390 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
392 for (; ubz->ubz_entries != 0; ubz++)
393 if (ubz->ubz_maxsize < size)
396 return (ubz->ubz_entries);
400 bucket_alloc(uma_zone_t zone, void *udata, int flags)
402 struct uma_bucket_zone *ubz;
406 * This is to stop us from allocating per cpu buckets while we're
407 * running out of vm.boot_pages. Otherwise, we would exhaust the
408 * boot pages. This also prevents us from allocating buckets in
409 * low memory situations.
414 * To limit bucket recursion we store the original zone flags
415 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
416 * NOVM flag to persist even through deep recursions. We also
417 * store ZFLAG_BUCKET once we have recursed attempting to allocate
418 * a bucket for a bucket zone so we do not allow infinite bucket
419 * recursion. This cookie will even persist to frees of unused
420 * buckets via the allocation path or bucket allocations in the
423 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
424 udata = (void *)(uintptr_t)zone->uz_flags;
426 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
428 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
430 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
432 ubz = bucket_zone_lookup(zone->uz_count);
433 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
435 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
438 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
441 bucket->ub_entries = ubz->ubz_entries;
448 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
450 struct uma_bucket_zone *ubz;
452 KASSERT(bucket->ub_cnt == 0,
453 ("bucket_free: Freeing a non free bucket."));
454 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
455 udata = (void *)(uintptr_t)zone->uz_flags;
456 ubz = bucket_zone_lookup(bucket->ub_entries);
457 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
461 bucket_zone_drain(void)
463 struct uma_bucket_zone *ubz;
465 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
466 zone_drain(ubz->ubz_zone);
470 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
474 ZONE_LOCK_ASSERT(zone);
476 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
477 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
478 LIST_REMOVE(bucket, ub_link);
479 zdom->uzd_nitems -= bucket->ub_cnt;
480 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
481 zdom->uzd_imin = zdom->uzd_nitems;
487 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
491 ZONE_LOCK_ASSERT(zone);
493 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
494 zdom->uzd_nitems += bucket->ub_cnt;
495 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
496 zdom->uzd_imax = zdom->uzd_nitems;
500 zone_log_warning(uma_zone_t zone)
502 static const struct timeval warninterval = { 300, 0 };
504 if (!zone_warnings || zone->uz_warning == NULL)
507 if (ratecheck(&zone->uz_ratecheck, &warninterval))
508 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
512 zone_maxaction(uma_zone_t zone)
515 if (zone->uz_maxaction.ta_func != NULL)
516 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
520 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
524 LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
525 kegfn(klink->kl_keg);
529 * Routine called by timeout which is used to fire off some time interval
530 * based calculations. (stats, hash size, etc.)
539 uma_timeout(void *unused)
542 zone_foreach(zone_timeout);
544 /* Reschedule this event */
545 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
549 * Update the working set size estimate for the zone's bucket cache.
550 * The constants chosen here are somewhat arbitrary. With an update period of
551 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
555 zone_domain_update_wss(uma_zone_domain_t zdom)
559 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
560 wss = zdom->uzd_imax - zdom->uzd_imin;
561 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
562 zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
566 * Routine to perform timeout driven calculations. This expands the
567 * hashes and does per cpu statistics aggregation.
572 keg_timeout(uma_keg_t keg)
578 * Expand the keg hash table.
580 * This is done if the number of slabs is larger than the hash size.
581 * What I'm trying to do here is completely reduce collisions. This
582 * may be a little aggressive. Should I allow for two collisions max?
584 if (keg->uk_flags & UMA_ZONE_HASH &&
585 (slabs = keg->uk_pages / keg->uk_ppera) >
586 keg->uk_hash.uh_hashsize) {
587 struct uma_hash newhash;
588 struct uma_hash oldhash;
592 * This is so involved because allocating and freeing
593 * while the keg lock is held will lead to deadlock.
594 * I have to do everything in stages and check for
598 ret = hash_alloc(&newhash, 1 << fls(slabs));
601 if (hash_expand(&keg->uk_hash, &newhash)) {
602 oldhash = keg->uk_hash;
603 keg->uk_hash = newhash;
616 zone_timeout(uma_zone_t zone)
620 zone_foreach_keg(zone, &keg_timeout);
623 for (i = 0; i < vm_ndomains; i++)
624 zone_domain_update_wss(&zone->uz_domain[i]);
629 * Allocate and zero fill the next sized hash table from the appropriate
633 * hash A new hash structure with the old hash size in uh_hashsize
636 * 1 on success and 0 on failure.
639 hash_alloc(struct uma_hash *hash, u_int size)
643 KASSERT(powerof2(size), ("hash size must be power of 2"));
644 if (size > UMA_HASH_SIZE_INIT) {
645 hash->uh_hashsize = size;
646 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
647 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
648 M_UMAHASH, M_NOWAIT);
650 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
651 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
652 UMA_ANYDOMAIN, M_WAITOK);
653 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
655 if (hash->uh_slab_hash) {
656 bzero(hash->uh_slab_hash, alloc);
657 hash->uh_hashmask = hash->uh_hashsize - 1;
665 * Expands the hash table for HASH zones. This is done from zone_timeout
666 * to reduce collisions. This must not be done in the regular allocation
667 * path, otherwise, we can recurse on the vm while allocating pages.
670 * oldhash The hash you want to expand
671 * newhash The hash structure for the new table
679 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
685 if (!newhash->uh_slab_hash)
688 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
692 * I need to investigate hash algorithms for resizing without a
696 for (idx = 0; idx < oldhash->uh_hashsize; idx++)
697 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
698 slab = SLIST_FIRST(&oldhash->uh_slab_hash[idx]);
699 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[idx], us_hlink);
700 hval = UMA_HASH(newhash, slab->us_data);
701 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
709 * Free the hash bucket to the appropriate backing store.
712 * slab_hash The hash bucket we're freeing
713 * hashsize The number of entries in that hash bucket
719 hash_free(struct uma_hash *hash)
721 if (hash->uh_slab_hash == NULL)
723 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
724 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
726 free(hash->uh_slab_hash, M_UMAHASH);
730 * Frees all outstanding items in a bucket
733 * zone The zone to free to, must be unlocked.
734 * bucket The free/alloc bucket with items, cpu queue must be locked.
741 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
749 for (i = 0; i < bucket->ub_cnt; i++)
750 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
751 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
756 * Drains the per cpu caches for a zone.
758 * NOTE: This may only be called while the zone is being turn down, and not
759 * during normal operation. This is necessary in order that we do not have
760 * to migrate CPUs to drain the per-CPU caches.
763 * zone The zone to drain, must be unlocked.
769 cache_drain(uma_zone_t zone)
775 * XXX: It is safe to not lock the per-CPU caches, because we're
776 * tearing down the zone anyway. I.e., there will be no further use
777 * of the caches at this point.
779 * XXX: It would good to be able to assert that the zone is being
780 * torn down to prevent improper use of cache_drain().
782 * XXX: We lock the zone before passing into bucket_cache_drain() as
783 * it is used elsewhere. Should the tear-down path be made special
784 * there in some form?
787 cache = &zone->uz_cpu[cpu];
788 bucket_drain(zone, cache->uc_allocbucket);
789 bucket_drain(zone, cache->uc_freebucket);
790 if (cache->uc_allocbucket != NULL)
791 bucket_free(zone, cache->uc_allocbucket, NULL);
792 if (cache->uc_freebucket != NULL)
793 bucket_free(zone, cache->uc_freebucket, NULL);
794 cache->uc_allocbucket = cache->uc_freebucket = NULL;
797 bucket_cache_drain(zone);
802 cache_shrink(uma_zone_t zone)
805 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
809 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
814 cache_drain_safe_cpu(uma_zone_t zone)
820 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
826 if (zone->uz_flags & UMA_ZONE_NUMA)
827 domain = PCPU_GET(domain);
830 cache = &zone->uz_cpu[curcpu];
831 if (cache->uc_allocbucket) {
832 if (cache->uc_allocbucket->ub_cnt != 0)
833 zone_put_bucket(zone, &zone->uz_domain[domain],
834 cache->uc_allocbucket, false);
836 b1 = cache->uc_allocbucket;
837 cache->uc_allocbucket = NULL;
839 if (cache->uc_freebucket) {
840 if (cache->uc_freebucket->ub_cnt != 0)
841 zone_put_bucket(zone, &zone->uz_domain[domain],
842 cache->uc_freebucket, false);
844 b2 = cache->uc_freebucket;
845 cache->uc_freebucket = NULL;
850 bucket_free(zone, b1, NULL);
852 bucket_free(zone, b2, NULL);
856 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
857 * This is an expensive call because it needs to bind to all CPUs
858 * one by one and enter a critical section on each of them in order
859 * to safely access their cache buckets.
860 * Zone lock must not be held on call this function.
863 cache_drain_safe(uma_zone_t zone)
868 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
873 zone_foreach(cache_shrink);
876 thread_lock(curthread);
877 sched_bind(curthread, cpu);
878 thread_unlock(curthread);
881 cache_drain_safe_cpu(zone);
883 zone_foreach(cache_drain_safe_cpu);
885 thread_lock(curthread);
886 sched_unbind(curthread);
887 thread_unlock(curthread);
891 * Drain the cached buckets from a zone. Expects a locked zone on entry.
894 bucket_cache_drain(uma_zone_t zone)
896 uma_zone_domain_t zdom;
901 * Drain the bucket queues and free the buckets.
903 for (i = 0; i < vm_ndomains; i++) {
904 zdom = &zone->uz_domain[i];
905 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
908 bucket_drain(zone, bucket);
909 bucket_free(zone, bucket, NULL);
915 * Shrink further bucket sizes. Price of single zone lock collision
916 * is probably lower then price of global cache drain.
918 if (zone->uz_count > zone->uz_count_min)
923 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
929 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
930 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
933 flags = slab->us_flags;
935 if (keg->uk_fini != NULL) {
936 for (i--; i > -1; i--)
939 * trash_fini implies that dtor was trash_dtor. trash_fini
940 * would check that memory hasn't been modified since free,
941 * which executed trash_dtor.
942 * That's why we need to run uma_dbg_kskip() check here,
943 * albeit we don't make skip check for other init/fini
946 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
947 keg->uk_fini != trash_fini)
949 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
952 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
953 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
954 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
955 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
959 * Frees pages from a keg back to the system. This is done on demand from
960 * the pageout daemon.
965 keg_drain(uma_keg_t keg)
967 struct slabhead freeslabs = { 0 };
969 uma_slab_t slab, tmp;
973 * We don't want to take pages from statically allocated kegs at this
976 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
979 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
980 keg->uk_name, keg, keg->uk_free);
982 if (keg->uk_free == 0)
985 for (i = 0; i < vm_ndomains; i++) {
986 dom = &keg->uk_domain[i];
987 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
988 /* We have nowhere to free these to. */
989 if (slab->us_flags & UMA_SLAB_BOOT)
992 LIST_REMOVE(slab, us_link);
993 keg->uk_pages -= keg->uk_ppera;
994 keg->uk_free -= keg->uk_ipers;
996 if (keg->uk_flags & UMA_ZONE_HASH)
997 UMA_HASH_REMOVE(&keg->uk_hash, slab,
1000 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1007 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1008 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1009 keg_free_slab(keg, slab, keg->uk_ipers);
1014 zone_drain_wait(uma_zone_t zone, int waitok)
1018 * Set draining to interlock with zone_dtor() so we can release our
1019 * locks as we go. Only dtor() should do a WAITOK call since it
1020 * is the only call that knows the structure will still be available
1024 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1025 if (waitok == M_NOWAIT)
1027 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1029 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1030 bucket_cache_drain(zone);
1033 * The DRAINING flag protects us from being freed while
1034 * we're running. Normally the uma_rwlock would protect us but we
1035 * must be able to release and acquire the right lock for each keg.
1037 zone_foreach_keg(zone, &keg_drain);
1039 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1046 zone_drain(uma_zone_t zone)
1049 zone_drain_wait(zone, M_NOWAIT);
1053 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1054 * If the allocation was successful, the keg lock will be held upon return,
1055 * otherwise the keg will be left unlocked.
1058 * flags Wait flags for the item initialization routine
1059 * aflags Wait flags for the slab allocation
1062 * The slab that was allocated or NULL if there is no memory and the
1063 * caller specified M_NOWAIT.
1066 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1076 KASSERT(domain >= 0 && domain < vm_ndomains,
1077 ("keg_alloc_slab: domain %d out of range", domain));
1078 mtx_assert(&keg->uk_lock, MA_OWNED);
1080 allocf = keg->uk_allocf;
1085 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1086 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, aflags);
1092 * This reproduces the old vm_zone behavior of zero filling pages the
1093 * first time they are added to a zone.
1095 * Malloced items are zeroed in uma_zalloc.
1098 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1103 if (keg->uk_flags & UMA_ZONE_NODUMP)
1106 /* zone is passed for legacy reasons. */
1107 size = keg->uk_ppera * PAGE_SIZE;
1108 mem = allocf(zone, size, domain, &sflags, aflags);
1110 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1111 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1115 uma_total_inc(size);
1117 /* Point the slab into the allocated memory */
1118 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1119 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1121 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1122 for (i = 0; i < keg->uk_ppera; i++)
1123 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1126 slab->us_data = mem;
1127 slab->us_freecount = keg->uk_ipers;
1128 slab->us_flags = sflags;
1129 slab->us_domain = domain;
1130 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1132 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1135 if (keg->uk_init != NULL) {
1136 for (i = 0; i < keg->uk_ipers; i++)
1137 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1138 keg->uk_size, flags) != 0)
1140 if (i != keg->uk_ipers) {
1141 keg_free_slab(keg, slab, i);
1148 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1149 slab, keg->uk_name, keg);
1151 if (keg->uk_flags & UMA_ZONE_HASH)
1152 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1154 keg->uk_pages += keg->uk_ppera;
1155 keg->uk_free += keg->uk_ipers;
1162 * This function is intended to be used early on in place of page_alloc() so
1163 * that we may use the boot time page cache to satisfy allocations before
1167 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1174 keg = zone_first_keg(zone);
1177 * If we are in BOOT_BUCKETS or higher, than switch to real
1178 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1184 case BOOT_PAGEALLOC:
1185 if (keg->uk_ppera > 1)
1189 #ifdef UMA_MD_SMALL_ALLOC
1190 keg->uk_allocf = (keg->uk_ppera > 1) ?
1191 page_alloc : uma_small_alloc;
1193 keg->uk_allocf = page_alloc;
1195 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1199 * Check our small startup cache to see if it has pages remaining.
1201 pages = howmany(bytes, PAGE_SIZE);
1202 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1203 if (pages > boot_pages)
1204 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1206 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1210 boot_pages -= pages;
1211 bootmem += pages * PAGE_SIZE;
1212 *pflag = UMA_SLAB_BOOT;
1218 * Allocates a number of pages from the system
1221 * bytes The number of bytes requested
1222 * wait Shall we wait?
1225 * A pointer to the alloced memory or possibly
1226 * NULL if M_NOWAIT is set.
1229 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1232 void *p; /* Returned page */
1234 *pflag = UMA_SLAB_KERNEL;
1235 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1241 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1244 struct pglist alloctail;
1245 vm_offset_t addr, zkva;
1247 vm_page_t p, p_next;
1252 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1254 TAILQ_INIT(&alloctail);
1255 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1256 malloc2vm_flags(wait);
1257 *pflag = UMA_SLAB_KERNEL;
1258 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1259 if (CPU_ABSENT(cpu)) {
1260 p = vm_page_alloc(NULL, 0, flags);
1263 p = vm_page_alloc(NULL, 0, flags);
1265 pc = pcpu_find(cpu);
1266 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1267 if (__predict_false(p == NULL))
1268 p = vm_page_alloc(NULL, 0, flags);
1271 if (__predict_false(p == NULL))
1273 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1275 if ((addr = kva_alloc(bytes)) == 0)
1278 TAILQ_FOREACH(p, &alloctail, listq) {
1279 pmap_qenter(zkva, &p, 1);
1282 return ((void*)addr);
1284 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1285 vm_page_unwire_noq(p);
1292 * Allocates a number of pages from within an object
1295 * bytes The number of bytes requested
1296 * wait Shall we wait?
1299 * A pointer to the alloced memory or possibly
1300 * NULL if M_NOWAIT is set.
1303 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1306 TAILQ_HEAD(, vm_page) alloctail;
1308 vm_offset_t retkva, zkva;
1309 vm_page_t p, p_next;
1312 TAILQ_INIT(&alloctail);
1313 keg = zone_first_keg(zone);
1315 npages = howmany(bytes, PAGE_SIZE);
1316 while (npages > 0) {
1317 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1318 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1319 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1323 * Since the page does not belong to an object, its
1326 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1331 * Page allocation failed, free intermediate pages and
1334 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1335 vm_page_unwire_noq(p);
1340 *flags = UMA_SLAB_PRIV;
1341 zkva = keg->uk_kva +
1342 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1344 TAILQ_FOREACH(p, &alloctail, listq) {
1345 pmap_qenter(zkva, &p, 1);
1349 return ((void *)retkva);
1353 * Frees a number of pages to the system
1356 * mem A pointer to the memory to be freed
1357 * size The size of the memory being freed
1358 * flags The original p->us_flags field
1364 page_free(void *mem, vm_size_t size, uint8_t flags)
1367 if ((flags & UMA_SLAB_KERNEL) == 0)
1368 panic("UMA: page_free used with invalid flags %x", flags);
1370 kmem_free((vm_offset_t)mem, size);
1374 * Frees pcpu zone allocations
1377 * mem A pointer to the memory to be freed
1378 * size The size of the memory being freed
1379 * flags The original p->us_flags field
1385 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1387 vm_offset_t sva, curva;
1391 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1392 sva = (vm_offset_t)mem;
1393 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1394 paddr = pmap_kextract(curva);
1395 m = PHYS_TO_VM_PAGE(paddr);
1396 vm_page_unwire_noq(m);
1399 pmap_qremove(sva, size >> PAGE_SHIFT);
1400 kva_free(sva, size);
1405 * Zero fill initializer
1407 * Arguments/Returns follow uma_init specifications
1410 zero_init(void *mem, int size, int flags)
1417 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1420 * keg The zone we should initialize
1426 keg_small_init(uma_keg_t keg)
1434 if (keg->uk_flags & UMA_ZONE_PCPU) {
1435 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1437 slabsize = UMA_PCPU_ALLOC_SIZE;
1438 keg->uk_ppera = ncpus;
1440 slabsize = UMA_SLAB_SIZE;
1445 * Calculate the size of each allocation (rsize) according to
1446 * alignment. If the requested size is smaller than we have
1447 * allocation bits for we round it up.
1449 rsize = keg->uk_size;
1450 if (rsize < slabsize / SLAB_SETSIZE)
1451 rsize = slabsize / SLAB_SETSIZE;
1452 if (rsize & keg->uk_align)
1453 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1454 keg->uk_rsize = rsize;
1456 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1457 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1458 ("%s: size %u too large", __func__, keg->uk_rsize));
1460 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1463 shsize = sizeof(struct uma_slab);
1465 if (rsize <= slabsize - shsize)
1466 keg->uk_ipers = (slabsize - shsize) / rsize;
1468 /* Handle special case when we have 1 item per slab, so
1469 * alignment requirement can be relaxed. */
1470 KASSERT(keg->uk_size <= slabsize - shsize,
1471 ("%s: size %u greater than slab", __func__, keg->uk_size));
1474 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1475 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1477 memused = keg->uk_ipers * rsize + shsize;
1478 wastedspace = slabsize - memused;
1481 * We can't do OFFPAGE if we're internal or if we've been
1482 * asked to not go to the VM for buckets. If we do this we
1483 * may end up going to the VM for slabs which we do not
1484 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1485 * of UMA_ZONE_VM, which clearly forbids it.
1487 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1488 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1492 * See if using an OFFPAGE slab will limit our waste. Only do
1493 * this if it permits more items per-slab.
1495 * XXX We could try growing slabsize to limit max waste as well.
1496 * Historically this was not done because the VM could not
1497 * efficiently handle contiguous allocations.
1499 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1500 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1501 keg->uk_ipers = slabsize / keg->uk_rsize;
1502 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1503 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1504 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1505 "keg: %s(%p), calculated wastedspace = %d, "
1506 "maximum wasted space allowed = %d, "
1507 "calculated ipers = %d, "
1508 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1509 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1510 slabsize - keg->uk_ipers * keg->uk_rsize);
1511 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1514 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1515 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1516 keg->uk_flags |= UMA_ZONE_HASH;
1520 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1521 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1525 * keg The keg we should initialize
1531 keg_large_init(uma_keg_t keg)
1535 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1536 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1537 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1538 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1539 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1541 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1543 keg->uk_rsize = keg->uk_size;
1545 /* Check whether we have enough space to not do OFFPAGE. */
1546 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0) {
1547 shsize = sizeof(struct uma_slab);
1548 if (shsize & UMA_ALIGN_PTR)
1549 shsize = (shsize & ~UMA_ALIGN_PTR) +
1550 (UMA_ALIGN_PTR + 1);
1552 if (PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < shsize) {
1554 * We can't do OFFPAGE if we're internal, in which case
1555 * we need an extra page per allocation to contain the
1558 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1559 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1565 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1566 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1567 keg->uk_flags |= UMA_ZONE_HASH;
1571 keg_cachespread_init(uma_keg_t keg)
1578 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1579 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1581 alignsize = keg->uk_align + 1;
1582 rsize = keg->uk_size;
1584 * We want one item to start on every align boundary in a page. To
1585 * do this we will span pages. We will also extend the item by the
1586 * size of align if it is an even multiple of align. Otherwise, it
1587 * would fall on the same boundary every time.
1589 if (rsize & keg->uk_align)
1590 rsize = (rsize & ~keg->uk_align) + alignsize;
1591 if ((rsize & alignsize) == 0)
1593 trailer = rsize - keg->uk_size;
1594 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1595 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1596 keg->uk_rsize = rsize;
1597 keg->uk_ppera = pages;
1598 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1599 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1600 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1601 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1606 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1607 * the keg onto the global keg list.
1609 * Arguments/Returns follow uma_ctor specifications
1610 * udata Actually uma_kctor_args
1613 keg_ctor(void *mem, int size, void *udata, int flags)
1615 struct uma_kctor_args *arg = udata;
1616 uma_keg_t keg = mem;
1620 keg->uk_size = arg->size;
1621 keg->uk_init = arg->uminit;
1622 keg->uk_fini = arg->fini;
1623 keg->uk_align = arg->align;
1625 keg->uk_reserve = 0;
1627 keg->uk_flags = arg->flags;
1628 keg->uk_slabzone = NULL;
1631 * We use a global round-robin policy by default. Zones with
1632 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1633 * iterator is never run.
1635 keg->uk_dr.dr_policy = DOMAINSET_RR();
1636 keg->uk_dr.dr_iter = 0;
1639 * The master zone is passed to us at keg-creation time.
1642 keg->uk_name = zone->uz_name;
1644 if (arg->flags & UMA_ZONE_VM)
1645 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1647 if (arg->flags & UMA_ZONE_ZINIT)
1648 keg->uk_init = zero_init;
1650 if (arg->flags & UMA_ZONE_MALLOC)
1651 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1653 if (arg->flags & UMA_ZONE_PCPU)
1655 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1657 keg->uk_flags &= ~UMA_ZONE_PCPU;
1660 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1661 keg_cachespread_init(keg);
1663 if (keg->uk_size > UMA_SLAB_SPACE)
1664 keg_large_init(keg);
1666 keg_small_init(keg);
1669 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1670 keg->uk_slabzone = slabzone;
1673 * If we haven't booted yet we need allocations to go through the
1674 * startup cache until the vm is ready.
1676 if (booted < BOOT_PAGEALLOC)
1677 keg->uk_allocf = startup_alloc;
1678 #ifdef UMA_MD_SMALL_ALLOC
1679 else if (keg->uk_ppera == 1)
1680 keg->uk_allocf = uma_small_alloc;
1682 else if (keg->uk_flags & UMA_ZONE_PCPU)
1683 keg->uk_allocf = pcpu_page_alloc;
1685 keg->uk_allocf = page_alloc;
1686 #ifdef UMA_MD_SMALL_ALLOC
1687 if (keg->uk_ppera == 1)
1688 keg->uk_freef = uma_small_free;
1691 if (keg->uk_flags & UMA_ZONE_PCPU)
1692 keg->uk_freef = pcpu_page_free;
1694 keg->uk_freef = page_free;
1697 * Initialize keg's lock
1699 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1702 * If we're putting the slab header in the actual page we need to
1703 * figure out where in each page it goes. This calculates a right
1704 * justified offset into the memory on an ALIGN_PTR boundary.
1706 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1709 /* Size of the slab struct and free list */
1710 totsize = sizeof(struct uma_slab);
1712 if (totsize & UMA_ALIGN_PTR)
1713 totsize = (totsize & ~UMA_ALIGN_PTR) +
1714 (UMA_ALIGN_PTR + 1);
1715 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - totsize;
1718 * The only way the following is possible is if with our
1719 * UMA_ALIGN_PTR adjustments we are now bigger than
1720 * UMA_SLAB_SIZE. I haven't checked whether this is
1721 * mathematically possible for all cases, so we make
1724 totsize = keg->uk_pgoff + sizeof(struct uma_slab);
1725 if (totsize > PAGE_SIZE * keg->uk_ppera) {
1726 printf("zone %s ipers %d rsize %d size %d\n",
1727 zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1729 panic("UMA slab won't fit.");
1733 if (keg->uk_flags & UMA_ZONE_HASH)
1734 hash_alloc(&keg->uk_hash, 0);
1736 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1737 keg, zone->uz_name, zone,
1738 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1741 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1743 rw_wlock(&uma_rwlock);
1744 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1745 rw_wunlock(&uma_rwlock);
1750 * Zone header ctor. This initializes all fields, locks, etc.
1752 * Arguments/Returns follow uma_ctor specifications
1753 * udata Actually uma_zctor_args
1756 zone_ctor(void *mem, int size, void *udata, int flags)
1758 struct uma_zctor_args *arg = udata;
1759 uma_zone_t zone = mem;
1764 zone->uz_name = arg->name;
1765 zone->uz_ctor = arg->ctor;
1766 zone->uz_dtor = arg->dtor;
1767 zone->uz_slab = zone_fetch_slab;
1768 zone->uz_init = NULL;
1769 zone->uz_fini = NULL;
1770 zone->uz_allocs = 0;
1773 zone->uz_sleeps = 0;
1775 zone->uz_count_min = 0;
1777 zone->uz_warning = NULL;
1778 /* The domain structures follow the cpu structures. */
1779 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1780 timevalclear(&zone->uz_ratecheck);
1783 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1786 * This is a pure cache zone, no kegs.
1789 if (arg->flags & UMA_ZONE_VM)
1790 arg->flags |= UMA_ZFLAG_CACHEONLY;
1791 zone->uz_flags = arg->flags;
1792 zone->uz_size = arg->size;
1793 zone->uz_import = arg->import;
1794 zone->uz_release = arg->release;
1795 zone->uz_arg = arg->arg;
1796 zone->uz_lockptr = &zone->uz_lock;
1797 rw_wlock(&uma_rwlock);
1798 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1799 rw_wunlock(&uma_rwlock);
1804 * Use the regular zone/keg/slab allocator.
1806 zone->uz_import = (uma_import)zone_import;
1807 zone->uz_release = (uma_release)zone_release;
1808 zone->uz_arg = zone;
1810 if (arg->flags & UMA_ZONE_SECONDARY) {
1811 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1812 zone->uz_init = arg->uminit;
1813 zone->uz_fini = arg->fini;
1814 zone->uz_lockptr = &keg->uk_lock;
1815 zone->uz_flags |= UMA_ZONE_SECONDARY;
1816 rw_wlock(&uma_rwlock);
1818 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1819 if (LIST_NEXT(z, uz_link) == NULL) {
1820 LIST_INSERT_AFTER(z, zone, uz_link);
1825 rw_wunlock(&uma_rwlock);
1826 } else if (keg == NULL) {
1827 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1828 arg->align, arg->flags)) == NULL)
1831 struct uma_kctor_args karg;
1834 /* We should only be here from uma_startup() */
1835 karg.size = arg->size;
1836 karg.uminit = arg->uminit;
1837 karg.fini = arg->fini;
1838 karg.align = arg->align;
1839 karg.flags = arg->flags;
1841 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1848 * Link in the first keg.
1850 zone->uz_klink.kl_keg = keg;
1851 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1852 zone->uz_lockptr = &keg->uk_lock;
1853 zone->uz_size = keg->uk_size;
1854 zone->uz_flags |= (keg->uk_flags &
1855 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1858 * Some internal zones don't have room allocated for the per cpu
1859 * caches. If we're internal, bail out here.
1861 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1862 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1863 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1868 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1869 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1870 ("Invalid zone flag combination"));
1871 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1872 zone->uz_count = BUCKET_MAX;
1873 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1876 zone->uz_count = bucket_select(zone->uz_size);
1877 zone->uz_count_min = zone->uz_count;
1883 * Keg header dtor. This frees all data, destroys locks, frees the hash
1884 * table and removes the keg from the global list.
1886 * Arguments/Returns follow uma_dtor specifications
1890 keg_dtor(void *arg, int size, void *udata)
1894 keg = (uma_keg_t)arg;
1896 if (keg->uk_free != 0) {
1897 printf("Freed UMA keg (%s) was not empty (%d items). "
1898 " Lost %d pages of memory.\n",
1899 keg->uk_name ? keg->uk_name : "",
1900 keg->uk_free, keg->uk_pages);
1904 hash_free(&keg->uk_hash);
1912 * Arguments/Returns follow uma_dtor specifications
1916 zone_dtor(void *arg, int size, void *udata)
1922 zone = (uma_zone_t)arg;
1923 keg = zone_first_keg(zone);
1925 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1928 rw_wlock(&uma_rwlock);
1929 LIST_REMOVE(zone, uz_link);
1930 rw_wunlock(&uma_rwlock);
1932 * XXX there are some races here where
1933 * the zone can be drained but zone lock
1934 * released and then refilled before we
1935 * remove it... we dont care for now
1937 zone_drain_wait(zone, M_WAITOK);
1939 * Unlink all of our kegs.
1941 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1942 klink->kl_keg = NULL;
1943 LIST_REMOVE(klink, kl_link);
1944 if (klink == &zone->uz_klink)
1946 free(klink, M_TEMP);
1949 * We only destroy kegs from non secondary zones.
1951 if (keg != NULL && (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1952 rw_wlock(&uma_rwlock);
1953 LIST_REMOVE(keg, uk_link);
1954 rw_wunlock(&uma_rwlock);
1955 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1957 ZONE_LOCK_FINI(zone);
1961 * Traverses every zone in the system and calls a callback
1964 * zfunc A pointer to a function which accepts a zone
1971 zone_foreach(void (*zfunc)(uma_zone_t))
1976 rw_rlock(&uma_rwlock);
1977 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1978 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1981 rw_runlock(&uma_rwlock);
1985 * Count how many pages do we need to bootstrap. VM supplies
1986 * its need in early zones in the argument, we add up our zones,
1987 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1988 * zone of zones and zone of kegs are accounted separately.
1990 #define UMA_BOOT_ZONES 11
1991 /* Zone of zones and zone of kegs have arbitrary alignment. */
1992 #define UMA_BOOT_ALIGN 32
1993 static int zsize, ksize;
1995 uma_startup_count(int vm_zones)
1999 ksize = sizeof(struct uma_keg) +
2000 (sizeof(struct uma_domain) * vm_ndomains);
2001 zsize = sizeof(struct uma_zone) +
2002 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2003 (sizeof(struct uma_zone_domain) * vm_ndomains);
2006 * Memory for the zone of kegs and its keg,
2007 * and for zone of zones.
2009 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
2010 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
2012 #ifdef UMA_MD_SMALL_ALLOC
2013 zones = UMA_BOOT_ZONES;
2015 zones = UMA_BOOT_ZONES + vm_zones;
2019 /* Memory for the rest of startup zones, UMA and VM, ... */
2020 if (zsize > UMA_SLAB_SPACE)
2021 pages += (zones + vm_zones) *
2022 howmany(roundup2(zsize, UMA_BOOT_ALIGN), UMA_SLAB_SIZE);
2023 else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2026 pages += howmany(zones,
2027 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2029 /* ... and their kegs. Note that zone of zones allocates a keg! */
2030 pages += howmany(zones + 1,
2031 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2034 * Most of startup zones are not going to be offpages, that's
2035 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2036 * calculations. Some large bucket zones will be offpage, and
2037 * thus will allocate hashes. We take conservative approach
2038 * and assume that all zones may allocate hash. This may give
2039 * us some positive inaccuracy, usually an extra single page.
2041 pages += howmany(zones, UMA_SLAB_SPACE /
2042 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2048 uma_startup(void *mem, int npages)
2050 struct uma_zctor_args args;
2051 uma_keg_t masterkeg;
2055 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2058 rw_init(&uma_rwlock, "UMA lock");
2060 /* Use bootpages memory for the zone of zones and zone of kegs. */
2062 zones = (uma_zone_t)m;
2063 m += roundup(zsize, CACHE_LINE_SIZE);
2064 kegs = (uma_zone_t)m;
2065 m += roundup(zsize, CACHE_LINE_SIZE);
2066 masterkeg = (uma_keg_t)m;
2067 m += roundup(ksize, CACHE_LINE_SIZE);
2068 m = roundup(m, PAGE_SIZE);
2069 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2072 /* "manually" create the initial zone */
2073 memset(&args, 0, sizeof(args));
2074 args.name = "UMA Kegs";
2076 args.ctor = keg_ctor;
2077 args.dtor = keg_dtor;
2078 args.uminit = zero_init;
2080 args.keg = masterkeg;
2081 args.align = UMA_BOOT_ALIGN - 1;
2082 args.flags = UMA_ZFLAG_INTERNAL;
2083 zone_ctor(kegs, zsize, &args, M_WAITOK);
2086 boot_pages = npages;
2088 args.name = "UMA Zones";
2090 args.ctor = zone_ctor;
2091 args.dtor = zone_dtor;
2092 args.uminit = zero_init;
2095 args.align = UMA_BOOT_ALIGN - 1;
2096 args.flags = UMA_ZFLAG_INTERNAL;
2097 zone_ctor(zones, zsize, &args, M_WAITOK);
2099 /* Now make a zone for slab headers */
2100 slabzone = uma_zcreate("UMA Slabs",
2101 sizeof(struct uma_slab),
2102 NULL, NULL, NULL, NULL,
2103 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2105 hashzone = uma_zcreate("UMA Hash",
2106 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2107 NULL, NULL, NULL, NULL,
2108 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2112 booted = BOOT_STRAPPED;
2120 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2122 booted = BOOT_PAGEALLOC;
2130 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2132 booted = BOOT_BUCKETS;
2133 sx_init(&uma_drain_lock, "umadrain");
2138 * Initialize our callout handle
2146 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2147 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2148 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2150 callout_init(&uma_callout, 1);
2151 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2152 booted = BOOT_RUNNING;
2156 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2157 int align, uint32_t flags)
2159 struct uma_kctor_args args;
2162 args.uminit = uminit;
2164 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2167 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2170 /* Public functions */
2173 uma_set_align(int align)
2176 if (align != UMA_ALIGN_CACHE)
2177 uma_align_cache = align;
2182 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2183 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2186 struct uma_zctor_args args;
2190 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2193 /* This stuff is essential for the zone ctor */
2194 memset(&args, 0, sizeof(args));
2199 args.uminit = uminit;
2203 * If a zone is being created with an empty constructor and
2204 * destructor, pass UMA constructor/destructor which checks for
2205 * memory use after free.
2207 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2208 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2209 args.ctor = trash_ctor;
2210 args.dtor = trash_dtor;
2211 args.uminit = trash_init;
2212 args.fini = trash_fini;
2219 if (booted < BOOT_BUCKETS) {
2222 sx_slock(&uma_drain_lock);
2225 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2227 sx_sunlock(&uma_drain_lock);
2233 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2234 uma_init zinit, uma_fini zfini, uma_zone_t master)
2236 struct uma_zctor_args args;
2241 keg = zone_first_keg(master);
2242 memset(&args, 0, sizeof(args));
2244 args.size = keg->uk_size;
2247 args.uminit = zinit;
2249 args.align = keg->uk_align;
2250 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2253 if (booted < BOOT_BUCKETS) {
2256 sx_slock(&uma_drain_lock);
2259 /* XXX Attaches only one keg of potentially many. */
2260 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2262 sx_sunlock(&uma_drain_lock);
2268 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2269 uma_init zinit, uma_fini zfini, uma_import zimport,
2270 uma_release zrelease, void *arg, int flags)
2272 struct uma_zctor_args args;
2274 memset(&args, 0, sizeof(args));
2279 args.uminit = zinit;
2281 args.import = zimport;
2282 args.release = zrelease;
2287 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2291 zone_lock_pair(uma_zone_t a, uma_zone_t b)
2295 mtx_lock_flags(b->uz_lockptr, MTX_DUPOK);
2298 mtx_lock_flags(a->uz_lockptr, MTX_DUPOK);
2303 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
2311 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
2318 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
2320 zone_lock_pair(zone, master);
2322 * zone must use vtoslab() to resolve objects and must already be
2325 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
2326 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
2331 * The new master must also use vtoslab().
2333 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
2339 * The underlying object must be the same size. rsize
2342 if (master->uz_size != zone->uz_size) {
2347 * Put it at the end of the list.
2349 klink->kl_keg = zone_first_keg(master);
2350 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
2351 if (LIST_NEXT(kl, kl_link) == NULL) {
2352 LIST_INSERT_AFTER(kl, klink, kl_link);
2357 zone->uz_flags |= UMA_ZFLAG_MULTI;
2358 zone->uz_slab = zone_fetch_slab_multi;
2361 zone_unlock_pair(zone, master);
2363 free(klink, M_TEMP);
2371 uma_zdestroy(uma_zone_t zone)
2374 sx_slock(&uma_drain_lock);
2375 zone_free_item(zones, zone, NULL, SKIP_NONE);
2376 sx_sunlock(&uma_drain_lock);
2380 uma_zwait(uma_zone_t zone)
2384 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2385 uma_zfree(zone, item);
2389 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2395 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2397 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2398 if (item != NULL && (flags & M_ZERO)) {
2400 for (i = 0; i <= mp_maxid; i++)
2401 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2403 bzero(item, zone->uz_size);
2410 * A stub while both regular and pcpu cases are identical.
2413 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2417 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2419 uma_zfree_arg(zone, item, udata);
2424 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2426 uma_zone_domain_t zdom;
2427 uma_bucket_t bucket;
2430 int cpu, domain, lockfail;
2435 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2436 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2438 /* This is the fast path allocation */
2439 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2440 curthread, zone->uz_name, zone, flags);
2442 if (flags & M_WAITOK) {
2443 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2444 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2446 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2447 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2448 ("uma_zalloc_arg: called with spinlock or critical section held"));
2449 if (zone->uz_flags & UMA_ZONE_PCPU)
2450 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2451 "with M_ZERO passed"));
2453 #ifdef DEBUG_MEMGUARD
2454 if (memguard_cmp_zone(zone)) {
2455 item = memguard_alloc(zone->uz_size, flags);
2457 if (zone->uz_init != NULL &&
2458 zone->uz_init(item, zone->uz_size, flags) != 0)
2460 if (zone->uz_ctor != NULL &&
2461 zone->uz_ctor(item, zone->uz_size, udata,
2463 zone->uz_fini(item, zone->uz_size);
2468 /* This is unfortunate but should not be fatal. */
2472 * If possible, allocate from the per-CPU cache. There are two
2473 * requirements for safe access to the per-CPU cache: (1) the thread
2474 * accessing the cache must not be preempted or yield during access,
2475 * and (2) the thread must not migrate CPUs without switching which
2476 * cache it accesses. We rely on a critical section to prevent
2477 * preemption and migration. We release the critical section in
2478 * order to acquire the zone mutex if we are unable to allocate from
2479 * the current cache; when we re-acquire the critical section, we
2480 * must detect and handle migration if it has occurred.
2485 cache = &zone->uz_cpu[cpu];
2488 bucket = cache->uc_allocbucket;
2489 if (bucket != NULL && bucket->ub_cnt > 0) {
2491 item = bucket->ub_bucket[bucket->ub_cnt];
2493 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2495 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2499 skipdbg = uma_dbg_zskip(zone, item);
2501 if (zone->uz_ctor != NULL &&
2503 (!skipdbg || zone->uz_ctor != trash_ctor ||
2504 zone->uz_dtor != trash_dtor) &&
2506 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2507 atomic_add_long(&zone->uz_fails, 1);
2508 zone_free_item(zone, item, udata, SKIP_DTOR);
2513 uma_dbg_alloc(zone, NULL, item);
2516 uma_zero_item(item, zone);
2521 * We have run out of items in our alloc bucket.
2522 * See if we can switch with our free bucket.
2524 bucket = cache->uc_freebucket;
2525 if (bucket != NULL && bucket->ub_cnt > 0) {
2527 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2528 zone->uz_name, zone);
2529 cache->uc_freebucket = cache->uc_allocbucket;
2530 cache->uc_allocbucket = bucket;
2535 * Discard any empty allocation bucket while we hold no locks.
2537 bucket = cache->uc_allocbucket;
2538 cache->uc_allocbucket = NULL;
2541 bucket_free(zone, bucket, udata);
2543 if (zone->uz_flags & UMA_ZONE_NUMA) {
2544 domain = PCPU_GET(domain);
2545 if (VM_DOMAIN_EMPTY(domain))
2546 domain = UMA_ANYDOMAIN;
2548 domain = UMA_ANYDOMAIN;
2550 /* Short-circuit for zones without buckets and low memory. */
2551 if (zone->uz_count == 0 || bucketdisable)
2555 * Attempt to retrieve the item from the per-CPU cache has failed, so
2556 * we must go back to the zone. This requires the zone lock, so we
2557 * must drop the critical section, then re-acquire it when we go back
2558 * to the cache. Since the critical section is released, we may be
2559 * preempted or migrate. As such, make sure not to maintain any
2560 * thread-local state specific to the cache from prior to releasing
2561 * the critical section.
2564 if (ZONE_TRYLOCK(zone) == 0) {
2565 /* Record contention to size the buckets. */
2571 cache = &zone->uz_cpu[cpu];
2573 /* See if we lost the race to fill the cache. */
2574 if (cache->uc_allocbucket != NULL) {
2580 * Check the zone's cache of buckets.
2582 if (domain == UMA_ANYDOMAIN)
2583 zdom = &zone->uz_domain[0];
2585 zdom = &zone->uz_domain[domain];
2586 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2587 KASSERT(bucket->ub_cnt != 0,
2588 ("uma_zalloc_arg: Returning an empty bucket."));
2589 cache->uc_allocbucket = bucket;
2593 /* We are no longer associated with this CPU. */
2597 * We bump the uz count when the cache size is insufficient to
2598 * handle the working set.
2600 if (lockfail && zone->uz_count < BUCKET_MAX)
2605 * Now lets just fill a bucket and put it on the free list. If that
2606 * works we'll restart the allocation from the beginning and it
2607 * will use the just filled bucket.
2609 bucket = zone_alloc_bucket(zone, udata, domain, flags);
2610 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2611 zone->uz_name, zone, bucket);
2612 if (bucket != NULL) {
2616 cache = &zone->uz_cpu[cpu];
2619 * See if we lost the race or were migrated. Cache the
2620 * initialized bucket to make this less likely or claim
2621 * the memory directly.
2623 if (cache->uc_allocbucket == NULL &&
2624 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2625 domain == PCPU_GET(domain))) {
2626 cache->uc_allocbucket = bucket;
2627 zdom->uzd_imax += bucket->ub_cnt;
2628 } else if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
2631 bucket_drain(zone, bucket);
2632 bucket_free(zone, bucket, udata);
2633 goto zalloc_restart;
2635 zone_put_bucket(zone, zdom, bucket, false);
2641 * We may not be able to get a bucket so return an actual item.
2644 item = zone_alloc_item(zone, udata, domain, flags);
2650 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2653 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2654 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2656 /* This is the fast path allocation */
2658 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2659 curthread, zone->uz_name, zone, domain, flags);
2661 if (flags & M_WAITOK) {
2662 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2663 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2665 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2666 ("uma_zalloc_domain: called with spinlock or critical section held"));
2668 return (zone_alloc_item(zone, udata, domain, flags));
2672 * Find a slab with some space. Prefer slabs that are partially used over those
2673 * that are totally full. This helps to reduce fragmentation.
2675 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2679 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2685 KASSERT(domain >= 0 && domain < vm_ndomains,
2686 ("keg_first_slab: domain %d out of range", domain));
2691 dom = &keg->uk_domain[domain];
2692 if (!LIST_EMPTY(&dom->ud_part_slab))
2693 return (LIST_FIRST(&dom->ud_part_slab));
2694 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2695 slab = LIST_FIRST(&dom->ud_free_slab);
2696 LIST_REMOVE(slab, us_link);
2697 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2701 domain = (domain + 1) % vm_ndomains;
2702 } while (domain != start);
2708 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2712 mtx_assert(&keg->uk_lock, MA_OWNED);
2714 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2715 if (keg->uk_free <= reserve)
2717 return (keg_first_slab(keg, domain, rr));
2721 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2723 struct vm_domainset_iter di;
2730 mtx_assert(&keg->uk_lock, MA_OWNED);
2733 * Use the keg's policy if upper layers haven't already specified a
2734 * domain (as happens with first-touch zones).
2736 * To avoid races we run the iterator with the keg lock held, but that
2737 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2738 * clear M_WAITOK and handle low memory conditions locally.
2740 rr = rdomain == UMA_ANYDOMAIN;
2742 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2743 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2751 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2753 MPASS(slab->us_keg == keg);
2758 * M_NOVM means don't ask at all!
2763 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2764 keg->uk_flags |= UMA_ZFLAG_FULL;
2766 * If this is not a multi-zone, set the FULL bit.
2767 * Otherwise slab_multi() takes care of it.
2769 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2770 zone->uz_flags |= UMA_ZFLAG_FULL;
2771 zone_log_warning(zone);
2772 zone_maxaction(zone);
2774 if (flags & M_NOWAIT)
2777 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2780 slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
2782 * If we got a slab here it's safe to mark it partially used
2783 * and return. We assume that the caller is going to remove
2784 * at least one item.
2787 MPASS(slab->us_keg == keg);
2788 dom = &keg->uk_domain[slab->us_domain];
2789 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2793 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2794 if ((flags & M_WAITOK) != 0) {
2796 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2805 * We might not have been able to get a slab but another cpu
2806 * could have while we were unlocked. Check again before we
2809 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2810 MPASS(slab->us_keg == keg);
2817 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2822 keg = zone_first_keg(zone);
2827 slab = keg_fetch_slab(keg, zone, domain, flags);
2830 if (flags & (M_NOWAIT | M_NOVM))
2838 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2839 * with the keg locked. On NULL no lock is held.
2841 * The last pointer is used to seed the search. It is not required.
2844 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int domain, int rflags)
2854 * Don't wait on the first pass. This will skip limit tests
2855 * as well. We don't want to block if we can find a provider
2858 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2860 * Use the last slab allocated as a hint for where to start
2864 slab = keg_fetch_slab(last, zone, domain, flags);
2870 * Loop until we have a slab incase of transient failures
2871 * while M_WAITOK is specified. I'm not sure this is 100%
2872 * required but we've done it for so long now.
2878 * Search the available kegs for slabs. Be careful to hold the
2879 * correct lock while calling into the keg layer.
2881 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2882 keg = klink->kl_keg;
2884 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2885 slab = keg_fetch_slab(keg, zone, domain, flags);
2889 if (keg->uk_flags & UMA_ZFLAG_FULL)
2895 if (rflags & (M_NOWAIT | M_NOVM))
2899 * All kegs are full. XXX We can't atomically check all kegs
2900 * and sleep so just sleep for a short period and retry.
2902 if (full && !empty) {
2904 zone->uz_flags |= UMA_ZFLAG_FULL;
2906 zone_log_warning(zone);
2907 zone_maxaction(zone);
2908 msleep(zone, zone->uz_lockptr, PVM,
2909 "zonelimit", hz/100);
2910 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2919 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2925 MPASS(keg == slab->us_keg);
2926 mtx_assert(&keg->uk_lock, MA_OWNED);
2928 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2929 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2930 item = slab->us_data + (keg->uk_rsize * freei);
2931 slab->us_freecount--;
2934 /* Move this slab to the full list */
2935 if (slab->us_freecount == 0) {
2936 LIST_REMOVE(slab, us_link);
2937 dom = &keg->uk_domain[slab->us_domain];
2938 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2945 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2956 /* Try to keep the buckets totally full */
2957 for (i = 0; i < max; ) {
2958 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2962 stripe = howmany(max, vm_ndomains);
2964 while (slab->us_freecount && i < max) {
2965 bucket[i++] = slab_alloc_item(keg, slab);
2966 if (keg->uk_free <= keg->uk_reserve)
2970 * If the zone is striped we pick a new slab for every
2971 * N allocations. Eliminating this conditional will
2972 * instead pick a new domain for each bucket rather
2973 * than stripe within each bucket. The current option
2974 * produces more fragmentation and requires more cpu
2975 * time but yields better distribution.
2977 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2978 vm_ndomains > 1 && --stripe == 0)
2982 /* Don't block if we allocated any successfully. */
2993 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
2995 uma_bucket_t bucket;
2998 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
3000 /* Don't wait for buckets, preserve caller's NOVM setting. */
3001 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
3005 max = MIN(bucket->ub_entries, zone->uz_count);
3006 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
3007 max, domain, flags);
3010 * Initialize the memory if necessary.
3012 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
3015 for (i = 0; i < bucket->ub_cnt; i++)
3016 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
3020 * If we couldn't initialize the whole bucket, put the
3021 * rest back onto the freelist.
3023 if (i != bucket->ub_cnt) {
3024 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
3025 bucket->ub_cnt - i);
3027 bzero(&bucket->ub_bucket[i],
3028 sizeof(void *) * (bucket->ub_cnt - i));
3034 if (bucket->ub_cnt == 0) {
3035 bucket_free(zone, bucket, udata);
3036 atomic_add_long(&zone->uz_fails, 1);
3044 * Allocates a single item from a zone.
3047 * zone The zone to alloc for.
3048 * udata The data to be passed to the constructor.
3049 * domain The domain to allocate from or UMA_ANYDOMAIN.
3050 * flags M_WAITOK, M_NOWAIT, M_ZERO.
3053 * NULL if there is no memory and M_NOWAIT is set
3054 * An item if successful
3058 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
3067 if (domain != UMA_ANYDOMAIN) {
3068 /* avoid allocs targeting empty domains */
3069 if (VM_DOMAIN_EMPTY(domain))
3070 domain = UMA_ANYDOMAIN;
3072 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
3074 atomic_add_long(&zone->uz_allocs, 1);
3077 skipdbg = uma_dbg_zskip(zone, item);
3080 * We have to call both the zone's init (not the keg's init)
3081 * and the zone's ctor. This is because the item is going from
3082 * a keg slab directly to the user, and the user is expecting it
3083 * to be both zone-init'd as well as zone-ctor'd.
3085 if (zone->uz_init != NULL) {
3086 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
3087 zone_free_item(zone, item, udata, SKIP_FINI);
3091 if (zone->uz_ctor != NULL &&
3093 (!skipdbg || zone->uz_ctor != trash_ctor ||
3094 zone->uz_dtor != trash_dtor) &&
3096 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
3097 zone_free_item(zone, item, udata, SKIP_DTOR);
3102 uma_dbg_alloc(zone, NULL, item);
3105 uma_zero_item(item, zone);
3107 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3108 zone->uz_name, zone);
3113 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3114 zone->uz_name, zone);
3115 atomic_add_long(&zone->uz_fails, 1);
3121 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3124 uma_bucket_t bucket;
3125 uma_zone_domain_t zdom;
3126 int cpu, domain, lockfail;
3131 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3132 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3134 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3137 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3138 ("uma_zfree_arg: called with spinlock or critical section held"));
3140 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3143 #ifdef DEBUG_MEMGUARD
3144 if (is_memguard_addr(item)) {
3145 if (zone->uz_dtor != NULL)
3146 zone->uz_dtor(item, zone->uz_size, udata);
3147 if (zone->uz_fini != NULL)
3148 zone->uz_fini(item, zone->uz_size);
3149 memguard_free(item);
3154 skipdbg = uma_dbg_zskip(zone, item);
3155 if (skipdbg == false) {
3156 if (zone->uz_flags & UMA_ZONE_MALLOC)
3157 uma_dbg_free(zone, udata, item);
3159 uma_dbg_free(zone, NULL, item);
3161 if (zone->uz_dtor != NULL && (!skipdbg ||
3162 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3164 if (zone->uz_dtor != NULL)
3166 zone->uz_dtor(item, zone->uz_size, udata);
3169 * The race here is acceptable. If we miss it we'll just have to wait
3170 * a little longer for the limits to be reset.
3172 if (zone->uz_flags & UMA_ZFLAG_FULL)
3176 * If possible, free to the per-CPU cache. There are two
3177 * requirements for safe access to the per-CPU cache: (1) the thread
3178 * accessing the cache must not be preempted or yield during access,
3179 * and (2) the thread must not migrate CPUs without switching which
3180 * cache it accesses. We rely on a critical section to prevent
3181 * preemption and migration. We release the critical section in
3182 * order to acquire the zone mutex if we are unable to free to the
3183 * current cache; when we re-acquire the critical section, we must
3184 * detect and handle migration if it has occurred.
3189 cache = &zone->uz_cpu[cpu];
3193 * Try to free into the allocbucket first to give LIFO ordering
3194 * for cache-hot datastructures. Spill over into the freebucket
3195 * if necessary. Alloc will swap them if one runs dry.
3197 bucket = cache->uc_allocbucket;
3198 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3199 bucket = cache->uc_freebucket;
3200 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3201 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3202 ("uma_zfree: Freeing to non free bucket index."));
3203 bucket->ub_bucket[bucket->ub_cnt] = item;
3211 * We must go back the zone, which requires acquiring the zone lock,
3212 * which in turn means we must release and re-acquire the critical
3213 * section. Since the critical section is released, we may be
3214 * preempted or migrate. As such, make sure not to maintain any
3215 * thread-local state specific to the cache from prior to releasing
3216 * the critical section.
3219 if (zone->uz_count == 0 || bucketdisable)
3223 if (ZONE_TRYLOCK(zone) == 0) {
3224 /* Record contention to size the buckets. */
3230 cache = &zone->uz_cpu[cpu];
3232 bucket = cache->uc_freebucket;
3233 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3237 cache->uc_freebucket = NULL;
3238 /* We are no longer associated with this CPU. */
3241 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3242 domain = PCPU_GET(domain);
3243 if (VM_DOMAIN_EMPTY(domain))
3244 domain = UMA_ANYDOMAIN;
3247 zdom = &zone->uz_domain[0];
3249 /* Can we throw this on the zone full list? */
3250 if (bucket != NULL) {
3252 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3253 zone->uz_name, zone, bucket);
3254 /* ub_cnt is pointing to the last free item */
3255 KASSERT(bucket->ub_cnt != 0,
3256 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
3257 if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
3259 bucket_drain(zone, bucket);
3260 bucket_free(zone, bucket, udata);
3263 zone_put_bucket(zone, zdom, bucket, true);
3267 * We bump the uz count when the cache size is insufficient to
3268 * handle the working set.
3270 if (lockfail && zone->uz_count < BUCKET_MAX)
3274 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3275 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3276 zone->uz_name, zone, bucket);
3280 cache = &zone->uz_cpu[cpu];
3281 if (cache->uc_freebucket == NULL &&
3282 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3283 domain == PCPU_GET(domain))) {
3284 cache->uc_freebucket = bucket;
3288 * We lost the race, start over. We have to drop our
3289 * critical section to free the bucket.
3292 bucket_free(zone, bucket, udata);
3297 * If nothing else caught this, we'll just do an internal free.
3300 zone_free_item(zone, item, udata, SKIP_DTOR);
3306 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3309 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3310 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3312 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3315 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3316 ("uma_zfree_domain: called with spinlock or critical section held"));
3318 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3321 zone_free_item(zone, item, udata, SKIP_NONE);
3325 slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item)
3330 mtx_assert(&keg->uk_lock, MA_OWNED);
3331 MPASS(keg == slab->us_keg);
3333 dom = &keg->uk_domain[slab->us_domain];
3335 /* Do we need to remove from any lists? */
3336 if (slab->us_freecount+1 == keg->uk_ipers) {
3337 LIST_REMOVE(slab, us_link);
3338 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3339 } else if (slab->us_freecount == 0) {
3340 LIST_REMOVE(slab, us_link);
3341 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3344 /* Slab management. */
3345 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3346 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3347 slab->us_freecount++;
3349 /* Keg statistics. */
3354 zone_release(uma_zone_t zone, void **bucket, int cnt)
3364 keg = zone_first_keg(zone);
3366 for (i = 0; i < cnt; i++) {
3368 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3369 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3370 if (zone->uz_flags & UMA_ZONE_HASH) {
3371 slab = hash_sfind(&keg->uk_hash, mem);
3373 mem += keg->uk_pgoff;
3374 slab = (uma_slab_t)mem;
3377 slab = vtoslab((vm_offset_t)item);
3378 if (slab->us_keg != keg) {
3384 slab_free_item(keg, slab, item);
3385 if (keg->uk_flags & UMA_ZFLAG_FULL) {
3386 if (keg->uk_pages < keg->uk_maxpages) {
3387 keg->uk_flags &= ~UMA_ZFLAG_FULL;
3392 * We can handle one more allocation. Since we're
3393 * clearing ZFLAG_FULL, wake up all procs blocked
3394 * on pages. This should be uncommon, so keeping this
3395 * simple for now (rather than adding count of blocked
3404 zone->uz_flags &= ~UMA_ZFLAG_FULL;
3412 * Frees a single item to any zone.
3415 * zone The zone to free to
3416 * item The item we're freeing
3417 * udata User supplied data for the dtor
3418 * skip Skip dtors and finis
3421 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3426 skipdbg = uma_dbg_zskip(zone, item);
3427 if (skip == SKIP_NONE && !skipdbg) {
3428 if (zone->uz_flags & UMA_ZONE_MALLOC)
3429 uma_dbg_free(zone, udata, item);
3431 uma_dbg_free(zone, NULL, item);
3434 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3435 (!skipdbg || zone->uz_dtor != trash_dtor ||
3436 zone->uz_ctor != trash_ctor))
3438 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3440 zone->uz_dtor(item, zone->uz_size, udata);
3442 if (skip < SKIP_FINI && zone->uz_fini)
3443 zone->uz_fini(item, zone->uz_size);
3445 atomic_add_long(&zone->uz_frees, 1);
3446 zone->uz_release(zone->uz_arg, &item, 1);
3451 uma_zone_set_max(uma_zone_t zone, int nitems)
3455 keg = zone_first_keg(zone);
3459 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
3460 if (keg->uk_maxpages * keg->uk_ipers < nitems)
3461 keg->uk_maxpages += keg->uk_ppera;
3462 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3470 uma_zone_get_max(uma_zone_t zone)
3475 keg = zone_first_keg(zone);
3479 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3487 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3491 zone->uz_warning = warning;
3497 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3501 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3507 uma_zone_get_cur(uma_zone_t zone)
3513 nitems = zone->uz_allocs - zone->uz_frees;
3516 * See the comment in sysctl_vm_zone_stats() regarding the
3517 * safety of accessing the per-cpu caches. With the zone lock
3518 * held, it is safe, but can potentially result in stale data.
3520 nitems += zone->uz_cpu[i].uc_allocs -
3521 zone->uz_cpu[i].uc_frees;
3525 return (nitems < 0 ? 0 : nitems);
3530 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3534 keg = zone_first_keg(zone);
3535 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
3537 KASSERT(keg->uk_pages == 0,
3538 ("uma_zone_set_init on non-empty keg"));
3539 keg->uk_init = uminit;
3545 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3549 keg = zone_first_keg(zone);
3550 KASSERT(keg != NULL, ("uma_zone_set_fini: Invalid zone type"));
3552 KASSERT(keg->uk_pages == 0,
3553 ("uma_zone_set_fini on non-empty keg"));
3554 keg->uk_fini = fini;
3560 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3564 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3565 ("uma_zone_set_zinit on non-empty keg"));
3566 zone->uz_init = zinit;
3572 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3576 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3577 ("uma_zone_set_zfini on non-empty keg"));
3578 zone->uz_fini = zfini;
3583 /* XXX uk_freef is not actually used with the zone locked */
3585 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3589 keg = zone_first_keg(zone);
3590 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3592 keg->uk_freef = freef;
3597 /* XXX uk_allocf is not actually used with the zone locked */
3599 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3603 keg = zone_first_keg(zone);
3605 keg->uk_allocf = allocf;
3611 uma_zone_reserve(uma_zone_t zone, int items)
3615 keg = zone_first_keg(zone);
3619 keg->uk_reserve = items;
3627 uma_zone_reserve_kva(uma_zone_t zone, int count)
3633 keg = zone_first_keg(zone);
3636 pages = count / keg->uk_ipers;
3638 if (pages * keg->uk_ipers < count)
3640 pages *= keg->uk_ppera;
3642 #ifdef UMA_MD_SMALL_ALLOC
3643 if (keg->uk_ppera > 1) {
3647 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3655 keg->uk_maxpages = pages;
3656 #ifdef UMA_MD_SMALL_ALLOC
3657 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3659 keg->uk_allocf = noobj_alloc;
3661 keg->uk_flags |= UMA_ZONE_NOFREE;
3669 uma_prealloc(uma_zone_t zone, int items)
3671 struct vm_domainset_iter di;
3675 int aflags, domain, slabs;
3677 keg = zone_first_keg(zone);
3681 slabs = items / keg->uk_ipers;
3682 if (slabs * keg->uk_ipers < items)
3684 while (slabs-- > 0) {
3686 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3689 slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
3692 MPASS(slab->us_keg == keg);
3693 dom = &keg->uk_domain[slab->us_domain];
3694 LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
3699 if (vm_domainset_iter_policy(&di, &domain) != 0) {
3701 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
3711 uma_reclaim_locked(bool kmem_danger)
3714 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3715 sx_assert(&uma_drain_lock, SA_XLOCKED);
3717 zone_foreach(zone_drain);
3718 if (vm_page_count_min() || kmem_danger) {
3719 cache_drain_safe(NULL);
3720 zone_foreach(zone_drain);
3724 * Some slabs may have been freed but this zone will be visited early
3725 * we visit again so that we can free pages that are empty once other
3726 * zones are drained. We have to do the same for buckets.
3728 zone_drain(slabzone);
3729 bucket_zone_drain();
3736 sx_xlock(&uma_drain_lock);
3737 uma_reclaim_locked(false);
3738 sx_xunlock(&uma_drain_lock);
3741 static volatile int uma_reclaim_needed;
3744 uma_reclaim_wakeup(void)
3747 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3748 wakeup(uma_reclaim);
3752 uma_reclaim_worker(void *arg __unused)
3756 sx_xlock(&uma_drain_lock);
3757 while (atomic_load_int(&uma_reclaim_needed) == 0)
3758 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3760 sx_xunlock(&uma_drain_lock);
3761 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3762 sx_xlock(&uma_drain_lock);
3763 uma_reclaim_locked(true);
3764 atomic_store_int(&uma_reclaim_needed, 0);
3765 sx_xunlock(&uma_drain_lock);
3766 /* Don't fire more than once per-second. */
3767 pause("umarclslp", hz);
3773 uma_zone_exhausted(uma_zone_t zone)
3778 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3784 uma_zone_exhausted_nolock(uma_zone_t zone)
3786 return (zone->uz_flags & UMA_ZFLAG_FULL);
3790 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3792 struct domainset *policy;
3796 if (domain != UMA_ANYDOMAIN) {
3797 /* avoid allocs targeting empty domains */
3798 if (VM_DOMAIN_EMPTY(domain))
3799 domain = UMA_ANYDOMAIN;
3801 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3804 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3805 DOMAINSET_FIXED(domain);
3806 addr = kmem_malloc_domainset(policy, size, wait);
3808 vsetslab(addr, slab);
3809 slab->us_data = (void *)addr;
3810 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3811 slab->us_size = size;
3812 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3813 pmap_kextract(addr)));
3814 uma_total_inc(size);
3816 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3819 return ((void *)addr);
3823 uma_large_malloc(vm_size_t size, int wait)
3826 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3830 uma_large_free(uma_slab_t slab)
3833 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3834 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3835 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3836 uma_total_dec(slab->us_size);
3837 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3841 uma_zero_item(void *item, uma_zone_t zone)
3844 bzero(item, zone->uz_size);
3851 return (uma_kmem_limit);
3855 uma_set_limit(unsigned long limit)
3858 uma_kmem_limit = limit;
3865 return (atomic_load_long(&uma_kmem_total));
3872 return (uma_kmem_limit - uma_size());
3876 uma_print_stats(void)
3878 zone_foreach(uma_print_zone);
3882 slab_print(uma_slab_t slab)
3884 printf("slab: keg %p, data %p, freecount %d\n",
3885 slab->us_keg, slab->us_data, slab->us_freecount);
3889 cache_print(uma_cache_t cache)
3891 printf("alloc: %p(%d), free: %p(%d)\n",
3892 cache->uc_allocbucket,
3893 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3894 cache->uc_freebucket,
3895 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3899 uma_print_keg(uma_keg_t keg)
3905 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3906 "out %d free %d limit %d\n",
3907 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3908 keg->uk_ipers, keg->uk_ppera,
3909 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3910 keg->uk_free, (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3911 for (i = 0; i < vm_ndomains; i++) {
3912 dom = &keg->uk_domain[i];
3913 printf("Part slabs:\n");
3914 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3916 printf("Free slabs:\n");
3917 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3919 printf("Full slabs:\n");
3920 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3926 uma_print_zone(uma_zone_t zone)
3932 printf("zone: %s(%p) size %d flags %#x\n",
3933 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3934 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3935 uma_print_keg(kl->kl_keg);
3937 cache = &zone->uz_cpu[i];
3938 printf("CPU %d Cache:\n", i);
3945 * Generate statistics across both the zone and its per-cpu cache's. Return
3946 * desired statistics if the pointer is non-NULL for that statistic.
3948 * Note: does not update the zone statistics, as it can't safely clear the
3949 * per-CPU cache statistic.
3951 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3952 * safe from off-CPU; we should modify the caches to track this information
3953 * directly so that we don't have to.
3956 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3957 uint64_t *freesp, uint64_t *sleepsp)
3960 uint64_t allocs, frees, sleeps;
3963 allocs = frees = sleeps = 0;
3966 cache = &z->uz_cpu[cpu];
3967 if (cache->uc_allocbucket != NULL)
3968 cachefree += cache->uc_allocbucket->ub_cnt;
3969 if (cache->uc_freebucket != NULL)
3970 cachefree += cache->uc_freebucket->ub_cnt;
3971 allocs += cache->uc_allocs;
3972 frees += cache->uc_frees;
3974 allocs += z->uz_allocs;
3975 frees += z->uz_frees;
3976 sleeps += z->uz_sleeps;
3977 if (cachefreep != NULL)
3978 *cachefreep = cachefree;
3979 if (allocsp != NULL)
3983 if (sleepsp != NULL)
3989 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3996 rw_rlock(&uma_rwlock);
3997 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3998 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4001 rw_runlock(&uma_rwlock);
4002 return (sysctl_handle_int(oidp, &count, 0, req));
4006 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
4008 struct uma_stream_header ush;
4009 struct uma_type_header uth;
4010 struct uma_percpu_stat *ups;
4011 uma_zone_domain_t zdom;
4018 int count, error, i;
4020 error = sysctl_wire_old_buffer(req, 0);
4023 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
4024 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
4025 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
4028 rw_rlock(&uma_rwlock);
4029 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4030 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4035 * Insert stream header.
4037 bzero(&ush, sizeof(ush));
4038 ush.ush_version = UMA_STREAM_VERSION;
4039 ush.ush_maxcpus = (mp_maxid + 1);
4040 ush.ush_count = count;
4041 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
4043 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4044 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4045 bzero(&uth, sizeof(uth));
4047 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4048 uth.uth_align = kz->uk_align;
4049 uth.uth_size = kz->uk_size;
4050 uth.uth_rsize = kz->uk_rsize;
4051 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
4053 uth.uth_maxpages += k->uk_maxpages;
4054 uth.uth_pages += k->uk_pages;
4055 uth.uth_keg_free += k->uk_free;
4056 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
4061 * A zone is secondary is it is not the first entry
4062 * on the keg's zone list.
4064 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
4065 (LIST_FIRST(&kz->uk_zones) != z))
4066 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
4068 for (i = 0; i < vm_ndomains; i++) {
4069 zdom = &z->uz_domain[i];
4070 uth.uth_zone_free += zdom->uzd_nitems;
4072 uth.uth_allocs = z->uz_allocs;
4073 uth.uth_frees = z->uz_frees;
4074 uth.uth_fails = z->uz_fails;
4075 uth.uth_sleeps = z->uz_sleeps;
4077 * While it is not normally safe to access the cache
4078 * bucket pointers while not on the CPU that owns the
4079 * cache, we only allow the pointers to be exchanged
4080 * without the zone lock held, not invalidated, so
4081 * accept the possible race associated with bucket
4082 * exchange during monitoring.
4084 for (i = 0; i < mp_maxid + 1; i++) {
4085 bzero(&ups[i], sizeof(*ups));
4086 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
4089 cache = &z->uz_cpu[i];
4090 if (cache->uc_allocbucket != NULL)
4091 ups[i].ups_cache_free +=
4092 cache->uc_allocbucket->ub_cnt;
4093 if (cache->uc_freebucket != NULL)
4094 ups[i].ups_cache_free +=
4095 cache->uc_freebucket->ub_cnt;
4096 ups[i].ups_allocs = cache->uc_allocs;
4097 ups[i].ups_frees = cache->uc_frees;
4100 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4101 for (i = 0; i < mp_maxid + 1; i++)
4102 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4105 rw_runlock(&uma_rwlock);
4106 error = sbuf_finish(&sbuf);
4113 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4115 uma_zone_t zone = *(uma_zone_t *)arg1;
4118 max = uma_zone_get_max(zone);
4119 error = sysctl_handle_int(oidp, &max, 0, req);
4120 if (error || !req->newptr)
4123 uma_zone_set_max(zone, max);
4129 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4131 uma_zone_t zone = *(uma_zone_t *)arg1;
4134 cur = uma_zone_get_cur(zone);
4135 return (sysctl_handle_int(oidp, &cur, 0, req));
4140 uma_dbg_getslab(uma_zone_t zone, void *item)
4146 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4147 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4148 slab = vtoslab((vm_offset_t)mem);
4151 * It is safe to return the slab here even though the
4152 * zone is unlocked because the item's allocation state
4153 * essentially holds a reference.
4156 keg = LIST_FIRST(&zone->uz_kegs)->kl_keg;
4157 if (keg->uk_flags & UMA_ZONE_HASH)
4158 slab = hash_sfind(&keg->uk_hash, mem);
4160 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4168 uma_dbg_zskip(uma_zone_t zone, void *mem)
4172 if ((keg = zone_first_keg(zone)) == NULL)
4175 return (uma_dbg_kskip(keg, mem));
4179 uma_dbg_kskip(uma_keg_t keg, void *mem)
4183 if (dbg_divisor == 0)
4186 if (dbg_divisor == 1)
4189 idx = (uintptr_t)mem >> PAGE_SHIFT;
4190 if (keg->uk_ipers > 1) {
4191 idx *= keg->uk_ipers;
4192 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4195 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4196 counter_u64_add(uma_skip_cnt, 1);
4199 counter_u64_add(uma_dbg_cnt, 1);
4205 * Set up the slab's freei data such that uma_dbg_free can function.
4209 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4215 slab = uma_dbg_getslab(zone, item);
4217 panic("uma: item %p did not belong to zone %s\n",
4218 item, zone->uz_name);
4221 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4223 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4224 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4225 item, zone, zone->uz_name, slab, freei);
4226 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4232 * Verifies freed addresses. Checks for alignment, valid slab membership
4233 * and duplicate frees.
4237 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4243 slab = uma_dbg_getslab(zone, item);
4245 panic("uma: Freed item %p did not belong to zone %s\n",
4246 item, zone->uz_name);
4249 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4251 if (freei >= keg->uk_ipers)
4252 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4253 item, zone, zone->uz_name, slab, freei);
4255 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4256 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4257 item, zone, zone->uz_name, slab, freei);
4259 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4260 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4261 item, zone, zone->uz_name, slab, freei);
4263 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4265 #endif /* INVARIANTS */
4268 DB_SHOW_COMMAND(uma, db_show_uma)
4272 uint64_t allocs, frees, sleeps;
4276 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4277 "Free", "Requests", "Sleeps", "Bucket");
4278 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4279 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4280 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4281 allocs = z->uz_allocs;
4282 frees = z->uz_frees;
4283 sleeps = z->uz_sleeps;
4286 uma_zone_sumstat(z, &cachefree, &allocs,
4288 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4289 (LIST_FIRST(&kz->uk_zones) != z)))
4290 cachefree += kz->uk_free;
4291 for (i = 0; i < vm_ndomains; i++)
4292 cachefree += z->uz_domain[i].uzd_nitems;
4294 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4295 z->uz_name, (uintmax_t)kz->uk_size,
4296 (intmax_t)(allocs - frees), cachefree,
4297 (uintmax_t)allocs, sleeps, z->uz_count);
4304 DB_SHOW_COMMAND(umacache, db_show_umacache)
4307 uint64_t allocs, frees;
4311 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4312 "Requests", "Bucket");
4313 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4314 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4315 for (i = 0; i < vm_ndomains; i++)
4316 cachefree += z->uz_domain[i].uzd_nitems;
4317 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4318 z->uz_name, (uintmax_t)z->uz_size,
4319 (intmax_t)(allocs - frees), cachefree,
4320 (uintmax_t)allocs, z->uz_count);