2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
5 * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6 * Copyright (c) 2004-2006 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice unmodified, this list of conditions, and the following
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * uma_core.c Implementation of the Universal Memory allocator
34 * This allocator is intended to replace the multitude of similar object caches
35 * in the standard FreeBSD kernel. The intent is to be flexible as well as
36 * efficient. A primary design goal is to return unused memory to the rest of
37 * the system. This will make the system as a whole more flexible due to the
38 * ability to move memory to subsystems which most need it instead of leaving
39 * pools of reserved memory unused.
41 * The basic ideas stem from similar slab/zone based allocators whose algorithms
48 * - Improve memory usage for large allocations
49 * - Investigate cache size adjustments
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
56 #include "opt_param.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
77 #include <sys/sched.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
100 #include <vm/memguard.h>
104 * This is the zone and keg from which all zones are spawned.
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
113 * The initial hash tables come out of this zone so they can be allocated
114 * prior to malloc coming up.
116 static uma_zone_t hashzone;
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
124 * Are we allowed to allocate buckets?
126 static int bucketdisable = 1;
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133 LIST_HEAD_INITIALIZER(uma_cachezones);
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
139 * Pointer and counter to pool of pages, that is preallocated at
140 * startup to bootstrap UMA.
142 static char *bootmem;
143 static int boot_pages;
145 static struct sx uma_drain_lock;
147 /* kmem soft limit. */
148 static unsigned long uma_kmem_limit = LONG_MAX;
149 static volatile unsigned long uma_kmem_total;
151 /* Is the VM done starting up? */
152 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
153 BOOT_RUNNING } booted = BOOT_COLD;
156 * This is the handle used to schedule events that need to happen
157 * outside of the allocation fast path.
159 static struct callout uma_callout;
160 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
163 * This structure is passed as the zone ctor arg so that I don't have to create
164 * a special allocation function just for zones.
166 struct uma_zctor_args {
181 struct uma_kctor_args {
190 struct uma_bucket_zone {
193 int ubz_entries; /* Number of items it can hold. */
194 int ubz_maxsize; /* Maximum allocation size per-item. */
198 * Compute the actual number of bucket entries to pack them in power
199 * of two sizes for more efficient space utilization.
201 #define BUCKET_SIZE(n) \
202 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
204 #define BUCKET_MAX BUCKET_SIZE(256)
206 struct uma_bucket_zone bucket_zones[] = {
207 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
208 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
209 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
210 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
211 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
212 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
213 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
214 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
215 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
220 * Flags and enumerations to be passed to internal functions.
222 enum zfreeskip { SKIP_NONE = 0, SKIP_DTOR, SKIP_FINI };
224 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
228 int uma_startup_count(int);
229 void uma_startup(void *, int);
230 void uma_startup1(void);
231 void uma_startup2(void);
233 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
234 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
235 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
236 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
237 static void page_free(void *, vm_size_t, uint8_t);
238 static void pcpu_page_free(void *, vm_size_t, uint8_t);
239 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int);
240 static void cache_drain(uma_zone_t);
241 static void bucket_drain(uma_zone_t, uma_bucket_t);
242 static void bucket_cache_drain(uma_zone_t zone);
243 static int keg_ctor(void *, int, void *, int);
244 static void keg_dtor(void *, int, void *);
245 static int zone_ctor(void *, int, void *, int);
246 static void zone_dtor(void *, int, void *);
247 static int zero_init(void *, int, int);
248 static void keg_small_init(uma_keg_t keg);
249 static void keg_large_init(uma_keg_t keg);
250 static void zone_foreach(void (*zfunc)(uma_zone_t));
251 static void zone_timeout(uma_zone_t zone);
252 static int hash_alloc(struct uma_hash *);
253 static int hash_expand(struct uma_hash *, struct uma_hash *);
254 static void hash_free(struct uma_hash *hash);
255 static void uma_timeout(void *);
256 static void uma_startup3(void);
257 static void *zone_alloc_item(uma_zone_t, void *, int, int);
258 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
259 static void bucket_enable(void);
260 static void bucket_init(void);
261 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
262 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
263 static void bucket_zone_drain(void);
264 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
265 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
266 static uma_slab_t zone_fetch_slab_multi(uma_zone_t, uma_keg_t, int, int);
267 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
268 static void slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item);
269 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
270 uma_fini fini, int align, uint32_t flags);
271 static int zone_import(uma_zone_t, void **, int, int, int);
272 static void zone_release(uma_zone_t, void **, int);
273 static void uma_zero_item(void *, uma_zone_t);
275 void uma_print_zone(uma_zone_t);
276 void uma_print_stats(void);
277 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
278 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
281 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
282 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
283 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
284 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
286 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
287 "Memory allocation debugging");
289 static u_int dbg_divisor = 1;
290 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
291 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
292 "Debug & thrash every this item in memory allocator");
294 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
295 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
296 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
297 &uma_dbg_cnt, "memory items debugged");
298 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
299 &uma_skip_cnt, "memory items skipped, not debugged");
302 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
304 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
305 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
307 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
308 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
310 static int zone_warnings = 1;
311 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
312 "Warn when UMA zones becomes full");
314 /* Adjust bytes under management by UMA. */
316 uma_total_dec(unsigned long size)
319 atomic_subtract_long(&uma_kmem_total, size);
323 uma_total_inc(unsigned long size)
326 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
327 uma_reclaim_wakeup();
331 * This routine checks to see whether or not it's safe to enable buckets.
336 bucketdisable = vm_page_count_min();
340 * Initialize bucket_zones, the array of zones of buckets of various sizes.
342 * For each zone, calculate the memory required for each bucket, consisting
343 * of the header and an array of pointers.
348 struct uma_bucket_zone *ubz;
351 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
352 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
353 size += sizeof(void *) * ubz->ubz_entries;
354 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
355 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
356 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
361 * Given a desired number of entries for a bucket, return the zone from which
362 * to allocate the bucket.
364 static struct uma_bucket_zone *
365 bucket_zone_lookup(int entries)
367 struct uma_bucket_zone *ubz;
369 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
370 if (ubz->ubz_entries >= entries)
377 bucket_select(int size)
379 struct uma_bucket_zone *ubz;
381 ubz = &bucket_zones[0];
382 if (size > ubz->ubz_maxsize)
383 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
385 for (; ubz->ubz_entries != 0; ubz++)
386 if (ubz->ubz_maxsize < size)
389 return (ubz->ubz_entries);
393 bucket_alloc(uma_zone_t zone, void *udata, int flags)
395 struct uma_bucket_zone *ubz;
399 * This is to stop us from allocating per cpu buckets while we're
400 * running out of vm.boot_pages. Otherwise, we would exhaust the
401 * boot pages. This also prevents us from allocating buckets in
402 * low memory situations.
407 * To limit bucket recursion we store the original zone flags
408 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
409 * NOVM flag to persist even through deep recursions. We also
410 * store ZFLAG_BUCKET once we have recursed attempting to allocate
411 * a bucket for a bucket zone so we do not allow infinite bucket
412 * recursion. This cookie will even persist to frees of unused
413 * buckets via the allocation path or bucket allocations in the
416 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
417 udata = (void *)(uintptr_t)zone->uz_flags;
419 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
421 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
423 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
425 ubz = bucket_zone_lookup(zone->uz_count);
426 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
428 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
431 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
434 bucket->ub_entries = ubz->ubz_entries;
441 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
443 struct uma_bucket_zone *ubz;
445 KASSERT(bucket->ub_cnt == 0,
446 ("bucket_free: Freeing a non free bucket."));
447 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
448 udata = (void *)(uintptr_t)zone->uz_flags;
449 ubz = bucket_zone_lookup(bucket->ub_entries);
450 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
454 bucket_zone_drain(void)
456 struct uma_bucket_zone *ubz;
458 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
459 zone_drain(ubz->ubz_zone);
463 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
467 ZONE_LOCK_ASSERT(zone);
469 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
470 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
471 LIST_REMOVE(bucket, ub_link);
472 zdom->uzd_nitems -= bucket->ub_cnt;
473 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
474 zdom->uzd_imin = zdom->uzd_nitems;
480 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
484 ZONE_LOCK_ASSERT(zone);
486 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
487 zdom->uzd_nitems += bucket->ub_cnt;
488 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
489 zdom->uzd_imax = zdom->uzd_nitems;
493 zone_log_warning(uma_zone_t zone)
495 static const struct timeval warninterval = { 300, 0 };
497 if (!zone_warnings || zone->uz_warning == NULL)
500 if (ratecheck(&zone->uz_ratecheck, &warninterval))
501 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
505 zone_maxaction(uma_zone_t zone)
508 if (zone->uz_maxaction.ta_func != NULL)
509 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
513 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
517 LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
518 kegfn(klink->kl_keg);
522 * Routine called by timeout which is used to fire off some time interval
523 * based calculations. (stats, hash size, etc.)
532 uma_timeout(void *unused)
535 zone_foreach(zone_timeout);
537 /* Reschedule this event */
538 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
542 * Update the working set size estimate for the zone's bucket cache.
543 * The constants chosen here are somewhat arbitrary. With an update period of
544 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
548 zone_domain_update_wss(uma_zone_domain_t zdom)
552 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
553 wss = zdom->uzd_imax - zdom->uzd_imin;
554 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
555 zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
559 * Routine to perform timeout driven calculations. This expands the
560 * hashes and does per cpu statistics aggregation.
565 keg_timeout(uma_keg_t keg)
570 * Expand the keg hash table.
572 * This is done if the number of slabs is larger than the hash size.
573 * What I'm trying to do here is completely reduce collisions. This
574 * may be a little aggressive. Should I allow for two collisions max?
576 if (keg->uk_flags & UMA_ZONE_HASH &&
577 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
578 struct uma_hash newhash;
579 struct uma_hash oldhash;
583 * This is so involved because allocating and freeing
584 * while the keg lock is held will lead to deadlock.
585 * I have to do everything in stages and check for
588 newhash = keg->uk_hash;
590 ret = hash_alloc(&newhash);
593 if (hash_expand(&keg->uk_hash, &newhash)) {
594 oldhash = keg->uk_hash;
595 keg->uk_hash = newhash;
608 zone_timeout(uma_zone_t zone)
612 zone_foreach_keg(zone, &keg_timeout);
615 for (i = 0; i < vm_ndomains; i++)
616 zone_domain_update_wss(&zone->uz_domain[i]);
621 * Allocate and zero fill the next sized hash table from the appropriate
625 * hash A new hash structure with the old hash size in uh_hashsize
628 * 1 on success and 0 on failure.
631 hash_alloc(struct uma_hash *hash)
636 oldsize = hash->uh_hashsize;
638 /* We're just going to go to a power of two greater */
640 hash->uh_hashsize = oldsize * 2;
641 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
642 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
643 M_UMAHASH, M_NOWAIT);
645 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
646 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
647 UMA_ANYDOMAIN, M_WAITOK);
648 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
650 if (hash->uh_slab_hash) {
651 bzero(hash->uh_slab_hash, alloc);
652 hash->uh_hashmask = hash->uh_hashsize - 1;
660 * Expands the hash table for HASH zones. This is done from zone_timeout
661 * to reduce collisions. This must not be done in the regular allocation
662 * path, otherwise, we can recurse on the vm while allocating pages.
665 * oldhash The hash you want to expand
666 * newhash The hash structure for the new table
674 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
680 if (!newhash->uh_slab_hash)
683 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
687 * I need to investigate hash algorithms for resizing without a
691 for (i = 0; i < oldhash->uh_hashsize; i++)
692 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
693 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
694 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
695 hval = UMA_HASH(newhash, slab->us_data);
696 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
704 * Free the hash bucket to the appropriate backing store.
707 * slab_hash The hash bucket we're freeing
708 * hashsize The number of entries in that hash bucket
714 hash_free(struct uma_hash *hash)
716 if (hash->uh_slab_hash == NULL)
718 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
719 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
721 free(hash->uh_slab_hash, M_UMAHASH);
725 * Frees all outstanding items in a bucket
728 * zone The zone to free to, must be unlocked.
729 * bucket The free/alloc bucket with items, cpu queue must be locked.
736 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
744 for (i = 0; i < bucket->ub_cnt; i++)
745 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
746 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
751 * Drains the per cpu caches for a zone.
753 * NOTE: This may only be called while the zone is being turn down, and not
754 * during normal operation. This is necessary in order that we do not have
755 * to migrate CPUs to drain the per-CPU caches.
758 * zone The zone to drain, must be unlocked.
764 cache_drain(uma_zone_t zone)
770 * XXX: It is safe to not lock the per-CPU caches, because we're
771 * tearing down the zone anyway. I.e., there will be no further use
772 * of the caches at this point.
774 * XXX: It would good to be able to assert that the zone is being
775 * torn down to prevent improper use of cache_drain().
777 * XXX: We lock the zone before passing into bucket_cache_drain() as
778 * it is used elsewhere. Should the tear-down path be made special
779 * there in some form?
782 cache = &zone->uz_cpu[cpu];
783 bucket_drain(zone, cache->uc_allocbucket);
784 bucket_drain(zone, cache->uc_freebucket);
785 if (cache->uc_allocbucket != NULL)
786 bucket_free(zone, cache->uc_allocbucket, NULL);
787 if (cache->uc_freebucket != NULL)
788 bucket_free(zone, cache->uc_freebucket, NULL);
789 cache->uc_allocbucket = cache->uc_freebucket = NULL;
792 bucket_cache_drain(zone);
797 cache_shrink(uma_zone_t zone)
800 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
804 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
809 cache_drain_safe_cpu(uma_zone_t zone)
815 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
821 if (zone->uz_flags & UMA_ZONE_NUMA)
822 domain = PCPU_GET(domain);
825 cache = &zone->uz_cpu[curcpu];
826 if (cache->uc_allocbucket) {
827 if (cache->uc_allocbucket->ub_cnt != 0)
828 zone_put_bucket(zone, &zone->uz_domain[domain],
829 cache->uc_allocbucket, false);
831 b1 = cache->uc_allocbucket;
832 cache->uc_allocbucket = NULL;
834 if (cache->uc_freebucket) {
835 if (cache->uc_freebucket->ub_cnt != 0)
836 zone_put_bucket(zone, &zone->uz_domain[domain],
837 cache->uc_freebucket, false);
839 b2 = cache->uc_freebucket;
840 cache->uc_freebucket = NULL;
845 bucket_free(zone, b1, NULL);
847 bucket_free(zone, b2, NULL);
851 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
852 * This is an expensive call because it needs to bind to all CPUs
853 * one by one and enter a critical section on each of them in order
854 * to safely access their cache buckets.
855 * Zone lock must not be held on call this function.
858 cache_drain_safe(uma_zone_t zone)
863 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
868 zone_foreach(cache_shrink);
871 thread_lock(curthread);
872 sched_bind(curthread, cpu);
873 thread_unlock(curthread);
876 cache_drain_safe_cpu(zone);
878 zone_foreach(cache_drain_safe_cpu);
880 thread_lock(curthread);
881 sched_unbind(curthread);
882 thread_unlock(curthread);
886 * Drain the cached buckets from a zone. Expects a locked zone on entry.
889 bucket_cache_drain(uma_zone_t zone)
891 uma_zone_domain_t zdom;
896 * Drain the bucket queues and free the buckets.
898 for (i = 0; i < vm_ndomains; i++) {
899 zdom = &zone->uz_domain[i];
900 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
903 bucket_drain(zone, bucket);
904 bucket_free(zone, bucket, NULL);
910 * Shrink further bucket sizes. Price of single zone lock collision
911 * is probably lower then price of global cache drain.
913 if (zone->uz_count > zone->uz_count_min)
918 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
924 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
925 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
928 flags = slab->us_flags;
930 if (keg->uk_fini != NULL) {
931 for (i--; i > -1; i--)
934 * trash_fini implies that dtor was trash_dtor. trash_fini
935 * would check that memory hasn't been modified since free,
936 * which executed trash_dtor.
937 * That's why we need to run uma_dbg_kskip() check here,
938 * albeit we don't make skip check for other init/fini
941 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
942 keg->uk_fini != trash_fini)
944 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
947 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
948 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
949 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
950 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
954 * Frees pages from a keg back to the system. This is done on demand from
955 * the pageout daemon.
960 keg_drain(uma_keg_t keg)
962 struct slabhead freeslabs = { 0 };
964 uma_slab_t slab, tmp;
968 * We don't want to take pages from statically allocated kegs at this
971 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
974 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
975 keg->uk_name, keg, keg->uk_free);
977 if (keg->uk_free == 0)
980 for (i = 0; i < vm_ndomains; i++) {
981 dom = &keg->uk_domain[i];
982 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
983 /* We have nowhere to free these to. */
984 if (slab->us_flags & UMA_SLAB_BOOT)
987 LIST_REMOVE(slab, us_link);
988 keg->uk_pages -= keg->uk_ppera;
989 keg->uk_free -= keg->uk_ipers;
991 if (keg->uk_flags & UMA_ZONE_HASH)
992 UMA_HASH_REMOVE(&keg->uk_hash, slab,
995 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
1002 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1003 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1004 keg_free_slab(keg, slab, keg->uk_ipers);
1009 zone_drain_wait(uma_zone_t zone, int waitok)
1013 * Set draining to interlock with zone_dtor() so we can release our
1014 * locks as we go. Only dtor() should do a WAITOK call since it
1015 * is the only call that knows the structure will still be available
1019 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1020 if (waitok == M_NOWAIT)
1022 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1024 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1025 bucket_cache_drain(zone);
1028 * The DRAINING flag protects us from being freed while
1029 * we're running. Normally the uma_rwlock would protect us but we
1030 * must be able to release and acquire the right lock for each keg.
1032 zone_foreach_keg(zone, &keg_drain);
1034 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1041 zone_drain(uma_zone_t zone)
1044 zone_drain_wait(zone, M_NOWAIT);
1048 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1049 * If the allocation was successful, the keg lock will be held upon return,
1050 * otherwise the keg will be left unlocked.
1053 * wait Shall we wait?
1056 * The slab that was allocated or NULL if there is no memory and the
1057 * caller specified M_NOWAIT.
1060 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int wait)
1069 KASSERT(domain >= 0 && domain < vm_ndomains,
1070 ("keg_alloc_slab: domain %d out of range", domain));
1071 mtx_assert(&keg->uk_lock, MA_OWNED);
1073 allocf = keg->uk_allocf;
1078 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1079 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, wait);
1085 * This reproduces the old vm_zone behavior of zero filling pages the
1086 * first time they are added to a zone.
1088 * Malloced items are zeroed in uma_zalloc.
1091 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1096 if (keg->uk_flags & UMA_ZONE_NODUMP)
1099 /* zone is passed for legacy reasons. */
1100 size = keg->uk_ppera * PAGE_SIZE;
1101 mem = allocf(zone, size, domain, &flags, wait);
1103 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1104 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1108 uma_total_inc(size);
1110 /* Point the slab into the allocated memory */
1111 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1112 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1114 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1115 for (i = 0; i < keg->uk_ppera; i++)
1116 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1119 slab->us_data = mem;
1120 slab->us_freecount = keg->uk_ipers;
1121 slab->us_flags = flags;
1122 slab->us_domain = domain;
1123 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1125 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1128 if (keg->uk_init != NULL) {
1129 for (i = 0; i < keg->uk_ipers; i++)
1130 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1131 keg->uk_size, wait) != 0)
1133 if (i != keg->uk_ipers) {
1134 keg_free_slab(keg, slab, i);
1141 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1142 slab, keg->uk_name, keg);
1144 if (keg->uk_flags & UMA_ZONE_HASH)
1145 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1147 keg->uk_pages += keg->uk_ppera;
1148 keg->uk_free += keg->uk_ipers;
1155 * This function is intended to be used early on in place of page_alloc() so
1156 * that we may use the boot time page cache to satisfy allocations before
1160 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1167 keg = zone_first_keg(zone);
1170 * If we are in BOOT_BUCKETS or higher, than switch to real
1171 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1177 case BOOT_PAGEALLOC:
1178 if (keg->uk_ppera > 1)
1182 #ifdef UMA_MD_SMALL_ALLOC
1183 keg->uk_allocf = (keg->uk_ppera > 1) ?
1184 page_alloc : uma_small_alloc;
1186 keg->uk_allocf = page_alloc;
1188 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1192 * Check our small startup cache to see if it has pages remaining.
1194 pages = howmany(bytes, PAGE_SIZE);
1195 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1196 if (pages > boot_pages)
1197 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1199 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1203 boot_pages -= pages;
1204 bootmem += pages * PAGE_SIZE;
1205 *pflag = UMA_SLAB_BOOT;
1211 * Allocates a number of pages from the system
1214 * bytes The number of bytes requested
1215 * wait Shall we wait?
1218 * A pointer to the alloced memory or possibly
1219 * NULL if M_NOWAIT is set.
1222 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1225 void *p; /* Returned page */
1227 *pflag = UMA_SLAB_KERNEL;
1228 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1234 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1237 struct pglist alloctail;
1238 vm_offset_t addr, zkva;
1240 vm_page_t p, p_next;
1245 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1247 TAILQ_INIT(&alloctail);
1248 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1249 malloc2vm_flags(wait);
1250 *pflag = UMA_SLAB_KERNEL;
1251 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1252 if (CPU_ABSENT(cpu)) {
1253 p = vm_page_alloc(NULL, 0, flags);
1256 p = vm_page_alloc(NULL, 0, flags);
1258 pc = pcpu_find(cpu);
1259 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1260 if (__predict_false(p == NULL))
1261 p = vm_page_alloc(NULL, 0, flags);
1264 if (__predict_false(p == NULL))
1266 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1268 if ((addr = kva_alloc(bytes)) == 0)
1271 TAILQ_FOREACH(p, &alloctail, listq) {
1272 pmap_qenter(zkva, &p, 1);
1275 return ((void*)addr);
1277 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1278 vm_page_unwire(p, PQ_NONE);
1285 * Allocates a number of pages from within an object
1288 * bytes The number of bytes requested
1289 * wait Shall we wait?
1292 * A pointer to the alloced memory or possibly
1293 * NULL if M_NOWAIT is set.
1296 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1299 TAILQ_HEAD(, vm_page) alloctail;
1301 vm_offset_t retkva, zkva;
1302 vm_page_t p, p_next;
1305 TAILQ_INIT(&alloctail);
1306 keg = zone_first_keg(zone);
1308 npages = howmany(bytes, PAGE_SIZE);
1309 while (npages > 0) {
1310 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1311 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1312 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1316 * Since the page does not belong to an object, its
1319 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1324 * Page allocation failed, free intermediate pages and
1327 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1328 vm_page_unwire(p, PQ_NONE);
1333 *flags = UMA_SLAB_PRIV;
1334 zkva = keg->uk_kva +
1335 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1337 TAILQ_FOREACH(p, &alloctail, listq) {
1338 pmap_qenter(zkva, &p, 1);
1342 return ((void *)retkva);
1346 * Frees a number of pages to the system
1349 * mem A pointer to the memory to be freed
1350 * size The size of the memory being freed
1351 * flags The original p->us_flags field
1357 page_free(void *mem, vm_size_t size, uint8_t flags)
1360 if ((flags & UMA_SLAB_KERNEL) == 0)
1361 panic("UMA: page_free used with invalid flags %x", flags);
1363 kmem_free((vm_offset_t)mem, size);
1367 * Frees pcpu zone allocations
1370 * mem A pointer to the memory to be freed
1371 * size The size of the memory being freed
1372 * flags The original p->us_flags field
1378 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1380 vm_offset_t sva, curva;
1384 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1385 sva = (vm_offset_t)mem;
1386 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1387 paddr = pmap_kextract(curva);
1388 m = PHYS_TO_VM_PAGE(paddr);
1389 vm_page_unwire(m, PQ_NONE);
1392 pmap_qremove(sva, size >> PAGE_SHIFT);
1393 kva_free(sva, size);
1398 * Zero fill initializer
1400 * Arguments/Returns follow uma_init specifications
1403 zero_init(void *mem, int size, int flags)
1410 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1413 * keg The zone we should initialize
1419 keg_small_init(uma_keg_t keg)
1427 if (keg->uk_flags & UMA_ZONE_PCPU) {
1428 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1430 slabsize = UMA_PCPU_ALLOC_SIZE;
1431 keg->uk_ppera = ncpus;
1433 slabsize = UMA_SLAB_SIZE;
1438 * Calculate the size of each allocation (rsize) according to
1439 * alignment. If the requested size is smaller than we have
1440 * allocation bits for we round it up.
1442 rsize = keg->uk_size;
1443 if (rsize < slabsize / SLAB_SETSIZE)
1444 rsize = slabsize / SLAB_SETSIZE;
1445 if (rsize & keg->uk_align)
1446 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1447 keg->uk_rsize = rsize;
1449 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1450 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1451 ("%s: size %u too large", __func__, keg->uk_rsize));
1453 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1456 shsize = sizeof(struct uma_slab);
1458 if (rsize <= slabsize - shsize)
1459 keg->uk_ipers = (slabsize - shsize) / rsize;
1461 /* Handle special case when we have 1 item per slab, so
1462 * alignment requirement can be relaxed. */
1463 KASSERT(keg->uk_size <= slabsize - shsize,
1464 ("%s: size %u greater than slab", __func__, keg->uk_size));
1467 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1468 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1470 memused = keg->uk_ipers * rsize + shsize;
1471 wastedspace = slabsize - memused;
1474 * We can't do OFFPAGE if we're internal or if we've been
1475 * asked to not go to the VM for buckets. If we do this we
1476 * may end up going to the VM for slabs which we do not
1477 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1478 * of UMA_ZONE_VM, which clearly forbids it.
1480 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1481 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1485 * See if using an OFFPAGE slab will limit our waste. Only do
1486 * this if it permits more items per-slab.
1488 * XXX We could try growing slabsize to limit max waste as well.
1489 * Historically this was not done because the VM could not
1490 * efficiently handle contiguous allocations.
1492 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1493 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1494 keg->uk_ipers = slabsize / keg->uk_rsize;
1495 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1496 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1497 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1498 "keg: %s(%p), calculated wastedspace = %d, "
1499 "maximum wasted space allowed = %d, "
1500 "calculated ipers = %d, "
1501 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1502 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1503 slabsize - keg->uk_ipers * keg->uk_rsize);
1504 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1507 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1508 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1509 keg->uk_flags |= UMA_ZONE_HASH;
1513 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1514 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1518 * keg The keg we should initialize
1524 keg_large_init(uma_keg_t keg)
1528 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1529 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1530 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1531 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1532 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1534 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1536 keg->uk_rsize = keg->uk_size;
1538 /* Check whether we have enough space to not do OFFPAGE. */
1539 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0) {
1540 shsize = sizeof(struct uma_slab);
1541 if (shsize & UMA_ALIGN_PTR)
1542 shsize = (shsize & ~UMA_ALIGN_PTR) +
1543 (UMA_ALIGN_PTR + 1);
1545 if (PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < shsize) {
1547 * We can't do OFFPAGE if we're internal, in which case
1548 * we need an extra page per allocation to contain the
1551 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1552 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1558 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1559 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1560 keg->uk_flags |= UMA_ZONE_HASH;
1564 keg_cachespread_init(uma_keg_t keg)
1571 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1572 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1574 alignsize = keg->uk_align + 1;
1575 rsize = keg->uk_size;
1577 * We want one item to start on every align boundary in a page. To
1578 * do this we will span pages. We will also extend the item by the
1579 * size of align if it is an even multiple of align. Otherwise, it
1580 * would fall on the same boundary every time.
1582 if (rsize & keg->uk_align)
1583 rsize = (rsize & ~keg->uk_align) + alignsize;
1584 if ((rsize & alignsize) == 0)
1586 trailer = rsize - keg->uk_size;
1587 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1588 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1589 keg->uk_rsize = rsize;
1590 keg->uk_ppera = pages;
1591 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1592 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1593 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1594 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1599 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1600 * the keg onto the global keg list.
1602 * Arguments/Returns follow uma_ctor specifications
1603 * udata Actually uma_kctor_args
1606 keg_ctor(void *mem, int size, void *udata, int flags)
1608 struct uma_kctor_args *arg = udata;
1609 uma_keg_t keg = mem;
1613 keg->uk_size = arg->size;
1614 keg->uk_init = arg->uminit;
1615 keg->uk_fini = arg->fini;
1616 keg->uk_align = arg->align;
1618 keg->uk_reserve = 0;
1620 keg->uk_flags = arg->flags;
1621 keg->uk_slabzone = NULL;
1624 * We use a global round-robin policy by default. Zones with
1625 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1626 * iterator is never run.
1628 keg->uk_dr.dr_policy = DOMAINSET_RR();
1629 keg->uk_dr.dr_iter = 0;
1632 * The master zone is passed to us at keg-creation time.
1635 keg->uk_name = zone->uz_name;
1637 if (arg->flags & UMA_ZONE_VM)
1638 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1640 if (arg->flags & UMA_ZONE_ZINIT)
1641 keg->uk_init = zero_init;
1643 if (arg->flags & UMA_ZONE_MALLOC)
1644 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1646 if (arg->flags & UMA_ZONE_PCPU)
1648 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1650 keg->uk_flags &= ~UMA_ZONE_PCPU;
1653 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1654 keg_cachespread_init(keg);
1656 if (keg->uk_size > UMA_SLAB_SPACE)
1657 keg_large_init(keg);
1659 keg_small_init(keg);
1662 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1663 keg->uk_slabzone = slabzone;
1666 * If we haven't booted yet we need allocations to go through the
1667 * startup cache until the vm is ready.
1669 if (booted < BOOT_PAGEALLOC)
1670 keg->uk_allocf = startup_alloc;
1671 #ifdef UMA_MD_SMALL_ALLOC
1672 else if (keg->uk_ppera == 1)
1673 keg->uk_allocf = uma_small_alloc;
1675 else if (keg->uk_flags & UMA_ZONE_PCPU)
1676 keg->uk_allocf = pcpu_page_alloc;
1678 keg->uk_allocf = page_alloc;
1679 #ifdef UMA_MD_SMALL_ALLOC
1680 if (keg->uk_ppera == 1)
1681 keg->uk_freef = uma_small_free;
1684 if (keg->uk_flags & UMA_ZONE_PCPU)
1685 keg->uk_freef = pcpu_page_free;
1687 keg->uk_freef = page_free;
1690 * Initialize keg's lock
1692 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1695 * If we're putting the slab header in the actual page we need to
1696 * figure out where in each page it goes. This calculates a right
1697 * justified offset into the memory on an ALIGN_PTR boundary.
1699 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1702 /* Size of the slab struct and free list */
1703 totsize = sizeof(struct uma_slab);
1705 if (totsize & UMA_ALIGN_PTR)
1706 totsize = (totsize & ~UMA_ALIGN_PTR) +
1707 (UMA_ALIGN_PTR + 1);
1708 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - totsize;
1711 * The only way the following is possible is if with our
1712 * UMA_ALIGN_PTR adjustments we are now bigger than
1713 * UMA_SLAB_SIZE. I haven't checked whether this is
1714 * mathematically possible for all cases, so we make
1717 totsize = keg->uk_pgoff + sizeof(struct uma_slab);
1718 if (totsize > PAGE_SIZE * keg->uk_ppera) {
1719 printf("zone %s ipers %d rsize %d size %d\n",
1720 zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1722 panic("UMA slab won't fit.");
1726 if (keg->uk_flags & UMA_ZONE_HASH)
1727 hash_alloc(&keg->uk_hash);
1729 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1730 keg, zone->uz_name, zone,
1731 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1734 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1736 rw_wlock(&uma_rwlock);
1737 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1738 rw_wunlock(&uma_rwlock);
1743 * Zone header ctor. This initializes all fields, locks, etc.
1745 * Arguments/Returns follow uma_ctor specifications
1746 * udata Actually uma_zctor_args
1749 zone_ctor(void *mem, int size, void *udata, int flags)
1751 struct uma_zctor_args *arg = udata;
1752 uma_zone_t zone = mem;
1757 zone->uz_name = arg->name;
1758 zone->uz_ctor = arg->ctor;
1759 zone->uz_dtor = arg->dtor;
1760 zone->uz_slab = zone_fetch_slab;
1761 zone->uz_init = NULL;
1762 zone->uz_fini = NULL;
1763 zone->uz_allocs = 0;
1766 zone->uz_sleeps = 0;
1768 zone->uz_count_min = 0;
1770 zone->uz_warning = NULL;
1771 /* The domain structures follow the cpu structures. */
1772 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1773 timevalclear(&zone->uz_ratecheck);
1776 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1779 * This is a pure cache zone, no kegs.
1782 if (arg->flags & UMA_ZONE_VM)
1783 arg->flags |= UMA_ZFLAG_CACHEONLY;
1784 zone->uz_flags = arg->flags;
1785 zone->uz_size = arg->size;
1786 zone->uz_import = arg->import;
1787 zone->uz_release = arg->release;
1788 zone->uz_arg = arg->arg;
1789 zone->uz_lockptr = &zone->uz_lock;
1790 rw_wlock(&uma_rwlock);
1791 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1792 rw_wunlock(&uma_rwlock);
1797 * Use the regular zone/keg/slab allocator.
1799 zone->uz_import = (uma_import)zone_import;
1800 zone->uz_release = (uma_release)zone_release;
1801 zone->uz_arg = zone;
1803 if (arg->flags & UMA_ZONE_SECONDARY) {
1804 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1805 zone->uz_init = arg->uminit;
1806 zone->uz_fini = arg->fini;
1807 zone->uz_lockptr = &keg->uk_lock;
1808 zone->uz_flags |= UMA_ZONE_SECONDARY;
1809 rw_wlock(&uma_rwlock);
1811 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1812 if (LIST_NEXT(z, uz_link) == NULL) {
1813 LIST_INSERT_AFTER(z, zone, uz_link);
1818 rw_wunlock(&uma_rwlock);
1819 } else if (keg == NULL) {
1820 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1821 arg->align, arg->flags)) == NULL)
1824 struct uma_kctor_args karg;
1827 /* We should only be here from uma_startup() */
1828 karg.size = arg->size;
1829 karg.uminit = arg->uminit;
1830 karg.fini = arg->fini;
1831 karg.align = arg->align;
1832 karg.flags = arg->flags;
1834 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1841 * Link in the first keg.
1843 zone->uz_klink.kl_keg = keg;
1844 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1845 zone->uz_lockptr = &keg->uk_lock;
1846 zone->uz_size = keg->uk_size;
1847 zone->uz_flags |= (keg->uk_flags &
1848 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1851 * Some internal zones don't have room allocated for the per cpu
1852 * caches. If we're internal, bail out here.
1854 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1855 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1856 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1861 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1862 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1863 ("Invalid zone flag combination"));
1864 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1865 zone->uz_count = BUCKET_MAX;
1866 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1869 zone->uz_count = bucket_select(zone->uz_size);
1870 zone->uz_count_min = zone->uz_count;
1876 * Keg header dtor. This frees all data, destroys locks, frees the hash
1877 * table and removes the keg from the global list.
1879 * Arguments/Returns follow uma_dtor specifications
1883 keg_dtor(void *arg, int size, void *udata)
1887 keg = (uma_keg_t)arg;
1889 if (keg->uk_free != 0) {
1890 printf("Freed UMA keg (%s) was not empty (%d items). "
1891 " Lost %d pages of memory.\n",
1892 keg->uk_name ? keg->uk_name : "",
1893 keg->uk_free, keg->uk_pages);
1897 hash_free(&keg->uk_hash);
1905 * Arguments/Returns follow uma_dtor specifications
1909 zone_dtor(void *arg, int size, void *udata)
1915 zone = (uma_zone_t)arg;
1916 keg = zone_first_keg(zone);
1918 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1921 rw_wlock(&uma_rwlock);
1922 LIST_REMOVE(zone, uz_link);
1923 rw_wunlock(&uma_rwlock);
1925 * XXX there are some races here where
1926 * the zone can be drained but zone lock
1927 * released and then refilled before we
1928 * remove it... we dont care for now
1930 zone_drain_wait(zone, M_WAITOK);
1932 * Unlink all of our kegs.
1934 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1935 klink->kl_keg = NULL;
1936 LIST_REMOVE(klink, kl_link);
1937 if (klink == &zone->uz_klink)
1939 free(klink, M_TEMP);
1942 * We only destroy kegs from non secondary zones.
1944 if (keg != NULL && (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1945 rw_wlock(&uma_rwlock);
1946 LIST_REMOVE(keg, uk_link);
1947 rw_wunlock(&uma_rwlock);
1948 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1950 ZONE_LOCK_FINI(zone);
1954 * Traverses every zone in the system and calls a callback
1957 * zfunc A pointer to a function which accepts a zone
1964 zone_foreach(void (*zfunc)(uma_zone_t))
1969 rw_rlock(&uma_rwlock);
1970 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1971 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1974 rw_runlock(&uma_rwlock);
1978 * Count how many pages do we need to bootstrap. VM supplies
1979 * its need in early zones in the argument, we add up our zones,
1980 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1981 * zone of zones and zone of kegs are accounted separately.
1983 #define UMA_BOOT_ZONES 11
1984 /* Zone of zones and zone of kegs have arbitrary alignment. */
1985 #define UMA_BOOT_ALIGN 32
1986 static int zsize, ksize;
1988 uma_startup_count(int vm_zones)
1992 ksize = sizeof(struct uma_keg) +
1993 (sizeof(struct uma_domain) * vm_ndomains);
1994 zsize = sizeof(struct uma_zone) +
1995 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1996 (sizeof(struct uma_zone_domain) * vm_ndomains);
1999 * Memory for the zone of kegs and its keg,
2000 * and for zone of zones.
2002 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
2003 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
2005 #ifdef UMA_MD_SMALL_ALLOC
2006 zones = UMA_BOOT_ZONES;
2008 zones = UMA_BOOT_ZONES + vm_zones;
2012 /* Memory for the rest of startup zones, UMA and VM, ... */
2013 if (zsize > UMA_SLAB_SPACE)
2014 pages += (zones + vm_zones) *
2015 howmany(roundup2(zsize, UMA_BOOT_ALIGN), UMA_SLAB_SIZE);
2016 else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2019 pages += howmany(zones,
2020 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2022 /* ... and their kegs. Note that zone of zones allocates a keg! */
2023 pages += howmany(zones + 1,
2024 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2027 * Most of startup zones are not going to be offpages, that's
2028 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2029 * calculations. Some large bucket zones will be offpage, and
2030 * thus will allocate hashes. We take conservative approach
2031 * and assume that all zones may allocate hash. This may give
2032 * us some positive inaccuracy, usually an extra single page.
2034 pages += howmany(zones, UMA_SLAB_SPACE /
2035 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2041 uma_startup(void *mem, int npages)
2043 struct uma_zctor_args args;
2044 uma_keg_t masterkeg;
2048 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2051 rw_init(&uma_rwlock, "UMA lock");
2053 /* Use bootpages memory for the zone of zones and zone of kegs. */
2055 zones = (uma_zone_t)m;
2056 m += roundup(zsize, CACHE_LINE_SIZE);
2057 kegs = (uma_zone_t)m;
2058 m += roundup(zsize, CACHE_LINE_SIZE);
2059 masterkeg = (uma_keg_t)m;
2060 m += roundup(ksize, CACHE_LINE_SIZE);
2061 m = roundup(m, PAGE_SIZE);
2062 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2065 /* "manually" create the initial zone */
2066 memset(&args, 0, sizeof(args));
2067 args.name = "UMA Kegs";
2069 args.ctor = keg_ctor;
2070 args.dtor = keg_dtor;
2071 args.uminit = zero_init;
2073 args.keg = masterkeg;
2074 args.align = UMA_BOOT_ALIGN - 1;
2075 args.flags = UMA_ZFLAG_INTERNAL;
2076 zone_ctor(kegs, zsize, &args, M_WAITOK);
2079 boot_pages = npages;
2081 args.name = "UMA Zones";
2083 args.ctor = zone_ctor;
2084 args.dtor = zone_dtor;
2085 args.uminit = zero_init;
2088 args.align = UMA_BOOT_ALIGN - 1;
2089 args.flags = UMA_ZFLAG_INTERNAL;
2090 zone_ctor(zones, zsize, &args, M_WAITOK);
2092 /* Now make a zone for slab headers */
2093 slabzone = uma_zcreate("UMA Slabs",
2094 sizeof(struct uma_slab),
2095 NULL, NULL, NULL, NULL,
2096 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2098 hashzone = uma_zcreate("UMA Hash",
2099 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2100 NULL, NULL, NULL, NULL,
2101 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2105 booted = BOOT_STRAPPED;
2113 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2115 booted = BOOT_PAGEALLOC;
2123 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2125 booted = BOOT_BUCKETS;
2126 sx_init(&uma_drain_lock, "umadrain");
2131 * Initialize our callout handle
2139 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2140 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2141 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2143 callout_init(&uma_callout, 1);
2144 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2145 booted = BOOT_RUNNING;
2149 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2150 int align, uint32_t flags)
2152 struct uma_kctor_args args;
2155 args.uminit = uminit;
2157 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2160 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2163 /* Public functions */
2166 uma_set_align(int align)
2169 if (align != UMA_ALIGN_CACHE)
2170 uma_align_cache = align;
2175 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2176 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2179 struct uma_zctor_args args;
2183 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2186 /* This stuff is essential for the zone ctor */
2187 memset(&args, 0, sizeof(args));
2192 args.uminit = uminit;
2196 * If a zone is being created with an empty constructor and
2197 * destructor, pass UMA constructor/destructor which checks for
2198 * memory use after free.
2200 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2201 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2202 args.ctor = trash_ctor;
2203 args.dtor = trash_dtor;
2204 args.uminit = trash_init;
2205 args.fini = trash_fini;
2212 if (booted < BOOT_BUCKETS) {
2215 sx_slock(&uma_drain_lock);
2218 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2220 sx_sunlock(&uma_drain_lock);
2226 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2227 uma_init zinit, uma_fini zfini, uma_zone_t master)
2229 struct uma_zctor_args args;
2234 keg = zone_first_keg(master);
2235 memset(&args, 0, sizeof(args));
2237 args.size = keg->uk_size;
2240 args.uminit = zinit;
2242 args.align = keg->uk_align;
2243 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2246 if (booted < BOOT_BUCKETS) {
2249 sx_slock(&uma_drain_lock);
2252 /* XXX Attaches only one keg of potentially many. */
2253 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2255 sx_sunlock(&uma_drain_lock);
2261 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2262 uma_init zinit, uma_fini zfini, uma_import zimport,
2263 uma_release zrelease, void *arg, int flags)
2265 struct uma_zctor_args args;
2267 memset(&args, 0, sizeof(args));
2272 args.uminit = zinit;
2274 args.import = zimport;
2275 args.release = zrelease;
2280 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2284 zone_lock_pair(uma_zone_t a, uma_zone_t b)
2288 mtx_lock_flags(b->uz_lockptr, MTX_DUPOK);
2291 mtx_lock_flags(a->uz_lockptr, MTX_DUPOK);
2296 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
2304 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
2311 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
2313 zone_lock_pair(zone, master);
2315 * zone must use vtoslab() to resolve objects and must already be
2318 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
2319 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
2324 * The new master must also use vtoslab().
2326 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
2332 * The underlying object must be the same size. rsize
2335 if (master->uz_size != zone->uz_size) {
2340 * Put it at the end of the list.
2342 klink->kl_keg = zone_first_keg(master);
2343 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
2344 if (LIST_NEXT(kl, kl_link) == NULL) {
2345 LIST_INSERT_AFTER(kl, klink, kl_link);
2350 zone->uz_flags |= UMA_ZFLAG_MULTI;
2351 zone->uz_slab = zone_fetch_slab_multi;
2354 zone_unlock_pair(zone, master);
2356 free(klink, M_TEMP);
2364 uma_zdestroy(uma_zone_t zone)
2367 sx_slock(&uma_drain_lock);
2368 zone_free_item(zones, zone, NULL, SKIP_NONE);
2369 sx_sunlock(&uma_drain_lock);
2373 uma_zwait(uma_zone_t zone)
2377 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2378 uma_zfree(zone, item);
2382 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2388 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2390 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2391 if (item != NULL && (flags & M_ZERO)) {
2393 for (i = 0; i <= mp_maxid; i++)
2394 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2396 bzero(item, zone->uz_size);
2403 * A stub while both regular and pcpu cases are identical.
2406 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2410 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2412 uma_zfree_arg(zone, item, udata);
2417 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2419 uma_zone_domain_t zdom;
2420 uma_bucket_t bucket;
2423 int cpu, domain, lockfail;
2428 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2429 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2431 /* This is the fast path allocation */
2432 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2433 curthread, zone->uz_name, zone, flags);
2435 if (flags & M_WAITOK) {
2436 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2437 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2439 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2440 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2441 ("uma_zalloc_arg: called with spinlock or critical section held"));
2442 if (zone->uz_flags & UMA_ZONE_PCPU)
2443 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2444 "with M_ZERO passed"));
2446 #ifdef DEBUG_MEMGUARD
2447 if (memguard_cmp_zone(zone)) {
2448 item = memguard_alloc(zone->uz_size, flags);
2450 if (zone->uz_init != NULL &&
2451 zone->uz_init(item, zone->uz_size, flags) != 0)
2453 if (zone->uz_ctor != NULL &&
2454 zone->uz_ctor(item, zone->uz_size, udata,
2456 zone->uz_fini(item, zone->uz_size);
2461 /* This is unfortunate but should not be fatal. */
2465 * If possible, allocate from the per-CPU cache. There are two
2466 * requirements for safe access to the per-CPU cache: (1) the thread
2467 * accessing the cache must not be preempted or yield during access,
2468 * and (2) the thread must not migrate CPUs without switching which
2469 * cache it accesses. We rely on a critical section to prevent
2470 * preemption and migration. We release the critical section in
2471 * order to acquire the zone mutex if we are unable to allocate from
2472 * the current cache; when we re-acquire the critical section, we
2473 * must detect and handle migration if it has occurred.
2478 cache = &zone->uz_cpu[cpu];
2481 bucket = cache->uc_allocbucket;
2482 if (bucket != NULL && bucket->ub_cnt > 0) {
2484 item = bucket->ub_bucket[bucket->ub_cnt];
2486 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2488 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2492 skipdbg = uma_dbg_zskip(zone, item);
2494 if (zone->uz_ctor != NULL &&
2496 (!skipdbg || zone->uz_ctor != trash_ctor ||
2497 zone->uz_dtor != trash_dtor) &&
2499 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2500 atomic_add_long(&zone->uz_fails, 1);
2501 zone_free_item(zone, item, udata, SKIP_DTOR);
2506 uma_dbg_alloc(zone, NULL, item);
2509 uma_zero_item(item, zone);
2514 * We have run out of items in our alloc bucket.
2515 * See if we can switch with our free bucket.
2517 bucket = cache->uc_freebucket;
2518 if (bucket != NULL && bucket->ub_cnt > 0) {
2520 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2521 zone->uz_name, zone);
2522 cache->uc_freebucket = cache->uc_allocbucket;
2523 cache->uc_allocbucket = bucket;
2528 * Discard any empty allocation bucket while we hold no locks.
2530 bucket = cache->uc_allocbucket;
2531 cache->uc_allocbucket = NULL;
2534 bucket_free(zone, bucket, udata);
2536 if (zone->uz_flags & UMA_ZONE_NUMA) {
2537 domain = PCPU_GET(domain);
2538 if (VM_DOMAIN_EMPTY(domain))
2539 domain = UMA_ANYDOMAIN;
2541 domain = UMA_ANYDOMAIN;
2543 /* Short-circuit for zones without buckets and low memory. */
2544 if (zone->uz_count == 0 || bucketdisable)
2548 * Attempt to retrieve the item from the per-CPU cache has failed, so
2549 * we must go back to the zone. This requires the zone lock, so we
2550 * must drop the critical section, then re-acquire it when we go back
2551 * to the cache. Since the critical section is released, we may be
2552 * preempted or migrate. As such, make sure not to maintain any
2553 * thread-local state specific to the cache from prior to releasing
2554 * the critical section.
2557 if (ZONE_TRYLOCK(zone) == 0) {
2558 /* Record contention to size the buckets. */
2564 cache = &zone->uz_cpu[cpu];
2566 /* See if we lost the race to fill the cache. */
2567 if (cache->uc_allocbucket != NULL) {
2573 * Check the zone's cache of buckets.
2575 if (domain == UMA_ANYDOMAIN)
2576 zdom = &zone->uz_domain[0];
2578 zdom = &zone->uz_domain[domain];
2579 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2580 KASSERT(bucket->ub_cnt != 0,
2581 ("uma_zalloc_arg: Returning an empty bucket."));
2582 cache->uc_allocbucket = bucket;
2586 /* We are no longer associated with this CPU. */
2590 * We bump the uz count when the cache size is insufficient to
2591 * handle the working set.
2593 if (lockfail && zone->uz_count < BUCKET_MAX)
2598 * Now lets just fill a bucket and put it on the free list. If that
2599 * works we'll restart the allocation from the beginning and it
2600 * will use the just filled bucket.
2602 bucket = zone_alloc_bucket(zone, udata, domain, flags);
2603 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2604 zone->uz_name, zone, bucket);
2605 if (bucket != NULL) {
2609 cache = &zone->uz_cpu[cpu];
2612 * See if we lost the race or were migrated. Cache the
2613 * initialized bucket to make this less likely or claim
2614 * the memory directly.
2616 if (cache->uc_allocbucket == NULL &&
2617 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2618 domain == PCPU_GET(domain))) {
2619 cache->uc_allocbucket = bucket;
2620 zdom->uzd_imax += bucket->ub_cnt;
2621 } else if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
2624 bucket_drain(zone, bucket);
2625 bucket_free(zone, bucket, udata);
2626 goto zalloc_restart;
2628 zone_put_bucket(zone, zdom, bucket, false);
2634 * We may not be able to get a bucket so return an actual item.
2637 item = zone_alloc_item(zone, udata, domain, flags);
2643 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2646 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2647 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2649 /* This is the fast path allocation */
2651 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2652 curthread, zone->uz_name, zone, domain, flags);
2654 if (flags & M_WAITOK) {
2655 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2656 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2658 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2659 ("uma_zalloc_domain: called with spinlock or critical section held"));
2661 return (zone_alloc_item(zone, udata, domain, flags));
2665 * Find a slab with some space. Prefer slabs that are partially used over those
2666 * that are totally full. This helps to reduce fragmentation.
2668 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2672 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2678 KASSERT(domain >= 0 && domain < vm_ndomains,
2679 ("keg_first_slab: domain %d out of range", domain));
2684 dom = &keg->uk_domain[domain];
2685 if (!LIST_EMPTY(&dom->ud_part_slab))
2686 return (LIST_FIRST(&dom->ud_part_slab));
2687 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2688 slab = LIST_FIRST(&dom->ud_free_slab);
2689 LIST_REMOVE(slab, us_link);
2690 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2694 domain = (domain + 1) % vm_ndomains;
2695 } while (domain != start);
2701 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2705 mtx_assert(&keg->uk_lock, MA_OWNED);
2707 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2708 if (keg->uk_free <= reserve)
2710 return (keg_first_slab(keg, domain, rr));
2714 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2716 struct vm_domainset_iter di;
2723 mtx_assert(&keg->uk_lock, MA_OWNED);
2726 * Use the keg's policy if upper layers haven't already specified a
2727 * domain (as happens with first-touch zones).
2729 * To avoid races we run the iterator with the keg lock held, but that
2730 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2731 * clear M_WAITOK and handle low memory conditions locally.
2733 rr = rdomain == UMA_ANYDOMAIN;
2735 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2736 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2744 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2746 MPASS(slab->us_keg == keg);
2751 * M_NOVM means don't ask at all!
2756 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2757 keg->uk_flags |= UMA_ZFLAG_FULL;
2759 * If this is not a multi-zone, set the FULL bit.
2760 * Otherwise slab_multi() takes care of it.
2762 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2763 zone->uz_flags |= UMA_ZFLAG_FULL;
2764 zone_log_warning(zone);
2765 zone_maxaction(zone);
2767 if (flags & M_NOWAIT)
2770 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2773 slab = keg_alloc_slab(keg, zone, domain, aflags);
2775 * If we got a slab here it's safe to mark it partially used
2776 * and return. We assume that the caller is going to remove
2777 * at least one item.
2780 MPASS(slab->us_keg == keg);
2781 dom = &keg->uk_domain[slab->us_domain];
2782 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2786 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2787 if ((flags & M_WAITOK) != 0) {
2789 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2798 * We might not have been able to get a slab but another cpu
2799 * could have while we were unlocked. Check again before we
2802 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2803 MPASS(slab->us_keg == keg);
2810 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2815 keg = zone_first_keg(zone);
2820 slab = keg_fetch_slab(keg, zone, domain, flags);
2823 if (flags & (M_NOWAIT | M_NOVM))
2831 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2832 * with the keg locked. On NULL no lock is held.
2834 * The last pointer is used to seed the search. It is not required.
2837 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int domain, int rflags)
2847 * Don't wait on the first pass. This will skip limit tests
2848 * as well. We don't want to block if we can find a provider
2851 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2853 * Use the last slab allocated as a hint for where to start
2857 slab = keg_fetch_slab(last, zone, domain, flags);
2863 * Loop until we have a slab incase of transient failures
2864 * while M_WAITOK is specified. I'm not sure this is 100%
2865 * required but we've done it for so long now.
2871 * Search the available kegs for slabs. Be careful to hold the
2872 * correct lock while calling into the keg layer.
2874 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2875 keg = klink->kl_keg;
2877 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2878 slab = keg_fetch_slab(keg, zone, domain, flags);
2882 if (keg->uk_flags & UMA_ZFLAG_FULL)
2888 if (rflags & (M_NOWAIT | M_NOVM))
2892 * All kegs are full. XXX We can't atomically check all kegs
2893 * and sleep so just sleep for a short period and retry.
2895 if (full && !empty) {
2897 zone->uz_flags |= UMA_ZFLAG_FULL;
2899 zone_log_warning(zone);
2900 zone_maxaction(zone);
2901 msleep(zone, zone->uz_lockptr, PVM,
2902 "zonelimit", hz/100);
2903 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2912 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2918 MPASS(keg == slab->us_keg);
2919 mtx_assert(&keg->uk_lock, MA_OWNED);
2921 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2922 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2923 item = slab->us_data + (keg->uk_rsize * freei);
2924 slab->us_freecount--;
2927 /* Move this slab to the full list */
2928 if (slab->us_freecount == 0) {
2929 LIST_REMOVE(slab, us_link);
2930 dom = &keg->uk_domain[slab->us_domain];
2931 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2938 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2949 /* Try to keep the buckets totally full */
2950 for (i = 0; i < max; ) {
2951 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2955 stripe = howmany(max, vm_ndomains);
2957 while (slab->us_freecount && i < max) {
2958 bucket[i++] = slab_alloc_item(keg, slab);
2959 if (keg->uk_free <= keg->uk_reserve)
2963 * If the zone is striped we pick a new slab for every
2964 * N allocations. Eliminating this conditional will
2965 * instead pick a new domain for each bucket rather
2966 * than stripe within each bucket. The current option
2967 * produces more fragmentation and requires more cpu
2968 * time but yields better distribution.
2970 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2971 vm_ndomains > 1 && --stripe == 0)
2975 /* Don't block if we allocated any successfully. */
2986 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
2988 uma_bucket_t bucket;
2991 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2993 /* Don't wait for buckets, preserve caller's NOVM setting. */
2994 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2998 max = MIN(bucket->ub_entries, zone->uz_count);
2999 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
3000 max, domain, flags);
3003 * Initialize the memory if necessary.
3005 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
3008 for (i = 0; i < bucket->ub_cnt; i++)
3009 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
3013 * If we couldn't initialize the whole bucket, put the
3014 * rest back onto the freelist.
3016 if (i != bucket->ub_cnt) {
3017 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
3018 bucket->ub_cnt - i);
3020 bzero(&bucket->ub_bucket[i],
3021 sizeof(void *) * (bucket->ub_cnt - i));
3027 if (bucket->ub_cnt == 0) {
3028 bucket_free(zone, bucket, udata);
3029 atomic_add_long(&zone->uz_fails, 1);
3037 * Allocates a single item from a zone.
3040 * zone The zone to alloc for.
3041 * udata The data to be passed to the constructor.
3042 * domain The domain to allocate from or UMA_ANYDOMAIN.
3043 * flags M_WAITOK, M_NOWAIT, M_ZERO.
3046 * NULL if there is no memory and M_NOWAIT is set
3047 * An item if successful
3051 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
3060 if (domain != UMA_ANYDOMAIN) {
3061 /* avoid allocs targeting empty domains */
3062 if (VM_DOMAIN_EMPTY(domain))
3063 domain = UMA_ANYDOMAIN;
3065 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
3067 atomic_add_long(&zone->uz_allocs, 1);
3070 skipdbg = uma_dbg_zskip(zone, item);
3073 * We have to call both the zone's init (not the keg's init)
3074 * and the zone's ctor. This is because the item is going from
3075 * a keg slab directly to the user, and the user is expecting it
3076 * to be both zone-init'd as well as zone-ctor'd.
3078 if (zone->uz_init != NULL) {
3079 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
3080 zone_free_item(zone, item, udata, SKIP_FINI);
3084 if (zone->uz_ctor != NULL &&
3086 (!skipdbg || zone->uz_ctor != trash_ctor ||
3087 zone->uz_dtor != trash_dtor) &&
3089 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
3090 zone_free_item(zone, item, udata, SKIP_DTOR);
3095 uma_dbg_alloc(zone, NULL, item);
3098 uma_zero_item(item, zone);
3100 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3101 zone->uz_name, zone);
3106 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3107 zone->uz_name, zone);
3108 atomic_add_long(&zone->uz_fails, 1);
3114 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3117 uma_bucket_t bucket;
3118 uma_zone_domain_t zdom;
3119 int cpu, domain, lockfail;
3124 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3125 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3127 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3130 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3131 ("uma_zfree_arg: called with spinlock or critical section held"));
3133 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3136 #ifdef DEBUG_MEMGUARD
3137 if (is_memguard_addr(item)) {
3138 if (zone->uz_dtor != NULL)
3139 zone->uz_dtor(item, zone->uz_size, udata);
3140 if (zone->uz_fini != NULL)
3141 zone->uz_fini(item, zone->uz_size);
3142 memguard_free(item);
3147 skipdbg = uma_dbg_zskip(zone, item);
3148 if (skipdbg == false) {
3149 if (zone->uz_flags & UMA_ZONE_MALLOC)
3150 uma_dbg_free(zone, udata, item);
3152 uma_dbg_free(zone, NULL, item);
3154 if (zone->uz_dtor != NULL && (!skipdbg ||
3155 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3157 if (zone->uz_dtor != NULL)
3159 zone->uz_dtor(item, zone->uz_size, udata);
3162 * The race here is acceptable. If we miss it we'll just have to wait
3163 * a little longer for the limits to be reset.
3165 if (zone->uz_flags & UMA_ZFLAG_FULL)
3169 * If possible, free to the per-CPU cache. There are two
3170 * requirements for safe access to the per-CPU cache: (1) the thread
3171 * accessing the cache must not be preempted or yield during access,
3172 * and (2) the thread must not migrate CPUs without switching which
3173 * cache it accesses. We rely on a critical section to prevent
3174 * preemption and migration. We release the critical section in
3175 * order to acquire the zone mutex if we are unable to free to the
3176 * current cache; when we re-acquire the critical section, we must
3177 * detect and handle migration if it has occurred.
3182 cache = &zone->uz_cpu[cpu];
3186 * Try to free into the allocbucket first to give LIFO ordering
3187 * for cache-hot datastructures. Spill over into the freebucket
3188 * if necessary. Alloc will swap them if one runs dry.
3190 bucket = cache->uc_allocbucket;
3191 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3192 bucket = cache->uc_freebucket;
3193 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3194 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3195 ("uma_zfree: Freeing to non free bucket index."));
3196 bucket->ub_bucket[bucket->ub_cnt] = item;
3204 * We must go back the zone, which requires acquiring the zone lock,
3205 * which in turn means we must release and re-acquire the critical
3206 * section. Since the critical section is released, we may be
3207 * preempted or migrate. As such, make sure not to maintain any
3208 * thread-local state specific to the cache from prior to releasing
3209 * the critical section.
3212 if (zone->uz_count == 0 || bucketdisable)
3216 if (ZONE_TRYLOCK(zone) == 0) {
3217 /* Record contention to size the buckets. */
3223 cache = &zone->uz_cpu[cpu];
3225 bucket = cache->uc_freebucket;
3226 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3230 cache->uc_freebucket = NULL;
3231 /* We are no longer associated with this CPU. */
3234 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3235 domain = PCPU_GET(domain);
3236 if (VM_DOMAIN_EMPTY(domain))
3237 domain = UMA_ANYDOMAIN;
3240 zdom = &zone->uz_domain[0];
3242 /* Can we throw this on the zone full list? */
3243 if (bucket != NULL) {
3245 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3246 zone->uz_name, zone, bucket);
3247 /* ub_cnt is pointing to the last free item */
3248 KASSERT(bucket->ub_cnt != 0,
3249 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
3250 if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
3252 bucket_drain(zone, bucket);
3253 bucket_free(zone, bucket, udata);
3256 zone_put_bucket(zone, zdom, bucket, true);
3260 * We bump the uz count when the cache size is insufficient to
3261 * handle the working set.
3263 if (lockfail && zone->uz_count < BUCKET_MAX)
3267 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3268 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3269 zone->uz_name, zone, bucket);
3273 cache = &zone->uz_cpu[cpu];
3274 if (cache->uc_freebucket == NULL &&
3275 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3276 domain == PCPU_GET(domain))) {
3277 cache->uc_freebucket = bucket;
3281 * We lost the race, start over. We have to drop our
3282 * critical section to free the bucket.
3285 bucket_free(zone, bucket, udata);
3290 * If nothing else caught this, we'll just do an internal free.
3293 zone_free_item(zone, item, udata, SKIP_DTOR);
3299 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3302 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3303 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3305 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3308 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3309 ("uma_zfree_domain: called with spinlock or critical section held"));
3311 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3314 zone_free_item(zone, item, udata, SKIP_NONE);
3318 slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item)
3323 mtx_assert(&keg->uk_lock, MA_OWNED);
3324 MPASS(keg == slab->us_keg);
3326 dom = &keg->uk_domain[slab->us_domain];
3328 /* Do we need to remove from any lists? */
3329 if (slab->us_freecount+1 == keg->uk_ipers) {
3330 LIST_REMOVE(slab, us_link);
3331 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3332 } else if (slab->us_freecount == 0) {
3333 LIST_REMOVE(slab, us_link);
3334 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3337 /* Slab management. */
3338 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3339 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3340 slab->us_freecount++;
3342 /* Keg statistics. */
3347 zone_release(uma_zone_t zone, void **bucket, int cnt)
3357 keg = zone_first_keg(zone);
3359 for (i = 0; i < cnt; i++) {
3361 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3362 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3363 if (zone->uz_flags & UMA_ZONE_HASH) {
3364 slab = hash_sfind(&keg->uk_hash, mem);
3366 mem += keg->uk_pgoff;
3367 slab = (uma_slab_t)mem;
3370 slab = vtoslab((vm_offset_t)item);
3371 if (slab->us_keg != keg) {
3377 slab_free_item(keg, slab, item);
3378 if (keg->uk_flags & UMA_ZFLAG_FULL) {
3379 if (keg->uk_pages < keg->uk_maxpages) {
3380 keg->uk_flags &= ~UMA_ZFLAG_FULL;
3385 * We can handle one more allocation. Since we're
3386 * clearing ZFLAG_FULL, wake up all procs blocked
3387 * on pages. This should be uncommon, so keeping this
3388 * simple for now (rather than adding count of blocked
3397 zone->uz_flags &= ~UMA_ZFLAG_FULL;
3405 * Frees a single item to any zone.
3408 * zone The zone to free to
3409 * item The item we're freeing
3410 * udata User supplied data for the dtor
3411 * skip Skip dtors and finis
3414 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3419 skipdbg = uma_dbg_zskip(zone, item);
3420 if (skip == SKIP_NONE && !skipdbg) {
3421 if (zone->uz_flags & UMA_ZONE_MALLOC)
3422 uma_dbg_free(zone, udata, item);
3424 uma_dbg_free(zone, NULL, item);
3427 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3428 (!skipdbg || zone->uz_dtor != trash_dtor ||
3429 zone->uz_ctor != trash_ctor))
3431 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3433 zone->uz_dtor(item, zone->uz_size, udata);
3435 if (skip < SKIP_FINI && zone->uz_fini)
3436 zone->uz_fini(item, zone->uz_size);
3438 atomic_add_long(&zone->uz_frees, 1);
3439 zone->uz_release(zone->uz_arg, &item, 1);
3444 uma_zone_set_max(uma_zone_t zone, int nitems)
3448 keg = zone_first_keg(zone);
3452 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
3453 if (keg->uk_maxpages * keg->uk_ipers < nitems)
3454 keg->uk_maxpages += keg->uk_ppera;
3455 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3463 uma_zone_get_max(uma_zone_t zone)
3468 keg = zone_first_keg(zone);
3472 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3480 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3484 zone->uz_warning = warning;
3490 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3494 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3500 uma_zone_get_cur(uma_zone_t zone)
3506 nitems = zone->uz_allocs - zone->uz_frees;
3509 * See the comment in sysctl_vm_zone_stats() regarding the
3510 * safety of accessing the per-cpu caches. With the zone lock
3511 * held, it is safe, but can potentially result in stale data.
3513 nitems += zone->uz_cpu[i].uc_allocs -
3514 zone->uz_cpu[i].uc_frees;
3518 return (nitems < 0 ? 0 : nitems);
3523 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3527 keg = zone_first_keg(zone);
3528 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
3530 KASSERT(keg->uk_pages == 0,
3531 ("uma_zone_set_init on non-empty keg"));
3532 keg->uk_init = uminit;
3538 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3542 keg = zone_first_keg(zone);
3543 KASSERT(keg != NULL, ("uma_zone_set_fini: Invalid zone type"));
3545 KASSERT(keg->uk_pages == 0,
3546 ("uma_zone_set_fini on non-empty keg"));
3547 keg->uk_fini = fini;
3553 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3557 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3558 ("uma_zone_set_zinit on non-empty keg"));
3559 zone->uz_init = zinit;
3565 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3569 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3570 ("uma_zone_set_zfini on non-empty keg"));
3571 zone->uz_fini = zfini;
3576 /* XXX uk_freef is not actually used with the zone locked */
3578 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3582 keg = zone_first_keg(zone);
3583 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3585 keg->uk_freef = freef;
3590 /* XXX uk_allocf is not actually used with the zone locked */
3592 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3596 keg = zone_first_keg(zone);
3598 keg->uk_allocf = allocf;
3604 uma_zone_reserve(uma_zone_t zone, int items)
3608 keg = zone_first_keg(zone);
3612 keg->uk_reserve = items;
3620 uma_zone_reserve_kva(uma_zone_t zone, int count)
3626 keg = zone_first_keg(zone);
3629 pages = count / keg->uk_ipers;
3631 if (pages * keg->uk_ipers < count)
3633 pages *= keg->uk_ppera;
3635 #ifdef UMA_MD_SMALL_ALLOC
3636 if (keg->uk_ppera > 1) {
3640 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3648 keg->uk_maxpages = pages;
3649 #ifdef UMA_MD_SMALL_ALLOC
3650 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3652 keg->uk_allocf = noobj_alloc;
3654 keg->uk_flags |= UMA_ZONE_NOFREE;
3662 uma_prealloc(uma_zone_t zone, int items)
3664 struct vm_domainset_iter di;
3668 int domain, flags, slabs;
3670 keg = zone_first_keg(zone);
3674 slabs = items / keg->uk_ipers;
3675 if (slabs * keg->uk_ipers < items)
3678 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain, &flags);
3679 while (slabs-- > 0) {
3680 slab = keg_alloc_slab(keg, zone, domain, flags);
3683 MPASS(slab->us_keg == keg);
3684 dom = &keg->uk_domain[slab->us_domain];
3685 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3686 if (vm_domainset_iter_policy(&di, &domain) != 0)
3694 uma_reclaim_locked(bool kmem_danger)
3697 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3698 sx_assert(&uma_drain_lock, SA_XLOCKED);
3700 zone_foreach(zone_drain);
3701 if (vm_page_count_min() || kmem_danger) {
3702 cache_drain_safe(NULL);
3703 zone_foreach(zone_drain);
3707 * Some slabs may have been freed but this zone will be visited early
3708 * we visit again so that we can free pages that are empty once other
3709 * zones are drained. We have to do the same for buckets.
3711 zone_drain(slabzone);
3712 bucket_zone_drain();
3719 sx_xlock(&uma_drain_lock);
3720 uma_reclaim_locked(false);
3721 sx_xunlock(&uma_drain_lock);
3724 static volatile int uma_reclaim_needed;
3727 uma_reclaim_wakeup(void)
3730 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3731 wakeup(uma_reclaim);
3735 uma_reclaim_worker(void *arg __unused)
3739 sx_xlock(&uma_drain_lock);
3740 while (atomic_load_int(&uma_reclaim_needed) == 0)
3741 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3743 sx_xunlock(&uma_drain_lock);
3744 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3745 sx_xlock(&uma_drain_lock);
3746 uma_reclaim_locked(true);
3747 atomic_store_int(&uma_reclaim_needed, 0);
3748 sx_xunlock(&uma_drain_lock);
3749 /* Don't fire more than once per-second. */
3750 pause("umarclslp", hz);
3756 uma_zone_exhausted(uma_zone_t zone)
3761 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3767 uma_zone_exhausted_nolock(uma_zone_t zone)
3769 return (zone->uz_flags & UMA_ZFLAG_FULL);
3773 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3775 struct domainset *policy;
3779 if (domain != UMA_ANYDOMAIN) {
3780 /* avoid allocs targeting empty domains */
3781 if (VM_DOMAIN_EMPTY(domain))
3782 domain = UMA_ANYDOMAIN;
3784 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3787 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3788 DOMAINSET_FIXED(domain);
3789 addr = kmem_malloc_domainset(policy, size, wait);
3791 vsetslab(addr, slab);
3792 slab->us_data = (void *)addr;
3793 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3794 slab->us_size = size;
3795 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3796 pmap_kextract(addr)));
3797 uma_total_inc(size);
3799 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3802 return ((void *)addr);
3806 uma_large_malloc(vm_size_t size, int wait)
3809 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3813 uma_large_free(uma_slab_t slab)
3816 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3817 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3818 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3819 uma_total_dec(slab->us_size);
3820 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3824 uma_zero_item(void *item, uma_zone_t zone)
3827 bzero(item, zone->uz_size);
3834 return (uma_kmem_limit);
3838 uma_set_limit(unsigned long limit)
3841 uma_kmem_limit = limit;
3848 return (uma_kmem_total);
3855 return (uma_kmem_limit - uma_kmem_total);
3859 uma_print_stats(void)
3861 zone_foreach(uma_print_zone);
3865 slab_print(uma_slab_t slab)
3867 printf("slab: keg %p, data %p, freecount %d\n",
3868 slab->us_keg, slab->us_data, slab->us_freecount);
3872 cache_print(uma_cache_t cache)
3874 printf("alloc: %p(%d), free: %p(%d)\n",
3875 cache->uc_allocbucket,
3876 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3877 cache->uc_freebucket,
3878 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3882 uma_print_keg(uma_keg_t keg)
3888 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3889 "out %d free %d limit %d\n",
3890 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3891 keg->uk_ipers, keg->uk_ppera,
3892 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3893 keg->uk_free, (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3894 for (i = 0; i < vm_ndomains; i++) {
3895 dom = &keg->uk_domain[i];
3896 printf("Part slabs:\n");
3897 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3899 printf("Free slabs:\n");
3900 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3902 printf("Full slabs:\n");
3903 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3909 uma_print_zone(uma_zone_t zone)
3915 printf("zone: %s(%p) size %d flags %#x\n",
3916 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3917 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3918 uma_print_keg(kl->kl_keg);
3920 cache = &zone->uz_cpu[i];
3921 printf("CPU %d Cache:\n", i);
3928 * Generate statistics across both the zone and its per-cpu cache's. Return
3929 * desired statistics if the pointer is non-NULL for that statistic.
3931 * Note: does not update the zone statistics, as it can't safely clear the
3932 * per-CPU cache statistic.
3934 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3935 * safe from off-CPU; we should modify the caches to track this information
3936 * directly so that we don't have to.
3939 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3940 uint64_t *freesp, uint64_t *sleepsp)
3943 uint64_t allocs, frees, sleeps;
3946 allocs = frees = sleeps = 0;
3949 cache = &z->uz_cpu[cpu];
3950 if (cache->uc_allocbucket != NULL)
3951 cachefree += cache->uc_allocbucket->ub_cnt;
3952 if (cache->uc_freebucket != NULL)
3953 cachefree += cache->uc_freebucket->ub_cnt;
3954 allocs += cache->uc_allocs;
3955 frees += cache->uc_frees;
3957 allocs += z->uz_allocs;
3958 frees += z->uz_frees;
3959 sleeps += z->uz_sleeps;
3960 if (cachefreep != NULL)
3961 *cachefreep = cachefree;
3962 if (allocsp != NULL)
3966 if (sleepsp != NULL)
3972 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3979 rw_rlock(&uma_rwlock);
3980 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3981 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3984 rw_runlock(&uma_rwlock);
3985 return (sysctl_handle_int(oidp, &count, 0, req));
3989 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3991 struct uma_stream_header ush;
3992 struct uma_type_header uth;
3993 struct uma_percpu_stat *ups;
3994 uma_zone_domain_t zdom;
4001 int count, error, i;
4003 error = sysctl_wire_old_buffer(req, 0);
4006 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
4007 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
4008 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
4011 rw_rlock(&uma_rwlock);
4012 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4013 LIST_FOREACH(z, &kz->uk_zones, uz_link)
4018 * Insert stream header.
4020 bzero(&ush, sizeof(ush));
4021 ush.ush_version = UMA_STREAM_VERSION;
4022 ush.ush_maxcpus = (mp_maxid + 1);
4023 ush.ush_count = count;
4024 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
4026 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4027 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4028 bzero(&uth, sizeof(uth));
4030 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
4031 uth.uth_align = kz->uk_align;
4032 uth.uth_size = kz->uk_size;
4033 uth.uth_rsize = kz->uk_rsize;
4034 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
4036 uth.uth_maxpages += k->uk_maxpages;
4037 uth.uth_pages += k->uk_pages;
4038 uth.uth_keg_free += k->uk_free;
4039 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
4044 * A zone is secondary is it is not the first entry
4045 * on the keg's zone list.
4047 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
4048 (LIST_FIRST(&kz->uk_zones) != z))
4049 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
4051 for (i = 0; i < vm_ndomains; i++) {
4052 zdom = &z->uz_domain[i];
4053 uth.uth_zone_free += zdom->uzd_nitems;
4055 uth.uth_allocs = z->uz_allocs;
4056 uth.uth_frees = z->uz_frees;
4057 uth.uth_fails = z->uz_fails;
4058 uth.uth_sleeps = z->uz_sleeps;
4060 * While it is not normally safe to access the cache
4061 * bucket pointers while not on the CPU that owns the
4062 * cache, we only allow the pointers to be exchanged
4063 * without the zone lock held, not invalidated, so
4064 * accept the possible race associated with bucket
4065 * exchange during monitoring.
4067 for (i = 0; i < mp_maxid + 1; i++) {
4068 bzero(&ups[i], sizeof(*ups));
4069 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
4072 cache = &z->uz_cpu[i];
4073 if (cache->uc_allocbucket != NULL)
4074 ups[i].ups_cache_free +=
4075 cache->uc_allocbucket->ub_cnt;
4076 if (cache->uc_freebucket != NULL)
4077 ups[i].ups_cache_free +=
4078 cache->uc_freebucket->ub_cnt;
4079 ups[i].ups_allocs = cache->uc_allocs;
4080 ups[i].ups_frees = cache->uc_frees;
4083 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4084 for (i = 0; i < mp_maxid + 1; i++)
4085 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4088 rw_runlock(&uma_rwlock);
4089 error = sbuf_finish(&sbuf);
4096 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4098 uma_zone_t zone = *(uma_zone_t *)arg1;
4101 max = uma_zone_get_max(zone);
4102 error = sysctl_handle_int(oidp, &max, 0, req);
4103 if (error || !req->newptr)
4106 uma_zone_set_max(zone, max);
4112 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4114 uma_zone_t zone = *(uma_zone_t *)arg1;
4117 cur = uma_zone_get_cur(zone);
4118 return (sysctl_handle_int(oidp, &cur, 0, req));
4123 uma_dbg_getslab(uma_zone_t zone, void *item)
4129 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4130 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4131 slab = vtoslab((vm_offset_t)mem);
4134 * It is safe to return the slab here even though the
4135 * zone is unlocked because the item's allocation state
4136 * essentially holds a reference.
4139 keg = LIST_FIRST(&zone->uz_kegs)->kl_keg;
4140 if (keg->uk_flags & UMA_ZONE_HASH)
4141 slab = hash_sfind(&keg->uk_hash, mem);
4143 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4151 uma_dbg_zskip(uma_zone_t zone, void *mem)
4155 if ((keg = zone_first_keg(zone)) == NULL)
4158 return (uma_dbg_kskip(keg, mem));
4162 uma_dbg_kskip(uma_keg_t keg, void *mem)
4166 if (dbg_divisor == 0)
4169 if (dbg_divisor == 1)
4172 idx = (uintptr_t)mem >> PAGE_SHIFT;
4173 if (keg->uk_ipers > 1) {
4174 idx *= keg->uk_ipers;
4175 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4178 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4179 counter_u64_add(uma_skip_cnt, 1);
4182 counter_u64_add(uma_dbg_cnt, 1);
4188 * Set up the slab's freei data such that uma_dbg_free can function.
4192 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4198 slab = uma_dbg_getslab(zone, item);
4200 panic("uma: item %p did not belong to zone %s\n",
4201 item, zone->uz_name);
4204 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4206 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4207 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4208 item, zone, zone->uz_name, slab, freei);
4209 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4215 * Verifies freed addresses. Checks for alignment, valid slab membership
4216 * and duplicate frees.
4220 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4226 slab = uma_dbg_getslab(zone, item);
4228 panic("uma: Freed item %p did not belong to zone %s\n",
4229 item, zone->uz_name);
4232 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4234 if (freei >= keg->uk_ipers)
4235 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4236 item, zone, zone->uz_name, slab, freei);
4238 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4239 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4240 item, zone, zone->uz_name, slab, freei);
4242 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4243 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4244 item, zone, zone->uz_name, slab, freei);
4246 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4248 #endif /* INVARIANTS */
4251 DB_SHOW_COMMAND(uma, db_show_uma)
4255 uint64_t allocs, frees, sleeps;
4259 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4260 "Free", "Requests", "Sleeps", "Bucket");
4261 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4262 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4263 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4264 allocs = z->uz_allocs;
4265 frees = z->uz_frees;
4266 sleeps = z->uz_sleeps;
4269 uma_zone_sumstat(z, &cachefree, &allocs,
4271 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4272 (LIST_FIRST(&kz->uk_zones) != z)))
4273 cachefree += kz->uk_free;
4274 for (i = 0; i < vm_ndomains; i++)
4275 cachefree += z->uz_domain[i].uzd_nitems;
4277 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4278 z->uz_name, (uintmax_t)kz->uk_size,
4279 (intmax_t)(allocs - frees), cachefree,
4280 (uintmax_t)allocs, sleeps, z->uz_count);
4287 DB_SHOW_COMMAND(umacache, db_show_umacache)
4290 uint64_t allocs, frees;
4294 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4295 "Requests", "Bucket");
4296 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4297 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4298 for (i = 0; i < vm_ndomains; i++)
4299 cachefree += z->uz_domain[i].uzd_nitems;
4300 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4301 z->uz_name, (uintmax_t)z->uz_size,
4302 (intmax_t)(allocs - frees), cachefree,
4303 (uintmax_t)allocs, z->uz_count);