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