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