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