xref: /freebsd/sys/vm/uma_core.c (revision 3a248c84419d4f7d6617d30744ab56d0b456fe03)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2019 Jeffrey Roberson <jeff@FreeBSD.org>
5  * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6  * Copyright (c) 2004-2006 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
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.
18  *
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.
29  */
30 
31 /*
32  * uma_core.c  Implementation of the Universal Memory allocator
33  *
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.
40  *
41  * The basic ideas stem from similar slab/zone based allocators whose algorithms
42  * are well known.
43  *
44  */
45 
46 /*
47  * TODO:
48  *	- Improve memory usage for large allocations
49  *	- Investigate cache size adjustments
50  */
51 
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54 
55 #include "opt_ddb.h"
56 #include "opt_param.h"
57 #include "opt_vm.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/asan.h>
62 #include <sys/bitset.h>
63 #include <sys/domainset.h>
64 #include <sys/eventhandler.h>
65 #include <sys/kernel.h>
66 #include <sys/types.h>
67 #include <sys/limits.h>
68 #include <sys/queue.h>
69 #include <sys/malloc.h>
70 #include <sys/ktr.h>
71 #include <sys/lock.h>
72 #include <sys/sysctl.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/random.h>
76 #include <sys/rwlock.h>
77 #include <sys/sbuf.h>
78 #include <sys/sched.h>
79 #include <sys/sleepqueue.h>
80 #include <sys/smp.h>
81 #include <sys/smr.h>
82 #include <sys/taskqueue.h>
83 #include <sys/vmmeter.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <vm/vm_domainset.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_phys.h>
92 #include <vm/vm_pagequeue.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_kern.h>
95 #include <vm/vm_extern.h>
96 #include <vm/vm_dumpset.h>
97 #include <vm/uma.h>
98 #include <vm/uma_int.h>
99 #include <vm/uma_dbg.h>
100 
101 #include <ddb/ddb.h>
102 
103 #ifdef DEBUG_MEMGUARD
104 #include <vm/memguard.h>
105 #endif
106 
107 #include <machine/md_var.h>
108 
109 #ifdef INVARIANTS
110 #define	UMA_ALWAYS_CTORDTOR	1
111 #else
112 #define	UMA_ALWAYS_CTORDTOR	0
113 #endif
114 
115 /*
116  * This is the zone and keg from which all zones are spawned.
117  */
118 static uma_zone_t kegs;
119 static uma_zone_t zones;
120 
121 /*
122  * On INVARIANTS builds, the slab contains a second bitset of the same size,
123  * "dbg_bits", which is laid out immediately after us_free.
124  */
125 #ifdef INVARIANTS
126 #define	SLAB_BITSETS	2
127 #else
128 #define	SLAB_BITSETS	1
129 #endif
130 
131 /*
132  * These are the two zones from which all offpage uma_slab_ts are allocated.
133  *
134  * One zone is for slab headers that can represent a larger number of items,
135  * making the slabs themselves more efficient, and the other zone is for
136  * headers that are smaller and represent fewer items, making the headers more
137  * efficient.
138  */
139 #define	SLABZONE_SIZE(setsize)					\
140     (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
141 #define	SLABZONE0_SETSIZE	(PAGE_SIZE / 16)
142 #define	SLABZONE1_SETSIZE	SLAB_MAX_SETSIZE
143 #define	SLABZONE0_SIZE	SLABZONE_SIZE(SLABZONE0_SETSIZE)
144 #define	SLABZONE1_SIZE	SLABZONE_SIZE(SLABZONE1_SETSIZE)
145 static uma_zone_t slabzones[2];
146 
147 /*
148  * The initial hash tables come out of this zone so they can be allocated
149  * prior to malloc coming up.
150  */
151 static uma_zone_t hashzone;
152 
153 /* The boot-time adjusted value for cache line alignment. */
154 int uma_align_cache = 64 - 1;
155 
156 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
157 static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
158 
159 /*
160  * Are we allowed to allocate buckets?
161  */
162 static int bucketdisable = 1;
163 
164 /* Linked list of all kegs in the system */
165 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
166 
167 /* Linked list of all cache-only zones in the system */
168 static LIST_HEAD(,uma_zone) uma_cachezones =
169     LIST_HEAD_INITIALIZER(uma_cachezones);
170 
171 /*
172  * Mutex for global lists: uma_kegs, uma_cachezones, and the per-keg list of
173  * zones.
174  */
175 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
176 
177 static struct sx uma_reclaim_lock;
178 
179 /*
180  * First available virual address for boot time allocations.
181  */
182 static vm_offset_t bootstart;
183 static vm_offset_t bootmem;
184 
185 /*
186  * kmem soft limit, initialized by uma_set_limit().  Ensure that early
187  * allocations don't trigger a wakeup of the reclaim thread.
188  */
189 unsigned long uma_kmem_limit = LONG_MAX;
190 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
191     "UMA kernel memory soft limit");
192 unsigned long uma_kmem_total;
193 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
194     "UMA kernel memory usage");
195 
196 /* Is the VM done starting up? */
197 static enum {
198 	BOOT_COLD,
199 	BOOT_KVA,
200 	BOOT_PCPU,
201 	BOOT_RUNNING,
202 	BOOT_SHUTDOWN,
203 } booted = BOOT_COLD;
204 
205 /*
206  * This is the handle used to schedule events that need to happen
207  * outside of the allocation fast path.
208  */
209 static struct callout uma_callout;
210 #define	UMA_TIMEOUT	20		/* Seconds for callout interval. */
211 
212 /*
213  * This structure is passed as the zone ctor arg so that I don't have to create
214  * a special allocation function just for zones.
215  */
216 struct uma_zctor_args {
217 	const char *name;
218 	size_t size;
219 	uma_ctor ctor;
220 	uma_dtor dtor;
221 	uma_init uminit;
222 	uma_fini fini;
223 	uma_import import;
224 	uma_release release;
225 	void *arg;
226 	uma_keg_t keg;
227 	int align;
228 	uint32_t flags;
229 };
230 
231 struct uma_kctor_args {
232 	uma_zone_t zone;
233 	size_t size;
234 	uma_init uminit;
235 	uma_fini fini;
236 	int align;
237 	uint32_t flags;
238 };
239 
240 struct uma_bucket_zone {
241 	uma_zone_t	ubz_zone;
242 	const char	*ubz_name;
243 	int		ubz_entries;	/* Number of items it can hold. */
244 	int		ubz_maxsize;	/* Maximum allocation size per-item. */
245 };
246 
247 /*
248  * Compute the actual number of bucket entries to pack them in power
249  * of two sizes for more efficient space utilization.
250  */
251 #define	BUCKET_SIZE(n)						\
252     (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
253 
254 #define	BUCKET_MAX	BUCKET_SIZE(256)
255 
256 struct uma_bucket_zone bucket_zones[] = {
257 	/* Literal bucket sizes. */
258 	{ NULL, "2 Bucket", 2, 4096 },
259 	{ NULL, "4 Bucket", 4, 3072 },
260 	{ NULL, "8 Bucket", 8, 2048 },
261 	{ NULL, "16 Bucket", 16, 1024 },
262 	/* Rounded down power of 2 sizes for efficiency. */
263 	{ NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
264 	{ NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
265 	{ NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
266 	{ NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
267 	{ NULL, NULL, 0}
268 };
269 
270 /*
271  * Flags and enumerations to be passed to internal functions.
272  */
273 enum zfreeskip {
274 	SKIP_NONE =	0,
275 	SKIP_CNT =	0x00000001,
276 	SKIP_DTOR =	0x00010000,
277 	SKIP_FINI =	0x00020000,
278 };
279 
280 /* Prototypes.. */
281 
282 void	uma_startup1(vm_offset_t);
283 void	uma_startup2(void);
284 
285 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
286 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
287 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
288 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
289 static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
290 static void page_free(void *, vm_size_t, uint8_t);
291 static void pcpu_page_free(void *, vm_size_t, uint8_t);
292 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
293 static void cache_drain(uma_zone_t);
294 static void bucket_drain(uma_zone_t, uma_bucket_t);
295 static void bucket_cache_reclaim(uma_zone_t zone, bool, int);
296 static int keg_ctor(void *, int, void *, int);
297 static void keg_dtor(void *, int, void *);
298 static int zone_ctor(void *, int, void *, int);
299 static void zone_dtor(void *, int, void *);
300 static inline void item_dtor(uma_zone_t zone, void *item, int size,
301     void *udata, enum zfreeskip skip);
302 static int zero_init(void *, int, int);
303 static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
304     int itemdomain, bool ws);
305 static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
306 static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
307 static void zone_timeout(uma_zone_t zone, void *);
308 static int hash_alloc(struct uma_hash *, u_int);
309 static int hash_expand(struct uma_hash *, struct uma_hash *);
310 static void hash_free(struct uma_hash *hash);
311 static void uma_timeout(void *);
312 static void uma_shutdown(void);
313 static void *zone_alloc_item(uma_zone_t, void *, int, int);
314 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
315 static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
316 static void zone_free_limit(uma_zone_t zone, int count);
317 static void bucket_enable(void);
318 static void bucket_init(void);
319 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
320 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
321 static void bucket_zone_drain(int domain);
322 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
323 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
324 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
325 static size_t slab_sizeof(int nitems);
326 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
327     uma_fini fini, int align, uint32_t flags);
328 static int zone_import(void *, void **, int, int, int);
329 static void zone_release(void *, void **, int);
330 static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
331 static bool cache_free(uma_zone_t, uma_cache_t, void *, void *, int);
332 
333 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
334 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
335 static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
336 static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
337 static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
338 static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
339 static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
340 
341 static uint64_t uma_zone_get_allocs(uma_zone_t zone);
342 
343 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
344     "Memory allocation debugging");
345 
346 #ifdef INVARIANTS
347 static uint64_t uma_keg_get_allocs(uma_keg_t zone);
348 static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
349 
350 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
351 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
352 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
353 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
354 
355 static u_int dbg_divisor = 1;
356 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
357     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
358     "Debug & thrash every this item in memory allocator");
359 
360 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
361 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
362 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
363     &uma_dbg_cnt, "memory items debugged");
364 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
365     &uma_skip_cnt, "memory items skipped, not debugged");
366 #endif
367 
368 SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
369     "Universal Memory Allocator");
370 
371 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
372     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
373 
374 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
375     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
376 
377 static int zone_warnings = 1;
378 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
379     "Warn when UMA zones becomes full");
380 
381 static int multipage_slabs = 1;
382 TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
383 SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
384     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
385     "UMA may choose larger slab sizes for better efficiency");
386 
387 /*
388  * Select the slab zone for an offpage slab with the given maximum item count.
389  */
390 static inline uma_zone_t
391 slabzone(int ipers)
392 {
393 
394 	return (slabzones[ipers > SLABZONE0_SETSIZE]);
395 }
396 
397 /*
398  * This routine checks to see whether or not it's safe to enable buckets.
399  */
400 static void
401 bucket_enable(void)
402 {
403 
404 	KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
405 	bucketdisable = vm_page_count_min();
406 }
407 
408 /*
409  * Initialize bucket_zones, the array of zones of buckets of various sizes.
410  *
411  * For each zone, calculate the memory required for each bucket, consisting
412  * of the header and an array of pointers.
413  */
414 static void
415 bucket_init(void)
416 {
417 	struct uma_bucket_zone *ubz;
418 	int size;
419 
420 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
421 		size = roundup(sizeof(struct uma_bucket), sizeof(void *));
422 		size += sizeof(void *) * ubz->ubz_entries;
423 		ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
424 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
425 		    UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
426 		    UMA_ZONE_FIRSTTOUCH);
427 	}
428 }
429 
430 /*
431  * Given a desired number of entries for a bucket, return the zone from which
432  * to allocate the bucket.
433  */
434 static struct uma_bucket_zone *
435 bucket_zone_lookup(int entries)
436 {
437 	struct uma_bucket_zone *ubz;
438 
439 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
440 		if (ubz->ubz_entries >= entries)
441 			return (ubz);
442 	ubz--;
443 	return (ubz);
444 }
445 
446 static int
447 bucket_select(int size)
448 {
449 	struct uma_bucket_zone *ubz;
450 
451 	ubz = &bucket_zones[0];
452 	if (size > ubz->ubz_maxsize)
453 		return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
454 
455 	for (; ubz->ubz_entries != 0; ubz++)
456 		if (ubz->ubz_maxsize < size)
457 			break;
458 	ubz--;
459 	return (ubz->ubz_entries);
460 }
461 
462 static uma_bucket_t
463 bucket_alloc(uma_zone_t zone, void *udata, int flags)
464 {
465 	struct uma_bucket_zone *ubz;
466 	uma_bucket_t bucket;
467 
468 	/*
469 	 * Don't allocate buckets early in boot.
470 	 */
471 	if (__predict_false(booted < BOOT_KVA))
472 		return (NULL);
473 
474 	/*
475 	 * To limit bucket recursion we store the original zone flags
476 	 * in a cookie passed via zalloc_arg/zfree_arg.  This allows the
477 	 * NOVM flag to persist even through deep recursions.  We also
478 	 * store ZFLAG_BUCKET once we have recursed attempting to allocate
479 	 * a bucket for a bucket zone so we do not allow infinite bucket
480 	 * recursion.  This cookie will even persist to frees of unused
481 	 * buckets via the allocation path or bucket allocations in the
482 	 * free path.
483 	 */
484 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
485 		udata = (void *)(uintptr_t)zone->uz_flags;
486 	else {
487 		if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
488 			return (NULL);
489 		udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
490 	}
491 	if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
492 		flags |= M_NOVM;
493 	ubz = bucket_zone_lookup(atomic_load_16(&zone->uz_bucket_size));
494 	if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
495 		ubz++;
496 	bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
497 	if (bucket) {
498 #ifdef INVARIANTS
499 		bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
500 #endif
501 		bucket->ub_cnt = 0;
502 		bucket->ub_entries = min(ubz->ubz_entries,
503 		    zone->uz_bucket_size_max);
504 		bucket->ub_seq = SMR_SEQ_INVALID;
505 		CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
506 		    zone->uz_name, zone, bucket);
507 	}
508 
509 	return (bucket);
510 }
511 
512 static void
513 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
514 {
515 	struct uma_bucket_zone *ubz;
516 
517 	if (bucket->ub_cnt != 0)
518 		bucket_drain(zone, bucket);
519 
520 	KASSERT(bucket->ub_cnt == 0,
521 	    ("bucket_free: Freeing a non free bucket."));
522 	KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
523 	    ("bucket_free: Freeing an SMR bucket."));
524 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
525 		udata = (void *)(uintptr_t)zone->uz_flags;
526 	ubz = bucket_zone_lookup(bucket->ub_entries);
527 	uma_zfree_arg(ubz->ubz_zone, bucket, udata);
528 }
529 
530 static void
531 bucket_zone_drain(int domain)
532 {
533 	struct uma_bucket_zone *ubz;
534 
535 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
536 		uma_zone_reclaim_domain(ubz->ubz_zone, UMA_RECLAIM_DRAIN,
537 		    domain);
538 }
539 
540 #ifdef KASAN
541 static void
542 kasan_mark_item_valid(uma_zone_t zone, void *item)
543 {
544 	void *pcpu_item;
545 	size_t sz, rsz;
546 	int i;
547 
548 	if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
549 		return;
550 
551 	sz = zone->uz_size;
552 	rsz = roundup2(sz, KASAN_SHADOW_SCALE);
553 	if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
554 		kasan_mark(item, sz, rsz, 0);
555 	} else {
556 		pcpu_item = zpcpu_base_to_offset(item);
557 		for (i = 0; i <= mp_maxid; i++)
558 			kasan_mark(zpcpu_get_cpu(pcpu_item, i), sz, rsz, 0);
559 	}
560 }
561 
562 static void
563 kasan_mark_item_invalid(uma_zone_t zone, void *item)
564 {
565 	void *pcpu_item;
566 	size_t sz;
567 	int i;
568 
569 	if ((zone->uz_flags & UMA_ZONE_NOKASAN) != 0)
570 		return;
571 
572 	sz = roundup2(zone->uz_size, KASAN_SHADOW_SCALE);
573 	if ((zone->uz_flags & UMA_ZONE_PCPU) == 0) {
574 		kasan_mark(item, 0, sz, KASAN_UMA_FREED);
575 	} else {
576 		pcpu_item = zpcpu_base_to_offset(item);
577 		for (i = 0; i <= mp_maxid; i++)
578 			kasan_mark(zpcpu_get_cpu(pcpu_item, i), 0, sz, 0);
579 	}
580 }
581 
582 static void
583 kasan_mark_slab_valid(uma_keg_t keg, void *mem)
584 {
585 	size_t sz;
586 
587 	if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
588 		sz = keg->uk_ppera * PAGE_SIZE;
589 		kasan_mark(mem, sz, sz, 0);
590 	}
591 }
592 
593 static void
594 kasan_mark_slab_invalid(uma_keg_t keg, void *mem)
595 {
596 	size_t sz;
597 
598 	if ((keg->uk_flags & UMA_ZONE_NOKASAN) == 0) {
599 		if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
600 			sz = keg->uk_ppera * PAGE_SIZE;
601 		else
602 			sz = keg->uk_pgoff;
603 		kasan_mark(mem, 0, sz, KASAN_UMA_FREED);
604 	}
605 }
606 #else /* !KASAN */
607 static void
608 kasan_mark_item_valid(uma_zone_t zone __unused, void *item __unused)
609 {
610 }
611 
612 static void
613 kasan_mark_item_invalid(uma_zone_t zone __unused, void *item __unused)
614 {
615 }
616 
617 static void
618 kasan_mark_slab_valid(uma_keg_t keg __unused, void *mem __unused)
619 {
620 }
621 
622 static void
623 kasan_mark_slab_invalid(uma_keg_t keg __unused, void *mem __unused)
624 {
625 }
626 #endif /* KASAN */
627 
628 /*
629  * Acquire the domain lock and record contention.
630  */
631 static uma_zone_domain_t
632 zone_domain_lock(uma_zone_t zone, int domain)
633 {
634 	uma_zone_domain_t zdom;
635 	bool lockfail;
636 
637 	zdom = ZDOM_GET(zone, domain);
638 	lockfail = false;
639 	if (ZDOM_OWNED(zdom))
640 		lockfail = true;
641 	ZDOM_LOCK(zdom);
642 	/* This is unsynchronized.  The counter does not need to be precise. */
643 	if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
644 		zone->uz_bucket_size++;
645 	return (zdom);
646 }
647 
648 /*
649  * Search for the domain with the least cached items and return it if it
650  * is out of balance with the preferred domain.
651  */
652 static __noinline int
653 zone_domain_lowest(uma_zone_t zone, int pref)
654 {
655 	long least, nitems, prefitems;
656 	int domain;
657 	int i;
658 
659 	prefitems = least = LONG_MAX;
660 	domain = 0;
661 	for (i = 0; i < vm_ndomains; i++) {
662 		nitems = ZDOM_GET(zone, i)->uzd_nitems;
663 		if (nitems < least) {
664 			domain = i;
665 			least = nitems;
666 		}
667 		if (domain == pref)
668 			prefitems = nitems;
669 	}
670 	if (prefitems < least * 2)
671 		return (pref);
672 
673 	return (domain);
674 }
675 
676 /*
677  * Search for the domain with the most cached items and return it or the
678  * preferred domain if it has enough to proceed.
679  */
680 static __noinline int
681 zone_domain_highest(uma_zone_t zone, int pref)
682 {
683 	long most, nitems;
684 	int domain;
685 	int i;
686 
687 	if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
688 		return (pref);
689 
690 	most = 0;
691 	domain = 0;
692 	for (i = 0; i < vm_ndomains; i++) {
693 		nitems = ZDOM_GET(zone, i)->uzd_nitems;
694 		if (nitems > most) {
695 			domain = i;
696 			most = nitems;
697 		}
698 	}
699 
700 	return (domain);
701 }
702 
703 /*
704  * Safely subtract cnt from imax.
705  */
706 static void
707 zone_domain_imax_sub(uma_zone_domain_t zdom, int cnt)
708 {
709 	long new;
710 	long old;
711 
712 	old = zdom->uzd_imax;
713 	do {
714 		if (old <= cnt)
715 			new = 0;
716 		else
717 			new = old - cnt;
718 	} while (atomic_fcmpset_long(&zdom->uzd_imax, &old, new) == 0);
719 }
720 
721 /*
722  * Set the maximum imax value.
723  */
724 static void
725 zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
726 {
727 	long old;
728 
729 	old = zdom->uzd_imax;
730 	do {
731 		if (old >= nitems)
732 			break;
733 	} while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
734 }
735 
736 /*
737  * Attempt to satisfy an allocation by retrieving a full bucket from one of the
738  * zone's caches.  If a bucket is found the zone is not locked on return.
739  */
740 static uma_bucket_t
741 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
742 {
743 	uma_bucket_t bucket;
744 	int i;
745 	bool dtor = false;
746 
747 	ZDOM_LOCK_ASSERT(zdom);
748 
749 	if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
750 		return (NULL);
751 
752 	/* SMR Buckets can not be re-used until readers expire. */
753 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
754 	    bucket->ub_seq != SMR_SEQ_INVALID) {
755 		if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
756 			return (NULL);
757 		bucket->ub_seq = SMR_SEQ_INVALID;
758 		dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
759 		if (STAILQ_NEXT(bucket, ub_link) != NULL)
760 			zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
761 	}
762 	STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
763 
764 	KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
765 	    ("%s: item count underflow (%ld, %d)",
766 	    __func__, zdom->uzd_nitems, bucket->ub_cnt));
767 	KASSERT(bucket->ub_cnt > 0,
768 	    ("%s: empty bucket in bucket cache", __func__));
769 	zdom->uzd_nitems -= bucket->ub_cnt;
770 
771 	/*
772 	 * Shift the bounds of the current WSS interval to avoid
773 	 * perturbing the estimate.
774 	 */
775 	if (reclaim) {
776 		zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
777 		zone_domain_imax_sub(zdom, bucket->ub_cnt);
778 	} else if (zdom->uzd_imin > zdom->uzd_nitems)
779 		zdom->uzd_imin = zdom->uzd_nitems;
780 
781 	ZDOM_UNLOCK(zdom);
782 	if (dtor)
783 		for (i = 0; i < bucket->ub_cnt; i++)
784 			item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
785 			    NULL, SKIP_NONE);
786 
787 	return (bucket);
788 }
789 
790 /*
791  * Insert a full bucket into the specified cache.  The "ws" parameter indicates
792  * whether the bucket's contents should be counted as part of the zone's working
793  * set.  The bucket may be freed if it exceeds the bucket limit.
794  */
795 static void
796 zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
797     const bool ws)
798 {
799 	uma_zone_domain_t zdom;
800 
801 	/* We don't cache empty buckets.  This can happen after a reclaim. */
802 	if (bucket->ub_cnt == 0)
803 		goto out;
804 	zdom = zone_domain_lock(zone, domain);
805 
806 	/*
807 	 * Conditionally set the maximum number of items.
808 	 */
809 	zdom->uzd_nitems += bucket->ub_cnt;
810 	if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
811 		if (ws)
812 			zone_domain_imax_set(zdom, zdom->uzd_nitems);
813 		if (STAILQ_EMPTY(&zdom->uzd_buckets))
814 			zdom->uzd_seq = bucket->ub_seq;
815 
816 		/*
817 		 * Try to promote reuse of recently used items.  For items
818 		 * protected by SMR, try to defer reuse to minimize polling.
819 		 */
820 		if (bucket->ub_seq == SMR_SEQ_INVALID)
821 			STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
822 		else
823 			STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
824 		ZDOM_UNLOCK(zdom);
825 		return;
826 	}
827 	zdom->uzd_nitems -= bucket->ub_cnt;
828 	ZDOM_UNLOCK(zdom);
829 out:
830 	bucket_free(zone, bucket, udata);
831 }
832 
833 /* Pops an item out of a per-cpu cache bucket. */
834 static inline void *
835 cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
836 {
837 	void *item;
838 
839 	CRITICAL_ASSERT(curthread);
840 
841 	bucket->ucb_cnt--;
842 	item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
843 #ifdef INVARIANTS
844 	bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
845 	KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
846 #endif
847 	cache->uc_allocs++;
848 
849 	return (item);
850 }
851 
852 /* Pushes an item into a per-cpu cache bucket. */
853 static inline void
854 cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
855 {
856 
857 	CRITICAL_ASSERT(curthread);
858 	KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
859 	    ("uma_zfree: Freeing to non free bucket index."));
860 
861 	bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
862 	bucket->ucb_cnt++;
863 	cache->uc_frees++;
864 }
865 
866 /*
867  * Unload a UMA bucket from a per-cpu cache.
868  */
869 static inline uma_bucket_t
870 cache_bucket_unload(uma_cache_bucket_t bucket)
871 {
872 	uma_bucket_t b;
873 
874 	b = bucket->ucb_bucket;
875 	if (b != NULL) {
876 		MPASS(b->ub_entries == bucket->ucb_entries);
877 		b->ub_cnt = bucket->ucb_cnt;
878 		bucket->ucb_bucket = NULL;
879 		bucket->ucb_entries = bucket->ucb_cnt = 0;
880 	}
881 
882 	return (b);
883 }
884 
885 static inline uma_bucket_t
886 cache_bucket_unload_alloc(uma_cache_t cache)
887 {
888 
889 	return (cache_bucket_unload(&cache->uc_allocbucket));
890 }
891 
892 static inline uma_bucket_t
893 cache_bucket_unload_free(uma_cache_t cache)
894 {
895 
896 	return (cache_bucket_unload(&cache->uc_freebucket));
897 }
898 
899 static inline uma_bucket_t
900 cache_bucket_unload_cross(uma_cache_t cache)
901 {
902 
903 	return (cache_bucket_unload(&cache->uc_crossbucket));
904 }
905 
906 /*
907  * Load a bucket into a per-cpu cache bucket.
908  */
909 static inline void
910 cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
911 {
912 
913 	CRITICAL_ASSERT(curthread);
914 	MPASS(bucket->ucb_bucket == NULL);
915 	MPASS(b->ub_seq == SMR_SEQ_INVALID);
916 
917 	bucket->ucb_bucket = b;
918 	bucket->ucb_cnt = b->ub_cnt;
919 	bucket->ucb_entries = b->ub_entries;
920 }
921 
922 static inline void
923 cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
924 {
925 
926 	cache_bucket_load(&cache->uc_allocbucket, b);
927 }
928 
929 static inline void
930 cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
931 {
932 
933 	cache_bucket_load(&cache->uc_freebucket, b);
934 }
935 
936 #ifdef NUMA
937 static inline void
938 cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
939 {
940 
941 	cache_bucket_load(&cache->uc_crossbucket, b);
942 }
943 #endif
944 
945 /*
946  * Copy and preserve ucb_spare.
947  */
948 static inline void
949 cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
950 {
951 
952 	b1->ucb_bucket = b2->ucb_bucket;
953 	b1->ucb_entries = b2->ucb_entries;
954 	b1->ucb_cnt = b2->ucb_cnt;
955 }
956 
957 /*
958  * Swap two cache buckets.
959  */
960 static inline void
961 cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
962 {
963 	struct uma_cache_bucket b3;
964 
965 	CRITICAL_ASSERT(curthread);
966 
967 	cache_bucket_copy(&b3, b1);
968 	cache_bucket_copy(b1, b2);
969 	cache_bucket_copy(b2, &b3);
970 }
971 
972 /*
973  * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
974  */
975 static uma_bucket_t
976 cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
977 {
978 	uma_zone_domain_t zdom;
979 	uma_bucket_t bucket;
980 
981 	/*
982 	 * Avoid the lock if possible.
983 	 */
984 	zdom = ZDOM_GET(zone, domain);
985 	if (zdom->uzd_nitems == 0)
986 		return (NULL);
987 
988 	if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
989 	    !smr_poll(zone->uz_smr, zdom->uzd_seq, false))
990 		return (NULL);
991 
992 	/*
993 	 * Check the zone's cache of buckets.
994 	 */
995 	zdom = zone_domain_lock(zone, domain);
996 	if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
997 		return (bucket);
998 	ZDOM_UNLOCK(zdom);
999 
1000 	return (NULL);
1001 }
1002 
1003 static void
1004 zone_log_warning(uma_zone_t zone)
1005 {
1006 	static const struct timeval warninterval = { 300, 0 };
1007 
1008 	if (!zone_warnings || zone->uz_warning == NULL)
1009 		return;
1010 
1011 	if (ratecheck(&zone->uz_ratecheck, &warninterval))
1012 		printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
1013 }
1014 
1015 static inline void
1016 zone_maxaction(uma_zone_t zone)
1017 {
1018 
1019 	if (zone->uz_maxaction.ta_func != NULL)
1020 		taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
1021 }
1022 
1023 /*
1024  * Routine called by timeout which is used to fire off some time interval
1025  * based calculations.  (stats, hash size, etc.)
1026  *
1027  * Arguments:
1028  *	arg   Unused
1029  *
1030  * Returns:
1031  *	Nothing
1032  */
1033 static void
1034 uma_timeout(void *unused)
1035 {
1036 	bucket_enable();
1037 	zone_foreach(zone_timeout, NULL);
1038 
1039 	/* Reschedule this event */
1040 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1041 }
1042 
1043 /*
1044  * Update the working set size estimate for the zone's bucket cache.
1045  * The constants chosen here are somewhat arbitrary.  With an update period of
1046  * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
1047  * last 100s.
1048  */
1049 static void
1050 zone_domain_update_wss(uma_zone_domain_t zdom)
1051 {
1052 	long wss;
1053 
1054 	ZDOM_LOCK(zdom);
1055 	MPASS(zdom->uzd_imax >= zdom->uzd_imin);
1056 	wss = zdom->uzd_imax - zdom->uzd_imin;
1057 	zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
1058 	zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
1059 	ZDOM_UNLOCK(zdom);
1060 }
1061 
1062 /*
1063  * Routine to perform timeout driven calculations.  This expands the
1064  * hashes and does per cpu statistics aggregation.
1065  *
1066  *  Returns nothing.
1067  */
1068 static void
1069 zone_timeout(uma_zone_t zone, void *unused)
1070 {
1071 	uma_keg_t keg;
1072 	u_int slabs, pages;
1073 
1074 	if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
1075 		goto update_wss;
1076 
1077 	keg = zone->uz_keg;
1078 
1079 	/*
1080 	 * Hash zones are non-numa by definition so the first domain
1081 	 * is the only one present.
1082 	 */
1083 	KEG_LOCK(keg, 0);
1084 	pages = keg->uk_domain[0].ud_pages;
1085 
1086 	/*
1087 	 * Expand the keg hash table.
1088 	 *
1089 	 * This is done if the number of slabs is larger than the hash size.
1090 	 * What I'm trying to do here is completely reduce collisions.  This
1091 	 * may be a little aggressive.  Should I allow for two collisions max?
1092 	 */
1093 	if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
1094 		struct uma_hash newhash;
1095 		struct uma_hash oldhash;
1096 		int ret;
1097 
1098 		/*
1099 		 * This is so involved because allocating and freeing
1100 		 * while the keg lock is held will lead to deadlock.
1101 		 * I have to do everything in stages and check for
1102 		 * races.
1103 		 */
1104 		KEG_UNLOCK(keg, 0);
1105 		ret = hash_alloc(&newhash, 1 << fls(slabs));
1106 		KEG_LOCK(keg, 0);
1107 		if (ret) {
1108 			if (hash_expand(&keg->uk_hash, &newhash)) {
1109 				oldhash = keg->uk_hash;
1110 				keg->uk_hash = newhash;
1111 			} else
1112 				oldhash = newhash;
1113 
1114 			KEG_UNLOCK(keg, 0);
1115 			hash_free(&oldhash);
1116 			goto update_wss;
1117 		}
1118 	}
1119 	KEG_UNLOCK(keg, 0);
1120 
1121 update_wss:
1122 	for (int i = 0; i < vm_ndomains; i++)
1123 		zone_domain_update_wss(ZDOM_GET(zone, i));
1124 }
1125 
1126 /*
1127  * Allocate and zero fill the next sized hash table from the appropriate
1128  * backing store.
1129  *
1130  * Arguments:
1131  *	hash  A new hash structure with the old hash size in uh_hashsize
1132  *
1133  * Returns:
1134  *	1 on success and 0 on failure.
1135  */
1136 static int
1137 hash_alloc(struct uma_hash *hash, u_int size)
1138 {
1139 	size_t alloc;
1140 
1141 	KASSERT(powerof2(size), ("hash size must be power of 2"));
1142 	if (size > UMA_HASH_SIZE_INIT)  {
1143 		hash->uh_hashsize = size;
1144 		alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
1145 		hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
1146 	} else {
1147 		alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
1148 		hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
1149 		    UMA_ANYDOMAIN, M_WAITOK);
1150 		hash->uh_hashsize = UMA_HASH_SIZE_INIT;
1151 	}
1152 	if (hash->uh_slab_hash) {
1153 		bzero(hash->uh_slab_hash, alloc);
1154 		hash->uh_hashmask = hash->uh_hashsize - 1;
1155 		return (1);
1156 	}
1157 
1158 	return (0);
1159 }
1160 
1161 /*
1162  * Expands the hash table for HASH zones.  This is done from zone_timeout
1163  * to reduce collisions.  This must not be done in the regular allocation
1164  * path, otherwise, we can recurse on the vm while allocating pages.
1165  *
1166  * Arguments:
1167  *	oldhash  The hash you want to expand
1168  *	newhash  The hash structure for the new table
1169  *
1170  * Returns:
1171  *	Nothing
1172  *
1173  * Discussion:
1174  */
1175 static int
1176 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
1177 {
1178 	uma_hash_slab_t slab;
1179 	u_int hval;
1180 	u_int idx;
1181 
1182 	if (!newhash->uh_slab_hash)
1183 		return (0);
1184 
1185 	if (oldhash->uh_hashsize >= newhash->uh_hashsize)
1186 		return (0);
1187 
1188 	/*
1189 	 * I need to investigate hash algorithms for resizing without a
1190 	 * full rehash.
1191 	 */
1192 
1193 	for (idx = 0; idx < oldhash->uh_hashsize; idx++)
1194 		while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
1195 			slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
1196 			LIST_REMOVE(slab, uhs_hlink);
1197 			hval = UMA_HASH(newhash, slab->uhs_data);
1198 			LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
1199 			    slab, uhs_hlink);
1200 		}
1201 
1202 	return (1);
1203 }
1204 
1205 /*
1206  * Free the hash bucket to the appropriate backing store.
1207  *
1208  * Arguments:
1209  *	slab_hash  The hash bucket we're freeing
1210  *	hashsize   The number of entries in that hash bucket
1211  *
1212  * Returns:
1213  *	Nothing
1214  */
1215 static void
1216 hash_free(struct uma_hash *hash)
1217 {
1218 	if (hash->uh_slab_hash == NULL)
1219 		return;
1220 	if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
1221 		zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
1222 	else
1223 		free(hash->uh_slab_hash, M_UMAHASH);
1224 }
1225 
1226 /*
1227  * Frees all outstanding items in a bucket
1228  *
1229  * Arguments:
1230  *	zone   The zone to free to, must be unlocked.
1231  *	bucket The free/alloc bucket with items.
1232  *
1233  * Returns:
1234  *	Nothing
1235  */
1236 static void
1237 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
1238 {
1239 	int i;
1240 
1241 	if (bucket->ub_cnt == 0)
1242 		return;
1243 
1244 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
1245 	    bucket->ub_seq != SMR_SEQ_INVALID) {
1246 		smr_wait(zone->uz_smr, bucket->ub_seq);
1247 		bucket->ub_seq = SMR_SEQ_INVALID;
1248 		for (i = 0; i < bucket->ub_cnt; i++)
1249 			item_dtor(zone, bucket->ub_bucket[i],
1250 			    zone->uz_size, NULL, SKIP_NONE);
1251 	}
1252 	if (zone->uz_fini)
1253 		for (i = 0; i < bucket->ub_cnt; i++) {
1254 			kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
1255 			zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
1256 			kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
1257 		}
1258 	zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
1259 	if (zone->uz_max_items > 0)
1260 		zone_free_limit(zone, bucket->ub_cnt);
1261 #ifdef INVARIANTS
1262 	bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
1263 #endif
1264 	bucket->ub_cnt = 0;
1265 }
1266 
1267 /*
1268  * Drains the per cpu caches for a zone.
1269  *
1270  * NOTE: This may only be called while the zone is being torn down, and not
1271  * during normal operation.  This is necessary in order that we do not have
1272  * to migrate CPUs to drain the per-CPU caches.
1273  *
1274  * Arguments:
1275  *	zone     The zone to drain, must be unlocked.
1276  *
1277  * Returns:
1278  *	Nothing
1279  */
1280 static void
1281 cache_drain(uma_zone_t zone)
1282 {
1283 	uma_cache_t cache;
1284 	uma_bucket_t bucket;
1285 	smr_seq_t seq;
1286 	int cpu;
1287 
1288 	/*
1289 	 * XXX: It is safe to not lock the per-CPU caches, because we're
1290 	 * tearing down the zone anyway.  I.e., there will be no further use
1291 	 * of the caches at this point.
1292 	 *
1293 	 * XXX: It would good to be able to assert that the zone is being
1294 	 * torn down to prevent improper use of cache_drain().
1295 	 */
1296 	seq = SMR_SEQ_INVALID;
1297 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
1298 		seq = smr_advance(zone->uz_smr);
1299 	CPU_FOREACH(cpu) {
1300 		cache = &zone->uz_cpu[cpu];
1301 		bucket = cache_bucket_unload_alloc(cache);
1302 		if (bucket != NULL)
1303 			bucket_free(zone, bucket, NULL);
1304 		bucket = cache_bucket_unload_free(cache);
1305 		if (bucket != NULL) {
1306 			bucket->ub_seq = seq;
1307 			bucket_free(zone, bucket, NULL);
1308 		}
1309 		bucket = cache_bucket_unload_cross(cache);
1310 		if (bucket != NULL) {
1311 			bucket->ub_seq = seq;
1312 			bucket_free(zone, bucket, NULL);
1313 		}
1314 	}
1315 	bucket_cache_reclaim(zone, true, UMA_ANYDOMAIN);
1316 }
1317 
1318 static void
1319 cache_shrink(uma_zone_t zone, void *unused)
1320 {
1321 
1322 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1323 		return;
1324 
1325 	ZONE_LOCK(zone);
1326 	zone->uz_bucket_size =
1327 	    (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
1328 	ZONE_UNLOCK(zone);
1329 }
1330 
1331 static void
1332 cache_drain_safe_cpu(uma_zone_t zone, void *unused)
1333 {
1334 	uma_cache_t cache;
1335 	uma_bucket_t b1, b2, b3;
1336 	int domain;
1337 
1338 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1339 		return;
1340 
1341 	b1 = b2 = b3 = NULL;
1342 	critical_enter();
1343 	cache = &zone->uz_cpu[curcpu];
1344 	domain = PCPU_GET(domain);
1345 	b1 = cache_bucket_unload_alloc(cache);
1346 
1347 	/*
1348 	 * Don't flush SMR zone buckets.  This leaves the zone without a
1349 	 * bucket and forces every free to synchronize().
1350 	 */
1351 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
1352 		b2 = cache_bucket_unload_free(cache);
1353 		b3 = cache_bucket_unload_cross(cache);
1354 	}
1355 	critical_exit();
1356 
1357 	if (b1 != NULL)
1358 		zone_free_bucket(zone, b1, NULL, domain, false);
1359 	if (b2 != NULL)
1360 		zone_free_bucket(zone, b2, NULL, domain, false);
1361 	if (b3 != NULL) {
1362 		/* Adjust the domain so it goes to zone_free_cross. */
1363 		domain = (domain + 1) % vm_ndomains;
1364 		zone_free_bucket(zone, b3, NULL, domain, false);
1365 	}
1366 }
1367 
1368 /*
1369  * Safely drain per-CPU caches of a zone(s) to alloc bucket.
1370  * This is an expensive call because it needs to bind to all CPUs
1371  * one by one and enter a critical section on each of them in order
1372  * to safely access their cache buckets.
1373  * Zone lock must not be held on call this function.
1374  */
1375 static void
1376 pcpu_cache_drain_safe(uma_zone_t zone)
1377 {
1378 	int cpu;
1379 
1380 	/*
1381 	 * Polite bucket sizes shrinking was not enough, shrink aggressively.
1382 	 */
1383 	if (zone)
1384 		cache_shrink(zone, NULL);
1385 	else
1386 		zone_foreach(cache_shrink, NULL);
1387 
1388 	CPU_FOREACH(cpu) {
1389 		thread_lock(curthread);
1390 		sched_bind(curthread, cpu);
1391 		thread_unlock(curthread);
1392 
1393 		if (zone)
1394 			cache_drain_safe_cpu(zone, NULL);
1395 		else
1396 			zone_foreach(cache_drain_safe_cpu, NULL);
1397 	}
1398 	thread_lock(curthread);
1399 	sched_unbind(curthread);
1400 	thread_unlock(curthread);
1401 }
1402 
1403 /*
1404  * Reclaim cached buckets from a zone.  All buckets are reclaimed if the caller
1405  * requested a drain, otherwise the per-domain caches are trimmed to either
1406  * estimated working set size.
1407  */
1408 static void
1409 bucket_cache_reclaim_domain(uma_zone_t zone, bool drain, int domain)
1410 {
1411 	uma_zone_domain_t zdom;
1412 	uma_bucket_t bucket;
1413 	long target;
1414 
1415 	/*
1416 	 * The cross bucket is partially filled and not part of
1417 	 * the item count.  Reclaim it individually here.
1418 	 */
1419 	zdom = ZDOM_GET(zone, domain);
1420 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
1421 		ZONE_CROSS_LOCK(zone);
1422 		bucket = zdom->uzd_cross;
1423 		zdom->uzd_cross = NULL;
1424 		ZONE_CROSS_UNLOCK(zone);
1425 		if (bucket != NULL)
1426 			bucket_free(zone, bucket, NULL);
1427 	}
1428 
1429 	/*
1430 	 * If we were asked to drain the zone, we are done only once
1431 	 * this bucket cache is empty.  Otherwise, we reclaim items in
1432 	 * excess of the zone's estimated working set size.  If the
1433 	 * difference nitems - imin is larger than the WSS estimate,
1434 	 * then the estimate will grow at the end of this interval and
1435 	 * we ignore the historical average.
1436 	 */
1437 	ZDOM_LOCK(zdom);
1438 	target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
1439 	    zdom->uzd_imin);
1440 	while (zdom->uzd_nitems > target) {
1441 		bucket = zone_fetch_bucket(zone, zdom, true);
1442 		if (bucket == NULL)
1443 			break;
1444 		bucket_free(zone, bucket, NULL);
1445 		ZDOM_LOCK(zdom);
1446 	}
1447 	ZDOM_UNLOCK(zdom);
1448 }
1449 
1450 static void
1451 bucket_cache_reclaim(uma_zone_t zone, bool drain, int domain)
1452 {
1453 	int i;
1454 
1455 	/*
1456 	 * Shrink the zone bucket size to ensure that the per-CPU caches
1457 	 * don't grow too large.
1458 	 */
1459 	if (zone->uz_bucket_size > zone->uz_bucket_size_min)
1460 		zone->uz_bucket_size--;
1461 
1462 	if (domain != UMA_ANYDOMAIN &&
1463 	    (zone->uz_flags & UMA_ZONE_ROUNDROBIN) == 0) {
1464 		bucket_cache_reclaim_domain(zone, drain, domain);
1465 	} else {
1466 		for (i = 0; i < vm_ndomains; i++)
1467 			bucket_cache_reclaim_domain(zone, drain, i);
1468 	}
1469 }
1470 
1471 static void
1472 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
1473 {
1474 	uint8_t *mem;
1475 	size_t size;
1476 	int i;
1477 	uint8_t flags;
1478 
1479 	CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
1480 	    keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
1481 
1482 	mem = slab_data(slab, keg);
1483 	size = PAGE_SIZE * keg->uk_ppera;
1484 
1485 	kasan_mark_slab_valid(keg, mem);
1486 	if (keg->uk_fini != NULL) {
1487 		for (i = start - 1; i > -1; i--)
1488 #ifdef INVARIANTS
1489 		/*
1490 		 * trash_fini implies that dtor was trash_dtor. trash_fini
1491 		 * would check that memory hasn't been modified since free,
1492 		 * which executed trash_dtor.
1493 		 * That's why we need to run uma_dbg_kskip() check here,
1494 		 * albeit we don't make skip check for other init/fini
1495 		 * invocations.
1496 		 */
1497 		if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
1498 		    keg->uk_fini != trash_fini)
1499 #endif
1500 			keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
1501 	}
1502 	flags = slab->us_flags;
1503 	if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1504 		zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
1505 		    NULL, SKIP_NONE);
1506 	}
1507 	keg->uk_freef(mem, size, flags);
1508 	uma_total_dec(size);
1509 }
1510 
1511 static void
1512 keg_drain_domain(uma_keg_t keg, int domain)
1513 {
1514 	struct slabhead freeslabs;
1515 	uma_domain_t dom;
1516 	uma_slab_t slab, tmp;
1517 	uint32_t i, stofree, stokeep, partial;
1518 
1519 	dom = &keg->uk_domain[domain];
1520 	LIST_INIT(&freeslabs);
1521 
1522 	CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1523 	    keg->uk_name, keg, domain, dom->ud_free_items);
1524 
1525 	KEG_LOCK(keg, domain);
1526 
1527 	/*
1528 	 * Are the free items in partially allocated slabs sufficient to meet
1529 	 * the reserve? If not, compute the number of fully free slabs that must
1530 	 * be kept.
1531 	 */
1532 	partial = dom->ud_free_items - dom->ud_free_slabs * keg->uk_ipers;
1533 	if (partial < keg->uk_reserve) {
1534 		stokeep = min(dom->ud_free_slabs,
1535 		    howmany(keg->uk_reserve - partial, keg->uk_ipers));
1536 	} else {
1537 		stokeep = 0;
1538 	}
1539 	stofree = dom->ud_free_slabs - stokeep;
1540 
1541 	/*
1542 	 * Partition the free slabs into two sets: those that must be kept in
1543 	 * order to maintain the reserve, and those that may be released back to
1544 	 * the system.  Since one set may be much larger than the other,
1545 	 * populate the smaller of the two sets and swap them if necessary.
1546 	 */
1547 	for (i = min(stofree, stokeep); i > 0; i--) {
1548 		slab = LIST_FIRST(&dom->ud_free_slab);
1549 		LIST_REMOVE(slab, us_link);
1550 		LIST_INSERT_HEAD(&freeslabs, slab, us_link);
1551 	}
1552 	if (stofree > stokeep)
1553 		LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1554 
1555 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1556 		LIST_FOREACH(slab, &freeslabs, us_link)
1557 			UMA_HASH_REMOVE(&keg->uk_hash, slab);
1558 	}
1559 	dom->ud_free_items -= stofree * keg->uk_ipers;
1560 	dom->ud_free_slabs -= stofree;
1561 	dom->ud_pages -= stofree * keg->uk_ppera;
1562 	KEG_UNLOCK(keg, domain);
1563 
1564 	LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1565 		keg_free_slab(keg, slab, keg->uk_ipers);
1566 }
1567 
1568 /*
1569  * Frees pages from a keg back to the system.  This is done on demand from
1570  * the pageout daemon.
1571  *
1572  * Returns nothing.
1573  */
1574 static void
1575 keg_drain(uma_keg_t keg, int domain)
1576 {
1577 	int i;
1578 
1579 	if ((keg->uk_flags & UMA_ZONE_NOFREE) != 0)
1580 		return;
1581 	if (domain != UMA_ANYDOMAIN) {
1582 		keg_drain_domain(keg, domain);
1583 	} else {
1584 		for (i = 0; i < vm_ndomains; i++)
1585 			keg_drain_domain(keg, i);
1586 	}
1587 }
1588 
1589 static void
1590 zone_reclaim(uma_zone_t zone, int domain, int waitok, bool drain)
1591 {
1592 	/*
1593 	 * Count active reclaim operations in order to interlock with
1594 	 * zone_dtor(), which removes the zone from global lists before
1595 	 * attempting to reclaim items itself.
1596 	 *
1597 	 * The zone may be destroyed while sleeping, so only zone_dtor() should
1598 	 * specify M_WAITOK.
1599 	 */
1600 	ZONE_LOCK(zone);
1601 	if (waitok == M_WAITOK) {
1602 		while (zone->uz_reclaimers > 0)
1603 			msleep(zone, ZONE_LOCKPTR(zone), PVM, "zonedrain", 1);
1604 	}
1605 	zone->uz_reclaimers++;
1606 	ZONE_UNLOCK(zone);
1607 	bucket_cache_reclaim(zone, drain, domain);
1608 
1609 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1610 		keg_drain(zone->uz_keg, domain);
1611 	ZONE_LOCK(zone);
1612 	zone->uz_reclaimers--;
1613 	if (zone->uz_reclaimers == 0)
1614 		wakeup(zone);
1615 	ZONE_UNLOCK(zone);
1616 }
1617 
1618 static void
1619 zone_drain(uma_zone_t zone, void *arg)
1620 {
1621 	int domain;
1622 
1623 	domain = (int)(uintptr_t)arg;
1624 	zone_reclaim(zone, domain, M_NOWAIT, true);
1625 }
1626 
1627 static void
1628 zone_trim(uma_zone_t zone, void *arg)
1629 {
1630 	int domain;
1631 
1632 	domain = (int)(uintptr_t)arg;
1633 	zone_reclaim(zone, domain, M_NOWAIT, false);
1634 }
1635 
1636 /*
1637  * Allocate a new slab for a keg and inserts it into the partial slab list.
1638  * The keg should be unlocked on entry.  If the allocation succeeds it will
1639  * be locked on return.
1640  *
1641  * Arguments:
1642  *	flags   Wait flags for the item initialization routine
1643  *	aflags  Wait flags for the slab allocation
1644  *
1645  * Returns:
1646  *	The slab that was allocated or NULL if there is no memory and the
1647  *	caller specified M_NOWAIT.
1648  */
1649 static uma_slab_t
1650 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1651     int aflags)
1652 {
1653 	uma_domain_t dom;
1654 	uma_slab_t slab;
1655 	unsigned long size;
1656 	uint8_t *mem;
1657 	uint8_t sflags;
1658 	int i;
1659 
1660 	KASSERT(domain >= 0 && domain < vm_ndomains,
1661 	    ("keg_alloc_slab: domain %d out of range", domain));
1662 
1663 	slab = NULL;
1664 	mem = NULL;
1665 	if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1666 		uma_hash_slab_t hslab;
1667 		hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1668 		    domain, aflags);
1669 		if (hslab == NULL)
1670 			goto fail;
1671 		slab = &hslab->uhs_slab;
1672 	}
1673 
1674 	/*
1675 	 * This reproduces the old vm_zone behavior of zero filling pages the
1676 	 * first time they are added to a zone.
1677 	 *
1678 	 * Malloced items are zeroed in uma_zalloc.
1679 	 */
1680 
1681 	if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1682 		aflags |= M_ZERO;
1683 	else
1684 		aflags &= ~M_ZERO;
1685 
1686 	if (keg->uk_flags & UMA_ZONE_NODUMP)
1687 		aflags |= M_NODUMP;
1688 
1689 	/* zone is passed for legacy reasons. */
1690 	size = keg->uk_ppera * PAGE_SIZE;
1691 	mem = keg->uk_allocf(zone, size, domain, &sflags, aflags);
1692 	if (mem == NULL) {
1693 		if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1694 			zone_free_item(slabzone(keg->uk_ipers),
1695 			    slab_tohashslab(slab), NULL, SKIP_NONE);
1696 		goto fail;
1697 	}
1698 	uma_total_inc(size);
1699 
1700 	/* For HASH zones all pages go to the same uma_domain. */
1701 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1702 		domain = 0;
1703 
1704 	/* Point the slab into the allocated memory */
1705 	if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1706 		slab = (uma_slab_t)(mem + keg->uk_pgoff);
1707 	else
1708 		slab_tohashslab(slab)->uhs_data = mem;
1709 
1710 	if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1711 		for (i = 0; i < keg->uk_ppera; i++)
1712 			vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1713 			    zone, slab);
1714 
1715 	slab->us_freecount = keg->uk_ipers;
1716 	slab->us_flags = sflags;
1717 	slab->us_domain = domain;
1718 
1719 	BIT_FILL(keg->uk_ipers, &slab->us_free);
1720 #ifdef INVARIANTS
1721 	BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1722 #endif
1723 
1724 	if (keg->uk_init != NULL) {
1725 		for (i = 0; i < keg->uk_ipers; i++)
1726 			if (keg->uk_init(slab_item(slab, keg, i),
1727 			    keg->uk_size, flags) != 0)
1728 				break;
1729 		if (i != keg->uk_ipers) {
1730 			keg_free_slab(keg, slab, i);
1731 			goto fail;
1732 		}
1733 	}
1734 	kasan_mark_slab_invalid(keg, mem);
1735 	KEG_LOCK(keg, domain);
1736 
1737 	CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1738 	    slab, keg->uk_name, keg);
1739 
1740 	if (keg->uk_flags & UMA_ZFLAG_HASH)
1741 		UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1742 
1743 	/*
1744 	 * If we got a slab here it's safe to mark it partially used
1745 	 * and return.  We assume that the caller is going to remove
1746 	 * at least one item.
1747 	 */
1748 	dom = &keg->uk_domain[domain];
1749 	LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1750 	dom->ud_pages += keg->uk_ppera;
1751 	dom->ud_free_items += keg->uk_ipers;
1752 
1753 	return (slab);
1754 
1755 fail:
1756 	return (NULL);
1757 }
1758 
1759 /*
1760  * This function is intended to be used early on in place of page_alloc().  It
1761  * performs contiguous physical memory allocations and uses a bump allocator for
1762  * KVA, so is usable before the kernel map is initialized.
1763  */
1764 static void *
1765 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1766     int wait)
1767 {
1768 	vm_paddr_t pa;
1769 	vm_page_t m;
1770 	void *mem;
1771 	int pages;
1772 	int i;
1773 
1774 	pages = howmany(bytes, PAGE_SIZE);
1775 	KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1776 
1777 	*pflag = UMA_SLAB_BOOT;
1778 	m = vm_page_alloc_contig_domain(NULL, 0, domain,
1779 	    malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages,
1780 	    (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1781 	if (m == NULL)
1782 		return (NULL);
1783 
1784 	pa = VM_PAGE_TO_PHYS(m);
1785 	for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1786 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1787     defined(__riscv) || defined(__powerpc64__)
1788 		if ((wait & M_NODUMP) == 0)
1789 			dump_add_page(pa);
1790 #endif
1791 	}
1792 	/* Allocate KVA and indirectly advance bootmem. */
1793 	mem = (void *)pmap_map(&bootmem, m->phys_addr,
1794 	    m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1795         if ((wait & M_ZERO) != 0)
1796                 bzero(mem, pages * PAGE_SIZE);
1797 
1798         return (mem);
1799 }
1800 
1801 static void
1802 startup_free(void *mem, vm_size_t bytes)
1803 {
1804 	vm_offset_t va;
1805 	vm_page_t m;
1806 
1807 	va = (vm_offset_t)mem;
1808 	m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1809 
1810 	/*
1811 	 * startup_alloc() returns direct-mapped slabs on some platforms.  Avoid
1812 	 * unmapping ranges of the direct map.
1813 	 */
1814 	if (va >= bootstart && va + bytes <= bootmem)
1815 		pmap_remove(kernel_pmap, va, va + bytes);
1816 	for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1817 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1818     defined(__riscv) || defined(__powerpc64__)
1819 		dump_drop_page(VM_PAGE_TO_PHYS(m));
1820 #endif
1821 		vm_page_unwire_noq(m);
1822 		vm_page_free(m);
1823 	}
1824 }
1825 
1826 /*
1827  * Allocates a number of pages from the system
1828  *
1829  * Arguments:
1830  *	bytes  The number of bytes requested
1831  *	wait  Shall we wait?
1832  *
1833  * Returns:
1834  *	A pointer to the alloced memory or possibly
1835  *	NULL if M_NOWAIT is set.
1836  */
1837 static void *
1838 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1839     int wait)
1840 {
1841 	void *p;	/* Returned page */
1842 
1843 	*pflag = UMA_SLAB_KERNEL;
1844 	p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1845 
1846 	return (p);
1847 }
1848 
1849 static void *
1850 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1851     int wait)
1852 {
1853 	struct pglist alloctail;
1854 	vm_offset_t addr, zkva;
1855 	int cpu, flags;
1856 	vm_page_t p, p_next;
1857 #ifdef NUMA
1858 	struct pcpu *pc;
1859 #endif
1860 
1861 	MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1862 
1863 	TAILQ_INIT(&alloctail);
1864 	flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1865 	    malloc2vm_flags(wait);
1866 	*pflag = UMA_SLAB_KERNEL;
1867 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
1868 		if (CPU_ABSENT(cpu)) {
1869 			p = vm_page_alloc(NULL, 0, flags);
1870 		} else {
1871 #ifndef NUMA
1872 			p = vm_page_alloc(NULL, 0, flags);
1873 #else
1874 			pc = pcpu_find(cpu);
1875 			if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1876 				p = NULL;
1877 			else
1878 				p = vm_page_alloc_domain(NULL, 0,
1879 				    pc->pc_domain, flags);
1880 			if (__predict_false(p == NULL))
1881 				p = vm_page_alloc(NULL, 0, flags);
1882 #endif
1883 		}
1884 		if (__predict_false(p == NULL))
1885 			goto fail;
1886 		TAILQ_INSERT_TAIL(&alloctail, p, listq);
1887 	}
1888 	if ((addr = kva_alloc(bytes)) == 0)
1889 		goto fail;
1890 	zkva = addr;
1891 	TAILQ_FOREACH(p, &alloctail, listq) {
1892 		pmap_qenter(zkva, &p, 1);
1893 		zkva += PAGE_SIZE;
1894 	}
1895 	return ((void*)addr);
1896 fail:
1897 	TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1898 		vm_page_unwire_noq(p);
1899 		vm_page_free(p);
1900 	}
1901 	return (NULL);
1902 }
1903 
1904 /*
1905  * Allocates a number of pages from within an object
1906  *
1907  * Arguments:
1908  *	bytes  The number of bytes requested
1909  *	wait   Shall we wait?
1910  *
1911  * Returns:
1912  *	A pointer to the alloced memory or possibly
1913  *	NULL if M_NOWAIT is set.
1914  */
1915 static void *
1916 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1917     int wait)
1918 {
1919 	TAILQ_HEAD(, vm_page) alloctail;
1920 	u_long npages;
1921 	vm_offset_t retkva, zkva;
1922 	vm_page_t p, p_next;
1923 	uma_keg_t keg;
1924 
1925 	TAILQ_INIT(&alloctail);
1926 	keg = zone->uz_keg;
1927 
1928 	npages = howmany(bytes, PAGE_SIZE);
1929 	while (npages > 0) {
1930 		p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1931 		    VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1932 		    ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1933 		    VM_ALLOC_NOWAIT));
1934 		if (p != NULL) {
1935 			/*
1936 			 * Since the page does not belong to an object, its
1937 			 * listq is unused.
1938 			 */
1939 			TAILQ_INSERT_TAIL(&alloctail, p, listq);
1940 			npages--;
1941 			continue;
1942 		}
1943 		/*
1944 		 * Page allocation failed, free intermediate pages and
1945 		 * exit.
1946 		 */
1947 		TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1948 			vm_page_unwire_noq(p);
1949 			vm_page_free(p);
1950 		}
1951 		return (NULL);
1952 	}
1953 	*flags = UMA_SLAB_PRIV;
1954 	zkva = keg->uk_kva +
1955 	    atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1956 	retkva = zkva;
1957 	TAILQ_FOREACH(p, &alloctail, listq) {
1958 		pmap_qenter(zkva, &p, 1);
1959 		zkva += PAGE_SIZE;
1960 	}
1961 
1962 	return ((void *)retkva);
1963 }
1964 
1965 /*
1966  * Allocate physically contiguous pages.
1967  */
1968 static void *
1969 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1970     int wait)
1971 {
1972 
1973 	*pflag = UMA_SLAB_KERNEL;
1974 	return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1975 	    bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1976 }
1977 
1978 /*
1979  * Frees a number of pages to the system
1980  *
1981  * Arguments:
1982  *	mem   A pointer to the memory to be freed
1983  *	size  The size of the memory being freed
1984  *	flags The original p->us_flags field
1985  *
1986  * Returns:
1987  *	Nothing
1988  */
1989 static void
1990 page_free(void *mem, vm_size_t size, uint8_t flags)
1991 {
1992 
1993 	if ((flags & UMA_SLAB_BOOT) != 0) {
1994 		startup_free(mem, size);
1995 		return;
1996 	}
1997 
1998 	KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1999 	    ("UMA: page_free used with invalid flags %x", flags));
2000 
2001 	kmem_free((vm_offset_t)mem, size);
2002 }
2003 
2004 /*
2005  * Frees pcpu zone allocations
2006  *
2007  * Arguments:
2008  *	mem   A pointer to the memory to be freed
2009  *	size  The size of the memory being freed
2010  *	flags The original p->us_flags field
2011  *
2012  * Returns:
2013  *	Nothing
2014  */
2015 static void
2016 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
2017 {
2018 	vm_offset_t sva, curva;
2019 	vm_paddr_t paddr;
2020 	vm_page_t m;
2021 
2022 	MPASS(size == (mp_maxid+1)*PAGE_SIZE);
2023 
2024 	if ((flags & UMA_SLAB_BOOT) != 0) {
2025 		startup_free(mem, size);
2026 		return;
2027 	}
2028 
2029 	sva = (vm_offset_t)mem;
2030 	for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
2031 		paddr = pmap_kextract(curva);
2032 		m = PHYS_TO_VM_PAGE(paddr);
2033 		vm_page_unwire_noq(m);
2034 		vm_page_free(m);
2035 	}
2036 	pmap_qremove(sva, size >> PAGE_SHIFT);
2037 	kva_free(sva, size);
2038 }
2039 
2040 /*
2041  * Zero fill initializer
2042  *
2043  * Arguments/Returns follow uma_init specifications
2044  */
2045 static int
2046 zero_init(void *mem, int size, int flags)
2047 {
2048 	bzero(mem, size);
2049 	return (0);
2050 }
2051 
2052 #ifdef INVARIANTS
2053 static struct noslabbits *
2054 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
2055 {
2056 
2057 	return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
2058 }
2059 #endif
2060 
2061 /*
2062  * Actual size of embedded struct slab (!OFFPAGE).
2063  */
2064 static size_t
2065 slab_sizeof(int nitems)
2066 {
2067 	size_t s;
2068 
2069 	s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
2070 	return (roundup(s, UMA_ALIGN_PTR + 1));
2071 }
2072 
2073 #define	UMA_FIXPT_SHIFT	31
2074 #define	UMA_FRAC_FIXPT(n, d)						\
2075 	((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
2076 #define	UMA_FIXPT_PCT(f)						\
2077 	((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
2078 #define	UMA_PCT_FIXPT(pct)	UMA_FRAC_FIXPT((pct), 100)
2079 #define	UMA_MIN_EFF	UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
2080 
2081 /*
2082  * Compute the number of items that will fit in a slab.  If hdr is true, the
2083  * item count may be limited to provide space in the slab for an inline slab
2084  * header.  Otherwise, all slab space will be provided for item storage.
2085  */
2086 static u_int
2087 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
2088 {
2089 	u_int ipers;
2090 	u_int padpi;
2091 
2092 	/* The padding between items is not needed after the last item. */
2093 	padpi = rsize - size;
2094 
2095 	if (hdr) {
2096 		/*
2097 		 * Start with the maximum item count and remove items until
2098 		 * the slab header first alongside the allocatable memory.
2099 		 */
2100 		for (ipers = MIN(SLAB_MAX_SETSIZE,
2101 		    (slabsize + padpi - slab_sizeof(1)) / rsize);
2102 		    ipers > 0 &&
2103 		    ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
2104 		    ipers--)
2105 			continue;
2106 	} else {
2107 		ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
2108 	}
2109 
2110 	return (ipers);
2111 }
2112 
2113 struct keg_layout_result {
2114 	u_int format;
2115 	u_int slabsize;
2116 	u_int ipers;
2117 	u_int eff;
2118 };
2119 
2120 static void
2121 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
2122     struct keg_layout_result *kl)
2123 {
2124 	u_int total;
2125 
2126 	kl->format = fmt;
2127 	kl->slabsize = slabsize;
2128 
2129 	/* Handle INTERNAL as inline with an extra page. */
2130 	if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
2131 		kl->format &= ~UMA_ZFLAG_INTERNAL;
2132 		kl->slabsize += PAGE_SIZE;
2133 	}
2134 
2135 	kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2136 	    (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2137 
2138 	/* Account for memory used by an offpage slab header. */
2139 	total = kl->slabsize;
2140 	if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2141 		total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2142 
2143 	kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2144 }
2145 
2146 /*
2147  * Determine the format of a uma keg.  This determines where the slab header
2148  * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2149  *
2150  * Arguments
2151  *	keg  The zone we should initialize
2152  *
2153  * Returns
2154  *	Nothing
2155  */
2156 static void
2157 keg_layout(uma_keg_t keg)
2158 {
2159 	struct keg_layout_result kl = {}, kl_tmp;
2160 	u_int fmts[2];
2161 	u_int alignsize;
2162 	u_int nfmt;
2163 	u_int pages;
2164 	u_int rsize;
2165 	u_int slabsize;
2166 	u_int i, j;
2167 
2168 	KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2169 	    (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2170 	     (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2171 	    ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2172 	     __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2173 	     PRINT_UMA_ZFLAGS));
2174 	KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2175 	    (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2176 	    ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2177 	     PRINT_UMA_ZFLAGS));
2178 
2179 	alignsize = keg->uk_align + 1;
2180 
2181 	/*
2182 	 * Calculate the size of each allocation (rsize) according to
2183 	 * alignment.  If the requested size is smaller than we have
2184 	 * allocation bits for we round it up.
2185 	 */
2186 	rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2187 	rsize = roundup2(rsize, alignsize);
2188 
2189 	if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2190 		/*
2191 		 * We want one item to start on every align boundary in a page.
2192 		 * To do this we will span pages.  We will also extend the item
2193 		 * by the size of align if it is an even multiple of align.
2194 		 * Otherwise, it would fall on the same boundary every time.
2195 		 */
2196 		if ((rsize & alignsize) == 0)
2197 			rsize += alignsize;
2198 		slabsize = rsize * (PAGE_SIZE / alignsize);
2199 		slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2200 		slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2201 		slabsize = round_page(slabsize);
2202 	} else {
2203 		/*
2204 		 * Start with a slab size of as many pages as it takes to
2205 		 * represent a single item.  We will try to fit as many
2206 		 * additional items into the slab as possible.
2207 		 */
2208 		slabsize = round_page(keg->uk_size);
2209 	}
2210 
2211 	/* Build a list of all of the available formats for this keg. */
2212 	nfmt = 0;
2213 
2214 	/* Evaluate an inline slab layout. */
2215 	if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2216 		fmts[nfmt++] = 0;
2217 
2218 	/* TODO: vm_page-embedded slab. */
2219 
2220 	/*
2221 	 * We can't do OFFPAGE if we're internal or if we've been
2222 	 * asked to not go to the VM for buckets.  If we do this we
2223 	 * may end up going to the VM for slabs which we do not want
2224 	 * to do if we're UMA_ZONE_VM, which clearly forbids it.
2225 	 * In those cases, evaluate a pseudo-format called INTERNAL
2226 	 * which has an inline slab header and one extra page to
2227 	 * guarantee that it fits.
2228 	 *
2229 	 * Otherwise, see if using an OFFPAGE slab will improve our
2230 	 * efficiency.
2231 	 */
2232 	if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2233 		fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2234 	else
2235 		fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2236 
2237 	/*
2238 	 * Choose a slab size and format which satisfy the minimum efficiency.
2239 	 * Prefer the smallest slab size that meets the constraints.
2240 	 *
2241 	 * Start with a minimum slab size, to accommodate CACHESPREAD.  Then,
2242 	 * for small items (up to PAGE_SIZE), the iteration increment is one
2243 	 * page; and for large items, the increment is one item.
2244 	 */
2245 	i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2246 	KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2247 	    keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2248 	    rsize, i));
2249 	for ( ; ; i++) {
2250 		slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2251 		    round_page(rsize * (i - 1) + keg->uk_size);
2252 
2253 		for (j = 0; j < nfmt; j++) {
2254 			/* Only if we have no viable format yet. */
2255 			if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2256 			    kl.ipers > 0)
2257 				continue;
2258 
2259 			keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2260 			if (kl_tmp.eff <= kl.eff)
2261 				continue;
2262 
2263 			kl = kl_tmp;
2264 
2265 			CTR6(KTR_UMA, "keg %s layout: format %#x "
2266 			    "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2267 			    keg->uk_name, kl.format, kl.ipers, rsize,
2268 			    kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2269 
2270 			/* Stop when we reach the minimum efficiency. */
2271 			if (kl.eff >= UMA_MIN_EFF)
2272 				break;
2273 		}
2274 
2275 		if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2276 		    slabsize >= SLAB_MAX_SETSIZE * rsize ||
2277 		    (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2278 			break;
2279 	}
2280 
2281 	pages = atop(kl.slabsize);
2282 	if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2283 		pages *= mp_maxid + 1;
2284 
2285 	keg->uk_rsize = rsize;
2286 	keg->uk_ipers = kl.ipers;
2287 	keg->uk_ppera = pages;
2288 	keg->uk_flags |= kl.format;
2289 
2290 	/*
2291 	 * How do we find the slab header if it is offpage or if not all item
2292 	 * start addresses are in the same page?  We could solve the latter
2293 	 * case with vaddr alignment, but we don't.
2294 	 */
2295 	if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2296 	    (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2297 		if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2298 			keg->uk_flags |= UMA_ZFLAG_HASH;
2299 		else
2300 			keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2301 	}
2302 
2303 	CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2304 	    __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2305 	    pages);
2306 	KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2307 	    ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2308 	     keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2309 	     keg->uk_ipers, pages));
2310 }
2311 
2312 /*
2313  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
2314  * the keg onto the global keg list.
2315  *
2316  * Arguments/Returns follow uma_ctor specifications
2317  *	udata  Actually uma_kctor_args
2318  */
2319 static int
2320 keg_ctor(void *mem, int size, void *udata, int flags)
2321 {
2322 	struct uma_kctor_args *arg = udata;
2323 	uma_keg_t keg = mem;
2324 	uma_zone_t zone;
2325 	int i;
2326 
2327 	bzero(keg, size);
2328 	keg->uk_size = arg->size;
2329 	keg->uk_init = arg->uminit;
2330 	keg->uk_fini = arg->fini;
2331 	keg->uk_align = arg->align;
2332 	keg->uk_reserve = 0;
2333 	keg->uk_flags = arg->flags;
2334 
2335 	/*
2336 	 * We use a global round-robin policy by default.  Zones with
2337 	 * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2338 	 * case the iterator is never run.
2339 	 */
2340 	keg->uk_dr.dr_policy = DOMAINSET_RR();
2341 	keg->uk_dr.dr_iter = 0;
2342 
2343 	/*
2344 	 * The primary zone is passed to us at keg-creation time.
2345 	 */
2346 	zone = arg->zone;
2347 	keg->uk_name = zone->uz_name;
2348 
2349 	if (arg->flags & UMA_ZONE_ZINIT)
2350 		keg->uk_init = zero_init;
2351 
2352 	if (arg->flags & UMA_ZONE_MALLOC)
2353 		keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2354 
2355 #ifndef SMP
2356 	keg->uk_flags &= ~UMA_ZONE_PCPU;
2357 #endif
2358 
2359 	keg_layout(keg);
2360 
2361 	/*
2362 	 * Use a first-touch NUMA policy for kegs that pmap_extract() will
2363 	 * work on.  Use round-robin for everything else.
2364 	 *
2365 	 * Zones may override the default by specifying either.
2366 	 */
2367 #ifdef NUMA
2368 	if ((keg->uk_flags &
2369 	    (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2370 		keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2371 	else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2372 		keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2373 #endif
2374 
2375 	/*
2376 	 * If we haven't booted yet we need allocations to go through the
2377 	 * startup cache until the vm is ready.
2378 	 */
2379 #ifdef UMA_MD_SMALL_ALLOC
2380 	if (keg->uk_ppera == 1)
2381 		keg->uk_allocf = uma_small_alloc;
2382 	else
2383 #endif
2384 	if (booted < BOOT_KVA)
2385 		keg->uk_allocf = startup_alloc;
2386 	else if (keg->uk_flags & UMA_ZONE_PCPU)
2387 		keg->uk_allocf = pcpu_page_alloc;
2388 	else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2389 		keg->uk_allocf = contig_alloc;
2390 	else
2391 		keg->uk_allocf = page_alloc;
2392 #ifdef UMA_MD_SMALL_ALLOC
2393 	if (keg->uk_ppera == 1)
2394 		keg->uk_freef = uma_small_free;
2395 	else
2396 #endif
2397 	if (keg->uk_flags & UMA_ZONE_PCPU)
2398 		keg->uk_freef = pcpu_page_free;
2399 	else
2400 		keg->uk_freef = page_free;
2401 
2402 	/*
2403 	 * Initialize keg's locks.
2404 	 */
2405 	for (i = 0; i < vm_ndomains; i++)
2406 		KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2407 
2408 	/*
2409 	 * If we're putting the slab header in the actual page we need to
2410 	 * figure out where in each page it goes.  See slab_sizeof
2411 	 * definition.
2412 	 */
2413 	if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2414 		size_t shsize;
2415 
2416 		shsize = slab_sizeof(keg->uk_ipers);
2417 		keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2418 		/*
2419 		 * The only way the following is possible is if with our
2420 		 * UMA_ALIGN_PTR adjustments we are now bigger than
2421 		 * UMA_SLAB_SIZE.  I haven't checked whether this is
2422 		 * mathematically possible for all cases, so we make
2423 		 * sure here anyway.
2424 		 */
2425 		KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2426 		    ("zone %s ipers %d rsize %d size %d slab won't fit",
2427 		    zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2428 	}
2429 
2430 	if (keg->uk_flags & UMA_ZFLAG_HASH)
2431 		hash_alloc(&keg->uk_hash, 0);
2432 
2433 	CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2434 
2435 	LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2436 
2437 	rw_wlock(&uma_rwlock);
2438 	LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2439 	rw_wunlock(&uma_rwlock);
2440 	return (0);
2441 }
2442 
2443 static void
2444 zone_kva_available(uma_zone_t zone, void *unused)
2445 {
2446 	uma_keg_t keg;
2447 
2448 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2449 		return;
2450 	KEG_GET(zone, keg);
2451 
2452 	if (keg->uk_allocf == startup_alloc) {
2453 		/* Switch to the real allocator. */
2454 		if (keg->uk_flags & UMA_ZONE_PCPU)
2455 			keg->uk_allocf = pcpu_page_alloc;
2456 		else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2457 		    keg->uk_ppera > 1)
2458 			keg->uk_allocf = contig_alloc;
2459 		else
2460 			keg->uk_allocf = page_alloc;
2461 	}
2462 }
2463 
2464 static void
2465 zone_alloc_counters(uma_zone_t zone, void *unused)
2466 {
2467 
2468 	zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2469 	zone->uz_frees = counter_u64_alloc(M_WAITOK);
2470 	zone->uz_fails = counter_u64_alloc(M_WAITOK);
2471 	zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2472 }
2473 
2474 static void
2475 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2476 {
2477 	uma_zone_domain_t zdom;
2478 	uma_domain_t dom;
2479 	uma_keg_t keg;
2480 	struct sysctl_oid *oid, *domainoid;
2481 	int domains, i, cnt;
2482 	static const char *nokeg = "cache zone";
2483 	char *c;
2484 
2485 	/*
2486 	 * Make a sysctl safe copy of the zone name by removing
2487 	 * any special characters and handling dups by appending
2488 	 * an index.
2489 	 */
2490 	if (zone->uz_namecnt != 0) {
2491 		/* Count the number of decimal digits and '_' separator. */
2492 		for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2493 			cnt /= 10;
2494 		zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2495 		    M_UMA, M_WAITOK);
2496 		sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2497 		    zone->uz_namecnt);
2498 	} else
2499 		zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2500 	for (c = zone->uz_ctlname; *c != '\0'; c++)
2501 		if (strchr("./\\ -", *c) != NULL)
2502 			*c = '_';
2503 
2504 	/*
2505 	 * Basic parameters at the root.
2506 	 */
2507 	zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2508 	    OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2509 	oid = zone->uz_oid;
2510 	SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2511 	    "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2512 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2513 	    "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2514 	    zone, 0, sysctl_handle_uma_zone_flags, "A",
2515 	    "Allocator configuration flags");
2516 	SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2517 	    "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2518 	    "Desired per-cpu cache size");
2519 	SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2520 	    "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2521 	    "Maximum allowed per-cpu cache size");
2522 
2523 	/*
2524 	 * keg if present.
2525 	 */
2526 	if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2527 		domains = vm_ndomains;
2528 	else
2529 		domains = 1;
2530 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2531 	    "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2532 	keg = zone->uz_keg;
2533 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2534 		SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2535 		    "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2536 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2537 		    "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2538 		    "Real object size with alignment");
2539 		SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2540 		    "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2541 		    "pages per-slab allocation");
2542 		SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2543 		    "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2544 		    "items available per-slab");
2545 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2546 		    "align", CTLFLAG_RD, &keg->uk_align, 0,
2547 		    "item alignment mask");
2548 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2549 		    "reserve", CTLFLAG_RD, &keg->uk_reserve, 0,
2550 		    "number of reserved items");
2551 		SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2552 		    "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2553 		    keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2554 		    "Slab utilization (100 - internal fragmentation %)");
2555 		domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2556 		    OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2557 		for (i = 0; i < domains; i++) {
2558 			dom = &keg->uk_domain[i];
2559 			oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2560 			    OID_AUTO, VM_DOMAIN(i)->vmd_name,
2561 			    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2562 			SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2563 			    "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2564 			    "Total pages currently allocated from VM");
2565 			SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2566 			    "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2567 			    "items free in the slab layer");
2568 		}
2569 	} else
2570 		SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2571 		    "name", CTLFLAG_RD, nokeg, "Keg name");
2572 
2573 	/*
2574 	 * Information about zone limits.
2575 	 */
2576 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2577 	    "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2578 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2579 	    "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2580 	    zone, 0, sysctl_handle_uma_zone_items, "QU",
2581 	    "Current number of allocated items if limit is set");
2582 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2583 	    "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2584 	    "Maximum number of allocated and cached items");
2585 	SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2586 	    "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2587 	    "Number of threads sleeping at limit");
2588 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2589 	    "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2590 	    "Total zone limit sleeps");
2591 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2592 	    "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2593 	    "Maximum number of items in each domain's bucket cache");
2594 
2595 	/*
2596 	 * Per-domain zone information.
2597 	 */
2598 	domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2599 	    OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2600 	for (i = 0; i < domains; i++) {
2601 		zdom = ZDOM_GET(zone, i);
2602 		oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2603 		    OID_AUTO, VM_DOMAIN(i)->vmd_name,
2604 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2605 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2606 		    "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2607 		    "number of items in this domain");
2608 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2609 		    "imax", CTLFLAG_RD, &zdom->uzd_imax,
2610 		    "maximum item count in this period");
2611 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2612 		    "imin", CTLFLAG_RD, &zdom->uzd_imin,
2613 		    "minimum item count in this period");
2614 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2615 		    "wss", CTLFLAG_RD, &zdom->uzd_wss,
2616 		    "Working set size");
2617 	}
2618 
2619 	/*
2620 	 * General statistics.
2621 	 */
2622 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2623 	    "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2624 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2625 	    "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2626 	    zone, 1, sysctl_handle_uma_zone_cur, "I",
2627 	    "Current number of allocated items");
2628 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2629 	    "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2630 	    zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2631 	    "Total allocation calls");
2632 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2633 	    "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2634 	    zone, 0, sysctl_handle_uma_zone_frees, "QU",
2635 	    "Total free calls");
2636 	SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2637 	    "fails", CTLFLAG_RD, &zone->uz_fails,
2638 	    "Number of allocation failures");
2639 	SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2640 	    "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2641 	    "Free calls from the wrong domain");
2642 }
2643 
2644 struct uma_zone_count {
2645 	const char	*name;
2646 	int		count;
2647 };
2648 
2649 static void
2650 zone_count(uma_zone_t zone, void *arg)
2651 {
2652 	struct uma_zone_count *cnt;
2653 
2654 	cnt = arg;
2655 	/*
2656 	 * Some zones are rapidly created with identical names and
2657 	 * destroyed out of order.  This can lead to gaps in the count.
2658 	 * Use one greater than the maximum observed for this name.
2659 	 */
2660 	if (strcmp(zone->uz_name, cnt->name) == 0)
2661 		cnt->count = MAX(cnt->count,
2662 		    zone->uz_namecnt + 1);
2663 }
2664 
2665 static void
2666 zone_update_caches(uma_zone_t zone)
2667 {
2668 	int i;
2669 
2670 	for (i = 0; i <= mp_maxid; i++) {
2671 		cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2672 		cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2673 	}
2674 }
2675 
2676 /*
2677  * Zone header ctor.  This initializes all fields, locks, etc.
2678  *
2679  * Arguments/Returns follow uma_ctor specifications
2680  *	udata  Actually uma_zctor_args
2681  */
2682 static int
2683 zone_ctor(void *mem, int size, void *udata, int flags)
2684 {
2685 	struct uma_zone_count cnt;
2686 	struct uma_zctor_args *arg = udata;
2687 	uma_zone_domain_t zdom;
2688 	uma_zone_t zone = mem;
2689 	uma_zone_t z;
2690 	uma_keg_t keg;
2691 	int i;
2692 
2693 	bzero(zone, size);
2694 	zone->uz_name = arg->name;
2695 	zone->uz_ctor = arg->ctor;
2696 	zone->uz_dtor = arg->dtor;
2697 	zone->uz_init = NULL;
2698 	zone->uz_fini = NULL;
2699 	zone->uz_sleeps = 0;
2700 	zone->uz_bucket_size = 0;
2701 	zone->uz_bucket_size_min = 0;
2702 	zone->uz_bucket_size_max = BUCKET_MAX;
2703 	zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2704 	zone->uz_warning = NULL;
2705 	/* The domain structures follow the cpu structures. */
2706 	zone->uz_bucket_max = ULONG_MAX;
2707 	timevalclear(&zone->uz_ratecheck);
2708 
2709 	/* Count the number of duplicate names. */
2710 	cnt.name = arg->name;
2711 	cnt.count = 0;
2712 	zone_foreach(zone_count, &cnt);
2713 	zone->uz_namecnt = cnt.count;
2714 	ZONE_CROSS_LOCK_INIT(zone);
2715 
2716 	for (i = 0; i < vm_ndomains; i++) {
2717 		zdom = ZDOM_GET(zone, i);
2718 		ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2719 		STAILQ_INIT(&zdom->uzd_buckets);
2720 	}
2721 
2722 #if defined(INVARIANTS) && !defined(KASAN)
2723 	if (arg->uminit == trash_init && arg->fini == trash_fini)
2724 		zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2725 #elif defined(KASAN)
2726 	if ((arg->flags & (UMA_ZONE_NOFREE | UMA_ZFLAG_CACHE)) != 0)
2727 		arg->flags |= UMA_ZONE_NOKASAN;
2728 #endif
2729 
2730 	/*
2731 	 * This is a pure cache zone, no kegs.
2732 	 */
2733 	if (arg->import) {
2734 		KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2735 		    ("zone_ctor: Import specified for non-cache zone."));
2736 		zone->uz_flags = arg->flags;
2737 		zone->uz_size = arg->size;
2738 		zone->uz_import = arg->import;
2739 		zone->uz_release = arg->release;
2740 		zone->uz_arg = arg->arg;
2741 #ifdef NUMA
2742 		/*
2743 		 * Cache zones are round-robin unless a policy is
2744 		 * specified because they may have incompatible
2745 		 * constraints.
2746 		 */
2747 		if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2748 			zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2749 #endif
2750 		rw_wlock(&uma_rwlock);
2751 		LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2752 		rw_wunlock(&uma_rwlock);
2753 		goto out;
2754 	}
2755 
2756 	/*
2757 	 * Use the regular zone/keg/slab allocator.
2758 	 */
2759 	zone->uz_import = zone_import;
2760 	zone->uz_release = zone_release;
2761 	zone->uz_arg = zone;
2762 	keg = arg->keg;
2763 
2764 	if (arg->flags & UMA_ZONE_SECONDARY) {
2765 		KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2766 		    ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2767 		KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2768 		zone->uz_init = arg->uminit;
2769 		zone->uz_fini = arg->fini;
2770 		zone->uz_flags |= UMA_ZONE_SECONDARY;
2771 		rw_wlock(&uma_rwlock);
2772 		ZONE_LOCK(zone);
2773 		LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2774 			if (LIST_NEXT(z, uz_link) == NULL) {
2775 				LIST_INSERT_AFTER(z, zone, uz_link);
2776 				break;
2777 			}
2778 		}
2779 		ZONE_UNLOCK(zone);
2780 		rw_wunlock(&uma_rwlock);
2781 	} else if (keg == NULL) {
2782 		if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2783 		    arg->align, arg->flags)) == NULL)
2784 			return (ENOMEM);
2785 	} else {
2786 		struct uma_kctor_args karg;
2787 		int error;
2788 
2789 		/* We should only be here from uma_startup() */
2790 		karg.size = arg->size;
2791 		karg.uminit = arg->uminit;
2792 		karg.fini = arg->fini;
2793 		karg.align = arg->align;
2794 		karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2795 		karg.zone = zone;
2796 		error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2797 		    flags);
2798 		if (error)
2799 			return (error);
2800 	}
2801 
2802 	/* Inherit properties from the keg. */
2803 	zone->uz_keg = keg;
2804 	zone->uz_size = keg->uk_size;
2805 	zone->uz_flags |= (keg->uk_flags &
2806 	    (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2807 
2808 out:
2809 	if (booted >= BOOT_PCPU) {
2810 		zone_alloc_counters(zone, NULL);
2811 		if (booted >= BOOT_RUNNING)
2812 			zone_alloc_sysctl(zone, NULL);
2813 	} else {
2814 		zone->uz_allocs = EARLY_COUNTER;
2815 		zone->uz_frees = EARLY_COUNTER;
2816 		zone->uz_fails = EARLY_COUNTER;
2817 	}
2818 
2819 	/* Caller requests a private SMR context. */
2820 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2821 		zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2822 
2823 	KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2824 	    (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2825 	    ("Invalid zone flag combination"));
2826 	if (arg->flags & UMA_ZFLAG_INTERNAL)
2827 		zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2828 	if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2829 		zone->uz_bucket_size = BUCKET_MAX;
2830 	else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2831 		zone->uz_bucket_size = 0;
2832 	else
2833 		zone->uz_bucket_size = bucket_select(zone->uz_size);
2834 	zone->uz_bucket_size_min = zone->uz_bucket_size;
2835 	if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2836 		zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2837 	zone_update_caches(zone);
2838 
2839 	return (0);
2840 }
2841 
2842 /*
2843  * Keg header dtor.  This frees all data, destroys locks, frees the hash
2844  * table and removes the keg from the global list.
2845  *
2846  * Arguments/Returns follow uma_dtor specifications
2847  *	udata  unused
2848  */
2849 static void
2850 keg_dtor(void *arg, int size, void *udata)
2851 {
2852 	uma_keg_t keg;
2853 	uint32_t free, pages;
2854 	int i;
2855 
2856 	keg = (uma_keg_t)arg;
2857 	free = pages = 0;
2858 	for (i = 0; i < vm_ndomains; i++) {
2859 		free += keg->uk_domain[i].ud_free_items;
2860 		pages += keg->uk_domain[i].ud_pages;
2861 		KEG_LOCK_FINI(keg, i);
2862 	}
2863 	if (pages != 0)
2864 		printf("Freed UMA keg (%s) was not empty (%u items). "
2865 		    " Lost %u pages of memory.\n",
2866 		    keg->uk_name ? keg->uk_name : "",
2867 		    pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2868 
2869 	hash_free(&keg->uk_hash);
2870 }
2871 
2872 /*
2873  * Zone header dtor.
2874  *
2875  * Arguments/Returns follow uma_dtor specifications
2876  *	udata  unused
2877  */
2878 static void
2879 zone_dtor(void *arg, int size, void *udata)
2880 {
2881 	uma_zone_t zone;
2882 	uma_keg_t keg;
2883 	int i;
2884 
2885 	zone = (uma_zone_t)arg;
2886 
2887 	sysctl_remove_oid(zone->uz_oid, 1, 1);
2888 
2889 	if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2890 		cache_drain(zone);
2891 
2892 	rw_wlock(&uma_rwlock);
2893 	LIST_REMOVE(zone, uz_link);
2894 	rw_wunlock(&uma_rwlock);
2895 	if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2896 		keg = zone->uz_keg;
2897 		keg->uk_reserve = 0;
2898 	}
2899 	zone_reclaim(zone, UMA_ANYDOMAIN, M_WAITOK, true);
2900 
2901 	/*
2902 	 * We only destroy kegs from non secondary/non cache zones.
2903 	 */
2904 	if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2905 		keg = zone->uz_keg;
2906 		rw_wlock(&uma_rwlock);
2907 		LIST_REMOVE(keg, uk_link);
2908 		rw_wunlock(&uma_rwlock);
2909 		zone_free_item(kegs, keg, NULL, SKIP_NONE);
2910 	}
2911 	counter_u64_free(zone->uz_allocs);
2912 	counter_u64_free(zone->uz_frees);
2913 	counter_u64_free(zone->uz_fails);
2914 	counter_u64_free(zone->uz_xdomain);
2915 	free(zone->uz_ctlname, M_UMA);
2916 	for (i = 0; i < vm_ndomains; i++)
2917 		ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2918 	ZONE_CROSS_LOCK_FINI(zone);
2919 }
2920 
2921 static void
2922 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2923 {
2924 	uma_keg_t keg;
2925 	uma_zone_t zone;
2926 
2927 	LIST_FOREACH(keg, &uma_kegs, uk_link) {
2928 		LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2929 			zfunc(zone, arg);
2930 	}
2931 	LIST_FOREACH(zone, &uma_cachezones, uz_link)
2932 		zfunc(zone, arg);
2933 }
2934 
2935 /*
2936  * Traverses every zone in the system and calls a callback
2937  *
2938  * Arguments:
2939  *	zfunc  A pointer to a function which accepts a zone
2940  *		as an argument.
2941  *
2942  * Returns:
2943  *	Nothing
2944  */
2945 static void
2946 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2947 {
2948 
2949 	rw_rlock(&uma_rwlock);
2950 	zone_foreach_unlocked(zfunc, arg);
2951 	rw_runlock(&uma_rwlock);
2952 }
2953 
2954 /*
2955  * Initialize the kernel memory allocator.  This is done after pages can be
2956  * allocated but before general KVA is available.
2957  */
2958 void
2959 uma_startup1(vm_offset_t virtual_avail)
2960 {
2961 	struct uma_zctor_args args;
2962 	size_t ksize, zsize, size;
2963 	uma_keg_t primarykeg;
2964 	uintptr_t m;
2965 	int domain;
2966 	uint8_t pflag;
2967 
2968 	bootstart = bootmem = virtual_avail;
2969 
2970 	rw_init(&uma_rwlock, "UMA lock");
2971 	sx_init(&uma_reclaim_lock, "umareclaim");
2972 
2973 	ksize = sizeof(struct uma_keg) +
2974 	    (sizeof(struct uma_domain) * vm_ndomains);
2975 	ksize = roundup(ksize, UMA_SUPER_ALIGN);
2976 	zsize = sizeof(struct uma_zone) +
2977 	    (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2978 	    (sizeof(struct uma_zone_domain) * vm_ndomains);
2979 	zsize = roundup(zsize, UMA_SUPER_ALIGN);
2980 
2981 	/* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2982 	size = (zsize * 2) + ksize;
2983 	for (domain = 0; domain < vm_ndomains; domain++) {
2984 		m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2985 		    M_NOWAIT | M_ZERO);
2986 		if (m != 0)
2987 			break;
2988 	}
2989 	zones = (uma_zone_t)m;
2990 	m += zsize;
2991 	kegs = (uma_zone_t)m;
2992 	m += zsize;
2993 	primarykeg = (uma_keg_t)m;
2994 
2995 	/* "manually" create the initial zone */
2996 	memset(&args, 0, sizeof(args));
2997 	args.name = "UMA Kegs";
2998 	args.size = ksize;
2999 	args.ctor = keg_ctor;
3000 	args.dtor = keg_dtor;
3001 	args.uminit = zero_init;
3002 	args.fini = NULL;
3003 	args.keg = primarykeg;
3004 	args.align = UMA_SUPER_ALIGN - 1;
3005 	args.flags = UMA_ZFLAG_INTERNAL;
3006 	zone_ctor(kegs, zsize, &args, M_WAITOK);
3007 
3008 	args.name = "UMA Zones";
3009 	args.size = zsize;
3010 	args.ctor = zone_ctor;
3011 	args.dtor = zone_dtor;
3012 	args.uminit = zero_init;
3013 	args.fini = NULL;
3014 	args.keg = NULL;
3015 	args.align = UMA_SUPER_ALIGN - 1;
3016 	args.flags = UMA_ZFLAG_INTERNAL;
3017 	zone_ctor(zones, zsize, &args, M_WAITOK);
3018 
3019 	/* Now make zones for slab headers */
3020 	slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
3021 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3022 	slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
3023 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3024 
3025 	hashzone = uma_zcreate("UMA Hash",
3026 	    sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
3027 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
3028 
3029 	bucket_init();
3030 	smr_init();
3031 }
3032 
3033 #ifndef UMA_MD_SMALL_ALLOC
3034 extern void vm_radix_reserve_kva(void);
3035 #endif
3036 
3037 /*
3038  * Advertise the availability of normal kva allocations and switch to
3039  * the default back-end allocator.  Marks the KVA we consumed on startup
3040  * as used in the map.
3041  */
3042 void
3043 uma_startup2(void)
3044 {
3045 
3046 	if (bootstart != bootmem) {
3047 		vm_map_lock(kernel_map);
3048 		(void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
3049 		    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
3050 		vm_map_unlock(kernel_map);
3051 	}
3052 
3053 #ifndef UMA_MD_SMALL_ALLOC
3054 	/* Set up radix zone to use noobj_alloc. */
3055 	vm_radix_reserve_kva();
3056 #endif
3057 
3058 	booted = BOOT_KVA;
3059 	zone_foreach_unlocked(zone_kva_available, NULL);
3060 	bucket_enable();
3061 }
3062 
3063 /*
3064  * Allocate counters as early as possible so that boot-time allocations are
3065  * accounted more precisely.
3066  */
3067 static void
3068 uma_startup_pcpu(void *arg __unused)
3069 {
3070 
3071 	zone_foreach_unlocked(zone_alloc_counters, NULL);
3072 	booted = BOOT_PCPU;
3073 }
3074 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
3075 
3076 /*
3077  * Finish our initialization steps.
3078  */
3079 static void
3080 uma_startup3(void *arg __unused)
3081 {
3082 
3083 #ifdef INVARIANTS
3084 	TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
3085 	uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
3086 	uma_skip_cnt = counter_u64_alloc(M_WAITOK);
3087 #endif
3088 	zone_foreach_unlocked(zone_alloc_sysctl, NULL);
3089 	callout_init(&uma_callout, 1);
3090 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
3091 	booted = BOOT_RUNNING;
3092 
3093 	EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
3094 	    EVENTHANDLER_PRI_FIRST);
3095 }
3096 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
3097 
3098 static void
3099 uma_shutdown(void)
3100 {
3101 
3102 	booted = BOOT_SHUTDOWN;
3103 }
3104 
3105 static uma_keg_t
3106 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
3107 		int align, uint32_t flags)
3108 {
3109 	struct uma_kctor_args args;
3110 
3111 	args.size = size;
3112 	args.uminit = uminit;
3113 	args.fini = fini;
3114 	args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
3115 	args.flags = flags;
3116 	args.zone = zone;
3117 	return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
3118 }
3119 
3120 /* Public functions */
3121 /* See uma.h */
3122 void
3123 uma_set_align(int align)
3124 {
3125 
3126 	if (align != UMA_ALIGN_CACHE)
3127 		uma_align_cache = align;
3128 }
3129 
3130 /* See uma.h */
3131 uma_zone_t
3132 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
3133 		uma_init uminit, uma_fini fini, int align, uint32_t flags)
3134 
3135 {
3136 	struct uma_zctor_args args;
3137 	uma_zone_t res;
3138 
3139 	KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
3140 	    align, name));
3141 
3142 	/* This stuff is essential for the zone ctor */
3143 	memset(&args, 0, sizeof(args));
3144 	args.name = name;
3145 	args.size = size;
3146 	args.ctor = ctor;
3147 	args.dtor = dtor;
3148 	args.uminit = uminit;
3149 	args.fini = fini;
3150 #if defined(INVARIANTS) && !defined(KASAN)
3151 	/*
3152 	 * Inject procedures which check for memory use after free if we are
3153 	 * allowed to scramble the memory while it is not allocated.  This
3154 	 * requires that: UMA is actually able to access the memory, no init
3155 	 * or fini procedures, no dependency on the initial value of the
3156 	 * memory, and no (legitimate) use of the memory after free.  Note,
3157 	 * the ctor and dtor do not need to be empty.
3158 	 */
3159 	if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3160 	    UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3161 		args.uminit = trash_init;
3162 		args.fini = trash_fini;
3163 	}
3164 #endif
3165 	args.align = align;
3166 	args.flags = flags;
3167 	args.keg = NULL;
3168 
3169 	sx_xlock(&uma_reclaim_lock);
3170 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3171 	sx_xunlock(&uma_reclaim_lock);
3172 
3173 	return (res);
3174 }
3175 
3176 /* See uma.h */
3177 uma_zone_t
3178 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3179     uma_init zinit, uma_fini zfini, uma_zone_t primary)
3180 {
3181 	struct uma_zctor_args args;
3182 	uma_keg_t keg;
3183 	uma_zone_t res;
3184 
3185 	keg = primary->uz_keg;
3186 	memset(&args, 0, sizeof(args));
3187 	args.name = name;
3188 	args.size = keg->uk_size;
3189 	args.ctor = ctor;
3190 	args.dtor = dtor;
3191 	args.uminit = zinit;
3192 	args.fini = zfini;
3193 	args.align = keg->uk_align;
3194 	args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3195 	args.keg = keg;
3196 
3197 	sx_xlock(&uma_reclaim_lock);
3198 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3199 	sx_xunlock(&uma_reclaim_lock);
3200 
3201 	return (res);
3202 }
3203 
3204 /* See uma.h */
3205 uma_zone_t
3206 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3207     uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3208     void *arg, int flags)
3209 {
3210 	struct uma_zctor_args args;
3211 
3212 	memset(&args, 0, sizeof(args));
3213 	args.name = name;
3214 	args.size = size;
3215 	args.ctor = ctor;
3216 	args.dtor = dtor;
3217 	args.uminit = zinit;
3218 	args.fini = zfini;
3219 	args.import = zimport;
3220 	args.release = zrelease;
3221 	args.arg = arg;
3222 	args.align = 0;
3223 	args.flags = flags | UMA_ZFLAG_CACHE;
3224 
3225 	return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3226 }
3227 
3228 /* See uma.h */
3229 void
3230 uma_zdestroy(uma_zone_t zone)
3231 {
3232 
3233 	/*
3234 	 * Large slabs are expensive to reclaim, so don't bother doing
3235 	 * unnecessary work if we're shutting down.
3236 	 */
3237 	if (booted == BOOT_SHUTDOWN &&
3238 	    zone->uz_fini == NULL && zone->uz_release == zone_release)
3239 		return;
3240 	sx_xlock(&uma_reclaim_lock);
3241 	zone_free_item(zones, zone, NULL, SKIP_NONE);
3242 	sx_xunlock(&uma_reclaim_lock);
3243 }
3244 
3245 void
3246 uma_zwait(uma_zone_t zone)
3247 {
3248 
3249 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3250 		uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3251 	else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3252 		uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3253 	else
3254 		uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3255 }
3256 
3257 void *
3258 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3259 {
3260 	void *item, *pcpu_item;
3261 #ifdef SMP
3262 	int i;
3263 
3264 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3265 #endif
3266 	item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3267 	if (item == NULL)
3268 		return (NULL);
3269 	pcpu_item = zpcpu_base_to_offset(item);
3270 	if (flags & M_ZERO) {
3271 #ifdef SMP
3272 		for (i = 0; i <= mp_maxid; i++)
3273 			bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3274 #else
3275 		bzero(item, zone->uz_size);
3276 #endif
3277 	}
3278 	return (pcpu_item);
3279 }
3280 
3281 /*
3282  * A stub while both regular and pcpu cases are identical.
3283  */
3284 void
3285 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3286 {
3287 	void *item;
3288 
3289 #ifdef SMP
3290 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3291 #endif
3292 
3293         /* uma_zfree_pcu_*(..., NULL) does nothing, to match free(9). */
3294         if (pcpu_item == NULL)
3295                 return;
3296 
3297 	item = zpcpu_offset_to_base(pcpu_item);
3298 	uma_zfree_arg(zone, item, udata);
3299 }
3300 
3301 static inline void *
3302 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3303     void *item)
3304 {
3305 #ifdef INVARIANTS
3306 	bool skipdbg;
3307 #endif
3308 
3309 	kasan_mark_item_valid(zone, item);
3310 
3311 #ifdef INVARIANTS
3312 	skipdbg = uma_dbg_zskip(zone, item);
3313 	if (!skipdbg && (uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3314 	    zone->uz_ctor != trash_ctor)
3315 		trash_ctor(item, size, udata, flags);
3316 #endif
3317 
3318 	/* Check flags before loading ctor pointer. */
3319 	if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3320 	    __predict_false(zone->uz_ctor != NULL) &&
3321 	    zone->uz_ctor(item, size, udata, flags) != 0) {
3322 		counter_u64_add(zone->uz_fails, 1);
3323 		zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3324 		return (NULL);
3325 	}
3326 #ifdef INVARIANTS
3327 	if (!skipdbg)
3328 		uma_dbg_alloc(zone, NULL, item);
3329 #endif
3330 	if (__predict_false(flags & M_ZERO))
3331 		return (memset(item, 0, size));
3332 
3333 	return (item);
3334 }
3335 
3336 static inline void
3337 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3338     enum zfreeskip skip)
3339 {
3340 #ifdef INVARIANTS
3341 	bool skipdbg;
3342 
3343 	skipdbg = uma_dbg_zskip(zone, item);
3344 	if (skip == SKIP_NONE && !skipdbg) {
3345 		if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3346 			uma_dbg_free(zone, udata, item);
3347 		else
3348 			uma_dbg_free(zone, NULL, item);
3349 	}
3350 #endif
3351 	if (__predict_true(skip < SKIP_DTOR)) {
3352 		if (zone->uz_dtor != NULL)
3353 			zone->uz_dtor(item, size, udata);
3354 #ifdef INVARIANTS
3355 		if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3356 		    zone->uz_dtor != trash_dtor)
3357 			trash_dtor(item, size, udata);
3358 #endif
3359 	}
3360 	kasan_mark_item_invalid(zone, item);
3361 }
3362 
3363 #ifdef NUMA
3364 static int
3365 item_domain(void *item)
3366 {
3367 	int domain;
3368 
3369 	domain = vm_phys_domain(vtophys(item));
3370 	KASSERT(domain >= 0 && domain < vm_ndomains,
3371 	    ("%s: unknown domain for item %p", __func__, item));
3372 	return (domain);
3373 }
3374 #endif
3375 
3376 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3377 #define	UMA_ZALLOC_DEBUG
3378 static int
3379 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3380 {
3381 	int error;
3382 
3383 	error = 0;
3384 #ifdef WITNESS
3385 	if (flags & M_WAITOK) {
3386 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3387 		    "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3388 	}
3389 #endif
3390 
3391 #ifdef INVARIANTS
3392 	KASSERT((flags & M_EXEC) == 0,
3393 	    ("uma_zalloc_debug: called with M_EXEC"));
3394 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3395 	    ("uma_zalloc_debug: called within spinlock or critical section"));
3396 	KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3397 	    ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3398 #endif
3399 
3400 #ifdef DEBUG_MEMGUARD
3401 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3402 		void *item;
3403 		item = memguard_alloc(zone->uz_size, flags);
3404 		if (item != NULL) {
3405 			error = EJUSTRETURN;
3406 			if (zone->uz_init != NULL &&
3407 			    zone->uz_init(item, zone->uz_size, flags) != 0) {
3408 				*itemp = NULL;
3409 				return (error);
3410 			}
3411 			if (zone->uz_ctor != NULL &&
3412 			    zone->uz_ctor(item, zone->uz_size, udata,
3413 			    flags) != 0) {
3414 				counter_u64_add(zone->uz_fails, 1);
3415 			    	zone->uz_fini(item, zone->uz_size);
3416 				*itemp = NULL;
3417 				return (error);
3418 			}
3419 			*itemp = item;
3420 			return (error);
3421 		}
3422 		/* This is unfortunate but should not be fatal. */
3423 	}
3424 #endif
3425 	return (error);
3426 }
3427 
3428 static int
3429 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3430 {
3431 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3432 	    ("uma_zfree_debug: called with spinlock or critical section held"));
3433 
3434 #ifdef DEBUG_MEMGUARD
3435 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3436 		if (zone->uz_dtor != NULL)
3437 			zone->uz_dtor(item, zone->uz_size, udata);
3438 		if (zone->uz_fini != NULL)
3439 			zone->uz_fini(item, zone->uz_size);
3440 		memguard_free(item);
3441 		return (EJUSTRETURN);
3442 	}
3443 #endif
3444 	return (0);
3445 }
3446 #endif
3447 
3448 static inline void *
3449 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3450     void *udata, int flags)
3451 {
3452 	void *item;
3453 	int size, uz_flags;
3454 
3455 	item = cache_bucket_pop(cache, bucket);
3456 	size = cache_uz_size(cache);
3457 	uz_flags = cache_uz_flags(cache);
3458 	critical_exit();
3459 	return (item_ctor(zone, uz_flags, size, udata, flags, item));
3460 }
3461 
3462 static __noinline void *
3463 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3464 {
3465 	uma_cache_bucket_t bucket;
3466 	int domain;
3467 
3468 	while (cache_alloc(zone, cache, udata, flags)) {
3469 		cache = &zone->uz_cpu[curcpu];
3470 		bucket = &cache->uc_allocbucket;
3471 		if (__predict_false(bucket->ucb_cnt == 0))
3472 			continue;
3473 		return (cache_alloc_item(zone, cache, bucket, udata, flags));
3474 	}
3475 	critical_exit();
3476 
3477 	/*
3478 	 * We can not get a bucket so try to return a single item.
3479 	 */
3480 	if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3481 		domain = PCPU_GET(domain);
3482 	else
3483 		domain = UMA_ANYDOMAIN;
3484 	return (zone_alloc_item(zone, udata, domain, flags));
3485 }
3486 
3487 /* See uma.h */
3488 void *
3489 uma_zalloc_smr(uma_zone_t zone, int flags)
3490 {
3491 	uma_cache_bucket_t bucket;
3492 	uma_cache_t cache;
3493 
3494 #ifdef UMA_ZALLOC_DEBUG
3495 	void *item;
3496 
3497 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3498 	    ("uma_zalloc_arg: called with non-SMR zone."));
3499 	if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3500 		return (item);
3501 #endif
3502 
3503 	critical_enter();
3504 	cache = &zone->uz_cpu[curcpu];
3505 	bucket = &cache->uc_allocbucket;
3506 	if (__predict_false(bucket->ucb_cnt == 0))
3507 		return (cache_alloc_retry(zone, cache, NULL, flags));
3508 	return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3509 }
3510 
3511 /* See uma.h */
3512 void *
3513 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3514 {
3515 	uma_cache_bucket_t bucket;
3516 	uma_cache_t cache;
3517 
3518 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3519 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3520 
3521 	/* This is the fast path allocation */
3522 	CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3523 	    zone, flags);
3524 
3525 #ifdef UMA_ZALLOC_DEBUG
3526 	void *item;
3527 
3528 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3529 	    ("uma_zalloc_arg: called with SMR zone."));
3530 	if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3531 		return (item);
3532 #endif
3533 
3534 	/*
3535 	 * If possible, allocate from the per-CPU cache.  There are two
3536 	 * requirements for safe access to the per-CPU cache: (1) the thread
3537 	 * accessing the cache must not be preempted or yield during access,
3538 	 * and (2) the thread must not migrate CPUs without switching which
3539 	 * cache it accesses.  We rely on a critical section to prevent
3540 	 * preemption and migration.  We release the critical section in
3541 	 * order to acquire the zone mutex if we are unable to allocate from
3542 	 * the current cache; when we re-acquire the critical section, we
3543 	 * must detect and handle migration if it has occurred.
3544 	 */
3545 	critical_enter();
3546 	cache = &zone->uz_cpu[curcpu];
3547 	bucket = &cache->uc_allocbucket;
3548 	if (__predict_false(bucket->ucb_cnt == 0))
3549 		return (cache_alloc_retry(zone, cache, udata, flags));
3550 	return (cache_alloc_item(zone, cache, bucket, udata, flags));
3551 }
3552 
3553 /*
3554  * Replenish an alloc bucket and possibly restore an old one.  Called in
3555  * a critical section.  Returns in a critical section.
3556  *
3557  * A false return value indicates an allocation failure.
3558  * A true return value indicates success and the caller should retry.
3559  */
3560 static __noinline bool
3561 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3562 {
3563 	uma_bucket_t bucket;
3564 	int curdomain, domain;
3565 	bool new;
3566 
3567 	CRITICAL_ASSERT(curthread);
3568 
3569 	/*
3570 	 * If we have run out of items in our alloc bucket see
3571 	 * if we can switch with the free bucket.
3572 	 *
3573 	 * SMR Zones can't re-use the free bucket until the sequence has
3574 	 * expired.
3575 	 */
3576 	if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3577 	    cache->uc_freebucket.ucb_cnt != 0) {
3578 		cache_bucket_swap(&cache->uc_freebucket,
3579 		    &cache->uc_allocbucket);
3580 		return (true);
3581 	}
3582 
3583 	/*
3584 	 * Discard any empty allocation bucket while we hold no locks.
3585 	 */
3586 	bucket = cache_bucket_unload_alloc(cache);
3587 	critical_exit();
3588 
3589 	if (bucket != NULL) {
3590 		KASSERT(bucket->ub_cnt == 0,
3591 		    ("cache_alloc: Entered with non-empty alloc bucket."));
3592 		bucket_free(zone, bucket, udata);
3593 	}
3594 
3595 	/*
3596 	 * Attempt to retrieve the item from the per-CPU cache has failed, so
3597 	 * we must go back to the zone.  This requires the zdom lock, so we
3598 	 * must drop the critical section, then re-acquire it when we go back
3599 	 * to the cache.  Since the critical section is released, we may be
3600 	 * preempted or migrate.  As such, make sure not to maintain any
3601 	 * thread-local state specific to the cache from prior to releasing
3602 	 * the critical section.
3603 	 */
3604 	domain = PCPU_GET(domain);
3605 	if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3606 	    VM_DOMAIN_EMPTY(domain))
3607 		domain = zone_domain_highest(zone, domain);
3608 	bucket = cache_fetch_bucket(zone, cache, domain);
3609 	if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3610 		bucket = zone_alloc_bucket(zone, udata, domain, flags);
3611 		new = true;
3612 	} else {
3613 		new = false;
3614 	}
3615 
3616 	CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3617 	    zone->uz_name, zone, bucket);
3618 	if (bucket == NULL) {
3619 		critical_enter();
3620 		return (false);
3621 	}
3622 
3623 	/*
3624 	 * See if we lost the race or were migrated.  Cache the
3625 	 * initialized bucket to make this less likely or claim
3626 	 * the memory directly.
3627 	 */
3628 	critical_enter();
3629 	cache = &zone->uz_cpu[curcpu];
3630 	if (cache->uc_allocbucket.ucb_bucket == NULL &&
3631 	    ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3632 	    (curdomain = PCPU_GET(domain)) == domain ||
3633 	    VM_DOMAIN_EMPTY(curdomain))) {
3634 		if (new)
3635 			atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3636 			    bucket->ub_cnt);
3637 		cache_bucket_load_alloc(cache, bucket);
3638 		return (true);
3639 	}
3640 
3641 	/*
3642 	 * We lost the race, release this bucket and start over.
3643 	 */
3644 	critical_exit();
3645 	zone_put_bucket(zone, domain, bucket, udata, false);
3646 	critical_enter();
3647 
3648 	return (true);
3649 }
3650 
3651 void *
3652 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3653 {
3654 #ifdef NUMA
3655 	uma_bucket_t bucket;
3656 	uma_zone_domain_t zdom;
3657 	void *item;
3658 #endif
3659 
3660 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3661 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3662 
3663 	/* This is the fast path allocation */
3664 	CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3665 	    zone->uz_name, zone, domain, flags);
3666 
3667 	if (flags & M_WAITOK) {
3668 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3669 		    "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3670 	}
3671 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3672 	    ("uma_zalloc_domain: called with spinlock or critical section held"));
3673 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3674 	    ("uma_zalloc_domain: called with SMR zone."));
3675 #ifdef NUMA
3676 	KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3677 	    ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3678 
3679 	if (vm_ndomains == 1)
3680 		return (uma_zalloc_arg(zone, udata, flags));
3681 
3682 	/*
3683 	 * Try to allocate from the bucket cache before falling back to the keg.
3684 	 * We could try harder and attempt to allocate from per-CPU caches or
3685 	 * the per-domain cross-domain buckets, but the complexity is probably
3686 	 * not worth it.  It is more important that frees of previous
3687 	 * cross-domain allocations do not blow up the cache.
3688 	 */
3689 	zdom = zone_domain_lock(zone, domain);
3690 	if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3691 		item = bucket->ub_bucket[bucket->ub_cnt - 1];
3692 #ifdef INVARIANTS
3693 		bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3694 #endif
3695 		bucket->ub_cnt--;
3696 		zone_put_bucket(zone, domain, bucket, udata, true);
3697 		item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3698 		    flags, item);
3699 		if (item != NULL) {
3700 			KASSERT(item_domain(item) == domain,
3701 			    ("%s: bucket cache item %p from wrong domain",
3702 			    __func__, item));
3703 			counter_u64_add(zone->uz_allocs, 1);
3704 		}
3705 		return (item);
3706 	}
3707 	ZDOM_UNLOCK(zdom);
3708 	return (zone_alloc_item(zone, udata, domain, flags));
3709 #else
3710 	return (uma_zalloc_arg(zone, udata, flags));
3711 #endif
3712 }
3713 
3714 /*
3715  * Find a slab with some space.  Prefer slabs that are partially used over those
3716  * that are totally full.  This helps to reduce fragmentation.
3717  *
3718  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
3719  * only 'domain'.
3720  */
3721 static uma_slab_t
3722 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3723 {
3724 	uma_domain_t dom;
3725 	uma_slab_t slab;
3726 	int start;
3727 
3728 	KASSERT(domain >= 0 && domain < vm_ndomains,
3729 	    ("keg_first_slab: domain %d out of range", domain));
3730 	KEG_LOCK_ASSERT(keg, domain);
3731 
3732 	slab = NULL;
3733 	start = domain;
3734 	do {
3735 		dom = &keg->uk_domain[domain];
3736 		if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3737 			return (slab);
3738 		if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3739 			LIST_REMOVE(slab, us_link);
3740 			dom->ud_free_slabs--;
3741 			LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3742 			return (slab);
3743 		}
3744 		if (rr)
3745 			domain = (domain + 1) % vm_ndomains;
3746 	} while (domain != start);
3747 
3748 	return (NULL);
3749 }
3750 
3751 /*
3752  * Fetch an existing slab from a free or partial list.  Returns with the
3753  * keg domain lock held if a slab was found or unlocked if not.
3754  */
3755 static uma_slab_t
3756 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3757 {
3758 	uma_slab_t slab;
3759 	uint32_t reserve;
3760 
3761 	/* HASH has a single free list. */
3762 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3763 		domain = 0;
3764 
3765 	KEG_LOCK(keg, domain);
3766 	reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3767 	if (keg->uk_domain[domain].ud_free_items <= reserve ||
3768 	    (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3769 		KEG_UNLOCK(keg, domain);
3770 		return (NULL);
3771 	}
3772 	return (slab);
3773 }
3774 
3775 static uma_slab_t
3776 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3777 {
3778 	struct vm_domainset_iter di;
3779 	uma_slab_t slab;
3780 	int aflags, domain;
3781 	bool rr;
3782 
3783 restart:
3784 	/*
3785 	 * Use the keg's policy if upper layers haven't already specified a
3786 	 * domain (as happens with first-touch zones).
3787 	 *
3788 	 * To avoid races we run the iterator with the keg lock held, but that
3789 	 * means that we cannot allow the vm_domainset layer to sleep.  Thus,
3790 	 * clear M_WAITOK and handle low memory conditions locally.
3791 	 */
3792 	rr = rdomain == UMA_ANYDOMAIN;
3793 	if (rr) {
3794 		aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3795 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3796 		    &aflags);
3797 	} else {
3798 		aflags = flags;
3799 		domain = rdomain;
3800 	}
3801 
3802 	for (;;) {
3803 		slab = keg_fetch_free_slab(keg, domain, rr, flags);
3804 		if (slab != NULL)
3805 			return (slab);
3806 
3807 		/*
3808 		 * M_NOVM means don't ask at all!
3809 		 */
3810 		if (flags & M_NOVM)
3811 			break;
3812 
3813 		slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3814 		if (slab != NULL)
3815 			return (slab);
3816 		if (!rr && (flags & M_WAITOK) == 0)
3817 			break;
3818 		if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3819 			if ((flags & M_WAITOK) != 0) {
3820 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3821 				goto restart;
3822 			}
3823 			break;
3824 		}
3825 	}
3826 
3827 	/*
3828 	 * We might not have been able to get a slab but another cpu
3829 	 * could have while we were unlocked.  Check again before we
3830 	 * fail.
3831 	 */
3832 	if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3833 		return (slab);
3834 
3835 	return (NULL);
3836 }
3837 
3838 static void *
3839 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3840 {
3841 	uma_domain_t dom;
3842 	void *item;
3843 	int freei;
3844 
3845 	KEG_LOCK_ASSERT(keg, slab->us_domain);
3846 
3847 	dom = &keg->uk_domain[slab->us_domain];
3848 	freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3849 	BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3850 	item = slab_item(slab, keg, freei);
3851 	slab->us_freecount--;
3852 	dom->ud_free_items--;
3853 
3854 	/*
3855 	 * Move this slab to the full list.  It must be on the partial list, so
3856 	 * we do not need to update the free slab count.  In particular,
3857 	 * keg_fetch_slab() always returns slabs on the partial list.
3858 	 */
3859 	if (slab->us_freecount == 0) {
3860 		LIST_REMOVE(slab, us_link);
3861 		LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3862 	}
3863 
3864 	return (item);
3865 }
3866 
3867 static int
3868 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3869 {
3870 	uma_domain_t dom;
3871 	uma_zone_t zone;
3872 	uma_slab_t slab;
3873 	uma_keg_t keg;
3874 #ifdef NUMA
3875 	int stripe;
3876 #endif
3877 	int i;
3878 
3879 	zone = arg;
3880 	slab = NULL;
3881 	keg = zone->uz_keg;
3882 	/* Try to keep the buckets totally full */
3883 	for (i = 0; i < max; ) {
3884 		if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3885 			break;
3886 #ifdef NUMA
3887 		stripe = howmany(max, vm_ndomains);
3888 #endif
3889 		dom = &keg->uk_domain[slab->us_domain];
3890 		do {
3891 			bucket[i++] = slab_alloc_item(keg, slab);
3892 			if (dom->ud_free_items <= keg->uk_reserve) {
3893 				/*
3894 				 * Avoid depleting the reserve after a
3895 				 * successful item allocation, even if
3896 				 * M_USE_RESERVE is specified.
3897 				 */
3898 				KEG_UNLOCK(keg, slab->us_domain);
3899 				goto out;
3900 			}
3901 #ifdef NUMA
3902 			/*
3903 			 * If the zone is striped we pick a new slab for every
3904 			 * N allocations.  Eliminating this conditional will
3905 			 * instead pick a new domain for each bucket rather
3906 			 * than stripe within each bucket.  The current option
3907 			 * produces more fragmentation and requires more cpu
3908 			 * time but yields better distribution.
3909 			 */
3910 			if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3911 			    vm_ndomains > 1 && --stripe == 0)
3912 				break;
3913 #endif
3914 		} while (slab->us_freecount != 0 && i < max);
3915 		KEG_UNLOCK(keg, slab->us_domain);
3916 
3917 		/* Don't block if we allocated any successfully. */
3918 		flags &= ~M_WAITOK;
3919 		flags |= M_NOWAIT;
3920 	}
3921 out:
3922 	return i;
3923 }
3924 
3925 static int
3926 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3927 {
3928 	uint64_t old, new, total, max;
3929 
3930 	/*
3931 	 * The hard case.  We're going to sleep because there were existing
3932 	 * sleepers or because we ran out of items.  This routine enforces
3933 	 * fairness by keeping fifo order.
3934 	 *
3935 	 * First release our ill gotten gains and make some noise.
3936 	 */
3937 	for (;;) {
3938 		zone_free_limit(zone, count);
3939 		zone_log_warning(zone);
3940 		zone_maxaction(zone);
3941 		if (flags & M_NOWAIT)
3942 			return (0);
3943 
3944 		/*
3945 		 * We need to allocate an item or set ourself as a sleeper
3946 		 * while the sleepq lock is held to avoid wakeup races.  This
3947 		 * is essentially a home rolled semaphore.
3948 		 */
3949 		sleepq_lock(&zone->uz_max_items);
3950 		old = zone->uz_items;
3951 		do {
3952 			MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3953 			/* Cache the max since we will evaluate twice. */
3954 			max = zone->uz_max_items;
3955 			if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3956 			    UZ_ITEMS_COUNT(old) >= max)
3957 				new = old + UZ_ITEMS_SLEEPER;
3958 			else
3959 				new = old + MIN(count, max - old);
3960 		} while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3961 
3962 		/* We may have successfully allocated under the sleepq lock. */
3963 		if (UZ_ITEMS_SLEEPERS(new) == 0) {
3964 			sleepq_release(&zone->uz_max_items);
3965 			return (new - old);
3966 		}
3967 
3968 		/*
3969 		 * This is in a different cacheline from uz_items so that we
3970 		 * don't constantly invalidate the fastpath cacheline when we
3971 		 * adjust item counts.  This could be limited to toggling on
3972 		 * transitions.
3973 		 */
3974 		atomic_add_32(&zone->uz_sleepers, 1);
3975 		atomic_add_64(&zone->uz_sleeps, 1);
3976 
3977 		/*
3978 		 * We have added ourselves as a sleeper.  The sleepq lock
3979 		 * protects us from wakeup races.  Sleep now and then retry.
3980 		 */
3981 		sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3982 		sleepq_wait(&zone->uz_max_items, PVM);
3983 
3984 		/*
3985 		 * After wakeup, remove ourselves as a sleeper and try
3986 		 * again.  We no longer have the sleepq lock for protection.
3987 		 *
3988 		 * Subract ourselves as a sleeper while attempting to add
3989 		 * our count.
3990 		 */
3991 		atomic_subtract_32(&zone->uz_sleepers, 1);
3992 		old = atomic_fetchadd_64(&zone->uz_items,
3993 		    -(UZ_ITEMS_SLEEPER - count));
3994 		/* We're no longer a sleeper. */
3995 		old -= UZ_ITEMS_SLEEPER;
3996 
3997 		/*
3998 		 * If we're still at the limit, restart.  Notably do not
3999 		 * block on other sleepers.  Cache the max value to protect
4000 		 * against changes via sysctl.
4001 		 */
4002 		total = UZ_ITEMS_COUNT(old);
4003 		max = zone->uz_max_items;
4004 		if (total >= max)
4005 			continue;
4006 		/* Truncate if necessary, otherwise wake other sleepers. */
4007 		if (total + count > max) {
4008 			zone_free_limit(zone, total + count - max);
4009 			count = max - total;
4010 		} else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
4011 			wakeup_one(&zone->uz_max_items);
4012 
4013 		return (count);
4014 	}
4015 }
4016 
4017 /*
4018  * Allocate 'count' items from our max_items limit.  Returns the number
4019  * available.  If M_NOWAIT is not specified it will sleep until at least
4020  * one item can be allocated.
4021  */
4022 static int
4023 zone_alloc_limit(uma_zone_t zone, int count, int flags)
4024 {
4025 	uint64_t old;
4026 	uint64_t max;
4027 
4028 	max = zone->uz_max_items;
4029 	MPASS(max > 0);
4030 
4031 	/*
4032 	 * We expect normal allocations to succeed with a simple
4033 	 * fetchadd.
4034 	 */
4035 	old = atomic_fetchadd_64(&zone->uz_items, count);
4036 	if (__predict_true(old + count <= max))
4037 		return (count);
4038 
4039 	/*
4040 	 * If we had some items and no sleepers just return the
4041 	 * truncated value.  We have to release the excess space
4042 	 * though because that may wake sleepers who weren't woken
4043 	 * because we were temporarily over the limit.
4044 	 */
4045 	if (old < max) {
4046 		zone_free_limit(zone, (old + count) - max);
4047 		return (max - old);
4048 	}
4049 	return (zone_alloc_limit_hard(zone, count, flags));
4050 }
4051 
4052 /*
4053  * Free a number of items back to the limit.
4054  */
4055 static void
4056 zone_free_limit(uma_zone_t zone, int count)
4057 {
4058 	uint64_t old;
4059 
4060 	MPASS(count > 0);
4061 
4062 	/*
4063 	 * In the common case we either have no sleepers or
4064 	 * are still over the limit and can just return.
4065 	 */
4066 	old = atomic_fetchadd_64(&zone->uz_items, -count);
4067 	if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
4068 	   UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
4069 		return;
4070 
4071 	/*
4072 	 * Moderate the rate of wakeups.  Sleepers will continue
4073 	 * to generate wakeups if necessary.
4074 	 */
4075 	wakeup_one(&zone->uz_max_items);
4076 }
4077 
4078 static uma_bucket_t
4079 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
4080 {
4081 	uma_bucket_t bucket;
4082 	int error, maxbucket, cnt;
4083 
4084 	CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
4085 	    zone, domain);
4086 
4087 	/* Avoid allocs targeting empty domains. */
4088 	if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4089 		domain = UMA_ANYDOMAIN;
4090 	else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4091 		domain = UMA_ANYDOMAIN;
4092 
4093 	if (zone->uz_max_items > 0)
4094 		maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
4095 		    M_NOWAIT);
4096 	else
4097 		maxbucket = zone->uz_bucket_size;
4098 	if (maxbucket == 0)
4099 		return (false);
4100 
4101 	/* Don't wait for buckets, preserve caller's NOVM setting. */
4102 	bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
4103 	if (bucket == NULL) {
4104 		cnt = 0;
4105 		goto out;
4106 	}
4107 
4108 	bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
4109 	    MIN(maxbucket, bucket->ub_entries), domain, flags);
4110 
4111 	/*
4112 	 * Initialize the memory if necessary.
4113 	 */
4114 	if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
4115 		int i;
4116 
4117 		for (i = 0; i < bucket->ub_cnt; i++) {
4118 			kasan_mark_item_valid(zone, bucket->ub_bucket[i]);
4119 			error = zone->uz_init(bucket->ub_bucket[i],
4120 			    zone->uz_size, flags);
4121 			kasan_mark_item_invalid(zone, bucket->ub_bucket[i]);
4122 			if (error != 0)
4123 				break;
4124 		}
4125 
4126 		/*
4127 		 * If we couldn't initialize the whole bucket, put the
4128 		 * rest back onto the freelist.
4129 		 */
4130 		if (i != bucket->ub_cnt) {
4131 			zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
4132 			    bucket->ub_cnt - i);
4133 #ifdef INVARIANTS
4134 			bzero(&bucket->ub_bucket[i],
4135 			    sizeof(void *) * (bucket->ub_cnt - i));
4136 #endif
4137 			bucket->ub_cnt = i;
4138 		}
4139 	}
4140 
4141 	cnt = bucket->ub_cnt;
4142 	if (bucket->ub_cnt == 0) {
4143 		bucket_free(zone, bucket, udata);
4144 		counter_u64_add(zone->uz_fails, 1);
4145 		bucket = NULL;
4146 	}
4147 out:
4148 	if (zone->uz_max_items > 0 && cnt < maxbucket)
4149 		zone_free_limit(zone, maxbucket - cnt);
4150 
4151 	return (bucket);
4152 }
4153 
4154 /*
4155  * Allocates a single item from a zone.
4156  *
4157  * Arguments
4158  *	zone   The zone to alloc for.
4159  *	udata  The data to be passed to the constructor.
4160  *	domain The domain to allocate from or UMA_ANYDOMAIN.
4161  *	flags  M_WAITOK, M_NOWAIT, M_ZERO.
4162  *
4163  * Returns
4164  *	NULL if there is no memory and M_NOWAIT is set
4165  *	An item if successful
4166  */
4167 
4168 static void *
4169 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4170 {
4171 	void *item;
4172 
4173 	if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4174 		counter_u64_add(zone->uz_fails, 1);
4175 		return (NULL);
4176 	}
4177 
4178 	/* Avoid allocs targeting empty domains. */
4179 	if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4180 		domain = UMA_ANYDOMAIN;
4181 
4182 	if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4183 		goto fail_cnt;
4184 
4185 	/*
4186 	 * We have to call both the zone's init (not the keg's init)
4187 	 * and the zone's ctor.  This is because the item is going from
4188 	 * a keg slab directly to the user, and the user is expecting it
4189 	 * to be both zone-init'd as well as zone-ctor'd.
4190 	 */
4191 	if (zone->uz_init != NULL) {
4192 		int error;
4193 
4194 		kasan_mark_item_valid(zone, item);
4195 		error = zone->uz_init(item, zone->uz_size, flags);
4196 		kasan_mark_item_invalid(zone, item);
4197 		if (error != 0) {
4198 			zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4199 			goto fail_cnt;
4200 		}
4201 	}
4202 	item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4203 	    item);
4204 	if (item == NULL)
4205 		goto fail;
4206 
4207 	counter_u64_add(zone->uz_allocs, 1);
4208 	CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4209 	    zone->uz_name, zone);
4210 
4211 	return (item);
4212 
4213 fail_cnt:
4214 	counter_u64_add(zone->uz_fails, 1);
4215 fail:
4216 	if (zone->uz_max_items > 0)
4217 		zone_free_limit(zone, 1);
4218 	CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4219 	    zone->uz_name, zone);
4220 
4221 	return (NULL);
4222 }
4223 
4224 /* See uma.h */
4225 void
4226 uma_zfree_smr(uma_zone_t zone, void *item)
4227 {
4228 	uma_cache_t cache;
4229 	uma_cache_bucket_t bucket;
4230 	int itemdomain, uz_flags;
4231 
4232 #ifdef UMA_ZALLOC_DEBUG
4233 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4234 	    ("uma_zfree_smr: called with non-SMR zone."));
4235 	KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4236 	SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4237 	if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4238 		return;
4239 #endif
4240 	cache = &zone->uz_cpu[curcpu];
4241 	uz_flags = cache_uz_flags(cache);
4242 	itemdomain = 0;
4243 #ifdef NUMA
4244 	if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4245 		itemdomain = item_domain(item);
4246 #endif
4247 	critical_enter();
4248 	do {
4249 		cache = &zone->uz_cpu[curcpu];
4250 		/* SMR Zones must free to the free bucket. */
4251 		bucket = &cache->uc_freebucket;
4252 #ifdef NUMA
4253 		if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4254 		    PCPU_GET(domain) != itemdomain) {
4255 			bucket = &cache->uc_crossbucket;
4256 		}
4257 #endif
4258 		if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4259 			cache_bucket_push(cache, bucket, item);
4260 			critical_exit();
4261 			return;
4262 		}
4263 	} while (cache_free(zone, cache, NULL, item, itemdomain));
4264 	critical_exit();
4265 
4266 	/*
4267 	 * If nothing else caught this, we'll just do an internal free.
4268 	 */
4269 	zone_free_item(zone, item, NULL, SKIP_NONE);
4270 }
4271 
4272 /* See uma.h */
4273 void
4274 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4275 {
4276 	uma_cache_t cache;
4277 	uma_cache_bucket_t bucket;
4278 	int itemdomain, uz_flags;
4279 
4280 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4281 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4282 
4283 	CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4284 
4285 #ifdef UMA_ZALLOC_DEBUG
4286 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4287 	    ("uma_zfree_arg: called with SMR zone."));
4288 	if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4289 		return;
4290 #endif
4291         /* uma_zfree(..., NULL) does nothing, to match free(9). */
4292         if (item == NULL)
4293                 return;
4294 
4295 	/*
4296 	 * We are accessing the per-cpu cache without a critical section to
4297 	 * fetch size and flags.  This is acceptable, if we are preempted we
4298 	 * will simply read another cpu's line.
4299 	 */
4300 	cache = &zone->uz_cpu[curcpu];
4301 	uz_flags = cache_uz_flags(cache);
4302 	if (UMA_ALWAYS_CTORDTOR ||
4303 	    __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4304 		item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4305 
4306 	/*
4307 	 * The race here is acceptable.  If we miss it we'll just have to wait
4308 	 * a little longer for the limits to be reset.
4309 	 */
4310 	if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4311 		if (atomic_load_32(&zone->uz_sleepers) > 0)
4312 			goto zfree_item;
4313 	}
4314 
4315 	/*
4316 	 * If possible, free to the per-CPU cache.  There are two
4317 	 * requirements for safe access to the per-CPU cache: (1) the thread
4318 	 * accessing the cache must not be preempted or yield during access,
4319 	 * and (2) the thread must not migrate CPUs without switching which
4320 	 * cache it accesses.  We rely on a critical section to prevent
4321 	 * preemption and migration.  We release the critical section in
4322 	 * order to acquire the zone mutex if we are unable to free to the
4323 	 * current cache; when we re-acquire the critical section, we must
4324 	 * detect and handle migration if it has occurred.
4325 	 */
4326 	itemdomain = 0;
4327 #ifdef NUMA
4328 	if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4329 		itemdomain = item_domain(item);
4330 #endif
4331 	critical_enter();
4332 	do {
4333 		cache = &zone->uz_cpu[curcpu];
4334 		/*
4335 		 * Try to free into the allocbucket first to give LIFO
4336 		 * ordering for cache-hot datastructures.  Spill over
4337 		 * into the freebucket if necessary.  Alloc will swap
4338 		 * them if one runs dry.
4339 		 */
4340 		bucket = &cache->uc_allocbucket;
4341 #ifdef NUMA
4342 		if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4343 		    PCPU_GET(domain) != itemdomain) {
4344 			bucket = &cache->uc_crossbucket;
4345 		} else
4346 #endif
4347 		if (bucket->ucb_cnt == bucket->ucb_entries &&
4348 		   cache->uc_freebucket.ucb_cnt <
4349 		   cache->uc_freebucket.ucb_entries)
4350 			cache_bucket_swap(&cache->uc_freebucket,
4351 			    &cache->uc_allocbucket);
4352 		if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4353 			cache_bucket_push(cache, bucket, item);
4354 			critical_exit();
4355 			return;
4356 		}
4357 	} while (cache_free(zone, cache, udata, item, itemdomain));
4358 	critical_exit();
4359 
4360 	/*
4361 	 * If nothing else caught this, we'll just do an internal free.
4362 	 */
4363 zfree_item:
4364 	zone_free_item(zone, item, udata, SKIP_DTOR);
4365 }
4366 
4367 #ifdef NUMA
4368 /*
4369  * sort crossdomain free buckets to domain correct buckets and cache
4370  * them.
4371  */
4372 static void
4373 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4374 {
4375 	struct uma_bucketlist emptybuckets, fullbuckets;
4376 	uma_zone_domain_t zdom;
4377 	uma_bucket_t b;
4378 	smr_seq_t seq;
4379 	void *item;
4380 	int domain;
4381 
4382 	CTR3(KTR_UMA,
4383 	    "uma_zfree: zone %s(%p) draining cross bucket %p",
4384 	    zone->uz_name, zone, bucket);
4385 
4386 	/*
4387 	 * It is possible for buckets to arrive here out of order so we fetch
4388 	 * the current smr seq rather than accepting the bucket's.
4389 	 */
4390 	seq = SMR_SEQ_INVALID;
4391 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4392 		seq = smr_advance(zone->uz_smr);
4393 
4394 	/*
4395 	 * To avoid having ndomain * ndomain buckets for sorting we have a
4396 	 * lock on the current crossfree bucket.  A full matrix with
4397 	 * per-domain locking could be used if necessary.
4398 	 */
4399 	STAILQ_INIT(&emptybuckets);
4400 	STAILQ_INIT(&fullbuckets);
4401 	ZONE_CROSS_LOCK(zone);
4402 	for (; bucket->ub_cnt > 0; bucket->ub_cnt--) {
4403 		item = bucket->ub_bucket[bucket->ub_cnt - 1];
4404 		domain = item_domain(item);
4405 		zdom = ZDOM_GET(zone, domain);
4406 		if (zdom->uzd_cross == NULL) {
4407 			if ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4408 				STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4409 				zdom->uzd_cross = b;
4410 			} else {
4411 				/*
4412 				 * Avoid allocating a bucket with the cross lock
4413 				 * held, since allocation can trigger a
4414 				 * cross-domain free and bucket zones may
4415 				 * allocate from each other.
4416 				 */
4417 				ZONE_CROSS_UNLOCK(zone);
4418 				b = bucket_alloc(zone, udata, M_NOWAIT);
4419 				if (b == NULL)
4420 					goto out;
4421 				ZONE_CROSS_LOCK(zone);
4422 				if (zdom->uzd_cross != NULL) {
4423 					STAILQ_INSERT_HEAD(&emptybuckets, b,
4424 					    ub_link);
4425 				} else {
4426 					zdom->uzd_cross = b;
4427 				}
4428 			}
4429 		}
4430 		b = zdom->uzd_cross;
4431 		b->ub_bucket[b->ub_cnt++] = item;
4432 		b->ub_seq = seq;
4433 		if (b->ub_cnt == b->ub_entries) {
4434 			STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4435 			if ((b = STAILQ_FIRST(&emptybuckets)) != NULL)
4436 				STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4437 			zdom->uzd_cross = b;
4438 		}
4439 	}
4440 	ZONE_CROSS_UNLOCK(zone);
4441 out:
4442 	if (bucket->ub_cnt == 0)
4443 		bucket->ub_seq = SMR_SEQ_INVALID;
4444 	bucket_free(zone, bucket, udata);
4445 
4446 	while ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4447 		STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4448 		bucket_free(zone, b, udata);
4449 	}
4450 	while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4451 		STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4452 		domain = item_domain(b->ub_bucket[0]);
4453 		zone_put_bucket(zone, domain, b, udata, true);
4454 	}
4455 }
4456 #endif
4457 
4458 static void
4459 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4460     int itemdomain, bool ws)
4461 {
4462 
4463 #ifdef NUMA
4464 	/*
4465 	 * Buckets coming from the wrong domain will be entirely for the
4466 	 * only other domain on two domain systems.  In this case we can
4467 	 * simply cache them.  Otherwise we need to sort them back to
4468 	 * correct domains.
4469 	 */
4470 	if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4471 	    vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4472 		zone_free_cross(zone, bucket, udata);
4473 		return;
4474 	}
4475 #endif
4476 
4477 	/*
4478 	 * Attempt to save the bucket in the zone's domain bucket cache.
4479 	 */
4480 	CTR3(KTR_UMA,
4481 	    "uma_zfree: zone %s(%p) putting bucket %p on free list",
4482 	    zone->uz_name, zone, bucket);
4483 	/* ub_cnt is pointing to the last free item */
4484 	if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4485 		itemdomain = zone_domain_lowest(zone, itemdomain);
4486 	zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4487 }
4488 
4489 /*
4490  * Populate a free or cross bucket for the current cpu cache.  Free any
4491  * existing full bucket either to the zone cache or back to the slab layer.
4492  *
4493  * Enters and returns in a critical section.  false return indicates that
4494  * we can not satisfy this free in the cache layer.  true indicates that
4495  * the caller should retry.
4496  */
4497 static __noinline bool
4498 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4499     int itemdomain)
4500 {
4501 	uma_cache_bucket_t cbucket;
4502 	uma_bucket_t newbucket, bucket;
4503 
4504 	CRITICAL_ASSERT(curthread);
4505 
4506 	if (zone->uz_bucket_size == 0)
4507 		return false;
4508 
4509 	cache = &zone->uz_cpu[curcpu];
4510 	newbucket = NULL;
4511 
4512 	/*
4513 	 * FIRSTTOUCH domains need to free to the correct zdom.  When
4514 	 * enabled this is the zdom of the item.   The bucket is the
4515 	 * cross bucket if the current domain and itemdomain do not match.
4516 	 */
4517 	cbucket = &cache->uc_freebucket;
4518 #ifdef NUMA
4519 	if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4520 		if (PCPU_GET(domain) != itemdomain) {
4521 			cbucket = &cache->uc_crossbucket;
4522 			if (cbucket->ucb_cnt != 0)
4523 				counter_u64_add(zone->uz_xdomain,
4524 				    cbucket->ucb_cnt);
4525 		}
4526 	}
4527 #endif
4528 	bucket = cache_bucket_unload(cbucket);
4529 	KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4530 	    ("cache_free: Entered with non-full free bucket."));
4531 
4532 	/* We are no longer associated with this CPU. */
4533 	critical_exit();
4534 
4535 	/*
4536 	 * Don't let SMR zones operate without a free bucket.  Force
4537 	 * a synchronize and re-use this one.  We will only degrade
4538 	 * to a synchronize every bucket_size items rather than every
4539 	 * item if we fail to allocate a bucket.
4540 	 */
4541 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4542 		if (bucket != NULL)
4543 			bucket->ub_seq = smr_advance(zone->uz_smr);
4544 		newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4545 		if (newbucket == NULL && bucket != NULL) {
4546 			bucket_drain(zone, bucket);
4547 			newbucket = bucket;
4548 			bucket = NULL;
4549 		}
4550 	} else if (!bucketdisable)
4551 		newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4552 
4553 	if (bucket != NULL)
4554 		zone_free_bucket(zone, bucket, udata, itemdomain, true);
4555 
4556 	critical_enter();
4557 	if ((bucket = newbucket) == NULL)
4558 		return (false);
4559 	cache = &zone->uz_cpu[curcpu];
4560 #ifdef NUMA
4561 	/*
4562 	 * Check to see if we should be populating the cross bucket.  If it
4563 	 * is already populated we will fall through and attempt to populate
4564 	 * the free bucket.
4565 	 */
4566 	if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4567 		if (PCPU_GET(domain) != itemdomain &&
4568 		    cache->uc_crossbucket.ucb_bucket == NULL) {
4569 			cache_bucket_load_cross(cache, bucket);
4570 			return (true);
4571 		}
4572 	}
4573 #endif
4574 	/*
4575 	 * We may have lost the race to fill the bucket or switched CPUs.
4576 	 */
4577 	if (cache->uc_freebucket.ucb_bucket != NULL) {
4578 		critical_exit();
4579 		bucket_free(zone, bucket, udata);
4580 		critical_enter();
4581 	} else
4582 		cache_bucket_load_free(cache, bucket);
4583 
4584 	return (true);
4585 }
4586 
4587 static void
4588 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4589 {
4590 	uma_keg_t keg;
4591 	uma_domain_t dom;
4592 	int freei;
4593 
4594 	keg = zone->uz_keg;
4595 	KEG_LOCK_ASSERT(keg, slab->us_domain);
4596 
4597 	/* Do we need to remove from any lists? */
4598 	dom = &keg->uk_domain[slab->us_domain];
4599 	if (slab->us_freecount + 1 == keg->uk_ipers) {
4600 		LIST_REMOVE(slab, us_link);
4601 		LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4602 		dom->ud_free_slabs++;
4603 	} else if (slab->us_freecount == 0) {
4604 		LIST_REMOVE(slab, us_link);
4605 		LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4606 	}
4607 
4608 	/* Slab management. */
4609 	freei = slab_item_index(slab, keg, item);
4610 	BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4611 	slab->us_freecount++;
4612 
4613 	/* Keg statistics. */
4614 	dom->ud_free_items++;
4615 }
4616 
4617 static void
4618 zone_release(void *arg, void **bucket, int cnt)
4619 {
4620 	struct mtx *lock;
4621 	uma_zone_t zone;
4622 	uma_slab_t slab;
4623 	uma_keg_t keg;
4624 	uint8_t *mem;
4625 	void *item;
4626 	int i;
4627 
4628 	zone = arg;
4629 	keg = zone->uz_keg;
4630 	lock = NULL;
4631 	if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4632 		lock = KEG_LOCK(keg, 0);
4633 	for (i = 0; i < cnt; i++) {
4634 		item = bucket[i];
4635 		if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4636 			slab = vtoslab((vm_offset_t)item);
4637 		} else {
4638 			mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4639 			if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4640 				slab = hash_sfind(&keg->uk_hash, mem);
4641 			else
4642 				slab = (uma_slab_t)(mem + keg->uk_pgoff);
4643 		}
4644 		if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4645 			if (lock != NULL)
4646 				mtx_unlock(lock);
4647 			lock = KEG_LOCK(keg, slab->us_domain);
4648 		}
4649 		slab_free_item(zone, slab, item);
4650 	}
4651 	if (lock != NULL)
4652 		mtx_unlock(lock);
4653 }
4654 
4655 /*
4656  * Frees a single item to any zone.
4657  *
4658  * Arguments:
4659  *	zone   The zone to free to
4660  *	item   The item we're freeing
4661  *	udata  User supplied data for the dtor
4662  *	skip   Skip dtors and finis
4663  */
4664 static __noinline void
4665 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4666 {
4667 
4668 	/*
4669 	 * If a free is sent directly to an SMR zone we have to
4670 	 * synchronize immediately because the item can instantly
4671 	 * be reallocated. This should only happen in degenerate
4672 	 * cases when no memory is available for per-cpu caches.
4673 	 */
4674 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4675 		smr_synchronize(zone->uz_smr);
4676 
4677 	item_dtor(zone, item, zone->uz_size, udata, skip);
4678 
4679 	if (skip < SKIP_FINI && zone->uz_fini) {
4680 		kasan_mark_item_valid(zone, item);
4681 		zone->uz_fini(item, zone->uz_size);
4682 		kasan_mark_item_invalid(zone, item);
4683 	}
4684 
4685 	zone->uz_release(zone->uz_arg, &item, 1);
4686 
4687 	if (skip & SKIP_CNT)
4688 		return;
4689 
4690 	counter_u64_add(zone->uz_frees, 1);
4691 
4692 	if (zone->uz_max_items > 0)
4693 		zone_free_limit(zone, 1);
4694 }
4695 
4696 /* See uma.h */
4697 int
4698 uma_zone_set_max(uma_zone_t zone, int nitems)
4699 {
4700 
4701 	/*
4702 	 * If the limit is small, we may need to constrain the maximum per-CPU
4703 	 * cache size, or disable caching entirely.
4704 	 */
4705 	uma_zone_set_maxcache(zone, nitems);
4706 
4707 	/*
4708 	 * XXX This can misbehave if the zone has any allocations with
4709 	 * no limit and a limit is imposed.  There is currently no
4710 	 * way to clear a limit.
4711 	 */
4712 	ZONE_LOCK(zone);
4713 	zone->uz_max_items = nitems;
4714 	zone->uz_flags |= UMA_ZFLAG_LIMIT;
4715 	zone_update_caches(zone);
4716 	/* We may need to wake waiters. */
4717 	wakeup(&zone->uz_max_items);
4718 	ZONE_UNLOCK(zone);
4719 
4720 	return (nitems);
4721 }
4722 
4723 /* See uma.h */
4724 void
4725 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4726 {
4727 	int bpcpu, bpdom, bsize, nb;
4728 
4729 	ZONE_LOCK(zone);
4730 
4731 	/*
4732 	 * Compute a lower bound on the number of items that may be cached in
4733 	 * the zone.  Each CPU gets at least two buckets, and for cross-domain
4734 	 * frees we use an additional bucket per CPU and per domain.  Select the
4735 	 * largest bucket size that does not exceed half of the requested limit,
4736 	 * with the left over space given to the full bucket cache.
4737 	 */
4738 	bpdom = 0;
4739 	bpcpu = 2;
4740 #ifdef NUMA
4741 	if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 && vm_ndomains > 1) {
4742 		bpcpu++;
4743 		bpdom++;
4744 	}
4745 #endif
4746 	nb = bpcpu * mp_ncpus + bpdom * vm_ndomains;
4747 	bsize = nitems / nb / 2;
4748 	if (bsize > BUCKET_MAX)
4749 		bsize = BUCKET_MAX;
4750 	else if (bsize == 0 && nitems / nb > 0)
4751 		bsize = 1;
4752 	zone->uz_bucket_size_max = zone->uz_bucket_size = bsize;
4753 	if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4754 		zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4755 	zone->uz_bucket_max = nitems - nb * bsize;
4756 	ZONE_UNLOCK(zone);
4757 }
4758 
4759 /* See uma.h */
4760 int
4761 uma_zone_get_max(uma_zone_t zone)
4762 {
4763 	int nitems;
4764 
4765 	nitems = atomic_load_64(&zone->uz_max_items);
4766 
4767 	return (nitems);
4768 }
4769 
4770 /* See uma.h */
4771 void
4772 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4773 {
4774 
4775 	ZONE_ASSERT_COLD(zone);
4776 	zone->uz_warning = warning;
4777 }
4778 
4779 /* See uma.h */
4780 void
4781 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4782 {
4783 
4784 	ZONE_ASSERT_COLD(zone);
4785 	TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4786 }
4787 
4788 /* See uma.h */
4789 int
4790 uma_zone_get_cur(uma_zone_t zone)
4791 {
4792 	int64_t nitems;
4793 	u_int i;
4794 
4795 	nitems = 0;
4796 	if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4797 		nitems = counter_u64_fetch(zone->uz_allocs) -
4798 		    counter_u64_fetch(zone->uz_frees);
4799 	CPU_FOREACH(i)
4800 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4801 		    atomic_load_64(&zone->uz_cpu[i].uc_frees);
4802 
4803 	return (nitems < 0 ? 0 : nitems);
4804 }
4805 
4806 static uint64_t
4807 uma_zone_get_allocs(uma_zone_t zone)
4808 {
4809 	uint64_t nitems;
4810 	u_int i;
4811 
4812 	nitems = 0;
4813 	if (zone->uz_allocs != EARLY_COUNTER)
4814 		nitems = counter_u64_fetch(zone->uz_allocs);
4815 	CPU_FOREACH(i)
4816 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4817 
4818 	return (nitems);
4819 }
4820 
4821 static uint64_t
4822 uma_zone_get_frees(uma_zone_t zone)
4823 {
4824 	uint64_t nitems;
4825 	u_int i;
4826 
4827 	nitems = 0;
4828 	if (zone->uz_frees != EARLY_COUNTER)
4829 		nitems = counter_u64_fetch(zone->uz_frees);
4830 	CPU_FOREACH(i)
4831 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4832 
4833 	return (nitems);
4834 }
4835 
4836 #ifdef INVARIANTS
4837 /* Used only for KEG_ASSERT_COLD(). */
4838 static uint64_t
4839 uma_keg_get_allocs(uma_keg_t keg)
4840 {
4841 	uma_zone_t z;
4842 	uint64_t nitems;
4843 
4844 	nitems = 0;
4845 	LIST_FOREACH(z, &keg->uk_zones, uz_link)
4846 		nitems += uma_zone_get_allocs(z);
4847 
4848 	return (nitems);
4849 }
4850 #endif
4851 
4852 /* See uma.h */
4853 void
4854 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4855 {
4856 	uma_keg_t keg;
4857 
4858 	KEG_GET(zone, keg);
4859 	KEG_ASSERT_COLD(keg);
4860 	keg->uk_init = uminit;
4861 }
4862 
4863 /* See uma.h */
4864 void
4865 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4866 {
4867 	uma_keg_t keg;
4868 
4869 	KEG_GET(zone, keg);
4870 	KEG_ASSERT_COLD(keg);
4871 	keg->uk_fini = fini;
4872 }
4873 
4874 /* See uma.h */
4875 void
4876 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4877 {
4878 
4879 	ZONE_ASSERT_COLD(zone);
4880 	zone->uz_init = zinit;
4881 }
4882 
4883 /* See uma.h */
4884 void
4885 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4886 {
4887 
4888 	ZONE_ASSERT_COLD(zone);
4889 	zone->uz_fini = zfini;
4890 }
4891 
4892 /* See uma.h */
4893 void
4894 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4895 {
4896 	uma_keg_t keg;
4897 
4898 	KEG_GET(zone, keg);
4899 	KEG_ASSERT_COLD(keg);
4900 	keg->uk_freef = freef;
4901 }
4902 
4903 /* See uma.h */
4904 void
4905 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4906 {
4907 	uma_keg_t keg;
4908 
4909 	KEG_GET(zone, keg);
4910 	KEG_ASSERT_COLD(keg);
4911 	keg->uk_allocf = allocf;
4912 }
4913 
4914 /* See uma.h */
4915 void
4916 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4917 {
4918 
4919 	ZONE_ASSERT_COLD(zone);
4920 
4921 	KASSERT(smr != NULL, ("Got NULL smr"));
4922 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4923 	    ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4924 	zone->uz_flags |= UMA_ZONE_SMR;
4925 	zone->uz_smr = smr;
4926 	zone_update_caches(zone);
4927 }
4928 
4929 smr_t
4930 uma_zone_get_smr(uma_zone_t zone)
4931 {
4932 
4933 	return (zone->uz_smr);
4934 }
4935 
4936 /* See uma.h */
4937 void
4938 uma_zone_reserve(uma_zone_t zone, int items)
4939 {
4940 	uma_keg_t keg;
4941 
4942 	KEG_GET(zone, keg);
4943 	KEG_ASSERT_COLD(keg);
4944 	keg->uk_reserve = items;
4945 }
4946 
4947 /* See uma.h */
4948 int
4949 uma_zone_reserve_kva(uma_zone_t zone, int count)
4950 {
4951 	uma_keg_t keg;
4952 	vm_offset_t kva;
4953 	u_int pages;
4954 
4955 	KEG_GET(zone, keg);
4956 	KEG_ASSERT_COLD(keg);
4957 	ZONE_ASSERT_COLD(zone);
4958 
4959 	pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4960 
4961 #ifdef UMA_MD_SMALL_ALLOC
4962 	if (keg->uk_ppera > 1) {
4963 #else
4964 	if (1) {
4965 #endif
4966 		kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4967 		if (kva == 0)
4968 			return (0);
4969 	} else
4970 		kva = 0;
4971 
4972 	MPASS(keg->uk_kva == 0);
4973 	keg->uk_kva = kva;
4974 	keg->uk_offset = 0;
4975 	zone->uz_max_items = pages * keg->uk_ipers;
4976 #ifdef UMA_MD_SMALL_ALLOC
4977 	keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4978 #else
4979 	keg->uk_allocf = noobj_alloc;
4980 #endif
4981 	keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4982 	zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4983 	zone_update_caches(zone);
4984 
4985 	return (1);
4986 }
4987 
4988 /* See uma.h */
4989 void
4990 uma_prealloc(uma_zone_t zone, int items)
4991 {
4992 	struct vm_domainset_iter di;
4993 	uma_domain_t dom;
4994 	uma_slab_t slab;
4995 	uma_keg_t keg;
4996 	int aflags, domain, slabs;
4997 
4998 	KEG_GET(zone, keg);
4999 	slabs = howmany(items, keg->uk_ipers);
5000 	while (slabs-- > 0) {
5001 		aflags = M_NOWAIT;
5002 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
5003 		    &aflags);
5004 		for (;;) {
5005 			slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
5006 			    aflags);
5007 			if (slab != NULL) {
5008 				dom = &keg->uk_domain[slab->us_domain];
5009 				/*
5010 				 * keg_alloc_slab() always returns a slab on the
5011 				 * partial list.
5012 				 */
5013 				LIST_REMOVE(slab, us_link);
5014 				LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
5015 				    us_link);
5016 				dom->ud_free_slabs++;
5017 				KEG_UNLOCK(keg, slab->us_domain);
5018 				break;
5019 			}
5020 			if (vm_domainset_iter_policy(&di, &domain) != 0)
5021 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
5022 		}
5023 	}
5024 }
5025 
5026 /*
5027  * Returns a snapshot of memory consumption in bytes.
5028  */
5029 size_t
5030 uma_zone_memory(uma_zone_t zone)
5031 {
5032 	size_t sz;
5033 	int i;
5034 
5035 	sz = 0;
5036 	if (zone->uz_flags & UMA_ZFLAG_CACHE) {
5037 		for (i = 0; i < vm_ndomains; i++)
5038 			sz += ZDOM_GET(zone, i)->uzd_nitems;
5039 		return (sz * zone->uz_size);
5040 	}
5041 	for (i = 0; i < vm_ndomains; i++)
5042 		sz += zone->uz_keg->uk_domain[i].ud_pages;
5043 
5044 	return (sz * PAGE_SIZE);
5045 }
5046 
5047 /* See uma.h */
5048 void
5049 uma_reclaim(int req)
5050 {
5051 	uma_reclaim_domain(req, UMA_ANYDOMAIN);
5052 }
5053 
5054 void
5055 uma_reclaim_domain(int req, int domain)
5056 {
5057 	void *arg;
5058 
5059 	bucket_enable();
5060 
5061 	arg = (void *)(uintptr_t)domain;
5062 	sx_slock(&uma_reclaim_lock);
5063 	switch (req) {
5064 	case UMA_RECLAIM_TRIM:
5065 		zone_foreach(zone_trim, arg);
5066 		break;
5067 	case UMA_RECLAIM_DRAIN:
5068 		zone_foreach(zone_drain, arg);
5069 		break;
5070 	case UMA_RECLAIM_DRAIN_CPU:
5071 		zone_foreach(zone_drain, arg);
5072 		pcpu_cache_drain_safe(NULL);
5073 		zone_foreach(zone_drain, arg);
5074 		break;
5075 	default:
5076 		panic("unhandled reclamation request %d", req);
5077 	}
5078 
5079 	/*
5080 	 * Some slabs may have been freed but this zone will be visited early
5081 	 * we visit again so that we can free pages that are empty once other
5082 	 * zones are drained.  We have to do the same for buckets.
5083 	 */
5084 	zone_drain(slabzones[0], arg);
5085 	zone_drain(slabzones[1], arg);
5086 	bucket_zone_drain(domain);
5087 	sx_sunlock(&uma_reclaim_lock);
5088 }
5089 
5090 static volatile int uma_reclaim_needed;
5091 
5092 void
5093 uma_reclaim_wakeup(void)
5094 {
5095 
5096 	if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
5097 		wakeup(uma_reclaim);
5098 }
5099 
5100 void
5101 uma_reclaim_worker(void *arg __unused)
5102 {
5103 
5104 	for (;;) {
5105 		sx_xlock(&uma_reclaim_lock);
5106 		while (atomic_load_int(&uma_reclaim_needed) == 0)
5107 			sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
5108 			    hz);
5109 		sx_xunlock(&uma_reclaim_lock);
5110 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
5111 		uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
5112 		atomic_store_int(&uma_reclaim_needed, 0);
5113 		/* Don't fire more than once per-second. */
5114 		pause("umarclslp", hz);
5115 	}
5116 }
5117 
5118 /* See uma.h */
5119 void
5120 uma_zone_reclaim(uma_zone_t zone, int req)
5121 {
5122 	uma_zone_reclaim_domain(zone, req, UMA_ANYDOMAIN);
5123 }
5124 
5125 void
5126 uma_zone_reclaim_domain(uma_zone_t zone, int req, int domain)
5127 {
5128 	void *arg;
5129 
5130 	arg = (void *)(uintptr_t)domain;
5131 	switch (req) {
5132 	case UMA_RECLAIM_TRIM:
5133 		zone_trim(zone, arg);
5134 		break;
5135 	case UMA_RECLAIM_DRAIN:
5136 		zone_drain(zone, arg);
5137 		break;
5138 	case UMA_RECLAIM_DRAIN_CPU:
5139 		pcpu_cache_drain_safe(zone);
5140 		zone_drain(zone, arg);
5141 		break;
5142 	default:
5143 		panic("unhandled reclamation request %d", req);
5144 	}
5145 }
5146 
5147 /* See uma.h */
5148 int
5149 uma_zone_exhausted(uma_zone_t zone)
5150 {
5151 
5152 	return (atomic_load_32(&zone->uz_sleepers) > 0);
5153 }
5154 
5155 unsigned long
5156 uma_limit(void)
5157 {
5158 
5159 	return (uma_kmem_limit);
5160 }
5161 
5162 void
5163 uma_set_limit(unsigned long limit)
5164 {
5165 
5166 	uma_kmem_limit = limit;
5167 }
5168 
5169 unsigned long
5170 uma_size(void)
5171 {
5172 
5173 	return (atomic_load_long(&uma_kmem_total));
5174 }
5175 
5176 long
5177 uma_avail(void)
5178 {
5179 
5180 	return (uma_kmem_limit - uma_size());
5181 }
5182 
5183 #ifdef DDB
5184 /*
5185  * Generate statistics across both the zone and its per-cpu cache's.  Return
5186  * desired statistics if the pointer is non-NULL for that statistic.
5187  *
5188  * Note: does not update the zone statistics, as it can't safely clear the
5189  * per-CPU cache statistic.
5190  *
5191  */
5192 static void
5193 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
5194     uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
5195 {
5196 	uma_cache_t cache;
5197 	uint64_t allocs, frees, sleeps, xdomain;
5198 	int cachefree, cpu;
5199 
5200 	allocs = frees = sleeps = xdomain = 0;
5201 	cachefree = 0;
5202 	CPU_FOREACH(cpu) {
5203 		cache = &z->uz_cpu[cpu];
5204 		cachefree += cache->uc_allocbucket.ucb_cnt;
5205 		cachefree += cache->uc_freebucket.ucb_cnt;
5206 		xdomain += cache->uc_crossbucket.ucb_cnt;
5207 		cachefree += cache->uc_crossbucket.ucb_cnt;
5208 		allocs += cache->uc_allocs;
5209 		frees += cache->uc_frees;
5210 	}
5211 	allocs += counter_u64_fetch(z->uz_allocs);
5212 	frees += counter_u64_fetch(z->uz_frees);
5213 	xdomain += counter_u64_fetch(z->uz_xdomain);
5214 	sleeps += z->uz_sleeps;
5215 	if (cachefreep != NULL)
5216 		*cachefreep = cachefree;
5217 	if (allocsp != NULL)
5218 		*allocsp = allocs;
5219 	if (freesp != NULL)
5220 		*freesp = frees;
5221 	if (sleepsp != NULL)
5222 		*sleepsp = sleeps;
5223 	if (xdomainp != NULL)
5224 		*xdomainp = xdomain;
5225 }
5226 #endif /* DDB */
5227 
5228 static int
5229 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5230 {
5231 	uma_keg_t kz;
5232 	uma_zone_t z;
5233 	int count;
5234 
5235 	count = 0;
5236 	rw_rlock(&uma_rwlock);
5237 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5238 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
5239 			count++;
5240 	}
5241 	LIST_FOREACH(z, &uma_cachezones, uz_link)
5242 		count++;
5243 
5244 	rw_runlock(&uma_rwlock);
5245 	return (sysctl_handle_int(oidp, &count, 0, req));
5246 }
5247 
5248 static void
5249 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5250     struct uma_percpu_stat *ups, bool internal)
5251 {
5252 	uma_zone_domain_t zdom;
5253 	uma_cache_t cache;
5254 	int i;
5255 
5256 	for (i = 0; i < vm_ndomains; i++) {
5257 		zdom = ZDOM_GET(z, i);
5258 		uth->uth_zone_free += zdom->uzd_nitems;
5259 	}
5260 	uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5261 	uth->uth_frees = counter_u64_fetch(z->uz_frees);
5262 	uth->uth_fails = counter_u64_fetch(z->uz_fails);
5263 	uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5264 	uth->uth_sleeps = z->uz_sleeps;
5265 
5266 	for (i = 0; i < mp_maxid + 1; i++) {
5267 		bzero(&ups[i], sizeof(*ups));
5268 		if (internal || CPU_ABSENT(i))
5269 			continue;
5270 		cache = &z->uz_cpu[i];
5271 		ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5272 		ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5273 		ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5274 		ups[i].ups_allocs = cache->uc_allocs;
5275 		ups[i].ups_frees = cache->uc_frees;
5276 	}
5277 }
5278 
5279 static int
5280 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5281 {
5282 	struct uma_stream_header ush;
5283 	struct uma_type_header uth;
5284 	struct uma_percpu_stat *ups;
5285 	struct sbuf sbuf;
5286 	uma_keg_t kz;
5287 	uma_zone_t z;
5288 	uint64_t items;
5289 	uint32_t kfree, pages;
5290 	int count, error, i;
5291 
5292 	error = sysctl_wire_old_buffer(req, 0);
5293 	if (error != 0)
5294 		return (error);
5295 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5296 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5297 	ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5298 
5299 	count = 0;
5300 	rw_rlock(&uma_rwlock);
5301 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5302 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
5303 			count++;
5304 	}
5305 
5306 	LIST_FOREACH(z, &uma_cachezones, uz_link)
5307 		count++;
5308 
5309 	/*
5310 	 * Insert stream header.
5311 	 */
5312 	bzero(&ush, sizeof(ush));
5313 	ush.ush_version = UMA_STREAM_VERSION;
5314 	ush.ush_maxcpus = (mp_maxid + 1);
5315 	ush.ush_count = count;
5316 	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5317 
5318 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5319 		kfree = pages = 0;
5320 		for (i = 0; i < vm_ndomains; i++) {
5321 			kfree += kz->uk_domain[i].ud_free_items;
5322 			pages += kz->uk_domain[i].ud_pages;
5323 		}
5324 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5325 			bzero(&uth, sizeof(uth));
5326 			strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5327 			uth.uth_align = kz->uk_align;
5328 			uth.uth_size = kz->uk_size;
5329 			uth.uth_rsize = kz->uk_rsize;
5330 			if (z->uz_max_items > 0) {
5331 				items = UZ_ITEMS_COUNT(z->uz_items);
5332 				uth.uth_pages = (items / kz->uk_ipers) *
5333 					kz->uk_ppera;
5334 			} else
5335 				uth.uth_pages = pages;
5336 			uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5337 			    kz->uk_ppera;
5338 			uth.uth_limit = z->uz_max_items;
5339 			uth.uth_keg_free = kfree;
5340 
5341 			/*
5342 			 * A zone is secondary is it is not the first entry
5343 			 * on the keg's zone list.
5344 			 */
5345 			if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5346 			    (LIST_FIRST(&kz->uk_zones) != z))
5347 				uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5348 			uma_vm_zone_stats(&uth, z, &sbuf, ups,
5349 			    kz->uk_flags & UMA_ZFLAG_INTERNAL);
5350 			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5351 			for (i = 0; i < mp_maxid + 1; i++)
5352 				(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5353 		}
5354 	}
5355 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
5356 		bzero(&uth, sizeof(uth));
5357 		strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5358 		uth.uth_size = z->uz_size;
5359 		uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5360 		(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5361 		for (i = 0; i < mp_maxid + 1; i++)
5362 			(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5363 	}
5364 
5365 	rw_runlock(&uma_rwlock);
5366 	error = sbuf_finish(&sbuf);
5367 	sbuf_delete(&sbuf);
5368 	free(ups, M_TEMP);
5369 	return (error);
5370 }
5371 
5372 int
5373 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5374 {
5375 	uma_zone_t zone = *(uma_zone_t *)arg1;
5376 	int error, max;
5377 
5378 	max = uma_zone_get_max(zone);
5379 	error = sysctl_handle_int(oidp, &max, 0, req);
5380 	if (error || !req->newptr)
5381 		return (error);
5382 
5383 	uma_zone_set_max(zone, max);
5384 
5385 	return (0);
5386 }
5387 
5388 int
5389 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5390 {
5391 	uma_zone_t zone;
5392 	int cur;
5393 
5394 	/*
5395 	 * Some callers want to add sysctls for global zones that
5396 	 * may not yet exist so they pass a pointer to a pointer.
5397 	 */
5398 	if (arg2 == 0)
5399 		zone = *(uma_zone_t *)arg1;
5400 	else
5401 		zone = arg1;
5402 	cur = uma_zone_get_cur(zone);
5403 	return (sysctl_handle_int(oidp, &cur, 0, req));
5404 }
5405 
5406 static int
5407 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5408 {
5409 	uma_zone_t zone = arg1;
5410 	uint64_t cur;
5411 
5412 	cur = uma_zone_get_allocs(zone);
5413 	return (sysctl_handle_64(oidp, &cur, 0, req));
5414 }
5415 
5416 static int
5417 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5418 {
5419 	uma_zone_t zone = arg1;
5420 	uint64_t cur;
5421 
5422 	cur = uma_zone_get_frees(zone);
5423 	return (sysctl_handle_64(oidp, &cur, 0, req));
5424 }
5425 
5426 static int
5427 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5428 {
5429 	struct sbuf sbuf;
5430 	uma_zone_t zone = arg1;
5431 	int error;
5432 
5433 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5434 	if (zone->uz_flags != 0)
5435 		sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5436 	else
5437 		sbuf_printf(&sbuf, "0");
5438 	error = sbuf_finish(&sbuf);
5439 	sbuf_delete(&sbuf);
5440 
5441 	return (error);
5442 }
5443 
5444 static int
5445 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5446 {
5447 	uma_keg_t keg = arg1;
5448 	int avail, effpct, total;
5449 
5450 	total = keg->uk_ppera * PAGE_SIZE;
5451 	if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5452 		total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5453 	/*
5454 	 * We consider the client's requested size and alignment here, not the
5455 	 * real size determination uk_rsize, because we also adjust the real
5456 	 * size for internal implementation reasons (max bitset size).
5457 	 */
5458 	avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5459 	if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5460 		avail *= mp_maxid + 1;
5461 	effpct = 100 * avail / total;
5462 	return (sysctl_handle_int(oidp, &effpct, 0, req));
5463 }
5464 
5465 static int
5466 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5467 {
5468 	uma_zone_t zone = arg1;
5469 	uint64_t cur;
5470 
5471 	cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5472 	return (sysctl_handle_64(oidp, &cur, 0, req));
5473 }
5474 
5475 #ifdef INVARIANTS
5476 static uma_slab_t
5477 uma_dbg_getslab(uma_zone_t zone, void *item)
5478 {
5479 	uma_slab_t slab;
5480 	uma_keg_t keg;
5481 	uint8_t *mem;
5482 
5483 	/*
5484 	 * It is safe to return the slab here even though the
5485 	 * zone is unlocked because the item's allocation state
5486 	 * essentially holds a reference.
5487 	 */
5488 	mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5489 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5490 		return (NULL);
5491 	if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5492 		return (vtoslab((vm_offset_t)mem));
5493 	keg = zone->uz_keg;
5494 	if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5495 		return ((uma_slab_t)(mem + keg->uk_pgoff));
5496 	KEG_LOCK(keg, 0);
5497 	slab = hash_sfind(&keg->uk_hash, mem);
5498 	KEG_UNLOCK(keg, 0);
5499 
5500 	return (slab);
5501 }
5502 
5503 static bool
5504 uma_dbg_zskip(uma_zone_t zone, void *mem)
5505 {
5506 
5507 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5508 		return (true);
5509 
5510 	return (uma_dbg_kskip(zone->uz_keg, mem));
5511 }
5512 
5513 static bool
5514 uma_dbg_kskip(uma_keg_t keg, void *mem)
5515 {
5516 	uintptr_t idx;
5517 
5518 	if (dbg_divisor == 0)
5519 		return (true);
5520 
5521 	if (dbg_divisor == 1)
5522 		return (false);
5523 
5524 	idx = (uintptr_t)mem >> PAGE_SHIFT;
5525 	if (keg->uk_ipers > 1) {
5526 		idx *= keg->uk_ipers;
5527 		idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5528 	}
5529 
5530 	if ((idx / dbg_divisor) * dbg_divisor != idx) {
5531 		counter_u64_add(uma_skip_cnt, 1);
5532 		return (true);
5533 	}
5534 	counter_u64_add(uma_dbg_cnt, 1);
5535 
5536 	return (false);
5537 }
5538 
5539 /*
5540  * Set up the slab's freei data such that uma_dbg_free can function.
5541  *
5542  */
5543 static void
5544 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5545 {
5546 	uma_keg_t keg;
5547 	int freei;
5548 
5549 	if (slab == NULL) {
5550 		slab = uma_dbg_getslab(zone, item);
5551 		if (slab == NULL)
5552 			panic("uma: item %p did not belong to zone %s",
5553 			    item, zone->uz_name);
5554 	}
5555 	keg = zone->uz_keg;
5556 	freei = slab_item_index(slab, keg, item);
5557 
5558 	if (BIT_TEST_SET_ATOMIC(keg->uk_ipers, freei,
5559 	    slab_dbg_bits(slab, keg)))
5560 		panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5561 		    item, zone, zone->uz_name, slab, freei);
5562 }
5563 
5564 /*
5565  * Verifies freed addresses.  Checks for alignment, valid slab membership
5566  * and duplicate frees.
5567  *
5568  */
5569 static void
5570 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5571 {
5572 	uma_keg_t keg;
5573 	int freei;
5574 
5575 	if (slab == NULL) {
5576 		slab = uma_dbg_getslab(zone, item);
5577 		if (slab == NULL)
5578 			panic("uma: Freed item %p did not belong to zone %s",
5579 			    item, zone->uz_name);
5580 	}
5581 	keg = zone->uz_keg;
5582 	freei = slab_item_index(slab, keg, item);
5583 
5584 	if (freei >= keg->uk_ipers)
5585 		panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5586 		    item, zone, zone->uz_name, slab, freei);
5587 
5588 	if (slab_item(slab, keg, freei) != item)
5589 		panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5590 		    item, zone, zone->uz_name, slab, freei);
5591 
5592 	if (!BIT_TEST_CLR_ATOMIC(keg->uk_ipers, freei,
5593 	    slab_dbg_bits(slab, keg)))
5594 		panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5595 		    item, zone, zone->uz_name, slab, freei);
5596 }
5597 #endif /* INVARIANTS */
5598 
5599 #ifdef DDB
5600 static int64_t
5601 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5602     uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5603 {
5604 	uint64_t frees;
5605 	int i;
5606 
5607 	if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5608 		*allocs = counter_u64_fetch(z->uz_allocs);
5609 		frees = counter_u64_fetch(z->uz_frees);
5610 		*sleeps = z->uz_sleeps;
5611 		*cachefree = 0;
5612 		*xdomain = 0;
5613 	} else
5614 		uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5615 		    xdomain);
5616 	for (i = 0; i < vm_ndomains; i++) {
5617 		*cachefree += ZDOM_GET(z, i)->uzd_nitems;
5618 		if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5619 		    (LIST_FIRST(&kz->uk_zones) != z)))
5620 			*cachefree += kz->uk_domain[i].ud_free_items;
5621 	}
5622 	*used = *allocs - frees;
5623 	return (((int64_t)*used + *cachefree) * kz->uk_size);
5624 }
5625 
5626 DB_SHOW_COMMAND(uma, db_show_uma)
5627 {
5628 	const char *fmt_hdr, *fmt_entry;
5629 	uma_keg_t kz;
5630 	uma_zone_t z;
5631 	uint64_t allocs, used, sleeps, xdomain;
5632 	long cachefree;
5633 	/* variables for sorting */
5634 	uma_keg_t cur_keg;
5635 	uma_zone_t cur_zone, last_zone;
5636 	int64_t cur_size, last_size, size;
5637 	int ties;
5638 
5639 	/* /i option produces machine-parseable CSV output */
5640 	if (modif[0] == 'i') {
5641 		fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5642 		fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5643 	} else {
5644 		fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5645 		fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5646 	}
5647 
5648 	db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5649 	    "Sleeps", "Bucket", "Total Mem", "XFree");
5650 
5651 	/* Sort the zones with largest size first. */
5652 	last_zone = NULL;
5653 	last_size = INT64_MAX;
5654 	for (;;) {
5655 		cur_zone = NULL;
5656 		cur_size = -1;
5657 		ties = 0;
5658 		LIST_FOREACH(kz, &uma_kegs, uk_link) {
5659 			LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5660 				/*
5661 				 * In the case of size ties, print out zones
5662 				 * in the order they are encountered.  That is,
5663 				 * when we encounter the most recently output
5664 				 * zone, we have already printed all preceding
5665 				 * ties, and we must print all following ties.
5666 				 */
5667 				if (z == last_zone) {
5668 					ties = 1;
5669 					continue;
5670 				}
5671 				size = get_uma_stats(kz, z, &allocs, &used,
5672 				    &sleeps, &cachefree, &xdomain);
5673 				if (size > cur_size && size < last_size + ties)
5674 				{
5675 					cur_size = size;
5676 					cur_zone = z;
5677 					cur_keg = kz;
5678 				}
5679 			}
5680 		}
5681 		if (cur_zone == NULL)
5682 			break;
5683 
5684 		size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5685 		    &sleeps, &cachefree, &xdomain);
5686 		db_printf(fmt_entry, cur_zone->uz_name,
5687 		    (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5688 		    (uintmax_t)allocs, (uintmax_t)sleeps,
5689 		    (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5690 		    xdomain);
5691 
5692 		if (db_pager_quit)
5693 			return;
5694 		last_zone = cur_zone;
5695 		last_size = cur_size;
5696 	}
5697 }
5698 
5699 DB_SHOW_COMMAND(umacache, db_show_umacache)
5700 {
5701 	uma_zone_t z;
5702 	uint64_t allocs, frees;
5703 	long cachefree;
5704 	int i;
5705 
5706 	db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5707 	    "Requests", "Bucket");
5708 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
5709 		uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5710 		for (i = 0; i < vm_ndomains; i++)
5711 			cachefree += ZDOM_GET(z, i)->uzd_nitems;
5712 		db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5713 		    z->uz_name, (uintmax_t)z->uz_size,
5714 		    (intmax_t)(allocs - frees), cachefree,
5715 		    (uintmax_t)allocs, z->uz_bucket_size);
5716 		if (db_pager_quit)
5717 			return;
5718 	}
5719 }
5720 #endif	/* DDB */
5721