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