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