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