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