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