2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
5 * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6 * Copyright (c) 2004-2006 Robert N. M. Watson
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice unmodified, this list of conditions, and the following
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * uma_core.c Implementation of the Universal Memory allocator
34 * This allocator is intended to replace the multitude of similar object caches
35 * in the standard FreeBSD kernel. The intent is to be flexible as well as
36 * efficient. A primary design goal is to return unused memory to the rest of
37 * the system. This will make the system as a whole more flexible due to the
38 * ability to move memory to subsystems which most need it instead of leaving
39 * pools of reserved memory unused.
41 * The basic ideas stem from similar slab/zone based allocators whose algorithms
48 * - Improve memory usage for large allocations
49 * - Investigate cache size adjustments
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
56 #include "opt_param.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
77 #include <sys/sched.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
100 #include <vm/memguard.h>
104 * This is the zone and keg from which all zones are spawned.
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
113 * The initial hash tables come out of this zone so they can be allocated
114 * prior to malloc coming up.
116 static uma_zone_t hashzone;
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
124 * Are we allowed to allocate buckets?
126 static int bucketdisable = 1;
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133 LIST_HEAD_INITIALIZER(uma_cachezones);
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
139 * Pointer and counter to pool of pages, that is preallocated at
140 * startup to bootstrap UMA.
142 static char *bootmem;
143 static int boot_pages;
145 static struct sx uma_drain_lock;
147 /* kmem soft limit. */
148 static unsigned long uma_kmem_limit = LONG_MAX;
149 static volatile unsigned long uma_kmem_total;
151 /* Is the VM done starting up? */
152 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
153 BOOT_RUNNING } booted = BOOT_COLD;
156 * This is the handle used to schedule events that need to happen
157 * outside of the allocation fast path.
159 static struct callout uma_callout;
160 #define UMA_TIMEOUT 20 /* Seconds for callout interval. */
163 * This structure is passed as the zone ctor arg so that I don't have to create
164 * a special allocation function just for zones.
166 struct uma_zctor_args {
181 struct uma_kctor_args {
190 struct uma_bucket_zone {
193 int ubz_entries; /* Number of items it can hold. */
194 int ubz_maxsize; /* Maximum allocation size per-item. */
198 * Compute the actual number of bucket entries to pack them in power
199 * of two sizes for more efficient space utilization.
201 #define BUCKET_SIZE(n) \
202 (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
204 #define BUCKET_MAX BUCKET_SIZE(256)
206 struct uma_bucket_zone bucket_zones[] = {
207 { NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
208 { NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
209 { NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
210 { NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
211 { NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
212 { NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
213 { NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
214 { NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
215 { NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
220 * Flags and enumerations to be passed to internal functions.
224 SKIP_CNT = 0x00000001,
225 SKIP_DTOR = 0x00010000,
226 SKIP_FINI = 0x00020000,
229 #define UMA_ANYDOMAIN -1 /* Special value for domain search. */
233 int uma_startup_count(int);
234 void uma_startup(void *, int);
235 void uma_startup1(void);
236 void uma_startup2(void);
238 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
239 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
240 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
241 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
242 static void page_free(void *, vm_size_t, uint8_t);
243 static void pcpu_page_free(void *, vm_size_t, uint8_t);
244 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int);
245 static void cache_drain(uma_zone_t);
246 static void bucket_drain(uma_zone_t, uma_bucket_t);
247 static void bucket_cache_drain(uma_zone_t zone);
248 static int keg_ctor(void *, int, void *, int);
249 static void keg_dtor(void *, int, void *);
250 static int zone_ctor(void *, int, void *, int);
251 static void zone_dtor(void *, int, void *);
252 static int zero_init(void *, int, int);
253 static void keg_small_init(uma_keg_t keg);
254 static void keg_large_init(uma_keg_t keg);
255 static void zone_foreach(void (*zfunc)(uma_zone_t));
256 static void zone_timeout(uma_zone_t zone);
257 static int hash_alloc(struct uma_hash *);
258 static int hash_expand(struct uma_hash *, struct uma_hash *);
259 static void hash_free(struct uma_hash *hash);
260 static void uma_timeout(void *);
261 static void uma_startup3(void);
262 static void *zone_alloc_item(uma_zone_t, void *, int, int);
263 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
264 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
265 static void bucket_enable(void);
266 static void bucket_init(void);
267 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
268 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
269 static void bucket_zone_drain(void);
270 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
271 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
272 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
273 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
274 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
275 uma_fini fini, int align, uint32_t flags);
276 static int zone_import(uma_zone_t, void **, int, int, int);
277 static void zone_release(uma_zone_t, void **, int);
278 static void uma_zero_item(void *, uma_zone_t);
280 void uma_print_zone(uma_zone_t);
281 void uma_print_stats(void);
282 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
283 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
286 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
287 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
288 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
289 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
291 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
292 "Memory allocation debugging");
294 static u_int dbg_divisor = 1;
295 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
296 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
297 "Debug & thrash every this item in memory allocator");
299 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
300 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
301 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
302 &uma_dbg_cnt, "memory items debugged");
303 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
304 &uma_skip_cnt, "memory items skipped, not debugged");
307 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
309 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
310 0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
312 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
313 0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
315 static int zone_warnings = 1;
316 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
317 "Warn when UMA zones becomes full");
319 /* Adjust bytes under management by UMA. */
321 uma_total_dec(unsigned long size)
324 atomic_subtract_long(&uma_kmem_total, size);
328 uma_total_inc(unsigned long size)
331 if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
332 uma_reclaim_wakeup();
336 * This routine checks to see whether or not it's safe to enable buckets.
341 bucketdisable = vm_page_count_min();
345 * Initialize bucket_zones, the array of zones of buckets of various sizes.
347 * For each zone, calculate the memory required for each bucket, consisting
348 * of the header and an array of pointers.
353 struct uma_bucket_zone *ubz;
356 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
357 size = roundup(sizeof(struct uma_bucket), sizeof(void *));
358 size += sizeof(void *) * ubz->ubz_entries;
359 ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
360 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
361 UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
366 * Given a desired number of entries for a bucket, return the zone from which
367 * to allocate the bucket.
369 static struct uma_bucket_zone *
370 bucket_zone_lookup(int entries)
372 struct uma_bucket_zone *ubz;
374 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
375 if (ubz->ubz_entries >= entries)
382 bucket_select(int size)
384 struct uma_bucket_zone *ubz;
386 ubz = &bucket_zones[0];
387 if (size > ubz->ubz_maxsize)
388 return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
390 for (; ubz->ubz_entries != 0; ubz++)
391 if (ubz->ubz_maxsize < size)
394 return (ubz->ubz_entries);
398 bucket_alloc(uma_zone_t zone, void *udata, int flags)
400 struct uma_bucket_zone *ubz;
404 * This is to stop us from allocating per cpu buckets while we're
405 * running out of vm.boot_pages. Otherwise, we would exhaust the
406 * boot pages. This also prevents us from allocating buckets in
407 * low memory situations.
412 * To limit bucket recursion we store the original zone flags
413 * in a cookie passed via zalloc_arg/zfree_arg. This allows the
414 * NOVM flag to persist even through deep recursions. We also
415 * store ZFLAG_BUCKET once we have recursed attempting to allocate
416 * a bucket for a bucket zone so we do not allow infinite bucket
417 * recursion. This cookie will even persist to frees of unused
418 * buckets via the allocation path or bucket allocations in the
421 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
422 udata = (void *)(uintptr_t)zone->uz_flags;
424 if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
426 udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
428 if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
430 ubz = bucket_zone_lookup(zone->uz_count);
431 if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
433 bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
436 bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
439 bucket->ub_entries = ubz->ubz_entries;
446 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
448 struct uma_bucket_zone *ubz;
450 KASSERT(bucket->ub_cnt == 0,
451 ("bucket_free: Freeing a non free bucket."));
452 if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
453 udata = (void *)(uintptr_t)zone->uz_flags;
454 ubz = bucket_zone_lookup(bucket->ub_entries);
455 uma_zfree_arg(ubz->ubz_zone, bucket, udata);
459 bucket_zone_drain(void)
461 struct uma_bucket_zone *ubz;
463 for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
464 zone_drain(ubz->ubz_zone);
468 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
472 ZONE_LOCK_ASSERT(zone);
474 if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
475 MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
476 LIST_REMOVE(bucket, ub_link);
477 zdom->uzd_nitems -= bucket->ub_cnt;
478 if (ws && zdom->uzd_imin > zdom->uzd_nitems)
479 zdom->uzd_imin = zdom->uzd_nitems;
480 zone->uz_bkt_count -= bucket->ub_cnt;
486 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
490 ZONE_LOCK_ASSERT(zone);
491 KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
494 LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
495 zdom->uzd_nitems += bucket->ub_cnt;
496 if (ws && zdom->uzd_imax < zdom->uzd_nitems)
497 zdom->uzd_imax = zdom->uzd_nitems;
498 zone->uz_bkt_count += bucket->ub_cnt;
502 zone_log_warning(uma_zone_t zone)
504 static const struct timeval warninterval = { 300, 0 };
506 if (!zone_warnings || zone->uz_warning == NULL)
509 if (ratecheck(&zone->uz_ratecheck, &warninterval))
510 printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
514 zone_maxaction(uma_zone_t zone)
517 if (zone->uz_maxaction.ta_func != NULL)
518 taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
522 * Routine called by timeout which is used to fire off some time interval
523 * based calculations. (stats, hash size, etc.)
532 uma_timeout(void *unused)
535 zone_foreach(zone_timeout);
537 /* Reschedule this event */
538 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
542 * Update the working set size estimate for the zone's bucket cache.
543 * The constants chosen here are somewhat arbitrary. With an update period of
544 * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
548 zone_domain_update_wss(uma_zone_domain_t zdom)
552 MPASS(zdom->uzd_imax >= zdom->uzd_imin);
553 wss = zdom->uzd_imax - zdom->uzd_imin;
554 zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
555 zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
559 * Routine to perform timeout driven calculations. This expands the
560 * hashes and does per cpu statistics aggregation.
565 zone_timeout(uma_zone_t zone)
567 uma_keg_t keg = zone->uz_keg;
571 * Expand the keg hash table.
573 * This is done if the number of slabs is larger than the hash size.
574 * What I'm trying to do here is completely reduce collisions. This
575 * may be a little aggressive. Should I allow for two collisions max?
577 if (keg->uk_flags & UMA_ZONE_HASH &&
578 keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
579 struct uma_hash newhash;
580 struct uma_hash oldhash;
584 * This is so involved because allocating and freeing
585 * while the keg lock is held will lead to deadlock.
586 * I have to do everything in stages and check for
589 newhash = keg->uk_hash;
591 ret = hash_alloc(&newhash);
594 if (hash_expand(&keg->uk_hash, &newhash)) {
595 oldhash = keg->uk_hash;
596 keg->uk_hash = newhash;
606 for (int i = 0; i < vm_ndomains; i++)
607 zone_domain_update_wss(&zone->uz_domain[i]);
613 * Allocate and zero fill the next sized hash table from the appropriate
617 * hash A new hash structure with the old hash size in uh_hashsize
620 * 1 on success and 0 on failure.
623 hash_alloc(struct uma_hash *hash)
628 oldsize = hash->uh_hashsize;
630 /* We're just going to go to a power of two greater */
632 hash->uh_hashsize = oldsize * 2;
633 alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
634 hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
635 M_UMAHASH, M_NOWAIT);
637 alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
638 hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
639 UMA_ANYDOMAIN, M_WAITOK);
640 hash->uh_hashsize = UMA_HASH_SIZE_INIT;
642 if (hash->uh_slab_hash) {
643 bzero(hash->uh_slab_hash, alloc);
644 hash->uh_hashmask = hash->uh_hashsize - 1;
652 * Expands the hash table for HASH zones. This is done from zone_timeout
653 * to reduce collisions. This must not be done in the regular allocation
654 * path, otherwise, we can recurse on the vm while allocating pages.
657 * oldhash The hash you want to expand
658 * newhash The hash structure for the new table
666 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
672 if (!newhash->uh_slab_hash)
675 if (oldhash->uh_hashsize >= newhash->uh_hashsize)
679 * I need to investigate hash algorithms for resizing without a
683 for (i = 0; i < oldhash->uh_hashsize; i++)
684 while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
685 slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
686 SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
687 hval = UMA_HASH(newhash, slab->us_data);
688 SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
696 * Free the hash bucket to the appropriate backing store.
699 * slab_hash The hash bucket we're freeing
700 * hashsize The number of entries in that hash bucket
706 hash_free(struct uma_hash *hash)
708 if (hash->uh_slab_hash == NULL)
710 if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
711 zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
713 free(hash->uh_slab_hash, M_UMAHASH);
717 * Frees all outstanding items in a bucket
720 * zone The zone to free to, must be unlocked.
721 * bucket The free/alloc bucket with items, cpu queue must be locked.
728 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
736 for (i = 0; i < bucket->ub_cnt; i++)
737 zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
738 zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
740 zone->uz_items -= bucket->ub_cnt;
741 if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
748 * Drains the per cpu caches for a zone.
750 * NOTE: This may only be called while the zone is being turn down, and not
751 * during normal operation. This is necessary in order that we do not have
752 * to migrate CPUs to drain the per-CPU caches.
755 * zone The zone to drain, must be unlocked.
761 cache_drain(uma_zone_t zone)
767 * XXX: It is safe to not lock the per-CPU caches, because we're
768 * tearing down the zone anyway. I.e., there will be no further use
769 * of the caches at this point.
771 * XXX: It would good to be able to assert that the zone is being
772 * torn down to prevent improper use of cache_drain().
774 * XXX: We lock the zone before passing into bucket_cache_drain() as
775 * it is used elsewhere. Should the tear-down path be made special
776 * there in some form?
779 cache = &zone->uz_cpu[cpu];
780 bucket_drain(zone, cache->uc_allocbucket);
781 bucket_drain(zone, cache->uc_freebucket);
782 if (cache->uc_allocbucket != NULL)
783 bucket_free(zone, cache->uc_allocbucket, NULL);
784 if (cache->uc_freebucket != NULL)
785 bucket_free(zone, cache->uc_freebucket, NULL);
786 cache->uc_allocbucket = cache->uc_freebucket = NULL;
789 bucket_cache_drain(zone);
794 cache_shrink(uma_zone_t zone)
797 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
801 zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
806 cache_drain_safe_cpu(uma_zone_t zone)
812 if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
818 if (zone->uz_flags & UMA_ZONE_NUMA)
819 domain = PCPU_GET(domain);
822 cache = &zone->uz_cpu[curcpu];
823 if (cache->uc_allocbucket) {
824 if (cache->uc_allocbucket->ub_cnt != 0)
825 zone_put_bucket(zone, &zone->uz_domain[domain],
826 cache->uc_allocbucket, false);
828 b1 = cache->uc_allocbucket;
829 cache->uc_allocbucket = NULL;
831 if (cache->uc_freebucket) {
832 if (cache->uc_freebucket->ub_cnt != 0)
833 zone_put_bucket(zone, &zone->uz_domain[domain],
834 cache->uc_freebucket, false);
836 b2 = cache->uc_freebucket;
837 cache->uc_freebucket = NULL;
842 bucket_free(zone, b1, NULL);
844 bucket_free(zone, b2, NULL);
848 * Safely drain per-CPU caches of a zone(s) to alloc bucket.
849 * This is an expensive call because it needs to bind to all CPUs
850 * one by one and enter a critical section on each of them in order
851 * to safely access their cache buckets.
852 * Zone lock must not be held on call this function.
855 cache_drain_safe(uma_zone_t zone)
860 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
865 zone_foreach(cache_shrink);
868 thread_lock(curthread);
869 sched_bind(curthread, cpu);
870 thread_unlock(curthread);
873 cache_drain_safe_cpu(zone);
875 zone_foreach(cache_drain_safe_cpu);
877 thread_lock(curthread);
878 sched_unbind(curthread);
879 thread_unlock(curthread);
883 * Drain the cached buckets from a zone. Expects a locked zone on entry.
886 bucket_cache_drain(uma_zone_t zone)
888 uma_zone_domain_t zdom;
893 * Drain the bucket queues and free the buckets.
895 for (i = 0; i < vm_ndomains; i++) {
896 zdom = &zone->uz_domain[i];
897 while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
900 bucket_drain(zone, bucket);
901 bucket_free(zone, bucket, NULL);
907 * Shrink further bucket sizes. Price of single zone lock collision
908 * is probably lower then price of global cache drain.
910 if (zone->uz_count > zone->uz_count_min)
915 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
921 CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
922 keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
925 flags = slab->us_flags;
927 if (keg->uk_fini != NULL) {
928 for (i--; i > -1; i--)
931 * trash_fini implies that dtor was trash_dtor. trash_fini
932 * would check that memory hasn't been modified since free,
933 * which executed trash_dtor.
934 * That's why we need to run uma_dbg_kskip() check here,
935 * albeit we don't make skip check for other init/fini
938 if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
939 keg->uk_fini != trash_fini)
941 keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
944 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
945 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
946 keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
947 uma_total_dec(PAGE_SIZE * keg->uk_ppera);
951 * Frees pages from a keg back to the system. This is done on demand from
952 * the pageout daemon.
957 keg_drain(uma_keg_t keg)
959 struct slabhead freeslabs = { 0 };
961 uma_slab_t slab, tmp;
965 * We don't want to take pages from statically allocated kegs at this
968 if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
971 CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
972 keg->uk_name, keg, keg->uk_free);
974 if (keg->uk_free == 0)
977 for (i = 0; i < vm_ndomains; i++) {
978 dom = &keg->uk_domain[i];
979 LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
980 /* We have nowhere to free these to. */
981 if (slab->us_flags & UMA_SLAB_BOOT)
984 LIST_REMOVE(slab, us_link);
985 keg->uk_pages -= keg->uk_ppera;
986 keg->uk_free -= keg->uk_ipers;
988 if (keg->uk_flags & UMA_ZONE_HASH)
989 UMA_HASH_REMOVE(&keg->uk_hash, slab,
992 SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
999 while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1000 SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1001 keg_free_slab(keg, slab, keg->uk_ipers);
1006 zone_drain_wait(uma_zone_t zone, int waitok)
1010 * Set draining to interlock with zone_dtor() so we can release our
1011 * locks as we go. Only dtor() should do a WAITOK call since it
1012 * is the only call that knows the structure will still be available
1016 while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1017 if (waitok == M_NOWAIT)
1019 msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1021 zone->uz_flags |= UMA_ZFLAG_DRAINING;
1022 bucket_cache_drain(zone);
1025 * The DRAINING flag protects us from being freed while
1026 * we're running. Normally the uma_rwlock would protect us but we
1027 * must be able to release and acquire the right lock for each keg.
1029 keg_drain(zone->uz_keg);
1031 zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1038 zone_drain(uma_zone_t zone)
1041 zone_drain_wait(zone, M_NOWAIT);
1045 * Allocate a new slab for a keg. This does not insert the slab onto a list.
1046 * If the allocation was successful, the keg lock will be held upon return,
1047 * otherwise the keg will be left unlocked.
1050 * wait Shall we wait?
1053 * The slab that was allocated or NULL if there is no memory and the
1054 * caller specified M_NOWAIT.
1057 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int wait)
1066 KASSERT(domain >= 0 && domain < vm_ndomains,
1067 ("keg_alloc_slab: domain %d out of range", domain));
1068 KEG_LOCK_ASSERT(keg);
1069 MPASS(zone->uz_lockptr == &keg->uk_lock);
1071 allocf = keg->uk_allocf;
1076 if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1077 slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, wait);
1083 * This reproduces the old vm_zone behavior of zero filling pages the
1084 * first time they are added to a zone.
1086 * Malloced items are zeroed in uma_zalloc.
1089 if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1094 if (keg->uk_flags & UMA_ZONE_NODUMP)
1097 /* zone is passed for legacy reasons. */
1098 size = keg->uk_ppera * PAGE_SIZE;
1099 mem = allocf(zone, size, domain, &flags, wait);
1101 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1102 zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1106 uma_total_inc(size);
1108 /* Point the slab into the allocated memory */
1109 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1110 slab = (uma_slab_t )(mem + keg->uk_pgoff);
1112 if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1113 for (i = 0; i < keg->uk_ppera; i++)
1114 vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1117 slab->us_data = mem;
1118 slab->us_freecount = keg->uk_ipers;
1119 slab->us_flags = flags;
1120 slab->us_domain = domain;
1121 BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1123 BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1126 if (keg->uk_init != NULL) {
1127 for (i = 0; i < keg->uk_ipers; i++)
1128 if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1129 keg->uk_size, wait) != 0)
1131 if (i != keg->uk_ipers) {
1132 keg_free_slab(keg, slab, i);
1139 CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1140 slab, keg->uk_name, keg);
1142 if (keg->uk_flags & UMA_ZONE_HASH)
1143 UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1145 keg->uk_pages += keg->uk_ppera;
1146 keg->uk_free += keg->uk_ipers;
1153 * This function is intended to be used early on in place of page_alloc() so
1154 * that we may use the boot time page cache to satisfy allocations before
1158 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1167 * If we are in BOOT_BUCKETS or higher, than switch to real
1168 * allocator. Zones with page sized slabs switch at BOOT_PAGEALLOC.
1174 case BOOT_PAGEALLOC:
1175 if (keg->uk_ppera > 1)
1179 #ifdef UMA_MD_SMALL_ALLOC
1180 keg->uk_allocf = (keg->uk_ppera > 1) ?
1181 page_alloc : uma_small_alloc;
1183 keg->uk_allocf = page_alloc;
1185 return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1189 * Check our small startup cache to see if it has pages remaining.
1191 pages = howmany(bytes, PAGE_SIZE);
1192 KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1193 if (pages > boot_pages)
1194 panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1196 printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1200 boot_pages -= pages;
1201 bootmem += pages * PAGE_SIZE;
1202 *pflag = UMA_SLAB_BOOT;
1208 * Allocates a number of pages from the system
1211 * bytes The number of bytes requested
1212 * wait Shall we wait?
1215 * A pointer to the alloced memory or possibly
1216 * NULL if M_NOWAIT is set.
1219 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1222 void *p; /* Returned page */
1224 *pflag = UMA_SLAB_KERNEL;
1225 p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1231 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1234 struct pglist alloctail;
1235 vm_offset_t addr, zkva;
1237 vm_page_t p, p_next;
1242 MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1244 TAILQ_INIT(&alloctail);
1245 flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1246 malloc2vm_flags(wait);
1247 *pflag = UMA_SLAB_KERNEL;
1248 for (cpu = 0; cpu <= mp_maxid; cpu++) {
1249 if (CPU_ABSENT(cpu)) {
1250 p = vm_page_alloc(NULL, 0, flags);
1253 p = vm_page_alloc(NULL, 0, flags);
1255 pc = pcpu_find(cpu);
1256 p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1257 if (__predict_false(p == NULL))
1258 p = vm_page_alloc(NULL, 0, flags);
1261 if (__predict_false(p == NULL))
1263 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1265 if ((addr = kva_alloc(bytes)) == 0)
1268 TAILQ_FOREACH(p, &alloctail, listq) {
1269 pmap_qenter(zkva, &p, 1);
1272 return ((void*)addr);
1274 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1275 vm_page_unwire(p, PQ_NONE);
1282 * Allocates a number of pages from within an object
1285 * bytes The number of bytes requested
1286 * wait Shall we wait?
1289 * A pointer to the alloced memory or possibly
1290 * NULL if M_NOWAIT is set.
1293 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1296 TAILQ_HEAD(, vm_page) alloctail;
1298 vm_offset_t retkva, zkva;
1299 vm_page_t p, p_next;
1302 TAILQ_INIT(&alloctail);
1305 npages = howmany(bytes, PAGE_SIZE);
1306 while (npages > 0) {
1307 p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1308 VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1309 ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1313 * Since the page does not belong to an object, its
1316 TAILQ_INSERT_TAIL(&alloctail, p, listq);
1321 * Page allocation failed, free intermediate pages and
1324 TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1325 vm_page_unwire(p, PQ_NONE);
1330 *flags = UMA_SLAB_PRIV;
1331 zkva = keg->uk_kva +
1332 atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1334 TAILQ_FOREACH(p, &alloctail, listq) {
1335 pmap_qenter(zkva, &p, 1);
1339 return ((void *)retkva);
1343 * Frees a number of pages to the system
1346 * mem A pointer to the memory to be freed
1347 * size The size of the memory being freed
1348 * flags The original p->us_flags field
1354 page_free(void *mem, vm_size_t size, uint8_t flags)
1357 if ((flags & UMA_SLAB_KERNEL) == 0)
1358 panic("UMA: page_free used with invalid flags %x", flags);
1360 kmem_free((vm_offset_t)mem, size);
1364 * Frees pcpu zone allocations
1367 * mem A pointer to the memory to be freed
1368 * size The size of the memory being freed
1369 * flags The original p->us_flags field
1375 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1377 vm_offset_t sva, curva;
1381 MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1382 sva = (vm_offset_t)mem;
1383 for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1384 paddr = pmap_kextract(curva);
1385 m = PHYS_TO_VM_PAGE(paddr);
1386 vm_page_unwire(m, PQ_NONE);
1389 pmap_qremove(sva, size >> PAGE_SHIFT);
1390 kva_free(sva, size);
1395 * Zero fill initializer
1397 * Arguments/Returns follow uma_init specifications
1400 zero_init(void *mem, int size, int flags)
1407 * Finish creating a small uma keg. This calculates ipers, and the keg size.
1410 * keg The zone we should initialize
1416 keg_small_init(uma_keg_t keg)
1424 if (keg->uk_flags & UMA_ZONE_PCPU) {
1425 u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1427 slabsize = UMA_PCPU_ALLOC_SIZE;
1428 keg->uk_ppera = ncpus;
1430 slabsize = UMA_SLAB_SIZE;
1435 * Calculate the size of each allocation (rsize) according to
1436 * alignment. If the requested size is smaller than we have
1437 * allocation bits for we round it up.
1439 rsize = keg->uk_size;
1440 if (rsize < slabsize / SLAB_SETSIZE)
1441 rsize = slabsize / SLAB_SETSIZE;
1442 if (rsize & keg->uk_align)
1443 rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1444 keg->uk_rsize = rsize;
1446 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1447 keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1448 ("%s: size %u too large", __func__, keg->uk_rsize));
1450 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1453 shsize = SIZEOF_UMA_SLAB;
1455 if (rsize <= slabsize - shsize)
1456 keg->uk_ipers = (slabsize - shsize) / rsize;
1458 /* Handle special case when we have 1 item per slab, so
1459 * alignment requirement can be relaxed. */
1460 KASSERT(keg->uk_size <= slabsize - shsize,
1461 ("%s: size %u greater than slab", __func__, keg->uk_size));
1464 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1465 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1467 memused = keg->uk_ipers * rsize + shsize;
1468 wastedspace = slabsize - memused;
1471 * We can't do OFFPAGE if we're internal or if we've been
1472 * asked to not go to the VM for buckets. If we do this we
1473 * may end up going to the VM for slabs which we do not
1474 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1475 * of UMA_ZONE_VM, which clearly forbids it.
1477 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1478 (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1482 * See if using an OFFPAGE slab will limit our waste. Only do
1483 * this if it permits more items per-slab.
1485 * XXX We could try growing slabsize to limit max waste as well.
1486 * Historically this was not done because the VM could not
1487 * efficiently handle contiguous allocations.
1489 if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1490 (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1491 keg->uk_ipers = slabsize / keg->uk_rsize;
1492 KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1493 ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1494 CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1495 "keg: %s(%p), calculated wastedspace = %d, "
1496 "maximum wasted space allowed = %d, "
1497 "calculated ipers = %d, "
1498 "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1499 slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1500 slabsize - keg->uk_ipers * keg->uk_rsize);
1501 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1504 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1505 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1506 keg->uk_flags |= UMA_ZONE_HASH;
1510 * Finish creating a large (> UMA_SLAB_SIZE) uma kegs. Just give in and do
1511 * OFFPAGE for now. When I can allow for more dynamic slab sizes this will be
1515 * keg The keg we should initialize
1521 keg_large_init(uma_keg_t keg)
1524 KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1525 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1526 ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1528 keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1530 keg->uk_rsize = keg->uk_size;
1532 /* Check whether we have enough space to not do OFFPAGE. */
1533 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1534 PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1536 * We can't do OFFPAGE if we're internal, in which case
1537 * we need an extra page per allocation to contain the
1540 if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1541 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1546 if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1547 (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1548 keg->uk_flags |= UMA_ZONE_HASH;
1552 keg_cachespread_init(uma_keg_t keg)
1559 KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1560 ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1562 alignsize = keg->uk_align + 1;
1563 rsize = keg->uk_size;
1565 * We want one item to start on every align boundary in a page. To
1566 * do this we will span pages. We will also extend the item by the
1567 * size of align if it is an even multiple of align. Otherwise, it
1568 * would fall on the same boundary every time.
1570 if (rsize & keg->uk_align)
1571 rsize = (rsize & ~keg->uk_align) + alignsize;
1572 if ((rsize & alignsize) == 0)
1574 trailer = rsize - keg->uk_size;
1575 pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1576 pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1577 keg->uk_rsize = rsize;
1578 keg->uk_ppera = pages;
1579 keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1580 keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1581 KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1582 ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1587 * Keg header ctor. This initializes all fields, locks, etc. And inserts
1588 * the keg onto the global keg list.
1590 * Arguments/Returns follow uma_ctor specifications
1591 * udata Actually uma_kctor_args
1594 keg_ctor(void *mem, int size, void *udata, int flags)
1596 struct uma_kctor_args *arg = udata;
1597 uma_keg_t keg = mem;
1601 keg->uk_size = arg->size;
1602 keg->uk_init = arg->uminit;
1603 keg->uk_fini = arg->fini;
1604 keg->uk_align = arg->align;
1606 keg->uk_reserve = 0;
1608 keg->uk_flags = arg->flags;
1609 keg->uk_slabzone = NULL;
1612 * We use a global round-robin policy by default. Zones with
1613 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1614 * iterator is never run.
1616 keg->uk_dr.dr_policy = DOMAINSET_RR();
1617 keg->uk_dr.dr_iter = 0;
1620 * The master zone is passed to us at keg-creation time.
1623 keg->uk_name = zone->uz_name;
1625 if (arg->flags & UMA_ZONE_VM)
1626 keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1628 if (arg->flags & UMA_ZONE_ZINIT)
1629 keg->uk_init = zero_init;
1631 if (arg->flags & UMA_ZONE_MALLOC)
1632 keg->uk_flags |= UMA_ZONE_VTOSLAB;
1634 if (arg->flags & UMA_ZONE_PCPU)
1636 keg->uk_flags |= UMA_ZONE_OFFPAGE;
1638 keg->uk_flags &= ~UMA_ZONE_PCPU;
1641 if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1642 keg_cachespread_init(keg);
1644 if (keg->uk_size > UMA_SLAB_SPACE)
1645 keg_large_init(keg);
1647 keg_small_init(keg);
1650 if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1651 keg->uk_slabzone = slabzone;
1654 * If we haven't booted yet we need allocations to go through the
1655 * startup cache until the vm is ready.
1657 if (booted < BOOT_PAGEALLOC)
1658 keg->uk_allocf = startup_alloc;
1659 #ifdef UMA_MD_SMALL_ALLOC
1660 else if (keg->uk_ppera == 1)
1661 keg->uk_allocf = uma_small_alloc;
1663 else if (keg->uk_flags & UMA_ZONE_PCPU)
1664 keg->uk_allocf = pcpu_page_alloc;
1666 keg->uk_allocf = page_alloc;
1667 #ifdef UMA_MD_SMALL_ALLOC
1668 if (keg->uk_ppera == 1)
1669 keg->uk_freef = uma_small_free;
1672 if (keg->uk_flags & UMA_ZONE_PCPU)
1673 keg->uk_freef = pcpu_page_free;
1675 keg->uk_freef = page_free;
1678 * Initialize keg's lock
1680 KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1683 * If we're putting the slab header in the actual page we need to
1684 * figure out where in each page it goes. See SIZEOF_UMA_SLAB
1687 if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1688 keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1690 * The only way the following is possible is if with our
1691 * UMA_ALIGN_PTR adjustments we are now bigger than
1692 * UMA_SLAB_SIZE. I haven't checked whether this is
1693 * mathematically possible for all cases, so we make
1696 KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1697 PAGE_SIZE * keg->uk_ppera,
1698 ("zone %s ipers %d rsize %d size %d slab won't fit",
1699 zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1702 if (keg->uk_flags & UMA_ZONE_HASH)
1703 hash_alloc(&keg->uk_hash);
1705 CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1706 keg, zone->uz_name, zone,
1707 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1710 LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1712 rw_wlock(&uma_rwlock);
1713 LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1714 rw_wunlock(&uma_rwlock);
1719 * Zone header ctor. This initializes all fields, locks, etc.
1721 * Arguments/Returns follow uma_ctor specifications
1722 * udata Actually uma_zctor_args
1725 zone_ctor(void *mem, int size, void *udata, int flags)
1727 struct uma_zctor_args *arg = udata;
1728 uma_zone_t zone = mem;
1733 zone->uz_name = arg->name;
1734 zone->uz_ctor = arg->ctor;
1735 zone->uz_dtor = arg->dtor;
1736 zone->uz_slab = zone_fetch_slab;
1737 zone->uz_init = NULL;
1738 zone->uz_fini = NULL;
1739 zone->uz_allocs = 0;
1742 zone->uz_sleeps = 0;
1744 zone->uz_count_min = 0;
1745 zone->uz_count_max = BUCKET_MAX;
1747 zone->uz_warning = NULL;
1748 /* The domain structures follow the cpu structures. */
1749 zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1750 zone->uz_bkt_max = ULONG_MAX;
1751 timevalclear(&zone->uz_ratecheck);
1754 * This is a pure cache zone, no kegs.
1757 if (arg->flags & UMA_ZONE_VM)
1758 arg->flags |= UMA_ZFLAG_CACHEONLY;
1759 zone->uz_flags = arg->flags;
1760 zone->uz_size = arg->size;
1761 zone->uz_import = arg->import;
1762 zone->uz_release = arg->release;
1763 zone->uz_arg = arg->arg;
1764 zone->uz_lockptr = &zone->uz_lock;
1765 ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1766 rw_wlock(&uma_rwlock);
1767 LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1768 rw_wunlock(&uma_rwlock);
1773 * Use the regular zone/keg/slab allocator.
1775 zone->uz_import = (uma_import)zone_import;
1776 zone->uz_release = (uma_release)zone_release;
1777 zone->uz_arg = zone;
1780 if (arg->flags & UMA_ZONE_SECONDARY) {
1781 KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1782 zone->uz_init = arg->uminit;
1783 zone->uz_fini = arg->fini;
1784 zone->uz_lockptr = &keg->uk_lock;
1785 zone->uz_flags |= UMA_ZONE_SECONDARY;
1786 rw_wlock(&uma_rwlock);
1788 LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1789 if (LIST_NEXT(z, uz_link) == NULL) {
1790 LIST_INSERT_AFTER(z, zone, uz_link);
1795 rw_wunlock(&uma_rwlock);
1796 } else if (keg == NULL) {
1797 if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1798 arg->align, arg->flags)) == NULL)
1801 struct uma_kctor_args karg;
1804 /* We should only be here from uma_startup() */
1805 karg.size = arg->size;
1806 karg.uminit = arg->uminit;
1807 karg.fini = arg->fini;
1808 karg.align = arg->align;
1809 karg.flags = arg->flags;
1811 error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1818 zone->uz_size = keg->uk_size;
1819 zone->uz_flags |= (keg->uk_flags &
1820 (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1823 * Some internal zones don't have room allocated for the per cpu
1824 * caches. If we're internal, bail out here.
1826 if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1827 KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1828 ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1833 KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1834 (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1835 ("Invalid zone flag combination"));
1836 if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1837 zone->uz_count = BUCKET_MAX;
1838 else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1841 zone->uz_count = bucket_select(zone->uz_size);
1842 zone->uz_count_min = zone->uz_count;
1848 * Keg header dtor. This frees all data, destroys locks, frees the hash
1849 * table and removes the keg from the global list.
1851 * Arguments/Returns follow uma_dtor specifications
1855 keg_dtor(void *arg, int size, void *udata)
1859 keg = (uma_keg_t)arg;
1861 if (keg->uk_free != 0) {
1862 printf("Freed UMA keg (%s) was not empty (%d items). "
1863 " Lost %d pages of memory.\n",
1864 keg->uk_name ? keg->uk_name : "",
1865 keg->uk_free, keg->uk_pages);
1869 hash_free(&keg->uk_hash);
1877 * Arguments/Returns follow uma_dtor specifications
1881 zone_dtor(void *arg, int size, void *udata)
1886 zone = (uma_zone_t)arg;
1888 if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1891 rw_wlock(&uma_rwlock);
1892 LIST_REMOVE(zone, uz_link);
1893 rw_wunlock(&uma_rwlock);
1895 * XXX there are some races here where
1896 * the zone can be drained but zone lock
1897 * released and then refilled before we
1898 * remove it... we dont care for now
1900 zone_drain_wait(zone, M_WAITOK);
1902 * We only destroy kegs from non secondary zones.
1904 if ((keg = zone->uz_keg) != NULL &&
1905 (zone->uz_flags & UMA_ZONE_SECONDARY) == 0) {
1906 rw_wlock(&uma_rwlock);
1907 LIST_REMOVE(keg, uk_link);
1908 rw_wunlock(&uma_rwlock);
1909 zone_free_item(kegs, keg, NULL, SKIP_NONE);
1911 if (zone->uz_lockptr == &zone->uz_lock)
1912 ZONE_LOCK_FINI(zone);
1916 * Traverses every zone in the system and calls a callback
1919 * zfunc A pointer to a function which accepts a zone
1926 zone_foreach(void (*zfunc)(uma_zone_t))
1931 rw_rlock(&uma_rwlock);
1932 LIST_FOREACH(keg, &uma_kegs, uk_link) {
1933 LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1936 rw_runlock(&uma_rwlock);
1940 * Count how many pages do we need to bootstrap. VM supplies
1941 * its need in early zones in the argument, we add up our zones,
1942 * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1943 * zone of zones and zone of kegs are accounted separately.
1945 #define UMA_BOOT_ZONES 11
1946 /* Zone of zones and zone of kegs have arbitrary alignment. */
1947 #define UMA_BOOT_ALIGN 32
1948 static int zsize, ksize;
1950 uma_startup_count(int vm_zones)
1954 ksize = sizeof(struct uma_keg) +
1955 (sizeof(struct uma_domain) * vm_ndomains);
1956 zsize = sizeof(struct uma_zone) +
1957 (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1958 (sizeof(struct uma_zone_domain) * vm_ndomains);
1961 * Memory for the zone of kegs and its keg,
1962 * and for zone of zones.
1964 pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1965 roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1967 #ifdef UMA_MD_SMALL_ALLOC
1968 zones = UMA_BOOT_ZONES;
1970 zones = UMA_BOOT_ZONES + vm_zones;
1974 /* Memory for the rest of startup zones, UMA and VM, ... */
1975 if (zsize > UMA_SLAB_SPACE) {
1976 /* See keg_large_init(). */
1979 ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
1980 if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
1983 pages += (zones + vm_zones) * ppera;
1984 } else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
1985 /* See keg_small_init() special case for uk_ppera = 1. */
1988 pages += howmany(zones,
1989 UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
1991 /* ... and their kegs. Note that zone of zones allocates a keg! */
1992 pages += howmany(zones + 1,
1993 UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
1996 * Most of startup zones are not going to be offpages, that's
1997 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
1998 * calculations. Some large bucket zones will be offpage, and
1999 * thus will allocate hashes. We take conservative approach
2000 * and assume that all zones may allocate hash. This may give
2001 * us some positive inaccuracy, usually an extra single page.
2003 pages += howmany(zones, UMA_SLAB_SPACE /
2004 (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2010 uma_startup(void *mem, int npages)
2012 struct uma_zctor_args args;
2013 uma_keg_t masterkeg;
2017 printf("Entering %s with %d boot pages configured\n", __func__, npages);
2020 rw_init(&uma_rwlock, "UMA lock");
2022 /* Use bootpages memory for the zone of zones and zone of kegs. */
2024 zones = (uma_zone_t)m;
2025 m += roundup(zsize, CACHE_LINE_SIZE);
2026 kegs = (uma_zone_t)m;
2027 m += roundup(zsize, CACHE_LINE_SIZE);
2028 masterkeg = (uma_keg_t)m;
2029 m += roundup(ksize, CACHE_LINE_SIZE);
2030 m = roundup(m, PAGE_SIZE);
2031 npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2034 /* "manually" create the initial zone */
2035 memset(&args, 0, sizeof(args));
2036 args.name = "UMA Kegs";
2038 args.ctor = keg_ctor;
2039 args.dtor = keg_dtor;
2040 args.uminit = zero_init;
2042 args.keg = masterkeg;
2043 args.align = UMA_BOOT_ALIGN - 1;
2044 args.flags = UMA_ZFLAG_INTERNAL;
2045 zone_ctor(kegs, zsize, &args, M_WAITOK);
2048 boot_pages = npages;
2050 args.name = "UMA Zones";
2052 args.ctor = zone_ctor;
2053 args.dtor = zone_dtor;
2054 args.uminit = zero_init;
2057 args.align = UMA_BOOT_ALIGN - 1;
2058 args.flags = UMA_ZFLAG_INTERNAL;
2059 zone_ctor(zones, zsize, &args, M_WAITOK);
2061 /* Now make a zone for slab headers */
2062 slabzone = uma_zcreate("UMA Slabs",
2063 sizeof(struct uma_slab),
2064 NULL, NULL, NULL, NULL,
2065 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2067 hashzone = uma_zcreate("UMA Hash",
2068 sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2069 NULL, NULL, NULL, NULL,
2070 UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2074 booted = BOOT_STRAPPED;
2082 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2084 booted = BOOT_PAGEALLOC;
2092 printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2094 booted = BOOT_BUCKETS;
2095 sx_init(&uma_drain_lock, "umadrain");
2100 * Initialize our callout handle
2108 TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2109 uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2110 uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2112 callout_init(&uma_callout, 1);
2113 callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2114 booted = BOOT_RUNNING;
2118 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2119 int align, uint32_t flags)
2121 struct uma_kctor_args args;
2124 args.uminit = uminit;
2126 args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2129 return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2132 /* Public functions */
2135 uma_set_align(int align)
2138 if (align != UMA_ALIGN_CACHE)
2139 uma_align_cache = align;
2144 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2145 uma_init uminit, uma_fini fini, int align, uint32_t flags)
2148 struct uma_zctor_args args;
2152 KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2155 /* This stuff is essential for the zone ctor */
2156 memset(&args, 0, sizeof(args));
2161 args.uminit = uminit;
2165 * If a zone is being created with an empty constructor and
2166 * destructor, pass UMA constructor/destructor which checks for
2167 * memory use after free.
2169 if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2170 ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2171 args.ctor = trash_ctor;
2172 args.dtor = trash_dtor;
2173 args.uminit = trash_init;
2174 args.fini = trash_fini;
2181 if (booted < BOOT_BUCKETS) {
2184 sx_slock(&uma_drain_lock);
2187 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2189 sx_sunlock(&uma_drain_lock);
2195 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2196 uma_init zinit, uma_fini zfini, uma_zone_t master)
2198 struct uma_zctor_args args;
2203 keg = master->uz_keg;
2204 memset(&args, 0, sizeof(args));
2206 args.size = keg->uk_size;
2209 args.uminit = zinit;
2211 args.align = keg->uk_align;
2212 args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2215 if (booted < BOOT_BUCKETS) {
2218 sx_slock(&uma_drain_lock);
2221 /* XXX Attaches only one keg of potentially many. */
2222 res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2224 sx_sunlock(&uma_drain_lock);
2230 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2231 uma_init zinit, uma_fini zfini, uma_import zimport,
2232 uma_release zrelease, void *arg, int flags)
2234 struct uma_zctor_args args;
2236 memset(&args, 0, sizeof(args));
2241 args.uminit = zinit;
2243 args.import = zimport;
2244 args.release = zrelease;
2247 args.flags = flags | UMA_ZFLAG_CACHE;
2249 return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2254 uma_zdestroy(uma_zone_t zone)
2257 sx_slock(&uma_drain_lock);
2258 zone_free_item(zones, zone, NULL, SKIP_NONE);
2259 sx_sunlock(&uma_drain_lock);
2263 uma_zwait(uma_zone_t zone)
2267 item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2268 uma_zfree(zone, item);
2272 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2278 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2280 item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2281 if (item != NULL && (flags & M_ZERO)) {
2283 for (i = 0; i <= mp_maxid; i++)
2284 bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2286 bzero(item, zone->uz_size);
2293 * A stub while both regular and pcpu cases are identical.
2296 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2300 MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2302 uma_zfree_arg(zone, item, udata);
2307 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2309 uma_zone_domain_t zdom;
2310 uma_bucket_t bucket;
2313 int cpu, domain, lockfail, maxbucket;
2318 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2319 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2321 /* This is the fast path allocation */
2322 CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2323 curthread, zone->uz_name, zone, flags);
2325 if (flags & M_WAITOK) {
2326 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2327 "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2329 KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2330 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2331 ("uma_zalloc_arg: called with spinlock or critical section held"));
2332 if (zone->uz_flags & UMA_ZONE_PCPU)
2333 KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2334 "with M_ZERO passed"));
2336 #ifdef DEBUG_MEMGUARD
2337 if (memguard_cmp_zone(zone)) {
2338 item = memguard_alloc(zone->uz_size, flags);
2340 if (zone->uz_init != NULL &&
2341 zone->uz_init(item, zone->uz_size, flags) != 0)
2343 if (zone->uz_ctor != NULL &&
2344 zone->uz_ctor(item, zone->uz_size, udata,
2346 zone->uz_fini(item, zone->uz_size);
2351 /* This is unfortunate but should not be fatal. */
2355 * If possible, allocate from the per-CPU cache. There are two
2356 * requirements for safe access to the per-CPU cache: (1) the thread
2357 * accessing the cache must not be preempted or yield during access,
2358 * and (2) the thread must not migrate CPUs without switching which
2359 * cache it accesses. We rely on a critical section to prevent
2360 * preemption and migration. We release the critical section in
2361 * order to acquire the zone mutex if we are unable to allocate from
2362 * the current cache; when we re-acquire the critical section, we
2363 * must detect and handle migration if it has occurred.
2368 cache = &zone->uz_cpu[cpu];
2371 bucket = cache->uc_allocbucket;
2372 if (bucket != NULL && bucket->ub_cnt > 0) {
2374 item = bucket->ub_bucket[bucket->ub_cnt];
2376 bucket->ub_bucket[bucket->ub_cnt] = NULL;
2378 KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2382 skipdbg = uma_dbg_zskip(zone, item);
2384 if (zone->uz_ctor != NULL &&
2386 (!skipdbg || zone->uz_ctor != trash_ctor ||
2387 zone->uz_dtor != trash_dtor) &&
2389 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2390 atomic_add_long(&zone->uz_fails, 1);
2391 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2396 uma_dbg_alloc(zone, NULL, item);
2399 uma_zero_item(item, zone);
2404 * We have run out of items in our alloc bucket.
2405 * See if we can switch with our free bucket.
2407 bucket = cache->uc_freebucket;
2408 if (bucket != NULL && bucket->ub_cnt > 0) {
2410 "uma_zalloc: zone %s(%p) swapping empty with alloc",
2411 zone->uz_name, zone);
2412 cache->uc_freebucket = cache->uc_allocbucket;
2413 cache->uc_allocbucket = bucket;
2418 * Discard any empty allocation bucket while we hold no locks.
2420 bucket = cache->uc_allocbucket;
2421 cache->uc_allocbucket = NULL;
2424 bucket_free(zone, bucket, udata);
2426 if (zone->uz_flags & UMA_ZONE_NUMA) {
2427 domain = PCPU_GET(domain);
2428 if (VM_DOMAIN_EMPTY(domain))
2429 domain = UMA_ANYDOMAIN;
2431 domain = UMA_ANYDOMAIN;
2433 /* Short-circuit for zones without buckets and low memory. */
2434 if (zone->uz_count == 0 || bucketdisable) {
2440 * Attempt to retrieve the item from the per-CPU cache has failed, so
2441 * we must go back to the zone. This requires the zone lock, so we
2442 * must drop the critical section, then re-acquire it when we go back
2443 * to the cache. Since the critical section is released, we may be
2444 * preempted or migrate. As such, make sure not to maintain any
2445 * thread-local state specific to the cache from prior to releasing
2446 * the critical section.
2449 if (ZONE_TRYLOCK(zone) == 0) {
2450 /* Record contention to size the buckets. */
2456 cache = &zone->uz_cpu[cpu];
2458 /* See if we lost the race to fill the cache. */
2459 if (cache->uc_allocbucket != NULL) {
2465 * Check the zone's cache of buckets.
2467 if (domain == UMA_ANYDOMAIN)
2468 zdom = &zone->uz_domain[0];
2470 zdom = &zone->uz_domain[domain];
2471 if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2472 KASSERT(bucket->ub_cnt != 0,
2473 ("uma_zalloc_arg: Returning an empty bucket."));
2474 cache->uc_allocbucket = bucket;
2478 /* We are no longer associated with this CPU. */
2482 * We bump the uz count when the cache size is insufficient to
2483 * handle the working set.
2485 if (lockfail && zone->uz_count < zone->uz_count_max)
2488 if (zone->uz_max_items > 0) {
2489 if (zone->uz_items >= zone->uz_max_items)
2491 maxbucket = MIN(zone->uz_count,
2492 zone->uz_max_items - zone->uz_items);
2494 maxbucket = zone->uz_count;
2495 zone->uz_items += maxbucket;
2499 * Now lets just fill a bucket and put it on the free list. If that
2500 * works we'll restart the allocation from the beginning and it
2501 * will use the just filled bucket.
2503 bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2504 CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2505 zone->uz_name, zone, bucket);
2507 if (bucket != NULL) {
2508 if (bucket->ub_cnt < maxbucket) {
2509 MPASS(zone->uz_flags & UMA_ZFLAG_CACHE ||
2510 zone->uz_items >= maxbucket - bucket->ub_cnt);
2511 zone->uz_items -= maxbucket - bucket->ub_cnt;
2512 if (zone->uz_sleepers > 0 &&
2513 zone->uz_items < zone->uz_max_items)
2518 cache = &zone->uz_cpu[cpu];
2521 * See if we lost the race or were migrated. Cache the
2522 * initialized bucket to make this less likely or claim
2523 * the memory directly.
2525 if (cache->uc_allocbucket == NULL &&
2526 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2527 domain == PCPU_GET(domain))) {
2528 cache->uc_allocbucket = bucket;
2529 zdom->uzd_imax += bucket->ub_cnt;
2530 } else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2533 bucket_drain(zone, bucket);
2534 bucket_free(zone, bucket, udata);
2535 goto zalloc_restart;
2537 zone_put_bucket(zone, zdom, bucket, false);
2541 zone->uz_items -= maxbucket;
2542 if (zone->uz_sleepers > 0 &&
2543 zone->uz_items + 1 < zone->uz_max_items)
2548 * We may not be able to get a bucket so return an actual item.
2551 item = zone_alloc_item_locked(zone, udata, domain, flags);
2557 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2560 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2561 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2563 /* This is the fast path allocation */
2565 "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2566 curthread, zone->uz_name, zone, domain, flags);
2568 if (flags & M_WAITOK) {
2569 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2570 "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2572 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2573 ("uma_zalloc_domain: called with spinlock or critical section held"));
2575 return (zone_alloc_item(zone, udata, domain, flags));
2579 * Find a slab with some space. Prefer slabs that are partially used over those
2580 * that are totally full. This helps to reduce fragmentation.
2582 * If 'rr' is 1, search all domains starting from 'domain'. Otherwise check
2586 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2592 KASSERT(domain >= 0 && domain < vm_ndomains,
2593 ("keg_first_slab: domain %d out of range", domain));
2594 KEG_LOCK_ASSERT(keg);
2599 dom = &keg->uk_domain[domain];
2600 if (!LIST_EMPTY(&dom->ud_part_slab))
2601 return (LIST_FIRST(&dom->ud_part_slab));
2602 if (!LIST_EMPTY(&dom->ud_free_slab)) {
2603 slab = LIST_FIRST(&dom->ud_free_slab);
2604 LIST_REMOVE(slab, us_link);
2605 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2609 domain = (domain + 1) % vm_ndomains;
2610 } while (domain != start);
2616 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2620 KEG_LOCK_ASSERT(keg);
2622 reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2623 if (keg->uk_free <= reserve)
2625 return (keg_first_slab(keg, domain, rr));
2629 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2631 struct vm_domainset_iter di;
2638 KEG_LOCK_ASSERT(keg);
2641 * Use the keg's policy if upper layers haven't already specified a
2642 * domain (as happens with first-touch zones).
2644 * To avoid races we run the iterator with the keg lock held, but that
2645 * means that we cannot allow the vm_domainset layer to sleep. Thus,
2646 * clear M_WAITOK and handle low memory conditions locally.
2648 rr = rdomain == UMA_ANYDOMAIN;
2650 aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2651 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2659 slab = keg_fetch_free_slab(keg, domain, rr, flags);
2661 MPASS(slab->us_keg == keg);
2666 * M_NOVM means don't ask at all!
2671 KASSERT(zone->uz_max_items == 0 ||
2672 zone->uz_items <= zone->uz_max_items,
2673 ("%s: zone %p overflow", __func__, zone));
2675 slab = keg_alloc_slab(keg, zone, domain, aflags);
2677 * If we got a slab here it's safe to mark it partially used
2678 * and return. We assume that the caller is going to remove
2679 * at least one item.
2682 MPASS(slab->us_keg == keg);
2683 dom = &keg->uk_domain[slab->us_domain];
2684 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2688 if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2689 if ((flags & M_WAITOK) != 0) {
2691 vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2700 * We might not have been able to get a slab but another cpu
2701 * could have while we were unlocked. Check again before we
2704 if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2705 MPASS(slab->us_keg == keg);
2712 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2722 slab = keg_fetch_slab(keg, zone, domain, flags);
2725 if (flags & (M_NOWAIT | M_NOVM))
2733 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2739 MPASS(keg == slab->us_keg);
2740 KEG_LOCK_ASSERT(keg);
2742 freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2743 BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2744 item = slab->us_data + (keg->uk_rsize * freei);
2745 slab->us_freecount--;
2748 /* Move this slab to the full list */
2749 if (slab->us_freecount == 0) {
2750 LIST_REMOVE(slab, us_link);
2751 dom = &keg->uk_domain[slab->us_domain];
2752 LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2759 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2770 /* Try to keep the buckets totally full */
2771 for (i = 0; i < max; ) {
2772 if ((slab = zone->uz_slab(zone, keg, domain, flags)) == NULL)
2776 stripe = howmany(max, vm_ndomains);
2778 while (slab->us_freecount && i < max) {
2779 bucket[i++] = slab_alloc_item(keg, slab);
2780 if (keg->uk_free <= keg->uk_reserve)
2784 * If the zone is striped we pick a new slab for every
2785 * N allocations. Eliminating this conditional will
2786 * instead pick a new domain for each bucket rather
2787 * than stripe within each bucket. The current option
2788 * produces more fragmentation and requires more cpu
2789 * time but yields better distribution.
2791 if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2792 vm_ndomains > 1 && --stripe == 0)
2796 /* Don't block if we allocated any successfully. */
2807 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2809 uma_bucket_t bucket;
2811 CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2813 /* Don't wait for buckets, preserve caller's NOVM setting. */
2814 bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2818 bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2819 max, domain, flags);
2822 * Initialize the memory if necessary.
2824 if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2827 for (i = 0; i < bucket->ub_cnt; i++)
2828 if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2832 * If we couldn't initialize the whole bucket, put the
2833 * rest back onto the freelist.
2835 if (i != bucket->ub_cnt) {
2836 zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2837 bucket->ub_cnt - i);
2839 bzero(&bucket->ub_bucket[i],
2840 sizeof(void *) * (bucket->ub_cnt - i));
2846 if (bucket->ub_cnt == 0) {
2847 bucket_free(zone, bucket, udata);
2848 atomic_add_long(&zone->uz_fails, 1);
2856 * Allocates a single item from a zone.
2859 * zone The zone to alloc for.
2860 * udata The data to be passed to the constructor.
2861 * domain The domain to allocate from or UMA_ANYDOMAIN.
2862 * flags M_WAITOK, M_NOWAIT, M_ZERO.
2865 * NULL if there is no memory and M_NOWAIT is set
2866 * An item if successful
2870 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2874 return (zone_alloc_item_locked(zone, udata, domain, flags));
2878 * Returns with zone unlocked.
2881 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2888 ZONE_LOCK_ASSERT(zone);
2890 if (zone->uz_max_items > 0 && zone->uz_items >= zone->uz_max_items) {
2891 zone_log_warning(zone);
2892 zone_maxaction(zone);
2893 if (flags & M_NOWAIT) {
2898 zone->uz_sleepers++;
2899 while (zone->uz_items >= zone->uz_max_items)
2900 mtx_sleep(zone, zone->uz_lockptr, PVM, "zonelimit", 0);
2901 zone->uz_sleepers--;
2902 if (zone->uz_sleepers > 0 &&
2903 zone->uz_items + 1 < zone->uz_max_items)
2911 if (domain != UMA_ANYDOMAIN) {
2912 /* avoid allocs targeting empty domains */
2913 if (VM_DOMAIN_EMPTY(domain))
2914 domain = UMA_ANYDOMAIN;
2916 if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
2920 skipdbg = uma_dbg_zskip(zone, item);
2923 * We have to call both the zone's init (not the keg's init)
2924 * and the zone's ctor. This is because the item is going from
2925 * a keg slab directly to the user, and the user is expecting it
2926 * to be both zone-init'd as well as zone-ctor'd.
2928 if (zone->uz_init != NULL) {
2929 if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2930 zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
2934 if (zone->uz_ctor != NULL &&
2936 (!skipdbg || zone->uz_ctor != trash_ctor ||
2937 zone->uz_dtor != trash_dtor) &&
2939 zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2940 zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2945 uma_dbg_alloc(zone, NULL, item);
2948 uma_zero_item(item, zone);
2950 CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
2951 zone->uz_name, zone);
2960 atomic_add_long(&zone->uz_fails, 1);
2961 CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
2962 zone->uz_name, zone);
2968 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2971 uma_bucket_t bucket;
2972 uma_zone_domain_t zdom;
2979 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2980 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2982 CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
2985 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2986 ("uma_zfree_arg: called with spinlock or critical section held"));
2988 /* uma_zfree(..., NULL) does nothing, to match free(9). */
2991 #ifdef DEBUG_MEMGUARD
2992 if (is_memguard_addr(item)) {
2993 if (zone->uz_dtor != NULL)
2994 zone->uz_dtor(item, zone->uz_size, udata);
2995 if (zone->uz_fini != NULL)
2996 zone->uz_fini(item, zone->uz_size);
2997 memguard_free(item);
3002 skipdbg = uma_dbg_zskip(zone, item);
3003 if (skipdbg == false) {
3004 if (zone->uz_flags & UMA_ZONE_MALLOC)
3005 uma_dbg_free(zone, udata, item);
3007 uma_dbg_free(zone, NULL, item);
3009 if (zone->uz_dtor != NULL && (!skipdbg ||
3010 zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3012 if (zone->uz_dtor != NULL)
3014 zone->uz_dtor(item, zone->uz_size, udata);
3017 * The race here is acceptable. If we miss it we'll just have to wait
3018 * a little longer for the limits to be reset.
3020 if (zone->uz_sleepers > 0)
3024 * If possible, free to the per-CPU cache. There are two
3025 * requirements for safe access to the per-CPU cache: (1) the thread
3026 * accessing the cache must not be preempted or yield during access,
3027 * and (2) the thread must not migrate CPUs without switching which
3028 * cache it accesses. We rely on a critical section to prevent
3029 * preemption and migration. We release the critical section in
3030 * order to acquire the zone mutex if we are unable to free to the
3031 * current cache; when we re-acquire the critical section, we must
3032 * detect and handle migration if it has occurred.
3037 cache = &zone->uz_cpu[cpu];
3041 * Try to free into the allocbucket first to give LIFO ordering
3042 * for cache-hot datastructures. Spill over into the freebucket
3043 * if necessary. Alloc will swap them if one runs dry.
3045 bucket = cache->uc_allocbucket;
3046 if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3047 bucket = cache->uc_freebucket;
3048 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3049 KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3050 ("uma_zfree: Freeing to non free bucket index."));
3051 bucket->ub_bucket[bucket->ub_cnt] = item;
3059 * We must go back the zone, which requires acquiring the zone lock,
3060 * which in turn means we must release and re-acquire the critical
3061 * section. Since the critical section is released, we may be
3062 * preempted or migrate. As such, make sure not to maintain any
3063 * thread-local state specific to the cache from prior to releasing
3064 * the critical section.
3067 if (zone->uz_count == 0 || bucketdisable)
3071 if (ZONE_TRYLOCK(zone) == 0) {
3072 /* Record contention to size the buckets. */
3078 cache = &zone->uz_cpu[cpu];
3080 bucket = cache->uc_freebucket;
3081 if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3085 cache->uc_freebucket = NULL;
3086 /* We are no longer associated with this CPU. */
3089 if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3090 domain = PCPU_GET(domain);
3091 if (VM_DOMAIN_EMPTY(domain))
3092 domain = UMA_ANYDOMAIN;
3095 zdom = &zone->uz_domain[0];
3097 /* Can we throw this on the zone full list? */
3098 if (bucket != NULL) {
3100 "uma_zfree: zone %s(%p) putting bucket %p on free list",
3101 zone->uz_name, zone, bucket);
3102 /* ub_cnt is pointing to the last free item */
3103 KASSERT(bucket->ub_cnt == bucket->ub_entries,
3104 ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3105 if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3107 bucket_drain(zone, bucket);
3108 bucket_free(zone, bucket, udata);
3111 zone_put_bucket(zone, zdom, bucket, true);
3115 * We bump the uz count when the cache size is insufficient to
3116 * handle the working set.
3118 if (lockfail && zone->uz_count < zone->uz_count_max)
3122 bucket = bucket_alloc(zone, udata, M_NOWAIT);
3123 CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3124 zone->uz_name, zone, bucket);
3128 cache = &zone->uz_cpu[cpu];
3129 if (cache->uc_freebucket == NULL &&
3130 ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3131 domain == PCPU_GET(domain))) {
3132 cache->uc_freebucket = bucket;
3136 * We lost the race, start over. We have to drop our
3137 * critical section to free the bucket.
3140 bucket_free(zone, bucket, udata);
3145 * If nothing else caught this, we'll just do an internal free.
3148 zone_free_item(zone, item, udata, SKIP_DTOR);
3152 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3155 /* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3156 random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3158 CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3161 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3162 ("uma_zfree_domain: called with spinlock or critical section held"));
3164 /* uma_zfree(..., NULL) does nothing, to match free(9). */
3167 zone_free_item(zone, item, udata, SKIP_NONE);
3171 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3178 MPASS(zone->uz_lockptr == &keg->uk_lock);
3179 KEG_LOCK_ASSERT(keg);
3180 MPASS(keg == slab->us_keg);
3182 dom = &keg->uk_domain[slab->us_domain];
3184 /* Do we need to remove from any lists? */
3185 if (slab->us_freecount+1 == keg->uk_ipers) {
3186 LIST_REMOVE(slab, us_link);
3187 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3188 } else if (slab->us_freecount == 0) {
3189 LIST_REMOVE(slab, us_link);
3190 LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3193 /* Slab management. */
3194 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3195 BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3196 slab->us_freecount++;
3198 /* Keg statistics. */
3203 zone_release(uma_zone_t zone, void **bucket, int cnt)
3213 for (i = 0; i < cnt; i++) {
3215 if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3216 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3217 if (zone->uz_flags & UMA_ZONE_HASH) {
3218 slab = hash_sfind(&keg->uk_hash, mem);
3220 mem += keg->uk_pgoff;
3221 slab = (uma_slab_t)mem;
3224 slab = vtoslab((vm_offset_t)item);
3225 MPASS(slab->us_keg == keg);
3227 slab_free_item(zone, slab, item);
3233 * Frees a single item to any zone.
3236 * zone The zone to free to
3237 * item The item we're freeing
3238 * udata User supplied data for the dtor
3239 * skip Skip dtors and finis
3242 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3247 skipdbg = uma_dbg_zskip(zone, item);
3248 if (skip == SKIP_NONE && !skipdbg) {
3249 if (zone->uz_flags & UMA_ZONE_MALLOC)
3250 uma_dbg_free(zone, udata, item);
3252 uma_dbg_free(zone, NULL, item);
3255 if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3256 (!skipdbg || zone->uz_dtor != trash_dtor ||
3257 zone->uz_ctor != trash_ctor))
3259 if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3261 zone->uz_dtor(item, zone->uz_size, udata);
3263 if (skip < SKIP_FINI && zone->uz_fini)
3264 zone->uz_fini(item, zone->uz_size);
3266 zone->uz_release(zone->uz_arg, &item, 1);
3268 if (skip & SKIP_CNT)
3274 if (zone->uz_sleepers > 0 && zone->uz_items < zone->uz_max_items)
3281 uma_zone_set_max(uma_zone_t zone, int nitems)
3283 struct uma_bucket_zone *ubz;
3286 * If limit is very low we may need to limit how
3287 * much items are allowed in CPU caches.
3289 ubz = &bucket_zones[0];
3290 for (; ubz->ubz_entries != 0; ubz++)
3291 if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3293 if (ubz == &bucket_zones[0])
3294 nitems = ubz->ubz_entries * 2 * mp_ncpus;
3299 zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3300 if (zone->uz_count_min > zone->uz_count_max)
3301 zone->uz_count_min = zone->uz_count_max;
3302 zone->uz_max_items = nitems;
3310 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3314 zone->uz_bkt_max = nitems;
3322 uma_zone_get_max(uma_zone_t zone)
3327 nitems = zone->uz_max_items;
3335 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3339 zone->uz_warning = warning;
3345 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3349 TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3355 uma_zone_get_cur(uma_zone_t zone)
3361 nitems = zone->uz_allocs - zone->uz_frees;
3364 * See the comment in sysctl_vm_zone_stats() regarding the
3365 * safety of accessing the per-cpu caches. With the zone lock
3366 * held, it is safe, but can potentially result in stale data.
3368 nitems += zone->uz_cpu[i].uc_allocs -
3369 zone->uz_cpu[i].uc_frees;
3373 return (nitems < 0 ? 0 : nitems);
3378 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3384 KASSERT(keg->uk_pages == 0,
3385 ("uma_zone_set_init on non-empty keg"));
3386 keg->uk_init = uminit;
3392 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3398 KASSERT(keg->uk_pages == 0,
3399 ("uma_zone_set_fini on non-empty keg"));
3400 keg->uk_fini = fini;
3406 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3410 KASSERT(zone->uz_keg->uk_pages == 0,
3411 ("uma_zone_set_zinit on non-empty keg"));
3412 zone->uz_init = zinit;
3418 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3422 KASSERT(zone->uz_keg->uk_pages == 0,
3423 ("uma_zone_set_zfini on non-empty keg"));
3424 zone->uz_fini = zfini;
3429 /* XXX uk_freef is not actually used with the zone locked */
3431 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3436 KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3438 keg->uk_freef = freef;
3443 /* XXX uk_allocf is not actually used with the zone locked */
3445 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3451 keg->uk_allocf = allocf;
3457 uma_zone_reserve(uma_zone_t zone, int items)
3463 keg->uk_reserve = items;
3469 uma_zone_reserve_kva(uma_zone_t zone, int count)
3477 pages = count / keg->uk_ipers;
3478 if (pages * keg->uk_ipers < count)
3480 pages *= keg->uk_ppera;
3482 #ifdef UMA_MD_SMALL_ALLOC
3483 if (keg->uk_ppera > 1) {
3487 kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3494 MPASS(keg->uk_kva == 0);
3497 zone->uz_max_items = pages * keg->uk_ipers;
3498 #ifdef UMA_MD_SMALL_ALLOC
3499 keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3501 keg->uk_allocf = noobj_alloc;
3503 keg->uk_flags |= UMA_ZONE_NOFREE;
3511 uma_prealloc(uma_zone_t zone, int items)
3513 struct vm_domainset_iter di;
3517 int domain, flags, slabs;
3521 slabs = items / keg->uk_ipers;
3522 if (slabs * keg->uk_ipers < items)
3525 vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain, &flags);
3526 while (slabs-- > 0) {
3527 slab = keg_alloc_slab(keg, zone, domain, flags);
3530 MPASS(slab->us_keg == keg);
3531 dom = &keg->uk_domain[slab->us_domain];
3532 LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3533 if (vm_domainset_iter_policy(&di, &domain) != 0)
3541 uma_reclaim_locked(bool kmem_danger)
3544 CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3545 sx_assert(&uma_drain_lock, SA_XLOCKED);
3547 zone_foreach(zone_drain);
3548 if (vm_page_count_min() || kmem_danger) {
3549 cache_drain_safe(NULL);
3550 zone_foreach(zone_drain);
3554 * Some slabs may have been freed but this zone will be visited early
3555 * we visit again so that we can free pages that are empty once other
3556 * zones are drained. We have to do the same for buckets.
3558 zone_drain(slabzone);
3559 bucket_zone_drain();
3566 sx_xlock(&uma_drain_lock);
3567 uma_reclaim_locked(false);
3568 sx_xunlock(&uma_drain_lock);
3571 static volatile int uma_reclaim_needed;
3574 uma_reclaim_wakeup(void)
3577 if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3578 wakeup(uma_reclaim);
3582 uma_reclaim_worker(void *arg __unused)
3586 sx_xlock(&uma_drain_lock);
3587 while (atomic_load_int(&uma_reclaim_needed) == 0)
3588 sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3590 sx_xunlock(&uma_drain_lock);
3591 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3592 sx_xlock(&uma_drain_lock);
3593 uma_reclaim_locked(true);
3594 atomic_store_int(&uma_reclaim_needed, 0);
3595 sx_xunlock(&uma_drain_lock);
3596 /* Don't fire more than once per-second. */
3597 pause("umarclslp", hz);
3603 uma_zone_exhausted(uma_zone_t zone)
3608 full = zone->uz_sleepers > 0;
3614 uma_zone_exhausted_nolock(uma_zone_t zone)
3616 return (zone->uz_sleepers > 0);
3620 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3622 struct domainset *policy;
3626 if (domain != UMA_ANYDOMAIN) {
3627 /* avoid allocs targeting empty domains */
3628 if (VM_DOMAIN_EMPTY(domain))
3629 domain = UMA_ANYDOMAIN;
3631 slab = zone_alloc_item(slabzone, NULL, domain, wait);
3634 policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3635 DOMAINSET_FIXED(domain);
3636 addr = kmem_malloc_domainset(policy, size, wait);
3638 vsetslab(addr, slab);
3639 slab->us_data = (void *)addr;
3640 slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3641 slab->us_size = size;
3642 slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3643 pmap_kextract(addr)));
3644 uma_total_inc(size);
3646 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3649 return ((void *)addr);
3653 uma_large_malloc(vm_size_t size, int wait)
3656 return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3660 uma_large_free(uma_slab_t slab)
3663 KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3664 ("uma_large_free: Memory not allocated with uma_large_malloc."));
3665 kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3666 uma_total_dec(slab->us_size);
3667 zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3671 uma_zero_item(void *item, uma_zone_t zone)
3674 bzero(item, zone->uz_size);
3681 return (uma_kmem_limit);
3685 uma_set_limit(unsigned long limit)
3688 uma_kmem_limit = limit;
3695 return (uma_kmem_total);
3702 return (uma_kmem_limit - uma_kmem_total);
3706 uma_print_stats(void)
3708 zone_foreach(uma_print_zone);
3712 slab_print(uma_slab_t slab)
3714 printf("slab: keg %p, data %p, freecount %d\n",
3715 slab->us_keg, slab->us_data, slab->us_freecount);
3719 cache_print(uma_cache_t cache)
3721 printf("alloc: %p(%d), free: %p(%d)\n",
3722 cache->uc_allocbucket,
3723 cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3724 cache->uc_freebucket,
3725 cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3729 uma_print_keg(uma_keg_t keg)
3735 printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3737 keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3738 keg->uk_ipers, keg->uk_ppera,
3739 (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3741 for (i = 0; i < vm_ndomains; i++) {
3742 dom = &keg->uk_domain[i];
3743 printf("Part slabs:\n");
3744 LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3746 printf("Free slabs:\n");
3747 LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3749 printf("Full slabs:\n");
3750 LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3756 uma_print_zone(uma_zone_t zone)
3761 printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3762 zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3764 if (zone->uz_lockptr != &zone->uz_lock)
3765 uma_print_keg(zone->uz_keg);
3767 cache = &zone->uz_cpu[i];
3768 printf("CPU %d Cache:\n", i);
3775 * Generate statistics across both the zone and its per-cpu cache's. Return
3776 * desired statistics if the pointer is non-NULL for that statistic.
3778 * Note: does not update the zone statistics, as it can't safely clear the
3779 * per-CPU cache statistic.
3781 * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3782 * safe from off-CPU; we should modify the caches to track this information
3783 * directly so that we don't have to.
3786 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3787 uint64_t *freesp, uint64_t *sleepsp)
3790 uint64_t allocs, frees, sleeps;
3793 allocs = frees = sleeps = 0;
3796 cache = &z->uz_cpu[cpu];
3797 if (cache->uc_allocbucket != NULL)
3798 cachefree += cache->uc_allocbucket->ub_cnt;
3799 if (cache->uc_freebucket != NULL)
3800 cachefree += cache->uc_freebucket->ub_cnt;
3801 allocs += cache->uc_allocs;
3802 frees += cache->uc_frees;
3804 allocs += z->uz_allocs;
3805 frees += z->uz_frees;
3806 sleeps += z->uz_sleeps;
3807 if (cachefreep != NULL)
3808 *cachefreep = cachefree;
3809 if (allocsp != NULL)
3813 if (sleepsp != NULL)
3819 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3826 rw_rlock(&uma_rwlock);
3827 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3828 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3831 rw_runlock(&uma_rwlock);
3832 return (sysctl_handle_int(oidp, &count, 0, req));
3836 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3838 struct uma_stream_header ush;
3839 struct uma_type_header uth;
3840 struct uma_percpu_stat *ups;
3841 uma_zone_domain_t zdom;
3846 int count, error, i;
3848 error = sysctl_wire_old_buffer(req, 0);
3851 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3852 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3853 ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3856 rw_rlock(&uma_rwlock);
3857 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3858 LIST_FOREACH(z, &kz->uk_zones, uz_link)
3863 * Insert stream header.
3865 bzero(&ush, sizeof(ush));
3866 ush.ush_version = UMA_STREAM_VERSION;
3867 ush.ush_maxcpus = (mp_maxid + 1);
3868 ush.ush_count = count;
3869 (void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3871 LIST_FOREACH(kz, &uma_kegs, uk_link) {
3872 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3873 bzero(&uth, sizeof(uth));
3875 strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3876 uth.uth_align = kz->uk_align;
3877 uth.uth_size = kz->uk_size;
3878 uth.uth_rsize = kz->uk_rsize;
3879 uth.uth_pages += (z->uz_items / kz->uk_ipers) *
3881 uth.uth_maxpages += (z->uz_max_items / kz->uk_ipers) *
3883 uth.uth_limit = z->uz_max_items;
3884 uth.uth_keg_free += z->uz_keg->uk_free;
3887 * A zone is secondary is it is not the first entry
3888 * on the keg's zone list.
3890 if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3891 (LIST_FIRST(&kz->uk_zones) != z))
3892 uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3894 for (i = 0; i < vm_ndomains; i++) {
3895 zdom = &z->uz_domain[i];
3896 uth.uth_zone_free += zdom->uzd_nitems;
3898 uth.uth_allocs = z->uz_allocs;
3899 uth.uth_frees = z->uz_frees;
3900 uth.uth_fails = z->uz_fails;
3901 uth.uth_sleeps = z->uz_sleeps;
3903 * While it is not normally safe to access the cache
3904 * bucket pointers while not on the CPU that owns the
3905 * cache, we only allow the pointers to be exchanged
3906 * without the zone lock held, not invalidated, so
3907 * accept the possible race associated with bucket
3908 * exchange during monitoring.
3910 for (i = 0; i < mp_maxid + 1; i++) {
3911 bzero(&ups[i], sizeof(*ups));
3912 if (kz->uk_flags & UMA_ZFLAG_INTERNAL ||
3915 cache = &z->uz_cpu[i];
3916 if (cache->uc_allocbucket != NULL)
3917 ups[i].ups_cache_free +=
3918 cache->uc_allocbucket->ub_cnt;
3919 if (cache->uc_freebucket != NULL)
3920 ups[i].ups_cache_free +=
3921 cache->uc_freebucket->ub_cnt;
3922 ups[i].ups_allocs = cache->uc_allocs;
3923 ups[i].ups_frees = cache->uc_frees;
3926 (void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3927 for (i = 0; i < mp_maxid + 1; i++)
3928 (void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
3931 rw_runlock(&uma_rwlock);
3932 error = sbuf_finish(&sbuf);
3939 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
3941 uma_zone_t zone = *(uma_zone_t *)arg1;
3944 max = uma_zone_get_max(zone);
3945 error = sysctl_handle_int(oidp, &max, 0, req);
3946 if (error || !req->newptr)
3949 uma_zone_set_max(zone, max);
3955 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
3957 uma_zone_t zone = *(uma_zone_t *)arg1;
3960 cur = uma_zone_get_cur(zone);
3961 return (sysctl_handle_int(oidp, &cur, 0, req));
3966 uma_dbg_getslab(uma_zone_t zone, void *item)
3972 mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3973 if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
3974 slab = vtoslab((vm_offset_t)mem);
3977 * It is safe to return the slab here even though the
3978 * zone is unlocked because the item's allocation state
3979 * essentially holds a reference.
3981 if (zone->uz_lockptr == &zone->uz_lock)
3985 if (keg->uk_flags & UMA_ZONE_HASH)
3986 slab = hash_sfind(&keg->uk_hash, mem);
3988 slab = (uma_slab_t)(mem + keg->uk_pgoff);
3996 uma_dbg_zskip(uma_zone_t zone, void *mem)
3999 if (zone->uz_lockptr == &zone->uz_lock)
4002 return (uma_dbg_kskip(zone->uz_keg, mem));
4006 uma_dbg_kskip(uma_keg_t keg, void *mem)
4010 if (dbg_divisor == 0)
4013 if (dbg_divisor == 1)
4016 idx = (uintptr_t)mem >> PAGE_SHIFT;
4017 if (keg->uk_ipers > 1) {
4018 idx *= keg->uk_ipers;
4019 idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4022 if ((idx / dbg_divisor) * dbg_divisor != idx) {
4023 counter_u64_add(uma_skip_cnt, 1);
4026 counter_u64_add(uma_dbg_cnt, 1);
4032 * Set up the slab's freei data such that uma_dbg_free can function.
4036 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4042 slab = uma_dbg_getslab(zone, item);
4044 panic("uma: item %p did not belong to zone %s\n",
4045 item, zone->uz_name);
4048 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4050 if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4051 panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4052 item, zone, zone->uz_name, slab, freei);
4053 BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4059 * Verifies freed addresses. Checks for alignment, valid slab membership
4060 * and duplicate frees.
4064 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4070 slab = uma_dbg_getslab(zone, item);
4072 panic("uma: Freed item %p did not belong to zone %s\n",
4073 item, zone->uz_name);
4076 freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4078 if (freei >= keg->uk_ipers)
4079 panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4080 item, zone, zone->uz_name, slab, freei);
4082 if (((freei * keg->uk_rsize) + slab->us_data) != item)
4083 panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4084 item, zone, zone->uz_name, slab, freei);
4086 if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4087 panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4088 item, zone, zone->uz_name, slab, freei);
4090 BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4092 #endif /* INVARIANTS */
4095 DB_SHOW_COMMAND(uma, db_show_uma)
4099 uint64_t allocs, frees, sleeps;
4103 db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4104 "Free", "Requests", "Sleeps", "Bucket");
4105 LIST_FOREACH(kz, &uma_kegs, uk_link) {
4106 LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4107 if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4108 allocs = z->uz_allocs;
4109 frees = z->uz_frees;
4110 sleeps = z->uz_sleeps;
4113 uma_zone_sumstat(z, &cachefree, &allocs,
4115 if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4116 (LIST_FIRST(&kz->uk_zones) != z)))
4117 cachefree += kz->uk_free;
4118 for (i = 0; i < vm_ndomains; i++)
4119 cachefree += z->uz_domain[i].uzd_nitems;
4121 db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4122 z->uz_name, (uintmax_t)kz->uk_size,
4123 (intmax_t)(allocs - frees), cachefree,
4124 (uintmax_t)allocs, sleeps, z->uz_count);
4131 DB_SHOW_COMMAND(umacache, db_show_umacache)
4134 uint64_t allocs, frees;
4138 db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4139 "Requests", "Bucket");
4140 LIST_FOREACH(z, &uma_cachezones, uz_link) {
4141 uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4142 for (i = 0; i < vm_ndomains; i++)
4143 cachefree += z->uz_domain[i].uzd_nitems;
4144 db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4145 z->uz_name, (uintmax_t)z->uz_size,
4146 (intmax_t)(allocs - frees), cachefree,
4147 (uintmax_t)allocs, z->uz_count);