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