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