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