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