xref: /f-stack/freebsd/vm/uma_core.c (revision 22ce4aff)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2019 Jeffrey Roberson <[email protected]>
5  * Copyright (c) 2004, 2005 Bosko Milekic <[email protected]>
6  * Copyright (c) 2004-2006 Robert N. M. Watson
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /*
32  * uma_core.c  Implementation of the Universal Memory allocator
33  *
34  * This allocator is intended to replace the multitude of similar object caches
35  * in the standard FreeBSD kernel.  The intent is to be flexible as well as
36  * efficient.  A primary design goal is to return unused memory to the rest of
37  * the system.  This will make the system as a whole more flexible due to the
38  * ability to move memory to subsystems which most need it instead of leaving
39  * pools of reserved memory unused.
40  *
41  * The basic ideas stem from similar slab/zone based allocators whose algorithms
42  * are well known.
43  *
44  */
45 
46 /*
47  * TODO:
48  *	- Improve memory usage for large allocations
49  *	- Investigate cache size adjustments
50  */
51 
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54 
55 #include "opt_ddb.h"
56 #include "opt_param.h"
57 #include "opt_vm.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bitset.h>
62 #include <sys/domainset.h>
63 #include <sys/eventhandler.h>
64 #include <sys/kernel.h>
65 #include <sys/types.h>
66 #include <sys/limits.h>
67 #include <sys/queue.h>
68 #include <sys/malloc.h>
69 #include <sys/ktr.h>
70 #include <sys/lock.h>
71 #include <sys/sysctl.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/random.h>
75 #include <sys/rwlock.h>
76 #include <sys/sbuf.h>
77 #include <sys/sched.h>
78 #include <sys/sleepqueue.h>
79 #include <sys/smp.h>
80 #include <sys/smr.h>
81 #include <sys/taskqueue.h>
82 #include <sys/vmmeter.h>
83 
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/vm_domainset.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_phys.h>
91 #include <vm/vm_pagequeue.h>
92 #include <vm/vm_map.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_extern.h>
95 #include <vm/vm_dumpset.h>
96 #include <vm/uma.h>
97 #include <vm/uma_int.h>
98 #include <vm/uma_dbg.h>
99 
100 #include <ddb/ddb.h>
101 
102 #ifdef DEBUG_MEMGUARD
103 #include <vm/memguard.h>
104 #endif
105 
106 #include <machine/md_var.h>
107 
108 #ifdef INVARIANTS
109 #define	UMA_ALWAYS_CTORDTOR	1
110 #else
111 #define	UMA_ALWAYS_CTORDTOR	0
112 #endif
113 
114 /*
115  * This is the zone and keg from which all zones are spawned.
116  */
117 static uma_zone_t kegs;
118 static uma_zone_t zones;
119 
120 /*
121  * On INVARIANTS builds, the slab contains a second bitset of the same size,
122  * "dbg_bits", which is laid out immediately after us_free.
123  */
124 #ifdef INVARIANTS
125 #define	SLAB_BITSETS	2
126 #else
127 #define	SLAB_BITSETS	1
128 #endif
129 
130 /*
131  * These are the two zones from which all offpage uma_slab_ts are allocated.
132  *
133  * One zone is for slab headers that can represent a larger number of items,
134  * making the slabs themselves more efficient, and the other zone is for
135  * headers that are smaller and represent fewer items, making the headers more
136  * efficient.
137  */
138 #define	SLABZONE_SIZE(setsize)					\
139     (sizeof(struct uma_hash_slab) + BITSET_SIZE(setsize) * SLAB_BITSETS)
140 #define	SLABZONE0_SETSIZE	(PAGE_SIZE / 16)
141 #define	SLABZONE1_SETSIZE	SLAB_MAX_SETSIZE
142 #define	SLABZONE0_SIZE	SLABZONE_SIZE(SLABZONE0_SETSIZE)
143 #define	SLABZONE1_SIZE	SLABZONE_SIZE(SLABZONE1_SETSIZE)
144 static uma_zone_t slabzones[2];
145 
146 /*
147  * The initial hash tables come out of this zone so they can be allocated
148  * prior to malloc coming up.
149  */
150 static uma_zone_t hashzone;
151 
152 /* The boot-time adjusted value for cache line alignment. */
153 int uma_align_cache = 64 - 1;
154 
155 static MALLOC_DEFINE(M_UMAHASH, "UMAHash", "UMA Hash Buckets");
156 static MALLOC_DEFINE(M_UMA, "UMA", "UMA Misc");
157 
158 /*
159  * Are we allowed to allocate buckets?
160  */
161 static int bucketdisable = 1;
162 
163 /* Linked list of all kegs in the system */
164 static LIST_HEAD(,uma_keg) uma_kegs = LIST_HEAD_INITIALIZER(uma_kegs);
165 
166 /* Linked list of all cache-only zones in the system */
167 static LIST_HEAD(,uma_zone) uma_cachezones =
168     LIST_HEAD_INITIALIZER(uma_cachezones);
169 
170 /* This RW lock protects the keg list */
171 static struct rwlock_padalign __exclusive_cache_line uma_rwlock;
172 
173 /*
174  * First available virual address for boot time allocations.
175  */
176 static vm_offset_t bootstart;
177 static vm_offset_t bootmem;
178 
179 static struct sx uma_reclaim_lock;
180 
181 /*
182  * kmem soft limit, initialized by uma_set_limit().  Ensure that early
183  * allocations don't trigger a wakeup of the reclaim thread.
184  */
185 unsigned long uma_kmem_limit = LONG_MAX;
186 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_limit, CTLFLAG_RD, &uma_kmem_limit, 0,
187     "UMA kernel memory soft limit");
188 unsigned long uma_kmem_total;
189 SYSCTL_ULONG(_vm, OID_AUTO, uma_kmem_total, CTLFLAG_RD, &uma_kmem_total, 0,
190     "UMA kernel memory usage");
191 
192 /* Is the VM done starting up? */
193 static enum {
194 	BOOT_COLD,
195 	BOOT_KVA,
196 	BOOT_PCPU,
197 	BOOT_RUNNING,
198 	BOOT_SHUTDOWN,
199 } booted = BOOT_COLD;
200 
201 /*
202  * This is the handle used to schedule events that need to happen
203  * outside of the allocation fast path.
204  */
205 static struct callout uma_callout;
206 #define	UMA_TIMEOUT	20		/* Seconds for callout interval. */
207 
208 /*
209  * This structure is passed as the zone ctor arg so that I don't have to create
210  * a special allocation function just for zones.
211  */
212 struct uma_zctor_args {
213 	const char *name;
214 	size_t size;
215 	uma_ctor ctor;
216 	uma_dtor dtor;
217 	uma_init uminit;
218 	uma_fini fini;
219 	uma_import import;
220 	uma_release release;
221 	void *arg;
222 	uma_keg_t keg;
223 	int align;
224 	uint32_t flags;
225 };
226 
227 struct uma_kctor_args {
228 	uma_zone_t zone;
229 	size_t size;
230 	uma_init uminit;
231 	uma_fini fini;
232 	int align;
233 	uint32_t flags;
234 };
235 
236 struct uma_bucket_zone {
237 	uma_zone_t	ubz_zone;
238 	const char	*ubz_name;
239 	int		ubz_entries;	/* Number of items it can hold. */
240 	int		ubz_maxsize;	/* Maximum allocation size per-item. */
241 };
242 
243 /*
244  * Compute the actual number of bucket entries to pack them in power
245  * of two sizes for more efficient space utilization.
246  */
247 #define	BUCKET_SIZE(n)						\
248     (((sizeof(void *) * (n)) - sizeof(struct uma_bucket)) / sizeof(void *))
249 
250 #define	BUCKET_MAX	BUCKET_SIZE(256)
251 
252 struct uma_bucket_zone bucket_zones[] = {
253 	/* Literal bucket sizes. */
254 	{ NULL, "2 Bucket", 2, 4096 },
255 	{ NULL, "4 Bucket", 4, 3072 },
256 	{ NULL, "8 Bucket", 8, 2048 },
257 	{ NULL, "16 Bucket", 16, 1024 },
258 	/* Rounded down power of 2 sizes for efficiency. */
259 	{ NULL, "32 Bucket", BUCKET_SIZE(32), 512 },
260 	{ NULL, "64 Bucket", BUCKET_SIZE(64), 256 },
261 	{ NULL, "128 Bucket", BUCKET_SIZE(128), 128 },
262 	{ NULL, "256 Bucket", BUCKET_SIZE(256), 64 },
263 	{ NULL, NULL, 0}
264 };
265 
266 /*
267  * Flags and enumerations to be passed to internal functions.
268  */
269 enum zfreeskip {
270 	SKIP_NONE =	0,
271 	SKIP_CNT =	0x00000001,
272 	SKIP_DTOR =	0x00010000,
273 	SKIP_FINI =	0x00020000,
274 };
275 
276 /* Prototypes.. */
277 
278 void	uma_startup1(vm_offset_t);
279 void	uma_startup2(void);
280 
281 #ifndef FSTACK
282 static void *noobj_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
283 #endif
284 static void *page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
285 static void *pcpu_page_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
286 static void *startup_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
287 static void *contig_alloc(uma_zone_t, vm_size_t, int, uint8_t *, int);
288 static void page_free(void *, vm_size_t, uint8_t);
289 static void pcpu_page_free(void *, vm_size_t, uint8_t);
290 static uma_slab_t keg_alloc_slab(uma_keg_t, uma_zone_t, int, int, int);
291 static void cache_drain(uma_zone_t);
292 static void bucket_drain(uma_zone_t, uma_bucket_t);
293 static void bucket_cache_reclaim(uma_zone_t zone, bool);
294 static int keg_ctor(void *, int, void *, int);
295 static void keg_dtor(void *, int, void *);
296 static int zone_ctor(void *, int, void *, int);
297 static void zone_dtor(void *, int, void *);
298 static inline void item_dtor(uma_zone_t zone, void *item, int size,
299     void *udata, enum zfreeskip skip);
300 static int zero_init(void *, int, int);
301 static void zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
302     int itemdomain, bool ws);
303 static void zone_foreach(void (*zfunc)(uma_zone_t, void *), void *);
304 static void zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *), void *);
305 static void zone_timeout(uma_zone_t zone, void *);
306 static int hash_alloc(struct uma_hash *, u_int);
307 static int hash_expand(struct uma_hash *, struct uma_hash *);
308 static void hash_free(struct uma_hash *hash);
309 static void uma_timeout(void *);
310 static void uma_shutdown(void);
311 static void *zone_alloc_item(uma_zone_t, void *, int, int);
312 static void zone_free_item(uma_zone_t, void *, void *, enum zfreeskip);
313 static int zone_alloc_limit(uma_zone_t zone, int count, int flags);
314 static void zone_free_limit(uma_zone_t zone, int count);
315 static void bucket_enable(void);
316 static void bucket_init(void);
317 static uma_bucket_t bucket_alloc(uma_zone_t zone, void *, int);
318 static void bucket_free(uma_zone_t zone, uma_bucket_t, void *);
319 static void bucket_zone_drain(void);
320 static uma_bucket_t zone_alloc_bucket(uma_zone_t, void *, int, int);
321 static void *slab_alloc_item(uma_keg_t keg, uma_slab_t slab);
322 static void slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item);
323 static uma_keg_t uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit,
324     uma_fini fini, int align, uint32_t flags);
325 static int zone_import(void *, void **, int, int, int);
326 static void zone_release(void *, void **, int);
327 static bool cache_alloc(uma_zone_t, uma_cache_t, void *, int);
328 static bool cache_free(uma_zone_t, uma_cache_t, void *, void *, int);
329 
330 static int sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS);
331 static int sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS);
332 static int sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS);
333 static int sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS);
334 static int sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS);
335 static int sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS);
336 static int sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS);
337 
338 static uint64_t uma_zone_get_allocs(uma_zone_t zone);
339 
340 static SYSCTL_NODE(_vm, OID_AUTO, debug, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
341     "Memory allocation debugging");
342 
343 #ifdef INVARIANTS
344 static uint64_t uma_keg_get_allocs(uma_keg_t zone);
345 static inline struct noslabbits *slab_dbg_bits(uma_slab_t slab, uma_keg_t keg);
346 
347 static bool uma_dbg_kskip(uma_keg_t keg, void *mem);
348 static bool uma_dbg_zskip(uma_zone_t zone, void *mem);
349 static void uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item);
350 static void uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item);
351 
352 static u_int dbg_divisor = 1;
353 SYSCTL_UINT(_vm_debug, OID_AUTO, divisor,
354     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &dbg_divisor, 0,
355     "Debug & thrash every this item in memory allocator");
356 
357 static counter_u64_t uma_dbg_cnt = EARLY_COUNTER;
358 static counter_u64_t uma_skip_cnt = EARLY_COUNTER;
359 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, trashed, CTLFLAG_RD,
360     &uma_dbg_cnt, "memory items debugged");
361 SYSCTL_COUNTER_U64(_vm_debug, OID_AUTO, skipped, CTLFLAG_RD,
362     &uma_skip_cnt, "memory items skipped, not debugged");
363 #endif
364 
365 SYSCTL_NODE(_vm, OID_AUTO, uma, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
366     "Universal Memory Allocator");
367 
368 SYSCTL_PROC(_vm, OID_AUTO, zone_count, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_INT,
369     0, 0, sysctl_vm_zone_count, "I", "Number of UMA zones");
370 
371 SYSCTL_PROC(_vm, OID_AUTO, zone_stats, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLTYPE_STRUCT,
372     0, 0, sysctl_vm_zone_stats, "s,struct uma_type_header", "Zone Stats");
373 
374 static int zone_warnings = 1;
375 SYSCTL_INT(_vm, OID_AUTO, zone_warnings, CTLFLAG_RWTUN, &zone_warnings, 0,
376     "Warn when UMA zones becomes full");
377 
378 static int multipage_slabs = 1;
379 TUNABLE_INT("vm.debug.uma_multipage_slabs", &multipage_slabs);
380 SYSCTL_INT(_vm_debug, OID_AUTO, uma_multipage_slabs,
381     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &multipage_slabs, 0,
382     "UMA may choose larger slab sizes for better efficiency");
383 
384 /*
385  * Select the slab zone for an offpage slab with the given maximum item count.
386  */
387 static inline uma_zone_t
slabzone(int ipers)388 slabzone(int ipers)
389 {
390 
391 	return (slabzones[ipers > SLABZONE0_SETSIZE]);
392 }
393 
394 /*
395  * This routine checks to see whether or not it's safe to enable buckets.
396  */
397 static void
bucket_enable(void)398 bucket_enable(void)
399 {
400 
401 	KASSERT(booted >= BOOT_KVA, ("Bucket enable before init"));
402 	bucketdisable = vm_page_count_min();
403 }
404 
405 /*
406  * Initialize bucket_zones, the array of zones of buckets of various sizes.
407  *
408  * For each zone, calculate the memory required for each bucket, consisting
409  * of the header and an array of pointers.
410  */
411 static void
bucket_init(void)412 bucket_init(void)
413 {
414 	struct uma_bucket_zone *ubz;
415 	int size;
416 
417 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++) {
418 		size = roundup(sizeof(struct uma_bucket), sizeof(void *));
419 		size += sizeof(void *) * ubz->ubz_entries;
420 		ubz->ubz_zone = uma_zcreate(ubz->ubz_name, size,
421 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
422 		    UMA_ZONE_MTXCLASS | UMA_ZFLAG_BUCKET |
423 		    UMA_ZONE_FIRSTTOUCH);
424 	}
425 }
426 
427 /*
428  * Given a desired number of entries for a bucket, return the zone from which
429  * to allocate the bucket.
430  */
431 static struct uma_bucket_zone *
bucket_zone_lookup(int entries)432 bucket_zone_lookup(int entries)
433 {
434 	struct uma_bucket_zone *ubz;
435 
436 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
437 		if (ubz->ubz_entries >= entries)
438 			return (ubz);
439 	ubz--;
440 	return (ubz);
441 }
442 
443 static int
bucket_select(int size)444 bucket_select(int size)
445 {
446 	struct uma_bucket_zone *ubz;
447 
448 	ubz = &bucket_zones[0];
449 	if (size > ubz->ubz_maxsize)
450 		return MAX((ubz->ubz_maxsize * ubz->ubz_entries) / size, 1);
451 
452 	for (; ubz->ubz_entries != 0; ubz++)
453 		if (ubz->ubz_maxsize < size)
454 			break;
455 	ubz--;
456 	return (ubz->ubz_entries);
457 }
458 
459 static uma_bucket_t
bucket_alloc(uma_zone_t zone,void * udata,int flags)460 bucket_alloc(uma_zone_t zone, void *udata, int flags)
461 {
462 	struct uma_bucket_zone *ubz;
463 	uma_bucket_t bucket;
464 
465 	/*
466 	 * Don't allocate buckets early in boot.
467 	 */
468 	if (__predict_false(booted < BOOT_KVA))
469 		return (NULL);
470 
471 	/*
472 	 * To limit bucket recursion we store the original zone flags
473 	 * in a cookie passed via zalloc_arg/zfree_arg.  This allows the
474 	 * NOVM flag to persist even through deep recursions.  We also
475 	 * store ZFLAG_BUCKET once we have recursed attempting to allocate
476 	 * a bucket for a bucket zone so we do not allow infinite bucket
477 	 * recursion.  This cookie will even persist to frees of unused
478 	 * buckets via the allocation path or bucket allocations in the
479 	 * free path.
480 	 */
481 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
482 		udata = (void *)(uintptr_t)zone->uz_flags;
483 	else {
484 		if ((uintptr_t)udata & UMA_ZFLAG_BUCKET)
485 			return (NULL);
486 		udata = (void *)((uintptr_t)udata | UMA_ZFLAG_BUCKET);
487 	}
488 	if (((uintptr_t)udata & UMA_ZONE_VM) != 0)
489 		flags |= M_NOVM;
490 	ubz = bucket_zone_lookup(atomic_load_16(&zone->uz_bucket_size));
491 	if (ubz->ubz_zone == zone && (ubz + 1)->ubz_entries != 0)
492 		ubz++;
493 	bucket = uma_zalloc_arg(ubz->ubz_zone, udata, flags);
494 	if (bucket) {
495 #ifdef INVARIANTS
496 		bzero(bucket->ub_bucket, sizeof(void *) * ubz->ubz_entries);
497 #endif
498 		bucket->ub_cnt = 0;
499 		bucket->ub_entries = min(ubz->ubz_entries,
500 		    zone->uz_bucket_size_max);
501 		bucket->ub_seq = SMR_SEQ_INVALID;
502 		CTR3(KTR_UMA, "bucket_alloc: zone %s(%p) allocated bucket %p",
503 		    zone->uz_name, zone, bucket);
504 	}
505 
506 	return (bucket);
507 }
508 
509 static void
bucket_free(uma_zone_t zone,uma_bucket_t bucket,void * udata)510 bucket_free(uma_zone_t zone, uma_bucket_t bucket, void *udata)
511 {
512 	struct uma_bucket_zone *ubz;
513 
514 	if (bucket->ub_cnt != 0)
515 		bucket_drain(zone, bucket);
516 
517 	KASSERT(bucket->ub_cnt == 0,
518 	    ("bucket_free: Freeing a non free bucket."));
519 	KASSERT(bucket->ub_seq == SMR_SEQ_INVALID,
520 	    ("bucket_free: Freeing an SMR bucket."));
521 	if ((zone->uz_flags & UMA_ZFLAG_BUCKET) == 0)
522 		udata = (void *)(uintptr_t)zone->uz_flags;
523 	ubz = bucket_zone_lookup(bucket->ub_entries);
524 	uma_zfree_arg(ubz->ubz_zone, bucket, udata);
525 }
526 
527 static void
bucket_zone_drain(void)528 bucket_zone_drain(void)
529 {
530 	struct uma_bucket_zone *ubz;
531 
532 	for (ubz = &bucket_zones[0]; ubz->ubz_entries != 0; ubz++)
533 		uma_zone_reclaim(ubz->ubz_zone, UMA_RECLAIM_DRAIN);
534 }
535 
536 /*
537  * Acquire the domain lock and record contention.
538  */
539 static uma_zone_domain_t
zone_domain_lock(uma_zone_t zone,int domain)540 zone_domain_lock(uma_zone_t zone, int domain)
541 {
542 	uma_zone_domain_t zdom;
543 	bool lockfail;
544 
545 	zdom = ZDOM_GET(zone, domain);
546 	lockfail = false;
547 	if (ZDOM_OWNED(zdom))
548 		lockfail = true;
549 	ZDOM_LOCK(zdom);
550 	/* This is unsynchronized.  The counter does not need to be precise. */
551 	if (lockfail && zone->uz_bucket_size < zone->uz_bucket_size_max)
552 		zone->uz_bucket_size++;
553 	return (zdom);
554 }
555 
556 /*
557  * Search for the domain with the least cached items and return it if it
558  * is out of balance with the preferred domain.
559  */
560 static __noinline int
zone_domain_lowest(uma_zone_t zone,int pref)561 zone_domain_lowest(uma_zone_t zone, int pref)
562 {
563 	long least, nitems, prefitems;
564 	int domain;
565 	int i;
566 
567 	prefitems = least = LONG_MAX;
568 	domain = 0;
569 	for (i = 0; i < vm_ndomains; i++) {
570 		nitems = ZDOM_GET(zone, i)->uzd_nitems;
571 		if (nitems < least) {
572 			domain = i;
573 			least = nitems;
574 		}
575 		if (domain == pref)
576 			prefitems = nitems;
577 	}
578 	if (prefitems < least * 2)
579 		return (pref);
580 
581 	return (domain);
582 }
583 
584 /*
585  * Search for the domain with the most cached items and return it or the
586  * preferred domain if it has enough to proceed.
587  */
588 static __noinline int
zone_domain_highest(uma_zone_t zone,int pref)589 zone_domain_highest(uma_zone_t zone, int pref)
590 {
591 	long most, nitems;
592 	int domain;
593 	int i;
594 
595 	if (ZDOM_GET(zone, pref)->uzd_nitems > BUCKET_MAX)
596 		return (pref);
597 
598 	most = 0;
599 	domain = 0;
600 	for (i = 0; i < vm_ndomains; i++) {
601 		nitems = ZDOM_GET(zone, i)->uzd_nitems;
602 		if (nitems > most) {
603 			domain = i;
604 			most = nitems;
605 		}
606 	}
607 
608 	return (domain);
609 }
610 
611 /*
612  * Safely subtract cnt from imax.
613  */
614 static void
zone_domain_imax_sub(uma_zone_domain_t zdom,int cnt)615 zone_domain_imax_sub(uma_zone_domain_t zdom, int cnt)
616 {
617 	long new;
618 	long old;
619 
620 	old = zdom->uzd_imax;
621 	do {
622 		if (old <= cnt)
623 			new = 0;
624 		else
625 			new = old - cnt;
626 	} while (atomic_fcmpset_long(&zdom->uzd_imax, &old, new) == 0);
627 }
628 
629 /*
630  * Set the maximum imax value.
631  */
632 static void
zone_domain_imax_set(uma_zone_domain_t zdom,int nitems)633 zone_domain_imax_set(uma_zone_domain_t zdom, int nitems)
634 {
635 	long old;
636 
637 	old = zdom->uzd_imax;
638 	do {
639 		if (old >= nitems)
640 			break;
641 	} while (atomic_fcmpset_long(&zdom->uzd_imax, &old, nitems) == 0);
642 }
643 
644 /*
645  * Attempt to satisfy an allocation by retrieving a full bucket from one of the
646  * zone's caches.  If a bucket is found the zone is not locked on return.
647  */
648 static uma_bucket_t
zone_fetch_bucket(uma_zone_t zone,uma_zone_domain_t zdom,bool reclaim)649 zone_fetch_bucket(uma_zone_t zone, uma_zone_domain_t zdom, bool reclaim)
650 {
651 	uma_bucket_t bucket;
652 	int i;
653 	bool dtor = false;
654 
655 	ZDOM_LOCK_ASSERT(zdom);
656 
657 	if ((bucket = STAILQ_FIRST(&zdom->uzd_buckets)) == NULL)
658 		return (NULL);
659 
660 	/* SMR Buckets can not be re-used until readers expire. */
661 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
662 	    bucket->ub_seq != SMR_SEQ_INVALID) {
663 		if (!smr_poll(zone->uz_smr, bucket->ub_seq, false))
664 			return (NULL);
665 		bucket->ub_seq = SMR_SEQ_INVALID;
666 		dtor = (zone->uz_dtor != NULL) || UMA_ALWAYS_CTORDTOR;
667 		if (STAILQ_NEXT(bucket, ub_link) != NULL)
668 			zdom->uzd_seq = STAILQ_NEXT(bucket, ub_link)->ub_seq;
669 	}
670 	STAILQ_REMOVE_HEAD(&zdom->uzd_buckets, ub_link);
671 
672 	KASSERT(zdom->uzd_nitems >= bucket->ub_cnt,
673 	    ("%s: item count underflow (%ld, %d)",
674 	    __func__, zdom->uzd_nitems, bucket->ub_cnt));
675 	KASSERT(bucket->ub_cnt > 0,
676 	    ("%s: empty bucket in bucket cache", __func__));
677 	zdom->uzd_nitems -= bucket->ub_cnt;
678 
679 	/*
680 	 * Shift the bounds of the current WSS interval to avoid
681 	 * perturbing the estimate.
682 	 */
683 	if (reclaim) {
684 		zdom->uzd_imin -= lmin(zdom->uzd_imin, bucket->ub_cnt);
685 		zone_domain_imax_sub(zdom, bucket->ub_cnt);
686 	} else if (zdom->uzd_imin > zdom->uzd_nitems)
687 		zdom->uzd_imin = zdom->uzd_nitems;
688 
689 	ZDOM_UNLOCK(zdom);
690 	if (dtor)
691 		for (i = 0; i < bucket->ub_cnt; i++)
692 			item_dtor(zone, bucket->ub_bucket[i], zone->uz_size,
693 			    NULL, SKIP_NONE);
694 
695 	return (bucket);
696 }
697 
698 /*
699  * Insert a full bucket into the specified cache.  The "ws" parameter indicates
700  * whether the bucket's contents should be counted as part of the zone's working
701  * set.  The bucket may be freed if it exceeds the bucket limit.
702  */
703 static void
zone_put_bucket(uma_zone_t zone,int domain,uma_bucket_t bucket,void * udata,const bool ws)704 zone_put_bucket(uma_zone_t zone, int domain, uma_bucket_t bucket, void *udata,
705     const bool ws)
706 {
707 	uma_zone_domain_t zdom;
708 
709 	/* We don't cache empty buckets.  This can happen after a reclaim. */
710 	if (bucket->ub_cnt == 0)
711 		goto out;
712 	zdom = zone_domain_lock(zone, domain);
713 
714 	/*
715 	 * Conditionally set the maximum number of items.
716 	 */
717 	zdom->uzd_nitems += bucket->ub_cnt;
718 	if (__predict_true(zdom->uzd_nitems < zone->uz_bucket_max)) {
719 		if (ws)
720 			zone_domain_imax_set(zdom, zdom->uzd_nitems);
721 		if (STAILQ_EMPTY(&zdom->uzd_buckets))
722 			zdom->uzd_seq = bucket->ub_seq;
723 
724 		/*
725 		 * Try to promote reuse of recently used items.  For items
726 		 * protected by SMR, try to defer reuse to minimize polling.
727 		 */
728 		if (bucket->ub_seq == SMR_SEQ_INVALID)
729 			STAILQ_INSERT_HEAD(&zdom->uzd_buckets, bucket, ub_link);
730 		else
731 			STAILQ_INSERT_TAIL(&zdom->uzd_buckets, bucket, ub_link);
732 		ZDOM_UNLOCK(zdom);
733 		return;
734 	}
735 	zdom->uzd_nitems -= bucket->ub_cnt;
736 	ZDOM_UNLOCK(zdom);
737 out:
738 	bucket_free(zone, bucket, udata);
739 }
740 
741 /* Pops an item out of a per-cpu cache bucket. */
742 static inline void *
cache_bucket_pop(uma_cache_t cache,uma_cache_bucket_t bucket)743 cache_bucket_pop(uma_cache_t cache, uma_cache_bucket_t bucket)
744 {
745 	void *item;
746 
747 	CRITICAL_ASSERT(curthread);
748 
749 	bucket->ucb_cnt--;
750 	item = bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt];
751 #ifdef INVARIANTS
752 	bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = NULL;
753 	KASSERT(item != NULL, ("uma_zalloc: Bucket pointer mangled."));
754 #endif
755 	cache->uc_allocs++;
756 
757 	return (item);
758 }
759 
760 /* Pushes an item into a per-cpu cache bucket. */
761 static inline void
cache_bucket_push(uma_cache_t cache,uma_cache_bucket_t bucket,void * item)762 cache_bucket_push(uma_cache_t cache, uma_cache_bucket_t bucket, void *item)
763 {
764 
765 	CRITICAL_ASSERT(curthread);
766 	KASSERT(bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] == NULL,
767 	    ("uma_zfree: Freeing to non free bucket index."));
768 
769 	bucket->ucb_bucket->ub_bucket[bucket->ucb_cnt] = item;
770 	bucket->ucb_cnt++;
771 	cache->uc_frees++;
772 }
773 
774 /*
775  * Unload a UMA bucket from a per-cpu cache.
776  */
777 static inline uma_bucket_t
cache_bucket_unload(uma_cache_bucket_t bucket)778 cache_bucket_unload(uma_cache_bucket_t bucket)
779 {
780 	uma_bucket_t b;
781 
782 	b = bucket->ucb_bucket;
783 	if (b != NULL) {
784 		MPASS(b->ub_entries == bucket->ucb_entries);
785 		b->ub_cnt = bucket->ucb_cnt;
786 		bucket->ucb_bucket = NULL;
787 		bucket->ucb_entries = bucket->ucb_cnt = 0;
788 	}
789 
790 	return (b);
791 }
792 
793 static inline uma_bucket_t
cache_bucket_unload_alloc(uma_cache_t cache)794 cache_bucket_unload_alloc(uma_cache_t cache)
795 {
796 
797 	return (cache_bucket_unload(&cache->uc_allocbucket));
798 }
799 
800 static inline uma_bucket_t
cache_bucket_unload_free(uma_cache_t cache)801 cache_bucket_unload_free(uma_cache_t cache)
802 {
803 
804 	return (cache_bucket_unload(&cache->uc_freebucket));
805 }
806 
807 static inline uma_bucket_t
cache_bucket_unload_cross(uma_cache_t cache)808 cache_bucket_unload_cross(uma_cache_t cache)
809 {
810 
811 	return (cache_bucket_unload(&cache->uc_crossbucket));
812 }
813 
814 /*
815  * Load a bucket into a per-cpu cache bucket.
816  */
817 static inline void
cache_bucket_load(uma_cache_bucket_t bucket,uma_bucket_t b)818 cache_bucket_load(uma_cache_bucket_t bucket, uma_bucket_t b)
819 {
820 
821 	CRITICAL_ASSERT(curthread);
822 	MPASS(bucket->ucb_bucket == NULL);
823 	MPASS(b->ub_seq == SMR_SEQ_INVALID);
824 
825 	bucket->ucb_bucket = b;
826 	bucket->ucb_cnt = b->ub_cnt;
827 	bucket->ucb_entries = b->ub_entries;
828 }
829 
830 static inline void
cache_bucket_load_alloc(uma_cache_t cache,uma_bucket_t b)831 cache_bucket_load_alloc(uma_cache_t cache, uma_bucket_t b)
832 {
833 
834 	cache_bucket_load(&cache->uc_allocbucket, b);
835 }
836 
837 static inline void
cache_bucket_load_free(uma_cache_t cache,uma_bucket_t b)838 cache_bucket_load_free(uma_cache_t cache, uma_bucket_t b)
839 {
840 
841 	cache_bucket_load(&cache->uc_freebucket, b);
842 }
843 
844 #ifdef NUMA
845 static inline void
cache_bucket_load_cross(uma_cache_t cache,uma_bucket_t b)846 cache_bucket_load_cross(uma_cache_t cache, uma_bucket_t b)
847 {
848 
849 	cache_bucket_load(&cache->uc_crossbucket, b);
850 }
851 #endif
852 
853 /*
854  * Copy and preserve ucb_spare.
855  */
856 static inline void
cache_bucket_copy(uma_cache_bucket_t b1,uma_cache_bucket_t b2)857 cache_bucket_copy(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
858 {
859 
860 	b1->ucb_bucket = b2->ucb_bucket;
861 	b1->ucb_entries = b2->ucb_entries;
862 	b1->ucb_cnt = b2->ucb_cnt;
863 }
864 
865 /*
866  * Swap two cache buckets.
867  */
868 static inline void
cache_bucket_swap(uma_cache_bucket_t b1,uma_cache_bucket_t b2)869 cache_bucket_swap(uma_cache_bucket_t b1, uma_cache_bucket_t b2)
870 {
871 	struct uma_cache_bucket b3;
872 
873 	CRITICAL_ASSERT(curthread);
874 
875 	cache_bucket_copy(&b3, b1);
876 	cache_bucket_copy(b1, b2);
877 	cache_bucket_copy(b2, &b3);
878 }
879 
880 /*
881  * Attempt to fetch a bucket from a zone on behalf of the current cpu cache.
882  */
883 static uma_bucket_t
cache_fetch_bucket(uma_zone_t zone,uma_cache_t cache,int domain)884 cache_fetch_bucket(uma_zone_t zone, uma_cache_t cache, int domain)
885 {
886 	uma_zone_domain_t zdom;
887 	uma_bucket_t bucket;
888 
889 	/*
890 	 * Avoid the lock if possible.
891 	 */
892 	zdom = ZDOM_GET(zone, domain);
893 	if (zdom->uzd_nitems == 0)
894 		return (NULL);
895 
896 	if ((cache_uz_flags(cache) & UMA_ZONE_SMR) != 0 &&
897 	    !smr_poll(zone->uz_smr, zdom->uzd_seq, false))
898 		return (NULL);
899 
900 	/*
901 	 * Check the zone's cache of buckets.
902 	 */
903 	zdom = zone_domain_lock(zone, domain);
904 	if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL)
905 		return (bucket);
906 	ZDOM_UNLOCK(zdom);
907 
908 	return (NULL);
909 }
910 
911 static void
zone_log_warning(uma_zone_t zone)912 zone_log_warning(uma_zone_t zone)
913 {
914 	static const struct timeval warninterval = { 300, 0 };
915 
916 	if (!zone_warnings || zone->uz_warning == NULL)
917 		return;
918 
919 	if (ratecheck(&zone->uz_ratecheck, &warninterval))
920 		printf("[zone: %s] %s\n", zone->uz_name, zone->uz_warning);
921 }
922 
923 static inline void
zone_maxaction(uma_zone_t zone)924 zone_maxaction(uma_zone_t zone)
925 {
926 
927 	if (zone->uz_maxaction.ta_func != NULL)
928 		taskqueue_enqueue(taskqueue_thread, &zone->uz_maxaction);
929 }
930 
931 /*
932  * Routine called by timeout which is used to fire off some time interval
933  * based calculations.  (stats, hash size, etc.)
934  *
935  * Arguments:
936  *	arg   Unused
937  *
938  * Returns:
939  *	Nothing
940  */
941 static void
uma_timeout(void * unused)942 uma_timeout(void *unused)
943 {
944 	bucket_enable();
945 	zone_foreach(zone_timeout, NULL);
946 
947 	/* Reschedule this event */
948 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
949 }
950 
951 /*
952  * Update the working set size estimate for the zone's bucket cache.
953  * The constants chosen here are somewhat arbitrary.  With an update period of
954  * 20s (UMA_TIMEOUT), this estimate is dominated by zone activity over the
955  * last 100s.
956  */
957 static void
zone_domain_update_wss(uma_zone_domain_t zdom)958 zone_domain_update_wss(uma_zone_domain_t zdom)
959 {
960 	long wss;
961 
962 	ZDOM_LOCK(zdom);
963 	MPASS(zdom->uzd_imax >= zdom->uzd_imin);
964 	wss = zdom->uzd_imax - zdom->uzd_imin;
965 	zdom->uzd_imax = zdom->uzd_imin = zdom->uzd_nitems;
966 	zdom->uzd_wss = (4 * wss + zdom->uzd_wss) / 5;
967 	ZDOM_UNLOCK(zdom);
968 }
969 
970 /*
971  * Routine to perform timeout driven calculations.  This expands the
972  * hashes and does per cpu statistics aggregation.
973  *
974  *  Returns nothing.
975  */
976 static void
zone_timeout(uma_zone_t zone,void * unused)977 zone_timeout(uma_zone_t zone, void *unused)
978 {
979 	uma_keg_t keg;
980 	u_int slabs, pages;
981 
982 	if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
983 		goto update_wss;
984 
985 	keg = zone->uz_keg;
986 
987 	/*
988 	 * Hash zones are non-numa by definition so the first domain
989 	 * is the only one present.
990 	 */
991 	KEG_LOCK(keg, 0);
992 	pages = keg->uk_domain[0].ud_pages;
993 
994 	/*
995 	 * Expand the keg hash table.
996 	 *
997 	 * This is done if the number of slabs is larger than the hash size.
998 	 * What I'm trying to do here is completely reduce collisions.  This
999 	 * may be a little aggressive.  Should I allow for two collisions max?
1000 	 */
1001 	if ((slabs = pages / keg->uk_ppera) > keg->uk_hash.uh_hashsize) {
1002 		struct uma_hash newhash;
1003 		struct uma_hash oldhash;
1004 		int ret;
1005 
1006 		/*
1007 		 * This is so involved because allocating and freeing
1008 		 * while the keg lock is held will lead to deadlock.
1009 		 * I have to do everything in stages and check for
1010 		 * races.
1011 		 */
1012 		KEG_UNLOCK(keg, 0);
1013 		ret = hash_alloc(&newhash, 1 << fls(slabs));
1014 		KEG_LOCK(keg, 0);
1015 		if (ret) {
1016 			if (hash_expand(&keg->uk_hash, &newhash)) {
1017 				oldhash = keg->uk_hash;
1018 				keg->uk_hash = newhash;
1019 			} else
1020 				oldhash = newhash;
1021 
1022 			KEG_UNLOCK(keg, 0);
1023 			hash_free(&oldhash);
1024 			goto update_wss;
1025 		}
1026 	}
1027 	KEG_UNLOCK(keg, 0);
1028 
1029 update_wss:
1030 	for (int i = 0; i < vm_ndomains; i++)
1031 		zone_domain_update_wss(ZDOM_GET(zone, i));
1032 }
1033 
1034 /*
1035  * Allocate and zero fill the next sized hash table from the appropriate
1036  * backing store.
1037  *
1038  * Arguments:
1039  *	hash  A new hash structure with the old hash size in uh_hashsize
1040  *
1041  * Returns:
1042  *	1 on success and 0 on failure.
1043  */
1044 static int
hash_alloc(struct uma_hash * hash,u_int size)1045 hash_alloc(struct uma_hash *hash, u_int size)
1046 {
1047 	size_t alloc;
1048 
1049 	KASSERT(powerof2(size), ("hash size must be power of 2"));
1050 	if (size > UMA_HASH_SIZE_INIT)  {
1051 		hash->uh_hashsize = size;
1052 		alloc = sizeof(hash->uh_slab_hash[0]) * hash->uh_hashsize;
1053 		hash->uh_slab_hash = malloc(alloc, M_UMAHASH, M_NOWAIT);
1054 	} else {
1055 		alloc = sizeof(hash->uh_slab_hash[0]) * UMA_HASH_SIZE_INIT;
1056 		hash->uh_slab_hash = zone_alloc_item(hashzone, NULL,
1057 		    UMA_ANYDOMAIN, M_WAITOK);
1058 		hash->uh_hashsize = UMA_HASH_SIZE_INIT;
1059 	}
1060 	if (hash->uh_slab_hash) {
1061 		bzero(hash->uh_slab_hash, alloc);
1062 		hash->uh_hashmask = hash->uh_hashsize - 1;
1063 		return (1);
1064 	}
1065 
1066 	return (0);
1067 }
1068 
1069 /*
1070  * Expands the hash table for HASH zones.  This is done from zone_timeout
1071  * to reduce collisions.  This must not be done in the regular allocation
1072  * path, otherwise, we can recurse on the vm while allocating pages.
1073  *
1074  * Arguments:
1075  *	oldhash  The hash you want to expand
1076  *	newhash  The hash structure for the new table
1077  *
1078  * Returns:
1079  *	Nothing
1080  *
1081  * Discussion:
1082  */
1083 static int
hash_expand(struct uma_hash * oldhash,struct uma_hash * newhash)1084 hash_expand(struct uma_hash *oldhash, struct uma_hash *newhash)
1085 {
1086 	uma_hash_slab_t slab;
1087 	u_int hval;
1088 	u_int idx;
1089 
1090 	if (!newhash->uh_slab_hash)
1091 		return (0);
1092 
1093 	if (oldhash->uh_hashsize >= newhash->uh_hashsize)
1094 		return (0);
1095 
1096 	/*
1097 	 * I need to investigate hash algorithms for resizing without a
1098 	 * full rehash.
1099 	 */
1100 
1101 	for (idx = 0; idx < oldhash->uh_hashsize; idx++)
1102 		while (!LIST_EMPTY(&oldhash->uh_slab_hash[idx])) {
1103 			slab = LIST_FIRST(&oldhash->uh_slab_hash[idx]);
1104 			LIST_REMOVE(slab, uhs_hlink);
1105 			hval = UMA_HASH(newhash, slab->uhs_data);
1106 			LIST_INSERT_HEAD(&newhash->uh_slab_hash[hval],
1107 			    slab, uhs_hlink);
1108 		}
1109 
1110 	return (1);
1111 }
1112 
1113 /*
1114  * Free the hash bucket to the appropriate backing store.
1115  *
1116  * Arguments:
1117  *	slab_hash  The hash bucket we're freeing
1118  *	hashsize   The number of entries in that hash bucket
1119  *
1120  * Returns:
1121  *	Nothing
1122  */
1123 static void
hash_free(struct uma_hash * hash)1124 hash_free(struct uma_hash *hash)
1125 {
1126 	if (hash->uh_slab_hash == NULL)
1127 		return;
1128 	if (hash->uh_hashsize == UMA_HASH_SIZE_INIT)
1129 		zone_free_item(hashzone, hash->uh_slab_hash, NULL, SKIP_NONE);
1130 	else
1131 		free(hash->uh_slab_hash, M_UMAHASH);
1132 }
1133 
1134 /*
1135  * Frees all outstanding items in a bucket
1136  *
1137  * Arguments:
1138  *	zone   The zone to free to, must be unlocked.
1139  *	bucket The free/alloc bucket with items.
1140  *
1141  * Returns:
1142  *	Nothing
1143  */
1144 static void
bucket_drain(uma_zone_t zone,uma_bucket_t bucket)1145 bucket_drain(uma_zone_t zone, uma_bucket_t bucket)
1146 {
1147 	int i;
1148 
1149 	if (bucket->ub_cnt == 0)
1150 		return;
1151 
1152 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 &&
1153 	    bucket->ub_seq != SMR_SEQ_INVALID) {
1154 		smr_wait(zone->uz_smr, bucket->ub_seq);
1155 		bucket->ub_seq = SMR_SEQ_INVALID;
1156 		for (i = 0; i < bucket->ub_cnt; i++)
1157 			item_dtor(zone, bucket->ub_bucket[i],
1158 			    zone->uz_size, NULL, SKIP_NONE);
1159 	}
1160 	if (zone->uz_fini)
1161 		for (i = 0; i < bucket->ub_cnt; i++)
1162 			zone->uz_fini(bucket->ub_bucket[i], zone->uz_size);
1163 	zone->uz_release(zone->uz_arg, bucket->ub_bucket, bucket->ub_cnt);
1164 	if (zone->uz_max_items > 0)
1165 		zone_free_limit(zone, bucket->ub_cnt);
1166 #ifdef INVARIANTS
1167 	bzero(bucket->ub_bucket, sizeof(void *) * bucket->ub_cnt);
1168 #endif
1169 	bucket->ub_cnt = 0;
1170 }
1171 
1172 /*
1173  * Drains the per cpu caches for a zone.
1174  *
1175  * NOTE: This may only be called while the zone is being torn down, and not
1176  * during normal operation.  This is necessary in order that we do not have
1177  * to migrate CPUs to drain the per-CPU caches.
1178  *
1179  * Arguments:
1180  *	zone     The zone to drain, must be unlocked.
1181  *
1182  * Returns:
1183  *	Nothing
1184  */
1185 static void
cache_drain(uma_zone_t zone)1186 cache_drain(uma_zone_t zone)
1187 {
1188 	uma_cache_t cache;
1189 	uma_bucket_t bucket;
1190 	smr_seq_t seq;
1191 	int cpu;
1192 
1193 	/*
1194 	 * XXX: It is safe to not lock the per-CPU caches, because we're
1195 	 * tearing down the zone anyway.  I.e., there will be no further use
1196 	 * of the caches at this point.
1197 	 *
1198 	 * XXX: It would good to be able to assert that the zone is being
1199 	 * torn down to prevent improper use of cache_drain().
1200 	 */
1201 	seq = SMR_SEQ_INVALID;
1202 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
1203 		seq = smr_advance(zone->uz_smr);
1204 	CPU_FOREACH(cpu) {
1205 		cache = &zone->uz_cpu[cpu];
1206 		bucket = cache_bucket_unload_alloc(cache);
1207 		if (bucket != NULL)
1208 			bucket_free(zone, bucket, NULL);
1209 		bucket = cache_bucket_unload_free(cache);
1210 		if (bucket != NULL) {
1211 			bucket->ub_seq = seq;
1212 			bucket_free(zone, bucket, NULL);
1213 		}
1214 		bucket = cache_bucket_unload_cross(cache);
1215 		if (bucket != NULL) {
1216 			bucket->ub_seq = seq;
1217 			bucket_free(zone, bucket, NULL);
1218 		}
1219 	}
1220 	bucket_cache_reclaim(zone, true);
1221 }
1222 
1223 static void
cache_shrink(uma_zone_t zone,void * unused)1224 cache_shrink(uma_zone_t zone, void *unused)
1225 {
1226 
1227 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1228 		return;
1229 
1230 	zone->uz_bucket_size =
1231 	    (zone->uz_bucket_size_min + zone->uz_bucket_size) / 2;
1232 }
1233 
1234 static void
cache_drain_safe_cpu(uma_zone_t zone,void * unused)1235 cache_drain_safe_cpu(uma_zone_t zone, void *unused)
1236 {
1237 	uma_cache_t cache;
1238 	uma_bucket_t b1, b2, b3;
1239 	int domain;
1240 
1241 	if (zone->uz_flags & UMA_ZFLAG_INTERNAL)
1242 		return;
1243 
1244 	b1 = b2 = b3 = NULL;
1245 	critical_enter();
1246 	cache = &zone->uz_cpu[curcpu];
1247 	domain = PCPU_GET(domain);
1248 	b1 = cache_bucket_unload_alloc(cache);
1249 
1250 	/*
1251 	 * Don't flush SMR zone buckets.  This leaves the zone without a
1252 	 * bucket and forces every free to synchronize().
1253 	 */
1254 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0) {
1255 		b2 = cache_bucket_unload_free(cache);
1256 		b3 = cache_bucket_unload_cross(cache);
1257 	}
1258 	critical_exit();
1259 
1260 	if (b1 != NULL)
1261 		zone_free_bucket(zone, b1, NULL, domain, false);
1262 	if (b2 != NULL)
1263 		zone_free_bucket(zone, b2, NULL, domain, false);
1264 	if (b3 != NULL) {
1265 		/* Adjust the domain so it goes to zone_free_cross. */
1266 		domain = (domain + 1) % vm_ndomains;
1267 		zone_free_bucket(zone, b3, NULL, domain, false);
1268 	}
1269 }
1270 
1271 /*
1272  * Safely drain per-CPU caches of a zone(s) to alloc bucket.
1273  * This is an expensive call because it needs to bind to all CPUs
1274  * one by one and enter a critical section on each of them in order
1275  * to safely access their cache buckets.
1276  * Zone lock must not be held on call this function.
1277  */
1278 static void
pcpu_cache_drain_safe(uma_zone_t zone)1279 pcpu_cache_drain_safe(uma_zone_t zone)
1280 {
1281 	int cpu;
1282 
1283 	/*
1284 	 * Polite bucket sizes shrinking was not enough, shrink aggressively.
1285 	 */
1286 	if (zone)
1287 		cache_shrink(zone, NULL);
1288 	else
1289 		zone_foreach(cache_shrink, NULL);
1290 
1291 	CPU_FOREACH(cpu) {
1292 		thread_lock(curthread);
1293 		sched_bind(curthread, cpu);
1294 		thread_unlock(curthread);
1295 
1296 		if (zone)
1297 			cache_drain_safe_cpu(zone, NULL);
1298 		else
1299 			zone_foreach(cache_drain_safe_cpu, NULL);
1300 	}
1301 	thread_lock(curthread);
1302 	sched_unbind(curthread);
1303 	thread_unlock(curthread);
1304 }
1305 
1306 /*
1307  * Reclaim cached buckets from a zone.  All buckets are reclaimed if the caller
1308  * requested a drain, otherwise the per-domain caches are trimmed to either
1309  * estimated working set size.
1310  */
1311 static void
bucket_cache_reclaim(uma_zone_t zone,bool drain)1312 bucket_cache_reclaim(uma_zone_t zone, bool drain)
1313 {
1314 	uma_zone_domain_t zdom;
1315 	uma_bucket_t bucket;
1316 	long target;
1317 	int i;
1318 
1319 	/*
1320 	 * Shrink the zone bucket size to ensure that the per-CPU caches
1321 	 * don't grow too large.
1322 	 */
1323 	if (zone->uz_bucket_size > zone->uz_bucket_size_min)
1324 		zone->uz_bucket_size--;
1325 
1326 	for (i = 0; i < vm_ndomains; i++) {
1327 		/*
1328 		 * The cross bucket is partially filled and not part of
1329 		 * the item count.  Reclaim it individually here.
1330 		 */
1331 		zdom = ZDOM_GET(zone, i);
1332 		if ((zone->uz_flags & UMA_ZONE_SMR) == 0 || drain) {
1333 			ZONE_CROSS_LOCK(zone);
1334 			bucket = zdom->uzd_cross;
1335 			zdom->uzd_cross = NULL;
1336 			ZONE_CROSS_UNLOCK(zone);
1337 			if (bucket != NULL)
1338 				bucket_free(zone, bucket, NULL);
1339 		}
1340 
1341 		/*
1342 		 * If we were asked to drain the zone, we are done only once
1343 		 * this bucket cache is empty.  Otherwise, we reclaim items in
1344 		 * excess of the zone's estimated working set size.  If the
1345 		 * difference nitems - imin is larger than the WSS estimate,
1346 		 * then the estimate will grow at the end of this interval and
1347 		 * we ignore the historical average.
1348 		 */
1349 		ZDOM_LOCK(zdom);
1350 		target = drain ? 0 : lmax(zdom->uzd_wss, zdom->uzd_nitems -
1351 		    zdom->uzd_imin);
1352 		while (zdom->uzd_nitems > target) {
1353 			bucket = zone_fetch_bucket(zone, zdom, true);
1354 			if (bucket == NULL)
1355 				break;
1356 			bucket_free(zone, bucket, NULL);
1357 			ZDOM_LOCK(zdom);
1358 		}
1359 		ZDOM_UNLOCK(zdom);
1360 	}
1361 }
1362 
1363 static void
keg_free_slab(uma_keg_t keg,uma_slab_t slab,int start)1364 keg_free_slab(uma_keg_t keg, uma_slab_t slab, int start)
1365 {
1366 	uint8_t *mem;
1367 	int i;
1368 	uint8_t flags;
1369 
1370 	CTR4(KTR_UMA, "keg_free_slab keg %s(%p) slab %p, returning %d bytes",
1371 	    keg->uk_name, keg, slab, PAGE_SIZE * keg->uk_ppera);
1372 
1373 	mem = slab_data(slab, keg);
1374 	flags = slab->us_flags;
1375 	i = start;
1376 	if (keg->uk_fini != NULL) {
1377 		for (i--; i > -1; i--)
1378 #ifdef INVARIANTS
1379 		/*
1380 		 * trash_fini implies that dtor was trash_dtor. trash_fini
1381 		 * would check that memory hasn't been modified since free,
1382 		 * which executed trash_dtor.
1383 		 * That's why we need to run uma_dbg_kskip() check here,
1384 		 * albeit we don't make skip check for other init/fini
1385 		 * invocations.
1386 		 */
1387 		if (!uma_dbg_kskip(keg, slab_item(slab, keg, i)) ||
1388 		    keg->uk_fini != trash_fini)
1389 #endif
1390 			keg->uk_fini(slab_item(slab, keg, i), keg->uk_size);
1391 	}
1392 	if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1393 		zone_free_item(slabzone(keg->uk_ipers), slab_tohashslab(slab),
1394 		    NULL, SKIP_NONE);
1395 	keg->uk_freef(mem, PAGE_SIZE * keg->uk_ppera, flags);
1396 	uma_total_dec(PAGE_SIZE * keg->uk_ppera);
1397 }
1398 
1399 static void
keg_drain_domain(uma_keg_t keg,int domain)1400 keg_drain_domain(uma_keg_t keg, int domain)
1401 {
1402 	struct slabhead freeslabs;
1403 	uma_domain_t dom;
1404 	uma_slab_t slab, tmp;
1405 	uint32_t i, stofree, stokeep, partial;
1406 
1407 	dom = &keg->uk_domain[domain];
1408 	LIST_INIT(&freeslabs);
1409 
1410 	CTR4(KTR_UMA, "keg_drain %s(%p) domain %d free items: %u",
1411 	    keg->uk_name, keg, domain, dom->ud_free_items);
1412 
1413 	KEG_LOCK(keg, domain);
1414 
1415 	/*
1416 	 * Are the free items in partially allocated slabs sufficient to meet
1417 	 * the reserve? If not, compute the number of fully free slabs that must
1418 	 * be kept.
1419 	 */
1420 	partial = dom->ud_free_items - dom->ud_free_slabs * keg->uk_ipers;
1421 	if (partial < keg->uk_reserve) {
1422 		stokeep = min(dom->ud_free_slabs,
1423 		    howmany(keg->uk_reserve - partial, keg->uk_ipers));
1424 	} else {
1425 		stokeep = 0;
1426 	}
1427 	stofree = dom->ud_free_slabs - stokeep;
1428 
1429 	/*
1430 	 * Partition the free slabs into two sets: those that must be kept in
1431 	 * order to maintain the reserve, and those that may be released back to
1432 	 * the system.  Since one set may be much larger than the other,
1433 	 * populate the smaller of the two sets and swap them if necessary.
1434 	 */
1435 	for (i = min(stofree, stokeep); i > 0; i--) {
1436 		slab = LIST_FIRST(&dom->ud_free_slab);
1437 		LIST_REMOVE(slab, us_link);
1438 		LIST_INSERT_HEAD(&freeslabs, slab, us_link);
1439 	}
1440 	if (stofree > stokeep)
1441 		LIST_SWAP(&freeslabs, &dom->ud_free_slab, uma_slab, us_link);
1442 
1443 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0) {
1444 		LIST_FOREACH(slab, &freeslabs, us_link)
1445 			UMA_HASH_REMOVE(&keg->uk_hash, slab);
1446 	}
1447 	dom->ud_free_items -= stofree * keg->uk_ipers;
1448 	dom->ud_free_slabs -= stofree;
1449 	dom->ud_pages -= stofree * keg->uk_ppera;
1450 	KEG_UNLOCK(keg, domain);
1451 
1452 	LIST_FOREACH_SAFE(slab, &freeslabs, us_link, tmp)
1453 		keg_free_slab(keg, slab, keg->uk_ipers);
1454 }
1455 
1456 /*
1457  * Frees pages from a keg back to the system.  This is done on demand from
1458  * the pageout daemon.
1459  *
1460  * Returns nothing.
1461  */
1462 static void
keg_drain(uma_keg_t keg)1463 keg_drain(uma_keg_t keg)
1464 {
1465 	int i;
1466 
1467 	if ((keg->uk_flags & UMA_ZONE_NOFREE) != 0)
1468 		return;
1469 	for (i = 0; i < vm_ndomains; i++)
1470 		keg_drain_domain(keg, i);
1471 }
1472 
1473 static void
zone_reclaim(uma_zone_t zone,int waitok,bool drain)1474 zone_reclaim(uma_zone_t zone, int waitok, bool drain)
1475 {
1476 
1477 	/*
1478 	 * Set draining to interlock with zone_dtor() so we can release our
1479 	 * locks as we go.  Only dtor() should do a WAITOK call since it
1480 	 * is the only call that knows the structure will still be available
1481 	 * when it wakes up.
1482 	 */
1483 	ZONE_LOCK(zone);
1484 	while (zone->uz_flags & UMA_ZFLAG_RECLAIMING) {
1485 		if (waitok == M_NOWAIT)
1486 			goto out;
1487 		msleep(zone, &ZDOM_GET(zone, 0)->uzd_lock, PVM, "zonedrain",
1488 		    1);
1489 	}
1490 	zone->uz_flags |= UMA_ZFLAG_RECLAIMING;
1491 	ZONE_UNLOCK(zone);
1492 	bucket_cache_reclaim(zone, drain);
1493 
1494 	/*
1495 	 * The DRAINING flag protects us from being freed while
1496 	 * we're running.  Normally the uma_rwlock would protect us but we
1497 	 * must be able to release and acquire the right lock for each keg.
1498 	 */
1499 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0)
1500 		keg_drain(zone->uz_keg);
1501 	ZONE_LOCK(zone);
1502 	zone->uz_flags &= ~UMA_ZFLAG_RECLAIMING;
1503 	wakeup(zone);
1504 out:
1505 	ZONE_UNLOCK(zone);
1506 }
1507 
1508 static void
zone_drain(uma_zone_t zone,void * unused)1509 zone_drain(uma_zone_t zone, void *unused)
1510 {
1511 
1512 	zone_reclaim(zone, M_NOWAIT, true);
1513 }
1514 
1515 static void
zone_trim(uma_zone_t zone,void * unused)1516 zone_trim(uma_zone_t zone, void *unused)
1517 {
1518 
1519 	zone_reclaim(zone, M_NOWAIT, false);
1520 }
1521 
1522 /*
1523  * Allocate a new slab for a keg and inserts it into the partial slab list.
1524  * The keg should be unlocked on entry.  If the allocation succeeds it will
1525  * be locked on return.
1526  *
1527  * Arguments:
1528  *	flags   Wait flags for the item initialization routine
1529  *	aflags  Wait flags for the slab allocation
1530  *
1531  * Returns:
1532  *	The slab that was allocated or NULL if there is no memory and the
1533  *	caller specified M_NOWAIT.
1534  */
1535 static uma_slab_t
keg_alloc_slab(uma_keg_t keg,uma_zone_t zone,int domain,int flags,int aflags)1536 keg_alloc_slab(uma_keg_t keg, uma_zone_t zone, int domain, int flags,
1537     int aflags)
1538 {
1539 	uma_domain_t dom;
1540 	uma_alloc allocf;
1541 	uma_slab_t slab;
1542 	unsigned long size;
1543 	uint8_t *mem;
1544 	uint8_t sflags;
1545 	int i;
1546 
1547 	KASSERT(domain >= 0 && domain < vm_ndomains,
1548 	    ("keg_alloc_slab: domain %d out of range", domain));
1549 
1550 	allocf = keg->uk_allocf;
1551 	slab = NULL;
1552 	mem = NULL;
1553 	if (keg->uk_flags & UMA_ZFLAG_OFFPAGE) {
1554 		uma_hash_slab_t hslab;
1555 		hslab = zone_alloc_item(slabzone(keg->uk_ipers), NULL,
1556 		    domain, aflags);
1557 		if (hslab == NULL)
1558 			goto fail;
1559 		slab = &hslab->uhs_slab;
1560 	}
1561 
1562 	/*
1563 	 * This reproduces the old vm_zone behavior of zero filling pages the
1564 	 * first time they are added to a zone.
1565 	 *
1566 	 * Malloced items are zeroed in uma_zalloc.
1567 	 */
1568 
1569 	if ((keg->uk_flags & UMA_ZONE_MALLOC) == 0)
1570 		aflags |= M_ZERO;
1571 	else
1572 		aflags &= ~M_ZERO;
1573 
1574 	if (keg->uk_flags & UMA_ZONE_NODUMP)
1575 		aflags |= M_NODUMP;
1576 
1577 	/* zone is passed for legacy reasons. */
1578 	size = keg->uk_ppera * PAGE_SIZE;
1579 	mem = allocf(zone, size, domain, &sflags, aflags);
1580 	if (mem == NULL) {
1581 		if (keg->uk_flags & UMA_ZFLAG_OFFPAGE)
1582 			zone_free_item(slabzone(keg->uk_ipers),
1583 			    slab_tohashslab(slab), NULL, SKIP_NONE);
1584 		goto fail;
1585 	}
1586 	uma_total_inc(size);
1587 
1588 	/* For HASH zones all pages go to the same uma_domain. */
1589 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
1590 		domain = 0;
1591 
1592 	/* Point the slab into the allocated memory */
1593 	if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE))
1594 		slab = (uma_slab_t )(mem + keg->uk_pgoff);
1595 	else
1596 		slab_tohashslab(slab)->uhs_data = mem;
1597 
1598 	if (keg->uk_flags & UMA_ZFLAG_VTOSLAB)
1599 		for (i = 0; i < keg->uk_ppera; i++)
1600 			vsetzoneslab((vm_offset_t)mem + (i * PAGE_SIZE),
1601 			    zone, slab);
1602 
1603 	slab->us_freecount = keg->uk_ipers;
1604 	slab->us_flags = sflags;
1605 	slab->us_domain = domain;
1606 
1607 	BIT_FILL(keg->uk_ipers, &slab->us_free);
1608 #ifdef INVARIANTS
1609 	BIT_ZERO(keg->uk_ipers, slab_dbg_bits(slab, keg));
1610 #endif
1611 
1612 	if (keg->uk_init != NULL) {
1613 		for (i = 0; i < keg->uk_ipers; i++)
1614 			if (keg->uk_init(slab_item(slab, keg, i),
1615 			    keg->uk_size, flags) != 0)
1616 				break;
1617 		if (i != keg->uk_ipers) {
1618 			keg_free_slab(keg, slab, i);
1619 			goto fail;
1620 		}
1621 	}
1622 	KEG_LOCK(keg, domain);
1623 
1624 	CTR3(KTR_UMA, "keg_alloc_slab: allocated slab %p for %s(%p)",
1625 	    slab, keg->uk_name, keg);
1626 
1627 	if (keg->uk_flags & UMA_ZFLAG_HASH)
1628 		UMA_HASH_INSERT(&keg->uk_hash, slab, mem);
1629 
1630 	/*
1631 	 * If we got a slab here it's safe to mark it partially used
1632 	 * and return.  We assume that the caller is going to remove
1633 	 * at least one item.
1634 	 */
1635 	dom = &keg->uk_domain[domain];
1636 	LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
1637 	dom->ud_pages += keg->uk_ppera;
1638 	dom->ud_free_items += keg->uk_ipers;
1639 
1640 	return (slab);
1641 
1642 fail:
1643 	return (NULL);
1644 }
1645 
1646 #ifndef FSTACK
1647 /*
1648  * This function is intended to be used early on in place of page_alloc() so
1649  * that we may use the boot time page cache to satisfy allocations before
1650  * the VM is ready.
1651  */
1652 static void *
startup_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1653 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1654     int wait)
1655 {
1656 	vm_paddr_t pa;
1657 	vm_page_t m;
1658 	void *mem;
1659 	int pages;
1660 	int i;
1661 
1662 	pages = howmany(bytes, PAGE_SIZE);
1663 	KASSERT(pages > 0, ("%s can't reserve 0 pages", __func__));
1664 
1665 	*pflag = UMA_SLAB_BOOT;
1666 	m = vm_page_alloc_contig_domain(NULL, 0, domain,
1667 	    malloc2vm_flags(wait) | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED, pages,
1668 	    (vm_paddr_t)0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT);
1669 	if (m == NULL)
1670 		return (NULL);
1671 
1672 	pa = VM_PAGE_TO_PHYS(m);
1673 	for (i = 0; i < pages; i++, pa += PAGE_SIZE) {
1674 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1675     defined(__riscv) || defined(__powerpc64__)
1676 		if ((wait & M_NODUMP) == 0)
1677 			dump_add_page(pa);
1678 #endif
1679 	}
1680 	/* Allocate KVA and indirectly advance bootmem. */
1681 	mem = (void *)pmap_map(&bootmem, m->phys_addr,
1682 	    m->phys_addr + (pages * PAGE_SIZE), VM_PROT_READ | VM_PROT_WRITE);
1683         if ((wait & M_ZERO) != 0)
1684                 bzero(mem, pages * PAGE_SIZE);
1685 
1686         return (mem);
1687 }
1688 
1689 static void
startup_free(void * mem,vm_size_t bytes)1690 startup_free(void *mem, vm_size_t bytes)
1691 {
1692 	vm_offset_t va;
1693 	vm_page_t m;
1694 
1695 	va = (vm_offset_t)mem;
1696 	m = PHYS_TO_VM_PAGE(pmap_kextract(va));
1697 
1698 	/*
1699 	 * startup_alloc() returns direct-mapped slabs on some platforms.  Avoid
1700 	 * unmapping ranges of the direct map.
1701 	 */
1702 	if (va >= bootstart && va + bytes <= bootmem)
1703 		pmap_remove(kernel_pmap, va, va + bytes);
1704 	for (; bytes != 0; bytes -= PAGE_SIZE, m++) {
1705 #if defined(__aarch64__) || defined(__amd64__) || defined(__mips__) || \
1706     defined(__riscv) || defined(__powerpc64__)
1707 		dump_drop_page(VM_PAGE_TO_PHYS(m));
1708 #endif
1709 		vm_page_unwire_noq(m);
1710 		vm_page_free(m);
1711 	}
1712 }
1713 #endif
1714 
1715 /*
1716  * Allocates a number of pages from the system
1717  *
1718  * Arguments:
1719  *	bytes  The number of bytes requested
1720  *	wait  Shall we wait?
1721  *
1722  * Returns:
1723  *	A pointer to the alloced memory or possibly
1724  *	NULL if M_NOWAIT is set.
1725  */
1726 static void *
page_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1727 page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1728     int wait)
1729 {
1730 	void *p;	/* Returned page */
1731 
1732 	*pflag = UMA_SLAB_KERNEL;
1733 	p = (void *)kmem_malloc_domainset(DOMAINSET_FIXED(domain), bytes, wait);
1734 
1735 	return (p);
1736 }
1737 
1738 #ifndef FSTACK
1739 static void *
pcpu_page_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1740 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1741     int wait)
1742 {
1743 	struct pglist alloctail;
1744 	vm_offset_t addr, zkva;
1745 	int cpu, flags;
1746 	vm_page_t p, p_next;
1747 #ifdef NUMA
1748 	struct pcpu *pc;
1749 #endif
1750 
1751 	MPASS(bytes == (mp_maxid + 1) * PAGE_SIZE);
1752 
1753 	TAILQ_INIT(&alloctail);
1754 	flags = VM_ALLOC_SYSTEM | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1755 	    malloc2vm_flags(wait);
1756 	*pflag = UMA_SLAB_KERNEL;
1757 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
1758 		if (CPU_ABSENT(cpu)) {
1759 			p = vm_page_alloc(NULL, 0, flags);
1760 		} else {
1761 #ifndef NUMA
1762 			p = vm_page_alloc(NULL, 0, flags);
1763 #else
1764 			pc = pcpu_find(cpu);
1765 			if (__predict_false(VM_DOMAIN_EMPTY(pc->pc_domain)))
1766 				p = NULL;
1767 			else
1768 				p = vm_page_alloc_domain(NULL, 0,
1769 				    pc->pc_domain, flags);
1770 			if (__predict_false(p == NULL))
1771 				p = vm_page_alloc(NULL, 0, flags);
1772 #endif
1773 		}
1774 		if (__predict_false(p == NULL))
1775 			goto fail;
1776 		TAILQ_INSERT_TAIL(&alloctail, p, listq);
1777 	}
1778 	if ((addr = kva_alloc(bytes)) == 0)
1779 		goto fail;
1780 	zkva = addr;
1781 	TAILQ_FOREACH(p, &alloctail, listq) {
1782 		pmap_qenter(zkva, &p, 1);
1783 		zkva += PAGE_SIZE;
1784 	}
1785 	return ((void*)addr);
1786 fail:
1787 	TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1788 		vm_page_unwire_noq(p);
1789 		vm_page_free(p);
1790 	}
1791 	return (NULL);
1792 }
1793 
1794 /*
1795  * Allocates a number of pages from within an object
1796  *
1797  * Arguments:
1798  *	bytes  The number of bytes requested
1799  *	wait   Shall we wait?
1800  *
1801  * Returns:
1802  *	A pointer to the alloced memory or possibly
1803  *	NULL if M_NOWAIT is set.
1804  */
1805 static void *
noobj_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * flags,int wait)1806 noobj_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
1807     int wait)
1808 {
1809 	TAILQ_HEAD(, vm_page) alloctail;
1810 	u_long npages;
1811 	vm_offset_t retkva, zkva;
1812 	vm_page_t p, p_next;
1813 	uma_keg_t keg;
1814 
1815 	TAILQ_INIT(&alloctail);
1816 	keg = zone->uz_keg;
1817 
1818 	npages = howmany(bytes, PAGE_SIZE);
1819 	while (npages > 0) {
1820 		p = vm_page_alloc_domain(NULL, 0, domain, VM_ALLOC_INTERRUPT |
1821 		    VM_ALLOC_WIRED | VM_ALLOC_NOOBJ |
1822 		    ((wait & M_WAITOK) != 0 ? VM_ALLOC_WAITOK :
1823 		    VM_ALLOC_NOWAIT));
1824 		if (p != NULL) {
1825 			/*
1826 			 * Since the page does not belong to an object, its
1827 			 * listq is unused.
1828 			 */
1829 			TAILQ_INSERT_TAIL(&alloctail, p, listq);
1830 			npages--;
1831 			continue;
1832 		}
1833 		/*
1834 		 * Page allocation failed, free intermediate pages and
1835 		 * exit.
1836 		 */
1837 		TAILQ_FOREACH_SAFE(p, &alloctail, listq, p_next) {
1838 			vm_page_unwire_noq(p);
1839 			vm_page_free(p);
1840 		}
1841 		return (NULL);
1842 	}
1843 	*flags = UMA_SLAB_PRIV;
1844 	zkva = keg->uk_kva +
1845 	    atomic_fetchadd_long(&keg->uk_offset, round_page(bytes));
1846 	retkva = zkva;
1847 	TAILQ_FOREACH(p, &alloctail, listq) {
1848 		pmap_qenter(zkva, &p, 1);
1849 		zkva += PAGE_SIZE;
1850 	}
1851 
1852 	return ((void *)retkva);
1853 }
1854 
1855 /*
1856  * Allocate physically contiguous pages.
1857  */
1858 static void *
contig_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1859 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1860     int wait)
1861 {
1862 
1863 	*pflag = UMA_SLAB_KERNEL;
1864 	return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
1865 	    bytes, wait, 0, ~(vm_paddr_t)0, 1, 0, VM_MEMATTR_DEFAULT));
1866 }
1867 #else
1868 static void *
pcpu_page_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1869 pcpu_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1870     int wait)
1871 {
1872 	*pflag = UMA_SLAB_KERNEL;
1873 	return page_alloc(zone, bytes, domain, pflag, wait);
1874 }
1875 
1876 static void *
contig_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1877 contig_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1878     int wait)
1879 {
1880 
1881 	*pflag = UMA_SLAB_KERNEL;
1882 	return page_alloc(zone, bytes, domain, pflag, wait);
1883 }
1884 
1885 static void *
startup_alloc(uma_zone_t zone,vm_size_t bytes,int domain,uint8_t * pflag,int wait)1886 startup_alloc(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *pflag,
1887     int wait)
1888 {
1889 	*pflag = UMA_SLAB_BOOT;
1890 	return page_alloc(zone, bytes, domain, pflag, wait);
1891 }
1892 
1893 static void
startup_free(void * mem,vm_size_t bytes)1894 startup_free(void *mem, vm_size_t bytes)
1895 {
1896 	kmem_free((vm_offset_t)mem, bytes);
1897 }
1898 
1899 #endif
1900 
1901 /*
1902  * Frees a number of pages to the system
1903  *
1904  * Arguments:
1905  *	mem   A pointer to the memory to be freed
1906  *	size  The size of the memory being freed
1907  *	flags The original p->us_flags field
1908  *
1909  * Returns:
1910  *	Nothing
1911  */
1912 static void
page_free(void * mem,vm_size_t size,uint8_t flags)1913 page_free(void *mem, vm_size_t size, uint8_t flags)
1914 {
1915 
1916 	if ((flags & UMA_SLAB_BOOT) != 0) {
1917 		startup_free(mem, size);
1918 		return;
1919 	}
1920 
1921 	KASSERT((flags & UMA_SLAB_KERNEL) != 0,
1922 	    ("UMA: page_free used with invalid flags %x", flags));
1923 
1924 	kmem_free((vm_offset_t)mem, size);
1925 }
1926 
1927 #ifndef FSTACK
1928 /*
1929  * Frees pcpu zone allocations
1930  *
1931  * Arguments:
1932  *	mem   A pointer to the memory to be freed
1933  *	size  The size of the memory being freed
1934  *	flags The original p->us_flags field
1935  *
1936  * Returns:
1937  *	Nothing
1938  */
1939 static void
pcpu_page_free(void * mem,vm_size_t size,uint8_t flags)1940 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1941 {
1942 	vm_offset_t sva, curva;
1943 	vm_paddr_t paddr;
1944 	vm_page_t m;
1945 
1946 	MPASS(size == (mp_maxid+1)*PAGE_SIZE);
1947 
1948 	if ((flags & UMA_SLAB_BOOT) != 0) {
1949 		startup_free(mem, size);
1950 		return;
1951 	}
1952 
1953 	sva = (vm_offset_t)mem;
1954 	for (curva = sva; curva < sva + size; curva += PAGE_SIZE) {
1955 		paddr = pmap_kextract(curva);
1956 		m = PHYS_TO_VM_PAGE(paddr);
1957 		vm_page_unwire_noq(m);
1958 		vm_page_free(m);
1959 	}
1960 	pmap_qremove(sva, size >> PAGE_SHIFT);
1961 	kva_free(sva, size);
1962 }
1963 #else
1964 static void
pcpu_page_free(void * mem,vm_size_t size,uint8_t flags)1965 pcpu_page_free(void *mem, vm_size_t size, uint8_t flags)
1966 {
1967 	page_free(mem, size, flags);
1968 }
1969 #endif
1970 
1971 /*
1972  * Zero fill initializer
1973  *
1974  * Arguments/Returns follow uma_init specifications
1975  */
1976 static int
zero_init(void * mem,int size,int flags)1977 zero_init(void *mem, int size, int flags)
1978 {
1979 	bzero(mem, size);
1980 	return (0);
1981 }
1982 
1983 #ifdef INVARIANTS
1984 static struct noslabbits *
slab_dbg_bits(uma_slab_t slab,uma_keg_t keg)1985 slab_dbg_bits(uma_slab_t slab, uma_keg_t keg)
1986 {
1987 
1988 	return ((void *)((char *)&slab->us_free + BITSET_SIZE(keg->uk_ipers)));
1989 }
1990 #endif
1991 
1992 /*
1993  * Actual size of embedded struct slab (!OFFPAGE).
1994  */
1995 static size_t
slab_sizeof(int nitems)1996 slab_sizeof(int nitems)
1997 {
1998 	size_t s;
1999 
2000 	s = sizeof(struct uma_slab) + BITSET_SIZE(nitems) * SLAB_BITSETS;
2001 	return (roundup(s, UMA_ALIGN_PTR + 1));
2002 }
2003 
2004 #define	UMA_FIXPT_SHIFT	31
2005 #define	UMA_FRAC_FIXPT(n, d)						\
2006 	((uint32_t)(((uint64_t)(n) << UMA_FIXPT_SHIFT) / (d)))
2007 #define	UMA_FIXPT_PCT(f)						\
2008 	((u_int)(((uint64_t)100 * (f)) >> UMA_FIXPT_SHIFT))
2009 #define	UMA_PCT_FIXPT(pct)	UMA_FRAC_FIXPT((pct), 100)
2010 #define	UMA_MIN_EFF	UMA_PCT_FIXPT(100 - UMA_MAX_WASTE)
2011 
2012 /*
2013  * Compute the number of items that will fit in a slab.  If hdr is true, the
2014  * item count may be limited to provide space in the slab for an inline slab
2015  * header.  Otherwise, all slab space will be provided for item storage.
2016  */
2017 static u_int
slab_ipers_hdr(u_int size,u_int rsize,u_int slabsize,bool hdr)2018 slab_ipers_hdr(u_int size, u_int rsize, u_int slabsize, bool hdr)
2019 {
2020 	u_int ipers;
2021 	u_int padpi;
2022 
2023 	/* The padding between items is not needed after the last item. */
2024 	padpi = rsize - size;
2025 
2026 	if (hdr) {
2027 		/*
2028 		 * Start with the maximum item count and remove items until
2029 		 * the slab header first alongside the allocatable memory.
2030 		 */
2031 		for (ipers = MIN(SLAB_MAX_SETSIZE,
2032 		    (slabsize + padpi - slab_sizeof(1)) / rsize);
2033 		    ipers > 0 &&
2034 		    ipers * rsize - padpi + slab_sizeof(ipers) > slabsize;
2035 		    ipers--)
2036 			continue;
2037 	} else {
2038 		ipers = MIN((slabsize + padpi) / rsize, SLAB_MAX_SETSIZE);
2039 	}
2040 
2041 	return (ipers);
2042 }
2043 
2044 struct keg_layout_result {
2045 	u_int format;
2046 	u_int slabsize;
2047 	u_int ipers;
2048 	u_int eff;
2049 };
2050 
2051 static void
keg_layout_one(uma_keg_t keg,u_int rsize,u_int slabsize,u_int fmt,struct keg_layout_result * kl)2052 keg_layout_one(uma_keg_t keg, u_int rsize, u_int slabsize, u_int fmt,
2053     struct keg_layout_result *kl)
2054 {
2055 	u_int total;
2056 
2057 	kl->format = fmt;
2058 	kl->slabsize = slabsize;
2059 
2060 	/* Handle INTERNAL as inline with an extra page. */
2061 	if ((fmt & UMA_ZFLAG_INTERNAL) != 0) {
2062 		kl->format &= ~UMA_ZFLAG_INTERNAL;
2063 		kl->slabsize += PAGE_SIZE;
2064 	}
2065 
2066 	kl->ipers = slab_ipers_hdr(keg->uk_size, rsize, kl->slabsize,
2067 	    (fmt & UMA_ZFLAG_OFFPAGE) == 0);
2068 
2069 	/* Account for memory used by an offpage slab header. */
2070 	total = kl->slabsize;
2071 	if ((fmt & UMA_ZFLAG_OFFPAGE) != 0)
2072 		total += slabzone(kl->ipers)->uz_keg->uk_rsize;
2073 
2074 	kl->eff = UMA_FRAC_FIXPT(kl->ipers * rsize, total);
2075 }
2076 
2077 /*
2078  * Determine the format of a uma keg.  This determines where the slab header
2079  * will be placed (inline or offpage) and calculates ipers, rsize, and ppera.
2080  *
2081  * Arguments
2082  *	keg  The zone we should initialize
2083  *
2084  * Returns
2085  *	Nothing
2086  */
2087 static void
keg_layout(uma_keg_t keg)2088 keg_layout(uma_keg_t keg)
2089 {
2090 	struct keg_layout_result kl = {}, kl_tmp;
2091 	u_int fmts[2];
2092 	u_int alignsize;
2093 	u_int nfmt;
2094 	u_int pages;
2095 	u_int rsize;
2096 	u_int slabsize;
2097 	u_int i, j;
2098 
2099 	KASSERT((keg->uk_flags & UMA_ZONE_PCPU) == 0 ||
2100 	    (keg->uk_size <= UMA_PCPU_ALLOC_SIZE &&
2101 	     (keg->uk_flags & UMA_ZONE_CACHESPREAD) == 0),
2102 	    ("%s: cannot configure for PCPU: keg=%s, size=%u, flags=0x%b",
2103 	     __func__, keg->uk_name, keg->uk_size, keg->uk_flags,
2104 	     PRINT_UMA_ZFLAGS));
2105 	KASSERT((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) == 0 ||
2106 	    (keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0,
2107 	    ("%s: incompatible flags 0x%b", __func__, keg->uk_flags,
2108 	     PRINT_UMA_ZFLAGS));
2109 
2110 	alignsize = keg->uk_align + 1;
2111 
2112 	/*
2113 	 * Calculate the size of each allocation (rsize) according to
2114 	 * alignment.  If the requested size is smaller than we have
2115 	 * allocation bits for we round it up.
2116 	 */
2117 	rsize = MAX(keg->uk_size, UMA_SMALLEST_UNIT);
2118 	rsize = roundup2(rsize, alignsize);
2119 
2120 	if ((keg->uk_flags & UMA_ZONE_CACHESPREAD) != 0) {
2121 		/*
2122 		 * We want one item to start on every align boundary in a page.
2123 		 * To do this we will span pages.  We will also extend the item
2124 		 * by the size of align if it is an even multiple of align.
2125 		 * Otherwise, it would fall on the same boundary every time.
2126 		 */
2127 		if ((rsize & alignsize) == 0)
2128 			rsize += alignsize;
2129 		slabsize = rsize * (PAGE_SIZE / alignsize);
2130 		slabsize = MIN(slabsize, rsize * SLAB_MAX_SETSIZE);
2131 		slabsize = MIN(slabsize, UMA_CACHESPREAD_MAX_SIZE);
2132 		slabsize = round_page(slabsize);
2133 	} else {
2134 		/*
2135 		 * Start with a slab size of as many pages as it takes to
2136 		 * represent a single item.  We will try to fit as many
2137 		 * additional items into the slab as possible.
2138 		 */
2139 		slabsize = round_page(keg->uk_size);
2140 	}
2141 
2142 	/* Build a list of all of the available formats for this keg. */
2143 	nfmt = 0;
2144 
2145 	/* Evaluate an inline slab layout. */
2146 	if ((keg->uk_flags & (UMA_ZONE_NOTOUCH | UMA_ZONE_PCPU)) == 0)
2147 		fmts[nfmt++] = 0;
2148 
2149 	/* TODO: vm_page-embedded slab. */
2150 
2151 	/*
2152 	 * We can't do OFFPAGE if we're internal or if we've been
2153 	 * asked to not go to the VM for buckets.  If we do this we
2154 	 * may end up going to the VM for slabs which we do not want
2155 	 * to do if we're UMA_ZONE_VM, which clearly forbids it.
2156 	 * In those cases, evaluate a pseudo-format called INTERNAL
2157 	 * which has an inline slab header and one extra page to
2158 	 * guarantee that it fits.
2159 	 *
2160 	 * Otherwise, see if using an OFFPAGE slab will improve our
2161 	 * efficiency.
2162 	 */
2163 	if ((keg->uk_flags & (UMA_ZFLAG_INTERNAL | UMA_ZONE_VM)) != 0)
2164 		fmts[nfmt++] = UMA_ZFLAG_INTERNAL;
2165 	else
2166 		fmts[nfmt++] = UMA_ZFLAG_OFFPAGE;
2167 
2168 	/*
2169 	 * Choose a slab size and format which satisfy the minimum efficiency.
2170 	 * Prefer the smallest slab size that meets the constraints.
2171 	 *
2172 	 * Start with a minimum slab size, to accommodate CACHESPREAD.  Then,
2173 	 * for small items (up to PAGE_SIZE), the iteration increment is one
2174 	 * page; and for large items, the increment is one item.
2175 	 */
2176 	i = (slabsize + rsize - keg->uk_size) / MAX(PAGE_SIZE, rsize);
2177 	KASSERT(i >= 1, ("keg %s(%p) flags=0x%b slabsize=%u, rsize=%u, i=%u",
2178 	    keg->uk_name, keg, keg->uk_flags, PRINT_UMA_ZFLAGS, slabsize,
2179 	    rsize, i));
2180 	for ( ; ; i++) {
2181 		slabsize = (rsize <= PAGE_SIZE) ? ptoa(i) :
2182 		    round_page(rsize * (i - 1) + keg->uk_size);
2183 
2184 		for (j = 0; j < nfmt; j++) {
2185 			/* Only if we have no viable format yet. */
2186 			if ((fmts[j] & UMA_ZFLAG_INTERNAL) != 0 &&
2187 			    kl.ipers > 0)
2188 				continue;
2189 
2190 			keg_layout_one(keg, rsize, slabsize, fmts[j], &kl_tmp);
2191 			if (kl_tmp.eff <= kl.eff)
2192 				continue;
2193 
2194 			kl = kl_tmp;
2195 
2196 			CTR6(KTR_UMA, "keg %s layout: format %#x "
2197 			    "(ipers %u * rsize %u) / slabsize %#x = %u%% eff",
2198 			    keg->uk_name, kl.format, kl.ipers, rsize,
2199 			    kl.slabsize, UMA_FIXPT_PCT(kl.eff));
2200 
2201 			/* Stop when we reach the minimum efficiency. */
2202 			if (kl.eff >= UMA_MIN_EFF)
2203 				break;
2204 		}
2205 
2206 		if (kl.eff >= UMA_MIN_EFF || !multipage_slabs ||
2207 		    slabsize >= SLAB_MAX_SETSIZE * rsize ||
2208 		    (keg->uk_flags & (UMA_ZONE_PCPU | UMA_ZONE_CONTIG)) != 0)
2209 			break;
2210 	}
2211 
2212 	pages = atop(kl.slabsize);
2213 	if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
2214 		pages *= mp_maxid + 1;
2215 
2216 	keg->uk_rsize = rsize;
2217 	keg->uk_ipers = kl.ipers;
2218 	keg->uk_ppera = pages;
2219 	keg->uk_flags |= kl.format;
2220 
2221 	/*
2222 	 * How do we find the slab header if it is offpage or if not all item
2223 	 * start addresses are in the same page?  We could solve the latter
2224 	 * case with vaddr alignment, but we don't.
2225 	 */
2226 	if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0 ||
2227 	    (keg->uk_ipers - 1) * rsize >= PAGE_SIZE) {
2228 		if ((keg->uk_flags & UMA_ZONE_NOTPAGE) != 0)
2229 			keg->uk_flags |= UMA_ZFLAG_HASH;
2230 		else
2231 			keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2232 	}
2233 
2234 	CTR6(KTR_UMA, "%s: keg=%s, flags=%#x, rsize=%u, ipers=%u, ppera=%u",
2235 	    __func__, keg->uk_name, keg->uk_flags, rsize, keg->uk_ipers,
2236 	    pages);
2237 	KASSERT(keg->uk_ipers > 0 && keg->uk_ipers <= SLAB_MAX_SETSIZE,
2238 	    ("%s: keg=%s, flags=0x%b, rsize=%u, ipers=%u, ppera=%u", __func__,
2239 	     keg->uk_name, keg->uk_flags, PRINT_UMA_ZFLAGS, rsize,
2240 	     keg->uk_ipers, pages));
2241 }
2242 
2243 /*
2244  * Keg header ctor.  This initializes all fields, locks, etc.  And inserts
2245  * the keg onto the global keg list.
2246  *
2247  * Arguments/Returns follow uma_ctor specifications
2248  *	udata  Actually uma_kctor_args
2249  */
2250 static int
keg_ctor(void * mem,int size,void * udata,int flags)2251 keg_ctor(void *mem, int size, void *udata, int flags)
2252 {
2253 	struct uma_kctor_args *arg = udata;
2254 	uma_keg_t keg = mem;
2255 	uma_zone_t zone;
2256 	int i;
2257 
2258 	bzero(keg, size);
2259 	keg->uk_size = arg->size;
2260 	keg->uk_init = arg->uminit;
2261 	keg->uk_fini = arg->fini;
2262 	keg->uk_align = arg->align;
2263 	keg->uk_reserve = 0;
2264 	keg->uk_flags = arg->flags;
2265 
2266 	/*
2267 	 * We use a global round-robin policy by default.  Zones with
2268 	 * UMA_ZONE_FIRSTTOUCH set will use first-touch instead, in which
2269 	 * case the iterator is never run.
2270 	 */
2271 	keg->uk_dr.dr_policy = DOMAINSET_RR();
2272 	keg->uk_dr.dr_iter = 0;
2273 
2274 	/*
2275 	 * The primary zone is passed to us at keg-creation time.
2276 	 */
2277 	zone = arg->zone;
2278 	keg->uk_name = zone->uz_name;
2279 
2280 	if (arg->flags & UMA_ZONE_ZINIT)
2281 		keg->uk_init = zero_init;
2282 
2283 	if (arg->flags & UMA_ZONE_MALLOC)
2284 		keg->uk_flags |= UMA_ZFLAG_VTOSLAB;
2285 
2286 #ifndef SMP
2287 	keg->uk_flags &= ~UMA_ZONE_PCPU;
2288 #endif
2289 
2290 	keg_layout(keg);
2291 
2292 	/*
2293 	 * Use a first-touch NUMA policy for kegs that pmap_extract() will
2294 	 * work on.  Use round-robin for everything else.
2295 	 *
2296 	 * Zones may override the default by specifying either.
2297 	 */
2298 #ifdef NUMA
2299 	if ((keg->uk_flags &
2300 	    (UMA_ZONE_ROUNDROBIN | UMA_ZFLAG_CACHE | UMA_ZONE_NOTPAGE)) == 0)
2301 		keg->uk_flags |= UMA_ZONE_FIRSTTOUCH;
2302 	else if ((keg->uk_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2303 		keg->uk_flags |= UMA_ZONE_ROUNDROBIN;
2304 #endif
2305 
2306 	/*
2307 	 * If we haven't booted yet we need allocations to go through the
2308 	 * startup cache until the vm is ready.
2309 	 */
2310 #ifdef UMA_MD_SMALL_ALLOC
2311 	if (keg->uk_ppera == 1)
2312 		keg->uk_allocf = uma_small_alloc;
2313 	else
2314 #endif
2315 	if (booted < BOOT_KVA)
2316 		keg->uk_allocf = startup_alloc;
2317 	else if (keg->uk_flags & UMA_ZONE_PCPU)
2318 		keg->uk_allocf = pcpu_page_alloc;
2319 	else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 && keg->uk_ppera > 1)
2320 		keg->uk_allocf = contig_alloc;
2321 	else
2322 		keg->uk_allocf = page_alloc;
2323 #ifdef UMA_MD_SMALL_ALLOC
2324 	if (keg->uk_ppera == 1)
2325 		keg->uk_freef = uma_small_free;
2326 	else
2327 #endif
2328 	if (keg->uk_flags & UMA_ZONE_PCPU)
2329 		keg->uk_freef = pcpu_page_free;
2330 	else
2331 		keg->uk_freef = page_free;
2332 
2333 	/*
2334 	 * Initialize keg's locks.
2335 	 */
2336 	for (i = 0; i < vm_ndomains; i++)
2337 		KEG_LOCK_INIT(keg, i, (arg->flags & UMA_ZONE_MTXCLASS));
2338 
2339 	/*
2340 	 * If we're putting the slab header in the actual page we need to
2341 	 * figure out where in each page it goes.  See slab_sizeof
2342 	 * definition.
2343 	 */
2344 	if (!(keg->uk_flags & UMA_ZFLAG_OFFPAGE)) {
2345 		size_t shsize;
2346 
2347 		shsize = slab_sizeof(keg->uk_ipers);
2348 		keg->uk_pgoff = (PAGE_SIZE * keg->uk_ppera) - shsize;
2349 		/*
2350 		 * The only way the following is possible is if with our
2351 		 * UMA_ALIGN_PTR adjustments we are now bigger than
2352 		 * UMA_SLAB_SIZE.  I haven't checked whether this is
2353 		 * mathematically possible for all cases, so we make
2354 		 * sure here anyway.
2355 		 */
2356 		KASSERT(keg->uk_pgoff + shsize <= PAGE_SIZE * keg->uk_ppera,
2357 		    ("zone %s ipers %d rsize %d size %d slab won't fit",
2358 		    zone->uz_name, keg->uk_ipers, keg->uk_rsize, keg->uk_size));
2359 	}
2360 
2361 	if (keg->uk_flags & UMA_ZFLAG_HASH)
2362 		hash_alloc(&keg->uk_hash, 0);
2363 
2364 	CTR3(KTR_UMA, "keg_ctor %p zone %s(%p)", keg, zone->uz_name, zone);
2365 
2366 	LIST_INSERT_HEAD(&keg->uk_zones, zone, uz_link);
2367 
2368 	rw_wlock(&uma_rwlock);
2369 	LIST_INSERT_HEAD(&uma_kegs, keg, uk_link);
2370 	rw_wunlock(&uma_rwlock);
2371 	return (0);
2372 }
2373 
2374 static void
zone_kva_available(uma_zone_t zone,void * unused)2375 zone_kva_available(uma_zone_t zone, void *unused)
2376 {
2377 	uma_keg_t keg;
2378 
2379 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
2380 		return;
2381 	KEG_GET(zone, keg);
2382 
2383 	if (keg->uk_allocf == startup_alloc) {
2384 		/* Switch to the real allocator. */
2385 		if (keg->uk_flags & UMA_ZONE_PCPU)
2386 			keg->uk_allocf = pcpu_page_alloc;
2387 		else if ((keg->uk_flags & UMA_ZONE_CONTIG) != 0 &&
2388 		    keg->uk_ppera > 1)
2389 			keg->uk_allocf = contig_alloc;
2390 		else
2391 			keg->uk_allocf = page_alloc;
2392 	}
2393 }
2394 
2395 static void
zone_alloc_counters(uma_zone_t zone,void * unused)2396 zone_alloc_counters(uma_zone_t zone, void *unused)
2397 {
2398 
2399 	zone->uz_allocs = counter_u64_alloc(M_WAITOK);
2400 	zone->uz_frees = counter_u64_alloc(M_WAITOK);
2401 	zone->uz_fails = counter_u64_alloc(M_WAITOK);
2402 	zone->uz_xdomain = counter_u64_alloc(M_WAITOK);
2403 }
2404 
2405 static void
zone_alloc_sysctl(uma_zone_t zone,void * unused)2406 zone_alloc_sysctl(uma_zone_t zone, void *unused)
2407 {
2408 	uma_zone_domain_t zdom;
2409 	uma_domain_t dom;
2410 	uma_keg_t keg;
2411 	struct sysctl_oid *oid, *domainoid;
2412 	int domains, i, cnt;
2413 	static const char *nokeg = "cache zone";
2414 	char *c;
2415 
2416 	/*
2417 	 * Make a sysctl safe copy of the zone name by removing
2418 	 * any special characters and handling dups by appending
2419 	 * an index.
2420 	 */
2421 	if (zone->uz_namecnt != 0) {
2422 		/* Count the number of decimal digits and '_' separator. */
2423 		for (i = 1, cnt = zone->uz_namecnt; cnt != 0; i++)
2424 			cnt /= 10;
2425 		zone->uz_ctlname = malloc(strlen(zone->uz_name) + i + 1,
2426 		    M_UMA, M_WAITOK);
2427 		sprintf(zone->uz_ctlname, "%s_%d", zone->uz_name,
2428 		    zone->uz_namecnt);
2429 	} else
2430 		zone->uz_ctlname = strdup(zone->uz_name, M_UMA);
2431 	for (c = zone->uz_ctlname; *c != '\0'; c++)
2432 		if (strchr("./\\ -", *c) != NULL)
2433 			*c = '_';
2434 
2435 	/*
2436 	 * Basic parameters at the root.
2437 	 */
2438 	zone->uz_oid = SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_vm_uma),
2439 	    OID_AUTO, zone->uz_ctlname, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2440 	oid = zone->uz_oid;
2441 	SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2442 	    "size", CTLFLAG_RD, &zone->uz_size, 0, "Allocation size");
2443 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2444 	    "flags", CTLFLAG_RD | CTLTYPE_STRING | CTLFLAG_MPSAFE,
2445 	    zone, 0, sysctl_handle_uma_zone_flags, "A",
2446 	    "Allocator configuration flags");
2447 	SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2448 	    "bucket_size", CTLFLAG_RD, &zone->uz_bucket_size, 0,
2449 	    "Desired per-cpu cache size");
2450 	SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2451 	    "bucket_size_max", CTLFLAG_RD, &zone->uz_bucket_size_max, 0,
2452 	    "Maximum allowed per-cpu cache size");
2453 
2454 	/*
2455 	 * keg if present.
2456 	 */
2457 	if ((zone->uz_flags & UMA_ZFLAG_HASH) == 0)
2458 		domains = vm_ndomains;
2459 	else
2460 		domains = 1;
2461 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2462 	    "keg", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2463 	keg = zone->uz_keg;
2464 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) == 0) {
2465 		SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2466 		    "name", CTLFLAG_RD, keg->uk_name, "Keg name");
2467 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2468 		    "rsize", CTLFLAG_RD, &keg->uk_rsize, 0,
2469 		    "Real object size with alignment");
2470 		SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2471 		    "ppera", CTLFLAG_RD, &keg->uk_ppera, 0,
2472 		    "pages per-slab allocation");
2473 		SYSCTL_ADD_U16(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2474 		    "ipers", CTLFLAG_RD, &keg->uk_ipers, 0,
2475 		    "items available per-slab");
2476 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2477 		    "align", CTLFLAG_RD, &keg->uk_align, 0,
2478 		    "item alignment mask");
2479 		SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2480 		    "reserve", CTLFLAG_RD, &keg->uk_reserve, 0,
2481 		    "number of reserved items");
2482 		SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2483 		    "efficiency", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2484 		    keg, 0, sysctl_handle_uma_slab_efficiency, "I",
2485 		    "Slab utilization (100 - internal fragmentation %)");
2486 		domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(oid),
2487 		    OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2488 		for (i = 0; i < domains; i++) {
2489 			dom = &keg->uk_domain[i];
2490 			oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2491 			    OID_AUTO, VM_DOMAIN(i)->vmd_name,
2492 			    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2493 			SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2494 			    "pages", CTLFLAG_RD, &dom->ud_pages, 0,
2495 			    "Total pages currently allocated from VM");
2496 			SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2497 			    "free_items", CTLFLAG_RD, &dom->ud_free_items, 0,
2498 			    "items free in the slab layer");
2499 		}
2500 	} else
2501 		SYSCTL_ADD_CONST_STRING(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2502 		    "name", CTLFLAG_RD, nokeg, "Keg name");
2503 
2504 	/*
2505 	 * Information about zone limits.
2506 	 */
2507 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2508 	    "limit", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2509 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2510 	    "items", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2511 	    zone, 0, sysctl_handle_uma_zone_items, "QU",
2512 	    "Current number of allocated items if limit is set");
2513 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2514 	    "max_items", CTLFLAG_RD, &zone->uz_max_items, 0,
2515 	    "Maximum number of allocated and cached items");
2516 	SYSCTL_ADD_U32(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2517 	    "sleepers", CTLFLAG_RD, &zone->uz_sleepers, 0,
2518 	    "Number of threads sleeping at limit");
2519 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2520 	    "sleeps", CTLFLAG_RD, &zone->uz_sleeps, 0,
2521 	    "Total zone limit sleeps");
2522 	SYSCTL_ADD_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2523 	    "bucket_max", CTLFLAG_RD, &zone->uz_bucket_max, 0,
2524 	    "Maximum number of items in each domain's bucket cache");
2525 
2526 	/*
2527 	 * Per-domain zone information.
2528 	 */
2529 	domainoid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid),
2530 	    OID_AUTO, "domain", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2531 	for (i = 0; i < domains; i++) {
2532 		zdom = ZDOM_GET(zone, i);
2533 		oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(domainoid),
2534 		    OID_AUTO, VM_DOMAIN(i)->vmd_name,
2535 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2536 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2537 		    "nitems", CTLFLAG_RD, &zdom->uzd_nitems,
2538 		    "number of items in this domain");
2539 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2540 		    "imax", CTLFLAG_RD, &zdom->uzd_imax,
2541 		    "maximum item count in this period");
2542 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2543 		    "imin", CTLFLAG_RD, &zdom->uzd_imin,
2544 		    "minimum item count in this period");
2545 		SYSCTL_ADD_LONG(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2546 		    "wss", CTLFLAG_RD, &zdom->uzd_wss,
2547 		    "Working set size");
2548 	}
2549 
2550 	/*
2551 	 * General statistics.
2552 	 */
2553 	oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(zone->uz_oid), OID_AUTO,
2554 	    "stats", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
2555 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2556 	    "current", CTLFLAG_RD | CTLTYPE_INT | CTLFLAG_MPSAFE,
2557 	    zone, 1, sysctl_handle_uma_zone_cur, "I",
2558 	    "Current number of allocated items");
2559 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2560 	    "allocs", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2561 	    zone, 0, sysctl_handle_uma_zone_allocs, "QU",
2562 	    "Total allocation calls");
2563 	SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2564 	    "frees", CTLFLAG_RD | CTLTYPE_U64 | CTLFLAG_MPSAFE,
2565 	    zone, 0, sysctl_handle_uma_zone_frees, "QU",
2566 	    "Total free calls");
2567 	SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2568 	    "fails", CTLFLAG_RD, &zone->uz_fails,
2569 	    "Number of allocation failures");
2570 	SYSCTL_ADD_COUNTER_U64(NULL, SYSCTL_CHILDREN(oid), OID_AUTO,
2571 	    "xdomain", CTLFLAG_RD, &zone->uz_xdomain,
2572 	    "Free calls from the wrong domain");
2573 }
2574 
2575 struct uma_zone_count {
2576 	const char	*name;
2577 	int		count;
2578 };
2579 
2580 static void
zone_count(uma_zone_t zone,void * arg)2581 zone_count(uma_zone_t zone, void *arg)
2582 {
2583 	struct uma_zone_count *cnt;
2584 
2585 	cnt = arg;
2586 	/*
2587 	 * Some zones are rapidly created with identical names and
2588 	 * destroyed out of order.  This can lead to gaps in the count.
2589 	 * Use one greater than the maximum observed for this name.
2590 	 */
2591 	if (strcmp(zone->uz_name, cnt->name) == 0)
2592 		cnt->count = MAX(cnt->count,
2593 		    zone->uz_namecnt + 1);
2594 }
2595 
2596 static void
zone_update_caches(uma_zone_t zone)2597 zone_update_caches(uma_zone_t zone)
2598 {
2599 	int i;
2600 
2601 	for (i = 0; i <= mp_maxid; i++) {
2602 		cache_set_uz_size(&zone->uz_cpu[i], zone->uz_size);
2603 		cache_set_uz_flags(&zone->uz_cpu[i], zone->uz_flags);
2604 	}
2605 }
2606 
2607 /*
2608  * Zone header ctor.  This initializes all fields, locks, etc.
2609  *
2610  * Arguments/Returns follow uma_ctor specifications
2611  *	udata  Actually uma_zctor_args
2612  */
2613 static int
zone_ctor(void * mem,int size,void * udata,int flags)2614 zone_ctor(void *mem, int size, void *udata, int flags)
2615 {
2616 	struct uma_zone_count cnt;
2617 	struct uma_zctor_args *arg = udata;
2618 	uma_zone_domain_t zdom;
2619 	uma_zone_t zone = mem;
2620 	uma_zone_t z;
2621 	uma_keg_t keg;
2622 	int i;
2623 
2624 	bzero(zone, size);
2625 	zone->uz_name = arg->name;
2626 	zone->uz_ctor = arg->ctor;
2627 	zone->uz_dtor = arg->dtor;
2628 	zone->uz_init = NULL;
2629 	zone->uz_fini = NULL;
2630 	zone->uz_sleeps = 0;
2631 	zone->uz_bucket_size = 0;
2632 	zone->uz_bucket_size_min = 0;
2633 	zone->uz_bucket_size_max = BUCKET_MAX;
2634 	zone->uz_flags = (arg->flags & UMA_ZONE_SMR);
2635 	zone->uz_warning = NULL;
2636 	/* The domain structures follow the cpu structures. */
2637 	zone->uz_bucket_max = ULONG_MAX;
2638 	timevalclear(&zone->uz_ratecheck);
2639 
2640 	/* Count the number of duplicate names. */
2641 	cnt.name = arg->name;
2642 	cnt.count = 0;
2643 	zone_foreach(zone_count, &cnt);
2644 	zone->uz_namecnt = cnt.count;
2645 	ZONE_CROSS_LOCK_INIT(zone);
2646 
2647 	for (i = 0; i < vm_ndomains; i++) {
2648 		zdom = ZDOM_GET(zone, i);
2649 		ZDOM_LOCK_INIT(zone, zdom, (arg->flags & UMA_ZONE_MTXCLASS));
2650 		STAILQ_INIT(&zdom->uzd_buckets);
2651 	}
2652 
2653 #ifdef INVARIANTS
2654 	if (arg->uminit == trash_init && arg->fini == trash_fini)
2655 		zone->uz_flags |= UMA_ZFLAG_TRASH | UMA_ZFLAG_CTORDTOR;
2656 #endif
2657 
2658 	/*
2659 	 * This is a pure cache zone, no kegs.
2660 	 */
2661 	if (arg->import) {
2662 		KASSERT((arg->flags & UMA_ZFLAG_CACHE) != 0,
2663 		    ("zone_ctor: Import specified for non-cache zone."));
2664 		zone->uz_flags = arg->flags;
2665 		zone->uz_size = arg->size;
2666 		zone->uz_import = arg->import;
2667 		zone->uz_release = arg->release;
2668 		zone->uz_arg = arg->arg;
2669 #ifdef NUMA
2670 		/*
2671 		 * Cache zones are round-robin unless a policy is
2672 		 * specified because they may have incompatible
2673 		 * constraints.
2674 		 */
2675 		if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) == 0)
2676 			zone->uz_flags |= UMA_ZONE_ROUNDROBIN;
2677 #endif
2678 		rw_wlock(&uma_rwlock);
2679 		LIST_INSERT_HEAD(&uma_cachezones, zone, uz_link);
2680 		rw_wunlock(&uma_rwlock);
2681 		goto out;
2682 	}
2683 
2684 	/*
2685 	 * Use the regular zone/keg/slab allocator.
2686 	 */
2687 	zone->uz_import = zone_import;
2688 	zone->uz_release = zone_release;
2689 	zone->uz_arg = zone;
2690 	keg = arg->keg;
2691 
2692 	if (arg->flags & UMA_ZONE_SECONDARY) {
2693 		KASSERT((zone->uz_flags & UMA_ZONE_SECONDARY) == 0,
2694 		    ("Secondary zone requested UMA_ZFLAG_INTERNAL"));
2695 		KASSERT(arg->keg != NULL, ("Secondary zone on zero'd keg"));
2696 		zone->uz_init = arg->uminit;
2697 		zone->uz_fini = arg->fini;
2698 		zone->uz_flags |= UMA_ZONE_SECONDARY;
2699 		rw_wlock(&uma_rwlock);
2700 		ZONE_LOCK(zone);
2701 		LIST_FOREACH(z, &keg->uk_zones, uz_link) {
2702 			if (LIST_NEXT(z, uz_link) == NULL) {
2703 				LIST_INSERT_AFTER(z, zone, uz_link);
2704 				break;
2705 			}
2706 		}
2707 		ZONE_UNLOCK(zone);
2708 		rw_wunlock(&uma_rwlock);
2709 	} else if (keg == NULL) {
2710 		if ((keg = uma_kcreate(zone, arg->size, arg->uminit, arg->fini,
2711 		    arg->align, arg->flags)) == NULL)
2712 			return (ENOMEM);
2713 	} else {
2714 		struct uma_kctor_args karg;
2715 		int error;
2716 
2717 		/* We should only be here from uma_startup() */
2718 		karg.size = arg->size;
2719 		karg.uminit = arg->uminit;
2720 		karg.fini = arg->fini;
2721 		karg.align = arg->align;
2722 		karg.flags = (arg->flags & ~UMA_ZONE_SMR);
2723 		karg.zone = zone;
2724 		error = keg_ctor(arg->keg, sizeof(struct uma_keg), &karg,
2725 		    flags);
2726 		if (error)
2727 			return (error);
2728 	}
2729 
2730 	/* Inherit properties from the keg. */
2731 	zone->uz_keg = keg;
2732 	zone->uz_size = keg->uk_size;
2733 	zone->uz_flags |= (keg->uk_flags &
2734 	    (UMA_ZONE_INHERIT | UMA_ZFLAG_INHERIT));
2735 
2736 out:
2737 	if (booted >= BOOT_PCPU) {
2738 		zone_alloc_counters(zone, NULL);
2739 		if (booted >= BOOT_RUNNING)
2740 			zone_alloc_sysctl(zone, NULL);
2741 	} else {
2742 		zone->uz_allocs = EARLY_COUNTER;
2743 		zone->uz_frees = EARLY_COUNTER;
2744 		zone->uz_fails = EARLY_COUNTER;
2745 	}
2746 
2747 	/* Caller requests a private SMR context. */
2748 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
2749 		zone->uz_smr = smr_create(zone->uz_name, 0, 0);
2750 
2751 	KASSERT((arg->flags & (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET)) !=
2752 	    (UMA_ZONE_MAXBUCKET | UMA_ZONE_NOBUCKET),
2753 	    ("Invalid zone flag combination"));
2754 	if (arg->flags & UMA_ZFLAG_INTERNAL)
2755 		zone->uz_bucket_size_max = zone->uz_bucket_size = 0;
2756 	if ((arg->flags & UMA_ZONE_MAXBUCKET) != 0)
2757 		zone->uz_bucket_size = BUCKET_MAX;
2758 	else if ((arg->flags & UMA_ZONE_NOBUCKET) != 0)
2759 		zone->uz_bucket_size = 0;
2760 	else
2761 		zone->uz_bucket_size = bucket_select(zone->uz_size);
2762 	zone->uz_bucket_size_min = zone->uz_bucket_size;
2763 	if (zone->uz_dtor != NULL || zone->uz_ctor != NULL)
2764 		zone->uz_flags |= UMA_ZFLAG_CTORDTOR;
2765 	zone_update_caches(zone);
2766 
2767 	return (0);
2768 }
2769 
2770 /*
2771  * Keg header dtor.  This frees all data, destroys locks, frees the hash
2772  * table and removes the keg from the global list.
2773  *
2774  * Arguments/Returns follow uma_dtor specifications
2775  *	udata  unused
2776  */
2777 static void
keg_dtor(void * arg,int size,void * udata)2778 keg_dtor(void *arg, int size, void *udata)
2779 {
2780 	uma_keg_t keg;
2781 	uint32_t free, pages;
2782 	int i;
2783 
2784 	keg = (uma_keg_t)arg;
2785 	free = pages = 0;
2786 	for (i = 0; i < vm_ndomains; i++) {
2787 		free += keg->uk_domain[i].ud_free_items;
2788 		pages += keg->uk_domain[i].ud_pages;
2789 		KEG_LOCK_FINI(keg, i);
2790 	}
2791 	if (pages != 0)
2792 		printf("Freed UMA keg (%s) was not empty (%u items). "
2793 		    " Lost %u pages of memory.\n",
2794 		    keg->uk_name ? keg->uk_name : "",
2795 		    pages / keg->uk_ppera * keg->uk_ipers - free, pages);
2796 
2797 	hash_free(&keg->uk_hash);
2798 }
2799 
2800 /*
2801  * Zone header dtor.
2802  *
2803  * Arguments/Returns follow uma_dtor specifications
2804  *	udata  unused
2805  */
2806 static void
zone_dtor(void * arg,int size,void * udata)2807 zone_dtor(void *arg, int size, void *udata)
2808 {
2809 	uma_zone_t zone;
2810 	uma_keg_t keg;
2811 	int i;
2812 
2813 	zone = (uma_zone_t)arg;
2814 
2815 	sysctl_remove_oid(zone->uz_oid, 1, 1);
2816 
2817 	if (!(zone->uz_flags & UMA_ZFLAG_INTERNAL))
2818 		cache_drain(zone);
2819 
2820 	rw_wlock(&uma_rwlock);
2821 	LIST_REMOVE(zone, uz_link);
2822 	rw_wunlock(&uma_rwlock);
2823 	if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2824 		keg = zone->uz_keg;
2825 		keg->uk_reserve = 0;
2826 	}
2827 	zone_reclaim(zone, M_WAITOK, true);
2828 
2829 	/*
2830 	 * We only destroy kegs from non secondary/non cache zones.
2831 	 */
2832 	if ((zone->uz_flags & (UMA_ZONE_SECONDARY | UMA_ZFLAG_CACHE)) == 0) {
2833 		keg = zone->uz_keg;
2834 		rw_wlock(&uma_rwlock);
2835 		LIST_REMOVE(keg, uk_link);
2836 		rw_wunlock(&uma_rwlock);
2837 		zone_free_item(kegs, keg, NULL, SKIP_NONE);
2838 	}
2839 	counter_u64_free(zone->uz_allocs);
2840 	counter_u64_free(zone->uz_frees);
2841 	counter_u64_free(zone->uz_fails);
2842 	counter_u64_free(zone->uz_xdomain);
2843 	free(zone->uz_ctlname, M_UMA);
2844 	for (i = 0; i < vm_ndomains; i++)
2845 		ZDOM_LOCK_FINI(ZDOM_GET(zone, i));
2846 	ZONE_CROSS_LOCK_FINI(zone);
2847 }
2848 
2849 static void
zone_foreach_unlocked(void (* zfunc)(uma_zone_t,void * arg),void * arg)2850 zone_foreach_unlocked(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2851 {
2852 	uma_keg_t keg;
2853 	uma_zone_t zone;
2854 
2855 	LIST_FOREACH(keg, &uma_kegs, uk_link) {
2856 		LIST_FOREACH(zone, &keg->uk_zones, uz_link)
2857 			zfunc(zone, arg);
2858 	}
2859 	LIST_FOREACH(zone, &uma_cachezones, uz_link)
2860 		zfunc(zone, arg);
2861 }
2862 
2863 /*
2864  * Traverses every zone in the system and calls a callback
2865  *
2866  * Arguments:
2867  *	zfunc  A pointer to a function which accepts a zone
2868  *		as an argument.
2869  *
2870  * Returns:
2871  *	Nothing
2872  */
2873 static void
zone_foreach(void (* zfunc)(uma_zone_t,void * arg),void * arg)2874 zone_foreach(void (*zfunc)(uma_zone_t, void *arg), void *arg)
2875 {
2876 
2877 	rw_rlock(&uma_rwlock);
2878 	zone_foreach_unlocked(zfunc, arg);
2879 	rw_runlock(&uma_rwlock);
2880 }
2881 
2882 /*
2883  * Initialize the kernel memory allocator.  This is done after pages can be
2884  * allocated but before general KVA is available.
2885  */
2886 void
uma_startup1(vm_offset_t virtual_avail)2887 uma_startup1(vm_offset_t virtual_avail)
2888 {
2889 	struct uma_zctor_args args;
2890 	size_t ksize, zsize, size;
2891 	uma_keg_t primarykeg;
2892 	uintptr_t m;
2893 	int domain;
2894 	uint8_t pflag;
2895 
2896 	bootstart = bootmem = virtual_avail;
2897 
2898 	rw_init(&uma_rwlock, "UMA lock");
2899 	sx_init(&uma_reclaim_lock, "umareclaim");
2900 
2901 	ksize = sizeof(struct uma_keg) +
2902 	    (sizeof(struct uma_domain) * vm_ndomains);
2903 	ksize = roundup(ksize, UMA_SUPER_ALIGN);
2904 	zsize = sizeof(struct uma_zone) +
2905 	    (sizeof(struct uma_cache) * (mp_maxid + 1)) +
2906 	    (sizeof(struct uma_zone_domain) * vm_ndomains);
2907 	zsize = roundup(zsize, UMA_SUPER_ALIGN);
2908 
2909 	/* Allocate the zone of zones, zone of kegs, and zone of zones keg. */
2910 	size = (zsize * 2) + ksize;
2911 	for (domain = 0; domain < vm_ndomains; domain++) {
2912 		m = (uintptr_t)startup_alloc(NULL, size, domain, &pflag,
2913 		    M_NOWAIT | M_ZERO);
2914 		if (m != 0)
2915 			break;
2916 	}
2917 	zones = (uma_zone_t)m;
2918 	m += zsize;
2919 	kegs = (uma_zone_t)m;
2920 	m += zsize;
2921 	primarykeg = (uma_keg_t)m;
2922 
2923 	/* "manually" create the initial zone */
2924 	memset(&args, 0, sizeof(args));
2925 	args.name = "UMA Kegs";
2926 	args.size = ksize;
2927 	args.ctor = keg_ctor;
2928 	args.dtor = keg_dtor;
2929 	args.uminit = zero_init;
2930 	args.fini = NULL;
2931 	args.keg = primarykeg;
2932 	args.align = UMA_SUPER_ALIGN - 1;
2933 	args.flags = UMA_ZFLAG_INTERNAL;
2934 	zone_ctor(kegs, zsize, &args, M_WAITOK);
2935 
2936 	args.name = "UMA Zones";
2937 	args.size = zsize;
2938 	args.ctor = zone_ctor;
2939 	args.dtor = zone_dtor;
2940 	args.uminit = zero_init;
2941 	args.fini = NULL;
2942 	args.keg = NULL;
2943 	args.align = UMA_SUPER_ALIGN - 1;
2944 	args.flags = UMA_ZFLAG_INTERNAL;
2945 	zone_ctor(zones, zsize, &args, M_WAITOK);
2946 
2947 	/* Now make zones for slab headers */
2948 	slabzones[0] = uma_zcreate("UMA Slabs 0", SLABZONE0_SIZE,
2949 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2950 	slabzones[1] = uma_zcreate("UMA Slabs 1", SLABZONE1_SIZE,
2951 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2952 
2953 	hashzone = uma_zcreate("UMA Hash",
2954 	    sizeof(struct slabhead *) * UMA_HASH_SIZE_INIT,
2955 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZFLAG_INTERNAL);
2956 
2957 	bucket_init();
2958 	smr_init();
2959 }
2960 
2961 #ifndef FSTACK
2962 #ifndef UMA_MD_SMALL_ALLOC
2963 extern void vm_radix_reserve_kva(void);
2964 #endif
2965 #endif
2966 
2967 /*
2968  * Advertise the availability of normal kva allocations and switch to
2969  * the default back-end allocator.  Marks the KVA we consumed on startup
2970  * as used in the map.
2971  */
2972 void
uma_startup2(void)2973 uma_startup2(void)
2974 {
2975 #ifndef FSTACK
2976 	if (bootstart != bootmem) {
2977 		vm_map_lock(kernel_map);
2978 		(void)vm_map_insert(kernel_map, NULL, 0, bootstart, bootmem,
2979 		    VM_PROT_RW, VM_PROT_RW, MAP_NOFAULT);
2980 		vm_map_unlock(kernel_map);
2981 	}
2982 
2983 #ifndef UMA_MD_SMALL_ALLOC
2984 	/* Set up radix zone to use noobj_alloc. */
2985 	vm_radix_reserve_kva();
2986 #endif
2987 #endif
2988 
2989 	booted = BOOT_KVA;
2990 	zone_foreach_unlocked(zone_kva_available, NULL);
2991 	bucket_enable();
2992 }
2993 
2994 /*
2995  * Allocate counters as early as possible so that boot-time allocations are
2996  * accounted more precisely.
2997  */
2998 static void
uma_startup_pcpu(void * arg __unused)2999 uma_startup_pcpu(void *arg __unused)
3000 {
3001 
3002 	zone_foreach_unlocked(zone_alloc_counters, NULL);
3003 	booted = BOOT_PCPU;
3004 }
3005 SYSINIT(uma_startup_pcpu, SI_SUB_COUNTER, SI_ORDER_ANY, uma_startup_pcpu, NULL);
3006 
3007 /*
3008  * Finish our initialization steps.
3009  */
3010 static void
uma_startup3(void * arg __unused)3011 uma_startup3(void *arg __unused)
3012 {
3013 
3014 #ifdef INVARIANTS
3015 	TUNABLE_INT_FETCH("vm.debug.divisor", &dbg_divisor);
3016 	uma_dbg_cnt = counter_u64_alloc(M_WAITOK);
3017 	uma_skip_cnt = counter_u64_alloc(M_WAITOK);
3018 #endif
3019 	zone_foreach_unlocked(zone_alloc_sysctl, NULL);
3020 	callout_init(&uma_callout, 1);
3021 	callout_reset(&uma_callout, UMA_TIMEOUT * hz, uma_timeout, NULL);
3022 	booted = BOOT_RUNNING;
3023 
3024 	EVENTHANDLER_REGISTER(shutdown_post_sync, uma_shutdown, NULL,
3025 	    EVENTHANDLER_PRI_FIRST);
3026 }
3027 SYSINIT(uma_startup3, SI_SUB_VM_CONF, SI_ORDER_SECOND, uma_startup3, NULL);
3028 
3029 static void
uma_shutdown(void)3030 uma_shutdown(void)
3031 {
3032 
3033 	booted = BOOT_SHUTDOWN;
3034 }
3035 
3036 static uma_keg_t
uma_kcreate(uma_zone_t zone,size_t size,uma_init uminit,uma_fini fini,int align,uint32_t flags)3037 uma_kcreate(uma_zone_t zone, size_t size, uma_init uminit, uma_fini fini,
3038 		int align, uint32_t flags)
3039 {
3040 	struct uma_kctor_args args;
3041 
3042 	args.size = size;
3043 	args.uminit = uminit;
3044 	args.fini = fini;
3045 	args.align = (align == UMA_ALIGN_CACHE) ? uma_align_cache : align;
3046 	args.flags = flags;
3047 	args.zone = zone;
3048 	return (zone_alloc_item(kegs, &args, UMA_ANYDOMAIN, M_WAITOK));
3049 }
3050 
3051 /* Public functions */
3052 /* See uma.h */
3053 void
uma_set_align(int align)3054 uma_set_align(int align)
3055 {
3056 
3057 	if (align != UMA_ALIGN_CACHE)
3058 		uma_align_cache = align;
3059 }
3060 
3061 /* See uma.h */
3062 uma_zone_t
uma_zcreate(const char * name,size_t size,uma_ctor ctor,uma_dtor dtor,uma_init uminit,uma_fini fini,int align,uint32_t flags)3063 uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor,
3064 		uma_init uminit, uma_fini fini, int align, uint32_t flags)
3065 
3066 {
3067 	struct uma_zctor_args args;
3068 	uma_zone_t res;
3069 
3070 	KASSERT(powerof2(align + 1), ("invalid zone alignment %d for \"%s\"",
3071 	    align, name));
3072 
3073 	/* This stuff is essential for the zone ctor */
3074 	memset(&args, 0, sizeof(args));
3075 	args.name = name;
3076 	args.size = size;
3077 	args.ctor = ctor;
3078 	args.dtor = dtor;
3079 	args.uminit = uminit;
3080 	args.fini = fini;
3081 #ifdef  INVARIANTS
3082 	/*
3083 	 * Inject procedures which check for memory use after free if we are
3084 	 * allowed to scramble the memory while it is not allocated.  This
3085 	 * requires that: UMA is actually able to access the memory, no init
3086 	 * or fini procedures, no dependency on the initial value of the
3087 	 * memory, and no (legitimate) use of the memory after free.  Note,
3088 	 * the ctor and dtor do not need to be empty.
3089 	 */
3090 	if ((!(flags & (UMA_ZONE_ZINIT | UMA_ZONE_NOTOUCH |
3091 	    UMA_ZONE_NOFREE))) && uminit == NULL && fini == NULL) {
3092 		args.uminit = trash_init;
3093 		args.fini = trash_fini;
3094 	}
3095 #endif
3096 	args.align = align;
3097 	args.flags = flags;
3098 	args.keg = NULL;
3099 
3100 	sx_slock(&uma_reclaim_lock);
3101 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3102 	sx_sunlock(&uma_reclaim_lock);
3103 
3104 	return (res);
3105 }
3106 
3107 /* See uma.h */
3108 uma_zone_t
uma_zsecond_create(const char * name,uma_ctor ctor,uma_dtor dtor,uma_init zinit,uma_fini zfini,uma_zone_t primary)3109 uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor,
3110     uma_init zinit, uma_fini zfini, uma_zone_t primary)
3111 {
3112 	struct uma_zctor_args args;
3113 	uma_keg_t keg;
3114 	uma_zone_t res;
3115 
3116 	keg = primary->uz_keg;
3117 	memset(&args, 0, sizeof(args));
3118 	args.name = name;
3119 	args.size = keg->uk_size;
3120 	args.ctor = ctor;
3121 	args.dtor = dtor;
3122 	args.uminit = zinit;
3123 	args.fini = zfini;
3124 	args.align = keg->uk_align;
3125 	args.flags = keg->uk_flags | UMA_ZONE_SECONDARY;
3126 	args.keg = keg;
3127 
3128 	sx_slock(&uma_reclaim_lock);
3129 	res = zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK);
3130 	sx_sunlock(&uma_reclaim_lock);
3131 
3132 	return (res);
3133 }
3134 
3135 /* See uma.h */
3136 uma_zone_t
uma_zcache_create(const char * name,int size,uma_ctor ctor,uma_dtor dtor,uma_init zinit,uma_fini zfini,uma_import zimport,uma_release zrelease,void * arg,int flags)3137 uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor,
3138     uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease,
3139     void *arg, int flags)
3140 {
3141 	struct uma_zctor_args args;
3142 
3143 	memset(&args, 0, sizeof(args));
3144 	args.name = name;
3145 	args.size = size;
3146 	args.ctor = ctor;
3147 	args.dtor = dtor;
3148 	args.uminit = zinit;
3149 	args.fini = zfini;
3150 	args.import = zimport;
3151 	args.release = zrelease;
3152 	args.arg = arg;
3153 	args.align = 0;
3154 	args.flags = flags | UMA_ZFLAG_CACHE;
3155 
3156 	return (zone_alloc_item(zones, &args, UMA_ANYDOMAIN, M_WAITOK));
3157 }
3158 
3159 /* See uma.h */
3160 void
uma_zdestroy(uma_zone_t zone)3161 uma_zdestroy(uma_zone_t zone)
3162 {
3163 
3164 	/*
3165 	 * Large slabs are expensive to reclaim, so don't bother doing
3166 	 * unnecessary work if we're shutting down.
3167 	 */
3168 	if (booted == BOOT_SHUTDOWN &&
3169 	    zone->uz_fini == NULL && zone->uz_release == zone_release)
3170 		return;
3171 	sx_slock(&uma_reclaim_lock);
3172 	zone_free_item(zones, zone, NULL, SKIP_NONE);
3173 	sx_sunlock(&uma_reclaim_lock);
3174 }
3175 
3176 void
uma_zwait(uma_zone_t zone)3177 uma_zwait(uma_zone_t zone)
3178 {
3179 
3180 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
3181 		uma_zfree_smr(zone, uma_zalloc_smr(zone, M_WAITOK));
3182 	else if ((zone->uz_flags & UMA_ZONE_PCPU) != 0)
3183 		uma_zfree_pcpu(zone, uma_zalloc_pcpu(zone, M_WAITOK));
3184 	else
3185 		uma_zfree(zone, uma_zalloc(zone, M_WAITOK));
3186 }
3187 
3188 void *
uma_zalloc_pcpu_arg(uma_zone_t zone,void * udata,int flags)3189 uma_zalloc_pcpu_arg(uma_zone_t zone, void *udata, int flags)
3190 {
3191 	void *item, *pcpu_item;
3192 #ifdef SMP
3193 	int i;
3194 
3195 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3196 #endif
3197 	item = uma_zalloc_arg(zone, udata, flags & ~M_ZERO);
3198 	if (item == NULL)
3199 		return (NULL);
3200 	pcpu_item = zpcpu_base_to_offset(item);
3201 	if (flags & M_ZERO) {
3202 #ifdef SMP
3203 		for (i = 0; i <= mp_maxid; i++)
3204 			bzero(zpcpu_get_cpu(pcpu_item, i), zone->uz_size);
3205 #else
3206 		bzero(item, zone->uz_size);
3207 #endif
3208 	}
3209 	return (pcpu_item);
3210 }
3211 
3212 /*
3213  * A stub while both regular and pcpu cases are identical.
3214  */
3215 void
uma_zfree_pcpu_arg(uma_zone_t zone,void * pcpu_item,void * udata)3216 uma_zfree_pcpu_arg(uma_zone_t zone, void *pcpu_item, void *udata)
3217 {
3218 	void *item;
3219 
3220 #ifdef SMP
3221 	MPASS(zone->uz_flags & UMA_ZONE_PCPU);
3222 #endif
3223 	item = zpcpu_offset_to_base(pcpu_item);
3224 	uma_zfree_arg(zone, item, udata);
3225 }
3226 
3227 static inline void *
item_ctor(uma_zone_t zone,int uz_flags,int size,void * udata,int flags,void * item)3228 item_ctor(uma_zone_t zone, int uz_flags, int size, void *udata, int flags,
3229     void *item)
3230 {
3231 #ifdef INVARIANTS
3232 	bool skipdbg;
3233 
3234 	skipdbg = uma_dbg_zskip(zone, item);
3235 	if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3236 	    zone->uz_ctor != trash_ctor)
3237 		trash_ctor(item, size, udata, flags);
3238 #endif
3239 	/* Check flags before loading ctor pointer. */
3240 	if (__predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0) &&
3241 	    __predict_false(zone->uz_ctor != NULL) &&
3242 	    zone->uz_ctor(item, size, udata, flags) != 0) {
3243 		counter_u64_add(zone->uz_fails, 1);
3244 		zone_free_item(zone, item, udata, SKIP_DTOR | SKIP_CNT);
3245 		return (NULL);
3246 	}
3247 #ifdef INVARIANTS
3248 	if (!skipdbg)
3249 		uma_dbg_alloc(zone, NULL, item);
3250 #endif
3251 	if (__predict_false(flags & M_ZERO))
3252 		return (memset(item, 0, size));
3253 
3254 	return (item);
3255 }
3256 
3257 static inline void
item_dtor(uma_zone_t zone,void * item,int size,void * udata,enum zfreeskip skip)3258 item_dtor(uma_zone_t zone, void *item, int size, void *udata,
3259     enum zfreeskip skip)
3260 {
3261 #ifdef INVARIANTS
3262 	bool skipdbg;
3263 
3264 	skipdbg = uma_dbg_zskip(zone, item);
3265 	if (skip == SKIP_NONE && !skipdbg) {
3266 		if ((zone->uz_flags & UMA_ZONE_MALLOC) != 0)
3267 			uma_dbg_free(zone, udata, item);
3268 		else
3269 			uma_dbg_free(zone, NULL, item);
3270 	}
3271 #endif
3272 	if (__predict_true(skip < SKIP_DTOR)) {
3273 		if (zone->uz_dtor != NULL)
3274 			zone->uz_dtor(item, size, udata);
3275 #ifdef INVARIANTS
3276 		if (!skipdbg && (zone->uz_flags & UMA_ZFLAG_TRASH) != 0 &&
3277 		    zone->uz_dtor != trash_dtor)
3278 			trash_dtor(item, size, udata);
3279 #endif
3280 	}
3281 }
3282 
3283 #ifdef NUMA
3284 static int
item_domain(void * item)3285 item_domain(void *item)
3286 {
3287 	int domain;
3288 
3289 	domain = vm_phys_domain(vtophys(item));
3290 	KASSERT(domain >= 0 && domain < vm_ndomains,
3291 	    ("%s: unknown domain for item %p", __func__, item));
3292 	return (domain);
3293 }
3294 #endif
3295 
3296 #if defined(INVARIANTS) || defined(DEBUG_MEMGUARD) || defined(WITNESS)
3297 #define	UMA_ZALLOC_DEBUG
3298 static int
uma_zalloc_debug(uma_zone_t zone,void ** itemp,void * udata,int flags)3299 uma_zalloc_debug(uma_zone_t zone, void **itemp, void *udata, int flags)
3300 {
3301 	int error;
3302 
3303 	error = 0;
3304 #ifdef WITNESS
3305 	if (flags & M_WAITOK) {
3306 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3307 		    "uma_zalloc_debug: zone \"%s\"", zone->uz_name);
3308 	}
3309 #endif
3310 
3311 #ifdef INVARIANTS
3312 	KASSERT((flags & M_EXEC) == 0,
3313 	    ("uma_zalloc_debug: called with M_EXEC"));
3314 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3315 	    ("uma_zalloc_debug: called within spinlock or critical section"));
3316 	KASSERT((zone->uz_flags & UMA_ZONE_PCPU) == 0 || (flags & M_ZERO) == 0,
3317 	    ("uma_zalloc_debug: allocating from a pcpu zone with M_ZERO"));
3318 #endif
3319 
3320 #ifdef DEBUG_MEMGUARD
3321 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && memguard_cmp_zone(zone)) {
3322 		void *item;
3323 		item = memguard_alloc(zone->uz_size, flags);
3324 		if (item != NULL) {
3325 			error = EJUSTRETURN;
3326 			if (zone->uz_init != NULL &&
3327 			    zone->uz_init(item, zone->uz_size, flags) != 0) {
3328 				*itemp = NULL;
3329 				return (error);
3330 			}
3331 			if (zone->uz_ctor != NULL &&
3332 			    zone->uz_ctor(item, zone->uz_size, udata,
3333 			    flags) != 0) {
3334 				counter_u64_add(zone->uz_fails, 1);
3335 			    	zone->uz_fini(item, zone->uz_size);
3336 				*itemp = NULL;
3337 				return (error);
3338 			}
3339 			*itemp = item;
3340 			return (error);
3341 		}
3342 		/* This is unfortunate but should not be fatal. */
3343 	}
3344 #endif
3345 	return (error);
3346 }
3347 
3348 static int
uma_zfree_debug(uma_zone_t zone,void * item,void * udata)3349 uma_zfree_debug(uma_zone_t zone, void *item, void *udata)
3350 {
3351 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3352 	    ("uma_zfree_debug: called with spinlock or critical section held"));
3353 
3354 #ifdef DEBUG_MEMGUARD
3355 	if ((zone->uz_flags & UMA_ZONE_SMR) == 0 && is_memguard_addr(item)) {
3356 		if (zone->uz_dtor != NULL)
3357 			zone->uz_dtor(item, zone->uz_size, udata);
3358 		if (zone->uz_fini != NULL)
3359 			zone->uz_fini(item, zone->uz_size);
3360 		memguard_free(item);
3361 		return (EJUSTRETURN);
3362 	}
3363 #endif
3364 	return (0);
3365 }
3366 #endif
3367 
3368 static inline void *
cache_alloc_item(uma_zone_t zone,uma_cache_t cache,uma_cache_bucket_t bucket,void * udata,int flags)3369 cache_alloc_item(uma_zone_t zone, uma_cache_t cache, uma_cache_bucket_t bucket,
3370     void *udata, int flags)
3371 {
3372 	void *item;
3373 	int size, uz_flags;
3374 
3375 	item = cache_bucket_pop(cache, bucket);
3376 	size = cache_uz_size(cache);
3377 	uz_flags = cache_uz_flags(cache);
3378 	critical_exit();
3379 	return (item_ctor(zone, uz_flags, size, udata, flags, item));
3380 }
3381 
3382 static __noinline void *
cache_alloc_retry(uma_zone_t zone,uma_cache_t cache,void * udata,int flags)3383 cache_alloc_retry(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3384 {
3385 	uma_cache_bucket_t bucket;
3386 	int domain;
3387 
3388 	while (cache_alloc(zone, cache, udata, flags)) {
3389 		cache = &zone->uz_cpu[curcpu];
3390 		bucket = &cache->uc_allocbucket;
3391 		if (__predict_false(bucket->ucb_cnt == 0))
3392 			continue;
3393 		return (cache_alloc_item(zone, cache, bucket, udata, flags));
3394 	}
3395 	critical_exit();
3396 
3397 	/*
3398 	 * We can not get a bucket so try to return a single item.
3399 	 */
3400 	if (zone->uz_flags & UMA_ZONE_FIRSTTOUCH)
3401 		domain = PCPU_GET(domain);
3402 	else
3403 		domain = UMA_ANYDOMAIN;
3404 	return (zone_alloc_item(zone, udata, domain, flags));
3405 }
3406 
3407 /* See uma.h */
3408 void *
uma_zalloc_smr(uma_zone_t zone,int flags)3409 uma_zalloc_smr(uma_zone_t zone, int flags)
3410 {
3411 	uma_cache_bucket_t bucket;
3412 	uma_cache_t cache;
3413 
3414 #ifdef UMA_ZALLOC_DEBUG
3415 	void *item;
3416 
3417 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
3418 	    ("uma_zalloc_arg: called with non-SMR zone."));
3419 	if (uma_zalloc_debug(zone, &item, NULL, flags) == EJUSTRETURN)
3420 		return (item);
3421 #endif
3422 
3423 	critical_enter();
3424 	cache = &zone->uz_cpu[curcpu];
3425 	bucket = &cache->uc_allocbucket;
3426 	if (__predict_false(bucket->ucb_cnt == 0))
3427 		return (cache_alloc_retry(zone, cache, NULL, flags));
3428 	return (cache_alloc_item(zone, cache, bucket, NULL, flags));
3429 }
3430 
3431 /* See uma.h */
3432 void *
uma_zalloc_arg(uma_zone_t zone,void * udata,int flags)3433 uma_zalloc_arg(uma_zone_t zone, void *udata, int flags)
3434 {
3435 	uma_cache_bucket_t bucket;
3436 	uma_cache_t cache;
3437 
3438 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3439 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3440 
3441 	/* This is the fast path allocation */
3442 	CTR3(KTR_UMA, "uma_zalloc_arg zone %s(%p) flags %d", zone->uz_name,
3443 	    zone, flags);
3444 
3445 #ifdef UMA_ZALLOC_DEBUG
3446 	void *item;
3447 
3448 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3449 	    ("uma_zalloc_arg: called with SMR zone."));
3450 	if (uma_zalloc_debug(zone, &item, udata, flags) == EJUSTRETURN)
3451 		return (item);
3452 #endif
3453 
3454 	/*
3455 	 * If possible, allocate from the per-CPU cache.  There are two
3456 	 * requirements for safe access to the per-CPU cache: (1) the thread
3457 	 * accessing the cache must not be preempted or yield during access,
3458 	 * and (2) the thread must not migrate CPUs without switching which
3459 	 * cache it accesses.  We rely on a critical section to prevent
3460 	 * preemption and migration.  We release the critical section in
3461 	 * order to acquire the zone mutex if we are unable to allocate from
3462 	 * the current cache; when we re-acquire the critical section, we
3463 	 * must detect and handle migration if it has occurred.
3464 	 */
3465 	critical_enter();
3466 	cache = &zone->uz_cpu[curcpu];
3467 	bucket = &cache->uc_allocbucket;
3468 	if (__predict_false(bucket->ucb_cnt == 0))
3469 		return (cache_alloc_retry(zone, cache, udata, flags));
3470 	return (cache_alloc_item(zone, cache, bucket, udata, flags));
3471 }
3472 
3473 /*
3474  * Replenish an alloc bucket and possibly restore an old one.  Called in
3475  * a critical section.  Returns in a critical section.
3476  *
3477  * A false return value indicates an allocation failure.
3478  * A true return value indicates success and the caller should retry.
3479  */
3480 static __noinline bool
cache_alloc(uma_zone_t zone,uma_cache_t cache,void * udata,int flags)3481 cache_alloc(uma_zone_t zone, uma_cache_t cache, void *udata, int flags)
3482 {
3483 	uma_bucket_t bucket;
3484 	int curdomain, domain;
3485 	bool new;
3486 
3487 	CRITICAL_ASSERT(curthread);
3488 
3489 	/*
3490 	 * If we have run out of items in our alloc bucket see
3491 	 * if we can switch with the free bucket.
3492 	 *
3493 	 * SMR Zones can't re-use the free bucket until the sequence has
3494 	 * expired.
3495 	 */
3496 	if ((cache_uz_flags(cache) & UMA_ZONE_SMR) == 0 &&
3497 	    cache->uc_freebucket.ucb_cnt != 0) {
3498 		cache_bucket_swap(&cache->uc_freebucket,
3499 		    &cache->uc_allocbucket);
3500 		return (true);
3501 	}
3502 
3503 	/*
3504 	 * Discard any empty allocation bucket while we hold no locks.
3505 	 */
3506 	bucket = cache_bucket_unload_alloc(cache);
3507 	critical_exit();
3508 
3509 	if (bucket != NULL) {
3510 		KASSERT(bucket->ub_cnt == 0,
3511 		    ("cache_alloc: Entered with non-empty alloc bucket."));
3512 		bucket_free(zone, bucket, udata);
3513 	}
3514 
3515 	/*
3516 	 * Attempt to retrieve the item from the per-CPU cache has failed, so
3517 	 * we must go back to the zone.  This requires the zdom lock, so we
3518 	 * must drop the critical section, then re-acquire it when we go back
3519 	 * to the cache.  Since the critical section is released, we may be
3520 	 * preempted or migrate.  As such, make sure not to maintain any
3521 	 * thread-local state specific to the cache from prior to releasing
3522 	 * the critical section.
3523 	 */
3524 	domain = PCPU_GET(domain);
3525 	if ((cache_uz_flags(cache) & UMA_ZONE_ROUNDROBIN) != 0 ||
3526 	    VM_DOMAIN_EMPTY(domain))
3527 		domain = zone_domain_highest(zone, domain);
3528 	bucket = cache_fetch_bucket(zone, cache, domain);
3529 	if (bucket == NULL && zone->uz_bucket_size != 0 && !bucketdisable) {
3530 		bucket = zone_alloc_bucket(zone, udata, domain, flags);
3531 		new = true;
3532 	} else {
3533 		new = false;
3534 	}
3535 
3536 	CTR3(KTR_UMA, "uma_zalloc: zone %s(%p) bucket zone returned %p",
3537 	    zone->uz_name, zone, bucket);
3538 	if (bucket == NULL) {
3539 		critical_enter();
3540 		return (false);
3541 	}
3542 
3543 	/*
3544 	 * See if we lost the race or were migrated.  Cache the
3545 	 * initialized bucket to make this less likely or claim
3546 	 * the memory directly.
3547 	 */
3548 	critical_enter();
3549 	cache = &zone->uz_cpu[curcpu];
3550 	if (cache->uc_allocbucket.ucb_bucket == NULL &&
3551 	    ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) == 0 ||
3552 	    (curdomain = PCPU_GET(domain)) == domain ||
3553 	    VM_DOMAIN_EMPTY(curdomain))) {
3554 		if (new)
3555 			atomic_add_long(&ZDOM_GET(zone, domain)->uzd_imax,
3556 			    bucket->ub_cnt);
3557 		cache_bucket_load_alloc(cache, bucket);
3558 		return (true);
3559 	}
3560 
3561 	/*
3562 	 * We lost the race, release this bucket and start over.
3563 	 */
3564 	critical_exit();
3565 	zone_put_bucket(zone, domain, bucket, udata, false);
3566 	critical_enter();
3567 
3568 	return (true);
3569 }
3570 
3571 void *
uma_zalloc_domain(uma_zone_t zone,void * udata,int domain,int flags)3572 uma_zalloc_domain(uma_zone_t zone, void *udata, int domain, int flags)
3573 {
3574 #ifdef NUMA
3575 	uma_bucket_t bucket;
3576 	uma_zone_domain_t zdom;
3577 	void *item;
3578 #endif
3579 
3580 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
3581 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
3582 
3583 	/* This is the fast path allocation */
3584 	CTR4(KTR_UMA, "uma_zalloc_domain zone %s(%p) domain %d flags %d",
3585 	    zone->uz_name, zone, domain, flags);
3586 
3587 	if (flags & M_WAITOK) {
3588 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
3589 		    "uma_zalloc_domain: zone \"%s\"", zone->uz_name);
3590 	}
3591 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
3592 	    ("uma_zalloc_domain: called with spinlock or critical section held"));
3593 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
3594 	    ("uma_zalloc_domain: called with SMR zone."));
3595 #ifdef NUMA
3596 	KASSERT((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0,
3597 	    ("uma_zalloc_domain: called with non-FIRSTTOUCH zone."));
3598 
3599 	if (vm_ndomains == 1)
3600 		return (uma_zalloc_arg(zone, udata, flags));
3601 
3602 	/*
3603 	 * Try to allocate from the bucket cache before falling back to the keg.
3604 	 * We could try harder and attempt to allocate from per-CPU caches or
3605 	 * the per-domain cross-domain buckets, but the complexity is probably
3606 	 * not worth it.  It is more important that frees of previous
3607 	 * cross-domain allocations do not blow up the cache.
3608 	 */
3609 	zdom = zone_domain_lock(zone, domain);
3610 	if ((bucket = zone_fetch_bucket(zone, zdom, false)) != NULL) {
3611 		item = bucket->ub_bucket[bucket->ub_cnt - 1];
3612 #ifdef INVARIANTS
3613 		bucket->ub_bucket[bucket->ub_cnt - 1] = NULL;
3614 #endif
3615 		bucket->ub_cnt--;
3616 		zone_put_bucket(zone, domain, bucket, udata, true);
3617 		item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata,
3618 		    flags, item);
3619 		if (item != NULL) {
3620 			KASSERT(item_domain(item) == domain,
3621 			    ("%s: bucket cache item %p from wrong domain",
3622 			    __func__, item));
3623 			counter_u64_add(zone->uz_allocs, 1);
3624 		}
3625 		return (item);
3626 	}
3627 	ZDOM_UNLOCK(zdom);
3628 	return (zone_alloc_item(zone, udata, domain, flags));
3629 #else
3630 	return (uma_zalloc_arg(zone, udata, flags));
3631 #endif
3632 }
3633 
3634 /*
3635  * Find a slab with some space.  Prefer slabs that are partially used over those
3636  * that are totally full.  This helps to reduce fragmentation.
3637  *
3638  * If 'rr' is 1, search all domains starting from 'domain'.  Otherwise check
3639  * only 'domain'.
3640  */
3641 static uma_slab_t
keg_first_slab(uma_keg_t keg,int domain,bool rr)3642 keg_first_slab(uma_keg_t keg, int domain, bool rr)
3643 {
3644 	uma_domain_t dom;
3645 	uma_slab_t slab;
3646 	int start;
3647 
3648 	KASSERT(domain >= 0 && domain < vm_ndomains,
3649 	    ("keg_first_slab: domain %d out of range", domain));
3650 	KEG_LOCK_ASSERT(keg, domain);
3651 
3652 	slab = NULL;
3653 	start = domain;
3654 	do {
3655 		dom = &keg->uk_domain[domain];
3656 		if ((slab = LIST_FIRST(&dom->ud_part_slab)) != NULL)
3657 			return (slab);
3658 		if ((slab = LIST_FIRST(&dom->ud_free_slab)) != NULL) {
3659 			LIST_REMOVE(slab, us_link);
3660 			dom->ud_free_slabs--;
3661 			LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
3662 			return (slab);
3663 		}
3664 		if (rr)
3665 			domain = (domain + 1) % vm_ndomains;
3666 	} while (domain != start);
3667 
3668 	return (NULL);
3669 }
3670 
3671 /*
3672  * Fetch an existing slab from a free or partial list.  Returns with the
3673  * keg domain lock held if a slab was found or unlocked if not.
3674  */
3675 static uma_slab_t
keg_fetch_free_slab(uma_keg_t keg,int domain,bool rr,int flags)3676 keg_fetch_free_slab(uma_keg_t keg, int domain, bool rr, int flags)
3677 {
3678 	uma_slab_t slab;
3679 	uint32_t reserve;
3680 
3681 	/* HASH has a single free list. */
3682 	if ((keg->uk_flags & UMA_ZFLAG_HASH) != 0)
3683 		domain = 0;
3684 
3685 	KEG_LOCK(keg, domain);
3686 	reserve = (flags & M_USE_RESERVE) != 0 ? 0 : keg->uk_reserve;
3687 	if (keg->uk_domain[domain].ud_free_items <= reserve ||
3688 	    (slab = keg_first_slab(keg, domain, rr)) == NULL) {
3689 		KEG_UNLOCK(keg, domain);
3690 		return (NULL);
3691 	}
3692 	return (slab);
3693 }
3694 
3695 static uma_slab_t
keg_fetch_slab(uma_keg_t keg,uma_zone_t zone,int rdomain,const int flags)3696 keg_fetch_slab(uma_keg_t keg, uma_zone_t zone, int rdomain, const int flags)
3697 {
3698 	struct vm_domainset_iter di;
3699 	uma_slab_t slab;
3700 	int aflags, domain;
3701 	bool rr;
3702 
3703 restart:
3704 	/*
3705 	 * Use the keg's policy if upper layers haven't already specified a
3706 	 * domain (as happens with first-touch zones).
3707 	 *
3708 	 * To avoid races we run the iterator with the keg lock held, but that
3709 	 * means that we cannot allow the vm_domainset layer to sleep.  Thus,
3710 	 * clear M_WAITOK and handle low memory conditions locally.
3711 	 */
3712 	rr = rdomain == UMA_ANYDOMAIN;
3713 	if (rr) {
3714 		aflags = (flags & ~M_WAITOK) | M_NOWAIT;
3715 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
3716 		    &aflags);
3717 	} else {
3718 		aflags = flags;
3719 		domain = rdomain;
3720 	}
3721 
3722 	for (;;) {
3723 		slab = keg_fetch_free_slab(keg, domain, rr, flags);
3724 		if (slab != NULL)
3725 			return (slab);
3726 
3727 		/*
3728 		 * M_NOVM means don't ask at all!
3729 		 */
3730 		if (flags & M_NOVM)
3731 			break;
3732 
3733 		slab = keg_alloc_slab(keg, zone, domain, flags, aflags);
3734 		if (slab != NULL)
3735 			return (slab);
3736 		if (!rr && (flags & M_WAITOK) == 0)
3737 			break;
3738 		if (rr && vm_domainset_iter_policy(&di, &domain) != 0) {
3739 			if ((flags & M_WAITOK) != 0) {
3740 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
3741 				goto restart;
3742 			}
3743 			break;
3744 		}
3745 	}
3746 
3747 	/*
3748 	 * We might not have been able to get a slab but another cpu
3749 	 * could have while we were unlocked.  Check again before we
3750 	 * fail.
3751 	 */
3752 	if ((slab = keg_fetch_free_slab(keg, domain, rr, flags)) != NULL)
3753 		return (slab);
3754 
3755 	return (NULL);
3756 }
3757 
3758 static void *
slab_alloc_item(uma_keg_t keg,uma_slab_t slab)3759 slab_alloc_item(uma_keg_t keg, uma_slab_t slab)
3760 {
3761 	uma_domain_t dom;
3762 	void *item;
3763 	int freei;
3764 
3765 	KEG_LOCK_ASSERT(keg, slab->us_domain);
3766 
3767 	dom = &keg->uk_domain[slab->us_domain];
3768 	freei = BIT_FFS(keg->uk_ipers, &slab->us_free) - 1;
3769 	BIT_CLR(keg->uk_ipers, freei, &slab->us_free);
3770 	item = slab_item(slab, keg, freei);
3771 	slab->us_freecount--;
3772 	dom->ud_free_items--;
3773 
3774 	/*
3775 	 * Move this slab to the full list.  It must be on the partial list, so
3776 	 * we do not need to update the free slab count.  In particular,
3777 	 * keg_fetch_slab() always returns slabs on the partial list.
3778 	 */
3779 	if (slab->us_freecount == 0) {
3780 		LIST_REMOVE(slab, us_link);
3781 		LIST_INSERT_HEAD(&dom->ud_full_slab, slab, us_link);
3782 	}
3783 
3784 	return (item);
3785 }
3786 
3787 static int
zone_import(void * arg,void ** bucket,int max,int domain,int flags)3788 zone_import(void *arg, void **bucket, int max, int domain, int flags)
3789 {
3790 	uma_domain_t dom;
3791 	uma_zone_t zone;
3792 	uma_slab_t slab;
3793 	uma_keg_t keg;
3794 #ifdef NUMA
3795 	int stripe;
3796 #endif
3797 	int i;
3798 
3799 	zone = arg;
3800 	slab = NULL;
3801 	keg = zone->uz_keg;
3802 	/* Try to keep the buckets totally full */
3803 	for (i = 0; i < max; ) {
3804 		if ((slab = keg_fetch_slab(keg, zone, domain, flags)) == NULL)
3805 			break;
3806 #ifdef NUMA
3807 		stripe = howmany(max, vm_ndomains);
3808 #endif
3809 		dom = &keg->uk_domain[slab->us_domain];
3810 		do {
3811 			bucket[i++] = slab_alloc_item(keg, slab);
3812 			if (dom->ud_free_items <= keg->uk_reserve) {
3813 				/*
3814 				 * Avoid depleting the reserve after a
3815 				 * successful item allocation, even if
3816 				 * M_USE_RESERVE is specified.
3817 				 */
3818 				KEG_UNLOCK(keg, slab->us_domain);
3819 				goto out;
3820 			}
3821 #ifdef NUMA
3822 			/*
3823 			 * If the zone is striped we pick a new slab for every
3824 			 * N allocations.  Eliminating this conditional will
3825 			 * instead pick a new domain for each bucket rather
3826 			 * than stripe within each bucket.  The current option
3827 			 * produces more fragmentation and requires more cpu
3828 			 * time but yields better distribution.
3829 			 */
3830 			if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0 &&
3831 			    vm_ndomains > 1 && --stripe == 0)
3832 				break;
3833 #endif
3834 		} while (slab->us_freecount != 0 && i < max);
3835 		KEG_UNLOCK(keg, slab->us_domain);
3836 
3837 		/* Don't block if we allocated any successfully. */
3838 		flags &= ~M_WAITOK;
3839 		flags |= M_NOWAIT;
3840 	}
3841 out:
3842 	return i;
3843 }
3844 
3845 static int
zone_alloc_limit_hard(uma_zone_t zone,int count,int flags)3846 zone_alloc_limit_hard(uma_zone_t zone, int count, int flags)
3847 {
3848 	uint64_t old, new, total, max;
3849 
3850 	/*
3851 	 * The hard case.  We're going to sleep because there were existing
3852 	 * sleepers or because we ran out of items.  This routine enforces
3853 	 * fairness by keeping fifo order.
3854 	 *
3855 	 * First release our ill gotten gains and make some noise.
3856 	 */
3857 	for (;;) {
3858 		zone_free_limit(zone, count);
3859 		zone_log_warning(zone);
3860 		zone_maxaction(zone);
3861 		if (flags & M_NOWAIT)
3862 			return (0);
3863 
3864 		/*
3865 		 * We need to allocate an item or set ourself as a sleeper
3866 		 * while the sleepq lock is held to avoid wakeup races.  This
3867 		 * is essentially a home rolled semaphore.
3868 		 */
3869 		sleepq_lock(&zone->uz_max_items);
3870 		old = zone->uz_items;
3871 		do {
3872 			MPASS(UZ_ITEMS_SLEEPERS(old) < UZ_ITEMS_SLEEPERS_MAX);
3873 			/* Cache the max since we will evaluate twice. */
3874 			max = zone->uz_max_items;
3875 			if (UZ_ITEMS_SLEEPERS(old) != 0 ||
3876 			    UZ_ITEMS_COUNT(old) >= max)
3877 				new = old + UZ_ITEMS_SLEEPER;
3878 			else
3879 				new = old + MIN(count, max - old);
3880 		} while (atomic_fcmpset_64(&zone->uz_items, &old, new) == 0);
3881 
3882 		/* We may have successfully allocated under the sleepq lock. */
3883 		if (UZ_ITEMS_SLEEPERS(new) == 0) {
3884 			sleepq_release(&zone->uz_max_items);
3885 			return (new - old);
3886 		}
3887 
3888 		/*
3889 		 * This is in a different cacheline from uz_items so that we
3890 		 * don't constantly invalidate the fastpath cacheline when we
3891 		 * adjust item counts.  This could be limited to toggling on
3892 		 * transitions.
3893 		 */
3894 		atomic_add_32(&zone->uz_sleepers, 1);
3895 		atomic_add_64(&zone->uz_sleeps, 1);
3896 
3897 		/*
3898 		 * We have added ourselves as a sleeper.  The sleepq lock
3899 		 * protects us from wakeup races.  Sleep now and then retry.
3900 		 */
3901 		sleepq_add(&zone->uz_max_items, NULL, "zonelimit", 0, 0);
3902 		sleepq_wait(&zone->uz_max_items, PVM);
3903 
3904 		/*
3905 		 * After wakeup, remove ourselves as a sleeper and try
3906 		 * again.  We no longer have the sleepq lock for protection.
3907 		 *
3908 		 * Subract ourselves as a sleeper while attempting to add
3909 		 * our count.
3910 		 */
3911 		atomic_subtract_32(&zone->uz_sleepers, 1);
3912 		old = atomic_fetchadd_64(&zone->uz_items,
3913 		    -(UZ_ITEMS_SLEEPER - count));
3914 		/* We're no longer a sleeper. */
3915 		old -= UZ_ITEMS_SLEEPER;
3916 
3917 		/*
3918 		 * If we're still at the limit, restart.  Notably do not
3919 		 * block on other sleepers.  Cache the max value to protect
3920 		 * against changes via sysctl.
3921 		 */
3922 		total = UZ_ITEMS_COUNT(old);
3923 		max = zone->uz_max_items;
3924 		if (total >= max)
3925 			continue;
3926 		/* Truncate if necessary, otherwise wake other sleepers. */
3927 		if (total + count > max) {
3928 			zone_free_limit(zone, total + count - max);
3929 			count = max - total;
3930 		} else if (total + count < max && UZ_ITEMS_SLEEPERS(old) != 0)
3931 			wakeup_one(&zone->uz_max_items);
3932 
3933 		return (count);
3934 	}
3935 }
3936 
3937 /*
3938  * Allocate 'count' items from our max_items limit.  Returns the number
3939  * available.  If M_NOWAIT is not specified it will sleep until at least
3940  * one item can be allocated.
3941  */
3942 static int
zone_alloc_limit(uma_zone_t zone,int count,int flags)3943 zone_alloc_limit(uma_zone_t zone, int count, int flags)
3944 {
3945 	uint64_t old;
3946 	uint64_t max;
3947 
3948 	max = zone->uz_max_items;
3949 	MPASS(max > 0);
3950 
3951 	/*
3952 	 * We expect normal allocations to succeed with a simple
3953 	 * fetchadd.
3954 	 */
3955 	old = atomic_fetchadd_64(&zone->uz_items, count);
3956 	if (__predict_true(old + count <= max))
3957 		return (count);
3958 
3959 	/*
3960 	 * If we had some items and no sleepers just return the
3961 	 * truncated value.  We have to release the excess space
3962 	 * though because that may wake sleepers who weren't woken
3963 	 * because we were temporarily over the limit.
3964 	 */
3965 	if (old < max) {
3966 		zone_free_limit(zone, (old + count) - max);
3967 		return (max - old);
3968 	}
3969 	return (zone_alloc_limit_hard(zone, count, flags));
3970 }
3971 
3972 /*
3973  * Free a number of items back to the limit.
3974  */
3975 static void
zone_free_limit(uma_zone_t zone,int count)3976 zone_free_limit(uma_zone_t zone, int count)
3977 {
3978 	uint64_t old;
3979 
3980 	MPASS(count > 0);
3981 
3982 	/*
3983 	 * In the common case we either have no sleepers or
3984 	 * are still over the limit and can just return.
3985 	 */
3986 	old = atomic_fetchadd_64(&zone->uz_items, -count);
3987 	if (__predict_true(UZ_ITEMS_SLEEPERS(old) == 0 ||
3988 	   UZ_ITEMS_COUNT(old) - count >= zone->uz_max_items))
3989 		return;
3990 
3991 	/*
3992 	 * Moderate the rate of wakeups.  Sleepers will continue
3993 	 * to generate wakeups if necessary.
3994 	 */
3995 	wakeup_one(&zone->uz_max_items);
3996 }
3997 
3998 static uma_bucket_t
zone_alloc_bucket(uma_zone_t zone,void * udata,int domain,int flags)3999 zone_alloc_bucket(uma_zone_t zone, void *udata, int domain, int flags)
4000 {
4001 	uma_bucket_t bucket;
4002 	int maxbucket, cnt;
4003 
4004 	CTR3(KTR_UMA, "zone_alloc_bucket zone %s(%p) domain %d", zone->uz_name,
4005 	    zone, domain);
4006 
4007 	/* Avoid allocs targeting empty domains. */
4008 	if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4009 		domain = UMA_ANYDOMAIN;
4010 	else if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4011 		domain = UMA_ANYDOMAIN;
4012 
4013 	if (zone->uz_max_items > 0)
4014 		maxbucket = zone_alloc_limit(zone, zone->uz_bucket_size,
4015 		    M_NOWAIT);
4016 	else
4017 		maxbucket = zone->uz_bucket_size;
4018 	if (maxbucket == 0)
4019 		return (false);
4020 
4021 	/* Don't wait for buckets, preserve caller's NOVM setting. */
4022 	bucket = bucket_alloc(zone, udata, M_NOWAIT | (flags & M_NOVM));
4023 	if (bucket == NULL) {
4024 		cnt = 0;
4025 		goto out;
4026 	}
4027 
4028 	bucket->ub_cnt = zone->uz_import(zone->uz_arg, bucket->ub_bucket,
4029 	    MIN(maxbucket, bucket->ub_entries), domain, flags);
4030 
4031 	/*
4032 	 * Initialize the memory if necessary.
4033 	 */
4034 	if (bucket->ub_cnt != 0 && zone->uz_init != NULL) {
4035 		int i;
4036 
4037 		for (i = 0; i < bucket->ub_cnt; i++)
4038 			if (zone->uz_init(bucket->ub_bucket[i], zone->uz_size,
4039 			    flags) != 0)
4040 				break;
4041 		/*
4042 		 * If we couldn't initialize the whole bucket, put the
4043 		 * rest back onto the freelist.
4044 		 */
4045 		if (i != bucket->ub_cnt) {
4046 			zone->uz_release(zone->uz_arg, &bucket->ub_bucket[i],
4047 			    bucket->ub_cnt - i);
4048 #ifdef INVARIANTS
4049 			bzero(&bucket->ub_bucket[i],
4050 			    sizeof(void *) * (bucket->ub_cnt - i));
4051 #endif
4052 			bucket->ub_cnt = i;
4053 		}
4054 	}
4055 
4056 	cnt = bucket->ub_cnt;
4057 	if (bucket->ub_cnt == 0) {
4058 		bucket_free(zone, bucket, udata);
4059 		counter_u64_add(zone->uz_fails, 1);
4060 		bucket = NULL;
4061 	}
4062 out:
4063 	if (zone->uz_max_items > 0 && cnt < maxbucket)
4064 		zone_free_limit(zone, maxbucket - cnt);
4065 
4066 	return (bucket);
4067 }
4068 
4069 /*
4070  * Allocates a single item from a zone.
4071  *
4072  * Arguments
4073  *	zone   The zone to alloc for.
4074  *	udata  The data to be passed to the constructor.
4075  *	domain The domain to allocate from or UMA_ANYDOMAIN.
4076  *	flags  M_WAITOK, M_NOWAIT, M_ZERO.
4077  *
4078  * Returns
4079  *	NULL if there is no memory and M_NOWAIT is set
4080  *	An item if successful
4081  */
4082 
4083 static void *
zone_alloc_item(uma_zone_t zone,void * udata,int domain,int flags)4084 zone_alloc_item(uma_zone_t zone, void *udata, int domain, int flags)
4085 {
4086 	void *item;
4087 
4088 	if (zone->uz_max_items > 0 && zone_alloc_limit(zone, 1, flags) == 0) {
4089 		counter_u64_add(zone->uz_fails, 1);
4090 		return (NULL);
4091 	}
4092 
4093 	/* Avoid allocs targeting empty domains. */
4094 	if (domain != UMA_ANYDOMAIN && VM_DOMAIN_EMPTY(domain))
4095 		domain = UMA_ANYDOMAIN;
4096 
4097 	if (zone->uz_import(zone->uz_arg, &item, 1, domain, flags) != 1)
4098 		goto fail_cnt;
4099 
4100 	/*
4101 	 * We have to call both the zone's init (not the keg's init)
4102 	 * and the zone's ctor.  This is because the item is going from
4103 	 * a keg slab directly to the user, and the user is expecting it
4104 	 * to be both zone-init'd as well as zone-ctor'd.
4105 	 */
4106 	if (zone->uz_init != NULL) {
4107 		if (zone->uz_init(item, zone->uz_size, flags) != 0) {
4108 			zone_free_item(zone, item, udata, SKIP_FINI | SKIP_CNT);
4109 			goto fail_cnt;
4110 		}
4111 	}
4112 	item = item_ctor(zone, zone->uz_flags, zone->uz_size, udata, flags,
4113 	    item);
4114 	if (item == NULL)
4115 		goto fail;
4116 
4117 	counter_u64_add(zone->uz_allocs, 1);
4118 	CTR3(KTR_UMA, "zone_alloc_item item %p from %s(%p)", item,
4119 	    zone->uz_name, zone);
4120 
4121 	return (item);
4122 
4123 fail_cnt:
4124 	counter_u64_add(zone->uz_fails, 1);
4125 fail:
4126 	if (zone->uz_max_items > 0)
4127 		zone_free_limit(zone, 1);
4128 	CTR2(KTR_UMA, "zone_alloc_item failed from %s(%p)",
4129 	    zone->uz_name, zone);
4130 
4131 	return (NULL);
4132 }
4133 
4134 /* See uma.h */
4135 void
uma_zfree_smr(uma_zone_t zone,void * item)4136 uma_zfree_smr(uma_zone_t zone, void *item)
4137 {
4138 	uma_cache_t cache;
4139 	uma_cache_bucket_t bucket;
4140 	int itemdomain, uz_flags;
4141 
4142 #ifdef UMA_ZALLOC_DEBUG
4143 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) != 0,
4144 	    ("uma_zfree_smr: called with non-SMR zone."));
4145 	KASSERT(item != NULL, ("uma_zfree_smr: Called with NULL pointer."));
4146 	SMR_ASSERT_NOT_ENTERED(zone->uz_smr);
4147 	if (uma_zfree_debug(zone, item, NULL) == EJUSTRETURN)
4148 		return;
4149 #endif
4150 	cache = &zone->uz_cpu[curcpu];
4151 	uz_flags = cache_uz_flags(cache);
4152 	itemdomain = 0;
4153 #ifdef NUMA
4154 	if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4155 		itemdomain = item_domain(item);
4156 #endif
4157 	critical_enter();
4158 	do {
4159 		cache = &zone->uz_cpu[curcpu];
4160 		/* SMR Zones must free to the free bucket. */
4161 		bucket = &cache->uc_freebucket;
4162 #ifdef NUMA
4163 		if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4164 		    PCPU_GET(domain) != itemdomain) {
4165 			bucket = &cache->uc_crossbucket;
4166 		}
4167 #endif
4168 		if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4169 			cache_bucket_push(cache, bucket, item);
4170 			critical_exit();
4171 			return;
4172 		}
4173 	} while (cache_free(zone, cache, NULL, item, itemdomain));
4174 	critical_exit();
4175 
4176 	/*
4177 	 * If nothing else caught this, we'll just do an internal free.
4178 	 */
4179 	zone_free_item(zone, item, NULL, SKIP_NONE);
4180 }
4181 
4182 /* See uma.h */
4183 void
uma_zfree_arg(uma_zone_t zone,void * item,void * udata)4184 uma_zfree_arg(uma_zone_t zone, void *item, void *udata)
4185 {
4186 	uma_cache_t cache;
4187 	uma_cache_bucket_t bucket;
4188 	int itemdomain, uz_flags;
4189 
4190 	/* Enable entropy collection for RANDOM_ENABLE_UMA kernel option */
4191 	random_harvest_fast_uma(&zone, sizeof(zone), RANDOM_UMA);
4192 
4193 	CTR2(KTR_UMA, "uma_zfree_arg zone %s(%p)", zone->uz_name, zone);
4194 
4195 #ifdef UMA_ZALLOC_DEBUG
4196 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4197 	    ("uma_zfree_arg: called with SMR zone."));
4198 	if (uma_zfree_debug(zone, item, udata) == EJUSTRETURN)
4199 		return;
4200 #endif
4201         /* uma_zfree(..., NULL) does nothing, to match free(9). */
4202         if (item == NULL)
4203                 return;
4204 
4205 	/*
4206 	 * We are accessing the per-cpu cache without a critical section to
4207 	 * fetch size and flags.  This is acceptable, if we are preempted we
4208 	 * will simply read another cpu's line.
4209 	 */
4210 	cache = &zone->uz_cpu[curcpu];
4211 	uz_flags = cache_uz_flags(cache);
4212 	if (UMA_ALWAYS_CTORDTOR ||
4213 	    __predict_false((uz_flags & UMA_ZFLAG_CTORDTOR) != 0))
4214 		item_dtor(zone, item, cache_uz_size(cache), udata, SKIP_NONE);
4215 
4216 	/*
4217 	 * The race here is acceptable.  If we miss it we'll just have to wait
4218 	 * a little longer for the limits to be reset.
4219 	 */
4220 	if (__predict_false(uz_flags & UMA_ZFLAG_LIMIT)) {
4221 		if (atomic_load_32(&zone->uz_sleepers) > 0)
4222 			goto zfree_item;
4223 	}
4224 
4225 	/*
4226 	 * If possible, free to the per-CPU cache.  There are two
4227 	 * requirements for safe access to the per-CPU cache: (1) the thread
4228 	 * accessing the cache must not be preempted or yield during access,
4229 	 * and (2) the thread must not migrate CPUs without switching which
4230 	 * cache it accesses.  We rely on a critical section to prevent
4231 	 * preemption and migration.  We release the critical section in
4232 	 * order to acquire the zone mutex if we are unable to free to the
4233 	 * current cache; when we re-acquire the critical section, we must
4234 	 * detect and handle migration if it has occurred.
4235 	 */
4236 	itemdomain = 0;
4237 #ifdef NUMA
4238 	if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0)
4239 		itemdomain = item_domain(item);
4240 #endif
4241 	critical_enter();
4242 	do {
4243 		cache = &zone->uz_cpu[curcpu];
4244 		/*
4245 		 * Try to free into the allocbucket first to give LIFO
4246 		 * ordering for cache-hot datastructures.  Spill over
4247 		 * into the freebucket if necessary.  Alloc will swap
4248 		 * them if one runs dry.
4249 		 */
4250 		bucket = &cache->uc_allocbucket;
4251 #ifdef NUMA
4252 		if ((uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4253 		    PCPU_GET(domain) != itemdomain) {
4254 			bucket = &cache->uc_crossbucket;
4255 		} else
4256 #endif
4257 		if (bucket->ucb_cnt == bucket->ucb_entries &&
4258 		   cache->uc_freebucket.ucb_cnt <
4259 		   cache->uc_freebucket.ucb_entries)
4260 			cache_bucket_swap(&cache->uc_freebucket,
4261 			    &cache->uc_allocbucket);
4262 		if (__predict_true(bucket->ucb_cnt < bucket->ucb_entries)) {
4263 			cache_bucket_push(cache, bucket, item);
4264 			critical_exit();
4265 			return;
4266 		}
4267 	} while (cache_free(zone, cache, udata, item, itemdomain));
4268 	critical_exit();
4269 
4270 	/*
4271 	 * If nothing else caught this, we'll just do an internal free.
4272 	 */
4273 zfree_item:
4274 	zone_free_item(zone, item, udata, SKIP_DTOR);
4275 }
4276 
4277 #ifdef NUMA
4278 /*
4279  * sort crossdomain free buckets to domain correct buckets and cache
4280  * them.
4281  */
4282 static void
zone_free_cross(uma_zone_t zone,uma_bucket_t bucket,void * udata)4283 zone_free_cross(uma_zone_t zone, uma_bucket_t bucket, void *udata)
4284 {
4285 	struct uma_bucketlist emptybuckets, fullbuckets;
4286 	uma_zone_domain_t zdom;
4287 	uma_bucket_t b;
4288 	smr_seq_t seq;
4289 	void *item;
4290 	int domain;
4291 
4292 	CTR3(KTR_UMA,
4293 	    "uma_zfree: zone %s(%p) draining cross bucket %p",
4294 	    zone->uz_name, zone, bucket);
4295 
4296 	/*
4297 	 * It is possible for buckets to arrive here out of order so we fetch
4298 	 * the current smr seq rather than accepting the bucket's.
4299 	 */
4300 	seq = SMR_SEQ_INVALID;
4301 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0)
4302 		seq = smr_advance(zone->uz_smr);
4303 
4304 	/*
4305 	 * To avoid having ndomain * ndomain buckets for sorting we have a
4306 	 * lock on the current crossfree bucket.  A full matrix with
4307 	 * per-domain locking could be used if necessary.
4308 	 */
4309 	STAILQ_INIT(&emptybuckets);
4310 	STAILQ_INIT(&fullbuckets);
4311 	ZONE_CROSS_LOCK(zone);
4312 	for (; bucket->ub_cnt > 0; bucket->ub_cnt--) {
4313 		item = bucket->ub_bucket[bucket->ub_cnt - 1];
4314 		domain = item_domain(item);
4315 		zdom = ZDOM_GET(zone, domain);
4316 		if (zdom->uzd_cross == NULL) {
4317 			if ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4318 				STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4319 				zdom->uzd_cross = b;
4320 			} else {
4321 				/*
4322 				 * Avoid allocating a bucket with the cross lock
4323 				 * held, since allocation can trigger a
4324 				 * cross-domain free and bucket zones may
4325 				 * allocate from each other.
4326 				 */
4327 				ZONE_CROSS_UNLOCK(zone);
4328 				b = bucket_alloc(zone, udata, M_NOWAIT);
4329 				if (b == NULL)
4330 					goto out;
4331 				ZONE_CROSS_LOCK(zone);
4332 				if (zdom->uzd_cross != NULL) {
4333 					STAILQ_INSERT_HEAD(&emptybuckets, b,
4334 					    ub_link);
4335 				} else {
4336 					zdom->uzd_cross = b;
4337 				}
4338 			}
4339 		}
4340 		b = zdom->uzd_cross;
4341 		b->ub_bucket[b->ub_cnt++] = item;
4342 		b->ub_seq = seq;
4343 		if (b->ub_cnt == b->ub_entries) {
4344 			STAILQ_INSERT_HEAD(&fullbuckets, b, ub_link);
4345 			if ((b = STAILQ_FIRST(&emptybuckets)) != NULL)
4346 				STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4347 			zdom->uzd_cross = b;
4348 		}
4349 	}
4350 	ZONE_CROSS_UNLOCK(zone);
4351 out:
4352 	if (bucket->ub_cnt == 0)
4353 		bucket->ub_seq = SMR_SEQ_INVALID;
4354 	bucket_free(zone, bucket, udata);
4355 
4356 	while ((b = STAILQ_FIRST(&emptybuckets)) != NULL) {
4357 		STAILQ_REMOVE_HEAD(&emptybuckets, ub_link);
4358 		bucket_free(zone, b, udata);
4359 	}
4360 	while ((b = STAILQ_FIRST(&fullbuckets)) != NULL) {
4361 		STAILQ_REMOVE_HEAD(&fullbuckets, ub_link);
4362 		domain = item_domain(b->ub_bucket[0]);
4363 		zone_put_bucket(zone, domain, b, udata, true);
4364 	}
4365 }
4366 #endif
4367 
4368 static void
zone_free_bucket(uma_zone_t zone,uma_bucket_t bucket,void * udata,int itemdomain,bool ws)4369 zone_free_bucket(uma_zone_t zone, uma_bucket_t bucket, void *udata,
4370     int itemdomain, bool ws)
4371 {
4372 
4373 #ifdef NUMA
4374 	/*
4375 	 * Buckets coming from the wrong domain will be entirely for the
4376 	 * only other domain on two domain systems.  In this case we can
4377 	 * simply cache them.  Otherwise we need to sort them back to
4378 	 * correct domains.
4379 	 */
4380 	if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 &&
4381 	    vm_ndomains > 2 && PCPU_GET(domain) != itemdomain) {
4382 		zone_free_cross(zone, bucket, udata);
4383 		return;
4384 	}
4385 #endif
4386 
4387 	/*
4388 	 * Attempt to save the bucket in the zone's domain bucket cache.
4389 	 */
4390 	CTR3(KTR_UMA,
4391 	    "uma_zfree: zone %s(%p) putting bucket %p on free list",
4392 	    zone->uz_name, zone, bucket);
4393 	/* ub_cnt is pointing to the last free item */
4394 	if ((zone->uz_flags & UMA_ZONE_ROUNDROBIN) != 0)
4395 		itemdomain = zone_domain_lowest(zone, itemdomain);
4396 	zone_put_bucket(zone, itemdomain, bucket, udata, ws);
4397 }
4398 
4399 /*
4400  * Populate a free or cross bucket for the current cpu cache.  Free any
4401  * existing full bucket either to the zone cache or back to the slab layer.
4402  *
4403  * Enters and returns in a critical section.  false return indicates that
4404  * we can not satisfy this free in the cache layer.  true indicates that
4405  * the caller should retry.
4406  */
4407 static __noinline bool
cache_free(uma_zone_t zone,uma_cache_t cache,void * udata,void * item,int itemdomain)4408 cache_free(uma_zone_t zone, uma_cache_t cache, void *udata, void *item,
4409     int itemdomain)
4410 {
4411 	uma_cache_bucket_t cbucket;
4412 	uma_bucket_t newbucket, bucket;
4413 
4414 	CRITICAL_ASSERT(curthread);
4415 
4416 	if (zone->uz_bucket_size == 0)
4417 		return false;
4418 
4419 	cache = &zone->uz_cpu[curcpu];
4420 	newbucket = NULL;
4421 
4422 	/*
4423 	 * FIRSTTOUCH domains need to free to the correct zdom.  When
4424 	 * enabled this is the zdom of the item.   The bucket is the
4425 	 * cross bucket if the current domain and itemdomain do not match.
4426 	 */
4427 	cbucket = &cache->uc_freebucket;
4428 #ifdef NUMA
4429 	if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4430 		if (PCPU_GET(domain) != itemdomain) {
4431 			cbucket = &cache->uc_crossbucket;
4432 			if (cbucket->ucb_cnt != 0)
4433 				counter_u64_add(zone->uz_xdomain,
4434 				    cbucket->ucb_cnt);
4435 		}
4436 	}
4437 #endif
4438 	bucket = cache_bucket_unload(cbucket);
4439 	KASSERT(bucket == NULL || bucket->ub_cnt == bucket->ub_entries,
4440 	    ("cache_free: Entered with non-full free bucket."));
4441 
4442 	/* We are no longer associated with this CPU. */
4443 	critical_exit();
4444 
4445 	/*
4446 	 * Don't let SMR zones operate without a free bucket.  Force
4447 	 * a synchronize and re-use this one.  We will only degrade
4448 	 * to a synchronize every bucket_size items rather than every
4449 	 * item if we fail to allocate a bucket.
4450 	 */
4451 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0) {
4452 		if (bucket != NULL)
4453 			bucket->ub_seq = smr_advance(zone->uz_smr);
4454 		newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4455 		if (newbucket == NULL && bucket != NULL) {
4456 			bucket_drain(zone, bucket);
4457 			newbucket = bucket;
4458 			bucket = NULL;
4459 		}
4460 	} else if (!bucketdisable)
4461 		newbucket = bucket_alloc(zone, udata, M_NOWAIT);
4462 
4463 	if (bucket != NULL)
4464 		zone_free_bucket(zone, bucket, udata, itemdomain, true);
4465 
4466 	critical_enter();
4467 	if ((bucket = newbucket) == NULL)
4468 		return (false);
4469 	cache = &zone->uz_cpu[curcpu];
4470 #ifdef NUMA
4471 	/*
4472 	 * Check to see if we should be populating the cross bucket.  If it
4473 	 * is already populated we will fall through and attempt to populate
4474 	 * the free bucket.
4475 	 */
4476 	if ((cache_uz_flags(cache) & UMA_ZONE_FIRSTTOUCH) != 0) {
4477 		if (PCPU_GET(domain) != itemdomain &&
4478 		    cache->uc_crossbucket.ucb_bucket == NULL) {
4479 			cache_bucket_load_cross(cache, bucket);
4480 			return (true);
4481 		}
4482 	}
4483 #endif
4484 	/*
4485 	 * We may have lost the race to fill the bucket or switched CPUs.
4486 	 */
4487 	if (cache->uc_freebucket.ucb_bucket != NULL) {
4488 		critical_exit();
4489 		bucket_free(zone, bucket, udata);
4490 		critical_enter();
4491 	} else
4492 		cache_bucket_load_free(cache, bucket);
4493 
4494 	return (true);
4495 }
4496 
4497 static void
slab_free_item(uma_zone_t zone,uma_slab_t slab,void * item)4498 slab_free_item(uma_zone_t zone, uma_slab_t slab, void *item)
4499 {
4500 	uma_keg_t keg;
4501 	uma_domain_t dom;
4502 	int freei;
4503 
4504 	keg = zone->uz_keg;
4505 	KEG_LOCK_ASSERT(keg, slab->us_domain);
4506 
4507 	/* Do we need to remove from any lists? */
4508 	dom = &keg->uk_domain[slab->us_domain];
4509 	if (slab->us_freecount + 1 == keg->uk_ipers) {
4510 		LIST_REMOVE(slab, us_link);
4511 		LIST_INSERT_HEAD(&dom->ud_free_slab, slab, us_link);
4512 		dom->ud_free_slabs++;
4513 	} else if (slab->us_freecount == 0) {
4514 		LIST_REMOVE(slab, us_link);
4515 		LIST_INSERT_HEAD(&dom->ud_part_slab, slab, us_link);
4516 	}
4517 
4518 	/* Slab management. */
4519 	freei = slab_item_index(slab, keg, item);
4520 	BIT_SET(keg->uk_ipers, freei, &slab->us_free);
4521 	slab->us_freecount++;
4522 
4523 	/* Keg statistics. */
4524 	dom->ud_free_items++;
4525 }
4526 
4527 static void
zone_release(void * arg,void ** bucket,int cnt)4528 zone_release(void *arg, void **bucket, int cnt)
4529 {
4530 	struct mtx *lock;
4531 	uma_zone_t zone;
4532 	uma_slab_t slab;
4533 	uma_keg_t keg;
4534 	uint8_t *mem;
4535 	void *item;
4536 	int i;
4537 
4538 	zone = arg;
4539 	keg = zone->uz_keg;
4540 	lock = NULL;
4541 	if (__predict_false((zone->uz_flags & UMA_ZFLAG_HASH) != 0))
4542 		lock = KEG_LOCK(keg, 0);
4543 	for (i = 0; i < cnt; i++) {
4544 		item = bucket[i];
4545 		if (__predict_true((zone->uz_flags & UMA_ZFLAG_VTOSLAB) != 0)) {
4546 			slab = vtoslab((vm_offset_t)item);
4547 		} else {
4548 			mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
4549 			if ((zone->uz_flags & UMA_ZFLAG_HASH) != 0)
4550 				slab = hash_sfind(&keg->uk_hash, mem);
4551 			else
4552 				slab = (uma_slab_t)(mem + keg->uk_pgoff);
4553 		}
4554 		if (lock != KEG_LOCKPTR(keg, slab->us_domain)) {
4555 			if (lock != NULL)
4556 				mtx_unlock(lock);
4557 			lock = KEG_LOCK(keg, slab->us_domain);
4558 		}
4559 		slab_free_item(zone, slab, item);
4560 	}
4561 	if (lock != NULL)
4562 		mtx_unlock(lock);
4563 }
4564 
4565 /*
4566  * Frees a single item to any zone.
4567  *
4568  * Arguments:
4569  *	zone   The zone to free to
4570  *	item   The item we're freeing
4571  *	udata  User supplied data for the dtor
4572  *	skip   Skip dtors and finis
4573  */
4574 static __noinline void
zone_free_item(uma_zone_t zone,void * item,void * udata,enum zfreeskip skip)4575 zone_free_item(uma_zone_t zone, void *item, void *udata, enum zfreeskip skip)
4576 {
4577 
4578 	/*
4579 	 * If a free is sent directly to an SMR zone we have to
4580 	 * synchronize immediately because the item can instantly
4581 	 * be reallocated. This should only happen in degenerate
4582 	 * cases when no memory is available for per-cpu caches.
4583 	 */
4584 	if ((zone->uz_flags & UMA_ZONE_SMR) != 0 && skip == SKIP_NONE)
4585 		smr_synchronize(zone->uz_smr);
4586 
4587 	item_dtor(zone, item, zone->uz_size, udata, skip);
4588 
4589 	if (skip < SKIP_FINI && zone->uz_fini)
4590 		zone->uz_fini(item, zone->uz_size);
4591 
4592 	zone->uz_release(zone->uz_arg, &item, 1);
4593 
4594 	if (skip & SKIP_CNT)
4595 		return;
4596 
4597 	counter_u64_add(zone->uz_frees, 1);
4598 
4599 	if (zone->uz_max_items > 0)
4600 		zone_free_limit(zone, 1);
4601 }
4602 
4603 /* See uma.h */
4604 int
uma_zone_set_max(uma_zone_t zone,int nitems)4605 uma_zone_set_max(uma_zone_t zone, int nitems)
4606 {
4607 
4608 	/*
4609 	 * If the limit is small, we may need to constrain the maximum per-CPU
4610 	 * cache size, or disable caching entirely.
4611 	 */
4612 	uma_zone_set_maxcache(zone, nitems);
4613 
4614 	/*
4615 	 * XXX This can misbehave if the zone has any allocations with
4616 	 * no limit and a limit is imposed.  There is currently no
4617 	 * way to clear a limit.
4618 	 */
4619 	ZONE_LOCK(zone);
4620 	zone->uz_max_items = nitems;
4621 	zone->uz_flags |= UMA_ZFLAG_LIMIT;
4622 	zone_update_caches(zone);
4623 	/* We may need to wake waiters. */
4624 	wakeup(&zone->uz_max_items);
4625 	ZONE_UNLOCK(zone);
4626 
4627 	return (nitems);
4628 }
4629 
4630 /* See uma.h */
4631 void
uma_zone_set_maxcache(uma_zone_t zone,int nitems)4632 uma_zone_set_maxcache(uma_zone_t zone, int nitems)
4633 {
4634 	int bpcpu, bpdom, bsize, nb;
4635 
4636 	ZONE_LOCK(zone);
4637 
4638 	/*
4639 	 * Compute a lower bound on the number of items that may be cached in
4640 	 * the zone.  Each CPU gets at least two buckets, and for cross-domain
4641 	 * frees we use an additional bucket per CPU and per domain.  Select the
4642 	 * largest bucket size that does not exceed half of the requested limit,
4643 	 * with the left over space given to the full bucket cache.
4644 	 */
4645 	bpdom = 0;
4646 	bpcpu = 2;
4647 #ifdef NUMA
4648 	if ((zone->uz_flags & UMA_ZONE_FIRSTTOUCH) != 0 && vm_ndomains > 1) {
4649 		bpcpu++;
4650 		bpdom++;
4651 	}
4652 #endif
4653 	nb = bpcpu * mp_ncpus + bpdom * vm_ndomains;
4654 	bsize = nitems / nb / 2;
4655 	if (bsize > BUCKET_MAX)
4656 		bsize = BUCKET_MAX;
4657 	else if (bsize == 0 && nitems / nb > 0)
4658 		bsize = 1;
4659 	zone->uz_bucket_size_max = zone->uz_bucket_size = bsize;
4660 	if (zone->uz_bucket_size_min > zone->uz_bucket_size_max)
4661 		zone->uz_bucket_size_min = zone->uz_bucket_size_max;
4662 	zone->uz_bucket_max = nitems - nb * bsize;
4663 	ZONE_UNLOCK(zone);
4664 }
4665 
4666 /* See uma.h */
4667 int
uma_zone_get_max(uma_zone_t zone)4668 uma_zone_get_max(uma_zone_t zone)
4669 {
4670 	int nitems;
4671 
4672 	nitems = atomic_load_64(&zone->uz_max_items);
4673 
4674 	return (nitems);
4675 }
4676 
4677 /* See uma.h */
4678 void
uma_zone_set_warning(uma_zone_t zone,const char * warning)4679 uma_zone_set_warning(uma_zone_t zone, const char *warning)
4680 {
4681 
4682 	ZONE_ASSERT_COLD(zone);
4683 	zone->uz_warning = warning;
4684 }
4685 
4686 /* See uma.h */
4687 void
uma_zone_set_maxaction(uma_zone_t zone,uma_maxaction_t maxaction)4688 uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t maxaction)
4689 {
4690 
4691 	ZONE_ASSERT_COLD(zone);
4692 	TASK_INIT(&zone->uz_maxaction, 0, (task_fn_t *)maxaction, zone);
4693 }
4694 
4695 /* See uma.h */
4696 int
uma_zone_get_cur(uma_zone_t zone)4697 uma_zone_get_cur(uma_zone_t zone)
4698 {
4699 	int64_t nitems;
4700 	u_int i;
4701 
4702 	nitems = 0;
4703 	if (zone->uz_allocs != EARLY_COUNTER && zone->uz_frees != EARLY_COUNTER)
4704 		nitems = counter_u64_fetch(zone->uz_allocs) -
4705 		    counter_u64_fetch(zone->uz_frees);
4706 	CPU_FOREACH(i)
4707 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs) -
4708 		    atomic_load_64(&zone->uz_cpu[i].uc_frees);
4709 
4710 	return (nitems < 0 ? 0 : nitems);
4711 }
4712 
4713 static uint64_t
uma_zone_get_allocs(uma_zone_t zone)4714 uma_zone_get_allocs(uma_zone_t zone)
4715 {
4716 	uint64_t nitems;
4717 	u_int i;
4718 
4719 	nitems = 0;
4720 	if (zone->uz_allocs != EARLY_COUNTER)
4721 		nitems = counter_u64_fetch(zone->uz_allocs);
4722 	CPU_FOREACH(i)
4723 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_allocs);
4724 
4725 	return (nitems);
4726 }
4727 
4728 static uint64_t
uma_zone_get_frees(uma_zone_t zone)4729 uma_zone_get_frees(uma_zone_t zone)
4730 {
4731 	uint64_t nitems;
4732 	u_int i;
4733 
4734 	nitems = 0;
4735 	if (zone->uz_frees != EARLY_COUNTER)
4736 		nitems = counter_u64_fetch(zone->uz_frees);
4737 	CPU_FOREACH(i)
4738 		nitems += atomic_load_64(&zone->uz_cpu[i].uc_frees);
4739 
4740 	return (nitems);
4741 }
4742 
4743 #ifdef INVARIANTS
4744 /* Used only for KEG_ASSERT_COLD(). */
4745 static uint64_t
uma_keg_get_allocs(uma_keg_t keg)4746 uma_keg_get_allocs(uma_keg_t keg)
4747 {
4748 	uma_zone_t z;
4749 	uint64_t nitems;
4750 
4751 	nitems = 0;
4752 	LIST_FOREACH(z, &keg->uk_zones, uz_link)
4753 		nitems += uma_zone_get_allocs(z);
4754 
4755 	return (nitems);
4756 }
4757 #endif
4758 
4759 /* See uma.h */
4760 void
uma_zone_set_init(uma_zone_t zone,uma_init uminit)4761 uma_zone_set_init(uma_zone_t zone, uma_init uminit)
4762 {
4763 	uma_keg_t keg;
4764 
4765 	KEG_GET(zone, keg);
4766 	KEG_ASSERT_COLD(keg);
4767 	keg->uk_init = uminit;
4768 }
4769 
4770 /* See uma.h */
4771 void
uma_zone_set_fini(uma_zone_t zone,uma_fini fini)4772 uma_zone_set_fini(uma_zone_t zone, uma_fini fini)
4773 {
4774 	uma_keg_t keg;
4775 
4776 	KEG_GET(zone, keg);
4777 	KEG_ASSERT_COLD(keg);
4778 	keg->uk_fini = fini;
4779 }
4780 
4781 /* See uma.h */
4782 void
uma_zone_set_zinit(uma_zone_t zone,uma_init zinit)4783 uma_zone_set_zinit(uma_zone_t zone, uma_init zinit)
4784 {
4785 
4786 	ZONE_ASSERT_COLD(zone);
4787 	zone->uz_init = zinit;
4788 }
4789 
4790 /* See uma.h */
4791 void
uma_zone_set_zfini(uma_zone_t zone,uma_fini zfini)4792 uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini)
4793 {
4794 
4795 	ZONE_ASSERT_COLD(zone);
4796 	zone->uz_fini = zfini;
4797 }
4798 
4799 /* See uma.h */
4800 void
uma_zone_set_freef(uma_zone_t zone,uma_free freef)4801 uma_zone_set_freef(uma_zone_t zone, uma_free freef)
4802 {
4803 	uma_keg_t keg;
4804 
4805 	KEG_GET(zone, keg);
4806 	KEG_ASSERT_COLD(keg);
4807 	keg->uk_freef = freef;
4808 }
4809 
4810 /* See uma.h */
4811 void
uma_zone_set_allocf(uma_zone_t zone,uma_alloc allocf)4812 uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf)
4813 {
4814 	uma_keg_t keg;
4815 
4816 	KEG_GET(zone, keg);
4817 	KEG_ASSERT_COLD(keg);
4818 	keg->uk_allocf = allocf;
4819 }
4820 
4821 /* See uma.h */
4822 void
uma_zone_set_smr(uma_zone_t zone,smr_t smr)4823 uma_zone_set_smr(uma_zone_t zone, smr_t smr)
4824 {
4825 
4826 	ZONE_ASSERT_COLD(zone);
4827 
4828 	KASSERT(smr != NULL, ("Got NULL smr"));
4829 	KASSERT((zone->uz_flags & UMA_ZONE_SMR) == 0,
4830 	    ("zone %p (%s) already uses SMR", zone, zone->uz_name));
4831 	zone->uz_flags |= UMA_ZONE_SMR;
4832 	zone->uz_smr = smr;
4833 	zone_update_caches(zone);
4834 }
4835 
4836 smr_t
uma_zone_get_smr(uma_zone_t zone)4837 uma_zone_get_smr(uma_zone_t zone)
4838 {
4839 
4840 	return (zone->uz_smr);
4841 }
4842 
4843 /* See uma.h */
4844 void
uma_zone_reserve(uma_zone_t zone,int items)4845 uma_zone_reserve(uma_zone_t zone, int items)
4846 {
4847 	uma_keg_t keg;
4848 
4849 	KEG_GET(zone, keg);
4850 	KEG_ASSERT_COLD(keg);
4851 	keg->uk_reserve = items;
4852 }
4853 
4854 #ifndef FSTACK
4855 /* See uma.h */
4856 int
uma_zone_reserve_kva(uma_zone_t zone,int count)4857 uma_zone_reserve_kva(uma_zone_t zone, int count)
4858 {
4859 	uma_keg_t keg;
4860 	vm_offset_t kva;
4861 	u_int pages;
4862 
4863 	KEG_GET(zone, keg);
4864 	KEG_ASSERT_COLD(keg);
4865 	ZONE_ASSERT_COLD(zone);
4866 
4867 	pages = howmany(count, keg->uk_ipers) * keg->uk_ppera;
4868 
4869 #ifdef UMA_MD_SMALL_ALLOC
4870 	if (keg->uk_ppera > 1) {
4871 #else
4872 	if (1) {
4873 #endif
4874 		kva = kva_alloc((vm_size_t)pages * PAGE_SIZE);
4875 		if (kva == 0)
4876 			return (0);
4877 	} else
4878 		kva = 0;
4879 
4880 	MPASS(keg->uk_kva == 0);
4881 	keg->uk_kva = kva;
4882 	keg->uk_offset = 0;
4883 	zone->uz_max_items = pages * keg->uk_ipers;
4884 #ifdef UMA_MD_SMALL_ALLOC
4885 	keg->uk_allocf = (keg->uk_ppera > 1) ? noobj_alloc : uma_small_alloc;
4886 #else
4887 	keg->uk_allocf = noobj_alloc;
4888 #endif
4889 	keg->uk_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4890 	zone->uz_flags |= UMA_ZFLAG_LIMIT | UMA_ZONE_NOFREE;
4891 	zone_update_caches(zone);
4892 
4893 	return (1);
4894 }
4895 #endif
4896 
4897 /* See uma.h */
4898 void
4899 uma_prealloc(uma_zone_t zone, int items)
4900 {
4901 	struct vm_domainset_iter di;
4902 	uma_domain_t dom;
4903 	uma_slab_t slab;
4904 	uma_keg_t keg;
4905 	int aflags, domain, slabs;
4906 
4907 	KEG_GET(zone, keg);
4908 	slabs = howmany(items, keg->uk_ipers);
4909 	while (slabs-- > 0) {
4910 		aflags = M_NOWAIT;
4911 		vm_domainset_iter_policy_ref_init(&di, &keg->uk_dr, &domain,
4912 		    &aflags);
4913 		for (;;) {
4914 			slab = keg_alloc_slab(keg, zone, domain, M_WAITOK,
4915 			    aflags);
4916 			if (slab != NULL) {
4917 				dom = &keg->uk_domain[slab->us_domain];
4918 				/*
4919 				 * keg_alloc_slab() always returns a slab on the
4920 				 * partial list.
4921 				 */
4922 				LIST_REMOVE(slab, us_link);
4923 				LIST_INSERT_HEAD(&dom->ud_free_slab, slab,
4924 				    us_link);
4925 				dom->ud_free_slabs++;
4926 				KEG_UNLOCK(keg, slab->us_domain);
4927 				break;
4928 			}
4929 			if (vm_domainset_iter_policy(&di, &domain) != 0)
4930 				vm_wait_doms(&keg->uk_dr.dr_policy->ds_mask, 0);
4931 		}
4932 	}
4933 }
4934 
4935 /*
4936  * Returns a snapshot of memory consumption in bytes.
4937  */
4938 size_t
4939 uma_zone_memory(uma_zone_t zone)
4940 {
4941 	size_t sz;
4942 	int i;
4943 
4944 	sz = 0;
4945 	if (zone->uz_flags & UMA_ZFLAG_CACHE) {
4946 		for (i = 0; i < vm_ndomains; i++)
4947 			sz += ZDOM_GET(zone, i)->uzd_nitems;
4948 		return (sz * zone->uz_size);
4949 	}
4950 	for (i = 0; i < vm_ndomains; i++)
4951 		sz += zone->uz_keg->uk_domain[i].ud_pages;
4952 
4953 	return (sz * PAGE_SIZE);
4954 }
4955 
4956 /* See uma.h */
4957 void
4958 uma_reclaim(int req)
4959 {
4960 
4961 	CTR0(KTR_UMA, "UMA: vm asked us to release pages!");
4962 	sx_xlock(&uma_reclaim_lock);
4963 	bucket_enable();
4964 
4965 	switch (req) {
4966 	case UMA_RECLAIM_TRIM:
4967 		zone_foreach(zone_trim, NULL);
4968 		break;
4969 	case UMA_RECLAIM_DRAIN:
4970 	case UMA_RECLAIM_DRAIN_CPU:
4971 		zone_foreach(zone_drain, NULL);
4972 		if (req == UMA_RECLAIM_DRAIN_CPU) {
4973 			pcpu_cache_drain_safe(NULL);
4974 			zone_foreach(zone_drain, NULL);
4975 		}
4976 		break;
4977 	default:
4978 		panic("unhandled reclamation request %d", req);
4979 	}
4980 
4981 	/*
4982 	 * Some slabs may have been freed but this zone will be visited early
4983 	 * we visit again so that we can free pages that are empty once other
4984 	 * zones are drained.  We have to do the same for buckets.
4985 	 */
4986 	zone_drain(slabzones[0], NULL);
4987 	zone_drain(slabzones[1], NULL);
4988 	bucket_zone_drain();
4989 	sx_xunlock(&uma_reclaim_lock);
4990 }
4991 
4992 static volatile int uma_reclaim_needed;
4993 
4994 void
4995 uma_reclaim_wakeup(void)
4996 {
4997 
4998 	if (atomic_fetchadd_int(&uma_reclaim_needed, 1) == 0)
4999 		wakeup(uma_reclaim);
5000 }
5001 
5002 void
5003 uma_reclaim_worker(void *arg __unused)
5004 {
5005 
5006 	for (;;) {
5007 		sx_xlock(&uma_reclaim_lock);
5008 		while (atomic_load_int(&uma_reclaim_needed) == 0)
5009 			sx_sleep(uma_reclaim, &uma_reclaim_lock, PVM, "umarcl",
5010 			    hz);
5011 		sx_xunlock(&uma_reclaim_lock);
5012 		EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_KMEM);
5013 		uma_reclaim(UMA_RECLAIM_DRAIN_CPU);
5014 		atomic_store_int(&uma_reclaim_needed, 0);
5015 		/* Don't fire more than once per-second. */
5016 		pause("umarclslp", hz);
5017 	}
5018 }
5019 
5020 /* See uma.h */
5021 void
5022 uma_zone_reclaim(uma_zone_t zone, int req)
5023 {
5024 
5025 	switch (req) {
5026 	case UMA_RECLAIM_TRIM:
5027 		zone_trim(zone, NULL);
5028 		break;
5029 	case UMA_RECLAIM_DRAIN:
5030 		zone_drain(zone, NULL);
5031 		break;
5032 	case UMA_RECLAIM_DRAIN_CPU:
5033 		pcpu_cache_drain_safe(zone);
5034 		zone_drain(zone, NULL);
5035 		break;
5036 	default:
5037 		panic("unhandled reclamation request %d", req);
5038 	}
5039 }
5040 
5041 /* See uma.h */
5042 int
5043 uma_zone_exhausted(uma_zone_t zone)
5044 {
5045 
5046 	return (atomic_load_32(&zone->uz_sleepers) > 0);
5047 }
5048 
5049 unsigned long
5050 uma_limit(void)
5051 {
5052 
5053 	return (uma_kmem_limit);
5054 }
5055 
5056 void
5057 uma_set_limit(unsigned long limit)
5058 {
5059 
5060 	uma_kmem_limit = limit;
5061 }
5062 
5063 unsigned long
5064 uma_size(void)
5065 {
5066 
5067 	return (atomic_load_long(&uma_kmem_total));
5068 }
5069 
5070 long
5071 uma_avail(void)
5072 {
5073 
5074 	return (uma_kmem_limit - uma_size());
5075 }
5076 
5077 #ifdef DDB
5078 /*
5079  * Generate statistics across both the zone and its per-cpu cache's.  Return
5080  * desired statistics if the pointer is non-NULL for that statistic.
5081  *
5082  * Note: does not update the zone statistics, as it can't safely clear the
5083  * per-CPU cache statistic.
5084  *
5085  */
5086 static void
5087 uma_zone_sumstat(uma_zone_t z, long *cachefreep, uint64_t *allocsp,
5088     uint64_t *freesp, uint64_t *sleepsp, uint64_t *xdomainp)
5089 {
5090 	uma_cache_t cache;
5091 	uint64_t allocs, frees, sleeps, xdomain;
5092 	int cachefree, cpu;
5093 
5094 	allocs = frees = sleeps = xdomain = 0;
5095 	cachefree = 0;
5096 	CPU_FOREACH(cpu) {
5097 		cache = &z->uz_cpu[cpu];
5098 		cachefree += cache->uc_allocbucket.ucb_cnt;
5099 		cachefree += cache->uc_freebucket.ucb_cnt;
5100 		xdomain += cache->uc_crossbucket.ucb_cnt;
5101 		cachefree += cache->uc_crossbucket.ucb_cnt;
5102 		allocs += cache->uc_allocs;
5103 		frees += cache->uc_frees;
5104 	}
5105 	allocs += counter_u64_fetch(z->uz_allocs);
5106 	frees += counter_u64_fetch(z->uz_frees);
5107 	xdomain += counter_u64_fetch(z->uz_xdomain);
5108 	sleeps += z->uz_sleeps;
5109 	if (cachefreep != NULL)
5110 		*cachefreep = cachefree;
5111 	if (allocsp != NULL)
5112 		*allocsp = allocs;
5113 	if (freesp != NULL)
5114 		*freesp = frees;
5115 	if (sleepsp != NULL)
5116 		*sleepsp = sleeps;
5117 	if (xdomainp != NULL)
5118 		*xdomainp = xdomain;
5119 }
5120 #endif /* DDB */
5121 
5122 static int
5123 sysctl_vm_zone_count(SYSCTL_HANDLER_ARGS)
5124 {
5125 	uma_keg_t kz;
5126 	uma_zone_t z;
5127 	int count;
5128 
5129 	count = 0;
5130 	rw_rlock(&uma_rwlock);
5131 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5132 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
5133 			count++;
5134 	}
5135 	LIST_FOREACH(z, &uma_cachezones, uz_link)
5136 		count++;
5137 
5138 	rw_runlock(&uma_rwlock);
5139 	return (sysctl_handle_int(oidp, &count, 0, req));
5140 }
5141 
5142 static void
5143 uma_vm_zone_stats(struct uma_type_header *uth, uma_zone_t z, struct sbuf *sbuf,
5144     struct uma_percpu_stat *ups, bool internal)
5145 {
5146 	uma_zone_domain_t zdom;
5147 	uma_cache_t cache;
5148 	int i;
5149 
5150 	for (i = 0; i < vm_ndomains; i++) {
5151 		zdom = ZDOM_GET(z, i);
5152 		uth->uth_zone_free += zdom->uzd_nitems;
5153 	}
5154 	uth->uth_allocs = counter_u64_fetch(z->uz_allocs);
5155 	uth->uth_frees = counter_u64_fetch(z->uz_frees);
5156 	uth->uth_fails = counter_u64_fetch(z->uz_fails);
5157 	uth->uth_xdomain = counter_u64_fetch(z->uz_xdomain);
5158 	uth->uth_sleeps = z->uz_sleeps;
5159 
5160 	for (i = 0; i < mp_maxid + 1; i++) {
5161 		bzero(&ups[i], sizeof(*ups));
5162 		if (internal || CPU_ABSENT(i))
5163 			continue;
5164 		cache = &z->uz_cpu[i];
5165 		ups[i].ups_cache_free += cache->uc_allocbucket.ucb_cnt;
5166 		ups[i].ups_cache_free += cache->uc_freebucket.ucb_cnt;
5167 		ups[i].ups_cache_free += cache->uc_crossbucket.ucb_cnt;
5168 		ups[i].ups_allocs = cache->uc_allocs;
5169 		ups[i].ups_frees = cache->uc_frees;
5170 	}
5171 }
5172 
5173 static int
5174 sysctl_vm_zone_stats(SYSCTL_HANDLER_ARGS)
5175 {
5176 	struct uma_stream_header ush;
5177 	struct uma_type_header uth;
5178 	struct uma_percpu_stat *ups;
5179 	struct sbuf sbuf;
5180 	uma_keg_t kz;
5181 	uma_zone_t z;
5182 	uint64_t items;
5183 	uint32_t kfree, pages;
5184 	int count, error, i;
5185 
5186 	error = sysctl_wire_old_buffer(req, 0);
5187 	if (error != 0)
5188 		return (error);
5189 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
5190 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
5191 	ups = malloc((mp_maxid + 1) * sizeof(*ups), M_TEMP, M_WAITOK);
5192 
5193 	count = 0;
5194 	rw_rlock(&uma_rwlock);
5195 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5196 		LIST_FOREACH(z, &kz->uk_zones, uz_link)
5197 			count++;
5198 	}
5199 
5200 	LIST_FOREACH(z, &uma_cachezones, uz_link)
5201 		count++;
5202 
5203 	/*
5204 	 * Insert stream header.
5205 	 */
5206 	bzero(&ush, sizeof(ush));
5207 	ush.ush_version = UMA_STREAM_VERSION;
5208 	ush.ush_maxcpus = (mp_maxid + 1);
5209 	ush.ush_count = count;
5210 	(void)sbuf_bcat(&sbuf, &ush, sizeof(ush));
5211 
5212 	LIST_FOREACH(kz, &uma_kegs, uk_link) {
5213 		kfree = pages = 0;
5214 		for (i = 0; i < vm_ndomains; i++) {
5215 			kfree += kz->uk_domain[i].ud_free_items;
5216 			pages += kz->uk_domain[i].ud_pages;
5217 		}
5218 		LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5219 			bzero(&uth, sizeof(uth));
5220 			strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5221 			uth.uth_align = kz->uk_align;
5222 			uth.uth_size = kz->uk_size;
5223 			uth.uth_rsize = kz->uk_rsize;
5224 			if (z->uz_max_items > 0) {
5225 				items = UZ_ITEMS_COUNT(z->uz_items);
5226 				uth.uth_pages = (items / kz->uk_ipers) *
5227 					kz->uk_ppera;
5228 			} else
5229 				uth.uth_pages = pages;
5230 			uth.uth_maxpages = (z->uz_max_items / kz->uk_ipers) *
5231 			    kz->uk_ppera;
5232 			uth.uth_limit = z->uz_max_items;
5233 			uth.uth_keg_free = kfree;
5234 
5235 			/*
5236 			 * A zone is secondary is it is not the first entry
5237 			 * on the keg's zone list.
5238 			 */
5239 			if ((z->uz_flags & UMA_ZONE_SECONDARY) &&
5240 			    (LIST_FIRST(&kz->uk_zones) != z))
5241 				uth.uth_zone_flags = UTH_ZONE_SECONDARY;
5242 			uma_vm_zone_stats(&uth, z, &sbuf, ups,
5243 			    kz->uk_flags & UMA_ZFLAG_INTERNAL);
5244 			(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5245 			for (i = 0; i < mp_maxid + 1; i++)
5246 				(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5247 		}
5248 	}
5249 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
5250 		bzero(&uth, sizeof(uth));
5251 		strlcpy(uth.uth_name, z->uz_name, UTH_MAX_NAME);
5252 		uth.uth_size = z->uz_size;
5253 		uma_vm_zone_stats(&uth, z, &sbuf, ups, false);
5254 		(void)sbuf_bcat(&sbuf, &uth, sizeof(uth));
5255 		for (i = 0; i < mp_maxid + 1; i++)
5256 			(void)sbuf_bcat(&sbuf, &ups[i], sizeof(ups[i]));
5257 	}
5258 
5259 	rw_runlock(&uma_rwlock);
5260 	error = sbuf_finish(&sbuf);
5261 	sbuf_delete(&sbuf);
5262 	free(ups, M_TEMP);
5263 	return (error);
5264 }
5265 
5266 int
5267 sysctl_handle_uma_zone_max(SYSCTL_HANDLER_ARGS)
5268 {
5269 	uma_zone_t zone = *(uma_zone_t *)arg1;
5270 	int error, max;
5271 
5272 	max = uma_zone_get_max(zone);
5273 	error = sysctl_handle_int(oidp, &max, 0, req);
5274 	if (error || !req->newptr)
5275 		return (error);
5276 
5277 	uma_zone_set_max(zone, max);
5278 
5279 	return (0);
5280 }
5281 
5282 int
5283 sysctl_handle_uma_zone_cur(SYSCTL_HANDLER_ARGS)
5284 {
5285 	uma_zone_t zone;
5286 	int cur;
5287 
5288 	/*
5289 	 * Some callers want to add sysctls for global zones that
5290 	 * may not yet exist so they pass a pointer to a pointer.
5291 	 */
5292 	if (arg2 == 0)
5293 		zone = *(uma_zone_t *)arg1;
5294 	else
5295 		zone = arg1;
5296 	cur = uma_zone_get_cur(zone);
5297 	return (sysctl_handle_int(oidp, &cur, 0, req));
5298 }
5299 
5300 static int
5301 sysctl_handle_uma_zone_allocs(SYSCTL_HANDLER_ARGS)
5302 {
5303 	uma_zone_t zone = arg1;
5304 	uint64_t cur;
5305 
5306 	cur = uma_zone_get_allocs(zone);
5307 	return (sysctl_handle_64(oidp, &cur, 0, req));
5308 }
5309 
5310 static int
5311 sysctl_handle_uma_zone_frees(SYSCTL_HANDLER_ARGS)
5312 {
5313 	uma_zone_t zone = arg1;
5314 	uint64_t cur;
5315 
5316 	cur = uma_zone_get_frees(zone);
5317 	return (sysctl_handle_64(oidp, &cur, 0, req));
5318 }
5319 
5320 static int
5321 sysctl_handle_uma_zone_flags(SYSCTL_HANDLER_ARGS)
5322 {
5323 	struct sbuf sbuf;
5324 	uma_zone_t zone = arg1;
5325 	int error;
5326 
5327 	sbuf_new_for_sysctl(&sbuf, NULL, 0, req);
5328 	#pragma GCC diagnostic ignored "-Wformat"
5329 	#pragma GCC diagnostic ignored "-Wformat-extra-args"
5330 	if (zone->uz_flags != 0)
5331 		sbuf_printf(&sbuf, "0x%b", zone->uz_flags, PRINT_UMA_ZFLAGS);
5332 	else
5333 		sbuf_printf(&sbuf, "0");
5334 	#pragma GCC diagnostic error "-Wformat"
5335 	#pragma GCC diagnostic ignored "-Wformat-extra-args"
5336 	error = sbuf_finish(&sbuf);
5337 	sbuf_delete(&sbuf);
5338 
5339 	return (error);
5340 }
5341 
5342 static int
5343 sysctl_handle_uma_slab_efficiency(SYSCTL_HANDLER_ARGS)
5344 {
5345 	uma_keg_t keg = arg1;
5346 	int avail, effpct, total;
5347 
5348 	total = keg->uk_ppera * PAGE_SIZE;
5349 	if ((keg->uk_flags & UMA_ZFLAG_OFFPAGE) != 0)
5350 		total += slabzone(keg->uk_ipers)->uz_keg->uk_rsize;
5351 	/*
5352 	 * We consider the client's requested size and alignment here, not the
5353 	 * real size determination uk_rsize, because we also adjust the real
5354 	 * size for internal implementation reasons (max bitset size).
5355 	 */
5356 	avail = keg->uk_ipers * roundup2(keg->uk_size, keg->uk_align + 1);
5357 	if ((keg->uk_flags & UMA_ZONE_PCPU) != 0)
5358 		avail *= mp_maxid + 1;
5359 	effpct = 100 * avail / total;
5360 	return (sysctl_handle_int(oidp, &effpct, 0, req));
5361 }
5362 
5363 static int
5364 sysctl_handle_uma_zone_items(SYSCTL_HANDLER_ARGS)
5365 {
5366 	uma_zone_t zone = arg1;
5367 	uint64_t cur;
5368 
5369 	cur = UZ_ITEMS_COUNT(atomic_load_64(&zone->uz_items));
5370 	return (sysctl_handle_64(oidp, &cur, 0, req));
5371 }
5372 
5373 #ifdef INVARIANTS
5374 static uma_slab_t
5375 uma_dbg_getslab(uma_zone_t zone, void *item)
5376 {
5377 	uma_slab_t slab;
5378 	uma_keg_t keg;
5379 	uint8_t *mem;
5380 
5381 	/*
5382 	 * It is safe to return the slab here even though the
5383 	 * zone is unlocked because the item's allocation state
5384 	 * essentially holds a reference.
5385 	 */
5386 	mem = (uint8_t *)((uintptr_t)item & (~UMA_SLAB_MASK));
5387 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5388 		return (NULL);
5389 	if (zone->uz_flags & UMA_ZFLAG_VTOSLAB)
5390 		return (vtoslab((vm_offset_t)mem));
5391 	keg = zone->uz_keg;
5392 	if ((keg->uk_flags & UMA_ZFLAG_HASH) == 0)
5393 		return ((uma_slab_t)(mem + keg->uk_pgoff));
5394 	KEG_LOCK(keg, 0);
5395 	slab = hash_sfind(&keg->uk_hash, mem);
5396 	KEG_UNLOCK(keg, 0);
5397 
5398 	return (slab);
5399 }
5400 
5401 static bool
5402 uma_dbg_zskip(uma_zone_t zone, void *mem)
5403 {
5404 
5405 	if ((zone->uz_flags & UMA_ZFLAG_CACHE) != 0)
5406 		return (true);
5407 
5408 	return (uma_dbg_kskip(zone->uz_keg, mem));
5409 }
5410 
5411 static bool
5412 uma_dbg_kskip(uma_keg_t keg, void *mem)
5413 {
5414 	uintptr_t idx;
5415 
5416 	if (dbg_divisor == 0)
5417 		return (true);
5418 
5419 	if (dbg_divisor == 1)
5420 		return (false);
5421 
5422 	idx = (uintptr_t)mem >> PAGE_SHIFT;
5423 	if (keg->uk_ipers > 1) {
5424 		idx *= keg->uk_ipers;
5425 		idx += ((uintptr_t)mem & PAGE_MASK) / keg->uk_rsize;
5426 	}
5427 
5428 	if ((idx / dbg_divisor) * dbg_divisor != idx) {
5429 		counter_u64_add(uma_skip_cnt, 1);
5430 		return (true);
5431 	}
5432 	counter_u64_add(uma_dbg_cnt, 1);
5433 
5434 	return (false);
5435 }
5436 
5437 /*
5438  * Set up the slab's freei data such that uma_dbg_free can function.
5439  *
5440  */
5441 static void
5442 uma_dbg_alloc(uma_zone_t zone, uma_slab_t slab, void *item)
5443 {
5444 	uma_keg_t keg;
5445 	int freei;
5446 
5447 	if (slab == NULL) {
5448 		slab = uma_dbg_getslab(zone, item);
5449 		if (slab == NULL)
5450 			panic("uma: item %p did not belong to zone %s",
5451 			    item, zone->uz_name);
5452 	}
5453 	keg = zone->uz_keg;
5454 	freei = slab_item_index(slab, keg, item);
5455 
5456 	if (BIT_TEST_SET_ATOMIC(keg->uk_ipers, freei,
5457 	    slab_dbg_bits(slab, keg)))
5458 		panic("Duplicate alloc of %p from zone %p(%s) slab %p(%d)",
5459 		    item, zone, zone->uz_name, slab, freei);
5460 }
5461 
5462 /*
5463  * Verifies freed addresses.  Checks for alignment, valid slab membership
5464  * and duplicate frees.
5465  *
5466  */
5467 static void
5468 uma_dbg_free(uma_zone_t zone, uma_slab_t slab, void *item)
5469 {
5470 	uma_keg_t keg;
5471 	int freei;
5472 
5473 	if (slab == NULL) {
5474 		slab = uma_dbg_getslab(zone, item);
5475 		if (slab == NULL)
5476 			panic("uma: Freed item %p did not belong to zone %s",
5477 			    item, zone->uz_name);
5478 	}
5479 	keg = zone->uz_keg;
5480 	freei = slab_item_index(slab, keg, item);
5481 
5482 	if (freei >= keg->uk_ipers)
5483 		panic("Invalid free of %p from zone %p(%s) slab %p(%d)",
5484 		    item, zone, zone->uz_name, slab, freei);
5485 
5486 	if (slab_item(slab, keg, freei) != item)
5487 		panic("Unaligned free of %p from zone %p(%s) slab %p(%d)",
5488 		    item, zone, zone->uz_name, slab, freei);
5489 
5490 	if (!BIT_TEST_CLR_ATOMIC(keg->uk_ipers, freei,
5491 	    slab_dbg_bits(slab, keg)))
5492 		panic("Duplicate free of %p from zone %p(%s) slab %p(%d)",
5493 		    item, zone, zone->uz_name, slab, freei);
5494 }
5495 #endif /* INVARIANTS */
5496 
5497 #ifdef DDB
5498 static int64_t
5499 get_uma_stats(uma_keg_t kz, uma_zone_t z, uint64_t *allocs, uint64_t *used,
5500     uint64_t *sleeps, long *cachefree, uint64_t *xdomain)
5501 {
5502 	uint64_t frees;
5503 	int i;
5504 
5505 	if (kz->uk_flags & UMA_ZFLAG_INTERNAL) {
5506 		*allocs = counter_u64_fetch(z->uz_allocs);
5507 		frees = counter_u64_fetch(z->uz_frees);
5508 		*sleeps = z->uz_sleeps;
5509 		*cachefree = 0;
5510 		*xdomain = 0;
5511 	} else
5512 		uma_zone_sumstat(z, cachefree, allocs, &frees, sleeps,
5513 		    xdomain);
5514 	for (i = 0; i < vm_ndomains; i++) {
5515 		*cachefree += ZDOM_GET(z, i)->uzd_nitems;
5516 		if (!((z->uz_flags & UMA_ZONE_SECONDARY) &&
5517 		    (LIST_FIRST(&kz->uk_zones) != z)))
5518 			*cachefree += kz->uk_domain[i].ud_free_items;
5519 	}
5520 	*used = *allocs - frees;
5521 	return (((int64_t)*used + *cachefree) * kz->uk_size);
5522 }
5523 
5524 DB_SHOW_COMMAND(uma, db_show_uma)
5525 {
5526 	const char *fmt_hdr, *fmt_entry;
5527 	uma_keg_t kz;
5528 	uma_zone_t z;
5529 	uint64_t allocs, used, sleeps, xdomain;
5530 	long cachefree;
5531 	/* variables for sorting */
5532 	uma_keg_t cur_keg;
5533 	uma_zone_t cur_zone, last_zone;
5534 	int64_t cur_size, last_size, size;
5535 	int ties;
5536 
5537 	/* /i option produces machine-parseable CSV output */
5538 	if (modif[0] == 'i') {
5539 		fmt_hdr = "%s,%s,%s,%s,%s,%s,%s,%s,%s\n";
5540 		fmt_entry = "\"%s\",%ju,%jd,%ld,%ju,%ju,%u,%jd,%ju\n";
5541 	} else {
5542 		fmt_hdr = "%18s %6s %7s %7s %11s %7s %7s %10s %8s\n";
5543 		fmt_entry = "%18s %6ju %7jd %7ld %11ju %7ju %7u %10jd %8ju\n";
5544 	}
5545 
5546 	db_printf(fmt_hdr, "Zone", "Size", "Used", "Free", "Requests",
5547 	    "Sleeps", "Bucket", "Total Mem", "XFree");
5548 
5549 	/* Sort the zones with largest size first. */
5550 	last_zone = NULL;
5551 	last_size = INT64_MAX;
5552 	for (;;) {
5553 		cur_zone = NULL;
5554 		cur_size = -1;
5555 		ties = 0;
5556 		LIST_FOREACH(kz, &uma_kegs, uk_link) {
5557 			LIST_FOREACH(z, &kz->uk_zones, uz_link) {
5558 				/*
5559 				 * In the case of size ties, print out zones
5560 				 * in the order they are encountered.  That is,
5561 				 * when we encounter the most recently output
5562 				 * zone, we have already printed all preceding
5563 				 * ties, and we must print all following ties.
5564 				 */
5565 				if (z == last_zone) {
5566 					ties = 1;
5567 					continue;
5568 				}
5569 				size = get_uma_stats(kz, z, &allocs, &used,
5570 				    &sleeps, &cachefree, &xdomain);
5571 				if (size > cur_size && size < last_size + ties)
5572 				{
5573 					cur_size = size;
5574 					cur_zone = z;
5575 					cur_keg = kz;
5576 				}
5577 			}
5578 		}
5579 		if (cur_zone == NULL)
5580 			break;
5581 
5582 		size = get_uma_stats(cur_keg, cur_zone, &allocs, &used,
5583 		    &sleeps, &cachefree, &xdomain);
5584 		db_printf(fmt_entry, cur_zone->uz_name,
5585 		    (uintmax_t)cur_keg->uk_size, (intmax_t)used, cachefree,
5586 		    (uintmax_t)allocs, (uintmax_t)sleeps,
5587 		    (unsigned)cur_zone->uz_bucket_size, (intmax_t)size,
5588 		    xdomain);
5589 
5590 		if (db_pager_quit)
5591 			return;
5592 		last_zone = cur_zone;
5593 		last_size = cur_size;
5594 	}
5595 }
5596 
5597 DB_SHOW_COMMAND(umacache, db_show_umacache)
5598 {
5599 	uma_zone_t z;
5600 	uint64_t allocs, frees;
5601 	long cachefree;
5602 	int i;
5603 
5604 	db_printf("%18s %8s %8s %8s %12s %8s\n", "Zone", "Size", "Used", "Free",
5605 	    "Requests", "Bucket");
5606 	LIST_FOREACH(z, &uma_cachezones, uz_link) {
5607 		uma_zone_sumstat(z, &cachefree, &allocs, &frees, NULL, NULL);
5608 		for (i = 0; i < vm_ndomains; i++)
5609 			cachefree += ZDOM_GET(z, i)->uzd_nitems;
5610 		db_printf("%18s %8ju %8jd %8ld %12ju %8u\n",
5611 		    z->uz_name, (uintmax_t)z->uz_size,
5612 		    (intmax_t)(allocs - frees), cachefree,
5613 		    (uintmax_t)allocs, z->uz_bucket_size);
5614 		if (db_pager_quit)
5615 			return;
5616 	}
5617 }
5618 #endif	/* DDB */
5619