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