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