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