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