xref: /freebsd/sys/vm/uma_core.c (revision c98323078dede7579020518ec84cdcb478e5c142)
1 /*
2  * Copyright (c) 2002, Jeffrey Roberson <jeff@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 /*
28  * uma_core.c  Implementation of the Universal Memory allocator
29  *
30  * This allocator is intended to replace the multitude of similar object caches
31  * in the standard FreeBSD kernel.  The intent is to be flexible as well as
32  * effecient.  A primary design goal is to return unused memory to the rest of
33  * the system.  This will make the system as a whole more flexible due to the
34  * ability to move memory to subsystems which most need it instead of leaving
35  * pools of reserved memory unused.
36  *
37  * The basic ideas stem from similar slab/zone based allocators whose algorithms
38  * are well known.
39  *
40  */
41 
42 /*
43  * TODO:
44  *	- Improve memory usage for large allocations
45  *	- Investigate cache size adjustments
46  */
47 
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50 
51 /* I should really use ktr.. */
52 /*
53 #define UMA_DEBUG 1
54 #define UMA_DEBUG_ALLOC 1
55 #define UMA_DEBUG_ALLOC_1 1
56 */
57 
58 #include "opt_param.h"
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/kernel.h>
62 #include <sys/types.h>
63 #include <sys/queue.h>
64 #include <sys/malloc.h>
65 #include <sys/lock.h>
66 #include <sys/sysctl.h>
67 #include <sys/mutex.h>
68 #include <sys/proc.h>
69 #include <sys/smp.h>
70 #include <sys/vmmeter.h>
71 
72 #include <vm/vm.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_param.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_extern.h>
79 #include <vm/uma.h>
80 #include <vm/uma_int.h>
81 #include <vm/uma_dbg.h>
82 
83 #include <machine/vmparam.h>
84 
85 /*
86  * This is the zone and keg from which all zones are spawned.  The idea is that
87  * even the zone & keg heads are allocated from the allocator, so we use the
88  * bss section to bootstrap us.
89  */
90 static struct uma_keg masterkeg;
91 static struct uma_zone masterzone_k;
92 static struct uma_zone masterzone_z;
93 static uma_zone_t kegs = &masterzone_k;
94 static uma_zone_t zones = &masterzone_z;
95 
96 /* This is the zone from which all of uma_slab_t's are allocated. */
97 static uma_zone_t slabzone;
98 static uma_zone_t slabrefzone;	/* With refcounters (for UMA_ZONE_REFCNT) */
99 
100 /*
101  * The initial hash tables come out of this zone so they can be allocated
102  * prior to malloc coming up.
103  */
104 static uma_zone_t hashzone;
105 
106 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
107 
108 /*
109  * Are we allowed to allocate buckets?
110  */
111 static int bucketdisable = 1;
112 
113 /* Linked list of all kegs in the system */
114 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(&uma_kegs);
115 
116 /* This mutex protects the keg list */
117 static struct mtx uma_mtx;
118 
119 /* These are the pcpu cache locks */
120 static struct mtx uma_pcpu_mtx[MAXCPU];
121 
122 /* Linked list of boot time pages */
123 static LIST_HEAD(,uma_slab) uma_boot_pages =
124     LIST_HEAD_INITIALIZER(&uma_boot_pages);
125 
126 /* Count of free boottime pages */
127 static int uma_boot_free = 0;
128 
129 /* Is the VM done starting up? */
130 static int booted = 0;
131 
132 /*
133  * This is the handle used to schedule events that need to happen
134  * outside of the allocation fast path.
135  */
136 static struct callout uma_callout;
137 #define	UMA_TIMEOUT	20		/* Seconds for callout interval. */
138 
139 /*
140  * This structure is passed as the zone ctor arg so that I don't have to create
141  * a special allocation function just for zones.
142  */
143 struct uma_zctor_args {
144 	char *name;
145 	size_t size;
146 	uma_ctor ctor;
147 	uma_dtor dtor;
148 	uma_init uminit;
149 	uma_fini fini;
150 	uma_keg_t keg;
151 	int align;
152 	u_int16_t flags;
153 };
154 
155 struct uma_kctor_args {
156 	uma_zone_t zone;
157 	size_t size;
158 	uma_init uminit;
159 	uma_fini fini;
160 	int align;
161 	u_int16_t flags;
162 };
163 
164 struct uma_bucket_zone {
165 	uma_zone_t	ubz_zone;
166 	char		*ubz_name;
167 	int		ubz_entries;
168 };
169 
170 #define	BUCKET_MAX	128
171 
172 struct uma_bucket_zone bucket_zones[] = {
173 	{ NULL, "16 Bucket", 16 },
174 	{ NULL, "32 Bucket", 32 },
175 	{ NULL, "64 Bucket", 64 },
176 	{ NULL, "128 Bucket", 128 },
177 	{ NULL, NULL, 0}
178 };
179 
180 #define	BUCKET_SHIFT	4
181 #define	BUCKET_ZONES	((BUCKET_MAX >> BUCKET_SHIFT) + 1)
182 
183 uint8_t bucket_size[BUCKET_ZONES];
184 
185 /* Prototypes.. */
186 
187 static void *obj_alloc(uma_zone_t, int, u_int8_t *, int);
188 static void *page_alloc(uma_zone_t, int, u_int8_t *, int);
189 static void *startup_alloc(uma_zone_t, int, u_int8_t *, int);
190 static void page_free(void *, int, u_int8_t);
191 static uma_slab_t slab_zalloc(uma_zone_t, int);
192 static void cache_drain(uma_zone_t);
193 static void bucket_drain(uma_zone_t, uma_bucket_t);
194 static void bucket_cache_drain(uma_zone_t zone);
195 static void keg_ctor(void *, int, void *);
196 static void keg_dtor(void *, int, void *);
197 static void zone_ctor(void *, int, void *);
198 static void zone_dtor(void *, int, void *);
199 static void zero_init(void *, int);
200 static void zone_small_init(uma_zone_t zone);
201 static void zone_large_init(uma_zone_t zone);
202 static void zone_foreach(void (*zfunc)(uma_zone_t));
203 static void zone_timeout(uma_zone_t zone);
204 static int hash_alloc(struct uma_hash *);
205 static int hash_expand(struct uma_hash *, struct uma_hash *);
206 static void hash_free(struct uma_hash *hash);
207 static void uma_timeout(void *);
208 static void uma_startup3(void);
209 static void *uma_zalloc_internal(uma_zone_t, void *, int);
210 static void uma_zfree_internal(uma_zone_t, void *, void *, int);
211 static void bucket_enable(void);
212 static void bucket_init(void);
213 static uma_bucket_t bucket_alloc(int, int);
214 static void bucket_free(uma_bucket_t);
215 static void bucket_zone_drain(void);
216 static int uma_zalloc_bucket(uma_zone_t zone, int flags);
217 static uma_slab_t uma_zone_slab(uma_zone_t zone, int flags);
218 static void *uma_slab_alloc(uma_zone_t zone, uma_slab_t slab);
219 static void zone_drain(uma_zone_t);
220 static void uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
221     uma_fini fini, int align, u_int16_t flags);
222 
223 void uma_print_zone(uma_zone_t);
224 void uma_print_stats(void);
225 static int sysctl_vm_zone(SYSCTL_HANDLER_ARGS);
226 
227 #ifdef WITNESS
228 static int nosleepwithlocks = 1;
229 SYSCTL_INT(_debug, OID_AUTO, nosleepwithlocks, CTLFLAG_RD, &nosleepwithlocks,
230     0, "Convert M_WAITOK to M_NOWAIT to avoid lock-held-across-sleep paths");
231 #else
232 static int nosleepwithlocks = 0;
233 SYSCTL_INT(_debug, OID_AUTO, nosleepwithlocks, CTLFLAG_RW, &nosleepwithlocks,
234     0, "Convert M_WAITOK to M_NOWAIT to avoid lock-held-across-sleep paths");
235 #endif
236 SYSCTL_OID(_vm, OID_AUTO, zone, CTLTYPE_STRING|CTLFLAG_RD,
237     NULL, 0, sysctl_vm_zone, "A", "Zone Info");
238 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
239 
240 /*
241  * This routine checks to see whether or not it's safe to enable buckets.
242  */
243 
244 static void
245 bucket_enable(void)
246 {
247 	if (cnt.v_free_count < cnt.v_free_min)
248 		bucketdisable = 1;
249 	else
250 		bucketdisable = 0;
251 }
252 
253 static void
254 bucket_init(void)
255 {
256 	struct uma_bucket_zone *ubz;
257 	int i;
258 	int j;
259 
260 	for (i = 0, j = 0; bucket_zones[j].ubz_entries != 0; j++) {
261 		int size;
262 
263 		ubz = &bucket_zones[j];
264 		size = roundup(sizeof(struct uma_bucket), sizeof(void *));
265 		size += sizeof(void *) * ubz->ubz_entries;
266 		ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
267 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
268 		for (; i <= ubz->ubz_entries; i += (1 << BUCKET_SHIFT))
269 			bucket_size[i >> BUCKET_SHIFT] = j;
270 	}
271 }
272 
273 static uma_bucket_t
274 bucket_alloc(int entries, int bflags)
275 {
276 	struct uma_bucket_zone *ubz;
277 	uma_bucket_t bucket;
278 	int idx;
279 
280 	/*
281 	 * This is to stop us from allocating per cpu buckets while we're
282 	 * running out of UMA_BOOT_PAGES.  Otherwise, we would exhaust the
283 	 * boot pages.  This also prevents us from allocating buckets in
284 	 * low memory situations.
285 	 */
286 
287 	if (bucketdisable)
288 		return (NULL);
289 	idx = howmany(entries, 1 << BUCKET_SHIFT);
290 	ubz = &bucket_zones[bucket_size[idx]];
291 	bucket = uma_zalloc_internal(ubz->ubz_zone, NULL, bflags);
292 	if (bucket) {
293 #ifdef INVARIANTS
294 		bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
295 #endif
296 		bucket->ub_cnt = 0;
297 		bucket->ub_entries = ubz->ubz_entries;
298 	}
299 
300 	return (bucket);
301 }
302 
303 static void
304 bucket_free(uma_bucket_t bucket)
305 {
306 	struct uma_bucket_zone *ubz;
307 	int idx;
308 
309 	idx = howmany(bucket->ub_entries, 1 << BUCKET_SHIFT);
310 	ubz = &bucket_zones[bucket_size[idx]];
311 	uma_zfree_internal(ubz->ubz_zone, bucket, NULL, 0);
312 }
313 
314 static void
315 bucket_zone_drain(void)
316 {
317 	struct uma_bucket_zone *ubz;
318 
319 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
320 		zone_drain(ubz->ubz_zone);
321 }
322 
323 
324 /*
325  * Routine called by timeout which is used to fire off some time interval
326  * based calculations.  (stats, hash size, etc.)
327  *
328  * Arguments:
329  *	arg   Unused
330  *
331  * Returns:
332  *	Nothing
333  */
334 static void
335 uma_timeout(void *unused)
336 {
337 	bucket_enable();
338 	zone_foreach(zone_timeout);
339 
340 	/* Reschedule this event */
341 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
342 }
343 
344 /*
345  * Routine to perform timeout driven calculations.  This expands the
346  * hashes and does per cpu statistics aggregation.
347  *
348  *  Arguments:
349  *	zone  The zone to operate on
350  *
351  *  Returns:
352  *	Nothing
353  */
354 static void
355 zone_timeout(uma_zone_t zone)
356 {
357 	uma_keg_t keg;
358 	uma_cache_t cache;
359 	u_int64_t alloc;
360 	int cpu;
361 
362 	keg = zone->uz_keg;
363 	alloc = 0;
364 
365 	/*
366 	 * Aggregate per cpu cache statistics back to the zone.
367 	 *
368 	 * XXX This should be done in the sysctl handler.
369 	 *
370 	 * I may rewrite this to set a flag in the per cpu cache instead of
371 	 * locking.  If the flag is not cleared on the next round I will have
372 	 * to lock and do it here instead so that the statistics don't get too
373 	 * far out of sync.
374 	 */
375 	if (!(keg->uk_flags & UMA_ZFLAG_INTERNAL)) {
376 		for (cpu = 0; cpu <= mp_maxid; cpu++) {
377 			if (CPU_ABSENT(cpu))
378 				continue;
379 			CPU_LOCK(cpu);
380 			cache = &zone->uz_cpu[cpu];
381 			/* Add them up, and reset */
382 			alloc += cache->uc_allocs;
383 			cache->uc_allocs = 0;
384 			CPU_UNLOCK(cpu);
385 		}
386 	}
387 
388 	/* Now push these stats back into the zone.. */
389 	ZONE_LOCK(zone);
390 	zone->uz_allocs += alloc;
391 
392 	/*
393 	 * Expand the zone hash table.
394 	 *
395 	 * This is done if the number of slabs is larger than the hash size.
396 	 * What I'm trying to do here is completely reduce collisions.  This
397 	 * may be a little aggressive.  Should I allow for two collisions max?
398 	 */
399 
400 	if (keg->uk_flags & UMA_ZONE_HASH &&
401 	    keg->uk_pages / keg->uk_ppera >= keg->uk_hash.uh_hashsize) {
402 		struct uma_hash newhash;
403 		struct uma_hash oldhash;
404 		int ret;
405 
406 		/*
407 		 * This is so involved because allocating and freeing
408 		 * while the zone lock is held will lead to deadlock.
409 		 * I have to do everything in stages and check for
410 		 * races.
411 		 */
412 		newhash = keg->uk_hash;
413 		ZONE_UNLOCK(zone);
414 		ret = hash_alloc(&newhash);
415 		ZONE_LOCK(zone);
416 		if (ret) {
417 			if (hash_expand(&keg->uk_hash, &newhash)) {
418 				oldhash = keg->uk_hash;
419 				keg->uk_hash = newhash;
420 			} else
421 				oldhash = newhash;
422 
423 			ZONE_UNLOCK(zone);
424 			hash_free(&oldhash);
425 			ZONE_LOCK(zone);
426 		}
427 	}
428 	ZONE_UNLOCK(zone);
429 }
430 
431 /*
432  * Allocate and zero fill the next sized hash table from the appropriate
433  * backing store.
434  *
435  * Arguments:
436  *	hash  A new hash structure with the old hash size in uh_hashsize
437  *
438  * Returns:
439  *	1 on sucess and 0 on failure.
440  */
441 static int
442 hash_alloc(struct uma_hash *hash)
443 {
444 	int oldsize;
445 	int alloc;
446 
447 	oldsize = hash->uh_hashsize;
448 
449 	/* We're just going to go to a power of two greater */
450 	if (oldsize)  {
451 		hash->uh_hashsize = oldsize * 2;
452 		alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
453 		hash->uh_slab_hash = (struct slabhead *)malloc(alloc,
454 		    M_UMAHASH, M_NOWAIT);
455 	} else {
456 		alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
457 		hash->uh_slab_hash = uma_zalloc_internal(hashzone, NULL,
458 		    M_WAITOK);
459 		hash->uh_hashsize = UMA_HASH_SIZE_INIT;
460 	}
461 	if (hash->uh_slab_hash) {
462 		bzero(hash->uh_slab_hash, alloc);
463 		hash->uh_hashmask = hash->uh_hashsize - 1;
464 		return (1);
465 	}
466 
467 	return (0);
468 }
469 
470 /*
471  * Expands the hash table for HASH zones.  This is done from zone_timeout
472  * to reduce collisions.  This must not be done in the regular allocation
473  * path, otherwise, we can recurse on the vm while allocating pages.
474  *
475  * Arguments:
476  *	oldhash  The hash you want to expand
477  *	newhash  The hash structure for the new table
478  *
479  * Returns:
480  *	Nothing
481  *
482  * Discussion:
483  */
484 static int
485 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
486 {
487 	uma_slab_t slab;
488 	int hval;
489 	int i;
490 
491 	if (!newhash->uh_slab_hash)
492 		return (0);
493 
494 	if (oldhash->uh_hashsize >= newhash->uh_hashsize)
495 		return (0);
496 
497 	/*
498 	 * I need to investigate hash algorithms for resizing without a
499 	 * full rehash.
500 	 */
501 
502 	for (i = 0; i < oldhash->uh_hashsize; i++)
503 		while (!SLIST_EMPTY(&oldhash->uh_slab_hash[i])) {
504 			slab = SLIST_FIRST(&oldhash->uh_slab_hash[i]);
505 			SLIST_REMOVE_HEAD(&oldhash->uh_slab_hash[i], us_hlink);
506 			hval = UMA_HASH(newhash, slab->us_data);
507 			SLIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
508 			    slab, us_hlink);
509 		}
510 
511 	return (1);
512 }
513 
514 /*
515  * Free the hash bucket to the appropriate backing store.
516  *
517  * Arguments:
518  *	slab_hash  The hash bucket we're freeing
519  *	hashsize   The number of entries in that hash bucket
520  *
521  * Returns:
522  *	Nothing
523  */
524 static void
525 hash_free(struct uma_hash *hash)
526 {
527 	if (hash->uh_slab_hash == NULL)
528 		return;
529 	if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
530 		uma_zfree_internal(hashzone,
531 		    hash->uh_slab_hash, NULL, 0);
532 	else
533 		free(hash->uh_slab_hash, M_UMAHASH);
534 }
535 
536 /*
537  * Frees all outstanding items in a bucket
538  *
539  * Arguments:
540  *	zone   The zone to free to, must be unlocked.
541  *	bucket The free/alloc bucket with items, cpu queue must be locked.
542  *
543  * Returns:
544  *	Nothing
545  */
546 
547 static void
548 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
549 {
550 	uma_slab_t slab;
551 	int mzone;
552 	void *item;
553 
554 	if (bucket == NULL)
555 		return;
556 
557 	slab = NULL;
558 	mzone = 0;
559 
560 	/* We have to lookup the slab again for malloc.. */
561 	if (zone->uz_keg->uk_flags & UMA_ZONE_MALLOC)
562 		mzone = 1;
563 
564 	while (bucket->ub_cnt > 0)  {
565 		bucket->ub_cnt--;
566 		item = bucket->ub_bucket[bucket->ub_cnt];
567 #ifdef INVARIANTS
568 		bucket->ub_bucket[bucket->ub_cnt] = NULL;
569 		KASSERT(item != NULL,
570 		    ("bucket_drain: botched ptr, item is NULL"));
571 #endif
572 		/*
573 		 * This is extremely inefficient.  The slab pointer was passed
574 		 * to uma_zfree_arg, but we lost it because the buckets don't
575 		 * hold them.  This will go away when free() gets a size passed
576 		 * to it.
577 		 */
578 		if (mzone)
579 			slab = vtoslab((vm_offset_t)item & (~UMA_SLAB_MASK));
580 		uma_zfree_internal(zone, item, slab, 1);
581 	}
582 }
583 
584 /*
585  * Drains the per cpu caches for a zone.
586  *
587  * Arguments:
588  *	zone     The zone to drain, must be unlocked.
589  *
590  * Returns:
591  *	Nothing
592  */
593 static void
594 cache_drain(uma_zone_t zone)
595 {
596 	uma_cache_t cache;
597 	int cpu;
598 
599 	/*
600 	 * We have to lock each cpu cache before locking the zone
601 	 */
602 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
603 		if (CPU_ABSENT(cpu))
604 			continue;
605 		CPU_LOCK(cpu);
606 		cache = &zone->uz_cpu[cpu];
607 		bucket_drain(zone, cache->uc_allocbucket);
608 		bucket_drain(zone, cache->uc_freebucket);
609 		if (cache->uc_allocbucket != NULL)
610 			bucket_free(cache->uc_allocbucket);
611 		if (cache->uc_freebucket != NULL)
612 			bucket_free(cache->uc_freebucket);
613 		cache->uc_allocbucket = cache->uc_freebucket = NULL;
614 	}
615 	ZONE_LOCK(zone);
616 	bucket_cache_drain(zone);
617 	ZONE_UNLOCK(zone);
618 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
619 		if (CPU_ABSENT(cpu))
620 			continue;
621 		CPU_UNLOCK(cpu);
622 	}
623 }
624 
625 /*
626  * Drain the cached buckets from a zone.  Expects a locked zone on entry.
627  */
628 static void
629 bucket_cache_drain(uma_zone_t zone)
630 {
631 	uma_bucket_t bucket;
632 
633 	/*
634 	 * Drain the bucket queues and free the buckets, we just keep two per
635 	 * cpu (alloc/free).
636 	 */
637 	while ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
638 		LIST_REMOVE(bucket, ub_link);
639 		ZONE_UNLOCK(zone);
640 		bucket_drain(zone, bucket);
641 		bucket_free(bucket);
642 		ZONE_LOCK(zone);
643 	}
644 
645 	/* Now we do the free queue.. */
646 	while ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
647 		LIST_REMOVE(bucket, ub_link);
648 		bucket_free(bucket);
649 	}
650 }
651 
652 /*
653  * Frees pages from a zone back to the system.  This is done on demand from
654  * the pageout daemon.
655  *
656  * Arguments:
657  *	zone  The zone to free pages from
658  *	 all  Should we drain all items?
659  *
660  * Returns:
661  *	Nothing.
662  */
663 static void
664 zone_drain(uma_zone_t zone)
665 {
666 	struct slabhead freeslabs = {};
667 	uma_keg_t keg;
668 	uma_slab_t slab;
669 	uma_slab_t n;
670 	u_int8_t flags;
671 	u_int8_t *mem;
672 	int i;
673 
674 	keg = zone->uz_keg;
675 
676 	/*
677 	 * We don't want to take pages from statically allocated zones at this
678 	 * time
679 	 */
680 	if (keg->uk_flags & UMA_ZONE_NOFREE || keg->uk_freef == NULL)
681 		return;
682 
683 	ZONE_LOCK(zone);
684 
685 #ifdef UMA_DEBUG
686 	printf("%s free items: %u\n", zone->uz_name, keg->uk_free);
687 #endif
688 	bucket_cache_drain(zone);
689 	if (keg->uk_free == 0)
690 		goto finished;
691 
692 	slab = LIST_FIRST(&keg->uk_free_slab);
693 	while (slab) {
694 		n = LIST_NEXT(slab, us_link);
695 
696 		/* We have no where to free these to */
697 		if (slab->us_flags & UMA_SLAB_BOOT) {
698 			slab = n;
699 			continue;
700 		}
701 
702 		LIST_REMOVE(slab, us_link);
703 		keg->uk_pages -= keg->uk_ppera;
704 		keg->uk_free -= keg->uk_ipers;
705 
706 		if (keg->uk_flags & UMA_ZONE_HASH)
707 			UMA_HASH_REMOVE(&keg->uk_hash, slab, slab->us_data);
708 
709 		SLIST_INSERT_HEAD(&freeslabs, slab, us_hlink);
710 
711 		slab = n;
712 	}
713 finished:
714 	ZONE_UNLOCK(zone);
715 
716 	while ((slab = SLIST_FIRST(&freeslabs)) != NULL) {
717 		SLIST_REMOVE(&freeslabs, slab, uma_slab, us_hlink);
718 		if (keg->uk_fini)
719 			for (i = 0; i < keg->uk_ipers; i++)
720 				keg->uk_fini(
721 				    slab->us_data + (keg->uk_rsize * i),
722 				    keg->uk_size);
723 		flags = slab->us_flags;
724 		mem = slab->us_data;
725 
726 		if ((keg->uk_flags & UMA_ZONE_MALLOC) ||
727 		    (keg->uk_flags & UMA_ZONE_REFCNT)) {
728 			vm_object_t obj;
729 
730 			if (flags & UMA_SLAB_KMEM)
731 				obj = kmem_object;
732 			else
733 				obj = NULL;
734 			for (i = 0; i < keg->uk_ppera; i++)
735 				vsetobj((vm_offset_t)mem + (i * PAGE_SIZE),
736 				    obj);
737 		}
738 		if (keg->uk_flags & UMA_ZONE_OFFPAGE)
739 			uma_zfree_internal(keg->uk_slabzone, slab, NULL, 0);
740 #ifdef UMA_DEBUG
741 		printf("%s: Returning %d bytes.\n",
742 		    zone->uz_name, UMA_SLAB_SIZE * keg->uk_ppera);
743 #endif
744 		keg->uk_freef(mem, UMA_SLAB_SIZE * keg->uk_ppera, flags);
745 	}
746 }
747 
748 /*
749  * Allocate a new slab for a zone.  This does not insert the slab onto a list.
750  *
751  * Arguments:
752  *	zone  The zone to allocate slabs for
753  *	wait  Shall we wait?
754  *
755  * Returns:
756  *	The slab that was allocated or NULL if there is no memory and the
757  *	caller specified M_NOWAIT.
758  */
759 static uma_slab_t
760 slab_zalloc(uma_zone_t zone, int wait)
761 {
762 	uma_slabrefcnt_t slabref;
763 	uma_slab_t slab;
764 	uma_keg_t keg;
765 	u_int8_t *mem;
766 	u_int8_t flags;
767 	int i;
768 
769 	slab = NULL;
770 	keg = zone->uz_keg;
771 
772 #ifdef UMA_DEBUG
773 	printf("slab_zalloc:  Allocating a new slab for %s\n", zone->uz_name);
774 #endif
775 	ZONE_UNLOCK(zone);
776 
777 	if (keg->uk_flags & UMA_ZONE_OFFPAGE) {
778 		slab = uma_zalloc_internal(keg->uk_slabzone, NULL, wait);
779 		if (slab == NULL) {
780 			ZONE_LOCK(zone);
781 			return NULL;
782 		}
783 	}
784 
785 	/*
786 	 * This reproduces the old vm_zone behavior of zero filling pages the
787 	 * first time they are added to a zone.
788 	 *
789 	 * Malloced items are zeroed in uma_zalloc.
790 	 */
791 
792 	if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
793 		wait |= M_ZERO;
794 	else
795 		wait &= ~M_ZERO;
796 
797 	mem = keg->uk_allocf(zone, keg->uk_ppera * UMA_SLAB_SIZE,
798 	    &flags, wait);
799 	if (mem == NULL) {
800 		ZONE_LOCK(zone);
801 		return (NULL);
802 	}
803 
804 	/* Point the slab into the allocated memory */
805 	if (!(keg->uk_flags & UMA_ZONE_OFFPAGE))
806 		slab = (uma_slab_t )(mem + keg->uk_pgoff);
807 
808 	if ((keg->uk_flags & UMA_ZONE_MALLOC) ||
809 	    (keg->uk_flags & UMA_ZONE_REFCNT))
810 		for (i = 0; i < keg->uk_ppera; i++)
811 			vsetslab((vm_offset_t)mem + (i * PAGE_SIZE), slab);
812 
813 	slab->us_keg = keg;
814 	slab->us_data = mem;
815 	slab->us_freecount = keg->uk_ipers;
816 	slab->us_firstfree = 0;
817 	slab->us_flags = flags;
818 	for (i = 0; i < keg->uk_ipers; i++)
819 		slab->us_freelist[i].us_item = i+1;
820 
821 	if (keg->uk_flags & UMA_ZONE_REFCNT) {
822 		slabref = (uma_slabrefcnt_t)slab;
823 		for (i = 0; i < keg->uk_ipers; i++)
824 			slabref->us_freelist[i].us_refcnt = 0;
825 	}
826 
827 	if (keg->uk_init)
828 		for (i = 0; i < keg->uk_ipers; i++)
829 			keg->uk_init(slab->us_data + (keg->uk_rsize * i),
830 			    keg->uk_size);
831 	ZONE_LOCK(zone);
832 
833 	if (keg->uk_flags & UMA_ZONE_HASH)
834 		UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
835 
836 	keg->uk_pages += keg->uk_ppera;
837 	keg->uk_free += keg->uk_ipers;
838 
839 	return (slab);
840 }
841 
842 /*
843  * This function is intended to be used early on in place of page_alloc() so
844  * that we may use the boot time page cache to satisfy allocations before
845  * the VM is ready.
846  */
847 static void *
848 startup_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
849 {
850 	uma_keg_t keg;
851 
852 	keg = zone->uz_keg;
853 
854 	/*
855 	 * Check our small startup cache to see if it has pages remaining.
856 	 */
857 	mtx_lock(&uma_mtx);
858 	if (uma_boot_free != 0) {
859 		uma_slab_t tmps;
860 
861 		tmps = LIST_FIRST(&uma_boot_pages);
862 		LIST_REMOVE(tmps, us_link);
863 		uma_boot_free--;
864 		mtx_unlock(&uma_mtx);
865 		*pflag = tmps->us_flags;
866 		return (tmps->us_data);
867 	}
868 	mtx_unlock(&uma_mtx);
869 	if (booted == 0)
870 		panic("UMA: Increase UMA_BOOT_PAGES");
871 	/*
872 	 * Now that we've booted reset these users to their real allocator.
873 	 */
874 #ifdef UMA_MD_SMALL_ALLOC
875 	keg->uk_allocf = uma_small_alloc;
876 #else
877 	keg->uk_allocf = page_alloc;
878 #endif
879 	return keg->uk_allocf(zone, bytes, pflag, wait);
880 }
881 
882 /*
883  * Allocates a number of pages from the system
884  *
885  * Arguments:
886  *	zone  Unused
887  *	bytes  The number of bytes requested
888  *	wait  Shall we wait?
889  *
890  * Returns:
891  *	A pointer to the alloced memory or possibly
892  *	NULL if M_NOWAIT is set.
893  */
894 static void *
895 page_alloc(uma_zone_t zone, int bytes, u_int8_t *pflag, int wait)
896 {
897 	void *p;	/* Returned page */
898 
899 	*pflag = UMA_SLAB_KMEM;
900 	p = (void *) kmem_malloc(kmem_map, bytes, wait);
901 
902 	return (p);
903 }
904 
905 /*
906  * Allocates a number of pages from within an object
907  *
908  * Arguments:
909  *	zone   Unused
910  *	bytes  The number of bytes requested
911  *	wait   Shall we wait?
912  *
913  * Returns:
914  *	A pointer to the alloced memory or possibly
915  *	NULL if M_NOWAIT is set.
916  */
917 static void *
918 obj_alloc(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
919 {
920 	vm_object_t object;
921 	vm_offset_t retkva, zkva;
922 	vm_page_t p;
923 	int pages, startpages;
924 
925 	object = zone->uz_keg->uk_obj;
926 	retkva = 0;
927 
928 	/*
929 	 * This looks a little weird since we're getting one page at a time.
930 	 */
931 	VM_OBJECT_LOCK(object);
932 	p = TAILQ_LAST(&object->memq, pglist);
933 	pages = p != NULL ? p->pindex + 1 : 0;
934 	startpages = pages;
935 	zkva = zone->uz_keg->uk_kva + pages * PAGE_SIZE;
936 	for (; bytes > 0; bytes -= PAGE_SIZE) {
937 		p = vm_page_alloc(object, pages,
938 		    VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED);
939 		if (p == NULL) {
940 			if (pages != startpages)
941 				pmap_qremove(retkva, pages - startpages);
942 			while (pages != startpages) {
943 				pages--;
944 				p = TAILQ_LAST(&object->memq, pglist);
945 				vm_page_lock_queues();
946 				vm_page_unwire(p, 0);
947 				vm_page_free(p);
948 				vm_page_unlock_queues();
949 			}
950 			retkva = 0;
951 			goto done;
952 		}
953 		pmap_qenter(zkva, &p, 1);
954 		if (retkva == 0)
955 			retkva = zkva;
956 		zkva += PAGE_SIZE;
957 		pages += 1;
958 	}
959 done:
960 	VM_OBJECT_UNLOCK(object);
961 	*flags = UMA_SLAB_PRIV;
962 
963 	return ((void *)retkva);
964 }
965 
966 /*
967  * Frees a number of pages to the system
968  *
969  * Arguments:
970  *	mem   A pointer to the memory to be freed
971  *	size  The size of the memory being freed
972  *	flags The original p->us_flags field
973  *
974  * Returns:
975  *	Nothing
976  */
977 static void
978 page_free(void *mem, int size, u_int8_t flags)
979 {
980 	vm_map_t map;
981 
982 	if (flags & UMA_SLAB_KMEM)
983 		map = kmem_map;
984 	else
985 		panic("UMA: page_free used with invalid flags %d\n", flags);
986 
987 	kmem_free(map, (vm_offset_t)mem, size);
988 }
989 
990 /*
991  * Zero fill initializer
992  *
993  * Arguments/Returns follow uma_init specifications
994  */
995 static void
996 zero_init(void *mem, int size)
997 {
998 	bzero(mem, size);
999 }
1000 
1001 /*
1002  * Finish creating a small uma zone.  This calculates ipers, and the zone size.
1003  *
1004  * Arguments
1005  *	zone  The zone we should initialize
1006  *
1007  * Returns
1008  *	Nothing
1009  */
1010 static void
1011 zone_small_init(uma_zone_t zone)
1012 {
1013 	uma_keg_t keg;
1014 	int rsize;
1015 	int memused;
1016 	int ipers;
1017 
1018 	keg = zone->uz_keg;
1019 	KASSERT(keg != NULL, ("Keg is null in zone_small_init"));
1020 	rsize = keg->uk_size;
1021 
1022 	if (rsize < UMA_SMALLEST_UNIT)
1023 		rsize = UMA_SMALLEST_UNIT;
1024 
1025 	if (rsize & keg->uk_align)
1026 		rsize = (rsize & ~keg->uk_align) + (keg->uk_align + 1);
1027 
1028 	keg->uk_rsize = rsize;
1029 
1030 	rsize += 1;	/* Account for the byte of linkage */
1031 	keg->uk_ipers = (UMA_SLAB_SIZE - sizeof(struct uma_slab)) / rsize;
1032 	keg->uk_ppera = 1;
1033 
1034 	KASSERT(keg->uk_ipers != 0, ("zone_small_init: ipers is 0, uh-oh!"));
1035 	memused = keg->uk_ipers * keg->uk_rsize;
1036 
1037 	/* Can we do any better? */
1038 	if ((keg->uk_flags & UMA_ZONE_REFCNT) ||
1039 	    ((UMA_SLAB_SIZE - memused) >= UMA_MAX_WASTE)) {
1040 		/*
1041 		 * We can't do this if we're internal or if we've been
1042 		 * asked to not go to the VM for buckets.  If we do this we
1043 		 * may end up going to the VM (kmem_map) for slabs which we
1044 		 * do not want to do if we're UMA_ZFLAG_CACHEONLY as a
1045 		 * result of UMA_ZONE_VM, which clearly forbids it.
1046 		 */
1047 		if ((keg->uk_flags & UMA_ZFLAG_INTERNAL) ||
1048 		    (keg->uk_flags & UMA_ZFLAG_CACHEONLY))
1049 			return;
1050 		ipers = UMA_SLAB_SIZE / keg->uk_rsize;
1051 		if ((keg->uk_flags & UMA_ZONE_REFCNT) ||
1052 		    (ipers > keg->uk_ipers)) {
1053 			keg->uk_flags |= UMA_ZONE_OFFPAGE;
1054 			if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1055 				keg->uk_flags |= UMA_ZONE_HASH;
1056 			keg->uk_ipers = ipers;
1057 		}
1058 	}
1059 }
1060 
1061 /*
1062  * Finish creating a large (> UMA_SLAB_SIZE) uma zone.  Just give in and do
1063  * OFFPAGE for now.  When I can allow for more dynamic slab sizes this will be
1064  * more complicated.
1065  *
1066  * Arguments
1067  *	zone  The zone we should initialize
1068  *
1069  * Returns
1070  *	Nothing
1071  */
1072 static void
1073 zone_large_init(uma_zone_t zone)
1074 {
1075 	uma_keg_t keg;
1076 	int pages;
1077 
1078 	keg = zone->uz_keg;
1079 
1080 	KASSERT(keg != NULL, ("Keg is null in zone_large_init"));
1081 	KASSERT((keg->uk_flags & UMA_ZFLAG_CACHEONLY) == 0,
1082 	    ("zone_large_init: Cannot large-init a UMA_ZFLAG_CACHEONLY zone"));
1083 
1084 	pages = keg->uk_size / UMA_SLAB_SIZE;
1085 
1086 	/* Account for remainder */
1087 	if ((pages * UMA_SLAB_SIZE) < keg->uk_size)
1088 		pages++;
1089 
1090 	keg->uk_ppera = pages;
1091 	keg->uk_ipers = 1;
1092 
1093 	keg->uk_flags |= UMA_ZONE_OFFPAGE;
1094 	if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1095 		keg->uk_flags |= UMA_ZONE_HASH;
1096 
1097 	keg->uk_rsize = keg->uk_size;
1098 }
1099 
1100 /*
1101  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
1102  * the keg onto the global keg list.
1103  *
1104  * Arguments/Returns follow uma_ctor specifications
1105  *	udata  Actually uma_kctor_args
1106  */
1107 static void
1108 keg_ctor(void *mem, int size, void *udata)
1109 {
1110 	struct uma_kctor_args *arg = udata;
1111 	uma_keg_t keg = mem;
1112 	uma_zone_t zone;
1113 
1114 	bzero(keg, size);
1115 	keg->uk_size = arg->size;
1116 	keg->uk_init = arg->uminit;
1117 	keg->uk_fini = arg->fini;
1118 	keg->uk_align = arg->align;
1119 	keg->uk_free = 0;
1120 	keg->uk_pages = 0;
1121 	keg->uk_flags = arg->flags;
1122 	keg->uk_allocf = page_alloc;
1123 	keg->uk_freef = page_free;
1124 	keg->uk_recurse = 0;
1125 	keg->uk_slabzone = NULL;
1126 
1127 	/*
1128 	 * The master zone is passed to us at keg-creation time.
1129 	 */
1130 	zone = arg->zone;
1131 	zone->uz_keg = keg;
1132 
1133 	if (arg->flags & UMA_ZONE_VM)
1134 		keg->uk_flags |= UMA_ZFLAG_CACHEONLY;
1135 
1136 	if (arg->flags & UMA_ZONE_ZINIT)
1137 		keg->uk_init = zero_init;
1138 
1139 	/*
1140 	 * The +1 byte added to uk_size is to account for the byte of
1141 	 * linkage that is added to the size in zone_small_init().  If
1142 	 * we don't account for this here then we may end up in
1143 	 * zone_small_init() with a calculated 'ipers' of 0.
1144 	 */
1145 	if ((keg->uk_size+1) > (UMA_SLAB_SIZE - sizeof(struct uma_slab)))
1146 		zone_large_init(zone);
1147 	else
1148 		zone_small_init(zone);
1149 
1150 	if (keg->uk_flags & UMA_ZONE_REFCNT)
1151 		keg->uk_slabzone = slabrefzone;
1152 	else if (keg->uk_flags & UMA_ZONE_OFFPAGE)
1153 		keg->uk_slabzone = slabzone;
1154 
1155 	/*
1156 	 * If we haven't booted yet we need allocations to go through the
1157 	 * startup cache until the vm is ready.
1158 	 */
1159 	if (keg->uk_ppera == 1) {
1160 #ifdef UMA_MD_SMALL_ALLOC
1161 		keg->uk_allocf = uma_small_alloc;
1162 		keg->uk_freef = uma_small_free;
1163 #endif
1164 		if (booted == 0)
1165 			keg->uk_allocf = startup_alloc;
1166 	}
1167 
1168 	/*
1169 	 * Initialize keg's lock (shared among zones) through
1170 	 * Master zone
1171 	 */
1172 	zone->uz_lock = &keg->uk_lock;
1173 	if (arg->flags & UMA_ZONE_MTXCLASS)
1174 		ZONE_LOCK_INIT(zone, 1);
1175 	else
1176 		ZONE_LOCK_INIT(zone, 0);
1177 
1178 	/*
1179 	 * If we're putting the slab header in the actual page we need to
1180 	 * figure out where in each page it goes.  This calculates a right
1181 	 * justified offset into the memory on an ALIGN_PTR boundary.
1182 	 */
1183 	if (!(keg->uk_flags & UMA_ZONE_OFFPAGE)) {
1184 		int totsize;
1185 
1186 		/* Size of the slab struct and free list */
1187 		totsize = sizeof(struct uma_slab) + keg->uk_ipers;
1188 		if (totsize & UMA_ALIGN_PTR)
1189 			totsize = (totsize & ~UMA_ALIGN_PTR) +
1190 			    (UMA_ALIGN_PTR + 1);
1191 		keg->uk_pgoff = UMA_SLAB_SIZE - totsize;
1192 		totsize = keg->uk_pgoff + sizeof(struct uma_slab)
1193 		    + keg->uk_ipers;
1194 		/* I don't think it's possible, but I'll make sure anyway */
1195 		if (totsize > UMA_SLAB_SIZE) {
1196 			printf("zone %s ipers %d rsize %d size %d\n",
1197 			    zone->uz_name, keg->uk_ipers, keg->uk_rsize,
1198 			    keg->uk_size);
1199 			panic("UMA slab won't fit.\n");
1200 		}
1201 	}
1202 
1203 	if (keg->uk_flags & UMA_ZONE_HASH)
1204 		hash_alloc(&keg->uk_hash);
1205 
1206 #ifdef UMA_DEBUG
1207 	printf("%s(%p) size = %d ipers = %d ppera = %d pgoff = %d\n",
1208 	    zone->uz_name, zone,
1209 	    keg->uk_size, keg->uk_ipers,
1210 	    keg->uk_ppera, keg->uk_pgoff);
1211 #endif
1212 
1213 	LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
1214 
1215 	mtx_lock(&uma_mtx);
1216 	LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
1217 	mtx_unlock(&uma_mtx);
1218 }
1219 
1220 /*
1221  * Zone header ctor.  This initializes all fields, locks, etc.
1222  *
1223  * Arguments/Returns follow uma_ctor specifications
1224  *	udata  Actually uma_zctor_args
1225  */
1226 
1227 static void
1228 zone_ctor(void *mem, int size, void *udata)
1229 {
1230 	struct uma_zctor_args *arg = udata;
1231 	uma_zone_t zone = mem;
1232 	uma_zone_t z;
1233 	uma_keg_t keg;
1234 
1235 	bzero(zone, size);
1236 	zone->uz_name = arg->name;
1237 	zone->uz_ctor = arg->ctor;
1238 	zone->uz_dtor = arg->dtor;
1239 	zone->uz_init = NULL;
1240 	zone->uz_fini = NULL;
1241 	zone->uz_allocs = 0;
1242 	zone->uz_fills = zone->uz_count = 0;
1243 
1244 	if (arg->flags & UMA_ZONE_SECONDARY) {
1245 		KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
1246 		keg = arg->keg;
1247 		zone->uz_keg = keg;
1248 		zone->uz_init = arg->uminit;
1249 		zone->uz_fini = arg->fini;
1250 		zone->uz_lock = &keg->uk_lock;
1251 		mtx_lock(&uma_mtx);
1252 		ZONE_LOCK(zone);
1253 		keg->uk_flags |= UMA_ZONE_SECONDARY;
1254 		LIST_FOREACH(z, &keg->uk_zones, uz_link) {
1255 			if (LIST_NEXT(z, uz_link) == NULL) {
1256 				LIST_INSERT_AFTER(z, zone, uz_link);
1257 				break;
1258 			}
1259 		}
1260 		ZONE_UNLOCK(zone);
1261 		mtx_unlock(&uma_mtx);
1262 	} else if (arg->keg == NULL) {
1263 		uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
1264 		    arg->align, arg->flags);
1265 	} else {
1266 		struct uma_kctor_args karg;
1267 
1268 		/* We should only be here from uma_startup() */
1269 		karg.size = arg->size;
1270 		karg.uminit = arg->uminit;
1271 		karg.fini = arg->fini;
1272 		karg.align = arg->align;
1273 		karg.flags = arg->flags;
1274 		karg.zone = zone;
1275 		keg_ctor(arg->keg, sizeof(struct uma_keg), &karg);
1276 	}
1277 	keg = zone->uz_keg;
1278 	zone->uz_lock = &keg->uk_lock;
1279 
1280 	/*
1281 	 * Some internal zones don't have room allocated for the per cpu
1282 	 * caches.  If we're internal, bail out here.
1283 	 */
1284 	if (keg->uk_flags & UMA_ZFLAG_INTERNAL) {
1285 		KASSERT((keg->uk_flags & UMA_ZONE_SECONDARY) == 0,
1286 		    ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
1287 		return;
1288 	}
1289 
1290 	if (keg->uk_flags & UMA_ZONE_MAXBUCKET)
1291 		zone->uz_count = BUCKET_MAX;
1292 	else if (keg->uk_ipers <= BUCKET_MAX)
1293 		zone->uz_count = keg->uk_ipers;
1294 	else
1295 		zone->uz_count = BUCKET_MAX;
1296 }
1297 
1298 /*
1299  * Keg header dtor.  This frees all data, destroys locks, frees the hash
1300  * table and removes the keg from the global list.
1301  *
1302  * Arguments/Returns follow uma_dtor specifications
1303  *	udata  unused
1304  */
1305 static void
1306 keg_dtor(void *arg, int size, void *udata)
1307 {
1308 	uma_keg_t keg;
1309 
1310 	keg = (uma_keg_t)arg;
1311 	mtx_lock(&keg->uk_lock);
1312 	if (keg->uk_free != 0) {
1313 		printf("Freed UMA keg was not empty (%d items). "
1314 		    " Lost %d pages of memory.\n",
1315 		    keg->uk_free, keg->uk_pages);
1316 	}
1317 	mtx_unlock(&keg->uk_lock);
1318 
1319 	if (keg->uk_flags & UMA_ZONE_HASH)
1320 		hash_free(&keg->uk_hash);
1321 
1322 	mtx_destroy(&keg->uk_lock);
1323 }
1324 
1325 /*
1326  * Zone header dtor.
1327  *
1328  * Arguments/Returns follow uma_dtor specifications
1329  *	udata  unused
1330  */
1331 static void
1332 zone_dtor(void *arg, int size, void *udata)
1333 {
1334 	uma_zone_t zone;
1335 	uma_keg_t keg;
1336 
1337 	zone = (uma_zone_t)arg;
1338 	keg = zone->uz_keg;
1339 
1340 	if (!(keg->uk_flags & UMA_ZFLAG_INTERNAL))
1341 		cache_drain(zone);
1342 
1343 	mtx_lock(&uma_mtx);
1344 	zone_drain(zone);
1345 	if (keg->uk_flags & UMA_ZONE_SECONDARY) {
1346 		LIST_REMOVE(zone, uz_link);
1347 		/*
1348 		 * XXX there are some races here where
1349 		 * the zone can be drained but zone lock
1350 		 * released and then refilled before we
1351 		 * remove it... we dont care for now
1352 		 */
1353 		ZONE_LOCK(zone);
1354 		if (LIST_EMPTY(&keg->uk_zones))
1355 			keg->uk_flags &= ~UMA_ZONE_SECONDARY;
1356 		ZONE_UNLOCK(zone);
1357 		mtx_unlock(&uma_mtx);
1358 	} else {
1359 		LIST_REMOVE(keg, uk_link);
1360 		LIST_REMOVE(zone, uz_link);
1361 		mtx_unlock(&uma_mtx);
1362 		uma_zfree_internal(kegs, keg, NULL, 0);
1363 	}
1364 	zone->uz_keg = NULL;
1365 }
1366 
1367 /*
1368  * Traverses every zone in the system and calls a callback
1369  *
1370  * Arguments:
1371  *	zfunc  A pointer to a function which accepts a zone
1372  *		as an argument.
1373  *
1374  * Returns:
1375  *	Nothing
1376  */
1377 static void
1378 zone_foreach(void (*zfunc)(uma_zone_t))
1379 {
1380 	uma_keg_t keg;
1381 	uma_zone_t zone;
1382 
1383 	mtx_lock(&uma_mtx);
1384 	LIST_FOREACH(keg, &uma_kegs, uk_link) {
1385 		LIST_FOREACH(zone, &keg->uk_zones, uz_link)
1386 			zfunc(zone);
1387 	}
1388 	mtx_unlock(&uma_mtx);
1389 }
1390 
1391 /* Public functions */
1392 /* See uma.h */
1393 void
1394 uma_startup(void *bootmem)
1395 {
1396 	struct uma_zctor_args args;
1397 	uma_slab_t slab;
1398 	int slabsize;
1399 	int i;
1400 
1401 #ifdef UMA_DEBUG
1402 	printf("Creating uma keg headers zone and keg.\n");
1403 #endif
1404 	/*
1405 	 * The general UMA lock is a recursion-allowed lock because
1406 	 * there is a code path where, while we're still configured
1407 	 * to use startup_alloc() for backend page allocations, we
1408 	 * may end up in uma_reclaim() which calls zone_foreach(zone_drain),
1409 	 * which grabs uma_mtx, only to later call into startup_alloc()
1410 	 * because while freeing we needed to allocate a bucket.  Since
1411 	 * startup_alloc() also takes uma_mtx, we need to be able to
1412 	 * recurse on it.
1413 	 */
1414 	mtx_init(&uma_mtx, "UMA lock", NULL, MTX_DEF | MTX_RECURSE);
1415 
1416 	/* "manually" create the initial zone */
1417 	args.name = "UMA Kegs";
1418 	args.size = sizeof(struct uma_keg);
1419 	args.ctor = keg_ctor;
1420 	args.dtor = keg_dtor;
1421 	args.uminit = zero_init;
1422 	args.fini = NULL;
1423 	args.keg = &masterkeg;
1424 	args.align = 32 - 1;
1425 	args.flags = UMA_ZFLAG_INTERNAL;
1426 	/* The initial zone has no Per cpu queues so it's smaller */
1427 	zone_ctor(kegs, sizeof(struct uma_zone), &args);
1428 
1429 #ifdef UMA_DEBUG
1430 	printf("Filling boot free list.\n");
1431 #endif
1432 	for (i = 0; i < UMA_BOOT_PAGES; i++) {
1433 		slab = (uma_slab_t)((u_int8_t *)bootmem + (i * UMA_SLAB_SIZE));
1434 		slab->us_data = (u_int8_t *)slab;
1435 		slab->us_flags = UMA_SLAB_BOOT;
1436 		LIST_INSERT_HEAD(&uma_boot_pages, slab, us_link);
1437 		uma_boot_free++;
1438 	}
1439 
1440 #ifdef UMA_DEBUG
1441 	printf("Creating uma zone headers zone and keg.\n");
1442 #endif
1443 	args.name = "UMA Zones";
1444 	args.size = sizeof(struct uma_zone) +
1445 	    (sizeof(struct uma_cache) * (mp_maxid + 1));
1446 	args.ctor = zone_ctor;
1447 	args.dtor = zone_dtor;
1448 	args.uminit = zero_init;
1449 	args.fini = NULL;
1450 	args.keg = NULL;
1451 	args.align = 32 - 1;
1452 	args.flags = UMA_ZFLAG_INTERNAL;
1453 	/* The initial zone has no Per cpu queues so it's smaller */
1454 	zone_ctor(zones, sizeof(struct uma_zone), &args);
1455 
1456 #ifdef UMA_DEBUG
1457 	printf("Initializing pcpu cache locks.\n");
1458 #endif
1459 	/* Initialize the pcpu cache lock set once and for all */
1460 	for (i = 0; i <= mp_maxid; i++)
1461 		CPU_LOCK_INIT(i);
1462 
1463 #ifdef UMA_DEBUG
1464 	printf("Creating slab and hash zones.\n");
1465 #endif
1466 
1467 	/*
1468 	 * This is the max number of free list items we'll have with
1469 	 * offpage slabs.
1470 	 */
1471 	slabsize = UMA_SLAB_SIZE - sizeof(struct uma_slab);
1472 	slabsize /= UMA_MAX_WASTE;
1473 	slabsize++;			/* In case there it's rounded */
1474 	slabsize += sizeof(struct uma_slab);
1475 
1476 	/* Now make a zone for slab headers */
1477 	slabzone = uma_zcreate("UMA Slabs",
1478 				slabsize,
1479 				NULL, NULL, NULL, NULL,
1480 				UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1481 
1482 	/*
1483 	 * We also create a zone for the bigger slabs with reference
1484 	 * counts in them, to accomodate UMA_ZONE_REFCNT zones.
1485 	 */
1486 	slabsize = UMA_SLAB_SIZE - sizeof(struct uma_slab_refcnt);
1487 	slabsize /= UMA_MAX_WASTE;
1488 	slabsize++;
1489 	slabsize += 4 * slabsize;
1490 	slabsize += sizeof(struct uma_slab_refcnt);
1491 	slabrefzone = uma_zcreate("UMA RCntSlabs",
1492 				  slabsize,
1493 				  NULL, NULL, NULL, NULL,
1494 				  UMA_ALIGN_PTR,
1495 				  UMA_ZFLAG_INTERNAL);
1496 
1497 	hashzone = uma_zcreate("UMA Hash",
1498 	    sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
1499 	    NULL, NULL, NULL, NULL,
1500 	    UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
1501 
1502 	bucket_init();
1503 
1504 #ifdef UMA_MD_SMALL_ALLOC
1505 	booted = 1;
1506 #endif
1507 
1508 #ifdef UMA_DEBUG
1509 	printf("UMA startup complete.\n");
1510 #endif
1511 }
1512 
1513 /* see uma.h */
1514 void
1515 uma_startup2(void)
1516 {
1517 	booted = 1;
1518 	bucket_enable();
1519 #ifdef UMA_DEBUG
1520 	printf("UMA startup2 complete.\n");
1521 #endif
1522 }
1523 
1524 /*
1525  * Initialize our callout handle
1526  *
1527  */
1528 
1529 static void
1530 uma_startup3(void)
1531 {
1532 #ifdef UMA_DEBUG
1533 	printf("Starting callout.\n");
1534 #endif
1535 	callout_init(&uma_callout, CALLOUT_MPSAFE);
1536 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
1537 #ifdef UMA_DEBUG
1538 	printf("UMA startup3 complete.\n");
1539 #endif
1540 }
1541 
1542 static void
1543 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
1544 		int align, u_int16_t flags)
1545 {
1546 	struct uma_kctor_args args;
1547 
1548 	args.size = size;
1549 	args.uminit = uminit;
1550 	args.fini = fini;
1551 	args.align = align;
1552 	args.flags = flags;
1553 	args.zone = zone;
1554 	zone = uma_zalloc_internal(kegs, &args, M_WAITOK);
1555 }
1556 
1557 /* See uma.h */
1558 uma_zone_t
1559 uma_zcreate(char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
1560 		uma_init uminit, uma_fini fini, int align, u_int16_t flags)
1561 
1562 {
1563 	struct uma_zctor_args args;
1564 
1565 	/* This stuff is essential for the zone ctor */
1566 	args.name = name;
1567 	args.size = size;
1568 	args.ctor = ctor;
1569 	args.dtor = dtor;
1570 	args.uminit = uminit;
1571 	args.fini = fini;
1572 	args.align = align;
1573 	args.flags = flags;
1574 	args.keg = NULL;
1575 
1576 	return (uma_zalloc_internal(zones, &args, M_WAITOK));
1577 }
1578 
1579 /* See uma.h */
1580 uma_zone_t
1581 uma_zsecond_create(char *name, uma_ctor ctor, uma_dtor dtor,
1582 		    uma_init zinit, uma_fini zfini, uma_zone_t master)
1583 {
1584 	struct uma_zctor_args args;
1585 
1586 	args.name = name;
1587 	args.size = master->uz_keg->uk_size;
1588 	args.ctor = ctor;
1589 	args.dtor = dtor;
1590 	args.uminit = zinit;
1591 	args.fini = zfini;
1592 	args.align = master->uz_keg->uk_align;
1593 	args.flags = master->uz_keg->uk_flags | UMA_ZONE_SECONDARY;
1594 	args.keg = master->uz_keg;
1595 
1596 	return (uma_zalloc_internal(zones, &args, M_WAITOK));
1597 }
1598 
1599 /* See uma.h */
1600 void
1601 uma_zdestroy(uma_zone_t zone)
1602 {
1603 	uma_zfree_internal(zones, zone, NULL, 0);
1604 }
1605 
1606 /* See uma.h */
1607 void *
1608 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
1609 {
1610 	void *item;
1611 	uma_cache_t cache;
1612 	uma_bucket_t bucket;
1613 	int cpu;
1614 	int badness;
1615 
1616 	/* This is the fast path allocation */
1617 #ifdef UMA_DEBUG_ALLOC_1
1618 	printf("Allocating one item from %s(%p)\n", zone->uz_name, zone);
1619 #endif
1620 
1621 	if (!(flags & M_NOWAIT)) {
1622 		KASSERT(curthread->td_intr_nesting_level == 0,
1623 		   ("malloc(M_WAITOK) in interrupt context"));
1624 		badness = nosleepwithlocks;
1625 #ifdef WITNESS
1626 		badness = WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK,
1627 		    NULL,
1628 		    "malloc(M_WAITOK) of \"%s\", forcing M_NOWAIT",
1629 		    zone->uz_name);
1630 #endif
1631 		if (badness) {
1632 			flags &= ~M_WAITOK;
1633 			flags |= M_NOWAIT;
1634 		}
1635 	}
1636 
1637 zalloc_restart:
1638 	cpu = PCPU_GET(cpuid);
1639 	CPU_LOCK(cpu);
1640 	cache = &zone->uz_cpu[cpu];
1641 
1642 zalloc_start:
1643 	bucket = cache->uc_allocbucket;
1644 
1645 	if (bucket) {
1646 		if (bucket->ub_cnt > 0) {
1647 			bucket->ub_cnt--;
1648 			item = bucket->ub_bucket[bucket->ub_cnt];
1649 #ifdef INVARIANTS
1650 			bucket->ub_bucket[bucket->ub_cnt] = NULL;
1651 #endif
1652 			KASSERT(item != NULL,
1653 			    ("uma_zalloc: Bucket pointer mangled."));
1654 			cache->uc_allocs++;
1655 #ifdef INVARIANTS
1656 			ZONE_LOCK(zone);
1657 			uma_dbg_alloc(zone, NULL, item);
1658 			ZONE_UNLOCK(zone);
1659 #endif
1660 			CPU_UNLOCK(cpu);
1661 			if (zone->uz_ctor)
1662 				zone->uz_ctor(item,zone->uz_keg->uk_size,udata);
1663 			if (flags & M_ZERO)
1664 				bzero(item, zone->uz_keg->uk_size);
1665 			return (item);
1666 		} else if (cache->uc_freebucket) {
1667 			/*
1668 			 * We have run out of items in our allocbucket.
1669 			 * See if we can switch with our free bucket.
1670 			 */
1671 			if (cache->uc_freebucket->ub_cnt > 0) {
1672 #ifdef UMA_DEBUG_ALLOC
1673 				printf("uma_zalloc: Swapping empty with"
1674 				    " alloc.\n");
1675 #endif
1676 				bucket = cache->uc_freebucket;
1677 				cache->uc_freebucket = cache->uc_allocbucket;
1678 				cache->uc_allocbucket = bucket;
1679 
1680 				goto zalloc_start;
1681 			}
1682 		}
1683 	}
1684 	ZONE_LOCK(zone);
1685 	/* Since we have locked the zone we may as well send back our stats */
1686 	zone->uz_allocs += cache->uc_allocs;
1687 	cache->uc_allocs = 0;
1688 
1689 	/* Our old one is now a free bucket */
1690 	if (cache->uc_allocbucket) {
1691 		KASSERT(cache->uc_allocbucket->ub_cnt == 0,
1692 		    ("uma_zalloc_arg: Freeing a non free bucket."));
1693 		LIST_INSERT_HEAD(&zone->uz_free_bucket,
1694 		    cache->uc_allocbucket, ub_link);
1695 		cache->uc_allocbucket = NULL;
1696 	}
1697 
1698 	/* Check the free list for a new alloc bucket */
1699 	if ((bucket = LIST_FIRST(&zone->uz_full_bucket)) != NULL) {
1700 		KASSERT(bucket->ub_cnt != 0,
1701 		    ("uma_zalloc_arg: Returning an empty bucket."));
1702 
1703 		LIST_REMOVE(bucket, ub_link);
1704 		cache->uc_allocbucket = bucket;
1705 		ZONE_UNLOCK(zone);
1706 		goto zalloc_start;
1707 	}
1708 	/* We are no longer associated with this cpu!!! */
1709 	CPU_UNLOCK(cpu);
1710 
1711 	/* Bump up our uz_count so we get here less */
1712 	if (zone->uz_count < BUCKET_MAX)
1713 		zone->uz_count++;
1714 
1715 	/*
1716 	 * Now lets just fill a bucket and put it on the free list.  If that
1717 	 * works we'll restart the allocation from the begining.
1718 	 */
1719 	if (uma_zalloc_bucket(zone, flags)) {
1720 		ZONE_UNLOCK(zone);
1721 		goto zalloc_restart;
1722 	}
1723 	ZONE_UNLOCK(zone);
1724 	/*
1725 	 * We may not be able to get a bucket so return an actual item.
1726 	 */
1727 #ifdef UMA_DEBUG
1728 	printf("uma_zalloc_arg: Bucketzone returned NULL\n");
1729 #endif
1730 
1731 	return (uma_zalloc_internal(zone, udata, flags));
1732 }
1733 
1734 static uma_slab_t
1735 uma_zone_slab(uma_zone_t zone, int flags)
1736 {
1737 	uma_slab_t slab;
1738 	uma_keg_t keg;
1739 
1740 	keg = zone->uz_keg;
1741 
1742 	/*
1743 	 * This is to prevent us from recursively trying to allocate
1744 	 * buckets.  The problem is that if an allocation forces us to
1745 	 * grab a new bucket we will call page_alloc, which will go off
1746 	 * and cause the vm to allocate vm_map_entries.  If we need new
1747 	 * buckets there too we will recurse in kmem_alloc and bad
1748 	 * things happen.  So instead we return a NULL bucket, and make
1749 	 * the code that allocates buckets smart enough to deal with it
1750 	 */
1751 	if (keg->uk_flags & UMA_ZFLAG_INTERNAL && keg->uk_recurse != 0)
1752 		return (NULL);
1753 
1754 	slab = NULL;
1755 
1756 	for (;;) {
1757 		/*
1758 		 * Find a slab with some space.  Prefer slabs that are partially
1759 		 * used over those that are totally full.  This helps to reduce
1760 		 * fragmentation.
1761 		 */
1762 		if (keg->uk_free != 0) {
1763 			if (!LIST_EMPTY(&keg->uk_part_slab)) {
1764 				slab = LIST_FIRST(&keg->uk_part_slab);
1765 			} else {
1766 				slab = LIST_FIRST(&keg->uk_free_slab);
1767 				LIST_REMOVE(slab, us_link);
1768 				LIST_INSERT_HEAD(&keg->uk_part_slab, slab,
1769 				    us_link);
1770 			}
1771 			return (slab);
1772 		}
1773 
1774 		/*
1775 		 * M_NOVM means don't ask at all!
1776 		 */
1777 		if (flags & M_NOVM)
1778 			break;
1779 
1780 		if (keg->uk_maxpages &&
1781 		    keg->uk_pages >= keg->uk_maxpages) {
1782 			keg->uk_flags |= UMA_ZFLAG_FULL;
1783 
1784 			if (flags & M_NOWAIT)
1785 				break;
1786 			else
1787 				msleep(keg, &keg->uk_lock, PVM,
1788 				    "zonelimit", 0);
1789 			continue;
1790 		}
1791 		keg->uk_recurse++;
1792 		slab = slab_zalloc(zone, flags);
1793 		keg->uk_recurse--;
1794 
1795 		/*
1796 		 * If we got a slab here it's safe to mark it partially used
1797 		 * and return.  We assume that the caller is going to remove
1798 		 * at least one item.
1799 		 */
1800 		if (slab) {
1801 			LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
1802 			return (slab);
1803 		}
1804 		/*
1805 		 * We might not have been able to get a slab but another cpu
1806 		 * could have while we were unlocked.  Check again before we
1807 		 * fail.
1808 		 */
1809 		if (flags & M_NOWAIT)
1810 			flags |= M_NOVM;
1811 	}
1812 	return (slab);
1813 }
1814 
1815 static void *
1816 uma_slab_alloc(uma_zone_t zone, uma_slab_t slab)
1817 {
1818 	uma_keg_t keg;
1819 	void *item;
1820 	u_int8_t freei;
1821 
1822 	keg = zone->uz_keg;
1823 
1824 	freei = slab->us_firstfree;
1825 	slab->us_firstfree = slab->us_freelist[freei].us_item;
1826 	item = slab->us_data + (keg->uk_rsize * freei);
1827 
1828 	slab->us_freecount--;
1829 	keg->uk_free--;
1830 #ifdef INVARIANTS
1831 	uma_dbg_alloc(zone, slab, item);
1832 #endif
1833 	/* Move this slab to the full list */
1834 	if (slab->us_freecount == 0) {
1835 		LIST_REMOVE(slab, us_link);
1836 		LIST_INSERT_HEAD(&keg->uk_full_slab, slab, us_link);
1837 	}
1838 
1839 	return (item);
1840 }
1841 
1842 static int
1843 uma_zalloc_bucket(uma_zone_t zone, int flags)
1844 {
1845 	uma_bucket_t bucket;
1846 	uma_slab_t slab;
1847 	int16_t saved;
1848 	int max;
1849 
1850 	/*
1851 	 * Try this zone's free list first so we don't allocate extra buckets.
1852 	 */
1853 	if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
1854 		KASSERT(bucket->ub_cnt == 0,
1855 		    ("uma_zalloc_bucket: Bucket on free list is not empty."));
1856 		LIST_REMOVE(bucket, ub_link);
1857 	} else {
1858 		int bflags;
1859 
1860 		bflags = (flags & ~M_ZERO);
1861 		if (zone->uz_keg->uk_flags & UMA_ZFLAG_CACHEONLY)
1862 			bflags |= M_NOVM;
1863 
1864 		ZONE_UNLOCK(zone);
1865 		bucket = bucket_alloc(zone->uz_count, bflags);
1866 		ZONE_LOCK(zone);
1867 	}
1868 
1869 	if (bucket == NULL)
1870 		return (0);
1871 
1872 #ifdef SMP
1873 	/*
1874 	 * This code is here to limit the number of simultaneous bucket fills
1875 	 * for any given zone to the number of per cpu caches in this zone. This
1876 	 * is done so that we don't allocate more memory than we really need.
1877 	 */
1878 	if (zone->uz_fills >= mp_ncpus)
1879 		goto done;
1880 
1881 #endif
1882 	zone->uz_fills++;
1883 
1884 	max = MIN(bucket->ub_entries, zone->uz_count);
1885 	/* Try to keep the buckets totally full */
1886 	saved = bucket->ub_cnt;
1887 	while (bucket->ub_cnt < max &&
1888 	    (slab = uma_zone_slab(zone, flags)) != NULL) {
1889 		while (slab->us_freecount && bucket->ub_cnt < max) {
1890 			bucket->ub_bucket[bucket->ub_cnt++] =
1891 			    uma_slab_alloc(zone, slab);
1892 		}
1893 
1894 		/* Don't block on the next fill */
1895 		flags |= M_NOWAIT;
1896 	}
1897 
1898 	/*
1899 	 * We unlock here because we need to call the zone's init.
1900 	 * It should be safe to unlock because the slab dealt with
1901 	 * above is already on the appropriate list within the keg
1902 	 * and the bucket we filled is not yet on any list, so we
1903 	 * own it.
1904 	 */
1905 	if (zone->uz_init != NULL) {
1906 		int i;
1907 
1908 		ZONE_UNLOCK(zone);
1909 		for (i = saved; i < bucket->ub_cnt; i++)
1910 			zone->uz_init(bucket->ub_bucket[i],
1911 			    zone->uz_keg->uk_size);
1912 		ZONE_LOCK(zone);
1913 	}
1914 
1915 	zone->uz_fills--;
1916 	if (bucket->ub_cnt != 0) {
1917 		LIST_INSERT_HEAD(&zone->uz_full_bucket,
1918 		    bucket, ub_link);
1919 		return (1);
1920 	}
1921 #ifdef SMP
1922 done:
1923 #endif
1924 	bucket_free(bucket);
1925 
1926 	return (0);
1927 }
1928 /*
1929  * Allocates an item for an internal zone
1930  *
1931  * Arguments
1932  *	zone   The zone to alloc for.
1933  *	udata  The data to be passed to the constructor.
1934  *	flags  M_WAITOK, M_NOWAIT, M_ZERO.
1935  *
1936  * Returns
1937  *	NULL if there is no memory and M_NOWAIT is set
1938  *	An item if successful
1939  */
1940 
1941 static void *
1942 uma_zalloc_internal(uma_zone_t zone, void *udata, int flags)
1943 {
1944 	uma_keg_t keg;
1945 	uma_slab_t slab;
1946 	void *item;
1947 
1948 	item = NULL;
1949 	keg = zone->uz_keg;
1950 
1951 #ifdef UMA_DEBUG_ALLOC
1952 	printf("INTERNAL: Allocating one item from %s(%p)\n", zone->uz_name, zone);
1953 #endif
1954 	ZONE_LOCK(zone);
1955 
1956 	slab = uma_zone_slab(zone, flags);
1957 	if (slab == NULL) {
1958 		ZONE_UNLOCK(zone);
1959 		return (NULL);
1960 	}
1961 
1962 	item = uma_slab_alloc(zone, slab);
1963 
1964 	ZONE_UNLOCK(zone);
1965 
1966 	/*
1967 	 * We have to call both the zone's init (not the keg's init)
1968 	 * and the zone's ctor.  This is because the item is going from
1969 	 * a keg slab directly to the user, and the user is expecting it
1970 	 * to be both zone-init'd as well as zone-ctor'd.
1971 	 */
1972 	if (zone->uz_init != NULL)
1973 		zone->uz_init(item, keg->uk_size);
1974 	if (zone->uz_ctor != NULL)
1975 		zone->uz_ctor(item, keg->uk_size, udata);
1976 	if (flags & M_ZERO)
1977 		bzero(item, keg->uk_size);
1978 
1979 	return (item);
1980 }
1981 
1982 /* See uma.h */
1983 void
1984 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
1985 {
1986 	uma_keg_t keg;
1987 	uma_cache_t cache;
1988 	uma_bucket_t bucket;
1989 	int bflags;
1990 	int cpu;
1991 	int skip;
1992 
1993 	/* This is the fast path free */
1994 	skip = 0;
1995 	keg = zone->uz_keg;
1996 
1997 #ifdef UMA_DEBUG_ALLOC_1
1998 	printf("Freeing item %p to %s(%p)\n", item, zone->uz_name, zone);
1999 #endif
2000 	/*
2001 	 * The race here is acceptable.  If we miss it we'll just have to wait
2002 	 * a little longer for the limits to be reset.
2003 	 */
2004 
2005 	if (keg->uk_flags & UMA_ZFLAG_FULL)
2006 		goto zfree_internal;
2007 
2008 	if (zone->uz_dtor) {
2009 		zone->uz_dtor(item, keg->uk_size, udata);
2010 		skip = 1;
2011 	}
2012 
2013 zfree_restart:
2014 	cpu = PCPU_GET(cpuid);
2015 	CPU_LOCK(cpu);
2016 	cache = &zone->uz_cpu[cpu];
2017 
2018 zfree_start:
2019 	bucket = cache->uc_freebucket;
2020 
2021 	if (bucket) {
2022 		/*
2023 		 * Do we have room in our bucket? It is OK for this uz count
2024 		 * check to be slightly out of sync.
2025 		 */
2026 
2027 		if (bucket->ub_cnt < bucket->ub_entries) {
2028 			KASSERT(bucket->ub_bucket[bucket->ub_cnt] == NULL,
2029 			    ("uma_zfree: Freeing to non free bucket index."));
2030 			bucket->ub_bucket[bucket->ub_cnt] = item;
2031 			bucket->ub_cnt++;
2032 #ifdef INVARIANTS
2033 			ZONE_LOCK(zone);
2034 			if (keg->uk_flags & UMA_ZONE_MALLOC)
2035 				uma_dbg_free(zone, udata, item);
2036 			else
2037 				uma_dbg_free(zone, NULL, item);
2038 			ZONE_UNLOCK(zone);
2039 #endif
2040 			CPU_UNLOCK(cpu);
2041 			return;
2042 		} else if (cache->uc_allocbucket) {
2043 #ifdef UMA_DEBUG_ALLOC
2044 			printf("uma_zfree: Swapping buckets.\n");
2045 #endif
2046 			/*
2047 			 * We have run out of space in our freebucket.
2048 			 * See if we can switch with our alloc bucket.
2049 			 */
2050 			if (cache->uc_allocbucket->ub_cnt <
2051 			    cache->uc_freebucket->ub_cnt) {
2052 				bucket = cache->uc_freebucket;
2053 				cache->uc_freebucket = cache->uc_allocbucket;
2054 				cache->uc_allocbucket = bucket;
2055 				goto zfree_start;
2056 			}
2057 		}
2058 	}
2059 	/*
2060 	 * We can get here for two reasons:
2061 	 *
2062 	 * 1) The buckets are NULL
2063 	 * 2) The alloc and free buckets are both somewhat full.
2064 	 */
2065 
2066 	ZONE_LOCK(zone);
2067 
2068 	bucket = cache->uc_freebucket;
2069 	cache->uc_freebucket = NULL;
2070 
2071 	/* Can we throw this on the zone full list? */
2072 	if (bucket != NULL) {
2073 #ifdef UMA_DEBUG_ALLOC
2074 		printf("uma_zfree: Putting old bucket on the free list.\n");
2075 #endif
2076 		/* ub_cnt is pointing to the last free item */
2077 		KASSERT(bucket->ub_cnt != 0,
2078 		    ("uma_zfree: Attempting to insert an empty bucket onto the full list.\n"));
2079 		LIST_INSERT_HEAD(&zone->uz_full_bucket,
2080 		    bucket, ub_link);
2081 	}
2082 	if ((bucket = LIST_FIRST(&zone->uz_free_bucket)) != NULL) {
2083 		LIST_REMOVE(bucket, ub_link);
2084 		ZONE_UNLOCK(zone);
2085 		cache->uc_freebucket = bucket;
2086 		goto zfree_start;
2087 	}
2088 	/* We're done with this CPU now */
2089 	CPU_UNLOCK(cpu);
2090 
2091 	/* And the zone.. */
2092 	ZONE_UNLOCK(zone);
2093 
2094 #ifdef UMA_DEBUG_ALLOC
2095 	printf("uma_zfree: Allocating new free bucket.\n");
2096 #endif
2097 	bflags = M_NOWAIT;
2098 
2099 	if (keg->uk_flags & UMA_ZFLAG_CACHEONLY)
2100 		bflags |= M_NOVM;
2101 	bucket = bucket_alloc(zone->uz_count, bflags);
2102 	if (bucket) {
2103 		ZONE_LOCK(zone);
2104 		LIST_INSERT_HEAD(&zone->uz_free_bucket,
2105 		    bucket, ub_link);
2106 		ZONE_UNLOCK(zone);
2107 		goto zfree_restart;
2108 	}
2109 
2110 	/*
2111 	 * If nothing else caught this, we'll just do an internal free.
2112 	 */
2113 
2114 zfree_internal:
2115 
2116 #ifdef INVARIANTS
2117 	/*
2118 	 * If we need to skip the dtor and the uma_dbg_free in
2119 	 * uma_zfree_internal because we've already called the dtor
2120 	 * above, but we ended up here, then we need to make sure
2121 	 * that we take care of the uma_dbg_free immediately.
2122 	 */
2123 	if (skip) {
2124 		ZONE_LOCK(zone);
2125 		if (keg->uk_flags & UMA_ZONE_MALLOC)
2126 			uma_dbg_free(zone, udata, item);
2127 		else
2128 			uma_dbg_free(zone, NULL, item);
2129 		ZONE_UNLOCK(zone);
2130 	}
2131 #endif
2132 	uma_zfree_internal(zone, item, udata, skip);
2133 
2134 	return;
2135 }
2136 
2137 /*
2138  * Frees an item to an INTERNAL zone or allocates a free bucket
2139  *
2140  * Arguments:
2141  *	zone   The zone to free to
2142  *	item   The item we're freeing
2143  *	udata  User supplied data for the dtor
2144  *	skip   Skip the dtor, it was done in uma_zfree_arg
2145  */
2146 static void
2147 uma_zfree_internal(uma_zone_t zone, void *item, void *udata, int skip)
2148 {
2149 	uma_slab_t slab;
2150 	uma_keg_t keg;
2151 	u_int8_t *mem;
2152 	u_int8_t freei;
2153 
2154 	keg = zone->uz_keg;
2155 
2156 	if (!skip && zone->uz_dtor)
2157 		zone->uz_dtor(item, keg->uk_size, udata);
2158 	if (zone->uz_fini)
2159 		zone->uz_fini(item, keg->uk_size);
2160 
2161 	ZONE_LOCK(zone);
2162 
2163 	if (!(keg->uk_flags & UMA_ZONE_MALLOC)) {
2164 		mem = (u_int8_t *)((unsigned long)item & (~UMA_SLAB_MASK));
2165 		if (keg->uk_flags & UMA_ZONE_HASH)
2166 			slab = hash_sfind(&keg->uk_hash, mem);
2167 		else {
2168 			mem += keg->uk_pgoff;
2169 			slab = (uma_slab_t)mem;
2170 		}
2171 	} else {
2172 		slab = (uma_slab_t)udata;
2173 	}
2174 
2175 	/* Do we need to remove from any lists? */
2176 	if (slab->us_freecount+1 == keg->uk_ipers) {
2177 		LIST_REMOVE(slab, us_link);
2178 		LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2179 	} else if (slab->us_freecount == 0) {
2180 		LIST_REMOVE(slab, us_link);
2181 		LIST_INSERT_HEAD(&keg->uk_part_slab, slab, us_link);
2182 	}
2183 
2184 	/* Slab management stuff */
2185 	freei = ((unsigned long)item - (unsigned long)slab->us_data)
2186 		/ keg->uk_rsize;
2187 
2188 #ifdef INVARIANTS
2189 	if (!skip)
2190 		uma_dbg_free(zone, slab, item);
2191 #endif
2192 
2193 	slab->us_freelist[freei].us_item = slab->us_firstfree;
2194 	slab->us_firstfree = freei;
2195 	slab->us_freecount++;
2196 
2197 	/* Zone statistics */
2198 	keg->uk_free++;
2199 
2200 	if (keg->uk_flags & UMA_ZFLAG_FULL) {
2201 		if (keg->uk_pages < keg->uk_maxpages)
2202 			keg->uk_flags &= ~UMA_ZFLAG_FULL;
2203 
2204 		/* We can handle one more allocation */
2205 		wakeup_one(keg);
2206 	}
2207 
2208 	ZONE_UNLOCK(zone);
2209 }
2210 
2211 /* See uma.h */
2212 void
2213 uma_zone_set_max(uma_zone_t zone, int nitems)
2214 {
2215 	uma_keg_t keg;
2216 
2217 	keg = zone->uz_keg;
2218 	ZONE_LOCK(zone);
2219 	if (keg->uk_ppera > 1)
2220 		keg->uk_maxpages = nitems * keg->uk_ppera;
2221 	else
2222 		keg->uk_maxpages = nitems / keg->uk_ipers;
2223 
2224 	if (keg->uk_maxpages * keg->uk_ipers < nitems)
2225 		keg->uk_maxpages++;
2226 
2227 	ZONE_UNLOCK(zone);
2228 }
2229 
2230 /* See uma.h */
2231 void
2232 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
2233 {
2234 	ZONE_LOCK(zone);
2235 	KASSERT(zone->uz_keg->uk_pages == 0,
2236 	    ("uma_zone_set_init on non-empty keg"));
2237 	zone->uz_keg->uk_init = uminit;
2238 	ZONE_UNLOCK(zone);
2239 }
2240 
2241 /* See uma.h */
2242 void
2243 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
2244 {
2245 	ZONE_LOCK(zone);
2246 	KASSERT(zone->uz_keg->uk_pages == 0,
2247 	    ("uma_zone_set_fini on non-empty keg"));
2248 	zone->uz_keg->uk_fini = fini;
2249 	ZONE_UNLOCK(zone);
2250 }
2251 
2252 /* See uma.h */
2253 void
2254 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
2255 {
2256 	ZONE_LOCK(zone);
2257 	KASSERT(zone->uz_keg->uk_pages == 0,
2258 	    ("uma_zone_set_zinit on non-empty keg"));
2259 	zone->uz_init = zinit;
2260 	ZONE_UNLOCK(zone);
2261 }
2262 
2263 /* See uma.h */
2264 void
2265 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
2266 {
2267 	ZONE_LOCK(zone);
2268 	KASSERT(zone->uz_keg->uk_pages == 0,
2269 	    ("uma_zone_set_zfini on non-empty keg"));
2270 	zone->uz_fini = zfini;
2271 	ZONE_UNLOCK(zone);
2272 }
2273 
2274 /* See uma.h */
2275 void
2276 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
2277 {
2278 	ZONE_LOCK(zone);
2279 	zone->uz_keg->uk_freef = freef;
2280 	ZONE_UNLOCK(zone);
2281 }
2282 
2283 /* See uma.h */
2284 void
2285 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
2286 {
2287 	ZONE_LOCK(zone);
2288 	zone->uz_keg->uk_flags |= UMA_ZFLAG_PRIVALLOC;
2289 	zone->uz_keg->uk_allocf = allocf;
2290 	ZONE_UNLOCK(zone);
2291 }
2292 
2293 /* See uma.h */
2294 int
2295 uma_zone_set_obj(uma_zone_t zone, struct vm_object *obj, int count)
2296 {
2297 	uma_keg_t keg;
2298 	vm_offset_t kva;
2299 	int pages;
2300 
2301 	keg = zone->uz_keg;
2302 	pages = count / keg->uk_ipers;
2303 
2304 	if (pages * keg->uk_ipers < count)
2305 		pages++;
2306 
2307 	kva = kmem_alloc_pageable(kernel_map, pages * UMA_SLAB_SIZE);
2308 
2309 	if (kva == 0)
2310 		return (0);
2311 	if (obj == NULL) {
2312 		obj = vm_object_allocate(OBJT_DEFAULT,
2313 		    pages);
2314 	} else {
2315 		VM_OBJECT_LOCK_INIT(obj);
2316 		_vm_object_allocate(OBJT_DEFAULT,
2317 		    pages, obj);
2318 	}
2319 	ZONE_LOCK(zone);
2320 	keg->uk_kva = kva;
2321 	keg->uk_obj = obj;
2322 	keg->uk_maxpages = pages;
2323 	keg->uk_allocf = obj_alloc;
2324 	keg->uk_flags |= UMA_ZONE_NOFREE | UMA_ZFLAG_PRIVALLOC;
2325 	ZONE_UNLOCK(zone);
2326 	return (1);
2327 }
2328 
2329 /* See uma.h */
2330 void
2331 uma_prealloc(uma_zone_t zone, int items)
2332 {
2333 	int slabs;
2334 	uma_slab_t slab;
2335 	uma_keg_t keg;
2336 
2337 	keg = zone->uz_keg;
2338 	ZONE_LOCK(zone);
2339 	slabs = items / keg->uk_ipers;
2340 	if (slabs * keg->uk_ipers < items)
2341 		slabs++;
2342 	while (slabs > 0) {
2343 		slab = slab_zalloc(zone, M_WAITOK);
2344 		LIST_INSERT_HEAD(&keg->uk_free_slab, slab, us_link);
2345 		slabs--;
2346 	}
2347 	ZONE_UNLOCK(zone);
2348 }
2349 
2350 /* See uma.h */
2351 u_int32_t *
2352 uma_find_refcnt(uma_zone_t zone, void *item)
2353 {
2354 	uma_slabrefcnt_t slab;
2355 	uma_keg_t keg;
2356 	u_int32_t *refcnt;
2357 	int idx;
2358 
2359 	keg = zone->uz_keg;
2360 	slab = (uma_slabrefcnt_t)vtoslab((vm_offset_t)item & (~UMA_SLAB_MASK));
2361 	KASSERT(slab != NULL,
2362 	    ("uma_find_refcnt(): zone possibly not UMA_ZONE_REFCNT"));
2363 	idx = ((unsigned long)item - (unsigned long)slab->us_data)
2364 	    / keg->uk_rsize;
2365 	refcnt = &(slab->us_freelist[idx].us_refcnt);
2366 	return refcnt;
2367 }
2368 
2369 /* See uma.h */
2370 void
2371 uma_reclaim(void)
2372 {
2373 #ifdef UMA_DEBUG
2374 	printf("UMA: vm asked us to release pages!\n");
2375 #endif
2376 	bucket_enable();
2377 	zone_foreach(zone_drain);
2378 	/*
2379 	 * Some slabs may have been freed but this zone will be visited early
2380 	 * we visit again so that we can free pages that are empty once other
2381 	 * zones are drained.  We have to do the same for buckets.
2382 	 */
2383 	zone_drain(slabzone);
2384 	zone_drain(slabrefzone);
2385 	bucket_zone_drain();
2386 }
2387 
2388 void *
2389 uma_large_malloc(int size, int wait)
2390 {
2391 	void *mem;
2392 	uma_slab_t slab;
2393 	u_int8_t flags;
2394 
2395 	slab = uma_zalloc_internal(slabzone, NULL, wait);
2396 	if (slab == NULL)
2397 		return (NULL);
2398 	mem = page_alloc(NULL, size, &flags, wait);
2399 	if (mem) {
2400 		vsetslab((vm_offset_t)mem, slab);
2401 		slab->us_data = mem;
2402 		slab->us_flags = flags | UMA_SLAB_MALLOC;
2403 		slab->us_size = size;
2404 	} else {
2405 		uma_zfree_internal(slabzone, slab, NULL, 0);
2406 	}
2407 
2408 	return (mem);
2409 }
2410 
2411 void
2412 uma_large_free(uma_slab_t slab)
2413 {
2414 	vsetobj((vm_offset_t)slab->us_data, kmem_object);
2415 	page_free(slab->us_data, slab->us_size, slab->us_flags);
2416 	uma_zfree_internal(slabzone, slab, NULL, 0);
2417 }
2418 
2419 void
2420 uma_print_stats(void)
2421 {
2422 	zone_foreach(uma_print_zone);
2423 }
2424 
2425 static void
2426 slab_print(uma_slab_t slab)
2427 {
2428 	printf("slab: keg %p, data %p, freecount %d, firstfree %d\n",
2429 		slab->us_keg, slab->us_data, slab->us_freecount,
2430 		slab->us_firstfree);
2431 }
2432 
2433 static void
2434 cache_print(uma_cache_t cache)
2435 {
2436 	printf("alloc: %p(%d), free: %p(%d)\n",
2437 		cache->uc_allocbucket,
2438 		cache->uc_allocbucket?cache->uc_allocbucket->ub_cnt:0,
2439 		cache->uc_freebucket,
2440 		cache->uc_freebucket?cache->uc_freebucket->ub_cnt:0);
2441 }
2442 
2443 void
2444 uma_print_zone(uma_zone_t zone)
2445 {
2446 	uma_cache_t cache;
2447 	uma_keg_t keg;
2448 	uma_slab_t slab;
2449 	int i;
2450 
2451 	keg = zone->uz_keg;
2452 	printf("%s(%p) size %d(%d) flags %d ipers %d ppera %d out %d free %d\n",
2453 	    zone->uz_name, zone, keg->uk_size, keg->uk_rsize, keg->uk_flags,
2454 	    keg->uk_ipers, keg->uk_ppera,
2455 	    (keg->uk_ipers * keg->uk_pages) - keg->uk_free, keg->uk_free);
2456 	printf("Part slabs:\n");
2457 	LIST_FOREACH(slab, &keg->uk_part_slab, us_link)
2458 		slab_print(slab);
2459 	printf("Free slabs:\n");
2460 	LIST_FOREACH(slab, &keg->uk_free_slab, us_link)
2461 		slab_print(slab);
2462 	printf("Full slabs:\n");
2463 	LIST_FOREACH(slab, &keg->uk_full_slab, us_link)
2464 		slab_print(slab);
2465 	for (i = 0; i <= mp_maxid; i++) {
2466 		if (CPU_ABSENT(i))
2467 			continue;
2468 		cache = &zone->uz_cpu[i];
2469 		printf("CPU %d Cache:\n", i);
2470 		cache_print(cache);
2471 	}
2472 }
2473 
2474 /*
2475  * Sysctl handler for vm.zone
2476  *
2477  * stolen from vm_zone.c
2478  */
2479 static int
2480 sysctl_vm_zone(SYSCTL_HANDLER_ARGS)
2481 {
2482 	int error, len, cnt;
2483 	const int linesize = 128;	/* conservative */
2484 	int totalfree;
2485 	char *tmpbuf, *offset;
2486 	uma_zone_t z;
2487 	uma_keg_t zk;
2488 	char *p;
2489 	int cpu;
2490 	int cachefree;
2491 	uma_bucket_t bucket;
2492 	uma_cache_t cache;
2493 
2494 	cnt = 0;
2495 	mtx_lock(&uma_mtx);
2496 	LIST_FOREACH(zk, &uma_kegs, uk_link) {
2497 		LIST_FOREACH(z, &zk->uk_zones, uz_link)
2498 			cnt++;
2499 	}
2500 	mtx_unlock(&uma_mtx);
2501 	MALLOC(tmpbuf, char *, (cnt == 0 ? 1 : cnt) * linesize,
2502 			M_TEMP, M_WAITOK);
2503 	len = snprintf(tmpbuf, linesize,
2504 	    "\nITEM            SIZE     LIMIT     USED    FREE  REQUESTS\n\n");
2505 	if (cnt == 0)
2506 		tmpbuf[len - 1] = '\0';
2507 	error = SYSCTL_OUT(req, tmpbuf, cnt == 0 ? len-1 : len);
2508 	if (error || cnt == 0)
2509 		goto out;
2510 	offset = tmpbuf;
2511 	mtx_lock(&uma_mtx);
2512 	LIST_FOREACH(zk, &uma_kegs, uk_link) {
2513 	  LIST_FOREACH(z, &zk->uk_zones, uz_link) {
2514 		if (cnt == 0)	/* list may have changed size */
2515 			break;
2516 		if (!(zk->uk_flags & UMA_ZFLAG_INTERNAL)) {
2517 			for (cpu = 0; cpu <= mp_maxid; cpu++) {
2518 				if (CPU_ABSENT(cpu))
2519 					continue;
2520 				CPU_LOCK(cpu);
2521 			}
2522 		}
2523 		ZONE_LOCK(z);
2524 		cachefree = 0;
2525 		if (!(zk->uk_flags & UMA_ZFLAG_INTERNAL)) {
2526 			for (cpu = 0; cpu <= mp_maxid; cpu++) {
2527 				if (CPU_ABSENT(cpu))
2528 					continue;
2529 				cache = &z->uz_cpu[cpu];
2530 				if (cache->uc_allocbucket != NULL)
2531 					cachefree += cache->uc_allocbucket->ub_cnt;
2532 				if (cache->uc_freebucket != NULL)
2533 					cachefree += cache->uc_freebucket->ub_cnt;
2534 				CPU_UNLOCK(cpu);
2535 			}
2536 		}
2537 		LIST_FOREACH(bucket, &z->uz_full_bucket, ub_link) {
2538 			cachefree += bucket->ub_cnt;
2539 		}
2540 		totalfree = zk->uk_free + cachefree;
2541 		len = snprintf(offset, linesize,
2542 		    "%-12.12s  %6.6u, %8.8u, %6.6u, %6.6u, %8.8llu\n",
2543 		    z->uz_name, zk->uk_size,
2544 		    zk->uk_maxpages * zk->uk_ipers,
2545 		    (zk->uk_ipers * (zk->uk_pages / zk->uk_ppera)) - totalfree,
2546 		    totalfree,
2547 		    (unsigned long long)z->uz_allocs);
2548 		ZONE_UNLOCK(z);
2549 		for (p = offset + 12; p > offset && *p == ' '; --p)
2550 			/* nothing */ ;
2551 		p[1] = ':';
2552 		cnt--;
2553 		offset += len;
2554 	  }
2555 	}
2556 	mtx_unlock(&uma_mtx);
2557 	*offset++ = '\0';
2558 	error = SYSCTL_OUT(req, tmpbuf, offset - tmpbuf);
2559 out:
2560 	FREE(tmpbuf, M_TEMP);
2561 	return (error);
2562 }
2563