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