xref: /freebsd/sys/kern/kern_malloc.c (revision 828afdda17cae119594b21cac689bbe681b5aa58)
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  *
150*828afddaSMateusz Guzik  * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
151*828afddaSMateusz Guzik  *
1520ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1530ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1540ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1550ce3f16dSRobert Watson  */
1568355f576SJeff Roberson struct {
1576f267175SJeff Roberson 	int kz_size;
158eaa17d42SRyan Libby 	const char *kz_name;
159d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1606f267175SJeff Roberson } kmemzones[] = {
161d7854da1SMatthew D Fleming 	{16, "16", },
162d7854da1SMatthew D Fleming 	{32, "32", },
163d7854da1SMatthew D Fleming 	{64, "64", },
164d7854da1SMatthew D Fleming 	{128, "128", },
165d7854da1SMatthew D Fleming 	{256, "256", },
166d7854da1SMatthew D Fleming 	{512, "512", },
167d7854da1SMatthew D Fleming 	{1024, "1024", },
168d7854da1SMatthew D Fleming 	{2048, "2048", },
169d7854da1SMatthew D Fleming 	{4096, "4096", },
170d7854da1SMatthew D Fleming 	{8192, "8192", },
171d7854da1SMatthew D Fleming 	{16384, "16384", },
172d7854da1SMatthew D Fleming 	{32768, "32768", },
173d7854da1SMatthew D Fleming 	{65536, "65536", },
1748355f576SJeff Roberson 	{0, NULL},
1758355f576SJeff Roberson };
1768355f576SJeff Roberson 
1770ce3f16dSRobert Watson /*
1780ce3f16dSRobert Watson  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
1790ce3f16dSRobert Watson  * types are described by a data structure passed by the declaring code, but
1800ce3f16dSRobert Watson  * the malloc(9) implementation has its own data structure describing the
1810ce3f16dSRobert Watson  * type and statistics.  This permits the malloc(9)-internal data structures
1820ce3f16dSRobert Watson  * to be modified without breaking binary-compiled kernel modules that
1830ce3f16dSRobert Watson  * declare malloc types.
1840ce3f16dSRobert Watson  */
18563a7e0a3SRobert Watson static uma_zone_t mt_zone;
1869afff6b1SMateusz Guzik static uma_zone_t mt_stats_zone;
18763a7e0a3SRobert Watson 
188b89eaf4eSAlan Cox u_long vm_kmem_size;
189d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
19084344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1915a34a9f0SJeff Roberson 
1927001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1937001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1947001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1957001d850SXin LI 
196b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
197d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1980e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1990e5179e4SStephane E. Potvin 
200b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
201d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
202479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
203479439b4SDag-Erling Smørgrav 
2044813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
205d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
206479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
207479439b4SDag-Erling Smørgrav 
2087814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
2097814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
2107814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2115df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
2127814c80aSAndriy Gapon 
21395bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
21495bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
21595bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2165df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
21795bb9d38SAndriy Gapon 
218*828afddaSMateusz Guzik static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
219*828afddaSMateusz Guzik     "Malloc information");
220*828afddaSMateusz Guzik 
221*828afddaSMateusz Guzik static u_int vm_malloc_zone_count = nitems(kmemzones);
222*828afddaSMateusz Guzik SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
223*828afddaSMateusz Guzik     CTLFLAG_RD, &vm_malloc_zone_count, 0,
224*828afddaSMateusz Guzik     "Number of malloc zones");
225*828afddaSMateusz Guzik 
226*828afddaSMateusz Guzik static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
227*828afddaSMateusz Guzik SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
228*828afddaSMateusz Guzik     CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
229*828afddaSMateusz Guzik     sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
230*828afddaSMateusz Guzik 
2315a34a9f0SJeff Roberson /*
23299571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2335a34a9f0SJeff Roberson  */
2345a34a9f0SJeff Roberson struct mtx malloc_mtx;
23569ef67f9SJason Evans 
2365e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2375e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2386f267175SJeff Roberson 
2395e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2405e914b96SJeff Roberson #endif
2415e914b96SJeff Roberson 
242cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
243df8bae1dSRodney W. Grimes 
2440ce3f16dSRobert Watson /*
2450ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2460ce3f16dSRobert Watson  */
2471fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2481fb14a47SPoul-Henning Kamp 
249d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2507029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
251d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
252d7854da1SMatthew D Fleming #endif
253d7854da1SMatthew D Fleming 
254eae870cdSRobert Watson /*
2550ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2560ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
257eae870cdSRobert Watson  */
2580ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
259eae870cdSRobert Watson static int malloc_failure_rate;
260eae870cdSRobert Watson static int malloc_nowait_count;
261eae870cdSRobert Watson static int malloc_failure_count;
262af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
263eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
264eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
265eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
266eae870cdSRobert Watson #endif
267eae870cdSRobert Watson 
2687814c80aSAndriy Gapon static int
2697814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2707814c80aSAndriy Gapon {
2717814c80aSAndriy Gapon 	u_long size;
2727814c80aSAndriy Gapon 
2732e47807cSJeff Roberson 	size = uma_size();
2747814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2757814c80aSAndriy Gapon }
2767814c80aSAndriy Gapon 
27795bb9d38SAndriy Gapon static int
27895bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
27995bb9d38SAndriy Gapon {
2802e47807cSJeff Roberson 	u_long size, limit;
28195bb9d38SAndriy Gapon 
2822e47807cSJeff Roberson 	/* The sysctl is unsigned, implement as a saturation value. */
2832e47807cSJeff Roberson 	size = uma_size();
2842e47807cSJeff Roberson 	limit = uma_limit();
2852e47807cSJeff Roberson 	if (size > limit)
2862e47807cSJeff Roberson 		size = 0;
2872e47807cSJeff Roberson 	else
2882e47807cSJeff Roberson 		size = limit - size;
28995bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
29095bb9d38SAndriy Gapon }
29195bb9d38SAndriy Gapon 
292*828afddaSMateusz Guzik static int
293*828afddaSMateusz Guzik sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
294*828afddaSMateusz Guzik {
295*828afddaSMateusz Guzik 	int sizes[nitems(kmemzones)];
296*828afddaSMateusz Guzik 	int i;
297*828afddaSMateusz Guzik 
298*828afddaSMateusz Guzik 	for (i = 0; i < nitems(kmemzones); i++) {
299*828afddaSMateusz Guzik 		sizes[i] = kmemzones[i].kz_size;
300*828afddaSMateusz Guzik 	}
301*828afddaSMateusz Guzik 
302*828afddaSMateusz Guzik 	return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
303*828afddaSMateusz Guzik }
304*828afddaSMateusz Guzik 
305d7854da1SMatthew D Fleming /*
306d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
307d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
308d7854da1SMatthew D Fleming  */
309d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
310d7854da1SMatthew D Fleming static void
311d7854da1SMatthew D Fleming tunable_set_numzones(void)
312d7854da1SMatthew D Fleming {
313d7854da1SMatthew D Fleming 
314d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
315d7854da1SMatthew D Fleming 	    &numzones);
316d7854da1SMatthew D Fleming 
317d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
318d7854da1SMatthew D Fleming 	if (numzones <= 0)
319d7854da1SMatthew D Fleming 		numzones = 1;
320d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
321d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
322d7854da1SMatthew D Fleming }
323d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
324af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
325d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
326d7854da1SMatthew D Fleming 
327d7854da1SMatthew D Fleming /*
328d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
329d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
330d7854da1SMatthew D Fleming  */
331d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
332d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
333d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
334d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
335d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
336d7854da1SMatthew D Fleming 
337c9e05ccdSMateusz Guzik static void
338c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
339d7854da1SMatthew D Fleming {
340c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
341c9e05ccdSMateusz Guzik 	const char *desc;
342d7854da1SMatthew D Fleming 	size_t len;
343d7854da1SMatthew D Fleming 	u_int val;
344d7854da1SMatthew D Fleming 
345c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
346c9e05ccdSMateusz Guzik 	desc = mtp->ks_shortdesc;
347d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
348c9e05ccdSMateusz Guzik 		val = 0;
349c9e05ccdSMateusz Guzik 	else
350d7854da1SMatthew D Fleming 		val = desc[zone_offset % len];
351c9e05ccdSMateusz Guzik 	mtip->mti_zone = (val % numzones);
352c9e05ccdSMateusz Guzik }
353c9e05ccdSMateusz Guzik 
354c9e05ccdSMateusz Guzik static inline u_int
355c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
356c9e05ccdSMateusz Guzik {
357c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
358c9e05ccdSMateusz Guzik 
359c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
360c9e05ccdSMateusz Guzik 
361c9e05ccdSMateusz Guzik 	KASSERT(mtip->mti_zone < numzones,
362c9e05ccdSMateusz Guzik 	    ("mti_zone %u out of range %d",
363c9e05ccdSMateusz Guzik 	    mtip->mti_zone, numzones));
364c9e05ccdSMateusz Guzik 	return (mtip->mti_zone);
365d7854da1SMatthew D Fleming }
366d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
367d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
368d7854da1SMatthew D Fleming #else
369c9e05ccdSMateusz Guzik static void
370c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
371c9e05ccdSMateusz Guzik {
372c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
373c9e05ccdSMateusz Guzik 
374c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
375c9e05ccdSMateusz Guzik 	mtip->mti_zone = 0;
376c9e05ccdSMateusz Guzik }
377c9e05ccdSMateusz Guzik 
378d7854da1SMatthew D Fleming static inline u_int
379c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
380d7854da1SMatthew D Fleming {
381d7854da1SMatthew D Fleming 
382d7854da1SMatthew D Fleming 	return (0);
383d7854da1SMatthew D Fleming }
384d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
385d7854da1SMatthew D Fleming 
3861fb14a47SPoul-Henning Kamp int
3871fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3881fb14a47SPoul-Henning Kamp {
3891fb14a47SPoul-Henning Kamp 
3901fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3911fb14a47SPoul-Henning Kamp }
3921fb14a47SPoul-Henning Kamp 
393df8bae1dSRodney W. Grimes /*
3940ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3950ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3960ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3970ce3f16dSRobert Watson  * statistics.
3984362fadaSBrian Feldman  */
3994362fadaSBrian Feldman static void
40063a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
4014362fadaSBrian Feldman     int zindx)
4024362fadaSBrian Feldman {
40363a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
40463a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
40563a7e0a3SRobert Watson 
40663a7e0a3SRobert Watson 	critical_enter();
40763a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
4089afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
40973864adbSPawel Jakub Dawidek 	if (size > 0) {
41063a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
41163a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
41273864adbSPawel Jakub Dawidek 	}
4134362fadaSBrian Feldman 	if (zindx != -1)
41463a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
41591dd776cSJohn Birrell 
41691dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4177cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
41891dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
41991dd776cSJohn Birrell 		if (probe_id != 0)
42091dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
42191dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
42291dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
42391dd776cSJohn Birrell 	}
42491dd776cSJohn Birrell #endif
42591dd776cSJohn Birrell 
42663a7e0a3SRobert Watson 	critical_exit();
4274362fadaSBrian Feldman }
4284362fadaSBrian Feldman 
4294362fadaSBrian Feldman void
43063a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
4314362fadaSBrian Feldman {
43263a7e0a3SRobert Watson 
43373864adbSPawel Jakub Dawidek 	if (size > 0)
43463a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
4354362fadaSBrian Feldman }
4364362fadaSBrian Feldman 
4374362fadaSBrian Feldman /*
4383805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
4390ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
4400ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
4410ce3f16dSRobert Watson  * statistics.
4424362fadaSBrian Feldman  */
4434362fadaSBrian Feldman void
44463a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
4454362fadaSBrian Feldman {
44663a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
44763a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
44863a7e0a3SRobert Watson 
44963a7e0a3SRobert Watson 	critical_enter();
45063a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
4519afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
45263a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
45363a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
45491dd776cSJohn Birrell 
45591dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4567cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
45791dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
45891dd776cSJohn Birrell 		if (probe_id != 0)
45991dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
46091dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
46191dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
46291dd776cSJohn Birrell 	}
46391dd776cSJohn Birrell #endif
46491dd776cSJohn Birrell 
46563a7e0a3SRobert Watson 	critical_exit();
4664362fadaSBrian Feldman }
4674362fadaSBrian Feldman 
4684362fadaSBrian Feldman /*
469f346986bSAlan Cox  *	contigmalloc:
470f346986bSAlan Cox  *
471f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
472f346986bSAlan Cox  *
473f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
474f346986bSAlan Cox  *	the allocation fails.
475f346986bSAlan Cox  */
476f346986bSAlan Cox void *
477f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
478f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
479831ce4cbSJohn Baldwin     vm_paddr_t boundary)
480f346986bSAlan Cox {
481f346986bSAlan Cox 	void *ret;
482f346986bSAlan Cox 
48344d0efb2SAlan Cox 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
48444d0efb2SAlan Cox 	    boundary, VM_MEMATTR_DEFAULT);
485f346986bSAlan Cox 	if (ret != NULL)
486f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
487f346986bSAlan Cox 	return (ret);
488f346986bSAlan Cox }
489f346986bSAlan Cox 
490ab3185d1SJeff Roberson void *
4919978bd99SMark Johnston contigmalloc_domainset(unsigned long size, struct malloc_type *type,
4929978bd99SMark Johnston     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
493ab3185d1SJeff Roberson     unsigned long alignment, vm_paddr_t boundary)
494ab3185d1SJeff Roberson {
495ab3185d1SJeff Roberson 	void *ret;
496ab3185d1SJeff Roberson 
4979978bd99SMark Johnston 	ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
498ab3185d1SJeff Roberson 	    alignment, boundary, VM_MEMATTR_DEFAULT);
499ab3185d1SJeff Roberson 	if (ret != NULL)
500ab3185d1SJeff Roberson 		malloc_type_allocated(type, round_page(size));
501ab3185d1SJeff Roberson 	return (ret);
502ab3185d1SJeff Roberson }
503ab3185d1SJeff Roberson 
504f346986bSAlan Cox /*
505f346986bSAlan Cox  *	contigfree:
506f346986bSAlan Cox  *
507f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
508f346986bSAlan Cox  *
509f346986bSAlan Cox  *	This routine may not block.
510f346986bSAlan Cox  */
511f346986bSAlan Cox void
512f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
513f346986bSAlan Cox {
514f346986bSAlan Cox 
51549bfa624SAlan Cox 	kmem_free((vm_offset_t)addr, size);
516f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
517f346986bSAlan Cox }
518f346986bSAlan Cox 
519ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
520ab3185d1SJeff Roberson static int
5215a70796aSLi-Wen Hsu malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
522ab3185d1SJeff Roberson     int flags)
523df8bae1dSRodney W. Grimes {
524194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
525ab3185d1SJeff Roberson 	int indx;
526ab3185d1SJeff Roberson 
527bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
528d3c11994SPoul-Henning Kamp 	/*
52923198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
530d3c11994SPoul-Henning Kamp 	 */
53123198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
532d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
533d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
534d3c11994SPoul-Henning Kamp 		static	int curerr, once;
535d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
536d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
5372d50560aSMarcel Moolenaar 			kdb_backtrace();
538d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
539d3c11994SPoul-Henning Kamp 			once++;
540d3c11994SPoul-Henning Kamp 		}
541d3c11994SPoul-Henning Kamp 	}
542194a0abfSPoul-Henning Kamp #endif
543eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
544eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
545eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
546eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
547eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
5483f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
549ab3185d1SJeff Roberson 			*vap = NULL;
550ab3185d1SJeff Roberson 			return (EJUSTRETURN);
551eae870cdSRobert Watson 		}
552eae870cdSRobert Watson 	}
553eae870cdSRobert Watson #endif
55406bf2a6aSMatt Macy 	if (flags & M_WAITOK) {
555b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
556a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
5575757b59fSGleb Smirnoff 		if (__predict_false(!THREAD_CAN_SLEEP())) {
558bac06038SGleb Smirnoff #ifdef EPOCH_TRACE
559bac06038SGleb Smirnoff 			epoch_trace_list(curthread);
560bac06038SGleb Smirnoff #endif
5615757b59fSGleb Smirnoff 			KASSERT(1,
5625757b59fSGleb Smirnoff 			    ("malloc(M_WAITOK) with sleeping prohibited"));
5635757b59fSGleb Smirnoff 		}
56406bf2a6aSMatt Macy 	}
565d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
5661067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
5671067a2baSJonathan T. Looney 
568e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
569ab3185d1SJeff Roberson 	if (memguard_cmp_mtp(mtp, *sizep)) {
570ab3185d1SJeff Roberson 		*vap = memguard_alloc(*sizep, flags);
571ab3185d1SJeff Roberson 		if (*vap != NULL)
572ab3185d1SJeff Roberson 			return (EJUSTRETURN);
573e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
574e3813573SMatthew D Fleming 	}
575e4eb384bSBosko Milekic #endif
576e4eb384bSBosko Milekic 
577847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
578ab3185d1SJeff Roberson 	*sizep = redzone_size_ntor(*sizep);
579ab3185d1SJeff Roberson #endif
580ab3185d1SJeff Roberson 
581ab3185d1SJeff Roberson 	return (0);
582ab3185d1SJeff Roberson }
583ab3185d1SJeff Roberson #endif
584ab3185d1SJeff Roberson 
585ab3185d1SJeff Roberson /*
5866d6a03d7SJeff Roberson  * Handle large allocations and frees by using kmem_malloc directly.
5876d6a03d7SJeff Roberson  */
5886d6a03d7SJeff Roberson static inline bool
5896d6a03d7SJeff Roberson malloc_large_slab(uma_slab_t slab)
5906d6a03d7SJeff Roberson {
5916d6a03d7SJeff Roberson 	uintptr_t va;
5926d6a03d7SJeff Roberson 
5936d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
5946d6a03d7SJeff Roberson 	return ((va & 1) != 0);
5956d6a03d7SJeff Roberson }
5966d6a03d7SJeff Roberson 
5976d6a03d7SJeff Roberson static inline size_t
5986d6a03d7SJeff Roberson malloc_large_size(uma_slab_t slab)
5996d6a03d7SJeff Roberson {
6006d6a03d7SJeff Roberson 	uintptr_t va;
6016d6a03d7SJeff Roberson 
6026d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
6036d6a03d7SJeff Roberson 	return (va >> 1);
6046d6a03d7SJeff Roberson }
6056d6a03d7SJeff Roberson 
6066d6a03d7SJeff Roberson static caddr_t
6076d6a03d7SJeff Roberson malloc_large(size_t *size, struct domainset *policy, int flags)
6086d6a03d7SJeff Roberson {
6096d6a03d7SJeff Roberson 	vm_offset_t va;
6106d6a03d7SJeff Roberson 	size_t sz;
6116d6a03d7SJeff Roberson 
6126d6a03d7SJeff Roberson 	sz = roundup(*size, PAGE_SIZE);
6136d6a03d7SJeff Roberson 	va = kmem_malloc_domainset(policy, sz, flags);
6146d6a03d7SJeff Roberson 	if (va != 0) {
6156d6a03d7SJeff Roberson 		/* The low bit is unused for slab pointers. */
6166d6a03d7SJeff Roberson 		vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
6176d6a03d7SJeff Roberson 		uma_total_inc(sz);
6186d6a03d7SJeff Roberson 		*size = sz;
6196d6a03d7SJeff Roberson 	}
6206d6a03d7SJeff Roberson 	return ((caddr_t)va);
6216d6a03d7SJeff Roberson }
6226d6a03d7SJeff Roberson 
6236d6a03d7SJeff Roberson static void
6246d6a03d7SJeff Roberson free_large(void *addr, size_t size)
6256d6a03d7SJeff Roberson {
6266d6a03d7SJeff Roberson 
6276d6a03d7SJeff Roberson 	kmem_free((vm_offset_t)addr, size);
6286d6a03d7SJeff Roberson 	uma_total_dec(size);
6296d6a03d7SJeff Roberson }
6306d6a03d7SJeff Roberson 
6316d6a03d7SJeff Roberson /*
632ab3185d1SJeff Roberson  *	malloc:
633ab3185d1SJeff Roberson  *
634ab3185d1SJeff Roberson  *	Allocate a block of memory.
635ab3185d1SJeff Roberson  *
636ab3185d1SJeff Roberson  *	If M_NOWAIT is set, this routine will not block and return NULL if
637ab3185d1SJeff Roberson  *	the allocation fails.
638ab3185d1SJeff Roberson  */
639ab3185d1SJeff Roberson void *
64034c538c3SMateusz Guzik (malloc)(size_t size, struct malloc_type *mtp, int flags)
641ab3185d1SJeff Roberson {
642ab3185d1SJeff Roberson 	int indx;
643ab3185d1SJeff Roberson 	caddr_t va;
644ab3185d1SJeff Roberson 	uma_zone_t zone;
645ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
646ab3185d1SJeff Roberson 	unsigned long osize = size;
647ab3185d1SJeff Roberson #endif
648ab3185d1SJeff Roberson 
64982c174a3SMateusz Guzik 	MPASS((flags & M_EXEC) == 0);
650ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
6515072a5f4SMatt Macy 	va = NULL;
652ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
653ab3185d1SJeff Roberson 		return (va);
654847a2a17SPawel Jakub Dawidek #endif
655847a2a17SPawel Jakub Dawidek 
65682c174a3SMateusz Guzik 	if (size <= kmem_zmax) {
6576f267175SJeff Roberson 		if (size & KMEM_ZMASK)
6586f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
6596f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
660c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
6616f267175SJeff Roberson #ifdef MALLOC_PROFILE
6626f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
6636f267175SJeff Roberson #endif
6648355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
6654362fadaSBrian Feldman 		if (va != NULL)
666e20a199fSJeff Roberson 			size = zone->uz_size;
66763a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
6688355f576SJeff Roberson 	} else {
6696d6a03d7SJeff Roberson 		va = malloc_large(&size, DOMAINSET_RR(), flags);
67063a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
671df8bae1dSRodney W. Grimes 	}
67282c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
67382c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
67482c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
6751fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
67682c174a3SMateusz Guzik 	}
677ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
678ab3185d1SJeff Roberson 	if (va != NULL)
679ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
6804db4f5c8SPoul-Henning Kamp #endif
681ab3185d1SJeff Roberson 	return ((void *) va);
682ab3185d1SJeff Roberson }
683ab3185d1SJeff Roberson 
6849978bd99SMark Johnston static void *
685dc727127SMark Johnston malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
6866d6a03d7SJeff Roberson     int flags)
687ab3185d1SJeff Roberson {
688ab3185d1SJeff Roberson 	uma_zone_t zone;
689dc727127SMark Johnston 	caddr_t va;
690dc727127SMark Johnston 	size_t size;
691dc727127SMark Johnston 	int indx;
692ab3185d1SJeff Roberson 
693dc727127SMark Johnston 	size = *sizep;
6946d6a03d7SJeff Roberson 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
6956d6a03d7SJeff Roberson 	    ("malloc_domain: Called with bad flag / size combination."));
696ab3185d1SJeff Roberson 	if (size & KMEM_ZMASK)
697ab3185d1SJeff Roberson 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
698ab3185d1SJeff Roberson 	indx = kmemsize[size >> KMEM_ZSHIFT];
699c9e05ccdSMateusz Guzik 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
700ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
701ab3185d1SJeff Roberson 	krequests[size >> KMEM_ZSHIFT]++;
702ab3185d1SJeff Roberson #endif
703ab3185d1SJeff Roberson 	va = uma_zalloc_domain(zone, NULL, domain, flags);
704ab3185d1SJeff Roberson 	if (va != NULL)
705dc727127SMark Johnston 		*sizep = zone->uz_size;
7066d6a03d7SJeff Roberson 	*indxp = indx;
707df8bae1dSRodney W. Grimes 	return ((void *)va);
708df8bae1dSRodney W. Grimes }
709df8bae1dSRodney W. Grimes 
710fd91e076SKristof Provost void *
7119978bd99SMark Johnston malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
7129978bd99SMark Johnston     int flags)
7139978bd99SMark Johnston {
7149978bd99SMark Johnston 	struct vm_domainset_iter di;
71582c174a3SMateusz Guzik 	caddr_t va;
7169978bd99SMark Johnston 	int domain;
7176d6a03d7SJeff Roberson 	int indx;
7189978bd99SMark Johnston 
7196d6a03d7SJeff Roberson #if defined(DEBUG_REDZONE)
7206d6a03d7SJeff Roberson 	unsigned long osize = size;
7216d6a03d7SJeff Roberson #endif
72282c174a3SMateusz Guzik 	MPASS((flags & M_EXEC) == 0);
7236d6a03d7SJeff Roberson #ifdef MALLOC_DEBUG
72482c174a3SMateusz Guzik 	va = NULL;
72582c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
72682c174a3SMateusz Guzik 		return (va);
7276d6a03d7SJeff Roberson #endif
72882c174a3SMateusz Guzik 	if (size <= kmem_zmax) {
7299978bd99SMark Johnston 		vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
7309978bd99SMark Johnston 		do {
73182c174a3SMateusz Guzik 			va = malloc_domain(&size, &indx, mtp, domain, flags);
73282c174a3SMateusz Guzik 		} while (va == NULL &&
7336d6a03d7SJeff Roberson 		    vm_domainset_iter_policy(&di, &domain) == 0);
73482c174a3SMateusz Guzik 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
7356d6a03d7SJeff Roberson 	} else {
7366d6a03d7SJeff Roberson 		/* Policy is handled by kmem. */
73782c174a3SMateusz Guzik 		va = malloc_large(&size, ds, flags);
73882c174a3SMateusz Guzik 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
73982c174a3SMateusz Guzik 	}
74082c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
74182c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
74282c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
74382c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
74482c174a3SMateusz Guzik 	}
74582c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
74682c174a3SMateusz Guzik 	if (va != NULL)
74782c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
74882c174a3SMateusz Guzik #endif
74982c174a3SMateusz Guzik 	return (va);
7506d6a03d7SJeff Roberson }
7519978bd99SMark Johnston 
75282c174a3SMateusz Guzik /*
75382c174a3SMateusz Guzik  * Allocate an executable area.
75482c174a3SMateusz Guzik  */
75582c174a3SMateusz Guzik void *
75682c174a3SMateusz Guzik malloc_exec(size_t size, struct malloc_type *mtp, int flags)
75782c174a3SMateusz Guzik {
75882c174a3SMateusz Guzik 	caddr_t va;
75982c174a3SMateusz Guzik #if defined(DEBUG_REDZONE)
76082c174a3SMateusz Guzik 	unsigned long osize = size;
7616d6a03d7SJeff Roberson #endif
76282c174a3SMateusz Guzik 
76382c174a3SMateusz Guzik 	flags |= M_EXEC;
76482c174a3SMateusz Guzik #ifdef MALLOC_DEBUG
76582c174a3SMateusz Guzik 	va = NULL;
76682c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
76782c174a3SMateusz Guzik 		return (va);
76882c174a3SMateusz Guzik #endif
76982c174a3SMateusz Guzik 	va = malloc_large(&size, DOMAINSET_RR(), flags);
77082c174a3SMateusz Guzik 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
77182c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
77282c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
77382c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
77482c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
77582c174a3SMateusz Guzik 	}
77682c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
77782c174a3SMateusz Guzik 	if (va != NULL)
77882c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
77982c174a3SMateusz Guzik #endif
78082c174a3SMateusz Guzik 	return ((void *) va);
78182c174a3SMateusz Guzik }
78282c174a3SMateusz Guzik 
78382c174a3SMateusz Guzik void *
78482c174a3SMateusz Guzik malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
78582c174a3SMateusz Guzik     int flags)
78682c174a3SMateusz Guzik {
78782c174a3SMateusz Guzik 	caddr_t va;
78882c174a3SMateusz Guzik #if defined(DEBUG_REDZONE)
78982c174a3SMateusz Guzik 	unsigned long osize = size;
79082c174a3SMateusz Guzik #endif
79182c174a3SMateusz Guzik 
79282c174a3SMateusz Guzik 	flags |= M_EXEC;
79382c174a3SMateusz Guzik #ifdef MALLOC_DEBUG
79482c174a3SMateusz Guzik 	va = NULL;
79582c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
79682c174a3SMateusz Guzik 		return (va);
79782c174a3SMateusz Guzik #endif
79882c174a3SMateusz Guzik 	/* Policy is handled by kmem. */
79982c174a3SMateusz Guzik 	va = malloc_large(&size, ds, flags);
80082c174a3SMateusz Guzik 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
80182c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
80282c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
80382c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
80482c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
80582c174a3SMateusz Guzik 	}
80682c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
80782c174a3SMateusz Guzik 	if (va != NULL)
80882c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
80982c174a3SMateusz Guzik #endif
81082c174a3SMateusz Guzik 	return (va);
8119978bd99SMark Johnston }
8129978bd99SMark Johnston 
8139978bd99SMark Johnston void *
814fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
815fd91e076SKristof Provost {
816fd91e076SKristof Provost 
817c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
818c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
819fd91e076SKristof Provost 
820fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
821fd91e076SKristof Provost }
822fd91e076SKristof Provost 
823ab3185d1SJeff Roberson #ifdef INVARIANTS
824ab3185d1SJeff Roberson static void
825ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
826ab3185d1SJeff Roberson {
827ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
828ab3185d1SJeff Roberson 
829ab3185d1SJeff Roberson 	/*
830ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
831ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
832ab3185d1SJeff Roberson 	 * have stepped on it later.
833ab3185d1SJeff Roberson 	 *
834ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
835ab3185d1SJeff Roberson 	 * 64 bit machines
836ab3185d1SJeff Roberson 	 */
837ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
838ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
839ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
840ab3185d1SJeff Roberson 	*mtpp = mtp;
841ab3185d1SJeff Roberson }
842ab3185d1SJeff Roberson #endif
843ab3185d1SJeff Roberson 
844ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
845ab3185d1SJeff Roberson static int
846ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
847ab3185d1SJeff Roberson {
848ab3185d1SJeff Roberson 	void *addr;
849ab3185d1SJeff Roberson 
850ab3185d1SJeff Roberson 	addr = *addrp;
851ab3185d1SJeff Roberson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
852ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
853ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
854ab3185d1SJeff Roberson 
855ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
856ab3185d1SJeff Roberson 	if (addr == NULL)
857ab3185d1SJeff Roberson 		return (EJUSTRETURN);
858ab3185d1SJeff Roberson 
859ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
860ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
861ab3185d1SJeff Roberson 		memguard_free(addr);
862ab3185d1SJeff Roberson 		return (EJUSTRETURN);
863ab3185d1SJeff Roberson 	}
864ab3185d1SJeff Roberson #endif
865ab3185d1SJeff Roberson 
866ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
867ab3185d1SJeff Roberson 	redzone_check(addr);
868ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
869ab3185d1SJeff Roberson #endif
870ab3185d1SJeff Roberson 
871ab3185d1SJeff Roberson 	return (0);
872ab3185d1SJeff Roberson }
873ab3185d1SJeff Roberson #endif
874ab3185d1SJeff Roberson 
875fd91e076SKristof Provost /*
8761c7c3c6aSMatthew Dillon  *	free:
8771c7c3c6aSMatthew Dillon  *
878df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
8791c7c3c6aSMatthew Dillon  *
8801c7c3c6aSMatthew Dillon  *	This routine may not block.
881df8bae1dSRodney W. Grimes  */
882df8bae1dSRodney W. Grimes void
88363a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
884df8bae1dSRodney W. Grimes {
885584061b4SJeff Roberson 	uma_zone_t zone;
88699571dc3SJeff Roberson 	uma_slab_t slab;
88799571dc3SJeff Roberson 	u_long size;
888254c6cb3SPoul-Henning Kamp 
889ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
890ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
891ab3185d1SJeff Roberson 		return;
892ab3185d1SJeff Roberson #endif
89344a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
89444a8ff31SArchie Cobbs 	if (addr == NULL)
89544a8ff31SArchie Cobbs 		return;
89644a8ff31SArchie Cobbs 
897584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
8988355f576SJeff Roberson 	if (slab == NULL)
8996f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
90099571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
90199571dc3SJeff Roberson 
9026d6a03d7SJeff Roberson 	if (__predict_true(!malloc_large_slab(slab))) {
903584061b4SJeff Roberson 		size = zone->uz_size;
9048f70816cSJeff Roberson #ifdef INVARIANTS
905ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
9068f70816cSJeff Roberson #endif
907584061b4SJeff Roberson 		uma_zfree_arg(zone, addr, slab);
90814bf02f8SJohn Dyson 	} else {
9096d6a03d7SJeff Roberson 		size = malloc_large_size(slab);
9106d6a03d7SJeff Roberson 		free_large(addr, size);
91114bf02f8SJohn Dyson 	}
91263a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
913df8bae1dSRodney W. Grimes }
914df8bae1dSRodney W. Grimes 
91545035becSMatt Macy /*
91645035becSMatt Macy  *	zfree:
91745035becSMatt Macy  *
91845035becSMatt Macy  *	Zero then free a block of memory allocated by malloc.
91945035becSMatt Macy  *
92045035becSMatt Macy  *	This routine may not block.
92145035becSMatt Macy  */
92245035becSMatt Macy void
92345035becSMatt Macy zfree(void *addr, struct malloc_type *mtp)
92445035becSMatt Macy {
92545035becSMatt Macy 	uma_zone_t zone;
92645035becSMatt Macy 	uma_slab_t slab;
92745035becSMatt Macy 	u_long size;
92845035becSMatt Macy 
92945035becSMatt Macy #ifdef MALLOC_DEBUG
93045035becSMatt Macy 	if (free_dbg(&addr, mtp) != 0)
93145035becSMatt Macy 		return;
93245035becSMatt Macy #endif
93345035becSMatt Macy 	/* free(NULL, ...) does nothing */
93445035becSMatt Macy 	if (addr == NULL)
93545035becSMatt Macy 		return;
93645035becSMatt Macy 
93745035becSMatt Macy 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
93845035becSMatt Macy 	if (slab == NULL)
93945035becSMatt Macy 		panic("free: address %p(%p) has not been allocated.\n",
94045035becSMatt Macy 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
94145035becSMatt Macy 
94245035becSMatt Macy 	if (__predict_true(!malloc_large_slab(slab))) {
94345035becSMatt Macy 		size = zone->uz_size;
94445035becSMatt Macy #ifdef INVARIANTS
94545035becSMatt Macy 		free_save_type(addr, mtp, size);
94645035becSMatt Macy #endif
94745035becSMatt Macy 		explicit_bzero(addr, size);
94845035becSMatt Macy 		uma_zfree_arg(zone, addr, slab);
94945035becSMatt Macy 	} else {
95045035becSMatt Macy 		size = malloc_large_size(slab);
95145035becSMatt Macy 		explicit_bzero(addr, size);
95245035becSMatt Macy 		free_large(addr, size);
95345035becSMatt Macy 	}
95445035becSMatt Macy 	malloc_type_freed(mtp, size);
95545035becSMatt Macy }
95645035becSMatt Macy 
957df8bae1dSRodney W. Grimes /*
95844a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
95944a8ff31SArchie Cobbs  */
96044a8ff31SArchie Cobbs void *
961bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
96244a8ff31SArchie Cobbs {
963584061b4SJeff Roberson 	uma_zone_t zone;
9648355f576SJeff Roberson 	uma_slab_t slab;
96544a8ff31SArchie Cobbs 	unsigned long alloc;
96644a8ff31SArchie Cobbs 	void *newaddr;
96744a8ff31SArchie Cobbs 
968bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
969bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
970d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
9711067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
9721067a2baSJonathan T. Looney 
97344a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
97444a8ff31SArchie Cobbs 	if (addr == NULL)
97563a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
97663a7e0a3SRobert Watson 
97763a7e0a3SRobert Watson 	/*
97863a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
97963a7e0a3SRobert Watson 	 * per-CPU stats.
98063a7e0a3SRobert Watson 	 */
98144a8ff31SArchie Cobbs 
982e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
9836d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
9846d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
985e4eb384bSBosko Milekic #endif
986e4eb384bSBosko Milekic 
987847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
988847a2a17SPawel Jakub Dawidek 	slab = NULL;
989b476ae7fSJeff Roberson 	zone = NULL;
990847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
991847a2a17SPawel Jakub Dawidek #else
992584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
9938355f576SJeff Roberson 
99444a8ff31SArchie Cobbs 	/* Sanity check */
9958355f576SJeff Roberson 	KASSERT(slab != NULL,
99644a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
99744a8ff31SArchie Cobbs 
99844a8ff31SArchie Cobbs 	/* Get the size of the original block */
9996d6a03d7SJeff Roberson 	if (!malloc_large_slab(slab))
1000584061b4SJeff Roberson 		alloc = zone->uz_size;
10018355f576SJeff Roberson 	else
10026d6a03d7SJeff Roberson 		alloc = malloc_large_size(slab);
100344a8ff31SArchie Cobbs 
100444a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
100544a8ff31SArchie Cobbs 	if (size <= alloc
100644a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
100744a8ff31SArchie Cobbs 		return (addr);
1008847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
100944a8ff31SArchie Cobbs 
101044a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
101163a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
101244a8ff31SArchie Cobbs 		return (NULL);
101344a8ff31SArchie Cobbs 
101444a8ff31SArchie Cobbs 	/* Copy over original contents */
101544a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
101663a7e0a3SRobert Watson 	free(addr, mtp);
101744a8ff31SArchie Cobbs 	return (newaddr);
101844a8ff31SArchie Cobbs }
101944a8ff31SArchie Cobbs 
102044a8ff31SArchie Cobbs /*
102144a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
102244a8ff31SArchie Cobbs  */
102344a8ff31SArchie Cobbs void *
1024bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
102544a8ff31SArchie Cobbs {
102644a8ff31SArchie Cobbs 	void *mem;
102744a8ff31SArchie Cobbs 
102863a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
102963a7e0a3SRobert Watson 		free(addr, mtp);
103044a8ff31SArchie Cobbs 	return (mem);
103144a8ff31SArchie Cobbs }
103244a8ff31SArchie Cobbs 
10335d4bf057SVladimir Kondratyev /*
10345d4bf057SVladimir Kondratyev  *	malloc_usable_size: returns the usable size of the allocation.
10355d4bf057SVladimir Kondratyev  */
10365d4bf057SVladimir Kondratyev size_t
10375d4bf057SVladimir Kondratyev malloc_usable_size(const void *addr)
10385d4bf057SVladimir Kondratyev {
10395d4bf057SVladimir Kondratyev #ifndef DEBUG_REDZONE
10405d4bf057SVladimir Kondratyev 	uma_zone_t zone;
10415d4bf057SVladimir Kondratyev 	uma_slab_t slab;
10425d4bf057SVladimir Kondratyev #endif
10435d4bf057SVladimir Kondratyev 	u_long size;
10445d4bf057SVladimir Kondratyev 
10455d4bf057SVladimir Kondratyev 	if (addr == NULL)
10465d4bf057SVladimir Kondratyev 		return (0);
10475d4bf057SVladimir Kondratyev 
10485d4bf057SVladimir Kondratyev #ifdef DEBUG_MEMGUARD
10495d4bf057SVladimir Kondratyev 	if (is_memguard_addr(__DECONST(void *, addr)))
10505d4bf057SVladimir Kondratyev 		return (memguard_get_req_size(addr));
10515d4bf057SVladimir Kondratyev #endif
10525d4bf057SVladimir Kondratyev 
10535d4bf057SVladimir Kondratyev #ifdef DEBUG_REDZONE
10545d4bf057SVladimir Kondratyev 	size = redzone_get_size(__DECONST(void *, addr));
10555d4bf057SVladimir Kondratyev #else
10565d4bf057SVladimir Kondratyev 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
10575d4bf057SVladimir Kondratyev 	if (slab == NULL)
10585d4bf057SVladimir Kondratyev 		panic("malloc_usable_size: address %p(%p) is not allocated.\n",
10595d4bf057SVladimir Kondratyev 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
10605d4bf057SVladimir Kondratyev 
10615d4bf057SVladimir Kondratyev 	if (!malloc_large_slab(slab))
10625d4bf057SVladimir Kondratyev 		size = zone->uz_size;
10635d4bf057SVladimir Kondratyev 	else
10645d4bf057SVladimir Kondratyev 		size = malloc_large_size(slab);
10655d4bf057SVladimir Kondratyev #endif
10665d4bf057SVladimir Kondratyev 	return (size);
10675d4bf057SVladimir Kondratyev }
10685d4bf057SVladimir Kondratyev 
1069c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1070c70af487SAlan Cox 
10715df87b21SJeff Roberson /*
1072c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
10735df87b21SJeff Roberson  */
10745df87b21SJeff Roberson void
10755df87b21SJeff Roberson kmeminit(void)
10765df87b21SJeff Roberson {
1077af3b2549SHans Petter Selasky 	u_long mem_size;
1078af3b2549SHans Petter Selasky 	u_long tmp;
107969ef67f9SJason Evans 
1080af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
1081af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
1082af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
1083af3b2549SHans Petter Selasky #endif
1084af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
1085af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
1086af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1087af3b2549SHans Petter Selasky #endif
1088af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
1089af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
1090af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1091af3b2549SHans Petter Selasky #endif
10928a58a9f6SJohn Dyson 	/*
1093c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
1094c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
1095c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
1096c70af487SAlan Cox 	 * specifically,
10978a58a9f6SJohn Dyson 	 *
1098c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1099c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1100c70af487SAlan Cox 	 *
1101c70af487SAlan Cox 	 * Every architecture must define an integral value for
1102c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1103c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1104c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
1105c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1106c70af487SAlan Cox 	 * a given architecture.
11078a58a9f6SJohn Dyson 	 */
110844f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
11097c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
11107c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
11118a58a9f6SJohn Dyson 
1112c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
1113c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1114c70af487SAlan Cox 
1115af3b2549SHans Petter Selasky 	/*
1116af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
1117af3b2549SHans Petter Selasky 	 * variable:
1118af3b2549SHans Petter Selasky 	 */
1119af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
112028b740daSKonstantin Belousov 		vm_kmem_size = mem_size / vm_kmem_size_scale;
112128b740daSKonstantin Belousov 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
112228b740daSKonstantin Belousov 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1123c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
11240e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
1125479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1126479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
1127af3b2549SHans Petter Selasky 	}
112828b740daSKonstantin Belousov 	if (vm_kmem_size == 0)
112928b740daSKonstantin Belousov 		panic("Tune VM_KMEM_SIZE_* for the platform");
11308a58a9f6SJohn Dyson 
113127b8623fSDavid Greenman 	/*
1132af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
1133c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
1134c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
1135c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
1136c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
113727b8623fSDavid Greenman 	 */
1138c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1139c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
11408a58a9f6SJohn Dyson 
1141e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
1142e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
1143f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1144e3813573SMatthew D Fleming #else
1145e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
1146e3813573SMatthew D Fleming #endif
11472e47807cSJeff Roberson 	uma_set_limit(tmp);
11488355f576SJeff Roberson 
1149e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
1150e4eb384bSBosko Milekic 	/*
1151e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1152e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
1153e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
1154e4eb384bSBosko Milekic 	 */
11552e47807cSJeff Roberson 	memguard_init(kernel_arena);
1156e4eb384bSBosko Milekic #endif
11575df87b21SJeff Roberson }
11585df87b21SJeff Roberson 
11595df87b21SJeff Roberson /*
11605df87b21SJeff Roberson  * Initialize the kernel memory allocator
11615df87b21SJeff Roberson  */
11625df87b21SJeff Roberson /* ARGSUSED*/
11635df87b21SJeff Roberson static void
11645df87b21SJeff Roberson mallocinit(void *dummy)
11655df87b21SJeff Roberson {
11665df87b21SJeff Roberson 	int i;
11675df87b21SJeff Roberson 	uint8_t indx;
11685df87b21SJeff Roberson 
11695df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
11705df87b21SJeff Roberson 
11715df87b21SJeff Roberson 	kmeminit();
1172e4eb384bSBosko Milekic 
11737001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
11747001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
11757001d850SXin LI 
11769afff6b1SMateusz Guzik 	mt_stats_zone = uma_zcreate("mt_stats_zone",
11779afff6b1SMateusz Guzik 	    sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
11789afff6b1SMateusz Guzik 	    UMA_ALIGN_PTR, UMA_ZONE_PCPU);
117963a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
118063a7e0a3SRobert Watson #ifdef INVARIANTS
118163a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
118263a7e0a3SRobert Watson #else
118363a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
118463a7e0a3SRobert Watson #endif
118563a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
11866f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
11876f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
1188eaa17d42SRyan Libby 		const char *name = kmemzones[indx].kz_name;
1189d7854da1SMatthew D Fleming 		int subzone;
11908355f576SJeff Roberson 
1191d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
1192d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
1193d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
11948efc4effSJeff Roberson #ifdef INVARIANTS
11958f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
11968efc4effSJeff Roberson #else
11978efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
11988efc4effSJeff Roberson #endif
11998efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1200d7854da1SMatthew D Fleming 		}
12018355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
12026f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1203df8bae1dSRodney W. Grimes 	}
1204254c6cb3SPoul-Henning Kamp }
1205af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1206254c6cb3SPoul-Henning Kamp 
1207db669378SPeter Wemm void
120887efd4d5SRobert Watson malloc_init(void *data)
1209254c6cb3SPoul-Henning Kamp {
121063a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
121163a7e0a3SRobert Watson 	struct malloc_type *mtp;
121263a7e0a3SRobert Watson 
121344f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
121463a7e0a3SRobert Watson 
121563a7e0a3SRobert Watson 	mtp = data;
1216f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
1217f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
1218bb1c7df8SRobert Watson 
121963a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
12209afff6b1SMateusz Guzik 	mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
122163a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
1222c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
1223254c6cb3SPoul-Henning Kamp 
12246f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
122563a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
122663a7e0a3SRobert Watson 	kmemstatistics = mtp;
1227cd814b26SRobert Watson 	kmemcount++;
12286f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1229df8bae1dSRodney W. Grimes }
1230db669378SPeter Wemm 
1231db669378SPeter Wemm void
123287efd4d5SRobert Watson malloc_uninit(void *data)
1233db669378SPeter Wemm {
123463a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
12352a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
123663a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
123745d48bdaSPaul Saab 	uma_slab_t slab;
12382a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
12392a143d5bSPawel Jakub Dawidek 	int i;
1240db669378SPeter Wemm 
124163a7e0a3SRobert Watson 	mtp = data;
1242bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
1243bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
124463a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1245bb1c7df8SRobert Watson 
12466f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
124763a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
124863a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
124963a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
125063a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
125163a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1252f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
125363a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1254f121baaaSBrian Somers 				break;
1255db669378SPeter Wemm 			}
1256f121baaaSBrian Somers 		}
1257f121baaaSBrian Somers 		KASSERT(temp,
1258f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
125963a7e0a3SRobert Watson 	} else
126063a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1261cd814b26SRobert Watson 	kmemcount--;
12626f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
12632a143d5bSPawel Jakub Dawidek 
12642a143d5bSPawel Jakub Dawidek 	/*
12652a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
12662a143d5bSPawel Jakub Dawidek 	 */
12672a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
12689afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
12699afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
12702a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
12712a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
12722a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
12732a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
12742a143d5bSPawel Jakub Dawidek 	}
12752a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
12762a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
12772a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
12782a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
12792a143d5bSPawel Jakub Dawidek 	}
12802a143d5bSPawel Jakub Dawidek 
128145d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
12829afff6b1SMateusz Guzik 	uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
128345d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
1284db669378SPeter Wemm }
12856f267175SJeff Roberson 
1286d362c40dSPawel Jakub Dawidek struct malloc_type *
1287d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1288d362c40dSPawel Jakub Dawidek {
1289d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1290d362c40dSPawel Jakub Dawidek 
1291d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1292d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1293d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1294d362c40dSPawel Jakub Dawidek 			return (mtp);
1295d362c40dSPawel Jakub Dawidek 	}
1296d362c40dSPawel Jakub Dawidek 	return (NULL);
1297d362c40dSPawel Jakub Dawidek }
1298d362c40dSPawel Jakub Dawidek 
12996f267175SJeff Roberson static int
1300cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1301cd814b26SRobert Watson {
1302cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1303cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
13049afff6b1SMateusz Guzik 	struct malloc_type_stats *mtsp, zeromts;
1305cd814b26SRobert Watson 	struct malloc_type_header mth;
1306cd814b26SRobert Watson 	struct malloc_type *mtp;
13074e657159SMatthew D Fleming 	int error, i;
1308cd814b26SRobert Watson 	struct sbuf sbuf;
1309cd814b26SRobert Watson 
131000f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
131100f0e671SMatthew D Fleming 	if (error != 0)
131200f0e671SMatthew D Fleming 		return (error);
13134e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
13141eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1315cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1316cd814b26SRobert Watson 
13179afff6b1SMateusz Guzik 	bzero(&zeromts, sizeof(zeromts));
13189afff6b1SMateusz Guzik 
1319cd814b26SRobert Watson 	/*
1320cd814b26SRobert Watson 	 * Insert stream header.
1321cd814b26SRobert Watson 	 */
1322cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1323cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1324cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1325cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
13264e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1327cd814b26SRobert Watson 
1328cd814b26SRobert Watson 	/*
1329cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1330cd814b26SRobert Watson 	 */
1331cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1332cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1333cd814b26SRobert Watson 
1334cd814b26SRobert Watson 		/*
1335cd814b26SRobert Watson 		 * Insert type header.
1336cd814b26SRobert Watson 		 */
1337cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1338cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
13394e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1340cd814b26SRobert Watson 
1341cd814b26SRobert Watson 		/*
1342cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1343cd814b26SRobert Watson 		 */
13449afff6b1SMateusz Guzik 		for (i = 0; i <= mp_maxid; i++) {
13459afff6b1SMateusz Guzik 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
13469afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1347cd814b26SRobert Watson 		}
13489afff6b1SMateusz Guzik 		/*
13499afff6b1SMateusz Guzik 		 * Fill in the missing CPUs.
13509afff6b1SMateusz Guzik 		 */
13519afff6b1SMateusz Guzik 		for (; i < MAXCPU; i++) {
13529afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
13539afff6b1SMateusz Guzik 		}
1354cd814b26SRobert Watson 	}
1355cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
13564e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1357cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1358cd814b26SRobert Watson 	return (error);
1359cd814b26SRobert Watson }
1360cd814b26SRobert Watson 
13617029da5cSPawel Biernacki SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
13627029da5cSPawel Biernacki     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
13637029da5cSPawel Biernacki     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1364cd814b26SRobert Watson     "Return malloc types");
1365cd814b26SRobert Watson 
1366cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1367cd814b26SRobert Watson     "Count of kernel malloc types");
1368cd814b26SRobert Watson 
136991dd776cSJohn Birrell void
137091dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
137191dd776cSJohn Birrell {
137291dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
137391dd776cSJohn Birrell 	int count, i;
137491dd776cSJohn Birrell 	size_t buflen;
137591dd776cSJohn Birrell 
137691dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
137791dd776cSJohn Birrell restart:
137891dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
137991dd776cSJohn Birrell 	count = kmemcount;
138091dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
138191dd776cSJohn Birrell 
138291dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
138391dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
138491dd776cSJohn Birrell 
138591dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
138691dd776cSJohn Birrell 
138791dd776cSJohn Birrell 	if (count < kmemcount) {
138891dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
138991dd776cSJohn Birrell 		goto restart;
139091dd776cSJohn Birrell 	}
139191dd776cSJohn Birrell 
139291dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
139391dd776cSJohn Birrell 		bufmtp[i] = mtp;
139491dd776cSJohn Birrell 
139591dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
139691dd776cSJohn Birrell 
139791dd776cSJohn Birrell 	for (i = 0; i < count; i++)
139891dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
139991dd776cSJohn Birrell 
140091dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
140191dd776cSJohn Birrell }
140291dd776cSJohn Birrell 
1403909ed16cSRobert Watson #ifdef DDB
140446d70077SConrad Meyer static int64_t
140546d70077SConrad Meyer get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
140646d70077SConrad Meyer     uint64_t *inuse)
1407909ed16cSRobert Watson {
140846d70077SConrad Meyer 	const struct malloc_type_stats *mtsp;
140946d70077SConrad Meyer 	uint64_t frees, alloced, freed;
1410909ed16cSRobert Watson 	int i;
1411909ed16cSRobert Watson 
141246d70077SConrad Meyer 	*allocs = 0;
1413909ed16cSRobert Watson 	frees = 0;
141424076d13SRobert Watson 	alloced = 0;
141524076d13SRobert Watson 	freed = 0;
14169afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
14179afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
141846d70077SConrad Meyer 
141946d70077SConrad Meyer 		*allocs += mtsp->mts_numallocs;
142026e9d9b0SMark Johnston 		frees += mtsp->mts_numfrees;
142126e9d9b0SMark Johnston 		alloced += mtsp->mts_memalloced;
142226e9d9b0SMark Johnston 		freed += mtsp->mts_memfreed;
1423909ed16cSRobert Watson 	}
142446d70077SConrad Meyer 	*inuse = *allocs - frees;
142546d70077SConrad Meyer 	return (alloced - freed);
142646d70077SConrad Meyer }
142746d70077SConrad Meyer 
142846d70077SConrad Meyer DB_SHOW_COMMAND(malloc, db_show_malloc)
142946d70077SConrad Meyer {
143046d70077SConrad Meyer 	const char *fmt_hdr, *fmt_entry;
143146d70077SConrad Meyer 	struct malloc_type *mtp;
143246d70077SConrad Meyer 	uint64_t allocs, inuse;
143346d70077SConrad Meyer 	int64_t size;
143446d70077SConrad Meyer 	/* variables for sorting */
143546d70077SConrad Meyer 	struct malloc_type *last_mtype, *cur_mtype;
143646d70077SConrad Meyer 	int64_t cur_size, last_size;
143746d70077SConrad Meyer 	int ties;
143846d70077SConrad Meyer 
143946d70077SConrad Meyer 	if (modif[0] == 'i') {
144046d70077SConrad Meyer 		fmt_hdr = "%s,%s,%s,%s\n";
144146d70077SConrad Meyer 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
144246d70077SConrad Meyer 	} else {
144346d70077SConrad Meyer 		fmt_hdr = "%18s %12s  %12s %12s\n";
144446d70077SConrad Meyer 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
144546d70077SConrad Meyer 	}
144646d70077SConrad Meyer 
144746d70077SConrad Meyer 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
144846d70077SConrad Meyer 
144946d70077SConrad Meyer 	/* Select sort, largest size first. */
145046d70077SConrad Meyer 	last_mtype = NULL;
145146d70077SConrad Meyer 	last_size = INT64_MAX;
145246d70077SConrad Meyer 	for (;;) {
145346d70077SConrad Meyer 		cur_mtype = NULL;
145446d70077SConrad Meyer 		cur_size = -1;
145546d70077SConrad Meyer 		ties = 0;
145646d70077SConrad Meyer 
145746d70077SConrad Meyer 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
145846d70077SConrad Meyer 			/*
145946d70077SConrad Meyer 			 * In the case of size ties, print out mtypes
146046d70077SConrad Meyer 			 * in the order they are encountered.  That is,
146146d70077SConrad Meyer 			 * when we encounter the most recently output
146246d70077SConrad Meyer 			 * mtype, we have already printed all preceding
146346d70077SConrad Meyer 			 * ties, and we must print all following ties.
146446d70077SConrad Meyer 			 */
146546d70077SConrad Meyer 			if (mtp == last_mtype) {
146646d70077SConrad Meyer 				ties = 1;
146746d70077SConrad Meyer 				continue;
146846d70077SConrad Meyer 			}
146946d70077SConrad Meyer 			size = get_malloc_stats(mtp->ks_handle, &allocs,
147046d70077SConrad Meyer 			    &inuse);
147146d70077SConrad Meyer 			if (size > cur_size && size < last_size + ties) {
147246d70077SConrad Meyer 				cur_size = size;
147346d70077SConrad Meyer 				cur_mtype = mtp;
147446d70077SConrad Meyer 			}
147546d70077SConrad Meyer 		}
147646d70077SConrad Meyer 		if (cur_mtype == NULL)
147746d70077SConrad Meyer 			break;
147846d70077SConrad Meyer 
147946d70077SConrad Meyer 		size = get_malloc_stats(cur_mtype->ks_handle, &allocs, &inuse);
148046d70077SConrad Meyer 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
148146d70077SConrad Meyer 		    howmany(size, 1024), allocs);
148246d70077SConrad Meyer 
1483687c94aaSJohn Baldwin 		if (db_pager_quit)
1484687c94aaSJohn Baldwin 			break;
148546d70077SConrad Meyer 
148646d70077SConrad Meyer 		last_mtype = cur_mtype;
148746d70077SConrad Meyer 		last_size = cur_size;
1488909ed16cSRobert Watson 	}
1489909ed16cSRobert Watson }
1490d7854da1SMatthew D Fleming 
1491d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1492d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1493d7854da1SMatthew D Fleming {
1494d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1495d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1496d7854da1SMatthew D Fleming 	u_int subzone;
1497d7854da1SMatthew D Fleming 
1498d7854da1SMatthew D Fleming 	if (!have_addr) {
1499d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1500d7854da1SMatthew D Fleming 		return;
1501d7854da1SMatthew D Fleming 	}
1502d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1503d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1504d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1505d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1506d7854da1SMatthew D Fleming 		return;
1507d7854da1SMatthew D Fleming 	}
1508d7854da1SMatthew D Fleming 
1509d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1510d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1511d7854da1SMatthew D Fleming 
1512d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1513d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1514d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1515d7854da1SMatthew D Fleming 			continue;
1516d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1517687c94aaSJohn Baldwin 		if (db_pager_quit)
1518687c94aaSJohn Baldwin 			break;
1519d7854da1SMatthew D Fleming 	}
1520d7854da1SMatthew D Fleming }
1521d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1522d7854da1SMatthew D Fleming #endif /* DDB */
1523909ed16cSRobert Watson 
15245e914b96SJeff Roberson #ifdef MALLOC_PROFILE
15255e914b96SJeff Roberson 
15265e914b96SJeff Roberson static int
15275e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
15285e914b96SJeff Roberson {
152963a7e0a3SRobert Watson 	struct sbuf sbuf;
15305e914b96SJeff Roberson 	uint64_t count;
15315e914b96SJeff Roberson 	uint64_t waste;
15325e914b96SJeff Roberson 	uint64_t mem;
15335e914b96SJeff Roberson 	int error;
15345e914b96SJeff Roberson 	int rsize;
15355e914b96SJeff Roberson 	int size;
15365e914b96SJeff Roberson 	int i;
15375e914b96SJeff Roberson 
15385e914b96SJeff Roberson 	waste = 0;
15395e914b96SJeff Roberson 	mem = 0;
15405e914b96SJeff Roberson 
154100f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
154200f0e671SMatthew D Fleming 	if (error != 0)
154300f0e671SMatthew D Fleming 		return (error);
15444e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
154563a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
15465e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
15475e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
15485e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
15495e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
15505e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
15515e914b96SJeff Roberson 
155263a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
155363a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
15545e914b96SJeff Roberson 
15555e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
15565e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
15575e914b96SJeff Roberson 		mem += (rsize * count);
15585e914b96SJeff Roberson 	}
155963a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
15605e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
15615e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
15624e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
156363a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
15645e914b96SJeff Roberson 	return (error);
15655e914b96SJeff Roberson }
15665e914b96SJeff Roberson 
15677029da5cSPawel Biernacki SYSCTL_OID(_kern, OID_AUTO, mprof,
15687029da5cSPawel Biernacki     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
15697029da5cSPawel Biernacki     sysctl_kern_mprof, "A",
15707029da5cSPawel Biernacki     "Malloc Profiling");
15715e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1572