xref: /freebsd/sys/kern/kern_malloc.c (revision 36712a94975f5bd0d26c85377283b49a2369c82f)
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 		if (__predict_false(!THREAD_CAN_SLEEP())) {
527 #ifdef EPOCH_TRACE
528 			epoch_trace_list(curthread);
529 #endif
530 			KASSERT(1,
531 			    ("malloc(M_WAITOK) with sleeping prohibited"));
532 		}
533 	}
534 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
535 	    ("malloc: called with spinlock or critical section held"));
536 
537 #ifdef DEBUG_MEMGUARD
538 	if (memguard_cmp_mtp(mtp, *sizep)) {
539 		*vap = memguard_alloc(*sizep, flags);
540 		if (*vap != NULL)
541 			return (EJUSTRETURN);
542 		/* This is unfortunate but should not be fatal. */
543 	}
544 #endif
545 
546 #ifdef DEBUG_REDZONE
547 	*sizep = redzone_size_ntor(*sizep);
548 #endif
549 
550 	return (0);
551 }
552 #endif
553 
554 /*
555  *	malloc:
556  *
557  *	Allocate a block of memory.
558  *
559  *	If M_NOWAIT is set, this routine will not block and return NULL if
560  *	the allocation fails.
561  */
562 void *
563 (malloc)(size_t size, struct malloc_type *mtp, int flags)
564 {
565 	int indx;
566 	caddr_t va;
567 	uma_zone_t zone;
568 #if defined(DEBUG_REDZONE)
569 	unsigned long osize = size;
570 #endif
571 
572 #ifdef MALLOC_DEBUG
573 	va = NULL;
574 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
575 		return (va);
576 #endif
577 
578 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
579 		if (size & KMEM_ZMASK)
580 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
581 		indx = kmemsize[size >> KMEM_ZSHIFT];
582 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
583 #ifdef MALLOC_PROFILE
584 		krequests[size >> KMEM_ZSHIFT]++;
585 #endif
586 		va = uma_zalloc(zone, flags);
587 		if (va != NULL)
588 			size = zone->uz_size;
589 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
590 	} else {
591 		size = roundup(size, PAGE_SIZE);
592 		zone = NULL;
593 		va = uma_large_malloc(size, flags);
594 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
595 	}
596 	if (flags & M_WAITOK)
597 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
598 	else if (va == NULL)
599 		t_malloc_fail = time_uptime;
600 #ifdef DEBUG_REDZONE
601 	if (va != NULL)
602 		va = redzone_setup(va, osize);
603 #endif
604 	return ((void *) va);
605 }
606 
607 static void *
608 malloc_domain(size_t size, struct malloc_type *mtp, int domain, int flags)
609 {
610 	int indx;
611 	caddr_t va;
612 	uma_zone_t zone;
613 #if defined(DEBUG_REDZONE)
614 	unsigned long osize = size;
615 #endif
616 
617 #ifdef MALLOC_DEBUG
618 	va = NULL;
619 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
620 		return (va);
621 #endif
622 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
623 		if (size & KMEM_ZMASK)
624 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
625 		indx = kmemsize[size >> KMEM_ZSHIFT];
626 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
627 #ifdef MALLOC_PROFILE
628 		krequests[size >> KMEM_ZSHIFT]++;
629 #endif
630 		va = uma_zalloc_domain(zone, NULL, domain, flags);
631 		if (va != NULL)
632 			size = zone->uz_size;
633 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
634 	} else {
635 		size = roundup(size, PAGE_SIZE);
636 		zone = NULL;
637 		va = uma_large_malloc_domain(size, domain, flags);
638 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
639 	}
640 	if (flags & M_WAITOK)
641 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
642 	else if (va == NULL)
643 		t_malloc_fail = time_uptime;
644 #ifdef DEBUG_REDZONE
645 	if (va != NULL)
646 		va = redzone_setup(va, osize);
647 #endif
648 	return ((void *) va);
649 }
650 
651 void *
652 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
653     int flags)
654 {
655 	struct vm_domainset_iter di;
656 	void *ret;
657 	int domain;
658 
659 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
660 	do {
661 		ret = malloc_domain(size, mtp, domain, flags);
662 		if (ret != NULL)
663 			break;
664 	} while (vm_domainset_iter_policy(&di, &domain) == 0);
665 
666 	return (ret);
667 }
668 
669 void *
670 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
671 {
672 
673 	if (WOULD_OVERFLOW(nmemb, size))
674 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
675 
676 	return (malloc(size * nmemb, type, flags));
677 }
678 
679 #ifdef INVARIANTS
680 static void
681 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
682 {
683 	struct malloc_type **mtpp = addr;
684 
685 	/*
686 	 * Cache a pointer to the malloc_type that most recently freed
687 	 * this memory here.  This way we know who is most likely to
688 	 * have stepped on it later.
689 	 *
690 	 * This code assumes that size is a multiple of 8 bytes for
691 	 * 64 bit machines
692 	 */
693 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
694 	mtpp += (size - sizeof(struct malloc_type *)) /
695 	    sizeof(struct malloc_type *);
696 	*mtpp = mtp;
697 }
698 #endif
699 
700 #ifdef MALLOC_DEBUG
701 static int
702 free_dbg(void **addrp, struct malloc_type *mtp)
703 {
704 	void *addr;
705 
706 	addr = *addrp;
707 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
708 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
709 	    ("free: called with spinlock or critical section held"));
710 
711 	/* free(NULL, ...) does nothing */
712 	if (addr == NULL)
713 		return (EJUSTRETURN);
714 
715 #ifdef DEBUG_MEMGUARD
716 	if (is_memguard_addr(addr)) {
717 		memguard_free(addr);
718 		return (EJUSTRETURN);
719 	}
720 #endif
721 
722 #ifdef DEBUG_REDZONE
723 	redzone_check(addr);
724 	*addrp = redzone_addr_ntor(addr);
725 #endif
726 
727 	return (0);
728 }
729 #endif
730 
731 /*
732  *	free:
733  *
734  *	Free a block of memory allocated by malloc.
735  *
736  *	This routine may not block.
737  */
738 void
739 free(void *addr, struct malloc_type *mtp)
740 {
741 	uma_slab_t slab;
742 	u_long size;
743 
744 #ifdef MALLOC_DEBUG
745 	if (free_dbg(&addr, mtp) != 0)
746 		return;
747 #endif
748 	/* free(NULL, ...) does nothing */
749 	if (addr == NULL)
750 		return;
751 
752 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
753 	if (slab == NULL)
754 		panic("free: address %p(%p) has not been allocated.\n",
755 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
756 
757 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
758 		size = slab->us_keg->uk_size;
759 #ifdef INVARIANTS
760 		free_save_type(addr, mtp, size);
761 #endif
762 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
763 	} else {
764 		size = slab->us_size;
765 		uma_large_free(slab);
766 	}
767 	malloc_type_freed(mtp, size);
768 }
769 
770 void
771 free_domain(void *addr, struct malloc_type *mtp)
772 {
773 	uma_slab_t slab;
774 	u_long size;
775 
776 #ifdef MALLOC_DEBUG
777 	if (free_dbg(&addr, mtp) != 0)
778 		return;
779 #endif
780 
781 	/* free(NULL, ...) does nothing */
782 	if (addr == NULL)
783 		return;
784 
785 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
786 	if (slab == NULL)
787 		panic("free_domain: address %p(%p) has not been allocated.\n",
788 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
789 
790 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
791 		size = slab->us_keg->uk_size;
792 #ifdef INVARIANTS
793 		free_save_type(addr, mtp, size);
794 #endif
795 		uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
796 		    addr, slab);
797 	} else {
798 		size = slab->us_size;
799 		uma_large_free(slab);
800 	}
801 	malloc_type_freed(mtp, size);
802 }
803 
804 /*
805  *	realloc: change the size of a memory block
806  */
807 void *
808 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
809 {
810 	uma_slab_t slab;
811 	unsigned long alloc;
812 	void *newaddr;
813 
814 	KASSERT(mtp->ks_magic == M_MAGIC,
815 	    ("realloc: bad malloc type magic"));
816 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
817 	    ("realloc: called with spinlock or critical section held"));
818 
819 	/* realloc(NULL, ...) is equivalent to malloc(...) */
820 	if (addr == NULL)
821 		return (malloc(size, mtp, flags));
822 
823 	/*
824 	 * XXX: Should report free of old memory and alloc of new memory to
825 	 * per-CPU stats.
826 	 */
827 
828 #ifdef DEBUG_MEMGUARD
829 	if (is_memguard_addr(addr))
830 		return (memguard_realloc(addr, size, mtp, flags));
831 #endif
832 
833 #ifdef DEBUG_REDZONE
834 	slab = NULL;
835 	alloc = redzone_get_size(addr);
836 #else
837 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
838 
839 	/* Sanity check */
840 	KASSERT(slab != NULL,
841 	    ("realloc: address %p out of range", (void *)addr));
842 
843 	/* Get the size of the original block */
844 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
845 		alloc = slab->us_keg->uk_size;
846 	else
847 		alloc = slab->us_size;
848 
849 	/* Reuse the original block if appropriate */
850 	if (size <= alloc
851 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
852 		return (addr);
853 #endif /* !DEBUG_REDZONE */
854 
855 	/* Allocate a new, bigger (or smaller) block */
856 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
857 		return (NULL);
858 
859 	/* Copy over original contents */
860 	bcopy(addr, newaddr, min(size, alloc));
861 	free(addr, mtp);
862 	return (newaddr);
863 }
864 
865 /*
866  *	reallocf: same as realloc() but free memory on failure.
867  */
868 void *
869 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
870 {
871 	void *mem;
872 
873 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
874 		free(addr, mtp);
875 	return (mem);
876 }
877 
878 #ifndef __sparc64__
879 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
880 #endif
881 
882 /*
883  * Initialize the kernel memory (kmem) arena.
884  */
885 void
886 kmeminit(void)
887 {
888 	u_long mem_size;
889 	u_long tmp;
890 
891 #ifdef VM_KMEM_SIZE
892 	if (vm_kmem_size == 0)
893 		vm_kmem_size = VM_KMEM_SIZE;
894 #endif
895 #ifdef VM_KMEM_SIZE_MIN
896 	if (vm_kmem_size_min == 0)
897 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
898 #endif
899 #ifdef VM_KMEM_SIZE_MAX
900 	if (vm_kmem_size_max == 0)
901 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
902 #endif
903 	/*
904 	 * Calculate the amount of kernel virtual address (KVA) space that is
905 	 * preallocated to the kmem arena.  In order to support a wide range
906 	 * of machines, it is a function of the physical memory size,
907 	 * specifically,
908 	 *
909 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
910 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
911 	 *
912 	 * Every architecture must define an integral value for
913 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
914 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
915 	 * ceiling on this preallocation, are optional.  Typically,
916 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
917 	 * a given architecture.
918 	 */
919 	mem_size = vm_cnt.v_page_count;
920 	if (mem_size <= 32768) /* delphij XXX 128MB */
921 		kmem_zmax = PAGE_SIZE;
922 
923 	if (vm_kmem_size_scale < 1)
924 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
925 
926 	/*
927 	 * Check if we should use defaults for the "vm_kmem_size"
928 	 * variable:
929 	 */
930 	if (vm_kmem_size == 0) {
931 		vm_kmem_size = mem_size / vm_kmem_size_scale;
932 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
933 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
934 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
935 			vm_kmem_size = vm_kmem_size_min;
936 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
937 			vm_kmem_size = vm_kmem_size_max;
938 	}
939 	if (vm_kmem_size == 0)
940 		panic("Tune VM_KMEM_SIZE_* for the platform");
941 
942 	/*
943 	 * The amount of KVA space that is preallocated to the
944 	 * kmem arena can be set statically at compile-time or manually
945 	 * through the kernel environment.  However, it is still limited to
946 	 * twice the physical memory size, which has been sufficient to handle
947 	 * the most severe cases of external fragmentation in the kmem arena.
948 	 */
949 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
950 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
951 
952 	vm_kmem_size = round_page(vm_kmem_size);
953 #ifdef DEBUG_MEMGUARD
954 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
955 #else
956 	tmp = vm_kmem_size;
957 #endif
958 	uma_set_limit(tmp);
959 
960 #ifdef DEBUG_MEMGUARD
961 	/*
962 	 * Initialize MemGuard if support compiled in.  MemGuard is a
963 	 * replacement allocator used for detecting tamper-after-free
964 	 * scenarios as they occur.  It is only used for debugging.
965 	 */
966 	memguard_init(kernel_arena);
967 #endif
968 }
969 
970 /*
971  * Initialize the kernel memory allocator
972  */
973 /* ARGSUSED*/
974 static void
975 mallocinit(void *dummy)
976 {
977 	int i;
978 	uint8_t indx;
979 
980 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
981 
982 	kmeminit();
983 
984 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
985 		kmem_zmax = KMEM_ZMAX;
986 
987 	mt_stats_zone = uma_zcreate("mt_stats_zone",
988 	    sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
989 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
990 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
991 #ifdef INVARIANTS
992 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
993 #else
994 	    NULL, NULL, NULL, NULL,
995 #endif
996 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
997 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
998 		int size = kmemzones[indx].kz_size;
999 		char *name = kmemzones[indx].kz_name;
1000 		int subzone;
1001 
1002 		for (subzone = 0; subzone < numzones; subzone++) {
1003 			kmemzones[indx].kz_zone[subzone] =
1004 			    uma_zcreate(name, size,
1005 #ifdef INVARIANTS
1006 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1007 #else
1008 			    NULL, NULL, NULL, NULL,
1009 #endif
1010 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1011 		}
1012 		for (;i <= size; i+= KMEM_ZBASE)
1013 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1014 
1015 	}
1016 }
1017 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1018 
1019 void
1020 malloc_init(void *data)
1021 {
1022 	struct malloc_type_internal *mtip;
1023 	struct malloc_type *mtp;
1024 
1025 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1026 
1027 	mtp = data;
1028 	if (mtp->ks_magic != M_MAGIC)
1029 		panic("malloc_init: bad malloc type magic");
1030 
1031 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1032 	mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1033 	mtp->ks_handle = mtip;
1034 	mtp_set_subzone(mtp);
1035 
1036 	mtx_lock(&malloc_mtx);
1037 	mtp->ks_next = kmemstatistics;
1038 	kmemstatistics = mtp;
1039 	kmemcount++;
1040 	mtx_unlock(&malloc_mtx);
1041 }
1042 
1043 void
1044 malloc_uninit(void *data)
1045 {
1046 	struct malloc_type_internal *mtip;
1047 	struct malloc_type_stats *mtsp;
1048 	struct malloc_type *mtp, *temp;
1049 	uma_slab_t slab;
1050 	long temp_allocs, temp_bytes;
1051 	int i;
1052 
1053 	mtp = data;
1054 	KASSERT(mtp->ks_magic == M_MAGIC,
1055 	    ("malloc_uninit: bad malloc type magic"));
1056 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1057 
1058 	mtx_lock(&malloc_mtx);
1059 	mtip = mtp->ks_handle;
1060 	mtp->ks_handle = NULL;
1061 	if (mtp != kmemstatistics) {
1062 		for (temp = kmemstatistics; temp != NULL;
1063 		    temp = temp->ks_next) {
1064 			if (temp->ks_next == mtp) {
1065 				temp->ks_next = mtp->ks_next;
1066 				break;
1067 			}
1068 		}
1069 		KASSERT(temp,
1070 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1071 	} else
1072 		kmemstatistics = mtp->ks_next;
1073 	kmemcount--;
1074 	mtx_unlock(&malloc_mtx);
1075 
1076 	/*
1077 	 * Look for memory leaks.
1078 	 */
1079 	temp_allocs = temp_bytes = 0;
1080 	for (i = 0; i <= mp_maxid; i++) {
1081 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1082 		temp_allocs += mtsp->mts_numallocs;
1083 		temp_allocs -= mtsp->mts_numfrees;
1084 		temp_bytes += mtsp->mts_memalloced;
1085 		temp_bytes -= mtsp->mts_memfreed;
1086 	}
1087 	if (temp_allocs > 0 || temp_bytes > 0) {
1088 		printf("Warning: memory type %s leaked memory on destroy "
1089 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1090 		    temp_allocs, temp_bytes);
1091 	}
1092 
1093 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1094 	uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1095 	uma_zfree_arg(mt_zone, mtip, slab);
1096 }
1097 
1098 struct malloc_type *
1099 malloc_desc2type(const char *desc)
1100 {
1101 	struct malloc_type *mtp;
1102 
1103 	mtx_assert(&malloc_mtx, MA_OWNED);
1104 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1105 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1106 			return (mtp);
1107 	}
1108 	return (NULL);
1109 }
1110 
1111 static int
1112 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1113 {
1114 	struct malloc_type_stream_header mtsh;
1115 	struct malloc_type_internal *mtip;
1116 	struct malloc_type_stats *mtsp, zeromts;
1117 	struct malloc_type_header mth;
1118 	struct malloc_type *mtp;
1119 	int error, i;
1120 	struct sbuf sbuf;
1121 
1122 	error = sysctl_wire_old_buffer(req, 0);
1123 	if (error != 0)
1124 		return (error);
1125 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1126 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1127 	mtx_lock(&malloc_mtx);
1128 
1129 	bzero(&zeromts, sizeof(zeromts));
1130 
1131 	/*
1132 	 * Insert stream header.
1133 	 */
1134 	bzero(&mtsh, sizeof(mtsh));
1135 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1136 	mtsh.mtsh_maxcpus = MAXCPU;
1137 	mtsh.mtsh_count = kmemcount;
1138 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1139 
1140 	/*
1141 	 * Insert alternating sequence of type headers and type statistics.
1142 	 */
1143 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1144 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1145 
1146 		/*
1147 		 * Insert type header.
1148 		 */
1149 		bzero(&mth, sizeof(mth));
1150 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1151 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1152 
1153 		/*
1154 		 * Insert type statistics for each CPU.
1155 		 */
1156 		for (i = 0; i <= mp_maxid; i++) {
1157 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1158 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1159 		}
1160 		/*
1161 		 * Fill in the missing CPUs.
1162 		 */
1163 		for (; i < MAXCPU; i++) {
1164 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1165 		}
1166 
1167 	}
1168 	mtx_unlock(&malloc_mtx);
1169 	error = sbuf_finish(&sbuf);
1170 	sbuf_delete(&sbuf);
1171 	return (error);
1172 }
1173 
1174 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1175     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1176     "Return malloc types");
1177 
1178 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1179     "Count of kernel malloc types");
1180 
1181 void
1182 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1183 {
1184 	struct malloc_type *mtp, **bufmtp;
1185 	int count, i;
1186 	size_t buflen;
1187 
1188 	mtx_lock(&malloc_mtx);
1189 restart:
1190 	mtx_assert(&malloc_mtx, MA_OWNED);
1191 	count = kmemcount;
1192 	mtx_unlock(&malloc_mtx);
1193 
1194 	buflen = sizeof(struct malloc_type *) * count;
1195 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1196 
1197 	mtx_lock(&malloc_mtx);
1198 
1199 	if (count < kmemcount) {
1200 		free(bufmtp, M_TEMP);
1201 		goto restart;
1202 	}
1203 
1204 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1205 		bufmtp[i] = mtp;
1206 
1207 	mtx_unlock(&malloc_mtx);
1208 
1209 	for (i = 0; i < count; i++)
1210 		(func)(bufmtp[i], arg);
1211 
1212 	free(bufmtp, M_TEMP);
1213 }
1214 
1215 #ifdef DDB
1216 static int64_t
1217 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1218     uint64_t *inuse)
1219 {
1220 	const struct malloc_type_stats *mtsp;
1221 	uint64_t frees, alloced, freed;
1222 	int i;
1223 
1224 	*allocs = 0;
1225 	frees = 0;
1226 	alloced = 0;
1227 	freed = 0;
1228 	for (i = 0; i <= mp_maxid; i++) {
1229 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1230 
1231 		*allocs += mtsp->mts_numallocs;
1232 		frees += mtsp->mts_numfrees;
1233 		alloced += mtsp->mts_memalloced;
1234 		freed += mtsp->mts_memfreed;
1235 	}
1236 	*inuse = *allocs - frees;
1237 	return (alloced - freed);
1238 }
1239 
1240 DB_SHOW_COMMAND(malloc, db_show_malloc)
1241 {
1242 	const char *fmt_hdr, *fmt_entry;
1243 	struct malloc_type *mtp;
1244 	uint64_t allocs, inuse;
1245 	int64_t size;
1246 	/* variables for sorting */
1247 	struct malloc_type *last_mtype, *cur_mtype;
1248 	int64_t cur_size, last_size;
1249 	int ties;
1250 
1251 	if (modif[0] == 'i') {
1252 		fmt_hdr = "%s,%s,%s,%s\n";
1253 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1254 	} else {
1255 		fmt_hdr = "%18s %12s  %12s %12s\n";
1256 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
1257 	}
1258 
1259 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1260 
1261 	/* Select sort, largest size first. */
1262 	last_mtype = NULL;
1263 	last_size = INT64_MAX;
1264 	for (;;) {
1265 		cur_mtype = NULL;
1266 		cur_size = -1;
1267 		ties = 0;
1268 
1269 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1270 			/*
1271 			 * In the case of size ties, print out mtypes
1272 			 * in the order they are encountered.  That is,
1273 			 * when we encounter the most recently output
1274 			 * mtype, we have already printed all preceding
1275 			 * ties, and we must print all following ties.
1276 			 */
1277 			if (mtp == last_mtype) {
1278 				ties = 1;
1279 				continue;
1280 			}
1281 			size = get_malloc_stats(mtp->ks_handle, &allocs,
1282 			    &inuse);
1283 			if (size > cur_size && size < last_size + ties) {
1284 				cur_size = size;
1285 				cur_mtype = mtp;
1286 			}
1287 		}
1288 		if (cur_mtype == NULL)
1289 			break;
1290 
1291 		size = get_malloc_stats(cur_mtype->ks_handle, &allocs, &inuse);
1292 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1293 		    howmany(size, 1024), allocs);
1294 
1295 		if (db_pager_quit)
1296 			break;
1297 
1298 		last_mtype = cur_mtype;
1299 		last_size = cur_size;
1300 	}
1301 }
1302 
1303 #if MALLOC_DEBUG_MAXZONES > 1
1304 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1305 {
1306 	struct malloc_type_internal *mtip;
1307 	struct malloc_type *mtp;
1308 	u_int subzone;
1309 
1310 	if (!have_addr) {
1311 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1312 		return;
1313 	}
1314 	mtp = (void *)addr;
1315 	if (mtp->ks_magic != M_MAGIC) {
1316 		db_printf("Magic %lx does not match expected %x\n",
1317 		    mtp->ks_magic, M_MAGIC);
1318 		return;
1319 	}
1320 
1321 	mtip = mtp->ks_handle;
1322 	subzone = mtip->mti_zone;
1323 
1324 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1325 		mtip = mtp->ks_handle;
1326 		if (mtip->mti_zone != subzone)
1327 			continue;
1328 		db_printf("%s\n", mtp->ks_shortdesc);
1329 		if (db_pager_quit)
1330 			break;
1331 	}
1332 }
1333 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1334 #endif /* DDB */
1335 
1336 #ifdef MALLOC_PROFILE
1337 
1338 static int
1339 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1340 {
1341 	struct sbuf sbuf;
1342 	uint64_t count;
1343 	uint64_t waste;
1344 	uint64_t mem;
1345 	int error;
1346 	int rsize;
1347 	int size;
1348 	int i;
1349 
1350 	waste = 0;
1351 	mem = 0;
1352 
1353 	error = sysctl_wire_old_buffer(req, 0);
1354 	if (error != 0)
1355 		return (error);
1356 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1357 	sbuf_printf(&sbuf,
1358 	    "\n  Size                    Requests  Real Size\n");
1359 	for (i = 0; i < KMEM_ZSIZE; i++) {
1360 		size = i << KMEM_ZSHIFT;
1361 		rsize = kmemzones[kmemsize[i]].kz_size;
1362 		count = (long long unsigned)krequests[i];
1363 
1364 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1365 		    (unsigned long long)count, rsize);
1366 
1367 		if ((rsize * count) > (size * count))
1368 			waste += (rsize * count) - (size * count);
1369 		mem += (rsize * count);
1370 	}
1371 	sbuf_printf(&sbuf,
1372 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1373 	    (unsigned long long)mem, (unsigned long long)waste);
1374 	error = sbuf_finish(&sbuf);
1375 	sbuf_delete(&sbuf);
1376 	return (error);
1377 }
1378 
1379 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1380     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1381 #endif /* MALLOC_PROFILE */
1382