xref: /freebsd/sys/vm/uma_core.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2005, 2009, 2013 Jeffrey Roberson <jeff@FreeBSD.org>
5  * Copyright (c) 2004, 2005 Bosko Milekic <bmilekic@FreeBSD.org>
6  * Copyright (c) 2004-2006 Robert N. M. Watson
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/smp.h>
79 #include <sys/taskqueue.h>
80 #include <sys/vmmeter.h>
81 
82 #include <vm/vm.h>
83 #include <vm/vm_domainset.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_phys.h>
89 #include <vm/vm_pagequeue.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/uma.h>
94 #include <vm/uma_int.h>
95 #include <vm/uma_dbg.h>
96 
97 #include <ddb/ddb.h>
98 
99 #ifdef DEBUG_MEMGUARD
100 #include <vm/memguard.h>
101 #endif
102 
103 /*
104  * This is the zone and keg from which all zones are spawned.
105  */
106 static uma_zone_t kegs;
107 static uma_zone_t zones;
108 
109 /* This is the zone from which all offpage uma_slab_ts are allocated. */
110 static uma_zone_t slabzone;
111 
112 /*
113  * The initial hash tables come out of this zone so they can be allocated
114  * prior to malloc coming up.
115  */
116 static uma_zone_t hashzone;
117 
118 /* The boot-time adjusted value for cache line alignment. */
119 int uma_align_cache = 64 - 1;
120 
121 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
122 
123 /*
124  * Are we allowed to allocate buckets?
125  */
126 static int bucketdisable = 1;
127 
128 /* Linked list of all kegs in the system */
129 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
130 
131 /* Linked list of all cache-only zones in the system */
132 static LIST_HEAD(,uma_zone) uma_cachezones =
133     LIST_HEAD_INITIALIZER(uma_cachezones);
134 
135 /* This RW lock protects the keg list */
136 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
137 
138 /*
139  * Pointer and counter to pool of pages, that is preallocated at
140  * startup to bootstrap UMA.
141  */
142 static char *bootmem;
143 static int boot_pages;
144 
145 static struct sx uma_drain_lock;
146 
147 /* kmem soft limit. */
148 static unsigned long uma_kmem_limit = LONG_MAX;
149 static volatile unsigned long uma_kmem_total;
150 
151 /* Is the VM done starting up? */
152 static enum { BOOT_COLD = 0, BOOT_STRAPPED, BOOT_PAGEALLOC, BOOT_BUCKETS,
153     BOOT_RUNNING } booted = BOOT_COLD;
154 
155 /*
156  * This is the handle used to schedule events that need to happen
157  * outside of the allocation fast path.
158  */
159 static struct callout uma_callout;
160 #define	UMA_TIMEOUT	20		/* Seconds for callout interval. */
161 
162 /*
163  * This structure is passed as the zone ctor arg so that I don't have to create
164  * a special allocation function just for zones.
165  */
166 struct uma_zctor_args {
167 	const char *name;
168 	size_t size;
169 	uma_ctor ctor;
170 	uma_dtor dtor;
171 	uma_init uminit;
172 	uma_fini fini;
173 	uma_import import;
174 	uma_release release;
175 	void *arg;
176 	uma_keg_t keg;
177 	int align;
178 	uint32_t flags;
179 };
180 
181 struct uma_kctor_args {
182 	uma_zone_t zone;
183 	size_t size;
184 	uma_init uminit;
185 	uma_fini fini;
186 	int align;
187 	uint32_t flags;
188 };
189 
190 struct uma_bucket_zone {
191 	uma_zone_t	ubz_zone;
192 	char		*ubz_name;
193 	int		ubz_entries;	/* Number of items it can hold. */
194 	int		ubz_maxsize;	/* Maximum allocation size per-item. */
195 };
196 
197 /*
198  * Compute the actual number of bucket entries to pack them in power
199  * of two sizes for more efficient space utilization.
200  */
201 #define	BUCKET_SIZE(n)						\
202     (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
203 
204 #define	BUCKET_MAX	BUCKET_SIZE(256)
205 
206 struct uma_bucket_zone bucket_zones[] = {
207 	{ NULL, "4 Bucket", BUCKET_SIZE(4), 4096 },
208 	{ NULL, "6 Bucket", BUCKET_SIZE(6), 3072 },
209 	{ NULL, "8 Bucket", BUCKET_SIZE(8), 2048 },
210 	{ NULL, "12 Bucket", BUCKET_SIZE(12), 1536 },
211 	{ NULL, "16 Bucket", BUCKET_SIZE(16), 1024 },
212 	{ NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
213 	{ NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
214 	{ NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
215 	{ NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
216 	{ NULL, NULL, 0}
217 };
218 
219 /*
220  * Flags and enumerations to be passed to internal functions.
221  */
222 enum zfreeskip {
223 	SKIP_NONE =	0,
224 	SKIP_CNT =	0x00000001,
225 	SKIP_DTOR =	0x00010000,
226 	SKIP_FINI =	0x00020000,
227 };
228 
229 #define	UMA_ANYDOMAIN	-1	/* Special value for domain search. */
230 
231 /* Prototypes.. */
232 
233 int	uma_startup_count(int);
234 void	uma_startup(void *, int);
235 void	uma_startup1(void);
236 void	uma_startup2(void);
237 
238 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
239 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
240 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
241 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
242 static void page_free(void *, vm_size_t, uint8_t);
243 static void pcpu_page_free(void *, vm_size_t, uint8_t);
244 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
245 static void cache_drain(uma_zone_t);
246 static void bucket_drain(uma_zone_t, uma_bucket_t);
247 static void bucket_cache_drain(uma_zone_t zone);
248 static int keg_ctor(void *, int, void *, int);
249 static void keg_dtor(void *, int, void *);
250 static int zone_ctor(void *, int, void *, int);
251 static void zone_dtor(void *, int, void *);
252 static int zero_init(void *, int, int);
253 static void keg_small_init(uma_keg_t keg);
254 static void keg_large_init(uma_keg_t keg);
255 static void zone_foreach(void (*zfunc)(uma_zone_t));
256 static void zone_timeout(uma_zone_t zone);
257 static int hash_alloc(struct uma_hash *);
258 static int hash_expand(struct uma_hash *, struct uma_hash *);
259 static void hash_free(struct uma_hash *hash);
260 static void uma_timeout(void *);
261 static void uma_startup3(void);
262 static void *zone_alloc_item(uma_zone_t, void *, int, int);
263 static void *zone_alloc_item_locked(uma_zone_t, void *, int, int);
264 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
265 static void bucket_enable(void);
266 static void bucket_init(void);
267 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
268 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
269 static void bucket_zone_drain(void);
270 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int, int);
271 static uma_slab_t zone_fetch_slab(uma_zone_t, uma_keg_t, int, int);
272 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
273 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
274 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
275     uma_fini fini, int align, uint32_t flags);
276 static int zone_import(uma_zone_t, void **, int, int, int);
277 static void zone_release(uma_zone_t, void **, int);
278 static void uma_zero_item(void *, uma_zone_t);
279 
280 void uma_print_zone(uma_zone_t);
281 void uma_print_stats(void);
282 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
283 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
284 
285 #ifdef INVARIANTS
286 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
287 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
288 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
289 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
290 
291 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD, 0,
292     "Memory allocation debugging");
293 
294 static u_int dbg_divisor = 1;
295 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
296     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
297     "Debug & thrash every this item in memory allocator");
298 
299 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
300 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
301 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
302     &uma_dbg_cnt, "memory items debugged");
303 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
304     &uma_skip_cnt, "memory items skipped, not debugged");
305 #endif
306 
307 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
308 
309 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLTYPE_INT,
310     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
311 
312 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
313     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
314 
315 static int zone_warnings = 1;
316 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
317     "Warn when UMA zones becomes full");
318 
319 /* Adjust bytes under management by UMA. */
320 static inline void
321 uma_total_dec(unsigned long size)
322 {
323 
324 	atomic_subtract_long(&uma_kmem_total, size);
325 }
326 
327 static inline void
328 uma_total_inc(unsigned long size)
329 {
330 
331 	if (atomic_fetchadd_long(&uma_kmem_total, size) > uma_kmem_limit)
332 		uma_reclaim_wakeup();
333 }
334 
335 /*
336  * This routine checks to see whether or not it's safe to enable buckets.
337  */
338 static void
339 bucket_enable(void)
340 {
341 	bucketdisable = vm_page_count_min();
342 }
343 
344 /*
345  * Initialize bucket_zones, the array of zones of buckets of various sizes.
346  *
347  * For each zone, calculate the memory required for each bucket, consisting
348  * of the header and an array of pointers.
349  */
350 static void
351 bucket_init(void)
352 {
353 	struct uma_bucket_zone *ubz;
354 	int size;
355 
356 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
357 		size = roundup(sizeof(struct uma_bucket), sizeof(void *));
358 		size += sizeof(void *) * ubz->ubz_entries;
359 		ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
360 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
361 		    UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET | UMA_ZONE_NUMA);
362 	}
363 }
364 
365 /*
366  * Given a desired number of entries for a bucket, return the zone from which
367  * to allocate the bucket.
368  */
369 static struct uma_bucket_zone *
370 bucket_zone_lookup(int entries)
371 {
372 	struct uma_bucket_zone *ubz;
373 
374 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
375 		if (ubz->ubz_entries >= entries)
376 			return (ubz);
377 	ubz--;
378 	return (ubz);
379 }
380 
381 static int
382 bucket_select(int size)
383 {
384 	struct uma_bucket_zone *ubz;
385 
386 	ubz = &bucket_zones[0];
387 	if (size > ubz->ubz_maxsize)
388 		return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
389 
390 	for (; ubz->ubz_entries != 0; ubz++)
391 		if (ubz->ubz_maxsize < size)
392 			break;
393 	ubz--;
394 	return (ubz->ubz_entries);
395 }
396 
397 static uma_bucket_t
398 bucket_alloc(uma_zone_t zone, void *udata, int flags)
399 {
400 	struct uma_bucket_zone *ubz;
401 	uma_bucket_t bucket;
402 
403 	/*
404 	 * This is to stop us from allocating per cpu buckets while we're
405 	 * running out of vm.boot_pages.  Otherwise, we would exhaust the
406 	 * boot pages.  This also prevents us from allocating buckets in
407 	 * low memory situations.
408 	 */
409 	if (bucketdisable)
410 		return (NULL);
411 	/*
412 	 * To limit bucket recursion we store the original zone flags
413 	 * in a cookie passed via zalloc_arg/zfree_arg.  This allows the
414 	 * NOVM flag to persist even through deep recursions.  We also
415 	 * store ZFLAG_BUCKET once we have recursed attempting to allocate
416 	 * a bucket for a bucket zone so we do not allow infinite bucket
417 	 * recursion.  This cookie will even persist to frees of unused
418 	 * buckets via the allocation path or bucket allocations in the
419 	 * free path.
420 	 */
421 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
422 		udata = (void *)(uintptr_t)zone->uz_flags;
423 	else {
424 		if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
425 			return (NULL);
426 		udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
427 	}
428 	if ((uintptr_t)udata & UMA_ZFLAG_CACHEONLY)
429 		flags |= M_NOVM;
430 	ubz = bucket_zone_lookup(zone->uz_count);
431 	if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
432 		ubz++;
433 	bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
434 	if (bucket) {
435 #ifdef INVARIANTS
436 		bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
437 #endif
438 		bucket->ub_cnt = 0;
439 		bucket->ub_entries = ubz->ubz_entries;
440 	}
441 
442 	return (bucket);
443 }
444 
445 static void
446 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
447 {
448 	struct uma_bucket_zone *ubz;
449 
450 	KASSERT(bucket->ub_cnt == 0,
451 	    ("bucket_free: Freeing a non free bucket."));
452 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
453 		udata = (void *)(uintptr_t)zone->uz_flags;
454 	ubz = bucket_zone_lookup(bucket->ub_entries);
455 	uma_zfree_arg(ubz->ubz_zone, bucket, udata);
456 }
457 
458 static void
459 bucket_zone_drain(void)
460 {
461 	struct uma_bucket_zone *ubz;
462 
463 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
464 		zone_drain(ubz->ubz_zone);
465 }
466 
467 static uma_bucket_t
468 zone_try_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, const bool ws)
469 {
470 	uma_bucket_t bucket;
471 
472 	ZONE_LOCK_ASSERT(zone);
473 
474 	if ((bucket = LIST_FIRST(&zdom->uzd_buckets)) != NULL) {
475 		MPASS(zdom->uzd_nitems >= bucket->ub_cnt);
476 		LIST_REMOVE(bucket, ub_link);
477 		zdom->uzd_nitems -= bucket->ub_cnt;
478 		if (ws && zdom->uzd_imin > zdom->uzd_nitems)
479 			zdom->uzd_imin = zdom->uzd_nitems;
480 		zone->uz_bkt_count -= bucket->ub_cnt;
481 	}
482 	return (bucket);
483 }
484 
485 static void
486 zone_put_bucket(uma_zone_t zone, uma_zone_domain_t zdom, uma_bucket_t bucket,
487     const bool ws)
488 {
489 
490 	ZONE_LOCK_ASSERT(zone);
491 	KASSERT(zone->uz_bkt_count < zone->uz_bkt_max, ("%s: zone %p overflow",
492 	    __func__, zone));
493 
494 	LIST_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
495 	zdom->uzd_nitems += bucket->ub_cnt;
496 	if (ws && zdom->uzd_imax < zdom->uzd_nitems)
497 		zdom->uzd_imax = zdom->uzd_nitems;
498 	zone->uz_bkt_count += bucket->ub_cnt;
499 }
500 
501 static void
502 zone_log_warning(uma_zone_t zone)
503 {
504 	static const struct timeval warninterval = { 300, 0 };
505 
506 	if (!zone_warnings || zone->uz_warning == NULL)
507 		return;
508 
509 	if (ratecheck(&zone->uz_ratecheck, &warninterval))
510 		printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
511 }
512 
513 static inline void
514 zone_maxaction(uma_zone_t zone)
515 {
516 
517 	if (zone->uz_maxaction.ta_func != NULL)
518 		taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
519 }
520 
521 /*
522  * Routine called by timeout which is used to fire off some time interval
523  * based calculations.  (stats, hash size, etc.)
524  *
525  * Arguments:
526  *	arg   Unused
527  *
528  * Returns:
529  *	Nothing
530  */
531 static void
532 uma_timeout(void *unused)
533 {
534 	bucket_enable();
535 	zone_foreach(zone_timeout);
536 
537 	/* Reschedule this event */
538 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
539 }
540 
541 /*
542  * Update the working set size estimate for the zone's bucket cache.
543  * The constants chosen here are somewhat arbitrary.  With an update period of
544  * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
545  * last 100s.
546  */
547 static void
548 zone_domain_update_wss(uma_zone_domain_t zdom)
549 {
550 	long wss;
551 
552 	MPASS(zdom->uzd_imax >= zdom->uzd_imin);
553 	wss = zdom->uzd_imax - zdom->uzd_imin;
554 	zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
555 	zdom->uzd_wss = (3 * wss + 2 * zdom->uzd_wss) / 5;
556 }
557 
558 /*
559  * Routine to perform timeout driven calculations.  This expands the
560  * hashes and does per cpu statistics aggregation.
561  *
562  *  Returns nothing.
563  */
564 static void
565 zone_timeout(uma_zone_t zone)
566 {
567 	uma_keg_t keg = zone->uz_keg;
568 
569 	KEG_LOCK(keg);
570 	/*
571 	 * Expand the keg hash table.
572 	 *
573 	 * This is done if the number of slabs is larger than the hash size.
574 	 * What I'm trying to do here is completely reduce collisions.  This
575 	 * may be a little aggressive.  Should I allow for two collisions max?
576 	 */
577 	if (keg->uk_flags & UMA_ZONE_HASH &&
578 	    keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
579 		struct uma_hash newhash;
580 		struct uma_hash oldhash;
581 		int ret;
582 
583 		/*
584 		 * This is so involved because allocating and freeing
585 		 * while the keg lock is held will lead to deadlock.
586 		 * I have to do everything in stages and check for
587 		 * races.
588 		 */
589 		newhash = keg->uk_hash;
590 		KEG_UNLOCK(keg);
591 		ret = hash_alloc(&newhash);
592 		KEG_LOCK(keg);
593 		if (ret) {
594 			if (hash_expand(&keg->uk_hash, &newhash)) {
595 				oldhash = keg->uk_hash;
596 				keg->uk_hash = newhash;
597 			} else
598 				oldhash = newhash;
599 
600 			KEG_UNLOCK(keg);
601 			hash_free(&oldhash);
602 			return;
603 		}
604 	}
605 
606 	for (int i = 0; i < vm_ndomains; i++)
607 		zone_domain_update_wss(&zone->uz_domain[i]);
608 
609 	KEG_UNLOCK(keg);
610 }
611 
612 /*
613  * Allocate and zero fill the next sized hash table from the appropriate
614  * backing store.
615  *
616  * Arguments:
617  *	hash  A new hash structure with the old hash size in uh_hashsize
618  *
619  * Returns:
620  *	1 on success and 0 on failure.
621  */
622 static int
623 hash_alloc(struct uma_hash *hash)
624 {
625 	u_int oldsize;
626 	size_t alloc;
627 
628 	oldsize = hash->uh_hashsize;
629 
630 	/* We're just going to go to a power of two greater */
631 	if (oldsize)  {
632 		hash->uh_hashsize = oldsize * 2;
633 		alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
634 		hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
635 		    M_UMAHASH, M_NOWAIT);
636 	} else {
637 		alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
638 		hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
639 		    UMA_ANYDOMAIN, M_WAITOK);
640 		hash->uh_hashsize = UMA_HASH_SIZE_INIT;
641 	}
642 	if (hash->uh_slab_hash) {
643 		bzero(hash->uh_slab_hash, alloc);
644 		hash->uh_hashmask = hash->uh_hashsize - 1;
645 		return (1);
646 	}
647 
648 	return (0);
649 }
650 
651 /*
652  * Expands the hash table for HASH zones.  This is done from zone_timeout
653  * to reduce collisions.  This must not be done in the regular allocation
654  * path, otherwise, we can recurse on the vm while allocating pages.
655  *
656  * Arguments:
657  *	oldhash  The hash you want to expand
658  *	newhash  The hash structure for the new table
659  *
660  * Returns:
661  *	Nothing
662  *
663  * Discussion:
664  */
665 static int
666 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
667 {
668 	uma_slab_t slab;
669 	u_int hval;
670 	u_int idx;
671 
672 	if (!newhash->uh_slab_hash)
673 		return (0);
674 
675 	if (oldhash->uh_hashsize >= newhash->uh_hashsize)
676 		return (0);
677 
678 	/*
679 	 * I need to investigate hash algorithms for resizing without a
680 	 * full rehash.
681 	 */
682 
683 	for (idx = 0; idx < oldhash->uh_hashsize; idx++)
684 		while (!SLIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
685 			slab = SLIST_FIRST(&oldhash->uh_slab_hash[idx]);
686 			SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[idx], us_hlink);
687 			hval = UMA_HASH(newhash, slab->us_data);
688 			SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
689 			    slab, us_hlink);
690 		}
691 
692 	return (1);
693 }
694 
695 /*
696  * Free the hash bucket to the appropriate backing store.
697  *
698  * Arguments:
699  *	slab_hash  The hash bucket we're freeing
700  *	hashsize   The number of entries in that hash bucket
701  *
702  * Returns:
703  *	Nothing
704  */
705 static void
706 hash_free(struct uma_hash *hash)
707 {
708 	if (hash->uh_slab_hash == NULL)
709 		return;
710 	if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
711 		zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
712 	else
713 		free(hash->uh_slab_hash, M_UMAHASH);
714 }
715 
716 /*
717  * Frees all outstanding items in a bucket
718  *
719  * Arguments:
720  *	zone   The zone to free to, must be unlocked.
721  *	bucket The free/alloc bucket with items, cpu queue must be locked.
722  *
723  * Returns:
724  *	Nothing
725  */
726 
727 static void
728 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
729 {
730 	int i;
731 
732 	if (bucket == NULL)
733 		return;
734 
735 	if (zone->uz_fini)
736 		for (i = 0; i < bucket->ub_cnt; i++)
737 			zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
738 	zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
739 	if (zone->uz_max_items > 0) {
740 		ZONE_LOCK(zone);
741 		zone->uz_items -= bucket->ub_cnt;
742 		if (zone->uz_sleepers && zone->uz_items < zone->uz_max_items)
743 			wakeup_one(zone);
744 		ZONE_UNLOCK(zone);
745 	}
746 	bucket->ub_cnt = 0;
747 }
748 
749 /*
750  * Drains the per cpu caches for a zone.
751  *
752  * NOTE: This may only be called while the zone is being turn down, and not
753  * during normal operation.  This is necessary in order that we do not have
754  * to migrate CPUs to drain the per-CPU caches.
755  *
756  * Arguments:
757  *	zone     The zone to drain, must be unlocked.
758  *
759  * Returns:
760  *	Nothing
761  */
762 static void
763 cache_drain(uma_zone_t zone)
764 {
765 	uma_cache_t cache;
766 	int cpu;
767 
768 	/*
769 	 * XXX: It is safe to not lock the per-CPU caches, because we're
770 	 * tearing down the zone anyway.  I.e., there will be no further use
771 	 * of the caches at this point.
772 	 *
773 	 * XXX: It would good to be able to assert that the zone is being
774 	 * torn down to prevent improper use of cache_drain().
775 	 *
776 	 * XXX: We lock the zone before passing into bucket_cache_drain() as
777 	 * it is used elsewhere.  Should the tear-down path be made special
778 	 * there in some form?
779 	 */
780 	CPU_FOREACH(cpu) {
781 		cache = &zone->uz_cpu[cpu];
782 		bucket_drain(zone, cache->uc_allocbucket);
783 		bucket_drain(zone, cache->uc_freebucket);
784 		if (cache->uc_allocbucket != NULL)
785 			bucket_free(zone, cache->uc_allocbucket, NULL);
786 		if (cache->uc_freebucket != NULL)
787 			bucket_free(zone, cache->uc_freebucket, NULL);
788 		cache->uc_allocbucket = cache->uc_freebucket = NULL;
789 	}
790 	ZONE_LOCK(zone);
791 	bucket_cache_drain(zone);
792 	ZONE_UNLOCK(zone);
793 }
794 
795 static void
796 cache_shrink(uma_zone_t zone)
797 {
798 
799 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
800 		return;
801 
802 	ZONE_LOCK(zone);
803 	zone->uz_count = (zone->uz_count_min + zone->uz_count) / 2;
804 	ZONE_UNLOCK(zone);
805 }
806 
807 static void
808 cache_drain_safe_cpu(uma_zone_t zone)
809 {
810 	uma_cache_t cache;
811 	uma_bucket_t b1, b2;
812 	int domain;
813 
814 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
815 		return;
816 
817 	b1 = b2 = NULL;
818 	ZONE_LOCK(zone);
819 	critical_enter();
820 	if (zone->uz_flags & UMA_ZONE_NUMA)
821 		domain = PCPU_GET(domain);
822 	else
823 		domain = 0;
824 	cache = &zone->uz_cpu[curcpu];
825 	if (cache->uc_allocbucket) {
826 		if (cache->uc_allocbucket->ub_cnt != 0)
827 			zone_put_bucket(zone, &zone->uz_domain[domain],
828 			    cache->uc_allocbucket, false);
829 		else
830 			b1 = cache->uc_allocbucket;
831 		cache->uc_allocbucket = NULL;
832 	}
833 	if (cache->uc_freebucket) {
834 		if (cache->uc_freebucket->ub_cnt != 0)
835 			zone_put_bucket(zone, &zone->uz_domain[domain],
836 			    cache->uc_freebucket, false);
837 		else
838 			b2 = cache->uc_freebucket;
839 		cache->uc_freebucket = NULL;
840 	}
841 	critical_exit();
842 	ZONE_UNLOCK(zone);
843 	if (b1)
844 		bucket_free(zone, b1, NULL);
845 	if (b2)
846 		bucket_free(zone, b2, NULL);
847 }
848 
849 /*
850  * Safely drain per-CPU caches of a zone(s) to alloc bucket.
851  * This is an expensive call because it needs to bind to all CPUs
852  * one by one and enter a critical section on each of them in order
853  * to safely access their cache buckets.
854  * Zone lock must not be held on call this function.
855  */
856 static void
857 cache_drain_safe(uma_zone_t zone)
858 {
859 	int cpu;
860 
861 	/*
862 	 * Polite bucket sizes shrinking was not enouth, shrink aggressively.
863 	 */
864 	if (zone)
865 		cache_shrink(zone);
866 	else
867 		zone_foreach(cache_shrink);
868 
869 	CPU_FOREACH(cpu) {
870 		thread_lock(curthread);
871 		sched_bind(curthread, cpu);
872 		thread_unlock(curthread);
873 
874 		if (zone)
875 			cache_drain_safe_cpu(zone);
876 		else
877 			zone_foreach(cache_drain_safe_cpu);
878 	}
879 	thread_lock(curthread);
880 	sched_unbind(curthread);
881 	thread_unlock(curthread);
882 }
883 
884 /*
885  * Drain the cached buckets from a zone.  Expects a locked zone on entry.
886  */
887 static void
888 bucket_cache_drain(uma_zone_t zone)
889 {
890 	uma_zone_domain_t zdom;
891 	uma_bucket_t bucket;
892 	int i;
893 
894 	/*
895 	 * Drain the bucket queues and free the buckets.
896 	 */
897 	for (i = 0; i < vm_ndomains; i++) {
898 		zdom = &zone->uz_domain[i];
899 		while ((bucket = zone_try_fetch_bucket(zone, zdom, false)) !=
900 		    NULL) {
901 			ZONE_UNLOCK(zone);
902 			bucket_drain(zone, bucket);
903 			bucket_free(zone, bucket, NULL);
904 			ZONE_LOCK(zone);
905 		}
906 	}
907 
908 	/*
909 	 * Shrink further bucket sizes.  Price of single zone lock collision
910 	 * is probably lower then price of global cache drain.
911 	 */
912 	if (zone->uz_count > zone->uz_count_min)
913 		zone->uz_count--;
914 }
915 
916 static void
917 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
918 {
919 	uint8_t *mem;
920 	int i;
921 	uint8_t flags;
922 
923 	CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
924 	    keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
925 
926 	mem = slab->us_data;
927 	flags = slab->us_flags;
928 	i = start;
929 	if (keg->uk_fini != NULL) {
930 		for (i--; i > -1; i--)
931 #ifdef INVARIANTS
932 		/*
933 		 * trash_fini implies that dtor was trash_dtor. trash_fini
934 		 * would check that memory hasn't been modified since free,
935 		 * which executed trash_dtor.
936 		 * That's why we need to run uma_dbg_kskip() check here,
937 		 * albeit we don't make skip check for other init/fini
938 		 * invocations.
939 		 */
940 		if (!uma_dbg_kskip(keg, slab->us_data + (keg->uk_rsize * i)) ||
941 		    keg->uk_fini != trash_fini)
942 #endif
943 			keg->uk_fini(slab->us_data + (keg->uk_rsize * i),
944 			    keg->uk_size);
945 	}
946 	if (keg->uk_flags & UMA_ZONE_OFFPAGE)
947 		zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
948 	keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
949 	uma_total_dec(PAGE_SIZE * keg->uk_ppera);
950 }
951 
952 /*
953  * Frees pages from a keg back to the system.  This is done on demand from
954  * the pageout daemon.
955  *
956  * Returns nothing.
957  */
958 static void
959 keg_drain(uma_keg_t keg)
960 {
961 	struct slabhead freeslabs = { 0 };
962 	uma_domain_t dom;
963 	uma_slab_t slab, tmp;
964 	int i;
965 
966 	/*
967 	 * We don't want to take pages from statically allocated kegs at this
968 	 * time
969 	 */
970 	if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
971 		return;
972 
973 	CTR3(KTR_UMA, "keg_drain %s(%p) free items: %u",
974 	    keg->uk_name, keg, keg->uk_free);
975 	KEG_LOCK(keg);
976 	if (keg->uk_free == 0)
977 		goto finished;
978 
979 	for (i = 0; i < vm_ndomains; i++) {
980 		dom = &keg->uk_domain[i];
981 		LIST_FOREACH_SAFE(slab, &dom->ud_free_slab, us_link, tmp) {
982 			/* We have nowhere to free these to. */
983 			if (slab->us_flags & UMA_SLAB_BOOT)
984 				continue;
985 
986 			LIST_REMOVE(slab, us_link);
987 			keg->uk_pages -= keg->uk_ppera;
988 			keg->uk_free -= keg->uk_ipers;
989 
990 			if (keg->uk_flags & UMA_ZONE_HASH)
991 				UMA_HASH_REMOVE(&keg->uk_hash, slab,
992 				    slab->us_data);
993 
994 			SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
995 		}
996 	}
997 
998 finished:
999 	KEG_UNLOCK(keg);
1000 
1001 	while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
1002 		SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
1003 		keg_free_slab(keg, slab, keg->uk_ipers);
1004 	}
1005 }
1006 
1007 static void
1008 zone_drain_wait(uma_zone_t zone, int waitok)
1009 {
1010 
1011 	/*
1012 	 * Set draining to interlock with zone_dtor() so we can release our
1013 	 * locks as we go.  Only dtor() should do a WAITOK call since it
1014 	 * is the only call that knows the structure will still be available
1015 	 * when it wakes up.
1016 	 */
1017 	ZONE_LOCK(zone);
1018 	while (zone->uz_flags & UMA_ZFLAG_DRAINING) {
1019 		if (waitok == M_NOWAIT)
1020 			goto out;
1021 		msleep(zone, zone->uz_lockptr, PVM, "zonedrain", 1);
1022 	}
1023 	zone->uz_flags |= UMA_ZFLAG_DRAINING;
1024 	bucket_cache_drain(zone);
1025 	ZONE_UNLOCK(zone);
1026 	/*
1027 	 * The DRAINING flag protects us from being freed while
1028 	 * we're running.  Normally the uma_rwlock would protect us but we
1029 	 * must be able to release and acquire the right lock for each keg.
1030 	 */
1031 	keg_drain(zone->uz_keg);
1032 	ZONE_LOCK(zone);
1033 	zone->uz_flags &= ~UMA_ZFLAG_DRAINING;
1034 	wakeup(zone);
1035 out:
1036 	ZONE_UNLOCK(zone);
1037 }
1038 
1039 void
1040 zone_drain(uma_zone_t zone)
1041 {
1042 
1043 	zone_drain_wait(zone, M_NOWAIT);
1044 }
1045 
1046 /*
1047  * Allocate a new slab for a keg.  This does not insert the slab onto a list.
1048  * If the allocation was successful, the keg lock will be held upon return,
1049  * otherwise the keg will be left unlocked.
1050  *
1051  * Arguments:
1052  *	flags   Wait flags for the item initialization routine
1053  *	aflags  Wait flags for the slab allocation
1054  *
1055  * Returns:
1056  *	The slab that was allocated or NULL if there is no memory and the
1057  *	caller specified M_NOWAIT.
1058  */
1059 static uma_slab_t
1060 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1061     int aflags)
1062 {
1063 	uma_alloc allocf;
1064 	uma_slab_t slab;
1065 	unsigned long size;
1066 	uint8_t *mem;
1067 	uint8_t sflags;
1068 	int i;
1069 
1070 	KASSERT(domain >= 0 && domain < vm_ndomains,
1071 	    ("keg_alloc_slab: domain %d out of range", domain));
1072 	KEG_LOCK_ASSERT(keg);
1073 	MPASS(zone->uz_lockptr == &keg->uk_lock);
1074 
1075 	allocf = keg->uk_allocf;
1076 	KEG_UNLOCK(keg);
1077 
1078 	slab = NULL;
1079 	mem = NULL;
1080 	if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
1081 		slab = zone_alloc_item(keg->uk_slabzone, NULL, domain, aflags);
1082 		if (slab == NULL)
1083 			goto out;
1084 	}
1085 
1086 	/*
1087 	 * This reproduces the old vm_zone behavior of zero filling pages the
1088 	 * first time they are added to a zone.
1089 	 *
1090 	 * Malloced items are zeroed in uma_zalloc.
1091 	 */
1092 
1093 	if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1094 		aflags |= M_ZERO;
1095 	else
1096 		aflags &= ~M_ZERO;
1097 
1098 	if (keg->uk_flags & UMA_ZONE_NODUMP)
1099 		aflags |= M_NODUMP;
1100 
1101 	/* zone is passed for legacy reasons. */
1102 	size = keg->uk_ppera * PAGE_SIZE;
1103 	mem = allocf(zone, size, domain, &sflags, aflags);
1104 	if (mem == NULL) {
1105 		if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1106 			zone_free_item(keg->uk_slabzone, slab, NULL, SKIP_NONE);
1107 		slab = NULL;
1108 		goto out;
1109 	}
1110 	uma_total_inc(size);
1111 
1112 	/* Point the slab into the allocated memory */
1113 	if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
1114 		slab = (uma_slab_t )(mem + keg->uk_pgoff);
1115 
1116 	if (keg->uk_flags & UMA_ZONE_VTOSLAB)
1117 		for (i = 0; i < keg->uk_ppera; i++)
1118 			vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
1119 
1120 	slab->us_keg = keg;
1121 	slab->us_data = mem;
1122 	slab->us_freecount = keg->uk_ipers;
1123 	slab->us_flags = sflags;
1124 	slab->us_domain = domain;
1125 	BIT_FILL(SLAB_SETSIZE, &slab->us_free);
1126 #ifdef INVARIANTS
1127 	BIT_ZERO(SLAB_SETSIZE, &slab->us_debugfree);
1128 #endif
1129 
1130 	if (keg->uk_init != NULL) {
1131 		for (i = 0; i < keg->uk_ipers; i++)
1132 			if (keg->uk_init(slab->us_data + (keg->uk_rsize * i),
1133 			    keg->uk_size, flags) != 0)
1134 				break;
1135 		if (i != keg->uk_ipers) {
1136 			keg_free_slab(keg, slab, i);
1137 			slab = NULL;
1138 			goto out;
1139 		}
1140 	}
1141 	KEG_LOCK(keg);
1142 
1143 	CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1144 	    slab, keg->uk_name, keg);
1145 
1146 	if (keg->uk_flags & UMA_ZONE_HASH)
1147 		UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1148 
1149 	keg->uk_pages += keg->uk_ppera;
1150 	keg->uk_free += keg->uk_ipers;
1151 
1152 out:
1153 	return (slab);
1154 }
1155 
1156 /*
1157  * This function is intended to be used early on in place of page_alloc() so
1158  * that we may use the boot time page cache to satisfy allocations before
1159  * the VM is ready.
1160  */
1161 static void *
1162 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1163     int wait)
1164 {
1165 	uma_keg_t keg;
1166 	void *mem;
1167 	int pages;
1168 
1169 	keg = zone->uz_keg;
1170 	/*
1171 	 * If we are in BOOT_BUCKETS or higher, than switch to real
1172 	 * allocator.  Zones with page sized slabs switch at BOOT_PAGEALLOC.
1173 	 */
1174 	switch (booted) {
1175 		case BOOT_COLD:
1176 		case BOOT_STRAPPED:
1177 			break;
1178 		case BOOT_PAGEALLOC:
1179 			if (keg->uk_ppera > 1)
1180 				break;
1181 		case BOOT_BUCKETS:
1182 		case BOOT_RUNNING:
1183 #ifdef UMA_MD_SMALL_ALLOC
1184 			keg->uk_allocf = (keg->uk_ppera > 1) ?
1185 			    page_alloc : uma_small_alloc;
1186 #else
1187 			keg->uk_allocf = page_alloc;
1188 #endif
1189 			return keg->uk_allocf(zone, bytes, domain, pflag, wait);
1190 	}
1191 
1192 	/*
1193 	 * Check our small startup cache to see if it has pages remaining.
1194 	 */
1195 	pages = howmany(bytes, PAGE_SIZE);
1196 	KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1197 	if (pages > boot_pages)
1198 		panic("UMA zone \"%s\": Increase vm.boot_pages", zone->uz_name);
1199 #ifdef DIAGNOSTIC
1200 	printf("%s from \"%s\", %d boot pages left\n", __func__, zone->uz_name,
1201 	    boot_pages);
1202 #endif
1203 	mem = bootmem;
1204 	boot_pages -= pages;
1205 	bootmem += pages * PAGE_SIZE;
1206 	*pflag = UMA_SLAB_BOOT;
1207 
1208 	return (mem);
1209 }
1210 
1211 /*
1212  * Allocates a number of pages from the system
1213  *
1214  * Arguments:
1215  *	bytes  The number of bytes requested
1216  *	wait  Shall we wait?
1217  *
1218  * Returns:
1219  *	A pointer to the alloced memory or possibly
1220  *	NULL if M_NOWAIT is set.
1221  */
1222 static void *
1223 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1224     int wait)
1225 {
1226 	void *p;	/* Returned page */
1227 
1228 	*pflag = UMA_SLAB_KERNEL;
1229 	p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1230 
1231 	return (p);
1232 }
1233 
1234 static void *
1235 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1236     int wait)
1237 {
1238 	struct pglist alloctail;
1239 	vm_offset_t addr, zkva;
1240 	int cpu, flags;
1241 	vm_page_t p, p_next;
1242 #ifdef NUMA
1243 	struct pcpu *pc;
1244 #endif
1245 
1246 	MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1247 
1248 	TAILQ_INIT(&alloctail);
1249 	flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1250 	    malloc2vm_flags(wait);
1251 	*pflag = UMA_SLAB_KERNEL;
1252 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
1253 		if (CPU_ABSENT(cpu)) {
1254 			p = vm_page_alloc(NULL, 0, flags);
1255 		} else {
1256 #ifndef NUMA
1257 			p = vm_page_alloc(NULL, 0, flags);
1258 #else
1259 			pc = pcpu_find(cpu);
1260 			p = vm_page_alloc_domain(NULL, 0, pc->pc_domain, flags);
1261 			if (__predict_false(p == NULL))
1262 				p = vm_page_alloc(NULL, 0, flags);
1263 #endif
1264 		}
1265 		if (__predict_false(p == NULL))
1266 			goto fail;
1267 		TAILQ_INSERT_TAIL(&alloctail, p, listq);
1268 	}
1269 	if ((addr = kva_alloc(bytes)) == 0)
1270 		goto fail;
1271 	zkva = addr;
1272 	TAILQ_FOREACH(p, &alloctail, listq) {
1273 		pmap_qenter(zkva, &p, 1);
1274 		zkva += PAGE_SIZE;
1275 	}
1276 	return ((void*)addr);
1277  fail:
1278 	TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1279 		vm_page_unwire(p, PQ_NONE);
1280 		vm_page_free(p);
1281 	}
1282 	return (NULL);
1283 }
1284 
1285 /*
1286  * Allocates a number of pages from within an object
1287  *
1288  * Arguments:
1289  *	bytes  The number of bytes requested
1290  *	wait   Shall we wait?
1291  *
1292  * Returns:
1293  *	A pointer to the alloced memory or possibly
1294  *	NULL if M_NOWAIT is set.
1295  */
1296 static void *
1297 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1298     int wait)
1299 {
1300 	TAILQ_HEAD(, vm_page) alloctail;
1301 	u_long npages;
1302 	vm_offset_t retkva, zkva;
1303 	vm_page_t p, p_next;
1304 	uma_keg_t keg;
1305 
1306 	TAILQ_INIT(&alloctail);
1307 	keg = zone->uz_keg;
1308 
1309 	npages = howmany(bytes, PAGE_SIZE);
1310 	while (npages > 0) {
1311 		p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1312 		    VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1313 		    ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1314 		    VM_ALLOC_NOWAIT));
1315 		if (p != NULL) {
1316 			/*
1317 			 * Since the page does not belong to an object, its
1318 			 * listq is unused.
1319 			 */
1320 			TAILQ_INSERT_TAIL(&alloctail, p, listq);
1321 			npages--;
1322 			continue;
1323 		}
1324 		/*
1325 		 * Page allocation failed, free intermediate pages and
1326 		 * exit.
1327 		 */
1328 		TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1329 			vm_page_unwire(p, PQ_NONE);
1330 			vm_page_free(p);
1331 		}
1332 		return (NULL);
1333 	}
1334 	*flags = UMA_SLAB_PRIV;
1335 	zkva = keg->uk_kva +
1336 	    atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1337 	retkva = zkva;
1338 	TAILQ_FOREACH(p, &alloctail, listq) {
1339 		pmap_qenter(zkva, &p, 1);
1340 		zkva += PAGE_SIZE;
1341 	}
1342 
1343 	return ((void *)retkva);
1344 }
1345 
1346 /*
1347  * Frees a number of pages to the system
1348  *
1349  * Arguments:
1350  *	mem   A pointer to the memory to be freed
1351  *	size  The size of the memory being freed
1352  *	flags The original p->us_flags field
1353  *
1354  * Returns:
1355  *	Nothing
1356  */
1357 static void
1358 page_free(void *mem, vm_size_t size, uint8_t flags)
1359 {
1360 
1361 	if ((flags & UMA_SLAB_KERNEL) == 0)
1362 		panic("UMA: page_free used with invalid flags %x", flags);
1363 
1364 	kmem_free((vm_offset_t)mem, size);
1365 }
1366 
1367 /*
1368  * Frees pcpu zone allocations
1369  *
1370  * Arguments:
1371  *	mem   A pointer to the memory to be freed
1372  *	size  The size of the memory being freed
1373  *	flags The original p->us_flags field
1374  *
1375  * Returns:
1376  *	Nothing
1377  */
1378 static void
1379 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1380 {
1381 	vm_offset_t sva, curva;
1382 	vm_paddr_t paddr;
1383 	vm_page_t m;
1384 
1385 	MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1386 	sva = (vm_offset_t)mem;
1387 	for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1388 		paddr = pmap_kextract(curva);
1389 		m = PHYS_TO_VM_PAGE(paddr);
1390 		vm_page_unwire(m, PQ_NONE);
1391 		vm_page_free(m);
1392 	}
1393 	pmap_qremove(sva, size >> PAGE_SHIFT);
1394 	kva_free(sva, size);
1395 }
1396 
1397 
1398 /*
1399  * Zero fill initializer
1400  *
1401  * Arguments/Returns follow uma_init specifications
1402  */
1403 static int
1404 zero_init(void *mem, int size, int flags)
1405 {
1406 	bzero(mem, size);
1407 	return (0);
1408 }
1409 
1410 /*
1411  * Finish creating a small uma keg.  This calculates ipers, and the keg size.
1412  *
1413  * Arguments
1414  *	keg  The zone we should initialize
1415  *
1416  * Returns
1417  *	Nothing
1418  */
1419 static void
1420 keg_small_init(uma_keg_t keg)
1421 {
1422 	u_int rsize;
1423 	u_int memused;
1424 	u_int wastedspace;
1425 	u_int shsize;
1426 	u_int slabsize;
1427 
1428 	if (keg->uk_flags & UMA_ZONE_PCPU) {
1429 		u_int ncpus = (mp_maxid + 1) ? (mp_maxid + 1) : MAXCPU;
1430 
1431 		slabsize = UMA_PCPU_ALLOC_SIZE;
1432 		keg->uk_ppera = ncpus;
1433 	} else {
1434 		slabsize = UMA_SLAB_SIZE;
1435 		keg->uk_ppera = 1;
1436 	}
1437 
1438 	/*
1439 	 * Calculate the size of each allocation (rsize) according to
1440 	 * alignment.  If the requested size is smaller than we have
1441 	 * allocation bits for we round it up.
1442 	 */
1443 	rsize = keg->uk_size;
1444 	if (rsize < slabsize / SLAB_SETSIZE)
1445 		rsize = slabsize / SLAB_SETSIZE;
1446 	if (rsize & keg->uk_align)
1447 		rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1448 	keg->uk_rsize = rsize;
1449 
1450 	KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
1451 	    keg->uk_rsize < UMA_PCPU_ALLOC_SIZE,
1452 	    ("%s: size %u too large", __func__, keg->uk_rsize));
1453 
1454 	if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1455 		shsize = 0;
1456 	else
1457 		shsize = SIZEOF_UMA_SLAB;
1458 
1459 	if (rsize <= slabsize - shsize)
1460 		keg->uk_ipers = (slabsize - shsize) / rsize;
1461 	else {
1462 		/* Handle special case when we have 1 item per slab, so
1463 		 * alignment requirement can be relaxed. */
1464 		KASSERT(keg->uk_size <= slabsize - shsize,
1465 		    ("%s: size %u greater than slab", __func__, keg->uk_size));
1466 		keg->uk_ipers = 1;
1467 	}
1468 	KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1469 	    ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1470 
1471 	memused = keg->uk_ipers * rsize + shsize;
1472 	wastedspace = slabsize - memused;
1473 
1474 	/*
1475 	 * We can't do OFFPAGE if we're internal or if we've been
1476 	 * asked to not go to the VM for buckets.  If we do this we
1477 	 * may end up going to the VM  for slabs which we do not
1478 	 * want to do if we're UMA_ZFLAG_CACHEONLY as a result
1479 	 * of UMA_ZONE_VM, which clearly forbids it.
1480 	 */
1481 	if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1482 	    (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1483 		return;
1484 
1485 	/*
1486 	 * See if using an OFFPAGE slab will limit our waste.  Only do
1487 	 * this if it permits more items per-slab.
1488 	 *
1489 	 * XXX We could try growing slabsize to limit max waste as well.
1490 	 * Historically this was not done because the VM could not
1491 	 * efficiently handle contiguous allocations.
1492 	 */
1493 	if ((wastedspace >= slabsize / UMA_MAX_WASTE) &&
1494 	    (keg->uk_ipers < (slabsize / keg->uk_rsize))) {
1495 		keg->uk_ipers = slabsize / keg->uk_rsize;
1496 		KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_SETSIZE,
1497 		    ("%s: keg->uk_ipers %u", __func__, keg->uk_ipers));
1498 		CTR6(KTR_UMA, "UMA decided we need offpage slab headers for "
1499 		    "keg: %s(%p), calculated wastedspace = %d, "
1500 		    "maximum wasted space allowed = %d, "
1501 		    "calculated ipers = %d, "
1502 		    "new wasted space = %d\n", keg->uk_name, keg, wastedspace,
1503 		    slabsize / UMA_MAX_WASTE, keg->uk_ipers,
1504 		    slabsize - keg->uk_ipers * keg->uk_rsize);
1505 		keg->uk_flags |= UMA_ZONE_OFFPAGE;
1506 	}
1507 
1508 	if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1509 	    (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1510 		keg->uk_flags |= UMA_ZONE_HASH;
1511 }
1512 
1513 /*
1514  * Finish creating a large (> UMA_SLAB_SIZE) uma kegs.  Just give in and do
1515  * OFFPAGE for now.  When I can allow for more dynamic slab sizes this will be
1516  * more complicated.
1517  *
1518  * Arguments
1519  *	keg  The keg we should initialize
1520  *
1521  * Returns
1522  *	Nothing
1523  */
1524 static void
1525 keg_large_init(uma_keg_t keg)
1526 {
1527 
1528 	KASSERT(keg != NULL, ("Keg is null in keg_large_init"));
1529 	KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1530 	    ("%s: Cannot large-init a UMA_ZONE_PCPU keg", __func__));
1531 
1532 	keg->uk_ppera = howmany(keg->uk_size, PAGE_SIZE);
1533 	keg->uk_ipers = 1;
1534 	keg->uk_rsize = keg->uk_size;
1535 
1536 	/* Check whether we have enough space to not do OFFPAGE. */
1537 	if ((keg->uk_flags & UMA_ZONE_OFFPAGE) == 0 &&
1538 	    PAGE_SIZE * keg->uk_ppera - keg->uk_rsize < SIZEOF_UMA_SLAB) {
1539 		/*
1540 		 * We can't do OFFPAGE if we're internal, in which case
1541 		 * we need an extra page per allocation to contain the
1542 		 * slab header.
1543 		 */
1544 		if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) == 0)
1545 			keg->uk_flags |= UMA_ZONE_OFFPAGE;
1546 		else
1547 			keg->uk_ppera++;
1548 	}
1549 
1550 	if ((keg->uk_flags & UMA_ZONE_OFFPAGE) &&
1551 	    (keg->uk_flags & UMA_ZONE_VTOSLAB) == 0)
1552 		keg->uk_flags |= UMA_ZONE_HASH;
1553 }
1554 
1555 static void
1556 keg_cachespread_init(uma_keg_t keg)
1557 {
1558 	int alignsize;
1559 	int trailer;
1560 	int pages;
1561 	int rsize;
1562 
1563 	KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0,
1564 	    ("%s: Cannot cachespread-init a UMA_ZONE_PCPU keg", __func__));
1565 
1566 	alignsize = keg->uk_align + 1;
1567 	rsize = keg->uk_size;
1568 	/*
1569 	 * We want one item to start on every align boundary in a page.  To
1570 	 * do this we will span pages.  We will also extend the item by the
1571 	 * size of align if it is an even multiple of align.  Otherwise, it
1572 	 * would fall on the same boundary every time.
1573 	 */
1574 	if (rsize & keg->uk_align)
1575 		rsize = (rsize & ~keg->uk_align) + alignsize;
1576 	if ((rsize & alignsize) == 0)
1577 		rsize += alignsize;
1578 	trailer = rsize - keg->uk_size;
1579 	pages = (rsize * (PAGE_SIZE / alignsize)) / PAGE_SIZE;
1580 	pages = MIN(pages, (128 * 1024) / PAGE_SIZE);
1581 	keg->uk_rsize = rsize;
1582 	keg->uk_ppera = pages;
1583 	keg->uk_ipers = ((pages * PAGE_SIZE) + trailer) / rsize;
1584 	keg->uk_flags |= UMA_ZONE_OFFPAGE | UMA_ZONE_VTOSLAB;
1585 	KASSERT(keg->uk_ipers <= SLAB_SETSIZE,
1586 	    ("%s: keg->uk_ipers too high(%d) increase max_ipers", __func__,
1587 	    keg->uk_ipers));
1588 }
1589 
1590 /*
1591  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
1592  * the keg onto the global keg list.
1593  *
1594  * Arguments/Returns follow uma_ctor specifications
1595  *	udata  Actually uma_kctor_args
1596  */
1597 static int
1598 keg_ctor(void *mem, int size, void *udata, int flags)
1599 {
1600 	struct uma_kctor_args *arg = udata;
1601 	uma_keg_t keg = mem;
1602 	uma_zone_t zone;
1603 
1604 	bzero(keg, size);
1605 	keg->uk_size = arg->size;
1606 	keg->uk_init = arg->uminit;
1607 	keg->uk_fini = arg->fini;
1608 	keg->uk_align = arg->align;
1609 	keg->uk_free = 0;
1610 	keg->uk_reserve = 0;
1611 	keg->uk_pages = 0;
1612 	keg->uk_flags = arg->flags;
1613 	keg->uk_slabzone = NULL;
1614 
1615 	/*
1616 	 * We use a global round-robin policy by default.  Zones with
1617 	 * UMA_ZONE_NUMA set will use first-touch instead, in which case the
1618 	 * iterator is never run.
1619 	 */
1620 	keg->uk_dr.dr_policy = DOMAINSET_RR();
1621 	keg->uk_dr.dr_iter = 0;
1622 
1623 	/*
1624 	 * The master zone is passed to us at keg-creation time.
1625 	 */
1626 	zone = arg->zone;
1627 	keg->uk_name = zone->uz_name;
1628 
1629 	if (arg->flags & UMA_ZONE_VM)
1630 		keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1631 
1632 	if (arg->flags & UMA_ZONE_ZINIT)
1633 		keg->uk_init = zero_init;
1634 
1635 	if (arg->flags & UMA_ZONE_MALLOC)
1636 		keg->uk_flags |= UMA_ZONE_VTOSLAB;
1637 
1638 	if (arg->flags & UMA_ZONE_PCPU)
1639 #ifdef SMP
1640 		keg->uk_flags |= UMA_ZONE_OFFPAGE;
1641 #else
1642 		keg->uk_flags &= ~UMA_ZONE_PCPU;
1643 #endif
1644 
1645 	if (keg->uk_flags & UMA_ZONE_CACHESPREAD) {
1646 		keg_cachespread_init(keg);
1647 	} else {
1648 		if (keg->uk_size > UMA_SLAB_SPACE)
1649 			keg_large_init(keg);
1650 		else
1651 			keg_small_init(keg);
1652 	}
1653 
1654 	if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1655 		keg->uk_slabzone = slabzone;
1656 
1657 	/*
1658 	 * If we haven't booted yet we need allocations to go through the
1659 	 * startup cache until the vm is ready.
1660 	 */
1661 	if (booted < BOOT_PAGEALLOC)
1662 		keg->uk_allocf = startup_alloc;
1663 #ifdef UMA_MD_SMALL_ALLOC
1664 	else if (keg->uk_ppera == 1)
1665 		keg->uk_allocf = uma_small_alloc;
1666 #endif
1667 	else if (keg->uk_flags & UMA_ZONE_PCPU)
1668 		keg->uk_allocf = pcpu_page_alloc;
1669 	else
1670 		keg->uk_allocf = page_alloc;
1671 #ifdef UMA_MD_SMALL_ALLOC
1672 	if (keg->uk_ppera == 1)
1673 		keg->uk_freef = uma_small_free;
1674 	else
1675 #endif
1676 	if (keg->uk_flags & UMA_ZONE_PCPU)
1677 		keg->uk_freef = pcpu_page_free;
1678 	else
1679 		keg->uk_freef = page_free;
1680 
1681 	/*
1682 	 * Initialize keg's lock
1683 	 */
1684 	KEG_LOCK_INIT(keg, (arg->flags & UMA_ZONE_MTXCLASS));
1685 
1686 	/*
1687 	 * If we're putting the slab header in the actual page we need to
1688 	 * figure out where in each page it goes.  See SIZEOF_UMA_SLAB
1689 	 * macro definition.
1690 	 */
1691 	if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1692 		keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - SIZEOF_UMA_SLAB;
1693 		/*
1694 		 * The only way the following is possible is if with our
1695 		 * UMA_ALIGN_PTR adjustments we are now bigger than
1696 		 * UMA_SLAB_SIZE.  I haven't checked whether this is
1697 		 * mathematically possible for all cases, so we make
1698 		 * sure here anyway.
1699 		 */
1700 		KASSERT(keg->uk_pgoff + sizeof(struct uma_slab) <=
1701 		    PAGE_SIZE * keg->uk_ppera,
1702 		    ("zone %s ipers %d rsize %d size %d slab won't fit",
1703 		    zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
1704 	}
1705 
1706 	if (keg->uk_flags & UMA_ZONE_HASH)
1707 		hash_alloc(&keg->uk_hash);
1708 
1709 	CTR5(KTR_UMA, "keg_ctor %p zone %s(%p) out %d free %d\n",
1710 	    keg, zone->uz_name, zone,
1711 	    (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
1712 	    keg->uk_free);
1713 
1714 	LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1715 
1716 	rw_wlock(&uma_rwlock);
1717 	LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1718 	rw_wunlock(&uma_rwlock);
1719 	return (0);
1720 }
1721 
1722 static void
1723 zone_alloc_counters(uma_zone_t zone)
1724 {
1725 
1726 	zone->uz_allocs = counter_u64_alloc(M_WAITOK);
1727 	zone->uz_frees = counter_u64_alloc(M_WAITOK);
1728 	zone->uz_fails = counter_u64_alloc(M_WAITOK);
1729 }
1730 
1731 /*
1732  * Zone header ctor.  This initializes all fields, locks, etc.
1733  *
1734  * Arguments/Returns follow uma_ctor specifications
1735  *	udata  Actually uma_zctor_args
1736  */
1737 static int
1738 zone_ctor(void *mem, int size, void *udata, int flags)
1739 {
1740 	struct uma_zctor_args *arg = udata;
1741 	uma_zone_t zone = mem;
1742 	uma_zone_t z;
1743 	uma_keg_t keg;
1744 
1745 	bzero(zone, size);
1746 	zone->uz_name = arg->name;
1747 	zone->uz_ctor = arg->ctor;
1748 	zone->uz_dtor = arg->dtor;
1749 	zone->uz_init = NULL;
1750 	zone->uz_fini = NULL;
1751 	zone->uz_sleeps = 0;
1752 	zone->uz_count = 0;
1753 	zone->uz_count_min = 0;
1754 	zone->uz_count_max = BUCKET_MAX;
1755 	zone->uz_flags = 0;
1756 	zone->uz_warning = NULL;
1757 	/* The domain structures follow the cpu structures. */
1758 	zone->uz_domain = (struct uma_zone_domain *)&zone->uz_cpu[mp_ncpus];
1759 	zone->uz_bkt_max = ULONG_MAX;
1760 	timevalclear(&zone->uz_ratecheck);
1761 
1762 	if (__predict_true(booted == BOOT_RUNNING))
1763 		zone_alloc_counters(zone);
1764 	else {
1765 		zone->uz_allocs = EARLY_COUNTER;
1766 		zone->uz_frees = EARLY_COUNTER;
1767 		zone->uz_fails = EARLY_COUNTER;
1768 	}
1769 
1770 	/*
1771 	 * This is a pure cache zone, no kegs.
1772 	 */
1773 	if (arg->import) {
1774 		if (arg->flags & UMA_ZONE_VM)
1775 			arg->flags |= UMA_ZFLAG_CACHEONLY;
1776 		zone->uz_flags = arg->flags;
1777 		zone->uz_size = arg->size;
1778 		zone->uz_import = arg->import;
1779 		zone->uz_release = arg->release;
1780 		zone->uz_arg = arg->arg;
1781 		zone->uz_lockptr = &zone->uz_lock;
1782 		ZONE_LOCK_INIT(zone, (arg->flags & UMA_ZONE_MTXCLASS));
1783 		rw_wlock(&uma_rwlock);
1784 		LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
1785 		rw_wunlock(&uma_rwlock);
1786 		goto out;
1787 	}
1788 
1789 	/*
1790 	 * Use the regular zone/keg/slab allocator.
1791 	 */
1792 	zone->uz_import = (uma_import)zone_import;
1793 	zone->uz_release = (uma_release)zone_release;
1794 	zone->uz_arg = zone;
1795 	keg = arg->keg;
1796 
1797 	if (arg->flags & UMA_ZONE_SECONDARY) {
1798 		KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1799 		zone->uz_init = arg->uminit;
1800 		zone->uz_fini = arg->fini;
1801 		zone->uz_lockptr = &keg->uk_lock;
1802 		zone->uz_flags |= UMA_ZONE_SECONDARY;
1803 		rw_wlock(&uma_rwlock);
1804 		ZONE_LOCK(zone);
1805 		LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1806 			if (LIST_NEXT(z, uz_link) == NULL) {
1807 				LIST_INSERT_AFTER(z, zone, uz_link);
1808 				break;
1809 			}
1810 		}
1811 		ZONE_UNLOCK(zone);
1812 		rw_wunlock(&uma_rwlock);
1813 	} else if (keg == NULL) {
1814 		if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1815 		    arg->align, arg->flags)) == NULL)
1816 			return (ENOMEM);
1817 	} else {
1818 		struct uma_kctor_args karg;
1819 		int error;
1820 
1821 		/* We should only be here from uma_startup() */
1822 		karg.size = arg->size;
1823 		karg.uminit = arg->uminit;
1824 		karg.fini = arg->fini;
1825 		karg.align = arg->align;
1826 		karg.flags = arg->flags;
1827 		karg.zone = zone;
1828 		error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
1829 		    flags);
1830 		if (error)
1831 			return (error);
1832 	}
1833 
1834 	zone->uz_keg = keg;
1835 	zone->uz_size = keg->uk_size;
1836 	zone->uz_flags |= (keg->uk_flags &
1837 	    (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
1838 
1839 	/*
1840 	 * Some internal zones don't have room allocated for the per cpu
1841 	 * caches.  If we're internal, bail out here.
1842 	 */
1843 	if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1844 		KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
1845 		    ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1846 		return (0);
1847 	}
1848 
1849 out:
1850 	KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
1851 	    (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
1852 	    ("Invalid zone flag combination"));
1853 	if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
1854 		zone->uz_count = BUCKET_MAX;
1855 	else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
1856 		zone->uz_count = 0;
1857 	else
1858 		zone->uz_count = bucket_select(zone->uz_size);
1859 	zone->uz_count_min = zone->uz_count;
1860 
1861 	return (0);
1862 }
1863 
1864 /*
1865  * Keg header dtor.  This frees all data, destroys locks, frees the hash
1866  * table and removes the keg from the global list.
1867  *
1868  * Arguments/Returns follow uma_dtor specifications
1869  *	udata  unused
1870  */
1871 static void
1872 keg_dtor(void *arg, int size, void *udata)
1873 {
1874 	uma_keg_t keg;
1875 
1876 	keg = (uma_keg_t)arg;
1877 	KEG_LOCK(keg);
1878 	if (keg->uk_free != 0) {
1879 		printf("Freed UMA keg (%s) was not empty (%d items). "
1880 		    " Lost %d pages of memory.\n",
1881 		    keg->uk_name ? keg->uk_name : "",
1882 		    keg->uk_free, keg->uk_pages);
1883 	}
1884 	KEG_UNLOCK(keg);
1885 
1886 	hash_free(&keg->uk_hash);
1887 
1888 	KEG_LOCK_FINI(keg);
1889 }
1890 
1891 /*
1892  * Zone header dtor.
1893  *
1894  * Arguments/Returns follow uma_dtor specifications
1895  *	udata  unused
1896  */
1897 static void
1898 zone_dtor(void *arg, int size, void *udata)
1899 {
1900 	uma_zone_t zone;
1901 	uma_keg_t keg;
1902 
1903 	zone = (uma_zone_t)arg;
1904 
1905 	if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
1906 		cache_drain(zone);
1907 
1908 	rw_wlock(&uma_rwlock);
1909 	LIST_REMOVE(zone, uz_link);
1910 	rw_wunlock(&uma_rwlock);
1911 	/*
1912 	 * XXX there are some races here where
1913 	 * the zone can be drained but zone lock
1914 	 * released and then refilled before we
1915 	 * remove it... we dont care for now
1916 	 */
1917 	zone_drain_wait(zone, M_WAITOK);
1918 	/*
1919 	 * We only destroy kegs from non secondary zones.
1920 	 */
1921 	if ((keg = zone->uz_keg) != NULL &&
1922 	    (zone->uz_flags & UMA_ZONE_SECONDARY) == 0)  {
1923 		rw_wlock(&uma_rwlock);
1924 		LIST_REMOVE(keg, uk_link);
1925 		rw_wunlock(&uma_rwlock);
1926 		zone_free_item(kegs, keg, NULL, SKIP_NONE);
1927 	}
1928 	counter_u64_free(zone->uz_allocs);
1929 	counter_u64_free(zone->uz_frees);
1930 	counter_u64_free(zone->uz_fails);
1931 	if (zone->uz_lockptr == &zone->uz_lock)
1932 		ZONE_LOCK_FINI(zone);
1933 }
1934 
1935 /*
1936  * Traverses every zone in the system and calls a callback
1937  *
1938  * Arguments:
1939  *	zfunc  A pointer to a function which accepts a zone
1940  *		as an argument.
1941  *
1942  * Returns:
1943  *	Nothing
1944  */
1945 static void
1946 zone_foreach(void (*zfunc)(uma_zone_t))
1947 {
1948 	uma_keg_t keg;
1949 	uma_zone_t zone;
1950 
1951 	/*
1952 	 * Before BOOT_RUNNING we are guaranteed to be single
1953 	 * threaded, so locking isn't needed. Startup functions
1954 	 * are allowed to use M_WAITOK.
1955 	 */
1956 	if (__predict_true(booted == BOOT_RUNNING))
1957 		rw_rlock(&uma_rwlock);
1958 	LIST_FOREACH(keg, &uma_kegs, uk_link) {
1959 		LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1960 			zfunc(zone);
1961 	}
1962 	if (__predict_true(booted == BOOT_RUNNING))
1963 		rw_runlock(&uma_rwlock);
1964 }
1965 
1966 /*
1967  * Count how many pages do we need to bootstrap.  VM supplies
1968  * its need in early zones in the argument, we add up our zones,
1969  * which consist of: UMA Slabs, UMA Hash and 9 Bucket zones. The
1970  * zone of zones and zone of kegs are accounted separately.
1971  */
1972 #define	UMA_BOOT_ZONES	11
1973 /* Zone of zones and zone of kegs have arbitrary alignment. */
1974 #define	UMA_BOOT_ALIGN	32
1975 static int zsize, ksize;
1976 int
1977 uma_startup_count(int vm_zones)
1978 {
1979 	int zones, pages;
1980 
1981 	ksize = sizeof(struct uma_keg) +
1982 	    (sizeof(struct uma_domain) * vm_ndomains);
1983 	zsize = sizeof(struct uma_zone) +
1984 	    (sizeof(struct uma_cache) * (mp_maxid + 1)) +
1985 	    (sizeof(struct uma_zone_domain) * vm_ndomains);
1986 
1987 	/*
1988 	 * Memory for the zone of kegs and its keg,
1989 	 * and for zone of zones.
1990 	 */
1991 	pages = howmany(roundup(zsize, CACHE_LINE_SIZE) * 2 +
1992 	    roundup(ksize, CACHE_LINE_SIZE), PAGE_SIZE);
1993 
1994 #ifdef	UMA_MD_SMALL_ALLOC
1995 	zones = UMA_BOOT_ZONES;
1996 #else
1997 	zones = UMA_BOOT_ZONES + vm_zones;
1998 	vm_zones = 0;
1999 #endif
2000 
2001 	/* Memory for the rest of startup zones, UMA and VM, ... */
2002 	if (zsize > UMA_SLAB_SPACE) {
2003 		/* See keg_large_init(). */
2004 		u_int ppera;
2005 
2006 		ppera = howmany(roundup2(zsize, UMA_BOOT_ALIGN), PAGE_SIZE);
2007 		if (PAGE_SIZE * ppera - roundup2(zsize, UMA_BOOT_ALIGN) <
2008 		    SIZEOF_UMA_SLAB)
2009 			ppera++;
2010 		pages += (zones + vm_zones) * ppera;
2011 	} else if (roundup2(zsize, UMA_BOOT_ALIGN) > UMA_SLAB_SPACE)
2012 		/* See keg_small_init() special case for uk_ppera = 1. */
2013 		pages += zones;
2014 	else
2015 		pages += howmany(zones,
2016 		    UMA_SLAB_SPACE / roundup2(zsize, UMA_BOOT_ALIGN));
2017 
2018 	/* ... and their kegs. Note that zone of zones allocates a keg! */
2019 	pages += howmany(zones + 1,
2020 	    UMA_SLAB_SPACE / roundup2(ksize, UMA_BOOT_ALIGN));
2021 
2022 	/*
2023 	 * Most of startup zones are not going to be offpages, that's
2024 	 * why we use UMA_SLAB_SPACE instead of UMA_SLAB_SIZE in all
2025 	 * calculations.  Some large bucket zones will be offpage, and
2026 	 * thus will allocate hashes.  We take conservative approach
2027 	 * and assume that all zones may allocate hash.  This may give
2028 	 * us some positive inaccuracy, usually an extra single page.
2029 	 */
2030 	pages += howmany(zones, UMA_SLAB_SPACE /
2031 	    (sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT));
2032 
2033 	return (pages);
2034 }
2035 
2036 void
2037 uma_startup(void *mem, int npages)
2038 {
2039 	struct uma_zctor_args args;
2040 	uma_keg_t masterkeg;
2041 	uintptr_t m;
2042 
2043 #ifdef DIAGNOSTIC
2044 	printf("Entering %s with %d boot pages configured\n", __func__, npages);
2045 #endif
2046 
2047 	rw_init(&uma_rwlock, "UMA lock");
2048 
2049 	/* Use bootpages memory for the zone of zones and zone of kegs. */
2050 	m = (uintptr_t)mem;
2051 	zones = (uma_zone_t)m;
2052 	m += roundup(zsize, CACHE_LINE_SIZE);
2053 	kegs = (uma_zone_t)m;
2054 	m += roundup(zsize, CACHE_LINE_SIZE);
2055 	masterkeg = (uma_keg_t)m;
2056 	m += roundup(ksize, CACHE_LINE_SIZE);
2057 	m = roundup(m, PAGE_SIZE);
2058 	npages -= (m - (uintptr_t)mem) / PAGE_SIZE;
2059 	mem = (void *)m;
2060 
2061 	/* "manually" create the initial zone */
2062 	memset(&args, 0, sizeof(args));
2063 	args.name = "UMA Kegs";
2064 	args.size = ksize;
2065 	args.ctor = keg_ctor;
2066 	args.dtor = keg_dtor;
2067 	args.uminit = zero_init;
2068 	args.fini = NULL;
2069 	args.keg = masterkeg;
2070 	args.align = UMA_BOOT_ALIGN - 1;
2071 	args.flags = UMA_ZFLAG_INTERNAL;
2072 	zone_ctor(kegs, zsize, &args, M_WAITOK);
2073 
2074 	bootmem = mem;
2075 	boot_pages = npages;
2076 
2077 	args.name = "UMA Zones";
2078 	args.size = zsize;
2079 	args.ctor = zone_ctor;
2080 	args.dtor = zone_dtor;
2081 	args.uminit = zero_init;
2082 	args.fini = NULL;
2083 	args.keg = NULL;
2084 	args.align = UMA_BOOT_ALIGN - 1;
2085 	args.flags = UMA_ZFLAG_INTERNAL;
2086 	zone_ctor(zones, zsize, &args, M_WAITOK);
2087 
2088 	/* Now make a zone for slab headers */
2089 	slabzone = uma_zcreate("UMA Slabs",
2090 				sizeof(struct uma_slab),
2091 				NULL, NULL, NULL, NULL,
2092 				UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2093 
2094 	hashzone = uma_zcreate("UMA Hash",
2095 	    sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2096 	    NULL, NULL, NULL, NULL,
2097 	    UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2098 
2099 	bucket_init();
2100 
2101 	booted = BOOT_STRAPPED;
2102 }
2103 
2104 void
2105 uma_startup1(void)
2106 {
2107 
2108 #ifdef DIAGNOSTIC
2109 	printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2110 #endif
2111 	booted = BOOT_PAGEALLOC;
2112 }
2113 
2114 void
2115 uma_startup2(void)
2116 {
2117 
2118 #ifdef DIAGNOSTIC
2119 	printf("Entering %s with %d boot pages left\n", __func__, boot_pages);
2120 #endif
2121 	booted = BOOT_BUCKETS;
2122 	sx_init(&uma_drain_lock, "umadrain");
2123 	bucket_enable();
2124 }
2125 
2126 /*
2127  * Initialize our callout handle
2128  *
2129  */
2130 static void
2131 uma_startup3(void)
2132 {
2133 
2134 #ifdef INVARIANTS
2135 	TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
2136 	uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
2137 	uma_skip_cnt = counter_u64_alloc(M_WAITOK);
2138 #endif
2139 	zone_foreach(zone_alloc_counters);
2140 	callout_init(&uma_callout, 1);
2141 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
2142 	booted = BOOT_RUNNING;
2143 }
2144 
2145 static uma_keg_t
2146 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
2147 		int align, uint32_t flags)
2148 {
2149 	struct uma_kctor_args args;
2150 
2151 	args.size = size;
2152 	args.uminit = uminit;
2153 	args.fini = fini;
2154 	args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
2155 	args.flags = flags;
2156 	args.zone = zone;
2157 	return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
2158 }
2159 
2160 /* Public functions */
2161 /* See uma.h */
2162 void
2163 uma_set_align(int align)
2164 {
2165 
2166 	if (align != UMA_ALIGN_CACHE)
2167 		uma_align_cache = align;
2168 }
2169 
2170 /* See uma.h */
2171 uma_zone_t
2172 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
2173 		uma_init uminit, uma_fini fini, int align, uint32_t flags)
2174 
2175 {
2176 	struct uma_zctor_args args;
2177 	uma_zone_t res;
2178 	bool locked;
2179 
2180 	KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
2181 	    align, name));
2182 
2183 	/* This stuff is essential for the zone ctor */
2184 	memset(&args, 0, sizeof(args));
2185 	args.name = name;
2186 	args.size = size;
2187 	args.ctor = ctor;
2188 	args.dtor = dtor;
2189 	args.uminit = uminit;
2190 	args.fini = fini;
2191 #ifdef  INVARIANTS
2192 	/*
2193 	 * If a zone is being created with an empty constructor and
2194 	 * destructor, pass UMA constructor/destructor which checks for
2195 	 * memory use after free.
2196 	 */
2197 	if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOFREE))) &&
2198 	    ctor == NULL && dtor == NULL && uminit == NULL && fini == NULL) {
2199 		args.ctor = trash_ctor;
2200 		args.dtor = trash_dtor;
2201 		args.uminit = trash_init;
2202 		args.fini = trash_fini;
2203 	}
2204 #endif
2205 	args.align = align;
2206 	args.flags = flags;
2207 	args.keg = NULL;
2208 
2209 	if (booted < BOOT_BUCKETS) {
2210 		locked = false;
2211 	} else {
2212 		sx_slock(&uma_drain_lock);
2213 		locked = true;
2214 	}
2215 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2216 	if (locked)
2217 		sx_sunlock(&uma_drain_lock);
2218 	return (res);
2219 }
2220 
2221 /* See uma.h */
2222 uma_zone_t
2223 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
2224 		    uma_init zinit, uma_fini zfini, uma_zone_t master)
2225 {
2226 	struct uma_zctor_args args;
2227 	uma_keg_t keg;
2228 	uma_zone_t res;
2229 	bool locked;
2230 
2231 	keg = master->uz_keg;
2232 	memset(&args, 0, sizeof(args));
2233 	args.name = name;
2234 	args.size = keg->uk_size;
2235 	args.ctor = ctor;
2236 	args.dtor = dtor;
2237 	args.uminit = zinit;
2238 	args.fini = zfini;
2239 	args.align = keg->uk_align;
2240 	args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
2241 	args.keg = keg;
2242 
2243 	if (booted < BOOT_BUCKETS) {
2244 		locked = false;
2245 	} else {
2246 		sx_slock(&uma_drain_lock);
2247 		locked = true;
2248 	}
2249 	/* XXX Attaches only one keg of potentially many. */
2250 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
2251 	if (locked)
2252 		sx_sunlock(&uma_drain_lock);
2253 	return (res);
2254 }
2255 
2256 /* See uma.h */
2257 uma_zone_t
2258 uma_zcache_create(char *name, int size, uma_ctor ctor, uma_dtor dtor,
2259 		    uma_init zinit, uma_fini zfini, uma_import zimport,
2260 		    uma_release zrelease, void *arg, int flags)
2261 {
2262 	struct uma_zctor_args args;
2263 
2264 	memset(&args, 0, sizeof(args));
2265 	args.name = name;
2266 	args.size = size;
2267 	args.ctor = ctor;
2268 	args.dtor = dtor;
2269 	args.uminit = zinit;
2270 	args.fini = zfini;
2271 	args.import = zimport;
2272 	args.release = zrelease;
2273 	args.arg = arg;
2274 	args.align = 0;
2275 	args.flags = flags | UMA_ZFLAG_CACHE;
2276 
2277 	return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
2278 }
2279 
2280 /* See uma.h */
2281 void
2282 uma_zdestroy(uma_zone_t zone)
2283 {
2284 
2285 	sx_slock(&uma_drain_lock);
2286 	zone_free_item(zones, zone, NULL, SKIP_NONE);
2287 	sx_sunlock(&uma_drain_lock);
2288 }
2289 
2290 void
2291 uma_zwait(uma_zone_t zone)
2292 {
2293 	void *item;
2294 
2295 	item = uma_zalloc_arg(zone, NULL, M_WAITOK);
2296 	uma_zfree(zone, item);
2297 }
2298 
2299 void *
2300 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
2301 {
2302 	void *item;
2303 #ifdef SMP
2304 	int i;
2305 
2306 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2307 #endif
2308 	item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
2309 	if (item != NULL && (flags & M_ZERO)) {
2310 #ifdef SMP
2311 		for (i = 0; i <= mp_maxid; i++)
2312 			bzero(zpcpu_get_cpu(item, i), zone->uz_size);
2313 #else
2314 		bzero(item, zone->uz_size);
2315 #endif
2316 	}
2317 	return (item);
2318 }
2319 
2320 /*
2321  * A stub while both regular and pcpu cases are identical.
2322  */
2323 void
2324 uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *udata)
2325 {
2326 
2327 #ifdef SMP
2328 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
2329 #endif
2330 	uma_zfree_arg(zone, item, udata);
2331 }
2332 
2333 /* See uma.h */
2334 void *
2335 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
2336 {
2337 	uma_zone_domain_t zdom;
2338 	uma_bucket_t bucket;
2339 	uma_cache_t cache;
2340 	void *item;
2341 	int cpu, domain, lockfail, maxbucket;
2342 #ifdef INVARIANTS
2343 	bool skipdbg;
2344 #endif
2345 
2346 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2347 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2348 
2349 	/* This is the fast path allocation */
2350 	CTR4(KTR_UMA, "uma_zalloc_arg thread %x zone %s(%p) flags %d",
2351 	    curthread, zone->uz_name, zone, flags);
2352 
2353 	if (flags & M_WAITOK) {
2354 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2355 		    "uma_zalloc_arg: zone \"%s\"", zone->uz_name);
2356 	}
2357 	KASSERT((flags & M_EXEC) == 0, ("uma_zalloc_arg: called with M_EXEC"));
2358 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2359 	    ("uma_zalloc_arg: called with spinlock or critical section held"));
2360 	if (zone->uz_flags & UMA_ZONE_PCPU)
2361 		KASSERT((flags & M_ZERO) == 0, ("allocating from a pcpu zone "
2362 		    "with M_ZERO passed"));
2363 
2364 #ifdef DEBUG_MEMGUARD
2365 	if (memguard_cmp_zone(zone)) {
2366 		item = memguard_alloc(zone->uz_size, flags);
2367 		if (item != NULL) {
2368 			if (zone->uz_init != NULL &&
2369 			    zone->uz_init(item, zone->uz_size, flags) != 0)
2370 				return (NULL);
2371 			if (zone->uz_ctor != NULL &&
2372 			    zone->uz_ctor(item, zone->uz_size, udata,
2373 			    flags) != 0) {
2374 			    	zone->uz_fini(item, zone->uz_size);
2375 				return (NULL);
2376 			}
2377 			return (item);
2378 		}
2379 		/* This is unfortunate but should not be fatal. */
2380 	}
2381 #endif
2382 	/*
2383 	 * If possible, allocate from the per-CPU cache.  There are two
2384 	 * requirements for safe access to the per-CPU cache: (1) the thread
2385 	 * accessing the cache must not be preempted or yield during access,
2386 	 * and (2) the thread must not migrate CPUs without switching which
2387 	 * cache it accesses.  We rely on a critical section to prevent
2388 	 * preemption and migration.  We release the critical section in
2389 	 * order to acquire the zone mutex if we are unable to allocate from
2390 	 * the current cache; when we re-acquire the critical section, we
2391 	 * must detect and handle migration if it has occurred.
2392 	 */
2393 zalloc_restart:
2394 	critical_enter();
2395 	cpu = curcpu;
2396 	cache = &zone->uz_cpu[cpu];
2397 
2398 zalloc_start:
2399 	bucket = cache->uc_allocbucket;
2400 	if (bucket != NULL && bucket->ub_cnt > 0) {
2401 		bucket->ub_cnt--;
2402 		item = bucket->ub_bucket[bucket->ub_cnt];
2403 #ifdef INVARIANTS
2404 		bucket->ub_bucket[bucket->ub_cnt] = NULL;
2405 #endif
2406 		KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
2407 		cache->uc_allocs++;
2408 		critical_exit();
2409 #ifdef INVARIANTS
2410 		skipdbg = uma_dbg_zskip(zone, item);
2411 #endif
2412 		if (zone->uz_ctor != NULL &&
2413 #ifdef INVARIANTS
2414 		    (!skipdbg || zone->uz_ctor != trash_ctor ||
2415 		    zone->uz_dtor != trash_dtor) &&
2416 #endif
2417 		    zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2418 			counter_u64_add(zone->uz_fails, 1);
2419 			zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2420 			return (NULL);
2421 		}
2422 #ifdef INVARIANTS
2423 		if (!skipdbg)
2424 			uma_dbg_alloc(zone, NULL, item);
2425 #endif
2426 		if (flags & M_ZERO)
2427 			uma_zero_item(item, zone);
2428 		return (item);
2429 	}
2430 
2431 	/*
2432 	 * We have run out of items in our alloc bucket.
2433 	 * See if we can switch with our free bucket.
2434 	 */
2435 	bucket = cache->uc_freebucket;
2436 	if (bucket != NULL && bucket->ub_cnt > 0) {
2437 		CTR2(KTR_UMA,
2438 		    "uma_zalloc: zone %s(%p) swapping empty with alloc",
2439 		    zone->uz_name, zone);
2440 		cache->uc_freebucket = cache->uc_allocbucket;
2441 		cache->uc_allocbucket = bucket;
2442 		goto zalloc_start;
2443 	}
2444 
2445 	/*
2446 	 * Discard any empty allocation bucket while we hold no locks.
2447 	 */
2448 	bucket = cache->uc_allocbucket;
2449 	cache->uc_allocbucket = NULL;
2450 	critical_exit();
2451 	if (bucket != NULL)
2452 		bucket_free(zone, bucket, udata);
2453 
2454 	if (zone->uz_flags & UMA_ZONE_NUMA) {
2455 		domain = PCPU_GET(domain);
2456 		if (VM_DOMAIN_EMPTY(domain))
2457 			domain = UMA_ANYDOMAIN;
2458 	} else
2459 		domain = UMA_ANYDOMAIN;
2460 
2461 	/* Short-circuit for zones without buckets and low memory. */
2462 	if (zone->uz_count == 0 || bucketdisable) {
2463 		ZONE_LOCK(zone);
2464 		goto zalloc_item;
2465 	}
2466 
2467 	/*
2468 	 * Attempt to retrieve the item from the per-CPU cache has failed, so
2469 	 * we must go back to the zone.  This requires the zone lock, so we
2470 	 * must drop the critical section, then re-acquire it when we go back
2471 	 * to the cache.  Since the critical section is released, we may be
2472 	 * preempted or migrate.  As such, make sure not to maintain any
2473 	 * thread-local state specific to the cache from prior to releasing
2474 	 * the critical section.
2475 	 */
2476 	lockfail = 0;
2477 	if (ZONE_TRYLOCK(zone) == 0) {
2478 		/* Record contention to size the buckets. */
2479 		ZONE_LOCK(zone);
2480 		lockfail = 1;
2481 	}
2482 	critical_enter();
2483 	cpu = curcpu;
2484 	cache = &zone->uz_cpu[cpu];
2485 
2486 	/* See if we lost the race to fill the cache. */
2487 	if (cache->uc_allocbucket != NULL) {
2488 		ZONE_UNLOCK(zone);
2489 		goto zalloc_start;
2490 	}
2491 
2492 	/*
2493 	 * Check the zone's cache of buckets.
2494 	 */
2495 	if (domain == UMA_ANYDOMAIN)
2496 		zdom = &zone->uz_domain[0];
2497 	else
2498 		zdom = &zone->uz_domain[domain];
2499 	if ((bucket = zone_try_fetch_bucket(zone, zdom, true)) != NULL) {
2500 		KASSERT(bucket->ub_cnt != 0,
2501 		    ("uma_zalloc_arg: Returning an empty bucket."));
2502 		cache->uc_allocbucket = bucket;
2503 		ZONE_UNLOCK(zone);
2504 		goto zalloc_start;
2505 	}
2506 	/* We are no longer associated with this CPU. */
2507 	critical_exit();
2508 
2509 	/*
2510 	 * We bump the uz count when the cache size is insufficient to
2511 	 * handle the working set.
2512 	 */
2513 	if (lockfail && zone->uz_count < zone->uz_count_max)
2514 		zone->uz_count++;
2515 
2516 	if (zone->uz_max_items > 0) {
2517 		if (zone->uz_items >= zone->uz_max_items)
2518 			goto zalloc_item;
2519 		maxbucket = MIN(zone->uz_count,
2520 		    zone->uz_max_items - zone->uz_items);
2521 		zone->uz_items += maxbucket;
2522 	} else
2523 		maxbucket = zone->uz_count;
2524 	ZONE_UNLOCK(zone);
2525 
2526 	/*
2527 	 * Now lets just fill a bucket and put it on the free list.  If that
2528 	 * works we'll restart the allocation from the beginning and it
2529 	 * will use the just filled bucket.
2530 	 */
2531 	bucket = zone_alloc_bucket(zone, udata, domain, flags, maxbucket);
2532 	CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
2533 	    zone->uz_name, zone, bucket);
2534 	ZONE_LOCK(zone);
2535 	if (bucket != NULL) {
2536 		if (zone->uz_max_items > 0 && bucket->ub_cnt < maxbucket) {
2537 			MPASS(zone->uz_items >= maxbucket - bucket->ub_cnt);
2538 			zone->uz_items -= maxbucket - bucket->ub_cnt;
2539 			if (zone->uz_sleepers > 0 &&
2540 			    zone->uz_items < zone->uz_max_items)
2541 				wakeup_one(zone);
2542 		}
2543 		critical_enter();
2544 		cpu = curcpu;
2545 		cache = &zone->uz_cpu[cpu];
2546 
2547 		/*
2548 		 * See if we lost the race or were migrated.  Cache the
2549 		 * initialized bucket to make this less likely or claim
2550 		 * the memory directly.
2551 		 */
2552 		if (cache->uc_allocbucket == NULL &&
2553 		    ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
2554 		    domain == PCPU_GET(domain))) {
2555 			cache->uc_allocbucket = bucket;
2556 			zdom->uzd_imax += bucket->ub_cnt;
2557 		} else if (zone->uz_bkt_count >= zone->uz_bkt_max) {
2558 			critical_exit();
2559 			ZONE_UNLOCK(zone);
2560 			bucket_drain(zone, bucket);
2561 			bucket_free(zone, bucket, udata);
2562 			goto zalloc_restart;
2563 		} else
2564 			zone_put_bucket(zone, zdom, bucket, false);
2565 		ZONE_UNLOCK(zone);
2566 		goto zalloc_start;
2567 	} else if (zone->uz_max_items > 0) {
2568 		zone->uz_items -= maxbucket;
2569 		if (zone->uz_sleepers > 0 &&
2570 		    zone->uz_items + 1 < zone->uz_max_items)
2571 			wakeup_one(zone);
2572 	}
2573 
2574 	/*
2575 	 * We may not be able to get a bucket so return an actual item.
2576 	 */
2577 zalloc_item:
2578 	item = zone_alloc_item_locked(zone, udata, domain, flags);
2579 
2580 	return (item);
2581 }
2582 
2583 void *
2584 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
2585 {
2586 
2587 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
2588 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
2589 
2590 	/* This is the fast path allocation */
2591 	CTR5(KTR_UMA,
2592 	    "uma_zalloc_domain thread %x zone %s(%p) domain %d flags %d",
2593 	    curthread, zone->uz_name, zone, domain, flags);
2594 
2595 	if (flags & M_WAITOK) {
2596 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2597 		    "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
2598 	}
2599 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
2600 	    ("uma_zalloc_domain: called with spinlock or critical section held"));
2601 
2602 	return (zone_alloc_item(zone, udata, domain, flags));
2603 }
2604 
2605 /*
2606  * Find a slab with some space.  Prefer slabs that are partially used over those
2607  * that are totally full.  This helps to reduce fragmentation.
2608  *
2609  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
2610  * only 'domain'.
2611  */
2612 static uma_slab_t
2613 keg_first_slab(uma_keg_t keg, int domain, bool rr)
2614 {
2615 	uma_domain_t dom;
2616 	uma_slab_t slab;
2617 	int start;
2618 
2619 	KASSERT(domain >= 0 && domain < vm_ndomains,
2620 	    ("keg_first_slab: domain %d out of range", domain));
2621 	KEG_LOCK_ASSERT(keg);
2622 
2623 	slab = NULL;
2624 	start = domain;
2625 	do {
2626 		dom = &keg->uk_domain[domain];
2627 		if (!LIST_EMPTY(&dom->ud_part_slab))
2628 			return (LIST_FIRST(&dom->ud_part_slab));
2629 		if (!LIST_EMPTY(&dom->ud_free_slab)) {
2630 			slab = LIST_FIRST(&dom->ud_free_slab);
2631 			LIST_REMOVE(slab, us_link);
2632 			LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2633 			return (slab);
2634 		}
2635 		if (rr)
2636 			domain = (domain + 1) % vm_ndomains;
2637 	} while (domain != start);
2638 
2639 	return (NULL);
2640 }
2641 
2642 static uma_slab_t
2643 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
2644 {
2645 	uint32_t reserve;
2646 
2647 	KEG_LOCK_ASSERT(keg);
2648 
2649 	reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
2650 	if (keg->uk_free <= reserve)
2651 		return (NULL);
2652 	return (keg_first_slab(keg, domain, rr));
2653 }
2654 
2655 static uma_slab_t
2656 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
2657 {
2658 	struct vm_domainset_iter di;
2659 	uma_domain_t dom;
2660 	uma_slab_t slab;
2661 	int aflags, domain;
2662 	bool rr;
2663 
2664 restart:
2665 	KEG_LOCK_ASSERT(keg);
2666 
2667 	/*
2668 	 * Use the keg's policy if upper layers haven't already specified a
2669 	 * domain (as happens with first-touch zones).
2670 	 *
2671 	 * To avoid races we run the iterator with the keg lock held, but that
2672 	 * means that we cannot allow the vm_domainset layer to sleep.  Thus,
2673 	 * clear M_WAITOK and handle low memory conditions locally.
2674 	 */
2675 	rr = rdomain == UMA_ANYDOMAIN;
2676 	if (rr) {
2677 		aflags = (flags & ~M_WAITOK) | M_NOWAIT;
2678 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
2679 		    &aflags);
2680 	} else {
2681 		aflags = flags;
2682 		domain = rdomain;
2683 	}
2684 
2685 	for (;;) {
2686 		slab = keg_fetch_free_slab(keg, domain, rr, flags);
2687 		if (slab != NULL) {
2688 			MPASS(slab->us_keg == keg);
2689 			return (slab);
2690 		}
2691 
2692 		/*
2693 		 * M_NOVM means don't ask at all!
2694 		 */
2695 		if (flags & M_NOVM)
2696 			break;
2697 
2698 		KASSERT(zone->uz_max_items == 0 ||
2699 		    zone->uz_items <= zone->uz_max_items,
2700 		    ("%s: zone %p overflow", __func__, zone));
2701 
2702 		slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
2703 		/*
2704 		 * If we got a slab here it's safe to mark it partially used
2705 		 * and return.  We assume that the caller is going to remove
2706 		 * at least one item.
2707 		 */
2708 		if (slab) {
2709 			MPASS(slab->us_keg == keg);
2710 			dom = &keg->uk_domain[slab->us_domain];
2711 			LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
2712 			return (slab);
2713 		}
2714 		KEG_LOCK(keg);
2715 		if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
2716 			if ((flags & M_WAITOK) != 0) {
2717 				KEG_UNLOCK(keg);
2718 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
2719 				KEG_LOCK(keg);
2720 				goto restart;
2721 			}
2722 			break;
2723 		}
2724 	}
2725 
2726 	/*
2727 	 * We might not have been able to get a slab but another cpu
2728 	 * could have while we were unlocked.  Check again before we
2729 	 * fail.
2730 	 */
2731 	if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL) {
2732 		MPASS(slab->us_keg == keg);
2733 		return (slab);
2734 	}
2735 	return (NULL);
2736 }
2737 
2738 static uma_slab_t
2739 zone_fetch_slab(uma_zone_t zone, uma_keg_t keg, int domain, int flags)
2740 {
2741 	uma_slab_t slab;
2742 
2743 	if (keg == NULL) {
2744 		keg = zone->uz_keg;
2745 		KEG_LOCK(keg);
2746 	}
2747 
2748 	for (;;) {
2749 		slab = keg_fetch_slab(keg, zone, domain, flags);
2750 		if (slab)
2751 			return (slab);
2752 		if (flags & (M_NOWAIT | M_NOVM))
2753 			break;
2754 	}
2755 	KEG_UNLOCK(keg);
2756 	return (NULL);
2757 }
2758 
2759 static void *
2760 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
2761 {
2762 	uma_domain_t dom;
2763 	void *item;
2764 	uint8_t freei;
2765 
2766 	MPASS(keg == slab->us_keg);
2767 	KEG_LOCK_ASSERT(keg);
2768 
2769 	freei = BIT_FFS(SLAB_SETSIZE, &slab->us_free) - 1;
2770 	BIT_CLR(SLAB_SETSIZE, freei, &slab->us_free);
2771 	item = slab->us_data + (keg->uk_rsize * freei);
2772 	slab->us_freecount--;
2773 	keg->uk_free--;
2774 
2775 	/* Move this slab to the full list */
2776 	if (slab->us_freecount == 0) {
2777 		LIST_REMOVE(slab, us_link);
2778 		dom = &keg->uk_domain[slab->us_domain];
2779 		LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
2780 	}
2781 
2782 	return (item);
2783 }
2784 
2785 static int
2786 zone_import(uma_zone_t zone, void **bucket, int max, int domain, int flags)
2787 {
2788 	uma_slab_t slab;
2789 	uma_keg_t keg;
2790 #ifdef NUMA
2791 	int stripe;
2792 #endif
2793 	int i;
2794 
2795 	slab = NULL;
2796 	keg = NULL;
2797 	/* Try to keep the buckets totally full */
2798 	for (i = 0; i < max; ) {
2799 		if ((slab = zone_fetch_slab(zone, keg, domain, flags)) == NULL)
2800 			break;
2801 		keg = slab->us_keg;
2802 #ifdef NUMA
2803 		stripe = howmany(max, vm_ndomains);
2804 #endif
2805 		while (slab->us_freecount && i < max) {
2806 			bucket[i++] = slab_alloc_item(keg, slab);
2807 			if (keg->uk_free <= keg->uk_reserve)
2808 				break;
2809 #ifdef NUMA
2810 			/*
2811 			 * If the zone is striped we pick a new slab for every
2812 			 * N allocations.  Eliminating this conditional will
2813 			 * instead pick a new domain for each bucket rather
2814 			 * than stripe within each bucket.  The current option
2815 			 * produces more fragmentation and requires more cpu
2816 			 * time but yields better distribution.
2817 			 */
2818 			if ((zone->uz_flags & UMA_ZONE_NUMA) == 0 &&
2819 			    vm_ndomains > 1 && --stripe == 0)
2820 				break;
2821 #endif
2822 		}
2823 		/* Don't block if we allocated any successfully. */
2824 		flags &= ~M_WAITOK;
2825 		flags |= M_NOWAIT;
2826 	}
2827 	if (slab != NULL)
2828 		KEG_UNLOCK(keg);
2829 
2830 	return i;
2831 }
2832 
2833 static uma_bucket_t
2834 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags, int max)
2835 {
2836 	uma_bucket_t bucket;
2837 
2838 	CTR1(KTR_UMA, "zone_alloc:_bucket domain %d)", domain);
2839 
2840 	/* Don't wait for buckets, preserve caller's NOVM setting. */
2841 	bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
2842 	if (bucket == NULL)
2843 		return (NULL);
2844 
2845 	bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
2846 	    MIN(max, bucket->ub_entries), domain, flags);
2847 
2848 	/*
2849 	 * Initialize the memory if necessary.
2850 	 */
2851 	if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
2852 		int i;
2853 
2854 		for (i = 0; i < bucket->ub_cnt; i++)
2855 			if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
2856 			    flags) != 0)
2857 				break;
2858 		/*
2859 		 * If we couldn't initialize the whole bucket, put the
2860 		 * rest back onto the freelist.
2861 		 */
2862 		if (i != bucket->ub_cnt) {
2863 			zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
2864 			    bucket->ub_cnt - i);
2865 #ifdef INVARIANTS
2866 			bzero(&bucket->ub_bucket[i],
2867 			    sizeof(void *) * (bucket->ub_cnt - i));
2868 #endif
2869 			bucket->ub_cnt = i;
2870 		}
2871 	}
2872 
2873 	if (bucket->ub_cnt == 0) {
2874 		bucket_free(zone, bucket, udata);
2875 		counter_u64_add(zone->uz_fails, 1);
2876 		return (NULL);
2877 	}
2878 
2879 	return (bucket);
2880 }
2881 
2882 /*
2883  * Allocates a single item from a zone.
2884  *
2885  * Arguments
2886  *	zone   The zone to alloc for.
2887  *	udata  The data to be passed to the constructor.
2888  *	domain The domain to allocate from or UMA_ANYDOMAIN.
2889  *	flags  M_WAITOK, M_NOWAIT, M_ZERO.
2890  *
2891  * Returns
2892  *	NULL if there is no memory and M_NOWAIT is set
2893  *	An item if successful
2894  */
2895 
2896 static void *
2897 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
2898 {
2899 
2900 	ZONE_LOCK(zone);
2901 	return (zone_alloc_item_locked(zone, udata, domain, flags));
2902 }
2903 
2904 /*
2905  * Returns with zone unlocked.
2906  */
2907 static void *
2908 zone_alloc_item_locked(uma_zone_t zone, void *udata, int domain, int flags)
2909 {
2910 	void *item;
2911 #ifdef INVARIANTS
2912 	bool skipdbg;
2913 #endif
2914 
2915 	ZONE_LOCK_ASSERT(zone);
2916 
2917 	if (zone->uz_max_items > 0) {
2918 		if (zone->uz_items >= zone->uz_max_items) {
2919 			zone_log_warning(zone);
2920 			zone_maxaction(zone);
2921 			if (flags & M_NOWAIT) {
2922 				ZONE_UNLOCK(zone);
2923 				return (NULL);
2924 			}
2925 			zone->uz_sleeps++;
2926 			zone->uz_sleepers++;
2927 			while (zone->uz_items >= zone->uz_max_items)
2928 				mtx_sleep(zone, zone->uz_lockptr, PVM,
2929 				    "zonelimit", 0);
2930 			zone->uz_sleepers--;
2931 			if (zone->uz_sleepers > 0 &&
2932 			    zone->uz_items + 1 < zone->uz_max_items)
2933 				wakeup_one(zone);
2934 		}
2935 		zone->uz_items++;
2936 	}
2937 	ZONE_UNLOCK(zone);
2938 
2939 	if (domain != UMA_ANYDOMAIN) {
2940 		/* avoid allocs targeting empty domains */
2941 		if (VM_DOMAIN_EMPTY(domain))
2942 			domain = UMA_ANYDOMAIN;
2943 	}
2944 	if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
2945 		goto fail;
2946 
2947 #ifdef INVARIANTS
2948 	skipdbg = uma_dbg_zskip(zone, item);
2949 #endif
2950 	/*
2951 	 * We have to call both the zone's init (not the keg's init)
2952 	 * and the zone's ctor.  This is because the item is going from
2953 	 * a keg slab directly to the user, and the user is expecting it
2954 	 * to be both zone-init'd as well as zone-ctor'd.
2955 	 */
2956 	if (zone->uz_init != NULL) {
2957 		if (zone->uz_init(item, zone->uz_size, flags) != 0) {
2958 			zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
2959 			goto fail;
2960 		}
2961 	}
2962 	if (zone->uz_ctor != NULL &&
2963 #ifdef INVARIANTS
2964 	    (!skipdbg || zone->uz_ctor != trash_ctor ||
2965 	    zone->uz_dtor != trash_dtor) &&
2966 #endif
2967 	    zone->uz_ctor(item, zone->uz_size, udata, flags) != 0) {
2968 		zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
2969 		goto fail;
2970 	}
2971 #ifdef INVARIANTS
2972 	if (!skipdbg)
2973 		uma_dbg_alloc(zone, NULL, item);
2974 #endif
2975 	if (flags & M_ZERO)
2976 		uma_zero_item(item, zone);
2977 
2978 	counter_u64_add(zone->uz_allocs, 1);
2979 	CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
2980 	    zone->uz_name, zone);
2981 
2982 	return (item);
2983 
2984 fail:
2985 	if (zone->uz_max_items > 0) {
2986 		ZONE_LOCK(zone);
2987 		zone->uz_items--;
2988 		ZONE_UNLOCK(zone);
2989 	}
2990 	counter_u64_add(zone->uz_fails, 1);
2991 	CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
2992 	    zone->uz_name, zone);
2993 	return (NULL);
2994 }
2995 
2996 /* See uma.h */
2997 void
2998 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
2999 {
3000 	uma_cache_t cache;
3001 	uma_bucket_t bucket;
3002 	uma_zone_domain_t zdom;
3003 	int cpu, domain;
3004 	bool lockfail;
3005 #ifdef INVARIANTS
3006 	bool skipdbg;
3007 #endif
3008 
3009 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3010 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3011 
3012 	CTR2(KTR_UMA, "uma_zfree_arg thread %x zone %s", curthread,
3013 	    zone->uz_name);
3014 
3015 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3016 	    ("uma_zfree_arg: called with spinlock or critical section held"));
3017 
3018         /* uma_zfree(..., NULL) does nothing, to match free(9). */
3019         if (item == NULL)
3020                 return;
3021 #ifdef DEBUG_MEMGUARD
3022 	if (is_memguard_addr(item)) {
3023 		if (zone->uz_dtor != NULL)
3024 			zone->uz_dtor(item, zone->uz_size, udata);
3025 		if (zone->uz_fini != NULL)
3026 			zone->uz_fini(item, zone->uz_size);
3027 		memguard_free(item);
3028 		return;
3029 	}
3030 #endif
3031 #ifdef INVARIANTS
3032 	skipdbg = uma_dbg_zskip(zone, item);
3033 	if (skipdbg == false) {
3034 		if (zone->uz_flags & UMA_ZONE_MALLOC)
3035 			uma_dbg_free(zone, udata, item);
3036 		else
3037 			uma_dbg_free(zone, NULL, item);
3038 	}
3039 	if (zone->uz_dtor != NULL && (!skipdbg ||
3040 	    zone->uz_dtor != trash_dtor || zone->uz_ctor != trash_ctor))
3041 #else
3042 	if (zone->uz_dtor != NULL)
3043 #endif
3044 		zone->uz_dtor(item, zone->uz_size, udata);
3045 
3046 	/*
3047 	 * The race here is acceptable.  If we miss it we'll just have to wait
3048 	 * a little longer for the limits to be reset.
3049 	 */
3050 	if (zone->uz_sleepers > 0)
3051 		goto zfree_item;
3052 
3053 	/*
3054 	 * If possible, free to the per-CPU cache.  There are two
3055 	 * requirements for safe access to the per-CPU cache: (1) the thread
3056 	 * accessing the cache must not be preempted or yield during access,
3057 	 * and (2) the thread must not migrate CPUs without switching which
3058 	 * cache it accesses.  We rely on a critical section to prevent
3059 	 * preemption and migration.  We release the critical section in
3060 	 * order to acquire the zone mutex if we are unable to free to the
3061 	 * current cache; when we re-acquire the critical section, we must
3062 	 * detect and handle migration if it has occurred.
3063 	 */
3064 zfree_restart:
3065 	critical_enter();
3066 	cpu = curcpu;
3067 	cache = &zone->uz_cpu[cpu];
3068 
3069 zfree_start:
3070 	/*
3071 	 * Try to free into the allocbucket first to give LIFO ordering
3072 	 * for cache-hot datastructures.  Spill over into the freebucket
3073 	 * if necessary.  Alloc will swap them if one runs dry.
3074 	 */
3075 	bucket = cache->uc_allocbucket;
3076 	if (bucket == NULL || bucket->ub_cnt >= bucket->ub_entries)
3077 		bucket = cache->uc_freebucket;
3078 	if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3079 		KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
3080 		    ("uma_zfree: Freeing to non free bucket index."));
3081 		bucket->ub_bucket[bucket->ub_cnt] = item;
3082 		bucket->ub_cnt++;
3083 		cache->uc_frees++;
3084 		critical_exit();
3085 		return;
3086 	}
3087 
3088 	/*
3089 	 * We must go back the zone, which requires acquiring the zone lock,
3090 	 * which in turn means we must release and re-acquire the critical
3091 	 * section.  Since the critical section is released, we may be
3092 	 * preempted or migrate.  As such, make sure not to maintain any
3093 	 * thread-local state specific to the cache from prior to releasing
3094 	 * the critical section.
3095 	 */
3096 	critical_exit();
3097 	if (zone->uz_count == 0 || bucketdisable)
3098 		goto zfree_item;
3099 
3100 	lockfail = false;
3101 	if (ZONE_TRYLOCK(zone) == 0) {
3102 		/* Record contention to size the buckets. */
3103 		ZONE_LOCK(zone);
3104 		lockfail = true;
3105 	}
3106 	critical_enter();
3107 	cpu = curcpu;
3108 	cache = &zone->uz_cpu[cpu];
3109 
3110 	bucket = cache->uc_freebucket;
3111 	if (bucket != NULL && bucket->ub_cnt < bucket->ub_entries) {
3112 		ZONE_UNLOCK(zone);
3113 		goto zfree_start;
3114 	}
3115 	cache->uc_freebucket = NULL;
3116 	/* We are no longer associated with this CPU. */
3117 	critical_exit();
3118 
3119 	if ((zone->uz_flags & UMA_ZONE_NUMA) != 0) {
3120 		domain = PCPU_GET(domain);
3121 		if (VM_DOMAIN_EMPTY(domain))
3122 			domain = UMA_ANYDOMAIN;
3123 	} else
3124 		domain = 0;
3125 	zdom = &zone->uz_domain[0];
3126 
3127 	/* Can we throw this on the zone full list? */
3128 	if (bucket != NULL) {
3129 		CTR3(KTR_UMA,
3130 		    "uma_zfree: zone %s(%p) putting bucket %p on free list",
3131 		    zone->uz_name, zone, bucket);
3132 		/* ub_cnt is pointing to the last free item */
3133 		KASSERT(bucket->ub_cnt == bucket->ub_entries,
3134 		    ("uma_zfree: Attempting to insert not full bucket onto the full list.\n"));
3135 		if (zone->uz_bkt_count >= zone->uz_bkt_max) {
3136 			ZONE_UNLOCK(zone);
3137 			bucket_drain(zone, bucket);
3138 			bucket_free(zone, bucket, udata);
3139 			goto zfree_restart;
3140 		} else
3141 			zone_put_bucket(zone, zdom, bucket, true);
3142 	}
3143 
3144 	/*
3145 	 * We bump the uz count when the cache size is insufficient to
3146 	 * handle the working set.
3147 	 */
3148 	if (lockfail && zone->uz_count < zone->uz_count_max)
3149 		zone->uz_count++;
3150 	ZONE_UNLOCK(zone);
3151 
3152 	bucket = bucket_alloc(zone, udata, M_NOWAIT);
3153 	CTR3(KTR_UMA, "uma_zfree: zone %s(%p) allocated bucket %p",
3154 	    zone->uz_name, zone, bucket);
3155 	if (bucket) {
3156 		critical_enter();
3157 		cpu = curcpu;
3158 		cache = &zone->uz_cpu[cpu];
3159 		if (cache->uc_freebucket == NULL &&
3160 		    ((zone->uz_flags & UMA_ZONE_NUMA) == 0 ||
3161 		    domain == PCPU_GET(domain))) {
3162 			cache->uc_freebucket = bucket;
3163 			goto zfree_start;
3164 		}
3165 		/*
3166 		 * We lost the race, start over.  We have to drop our
3167 		 * critical section to free the bucket.
3168 		 */
3169 		critical_exit();
3170 		bucket_free(zone, bucket, udata);
3171 		goto zfree_restart;
3172 	}
3173 
3174 	/*
3175 	 * If nothing else caught this, we'll just do an internal free.
3176 	 */
3177 zfree_item:
3178 	zone_free_item(zone, item, udata, SKIP_DTOR);
3179 }
3180 
3181 void
3182 uma_zfree_domain(uma_zone_t zone, void *item, void *udata)
3183 {
3184 
3185 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3186 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3187 
3188 	CTR2(KTR_UMA, "uma_zfree_domain thread %x zone %s", curthread,
3189 	    zone->uz_name);
3190 
3191 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3192 	    ("uma_zfree_domain: called with spinlock or critical section held"));
3193 
3194         /* uma_zfree(..., NULL) does nothing, to match free(9). */
3195         if (item == NULL)
3196                 return;
3197 	zone_free_item(zone, item, udata, SKIP_NONE);
3198 }
3199 
3200 static void
3201 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
3202 {
3203 	uma_keg_t keg;
3204 	uma_domain_t dom;
3205 	uint8_t freei;
3206 
3207 	keg = zone->uz_keg;
3208 	MPASS(zone->uz_lockptr == &keg->uk_lock);
3209 	KEG_LOCK_ASSERT(keg);
3210 	MPASS(keg == slab->us_keg);
3211 
3212 	dom = &keg->uk_domain[slab->us_domain];
3213 
3214 	/* Do we need to remove from any lists? */
3215 	if (slab->us_freecount+1 == keg->uk_ipers) {
3216 		LIST_REMOVE(slab, us_link);
3217 		LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
3218 	} else if (slab->us_freecount == 0) {
3219 		LIST_REMOVE(slab, us_link);
3220 		LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3221 	}
3222 
3223 	/* Slab management. */
3224 	freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
3225 	BIT_SET(SLAB_SETSIZE, freei, &slab->us_free);
3226 	slab->us_freecount++;
3227 
3228 	/* Keg statistics. */
3229 	keg->uk_free++;
3230 }
3231 
3232 static void
3233 zone_release(uma_zone_t zone, void **bucket, int cnt)
3234 {
3235 	void *item;
3236 	uma_slab_t slab;
3237 	uma_keg_t keg;
3238 	uint8_t *mem;
3239 	int i;
3240 
3241 	keg = zone->uz_keg;
3242 	KEG_LOCK(keg);
3243 	for (i = 0; i < cnt; i++) {
3244 		item = bucket[i];
3245 		if (!(zone->uz_flags & UMA_ZONE_VTOSLAB)) {
3246 			mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
3247 			if (zone->uz_flags & UMA_ZONE_HASH) {
3248 				slab = hash_sfind(&keg->uk_hash, mem);
3249 			} else {
3250 				mem += keg->uk_pgoff;
3251 				slab = (uma_slab_t)mem;
3252 			}
3253 		} else {
3254 			slab = vtoslab((vm_offset_t)item);
3255 			MPASS(slab->us_keg == keg);
3256 		}
3257 		slab_free_item(zone, slab, item);
3258 	}
3259 	KEG_UNLOCK(keg);
3260 }
3261 
3262 /*
3263  * Frees a single item to any zone.
3264  *
3265  * Arguments:
3266  *	zone   The zone to free to
3267  *	item   The item we're freeing
3268  *	udata  User supplied data for the dtor
3269  *	skip   Skip dtors and finis
3270  */
3271 static void
3272 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
3273 {
3274 #ifdef INVARIANTS
3275 	bool skipdbg;
3276 
3277 	skipdbg = uma_dbg_zskip(zone, item);
3278 	if (skip == SKIP_NONE && !skipdbg) {
3279 		if (zone->uz_flags & UMA_ZONE_MALLOC)
3280 			uma_dbg_free(zone, udata, item);
3281 		else
3282 			uma_dbg_free(zone, NULL, item);
3283 	}
3284 
3285 	if (skip < SKIP_DTOR && zone->uz_dtor != NULL &&
3286 	    (!skipdbg || zone->uz_dtor != trash_dtor ||
3287 	    zone->uz_ctor != trash_ctor))
3288 #else
3289 	if (skip < SKIP_DTOR && zone->uz_dtor != NULL)
3290 #endif
3291 		zone->uz_dtor(item, zone->uz_size, udata);
3292 
3293 	if (skip < SKIP_FINI && zone->uz_fini)
3294 		zone->uz_fini(item, zone->uz_size);
3295 
3296 	zone->uz_release(zone->uz_arg, &item, 1);
3297 
3298 	if (skip & SKIP_CNT)
3299 		return;
3300 
3301 	counter_u64_add(zone->uz_frees, 1);
3302 
3303 	if (zone->uz_max_items > 0) {
3304 		ZONE_LOCK(zone);
3305 		zone->uz_items--;
3306 		if (zone->uz_sleepers > 0 &&
3307 		    zone->uz_items < zone->uz_max_items)
3308 			wakeup_one(zone);
3309 		ZONE_UNLOCK(zone);
3310 	}
3311 }
3312 
3313 /* See uma.h */
3314 int
3315 uma_zone_set_max(uma_zone_t zone, int nitems)
3316 {
3317 	struct uma_bucket_zone *ubz;
3318 
3319 	/*
3320 	 * If limit is very low we may need to limit how
3321 	 * much items are allowed in CPU caches.
3322 	 */
3323 	ubz = &bucket_zones[0];
3324 	for (; ubz->ubz_entries != 0; ubz++)
3325 		if (ubz->ubz_entries * 2 * mp_ncpus > nitems)
3326 			break;
3327 	if (ubz == &bucket_zones[0])
3328 		nitems = ubz->ubz_entries * 2 * mp_ncpus;
3329 	else
3330 		ubz--;
3331 
3332 	ZONE_LOCK(zone);
3333 	zone->uz_count_max = zone->uz_count = ubz->ubz_entries;
3334 	if (zone->uz_count_min > zone->uz_count_max)
3335 		zone->uz_count_min = zone->uz_count_max;
3336 	zone->uz_max_items = nitems;
3337 	ZONE_UNLOCK(zone);
3338 
3339 	return (nitems);
3340 }
3341 
3342 /* See uma.h */
3343 int
3344 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
3345 {
3346 
3347 	ZONE_LOCK(zone);
3348 	zone->uz_bkt_max = nitems;
3349 	ZONE_UNLOCK(zone);
3350 
3351 	return (nitems);
3352 }
3353 
3354 /* See uma.h */
3355 int
3356 uma_zone_get_max(uma_zone_t zone)
3357 {
3358 	int nitems;
3359 
3360 	ZONE_LOCK(zone);
3361 	nitems = zone->uz_max_items;
3362 	ZONE_UNLOCK(zone);
3363 
3364 	return (nitems);
3365 }
3366 
3367 /* See uma.h */
3368 void
3369 uma_zone_set_warning(uma_zone_t zone, const char *warning)
3370 {
3371 
3372 	ZONE_LOCK(zone);
3373 	zone->uz_warning = warning;
3374 	ZONE_UNLOCK(zone);
3375 }
3376 
3377 /* See uma.h */
3378 void
3379 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
3380 {
3381 
3382 	ZONE_LOCK(zone);
3383 	TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
3384 	ZONE_UNLOCK(zone);
3385 }
3386 
3387 /* See uma.h */
3388 int
3389 uma_zone_get_cur(uma_zone_t zone)
3390 {
3391 	int64_t nitems;
3392 	u_int i;
3393 
3394 	ZONE_LOCK(zone);
3395 	nitems = counter_u64_fetch(zone->uz_allocs) -
3396 	    counter_u64_fetch(zone->uz_frees);
3397 	CPU_FOREACH(i) {
3398 		/*
3399 		 * See the comment in sysctl_vm_zone_stats() regarding the
3400 		 * safety of accessing the per-cpu caches. With the zone lock
3401 		 * held, it is safe, but can potentially result in stale data.
3402 		 */
3403 		nitems += zone->uz_cpu[i].uc_allocs -
3404 		    zone->uz_cpu[i].uc_frees;
3405 	}
3406 	ZONE_UNLOCK(zone);
3407 
3408 	return (nitems < 0 ? 0 : nitems);
3409 }
3410 
3411 /* See uma.h */
3412 void
3413 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
3414 {
3415 	uma_keg_t keg;
3416 
3417 	KEG_GET(zone, keg);
3418 	KEG_LOCK(keg);
3419 	KASSERT(keg->uk_pages == 0,
3420 	    ("uma_zone_set_init on non-empty keg"));
3421 	keg->uk_init = uminit;
3422 	KEG_UNLOCK(keg);
3423 }
3424 
3425 /* See uma.h */
3426 void
3427 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
3428 {
3429 	uma_keg_t keg;
3430 
3431 	KEG_GET(zone, keg);
3432 	KEG_LOCK(keg);
3433 	KASSERT(keg->uk_pages == 0,
3434 	    ("uma_zone_set_fini on non-empty keg"));
3435 	keg->uk_fini = fini;
3436 	KEG_UNLOCK(keg);
3437 }
3438 
3439 /* See uma.h */
3440 void
3441 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
3442 {
3443 
3444 	ZONE_LOCK(zone);
3445 	KASSERT(zone->uz_keg->uk_pages == 0,
3446 	    ("uma_zone_set_zinit on non-empty keg"));
3447 	zone->uz_init = zinit;
3448 	ZONE_UNLOCK(zone);
3449 }
3450 
3451 /* See uma.h */
3452 void
3453 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
3454 {
3455 
3456 	ZONE_LOCK(zone);
3457 	KASSERT(zone->uz_keg->uk_pages == 0,
3458 	    ("uma_zone_set_zfini on non-empty keg"));
3459 	zone->uz_fini = zfini;
3460 	ZONE_UNLOCK(zone);
3461 }
3462 
3463 /* See uma.h */
3464 /* XXX uk_freef is not actually used with the zone locked */
3465 void
3466 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
3467 {
3468 	uma_keg_t keg;
3469 
3470 	KEG_GET(zone, keg);
3471 	KASSERT(keg != NULL, ("uma_zone_set_freef: Invalid zone type"));
3472 	KEG_LOCK(keg);
3473 	keg->uk_freef = freef;
3474 	KEG_UNLOCK(keg);
3475 }
3476 
3477 /* See uma.h */
3478 /* XXX uk_allocf is not actually used with the zone locked */
3479 void
3480 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
3481 {
3482 	uma_keg_t keg;
3483 
3484 	KEG_GET(zone, keg);
3485 	KEG_LOCK(keg);
3486 	keg->uk_allocf = allocf;
3487 	KEG_UNLOCK(keg);
3488 }
3489 
3490 /* See uma.h */
3491 void
3492 uma_zone_reserve(uma_zone_t zone, int items)
3493 {
3494 	uma_keg_t keg;
3495 
3496 	KEG_GET(zone, keg);
3497 	KEG_LOCK(keg);
3498 	keg->uk_reserve = items;
3499 	KEG_UNLOCK(keg);
3500 }
3501 
3502 /* See uma.h */
3503 int
3504 uma_zone_reserve_kva(uma_zone_t zone, int count)
3505 {
3506 	uma_keg_t keg;
3507 	vm_offset_t kva;
3508 	u_int pages;
3509 
3510 	KEG_GET(zone, keg);
3511 
3512 	pages = count / keg->uk_ipers;
3513 	if (pages * keg->uk_ipers < count)
3514 		pages++;
3515 	pages *= keg->uk_ppera;
3516 
3517 #ifdef UMA_MD_SMALL_ALLOC
3518 	if (keg->uk_ppera > 1) {
3519 #else
3520 	if (1) {
3521 #endif
3522 		kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
3523 		if (kva == 0)
3524 			return (0);
3525 	} else
3526 		kva = 0;
3527 
3528 	ZONE_LOCK(zone);
3529 	MPASS(keg->uk_kva == 0);
3530 	keg->uk_kva = kva;
3531 	keg->uk_offset = 0;
3532 	zone->uz_max_items = pages * keg->uk_ipers;
3533 #ifdef UMA_MD_SMALL_ALLOC
3534 	keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
3535 #else
3536 	keg->uk_allocf = noobj_alloc;
3537 #endif
3538 	keg->uk_flags |= UMA_ZONE_NOFREE;
3539 	ZONE_UNLOCK(zone);
3540 
3541 	return (1);
3542 }
3543 
3544 /* See uma.h */
3545 void
3546 uma_prealloc(uma_zone_t zone, int items)
3547 {
3548 	struct vm_domainset_iter di;
3549 	uma_domain_t dom;
3550 	uma_slab_t slab;
3551 	uma_keg_t keg;
3552 	int aflags, domain, slabs;
3553 
3554 	KEG_GET(zone, keg);
3555 	KEG_LOCK(keg);
3556 	slabs = items / keg->uk_ipers;
3557 	if (slabs * keg->uk_ipers < items)
3558 		slabs++;
3559 	while (slabs-- > 0) {
3560 		aflags = M_NOWAIT;
3561 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3562 		    &aflags);
3563 		for (;;) {
3564 			slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
3565 			    aflags);
3566 			if (slab != NULL) {
3567 				MPASS(slab->us_keg == keg);
3568 				dom = &keg->uk_domain[slab->us_domain];
3569 				LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
3570 				    us_link);
3571 				break;
3572 			}
3573 			KEG_LOCK(keg);
3574 			if (vm_domainset_iter_policy(&di, &domain) != 0) {
3575 				KEG_UNLOCK(keg);
3576 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask);
3577 				KEG_LOCK(keg);
3578 			}
3579 		}
3580 	}
3581 	KEG_UNLOCK(keg);
3582 }
3583 
3584 /* See uma.h */
3585 static void
3586 uma_reclaim_locked(bool kmem_danger)
3587 {
3588 
3589 	CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
3590 	sx_assert(&uma_drain_lock, SA_XLOCKED);
3591 	bucket_enable();
3592 	zone_foreach(zone_drain);
3593 	if (vm_page_count_min() || kmem_danger) {
3594 		cache_drain_safe(NULL);
3595 		zone_foreach(zone_drain);
3596 	}
3597 
3598 	/*
3599 	 * Some slabs may have been freed but this zone will be visited early
3600 	 * we visit again so that we can free pages that are empty once other
3601 	 * zones are drained.  We have to do the same for buckets.
3602 	 */
3603 	zone_drain(slabzone);
3604 	bucket_zone_drain();
3605 }
3606 
3607 void
3608 uma_reclaim(void)
3609 {
3610 
3611 	sx_xlock(&uma_drain_lock);
3612 	uma_reclaim_locked(false);
3613 	sx_xunlock(&uma_drain_lock);
3614 }
3615 
3616 static volatile int uma_reclaim_needed;
3617 
3618 void
3619 uma_reclaim_wakeup(void)
3620 {
3621 
3622 	if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
3623 		wakeup(uma_reclaim);
3624 }
3625 
3626 void
3627 uma_reclaim_worker(void *arg __unused)
3628 {
3629 
3630 	for (;;) {
3631 		sx_xlock(&uma_drain_lock);
3632 		while (atomic_load_int(&uma_reclaim_needed) == 0)
3633 			sx_sleep(uma_reclaim, &uma_drain_lock, PVM, "umarcl",
3634 			    hz);
3635 		sx_xunlock(&uma_drain_lock);
3636 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
3637 		sx_xlock(&uma_drain_lock);
3638 		uma_reclaim_locked(true);
3639 		atomic_store_int(&uma_reclaim_needed, 0);
3640 		sx_xunlock(&uma_drain_lock);
3641 		/* Don't fire more than once per-second. */
3642 		pause("umarclslp", hz);
3643 	}
3644 }
3645 
3646 /* See uma.h */
3647 int
3648 uma_zone_exhausted(uma_zone_t zone)
3649 {
3650 	int full;
3651 
3652 	ZONE_LOCK(zone);
3653 	full = zone->uz_sleepers > 0;
3654 	ZONE_UNLOCK(zone);
3655 	return (full);
3656 }
3657 
3658 int
3659 uma_zone_exhausted_nolock(uma_zone_t zone)
3660 {
3661 	return (zone->uz_sleepers > 0);
3662 }
3663 
3664 void *
3665 uma_large_malloc_domain(vm_size_t size, int domain, int wait)
3666 {
3667 	struct domainset *policy;
3668 	vm_offset_t addr;
3669 	uma_slab_t slab;
3670 
3671 	if (domain != UMA_ANYDOMAIN) {
3672 		/* avoid allocs targeting empty domains */
3673 		if (VM_DOMAIN_EMPTY(domain))
3674 			domain = UMA_ANYDOMAIN;
3675 	}
3676 	slab = zone_alloc_item(slabzone, NULL, domain, wait);
3677 	if (slab == NULL)
3678 		return (NULL);
3679 	policy = (domain == UMA_ANYDOMAIN) ? DOMAINSET_RR() :
3680 	    DOMAINSET_FIXED(domain);
3681 	addr = kmem_malloc_domainset(policy, size, wait);
3682 	if (addr != 0) {
3683 		vsetslab(addr, slab);
3684 		slab->us_data = (void *)addr;
3685 		slab->us_flags = UMA_SLAB_KERNEL | UMA_SLAB_MALLOC;
3686 		slab->us_size = size;
3687 		slab->us_domain = vm_phys_domain(PHYS_TO_VM_PAGE(
3688 		    pmap_kextract(addr)));
3689 		uma_total_inc(size);
3690 	} else {
3691 		zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3692 	}
3693 
3694 	return ((void *)addr);
3695 }
3696 
3697 void *
3698 uma_large_malloc(vm_size_t size, int wait)
3699 {
3700 
3701 	return uma_large_malloc_domain(size, UMA_ANYDOMAIN, wait);
3702 }
3703 
3704 void
3705 uma_large_free(uma_slab_t slab)
3706 {
3707 
3708 	KASSERT((slab->us_flags & UMA_SLAB_KERNEL) != 0,
3709 	    ("uma_large_free:  Memory not allocated with uma_large_malloc."));
3710 	kmem_free((vm_offset_t)slab->us_data, slab->us_size);
3711 	uma_total_dec(slab->us_size);
3712 	zone_free_item(slabzone, slab, NULL, SKIP_NONE);
3713 }
3714 
3715 static void
3716 uma_zero_item(void *item, uma_zone_t zone)
3717 {
3718 
3719 	bzero(item, zone->uz_size);
3720 }
3721 
3722 unsigned long
3723 uma_limit(void)
3724 {
3725 
3726 	return (uma_kmem_limit);
3727 }
3728 
3729 void
3730 uma_set_limit(unsigned long limit)
3731 {
3732 
3733 	uma_kmem_limit = limit;
3734 }
3735 
3736 unsigned long
3737 uma_size(void)
3738 {
3739 
3740 	return (uma_kmem_total);
3741 }
3742 
3743 long
3744 uma_avail(void)
3745 {
3746 
3747 	return (uma_kmem_limit - uma_kmem_total);
3748 }
3749 
3750 void
3751 uma_print_stats(void)
3752 {
3753 	zone_foreach(uma_print_zone);
3754 }
3755 
3756 static void
3757 slab_print(uma_slab_t slab)
3758 {
3759 	printf("slab: keg %p, data %p, freecount %d\n",
3760 		slab->us_keg, slab->us_data, slab->us_freecount);
3761 }
3762 
3763 static void
3764 cache_print(uma_cache_t cache)
3765 {
3766 	printf("alloc: %p(%d), free: %p(%d)\n",
3767 		cache->uc_allocbucket,
3768 		cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
3769 		cache->uc_freebucket,
3770 		cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
3771 }
3772 
3773 static void
3774 uma_print_keg(uma_keg_t keg)
3775 {
3776 	uma_domain_t dom;
3777 	uma_slab_t slab;
3778 	int i;
3779 
3780 	printf("keg: %s(%p) size %d(%d) flags %#x ipers %d ppera %d "
3781 	    "out %d free %d\n",
3782 	    keg->uk_name, keg, keg->uk_size, keg->uk_rsize, keg->uk_flags,
3783 	    keg->uk_ipers, keg->uk_ppera,
3784 	    (keg->uk_pages / keg->uk_ppera) * keg->uk_ipers - keg->uk_free,
3785 	    keg->uk_free);
3786 	for (i = 0; i < vm_ndomains; i++) {
3787 		dom = &keg->uk_domain[i];
3788 		printf("Part slabs:\n");
3789 		LIST_FOREACH(slab, &dom->ud_part_slab, us_link)
3790 			slab_print(slab);
3791 		printf("Free slabs:\n");
3792 		LIST_FOREACH(slab, &dom->ud_free_slab, us_link)
3793 			slab_print(slab);
3794 		printf("Full slabs:\n");
3795 		LIST_FOREACH(slab, &dom->ud_full_slab, us_link)
3796 			slab_print(slab);
3797 	}
3798 }
3799 
3800 void
3801 uma_print_zone(uma_zone_t zone)
3802 {
3803 	uma_cache_t cache;
3804 	int i;
3805 
3806 	printf("zone: %s(%p) size %d maxitems %ju flags %#x\n",
3807 	    zone->uz_name, zone, zone->uz_size, (uintmax_t)zone->uz_max_items,
3808 	    zone->uz_flags);
3809 	if (zone->uz_lockptr != &zone->uz_lock)
3810 		uma_print_keg(zone->uz_keg);
3811 	CPU_FOREACH(i) {
3812 		cache = &zone->uz_cpu[i];
3813 		printf("CPU %d Cache:\n", i);
3814 		cache_print(cache);
3815 	}
3816 }
3817 
3818 #ifdef DDB
3819 /*
3820  * Generate statistics across both the zone and its per-cpu cache's.  Return
3821  * desired statistics if the pointer is non-NULL for that statistic.
3822  *
3823  * Note: does not update the zone statistics, as it can't safely clear the
3824  * per-CPU cache statistic.
3825  *
3826  * XXXRW: Following the uc_allocbucket and uc_freebucket pointers here isn't
3827  * safe from off-CPU; we should modify the caches to track this information
3828  * directly so that we don't have to.
3829  */
3830 static void
3831 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
3832     uint64_t *freesp, uint64_t *sleepsp)
3833 {
3834 	uma_cache_t cache;
3835 	uint64_t allocs, frees, sleeps;
3836 	int cachefree, cpu;
3837 
3838 	allocs = frees = sleeps = 0;
3839 	cachefree = 0;
3840 	CPU_FOREACH(cpu) {
3841 		cache = &z->uz_cpu[cpu];
3842 		if (cache->uc_allocbucket != NULL)
3843 			cachefree += cache->uc_allocbucket->ub_cnt;
3844 		if (cache->uc_freebucket != NULL)
3845 			cachefree += cache->uc_freebucket->ub_cnt;
3846 		allocs += cache->uc_allocs;
3847 		frees += cache->uc_frees;
3848 	}
3849 	allocs += counter_u64_fetch(z->uz_allocs);
3850 	frees += counter_u64_fetch(z->uz_frees);
3851 	sleeps += z->uz_sleeps;
3852 	if (cachefreep != NULL)
3853 		*cachefreep = cachefree;
3854 	if (allocsp != NULL)
3855 		*allocsp = allocs;
3856 	if (freesp != NULL)
3857 		*freesp = frees;
3858 	if (sleepsp != NULL)
3859 		*sleepsp = sleeps;
3860 }
3861 #endif /* DDB */
3862 
3863 static int
3864 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
3865 {
3866 	uma_keg_t kz;
3867 	uma_zone_t z;
3868 	int count;
3869 
3870 	count = 0;
3871 	rw_rlock(&uma_rwlock);
3872 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
3873 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
3874 			count++;
3875 	}
3876 	LIST_FOREACH(z, &uma_cachezones, uz_link)
3877 		count++;
3878 
3879 	rw_runlock(&uma_rwlock);
3880 	return (sysctl_handle_int(oidp, &count, 0, req));
3881 }
3882 
3883 static void
3884 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
3885     struct uma_percpu_stat *ups, bool internal)
3886 {
3887 	uma_zone_domain_t zdom;
3888 	uma_cache_t cache;
3889 	int i;
3890 
3891 
3892 	for (i = 0; i < vm_ndomains; i++) {
3893 		zdom = &z->uz_domain[i];
3894 		uth->uth_zone_free += zdom->uzd_nitems;
3895 	}
3896 	uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
3897 	uth->uth_frees = counter_u64_fetch(z->uz_frees);
3898 	uth->uth_fails = counter_u64_fetch(z->uz_fails);
3899 	uth->uth_sleeps = z->uz_sleeps;
3900 	/*
3901 	 * While it is not normally safe to access the cache
3902 	 * bucket pointers while not on the CPU that owns the
3903 	 * cache, we only allow the pointers to be exchanged
3904 	 * without the zone lock held, not invalidated, so
3905 	 * accept the possible race associated with bucket
3906 	 * exchange during monitoring.
3907 	 */
3908 	for (i = 0; i < mp_maxid + 1; i++) {
3909 		bzero(&ups[i], sizeof(*ups));
3910 		if (internal || CPU_ABSENT(i))
3911 			continue;
3912 		cache = &z->uz_cpu[i];
3913 		if (cache->uc_allocbucket != NULL)
3914 			ups[i].ups_cache_free +=
3915 			    cache->uc_allocbucket->ub_cnt;
3916 		if (cache->uc_freebucket != NULL)
3917 			ups[i].ups_cache_free +=
3918 			    cache->uc_freebucket->ub_cnt;
3919 		ups[i].ups_allocs = cache->uc_allocs;
3920 		ups[i].ups_frees = cache->uc_frees;
3921 	}
3922 }
3923 
3924 static int
3925 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
3926 {
3927 	struct uma_stream_header ush;
3928 	struct uma_type_header uth;
3929 	struct uma_percpu_stat *ups;
3930 	struct sbuf sbuf;
3931 	uma_keg_t kz;
3932 	uma_zone_t z;
3933 	int count, error, i;
3934 
3935 	error = sysctl_wire_old_buffer(req, 0);
3936 	if (error != 0)
3937 		return (error);
3938 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
3939 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
3940 	ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
3941 
3942 	count = 0;
3943 	rw_rlock(&uma_rwlock);
3944 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
3945 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
3946 			count++;
3947 	}
3948 
3949 	LIST_FOREACH(z, &uma_cachezones, uz_link)
3950 		count++;
3951 
3952 	/*
3953 	 * Insert stream header.
3954 	 */
3955 	bzero(&ush, sizeof(ush));
3956 	ush.ush_version = UMA_STREAM_VERSION;
3957 	ush.ush_maxcpus = (mp_maxid + 1);
3958 	ush.ush_count = count;
3959 	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
3960 
3961 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
3962 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
3963 			bzero(&uth, sizeof(uth));
3964 			ZONE_LOCK(z);
3965 			strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3966 			uth.uth_align = kz->uk_align;
3967 			uth.uth_size = kz->uk_size;
3968 			uth.uth_rsize = kz->uk_rsize;
3969 			if (z->uz_max_items > 0)
3970 				uth.uth_pages = (z->uz_items / kz->uk_ipers) *
3971 					kz->uk_ppera;
3972 			else
3973 				uth.uth_pages = kz->uk_pages;
3974 			uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
3975 			    kz->uk_ppera;
3976 			uth.uth_limit = z->uz_max_items;
3977 			uth.uth_keg_free = z->uz_keg->uk_free;
3978 
3979 			/*
3980 			 * A zone is secondary is it is not the first entry
3981 			 * on the keg's zone list.
3982 			 */
3983 			if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
3984 			    (LIST_FIRST(&kz->uk_zones) != z))
3985 				uth.uth_zone_flags = UTH_ZONE_SECONDARY;
3986 			uma_vm_zone_stats(&uth, z, &sbuf, ups,
3987 			    kz->uk_flags & UMA_ZFLAG_INTERNAL);
3988 			ZONE_UNLOCK(z);
3989 			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
3990 			for (i = 0; i < mp_maxid + 1; i++)
3991 				(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
3992 		}
3993 	}
3994 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
3995 		bzero(&uth, sizeof(uth));
3996 		ZONE_LOCK(z);
3997 		strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
3998 		uth.uth_size = z->uz_size;
3999 		uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
4000 		ZONE_UNLOCK(z);
4001 		(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
4002 		for (i = 0; i < mp_maxid + 1; i++)
4003 			(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
4004 	}
4005 
4006 	rw_runlock(&uma_rwlock);
4007 	error = sbuf_finish(&sbuf);
4008 	sbuf_delete(&sbuf);
4009 	free(ups, M_TEMP);
4010 	return (error);
4011 }
4012 
4013 int
4014 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
4015 {
4016 	uma_zone_t zone = *(uma_zone_t *)arg1;
4017 	int error, max;
4018 
4019 	max = uma_zone_get_max(zone);
4020 	error = sysctl_handle_int(oidp, &max, 0, req);
4021 	if (error || !req->newptr)
4022 		return (error);
4023 
4024 	uma_zone_set_max(zone, max);
4025 
4026 	return (0);
4027 }
4028 
4029 int
4030 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
4031 {
4032 	uma_zone_t zone = *(uma_zone_t *)arg1;
4033 	int cur;
4034 
4035 	cur = uma_zone_get_cur(zone);
4036 	return (sysctl_handle_int(oidp, &cur, 0, req));
4037 }
4038 
4039 #ifdef INVARIANTS
4040 static uma_slab_t
4041 uma_dbg_getslab(uma_zone_t zone, void *item)
4042 {
4043 	uma_slab_t slab;
4044 	uma_keg_t keg;
4045 	uint8_t *mem;
4046 
4047 	mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4048 	if (zone->uz_flags & UMA_ZONE_VTOSLAB) {
4049 		slab = vtoslab((vm_offset_t)mem);
4050 	} else {
4051 		/*
4052 		 * It is safe to return the slab here even though the
4053 		 * zone is unlocked because the item's allocation state
4054 		 * essentially holds a reference.
4055 		 */
4056 		if (zone->uz_lockptr == &zone->uz_lock)
4057 			return (NULL);
4058 		ZONE_LOCK(zone);
4059 		keg = zone->uz_keg;
4060 		if (keg->uk_flags & UMA_ZONE_HASH)
4061 			slab = hash_sfind(&keg->uk_hash, mem);
4062 		else
4063 			slab = (uma_slab_t)(mem + keg->uk_pgoff);
4064 		ZONE_UNLOCK(zone);
4065 	}
4066 
4067 	return (slab);
4068 }
4069 
4070 static bool
4071 uma_dbg_zskip(uma_zone_t zone, void *mem)
4072 {
4073 
4074 	if (zone->uz_lockptr == &zone->uz_lock)
4075 		return (true);
4076 
4077 	return (uma_dbg_kskip(zone->uz_keg, mem));
4078 }
4079 
4080 static bool
4081 uma_dbg_kskip(uma_keg_t keg, void *mem)
4082 {
4083 	uintptr_t idx;
4084 
4085 	if (dbg_divisor == 0)
4086 		return (true);
4087 
4088 	if (dbg_divisor == 1)
4089 		return (false);
4090 
4091 	idx = (uintptr_t)mem >> PAGE_SHIFT;
4092 	if (keg->uk_ipers > 1) {
4093 		idx *= keg->uk_ipers;
4094 		idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
4095 	}
4096 
4097 	if ((idx / dbg_divisor) * dbg_divisor != idx) {
4098 		counter_u64_add(uma_skip_cnt, 1);
4099 		return (true);
4100 	}
4101 	counter_u64_add(uma_dbg_cnt, 1);
4102 
4103 	return (false);
4104 }
4105 
4106 /*
4107  * Set up the slab's freei data such that uma_dbg_free can function.
4108  *
4109  */
4110 static void
4111 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
4112 {
4113 	uma_keg_t keg;
4114 	int freei;
4115 
4116 	if (slab == NULL) {
4117 		slab = uma_dbg_getslab(zone, item);
4118 		if (slab == NULL)
4119 			panic("uma: item %p did not belong to zone %s\n",
4120 			    item, zone->uz_name);
4121 	}
4122 	keg = slab->us_keg;
4123 	freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4124 
4125 	if (BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4126 		panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)\n",
4127 		    item, zone, zone->uz_name, slab, freei);
4128 	BIT_SET_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4129 
4130 	return;
4131 }
4132 
4133 /*
4134  * Verifies freed addresses.  Checks for alignment, valid slab membership
4135  * and duplicate frees.
4136  *
4137  */
4138 static void
4139 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
4140 {
4141 	uma_keg_t keg;
4142 	int freei;
4143 
4144 	if (slab == NULL) {
4145 		slab = uma_dbg_getslab(zone, item);
4146 		if (slab == NULL)
4147 			panic("uma: Freed item %p did not belong to zone %s\n",
4148 			    item, zone->uz_name);
4149 	}
4150 	keg = slab->us_keg;
4151 	freei = ((uintptr_t)item - (uintptr_t)slab->us_data) / keg->uk_rsize;
4152 
4153 	if (freei >= keg->uk_ipers)
4154 		panic("Invalid free of %p from zone %p(%s) slab %p(%d)\n",
4155 		    item, zone, zone->uz_name, slab, freei);
4156 
4157 	if (((freei * keg->uk_rsize) + slab->us_data) != item)
4158 		panic("Unaligned free of %p from zone %p(%s) slab %p(%d)\n",
4159 		    item, zone, zone->uz_name, slab, freei);
4160 
4161 	if (!BIT_ISSET(SLAB_SETSIZE, freei, &slab->us_debugfree))
4162 		panic("Duplicate free of %p from zone %p(%s) slab %p(%d)\n",
4163 		    item, zone, zone->uz_name, slab, freei);
4164 
4165 	BIT_CLR_ATOMIC(SLAB_SETSIZE, freei, &slab->us_debugfree);
4166 }
4167 #endif /* INVARIANTS */
4168 
4169 #ifdef DDB
4170 DB_SHOW_COMMAND(uma, db_show_uma)
4171 {
4172 	uma_keg_t kz;
4173 	uma_zone_t z;
4174 	uint64_t allocs, frees, sleeps;
4175 	long cachefree;
4176 	int i;
4177 
4178 	db_printf("%18s %8s %8s %8s %12s %8s %8s\n", "Zone", "Size", "Used",
4179 	    "Free", "Requests", "Sleeps", "Bucket");
4180 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
4181 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
4182 			if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
4183 				allocs = counter_u64_fetch(z->uz_allocs);
4184 				frees = counter_u64_fetch(z->uz_frees);
4185 				sleeps = z->uz_sleeps;
4186 				cachefree = 0;
4187 			} else
4188 				uma_zone_sumstat(z, &cachefree, &allocs,
4189 				    &frees, &sleeps);
4190 			if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
4191 			    (LIST_FIRST(&kz->uk_zones) != z)))
4192 				cachefree += kz->uk_free;
4193 			for (i = 0; i < vm_ndomains; i++)
4194 				cachefree += z->uz_domain[i].uzd_nitems;
4195 
4196 			db_printf("%18s %8ju %8jd %8ld %12ju %8ju %8u\n",
4197 			    z->uz_name, (uintmax_t)kz->uk_size,
4198 			    (intmax_t)(allocs - frees), cachefree,
4199 			    (uintmax_t)allocs, sleeps, z->uz_count);
4200 			if (db_pager_quit)
4201 				return;
4202 		}
4203 	}
4204 }
4205 
4206 DB_SHOW_COMMAND(umacache, db_show_umacache)
4207 {
4208 	uma_zone_t z;
4209 	uint64_t allocs, frees;
4210 	long cachefree;
4211 	int i;
4212 
4213 	db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
4214 	    "Requests", "Bucket");
4215 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
4216 		uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL);
4217 		for (i = 0; i < vm_ndomains; i++)
4218 			cachefree += z->uz_domain[i].uzd_nitems;
4219 		db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
4220 		    z->uz_name, (uintmax_t)z->uz_size,
4221 		    (intmax_t)(allocs - frees), cachefree,
4222 		    (uintmax_t)allocs, z->uz_count);
4223 		if (db_pager_quit)
4224 			return;
4225 	}
4226 }
4227 #endif	/* DDB */
4228