2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
5 * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6 * Copyright (c) 2004-2006 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice unmodified, this list of conditions, and the following
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * uma_core.c Implementation of the Universal Memory allocator
34 * This allocator is intended to replace the multitude of similar object caches
35 * in the standard FreeBSD kernel. The intent is to be flexible as well as
36 * efficient. A primary design goal is to return unused memory to the rest of
37 * the system. This will make the system as a whole more flexible due to the
38 * ability to move memory to subsystems which most need it instead of leaving
39 * pools of reserved memory unused.
41 * The basic ideas stem from similar slab/zone based allocators whose algorithms
48 * - Improve memory usage for large allocations
49 * - Investigate cache size adjustments
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
56 #include "opt_param.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
77 #include <sys/sched.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
100 #include <vm/memguard.h>
104 * This is the zone and keg from which all zones are spawned.
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
113 * The initial hash tables come out of this zone so they can be allocated
114 * prior to malloc coming up.
116 static uma_zone_t hashzone;
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
124 * Are we allowed to allocate buckets?
126 static int bucketdisable = 1;
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133 LIST_HEAD_INITIALIZER(uma_cachezones);
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
139 * Pointer and counter to pool of pages, that is preallocated at
140 * startup to bootstrap UMA.
142 static char *bootmem;
143 static int boot_pages;
145 static struct sx uma_drain_lock;
147 /* kmem soft limit. */
148 static unsigned long uma_kmem_limit = LONG_MAX;
149 static volatile unsigned long uma_kmem_total;
151 /* Is the VM done starting up? */
152 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
153 BOOT_RUNNING } booted = BOOT_COLD;
156 * This is the handle used to schedule events that need to happen
157 * outside of the allocation fast path.
159 static struct callout uma_callout;
160 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
163 * This structure is passed as the zone ctor arg so that I don't have to create
164 * a special allocation function just for zones.
166 struct uma_zctor_args {
181 struct uma_kctor_args {
190 struct uma_bucket_zone {
193 int ubz_entries; /* Number of items it can hold. */
194 int ubz_maxsize; /* Maximum allocation size per-item. */
198 * Compute the actual number of bucket entries to pack them in power
199 * of two sizes for more efficient space utilization.
201 #define BUCKET_SIZE(n) \
202 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
204 #define BUCKET_MAX BUCKET_SIZE(256)
206 struct uma_bucket_zone bucket_zones[] = {
207 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
208 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
209 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
210 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
211 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
212 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
213 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
214 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
215 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
220 * Flags and enumerations to be passed to internal functions.
224 SKIP_CNT = 0x00000001,
225 SKIP_DTOR = 0x00010000,
226 SKIP_FINI = 0x00020000,
229 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
233 int uma_startup_count(int);
234 void uma_startup(void *, int);
235 void uma_startup1(void);
236 void uma_startup2(void);
238 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
239 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
240 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
241 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
242 static void page_free(void *, vm_size_t, uint8_t);
243 static void pcpu_page_free(void *, vm_size_t, uint8_t);
244 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int);
245 static void cache_drain(uma_zone_t);
246 static void bucket_drain(uma_zone_t, uma_bucket_t);
247 static void bucket_cache_drain(uma_zone_t zone);
248 static int keg_ctor(void *, int, void *, int);
249 static void keg_dtor(void *, int, void *);
250 static int zone_ctor(void *, int, void *, int);
251 static void zone_dtor(void *, int, void *);
252 static int zero_init(void *, int, int);
253 static void keg_small_init(uma_keg_t keg);
254 static void keg_large_init(uma_keg_t keg);
255 static void zone_foreach(void (*zfunc)(uma_zone_t));
256 static void zone_timeout(uma_zone_t zone);
257 static int hash_alloc(struct uma_hash *);
258 static int hash_expand(struct uma_hash *, struct uma_hash *);
259 static void hash_free(struct uma_hash *hash);
260 static void uma_timeout(void *);
261 static void uma_startup3(void);
262 static void *zone_alloc_item(uma_zone_t, void *, int, int);
263 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
264 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
265 static void bucket_enable(void);
266 static void bucket_init(void);
267 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
268 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
269 static void bucket_zone_drain(void);
270 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
271 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
272 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
273 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
274 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
275 uma_fini fini, int align, uint32_t flags);
276 static int zone_import(uma_zone_t, void **, int, int, int);
277 static void zone_release(uma_zone_t, void **, int);
278 static void uma_zero_item(void *, uma_zone_t);
280 void uma_print_zone(uma_zone_t);
281 void uma_print_stats(void);
282 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
283 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
286 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
287 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
288 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
289 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
291 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
292 "Memory allocation debugging");
294 static u_int dbg_divisor = 1;
295 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
296 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
297 "Debug & thrash every this item in memory allocator");
299 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
300 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
301 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
302 &uma_dbg_cnt, "memory items debugged");
303 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
304 &uma_skip_cnt, "memory items skipped, not debugged");
307 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
309 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
310 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
312 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
313 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
315 static int zone_warnings = 1;
316 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
317 "Warn when UMA zones becomes full");
319 /* Adjust bytes under management by UMA. */
321 uma_total_dec(unsigned long size)
324 atomic_subtract_long(&uma_kmem_total, size);
328 uma_total_inc(unsigned long size)
331 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
332 uma_reclaim_wakeup();
336 * This routine checks to see whether or not it's safe to enable buckets.
341 bucketdisable = vm_page_count_min();
345 * Initialize bucket_zones, the array of zones of buckets of various sizes.
347 * For each zone, calculate the memory required for each bucket, consisting
348 * of the header and an array of pointers.
353 struct uma_bucket_zone *ubz;
356 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
357 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
358 size += sizeof(void *) * ubz->ubz_entries;
359 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
360 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
361 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
366 * Given a desired number of entries for a bucket, return the zone from which
367 * to allocate the bucket.
369 static struct uma_bucket_zone *
370 bucket_zone_lookup(int entries)
372 struct uma_bucket_zone *ubz;
374 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
375 if (ubz->ubz_entries >= entries)
382 bucket_select(int size)
384 struct uma_bucket_zone *ubz;
386 ubz = &bucket_zones[0];
387 if (size > ubz->ubz_maxsize)
388 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
390 for (; ubz->ubz_entries != 0; ubz++)
391 if (ubz->ubz_maxsize < size)
394 return (ubz->ubz_entries);
398 bucket_alloc(uma_zone_t zone, void *udata, int flags)
400 struct uma_bucket_zone *ubz;
404 * This is to stop us from allocating per cpu buckets while we're
405 * running out of vm.boot_pages. Otherwise, we would exhaust the
406 * boot pages. This also prevents us from allocating buckets in
407 * low memory situations.
412 * To limit bucket recursion we store the original zone flags
413 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
414 * NOVM flag to persist even through deep recursions. We also
415 * store ZFLAG_BUCKET once we have recursed attempting to allocate
416 * a bucket for a bucket zone so we do not allow infinite bucket
417 * recursion. This cookie will even persist to frees of unused
418 * buckets via the allocation path or bucket allocations in the
421 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
422 udata = (void *)(uintptr_t)zone->uz_flags;
424 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
426 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
428 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
430 ubz = bucket_zone_lookup(zone->uz_count);
431 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
433 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
436 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
439 bucket->ub_entries = ubz->ubz_entries;
446 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
448 struct uma_bucket_zone *ubz;
450 KASSERT(bucket->ub_cnt == 0,
451 ("bucket_free: Freeing a non free bucket."));
452 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
453 udata = (void *)(uintptr_t)zone->uz_flags;
454 ubz = bucket_zone_lookup(bucket->ub_entries);
455 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
459 bucket_zone_drain(void)
461 struct uma_bucket_zone *ubz;
463 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
464 zone_drain(ubz->ubz_zone);
468 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
472 ZONE_LOCK_ASSERT(zone);
474 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
475 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
476 LIST_REMOVE(bucket, ub_link);
477 zdom->uzd_nitems -= bucket->ub_cnt;
478 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
479 zdom->uzd_imin = zdom->uzd_nitems;
480 zone->uz_bkt_count -= bucket->ub_cnt;
486 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
490 ZONE_LOCK_ASSERT(zone);
491 KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
494 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
495 zdom->uzd_nitems += bucket->ub_cnt;
496 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
497 zdom->uzd_imax = zdom->uzd_nitems;
498 zone->uz_bkt_count += bucket->ub_cnt;
502 zone_log_warning(uma_zone_t zone)
504 static const struct timeval warninterval = { 300, 0 };
506 if (!zone_warnings || zone->uz_warning == NULL)
509 if (ratecheck(&zone->uz_ratecheck, &warninterval))
510 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
514 zone_maxaction(uma_zone_t zone)
517 if (zone->uz_maxaction.ta_func != NULL)
518 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
522 * Routine called by timeout which is used to fire off some time interval
523 * based calculations. (stats, hash size, etc.)
532 uma_timeout(void *unused)
535 zone_foreach(zone_timeout);
537 /* Reschedule this event */
538 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
542 * Update the working set size estimate for the zone's bucket cache.
543 * The constants chosen here are somewhat arbitrary. With an update period of
544 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
548 zone_domain_update_wss(uma_zone_domain_t zdom)
552 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
553 wss = zdom->uzd_imax - zdom->uzd_imin;
554 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
555 zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
559 * Routine to perform timeout driven calculations. This expands the
560 * hashes and does per cpu statistics aggregation.
565 zone_timeout(uma_zone_t zone)
567 uma_keg_t keg = zone->uz_keg;
571 * Expand the keg hash table.
573 * This is done if the number of slabs is larger than the hash size.
574 * What I'm trying to do here is completely reduce collisions. This
575 * may be a little aggressive. Should I allow for two collisions max?
577 if (keg->uk_flags & UMA_ZONE_HASH &&
578 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
579 struct uma_hash newhash;
580 struct uma_hash oldhash;
584 * This is so involved because allocating and freeing
585 * while the keg lock is held will lead to deadlock.
586 * I have to do everything in stages and check for
589 newhash = keg->uk_hash;
591 ret = hash_alloc(&newhash);
594 if (hash_expand(&keg->uk_hash, &newhash)) {
595 oldhash = keg->uk_hash;
596 keg->uk_hash = newhash;
606 for (int i = 0; i < vm_ndomains; i++)
607 zone_domain_update_wss(&zone->uz_domain[i]);
613 * Allocate and zero fill the next sized hash table from the appropriate
617 * hash A new hash structure with the old hash size in uh_hashsize
620 * 1 on success and 0 on failure.
623 hash_alloc(struct uma_hash *hash)
628 oldsize = hash->uh_hashsize;
630 /* We're just going to go to a power of two greater */
632 hash->uh_hashsize = oldsize * 2;
633 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
634 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
635 M_UMAHASH, M_NOWAIT);
637 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
638 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
639 UMA_ANYDOMAIN, M_WAITOK);
640 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
642 if (hash->uh_slab_hash) {
643 bzero(hash->uh_slab_hash, alloc);
644 hash->uh_hashmask = hash->uh_hashsize - 1;
652 * Expands the hash table for HASH zones. This is done from zone_timeout
653 * to reduce collisions. This must not be done in the regular allocation
654 * path, otherwise, we can recurse on the vm while allocating pages.
657 * oldhash The hash you want to expand
658 * newhash The hash structure for the new table
666 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
672 if (!newhash->uh_slab_hash)
675 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
679 * I need to investigate hash algorithms for resizing without a
683 for (i = 0; i < oldhash->uh_hashsize; i++)
684 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
685 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
686 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
687 hval = UMA_HASH(newhash, slab->us_data);
688 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
696 * Free the hash bucket to the appropriate backing store.
699 * slab_hash The hash bucket we're freeing
700 * hashsize The number of entries in that hash bucket
706 hash_free(struct uma_hash *hash)
708 if (hash->uh_slab_hash == NULL)
710 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
711 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
713 free(hash->uh_slab_hash, M_UMAHASH);
717 * Frees all outstanding items in a bucket
720 * zone The zone to free to, must be unlocked.
721 * bucket The free/alloc bucket with items, cpu queue must be locked.
728 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
736 for (i = 0; i < bucket->ub_cnt; i++)
737 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
738 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
739 if (zone->uz_max_items > 0) {
741 zone->uz_items -= bucket->ub_cnt;
742 if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
750 * Drains the per cpu caches for a zone.
752 * NOTE: This may only be called while the zone is being turn down, and not
753 * during normal operation. This is necessary in order that we do not have
754 * to migrate CPUs to drain the per-CPU caches.
757 * zone The zone to drain, must be unlocked.
763 cache_drain(uma_zone_t zone)
769 * XXX: It is safe to not lock the per-CPU caches, because we're
770 * tearing down the zone anyway. I.e., there will be no further use
771 * of the caches at this point.
773 * XXX: It would good to be able to assert that the zone is being
774 * torn down to prevent improper use of cache_drain().
776 * XXX: We lock the zone before passing into bucket_cache_drain() as
777 * it is used elsewhere. Should the tear-down path be made special
778 * there in some form?
781 cache = &zone->uz_cpu[cpu];
782 bucket_drain(zone, cache->uc_allocbucket);
783 bucket_drain(zone, cache->uc_freebucket);
784 if (cache->uc_allocbucket != NULL)
785 bucket_free(zone, cache->uc_allocbucket, NULL);
786 if (cache->uc_freebucket != NULL)
787 bucket_free(zone, cache->uc_freebucket, NULL);
788 cache->uc_allocbucket = cache->uc_freebucket = NULL;
791 bucket_cache_drain(zone);
796 cache_shrink(uma_zone_t zone)
799 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
803 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
808 cache_drain_safe_cpu(uma_zone_t zone)
814 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
820 if (zone->uz_flags & UMA_ZONE_NUMA)
821 domain = PCPU_GET(domain);
824 cache = &zone->uz_cpu[curcpu];
825 if (cache->uc_allocbucket) {
826 if (cache->uc_allocbucket->ub_cnt != 0)
827 zone_put_bucket(zone, &zone->uz_domain[domain],
828 cache->uc_allocbucket, false);
830 b1 = cache->uc_allocbucket;
831 cache->uc_allocbucket = NULL;
833 if (cache->uc_freebucket) {
834 if (cache->uc_freebucket->ub_cnt != 0)
835 zone_put_bucket(zone, &zone->uz_domain[domain],
836 cache->uc_freebucket, false);
838 b2 = cache->uc_freebucket;
839 cache->uc_freebucket = NULL;
844 bucket_free(zone, b1, NULL);
846 bucket_free(zone, b2, NULL);
850 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
851 * This is an expensive call because it needs to bind to all CPUs
852 * one by one and enter a critical section on each of them in order
853 * to safely access their cache buckets.
854 * Zone lock must not be held on call this function.
857 cache_drain_safe(uma_zone_t zone)
862 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
867 zone_foreach(cache_shrink);
870 thread_lock(curthread);
871 sched_bind(curthread, cpu);
872 thread_unlock(curthread);
875 cache_drain_safe_cpu(zone);
877 zone_foreach(cache_drain_safe_cpu);
879 thread_lock(curthread);
880 sched_unbind(curthread);
881 thread_unlock(curthread);
885 * Drain the cached buckets from a zone. Expects a locked zone on entry.
888 bucket_cache_drain(uma_zone_t zone)
890 uma_zone_domain_t zdom;
895 * Drain the bucket queues and free the buckets.
897 for (i = 0; i < vm_ndomains; i++) {
898 zdom = &zone->uz_domain[i];
899 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
902 bucket_drain(zone, bucket);
903 bucket_free(zone, bucket, NULL);
909 * Shrink further bucket sizes. Price of single zone lock collision
910 * is probably lower then price of global cache drain.
912 if (zone->uz_count > zone->uz_count_min)
917 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
923 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
924 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
927 flags = slab->us_flags;
929 if (keg->uk_fini != NULL) {
930 for (i--; i > -1; i--)
933 * trash_fini implies that dtor was trash_dtor. trash_fini
934 * would check that memory hasn't been modified since free,
935 * which executed trash_dtor.
936 * That's why we need to run uma_dbg_kskip() check here,
937 * albeit we don't make skip check for other init/fini
940 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
941 keg->uk_fini != trash_fini)
943 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
946 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
947 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
948 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
949 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
953 * Frees pages from a keg back to the system. This is done on demand from
954 * the pageout daemon.
959 keg_drain(uma_keg_t keg)
961 struct slabhead freeslabs = { 0 };
963 uma_slab_t slab, tmp;
967 * We don't want to take pages from statically allocated kegs at this
970 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
973 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
974 keg->uk_name, keg, keg->uk_free);
976 if (keg->uk_free == 0)
979 for (i = 0; i < vm_ndomains; i++) {
980 dom = &keg->uk_domain[i];
981 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
982 /* We have nowhere to free these to. */
983 if (slab->us_flags & UMA_SLAB_BOOT)
986 LIST_REMOVE(slab, us_link);
987 keg->uk_pages -= keg->uk_ppera;
988 keg->uk_free -= keg->uk_ipers;
990 if (keg->uk_flags & UMA_ZONE_HASH)
991 UMA_HASH_REMOVE(&keg->uk_hash, slab,
994 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1001 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1002 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1003 keg_free_slab(keg, slab, keg->uk_ipers);
1008 zone_drain_wait(uma_zone_t zone, int waitok)
1012 * Set draining to interlock with zone_dtor() so we can release our
1013 * locks as we go. Only dtor() should do a WAITOK call since it
1014 * is the only call that knows the structure will still be available
1018 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1019 if (waitok == M_NOWAIT)
1021 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1023 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1024 bucket_cache_drain(zone);
1027 * The DRAINING flag protects us from being freed while
1028 * we're running. Normally the uma_rwlock would protect us but we
1029 * must be able to release and acquire the right lock for each keg.
1031 keg_drain(zone->uz_keg);
1033 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1040 zone_drain(uma_zone_t zone)
1043 zone_drain_wait(zone, M_NOWAIT);
1047 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1048 * If the allocation was successful, the keg lock will be held upon return,
1049 * otherwise the keg will be left unlocked.
1052 * wait Shall we wait?
1055 * The slab that was allocated or NULL if there is no memory and the
1056 * caller specified M_NOWAIT.
1059 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int wait)
1068 KASSERT(domain >= 0 && domain < vm_ndomains,
1069 ("keg_alloc_slab: domain %d out of range", domain));
1070 KEG_LOCK_ASSERT(keg);
1071 MPASS(zone->uz_lockptr == &keg->uk_lock);
1073 allocf = keg->uk_allocf;
1078 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1079 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, wait);
1085 * This reproduces the old vm_zone behavior of zero filling pages the
1086 * first time they are added to a zone.
1088 * Malloced items are zeroed in uma_zalloc.
1091 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1096 if (keg->uk_flags & UMA_ZONE_NODUMP)
1099 /* zone is passed for legacy reasons. */
1100 size = keg->uk_ppera * PAGE_SIZE;
1101 mem = allocf(zone, size, domain, &flags, wait);
1103 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1104 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1108 uma_total_inc(size);
1110 /* Point the slab into the allocated memory */
1111 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1112 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1114 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1115 for (i = 0; i < keg->uk_ppera; i++)
1116 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1119 slab->us_data = mem;
1120 slab->us_freecount = keg->uk_ipers;
1121 slab->us_flags = flags;
1122 slab->us_domain = domain;
1123 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1125 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1128 if (keg->uk_init != NULL) {
1129 for (i = 0; i < keg->uk_ipers; i++)
1130 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1131 keg->uk_size, wait) != 0)
1133 if (i != keg->uk_ipers) {
1134 keg_free_slab(keg, slab, i);
1141 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1142 slab, keg->uk_name, keg);
1144 if (keg->uk_flags & UMA_ZONE_HASH)
1145 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1147 keg->uk_pages += keg->uk_ppera;
1148 keg->uk_free += keg->uk_ipers;
1155 * This function is intended to be used early on in place of page_alloc() so
1156 * that we may use the boot time page cache to satisfy allocations before
1160 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1169 * If we are in BOOT_BUCKETS or higher, than switch to real
1170 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1176 case BOOT_PAGEALLOC:
1177 if (keg->uk_ppera > 1)
1181 #ifdef UMA_MD_SMALL_ALLOC
1182 keg->uk_allocf = (keg->uk_ppera > 1) ?
1183 page_alloc : uma_small_alloc;
1185 keg->uk_allocf = page_alloc;
1187 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1191 * Check our small startup cache to see if it has pages remaining.
1193 pages = howmany(bytes, PAGE_SIZE);
1194 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1195 if (pages > boot_pages)
1196 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1198 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1202 boot_pages -= pages;
1203 bootmem += pages * PAGE_SIZE;
1204 *pflag = UMA_SLAB_BOOT;
1210 * Allocates a number of pages from the system
1213 * bytes The number of bytes requested
1214 * wait Shall we wait?
1217 * A pointer to the alloced memory or possibly
1218 * NULL if M_NOWAIT is set.
1221 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1224 void *p; /* Returned page */
1226 *pflag = UMA_SLAB_KERNEL;
1227 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1233 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1236 struct pglist alloctail;
1237 vm_offset_t addr, zkva;
1239 vm_page_t p, p_next;
1244 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1246 TAILQ_INIT(&alloctail);
1247 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1248 malloc2vm_flags(wait);
1249 *pflag = UMA_SLAB_KERNEL;
1250 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1251 if (CPU_ABSENT(cpu)) {
1252 p = vm_page_alloc(NULL, 0, flags);
1255 p = vm_page_alloc(NULL, 0, flags);
1257 pc = pcpu_find(cpu);
1258 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1259 if (__predict_false(p == NULL))
1260 p = vm_page_alloc(NULL, 0, flags);
1263 if (__predict_false(p == NULL))
1265 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1267 if ((addr = kva_alloc(bytes)) == 0)
1270 TAILQ_FOREACH(p, &alloctail, listq) {
1271 pmap_qenter(zkva, &p, 1);
1274 return ((void*)addr);
1276 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1277 vm_page_unwire(p, PQ_NONE);
1284 * Allocates a number of pages from within an object
1287 * bytes The number of bytes requested
1288 * wait Shall we wait?
1291 * A pointer to the alloced memory or possibly
1292 * NULL if M_NOWAIT is set.
1295 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1298 TAILQ_HEAD(, vm_page) alloctail;
1300 vm_offset_t retkva, zkva;
1301 vm_page_t p, p_next;
1304 TAILQ_INIT(&alloctail);
1307 npages = howmany(bytes, PAGE_SIZE);
1308 while (npages > 0) {
1309 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1310 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1311 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1315 * Since the page does not belong to an object, its
1318 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1323 * Page allocation failed, free intermediate pages and
1326 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1327 vm_page_unwire(p, PQ_NONE);
1332 *flags = UMA_SLAB_PRIV;
1333 zkva = keg->uk_kva +
1334 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1336 TAILQ_FOREACH(p, &alloctail, listq) {
1337 pmap_qenter(zkva, &p, 1);
1341 return ((void *)retkva);
1345 * Frees a number of pages to the system
1348 * mem A pointer to the memory to be freed
1349 * size The size of the memory being freed
1350 * flags The original p->us_flags field
1356 page_free(void *mem, vm_size_t size, uint8_t flags)
1359 if ((flags & UMA_SLAB_KERNEL) == 0)
1360 panic("UMA: page_free used with invalid flags %x", flags);
1362 kmem_free((vm_offset_t)mem, size);
1366 * Frees pcpu zone allocations
1369 * mem A pointer to the memory to be freed
1370 * size The size of the memory being freed
1371 * flags The original p->us_flags field
1377 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1379 vm_offset_t sva, curva;
1383 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1384 sva = (vm_offset_t)mem;
1385 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1386 paddr = pmap_kextract(curva);
1387 m = PHYS_TO_VM_PAGE(paddr);
1388 vm_page_unwire(m, PQ_NONE);
1391 pmap_qremove(sva, size >> PAGE_SHIFT);
1392 kva_free(sva, size);
1397 * Zero fill initializer
1399 * Arguments/Returns follow uma_init specifications
1402 zero_init(void *mem, int size, int flags)
1409 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1412 * keg The zone we should initialize
1418 keg_small_init(uma_keg_t keg)
1426 if (keg->uk_flags & UMA_ZONE_PCPU) {
1427 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1429 slabsize = UMA_PCPU_ALLOC_SIZE;
1430 keg->uk_ppera = ncpus;
1432 slabsize = UMA_SLAB_SIZE;
1437 * Calculate the size of each allocation (rsize) according to
1438 * alignment. If the requested size is smaller than we have
1439 * allocation bits for we round it up.
1441 rsize = keg->uk_size;
1442 if (rsize < slabsize / SLAB_SETSIZE)
1443 rsize = slabsize / SLAB_SETSIZE;
1444 if (rsize & keg->uk_align)
1445 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1446 keg->uk_rsize = rsize;
1448 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1449 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1450 ("%s: size %u too large", __func__, keg->uk_rsize));
1452 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1455 shsize = SIZEOF_UMA_SLAB;
1457 if (rsize <= slabsize - shsize)
1458 keg->uk_ipers = (slabsize - shsize) / rsize;
1460 /* Handle special case when we have 1 item per slab, so
1461 * alignment requirement can be relaxed. */
1462 KASSERT(keg->uk_size <= slabsize - shsize,
1463 ("%s: size %u greater than slab", __func__, keg->uk_size));
1466 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1467 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1469 memused = keg->uk_ipers * rsize + shsize;
1470 wastedspace = slabsize - memused;
1473 * We can't do OFFPAGE if we're internal or if we've been
1474 * asked to not go to the VM for buckets. If we do this we
1475 * may end up going to the VM for slabs which we do not
1476 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1477 * of UMA_ZONE_VM, which clearly forbids it.
1479 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1480 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1484 * See if using an OFFPAGE slab will limit our waste. Only do
1485 * this if it permits more items per-slab.
1487 * XXX We could try growing slabsize to limit max waste as well.
1488 * Historically this was not done because the VM could not
1489 * efficiently handle contiguous allocations.
1491 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1492 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1493 keg->uk_ipers = slabsize / keg->uk_rsize;
1494 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1495 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1496 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1497 "keg: %s(%p), calculated wastedspace = %d, "
1498 "maximum wasted space allowed = %d, "
1499 "calculated ipers = %d, "
1500 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1501 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1502 slabsize - keg->uk_ipers * keg->uk_rsize);
1503 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1506 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1507 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1508 keg->uk_flags |= UMA_ZONE_HASH;
1512 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1513 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1517 * keg The keg we should initialize
1523 keg_large_init(uma_keg_t keg)
1526 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1527 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1528 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1530 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1532 keg->uk_rsize = keg->uk_size;
1534 /* Check whether we have enough space to not do OFFPAGE. */
1535 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1536 PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1538 * We can't do OFFPAGE if we're internal, in which case
1539 * we need an extra page per allocation to contain the
1542 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1543 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1548 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1549 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1550 keg->uk_flags |= UMA_ZONE_HASH;
1554 keg_cachespread_init(uma_keg_t keg)
1561 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1562 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1564 alignsize = keg->uk_align + 1;
1565 rsize = keg->uk_size;
1567 * We want one item to start on every align boundary in a page. To
1568 * do this we will span pages. We will also extend the item by the
1569 * size of align if it is an even multiple of align. Otherwise, it
1570 * would fall on the same boundary every time.
1572 if (rsize & keg->uk_align)
1573 rsize = (rsize & ~keg->uk_align) + alignsize;
1574 if ((rsize & alignsize) == 0)
1576 trailer = rsize - keg->uk_size;
1577 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1578 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1579 keg->uk_rsize = rsize;
1580 keg->uk_ppera = pages;
1581 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1582 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1583 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1584 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1589 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1590 * the keg onto the global keg list.
1592 * Arguments/Returns follow uma_ctor specifications
1593 * udata Actually uma_kctor_args
1596 keg_ctor(void *mem, int size, void *udata, int flags)
1598 struct uma_kctor_args *arg = udata;
1599 uma_keg_t keg = mem;
1603 keg->uk_size = arg->size;
1604 keg->uk_init = arg->uminit;
1605 keg->uk_fini = arg->fini;
1606 keg->uk_align = arg->align;
1608 keg->uk_reserve = 0;
1610 keg->uk_flags = arg->flags;
1611 keg->uk_slabzone = NULL;
1614 * We use a global round-robin policy by default. Zones with
1615 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1616 * iterator is never run.
1618 keg->uk_dr.dr_policy = DOMAINSET_RR();
1619 keg->uk_dr.dr_iter = 0;
1622 * The master zone is passed to us at keg-creation time.
1625 keg->uk_name = zone->uz_name;
1627 if (arg->flags & UMA_ZONE_VM)
1628 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1630 if (arg->flags & UMA_ZONE_ZINIT)
1631 keg->uk_init = zero_init;
1633 if (arg->flags & UMA_ZONE_MALLOC)
1634 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1636 if (arg->flags & UMA_ZONE_PCPU)
1638 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1640 keg->uk_flags &= ~UMA_ZONE_PCPU;
1643 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1644 keg_cachespread_init(keg);
1646 if (keg->uk_size > UMA_SLAB_SPACE)
1647 keg_large_init(keg);
1649 keg_small_init(keg);
1652 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1653 keg->uk_slabzone = slabzone;
1656 * If we haven't booted yet we need allocations to go through the
1657 * startup cache until the vm is ready.
1659 if (booted < BOOT_PAGEALLOC)
1660 keg->uk_allocf = startup_alloc;
1661 #ifdef UMA_MD_SMALL_ALLOC
1662 else if (keg->uk_ppera == 1)
1663 keg->uk_allocf = uma_small_alloc;
1665 else if (keg->uk_flags & UMA_ZONE_PCPU)
1666 keg->uk_allocf = pcpu_page_alloc;
1668 keg->uk_allocf = page_alloc;
1669 #ifdef UMA_MD_SMALL_ALLOC
1670 if (keg->uk_ppera == 1)
1671 keg->uk_freef = uma_small_free;
1674 if (keg->uk_flags & UMA_ZONE_PCPU)
1675 keg->uk_freef = pcpu_page_free;
1677 keg->uk_freef = page_free;
1680 * Initialize keg's lock
1682 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1685 * If we're putting the slab header in the actual page we need to
1686 * figure out where in each page it goes. See SIZEOF_UMA_SLAB
1689 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1690 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1692 * The only way the following is possible is if with our
1693 * UMA_ALIGN_PTR adjustments we are now bigger than
1694 * UMA_SLAB_SIZE. I haven't checked whether this is
1695 * mathematically possible for all cases, so we make
1698 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1699 PAGE_SIZE * keg->uk_ppera,
1700 ("zone %s ipers %d rsize %d size %d slab won't fit",
1701 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1704 if (keg->uk_flags & UMA_ZONE_HASH)
1705 hash_alloc(&keg->uk_hash);
1707 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1708 keg, zone->uz_name, zone,
1709 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1712 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1714 rw_wlock(&uma_rwlock);
1715 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1716 rw_wunlock(&uma_rwlock);
1721 zone_alloc_counters(uma_zone_t zone)
1724 zone->uz_allocs = counter_u64_alloc(M_WAITOK);
1725 zone->uz_frees = counter_u64_alloc(M_WAITOK);
1726 zone->uz_fails = counter_u64_alloc(M_WAITOK);
1730 * Zone header ctor. This initializes all fields, locks, etc.
1732 * Arguments/Returns follow uma_ctor specifications
1733 * udata Actually uma_zctor_args
1736 zone_ctor(void *mem, int size, void *udata, int flags)
1738 struct uma_zctor_args *arg = udata;
1739 uma_zone_t zone = mem;
1744 zone->uz_name = arg->name;
1745 zone->uz_ctor = arg->ctor;
1746 zone->uz_dtor = arg->dtor;
1747 zone->uz_slab = zone_fetch_slab;
1748 zone->uz_init = NULL;
1749 zone->uz_fini = NULL;
1750 zone->uz_sleeps = 0;
1752 zone->uz_count_min = 0;
1753 zone->uz_count_max = BUCKET_MAX;
1755 zone->uz_warning = NULL;
1756 /* The domain structures follow the cpu structures. */
1757 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1758 zone->uz_bkt_max = ULONG_MAX;
1759 timevalclear(&zone->uz_ratecheck);
1761 if (__predict_true(booted == BOOT_RUNNING))
1762 zone_alloc_counters(zone);
1764 zone->uz_allocs = EARLY_COUNTER;
1765 zone->uz_frees = EARLY_COUNTER;
1766 zone->uz_fails = EARLY_COUNTER;
1770 * This is a pure cache zone, no kegs.
1773 if (arg->flags & UMA_ZONE_VM)
1774 arg->flags |= UMA_ZFLAG_CACHEONLY;
1775 zone->uz_flags = arg->flags;
1776 zone->uz_size = arg->size;
1777 zone->uz_import = arg->import;
1778 zone->uz_release = arg->release;
1779 zone->uz_arg = arg->arg;
1780 zone->uz_lockptr = &zone->uz_lock;
1781 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1782 rw_wlock(&uma_rwlock);
1783 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1784 rw_wunlock(&uma_rwlock);
1789 * Use the regular zone/keg/slab allocator.
1791 zone->uz_import = (uma_import)zone_import;
1792 zone->uz_release = (uma_release)zone_release;
1793 zone->uz_arg = zone;
1796 if (arg->flags & UMA_ZONE_SECONDARY) {
1797 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1798 zone->uz_init = arg->uminit;
1799 zone->uz_fini = arg->fini;
1800 zone->uz_lockptr = &keg->uk_lock;
1801 zone->uz_flags |= UMA_ZONE_SECONDARY;
1802 rw_wlock(&uma_rwlock);
1804 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1805 if (LIST_NEXT(z, uz_link) == NULL) {
1806 LIST_INSERT_AFTER(z, zone, uz_link);
1811 rw_wunlock(&uma_rwlock);
1812 } else if (keg == NULL) {
1813 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1814 arg->align, arg->flags)) == NULL)
1817 struct uma_kctor_args karg;
1820 /* We should only be here from uma_startup() */
1821 karg.size = arg->size;
1822 karg.uminit = arg->uminit;
1823 karg.fini = arg->fini;
1824 karg.align = arg->align;
1825 karg.flags = arg->flags;
1827 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1834 zone->uz_size = keg->uk_size;
1835 zone->uz_flags |= (keg->uk_flags &
1836 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1839 * Some internal zones don't have room allocated for the per cpu
1840 * caches. If we're internal, bail out here.
1842 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1843 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1844 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1849 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1850 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1851 ("Invalid zone flag combination"));
1852 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1853 zone->uz_count = BUCKET_MAX;
1854 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1857 zone->uz_count = bucket_select(zone->uz_size);
1858 zone->uz_count_min = zone->uz_count;
1864 * Keg header dtor. This frees all data, destroys locks, frees the hash
1865 * table and removes the keg from the global list.
1867 * Arguments/Returns follow uma_dtor specifications
1871 keg_dtor(void *arg, int size, void *udata)
1875 keg = (uma_keg_t)arg;
1877 if (keg->uk_free != 0) {
1878 printf("Freed UMA keg (%s) was not empty (%d items). "
1879 " Lost %d pages of memory.\n",
1880 keg->uk_name ? keg->uk_name : "",
1881 keg->uk_free, keg->uk_pages);
1885 hash_free(&keg->uk_hash);
1893 * Arguments/Returns follow uma_dtor specifications
1897 zone_dtor(void *arg, int size, void *udata)
1902 zone = (uma_zone_t)arg;
1904 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1907 rw_wlock(&uma_rwlock);
1908 LIST_REMOVE(zone, uz_link);
1909 rw_wunlock(&uma_rwlock);
1911 * XXX there are some races here where
1912 * the zone can be drained but zone lock
1913 * released and then refilled before we
1914 * remove it... we dont care for now
1916 zone_drain_wait(zone, M_WAITOK);
1918 * We only destroy kegs from non secondary zones.
1920 if ((keg = zone->uz_keg) != NULL &&
1921 (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1922 rw_wlock(&uma_rwlock);
1923 LIST_REMOVE(keg, uk_link);
1924 rw_wunlock(&uma_rwlock);
1925 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1927 counter_u64_free(zone->uz_allocs);
1928 counter_u64_free(zone->uz_frees);
1929 counter_u64_free(zone->uz_fails);
1930 if (zone->uz_lockptr == &zone->uz_lock)
1931 ZONE_LOCK_FINI(zone);
1935 * Traverses every zone in the system and calls a callback
1938 * zfunc A pointer to a function which accepts a zone
1945 zone_foreach(void (*zfunc)(uma_zone_t))
1951 * Before BOOT_RUNNING we are guaranteed to be single
1952 * threaded, so locking isn't needed. Startup functions
1953 * are allowed to use M_WAITOK.
1955 if (__predict_true(booted == BOOT_RUNNING))
1956 rw_rlock(&uma_rwlock);
1957 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1958 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1961 if (__predict_true(booted == BOOT_RUNNING))
1962 rw_runlock(&uma_rwlock);
1966 * Count how many pages do we need to bootstrap. VM supplies
1967 * its need in early zones in the argument, we add up our zones,
1968 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1969 * zone of zones and zone of kegs are accounted separately.
1971 #define UMA_BOOT_ZONES 11
1972 /* Zone of zones and zone of kegs have arbitrary alignment. */
1973 #define UMA_BOOT_ALIGN 32
1974 static int zsize, ksize;
1976 uma_startup_count(int vm_zones)
1980 ksize = sizeof(struct uma_keg) +
1981 (sizeof(struct uma_domain) * vm_ndomains);
1982 zsize = sizeof(struct uma_zone) +
1983 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1984 (sizeof(struct uma_zone_domain) * vm_ndomains);
1987 * Memory for the zone of kegs and its keg,
1988 * and for zone of zones.
1990 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1991 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1993 #ifdef UMA_MD_SMALL_ALLOC
1994 zones = UMA_BOOT_ZONES;
1996 zones = UMA_BOOT_ZONES + vm_zones;
2000 /* Memory for the rest of startup zones, UMA and VM, ... */
2001 if (zsize > UMA_SLAB_SPACE) {
2002 /* See keg_large_init(). */
2005 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
2006 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2009 pages += (zones + vm_zones) * ppera;
2010 } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2011 /* See keg_small_init() special case for uk_ppera = 1. */
2014 pages += howmany(zones,
2015 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2017 /* ... and their kegs. Note that zone of zones allocates a keg! */
2018 pages += howmany(zones + 1,
2019 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2022 * Most of startup zones are not going to be offpages, that's
2023 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2024 * calculations. Some large bucket zones will be offpage, and
2025 * thus will allocate hashes. We take conservative approach
2026 * and assume that all zones may allocate hash. This may give
2027 * us some positive inaccuracy, usually an extra single page.
2029 pages += howmany(zones, UMA_SLAB_SPACE /
2030 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2036 uma_startup(void *mem, int npages)
2038 struct uma_zctor_args args;
2039 uma_keg_t masterkeg;
2043 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2046 rw_init(&uma_rwlock, "UMA lock");
2048 /* Use bootpages memory for the zone of zones and zone of kegs. */
2050 zones = (uma_zone_t)m;
2051 m += roundup(zsize, CACHE_LINE_SIZE);
2052 kegs = (uma_zone_t)m;
2053 m += roundup(zsize, CACHE_LINE_SIZE);
2054 masterkeg = (uma_keg_t)m;
2055 m += roundup(ksize, CACHE_LINE_SIZE);
2056 m = roundup(m, PAGE_SIZE);
2057 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2060 /* "manually" create the initial zone */
2061 memset(&args, 0, sizeof(args));
2062 args.name = "UMA Kegs";
2064 args.ctor = keg_ctor;
2065 args.dtor = keg_dtor;
2066 args.uminit = zero_init;
2068 args.keg = masterkeg;
2069 args.align = UMA_BOOT_ALIGN - 1;
2070 args.flags = UMA_ZFLAG_INTERNAL;
2071 zone_ctor(kegs, zsize, &args, M_WAITOK);
2074 boot_pages = npages;
2076 args.name = "UMA Zones";
2078 args.ctor = zone_ctor;
2079 args.dtor = zone_dtor;
2080 args.uminit = zero_init;
2083 args.align = UMA_BOOT_ALIGN - 1;
2084 args.flags = UMA_ZFLAG_INTERNAL;
2085 zone_ctor(zones, zsize, &args, M_WAITOK);
2087 /* Now make a zone for slab headers */
2088 slabzone = uma_zcreate("UMA Slabs",
2089 sizeof(struct uma_slab),
2090 NULL, NULL, NULL, NULL,
2091 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2093 hashzone = uma_zcreate("UMA Hash",
2094 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2095 NULL, NULL, NULL, NULL,
2096 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2100 booted = BOOT_STRAPPED;
2108 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2110 booted = BOOT_PAGEALLOC;
2118 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2120 booted = BOOT_BUCKETS;
2121 sx_init(&uma_drain_lock, "umadrain");
2126 * Initialize our callout handle
2134 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2135 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2136 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2138 zone_foreach(zone_alloc_counters);
2139 callout_init(&uma_callout, 1);
2140 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2141 booted = BOOT_RUNNING;
2145 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2146 int align, uint32_t flags)
2148 struct uma_kctor_args args;
2151 args.uminit = uminit;
2153 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2156 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2159 /* Public functions */
2162 uma_set_align(int align)
2165 if (align != UMA_ALIGN_CACHE)
2166 uma_align_cache = align;
2171 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2172 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2175 struct uma_zctor_args args;
2179 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2182 /* This stuff is essential for the zone ctor */
2183 memset(&args, 0, sizeof(args));
2188 args.uminit = uminit;
2192 * If a zone is being created with an empty constructor and
2193 * destructor, pass UMA constructor/destructor which checks for
2194 * memory use after free.
2196 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2197 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2198 args.ctor = trash_ctor;
2199 args.dtor = trash_dtor;
2200 args.uminit = trash_init;
2201 args.fini = trash_fini;
2208 if (booted < BOOT_BUCKETS) {
2211 sx_slock(&uma_drain_lock);
2214 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2216 sx_sunlock(&uma_drain_lock);
2222 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2223 uma_init zinit, uma_fini zfini, uma_zone_t master)
2225 struct uma_zctor_args args;
2230 keg = master->uz_keg;
2231 memset(&args, 0, sizeof(args));
2233 args.size = keg->uk_size;
2236 args.uminit = zinit;
2238 args.align = keg->uk_align;
2239 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2242 if (booted < BOOT_BUCKETS) {
2245 sx_slock(&uma_drain_lock);
2248 /* XXX Attaches only one keg of potentially many. */
2249 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2251 sx_sunlock(&uma_drain_lock);
2257 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2258 uma_init zinit, uma_fini zfini, uma_import zimport,
2259 uma_release zrelease, void *arg, int flags)
2261 struct uma_zctor_args args;
2263 memset(&args, 0, sizeof(args));
2268 args.uminit = zinit;
2270 args.import = zimport;
2271 args.release = zrelease;
2274 args.flags = flags | UMA_ZFLAG_CACHE;
2276 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2281 uma_zdestroy(uma_zone_t zone)
2284 sx_slock(&uma_drain_lock);
2285 zone_free_item(zones, zone, NULL, SKIP_NONE);
2286 sx_sunlock(&uma_drain_lock);
2290 uma_zwait(uma_zone_t zone)
2294 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2295 uma_zfree(zone, item);
2299 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2305 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2307 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2308 if (item != NULL && (flags & M_ZERO)) {
2310 for (i = 0; i <= mp_maxid; i++)
2311 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2313 bzero(item, zone->uz_size);
2320 * A stub while both regular and pcpu cases are identical.
2323 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2327 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2329 uma_zfree_arg(zone, item, udata);
2334 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2336 uma_zone_domain_t zdom;
2337 uma_bucket_t bucket;
2340 int cpu, domain, lockfail, maxbucket;
2345 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2346 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2348 /* This is the fast path allocation */
2349 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2350 curthread, zone->uz_name, zone, flags);
2352 if (flags & M_WAITOK) {
2353 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2354 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2356 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2357 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2358 ("uma_zalloc_arg: called with spinlock or critical section held"));
2359 if (zone->uz_flags & UMA_ZONE_PCPU)
2360 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2361 "with M_ZERO passed"));
2363 #ifdef DEBUG_MEMGUARD
2364 if (memguard_cmp_zone(zone)) {
2365 item = memguard_alloc(zone->uz_size, flags);
2367 if (zone->uz_init != NULL &&
2368 zone->uz_init(item, zone->uz_size, flags) != 0)
2370 if (zone->uz_ctor != NULL &&
2371 zone->uz_ctor(item, zone->uz_size, udata,
2373 zone->uz_fini(item, zone->uz_size);
2378 /* This is unfortunate but should not be fatal. */
2382 * If possible, allocate from the per-CPU cache. There are two
2383 * requirements for safe access to the per-CPU cache: (1) the thread
2384 * accessing the cache must not be preempted or yield during access,
2385 * and (2) the thread must not migrate CPUs without switching which
2386 * cache it accesses. We rely on a critical section to prevent
2387 * preemption and migration. We release the critical section in
2388 * order to acquire the zone mutex if we are unable to allocate from
2389 * the current cache; when we re-acquire the critical section, we
2390 * must detect and handle migration if it has occurred.
2395 cache = &zone->uz_cpu[cpu];
2398 bucket = cache->uc_allocbucket;
2399 if (bucket != NULL && bucket->ub_cnt > 0) {
2401 item = bucket->ub_bucket[bucket->ub_cnt];
2403 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2405 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2409 skipdbg = uma_dbg_zskip(zone, item);
2411 if (zone->uz_ctor != NULL &&
2413 (!skipdbg || zone->uz_ctor != trash_ctor ||
2414 zone->uz_dtor != trash_dtor) &&
2416 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2417 counter_u64_add(zone->uz_fails, 1);
2418 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2423 uma_dbg_alloc(zone, NULL, item);
2426 uma_zero_item(item, zone);
2431 * We have run out of items in our alloc bucket.
2432 * See if we can switch with our free bucket.
2434 bucket = cache->uc_freebucket;
2435 if (bucket != NULL && bucket->ub_cnt > 0) {
2437 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2438 zone->uz_name, zone);
2439 cache->uc_freebucket = cache->uc_allocbucket;
2440 cache->uc_allocbucket = bucket;
2445 * Discard any empty allocation bucket while we hold no locks.
2447 bucket = cache->uc_allocbucket;
2448 cache->uc_allocbucket = NULL;
2451 bucket_free(zone, bucket, udata);
2453 if (zone->uz_flags & UMA_ZONE_NUMA) {
2454 domain = PCPU_GET(domain);
2455 if (VM_DOMAIN_EMPTY(domain))
2456 domain = UMA_ANYDOMAIN;
2458 domain = UMA_ANYDOMAIN;
2460 /* Short-circuit for zones without buckets and low memory. */
2461 if (zone->uz_count == 0 || bucketdisable) {
2467 * Attempt to retrieve the item from the per-CPU cache has failed, so
2468 * we must go back to the zone. This requires the zone lock, so we
2469 * must drop the critical section, then re-acquire it when we go back
2470 * to the cache. Since the critical section is released, we may be
2471 * preempted or migrate. As such, make sure not to maintain any
2472 * thread-local state specific to the cache from prior to releasing
2473 * the critical section.
2476 if (ZONE_TRYLOCK(zone) == 0) {
2477 /* Record contention to size the buckets. */
2483 cache = &zone->uz_cpu[cpu];
2485 /* See if we lost the race to fill the cache. */
2486 if (cache->uc_allocbucket != NULL) {
2492 * Check the zone's cache of buckets.
2494 if (domain == UMA_ANYDOMAIN)
2495 zdom = &zone->uz_domain[0];
2497 zdom = &zone->uz_domain[domain];
2498 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2499 KASSERT(bucket->ub_cnt != 0,
2500 ("uma_zalloc_arg: Returning an empty bucket."));
2501 cache->uc_allocbucket = bucket;
2505 /* We are no longer associated with this CPU. */
2509 * We bump the uz count when the cache size is insufficient to
2510 * handle the working set.
2512 if (lockfail && zone->uz_count < zone->uz_count_max)
2515 if (zone->uz_max_items > 0) {
2516 if (zone->uz_items >= zone->uz_max_items)
2518 maxbucket = MIN(zone->uz_count,
2519 zone->uz_max_items - zone->uz_items);
2520 zone->uz_items += maxbucket;
2522 maxbucket = zone->uz_count;
2526 * Now lets just fill a bucket and put it on the free list. If that
2527 * works we'll restart the allocation from the beginning and it
2528 * will use the just filled bucket.
2530 bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2531 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2532 zone->uz_name, zone, bucket);
2534 if (bucket != NULL) {
2535 if (zone->uz_max_items > 0 && bucket->ub_cnt < maxbucket) {
2536 MPASS(zone->uz_items >= maxbucket - bucket->ub_cnt);
2537 zone->uz_items -= maxbucket - bucket->ub_cnt;
2538 if (zone->uz_sleepers > 0 &&
2539 zone->uz_items < zone->uz_max_items)
2544 cache = &zone->uz_cpu[cpu];
2547 * See if we lost the race or were migrated. Cache the
2548 * initialized bucket to make this less likely or claim
2549 * the memory directly.
2551 if (cache->uc_allocbucket == NULL &&
2552 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2553 domain == PCPU_GET(domain))) {
2554 cache->uc_allocbucket = bucket;
2555 zdom->uzd_imax += bucket->ub_cnt;
2556 } else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2559 bucket_drain(zone, bucket);
2560 bucket_free(zone, bucket, udata);
2561 goto zalloc_restart;
2563 zone_put_bucket(zone, zdom, bucket, false);
2566 } else if (zone->uz_max_items > 0) {
2567 zone->uz_items -= maxbucket;
2568 if (zone->uz_sleepers > 0 &&
2569 zone->uz_items + 1 < zone->uz_max_items)
2574 * We may not be able to get a bucket so return an actual item.
2577 item = zone_alloc_item_locked(zone, udata, domain, flags);
2583 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2586 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2587 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2589 /* This is the fast path allocation */
2591 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2592 curthread, zone->uz_name, zone, domain, flags);
2594 if (flags & M_WAITOK) {
2595 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2596 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2598 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2599 ("uma_zalloc_domain: called with spinlock or critical section held"));
2601 return (zone_alloc_item(zone, udata, domain, flags));
2605 * Find a slab with some space. Prefer slabs that are partially used over those
2606 * that are totally full. This helps to reduce fragmentation.
2608 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2612 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2618 KASSERT(domain >= 0 && domain < vm_ndomains,
2619 ("keg_first_slab: domain %d out of range", domain));
2620 KEG_LOCK_ASSERT(keg);
2625 dom = &keg->uk_domain[domain];
2626 if (!LIST_EMPTY(&dom->ud_part_slab))
2627 return (LIST_FIRST(&dom->ud_part_slab));
2628 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2629 slab = LIST_FIRST(&dom->ud_free_slab);
2630 LIST_REMOVE(slab, us_link);
2631 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2635 domain = (domain + 1) % vm_ndomains;
2636 } while (domain != start);
2642 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2646 KEG_LOCK_ASSERT(keg);
2648 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2649 if (keg->uk_free <= reserve)
2651 return (keg_first_slab(keg, domain, rr));
2655 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2657 struct vm_domainset_iter di;
2664 KEG_LOCK_ASSERT(keg);
2667 * Use the keg's policy if upper layers haven't already specified a
2668 * domain (as happens with first-touch zones).
2670 * To avoid races we run the iterator with the keg lock held, but that
2671 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2672 * clear M_WAITOK and handle low memory conditions locally.
2674 rr = rdomain == UMA_ANYDOMAIN;
2676 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2677 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2685 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2687 MPASS(slab->us_keg == keg);
2692 * M_NOVM means don't ask at all!
2697 KASSERT(zone->uz_max_items == 0 ||
2698 zone->uz_items <= zone->uz_max_items,
2699 ("%s: zone %p overflow", __func__, zone));
2701 slab = keg_alloc_slab(keg, zone, domain, aflags);
2703 * If we got a slab here it's safe to mark it partially used
2704 * and return. We assume that the caller is going to remove
2705 * at least one item.
2708 MPASS(slab->us_keg == keg);
2709 dom = &keg->uk_domain[slab->us_domain];
2710 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2714 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2715 if ((flags & M_WAITOK) != 0) {
2717 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2726 * We might not have been able to get a slab but another cpu
2727 * could have while we were unlocked. Check again before we
2730 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2731 MPASS(slab->us_keg == keg);
2738 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2748 slab = keg_fetch_slab(keg, zone, domain, flags);
2751 if (flags & (M_NOWAIT | M_NOVM))
2759 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2765 MPASS(keg == slab->us_keg);
2766 KEG_LOCK_ASSERT(keg);
2768 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2769 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2770 item = slab->us_data + (keg->uk_rsize * freei);
2771 slab->us_freecount--;
2774 /* Move this slab to the full list */
2775 if (slab->us_freecount == 0) {
2776 LIST_REMOVE(slab, us_link);
2777 dom = &keg->uk_domain[slab->us_domain];
2778 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2785 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2796 /* Try to keep the buckets totally full */
2797 for (i = 0; i < max; ) {
2798 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2802 stripe = howmany(max, vm_ndomains);
2804 while (slab->us_freecount && i < max) {
2805 bucket[i++] = slab_alloc_item(keg, slab);
2806 if (keg->uk_free <= keg->uk_reserve)
2810 * If the zone is striped we pick a new slab for every
2811 * N allocations. Eliminating this conditional will
2812 * instead pick a new domain for each bucket rather
2813 * than stripe within each bucket. The current option
2814 * produces more fragmentation and requires more cpu
2815 * time but yields better distribution.
2817 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2818 vm_ndomains > 1 && --stripe == 0)
2822 /* Don't block if we allocated any successfully. */
2833 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2835 uma_bucket_t bucket;
2837 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2839 /* Don't wait for buckets, preserve caller's NOVM setting. */
2840 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2844 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2845 max, domain, flags);
2848 * Initialize the memory if necessary.
2850 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2853 for (i = 0; i < bucket->ub_cnt; i++)
2854 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2858 * If we couldn't initialize the whole bucket, put the
2859 * rest back onto the freelist.
2861 if (i != bucket->ub_cnt) {
2862 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2863 bucket->ub_cnt - i);
2865 bzero(&bucket->ub_bucket[i],
2866 sizeof(void *) * (bucket->ub_cnt - i));
2872 if (bucket->ub_cnt == 0) {
2873 bucket_free(zone, bucket, udata);
2874 counter_u64_add(zone->uz_fails, 1);
2882 * Allocates a single item from a zone.
2885 * zone The zone to alloc for.
2886 * udata The data to be passed to the constructor.
2887 * domain The domain to allocate from or UMA_ANYDOMAIN.
2888 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2891 * NULL if there is no memory and M_NOWAIT is set
2892 * An item if successful
2896 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2900 return (zone_alloc_item_locked(zone, udata, domain, flags));
2904 * Returns with zone unlocked.
2907 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2914 ZONE_LOCK_ASSERT(zone);
2916 if (zone->uz_max_items > 0) {
2917 if (zone->uz_items >= zone->uz_max_items) {
2918 zone_log_warning(zone);
2919 zone_maxaction(zone);
2920 if (flags & M_NOWAIT) {
2925 zone->uz_sleepers++;
2926 while (zone->uz_items >= zone->uz_max_items)
2927 mtx_sleep(zone, zone->uz_lockptr, PVM,
2929 zone->uz_sleepers--;
2930 if (zone->uz_sleepers > 0 &&
2931 zone->uz_items + 1 < zone->uz_max_items)
2938 if (domain != UMA_ANYDOMAIN) {
2939 /* avoid allocs targeting empty domains */
2940 if (VM_DOMAIN_EMPTY(domain))
2941 domain = UMA_ANYDOMAIN;
2943 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
2947 skipdbg = uma_dbg_zskip(zone, item);
2950 * We have to call both the zone's init (not the keg's init)
2951 * and the zone's ctor. This is because the item is going from
2952 * a keg slab directly to the user, and the user is expecting it
2953 * to be both zone-init'd as well as zone-ctor'd.
2955 if (zone->uz_init != NULL) {
2956 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2957 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
2961 if (zone->uz_ctor != NULL &&
2963 (!skipdbg || zone->uz_ctor != trash_ctor ||
2964 zone->uz_dtor != trash_dtor) &&
2966 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2967 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2972 uma_dbg_alloc(zone, NULL, item);
2975 uma_zero_item(item, zone);
2977 counter_u64_add(zone->uz_allocs, 1);
2978 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
2979 zone->uz_name, zone);
2984 if (zone->uz_max_items > 0) {
2989 counter_u64_add(zone->uz_fails, 1);
2990 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
2991 zone->uz_name, zone);
2997 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3000 uma_bucket_t bucket;
3001 uma_zone_domain_t zdom;
3008 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3009 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3011 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3014 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3015 ("uma_zfree_arg: called with spinlock or critical section held"));
3017 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3020 #ifdef DEBUG_MEMGUARD
3021 if (is_memguard_addr(item)) {
3022 if (zone->uz_dtor != NULL)
3023 zone->uz_dtor(item, zone->uz_size, udata);
3024 if (zone->uz_fini != NULL)
3025 zone->uz_fini(item, zone->uz_size);
3026 memguard_free(item);
3031 skipdbg = uma_dbg_zskip(zone, item);
3032 if (skipdbg == false) {
3033 if (zone->uz_flags & UMA_ZONE_MALLOC)
3034 uma_dbg_free(zone, udata, item);
3036 uma_dbg_free(zone, NULL, item);
3038 if (zone->uz_dtor != NULL && (!skipdbg ||
3039 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3041 if (zone->uz_dtor != NULL)
3043 zone->uz_dtor(item, zone->uz_size, udata);
3046 * The race here is acceptable. If we miss it we'll just have to wait
3047 * a little longer for the limits to be reset.
3049 if (zone->uz_sleepers > 0)
3053 * If possible, free to the per-CPU cache. There are two
3054 * requirements for safe access to the per-CPU cache: (1) the thread
3055 * accessing the cache must not be preempted or yield during access,
3056 * and (2) the thread must not migrate CPUs without switching which
3057 * cache it accesses. We rely on a critical section to prevent
3058 * preemption and migration. We release the critical section in
3059 * order to acquire the zone mutex if we are unable to free to the
3060 * current cache; when we re-acquire the critical section, we must
3061 * detect and handle migration if it has occurred.
3066 cache = &zone->uz_cpu[cpu];
3070 * Try to free into the allocbucket first to give LIFO ordering
3071 * for cache-hot datastructures. Spill over into the freebucket
3072 * if necessary. Alloc will swap them if one runs dry.
3074 bucket = cache->uc_allocbucket;
3075 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3076 bucket = cache->uc_freebucket;
3077 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3078 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3079 ("uma_zfree: Freeing to non free bucket index."));
3080 bucket->ub_bucket[bucket->ub_cnt] = item;
3088 * We must go back the zone, which requires acquiring the zone lock,
3089 * which in turn means we must release and re-acquire the critical
3090 * section. Since the critical section is released, we may be
3091 * preempted or migrate. As such, make sure not to maintain any
3092 * thread-local state specific to the cache from prior to releasing
3093 * the critical section.
3096 if (zone->uz_count == 0 || bucketdisable)
3100 if (ZONE_TRYLOCK(zone) == 0) {
3101 /* Record contention to size the buckets. */
3107 cache = &zone->uz_cpu[cpu];
3109 bucket = cache->uc_freebucket;
3110 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3114 cache->uc_freebucket = NULL;
3115 /* We are no longer associated with this CPU. */
3118 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3119 domain = PCPU_GET(domain);
3120 if (VM_DOMAIN_EMPTY(domain))
3121 domain = UMA_ANYDOMAIN;
3124 zdom = &zone->uz_domain[0];
3126 /* Can we throw this on the zone full list? */
3127 if (bucket != NULL) {
3129 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3130 zone->uz_name, zone, bucket);
3131 /* ub_cnt is pointing to the last free item */
3132 KASSERT(bucket->ub_cnt == bucket->ub_entries,
3133 ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3134 if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3136 bucket_drain(zone, bucket);
3137 bucket_free(zone, bucket, udata);
3140 zone_put_bucket(zone, zdom, bucket, true);
3144 * We bump the uz count when the cache size is insufficient to
3145 * handle the working set.
3147 if (lockfail && zone->uz_count < zone->uz_count_max)
3151 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3152 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3153 zone->uz_name, zone, bucket);
3157 cache = &zone->uz_cpu[cpu];
3158 if (cache->uc_freebucket == NULL &&
3159 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3160 domain == PCPU_GET(domain))) {
3161 cache->uc_freebucket = bucket;
3165 * We lost the race, start over. We have to drop our
3166 * critical section to free the bucket.
3169 bucket_free(zone, bucket, udata);
3174 * If nothing else caught this, we'll just do an internal free.
3177 zone_free_item(zone, item, udata, SKIP_DTOR);
3181 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3184 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3185 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3187 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3190 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3191 ("uma_zfree_domain: called with spinlock or critical section held"));
3193 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3196 zone_free_item(zone, item, udata, SKIP_NONE);
3200 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3207 MPASS(zone->uz_lockptr == &keg->uk_lock);
3208 KEG_LOCK_ASSERT(keg);
3209 MPASS(keg == slab->us_keg);
3211 dom = &keg->uk_domain[slab->us_domain];
3213 /* Do we need to remove from any lists? */
3214 if (slab->us_freecount+1 == keg->uk_ipers) {
3215 LIST_REMOVE(slab, us_link);
3216 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3217 } else if (slab->us_freecount == 0) {
3218 LIST_REMOVE(slab, us_link);
3219 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3222 /* Slab management. */
3223 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3224 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3225 slab->us_freecount++;
3227 /* Keg statistics. */
3232 zone_release(uma_zone_t zone, void **bucket, int cnt)
3242 for (i = 0; i < cnt; i++) {
3244 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3245 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3246 if (zone->uz_flags & UMA_ZONE_HASH) {
3247 slab = hash_sfind(&keg->uk_hash, mem);
3249 mem += keg->uk_pgoff;
3250 slab = (uma_slab_t)mem;
3253 slab = vtoslab((vm_offset_t)item);
3254 MPASS(slab->us_keg == keg);
3256 slab_free_item(zone, slab, item);
3262 * Frees a single item to any zone.
3265 * zone The zone to free to
3266 * item The item we're freeing
3267 * udata User supplied data for the dtor
3268 * skip Skip dtors and finis
3271 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3276 skipdbg = uma_dbg_zskip(zone, item);
3277 if (skip == SKIP_NONE && !skipdbg) {
3278 if (zone->uz_flags & UMA_ZONE_MALLOC)
3279 uma_dbg_free(zone, udata, item);
3281 uma_dbg_free(zone, NULL, item);
3284 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3285 (!skipdbg || zone->uz_dtor != trash_dtor ||
3286 zone->uz_ctor != trash_ctor))
3288 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3290 zone->uz_dtor(item, zone->uz_size, udata);
3292 if (skip < SKIP_FINI && zone->uz_fini)
3293 zone->uz_fini(item, zone->uz_size);
3295 zone->uz_release(zone->uz_arg, &item, 1);
3297 if (skip & SKIP_CNT)
3300 counter_u64_add(zone->uz_frees, 1);
3302 if (zone->uz_max_items > 0) {
3305 if (zone->uz_sleepers > 0 &&
3306 zone->uz_items < zone->uz_max_items)
3314 uma_zone_set_max(uma_zone_t zone, int nitems)
3316 struct uma_bucket_zone *ubz;
3319 * If limit is very low we may need to limit how
3320 * much items are allowed in CPU caches.
3322 ubz = &bucket_zones[0];
3323 for (; ubz->ubz_entries != 0; ubz++)
3324 if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3326 if (ubz == &bucket_zones[0])
3327 nitems = ubz->ubz_entries * 2 * mp_ncpus;
3332 zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3333 if (zone->uz_count_min > zone->uz_count_max)
3334 zone->uz_count_min = zone->uz_count_max;
3335 zone->uz_max_items = nitems;
3343 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3347 zone->uz_bkt_max = nitems;
3355 uma_zone_get_max(uma_zone_t zone)
3360 nitems = zone->uz_max_items;
3368 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3372 zone->uz_warning = warning;
3378 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3382 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3388 uma_zone_get_cur(uma_zone_t zone)
3394 nitems = counter_u64_fetch(zone->uz_allocs) -
3395 counter_u64_fetch(zone->uz_frees);
3398 * See the comment in sysctl_vm_zone_stats() regarding the
3399 * safety of accessing the per-cpu caches. With the zone lock
3400 * held, it is safe, but can potentially result in stale data.
3402 nitems += zone->uz_cpu[i].uc_allocs -
3403 zone->uz_cpu[i].uc_frees;
3407 return (nitems < 0 ? 0 : nitems);
3412 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3418 KASSERT(keg->uk_pages == 0,
3419 ("uma_zone_set_init on non-empty keg"));
3420 keg->uk_init = uminit;
3426 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3432 KASSERT(keg->uk_pages == 0,
3433 ("uma_zone_set_fini on non-empty keg"));
3434 keg->uk_fini = fini;
3440 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3444 KASSERT(zone->uz_keg->uk_pages == 0,
3445 ("uma_zone_set_zinit on non-empty keg"));
3446 zone->uz_init = zinit;
3452 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3456 KASSERT(zone->uz_keg->uk_pages == 0,
3457 ("uma_zone_set_zfini on non-empty keg"));
3458 zone->uz_fini = zfini;
3463 /* XXX uk_freef is not actually used with the zone locked */
3465 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3470 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3472 keg->uk_freef = freef;
3477 /* XXX uk_allocf is not actually used with the zone locked */
3479 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3485 keg->uk_allocf = allocf;
3491 uma_zone_reserve(uma_zone_t zone, int items)
3497 keg->uk_reserve = items;
3503 uma_zone_reserve_kva(uma_zone_t zone, int count)
3511 pages = count / keg->uk_ipers;
3512 if (pages * keg->uk_ipers < count)
3514 pages *= keg->uk_ppera;
3516 #ifdef UMA_MD_SMALL_ALLOC
3517 if (keg->uk_ppera > 1) {
3521 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3528 MPASS(keg->uk_kva == 0);
3531 zone->uz_max_items = pages * keg->uk_ipers;
3532 #ifdef UMA_MD_SMALL_ALLOC
3533 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3535 keg->uk_allocf = noobj_alloc;
3537 keg->uk_flags |= UMA_ZONE_NOFREE;
3545 uma_prealloc(uma_zone_t zone, int items)
3547 struct vm_domainset_iter di;
3551 int domain, flags, slabs;
3555 slabs = items / keg->uk_ipers;
3556 if (slabs * keg->uk_ipers < items)
3559 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain, &flags);
3560 while (slabs-- > 0) {
3561 slab = keg_alloc_slab(keg, zone, domain, flags);
3564 MPASS(slab->us_keg == keg);
3565 dom = &keg->uk_domain[slab->us_domain];
3566 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3567 if (vm_domainset_iter_policy(&di, &domain) != 0)
3575 uma_reclaim_locked(bool kmem_danger)
3578 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3579 sx_assert(&uma_drain_lock, SA_XLOCKED);
3581 zone_foreach(zone_drain);
3582 if (vm_page_count_min() || kmem_danger) {
3583 cache_drain_safe(NULL);
3584 zone_foreach(zone_drain);
3588 * Some slabs may have been freed but this zone will be visited early
3589 * we visit again so that we can free pages that are empty once other
3590 * zones are drained. We have to do the same for buckets.
3592 zone_drain(slabzone);
3593 bucket_zone_drain();
3600 sx_xlock(&uma_drain_lock);
3601 uma_reclaim_locked(false);
3602 sx_xunlock(&uma_drain_lock);
3605 static volatile int uma_reclaim_needed;
3608 uma_reclaim_wakeup(void)
3611 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3612 wakeup(uma_reclaim);
3616 uma_reclaim_worker(void *arg __unused)
3620 sx_xlock(&uma_drain_lock);
3621 while (atomic_load_int(&uma_reclaim_needed) == 0)
3622 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3624 sx_xunlock(&uma_drain_lock);
3625 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3626 sx_xlock(&uma_drain_lock);
3627 uma_reclaim_locked(true);
3628 atomic_store_int(&uma_reclaim_needed, 0);
3629 sx_xunlock(&uma_drain_lock);
3630 /* Don't fire more than once per-second. */
3631 pause("umarclslp", hz);
3637 uma_zone_exhausted(uma_zone_t zone)
3642 full = zone->uz_sleepers > 0;
3648 uma_zone_exhausted_nolock(uma_zone_t zone)
3650 return (zone->uz_sleepers > 0);
3654 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3656 struct domainset *policy;
3660 if (domain != UMA_ANYDOMAIN) {
3661 /* avoid allocs targeting empty domains */
3662 if (VM_DOMAIN_EMPTY(domain))
3663 domain = UMA_ANYDOMAIN;
3665 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3668 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3669 DOMAINSET_FIXED(domain);
3670 addr = kmem_malloc_domainset(policy, size, wait);
3672 vsetslab(addr, slab);
3673 slab->us_data = (void *)addr;
3674 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3675 slab->us_size = size;
3676 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3677 pmap_kextract(addr)));
3678 uma_total_inc(size);
3680 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3683 return ((void *)addr);
3687 uma_large_malloc(vm_size_t size, int wait)
3690 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3694 uma_large_free(uma_slab_t slab)
3697 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3698 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3699 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3700 uma_total_dec(slab->us_size);
3701 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3705 uma_zero_item(void *item, uma_zone_t zone)
3708 bzero(item, zone->uz_size);
3715 return (uma_kmem_limit);
3719 uma_set_limit(unsigned long limit)
3722 uma_kmem_limit = limit;
3729 return (uma_kmem_total);
3736 return (uma_kmem_limit - uma_kmem_total);
3740 uma_print_stats(void)
3742 zone_foreach(uma_print_zone);
3746 slab_print(uma_slab_t slab)
3748 printf("slab: keg %p, data %p, freecount %d\n",
3749 slab->us_keg, slab->us_data, slab->us_freecount);
3753 cache_print(uma_cache_t cache)
3755 printf("alloc: %p(%d), free: %p(%d)\n",
3756 cache->uc_allocbucket,
3757 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3758 cache->uc_freebucket,
3759 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3763 uma_print_keg(uma_keg_t keg)
3769 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3771 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3772 keg->uk_ipers, keg->uk_ppera,
3773 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3775 for (i = 0; i < vm_ndomains; i++) {
3776 dom = &keg->uk_domain[i];
3777 printf("Part slabs:\n");
3778 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3780 printf("Free slabs:\n");
3781 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3783 printf("Full slabs:\n");
3784 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3790 uma_print_zone(uma_zone_t zone)
3795 printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3796 zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3798 if (zone->uz_lockptr != &zone->uz_lock)
3799 uma_print_keg(zone->uz_keg);
3801 cache = &zone->uz_cpu[i];
3802 printf("CPU %d Cache:\n", i);
3809 * Generate statistics across both the zone and its per-cpu cache's. Return
3810 * desired statistics if the pointer is non-NULL for that statistic.
3812 * Note: does not update the zone statistics, as it can't safely clear the
3813 * per-CPU cache statistic.
3815 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3816 * safe from off-CPU; we should modify the caches to track this information
3817 * directly so that we don't have to.
3820 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3821 uint64_t *freesp, uint64_t *sleepsp)
3824 uint64_t allocs, frees, sleeps;
3827 allocs = frees = sleeps = 0;
3830 cache = &z->uz_cpu[cpu];
3831 if (cache->uc_allocbucket != NULL)
3832 cachefree += cache->uc_allocbucket->ub_cnt;
3833 if (cache->uc_freebucket != NULL)
3834 cachefree += cache->uc_freebucket->ub_cnt;
3835 allocs += cache->uc_allocs;
3836 frees += cache->uc_frees;
3838 allocs += counter_u64_fetch(z->uz_allocs);
3839 frees += counter_u64_fetch(z->uz_frees);
3840 sleeps += z->uz_sleeps;
3841 if (cachefreep != NULL)
3842 *cachefreep = cachefree;
3843 if (allocsp != NULL)
3847 if (sleepsp != NULL)
3853 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3860 rw_rlock(&uma_rwlock);
3861 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3862 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3865 rw_runlock(&uma_rwlock);
3866 return (sysctl_handle_int(oidp, &count, 0, req));
3870 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3872 struct uma_stream_header ush;
3873 struct uma_type_header uth;
3874 struct uma_percpu_stat *ups;
3875 uma_zone_domain_t zdom;
3880 int count, error, i;
3882 error = sysctl_wire_old_buffer(req, 0);
3885 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3886 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3887 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3890 rw_rlock(&uma_rwlock);
3891 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3892 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3897 * Insert stream header.
3899 bzero(&ush, sizeof(ush));
3900 ush.ush_version = UMA_STREAM_VERSION;
3901 ush.ush_maxcpus = (mp_maxid + 1);
3902 ush.ush_count = count;
3903 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3905 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3906 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3907 bzero(&uth, sizeof(uth));
3909 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3910 uth.uth_align = kz->uk_align;
3911 uth.uth_size = kz->uk_size;
3912 uth.uth_rsize = kz->uk_rsize;
3913 if (z->uz_max_items > 0)
3914 uth.uth_pages = (z->uz_items / kz->uk_ipers) *
3917 uth.uth_pages = kz->uk_pages;
3918 uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
3920 uth.uth_limit = z->uz_max_items;
3921 uth.uth_keg_free = z->uz_keg->uk_free;
3924 * A zone is secondary is it is not the first entry
3925 * on the keg's zone list.
3927 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3928 (LIST_FIRST(&kz->uk_zones) != z))
3929 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3931 for (i = 0; i < vm_ndomains; i++) {
3932 zdom = &z->uz_domain[i];
3933 uth.uth_zone_free += zdom->uzd_nitems;
3935 uth.uth_allocs = counter_u64_fetch(z->uz_allocs);
3936 uth.uth_frees = counter_u64_fetch(z->uz_frees);
3937 uth.uth_fails = counter_u64_fetch(z->uz_fails);
3938 uth.uth_sleeps = z->uz_sleeps;
3940 * While it is not normally safe to access the cache
3941 * bucket pointers while not on the CPU that owns the
3942 * cache, we only allow the pointers to be exchanged
3943 * without the zone lock held, not invalidated, so
3944 * accept the possible race associated with bucket
3945 * exchange during monitoring.
3947 for (i = 0; i < mp_maxid + 1; i++) {
3948 bzero(&ups[i], sizeof(*ups));
3949 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
3952 cache = &z->uz_cpu[i];
3953 if (cache->uc_allocbucket != NULL)
3954 ups[i].ups_cache_free +=
3955 cache->uc_allocbucket->ub_cnt;
3956 if (cache->uc_freebucket != NULL)
3957 ups[i].ups_cache_free +=
3958 cache->uc_freebucket->ub_cnt;
3959 ups[i].ups_allocs = cache->uc_allocs;
3960 ups[i].ups_frees = cache->uc_frees;
3963 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3964 for (i = 0; i < mp_maxid + 1; i++)
3965 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
3968 rw_runlock(&uma_rwlock);
3969 error = sbuf_finish(&sbuf);
3976 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
3978 uma_zone_t zone = *(uma_zone_t *)arg1;
3981 max = uma_zone_get_max(zone);
3982 error = sysctl_handle_int(oidp, &max, 0, req);
3983 if (error || !req->newptr)
3986 uma_zone_set_max(zone, max);
3992 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
3994 uma_zone_t zone = *(uma_zone_t *)arg1;
3997 cur = uma_zone_get_cur(zone);
3998 return (sysctl_handle_int(oidp, &cur, 0, req));
4003 uma_dbg_getslab(uma_zone_t zone, void *item)
4009 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4010 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4011 slab = vtoslab((vm_offset_t)mem);
4014 * It is safe to return the slab here even though the
4015 * zone is unlocked because the item's allocation state
4016 * essentially holds a reference.
4018 if (zone->uz_lockptr == &zone->uz_lock)
4022 if (keg->uk_flags & UMA_ZONE_HASH)
4023 slab = hash_sfind(&keg->uk_hash, mem);
4025 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4033 uma_dbg_zskip(uma_zone_t zone, void *mem)
4036 if (zone->uz_lockptr == &zone->uz_lock)
4039 return (uma_dbg_kskip(zone->uz_keg, mem));
4043 uma_dbg_kskip(uma_keg_t keg, void *mem)
4047 if (dbg_divisor == 0)
4050 if (dbg_divisor == 1)
4053 idx = (uintptr_t)mem >> PAGE_SHIFT;
4054 if (keg->uk_ipers > 1) {
4055 idx *= keg->uk_ipers;
4056 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4059 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4060 counter_u64_add(uma_skip_cnt, 1);
4063 counter_u64_add(uma_dbg_cnt, 1);
4069 * Set up the slab's freei data such that uma_dbg_free can function.
4073 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4079 slab = uma_dbg_getslab(zone, item);
4081 panic("uma: item %p did not belong to zone %s\n",
4082 item, zone->uz_name);
4085 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4087 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4088 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4089 item, zone, zone->uz_name, slab, freei);
4090 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4096 * Verifies freed addresses. Checks for alignment, valid slab membership
4097 * and duplicate frees.
4101 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4107 slab = uma_dbg_getslab(zone, item);
4109 panic("uma: Freed item %p did not belong to zone %s\n",
4110 item, zone->uz_name);
4113 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4115 if (freei >= keg->uk_ipers)
4116 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4117 item, zone, zone->uz_name, slab, freei);
4119 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4120 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4121 item, zone, zone->uz_name, slab, freei);
4123 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4124 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4125 item, zone, zone->uz_name, slab, freei);
4127 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4129 #endif /* INVARIANTS */
4132 DB_SHOW_COMMAND(uma, db_show_uma)
4136 uint64_t allocs, frees, sleeps;
4140 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4141 "Free", "Requests", "Sleeps", "Bucket");
4142 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4143 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4144 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4145 allocs = counter_u64_fetch(z->uz_allocs);
4146 frees = counter_u64_fetch(z->uz_frees);
4147 sleeps = z->uz_sleeps;
4150 uma_zone_sumstat(z, &cachefree, &allocs,
4152 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4153 (LIST_FIRST(&kz->uk_zones) != z)))
4154 cachefree += kz->uk_free;
4155 for (i = 0; i < vm_ndomains; i++)
4156 cachefree += z->uz_domain[i].uzd_nitems;
4158 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4159 z->uz_name, (uintmax_t)kz->uk_size,
4160 (intmax_t)(allocs - frees), cachefree,
4161 (uintmax_t)allocs, sleeps, z->uz_count);
4168 DB_SHOW_COMMAND(umacache, db_show_umacache)
4171 uint64_t allocs, frees;
4175 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4176 "Requests", "Bucket");
4177 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4178 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4179 for (i = 0; i < vm_ndomains; i++)
4180 cachefree += z->uz_domain[i].uzd_nitems;
4181 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4182 z->uz_name, (uintmax_t)z->uz_size,
4183 (intmax_t)(allocs - frees), cachefree,
4184 (uintmax_t)allocs, z->uz_count);