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