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