xref: /freebsd/sys/kern/kern_malloc.c (revision 357378bbdedf24ce2b90e9bd831af4a9db3ec70a)
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 #endif
546 #ifdef MALLOC_MAKE_FAILURES
547 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
548 		atomic_add_int(&malloc_nowait_count, 1);
549 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
550 			atomic_add_int(&malloc_failure_count, 1);
551 			*vap = NULL;
552 			return (EJUSTRETURN);
553 		}
554 	}
555 #endif
556 	if (flags & M_WAITOK) {
557 		KASSERT(curthread->td_intr_nesting_level == 0,
558 		   ("malloc(M_WAITOK) in interrupt context"));
559 		if (__predict_false(!THREAD_CAN_SLEEP())) {
560 #ifdef EPOCH_TRACE
561 			epoch_trace_list(curthread);
562 #endif
563 			KASSERT(0,
564 			    ("malloc(M_WAITOK) with sleeping prohibited"));
565 		}
566 	}
567 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
568 	    ("malloc: called with spinlock or critical section held"));
569 
570 #ifdef DEBUG_MEMGUARD
571 	if (memguard_cmp_mtp(mtp, *sizep)) {
572 		*vap = memguard_alloc(*sizep, flags);
573 		if (*vap != NULL)
574 			return (EJUSTRETURN);
575 		/* This is unfortunate but should not be fatal. */
576 	}
577 #endif
578 
579 #ifdef DEBUG_REDZONE
580 	*sizep = redzone_size_ntor(*sizep);
581 #endif
582 
583 	return (0);
584 }
585 #endif
586 
587 /*
588  * Handle large allocations and frees by using kmem_malloc directly.
589  */
590 #define	IS_MALLOC_LARGE(_slab)						\
591     (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_MALLOC_LARGE)
592 #define	MALLOC_LARGE_SLAB(_size)					\
593     ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_MALLOC_LARGE))
594 static inline size_t
595 malloc_large_size(uma_slab_t slab)
596 {
597 	uintptr_t va;
598 
599 	va = (uintptr_t)slab;
600 	KASSERT(IS_MALLOC_LARGE(slab),
601 	    ("%s: called on non-malloc_large allocation: %p", __func__, slab));
602 	return (va >> SLAB_COOKIE_SHIFT);
603 }
604 
605 static caddr_t __noinline
606 malloc_large(size_t size, struct malloc_type *mtp, struct domainset *policy,
607     int flags DEBUG_REDZONE_ARG_DEF)
608 {
609 	void *va;
610 
611 	size = roundup(size, PAGE_SIZE);
612 	va = kmem_malloc_domainset(policy, size, flags);
613 	if (va != NULL) {
614 		/* Use low bits unused for slab pointers. */
615 		vsetzoneslab((uintptr_t)va, NULL, MALLOC_LARGE_SLAB(size));
616 		uma_total_inc(size);
617 	}
618 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
619 	if (__predict_false(va == NULL)) {
620 		KASSERT((flags & M_WAITOK) == 0,
621 		    ("malloc(M_WAITOK) returned NULL"));
622 	} else {
623 #ifdef DEBUG_REDZONE
624 		va = redzone_setup(va, osize);
625 #endif
626 		kasan_mark(va, osize, size, KASAN_MALLOC_REDZONE);
627 	}
628 	return (va);
629 }
630 
631 static void
632 free_large(void *addr, size_t size)
633 {
634 
635 	kmem_free(addr, size);
636 	uma_total_dec(size);
637 }
638 #undef	IS_MALLOC_LARGE
639 #undef	MALLOC_LARGE_SLAB
640 
641 /*
642  *	malloc:
643  *
644  *	Allocate a block of memory.
645  *
646  *	If M_NOWAIT is set, this routine will not block and return NULL if
647  *	the allocation fails.
648  */
649 void *
650 (malloc)(size_t size, struct malloc_type *mtp, int flags)
651 {
652 	int indx;
653 	caddr_t va;
654 	uma_zone_t zone;
655 #if defined(DEBUG_REDZONE) || defined(KASAN)
656 	unsigned long osize = size;
657 #endif
658 
659 	MPASS((flags & M_EXEC) == 0);
660 
661 #ifdef MALLOC_DEBUG
662 	va = NULL;
663 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
664 		return (va);
665 #endif
666 
667 	if (__predict_false(size > kmem_zmax))
668 		return (malloc_large(size, mtp, DOMAINSET_RR(), flags
669 		    DEBUG_REDZONE_ARG));
670 
671 	if (size & KMEM_ZMASK)
672 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
673 	indx = kmemsize[size >> KMEM_ZSHIFT];
674 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
675 	va = uma_zalloc_arg(zone, zone, flags);
676 	if (va != NULL) {
677 		size = zone->uz_size;
678 		if ((flags & M_ZERO) == 0) {
679 			kmsan_mark(va, size, KMSAN_STATE_UNINIT);
680 			kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
681 		}
682 	}
683 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
684 	if (__predict_false(va == NULL)) {
685 		KASSERT((flags & M_WAITOK) == 0,
686 		    ("malloc(M_WAITOK) returned NULL"));
687 	}
688 #ifdef DEBUG_REDZONE
689 	if (va != NULL)
690 		va = redzone_setup(va, osize);
691 #endif
692 #ifdef KASAN
693 	if (va != NULL)
694 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
695 #endif
696 	return ((void *) va);
697 }
698 
699 static void *
700 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
701     int flags)
702 {
703 	uma_zone_t zone;
704 	caddr_t va;
705 	size_t size;
706 	int indx;
707 
708 	size = *sizep;
709 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
710 	    ("malloc_domain: Called with bad flag / size combination"));
711 	if (size & KMEM_ZMASK)
712 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
713 	indx = kmemsize[size >> KMEM_ZSHIFT];
714 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
715 	va = uma_zalloc_domain(zone, zone, domain, flags);
716 	if (va != NULL)
717 		*sizep = zone->uz_size;
718 	*indxp = indx;
719 	return ((void *)va);
720 }
721 
722 void *
723 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
724     int flags)
725 {
726 	struct vm_domainset_iter di;
727 	caddr_t va;
728 	int domain;
729 	int indx;
730 #if defined(KASAN) || defined(DEBUG_REDZONE)
731 	unsigned long osize = size;
732 #endif
733 
734 	MPASS((flags & M_EXEC) == 0);
735 
736 #ifdef MALLOC_DEBUG
737 	va = NULL;
738 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
739 		return (va);
740 #endif
741 
742 	if (__predict_false(size > kmem_zmax))
743 		return (malloc_large(size, mtp, DOMAINSET_RR(), flags
744 		    DEBUG_REDZONE_ARG));
745 
746 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
747 	do {
748 		va = malloc_domain(&size, &indx, mtp, domain, flags);
749 	} while (va == NULL && vm_domainset_iter_policy(&di, &domain) == 0);
750 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
751 	if (__predict_false(va == NULL)) {
752 		KASSERT((flags & M_WAITOK) == 0,
753 		    ("malloc(M_WAITOK) returned NULL"));
754 	}
755 #ifdef DEBUG_REDZONE
756 	if (va != NULL)
757 		va = redzone_setup(va, osize);
758 #endif
759 #ifdef KASAN
760 	if (va != NULL)
761 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
762 #endif
763 #ifdef KMSAN
764 	if ((flags & M_ZERO) == 0) {
765 		kmsan_mark(va, size, KMSAN_STATE_UNINIT);
766 		kmsan_orig(va, size, KMSAN_TYPE_MALLOC, KMSAN_RET_ADDR);
767 	}
768 #endif
769 	return (va);
770 }
771 
772 /*
773  * Allocate an executable area.
774  */
775 void *
776 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
777 {
778 
779 	return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
780 }
781 
782 void *
783 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
784     int flags)
785 {
786 #if defined(DEBUG_REDZONE) || defined(KASAN)
787 	unsigned long osize = size;
788 #endif
789 #ifdef MALLOC_DEBUG
790 	caddr_t va;
791 #endif
792 
793 	flags |= M_EXEC;
794 
795 #ifdef MALLOC_DEBUG
796 	va = NULL;
797 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
798 		return (va);
799 #endif
800 
801 	return (malloc_large(size, mtp, ds, flags DEBUG_REDZONE_ARG));
802 }
803 
804 void *
805 malloc_aligned(size_t size, size_t align, struct malloc_type *type, int flags)
806 {
807 	return (malloc_domainset_aligned(size, align, type, DOMAINSET_RR(),
808 	    flags));
809 }
810 
811 void *
812 malloc_domainset_aligned(size_t size, size_t align,
813     struct malloc_type *mtp, struct domainset *ds, int flags)
814 {
815 	void *res;
816 	size_t asize;
817 
818 	KASSERT(powerof2(align),
819 	    ("malloc_domainset_aligned: wrong align %#zx size %#zx",
820 	    align, size));
821 	KASSERT(align <= PAGE_SIZE,
822 	    ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
823 	    align, size));
824 
825 	/*
826 	 * Round the allocation size up to the next power of 2,
827 	 * because we can only guarantee alignment for
828 	 * power-of-2-sized allocations.  Further increase the
829 	 * allocation size to align if the rounded size is less than
830 	 * align, since malloc zones provide alignment equal to their
831 	 * size.
832 	 */
833 	if (size == 0)
834 		size = 1;
835 	asize = size <= align ? align : 1UL << flsl(size - 1);
836 
837 	res = malloc_domainset(asize, mtp, ds, flags);
838 	KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
839 	    ("malloc_domainset_aligned: result not aligned %p size %#zx "
840 	    "allocsize %#zx align %#zx", res, size, asize, align));
841 	return (res);
842 }
843 
844 void *
845 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
846 {
847 
848 	if (WOULD_OVERFLOW(nmemb, size))
849 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
850 
851 	return (malloc(size * nmemb, type, flags));
852 }
853 
854 void *
855 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
856     struct domainset *ds, int flags)
857 {
858 
859 	if (WOULD_OVERFLOW(nmemb, size))
860 		panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
861 
862 	return (malloc_domainset(size * nmemb, type, ds, flags));
863 }
864 
865 #if defined(INVARIANTS) && !defined(KASAN)
866 static void
867 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
868 {
869 	struct malloc_type **mtpp = addr;
870 
871 	/*
872 	 * Cache a pointer to the malloc_type that most recently freed
873 	 * this memory here.  This way we know who is most likely to
874 	 * have stepped on it later.
875 	 *
876 	 * This code assumes that size is a multiple of 8 bytes for
877 	 * 64 bit machines
878 	 */
879 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
880 	mtpp += (size - sizeof(struct malloc_type *)) /
881 	    sizeof(struct malloc_type *);
882 	*mtpp = mtp;
883 }
884 #endif
885 
886 #ifdef MALLOC_DEBUG
887 static int
888 free_dbg(void **addrp, struct malloc_type *mtp)
889 {
890 	void *addr;
891 
892 	addr = *addrp;
893 	KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
894 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
895 	    ("free: called with spinlock or critical section held"));
896 
897 	/* free(NULL, ...) does nothing */
898 	if (addr == NULL)
899 		return (EJUSTRETURN);
900 
901 #ifdef DEBUG_MEMGUARD
902 	if (is_memguard_addr(addr)) {
903 		memguard_free(addr);
904 		return (EJUSTRETURN);
905 	}
906 #endif
907 
908 #ifdef DEBUG_REDZONE
909 	redzone_check(addr);
910 	*addrp = redzone_addr_ntor(addr);
911 #endif
912 
913 	return (0);
914 }
915 #endif
916 
917 static __always_inline void
918 _free(void *addr, struct malloc_type *mtp, bool dozero)
919 {
920 	uma_zone_t zone;
921 	uma_slab_t slab;
922 	u_long size;
923 
924 #ifdef MALLOC_DEBUG
925 	if (free_dbg(&addr, mtp) != 0)
926 		return;
927 #endif
928 	/* free(NULL, ...) does nothing */
929 	if (addr == NULL)
930 		return;
931 
932 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
933 	if (slab == NULL)
934 		panic("%s(%d): address %p(%p) has not been allocated", __func__,
935 		    dozero, addr, (void *)((uintptr_t)addr & (~UMA_SLAB_MASK)));
936 
937 	switch (GET_SLAB_COOKIE(slab)) {
938 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
939 		size = zone->uz_size;
940 #if defined(INVARIANTS) && !defined(KASAN)
941 		free_save_type(addr, mtp, size);
942 #endif
943 		if (dozero)
944 			explicit_bzero(addr, size);
945 		uma_zfree_arg(zone, addr, slab);
946 		break;
947 	case SLAB_COOKIE_MALLOC_LARGE:
948 		size = malloc_large_size(slab);
949 		if (dozero)
950 			explicit_bzero(addr, size);
951 		free_large(addr, size);
952 		break;
953 	case SLAB_COOKIE_CONTIG_MALLOC:
954 		size = round_page(contigmalloc_size(slab));
955 		if (dozero)
956 			explicit_bzero(addr, size);
957 		kmem_free(addr, size);
958 		break;
959 	default:
960 		panic("%s(%d): addr %p slab %p with unknown cookie %d",
961 		    __func__, dozero, addr, slab, GET_SLAB_COOKIE(slab));
962 		/* NOTREACHED */
963 	}
964 	malloc_type_freed(mtp, size);
965 }
966 
967 /*
968  * free:
969  *	Free a block of memory allocated by malloc/contigmalloc.
970  *	This routine may not block.
971  */
972 void
973 free(void *addr, struct malloc_type *mtp)
974 {
975 	_free(addr, mtp, false);
976 }
977 
978 /*
979  * zfree:
980  *	Zero then free a block of memory allocated by malloc/contigmalloc.
981  *	This routine may not block.
982  */
983 void
984 zfree(void *addr, struct malloc_type *mtp)
985 {
986 	_free(addr, mtp, true);
987 }
988 
989 /*
990  *	realloc: change the size of a memory block
991  */
992 void *
993 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
994 {
995 #ifndef DEBUG_REDZONE
996 	uma_zone_t zone;
997 	uma_slab_t slab;
998 #endif
999 	unsigned long alloc;
1000 	void *newaddr;
1001 
1002 	KASSERT(mtp->ks_version == M_VERSION,
1003 	    ("realloc: bad malloc type version"));
1004 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
1005 	    ("realloc: called with spinlock or critical section held"));
1006 
1007 	/* realloc(NULL, ...) is equivalent to malloc(...) */
1008 	if (addr == NULL)
1009 		return (malloc(size, mtp, flags));
1010 
1011 	/*
1012 	 * XXX: Should report free of old memory and alloc of new memory to
1013 	 * per-CPU stats.
1014 	 */
1015 
1016 #ifdef DEBUG_MEMGUARD
1017 	if (is_memguard_addr(addr))
1018 		return (memguard_realloc(addr, size, mtp, flags));
1019 #endif
1020 
1021 #ifdef DEBUG_REDZONE
1022 	alloc = redzone_get_size(addr);
1023 #else
1024 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1025 
1026 	/* Sanity check */
1027 	KASSERT(slab != NULL,
1028 	    ("realloc: address %p out of range", (void *)addr));
1029 
1030 	/* Get the size of the original block */
1031 	switch (GET_SLAB_COOKIE(slab)) {
1032 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1033 		alloc = zone->uz_size;
1034 		break;
1035 	case SLAB_COOKIE_MALLOC_LARGE:
1036 		alloc = malloc_large_size(slab);
1037 		break;
1038 	default:
1039 #ifdef INVARIANTS
1040 		panic("%s: called for addr %p of unsupported allocation type; "
1041 		    "slab %p cookie %d", __func__, addr, slab, GET_SLAB_COOKIE(slab));
1042 #endif
1043 		return (NULL);
1044 	}
1045 
1046 	/* Reuse the original block if appropriate */
1047 	if (size <= alloc &&
1048 	    (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1049 		kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1050 		return (addr);
1051 	}
1052 #endif /* !DEBUG_REDZONE */
1053 
1054 	/* Allocate a new, bigger (or smaller) block */
1055 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
1056 		return (NULL);
1057 
1058 	/*
1059 	 * Copy over original contents.  For KASAN, the redzone must be marked
1060 	 * valid before performing the copy.
1061 	 */
1062 	kasan_mark(addr, alloc, alloc, 0);
1063 	bcopy(addr, newaddr, min(size, alloc));
1064 	free(addr, mtp);
1065 	return (newaddr);
1066 }
1067 
1068 /*
1069  *	reallocf: same as realloc() but free memory on failure.
1070  */
1071 void *
1072 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1073 {
1074 	void *mem;
1075 
1076 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1077 		free(addr, mtp);
1078 	return (mem);
1079 }
1080 
1081 /*
1082  * 	malloc_size: returns the number of bytes allocated for a request of the
1083  * 		     specified size
1084  */
1085 size_t
1086 malloc_size(size_t size)
1087 {
1088 	int indx;
1089 
1090 	if (size > kmem_zmax)
1091 		return (round_page(size));
1092 	if (size & KMEM_ZMASK)
1093 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1094 	indx = kmemsize[size >> KMEM_ZSHIFT];
1095 	return (kmemzones[indx].kz_size);
1096 }
1097 
1098 /*
1099  *	malloc_usable_size: returns the usable size of the allocation.
1100  */
1101 size_t
1102 malloc_usable_size(const void *addr)
1103 {
1104 #ifndef DEBUG_REDZONE
1105 	uma_zone_t zone;
1106 	uma_slab_t slab;
1107 #endif
1108 	u_long size;
1109 
1110 	if (addr == NULL)
1111 		return (0);
1112 
1113 #ifdef DEBUG_MEMGUARD
1114 	if (is_memguard_addr(__DECONST(void *, addr)))
1115 		return (memguard_get_req_size(addr));
1116 #endif
1117 
1118 #ifdef DEBUG_REDZONE
1119 	size = redzone_get_size(__DECONST(void *, addr));
1120 #else
1121 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1122 	if (slab == NULL)
1123 		panic("malloc_usable_size: address %p(%p) is not allocated",
1124 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1125 
1126 	switch (GET_SLAB_COOKIE(slab)) {
1127 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1128 		size = zone->uz_size;
1129 		break;
1130 	case SLAB_COOKIE_MALLOC_LARGE:
1131 		size = malloc_large_size(slab);
1132 		break;
1133 	default:
1134 		__assert_unreachable();
1135 		size = 0;
1136 		break;
1137 	}
1138 #endif
1139 
1140 	/*
1141 	 * Unmark the redzone to avoid reports from consumers who are
1142 	 * (presumably) about to use the full allocation size.
1143 	 */
1144 	kasan_mark(addr, size, size, 0);
1145 
1146 	return (size);
1147 }
1148 
1149 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1150 
1151 /*
1152  * Initialize the kernel memory (kmem) arena.
1153  */
1154 void
1155 kmeminit(void)
1156 {
1157 	u_long mem_size;
1158 	u_long tmp;
1159 
1160 #ifdef VM_KMEM_SIZE
1161 	if (vm_kmem_size == 0)
1162 		vm_kmem_size = VM_KMEM_SIZE;
1163 #endif
1164 #ifdef VM_KMEM_SIZE_MIN
1165 	if (vm_kmem_size_min == 0)
1166 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1167 #endif
1168 #ifdef VM_KMEM_SIZE_MAX
1169 	if (vm_kmem_size_max == 0)
1170 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1171 #endif
1172 	/*
1173 	 * Calculate the amount of kernel virtual address (KVA) space that is
1174 	 * preallocated to the kmem arena.  In order to support a wide range
1175 	 * of machines, it is a function of the physical memory size,
1176 	 * specifically,
1177 	 *
1178 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1179 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1180 	 *
1181 	 * Every architecture must define an integral value for
1182 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1183 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1184 	 * ceiling on this preallocation, are optional.  Typically,
1185 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1186 	 * a given architecture.
1187 	 */
1188 	mem_size = vm_cnt.v_page_count;
1189 	if (mem_size <= 32768) /* delphij XXX 128MB */
1190 		kmem_zmax = PAGE_SIZE;
1191 
1192 	if (vm_kmem_size_scale < 1)
1193 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1194 
1195 	/*
1196 	 * Check if we should use defaults for the "vm_kmem_size"
1197 	 * variable:
1198 	 */
1199 	if (vm_kmem_size == 0) {
1200 		vm_kmem_size = mem_size / vm_kmem_size_scale;
1201 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1202 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1203 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1204 			vm_kmem_size = vm_kmem_size_min;
1205 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1206 			vm_kmem_size = vm_kmem_size_max;
1207 	}
1208 	if (vm_kmem_size == 0)
1209 		panic("Tune VM_KMEM_SIZE_* for the platform");
1210 
1211 	/*
1212 	 * The amount of KVA space that is preallocated to the
1213 	 * kmem arena can be set statically at compile-time or manually
1214 	 * through the kernel environment.  However, it is still limited to
1215 	 * twice the physical memory size, which has been sufficient to handle
1216 	 * the most severe cases of external fragmentation in the kmem arena.
1217 	 */
1218 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1219 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1220 
1221 	vm_kmem_size = round_page(vm_kmem_size);
1222 
1223 	/*
1224 	 * With KASAN or KMSAN enabled, dynamically allocated kernel memory is
1225 	 * shadowed.  Account for this when setting the UMA limit.
1226 	 */
1227 #if defined(KASAN)
1228 	vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1229 	    (KASAN_SHADOW_SCALE + 1);
1230 #elif defined(KMSAN)
1231 	vm_kmem_size /= 3;
1232 #endif
1233 
1234 #ifdef DEBUG_MEMGUARD
1235 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1236 #else
1237 	tmp = vm_kmem_size;
1238 #endif
1239 	uma_set_limit(tmp);
1240 
1241 #ifdef DEBUG_MEMGUARD
1242 	/*
1243 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1244 	 * replacement allocator used for detecting tamper-after-free
1245 	 * scenarios as they occur.  It is only used for debugging.
1246 	 */
1247 	memguard_init(kernel_arena);
1248 #endif
1249 }
1250 
1251 /*
1252  * Initialize the kernel memory allocator
1253  */
1254 /* ARGSUSED*/
1255 static void
1256 mallocinit(void *dummy)
1257 {
1258 	int i;
1259 	uint8_t indx;
1260 
1261 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1262 
1263 	kmeminit();
1264 
1265 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1266 		kmem_zmax = KMEM_ZMAX;
1267 
1268 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1269 		int size = kmemzones[indx].kz_size;
1270 		const char *name = kmemzones[indx].kz_name;
1271 		size_t align;
1272 		int subzone;
1273 
1274 		align = UMA_ALIGN_PTR;
1275 		if (powerof2(size) && size > sizeof(void *))
1276 			align = MIN(size, PAGE_SIZE) - 1;
1277 		for (subzone = 0; subzone < numzones; subzone++) {
1278 			kmemzones[indx].kz_zone[subzone] =
1279 			    uma_zcreate(name, size,
1280 #if defined(INVARIANTS) && !defined(KASAN) && !defined(KMSAN)
1281 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1282 #else
1283 			    NULL, NULL, NULL, NULL,
1284 #endif
1285 			    align, UMA_ZONE_MALLOC);
1286 		}
1287 		for (;i <= size; i+= KMEM_ZBASE)
1288 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1289 	}
1290 }
1291 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1292 
1293 void
1294 malloc_init(void *data)
1295 {
1296 	struct malloc_type_internal *mtip;
1297 	struct malloc_type *mtp;
1298 
1299 	KASSERT(vm_cnt.v_page_count != 0,
1300 	    ("malloc_init() called before vm_mem_init()"));
1301 
1302 	mtp = data;
1303 	if (mtp->ks_version != M_VERSION)
1304 		panic("malloc_init: type %s with unsupported version %lu",
1305 		    mtp->ks_shortdesc, mtp->ks_version);
1306 
1307 	mtip = &mtp->ks_mti;
1308 	mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1309 	mtp_set_subzone(mtp);
1310 
1311 	mtx_lock(&malloc_mtx);
1312 	mtp->ks_next = kmemstatistics;
1313 	kmemstatistics = mtp;
1314 	kmemcount++;
1315 	mtx_unlock(&malloc_mtx);
1316 }
1317 
1318 void
1319 malloc_uninit(void *data)
1320 {
1321 	struct malloc_type_internal *mtip;
1322 	struct malloc_type_stats *mtsp;
1323 	struct malloc_type *mtp, *temp;
1324 	long temp_allocs, temp_bytes;
1325 	int i;
1326 
1327 	mtp = data;
1328 	KASSERT(mtp->ks_version == M_VERSION,
1329 	    ("malloc_uninit: bad malloc type version"));
1330 
1331 	mtx_lock(&malloc_mtx);
1332 	mtip = &mtp->ks_mti;
1333 	if (mtp != kmemstatistics) {
1334 		for (temp = kmemstatistics; temp != NULL;
1335 		    temp = temp->ks_next) {
1336 			if (temp->ks_next == mtp) {
1337 				temp->ks_next = mtp->ks_next;
1338 				break;
1339 			}
1340 		}
1341 		KASSERT(temp,
1342 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1343 	} else
1344 		kmemstatistics = mtp->ks_next;
1345 	kmemcount--;
1346 	mtx_unlock(&malloc_mtx);
1347 
1348 	/*
1349 	 * Look for memory leaks.
1350 	 */
1351 	temp_allocs = temp_bytes = 0;
1352 	for (i = 0; i <= mp_maxid; i++) {
1353 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1354 		temp_allocs += mtsp->mts_numallocs;
1355 		temp_allocs -= mtsp->mts_numfrees;
1356 		temp_bytes += mtsp->mts_memalloced;
1357 		temp_bytes -= mtsp->mts_memfreed;
1358 	}
1359 	if (temp_allocs > 0 || temp_bytes > 0) {
1360 		printf("Warning: memory type %s leaked memory on destroy "
1361 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1362 		    temp_allocs, temp_bytes);
1363 	}
1364 
1365 	uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1366 }
1367 
1368 struct malloc_type *
1369 malloc_desc2type(const char *desc)
1370 {
1371 	struct malloc_type *mtp;
1372 
1373 	mtx_assert(&malloc_mtx, MA_OWNED);
1374 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1375 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1376 			return (mtp);
1377 	}
1378 	return (NULL);
1379 }
1380 
1381 static int
1382 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1383 {
1384 	struct malloc_type_stream_header mtsh;
1385 	struct malloc_type_internal *mtip;
1386 	struct malloc_type_stats *mtsp, zeromts;
1387 	struct malloc_type_header mth;
1388 	struct malloc_type *mtp;
1389 	int error, i;
1390 	struct sbuf sbuf;
1391 
1392 	error = sysctl_wire_old_buffer(req, 0);
1393 	if (error != 0)
1394 		return (error);
1395 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1396 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1397 	mtx_lock(&malloc_mtx);
1398 
1399 	bzero(&zeromts, sizeof(zeromts));
1400 
1401 	/*
1402 	 * Insert stream header.
1403 	 */
1404 	bzero(&mtsh, sizeof(mtsh));
1405 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1406 	mtsh.mtsh_maxcpus = MAXCPU;
1407 	mtsh.mtsh_count = kmemcount;
1408 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1409 
1410 	/*
1411 	 * Insert alternating sequence of type headers and type statistics.
1412 	 */
1413 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1414 		mtip = &mtp->ks_mti;
1415 
1416 		/*
1417 		 * Insert type header.
1418 		 */
1419 		bzero(&mth, sizeof(mth));
1420 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1421 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1422 
1423 		/*
1424 		 * Insert type statistics for each CPU.
1425 		 */
1426 		for (i = 0; i <= mp_maxid; i++) {
1427 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1428 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1429 		}
1430 		/*
1431 		 * Fill in the missing CPUs.
1432 		 */
1433 		for (; i < MAXCPU; i++) {
1434 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1435 		}
1436 	}
1437 	mtx_unlock(&malloc_mtx);
1438 	error = sbuf_finish(&sbuf);
1439 	sbuf_delete(&sbuf);
1440 	return (error);
1441 }
1442 
1443 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1444     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1445     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1446     "Return malloc types");
1447 
1448 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1449     "Count of kernel malloc types");
1450 
1451 void
1452 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1453 {
1454 	struct malloc_type *mtp, **bufmtp;
1455 	int count, i;
1456 	size_t buflen;
1457 
1458 	mtx_lock(&malloc_mtx);
1459 restart:
1460 	mtx_assert(&malloc_mtx, MA_OWNED);
1461 	count = kmemcount;
1462 	mtx_unlock(&malloc_mtx);
1463 
1464 	buflen = sizeof(struct malloc_type *) * count;
1465 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1466 
1467 	mtx_lock(&malloc_mtx);
1468 
1469 	if (count < kmemcount) {
1470 		free(bufmtp, M_TEMP);
1471 		goto restart;
1472 	}
1473 
1474 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1475 		bufmtp[i] = mtp;
1476 
1477 	mtx_unlock(&malloc_mtx);
1478 
1479 	for (i = 0; i < count; i++)
1480 		(func)(bufmtp[i], arg);
1481 
1482 	free(bufmtp, M_TEMP);
1483 }
1484 
1485 #ifdef DDB
1486 static int64_t
1487 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1488     uint64_t *inuse)
1489 {
1490 	const struct malloc_type_stats *mtsp;
1491 	uint64_t frees, alloced, freed;
1492 	int i;
1493 
1494 	*allocs = 0;
1495 	frees = 0;
1496 	alloced = 0;
1497 	freed = 0;
1498 	for (i = 0; i <= mp_maxid; i++) {
1499 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1500 
1501 		*allocs += mtsp->mts_numallocs;
1502 		frees += mtsp->mts_numfrees;
1503 		alloced += mtsp->mts_memalloced;
1504 		freed += mtsp->mts_memfreed;
1505 	}
1506 	*inuse = *allocs - frees;
1507 	return (alloced - freed);
1508 }
1509 
1510 DB_SHOW_COMMAND_FLAGS(malloc, db_show_malloc, DB_CMD_MEMSAFE)
1511 {
1512 	const char *fmt_hdr, *fmt_entry;
1513 	struct malloc_type *mtp;
1514 	uint64_t allocs, inuse;
1515 	int64_t size;
1516 	/* variables for sorting */
1517 	struct malloc_type *last_mtype, *cur_mtype;
1518 	int64_t cur_size, last_size;
1519 	int ties;
1520 
1521 	if (modif[0] == 'i') {
1522 		fmt_hdr = "%s,%s,%s,%s\n";
1523 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1524 	} else {
1525 		fmt_hdr = "%18s %12s  %12s %12s\n";
1526 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
1527 	}
1528 
1529 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1530 
1531 	/* Select sort, largest size first. */
1532 	last_mtype = NULL;
1533 	last_size = INT64_MAX;
1534 	for (;;) {
1535 		cur_mtype = NULL;
1536 		cur_size = -1;
1537 		ties = 0;
1538 
1539 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1540 			/*
1541 			 * In the case of size ties, print out mtypes
1542 			 * in the order they are encountered.  That is,
1543 			 * when we encounter the most recently output
1544 			 * mtype, we have already printed all preceding
1545 			 * ties, and we must print all following ties.
1546 			 */
1547 			if (mtp == last_mtype) {
1548 				ties = 1;
1549 				continue;
1550 			}
1551 			size = get_malloc_stats(&mtp->ks_mti, &allocs,
1552 			    &inuse);
1553 			if (size > cur_size && size < last_size + ties) {
1554 				cur_size = size;
1555 				cur_mtype = mtp;
1556 			}
1557 		}
1558 		if (cur_mtype == NULL)
1559 			break;
1560 
1561 		size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1562 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1563 		    howmany(size, 1024), allocs);
1564 
1565 		if (db_pager_quit)
1566 			break;
1567 
1568 		last_mtype = cur_mtype;
1569 		last_size = cur_size;
1570 	}
1571 }
1572 
1573 #if MALLOC_DEBUG_MAXZONES > 1
1574 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1575 {
1576 	struct malloc_type_internal *mtip;
1577 	struct malloc_type *mtp;
1578 	u_int subzone;
1579 
1580 	if (!have_addr) {
1581 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1582 		return;
1583 	}
1584 	mtp = (void *)addr;
1585 	if (mtp->ks_version != M_VERSION) {
1586 		db_printf("Version %lx does not match expected %x\n",
1587 		    mtp->ks_version, M_VERSION);
1588 		return;
1589 	}
1590 
1591 	mtip = &mtp->ks_mti;
1592 	subzone = mtip->mti_zone;
1593 
1594 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1595 		mtip = &mtp->ks_mti;
1596 		if (mtip->mti_zone != subzone)
1597 			continue;
1598 		db_printf("%s\n", mtp->ks_shortdesc);
1599 		if (db_pager_quit)
1600 			break;
1601 	}
1602 }
1603 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1604 #endif /* DDB */
1605