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