xref: /freebsd/sys/kern/kern_malloc.c (revision 87b759f0fa1f7554d50ce640c40138512bbded44)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1991, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2005-2009 Robert N. M. Watson
7  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following 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  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
37  * based on memory types.  Back end is implemented using the UMA(9) zone
38  * allocator.  A set of fixed-size buckets are used for smaller allocations,
39  * and a special UMA allocation interface is used for larger allocations.
40  * Callers declare memory types, and statistics are maintained independently
41  * for each memory type.  Statistics are maintained per-CPU for performance
42  * reasons.  See malloc(9) and comments in malloc.h for a detailed
43  * description.
44  */
45 
46 #include <sys/cdefs.h>
47 #include "opt_ddb.h"
48 #include "opt_vm.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/asan.h>
53 #include <sys/kdb.h>
54 #include <sys/kernel.h>
55 #include <sys/lock.h>
56 #include <sys/malloc.h>
57 #include <sys/msan.h>
58 #include <sys/mutex.h>
59 #include <sys/vmmeter.h>
60 #include <sys/proc.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/sysctl.h>
65 #include <sys/time.h>
66 #include <sys/vmem.h>
67 #ifdef EPOCH_TRACE
68 #include <sys/epoch.h>
69 #endif
70 
71 #include <vm/vm.h>
72 #include <vm/pmap.h>
73 #include <vm/vm_domainset.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_param.h>
76 #include <vm/vm_kern.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_phys.h>
81 #include <vm/vm_pagequeue.h>
82 #include <vm/uma.h>
83 #include <vm/uma_int.h>
84 #include <vm/uma_dbg.h>
85 
86 #ifdef DEBUG_MEMGUARD
87 #include <vm/memguard.h>
88 #endif
89 #ifdef DEBUG_REDZONE
90 #include <vm/redzone.h>
91 #endif
92 
93 #if defined(INVARIANTS) && defined(__i386__)
94 #include <machine/cpu.h>
95 #endif
96 
97 #include <ddb/ddb.h>
98 
99 #ifdef KDTRACE_HOOKS
100 #include <sys/dtrace_bsd.h>
101 
102 bool	__read_frequently			dtrace_malloc_enabled;
103 dtrace_malloc_probe_func_t __read_mostly	dtrace_malloc_probe;
104 #endif
105 
106 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
107     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
108 #define	MALLOC_DEBUG	1
109 #endif
110 
111 #if defined(KASAN) || defined(DEBUG_REDZONE)
112 #define	DEBUG_REDZONE_ARG_DEF	, unsigned long osize
113 #define	DEBUG_REDZONE_ARG	, osize
114 #else
115 #define	DEBUG_REDZONE_ARG_DEF
116 #define	DEBUG_REDZONE_ARG
117 #endif
118 
119 typedef	enum {
120 	SLAB_COOKIE_SLAB_PTR		= 0x0,
121 	SLAB_COOKIE_MALLOC_LARGE	= 0x1,
122 	SLAB_COOKIE_CONTIG_MALLOC	= 0x2,
123 } slab_cookie_t;
124 #define	SLAB_COOKIE_MASK		0x3
125 #define	SLAB_COOKIE_SHIFT		2
126 #define	GET_SLAB_COOKIE(_slab)						\
127     ((slab_cookie_t)(uintptr_t)(_slab) & SLAB_COOKIE_MASK)
128 
129 /*
130  * When realloc() is called, if the new size is sufficiently smaller than
131  * the old size, realloc() will allocate a new, smaller block to avoid
132  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
133  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
134  */
135 #ifndef REALLOC_FRACTION
136 #define	REALLOC_FRACTION	1	/* new block if <= half the size */
137 #endif
138 
139 /*
140  * Centrally define some common malloc types.
141  */
142 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
143 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
144 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
145 
146 static struct malloc_type *kmemstatistics;
147 static int kmemcount;
148 
149 #define KMEM_ZSHIFT	4
150 #define KMEM_ZBASE	16
151 #define KMEM_ZMASK	(KMEM_ZBASE - 1)
152 
153 #define KMEM_ZMAX	65536
154 #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
155 static uint8_t kmemsize[KMEM_ZSIZE + 1];
156 
157 #ifndef MALLOC_DEBUG_MAXZONES
158 #define	MALLOC_DEBUG_MAXZONES	1
159 #endif
160 static int numzones = MALLOC_DEBUG_MAXZONES;
161 
162 /*
163  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
164  * of various sizes.
165  *
166  * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
167  *
168  * XXX: The comment here used to read "These won't be powers of two for
169  * long."  It's possible that a significant amount of wasted memory could be
170  * recovered by tuning the sizes of these buckets.
171  */
172 struct {
173 	int kz_size;
174 	const char *kz_name;
175 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
176 } kmemzones[] = {
177 	{16, "malloc-16", },
178 	{32, "malloc-32", },
179 	{64, "malloc-64", },
180 	{128, "malloc-128", },
181 	{256, "malloc-256", },
182 	{384, "malloc-384", },
183 	{512, "malloc-512", },
184 	{1024, "malloc-1024", },
185 	{2048, "malloc-2048", },
186 	{4096, "malloc-4096", },
187 	{8192, "malloc-8192", },
188 	{16384, "malloc-16384", },
189 	{32768, "malloc-32768", },
190 	{65536, "malloc-65536", },
191 	{0, NULL},
192 };
193 
194 u_long vm_kmem_size;
195 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
196     "Size of kernel memory");
197 
198 static u_long kmem_zmax = KMEM_ZMAX;
199 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
200     "Maximum allocation size that malloc(9) would use UMA as backend");
201 
202 static u_long vm_kmem_size_min;
203 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
204     "Minimum size of kernel memory");
205 
206 static u_long vm_kmem_size_max;
207 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
208     "Maximum size of kernel memory");
209 
210 static u_int vm_kmem_size_scale;
211 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
212     "Scale factor for kernel memory size");
213 
214 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
215 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
216     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
217     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
218 
219 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
220 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
221     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
222     sysctl_kmem_map_free, "LU", "Free space in kmem");
223 
224 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
225     "Malloc information");
226 
227 static u_int vm_malloc_zone_count = nitems(kmemzones);
228 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
229     CTLFLAG_RD, &vm_malloc_zone_count, 0,
230     "Number of malloc zones");
231 
232 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
233 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
234     CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
235     sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
236 
237 /*
238  * The malloc_mtx protects the kmemstatistics linked list.
239  */
240 struct mtx malloc_mtx;
241 
242 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
243 
244 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
245 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
246     "Kernel malloc debugging options");
247 #endif
248 
249 /*
250  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
251  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
252  */
253 #ifdef MALLOC_MAKE_FAILURES
254 static int malloc_failure_rate;
255 static int malloc_nowait_count;
256 static int malloc_failure_count;
257 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
258     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
259 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
260     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
261 #endif
262 
263 static int
264 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
265 {
266 	u_long size;
267 
268 	size = uma_size();
269 	return (sysctl_handle_long(oidp, &size, 0, req));
270 }
271 
272 static int
273 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
274 {
275 	u_long size, limit;
276 
277 	/* The sysctl is unsigned, implement as a saturation value. */
278 	size = uma_size();
279 	limit = uma_limit();
280 	if (size > limit)
281 		size = 0;
282 	else
283 		size = limit - size;
284 	return (sysctl_handle_long(oidp, &size, 0, req));
285 }
286 
287 static int
288 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
289 {
290 	int sizes[nitems(kmemzones)];
291 	int i;
292 
293 	for (i = 0; i < nitems(kmemzones); i++) {
294 		sizes[i] = kmemzones[i].kz_size;
295 	}
296 
297 	return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
298 }
299 
300 /*
301  * malloc(9) uma zone separation -- sub-page buffer overruns in one
302  * malloc type will affect only a subset of other malloc types.
303  */
304 #if MALLOC_DEBUG_MAXZONES > 1
305 static void
306 tunable_set_numzones(void)
307 {
308 
309 	TUNABLE_INT_FETCH("debug.malloc.numzones",
310 	    &numzones);
311 
312 	/* Sanity check the number of malloc uma zones. */
313 	if (numzones <= 0)
314 		numzones = 1;
315 	if (numzones > MALLOC_DEBUG_MAXZONES)
316 		numzones = MALLOC_DEBUG_MAXZONES;
317 }
318 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
319 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
320     &numzones, 0, "Number of malloc uma subzones");
321 
322 /*
323  * Any number that changes regularly is an okay choice for the
324  * offset.  Build numbers are pretty good of you have them.
325  */
326 static u_int zone_offset = __FreeBSD_version;
327 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
328 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
329     &zone_offset, 0, "Separate malloc types by examining the "
330     "Nth character in the malloc type short description.");
331 
332 static void
333 mtp_set_subzone(struct malloc_type *mtp)
334 {
335 	struct malloc_type_internal *mtip;
336 	const char *desc;
337 	size_t len;
338 	u_int val;
339 
340 	mtip = &mtp->ks_mti;
341 	desc = mtp->ks_shortdesc;
342 	if (desc == NULL || (len = strlen(desc)) == 0)
343 		val = 0;
344 	else
345 		val = desc[zone_offset % len];
346 	mtip->mti_zone = (val % numzones);
347 }
348 
349 static inline u_int
350 mtp_get_subzone(struct malloc_type *mtp)
351 {
352 	struct malloc_type_internal *mtip;
353 
354 	mtip = &mtp->ks_mti;
355 
356 	KASSERT(mtip->mti_zone < numzones,
357 	    ("mti_zone %u out of range %d",
358 	    mtip->mti_zone, numzones));
359 	return (mtip->mti_zone);
360 }
361 #elif MALLOC_DEBUG_MAXZONES == 0
362 #error "MALLOC_DEBUG_MAXZONES must be positive."
363 #else
364 static void
365 mtp_set_subzone(struct malloc_type *mtp)
366 {
367 	struct malloc_type_internal *mtip;
368 
369 	mtip = &mtp->ks_mti;
370 	mtip->mti_zone = 0;
371 }
372 
373 static inline u_int
374 mtp_get_subzone(struct malloc_type *mtp)
375 {
376 
377 	return (0);
378 }
379 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
380 
381 /*
382  * An allocation has succeeded -- update malloc type statistics for the
383  * amount of bucket size.  Occurs within a critical section so that the
384  * thread isn't preempted and doesn't migrate while updating per-PCU
385  * statistics.
386  */
387 static void
388 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
389     int zindx)
390 {
391 	struct malloc_type_internal *mtip;
392 	struct malloc_type_stats *mtsp;
393 
394 	critical_enter();
395 	mtip = &mtp->ks_mti;
396 	mtsp = zpcpu_get(mtip->mti_stats);
397 	if (size > 0) {
398 		mtsp->mts_memalloced += size;
399 		mtsp->mts_numallocs++;
400 	}
401 	if (zindx != -1)
402 		mtsp->mts_size |= 1 << zindx;
403 
404 #ifdef KDTRACE_HOOKS
405 	if (__predict_false(dtrace_malloc_enabled)) {
406 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
407 		if (probe_id != 0)
408 			(dtrace_malloc_probe)(probe_id,
409 			    (uintptr_t) mtp, (uintptr_t) mtip,
410 			    (uintptr_t) mtsp, size, zindx);
411 	}
412 #endif
413 
414 	critical_exit();
415 }
416 
417 void
418 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
419 {
420 
421 	if (size > 0)
422 		malloc_type_zone_allocated(mtp, size, -1);
423 }
424 
425 /*
426  * A free operation has occurred -- update malloc type statistics for the
427  * amount of the bucket size.  Occurs within a critical section so that the
428  * thread isn't preempted and doesn't migrate while updating per-CPU
429  * statistics.
430  */
431 void
432 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
433 {
434 	struct malloc_type_internal *mtip;
435 	struct malloc_type_stats *mtsp;
436 
437 	critical_enter();
438 	mtip = &mtp->ks_mti;
439 	mtsp = zpcpu_get(mtip->mti_stats);
440 	mtsp->mts_memfreed += size;
441 	mtsp->mts_numfrees++;
442 
443 #ifdef KDTRACE_HOOKS
444 	if (__predict_false(dtrace_malloc_enabled)) {
445 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
446 		if (probe_id != 0)
447 			(dtrace_malloc_probe)(probe_id,
448 			    (uintptr_t) mtp, (uintptr_t) mtip,
449 			    (uintptr_t) mtsp, size, 0);
450 	}
451 #endif
452 
453 	critical_exit();
454 }
455 
456 /*
457  *	contigmalloc:
458  *
459  *	Allocate a block of physically contiguous memory.
460  *
461  *	If M_NOWAIT is set, this routine will not block and return NULL if
462  *	the allocation fails.
463  */
464 #define	IS_CONTIG_MALLOC(_slab)						\
465     (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_CONTIG_MALLOC)
466 #define	CONTIG_MALLOC_SLAB(_size)					\
467     ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_CONTIG_MALLOC))
468 static inline size_t
469 contigmalloc_size(uma_slab_t slab)
470 {
471 	uintptr_t va;
472 
473 	KASSERT(IS_CONTIG_MALLOC(slab),
474 	    ("%s: called on non-contigmalloc allocation: %p", __func__, slab));
475 	va = (uintptr_t)slab;
476 	return (va >> SLAB_COOKIE_SHIFT);
477 }
478 
479 void *
480 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
481     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
482     vm_paddr_t boundary)
483 {
484 	void *ret;
485 
486 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
487 	    boundary, VM_MEMATTR_DEFAULT);
488 	if (ret != NULL) {
489 		/* Use low bits unused for slab pointers. */
490 		vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
491 		malloc_type_allocated(type, round_page(size));
492 	}
493 	return (ret);
494 }
495 
496 void *
497 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
498     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
499     unsigned long alignment, vm_paddr_t boundary)
500 {
501 	void *ret;
502 
503 	ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
504 	    alignment, boundary, VM_MEMATTR_DEFAULT);
505 	if (ret != NULL) {
506 		/* Use low bits unused for slab pointers. */
507 		vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
508 		malloc_type_allocated(type, round_page(size));
509 	}
510 	return (ret);
511 }
512 #undef	IS_CONTIG_MALLOC
513 #undef	CONTIG_MALLOC_SLAB
514 
515 /* contigfree(9) is deprecated. */
516 void
517 contigfree(void *addr, unsigned long size __unused, struct malloc_type *type)
518 {
519 	free(addr, type);
520 }
521 
522 #ifdef MALLOC_DEBUG
523 static int
524 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
525     int flags)
526 {
527 #ifdef INVARIANTS
528 	int indx;
529 
530 	KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
531 	/*
532 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
533 	 */
534 	indx = flags & (M_WAITOK | M_NOWAIT);
535 	if (indx != M_NOWAIT && indx != M_WAITOK) {
536 		static	struct timeval lasterr;
537 		static	int curerr, once;
538 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
539 			printf("Bad malloc flags: %x\n", indx);
540 			kdb_backtrace();
541 			flags |= M_WAITOK;
542 			once++;
543 		}
544 	}
545 	KASSERT((flags & M_NEVERFREED) == 0,
546 	    ("malloc: M_NEVERFREED is for internal use only"));
547 #endif
548 #ifdef MALLOC_MAKE_FAILURES
549 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
550 		atomic_add_int(&malloc_nowait_count, 1);
551 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
552 			atomic_add_int(&malloc_failure_count, 1);
553 			*vap = NULL;
554 			return (EJUSTRETURN);
555 		}
556 	}
557 #endif
558 	if (flags & M_WAITOK) {
559 		KASSERT(curthread->td_intr_nesting_level == 0,
560 		   ("malloc(M_WAITOK) in interrupt context"));
561 		if (__predict_false(!THREAD_CAN_SLEEP())) {
562 #ifdef EPOCH_TRACE
563 			epoch_trace_list(curthread);
564 #endif
565 			KASSERT(0,
566 			    ("malloc(M_WAITOK) with sleeping prohibited"));
567 		}
568 	}
569 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
570 	    ("malloc: called with spinlock or critical section held"));
571 
572 #ifdef DEBUG_MEMGUARD
573 	if (memguard_cmp_mtp(mtp, *sizep)) {
574 		*vap = memguard_alloc(*sizep, flags);
575 		if (*vap != NULL)
576 			return (EJUSTRETURN);
577 		/* This is unfortunate but should not be fatal. */
578 	}
579 #endif
580 
581 #ifdef DEBUG_REDZONE
582 	*sizep = redzone_size_ntor(*sizep);
583 #endif
584 
585 	return (0);
586 }
587 #endif
588 
589 /*
590  * Handle large allocations and frees by using kmem_malloc directly.
591  */
592 #define	IS_MALLOC_LARGE(_slab)						\
593     (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_MALLOC_LARGE)
594 #define	MALLOC_LARGE_SLAB(_size)					\
595     ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_MALLOC_LARGE))
596 static inline size_t
597 malloc_large_size(uma_slab_t slab)
598 {
599 	uintptr_t va;
600 
601 	va = (uintptr_t)slab;
602 	KASSERT(IS_MALLOC_LARGE(slab),
603 	    ("%s: called on non-malloc_large allocation: %p", __func__, slab));
604 	return (va >> SLAB_COOKIE_SHIFT);
605 }
606 
607 static caddr_t __noinline
608 malloc_large(size_t size, struct malloc_type *mtp, struct domainset *policy,
609     int flags DEBUG_REDZONE_ARG_DEF)
610 {
611 	void *va;
612 
613 	size = roundup(size, PAGE_SIZE);
614 	va = kmem_malloc_domainset(policy, size, flags);
615 	if (va != NULL) {
616 		/* Use low bits unused for slab pointers. */
617 		vsetzoneslab((uintptr_t)va, NULL, MALLOC_LARGE_SLAB(size));
618 		uma_total_inc(size);
619 	}
620 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
621 	if (__predict_false(va == NULL)) {
622 		KASSERT((flags & M_WAITOK) == 0,
623 		    ("malloc(M_WAITOK) returned NULL"));
624 	} else {
625 #ifdef DEBUG_REDZONE
626 		va = redzone_setup(va, osize);
627 #endif
628 		kasan_mark(va, osize, size, KASAN_MALLOC_REDZONE);
629 	}
630 	return (va);
631 }
632 
633 static void
634 free_large(void *addr, size_t size)
635 {
636 
637 	kmem_free(addr, size);
638 	uma_total_dec(size);
639 }
640 #undef	IS_MALLOC_LARGE
641 #undef	MALLOC_LARGE_SLAB
642 
643 /*
644  *	malloc:
645  *
646  *	Allocate a block of memory.
647  *
648  *	If M_NOWAIT is set, this routine will not block and return NULL if
649  *	the allocation fails.
650  */
651 void *
652 (malloc)(size_t size, struct malloc_type *mtp, int flags)
653 {
654 	int indx;
655 	caddr_t va;
656 	uma_zone_t zone;
657 #if defined(DEBUG_REDZONE) || defined(KASAN)
658 	unsigned long osize = size;
659 #endif
660 
661 	MPASS((flags & M_EXEC) == 0);
662 
663 #ifdef MALLOC_DEBUG
664 	va = NULL;
665 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
666 		return (va);
667 #endif
668 
669 	if (__predict_false(size > kmem_zmax))
670 		return (malloc_large(size, mtp, DOMAINSET_RR(), flags
671 		    DEBUG_REDZONE_ARG));
672 
673 	if (size & KMEM_ZMASK)
674 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
675 	indx = kmemsize[size >> KMEM_ZSHIFT];
676 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
677 	va = uma_zalloc_arg(zone, zone, flags);
678 	if (va != NULL) {
679 		size = zone->uz_size;
680 		if ((flags & M_ZERO) == 0) {
681 			kmsan_mark(va, size, KMSAN_STATE_UNINIT);
682 			kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
683 		}
684 	}
685 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
686 	if (__predict_false(va == NULL)) {
687 		KASSERT((flags & M_WAITOK) == 0,
688 		    ("malloc(M_WAITOK) returned NULL"));
689 	}
690 #ifdef DEBUG_REDZONE
691 	if (va != NULL)
692 		va = redzone_setup(va, osize);
693 #endif
694 #ifdef KASAN
695 	if (va != NULL)
696 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
697 #endif
698 	return ((void *) va);
699 }
700 
701 static void *
702 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
703     int flags)
704 {
705 	uma_zone_t zone;
706 	caddr_t va;
707 	size_t size;
708 	int indx;
709 
710 	size = *sizep;
711 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
712 	    ("malloc_domain: Called with bad flag / size combination"));
713 	if (size & KMEM_ZMASK)
714 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
715 	indx = kmemsize[size >> KMEM_ZSHIFT];
716 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
717 	va = uma_zalloc_domain(zone, zone, domain, flags);
718 	if (va != NULL)
719 		*sizep = zone->uz_size;
720 	*indxp = indx;
721 	return ((void *)va);
722 }
723 
724 void *
725 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
726     int flags)
727 {
728 	struct vm_domainset_iter di;
729 	caddr_t va;
730 	int domain;
731 	int indx;
732 #if defined(KASAN) || defined(DEBUG_REDZONE)
733 	unsigned long osize = size;
734 #endif
735 
736 	MPASS((flags & M_EXEC) == 0);
737 
738 #ifdef MALLOC_DEBUG
739 	va = NULL;
740 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
741 		return (va);
742 #endif
743 
744 	if (__predict_false(size > kmem_zmax))
745 		return (malloc_large(size, mtp, DOMAINSET_RR(), flags
746 		    DEBUG_REDZONE_ARG));
747 
748 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
749 	do {
750 		va = malloc_domain(&size, &indx, mtp, domain, flags);
751 	} while (va == NULL && vm_domainset_iter_policy(&di, &domain) == 0);
752 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
753 	if (__predict_false(va == NULL)) {
754 		KASSERT((flags & M_WAITOK) == 0,
755 		    ("malloc(M_WAITOK) returned NULL"));
756 	}
757 #ifdef DEBUG_REDZONE
758 	if (va != NULL)
759 		va = redzone_setup(va, osize);
760 #endif
761 #ifdef KASAN
762 	if (va != NULL)
763 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
764 #endif
765 #ifdef KMSAN
766 	if ((flags & M_ZERO) == 0) {
767 		kmsan_mark(va, size, KMSAN_STATE_UNINIT);
768 		kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
769 	}
770 #endif
771 	return (va);
772 }
773 
774 /*
775  * Allocate an executable area.
776  */
777 void *
778 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
779 {
780 
781 	return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
782 }
783 
784 void *
785 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
786     int flags)
787 {
788 #if defined(DEBUG_REDZONE) || defined(KASAN)
789 	unsigned long osize = size;
790 #endif
791 #ifdef MALLOC_DEBUG
792 	caddr_t va;
793 #endif
794 
795 	flags |= M_EXEC;
796 
797 #ifdef MALLOC_DEBUG
798 	va = NULL;
799 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
800 		return (va);
801 #endif
802 
803 	return (malloc_large(size, mtp, ds, flags DEBUG_REDZONE_ARG));
804 }
805 
806 void *
807 malloc_aligned(size_t size, size_t align, struct malloc_type *type, int flags)
808 {
809 	return (malloc_domainset_aligned(size, align, type, DOMAINSET_RR(),
810 	    flags));
811 }
812 
813 void *
814 malloc_domainset_aligned(size_t size, size_t align,
815     struct malloc_type *mtp, struct domainset *ds, int flags)
816 {
817 	void *res;
818 	size_t asize;
819 
820 	KASSERT(powerof2(align),
821 	    ("malloc_domainset_aligned: wrong align %#zx size %#zx",
822 	    align, size));
823 	KASSERT(align <= PAGE_SIZE,
824 	    ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
825 	    align, size));
826 
827 	/*
828 	 * Round the allocation size up to the next power of 2,
829 	 * because we can only guarantee alignment for
830 	 * power-of-2-sized allocations.  Further increase the
831 	 * allocation size to align if the rounded size is less than
832 	 * align, since malloc zones provide alignment equal to their
833 	 * size.
834 	 */
835 	if (size == 0)
836 		size = 1;
837 	asize = size <= align ? align : 1UL << flsl(size - 1);
838 
839 	res = malloc_domainset(asize, mtp, ds, flags);
840 	KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
841 	    ("malloc_domainset_aligned: result not aligned %p size %#zx "
842 	    "allocsize %#zx align %#zx", res, size, asize, align));
843 	return (res);
844 }
845 
846 void *
847 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
848 {
849 
850 	if (WOULD_OVERFLOW(nmemb, size))
851 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
852 
853 	return (malloc(size * nmemb, type, flags));
854 }
855 
856 void *
857 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
858     struct domainset *ds, int flags)
859 {
860 
861 	if (WOULD_OVERFLOW(nmemb, size))
862 		panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
863 
864 	return (malloc_domainset(size * nmemb, type, ds, flags));
865 }
866 
867 #if defined(INVARIANTS) && !defined(KASAN)
868 static void
869 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
870 {
871 	struct malloc_type **mtpp = addr;
872 
873 	/*
874 	 * Cache a pointer to the malloc_type that most recently freed
875 	 * this memory here.  This way we know who is most likely to
876 	 * have stepped on it later.
877 	 *
878 	 * This code assumes that size is a multiple of 8 bytes for
879 	 * 64 bit machines
880 	 */
881 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
882 	mtpp += (size - sizeof(struct malloc_type *)) /
883 	    sizeof(struct malloc_type *);
884 	*mtpp = mtp;
885 }
886 #endif
887 
888 #ifdef MALLOC_DEBUG
889 static int
890 free_dbg(void **addrp, struct malloc_type *mtp)
891 {
892 	void *addr;
893 
894 	addr = *addrp;
895 	KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
896 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
897 	    ("free: called with spinlock or critical section held"));
898 
899 	/* free(NULL, ...) does nothing */
900 	if (addr == NULL)
901 		return (EJUSTRETURN);
902 
903 #ifdef DEBUG_MEMGUARD
904 	if (is_memguard_addr(addr)) {
905 		memguard_free(addr);
906 		return (EJUSTRETURN);
907 	}
908 #endif
909 
910 #ifdef DEBUG_REDZONE
911 	redzone_check(addr);
912 	*addrp = redzone_addr_ntor(addr);
913 #endif
914 
915 	return (0);
916 }
917 #endif
918 
919 static __always_inline void
920 _free(void *addr, struct malloc_type *mtp, bool dozero)
921 {
922 	uma_zone_t zone;
923 	uma_slab_t slab;
924 	u_long size;
925 
926 #ifdef MALLOC_DEBUG
927 	if (free_dbg(&addr, mtp) != 0)
928 		return;
929 #endif
930 	/* free(NULL, ...) does nothing */
931 	if (addr == NULL)
932 		return;
933 
934 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
935 	if (slab == NULL)
936 		panic("%s(%d): address %p(%p) has not been allocated", __func__,
937 		    dozero, addr, (void *)((uintptr_t)addr & (~UMA_SLAB_MASK)));
938 
939 	switch (GET_SLAB_COOKIE(slab)) {
940 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
941 		size = zone->uz_size;
942 #if defined(INVARIANTS) && !defined(KASAN)
943 		free_save_type(addr, mtp, size);
944 #endif
945 		if (dozero) {
946 			kasan_mark(addr, size, size, 0);
947 			explicit_bzero(addr, size);
948 		}
949 		uma_zfree_arg(zone, addr, slab);
950 		break;
951 	case SLAB_COOKIE_MALLOC_LARGE:
952 		size = malloc_large_size(slab);
953 		if (dozero) {
954 			kasan_mark(addr, size, size, 0);
955 			explicit_bzero(addr, size);
956 		}
957 		free_large(addr, size);
958 		break;
959 	case SLAB_COOKIE_CONTIG_MALLOC:
960 		size = round_page(contigmalloc_size(slab));
961 		if (dozero)
962 			explicit_bzero(addr, size);
963 		kmem_free(addr, size);
964 		break;
965 	default:
966 		panic("%s(%d): addr %p slab %p with unknown cookie %d",
967 		    __func__, dozero, addr, slab, GET_SLAB_COOKIE(slab));
968 		/* NOTREACHED */
969 	}
970 	malloc_type_freed(mtp, size);
971 }
972 
973 /*
974  * free:
975  *	Free a block of memory allocated by malloc/contigmalloc.
976  *	This routine may not block.
977  */
978 void
979 free(void *addr, struct malloc_type *mtp)
980 {
981 	_free(addr, mtp, false);
982 }
983 
984 /*
985  * zfree:
986  *	Zero then free a block of memory allocated by malloc/contigmalloc.
987  *	This routine may not block.
988  */
989 void
990 zfree(void *addr, struct malloc_type *mtp)
991 {
992 	_free(addr, mtp, true);
993 }
994 
995 /*
996  *	realloc: change the size of a memory block
997  */
998 void *
999 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
1000 {
1001 #ifndef DEBUG_REDZONE
1002 	uma_zone_t zone;
1003 	uma_slab_t slab;
1004 #endif
1005 	unsigned long alloc;
1006 	void *newaddr;
1007 
1008 	KASSERT(mtp->ks_version == M_VERSION,
1009 	    ("realloc: bad malloc type version"));
1010 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
1011 	    ("realloc: called with spinlock or critical section held"));
1012 
1013 	/* realloc(NULL, ...) is equivalent to malloc(...) */
1014 	if (addr == NULL)
1015 		return (malloc(size, mtp, flags));
1016 
1017 	/*
1018 	 * XXX: Should report free of old memory and alloc of new memory to
1019 	 * per-CPU stats.
1020 	 */
1021 
1022 #ifdef DEBUG_MEMGUARD
1023 	if (is_memguard_addr(addr))
1024 		return (memguard_realloc(addr, size, mtp, flags));
1025 #endif
1026 
1027 #ifdef DEBUG_REDZONE
1028 	alloc = redzone_get_size(addr);
1029 #else
1030 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1031 
1032 	/* Sanity check */
1033 	KASSERT(slab != NULL,
1034 	    ("realloc: address %p out of range", (void *)addr));
1035 
1036 	/* Get the size of the original block */
1037 	switch (GET_SLAB_COOKIE(slab)) {
1038 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1039 		alloc = zone->uz_size;
1040 		break;
1041 	case SLAB_COOKIE_MALLOC_LARGE:
1042 		alloc = malloc_large_size(slab);
1043 		break;
1044 	default:
1045 #ifdef INVARIANTS
1046 		panic("%s: called for addr %p of unsupported allocation type; "
1047 		    "slab %p cookie %d", __func__, addr, slab, GET_SLAB_COOKIE(slab));
1048 #endif
1049 		return (NULL);
1050 	}
1051 
1052 	/* Reuse the original block if appropriate */
1053 	if (size <= alloc &&
1054 	    (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1055 		kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1056 		return (addr);
1057 	}
1058 #endif /* !DEBUG_REDZONE */
1059 
1060 	/* Allocate a new, bigger (or smaller) block */
1061 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
1062 		return (NULL);
1063 
1064 	/*
1065 	 * Copy over original contents.  For KASAN, the redzone must be marked
1066 	 * valid before performing the copy.
1067 	 */
1068 	kasan_mark(addr, alloc, alloc, 0);
1069 	bcopy(addr, newaddr, min(size, alloc));
1070 	free(addr, mtp);
1071 	return (newaddr);
1072 }
1073 
1074 /*
1075  *	reallocf: same as realloc() but free memory on failure.
1076  */
1077 void *
1078 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1079 {
1080 	void *mem;
1081 
1082 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1083 		free(addr, mtp);
1084 	return (mem);
1085 }
1086 
1087 /*
1088  * 	malloc_size: returns the number of bytes allocated for a request of the
1089  * 		     specified size
1090  */
1091 size_t
1092 malloc_size(size_t size)
1093 {
1094 	int indx;
1095 
1096 	if (size > kmem_zmax)
1097 		return (round_page(size));
1098 	if (size & KMEM_ZMASK)
1099 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1100 	indx = kmemsize[size >> KMEM_ZSHIFT];
1101 	return (kmemzones[indx].kz_size);
1102 }
1103 
1104 /*
1105  *	malloc_usable_size: returns the usable size of the allocation.
1106  */
1107 size_t
1108 malloc_usable_size(const void *addr)
1109 {
1110 #ifndef DEBUG_REDZONE
1111 	uma_zone_t zone;
1112 	uma_slab_t slab;
1113 #endif
1114 	u_long size;
1115 
1116 	if (addr == NULL)
1117 		return (0);
1118 
1119 #ifdef DEBUG_MEMGUARD
1120 	if (is_memguard_addr(__DECONST(void *, addr)))
1121 		return (memguard_get_req_size(addr));
1122 #endif
1123 
1124 #ifdef DEBUG_REDZONE
1125 	size = redzone_get_size(__DECONST(void *, addr));
1126 #else
1127 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1128 	if (slab == NULL)
1129 		panic("malloc_usable_size: address %p(%p) is not allocated",
1130 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1131 
1132 	switch (GET_SLAB_COOKIE(slab)) {
1133 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1134 		size = zone->uz_size;
1135 		break;
1136 	case SLAB_COOKIE_MALLOC_LARGE:
1137 		size = malloc_large_size(slab);
1138 		break;
1139 	default:
1140 		__assert_unreachable();
1141 		size = 0;
1142 		break;
1143 	}
1144 #endif
1145 
1146 	/*
1147 	 * Unmark the redzone to avoid reports from consumers who are
1148 	 * (presumably) about to use the full allocation size.
1149 	 */
1150 	kasan_mark(addr, size, size, 0);
1151 
1152 	return (size);
1153 }
1154 
1155 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1156 
1157 /*
1158  * Initialize the kernel memory (kmem) arena.
1159  */
1160 void
1161 kmeminit(void)
1162 {
1163 	u_long mem_size;
1164 	u_long tmp;
1165 
1166 #ifdef VM_KMEM_SIZE
1167 	if (vm_kmem_size == 0)
1168 		vm_kmem_size = VM_KMEM_SIZE;
1169 #endif
1170 #ifdef VM_KMEM_SIZE_MIN
1171 	if (vm_kmem_size_min == 0)
1172 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1173 #endif
1174 #ifdef VM_KMEM_SIZE_MAX
1175 	if (vm_kmem_size_max == 0)
1176 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1177 #endif
1178 	/*
1179 	 * Calculate the amount of kernel virtual address (KVA) space that is
1180 	 * preallocated to the kmem arena.  In order to support a wide range
1181 	 * of machines, it is a function of the physical memory size,
1182 	 * specifically,
1183 	 *
1184 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1185 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1186 	 *
1187 	 * Every architecture must define an integral value for
1188 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1189 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1190 	 * ceiling on this preallocation, are optional.  Typically,
1191 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1192 	 * a given architecture.
1193 	 */
1194 	mem_size = vm_cnt.v_page_count;
1195 	if (mem_size <= 32768) /* delphij XXX 128MB */
1196 		kmem_zmax = PAGE_SIZE;
1197 
1198 	if (vm_kmem_size_scale < 1)
1199 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1200 
1201 	/*
1202 	 * Check if we should use defaults for the "vm_kmem_size"
1203 	 * variable:
1204 	 */
1205 	if (vm_kmem_size == 0) {
1206 		vm_kmem_size = mem_size / vm_kmem_size_scale;
1207 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1208 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1209 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1210 			vm_kmem_size = vm_kmem_size_min;
1211 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1212 			vm_kmem_size = vm_kmem_size_max;
1213 	}
1214 	if (vm_kmem_size == 0)
1215 		panic("Tune VM_KMEM_SIZE_* for the platform");
1216 
1217 	/*
1218 	 * The amount of KVA space that is preallocated to the
1219 	 * kmem arena can be set statically at compile-time or manually
1220 	 * through the kernel environment.  However, it is still limited to
1221 	 * twice the physical memory size, which has been sufficient to handle
1222 	 * the most severe cases of external fragmentation in the kmem arena.
1223 	 */
1224 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1225 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1226 
1227 	vm_kmem_size = round_page(vm_kmem_size);
1228 
1229 	/*
1230 	 * With KASAN or KMSAN enabled, dynamically allocated kernel memory is
1231 	 * shadowed.  Account for this when setting the UMA limit.
1232 	 */
1233 #if defined(KASAN)
1234 	vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1235 	    (KASAN_SHADOW_SCALE + 1);
1236 #elif defined(KMSAN)
1237 	vm_kmem_size /= 3;
1238 #endif
1239 
1240 #ifdef DEBUG_MEMGUARD
1241 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1242 #else
1243 	tmp = vm_kmem_size;
1244 #endif
1245 	uma_set_limit(tmp);
1246 
1247 #ifdef DEBUG_MEMGUARD
1248 	/*
1249 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1250 	 * replacement allocator used for detecting tamper-after-free
1251 	 * scenarios as they occur.  It is only used for debugging.
1252 	 */
1253 	memguard_init(kernel_arena);
1254 #endif
1255 }
1256 
1257 /*
1258  * Initialize the kernel memory allocator
1259  */
1260 /* ARGSUSED*/
1261 static void
1262 mallocinit(void *dummy)
1263 {
1264 	int i;
1265 	uint8_t indx;
1266 
1267 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1268 
1269 	kmeminit();
1270 
1271 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1272 		kmem_zmax = KMEM_ZMAX;
1273 
1274 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1275 		int size = kmemzones[indx].kz_size;
1276 		const char *name = kmemzones[indx].kz_name;
1277 		size_t align;
1278 		int subzone;
1279 
1280 		align = UMA_ALIGN_PTR;
1281 		if (powerof2(size) && size > sizeof(void *))
1282 			align = MIN(size, PAGE_SIZE) - 1;
1283 		for (subzone = 0; subzone < numzones; subzone++) {
1284 			kmemzones[indx].kz_zone[subzone] =
1285 			    uma_zcreate(name, size,
1286 #if defined(INVARIANTS) && !defined(KASAN) && !defined(KMSAN)
1287 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1288 #else
1289 			    NULL, NULL, NULL, NULL,
1290 #endif
1291 			    align, UMA_ZONE_MALLOC);
1292 		}
1293 		for (;i <= size; i+= KMEM_ZBASE)
1294 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1295 	}
1296 }
1297 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1298 
1299 void
1300 malloc_init(void *data)
1301 {
1302 	struct malloc_type_internal *mtip;
1303 	struct malloc_type *mtp;
1304 
1305 	KASSERT(vm_cnt.v_page_count != 0,
1306 	    ("malloc_init() called before vm_mem_init()"));
1307 
1308 	mtp = data;
1309 	if (mtp->ks_version != M_VERSION)
1310 		panic("malloc_init: type %s with unsupported version %lu",
1311 		    mtp->ks_shortdesc, mtp->ks_version);
1312 
1313 	mtip = &mtp->ks_mti;
1314 	mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1315 	mtp_set_subzone(mtp);
1316 
1317 	mtx_lock(&malloc_mtx);
1318 	mtp->ks_next = kmemstatistics;
1319 	kmemstatistics = mtp;
1320 	kmemcount++;
1321 	mtx_unlock(&malloc_mtx);
1322 }
1323 
1324 void
1325 malloc_uninit(void *data)
1326 {
1327 	struct malloc_type_internal *mtip;
1328 	struct malloc_type_stats *mtsp;
1329 	struct malloc_type *mtp, *temp;
1330 	long temp_allocs, temp_bytes;
1331 	int i;
1332 
1333 	mtp = data;
1334 	KASSERT(mtp->ks_version == M_VERSION,
1335 	    ("malloc_uninit: bad malloc type version"));
1336 
1337 	mtx_lock(&malloc_mtx);
1338 	mtip = &mtp->ks_mti;
1339 	if (mtp != kmemstatistics) {
1340 		for (temp = kmemstatistics; temp != NULL;
1341 		    temp = temp->ks_next) {
1342 			if (temp->ks_next == mtp) {
1343 				temp->ks_next = mtp->ks_next;
1344 				break;
1345 			}
1346 		}
1347 		KASSERT(temp,
1348 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1349 	} else
1350 		kmemstatistics = mtp->ks_next;
1351 	kmemcount--;
1352 	mtx_unlock(&malloc_mtx);
1353 
1354 	/*
1355 	 * Look for memory leaks.
1356 	 */
1357 	temp_allocs = temp_bytes = 0;
1358 	for (i = 0; i <= mp_maxid; i++) {
1359 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1360 		temp_allocs += mtsp->mts_numallocs;
1361 		temp_allocs -= mtsp->mts_numfrees;
1362 		temp_bytes += mtsp->mts_memalloced;
1363 		temp_bytes -= mtsp->mts_memfreed;
1364 	}
1365 	if (temp_allocs > 0 || temp_bytes > 0) {
1366 		printf("Warning: memory type %s leaked memory on destroy "
1367 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1368 		    temp_allocs, temp_bytes);
1369 	}
1370 
1371 	uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1372 }
1373 
1374 struct malloc_type *
1375 malloc_desc2type(const char *desc)
1376 {
1377 	struct malloc_type *mtp;
1378 
1379 	mtx_assert(&malloc_mtx, MA_OWNED);
1380 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1381 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1382 			return (mtp);
1383 	}
1384 	return (NULL);
1385 }
1386 
1387 static int
1388 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1389 {
1390 	struct malloc_type_stream_header mtsh;
1391 	struct malloc_type_internal *mtip;
1392 	struct malloc_type_stats *mtsp, zeromts;
1393 	struct malloc_type_header mth;
1394 	struct malloc_type *mtp;
1395 	int error, i;
1396 	struct sbuf sbuf;
1397 
1398 	error = sysctl_wire_old_buffer(req, 0);
1399 	if (error != 0)
1400 		return (error);
1401 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1402 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1403 	mtx_lock(&malloc_mtx);
1404 
1405 	bzero(&zeromts, sizeof(zeromts));
1406 
1407 	/*
1408 	 * Insert stream header.
1409 	 */
1410 	bzero(&mtsh, sizeof(mtsh));
1411 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1412 	mtsh.mtsh_maxcpus = MAXCPU;
1413 	mtsh.mtsh_count = kmemcount;
1414 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1415 
1416 	/*
1417 	 * Insert alternating sequence of type headers and type statistics.
1418 	 */
1419 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1420 		mtip = &mtp->ks_mti;
1421 
1422 		/*
1423 		 * Insert type header.
1424 		 */
1425 		bzero(&mth, sizeof(mth));
1426 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1427 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1428 
1429 		/*
1430 		 * Insert type statistics for each CPU.
1431 		 */
1432 		for (i = 0; i <= mp_maxid; i++) {
1433 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1434 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1435 		}
1436 		/*
1437 		 * Fill in the missing CPUs.
1438 		 */
1439 		for (; i < MAXCPU; i++) {
1440 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1441 		}
1442 	}
1443 	mtx_unlock(&malloc_mtx);
1444 	error = sbuf_finish(&sbuf);
1445 	sbuf_delete(&sbuf);
1446 	return (error);
1447 }
1448 
1449 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1450     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1451     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1452     "Return malloc types");
1453 
1454 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1455     "Count of kernel malloc types");
1456 
1457 void
1458 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1459 {
1460 	struct malloc_type *mtp, **bufmtp;
1461 	int count, i;
1462 	size_t buflen;
1463 
1464 	mtx_lock(&malloc_mtx);
1465 restart:
1466 	mtx_assert(&malloc_mtx, MA_OWNED);
1467 	count = kmemcount;
1468 	mtx_unlock(&malloc_mtx);
1469 
1470 	buflen = sizeof(struct malloc_type *) * count;
1471 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1472 
1473 	mtx_lock(&malloc_mtx);
1474 
1475 	if (count < kmemcount) {
1476 		free(bufmtp, M_TEMP);
1477 		goto restart;
1478 	}
1479 
1480 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1481 		bufmtp[i] = mtp;
1482 
1483 	mtx_unlock(&malloc_mtx);
1484 
1485 	for (i = 0; i < count; i++)
1486 		(func)(bufmtp[i], arg);
1487 
1488 	free(bufmtp, M_TEMP);
1489 }
1490 
1491 #ifdef DDB
1492 static int64_t
1493 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1494     uint64_t *inuse)
1495 {
1496 	const struct malloc_type_stats *mtsp;
1497 	uint64_t frees, alloced, freed;
1498 	int i;
1499 
1500 	*allocs = 0;
1501 	frees = 0;
1502 	alloced = 0;
1503 	freed = 0;
1504 	for (i = 0; i <= mp_maxid; i++) {
1505 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1506 
1507 		*allocs += mtsp->mts_numallocs;
1508 		frees += mtsp->mts_numfrees;
1509 		alloced += mtsp->mts_memalloced;
1510 		freed += mtsp->mts_memfreed;
1511 	}
1512 	*inuse = *allocs - frees;
1513 	return (alloced - freed);
1514 }
1515 
1516 DB_SHOW_COMMAND_FLAGS(malloc, db_show_malloc, DB_CMD_MEMSAFE)
1517 {
1518 	const char *fmt_hdr, *fmt_entry;
1519 	struct malloc_type *mtp;
1520 	uint64_t allocs, inuse;
1521 	int64_t size;
1522 	/* variables for sorting */
1523 	struct malloc_type *last_mtype, *cur_mtype;
1524 	int64_t cur_size, last_size;
1525 	int ties;
1526 
1527 	if (modif[0] == 'i') {
1528 		fmt_hdr = "%s,%s,%s,%s\n";
1529 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1530 	} else {
1531 		fmt_hdr = "%18s %12s  %12s %12s\n";
1532 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
1533 	}
1534 
1535 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1536 
1537 	/* Select sort, largest size first. */
1538 	last_mtype = NULL;
1539 	last_size = INT64_MAX;
1540 	for (;;) {
1541 		cur_mtype = NULL;
1542 		cur_size = -1;
1543 		ties = 0;
1544 
1545 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1546 			/*
1547 			 * In the case of size ties, print out mtypes
1548 			 * in the order they are encountered.  That is,
1549 			 * when we encounter the most recently output
1550 			 * mtype, we have already printed all preceding
1551 			 * ties, and we must print all following ties.
1552 			 */
1553 			if (mtp == last_mtype) {
1554 				ties = 1;
1555 				continue;
1556 			}
1557 			size = get_malloc_stats(&mtp->ks_mti, &allocs,
1558 			    &inuse);
1559 			if (size > cur_size && size < last_size + ties) {
1560 				cur_size = size;
1561 				cur_mtype = mtp;
1562 			}
1563 		}
1564 		if (cur_mtype == NULL)
1565 			break;
1566 
1567 		size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1568 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1569 		    howmany(size, 1024), allocs);
1570 
1571 		if (db_pager_quit)
1572 			break;
1573 
1574 		last_mtype = cur_mtype;
1575 		last_size = cur_size;
1576 	}
1577 }
1578 
1579 #if MALLOC_DEBUG_MAXZONES > 1
1580 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1581 {
1582 	struct malloc_type_internal *mtip;
1583 	struct malloc_type *mtp;
1584 	u_int subzone;
1585 
1586 	if (!have_addr) {
1587 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1588 		return;
1589 	}
1590 	mtp = (void *)addr;
1591 	if (mtp->ks_version != M_VERSION) {
1592 		db_printf("Version %lx does not match expected %x\n",
1593 		    mtp->ks_version, M_VERSION);
1594 		return;
1595 	}
1596 
1597 	mtip = &mtp->ks_mti;
1598 	subzone = mtip->mti_zone;
1599 
1600 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1601 		mtip = &mtp->ks_mti;
1602 		if (mtip->mti_zone != subzone)
1603 			continue;
1604 		db_printf("%s\n", mtp->ks_shortdesc);
1605 		if (db_pager_quit)
1606 			break;
1607 	}
1608 }
1609 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1610 #endif /* DDB */
1611