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