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