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