xref: /freebsd/sys/kern/kern_malloc.c (revision 06bf2a6aefbf98f0717954368a8791cd70bfba30)
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>
6363a7e0a3SRobert Watson #include <sys/sbuf.h>
646f267175SJeff Roberson #include <sys/sysctl.h>
651fb14a47SPoul-Henning Kamp #include <sys/time.h>
665df87b21SJeff Roberson #include <sys/vmem.h>
679a02e8c6SJason Evans 
68df8bae1dSRodney W. Grimes #include <vm/vm.h>
6999571dc3SJeff Roberson #include <vm/pmap.h>
705df87b21SJeff Roberson #include <vm/vm_pageout.h>
71efeaf95aSDavid Greenman #include <vm/vm_param.h>
72df8bae1dSRodney W. Grimes #include <vm/vm_kern.h>
73efeaf95aSDavid Greenman #include <vm/vm_extern.h>
743075778bSJohn Dyson #include <vm/vm_map.h>
7599571dc3SJeff Roberson #include <vm/vm_page.h>
768355f576SJeff Roberson #include <vm/uma.h>
778355f576SJeff Roberson #include <vm/uma_int.h>
788efc4effSJeff Roberson #include <vm/uma_dbg.h>
79df8bae1dSRodney W. Grimes 
80e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
81e4eb384bSBosko Milekic #include <vm/memguard.h>
82e4eb384bSBosko Milekic #endif
83847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
84847a2a17SPawel Jakub Dawidek #include <vm/redzone.h>
85847a2a17SPawel Jakub Dawidek #endif
86e4eb384bSBosko Milekic 
87984982d6SPoul-Henning Kamp #if defined(INVARIANTS) && defined(__i386__)
88984982d6SPoul-Henning Kamp #include <machine/cpu.h>
89984982d6SPoul-Henning Kamp #endif
90984982d6SPoul-Henning Kamp 
91909ed16cSRobert Watson #include <ddb/ddb.h>
92909ed16cSRobert Watson 
9391dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
9491dd776cSJohn Birrell #include <sys/dtrace_bsd.h>
9591dd776cSJohn Birrell 
967cd79421SMateusz Guzik bool	__read_frequently			dtrace_malloc_enabled;
977cd79421SMateusz Guzik dtrace_malloc_probe_func_t __read_mostly	dtrace_malloc_probe;
9891dd776cSJohn Birrell #endif
9991dd776cSJohn Birrell 
100ab3185d1SJeff Roberson #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
101ab3185d1SJeff Roberson     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
102ab3185d1SJeff Roberson #define	MALLOC_DEBUG	1
103ab3185d1SJeff Roberson #endif
104ab3185d1SJeff Roberson 
10544a8ff31SArchie Cobbs /*
10644a8ff31SArchie Cobbs  * When realloc() is called, if the new size is sufficiently smaller than
10744a8ff31SArchie Cobbs  * the old size, realloc() will allocate a new, smaller block to avoid
10844a8ff31SArchie Cobbs  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
10944a8ff31SArchie Cobbs  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
11044a8ff31SArchie Cobbs  */
11144a8ff31SArchie Cobbs #ifndef REALLOC_FRACTION
11244a8ff31SArchie Cobbs #define	REALLOC_FRACTION	1	/* new block if <= half the size */
11344a8ff31SArchie Cobbs #endif
11444a8ff31SArchie Cobbs 
1150ce3f16dSRobert Watson /*
1160ce3f16dSRobert Watson  * Centrally define some common malloc types.
1170ce3f16dSRobert Watson  */
1183b6fb885SPoul-Henning Kamp MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
1199ef246c6SBruce Evans MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
1209ef246c6SBruce Evans MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
1219ef246c6SBruce Evans 
122db669378SPeter Wemm static struct malloc_type *kmemstatistics;
123cd814b26SRobert Watson static int kmemcount;
1241f6889a1SMatthew Dillon 
1258355f576SJeff Roberson #define KMEM_ZSHIFT	4
1268355f576SJeff Roberson #define KMEM_ZBASE	16
1278355f576SJeff Roberson #define KMEM_ZMASK	(KMEM_ZBASE - 1)
1288355f576SJeff Roberson 
129bda06553SXin LI #define KMEM_ZMAX	65536
1308355f576SJeff Roberson #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
13160ae52f7SEd Schouten static uint8_t kmemsize[KMEM_ZSIZE + 1];
1326f267175SJeff Roberson 
133d7854da1SMatthew D Fleming #ifndef MALLOC_DEBUG_MAXZONES
134d7854da1SMatthew D Fleming #define	MALLOC_DEBUG_MAXZONES	1
135d7854da1SMatthew D Fleming #endif
136d7854da1SMatthew D Fleming static int numzones = MALLOC_DEBUG_MAXZONES;
137d7854da1SMatthew D Fleming 
1380ce3f16dSRobert Watson /*
1390ce3f16dSRobert Watson  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
1400ce3f16dSRobert Watson  * of various sizes.
1410ce3f16dSRobert Watson  *
1420ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1430ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1440ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1450ce3f16dSRobert Watson  */
1468355f576SJeff Roberson struct {
1476f267175SJeff Roberson 	int kz_size;
1486f267175SJeff Roberson 	char *kz_name;
149d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1506f267175SJeff Roberson } kmemzones[] = {
151d7854da1SMatthew D Fleming 	{16, "16", },
152d7854da1SMatthew D Fleming 	{32, "32", },
153d7854da1SMatthew D Fleming 	{64, "64", },
154d7854da1SMatthew D Fleming 	{128, "128", },
155d7854da1SMatthew D Fleming 	{256, "256", },
156d7854da1SMatthew D Fleming 	{512, "512", },
157d7854da1SMatthew D Fleming 	{1024, "1024", },
158d7854da1SMatthew D Fleming 	{2048, "2048", },
159d7854da1SMatthew D Fleming 	{4096, "4096", },
160d7854da1SMatthew D Fleming 	{8192, "8192", },
161d7854da1SMatthew D Fleming 	{16384, "16384", },
162d7854da1SMatthew D Fleming 	{32768, "32768", },
163d7854da1SMatthew D Fleming 	{65536, "65536", },
1648355f576SJeff Roberson 	{0, NULL},
1658355f576SJeff Roberson };
1668355f576SJeff Roberson 
1670ce3f16dSRobert Watson /*
1680ce3f16dSRobert Watson  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
1690ce3f16dSRobert Watson  * types are described by a data structure passed by the declaring code, but
1700ce3f16dSRobert Watson  * the malloc(9) implementation has its own data structure describing the
1710ce3f16dSRobert Watson  * type and statistics.  This permits the malloc(9)-internal data structures
1720ce3f16dSRobert Watson  * to be modified without breaking binary-compiled kernel modules that
1730ce3f16dSRobert Watson  * declare malloc types.
1740ce3f16dSRobert Watson  */
17563a7e0a3SRobert Watson static uma_zone_t mt_zone;
17663a7e0a3SRobert Watson 
177b89eaf4eSAlan Cox u_long vm_kmem_size;
178d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
17984344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1805a34a9f0SJeff Roberson 
1817001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1827001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1837001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1847001d850SXin LI 
185b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
186d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1870e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1880e5179e4SStephane E. Potvin 
189b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
190d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
191479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
192479439b4SDag-Erling Smørgrav 
1934813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
194d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
195479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
196479439b4SDag-Erling Smørgrav 
1977814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
1987814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
1997814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2005df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
2017814c80aSAndriy Gapon 
20295bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
20395bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
20495bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2055df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
20695bb9d38SAndriy Gapon 
2075a34a9f0SJeff Roberson /*
20899571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2095a34a9f0SJeff Roberson  */
2105a34a9f0SJeff Roberson struct mtx malloc_mtx;
21169ef67f9SJason Evans 
2125e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2135e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2146f267175SJeff Roberson 
2155e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2165e914b96SJeff Roberson #endif
2175e914b96SJeff Roberson 
218cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
219df8bae1dSRodney W. Grimes 
2200ce3f16dSRobert Watson /*
2210ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2220ce3f16dSRobert Watson  */
2231fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2241fb14a47SPoul-Henning Kamp 
225d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2266472ac3dSEd Schouten static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
227d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
228d7854da1SMatthew D Fleming #endif
229d7854da1SMatthew D Fleming 
230eae870cdSRobert Watson /*
2310ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2320ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
233eae870cdSRobert Watson  */
2340ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
235eae870cdSRobert Watson static int malloc_failure_rate;
236eae870cdSRobert Watson static int malloc_nowait_count;
237eae870cdSRobert Watson static int malloc_failure_count;
238af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
239eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
240eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
241eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
242eae870cdSRobert Watson #endif
243eae870cdSRobert Watson 
2447814c80aSAndriy Gapon static int
2457814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2467814c80aSAndriy Gapon {
2477814c80aSAndriy Gapon 	u_long size;
2487814c80aSAndriy Gapon 
2492e47807cSJeff Roberson 	size = uma_size();
2507814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2517814c80aSAndriy Gapon }
2527814c80aSAndriy Gapon 
25395bb9d38SAndriy Gapon static int
25495bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
25595bb9d38SAndriy Gapon {
2562e47807cSJeff Roberson 	u_long size, limit;
25795bb9d38SAndriy Gapon 
2582e47807cSJeff Roberson 	/* The sysctl is unsigned, implement as a saturation value. */
2592e47807cSJeff Roberson 	size = uma_size();
2602e47807cSJeff Roberson 	limit = uma_limit();
2612e47807cSJeff Roberson 	if (size > limit)
2622e47807cSJeff Roberson 		size = 0;
2632e47807cSJeff Roberson 	else
2642e47807cSJeff Roberson 		size = limit - size;
26595bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
26695bb9d38SAndriy Gapon }
26795bb9d38SAndriy Gapon 
268d7854da1SMatthew D Fleming /*
269d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
270d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
271d7854da1SMatthew D Fleming  */
272d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
273d7854da1SMatthew D Fleming static void
274d7854da1SMatthew D Fleming tunable_set_numzones(void)
275d7854da1SMatthew D Fleming {
276d7854da1SMatthew D Fleming 
277d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
278d7854da1SMatthew D Fleming 	    &numzones);
279d7854da1SMatthew D Fleming 
280d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
281d7854da1SMatthew D Fleming 	if (numzones <= 0)
282d7854da1SMatthew D Fleming 		numzones = 1;
283d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
284d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
285d7854da1SMatthew D Fleming }
286d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
287af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
288d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
289d7854da1SMatthew D Fleming 
290d7854da1SMatthew D Fleming /*
291d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
292d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
293d7854da1SMatthew D Fleming  */
294d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
295d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
296d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
297d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
298d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
299d7854da1SMatthew D Fleming 
300c9e05ccdSMateusz Guzik static void
301c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
302d7854da1SMatthew D Fleming {
303c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
304c9e05ccdSMateusz Guzik 	const char *desc;
305d7854da1SMatthew D Fleming 	size_t len;
306d7854da1SMatthew D Fleming 	u_int val;
307d7854da1SMatthew D Fleming 
308c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
309c9e05ccdSMateusz Guzik 	desc = mtp->ks_shortdesc;
310d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
311c9e05ccdSMateusz Guzik 		val = 0;
312c9e05ccdSMateusz Guzik 	else
313d7854da1SMatthew D Fleming 		val = desc[zone_offset % len];
314c9e05ccdSMateusz Guzik 	mtip->mti_zone = (val % numzones);
315c9e05ccdSMateusz Guzik }
316c9e05ccdSMateusz Guzik 
317c9e05ccdSMateusz Guzik static inline u_int
318c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
319c9e05ccdSMateusz Guzik {
320c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
321c9e05ccdSMateusz Guzik 
322c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
323c9e05ccdSMateusz Guzik 
324c9e05ccdSMateusz Guzik 	KASSERT(mtip->mti_zone < numzones,
325c9e05ccdSMateusz Guzik 	    ("mti_zone %u out of range %d",
326c9e05ccdSMateusz Guzik 	    mtip->mti_zone, numzones));
327c9e05ccdSMateusz Guzik 	return (mtip->mti_zone);
328d7854da1SMatthew D Fleming }
329d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
330d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
331d7854da1SMatthew D Fleming #else
332c9e05ccdSMateusz Guzik static void
333c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
334c9e05ccdSMateusz Guzik {
335c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
336c9e05ccdSMateusz Guzik 
337c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
338c9e05ccdSMateusz Guzik 	mtip->mti_zone = 0;
339c9e05ccdSMateusz Guzik }
340c9e05ccdSMateusz Guzik 
341d7854da1SMatthew D Fleming static inline u_int
342c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
343d7854da1SMatthew D Fleming {
344d7854da1SMatthew D Fleming 
345d7854da1SMatthew D Fleming 	return (0);
346d7854da1SMatthew D Fleming }
347d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
348d7854da1SMatthew D Fleming 
3491fb14a47SPoul-Henning Kamp int
3501fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3511fb14a47SPoul-Henning Kamp {
3521fb14a47SPoul-Henning Kamp 
3531fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3541fb14a47SPoul-Henning Kamp }
3551fb14a47SPoul-Henning Kamp 
356df8bae1dSRodney W. Grimes /*
3570ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3580ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3590ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3600ce3f16dSRobert Watson  * statistics.
3614362fadaSBrian Feldman  */
3624362fadaSBrian Feldman static void
36363a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
3644362fadaSBrian Feldman     int zindx)
3654362fadaSBrian Feldman {
36663a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
36763a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
36863a7e0a3SRobert Watson 
36963a7e0a3SRobert Watson 	critical_enter();
37063a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
37163a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
37273864adbSPawel Jakub Dawidek 	if (size > 0) {
37363a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
37463a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
37573864adbSPawel Jakub Dawidek 	}
3764362fadaSBrian Feldman 	if (zindx != -1)
37763a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
37891dd776cSJohn Birrell 
37991dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
3807cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
38191dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
38291dd776cSJohn Birrell 		if (probe_id != 0)
38391dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
38491dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
38591dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
38691dd776cSJohn Birrell 	}
38791dd776cSJohn Birrell #endif
38891dd776cSJohn Birrell 
38963a7e0a3SRobert Watson 	critical_exit();
3904362fadaSBrian Feldman }
3914362fadaSBrian Feldman 
3924362fadaSBrian Feldman void
39363a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
3944362fadaSBrian Feldman {
39563a7e0a3SRobert Watson 
39673864adbSPawel Jakub Dawidek 	if (size > 0)
39763a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
3984362fadaSBrian Feldman }
3994362fadaSBrian Feldman 
4004362fadaSBrian Feldman /*
4013805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
4020ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
4030ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
4040ce3f16dSRobert Watson  * statistics.
4054362fadaSBrian Feldman  */
4064362fadaSBrian Feldman void
40763a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
4084362fadaSBrian Feldman {
40963a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
41063a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
41163a7e0a3SRobert Watson 
41263a7e0a3SRobert Watson 	critical_enter();
41363a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
41463a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
41563a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
41663a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
41791dd776cSJohn Birrell 
41891dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4197cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
42091dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
42191dd776cSJohn Birrell 		if (probe_id != 0)
42291dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
42391dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
42491dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
42591dd776cSJohn Birrell 	}
42691dd776cSJohn Birrell #endif
42791dd776cSJohn Birrell 
42863a7e0a3SRobert Watson 	critical_exit();
4294362fadaSBrian Feldman }
4304362fadaSBrian Feldman 
4314362fadaSBrian Feldman /*
432f346986bSAlan Cox  *	contigmalloc:
433f346986bSAlan Cox  *
434f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
435f346986bSAlan Cox  *
436f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
437f346986bSAlan Cox  *	the allocation fails.
438f346986bSAlan Cox  */
439f346986bSAlan Cox void *
440f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
441f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
442831ce4cbSJohn Baldwin     vm_paddr_t boundary)
443f346986bSAlan Cox {
444f346986bSAlan Cox 	void *ret;
445f346986bSAlan Cox 
4465df87b21SJeff Roberson 	ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
447f346986bSAlan Cox 	    alignment, boundary, VM_MEMATTR_DEFAULT);
448f346986bSAlan Cox 	if (ret != NULL)
449f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
450f346986bSAlan Cox 	return (ret);
451f346986bSAlan Cox }
452f346986bSAlan Cox 
453ab3185d1SJeff Roberson void *
454ab3185d1SJeff Roberson contigmalloc_domain(unsigned long size, struct malloc_type *type,
455ab3185d1SJeff Roberson     int domain, int flags, vm_paddr_t low, vm_paddr_t high,
456ab3185d1SJeff Roberson     unsigned long alignment, vm_paddr_t boundary)
457ab3185d1SJeff Roberson {
458ab3185d1SJeff Roberson 	void *ret;
459ab3185d1SJeff Roberson 
460ab3185d1SJeff Roberson 	ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
461ab3185d1SJeff Roberson 	    alignment, boundary, VM_MEMATTR_DEFAULT);
462ab3185d1SJeff Roberson 	if (ret != NULL)
463ab3185d1SJeff Roberson 		malloc_type_allocated(type, round_page(size));
464ab3185d1SJeff Roberson 	return (ret);
465ab3185d1SJeff Roberson }
466ab3185d1SJeff Roberson 
467f346986bSAlan Cox /*
468f346986bSAlan Cox  *	contigfree:
469f346986bSAlan Cox  *
470f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
471f346986bSAlan Cox  *
472f346986bSAlan Cox  *	This routine may not block.
473f346986bSAlan Cox  */
474f346986bSAlan Cox void
475f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
476f346986bSAlan Cox {
477f346986bSAlan Cox 
4785df87b21SJeff Roberson 	kmem_free(kernel_arena, (vm_offset_t)addr, size);
479f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
480f346986bSAlan Cox }
481f346986bSAlan Cox 
482ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
483ab3185d1SJeff Roberson static int
4845a70796aSLi-Wen Hsu malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
485ab3185d1SJeff Roberson     int flags)
486df8bae1dSRodney W. Grimes {
487194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
488ab3185d1SJeff Roberson 	int indx;
489ab3185d1SJeff Roberson 
490bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
491d3c11994SPoul-Henning Kamp 	/*
49223198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
493d3c11994SPoul-Henning Kamp 	 */
49423198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
495d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
496d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
497d3c11994SPoul-Henning Kamp 		static	int curerr, once;
498d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
499d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
5002d50560aSMarcel Moolenaar 			kdb_backtrace();
501d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
502d3c11994SPoul-Henning Kamp 			once++;
503d3c11994SPoul-Henning Kamp 		}
504d3c11994SPoul-Henning Kamp 	}
505194a0abfSPoul-Henning Kamp #endif
506eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
507eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
508eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
509eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
510eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
5113f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
512ab3185d1SJeff Roberson 			*vap = NULL;
513ab3185d1SJeff Roberson 			return (EJUSTRETURN);
514eae870cdSRobert Watson 		}
515eae870cdSRobert Watson 	}
516eae870cdSRobert Watson #endif
517*06bf2a6aSMatt Macy 	if (flags & M_WAITOK) {
518b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
519a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
520*06bf2a6aSMatt Macy 		KASSERT(curthread->td_epochnest == 0,
521*06bf2a6aSMatt Macy 			("malloc(M_WAITOK) in epoch context"));
522*06bf2a6aSMatt Macy 	}
523d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
5241067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
5251067a2baSJonathan T. Looney 
526e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
527ab3185d1SJeff Roberson 	if (memguard_cmp_mtp(mtp, *sizep)) {
528ab3185d1SJeff Roberson 		*vap = memguard_alloc(*sizep, flags);
529ab3185d1SJeff Roberson 		if (*vap != NULL)
530ab3185d1SJeff Roberson 			return (EJUSTRETURN);
531e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
532e3813573SMatthew D Fleming 	}
533e4eb384bSBosko Milekic #endif
534e4eb384bSBosko Milekic 
535847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
536ab3185d1SJeff Roberson 	*sizep = redzone_size_ntor(*sizep);
537ab3185d1SJeff Roberson #endif
538ab3185d1SJeff Roberson 
539ab3185d1SJeff Roberson 	return (0);
540ab3185d1SJeff Roberson }
541ab3185d1SJeff Roberson #endif
542ab3185d1SJeff Roberson 
543ab3185d1SJeff Roberson /*
544ab3185d1SJeff Roberson  *	malloc:
545ab3185d1SJeff Roberson  *
546ab3185d1SJeff Roberson  *	Allocate a block of memory.
547ab3185d1SJeff Roberson  *
548ab3185d1SJeff Roberson  *	If M_NOWAIT is set, this routine will not block and return NULL if
549ab3185d1SJeff Roberson  *	the allocation fails.
550ab3185d1SJeff Roberson  */
551ab3185d1SJeff Roberson void *
552bd555da9SConrad Meyer malloc(size_t size, struct malloc_type *mtp, int flags)
553ab3185d1SJeff Roberson {
554ab3185d1SJeff Roberson 	int indx;
555ab3185d1SJeff Roberson 	caddr_t va;
556ab3185d1SJeff Roberson 	uma_zone_t zone;
557ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
558ab3185d1SJeff Roberson 	unsigned long osize = size;
559ab3185d1SJeff Roberson #endif
560ab3185d1SJeff Roberson 
561ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
562ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
563ab3185d1SJeff Roberson 		return (va);
564847a2a17SPawel Jakub Dawidek #endif
565847a2a17SPawel Jakub Dawidek 
5667001d850SXin LI 	if (size <= kmem_zmax) {
5676f267175SJeff Roberson 		if (size & KMEM_ZMASK)
5686f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
5696f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
570c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
5716f267175SJeff Roberson #ifdef MALLOC_PROFILE
5726f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
5736f267175SJeff Roberson #endif
5748355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
5754362fadaSBrian Feldman 		if (va != NULL)
576e20a199fSJeff Roberson 			size = zone->uz_size;
57763a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
5788355f576SJeff Roberson 	} else {
5796f267175SJeff Roberson 		size = roundup(size, PAGE_SIZE);
5808355f576SJeff Roberson 		zone = NULL;
5818355f576SJeff Roberson 		va = uma_large_malloc(size, flags);
58263a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
583df8bae1dSRodney W. Grimes 	}
5841282e9acSPoul-Henning Kamp 	if (flags & M_WAITOK)
585a163d034SWarner Losh 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
5861282e9acSPoul-Henning Kamp 	else if (va == NULL)
5871fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
588ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
589ab3185d1SJeff Roberson 	if (va != NULL)
590ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
5914db4f5c8SPoul-Henning Kamp #endif
592ab3185d1SJeff Roberson 	return ((void *) va);
593ab3185d1SJeff Roberson }
594ab3185d1SJeff Roberson 
595ab3185d1SJeff Roberson void *
596bd555da9SConrad Meyer malloc_domain(size_t size, struct malloc_type *mtp, int domain,
597ab3185d1SJeff Roberson     int flags)
598ab3185d1SJeff Roberson {
599ab3185d1SJeff Roberson 	int indx;
600ab3185d1SJeff Roberson 	caddr_t va;
601ab3185d1SJeff Roberson 	uma_zone_t zone;
602ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
603ab3185d1SJeff Roberson 	unsigned long osize = size;
604ab3185d1SJeff Roberson #endif
605ab3185d1SJeff Roberson 
606ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
607ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
608ab3185d1SJeff Roberson 		return (va);
609ab3185d1SJeff Roberson #endif
610ab3185d1SJeff Roberson 	if (size <= kmem_zmax) {
611ab3185d1SJeff Roberson 		if (size & KMEM_ZMASK)
612ab3185d1SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
613ab3185d1SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
614c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
615ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
616ab3185d1SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
617ab3185d1SJeff Roberson #endif
618ab3185d1SJeff Roberson 		va = uma_zalloc_domain(zone, NULL, domain, flags);
619ab3185d1SJeff Roberson 		if (va != NULL)
620ab3185d1SJeff Roberson 			size = zone->uz_size;
621ab3185d1SJeff Roberson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
622ab3185d1SJeff Roberson 	} else {
623ab3185d1SJeff Roberson 		size = roundup(size, PAGE_SIZE);
624ab3185d1SJeff Roberson 		zone = NULL;
625ab3185d1SJeff Roberson 		va = uma_large_malloc_domain(size, domain, flags);
626ab3185d1SJeff Roberson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
627ab3185d1SJeff Roberson 	}
628ab3185d1SJeff Roberson 	if (flags & M_WAITOK)
629ab3185d1SJeff Roberson 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
630ab3185d1SJeff Roberson 	else if (va == NULL)
631ab3185d1SJeff Roberson 		t_malloc_fail = time_uptime;
632847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
633847a2a17SPawel Jakub Dawidek 	if (va != NULL)
634847a2a17SPawel Jakub Dawidek 		va = redzone_setup(va, osize);
635847a2a17SPawel Jakub Dawidek #endif
636df8bae1dSRodney W. Grimes 	return ((void *) va);
637df8bae1dSRodney W. Grimes }
638df8bae1dSRodney W. Grimes 
639fd91e076SKristof Provost void *
640fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
641fd91e076SKristof Provost {
642fd91e076SKristof Provost 
643c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
644c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
645fd91e076SKristof Provost 
646fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
647fd91e076SKristof Provost }
648fd91e076SKristof Provost 
649ab3185d1SJeff Roberson #ifdef INVARIANTS
650ab3185d1SJeff Roberson static void
651ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
652ab3185d1SJeff Roberson {
653ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
654ab3185d1SJeff Roberson 
655ab3185d1SJeff Roberson 	/*
656ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
657ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
658ab3185d1SJeff Roberson 	 * have stepped on it later.
659ab3185d1SJeff Roberson 	 *
660ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
661ab3185d1SJeff Roberson 	 * 64 bit machines
662ab3185d1SJeff Roberson 	 */
663ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
664ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
665ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
666ab3185d1SJeff Roberson 	*mtpp = mtp;
667ab3185d1SJeff Roberson }
668ab3185d1SJeff Roberson #endif
669ab3185d1SJeff Roberson 
670ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
671ab3185d1SJeff Roberson static int
672ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
673ab3185d1SJeff Roberson {
674ab3185d1SJeff Roberson 	void *addr;
675ab3185d1SJeff Roberson 
676ab3185d1SJeff Roberson 	addr = *addrp;
677ab3185d1SJeff Roberson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
678ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
679ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
680ab3185d1SJeff Roberson 
681ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
682ab3185d1SJeff Roberson 	if (addr == NULL)
683ab3185d1SJeff Roberson 		return (EJUSTRETURN);
684ab3185d1SJeff Roberson 
685ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
686ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
687ab3185d1SJeff Roberson 		memguard_free(addr);
688ab3185d1SJeff Roberson 		return (EJUSTRETURN);
689ab3185d1SJeff Roberson 	}
690ab3185d1SJeff Roberson #endif
691ab3185d1SJeff Roberson 
692ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
693ab3185d1SJeff Roberson 	redzone_check(addr);
694ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
695ab3185d1SJeff Roberson #endif
696ab3185d1SJeff Roberson 
697ab3185d1SJeff Roberson 	return (0);
698ab3185d1SJeff Roberson }
699ab3185d1SJeff Roberson #endif
700ab3185d1SJeff Roberson 
701fd91e076SKristof Provost /*
7021c7c3c6aSMatthew Dillon  *	free:
7031c7c3c6aSMatthew Dillon  *
704df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
7051c7c3c6aSMatthew Dillon  *
7061c7c3c6aSMatthew Dillon  *	This routine may not block.
707df8bae1dSRodney W. Grimes  */
708df8bae1dSRodney W. Grimes void
70963a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
710df8bae1dSRodney W. Grimes {
71199571dc3SJeff Roberson 	uma_slab_t slab;
71299571dc3SJeff Roberson 	u_long size;
713254c6cb3SPoul-Henning Kamp 
714ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
715ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
716ab3185d1SJeff Roberson 		return;
717ab3185d1SJeff Roberson #endif
71844a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
71944a8ff31SArchie Cobbs 	if (addr == NULL)
72044a8ff31SArchie Cobbs 		return;
72144a8ff31SArchie Cobbs 
72299571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
7238355f576SJeff Roberson 	if (slab == NULL)
7246f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
72599571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
72699571dc3SJeff Roberson 
7278355f576SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
728099a0e58SBosko Milekic 		size = slab->us_keg->uk_size;
7298f70816cSJeff Roberson #ifdef INVARIANTS
730ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
7318f70816cSJeff Roberson #endif
732099a0e58SBosko Milekic 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
73314bf02f8SJohn Dyson 	} else {
7348355f576SJeff Roberson 		size = slab->us_size;
7358355f576SJeff Roberson 		uma_large_free(slab);
73614bf02f8SJohn Dyson 	}
73763a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
738df8bae1dSRodney W. Grimes }
739df8bae1dSRodney W. Grimes 
740ab3185d1SJeff Roberson void
741ab3185d1SJeff Roberson free_domain(void *addr, struct malloc_type *mtp)
742ab3185d1SJeff Roberson {
743ab3185d1SJeff Roberson 	uma_slab_t slab;
744ab3185d1SJeff Roberson 	u_long size;
745ab3185d1SJeff Roberson 
746ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
747ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
748ab3185d1SJeff Roberson 		return;
749ab3185d1SJeff Roberson #endif
750ab3185d1SJeff Roberson 
751ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
752ab3185d1SJeff Roberson 	if (addr == NULL)
753ab3185d1SJeff Roberson 		return;
754ab3185d1SJeff Roberson 
755ab3185d1SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
756ab3185d1SJeff Roberson 	if (slab == NULL)
757ab3185d1SJeff Roberson 		panic("free_domain: address %p(%p) has not been allocated.\n",
758ab3185d1SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
759ab3185d1SJeff Roberson 
760ab3185d1SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
761ab3185d1SJeff Roberson 		size = slab->us_keg->uk_size;
762ab3185d1SJeff Roberson #ifdef INVARIANTS
763ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
764ab3185d1SJeff Roberson #endif
765ab3185d1SJeff Roberson 		uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
766ab3185d1SJeff Roberson 		    addr, slab);
767ab3185d1SJeff Roberson 	} else {
768ab3185d1SJeff Roberson 		size = slab->us_size;
769ab3185d1SJeff Roberson 		uma_large_free(slab);
770ab3185d1SJeff Roberson 	}
771ab3185d1SJeff Roberson 	malloc_type_freed(mtp, size);
772ab3185d1SJeff Roberson }
773ab3185d1SJeff Roberson 
774df8bae1dSRodney W. Grimes /*
77544a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
77644a8ff31SArchie Cobbs  */
77744a8ff31SArchie Cobbs void *
778bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
77944a8ff31SArchie Cobbs {
7808355f576SJeff Roberson 	uma_slab_t slab;
78144a8ff31SArchie Cobbs 	unsigned long alloc;
78244a8ff31SArchie Cobbs 	void *newaddr;
78344a8ff31SArchie Cobbs 
784bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
785bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
786d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
7871067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
7881067a2baSJonathan T. Looney 
78944a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
79044a8ff31SArchie Cobbs 	if (addr == NULL)
79163a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
79263a7e0a3SRobert Watson 
79363a7e0a3SRobert Watson 	/*
79463a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
79563a7e0a3SRobert Watson 	 * per-CPU stats.
79663a7e0a3SRobert Watson 	 */
79744a8ff31SArchie Cobbs 
798e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
7996d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
8006d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
801e4eb384bSBosko Milekic #endif
802e4eb384bSBosko Milekic 
803847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
804847a2a17SPawel Jakub Dawidek 	slab = NULL;
805847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
806847a2a17SPawel Jakub Dawidek #else
80799571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
8088355f576SJeff Roberson 
80944a8ff31SArchie Cobbs 	/* Sanity check */
8108355f576SJeff Roberson 	KASSERT(slab != NULL,
81144a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
81244a8ff31SArchie Cobbs 
81344a8ff31SArchie Cobbs 	/* Get the size of the original block */
814619f2841SPawel Jakub Dawidek 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
815099a0e58SBosko Milekic 		alloc = slab->us_keg->uk_size;
8168355f576SJeff Roberson 	else
8178355f576SJeff Roberson 		alloc = slab->us_size;
81844a8ff31SArchie Cobbs 
81944a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
82044a8ff31SArchie Cobbs 	if (size <= alloc
82144a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
82244a8ff31SArchie Cobbs 		return (addr);
823847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
82444a8ff31SArchie Cobbs 
82544a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
82663a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
82744a8ff31SArchie Cobbs 		return (NULL);
82844a8ff31SArchie Cobbs 
82944a8ff31SArchie Cobbs 	/* Copy over original contents */
83044a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
83163a7e0a3SRobert Watson 	free(addr, mtp);
83244a8ff31SArchie Cobbs 	return (newaddr);
83344a8ff31SArchie Cobbs }
83444a8ff31SArchie Cobbs 
83544a8ff31SArchie Cobbs /*
83644a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
83744a8ff31SArchie Cobbs  */
83844a8ff31SArchie Cobbs void *
839bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
84044a8ff31SArchie Cobbs {
84144a8ff31SArchie Cobbs 	void *mem;
84244a8ff31SArchie Cobbs 
84363a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
84463a7e0a3SRobert Watson 		free(addr, mtp);
84544a8ff31SArchie Cobbs 	return (mem);
84644a8ff31SArchie Cobbs }
84744a8ff31SArchie Cobbs 
848f9d498adSDimitry Andric #ifndef __sparc64__
849c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
850f9d498adSDimitry Andric #endif
851c70af487SAlan Cox 
8525df87b21SJeff Roberson /*
853c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
8545df87b21SJeff Roberson  */
8555df87b21SJeff Roberson void
8565df87b21SJeff Roberson kmeminit(void)
8575df87b21SJeff Roberson {
858af3b2549SHans Petter Selasky 	u_long mem_size;
859af3b2549SHans Petter Selasky 	u_long tmp;
86069ef67f9SJason Evans 
861af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
862af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
863af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
864af3b2549SHans Petter Selasky #endif
865af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
866af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
867af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
868af3b2549SHans Petter Selasky #endif
869af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
870af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
871af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
872af3b2549SHans Petter Selasky #endif
8738a58a9f6SJohn Dyson 	/*
874c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
875c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
876c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
877c70af487SAlan Cox 	 * specifically,
8788a58a9f6SJohn Dyson 	 *
879c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
880c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
881c70af487SAlan Cox 	 *
882c70af487SAlan Cox 	 * Every architecture must define an integral value for
883c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
884c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
885c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
886c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
887c70af487SAlan Cox 	 * a given architecture.
8888a58a9f6SJohn Dyson 	 */
88944f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
8907c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
8917c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
8928a58a9f6SJohn Dyson 
893c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
894c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
895c70af487SAlan Cox 
896af3b2549SHans Petter Selasky 	/*
897af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
898af3b2549SHans Petter Selasky 	 * variable:
899af3b2549SHans Petter Selasky 	 */
900af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
901479439b4SDag-Erling Smørgrav 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
9028a58a9f6SJohn Dyson 
903c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
9040e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
905479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
906479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
907af3b2549SHans Petter Selasky 	}
9088a58a9f6SJohn Dyson 
90927b8623fSDavid Greenman 	/*
910af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
911c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
912c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
913c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
914c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
91527b8623fSDavid Greenman 	 */
916c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
917c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
9188a58a9f6SJohn Dyson 
919e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
920e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
921f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
922e3813573SMatthew D Fleming #else
923e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
924e3813573SMatthew D Fleming #endif
9252e47807cSJeff Roberson 	uma_set_limit(tmp);
9268355f576SJeff Roberson 
927e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
928e4eb384bSBosko Milekic 	/*
929e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
930e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
931e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
932e4eb384bSBosko Milekic 	 */
9332e47807cSJeff Roberson 	memguard_init(kernel_arena);
934e4eb384bSBosko Milekic #endif
9355df87b21SJeff Roberson }
9365df87b21SJeff Roberson 
9375df87b21SJeff Roberson /*
9385df87b21SJeff Roberson  * Initialize the kernel memory allocator
9395df87b21SJeff Roberson  */
9405df87b21SJeff Roberson /* ARGSUSED*/
9415df87b21SJeff Roberson static void
9425df87b21SJeff Roberson mallocinit(void *dummy)
9435df87b21SJeff Roberson {
9445df87b21SJeff Roberson 	int i;
9455df87b21SJeff Roberson 	uint8_t indx;
9465df87b21SJeff Roberson 
9475df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
9485df87b21SJeff Roberson 
9495df87b21SJeff Roberson 	kmeminit();
950e4eb384bSBosko Milekic 
9517001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
9527001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
9537001d850SXin LI 
95463a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
95563a7e0a3SRobert Watson #ifdef INVARIANTS
95663a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
95763a7e0a3SRobert Watson #else
95863a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
95963a7e0a3SRobert Watson #endif
96063a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
9616f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
9626f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
9636f267175SJeff Roberson 		char *name = kmemzones[indx].kz_name;
964d7854da1SMatthew D Fleming 		int subzone;
9658355f576SJeff Roberson 
966d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
967d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
968d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
9698efc4effSJeff Roberson #ifdef INVARIANTS
9708f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
9718efc4effSJeff Roberson #else
9728efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
9738efc4effSJeff Roberson #endif
9748efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
975d7854da1SMatthew D Fleming 		}
9768355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
9776f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
9788355f576SJeff Roberson 
979df8bae1dSRodney W. Grimes 	}
980254c6cb3SPoul-Henning Kamp }
981af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
982254c6cb3SPoul-Henning Kamp 
983db669378SPeter Wemm void
98487efd4d5SRobert Watson malloc_init(void *data)
985254c6cb3SPoul-Henning Kamp {
98663a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
98763a7e0a3SRobert Watson 	struct malloc_type *mtp;
98863a7e0a3SRobert Watson 
98944f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
99063a7e0a3SRobert Watson 
99163a7e0a3SRobert Watson 	mtp = data;
992f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
993f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
994bb1c7df8SRobert Watson 
99563a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
99663a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
997c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
998254c6cb3SPoul-Henning Kamp 
9996f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
100063a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
100163a7e0a3SRobert Watson 	kmemstatistics = mtp;
1002cd814b26SRobert Watson 	kmemcount++;
10036f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1004df8bae1dSRodney W. Grimes }
1005db669378SPeter Wemm 
1006db669378SPeter Wemm void
100787efd4d5SRobert Watson malloc_uninit(void *data)
1008db669378SPeter Wemm {
100963a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
10102a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
101163a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
101245d48bdaSPaul Saab 	uma_slab_t slab;
10132a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
10142a143d5bSPawel Jakub Dawidek 	int i;
1015db669378SPeter Wemm 
101663a7e0a3SRobert Watson 	mtp = data;
1017bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
1018bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
101963a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1020bb1c7df8SRobert Watson 
10216f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
102263a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
102363a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
102463a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
102563a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
102663a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1027f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
102863a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1029f121baaaSBrian Somers 				break;
1030db669378SPeter Wemm 			}
1031f121baaaSBrian Somers 		}
1032f121baaaSBrian Somers 		KASSERT(temp,
1033f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
103463a7e0a3SRobert Watson 	} else
103563a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1036cd814b26SRobert Watson 	kmemcount--;
10376f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
10382a143d5bSPawel Jakub Dawidek 
10392a143d5bSPawel Jakub Dawidek 	/*
10402a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
10412a143d5bSPawel Jakub Dawidek 	 */
10422a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
10432a143d5bSPawel Jakub Dawidek 	for (i = 0; i < MAXCPU; i++) {
10442a143d5bSPawel Jakub Dawidek 		mtsp = &mtip->mti_stats[i];
10452a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
10462a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
10472a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
10482a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
10492a143d5bSPawel Jakub Dawidek 	}
10502a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
10512a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
10522a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
10532a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
10542a143d5bSPawel Jakub Dawidek 	}
10552a143d5bSPawel Jakub Dawidek 
105645d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
105745d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
1058db669378SPeter Wemm }
10596f267175SJeff Roberson 
1060d362c40dSPawel Jakub Dawidek struct malloc_type *
1061d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1062d362c40dSPawel Jakub Dawidek {
1063d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1064d362c40dSPawel Jakub Dawidek 
1065d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1066d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1067d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1068d362c40dSPawel Jakub Dawidek 			return (mtp);
1069d362c40dSPawel Jakub Dawidek 	}
1070d362c40dSPawel Jakub Dawidek 	return (NULL);
1071d362c40dSPawel Jakub Dawidek }
1072d362c40dSPawel Jakub Dawidek 
10736f267175SJeff Roberson static int
1074cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1075cd814b26SRobert Watson {
1076cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1077cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
1078cd814b26SRobert Watson 	struct malloc_type_header mth;
1079cd814b26SRobert Watson 	struct malloc_type *mtp;
10804e657159SMatthew D Fleming 	int error, i;
1081cd814b26SRobert Watson 	struct sbuf sbuf;
1082cd814b26SRobert Watson 
108300f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
108400f0e671SMatthew D Fleming 	if (error != 0)
108500f0e671SMatthew D Fleming 		return (error);
10864e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
10871eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1088cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1089cd814b26SRobert Watson 
1090cd814b26SRobert Watson 	/*
1091cd814b26SRobert Watson 	 * Insert stream header.
1092cd814b26SRobert Watson 	 */
1093cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1094cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1095cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1096cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
10974e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1098cd814b26SRobert Watson 
1099cd814b26SRobert Watson 	/*
1100cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1101cd814b26SRobert Watson 	 */
1102cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1103cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1104cd814b26SRobert Watson 
1105cd814b26SRobert Watson 		/*
1106cd814b26SRobert Watson 		 * Insert type header.
1107cd814b26SRobert Watson 		 */
1108cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1109cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
11104e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1111cd814b26SRobert Watson 
1112cd814b26SRobert Watson 		/*
1113cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1114cd814b26SRobert Watson 		 */
1115cd814b26SRobert Watson 		for (i = 0; i < MAXCPU; i++) {
11164e657159SMatthew D Fleming 			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
11174e657159SMatthew D Fleming 			    sizeof(mtip->mti_stats[i]));
1118cd814b26SRobert Watson 		}
1119cd814b26SRobert Watson 	}
1120cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
11214e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1122cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1123cd814b26SRobert Watson 	return (error);
1124cd814b26SRobert Watson }
1125cd814b26SRobert Watson 
1126cd814b26SRobert Watson SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1127cd814b26SRobert Watson     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1128cd814b26SRobert Watson     "Return malloc types");
1129cd814b26SRobert Watson 
1130cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1131cd814b26SRobert Watson     "Count of kernel malloc types");
1132cd814b26SRobert Watson 
113391dd776cSJohn Birrell void
113491dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
113591dd776cSJohn Birrell {
113691dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
113791dd776cSJohn Birrell 	int count, i;
113891dd776cSJohn Birrell 	size_t buflen;
113991dd776cSJohn Birrell 
114091dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
114191dd776cSJohn Birrell restart:
114291dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
114391dd776cSJohn Birrell 	count = kmemcount;
114491dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
114591dd776cSJohn Birrell 
114691dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
114791dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
114891dd776cSJohn Birrell 
114991dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
115091dd776cSJohn Birrell 
115191dd776cSJohn Birrell 	if (count < kmemcount) {
115291dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
115391dd776cSJohn Birrell 		goto restart;
115491dd776cSJohn Birrell 	}
115591dd776cSJohn Birrell 
115691dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
115791dd776cSJohn Birrell 		bufmtp[i] = mtp;
115891dd776cSJohn Birrell 
115991dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
116091dd776cSJohn Birrell 
116191dd776cSJohn Birrell 	for (i = 0; i < count; i++)
116291dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
116391dd776cSJohn Birrell 
116491dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
116591dd776cSJohn Birrell }
116691dd776cSJohn Birrell 
1167909ed16cSRobert Watson #ifdef DDB
1168909ed16cSRobert Watson DB_SHOW_COMMAND(malloc, db_show_malloc)
1169909ed16cSRobert Watson {
1170909ed16cSRobert Watson 	struct malloc_type_internal *mtip;
1171909ed16cSRobert Watson 	struct malloc_type *mtp;
117260ae52f7SEd Schouten 	uint64_t allocs, frees;
117360ae52f7SEd Schouten 	uint64_t alloced, freed;
1174909ed16cSRobert Watson 	int i;
1175909ed16cSRobert Watson 
117624076d13SRobert Watson 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
117724076d13SRobert Watson 	    "Requests");
1178909ed16cSRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1179909ed16cSRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1180909ed16cSRobert Watson 		allocs = 0;
1181909ed16cSRobert Watson 		frees = 0;
118224076d13SRobert Watson 		alloced = 0;
118324076d13SRobert Watson 		freed = 0;
1184909ed16cSRobert Watson 		for (i = 0; i < MAXCPU; i++) {
1185909ed16cSRobert Watson 			allocs += mtip->mti_stats[i].mts_numallocs;
1186909ed16cSRobert Watson 			frees += mtip->mti_stats[i].mts_numfrees;
118724076d13SRobert Watson 			alloced += mtip->mti_stats[i].mts_memalloced;
118824076d13SRobert Watson 			freed += mtip->mti_stats[i].mts_memfreed;
1189909ed16cSRobert Watson 		}
119024076d13SRobert Watson 		db_printf("%18s %12ju %12juK %12ju\n",
119124076d13SRobert Watson 		    mtp->ks_shortdesc, allocs - frees,
119224076d13SRobert Watson 		    (alloced - freed + 1023) / 1024, allocs);
1193687c94aaSJohn Baldwin 		if (db_pager_quit)
1194687c94aaSJohn Baldwin 			break;
1195909ed16cSRobert Watson 	}
1196909ed16cSRobert Watson }
1197d7854da1SMatthew D Fleming 
1198d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1199d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1200d7854da1SMatthew D Fleming {
1201d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1202d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1203d7854da1SMatthew D Fleming 	u_int subzone;
1204d7854da1SMatthew D Fleming 
1205d7854da1SMatthew D Fleming 	if (!have_addr) {
1206d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1207d7854da1SMatthew D Fleming 		return;
1208d7854da1SMatthew D Fleming 	}
1209d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1210d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1211d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1212d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1213d7854da1SMatthew D Fleming 		return;
1214d7854da1SMatthew D Fleming 	}
1215d7854da1SMatthew D Fleming 
1216d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1217d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1218d7854da1SMatthew D Fleming 
1219d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1220d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1221d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1222d7854da1SMatthew D Fleming 			continue;
1223d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1224687c94aaSJohn Baldwin 		if (db_pager_quit)
1225687c94aaSJohn Baldwin 			break;
1226d7854da1SMatthew D Fleming 	}
1227d7854da1SMatthew D Fleming }
1228d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1229d7854da1SMatthew D Fleming #endif /* DDB */
1230909ed16cSRobert Watson 
12315e914b96SJeff Roberson #ifdef MALLOC_PROFILE
12325e914b96SJeff Roberson 
12335e914b96SJeff Roberson static int
12345e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
12355e914b96SJeff Roberson {
123663a7e0a3SRobert Watson 	struct sbuf sbuf;
12375e914b96SJeff Roberson 	uint64_t count;
12385e914b96SJeff Roberson 	uint64_t waste;
12395e914b96SJeff Roberson 	uint64_t mem;
12405e914b96SJeff Roberson 	int error;
12415e914b96SJeff Roberson 	int rsize;
12425e914b96SJeff Roberson 	int size;
12435e914b96SJeff Roberson 	int i;
12445e914b96SJeff Roberson 
12455e914b96SJeff Roberson 	waste = 0;
12465e914b96SJeff Roberson 	mem = 0;
12475e914b96SJeff Roberson 
124800f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
124900f0e671SMatthew D Fleming 	if (error != 0)
125000f0e671SMatthew D Fleming 		return (error);
12514e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
125263a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12535e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
12545e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
12555e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
12565e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
12575e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
12585e914b96SJeff Roberson 
125963a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
126063a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
12615e914b96SJeff Roberson 
12625e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
12635e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
12645e914b96SJeff Roberson 		mem += (rsize * count);
12655e914b96SJeff Roberson 	}
126663a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12675e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
12685e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
12694e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
127063a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
12715e914b96SJeff Roberson 	return (error);
12725e914b96SJeff Roberson }
12735e914b96SJeff Roberson 
12745e914b96SJeff Roberson SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
12755e914b96SJeff Roberson     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
12765e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1277