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_log_warning(uma_zone_t zone)
465 static const struct timeval warninterval = { 300, 0 };
467 if (!zone_warnings || zone->uz_warning == NULL)
470 if (ratecheck(&zone->uz_ratecheck, &warninterval))
471 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
475 zone_maxaction(uma_zone_t zone)
478 if (zone->uz_maxaction.ta_func != NULL)
479 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
483 zone_foreach_keg(uma_zone_t zone, void (*kegfn)(uma_keg_t))
487 LIST_FOREACH(klink, &zone->uz_kegs, kl_link)
488 kegfn(klink->kl_keg);
492 * Routine called by timeout which is used to fire off some time interval
493 * based calculations. (stats, hash size, etc.)
502 uma_timeout(void *unused)
505 zone_foreach(zone_timeout);
507 /* Reschedule this event */
508 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
512 * Routine to perform timeout driven calculations. This expands the
513 * hashes and does per cpu statistics aggregation.
518 keg_timeout(uma_keg_t keg)
523 * Expand the keg hash table.
525 * This is done if the number of slabs is larger than the hash size.
526 * What I'm trying to do here is completely reduce collisions. This
527 * may be a little aggressive. Should I allow for two collisions max?
529 if (keg->uk_flags & UMA_ZONE_HASH &&
530 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
531 struct uma_hash newhash;
532 struct uma_hash oldhash;
536 * This is so involved because allocating and freeing
537 * while the keg lock is held will lead to deadlock.
538 * I have to do everything in stages and check for
541 newhash = keg->uk_hash;
543 ret = hash_alloc(&newhash);
546 if (hash_expand(&keg->uk_hash, &newhash)) {
547 oldhash = keg->uk_hash;
548 keg->uk_hash = newhash;
561 zone_timeout(uma_zone_t zone)
564 zone_foreach_keg(zone, &keg_timeout);
568 * Allocate and zero fill the next sized hash table from the appropriate
572 * hash A new hash structure with the old hash size in uh_hashsize
575 * 1 on success and 0 on failure.
578 hash_alloc(struct uma_hash *hash)
583 oldsize = hash->uh_hashsize;
585 /* We're just going to go to a power of two greater */
587 hash->uh_hashsize = oldsize * 2;
588 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
589 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
590 M_UMAHASH, M_NOWAIT);
592 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
593 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
594 UMA_ANYDOMAIN, M_WAITOK);
595 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
597 if (hash->uh_slab_hash) {
598 bzero(hash->uh_slab_hash, alloc);
599 hash->uh_hashmask = hash->uh_hashsize - 1;
607 * Expands the hash table for HASH zones. This is done from zone_timeout
608 * to reduce collisions. This must not be done in the regular allocation
609 * path, otherwise, we can recurse on the vm while allocating pages.
612 * oldhash The hash you want to expand
613 * newhash The hash structure for the new table
621 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
627 if (!newhash->uh_slab_hash)
630 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
634 * I need to investigate hash algorithms for resizing without a
638 for (i = 0; i < oldhash->uh_hashsize; i++)
639 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
640 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
641 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
642 hval = UMA_HASH(newhash, slab->us_data);
643 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
651 * Free the hash bucket to the appropriate backing store.
654 * slab_hash The hash bucket we're freeing
655 * hashsize The number of entries in that hash bucket
661 hash_free(struct uma_hash *hash)
663 if (hash->uh_slab_hash == NULL)
665 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
666 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
668 free(hash->uh_slab_hash, M_UMAHASH);
672 * Frees all outstanding items in a bucket
675 * zone The zone to free to, must be unlocked.
676 * bucket The free/alloc bucket with items, cpu queue must be locked.
683 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
691 for (i = 0; i < bucket->ub_cnt; i++)
692 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
693 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
698 * Drains the per cpu caches for a zone.
700 * NOTE: This may only be called while the zone is being turn down, and not
701 * during normal operation. This is necessary in order that we do not have
702 * to migrate CPUs to drain the per-CPU caches.
705 * zone The zone to drain, must be unlocked.
711 cache_drain(uma_zone_t zone)
717 * XXX: It is safe to not lock the per-CPU caches, because we're
718 * tearing down the zone anyway. I.e., there will be no further use
719 * of the caches at this point.
721 * XXX: It would good to be able to assert that the zone is being
722 * torn down to prevent improper use of cache_drain().
724 * XXX: We lock the zone before passing into bucket_cache_drain() as
725 * it is used elsewhere. Should the tear-down path be made special
726 * there in some form?
729 cache = &zone->uz_cpu[cpu];
730 bucket_drain(zone, cache->uc_allocbucket);
731 bucket_drain(zone, cache->uc_freebucket);
732 if (cache->uc_allocbucket != NULL)
733 bucket_free(zone, cache->uc_allocbucket, NULL);
734 if (cache->uc_freebucket != NULL)
735 bucket_free(zone, cache->uc_freebucket, NULL);
736 cache->uc_allocbucket = cache->uc_freebucket = NULL;
739 bucket_cache_drain(zone);
744 cache_shrink(uma_zone_t zone)
747 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
751 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
756 cache_drain_safe_cpu(uma_zone_t zone)
762 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
768 if (zone->uz_flags & UMA_ZONE_NUMA)
769 domain = PCPU_GET(domain);
772 cache = &zone->uz_cpu[curcpu];
773 if (cache->uc_allocbucket) {
774 if (cache->uc_allocbucket->ub_cnt != 0)
775 LIST_INSERT_HEAD(&zone->uz_domain[domain].uzd_buckets,
776 cache->uc_allocbucket, ub_link);
778 b1 = cache->uc_allocbucket;
779 cache->uc_allocbucket = NULL;
781 if (cache->uc_freebucket) {
782 if (cache->uc_freebucket->ub_cnt != 0)
783 LIST_INSERT_HEAD(&zone->uz_domain[domain].uzd_buckets,
784 cache->uc_freebucket, ub_link);
786 b2 = cache->uc_freebucket;
787 cache->uc_freebucket = NULL;
792 bucket_free(zone, b1, NULL);
794 bucket_free(zone, b2, NULL);
798 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
799 * This is an expensive call because it needs to bind to all CPUs
800 * one by one and enter a critical section on each of them in order
801 * to safely access their cache buckets.
802 * Zone lock must not be held on call this function.
805 cache_drain_safe(uma_zone_t zone)
810 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
815 zone_foreach(cache_shrink);
818 thread_lock(curthread);
819 sched_bind(curthread, cpu);
820 thread_unlock(curthread);
823 cache_drain_safe_cpu(zone);
825 zone_foreach(cache_drain_safe_cpu);
827 thread_lock(curthread);
828 sched_unbind(curthread);
829 thread_unlock(curthread);
833 * Drain the cached buckets from a zone. Expects a locked zone on entry.
836 bucket_cache_drain(uma_zone_t zone)
838 uma_zone_domain_t zdom;
843 * Drain the bucket queues and free the buckets.
845 for (i = 0; i < vm_ndomains; i++) {
846 zdom = &zone->uz_domain[i];
847 while ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
848 LIST_REMOVE(bucket, ub_link);
850 bucket_drain(zone, bucket);
851 bucket_free(zone, bucket, NULL);
857 * Shrink further bucket sizes. Price of single zone lock collision
858 * is probably lower then price of global cache drain.
860 if (zone->uz_count > zone->uz_count_min)
865 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
871 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
872 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
875 flags = slab->us_flags;
877 if (keg->uk_fini != NULL) {
878 for (i--; i > -1; i--)
881 * trash_fini implies that dtor was trash_dtor. trash_fini
882 * would check that memory hasn't been modified since free,
883 * which executed trash_dtor.
884 * That's why we need to run uma_dbg_kskip() check here,
885 * albeit we don't make skip check for other init/fini
888 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
889 keg->uk_fini != trash_fini)
891 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
894 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
895 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
896 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
897 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
901 * Frees pages from a keg back to the system. This is done on demand from
902 * the pageout daemon.
907 keg_drain(uma_keg_t keg)
909 struct slabhead freeslabs = { 0 };
911 uma_slab_t slab, tmp;
915 * We don't want to take pages from statically allocated kegs at this
918 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
921 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
922 keg->uk_name, keg, keg->uk_free);
924 if (keg->uk_free == 0)
927 for (i = 0; i < vm_ndomains; i++) {
928 dom = &keg->uk_domain[i];
929 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
930 /* We have nowhere to free these to. */
931 if (slab->us_flags & UMA_SLAB_BOOT)
934 LIST_REMOVE(slab, us_link);
935 keg->uk_pages -= keg->uk_ppera;
936 keg->uk_free -= keg->uk_ipers;
938 if (keg->uk_flags & UMA_ZONE_HASH)
939 UMA_HASH_REMOVE(&keg->uk_hash, slab,
942 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
949 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
950 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
951 keg_free_slab(keg, slab, keg->uk_ipers);
956 zone_drain_wait(uma_zone_t zone, int waitok)
960 * Set draining to interlock with zone_dtor() so we can release our
961 * locks as we go. Only dtor() should do a WAITOK call since it
962 * is the only call that knows the structure will still be available
966 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
967 if (waitok == M_NOWAIT)
969 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
971 zone->uz_flags |= UMA_ZFLAG_DRAINING;
972 bucket_cache_drain(zone);
975 * The DRAINING flag protects us from being freed while
976 * we're running. Normally the uma_rwlock would protect us but we
977 * must be able to release and acquire the right lock for each keg.
979 zone_foreach_keg(zone, &keg_drain);
981 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
988 zone_drain(uma_zone_t zone)
991 zone_drain_wait(zone, M_NOWAIT);
995 * Allocate a new slab for a keg. This does not insert the slab onto a list.
996 * If the allocation was successful, the keg lock will be held upon return,
997 * otherwise the keg will be left unlocked.
1000 * wait Shall we wait?
1003 * The slab that was allocated or NULL if there is no memory and the
1004 * caller specified M_NOWAIT.
1007 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int wait)
1016 KASSERT(domain >= 0 && domain < vm_ndomains,
1017 ("keg_alloc_slab: domain %d out of range", domain));
1018 mtx_assert(&keg->uk_lock, MA_OWNED);
1020 allocf = keg->uk_allocf;
1025 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1026 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, wait);
1032 * This reproduces the old vm_zone behavior of zero filling pages the
1033 * first time they are added to a zone.
1035 * Malloced items are zeroed in uma_zalloc.
1038 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1043 if (keg->uk_flags & UMA_ZONE_NODUMP)
1046 /* zone is passed for legacy reasons. */
1047 size = keg->uk_ppera * PAGE_SIZE;
1048 mem = allocf(zone, size, domain, &flags, wait);
1050 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1051 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1055 uma_total_inc(size);
1057 /* Point the slab into the allocated memory */
1058 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1059 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1061 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1062 for (i = 0; i < keg->uk_ppera; i++)
1063 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1066 slab->us_data = mem;
1067 slab->us_freecount = keg->uk_ipers;
1068 slab->us_flags = flags;
1069 slab->us_domain = domain;
1070 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1072 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1075 if (keg->uk_init != NULL) {
1076 for (i = 0; i < keg->uk_ipers; i++)
1077 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1078 keg->uk_size, wait) != 0)
1080 if (i != keg->uk_ipers) {
1081 keg_free_slab(keg, slab, i);
1088 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1089 slab, keg->uk_name, keg);
1091 if (keg->uk_flags & UMA_ZONE_HASH)
1092 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1094 keg->uk_pages += keg->uk_ppera;
1095 keg->uk_free += keg->uk_ipers;
1102 * This function is intended to be used early on in place of page_alloc() so
1103 * that we may use the boot time page cache to satisfy allocations before
1107 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1114 keg = zone_first_keg(zone);
1117 * If we are in BOOT_BUCKETS or higher, than switch to real
1118 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1124 case BOOT_PAGEALLOC:
1125 if (keg->uk_ppera > 1)
1129 #ifdef UMA_MD_SMALL_ALLOC
1130 keg->uk_allocf = (keg->uk_ppera > 1) ?
1131 page_alloc : uma_small_alloc;
1133 keg->uk_allocf = page_alloc;
1135 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1139 * Check our small startup cache to see if it has pages remaining.
1141 pages = howmany(bytes, PAGE_SIZE);
1142 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1143 if (pages > boot_pages)
1144 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1146 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1150 boot_pages -= pages;
1151 bootmem += pages * PAGE_SIZE;
1152 *pflag = UMA_SLAB_BOOT;
1158 * Allocates a number of pages from the system
1161 * bytes The number of bytes requested
1162 * wait Shall we wait?
1165 * A pointer to the alloced memory or possibly
1166 * NULL if M_NOWAIT is set.
1169 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1172 void *p; /* Returned page */
1174 *pflag = UMA_SLAB_KERNEL;
1175 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1181 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1184 struct pglist alloctail;
1185 vm_offset_t addr, zkva;
1187 vm_page_t p, p_next;
1192 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1194 TAILQ_INIT(&alloctail);
1195 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1196 malloc2vm_flags(wait);
1197 *pflag = UMA_SLAB_KERNEL;
1198 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1199 if (CPU_ABSENT(cpu)) {
1200 p = vm_page_alloc(NULL, 0, flags);
1203 p = vm_page_alloc(NULL, 0, flags);
1205 pc = pcpu_find(cpu);
1206 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1207 if (__predict_false(p == NULL))
1208 p = vm_page_alloc(NULL, 0, flags);
1211 if (__predict_false(p == NULL))
1213 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1215 if ((addr = kva_alloc(bytes)) == 0)
1218 TAILQ_FOREACH(p, &alloctail, listq) {
1219 pmap_qenter(zkva, &p, 1);
1222 return ((void*)addr);
1224 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1225 vm_page_unwire(p, PQ_NONE);
1232 * Allocates a number of pages from within an object
1235 * bytes The number of bytes requested
1236 * wait Shall we wait?
1239 * A pointer to the alloced memory or possibly
1240 * NULL if M_NOWAIT is set.
1243 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1246 TAILQ_HEAD(, vm_page) alloctail;
1248 vm_offset_t retkva, zkva;
1249 vm_page_t p, p_next;
1252 TAILQ_INIT(&alloctail);
1253 keg = zone_first_keg(zone);
1255 npages = howmany(bytes, PAGE_SIZE);
1256 while (npages > 0) {
1257 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1258 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1259 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1263 * Since the page does not belong to an object, its
1266 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1271 * Page allocation failed, free intermediate pages and
1274 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1275 vm_page_unwire(p, PQ_NONE);
1280 *flags = UMA_SLAB_PRIV;
1281 zkva = keg->uk_kva +
1282 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1284 TAILQ_FOREACH(p, &alloctail, listq) {
1285 pmap_qenter(zkva, &p, 1);
1289 return ((void *)retkva);
1293 * Frees a number of pages to the system
1296 * mem A pointer to the memory to be freed
1297 * size The size of the memory being freed
1298 * flags The original p->us_flags field
1304 page_free(void *mem, vm_size_t size, uint8_t flags)
1307 if ((flags & UMA_SLAB_KERNEL) == 0)
1308 panic("UMA: page_free used with invalid flags %x", flags);
1310 kmem_free((vm_offset_t)mem, size);
1314 * Frees pcpu zone allocations
1317 * mem A pointer to the memory to be freed
1318 * size The size of the memory being freed
1319 * flags The original p->us_flags field
1325 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1327 vm_offset_t sva, curva;
1331 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1332 sva = (vm_offset_t)mem;
1333 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1334 paddr = pmap_kextract(curva);
1335 m = PHYS_TO_VM_PAGE(paddr);
1336 vm_page_unwire(m, PQ_NONE);
1339 pmap_qremove(sva, size >> PAGE_SHIFT);
1340 kva_free(sva, size);
1345 * Zero fill initializer
1347 * Arguments/Returns follow uma_init specifications
1350 zero_init(void *mem, int size, int flags)
1357 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1360 * keg The zone we should initialize
1366 keg_small_init(uma_keg_t keg)
1374 if (keg->uk_flags & UMA_ZONE_PCPU) {
1375 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1377 slabsize = UMA_PCPU_ALLOC_SIZE;
1378 keg->uk_ppera = ncpus;
1380 slabsize = UMA_SLAB_SIZE;
1385 * Calculate the size of each allocation (rsize) according to
1386 * alignment. If the requested size is smaller than we have
1387 * allocation bits for we round it up.
1389 rsize = keg->uk_size;
1390 if (rsize < slabsize / SLAB_SETSIZE)
1391 rsize = slabsize / SLAB_SETSIZE;
1392 if (rsize & keg->uk_align)
1393 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1394 keg->uk_rsize = rsize;
1396 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1397 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1398 ("%s: size %u too large", __func__, keg->uk_rsize));
1400 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1403 shsize = sizeof(struct uma_slab);
1405 if (rsize <= slabsize - shsize)
1406 keg->uk_ipers = (slabsize - shsize) / rsize;
1408 /* Handle special case when we have 1 item per slab, so
1409 * alignment requirement can be relaxed. */
1410 KASSERT(keg->uk_size <= slabsize - shsize,
1411 ("%s: size %u greater than slab", __func__, keg->uk_size));
1414 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1415 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1417 memused = keg->uk_ipers * rsize + shsize;
1418 wastedspace = slabsize - memused;
1421 * We can't do OFFPAGE if we're internal or if we've been
1422 * asked to not go to the VM for buckets. If we do this we
1423 * may end up going to the VM for slabs which we do not
1424 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1425 * of UMA_ZONE_VM, which clearly forbids it.
1427 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1428 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1432 * See if using an OFFPAGE slab will limit our waste. Only do
1433 * this if it permits more items per-slab.
1435 * XXX We could try growing slabsize to limit max waste as well.
1436 * Historically this was not done because the VM could not
1437 * efficiently handle contiguous allocations.
1439 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1440 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1441 keg->uk_ipers = slabsize / keg->uk_rsize;
1442 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1443 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1444 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1445 "keg: %s(%p), calculated wastedspace = %d, "
1446 "maximum wasted space allowed = %d, "
1447 "calculated ipers = %d, "
1448 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1449 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1450 slabsize - keg->uk_ipers * keg->uk_rsize);
1451 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1454 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1455 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1456 keg->uk_flags |= UMA_ZONE_HASH;
1460 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1461 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1465 * keg The keg we should initialize
1471 keg_large_init(uma_keg_t keg)
1475 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1476 KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1477 ("keg_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY keg"));
1478 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1479 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1481 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1483 keg->uk_rsize = keg->uk_size;
1485 /* Check whether we have enough space to not do OFFPAGE. */
1486 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0) {
1487 shsize = sizeof(struct uma_slab);
1488 if (shsize & UMA_ALIGN_PTR)
1489 shsize = (shsize & ~UMA_ALIGN_PTR) +
1490 (UMA_ALIGN_PTR + 1);
1492 if (PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < shsize) {
1494 * We can't do OFFPAGE if we're internal, in which case
1495 * we need an extra page per allocation to contain the
1498 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1499 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1505 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1506 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1507 keg->uk_flags |= UMA_ZONE_HASH;
1511 keg_cachespread_init(uma_keg_t keg)
1518 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1519 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1521 alignsize = keg->uk_align + 1;
1522 rsize = keg->uk_size;
1524 * We want one item to start on every align boundary in a page. To
1525 * do this we will span pages. We will also extend the item by the
1526 * size of align if it is an even multiple of align. Otherwise, it
1527 * would fall on the same boundary every time.
1529 if (rsize & keg->uk_align)
1530 rsize = (rsize & ~keg->uk_align) + alignsize;
1531 if ((rsize & alignsize) == 0)
1533 trailer = rsize - keg->uk_size;
1534 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1535 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1536 keg->uk_rsize = rsize;
1537 keg->uk_ppera = pages;
1538 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1539 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1540 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1541 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1546 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1547 * the keg onto the global keg list.
1549 * Arguments/Returns follow uma_ctor specifications
1550 * udata Actually uma_kctor_args
1553 keg_ctor(void *mem, int size, void *udata, int flags)
1555 struct uma_kctor_args *arg = udata;
1556 uma_keg_t keg = mem;
1560 keg->uk_size = arg->size;
1561 keg->uk_init = arg->uminit;
1562 keg->uk_fini = arg->fini;
1563 keg->uk_align = arg->align;
1565 keg->uk_reserve = 0;
1567 keg->uk_flags = arg->flags;
1568 keg->uk_slabzone = NULL;
1571 * We use a global round-robin policy by default. Zones with
1572 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1573 * iterator is never run.
1575 keg->uk_dr.dr_policy = DOMAINSET_RR();
1576 keg->uk_dr.dr_iter = 0;
1579 * The master zone is passed to us at keg-creation time.
1582 keg->uk_name = zone->uz_name;
1584 if (arg->flags & UMA_ZONE_VM)
1585 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1587 if (arg->flags & UMA_ZONE_ZINIT)
1588 keg->uk_init = zero_init;
1590 if (arg->flags & UMA_ZONE_MALLOC)
1591 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1593 if (arg->flags & UMA_ZONE_PCPU)
1595 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1597 keg->uk_flags &= ~UMA_ZONE_PCPU;
1600 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1601 keg_cachespread_init(keg);
1603 if (keg->uk_size > UMA_SLAB_SPACE)
1604 keg_large_init(keg);
1606 keg_small_init(keg);
1609 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1610 keg->uk_slabzone = slabzone;
1613 * If we haven't booted yet we need allocations to go through the
1614 * startup cache until the vm is ready.
1616 if (booted < BOOT_PAGEALLOC)
1617 keg->uk_allocf = startup_alloc;
1618 #ifdef UMA_MD_SMALL_ALLOC
1619 else if (keg->uk_ppera == 1)
1620 keg->uk_allocf = uma_small_alloc;
1622 else if (keg->uk_flags & UMA_ZONE_PCPU)
1623 keg->uk_allocf = pcpu_page_alloc;
1625 keg->uk_allocf = page_alloc;
1626 #ifdef UMA_MD_SMALL_ALLOC
1627 if (keg->uk_ppera == 1)
1628 keg->uk_freef = uma_small_free;
1631 if (keg->uk_flags & UMA_ZONE_PCPU)
1632 keg->uk_freef = pcpu_page_free;
1634 keg->uk_freef = page_free;
1637 * Initialize keg's lock
1639 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1642 * If we're putting the slab header in the actual page we need to
1643 * figure out where in each page it goes. This calculates a right
1644 * justified offset into the memory on an ALIGN_PTR boundary.
1646 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1649 /* Size of the slab struct and free list */
1650 totsize = sizeof(struct uma_slab);
1652 if (totsize & UMA_ALIGN_PTR)
1653 totsize = (totsize & ~UMA_ALIGN_PTR) +
1654 (UMA_ALIGN_PTR + 1);
1655 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - totsize;
1658 * The only way the following is possible is if with our
1659 * UMA_ALIGN_PTR adjustments we are now bigger than
1660 * UMA_SLAB_SIZE. I haven't checked whether this is
1661 * mathematically possible for all cases, so we make
1664 totsize = keg->uk_pgoff + sizeof(struct uma_slab);
1665 if (totsize > PAGE_SIZE * keg->uk_ppera) {
1666 printf("zone %s ipers %d rsize %d size %d\n",
1667 zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1669 panic("UMA slab won't fit.");
1673 if (keg->uk_flags & UMA_ZONE_HASH)
1674 hash_alloc(&keg->uk_hash);
1676 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1677 keg, zone->uz_name, zone,
1678 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1681 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1683 rw_wlock(&uma_rwlock);
1684 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1685 rw_wunlock(&uma_rwlock);
1690 * Zone header ctor. This initializes all fields, locks, etc.
1692 * Arguments/Returns follow uma_ctor specifications
1693 * udata Actually uma_zctor_args
1696 zone_ctor(void *mem, int size, void *udata, int flags)
1698 struct uma_zctor_args *arg = udata;
1699 uma_zone_t zone = mem;
1704 zone->uz_name = arg->name;
1705 zone->uz_ctor = arg->ctor;
1706 zone->uz_dtor = arg->dtor;
1707 zone->uz_slab = zone_fetch_slab;
1708 zone->uz_init = NULL;
1709 zone->uz_fini = NULL;
1710 zone->uz_allocs = 0;
1713 zone->uz_sleeps = 0;
1715 zone->uz_count_min = 0;
1717 zone->uz_warning = NULL;
1718 /* The domain structures follow the cpu structures. */
1719 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1720 timevalclear(&zone->uz_ratecheck);
1723 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1726 * This is a pure cache zone, no kegs.
1729 if (arg->flags & UMA_ZONE_VM)
1730 arg->flags |= UMA_ZFLAG_CACHEONLY;
1731 zone->uz_flags = arg->flags;
1732 zone->uz_size = arg->size;
1733 zone->uz_import = arg->import;
1734 zone->uz_release = arg->release;
1735 zone->uz_arg = arg->arg;
1736 zone->uz_lockptr = &zone->uz_lock;
1737 rw_wlock(&uma_rwlock);
1738 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1739 rw_wunlock(&uma_rwlock);
1744 * Use the regular zone/keg/slab allocator.
1746 zone->uz_import = (uma_import)zone_import;
1747 zone->uz_release = (uma_release)zone_release;
1748 zone->uz_arg = zone;
1750 if (arg->flags & UMA_ZONE_SECONDARY) {
1751 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1752 zone->uz_init = arg->uminit;
1753 zone->uz_fini = arg->fini;
1754 zone->uz_lockptr = &keg->uk_lock;
1755 zone->uz_flags |= UMA_ZONE_SECONDARY;
1756 rw_wlock(&uma_rwlock);
1758 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1759 if (LIST_NEXT(z, uz_link) == NULL) {
1760 LIST_INSERT_AFTER(z, zone, uz_link);
1765 rw_wunlock(&uma_rwlock);
1766 } else if (keg == NULL) {
1767 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1768 arg->align, arg->flags)) == NULL)
1771 struct uma_kctor_args karg;
1774 /* We should only be here from uma_startup() */
1775 karg.size = arg->size;
1776 karg.uminit = arg->uminit;
1777 karg.fini = arg->fini;
1778 karg.align = arg->align;
1779 karg.flags = arg->flags;
1781 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1788 * Link in the first keg.
1790 zone->uz_klink.kl_keg = keg;
1791 LIST_INSERT_HEAD(&zone->uz_kegs, &zone->uz_klink, kl_link);
1792 zone->uz_lockptr = &keg->uk_lock;
1793 zone->uz_size = keg->uk_size;
1794 zone->uz_flags |= (keg->uk_flags &
1795 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1798 * Some internal zones don't have room allocated for the per cpu
1799 * caches. If we're internal, bail out here.
1801 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1802 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1803 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1808 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1809 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1810 ("Invalid zone flag combination"));
1811 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1812 zone->uz_count = BUCKET_MAX;
1813 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1816 zone->uz_count = bucket_select(zone->uz_size);
1817 zone->uz_count_min = zone->uz_count;
1823 * Keg header dtor. This frees all data, destroys locks, frees the hash
1824 * table and removes the keg from the global list.
1826 * Arguments/Returns follow uma_dtor specifications
1830 keg_dtor(void *arg, int size, void *udata)
1834 keg = (uma_keg_t)arg;
1836 if (keg->uk_free != 0) {
1837 printf("Freed UMA keg (%s) was not empty (%d items). "
1838 " Lost %d pages of memory.\n",
1839 keg->uk_name ? keg->uk_name : "",
1840 keg->uk_free, keg->uk_pages);
1844 hash_free(&keg->uk_hash);
1852 * Arguments/Returns follow uma_dtor specifications
1856 zone_dtor(void *arg, int size, void *udata)
1862 zone = (uma_zone_t)arg;
1863 keg = zone_first_keg(zone);
1865 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1868 rw_wlock(&uma_rwlock);
1869 LIST_REMOVE(zone, uz_link);
1870 rw_wunlock(&uma_rwlock);
1872 * XXX there are some races here where
1873 * the zone can be drained but zone lock
1874 * released and then refilled before we
1875 * remove it... we dont care for now
1877 zone_drain_wait(zone, M_WAITOK);
1879 * Unlink all of our kegs.
1881 while ((klink = LIST_FIRST(&zone->uz_kegs)) != NULL) {
1882 klink->kl_keg = NULL;
1883 LIST_REMOVE(klink, kl_link);
1884 if (klink == &zone->uz_klink)
1886 free(klink, M_TEMP);
1889 * We only destroy kegs from non secondary zones.
1891 if (keg != NULL && (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1892 rw_wlock(&uma_rwlock);
1893 LIST_REMOVE(keg, uk_link);
1894 rw_wunlock(&uma_rwlock);
1895 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1897 ZONE_LOCK_FINI(zone);
1901 * Traverses every zone in the system and calls a callback
1904 * zfunc A pointer to a function which accepts a zone
1911 zone_foreach(void (*zfunc)(uma_zone_t))
1916 rw_rlock(&uma_rwlock);
1917 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1918 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1921 rw_runlock(&uma_rwlock);
1925 * Count how many pages do we need to bootstrap. VM supplies
1926 * its need in early zones in the argument, we add up our zones,
1927 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1928 * zone of zones and zone of kegs are accounted separately.
1930 #define UMA_BOOT_ZONES 11
1931 /* Zone of zones and zone of kegs have arbitrary alignment. */
1932 #define UMA_BOOT_ALIGN 32
1933 static int zsize, ksize;
1935 uma_startup_count(int vm_zones)
1939 ksize = sizeof(struct uma_keg) +
1940 (sizeof(struct uma_domain) * vm_ndomains);
1941 zsize = sizeof(struct uma_zone) +
1942 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1943 (sizeof(struct uma_zone_domain) * vm_ndomains);
1946 * Memory for the zone of kegs and its keg,
1947 * and for zone of zones.
1949 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1950 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1952 #ifdef UMA_MD_SMALL_ALLOC
1953 zones = UMA_BOOT_ZONES;
1955 zones = UMA_BOOT_ZONES + vm_zones;
1959 /* Memory for the rest of startup zones, UMA and VM, ... */
1960 if (zsize > UMA_SLAB_SPACE)
1961 pages += (zones + vm_zones) *
1962 howmany(roundup2(zsize, UMA_BOOT_ALIGN), UMA_SLAB_SIZE);
1963 else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
1966 pages += howmany(zones,
1967 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
1969 /* ... and their kegs. Note that zone of zones allocates a keg! */
1970 pages += howmany(zones + 1,
1971 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
1974 * Most of startup zones are not going to be offpages, that's
1975 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
1976 * calculations. Some large bucket zones will be offpage, and
1977 * thus will allocate hashes. We take conservative approach
1978 * and assume that all zones may allocate hash. This may give
1979 * us some positive inaccuracy, usually an extra single page.
1981 pages += howmany(zones, UMA_SLAB_SPACE /
1982 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
1988 uma_startup(void *mem, int npages)
1990 struct uma_zctor_args args;
1991 uma_keg_t masterkeg;
1995 printf("Entering %s with %d boot pages configured\n", __func__, npages);
1998 rw_init(&uma_rwlock, "UMA lock");
2000 /* Use bootpages memory for the zone of zones and zone of kegs. */
2002 zones = (uma_zone_t)m;
2003 m += roundup(zsize, CACHE_LINE_SIZE);
2004 kegs = (uma_zone_t)m;
2005 m += roundup(zsize, CACHE_LINE_SIZE);
2006 masterkeg = (uma_keg_t)m;
2007 m += roundup(ksize, CACHE_LINE_SIZE);
2008 m = roundup(m, PAGE_SIZE);
2009 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2012 /* "manually" create the initial zone */
2013 memset(&args, 0, sizeof(args));
2014 args.name = "UMA Kegs";
2016 args.ctor = keg_ctor;
2017 args.dtor = keg_dtor;
2018 args.uminit = zero_init;
2020 args.keg = masterkeg;
2021 args.align = UMA_BOOT_ALIGN - 1;
2022 args.flags = UMA_ZFLAG_INTERNAL;
2023 zone_ctor(kegs, zsize, &args, M_WAITOK);
2026 boot_pages = npages;
2028 args.name = "UMA Zones";
2030 args.ctor = zone_ctor;
2031 args.dtor = zone_dtor;
2032 args.uminit = zero_init;
2035 args.align = UMA_BOOT_ALIGN - 1;
2036 args.flags = UMA_ZFLAG_INTERNAL;
2037 zone_ctor(zones, zsize, &args, M_WAITOK);
2039 /* Now make a zone for slab headers */
2040 slabzone = uma_zcreate("UMA Slabs",
2041 sizeof(struct uma_slab),
2042 NULL, NULL, NULL, NULL,
2043 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2045 hashzone = uma_zcreate("UMA Hash",
2046 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2047 NULL, NULL, NULL, NULL,
2048 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2052 booted = BOOT_STRAPPED;
2060 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2062 booted = BOOT_PAGEALLOC;
2070 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2072 booted = BOOT_BUCKETS;
2073 sx_init(&uma_drain_lock, "umadrain");
2078 * Initialize our callout handle
2086 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2087 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2088 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2090 callout_init(&uma_callout, 1);
2091 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2092 booted = BOOT_RUNNING;
2096 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2097 int align, uint32_t flags)
2099 struct uma_kctor_args args;
2102 args.uminit = uminit;
2104 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2107 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2110 /* Public functions */
2113 uma_set_align(int align)
2116 if (align != UMA_ALIGN_CACHE)
2117 uma_align_cache = align;
2122 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2123 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2126 struct uma_zctor_args args;
2130 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2133 /* This stuff is essential for the zone ctor */
2134 memset(&args, 0, sizeof(args));
2139 args.uminit = uminit;
2143 * If a zone is being created with an empty constructor and
2144 * destructor, pass UMA constructor/destructor which checks for
2145 * memory use after free.
2147 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2148 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2149 args.ctor = trash_ctor;
2150 args.dtor = trash_dtor;
2151 args.uminit = trash_init;
2152 args.fini = trash_fini;
2159 if (booted < BOOT_BUCKETS) {
2162 sx_slock(&uma_drain_lock);
2165 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2167 sx_sunlock(&uma_drain_lock);
2173 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2174 uma_init zinit, uma_fini zfini, uma_zone_t master)
2176 struct uma_zctor_args args;
2181 keg = zone_first_keg(master);
2182 memset(&args, 0, sizeof(args));
2184 args.size = keg->uk_size;
2187 args.uminit = zinit;
2189 args.align = keg->uk_align;
2190 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2193 if (booted < BOOT_BUCKETS) {
2196 sx_slock(&uma_drain_lock);
2199 /* XXX Attaches only one keg of potentially many. */
2200 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2202 sx_sunlock(&uma_drain_lock);
2208 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2209 uma_init zinit, uma_fini zfini, uma_import zimport,
2210 uma_release zrelease, void *arg, int flags)
2212 struct uma_zctor_args args;
2214 memset(&args, 0, sizeof(args));
2219 args.uminit = zinit;
2221 args.import = zimport;
2222 args.release = zrelease;
2227 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2231 zone_lock_pair(uma_zone_t a, uma_zone_t b)
2235 mtx_lock_flags(b->uz_lockptr, MTX_DUPOK);
2238 mtx_lock_flags(a->uz_lockptr, MTX_DUPOK);
2243 zone_unlock_pair(uma_zone_t a, uma_zone_t b)
2251 uma_zsecond_add(uma_zone_t zone, uma_zone_t master)
2258 klink = malloc(sizeof(*klink), M_TEMP, M_WAITOK | M_ZERO);
2260 zone_lock_pair(zone, master);
2262 * zone must use vtoslab() to resolve objects and must already be
2265 if ((zone->uz_flags & (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY))
2266 != (UMA_ZONE_VTOSLAB | UMA_ZONE_SECONDARY)) {
2271 * The new master must also use vtoslab().
2273 if ((zone->uz_flags & UMA_ZONE_VTOSLAB) != UMA_ZONE_VTOSLAB) {
2279 * The underlying object must be the same size. rsize
2282 if (master->uz_size != zone->uz_size) {
2287 * Put it at the end of the list.
2289 klink->kl_keg = zone_first_keg(master);
2290 LIST_FOREACH(kl, &zone->uz_kegs, kl_link) {
2291 if (LIST_NEXT(kl, kl_link) == NULL) {
2292 LIST_INSERT_AFTER(kl, klink, kl_link);
2297 zone->uz_flags |= UMA_ZFLAG_MULTI;
2298 zone->uz_slab = zone_fetch_slab_multi;
2301 zone_unlock_pair(zone, master);
2303 free(klink, M_TEMP);
2311 uma_zdestroy(uma_zone_t zone)
2314 sx_slock(&uma_drain_lock);
2315 zone_free_item(zones, zone, NULL, SKIP_NONE);
2316 sx_sunlock(&uma_drain_lock);
2320 uma_zwait(uma_zone_t zone)
2324 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2325 uma_zfree(zone, item);
2329 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2335 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2337 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2338 if (item != NULL && (flags & M_ZERO)) {
2340 for (i = 0; i <= mp_maxid; i++)
2341 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2343 bzero(item, zone->uz_size);
2350 * A stub while both regular and pcpu cases are identical.
2353 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2357 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2359 uma_zfree_arg(zone, item, udata);
2364 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2366 uma_zone_domain_t zdom;
2367 uma_bucket_t bucket;
2370 int cpu, domain, lockfail;
2375 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2376 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2378 /* This is the fast path allocation */
2379 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2380 curthread, zone->uz_name, zone, flags);
2382 if (flags & M_WAITOK) {
2383 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2384 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2386 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2387 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2388 ("uma_zalloc_arg: called with spinlock or critical section held"));
2389 if (zone->uz_flags & UMA_ZONE_PCPU)
2390 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2391 "with M_ZERO passed"));
2393 #ifdef DEBUG_MEMGUARD
2394 if (memguard_cmp_zone(zone)) {
2395 item = memguard_alloc(zone->uz_size, flags);
2397 if (zone->uz_init != NULL &&
2398 zone->uz_init(item, zone->uz_size, flags) != 0)
2400 if (zone->uz_ctor != NULL &&
2401 zone->uz_ctor(item, zone->uz_size, udata,
2403 zone->uz_fini(item, zone->uz_size);
2408 /* This is unfortunate but should not be fatal. */
2412 * If possible, allocate from the per-CPU cache. There are two
2413 * requirements for safe access to the per-CPU cache: (1) the thread
2414 * accessing the cache must not be preempted or yield during access,
2415 * and (2) the thread must not migrate CPUs without switching which
2416 * cache it accesses. We rely on a critical section to prevent
2417 * preemption and migration. We release the critical section in
2418 * order to acquire the zone mutex if we are unable to allocate from
2419 * the current cache; when we re-acquire the critical section, we
2420 * must detect and handle migration if it has occurred.
2425 cache = &zone->uz_cpu[cpu];
2428 bucket = cache->uc_allocbucket;
2429 if (bucket != NULL && bucket->ub_cnt > 0) {
2431 item = bucket->ub_bucket[bucket->ub_cnt];
2433 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2435 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2439 skipdbg = uma_dbg_zskip(zone, item);
2441 if (zone->uz_ctor != NULL &&
2443 (!skipdbg || zone->uz_ctor != trash_ctor ||
2444 zone->uz_dtor != trash_dtor) &&
2446 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2447 atomic_add_long(&zone->uz_fails, 1);
2448 zone_free_item(zone, item, udata, SKIP_DTOR);
2453 uma_dbg_alloc(zone, NULL, item);
2456 uma_zero_item(item, zone);
2461 * We have run out of items in our alloc bucket.
2462 * See if we can switch with our free bucket.
2464 bucket = cache->uc_freebucket;
2465 if (bucket != NULL && bucket->ub_cnt > 0) {
2467 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2468 zone->uz_name, zone);
2469 cache->uc_freebucket = cache->uc_allocbucket;
2470 cache->uc_allocbucket = bucket;
2475 * Discard any empty allocation bucket while we hold no locks.
2477 bucket = cache->uc_allocbucket;
2478 cache->uc_allocbucket = NULL;
2481 bucket_free(zone, bucket, udata);
2483 if (zone->uz_flags & UMA_ZONE_NUMA) {
2484 domain = PCPU_GET(domain);
2485 if (VM_DOMAIN_EMPTY(domain))
2486 domain = UMA_ANYDOMAIN;
2488 domain = UMA_ANYDOMAIN;
2490 /* Short-circuit for zones without buckets and low memory. */
2491 if (zone->uz_count == 0 || bucketdisable)
2495 * Attempt to retrieve the item from the per-CPU cache has failed, so
2496 * we must go back to the zone. This requires the zone lock, so we
2497 * must drop the critical section, then re-acquire it when we go back
2498 * to the cache. Since the critical section is released, we may be
2499 * preempted or migrate. As such, make sure not to maintain any
2500 * thread-local state specific to the cache from prior to releasing
2501 * the critical section.
2504 if (ZONE_TRYLOCK(zone) == 0) {
2505 /* Record contention to size the buckets. */
2511 cache = &zone->uz_cpu[cpu];
2513 /* See if we lost the race to fill the cache. */
2514 if (cache->uc_allocbucket != NULL) {
2520 * Check the zone's cache of buckets.
2522 if (domain == UMA_ANYDOMAIN)
2523 zdom = &zone->uz_domain[0];
2525 zdom = &zone->uz_domain[domain];
2526 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
2527 KASSERT(bucket->ub_cnt != 0,
2528 ("uma_zalloc_arg: Returning an empty bucket."));
2530 LIST_REMOVE(bucket, ub_link);
2531 cache->uc_allocbucket = bucket;
2535 /* We are no longer associated with this CPU. */
2539 * We bump the uz count when the cache size is insufficient to
2540 * handle the working set.
2542 if (lockfail && zone->uz_count < BUCKET_MAX)
2547 * Now lets just fill a bucket and put it on the free list. If that
2548 * works we'll restart the allocation from the beginning and it
2549 * will use the just filled bucket.
2551 bucket = zone_alloc_bucket(zone, udata, domain, flags);
2552 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2553 zone->uz_name, zone, bucket);
2554 if (bucket != NULL) {
2558 cache = &zone->uz_cpu[cpu];
2560 * See if we lost the race or were migrated. Cache the
2561 * initialized bucket to make this less likely or claim
2562 * the memory directly.
2564 if (cache->uc_allocbucket == NULL &&
2565 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2566 domain == PCPU_GET(domain))) {
2567 cache->uc_allocbucket = bucket;
2568 } else if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
2571 bucket_drain(zone, bucket);
2572 bucket_free(zone, bucket, udata);
2573 goto zalloc_restart;
2575 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
2581 * We may not be able to get a bucket so return an actual item.
2584 item = zone_alloc_item(zone, udata, domain, flags);
2590 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2593 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2594 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2596 /* This is the fast path allocation */
2598 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2599 curthread, zone->uz_name, zone, domain, flags);
2601 if (flags & M_WAITOK) {
2602 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2603 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2605 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2606 ("uma_zalloc_domain: called with spinlock or critical section held"));
2608 return (zone_alloc_item(zone, udata, domain, flags));
2612 * Find a slab with some space. Prefer slabs that are partially used over those
2613 * that are totally full. This helps to reduce fragmentation.
2615 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2619 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2625 KASSERT(domain >= 0 && domain < vm_ndomains,
2626 ("keg_first_slab: domain %d out of range", domain));
2631 dom = &keg->uk_domain[domain];
2632 if (!LIST_EMPTY(&dom->ud_part_slab))
2633 return (LIST_FIRST(&dom->ud_part_slab));
2634 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2635 slab = LIST_FIRST(&dom->ud_free_slab);
2636 LIST_REMOVE(slab, us_link);
2637 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2641 domain = (domain + 1) % vm_ndomains;
2642 } while (domain != start);
2648 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2652 mtx_assert(&keg->uk_lock, MA_OWNED);
2654 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2655 if (keg->uk_free <= reserve)
2657 return (keg_first_slab(keg, domain, rr));
2661 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2663 struct vm_domainset_iter di;
2670 mtx_assert(&keg->uk_lock, MA_OWNED);
2673 * Use the keg's policy if upper layers haven't already specified a
2674 * domain (as happens with first-touch zones).
2676 * To avoid races we run the iterator with the keg lock held, but that
2677 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2678 * clear M_WAITOK and handle low memory conditions locally.
2680 rr = rdomain == UMA_ANYDOMAIN;
2682 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2683 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2691 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2693 MPASS(slab->us_keg == keg);
2698 * M_NOVM means don't ask at all!
2703 if (keg->uk_maxpages && keg->uk_pages >= keg->uk_maxpages) {
2704 keg->uk_flags |= UMA_ZFLAG_FULL;
2706 * If this is not a multi-zone, set the FULL bit.
2707 * Otherwise slab_multi() takes care of it.
2709 if ((zone->uz_flags & UMA_ZFLAG_MULTI) == 0) {
2710 zone->uz_flags |= UMA_ZFLAG_FULL;
2711 zone_log_warning(zone);
2712 zone_maxaction(zone);
2714 if (flags & M_NOWAIT)
2717 msleep(keg, &keg->uk_lock, PVM, "keglimit", 0);
2720 slab = keg_alloc_slab(keg, zone, domain, aflags);
2722 * If we got a slab here it's safe to mark it partially used
2723 * and return. We assume that the caller is going to remove
2724 * at least one item.
2727 MPASS(slab->us_keg == keg);
2728 dom = &keg->uk_domain[slab->us_domain];
2729 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2733 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2734 if ((flags & M_WAITOK) != 0) {
2736 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2745 * We might not have been able to get a slab but another cpu
2746 * could have while we were unlocked. Check again before we
2749 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2750 MPASS(slab->us_keg == keg);
2757 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2762 keg = zone_first_keg(zone);
2767 slab = keg_fetch_slab(keg, zone, domain, flags);
2770 if (flags & (M_NOWAIT | M_NOVM))
2778 * uma_zone_fetch_slab_multi: Fetches a slab from one available keg. Returns
2779 * with the keg locked. On NULL no lock is held.
2781 * The last pointer is used to seed the search. It is not required.
2784 zone_fetch_slab_multi(uma_zone_t zone, uma_keg_t last, int domain, int rflags)
2794 * Don't wait on the first pass. This will skip limit tests
2795 * as well. We don't want to block if we can find a provider
2798 flags = (rflags & ~M_WAITOK) | M_NOWAIT;
2800 * Use the last slab allocated as a hint for where to start
2804 slab = keg_fetch_slab(last, zone, domain, flags);
2810 * Loop until we have a slab incase of transient failures
2811 * while M_WAITOK is specified. I'm not sure this is 100%
2812 * required but we've done it for so long now.
2818 * Search the available kegs for slabs. Be careful to hold the
2819 * correct lock while calling into the keg layer.
2821 LIST_FOREACH(klink, &zone->uz_kegs, kl_link) {
2822 keg = klink->kl_keg;
2824 if ((keg->uk_flags & UMA_ZFLAG_FULL) == 0) {
2825 slab = keg_fetch_slab(keg, zone, domain, flags);
2829 if (keg->uk_flags & UMA_ZFLAG_FULL)
2835 if (rflags & (M_NOWAIT | M_NOVM))
2839 * All kegs are full. XXX We can't atomically check all kegs
2840 * and sleep so just sleep for a short period and retry.
2842 if (full && !empty) {
2844 zone->uz_flags |= UMA_ZFLAG_FULL;
2846 zone_log_warning(zone);
2847 zone_maxaction(zone);
2848 msleep(zone, zone->uz_lockptr, PVM,
2849 "zonelimit", hz/100);
2850 zone->uz_flags &= ~UMA_ZFLAG_FULL;
2859 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2865 MPASS(keg == slab->us_keg);
2866 mtx_assert(&keg->uk_lock, MA_OWNED);
2868 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2869 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2870 item = slab->us_data + (keg->uk_rsize * freei);
2871 slab->us_freecount--;
2874 /* Move this slab to the full list */
2875 if (slab->us_freecount == 0) {
2876 LIST_REMOVE(slab, us_link);
2877 dom = &keg->uk_domain[slab->us_domain];
2878 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2885 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2896 /* Try to keep the buckets totally full */
2897 for (i = 0; i < max; ) {
2898 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2902 stripe = howmany(max, vm_ndomains);
2904 while (slab->us_freecount && i < max) {
2905 bucket[i++] = slab_alloc_item(keg, slab);
2906 if (keg->uk_free <= keg->uk_reserve)
2910 * If the zone is striped we pick a new slab for every
2911 * N allocations. Eliminating this conditional will
2912 * instead pick a new domain for each bucket rather
2913 * than stripe within each bucket. The current option
2914 * produces more fragmentation and requires more cpu
2915 * time but yields better distribution.
2917 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2918 vm_ndomains > 1 && --stripe == 0)
2922 /* Don't block if we allocated any successfully. */
2933 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
2935 uma_bucket_t bucket;
2938 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2940 /* Don't wait for buckets, preserve caller's NOVM setting. */
2941 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2945 max = MIN(bucket->ub_entries, zone->uz_count);
2946 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2947 max, domain, flags);
2950 * Initialize the memory if necessary.
2952 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2955 for (i = 0; i < bucket->ub_cnt; i++)
2956 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2960 * If we couldn't initialize the whole bucket, put the
2961 * rest back onto the freelist.
2963 if (i != bucket->ub_cnt) {
2964 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2965 bucket->ub_cnt - i);
2967 bzero(&bucket->ub_bucket[i],
2968 sizeof(void *) * (bucket->ub_cnt - i));
2974 if (bucket->ub_cnt == 0) {
2975 bucket_free(zone, bucket, udata);
2976 atomic_add_long(&zone->uz_fails, 1);
2984 * Allocates a single item from a zone.
2987 * zone The zone to alloc for.
2988 * udata The data to be passed to the constructor.
2989 * domain The domain to allocate from or UMA_ANYDOMAIN.
2990 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2993 * NULL if there is no memory and M_NOWAIT is set
2994 * An item if successful
2998 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
3007 if (domain != UMA_ANYDOMAIN) {
3008 /* avoid allocs targeting empty domains */
3009 if (VM_DOMAIN_EMPTY(domain))
3010 domain = UMA_ANYDOMAIN;
3012 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
3014 atomic_add_long(&zone->uz_allocs, 1);
3017 skipdbg = uma_dbg_zskip(zone, item);
3020 * We have to call both the zone's init (not the keg's init)
3021 * and the zone's ctor. This is because the item is going from
3022 * a keg slab directly to the user, and the user is expecting it
3023 * to be both zone-init'd as well as zone-ctor'd.
3025 if (zone->uz_init != NULL) {
3026 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
3027 zone_free_item(zone, item, udata, SKIP_FINI);
3031 if (zone->uz_ctor != NULL &&
3033 (!skipdbg || zone->uz_ctor != trash_ctor ||
3034 zone->uz_dtor != trash_dtor) &&
3036 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
3037 zone_free_item(zone, item, udata, SKIP_DTOR);
3042 uma_dbg_alloc(zone, NULL, item);
3045 uma_zero_item(item, zone);
3047 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
3048 zone->uz_name, zone);
3053 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
3054 zone->uz_name, zone);
3055 atomic_add_long(&zone->uz_fails, 1);
3061 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
3064 uma_bucket_t bucket;
3065 uma_zone_domain_t zdom;
3066 int cpu, domain, lockfail;
3071 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3072 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3074 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3077 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3078 ("uma_zfree_arg: called with spinlock or critical section held"));
3080 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3083 #ifdef DEBUG_MEMGUARD
3084 if (is_memguard_addr(item)) {
3085 if (zone->uz_dtor != NULL)
3086 zone->uz_dtor(item, zone->uz_size, udata);
3087 if (zone->uz_fini != NULL)
3088 zone->uz_fini(item, zone->uz_size);
3089 memguard_free(item);
3094 skipdbg = uma_dbg_zskip(zone, item);
3095 if (skipdbg == false) {
3096 if (zone->uz_flags & UMA_ZONE_MALLOC)
3097 uma_dbg_free(zone, udata, item);
3099 uma_dbg_free(zone, NULL, item);
3101 if (zone->uz_dtor != NULL && (!skipdbg ||
3102 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3104 if (zone->uz_dtor != NULL)
3106 zone->uz_dtor(item, zone->uz_size, udata);
3109 * The race here is acceptable. If we miss it we'll just have to wait
3110 * a little longer for the limits to be reset.
3112 if (zone->uz_flags & UMA_ZFLAG_FULL)
3116 * If possible, free to the per-CPU cache. There are two
3117 * requirements for safe access to the per-CPU cache: (1) the thread
3118 * accessing the cache must not be preempted or yield during access,
3119 * and (2) the thread must not migrate CPUs without switching which
3120 * cache it accesses. We rely on a critical section to prevent
3121 * preemption and migration. We release the critical section in
3122 * order to acquire the zone mutex if we are unable to free to the
3123 * current cache; when we re-acquire the critical section, we must
3124 * detect and handle migration if it has occurred.
3129 cache = &zone->uz_cpu[cpu];
3133 * Try to free into the allocbucket first to give LIFO ordering
3134 * for cache-hot datastructures. Spill over into the freebucket
3135 * if necessary. Alloc will swap them if one runs dry.
3137 bucket = cache->uc_allocbucket;
3138 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3139 bucket = cache->uc_freebucket;
3140 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3141 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3142 ("uma_zfree: Freeing to non free bucket index."));
3143 bucket->ub_bucket[bucket->ub_cnt] = item;
3151 * We must go back the zone, which requires acquiring the zone lock,
3152 * which in turn means we must release and re-acquire the critical
3153 * section. Since the critical section is released, we may be
3154 * preempted or migrate. As such, make sure not to maintain any
3155 * thread-local state specific to the cache from prior to releasing
3156 * the critical section.
3159 if (zone->uz_count == 0 || bucketdisable)
3163 if (ZONE_TRYLOCK(zone) == 0) {
3164 /* Record contention to size the buckets. */
3170 cache = &zone->uz_cpu[cpu];
3172 bucket = cache->uc_freebucket;
3173 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3177 cache->uc_freebucket = NULL;
3178 /* We are no longer associated with this CPU. */
3181 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3182 domain = PCPU_GET(domain);
3183 if (VM_DOMAIN_EMPTY(domain))
3184 domain = UMA_ANYDOMAIN;
3187 zdom = &zone->uz_domain[0];
3189 /* Can we throw this on the zone full list? */
3190 if (bucket != NULL) {
3192 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3193 zone->uz_name, zone, bucket);
3194 /* ub_cnt is pointing to the last free item */
3195 KASSERT(bucket->ub_cnt != 0,
3196 ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
3197 if ((zone->uz_flags & UMA_ZONE_NOBUCKETCACHE) != 0) {
3199 bucket_drain(zone, bucket);
3200 bucket_free(zone, bucket, udata);
3203 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
3207 * We bump the uz count when the cache size is insufficient to
3208 * handle the working set.
3210 if (lockfail && zone->uz_count < BUCKET_MAX)
3214 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3215 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3216 zone->uz_name, zone, bucket);
3220 cache = &zone->uz_cpu[cpu];
3221 if (cache->uc_freebucket == NULL &&
3222 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3223 domain == PCPU_GET(domain))) {
3224 cache->uc_freebucket = bucket;
3228 * We lost the race, start over. We have to drop our
3229 * critical section to free the bucket.
3232 bucket_free(zone, bucket, udata);
3237 * If nothing else caught this, we'll just do an internal free.
3240 zone_free_item(zone, item, udata, SKIP_DTOR);
3246 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3249 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3250 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3252 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3255 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3256 ("uma_zfree_domain: called with spinlock or critical section held"));
3258 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3261 zone_free_item(zone, item, udata, SKIP_NONE);
3265 slab_free_item(uma_keg_t keg, uma_slab_t slab, void *item)
3270 mtx_assert(&keg->uk_lock, MA_OWNED);
3271 MPASS(keg == slab->us_keg);
3273 dom = &keg->uk_domain[slab->us_domain];
3275 /* Do we need to remove from any lists? */
3276 if (slab->us_freecount+1 == keg->uk_ipers) {
3277 LIST_REMOVE(slab, us_link);
3278 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3279 } else if (slab->us_freecount == 0) {
3280 LIST_REMOVE(slab, us_link);
3281 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3284 /* Slab management. */
3285 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3286 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3287 slab->us_freecount++;
3289 /* Keg statistics. */
3294 zone_release(uma_zone_t zone, void **bucket, int cnt)
3304 keg = zone_first_keg(zone);
3306 for (i = 0; i < cnt; i++) {
3308 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3309 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3310 if (zone->uz_flags & UMA_ZONE_HASH) {
3311 slab = hash_sfind(&keg->uk_hash, mem);
3313 mem += keg->uk_pgoff;
3314 slab = (uma_slab_t)mem;
3317 slab = vtoslab((vm_offset_t)item);
3318 if (slab->us_keg != keg) {
3324 slab_free_item(keg, slab, item);
3325 if (keg->uk_flags & UMA_ZFLAG_FULL) {
3326 if (keg->uk_pages < keg->uk_maxpages) {
3327 keg->uk_flags &= ~UMA_ZFLAG_FULL;
3332 * We can handle one more allocation. Since we're
3333 * clearing ZFLAG_FULL, wake up all procs blocked
3334 * on pages. This should be uncommon, so keeping this
3335 * simple for now (rather than adding count of blocked
3344 zone->uz_flags &= ~UMA_ZFLAG_FULL;
3352 * Frees a single item to any zone.
3355 * zone The zone to free to
3356 * item The item we're freeing
3357 * udata User supplied data for the dtor
3358 * skip Skip dtors and finis
3361 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3366 skipdbg = uma_dbg_zskip(zone, item);
3367 if (skip == SKIP_NONE && !skipdbg) {
3368 if (zone->uz_flags & UMA_ZONE_MALLOC)
3369 uma_dbg_free(zone, udata, item);
3371 uma_dbg_free(zone, NULL, item);
3374 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3375 (!skipdbg || zone->uz_dtor != trash_dtor ||
3376 zone->uz_ctor != trash_ctor))
3378 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3380 zone->uz_dtor(item, zone->uz_size, udata);
3382 if (skip < SKIP_FINI && zone->uz_fini)
3383 zone->uz_fini(item, zone->uz_size);
3385 atomic_add_long(&zone->uz_frees, 1);
3386 zone->uz_release(zone->uz_arg, &item, 1);
3391 uma_zone_set_max(uma_zone_t zone, int nitems)
3395 keg = zone_first_keg(zone);
3399 keg->uk_maxpages = (nitems / keg->uk_ipers) * keg->uk_ppera;
3400 if (keg->uk_maxpages * keg->uk_ipers < nitems)
3401 keg->uk_maxpages += keg->uk_ppera;
3402 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3410 uma_zone_get_max(uma_zone_t zone)
3415 keg = zone_first_keg(zone);
3419 nitems = (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers;
3427 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3431 zone->uz_warning = warning;
3437 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3441 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3447 uma_zone_get_cur(uma_zone_t zone)
3453 nitems = zone->uz_allocs - zone->uz_frees;
3456 * See the comment in sysctl_vm_zone_stats() regarding the
3457 * safety of accessing the per-cpu caches. With the zone lock
3458 * held, it is safe, but can potentially result in stale data.
3460 nitems += zone->uz_cpu[i].uc_allocs -
3461 zone->uz_cpu[i].uc_frees;
3465 return (nitems < 0 ? 0 : nitems);
3470 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3474 keg = zone_first_keg(zone);
3475 KASSERT(keg != NULL, ("uma_zone_set_init: Invalid zone type"));
3477 KASSERT(keg->uk_pages == 0,
3478 ("uma_zone_set_init on non-empty keg"));
3479 keg->uk_init = uminit;
3485 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3489 keg = zone_first_keg(zone);
3490 KASSERT(keg != NULL, ("uma_zone_set_fini: Invalid zone type"));
3492 KASSERT(keg->uk_pages == 0,
3493 ("uma_zone_set_fini on non-empty keg"));
3494 keg->uk_fini = fini;
3500 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3504 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3505 ("uma_zone_set_zinit on non-empty keg"));
3506 zone->uz_init = zinit;
3512 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3516 KASSERT(zone_first_keg(zone)->uk_pages == 0,
3517 ("uma_zone_set_zfini on non-empty keg"));
3518 zone->uz_fini = zfini;
3523 /* XXX uk_freef is not actually used with the zone locked */
3525 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3529 keg = zone_first_keg(zone);
3530 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3532 keg->uk_freef = freef;
3537 /* XXX uk_allocf is not actually used with the zone locked */
3539 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3543 keg = zone_first_keg(zone);
3545 keg->uk_allocf = allocf;
3551 uma_zone_reserve(uma_zone_t zone, int items)
3555 keg = zone_first_keg(zone);
3559 keg->uk_reserve = items;
3567 uma_zone_reserve_kva(uma_zone_t zone, int count)
3573 keg = zone_first_keg(zone);
3576 pages = count / keg->uk_ipers;
3578 if (pages * keg->uk_ipers < count)
3580 pages *= keg->uk_ppera;
3582 #ifdef UMA_MD_SMALL_ALLOC
3583 if (keg->uk_ppera > 1) {
3587 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3595 keg->uk_maxpages = pages;
3596 #ifdef UMA_MD_SMALL_ALLOC
3597 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3599 keg->uk_allocf = noobj_alloc;
3601 keg->uk_flags |= UMA_ZONE_NOFREE;
3609 uma_prealloc(uma_zone_t zone, int items)
3611 struct vm_domainset_iter di;
3615 int domain, flags, slabs;
3617 keg = zone_first_keg(zone);
3621 slabs = items / keg->uk_ipers;
3622 if (slabs * keg->uk_ipers < items)
3625 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain, &flags);
3626 while (slabs-- > 0) {
3627 slab = keg_alloc_slab(keg, zone, domain, flags);
3630 MPASS(slab->us_keg == keg);
3631 dom = &keg->uk_domain[slab->us_domain];
3632 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3633 if (vm_domainset_iter_policy(&di, &domain) != 0)
3641 uma_reclaim_locked(bool kmem_danger)
3644 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3645 sx_assert(&uma_drain_lock, SA_XLOCKED);
3647 zone_foreach(zone_drain);
3648 if (vm_page_count_min() || kmem_danger) {
3649 cache_drain_safe(NULL);
3650 zone_foreach(zone_drain);
3653 * Some slabs may have been freed but this zone will be visited early
3654 * we visit again so that we can free pages that are empty once other
3655 * zones are drained. We have to do the same for buckets.
3657 zone_drain(slabzone);
3658 bucket_zone_drain();
3665 sx_xlock(&uma_drain_lock);
3666 uma_reclaim_locked(false);
3667 sx_xunlock(&uma_drain_lock);
3670 static volatile int uma_reclaim_needed;
3673 uma_reclaim_wakeup(void)
3676 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3677 wakeup(uma_reclaim);
3681 uma_reclaim_worker(void *arg __unused)
3685 sx_xlock(&uma_drain_lock);
3686 while (atomic_load_int(&uma_reclaim_needed) == 0)
3687 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3689 sx_xunlock(&uma_drain_lock);
3690 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3691 sx_xlock(&uma_drain_lock);
3692 uma_reclaim_locked(true);
3693 atomic_store_int(&uma_reclaim_needed, 0);
3694 sx_xunlock(&uma_drain_lock);
3695 /* Don't fire more than once per-second. */
3696 pause("umarclslp", hz);
3702 uma_zone_exhausted(uma_zone_t zone)
3707 full = (zone->uz_flags & UMA_ZFLAG_FULL);
3713 uma_zone_exhausted_nolock(uma_zone_t zone)
3715 return (zone->uz_flags & UMA_ZFLAG_FULL);
3719 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3721 struct domainset *policy;
3725 if (domain != UMA_ANYDOMAIN) {
3726 /* avoid allocs targeting empty domains */
3727 if (VM_DOMAIN_EMPTY(domain))
3728 domain = UMA_ANYDOMAIN;
3730 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3733 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3734 DOMAINSET_FIXED(domain);
3735 addr = kmem_malloc_domainset(policy, size, wait);
3737 vsetslab(addr, slab);
3738 slab->us_data = (void *)addr;
3739 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3740 slab->us_size = size;
3741 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3742 pmap_kextract(addr)));
3743 uma_total_inc(size);
3745 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3748 return ((void *)addr);
3752 uma_large_malloc(vm_size_t size, int wait)
3755 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3759 uma_large_free(uma_slab_t slab)
3762 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3763 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3764 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3765 uma_total_dec(slab->us_size);
3766 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3770 uma_zero_item(void *item, uma_zone_t zone)
3773 bzero(item, zone->uz_size);
3780 return (uma_kmem_limit);
3784 uma_set_limit(unsigned long limit)
3787 uma_kmem_limit = limit;
3794 return (uma_kmem_total);
3801 return (uma_kmem_limit - uma_kmem_total);
3805 uma_print_stats(void)
3807 zone_foreach(uma_print_zone);
3811 slab_print(uma_slab_t slab)
3813 printf("slab: keg %p, data %p, freecount %d\n",
3814 slab->us_keg, slab->us_data, slab->us_freecount);
3818 cache_print(uma_cache_t cache)
3820 printf("alloc: %p(%d), free: %p(%d)\n",
3821 cache->uc_allocbucket,
3822 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3823 cache->uc_freebucket,
3824 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3828 uma_print_keg(uma_keg_t keg)
3834 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3835 "out %d free %d limit %d\n",
3836 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3837 keg->uk_ipers, keg->uk_ppera,
3838 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3839 keg->uk_free, (keg->uk_maxpages / keg->uk_ppera) * keg->uk_ipers);
3840 for (i = 0; i < vm_ndomains; i++) {
3841 dom = &keg->uk_domain[i];
3842 printf("Part slabs:\n");
3843 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3845 printf("Free slabs:\n");
3846 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3848 printf("Full slabs:\n");
3849 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3855 uma_print_zone(uma_zone_t zone)
3861 printf("zone: %s(%p) size %d flags %#x\n",
3862 zone->uz_name, zone, zone->uz_size, zone->uz_flags);
3863 LIST_FOREACH(kl, &zone->uz_kegs, kl_link)
3864 uma_print_keg(kl->kl_keg);
3866 cache = &zone->uz_cpu[i];
3867 printf("CPU %d Cache:\n", i);
3874 * Generate statistics across both the zone and its per-cpu cache's. Return
3875 * desired statistics if the pointer is non-NULL for that statistic.
3877 * Note: does not update the zone statistics, as it can't safely clear the
3878 * per-CPU cache statistic.
3880 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3881 * safe from off-CPU; we should modify the caches to track this information
3882 * directly so that we don't have to.
3885 uma_zone_sumstat(uma_zone_t z, int *cachefreep, uint64_t *allocsp,
3886 uint64_t *freesp, uint64_t *sleepsp)
3889 uint64_t allocs, frees, sleeps;
3892 allocs = frees = sleeps = 0;
3895 cache = &z->uz_cpu[cpu];
3896 if (cache->uc_allocbucket != NULL)
3897 cachefree += cache->uc_allocbucket->ub_cnt;
3898 if (cache->uc_freebucket != NULL)
3899 cachefree += cache->uc_freebucket->ub_cnt;
3900 allocs += cache->uc_allocs;
3901 frees += cache->uc_frees;
3903 allocs += z->uz_allocs;
3904 frees += z->uz_frees;
3905 sleeps += z->uz_sleeps;
3906 if (cachefreep != NULL)
3907 *cachefreep = cachefree;
3908 if (allocsp != NULL)
3912 if (sleepsp != NULL)
3918 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3925 rw_rlock(&uma_rwlock);
3926 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3927 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3930 rw_runlock(&uma_rwlock);
3931 return (sysctl_handle_int(oidp, &count, 0, req));
3935 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3937 struct uma_stream_header ush;
3938 struct uma_type_header uth;
3939 struct uma_percpu_stat *ups;
3940 uma_bucket_t bucket;
3941 uma_zone_domain_t zdom;
3948 int count, error, i;
3950 error = sysctl_wire_old_buffer(req, 0);
3953 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3954 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3955 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3958 rw_rlock(&uma_rwlock);
3959 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3960 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3965 * Insert stream header.
3967 bzero(&ush, sizeof(ush));
3968 ush.ush_version = UMA_STREAM_VERSION;
3969 ush.ush_maxcpus = (mp_maxid + 1);
3970 ush.ush_count = count;
3971 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3973 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3974 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3975 bzero(&uth, sizeof(uth));
3977 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3978 uth.uth_align = kz->uk_align;
3979 uth.uth_size = kz->uk_size;
3980 uth.uth_rsize = kz->uk_rsize;
3981 LIST_FOREACH(kl, &z->uz_kegs, kl_link) {
3983 uth.uth_maxpages += k->uk_maxpages;
3984 uth.uth_pages += k->uk_pages;
3985 uth.uth_keg_free += k->uk_free;
3986 uth.uth_limit = (k->uk_maxpages / k->uk_ppera)
3991 * A zone is secondary is it is not the first entry
3992 * on the keg's zone list.
3994 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3995 (LIST_FIRST(&kz->uk_zones) != z))
3996 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3998 for (i = 0; i < vm_ndomains; i++) {
3999 zdom = &z->uz_domain[i];
4000 LIST_FOREACH(bucket, &zdom->uzd_buckets,
4002 uth.uth_zone_free += bucket->ub_cnt;
4004 uth.uth_allocs = z->uz_allocs;
4005 uth.uth_frees = z->uz_frees;
4006 uth.uth_fails = z->uz_fails;
4007 uth.uth_sleeps = z->uz_sleeps;
4009 * While it is not normally safe to access the cache
4010 * bucket pointers while not on the CPU that owns the
4011 * cache, we only allow the pointers to be exchanged
4012 * without the zone lock held, not invalidated, so
4013 * accept the possible race associated with bucket
4014 * exchange during monitoring.
4016 for (i = 0; i < mp_maxid + 1; i++) {
4017 bzero(&ups[i], sizeof(*ups));
4018 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
4021 cache = &z->uz_cpu[i];
4022 if (cache->uc_allocbucket != NULL)
4023 ups[i].ups_cache_free +=
4024 cache->uc_allocbucket->ub_cnt;
4025 if (cache->uc_freebucket != NULL)
4026 ups[i].ups_cache_free +=
4027 cache->uc_freebucket->ub_cnt;
4028 ups[i].ups_allocs = cache->uc_allocs;
4029 ups[i].ups_frees = cache->uc_frees;
4032 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4033 for (i = 0; i < mp_maxid + 1; i++)
4034 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4037 rw_runlock(&uma_rwlock);
4038 error = sbuf_finish(&sbuf);
4045 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4047 uma_zone_t zone = *(uma_zone_t *)arg1;
4050 max = uma_zone_get_max(zone);
4051 error = sysctl_handle_int(oidp, &max, 0, req);
4052 if (error || !req->newptr)
4055 uma_zone_set_max(zone, max);
4061 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4063 uma_zone_t zone = *(uma_zone_t *)arg1;
4066 cur = uma_zone_get_cur(zone);
4067 return (sysctl_handle_int(oidp, &cur, 0, req));
4072 uma_dbg_getslab(uma_zone_t zone, void *item)
4078 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4079 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4080 slab = vtoslab((vm_offset_t)mem);
4083 * It is safe to return the slab here even though the
4084 * zone is unlocked because the item's allocation state
4085 * essentially holds a reference.
4088 keg = LIST_FIRST(&zone->uz_kegs)->kl_keg;
4089 if (keg->uk_flags & UMA_ZONE_HASH)
4090 slab = hash_sfind(&keg->uk_hash, mem);
4092 slab = (uma_slab_t)(mem + keg->uk_pgoff);
4100 uma_dbg_zskip(uma_zone_t zone, void *mem)
4104 if ((keg = zone_first_keg(zone)) == NULL)
4107 return (uma_dbg_kskip(keg, mem));
4111 uma_dbg_kskip(uma_keg_t keg, void *mem)
4115 if (dbg_divisor == 0)
4118 if (dbg_divisor == 1)
4121 idx = (uintptr_t)mem >> PAGE_SHIFT;
4122 if (keg->uk_ipers > 1) {
4123 idx *= keg->uk_ipers;
4124 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4127 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4128 counter_u64_add(uma_skip_cnt, 1);
4131 counter_u64_add(uma_dbg_cnt, 1);
4137 * Set up the slab's freei data such that uma_dbg_free can function.
4141 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4147 slab = uma_dbg_getslab(zone, item);
4149 panic("uma: item %p did not belong to zone %s\n",
4150 item, zone->uz_name);
4153 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4155 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4156 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4157 item, zone, zone->uz_name, slab, freei);
4158 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4164 * Verifies freed addresses. Checks for alignment, valid slab membership
4165 * and duplicate frees.
4169 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4175 slab = uma_dbg_getslab(zone, item);
4177 panic("uma: Freed item %p did not belong to zone %s\n",
4178 item, zone->uz_name);
4181 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4183 if (freei >= keg->uk_ipers)
4184 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4185 item, zone, zone->uz_name, slab, freei);
4187 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4188 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4189 item, zone, zone->uz_name, slab, freei);
4191 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4192 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4193 item, zone, zone->uz_name, slab, freei);
4195 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4197 #endif /* INVARIANTS */
4200 DB_SHOW_COMMAND(uma, db_show_uma)
4202 uma_bucket_t bucket;
4205 uma_zone_domain_t zdom;
4206 uint64_t allocs, frees, sleeps;
4209 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4210 "Free", "Requests", "Sleeps", "Bucket");
4211 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4212 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4213 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4214 allocs = z->uz_allocs;
4215 frees = z->uz_frees;
4216 sleeps = z->uz_sleeps;
4219 uma_zone_sumstat(z, &cachefree, &allocs,
4221 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4222 (LIST_FIRST(&kz->uk_zones) != z)))
4223 cachefree += kz->uk_free;
4224 for (i = 0; i < vm_ndomains; i++) {
4225 zdom = &z->uz_domain[i];
4226 LIST_FOREACH(bucket, &zdom->uzd_buckets,
4228 cachefree += bucket->ub_cnt;
4230 db_printf("%18s %8ju %8jd %8d %12ju %8ju %8u\n",
4231 z->uz_name, (uintmax_t)kz->uk_size,
4232 (intmax_t)(allocs - frees), cachefree,
4233 (uintmax_t)allocs, sleeps, z->uz_count);
4240 DB_SHOW_COMMAND(umacache, db_show_umacache)
4242 uma_bucket_t bucket;
4244 uma_zone_domain_t zdom;
4245 uint64_t allocs, frees;
4248 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4249 "Requests", "Bucket");
4250 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4251 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4252 for (i = 0; i < vm_ndomains; i++) {
4253 zdom = &z->uz_domain[i];
4254 LIST_FOREACH(bucket, &zdom->uzd_buckets, ub_link)
4255 cachefree += bucket->ub_cnt;
4257 db_printf("%18s %8ju %8jd %8d %12ju %8u\n",
4258 z->uz_name, (uintmax_t)z->uz_size,
4259 (intmax_t)(allocs - frees), cachefree,
4260 (uintmax_t)allocs, z->uz_count);