xref: /freebsd/sys/kern/kern_malloc.c (revision 45035becfe8aed04d0da70585e7c8bc07a385980)
19454b2d8SWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1991, 1993
563a7e0a3SRobert Watson  *	The Regents of the University of California.
6bb1c7df8SRobert Watson  * Copyright (c) 2005-2009 Robert N. M. Watson
7fd91e076SKristof Provost  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
863a7e0a3SRobert Watson  * All rights reserved.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
1869a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
34df8bae1dSRodney W. Grimes  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
370ce3f16dSRobert Watson /*
380ce3f16dSRobert Watson  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
390ce3f16dSRobert Watson  * based on memory types.  Back end is implemented using the UMA(9) zone
400ce3f16dSRobert Watson  * allocator.  A set of fixed-size buckets are used for smaller allocations,
410ce3f16dSRobert Watson  * and a special UMA allocation interface is used for larger allocations.
420ce3f16dSRobert Watson  * Callers declare memory types, and statistics are maintained independently
430ce3f16dSRobert Watson  * for each memory type.  Statistics are maintained per-CPU for performance
440ce3f16dSRobert Watson  * reasons.  See malloc(9) and comments in malloc.h for a detailed
450ce3f16dSRobert Watson  * description.
460ce3f16dSRobert Watson  */
470ce3f16dSRobert Watson 
48677b542eSDavid E. O'Brien #include <sys/cdefs.h>
49677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
50677b542eSDavid E. O'Brien 
51909ed16cSRobert Watson #include "opt_ddb.h"
528a58a9f6SJohn Dyson #include "opt_vm.h"
538a58a9f6SJohn Dyson 
54df8bae1dSRodney W. Grimes #include <sys/param.h>
5526f9a767SRodney W. Grimes #include <sys/systm.h>
562d50560aSMarcel Moolenaar #include <sys/kdb.h>
57df8bae1dSRodney W. Grimes #include <sys/kernel.h>
58fb919e4dSMark Murray #include <sys/lock.h>
59df8bae1dSRodney W. Grimes #include <sys/malloc.h>
60eec258d2SJohn Baldwin #include <sys/mutex.h>
61efeaf95aSDavid Greenman #include <sys/vmmeter.h>
62a448b62aSJake Burkholder #include <sys/proc.h>
636d6a03d7SJeff Roberson #include <sys/queue.h>
6463a7e0a3SRobert Watson #include <sys/sbuf.h>
659afff6b1SMateusz Guzik #include <sys/smp.h>
666f267175SJeff Roberson #include <sys/sysctl.h>
671fb14a47SPoul-Henning Kamp #include <sys/time.h>
685df87b21SJeff Roberson #include <sys/vmem.h>
694b25d1f2SGleb Smirnoff #ifdef EPOCH_TRACE
704b25d1f2SGleb Smirnoff #include <sys/epoch.h>
714b25d1f2SGleb Smirnoff #endif
729a02e8c6SJason Evans 
73df8bae1dSRodney W. Grimes #include <vm/vm.h>
7499571dc3SJeff Roberson #include <vm/pmap.h>
759978bd99SMark Johnston #include <vm/vm_domainset.h>
765df87b21SJeff Roberson #include <vm/vm_pageout.h>
77efeaf95aSDavid Greenman #include <vm/vm_param.h>
78df8bae1dSRodney W. Grimes #include <vm/vm_kern.h>
79efeaf95aSDavid Greenman #include <vm/vm_extern.h>
803075778bSJohn Dyson #include <vm/vm_map.h>
8199571dc3SJeff Roberson #include <vm/vm_page.h>
826d6a03d7SJeff Roberson #include <vm/vm_phys.h>
836d6a03d7SJeff Roberson #include <vm/vm_pagequeue.h>
848355f576SJeff Roberson #include <vm/uma.h>
858355f576SJeff Roberson #include <vm/uma_int.h>
868efc4effSJeff Roberson #include <vm/uma_dbg.h>
87df8bae1dSRodney W. Grimes 
88e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
89e4eb384bSBosko Milekic #include <vm/memguard.h>
90e4eb384bSBosko Milekic #endif
91847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
92847a2a17SPawel Jakub Dawidek #include <vm/redzone.h>
93847a2a17SPawel Jakub Dawidek #endif
94e4eb384bSBosko Milekic 
95984982d6SPoul-Henning Kamp #if defined(INVARIANTS) && defined(__i386__)
96984982d6SPoul-Henning Kamp #include <machine/cpu.h>
97984982d6SPoul-Henning Kamp #endif
98984982d6SPoul-Henning Kamp 
99909ed16cSRobert Watson #include <ddb/ddb.h>
100909ed16cSRobert Watson 
10191dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
10291dd776cSJohn Birrell #include <sys/dtrace_bsd.h>
10391dd776cSJohn Birrell 
1047cd79421SMateusz Guzik bool	__read_frequently			dtrace_malloc_enabled;
1057cd79421SMateusz Guzik dtrace_malloc_probe_func_t __read_mostly	dtrace_malloc_probe;
10691dd776cSJohn Birrell #endif
10791dd776cSJohn Birrell 
108ab3185d1SJeff Roberson #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
109ab3185d1SJeff Roberson     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
110ab3185d1SJeff Roberson #define	MALLOC_DEBUG	1
111ab3185d1SJeff Roberson #endif
112ab3185d1SJeff Roberson 
11344a8ff31SArchie Cobbs /*
11444a8ff31SArchie Cobbs  * When realloc() is called, if the new size is sufficiently smaller than
11544a8ff31SArchie Cobbs  * the old size, realloc() will allocate a new, smaller block to avoid
11644a8ff31SArchie Cobbs  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
11744a8ff31SArchie Cobbs  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
11844a8ff31SArchie Cobbs  */
11944a8ff31SArchie Cobbs #ifndef REALLOC_FRACTION
12044a8ff31SArchie Cobbs #define	REALLOC_FRACTION	1	/* new block if <= half the size */
12144a8ff31SArchie Cobbs #endif
12244a8ff31SArchie Cobbs 
1230ce3f16dSRobert Watson /*
1240ce3f16dSRobert Watson  * Centrally define some common malloc types.
1250ce3f16dSRobert Watson  */
1263b6fb885SPoul-Henning Kamp MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
1279ef246c6SBruce Evans MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
1289ef246c6SBruce Evans MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
1299ef246c6SBruce Evans 
130db669378SPeter Wemm static struct malloc_type *kmemstatistics;
131cd814b26SRobert Watson static int kmemcount;
1321f6889a1SMatthew Dillon 
1338355f576SJeff Roberson #define KMEM_ZSHIFT	4
1348355f576SJeff Roberson #define KMEM_ZBASE	16
1358355f576SJeff Roberson #define KMEM_ZMASK	(KMEM_ZBASE - 1)
1368355f576SJeff Roberson 
137bda06553SXin LI #define KMEM_ZMAX	65536
1388355f576SJeff Roberson #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
13960ae52f7SEd Schouten static uint8_t kmemsize[KMEM_ZSIZE + 1];
1406f267175SJeff Roberson 
141d7854da1SMatthew D Fleming #ifndef MALLOC_DEBUG_MAXZONES
142d7854da1SMatthew D Fleming #define	MALLOC_DEBUG_MAXZONES	1
143d7854da1SMatthew D Fleming #endif
144d7854da1SMatthew D Fleming static int numzones = MALLOC_DEBUG_MAXZONES;
145d7854da1SMatthew D Fleming 
1460ce3f16dSRobert Watson /*
1470ce3f16dSRobert Watson  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
1480ce3f16dSRobert Watson  * of various sizes.
1490ce3f16dSRobert Watson  *
1500ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1510ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1520ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1530ce3f16dSRobert Watson  */
1548355f576SJeff Roberson struct {
1556f267175SJeff Roberson 	int kz_size;
1566f267175SJeff Roberson 	char *kz_name;
157d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1586f267175SJeff Roberson } kmemzones[] = {
159d7854da1SMatthew D Fleming 	{16, "16", },
160d7854da1SMatthew D Fleming 	{32, "32", },
161d7854da1SMatthew D Fleming 	{64, "64", },
162d7854da1SMatthew D Fleming 	{128, "128", },
163d7854da1SMatthew D Fleming 	{256, "256", },
164d7854da1SMatthew D Fleming 	{512, "512", },
165d7854da1SMatthew D Fleming 	{1024, "1024", },
166d7854da1SMatthew D Fleming 	{2048, "2048", },
167d7854da1SMatthew D Fleming 	{4096, "4096", },
168d7854da1SMatthew D Fleming 	{8192, "8192", },
169d7854da1SMatthew D Fleming 	{16384, "16384", },
170d7854da1SMatthew D Fleming 	{32768, "32768", },
171d7854da1SMatthew D Fleming 	{65536, "65536", },
1728355f576SJeff Roberson 	{0, NULL},
1738355f576SJeff Roberson };
1748355f576SJeff Roberson 
1750ce3f16dSRobert Watson /*
1760ce3f16dSRobert Watson  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
1770ce3f16dSRobert Watson  * types are described by a data structure passed by the declaring code, but
1780ce3f16dSRobert Watson  * the malloc(9) implementation has its own data structure describing the
1790ce3f16dSRobert Watson  * type and statistics.  This permits the malloc(9)-internal data structures
1800ce3f16dSRobert Watson  * to be modified without breaking binary-compiled kernel modules that
1810ce3f16dSRobert Watson  * declare malloc types.
1820ce3f16dSRobert Watson  */
18363a7e0a3SRobert Watson static uma_zone_t mt_zone;
1849afff6b1SMateusz Guzik static uma_zone_t mt_stats_zone;
18563a7e0a3SRobert Watson 
186b89eaf4eSAlan Cox u_long vm_kmem_size;
187d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
18884344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1895a34a9f0SJeff Roberson 
1907001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1917001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1927001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1937001d850SXin LI 
194b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
195d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1960e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1970e5179e4SStephane E. Potvin 
198b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
199d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
200479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
201479439b4SDag-Erling Smørgrav 
2024813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
203d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
204479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
205479439b4SDag-Erling Smørgrav 
2067814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
2077814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
2087814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2095df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
2107814c80aSAndriy Gapon 
21195bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
21295bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
21395bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2145df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
21595bb9d38SAndriy Gapon 
2165a34a9f0SJeff Roberson /*
21799571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2185a34a9f0SJeff Roberson  */
2195a34a9f0SJeff Roberson struct mtx malloc_mtx;
22069ef67f9SJason Evans 
2215e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2225e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2236f267175SJeff Roberson 
2245e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2255e914b96SJeff Roberson #endif
2265e914b96SJeff Roberson 
227cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
228df8bae1dSRodney W. Grimes 
2290ce3f16dSRobert Watson /*
2300ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2310ce3f16dSRobert Watson  */
2321fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2331fb14a47SPoul-Henning Kamp 
234d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2356472ac3dSEd Schouten static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
236d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
237d7854da1SMatthew D Fleming #endif
238d7854da1SMatthew D Fleming 
239eae870cdSRobert Watson /*
2400ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2410ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
242eae870cdSRobert Watson  */
2430ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
244eae870cdSRobert Watson static int malloc_failure_rate;
245eae870cdSRobert Watson static int malloc_nowait_count;
246eae870cdSRobert Watson static int malloc_failure_count;
247af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
248eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
249eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
250eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
251eae870cdSRobert Watson #endif
252eae870cdSRobert Watson 
2537814c80aSAndriy Gapon static int
2547814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2557814c80aSAndriy Gapon {
2567814c80aSAndriy Gapon 	u_long size;
2577814c80aSAndriy Gapon 
2582e47807cSJeff Roberson 	size = uma_size();
2597814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2607814c80aSAndriy Gapon }
2617814c80aSAndriy Gapon 
26295bb9d38SAndriy Gapon static int
26395bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
26495bb9d38SAndriy Gapon {
2652e47807cSJeff Roberson 	u_long size, limit;
26695bb9d38SAndriy Gapon 
2672e47807cSJeff Roberson 	/* The sysctl is unsigned, implement as a saturation value. */
2682e47807cSJeff Roberson 	size = uma_size();
2692e47807cSJeff Roberson 	limit = uma_limit();
2702e47807cSJeff Roberson 	if (size > limit)
2712e47807cSJeff Roberson 		size = 0;
2722e47807cSJeff Roberson 	else
2732e47807cSJeff Roberson 		size = limit - size;
27495bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
27595bb9d38SAndriy Gapon }
27695bb9d38SAndriy Gapon 
277d7854da1SMatthew D Fleming /*
278d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
279d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
280d7854da1SMatthew D Fleming  */
281d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
282d7854da1SMatthew D Fleming static void
283d7854da1SMatthew D Fleming tunable_set_numzones(void)
284d7854da1SMatthew D Fleming {
285d7854da1SMatthew D Fleming 
286d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
287d7854da1SMatthew D Fleming 	    &numzones);
288d7854da1SMatthew D Fleming 
289d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
290d7854da1SMatthew D Fleming 	if (numzones <= 0)
291d7854da1SMatthew D Fleming 		numzones = 1;
292d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
293d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
294d7854da1SMatthew D Fleming }
295d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
296af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
297d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
298d7854da1SMatthew D Fleming 
299d7854da1SMatthew D Fleming /*
300d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
301d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
302d7854da1SMatthew D Fleming  */
303d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
304d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
305d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
306d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
307d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
308d7854da1SMatthew D Fleming 
309c9e05ccdSMateusz Guzik static void
310c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
311d7854da1SMatthew D Fleming {
312c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
313c9e05ccdSMateusz Guzik 	const char *desc;
314d7854da1SMatthew D Fleming 	size_t len;
315d7854da1SMatthew D Fleming 	u_int val;
316d7854da1SMatthew D Fleming 
317c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
318c9e05ccdSMateusz Guzik 	desc = mtp->ks_shortdesc;
319d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
320c9e05ccdSMateusz Guzik 		val = 0;
321c9e05ccdSMateusz Guzik 	else
322d7854da1SMatthew D Fleming 		val = desc[zone_offset % len];
323c9e05ccdSMateusz Guzik 	mtip->mti_zone = (val % numzones);
324c9e05ccdSMateusz Guzik }
325c9e05ccdSMateusz Guzik 
326c9e05ccdSMateusz Guzik static inline u_int
327c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
328c9e05ccdSMateusz Guzik {
329c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
330c9e05ccdSMateusz Guzik 
331c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
332c9e05ccdSMateusz Guzik 
333c9e05ccdSMateusz Guzik 	KASSERT(mtip->mti_zone < numzones,
334c9e05ccdSMateusz Guzik 	    ("mti_zone %u out of range %d",
335c9e05ccdSMateusz Guzik 	    mtip->mti_zone, numzones));
336c9e05ccdSMateusz Guzik 	return (mtip->mti_zone);
337d7854da1SMatthew D Fleming }
338d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
339d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
340d7854da1SMatthew D Fleming #else
341c9e05ccdSMateusz Guzik static void
342c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
343c9e05ccdSMateusz Guzik {
344c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
345c9e05ccdSMateusz Guzik 
346c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
347c9e05ccdSMateusz Guzik 	mtip->mti_zone = 0;
348c9e05ccdSMateusz Guzik }
349c9e05ccdSMateusz Guzik 
350d7854da1SMatthew D Fleming static inline u_int
351c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
352d7854da1SMatthew D Fleming {
353d7854da1SMatthew D Fleming 
354d7854da1SMatthew D Fleming 	return (0);
355d7854da1SMatthew D Fleming }
356d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
357d7854da1SMatthew D Fleming 
3581fb14a47SPoul-Henning Kamp int
3591fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3601fb14a47SPoul-Henning Kamp {
3611fb14a47SPoul-Henning Kamp 
3621fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3631fb14a47SPoul-Henning Kamp }
3641fb14a47SPoul-Henning Kamp 
365df8bae1dSRodney W. Grimes /*
3660ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3670ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3680ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3690ce3f16dSRobert Watson  * statistics.
3704362fadaSBrian Feldman  */
3714362fadaSBrian Feldman static void
37263a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
3734362fadaSBrian Feldman     int zindx)
3744362fadaSBrian Feldman {
37563a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
37663a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
37763a7e0a3SRobert Watson 
37863a7e0a3SRobert Watson 	critical_enter();
37963a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
3809afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
38173864adbSPawel Jakub Dawidek 	if (size > 0) {
38263a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
38363a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
38473864adbSPawel Jakub Dawidek 	}
3854362fadaSBrian Feldman 	if (zindx != -1)
38663a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
38791dd776cSJohn Birrell 
38891dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
3897cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
39091dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
39191dd776cSJohn Birrell 		if (probe_id != 0)
39291dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
39391dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
39491dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
39591dd776cSJohn Birrell 	}
39691dd776cSJohn Birrell #endif
39791dd776cSJohn Birrell 
39863a7e0a3SRobert Watson 	critical_exit();
3994362fadaSBrian Feldman }
4004362fadaSBrian Feldman 
4014362fadaSBrian Feldman void
40263a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
4034362fadaSBrian Feldman {
40463a7e0a3SRobert Watson 
40573864adbSPawel Jakub Dawidek 	if (size > 0)
40663a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
4074362fadaSBrian Feldman }
4084362fadaSBrian Feldman 
4094362fadaSBrian Feldman /*
4103805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
4110ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
4120ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
4130ce3f16dSRobert Watson  * statistics.
4144362fadaSBrian Feldman  */
4154362fadaSBrian Feldman void
41663a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
4174362fadaSBrian Feldman {
41863a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
41963a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
42063a7e0a3SRobert Watson 
42163a7e0a3SRobert Watson 	critical_enter();
42263a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
4239afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
42463a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
42563a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
42691dd776cSJohn Birrell 
42791dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4287cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
42991dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
43091dd776cSJohn Birrell 		if (probe_id != 0)
43191dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
43291dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
43391dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
43491dd776cSJohn Birrell 	}
43591dd776cSJohn Birrell #endif
43691dd776cSJohn Birrell 
43763a7e0a3SRobert Watson 	critical_exit();
4384362fadaSBrian Feldman }
4394362fadaSBrian Feldman 
4404362fadaSBrian Feldman /*
441f346986bSAlan Cox  *	contigmalloc:
442f346986bSAlan Cox  *
443f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
444f346986bSAlan Cox  *
445f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
446f346986bSAlan Cox  *	the allocation fails.
447f346986bSAlan Cox  */
448f346986bSAlan Cox void *
449f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
450f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
451831ce4cbSJohn Baldwin     vm_paddr_t boundary)
452f346986bSAlan Cox {
453f346986bSAlan Cox 	void *ret;
454f346986bSAlan Cox 
45544d0efb2SAlan Cox 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
45644d0efb2SAlan Cox 	    boundary, VM_MEMATTR_DEFAULT);
457f346986bSAlan Cox 	if (ret != NULL)
458f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
459f346986bSAlan Cox 	return (ret);
460f346986bSAlan Cox }
461f346986bSAlan Cox 
462ab3185d1SJeff Roberson void *
4639978bd99SMark Johnston contigmalloc_domainset(unsigned long size, struct malloc_type *type,
4649978bd99SMark Johnston     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
465ab3185d1SJeff Roberson     unsigned long alignment, vm_paddr_t boundary)
466ab3185d1SJeff Roberson {
467ab3185d1SJeff Roberson 	void *ret;
468ab3185d1SJeff Roberson 
4699978bd99SMark Johnston 	ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
470ab3185d1SJeff Roberson 	    alignment, boundary, VM_MEMATTR_DEFAULT);
471ab3185d1SJeff Roberson 	if (ret != NULL)
472ab3185d1SJeff Roberson 		malloc_type_allocated(type, round_page(size));
473ab3185d1SJeff Roberson 	return (ret);
474ab3185d1SJeff Roberson }
475ab3185d1SJeff Roberson 
476f346986bSAlan Cox /*
477f346986bSAlan Cox  *	contigfree:
478f346986bSAlan Cox  *
479f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
480f346986bSAlan Cox  *
481f346986bSAlan Cox  *	This routine may not block.
482f346986bSAlan Cox  */
483f346986bSAlan Cox void
484f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
485f346986bSAlan Cox {
486f346986bSAlan Cox 
48749bfa624SAlan Cox 	kmem_free((vm_offset_t)addr, size);
488f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
489f346986bSAlan Cox }
490f346986bSAlan Cox 
491ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
492ab3185d1SJeff Roberson static int
4935a70796aSLi-Wen Hsu malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
494ab3185d1SJeff Roberson     int flags)
495df8bae1dSRodney W. Grimes {
496194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
497ab3185d1SJeff Roberson 	int indx;
498ab3185d1SJeff Roberson 
499bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
500d3c11994SPoul-Henning Kamp 	/*
50123198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
502d3c11994SPoul-Henning Kamp 	 */
50323198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
504d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
505d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
506d3c11994SPoul-Henning Kamp 		static	int curerr, once;
507d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
508d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
5092d50560aSMarcel Moolenaar 			kdb_backtrace();
510d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
511d3c11994SPoul-Henning Kamp 			once++;
512d3c11994SPoul-Henning Kamp 		}
513d3c11994SPoul-Henning Kamp 	}
514194a0abfSPoul-Henning Kamp #endif
515eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
516eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
517eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
518eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
519eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
5203f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
521ab3185d1SJeff Roberson 			*vap = NULL;
522ab3185d1SJeff Roberson 			return (EJUSTRETURN);
523eae870cdSRobert Watson 		}
524eae870cdSRobert Watson 	}
525eae870cdSRobert Watson #endif
52606bf2a6aSMatt Macy 	if (flags & M_WAITOK) {
527b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
528a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
5295757b59fSGleb Smirnoff 		if (__predict_false(!THREAD_CAN_SLEEP())) {
530bac06038SGleb Smirnoff #ifdef EPOCH_TRACE
531bac06038SGleb Smirnoff 			epoch_trace_list(curthread);
532bac06038SGleb Smirnoff #endif
5335757b59fSGleb Smirnoff 			KASSERT(1,
5345757b59fSGleb Smirnoff 			    ("malloc(M_WAITOK) with sleeping prohibited"));
5355757b59fSGleb Smirnoff 		}
53606bf2a6aSMatt Macy 	}
537d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
5381067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
5391067a2baSJonathan T. Looney 
540e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
541ab3185d1SJeff Roberson 	if (memguard_cmp_mtp(mtp, *sizep)) {
542ab3185d1SJeff Roberson 		*vap = memguard_alloc(*sizep, flags);
543ab3185d1SJeff Roberson 		if (*vap != NULL)
544ab3185d1SJeff Roberson 			return (EJUSTRETURN);
545e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
546e3813573SMatthew D Fleming 	}
547e4eb384bSBosko Milekic #endif
548e4eb384bSBosko Milekic 
549847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
550ab3185d1SJeff Roberson 	*sizep = redzone_size_ntor(*sizep);
551ab3185d1SJeff Roberson #endif
552ab3185d1SJeff Roberson 
553ab3185d1SJeff Roberson 	return (0);
554ab3185d1SJeff Roberson }
555ab3185d1SJeff Roberson #endif
556ab3185d1SJeff Roberson 
557ab3185d1SJeff Roberson /*
5586d6a03d7SJeff Roberson  * Handle large allocations and frees by using kmem_malloc directly.
5596d6a03d7SJeff Roberson  */
5606d6a03d7SJeff Roberson static inline bool
5616d6a03d7SJeff Roberson malloc_large_slab(uma_slab_t slab)
5626d6a03d7SJeff Roberson {
5636d6a03d7SJeff Roberson 	uintptr_t va;
5646d6a03d7SJeff Roberson 
5656d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
5666d6a03d7SJeff Roberson 	return ((va & 1) != 0);
5676d6a03d7SJeff Roberson }
5686d6a03d7SJeff Roberson 
5696d6a03d7SJeff Roberson static inline size_t
5706d6a03d7SJeff Roberson malloc_large_size(uma_slab_t slab)
5716d6a03d7SJeff Roberson {
5726d6a03d7SJeff Roberson 	uintptr_t va;
5736d6a03d7SJeff Roberson 
5746d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
5756d6a03d7SJeff Roberson 	return (va >> 1);
5766d6a03d7SJeff Roberson }
5776d6a03d7SJeff Roberson 
5786d6a03d7SJeff Roberson static caddr_t
5796d6a03d7SJeff Roberson malloc_large(size_t *size, struct domainset *policy, int flags)
5806d6a03d7SJeff Roberson {
5816d6a03d7SJeff Roberson 	vm_offset_t va;
5826d6a03d7SJeff Roberson 	size_t sz;
5836d6a03d7SJeff Roberson 
5846d6a03d7SJeff Roberson 	sz = roundup(*size, PAGE_SIZE);
5856d6a03d7SJeff Roberson 	va = kmem_malloc_domainset(policy, sz, flags);
5866d6a03d7SJeff Roberson 	if (va != 0) {
5876d6a03d7SJeff Roberson 		/* The low bit is unused for slab pointers. */
5886d6a03d7SJeff Roberson 		vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
5896d6a03d7SJeff Roberson 		uma_total_inc(sz);
5906d6a03d7SJeff Roberson 		*size = sz;
5916d6a03d7SJeff Roberson 	}
5926d6a03d7SJeff Roberson 	return ((caddr_t)va);
5936d6a03d7SJeff Roberson }
5946d6a03d7SJeff Roberson 
5956d6a03d7SJeff Roberson static void
5966d6a03d7SJeff Roberson free_large(void *addr, size_t size)
5976d6a03d7SJeff Roberson {
5986d6a03d7SJeff Roberson 
5996d6a03d7SJeff Roberson 	kmem_free((vm_offset_t)addr, size);
6006d6a03d7SJeff Roberson 	uma_total_dec(size);
6016d6a03d7SJeff Roberson }
6026d6a03d7SJeff Roberson 
6036d6a03d7SJeff Roberson /*
604ab3185d1SJeff Roberson  *	malloc:
605ab3185d1SJeff Roberson  *
606ab3185d1SJeff Roberson  *	Allocate a block of memory.
607ab3185d1SJeff Roberson  *
608ab3185d1SJeff Roberson  *	If M_NOWAIT is set, this routine will not block and return NULL if
609ab3185d1SJeff Roberson  *	the allocation fails.
610ab3185d1SJeff Roberson  */
611ab3185d1SJeff Roberson void *
61234c538c3SMateusz Guzik (malloc)(size_t size, struct malloc_type *mtp, int flags)
613ab3185d1SJeff Roberson {
614ab3185d1SJeff Roberson 	int indx;
615ab3185d1SJeff Roberson 	caddr_t va;
616ab3185d1SJeff Roberson 	uma_zone_t zone;
617ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
618ab3185d1SJeff Roberson 	unsigned long osize = size;
619ab3185d1SJeff Roberson #endif
620ab3185d1SJeff Roberson 
621ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
6225072a5f4SMatt Macy 	va = NULL;
623ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
624ab3185d1SJeff Roberson 		return (va);
625847a2a17SPawel Jakub Dawidek #endif
626847a2a17SPawel Jakub Dawidek 
6270766f278SJonathan T. Looney 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
6286f267175SJeff Roberson 		if (size & KMEM_ZMASK)
6296f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
6306f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
631c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
6326f267175SJeff Roberson #ifdef MALLOC_PROFILE
6336f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
6346f267175SJeff Roberson #endif
6358355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
6364362fadaSBrian Feldman 		if (va != NULL)
637e20a199fSJeff Roberson 			size = zone->uz_size;
63863a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
6398355f576SJeff Roberson 	} else {
6406d6a03d7SJeff Roberson 		va = malloc_large(&size, DOMAINSET_RR(), flags);
64163a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
642df8bae1dSRodney W. Grimes 	}
6431282e9acSPoul-Henning Kamp 	if (flags & M_WAITOK)
644a163d034SWarner Losh 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
6451282e9acSPoul-Henning Kamp 	else if (va == NULL)
6461fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
647ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
648ab3185d1SJeff Roberson 	if (va != NULL)
649ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
6504db4f5c8SPoul-Henning Kamp #endif
651ab3185d1SJeff Roberson 	return ((void *) va);
652ab3185d1SJeff Roberson }
653ab3185d1SJeff Roberson 
6549978bd99SMark Johnston static void *
655dc727127SMark Johnston malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
6566d6a03d7SJeff Roberson     int flags)
657ab3185d1SJeff Roberson {
658ab3185d1SJeff Roberson 	uma_zone_t zone;
659dc727127SMark Johnston 	caddr_t va;
660dc727127SMark Johnston 	size_t size;
661dc727127SMark Johnston 	int indx;
662ab3185d1SJeff Roberson 
663dc727127SMark Johnston 	size = *sizep;
6646d6a03d7SJeff Roberson 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
6656d6a03d7SJeff Roberson 	    ("malloc_domain: Called with bad flag / size combination."));
666ab3185d1SJeff Roberson 	if (size & KMEM_ZMASK)
667ab3185d1SJeff Roberson 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
668ab3185d1SJeff Roberson 	indx = kmemsize[size >> KMEM_ZSHIFT];
669c9e05ccdSMateusz Guzik 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
670ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
671ab3185d1SJeff Roberson 	krequests[size >> KMEM_ZSHIFT]++;
672ab3185d1SJeff Roberson #endif
673ab3185d1SJeff Roberson 	va = uma_zalloc_domain(zone, NULL, domain, flags);
674ab3185d1SJeff Roberson 	if (va != NULL)
675dc727127SMark Johnston 		*sizep = zone->uz_size;
6766d6a03d7SJeff Roberson 	*indxp = indx;
677df8bae1dSRodney W. Grimes 	return ((void *)va);
678df8bae1dSRodney W. Grimes }
679df8bae1dSRodney W. Grimes 
680fd91e076SKristof Provost void *
6819978bd99SMark Johnston malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
6829978bd99SMark Johnston     int flags)
6839978bd99SMark Johnston {
6849978bd99SMark Johnston 	struct vm_domainset_iter di;
6856d6a03d7SJeff Roberson 	caddr_t ret;
6869978bd99SMark Johnston 	int domain;
6876d6a03d7SJeff Roberson 	int indx;
6889978bd99SMark Johnston 
6896d6a03d7SJeff Roberson #if defined(DEBUG_REDZONE)
6906d6a03d7SJeff Roberson 	unsigned long osize = size;
6916d6a03d7SJeff Roberson #endif
6926d6a03d7SJeff Roberson #ifdef MALLOC_DEBUG
6936d6a03d7SJeff Roberson 	ret= NULL;
6946d6a03d7SJeff Roberson 	if (malloc_dbg(&ret, &size, mtp, flags) != 0)
6956d6a03d7SJeff Roberson 		return (ret);
6966d6a03d7SJeff Roberson #endif
6976d6a03d7SJeff Roberson 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
6989978bd99SMark Johnston 		vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
6999978bd99SMark Johnston 		do {
700dc727127SMark Johnston 			ret = malloc_domain(&size, &indx, mtp, domain, flags);
7016d6a03d7SJeff Roberson 		} while (ret == NULL &&
7026d6a03d7SJeff Roberson 		    vm_domainset_iter_policy(&di, &domain) == 0);
7036d6a03d7SJeff Roberson 		malloc_type_zone_allocated(mtp, ret == NULL ? 0 : size, indx);
7046d6a03d7SJeff Roberson 	} else {
7056d6a03d7SJeff Roberson 		/* Policy is handled by kmem. */
7066d6a03d7SJeff Roberson 		ret = malloc_large(&size, ds, flags);
7076d6a03d7SJeff Roberson 		malloc_type_allocated(mtp, ret == NULL ? 0 : size);
7086d6a03d7SJeff Roberson 	}
7099978bd99SMark Johnston 
7106d6a03d7SJeff Roberson 	if (flags & M_WAITOK)
7116d6a03d7SJeff Roberson 		KASSERT(ret != NULL, ("malloc(M_WAITOK) returned NULL"));
7126d6a03d7SJeff Roberson 	else if (ret == NULL)
7136d6a03d7SJeff Roberson 		t_malloc_fail = time_uptime;
7146d6a03d7SJeff Roberson #ifdef DEBUG_REDZONE
7156d6a03d7SJeff Roberson 	if (ret != NULL)
7166d6a03d7SJeff Roberson 		ret = redzone_setup(ret, osize);
7176d6a03d7SJeff Roberson #endif
7189978bd99SMark Johnston 	return (ret);
7199978bd99SMark Johnston }
7209978bd99SMark Johnston 
7219978bd99SMark Johnston void *
722fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
723fd91e076SKristof Provost {
724fd91e076SKristof Provost 
725c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
726c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
727fd91e076SKristof Provost 
728fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
729fd91e076SKristof Provost }
730fd91e076SKristof Provost 
731ab3185d1SJeff Roberson #ifdef INVARIANTS
732ab3185d1SJeff Roberson static void
733ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
734ab3185d1SJeff Roberson {
735ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
736ab3185d1SJeff Roberson 
737ab3185d1SJeff Roberson 	/*
738ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
739ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
740ab3185d1SJeff Roberson 	 * have stepped on it later.
741ab3185d1SJeff Roberson 	 *
742ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
743ab3185d1SJeff Roberson 	 * 64 bit machines
744ab3185d1SJeff Roberson 	 */
745ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
746ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
747ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
748ab3185d1SJeff Roberson 	*mtpp = mtp;
749ab3185d1SJeff Roberson }
750ab3185d1SJeff Roberson #endif
751ab3185d1SJeff Roberson 
752ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
753ab3185d1SJeff Roberson static int
754ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
755ab3185d1SJeff Roberson {
756ab3185d1SJeff Roberson 	void *addr;
757ab3185d1SJeff Roberson 
758ab3185d1SJeff Roberson 	addr = *addrp;
759ab3185d1SJeff Roberson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
760ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
761ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
762ab3185d1SJeff Roberson 
763ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
764ab3185d1SJeff Roberson 	if (addr == NULL)
765ab3185d1SJeff Roberson 		return (EJUSTRETURN);
766ab3185d1SJeff Roberson 
767ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
768ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
769ab3185d1SJeff Roberson 		memguard_free(addr);
770ab3185d1SJeff Roberson 		return (EJUSTRETURN);
771ab3185d1SJeff Roberson 	}
772ab3185d1SJeff Roberson #endif
773ab3185d1SJeff Roberson 
774ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
775ab3185d1SJeff Roberson 	redzone_check(addr);
776ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
777ab3185d1SJeff Roberson #endif
778ab3185d1SJeff Roberson 
779ab3185d1SJeff Roberson 	return (0);
780ab3185d1SJeff Roberson }
781ab3185d1SJeff Roberson #endif
782ab3185d1SJeff Roberson 
783fd91e076SKristof Provost /*
7841c7c3c6aSMatthew Dillon  *	free:
7851c7c3c6aSMatthew Dillon  *
786df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
7871c7c3c6aSMatthew Dillon  *
7881c7c3c6aSMatthew Dillon  *	This routine may not block.
789df8bae1dSRodney W. Grimes  */
790df8bae1dSRodney W. Grimes void
79163a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
792df8bae1dSRodney W. Grimes {
793584061b4SJeff Roberson 	uma_zone_t zone;
79499571dc3SJeff Roberson 	uma_slab_t slab;
79599571dc3SJeff Roberson 	u_long size;
796254c6cb3SPoul-Henning Kamp 
797ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
798ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
799ab3185d1SJeff Roberson 		return;
800ab3185d1SJeff Roberson #endif
80144a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
80244a8ff31SArchie Cobbs 	if (addr == NULL)
80344a8ff31SArchie Cobbs 		return;
80444a8ff31SArchie Cobbs 
805584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
8068355f576SJeff Roberson 	if (slab == NULL)
8076f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
80899571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
80999571dc3SJeff Roberson 
8106d6a03d7SJeff Roberson 	if (__predict_true(!malloc_large_slab(slab))) {
811584061b4SJeff Roberson 		size = zone->uz_size;
8128f70816cSJeff Roberson #ifdef INVARIANTS
813ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
8148f70816cSJeff Roberson #endif
815584061b4SJeff Roberson 		uma_zfree_arg(zone, addr, slab);
81614bf02f8SJohn Dyson 	} else {
8176d6a03d7SJeff Roberson 		size = malloc_large_size(slab);
8186d6a03d7SJeff Roberson 		free_large(addr, size);
81914bf02f8SJohn Dyson 	}
82063a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
821df8bae1dSRodney W. Grimes }
822df8bae1dSRodney W. Grimes 
823*45035becSMatt Macy /*
824*45035becSMatt Macy  *	zfree:
825*45035becSMatt Macy  *
826*45035becSMatt Macy  *	Zero then free a block of memory allocated by malloc.
827*45035becSMatt Macy  *
828*45035becSMatt Macy  *	This routine may not block.
829*45035becSMatt Macy  */
830*45035becSMatt Macy void
831*45035becSMatt Macy zfree(void *addr, struct malloc_type *mtp)
832*45035becSMatt Macy {
833*45035becSMatt Macy 	uma_zone_t zone;
834*45035becSMatt Macy 	uma_slab_t slab;
835*45035becSMatt Macy 	u_long size;
836*45035becSMatt Macy 
837*45035becSMatt Macy #ifdef MALLOC_DEBUG
838*45035becSMatt Macy 	if (free_dbg(&addr, mtp) != 0)
839*45035becSMatt Macy 		return;
840*45035becSMatt Macy #endif
841*45035becSMatt Macy 	/* free(NULL, ...) does nothing */
842*45035becSMatt Macy 	if (addr == NULL)
843*45035becSMatt Macy 		return;
844*45035becSMatt Macy 
845*45035becSMatt Macy 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
846*45035becSMatt Macy 	if (slab == NULL)
847*45035becSMatt Macy 		panic("free: address %p(%p) has not been allocated.\n",
848*45035becSMatt Macy 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
849*45035becSMatt Macy 
850*45035becSMatt Macy 	if (__predict_true(!malloc_large_slab(slab))) {
851*45035becSMatt Macy 		size = zone->uz_size;
852*45035becSMatt Macy #ifdef INVARIANTS
853*45035becSMatt Macy 		free_save_type(addr, mtp, size);
854*45035becSMatt Macy #endif
855*45035becSMatt Macy 		explicit_bzero(addr, size);
856*45035becSMatt Macy 		uma_zfree_arg(zone, addr, slab);
857*45035becSMatt Macy 	} else {
858*45035becSMatt Macy 		size = malloc_large_size(slab);
859*45035becSMatt Macy 		explicit_bzero(addr, size);
860*45035becSMatt Macy 		free_large(addr, size);
861*45035becSMatt Macy 	}
862*45035becSMatt Macy 	malloc_type_freed(mtp, size);
863*45035becSMatt Macy }
864*45035becSMatt Macy 
865ab3185d1SJeff Roberson void
866ab3185d1SJeff Roberson free_domain(void *addr, struct malloc_type *mtp)
867ab3185d1SJeff Roberson {
868584061b4SJeff Roberson 	uma_zone_t zone;
869ab3185d1SJeff Roberson 	uma_slab_t slab;
870ab3185d1SJeff Roberson 	u_long size;
871ab3185d1SJeff Roberson 
872ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
873ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
874ab3185d1SJeff Roberson 		return;
875ab3185d1SJeff Roberson #endif
876ab3185d1SJeff Roberson 
877ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
878ab3185d1SJeff Roberson 	if (addr == NULL)
879ab3185d1SJeff Roberson 		return;
880ab3185d1SJeff Roberson 
881584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
882ab3185d1SJeff Roberson 	if (slab == NULL)
883ab3185d1SJeff Roberson 		panic("free_domain: address %p(%p) has not been allocated.\n",
884ab3185d1SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
885ab3185d1SJeff Roberson 
8866d6a03d7SJeff Roberson 	if (__predict_true(!malloc_large_slab(slab))) {
887584061b4SJeff Roberson 		size = zone->uz_size;
888ab3185d1SJeff Roberson #ifdef INVARIANTS
889ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
890ab3185d1SJeff Roberson #endif
891584061b4SJeff Roberson 		uma_zfree_domain(zone, addr, slab);
892ab3185d1SJeff Roberson 	} else {
8936d6a03d7SJeff Roberson 		size = malloc_large_size(slab);
8946d6a03d7SJeff Roberson 		free_large(addr, size);
895ab3185d1SJeff Roberson 	}
896ab3185d1SJeff Roberson 	malloc_type_freed(mtp, size);
897ab3185d1SJeff Roberson }
898ab3185d1SJeff Roberson 
899df8bae1dSRodney W. Grimes /*
90044a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
90144a8ff31SArchie Cobbs  */
90244a8ff31SArchie Cobbs void *
903bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
90444a8ff31SArchie Cobbs {
905584061b4SJeff Roberson 	uma_zone_t zone;
9068355f576SJeff Roberson 	uma_slab_t slab;
90744a8ff31SArchie Cobbs 	unsigned long alloc;
90844a8ff31SArchie Cobbs 	void *newaddr;
90944a8ff31SArchie Cobbs 
910bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
911bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
912d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
9131067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
9141067a2baSJonathan T. Looney 
91544a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
91644a8ff31SArchie Cobbs 	if (addr == NULL)
91763a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
91863a7e0a3SRobert Watson 
91963a7e0a3SRobert Watson 	/*
92063a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
92163a7e0a3SRobert Watson 	 * per-CPU stats.
92263a7e0a3SRobert Watson 	 */
92344a8ff31SArchie Cobbs 
924e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
9256d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
9266d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
927e4eb384bSBosko Milekic #endif
928e4eb384bSBosko Milekic 
929847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
930847a2a17SPawel Jakub Dawidek 	slab = NULL;
931b476ae7fSJeff Roberson 	zone = NULL;
932847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
933847a2a17SPawel Jakub Dawidek #else
934584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
9358355f576SJeff Roberson 
93644a8ff31SArchie Cobbs 	/* Sanity check */
9378355f576SJeff Roberson 	KASSERT(slab != NULL,
93844a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
93944a8ff31SArchie Cobbs 
94044a8ff31SArchie Cobbs 	/* Get the size of the original block */
9416d6a03d7SJeff Roberson 	if (!malloc_large_slab(slab))
942584061b4SJeff Roberson 		alloc = zone->uz_size;
9438355f576SJeff Roberson 	else
9446d6a03d7SJeff Roberson 		alloc = malloc_large_size(slab);
94544a8ff31SArchie Cobbs 
94644a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
94744a8ff31SArchie Cobbs 	if (size <= alloc
94844a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
94944a8ff31SArchie Cobbs 		return (addr);
950847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
95144a8ff31SArchie Cobbs 
95244a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
95363a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
95444a8ff31SArchie Cobbs 		return (NULL);
95544a8ff31SArchie Cobbs 
95644a8ff31SArchie Cobbs 	/* Copy over original contents */
95744a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
95863a7e0a3SRobert Watson 	free(addr, mtp);
95944a8ff31SArchie Cobbs 	return (newaddr);
96044a8ff31SArchie Cobbs }
96144a8ff31SArchie Cobbs 
96244a8ff31SArchie Cobbs /*
96344a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
96444a8ff31SArchie Cobbs  */
96544a8ff31SArchie Cobbs void *
966bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
96744a8ff31SArchie Cobbs {
96844a8ff31SArchie Cobbs 	void *mem;
96944a8ff31SArchie Cobbs 
97063a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
97163a7e0a3SRobert Watson 		free(addr, mtp);
97244a8ff31SArchie Cobbs 	return (mem);
97344a8ff31SArchie Cobbs }
97444a8ff31SArchie Cobbs 
975c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
976c70af487SAlan Cox 
9775df87b21SJeff Roberson /*
978c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
9795df87b21SJeff Roberson  */
9805df87b21SJeff Roberson void
9815df87b21SJeff Roberson kmeminit(void)
9825df87b21SJeff Roberson {
983af3b2549SHans Petter Selasky 	u_long mem_size;
984af3b2549SHans Petter Selasky 	u_long tmp;
98569ef67f9SJason Evans 
986af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
987af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
988af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
989af3b2549SHans Petter Selasky #endif
990af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
991af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
992af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
993af3b2549SHans Petter Selasky #endif
994af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
995af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
996af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
997af3b2549SHans Petter Selasky #endif
9988a58a9f6SJohn Dyson 	/*
999c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
1000c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
1001c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
1002c70af487SAlan Cox 	 * specifically,
10038a58a9f6SJohn Dyson 	 *
1004c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1005c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1006c70af487SAlan Cox 	 *
1007c70af487SAlan Cox 	 * Every architecture must define an integral value for
1008c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1009c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1010c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
1011c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1012c70af487SAlan Cox 	 * a given architecture.
10138a58a9f6SJohn Dyson 	 */
101444f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
10157c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
10167c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
10178a58a9f6SJohn Dyson 
1018c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
1019c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1020c70af487SAlan Cox 
1021af3b2549SHans Petter Selasky 	/*
1022af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
1023af3b2549SHans Petter Selasky 	 * variable:
1024af3b2549SHans Petter Selasky 	 */
1025af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
102628b740daSKonstantin Belousov 		vm_kmem_size = mem_size / vm_kmem_size_scale;
102728b740daSKonstantin Belousov 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
102828b740daSKonstantin Belousov 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1029c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
10300e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
1031479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1032479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
1033af3b2549SHans Petter Selasky 	}
103428b740daSKonstantin Belousov 	if (vm_kmem_size == 0)
103528b740daSKonstantin Belousov 		panic("Tune VM_KMEM_SIZE_* for the platform");
10368a58a9f6SJohn Dyson 
103727b8623fSDavid Greenman 	/*
1038af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
1039c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
1040c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
1041c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
1042c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
104327b8623fSDavid Greenman 	 */
1044c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1045c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
10468a58a9f6SJohn Dyson 
1047e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
1048e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
1049f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1050e3813573SMatthew D Fleming #else
1051e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
1052e3813573SMatthew D Fleming #endif
10532e47807cSJeff Roberson 	uma_set_limit(tmp);
10548355f576SJeff Roberson 
1055e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
1056e4eb384bSBosko Milekic 	/*
1057e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1058e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
1059e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
1060e4eb384bSBosko Milekic 	 */
10612e47807cSJeff Roberson 	memguard_init(kernel_arena);
1062e4eb384bSBosko Milekic #endif
10635df87b21SJeff Roberson }
10645df87b21SJeff Roberson 
10655df87b21SJeff Roberson /*
10665df87b21SJeff Roberson  * Initialize the kernel memory allocator
10675df87b21SJeff Roberson  */
10685df87b21SJeff Roberson /* ARGSUSED*/
10695df87b21SJeff Roberson static void
10705df87b21SJeff Roberson mallocinit(void *dummy)
10715df87b21SJeff Roberson {
10725df87b21SJeff Roberson 	int i;
10735df87b21SJeff Roberson 	uint8_t indx;
10745df87b21SJeff Roberson 
10755df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
10765df87b21SJeff Roberson 
10775df87b21SJeff Roberson 	kmeminit();
1078e4eb384bSBosko Milekic 
10797001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
10807001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
10817001d850SXin LI 
10829afff6b1SMateusz Guzik 	mt_stats_zone = uma_zcreate("mt_stats_zone",
10839afff6b1SMateusz Guzik 	    sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
10849afff6b1SMateusz Guzik 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
108563a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
108663a7e0a3SRobert Watson #ifdef INVARIANTS
108763a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
108863a7e0a3SRobert Watson #else
108963a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
109063a7e0a3SRobert Watson #endif
109163a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
10926f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
10936f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
10946f267175SJeff Roberson 		char *name = kmemzones[indx].kz_name;
1095d7854da1SMatthew D Fleming 		int subzone;
10968355f576SJeff Roberson 
1097d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
1098d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
1099d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
11008efc4effSJeff Roberson #ifdef INVARIANTS
11018f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
11028efc4effSJeff Roberson #else
11038efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
11048efc4effSJeff Roberson #endif
11058efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1106d7854da1SMatthew D Fleming 		}
11078355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
11086f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
11098355f576SJeff Roberson 
1110df8bae1dSRodney W. Grimes 	}
1111254c6cb3SPoul-Henning Kamp }
1112af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1113254c6cb3SPoul-Henning Kamp 
1114db669378SPeter Wemm void
111587efd4d5SRobert Watson malloc_init(void *data)
1116254c6cb3SPoul-Henning Kamp {
111763a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
111863a7e0a3SRobert Watson 	struct malloc_type *mtp;
111963a7e0a3SRobert Watson 
112044f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
112163a7e0a3SRobert Watson 
112263a7e0a3SRobert Watson 	mtp = data;
1123f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
1124f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
1125bb1c7df8SRobert Watson 
112663a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
11279afff6b1SMateusz Guzik 	mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
112863a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
1129c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
1130254c6cb3SPoul-Henning Kamp 
11316f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
113263a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
113363a7e0a3SRobert Watson 	kmemstatistics = mtp;
1134cd814b26SRobert Watson 	kmemcount++;
11356f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1136df8bae1dSRodney W. Grimes }
1137db669378SPeter Wemm 
1138db669378SPeter Wemm void
113987efd4d5SRobert Watson malloc_uninit(void *data)
1140db669378SPeter Wemm {
114163a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
11422a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
114363a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
114445d48bdaSPaul Saab 	uma_slab_t slab;
11452a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
11462a143d5bSPawel Jakub Dawidek 	int i;
1147db669378SPeter Wemm 
114863a7e0a3SRobert Watson 	mtp = data;
1149bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
1150bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
115163a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1152bb1c7df8SRobert Watson 
11536f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
115463a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
115563a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
115663a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
115763a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
115863a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1159f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
116063a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1161f121baaaSBrian Somers 				break;
1162db669378SPeter Wemm 			}
1163f121baaaSBrian Somers 		}
1164f121baaaSBrian Somers 		KASSERT(temp,
1165f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
116663a7e0a3SRobert Watson 	} else
116763a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1168cd814b26SRobert Watson 	kmemcount--;
11696f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
11702a143d5bSPawel Jakub Dawidek 
11712a143d5bSPawel Jakub Dawidek 	/*
11722a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
11732a143d5bSPawel Jakub Dawidek 	 */
11742a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
11759afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
11769afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
11772a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
11782a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
11792a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
11802a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
11812a143d5bSPawel Jakub Dawidek 	}
11822a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
11832a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
11842a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
11852a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
11862a143d5bSPawel Jakub Dawidek 	}
11872a143d5bSPawel Jakub Dawidek 
118845d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
11899afff6b1SMateusz Guzik 	uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
119045d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
1191db669378SPeter Wemm }
11926f267175SJeff Roberson 
1193d362c40dSPawel Jakub Dawidek struct malloc_type *
1194d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1195d362c40dSPawel Jakub Dawidek {
1196d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1197d362c40dSPawel Jakub Dawidek 
1198d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1199d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1200d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1201d362c40dSPawel Jakub Dawidek 			return (mtp);
1202d362c40dSPawel Jakub Dawidek 	}
1203d362c40dSPawel Jakub Dawidek 	return (NULL);
1204d362c40dSPawel Jakub Dawidek }
1205d362c40dSPawel Jakub Dawidek 
12066f267175SJeff Roberson static int
1207cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1208cd814b26SRobert Watson {
1209cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1210cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
12119afff6b1SMateusz Guzik 	struct malloc_type_stats *mtsp, zeromts;
1212cd814b26SRobert Watson 	struct malloc_type_header mth;
1213cd814b26SRobert Watson 	struct malloc_type *mtp;
12144e657159SMatthew D Fleming 	int error, i;
1215cd814b26SRobert Watson 	struct sbuf sbuf;
1216cd814b26SRobert Watson 
121700f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
121800f0e671SMatthew D Fleming 	if (error != 0)
121900f0e671SMatthew D Fleming 		return (error);
12204e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
12211eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1222cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1223cd814b26SRobert Watson 
12249afff6b1SMateusz Guzik 	bzero(&zeromts, sizeof(zeromts));
12259afff6b1SMateusz Guzik 
1226cd814b26SRobert Watson 	/*
1227cd814b26SRobert Watson 	 * Insert stream header.
1228cd814b26SRobert Watson 	 */
1229cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1230cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1231cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1232cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
12334e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1234cd814b26SRobert Watson 
1235cd814b26SRobert Watson 	/*
1236cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1237cd814b26SRobert Watson 	 */
1238cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1239cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1240cd814b26SRobert Watson 
1241cd814b26SRobert Watson 		/*
1242cd814b26SRobert Watson 		 * Insert type header.
1243cd814b26SRobert Watson 		 */
1244cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1245cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
12464e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1247cd814b26SRobert Watson 
1248cd814b26SRobert Watson 		/*
1249cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1250cd814b26SRobert Watson 		 */
12519afff6b1SMateusz Guzik 		for (i = 0; i <= mp_maxid; i++) {
12529afff6b1SMateusz Guzik 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
12539afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1254cd814b26SRobert Watson 		}
12559afff6b1SMateusz Guzik 		/*
12569afff6b1SMateusz Guzik 		 * Fill in the missing CPUs.
12579afff6b1SMateusz Guzik 		 */
12589afff6b1SMateusz Guzik 		for (; i < MAXCPU; i++) {
12599afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
12609afff6b1SMateusz Guzik 		}
12619afff6b1SMateusz Guzik 
1262cd814b26SRobert Watson 	}
1263cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
12644e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1265cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1266cd814b26SRobert Watson 	return (error);
1267cd814b26SRobert Watson }
1268cd814b26SRobert Watson 
1269cd814b26SRobert Watson SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1270cd814b26SRobert Watson     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1271cd814b26SRobert Watson     "Return malloc types");
1272cd814b26SRobert Watson 
1273cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1274cd814b26SRobert Watson     "Count of kernel malloc types");
1275cd814b26SRobert Watson 
127691dd776cSJohn Birrell void
127791dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
127891dd776cSJohn Birrell {
127991dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
128091dd776cSJohn Birrell 	int count, i;
128191dd776cSJohn Birrell 	size_t buflen;
128291dd776cSJohn Birrell 
128391dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
128491dd776cSJohn Birrell restart:
128591dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
128691dd776cSJohn Birrell 	count = kmemcount;
128791dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
128891dd776cSJohn Birrell 
128991dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
129091dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
129191dd776cSJohn Birrell 
129291dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
129391dd776cSJohn Birrell 
129491dd776cSJohn Birrell 	if (count < kmemcount) {
129591dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
129691dd776cSJohn Birrell 		goto restart;
129791dd776cSJohn Birrell 	}
129891dd776cSJohn Birrell 
129991dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
130091dd776cSJohn Birrell 		bufmtp[i] = mtp;
130191dd776cSJohn Birrell 
130291dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
130391dd776cSJohn Birrell 
130491dd776cSJohn Birrell 	for (i = 0; i < count; i++)
130591dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
130691dd776cSJohn Birrell 
130791dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
130891dd776cSJohn Birrell }
130991dd776cSJohn Birrell 
1310909ed16cSRobert Watson #ifdef DDB
131146d70077SConrad Meyer static int64_t
131246d70077SConrad Meyer get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
131346d70077SConrad Meyer     uint64_t *inuse)
1314909ed16cSRobert Watson {
131546d70077SConrad Meyer 	const struct malloc_type_stats *mtsp;
131646d70077SConrad Meyer 	uint64_t frees, alloced, freed;
1317909ed16cSRobert Watson 	int i;
1318909ed16cSRobert Watson 
131946d70077SConrad Meyer 	*allocs = 0;
1320909ed16cSRobert Watson 	frees = 0;
132124076d13SRobert Watson 	alloced = 0;
132224076d13SRobert Watson 	freed = 0;
13239afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
13249afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
132546d70077SConrad Meyer 
132646d70077SConrad Meyer 		*allocs += mtsp->mts_numallocs;
132726e9d9b0SMark Johnston 		frees += mtsp->mts_numfrees;
132826e9d9b0SMark Johnston 		alloced += mtsp->mts_memalloced;
132926e9d9b0SMark Johnston 		freed += mtsp->mts_memfreed;
1330909ed16cSRobert Watson 	}
133146d70077SConrad Meyer 	*inuse = *allocs - frees;
133246d70077SConrad Meyer 	return (alloced - freed);
133346d70077SConrad Meyer }
133446d70077SConrad Meyer 
133546d70077SConrad Meyer DB_SHOW_COMMAND(malloc, db_show_malloc)
133646d70077SConrad Meyer {
133746d70077SConrad Meyer 	const char *fmt_hdr, *fmt_entry;
133846d70077SConrad Meyer 	struct malloc_type *mtp;
133946d70077SConrad Meyer 	uint64_t allocs, inuse;
134046d70077SConrad Meyer 	int64_t size;
134146d70077SConrad Meyer 	/* variables for sorting */
134246d70077SConrad Meyer 	struct malloc_type *last_mtype, *cur_mtype;
134346d70077SConrad Meyer 	int64_t cur_size, last_size;
134446d70077SConrad Meyer 	int ties;
134546d70077SConrad Meyer 
134646d70077SConrad Meyer 	if (modif[0] == 'i') {
134746d70077SConrad Meyer 		fmt_hdr = "%s,%s,%s,%s\n";
134846d70077SConrad Meyer 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
134946d70077SConrad Meyer 	} else {
135046d70077SConrad Meyer 		fmt_hdr = "%18s %12s  %12s %12s\n";
135146d70077SConrad Meyer 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
135246d70077SConrad Meyer 	}
135346d70077SConrad Meyer 
135446d70077SConrad Meyer 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
135546d70077SConrad Meyer 
135646d70077SConrad Meyer 	/* Select sort, largest size first. */
135746d70077SConrad Meyer 	last_mtype = NULL;
135846d70077SConrad Meyer 	last_size = INT64_MAX;
135946d70077SConrad Meyer 	for (;;) {
136046d70077SConrad Meyer 		cur_mtype = NULL;
136146d70077SConrad Meyer 		cur_size = -1;
136246d70077SConrad Meyer 		ties = 0;
136346d70077SConrad Meyer 
136446d70077SConrad Meyer 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
136546d70077SConrad Meyer 			/*
136646d70077SConrad Meyer 			 * In the case of size ties, print out mtypes
136746d70077SConrad Meyer 			 * in the order they are encountered.  That is,
136846d70077SConrad Meyer 			 * when we encounter the most recently output
136946d70077SConrad Meyer 			 * mtype, we have already printed all preceding
137046d70077SConrad Meyer 			 * ties, and we must print all following ties.
137146d70077SConrad Meyer 			 */
137246d70077SConrad Meyer 			if (mtp == last_mtype) {
137346d70077SConrad Meyer 				ties = 1;
137446d70077SConrad Meyer 				continue;
137546d70077SConrad Meyer 			}
137646d70077SConrad Meyer 			size = get_malloc_stats(mtp->ks_handle, &allocs,
137746d70077SConrad Meyer 			    &inuse);
137846d70077SConrad Meyer 			if (size > cur_size && size < last_size + ties) {
137946d70077SConrad Meyer 				cur_size = size;
138046d70077SConrad Meyer 				cur_mtype = mtp;
138146d70077SConrad Meyer 			}
138246d70077SConrad Meyer 		}
138346d70077SConrad Meyer 		if (cur_mtype == NULL)
138446d70077SConrad Meyer 			break;
138546d70077SConrad Meyer 
138646d70077SConrad Meyer 		size = get_malloc_stats(cur_mtype->ks_handle, &allocs, &inuse);
138746d70077SConrad Meyer 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
138846d70077SConrad Meyer 		    howmany(size, 1024), allocs);
138946d70077SConrad Meyer 
1390687c94aaSJohn Baldwin 		if (db_pager_quit)
1391687c94aaSJohn Baldwin 			break;
139246d70077SConrad Meyer 
139346d70077SConrad Meyer 		last_mtype = cur_mtype;
139446d70077SConrad Meyer 		last_size = cur_size;
1395909ed16cSRobert Watson 	}
1396909ed16cSRobert Watson }
1397d7854da1SMatthew D Fleming 
1398d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1399d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1400d7854da1SMatthew D Fleming {
1401d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1402d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1403d7854da1SMatthew D Fleming 	u_int subzone;
1404d7854da1SMatthew D Fleming 
1405d7854da1SMatthew D Fleming 	if (!have_addr) {
1406d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1407d7854da1SMatthew D Fleming 		return;
1408d7854da1SMatthew D Fleming 	}
1409d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1410d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1411d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1412d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1413d7854da1SMatthew D Fleming 		return;
1414d7854da1SMatthew D Fleming 	}
1415d7854da1SMatthew D Fleming 
1416d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1417d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1418d7854da1SMatthew D Fleming 
1419d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1420d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1421d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1422d7854da1SMatthew D Fleming 			continue;
1423d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1424687c94aaSJohn Baldwin 		if (db_pager_quit)
1425687c94aaSJohn Baldwin 			break;
1426d7854da1SMatthew D Fleming 	}
1427d7854da1SMatthew D Fleming }
1428d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1429d7854da1SMatthew D Fleming #endif /* DDB */
1430909ed16cSRobert Watson 
14315e914b96SJeff Roberson #ifdef MALLOC_PROFILE
14325e914b96SJeff Roberson 
14335e914b96SJeff Roberson static int
14345e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
14355e914b96SJeff Roberson {
143663a7e0a3SRobert Watson 	struct sbuf sbuf;
14375e914b96SJeff Roberson 	uint64_t count;
14385e914b96SJeff Roberson 	uint64_t waste;
14395e914b96SJeff Roberson 	uint64_t mem;
14405e914b96SJeff Roberson 	int error;
14415e914b96SJeff Roberson 	int rsize;
14425e914b96SJeff Roberson 	int size;
14435e914b96SJeff Roberson 	int i;
14445e914b96SJeff Roberson 
14455e914b96SJeff Roberson 	waste = 0;
14465e914b96SJeff Roberson 	mem = 0;
14475e914b96SJeff Roberson 
144800f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
144900f0e671SMatthew D Fleming 	if (error != 0)
145000f0e671SMatthew D Fleming 		return (error);
14514e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
145263a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
14535e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
14545e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
14555e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
14565e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
14575e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
14585e914b96SJeff Roberson 
145963a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
146063a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
14615e914b96SJeff Roberson 
14625e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
14635e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
14645e914b96SJeff Roberson 		mem += (rsize * count);
14655e914b96SJeff Roberson 	}
146663a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
14675e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
14685e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
14694e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
147063a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
14715e914b96SJeff Roberson 	return (error);
14725e914b96SJeff Roberson }
14735e914b96SJeff Roberson 
14745e914b96SJeff Roberson SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
14755e914b96SJeff Roberson     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
14765e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1477