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