xref: /freebsd/sys/kern/kern_malloc.c (revision 44d0efb2154d884c85919229f28b31d50d25a350)
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 
446*44d0efb2SAlan Cox 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
447*44d0efb2SAlan Cox 	    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
51706bf2a6aSMatt Macy 	if (flags & M_WAITOK) {
518b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
519a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
52006bf2a6aSMatt Macy 		KASSERT(curthread->td_epochnest == 0,
52106bf2a6aSMatt Macy 			("malloc(M_WAITOK) in epoch context"));
52206bf2a6aSMatt 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 *
55234c538c3SMateusz Guzik (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
5625072a5f4SMatt Macy 	va = NULL;
563ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
564ab3185d1SJeff Roberson 		return (va);
565847a2a17SPawel Jakub Dawidek #endif
566847a2a17SPawel Jakub Dawidek 
5670766f278SJonathan T. Looney 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
5686f267175SJeff Roberson 		if (size & KMEM_ZMASK)
5696f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
5706f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
571c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
5726f267175SJeff Roberson #ifdef MALLOC_PROFILE
5736f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
5746f267175SJeff Roberson #endif
5758355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
5764362fadaSBrian Feldman 		if (va != NULL)
577e20a199fSJeff Roberson 			size = zone->uz_size;
57863a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
5798355f576SJeff Roberson 	} else {
5806f267175SJeff Roberson 		size = roundup(size, PAGE_SIZE);
5818355f576SJeff Roberson 		zone = NULL;
5828355f576SJeff Roberson 		va = uma_large_malloc(size, flags);
58363a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
584df8bae1dSRodney W. Grimes 	}
5851282e9acSPoul-Henning Kamp 	if (flags & M_WAITOK)
586a163d034SWarner Losh 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
5871282e9acSPoul-Henning Kamp 	else if (va == NULL)
5881fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
589ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
590ab3185d1SJeff Roberson 	if (va != NULL)
591ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
5924db4f5c8SPoul-Henning Kamp #endif
593ab3185d1SJeff Roberson 	return ((void *) va);
594ab3185d1SJeff Roberson }
595ab3185d1SJeff Roberson 
596ab3185d1SJeff Roberson void *
597bd555da9SConrad Meyer malloc_domain(size_t size, struct malloc_type *mtp, int domain,
598ab3185d1SJeff Roberson     int flags)
599ab3185d1SJeff Roberson {
600ab3185d1SJeff Roberson 	int indx;
601ab3185d1SJeff Roberson 	caddr_t va;
602ab3185d1SJeff Roberson 	uma_zone_t zone;
603ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
604ab3185d1SJeff Roberson 	unsigned long osize = size;
605ab3185d1SJeff Roberson #endif
606ab3185d1SJeff Roberson 
607ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
6085072a5f4SMatt Macy 	va = NULL;
609ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
610ab3185d1SJeff Roberson 		return (va);
611ab3185d1SJeff Roberson #endif
6120766f278SJonathan T. Looney 	if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
613ab3185d1SJeff Roberson 		if (size & KMEM_ZMASK)
614ab3185d1SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
615ab3185d1SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
616c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
617ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
618ab3185d1SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
619ab3185d1SJeff Roberson #endif
620ab3185d1SJeff Roberson 		va = uma_zalloc_domain(zone, NULL, domain, flags);
621ab3185d1SJeff Roberson 		if (va != NULL)
622ab3185d1SJeff Roberson 			size = zone->uz_size;
623ab3185d1SJeff Roberson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
624ab3185d1SJeff Roberson 	} else {
625ab3185d1SJeff Roberson 		size = roundup(size, PAGE_SIZE);
626ab3185d1SJeff Roberson 		zone = NULL;
627ab3185d1SJeff Roberson 		va = uma_large_malloc_domain(size, domain, flags);
628ab3185d1SJeff Roberson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
629ab3185d1SJeff Roberson 	}
630ab3185d1SJeff Roberson 	if (flags & M_WAITOK)
631ab3185d1SJeff Roberson 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
632ab3185d1SJeff Roberson 	else if (va == NULL)
633ab3185d1SJeff Roberson 		t_malloc_fail = time_uptime;
634847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
635847a2a17SPawel Jakub Dawidek 	if (va != NULL)
636847a2a17SPawel Jakub Dawidek 		va = redzone_setup(va, osize);
637847a2a17SPawel Jakub Dawidek #endif
638df8bae1dSRodney W. Grimes 	return ((void *) va);
639df8bae1dSRodney W. Grimes }
640df8bae1dSRodney W. Grimes 
641fd91e076SKristof Provost void *
642fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
643fd91e076SKristof Provost {
644fd91e076SKristof Provost 
645c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
646c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
647fd91e076SKristof Provost 
648fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
649fd91e076SKristof Provost }
650fd91e076SKristof Provost 
651ab3185d1SJeff Roberson #ifdef INVARIANTS
652ab3185d1SJeff Roberson static void
653ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
654ab3185d1SJeff Roberson {
655ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
656ab3185d1SJeff Roberson 
657ab3185d1SJeff Roberson 	/*
658ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
659ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
660ab3185d1SJeff Roberson 	 * have stepped on it later.
661ab3185d1SJeff Roberson 	 *
662ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
663ab3185d1SJeff Roberson 	 * 64 bit machines
664ab3185d1SJeff Roberson 	 */
665ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
666ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
667ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
668ab3185d1SJeff Roberson 	*mtpp = mtp;
669ab3185d1SJeff Roberson }
670ab3185d1SJeff Roberson #endif
671ab3185d1SJeff Roberson 
672ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
673ab3185d1SJeff Roberson static int
674ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
675ab3185d1SJeff Roberson {
676ab3185d1SJeff Roberson 	void *addr;
677ab3185d1SJeff Roberson 
678ab3185d1SJeff Roberson 	addr = *addrp;
679ab3185d1SJeff Roberson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
680ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
681ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
682ab3185d1SJeff Roberson 
683ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
684ab3185d1SJeff Roberson 	if (addr == NULL)
685ab3185d1SJeff Roberson 		return (EJUSTRETURN);
686ab3185d1SJeff Roberson 
687ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
688ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
689ab3185d1SJeff Roberson 		memguard_free(addr);
690ab3185d1SJeff Roberson 		return (EJUSTRETURN);
691ab3185d1SJeff Roberson 	}
692ab3185d1SJeff Roberson #endif
693ab3185d1SJeff Roberson 
694ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
695ab3185d1SJeff Roberson 	redzone_check(addr);
696ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
697ab3185d1SJeff Roberson #endif
698ab3185d1SJeff Roberson 
699ab3185d1SJeff Roberson 	return (0);
700ab3185d1SJeff Roberson }
701ab3185d1SJeff Roberson #endif
702ab3185d1SJeff Roberson 
703fd91e076SKristof Provost /*
7041c7c3c6aSMatthew Dillon  *	free:
7051c7c3c6aSMatthew Dillon  *
706df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
7071c7c3c6aSMatthew Dillon  *
7081c7c3c6aSMatthew Dillon  *	This routine may not block.
709df8bae1dSRodney W. Grimes  */
710df8bae1dSRodney W. Grimes void
71163a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
712df8bae1dSRodney W. Grimes {
71399571dc3SJeff Roberson 	uma_slab_t slab;
71499571dc3SJeff Roberson 	u_long size;
715254c6cb3SPoul-Henning Kamp 
716ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
717ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
718ab3185d1SJeff Roberson 		return;
719ab3185d1SJeff Roberson #endif
72044a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
72144a8ff31SArchie Cobbs 	if (addr == NULL)
72244a8ff31SArchie Cobbs 		return;
72344a8ff31SArchie Cobbs 
72499571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
7258355f576SJeff Roberson 	if (slab == NULL)
7266f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
72799571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
72899571dc3SJeff Roberson 
7298355f576SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
730099a0e58SBosko Milekic 		size = slab->us_keg->uk_size;
7318f70816cSJeff Roberson #ifdef INVARIANTS
732ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
7338f70816cSJeff Roberson #endif
734099a0e58SBosko Milekic 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
73514bf02f8SJohn Dyson 	} else {
7368355f576SJeff Roberson 		size = slab->us_size;
7378355f576SJeff Roberson 		uma_large_free(slab);
73814bf02f8SJohn Dyson 	}
73963a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
740df8bae1dSRodney W. Grimes }
741df8bae1dSRodney W. Grimes 
742ab3185d1SJeff Roberson void
743ab3185d1SJeff Roberson free_domain(void *addr, struct malloc_type *mtp)
744ab3185d1SJeff Roberson {
745ab3185d1SJeff Roberson 	uma_slab_t slab;
746ab3185d1SJeff Roberson 	u_long size;
747ab3185d1SJeff Roberson 
748ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
749ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
750ab3185d1SJeff Roberson 		return;
751ab3185d1SJeff Roberson #endif
752ab3185d1SJeff Roberson 
753ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
754ab3185d1SJeff Roberson 	if (addr == NULL)
755ab3185d1SJeff Roberson 		return;
756ab3185d1SJeff Roberson 
757ab3185d1SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
758ab3185d1SJeff Roberson 	if (slab == NULL)
759ab3185d1SJeff Roberson 		panic("free_domain: address %p(%p) has not been allocated.\n",
760ab3185d1SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
761ab3185d1SJeff Roberson 
762ab3185d1SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
763ab3185d1SJeff Roberson 		size = slab->us_keg->uk_size;
764ab3185d1SJeff Roberson #ifdef INVARIANTS
765ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
766ab3185d1SJeff Roberson #endif
767ab3185d1SJeff Roberson 		uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
768ab3185d1SJeff Roberson 		    addr, slab);
769ab3185d1SJeff Roberson 	} else {
770ab3185d1SJeff Roberson 		size = slab->us_size;
771ab3185d1SJeff Roberson 		uma_large_free(slab);
772ab3185d1SJeff Roberson 	}
773ab3185d1SJeff Roberson 	malloc_type_freed(mtp, size);
774ab3185d1SJeff Roberson }
775ab3185d1SJeff Roberson 
776df8bae1dSRodney W. Grimes /*
77744a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
77844a8ff31SArchie Cobbs  */
77944a8ff31SArchie Cobbs void *
780bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
78144a8ff31SArchie Cobbs {
7828355f576SJeff Roberson 	uma_slab_t slab;
78344a8ff31SArchie Cobbs 	unsigned long alloc;
78444a8ff31SArchie Cobbs 	void *newaddr;
78544a8ff31SArchie Cobbs 
786bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
787bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
788d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
7891067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
7901067a2baSJonathan T. Looney 
79144a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
79244a8ff31SArchie Cobbs 	if (addr == NULL)
79363a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
79463a7e0a3SRobert Watson 
79563a7e0a3SRobert Watson 	/*
79663a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
79763a7e0a3SRobert Watson 	 * per-CPU stats.
79863a7e0a3SRobert Watson 	 */
79944a8ff31SArchie Cobbs 
800e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
8016d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
8026d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
803e4eb384bSBosko Milekic #endif
804e4eb384bSBosko Milekic 
805847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
806847a2a17SPawel Jakub Dawidek 	slab = NULL;
807847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
808847a2a17SPawel Jakub Dawidek #else
80999571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
8108355f576SJeff Roberson 
81144a8ff31SArchie Cobbs 	/* Sanity check */
8128355f576SJeff Roberson 	KASSERT(slab != NULL,
81344a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
81444a8ff31SArchie Cobbs 
81544a8ff31SArchie Cobbs 	/* Get the size of the original block */
816619f2841SPawel Jakub Dawidek 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
817099a0e58SBosko Milekic 		alloc = slab->us_keg->uk_size;
8188355f576SJeff Roberson 	else
8198355f576SJeff Roberson 		alloc = slab->us_size;
82044a8ff31SArchie Cobbs 
82144a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
82244a8ff31SArchie Cobbs 	if (size <= alloc
82344a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
82444a8ff31SArchie Cobbs 		return (addr);
825847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
82644a8ff31SArchie Cobbs 
82744a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
82863a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
82944a8ff31SArchie Cobbs 		return (NULL);
83044a8ff31SArchie Cobbs 
83144a8ff31SArchie Cobbs 	/* Copy over original contents */
83244a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
83363a7e0a3SRobert Watson 	free(addr, mtp);
83444a8ff31SArchie Cobbs 	return (newaddr);
83544a8ff31SArchie Cobbs }
83644a8ff31SArchie Cobbs 
83744a8ff31SArchie Cobbs /*
83844a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
83944a8ff31SArchie Cobbs  */
84044a8ff31SArchie Cobbs void *
841bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
84244a8ff31SArchie Cobbs {
84344a8ff31SArchie Cobbs 	void *mem;
84444a8ff31SArchie Cobbs 
84563a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
84663a7e0a3SRobert Watson 		free(addr, mtp);
84744a8ff31SArchie Cobbs 	return (mem);
84844a8ff31SArchie Cobbs }
84944a8ff31SArchie Cobbs 
850f9d498adSDimitry Andric #ifndef __sparc64__
851c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
852f9d498adSDimitry Andric #endif
853c70af487SAlan Cox 
8545df87b21SJeff Roberson /*
855c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
8565df87b21SJeff Roberson  */
8575df87b21SJeff Roberson void
8585df87b21SJeff Roberson kmeminit(void)
8595df87b21SJeff Roberson {
860af3b2549SHans Petter Selasky 	u_long mem_size;
861af3b2549SHans Petter Selasky 	u_long tmp;
86269ef67f9SJason Evans 
863af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
864af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
865af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
866af3b2549SHans Petter Selasky #endif
867af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
868af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
869af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
870af3b2549SHans Petter Selasky #endif
871af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
872af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
873af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
874af3b2549SHans Petter Selasky #endif
8758a58a9f6SJohn Dyson 	/*
876c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
877c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
878c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
879c70af487SAlan Cox 	 * specifically,
8808a58a9f6SJohn Dyson 	 *
881c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
882c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
883c70af487SAlan Cox 	 *
884c70af487SAlan Cox 	 * Every architecture must define an integral value for
885c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
886c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
887c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
888c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
889c70af487SAlan Cox 	 * a given architecture.
8908a58a9f6SJohn Dyson 	 */
89144f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
8927c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
8937c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
8948a58a9f6SJohn Dyson 
895c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
896c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
897c70af487SAlan Cox 
898af3b2549SHans Petter Selasky 	/*
899af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
900af3b2549SHans Petter Selasky 	 * variable:
901af3b2549SHans Petter Selasky 	 */
902af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
903479439b4SDag-Erling Smørgrav 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
9048a58a9f6SJohn Dyson 
905c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
9060e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
907479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
908479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
909af3b2549SHans Petter Selasky 	}
9108a58a9f6SJohn Dyson 
91127b8623fSDavid Greenman 	/*
912af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
913c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
914c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
915c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
916c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
91727b8623fSDavid Greenman 	 */
918c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
919c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
9208a58a9f6SJohn Dyson 
921e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
922e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
923f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
924e3813573SMatthew D Fleming #else
925e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
926e3813573SMatthew D Fleming #endif
9272e47807cSJeff Roberson 	uma_set_limit(tmp);
9288355f576SJeff Roberson 
929e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
930e4eb384bSBosko Milekic 	/*
931e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
932e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
933e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
934e4eb384bSBosko Milekic 	 */
9352e47807cSJeff Roberson 	memguard_init(kernel_arena);
936e4eb384bSBosko Milekic #endif
9375df87b21SJeff Roberson }
9385df87b21SJeff Roberson 
9395df87b21SJeff Roberson /*
9405df87b21SJeff Roberson  * Initialize the kernel memory allocator
9415df87b21SJeff Roberson  */
9425df87b21SJeff Roberson /* ARGSUSED*/
9435df87b21SJeff Roberson static void
9445df87b21SJeff Roberson mallocinit(void *dummy)
9455df87b21SJeff Roberson {
9465df87b21SJeff Roberson 	int i;
9475df87b21SJeff Roberson 	uint8_t indx;
9485df87b21SJeff Roberson 
9495df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
9505df87b21SJeff Roberson 
9515df87b21SJeff Roberson 	kmeminit();
952e4eb384bSBosko Milekic 
9537001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
9547001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
9557001d850SXin LI 
95663a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
95763a7e0a3SRobert Watson #ifdef INVARIANTS
95863a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
95963a7e0a3SRobert Watson #else
96063a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
96163a7e0a3SRobert Watson #endif
96263a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
9636f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
9646f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
9656f267175SJeff Roberson 		char *name = kmemzones[indx].kz_name;
966d7854da1SMatthew D Fleming 		int subzone;
9678355f576SJeff Roberson 
968d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
969d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
970d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
9718efc4effSJeff Roberson #ifdef INVARIANTS
9728f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
9738efc4effSJeff Roberson #else
9748efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
9758efc4effSJeff Roberson #endif
9768efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
977d7854da1SMatthew D Fleming 		}
9788355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
9796f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
9808355f576SJeff Roberson 
981df8bae1dSRodney W. Grimes 	}
982254c6cb3SPoul-Henning Kamp }
983af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
984254c6cb3SPoul-Henning Kamp 
985db669378SPeter Wemm void
98687efd4d5SRobert Watson malloc_init(void *data)
987254c6cb3SPoul-Henning Kamp {
98863a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
98963a7e0a3SRobert Watson 	struct malloc_type *mtp;
99063a7e0a3SRobert Watson 
99144f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
99263a7e0a3SRobert Watson 
99363a7e0a3SRobert Watson 	mtp = data;
994f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
995f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
996bb1c7df8SRobert Watson 
99763a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
99863a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
999c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
1000254c6cb3SPoul-Henning Kamp 
10016f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
100263a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
100363a7e0a3SRobert Watson 	kmemstatistics = mtp;
1004cd814b26SRobert Watson 	kmemcount++;
10056f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1006df8bae1dSRodney W. Grimes }
1007db669378SPeter Wemm 
1008db669378SPeter Wemm void
100987efd4d5SRobert Watson malloc_uninit(void *data)
1010db669378SPeter Wemm {
101163a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
10122a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
101363a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
101445d48bdaSPaul Saab 	uma_slab_t slab;
10152a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
10162a143d5bSPawel Jakub Dawidek 	int i;
1017db669378SPeter Wemm 
101863a7e0a3SRobert Watson 	mtp = data;
1019bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
1020bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
102163a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1022bb1c7df8SRobert Watson 
10236f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
102463a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
102563a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
102663a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
102763a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
102863a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1029f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
103063a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1031f121baaaSBrian Somers 				break;
1032db669378SPeter Wemm 			}
1033f121baaaSBrian Somers 		}
1034f121baaaSBrian Somers 		KASSERT(temp,
1035f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
103663a7e0a3SRobert Watson 	} else
103763a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1038cd814b26SRobert Watson 	kmemcount--;
10396f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
10402a143d5bSPawel Jakub Dawidek 
10412a143d5bSPawel Jakub Dawidek 	/*
10422a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
10432a143d5bSPawel Jakub Dawidek 	 */
10442a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
10452a143d5bSPawel Jakub Dawidek 	for (i = 0; i < MAXCPU; i++) {
10462a143d5bSPawel Jakub Dawidek 		mtsp = &mtip->mti_stats[i];
10472a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
10482a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
10492a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
10502a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
10512a143d5bSPawel Jakub Dawidek 	}
10522a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
10532a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
10542a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
10552a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
10562a143d5bSPawel Jakub Dawidek 	}
10572a143d5bSPawel Jakub Dawidek 
105845d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
105945d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
1060db669378SPeter Wemm }
10616f267175SJeff Roberson 
1062d362c40dSPawel Jakub Dawidek struct malloc_type *
1063d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1064d362c40dSPawel Jakub Dawidek {
1065d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1066d362c40dSPawel Jakub Dawidek 
1067d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1068d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1069d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1070d362c40dSPawel Jakub Dawidek 			return (mtp);
1071d362c40dSPawel Jakub Dawidek 	}
1072d362c40dSPawel Jakub Dawidek 	return (NULL);
1073d362c40dSPawel Jakub Dawidek }
1074d362c40dSPawel Jakub Dawidek 
10756f267175SJeff Roberson static int
1076cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1077cd814b26SRobert Watson {
1078cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1079cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
1080cd814b26SRobert Watson 	struct malloc_type_header mth;
1081cd814b26SRobert Watson 	struct malloc_type *mtp;
10824e657159SMatthew D Fleming 	int error, i;
1083cd814b26SRobert Watson 	struct sbuf sbuf;
1084cd814b26SRobert Watson 
108500f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
108600f0e671SMatthew D Fleming 	if (error != 0)
108700f0e671SMatthew D Fleming 		return (error);
10884e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
10891eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1090cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1091cd814b26SRobert Watson 
1092cd814b26SRobert Watson 	/*
1093cd814b26SRobert Watson 	 * Insert stream header.
1094cd814b26SRobert Watson 	 */
1095cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1096cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1097cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1098cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
10994e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1100cd814b26SRobert Watson 
1101cd814b26SRobert Watson 	/*
1102cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1103cd814b26SRobert Watson 	 */
1104cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1105cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1106cd814b26SRobert Watson 
1107cd814b26SRobert Watson 		/*
1108cd814b26SRobert Watson 		 * Insert type header.
1109cd814b26SRobert Watson 		 */
1110cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1111cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
11124e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1113cd814b26SRobert Watson 
1114cd814b26SRobert Watson 		/*
1115cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1116cd814b26SRobert Watson 		 */
1117cd814b26SRobert Watson 		for (i = 0; i < MAXCPU; i++) {
11184e657159SMatthew D Fleming 			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
11194e657159SMatthew D Fleming 			    sizeof(mtip->mti_stats[i]));
1120cd814b26SRobert Watson 		}
1121cd814b26SRobert Watson 	}
1122cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
11234e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1124cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1125cd814b26SRobert Watson 	return (error);
1126cd814b26SRobert Watson }
1127cd814b26SRobert Watson 
1128cd814b26SRobert Watson SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1129cd814b26SRobert Watson     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1130cd814b26SRobert Watson     "Return malloc types");
1131cd814b26SRobert Watson 
1132cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1133cd814b26SRobert Watson     "Count of kernel malloc types");
1134cd814b26SRobert Watson 
113591dd776cSJohn Birrell void
113691dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
113791dd776cSJohn Birrell {
113891dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
113991dd776cSJohn Birrell 	int count, i;
114091dd776cSJohn Birrell 	size_t buflen;
114191dd776cSJohn Birrell 
114291dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
114391dd776cSJohn Birrell restart:
114491dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
114591dd776cSJohn Birrell 	count = kmemcount;
114691dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
114791dd776cSJohn Birrell 
114891dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
114991dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
115091dd776cSJohn Birrell 
115191dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
115291dd776cSJohn Birrell 
115391dd776cSJohn Birrell 	if (count < kmemcount) {
115491dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
115591dd776cSJohn Birrell 		goto restart;
115691dd776cSJohn Birrell 	}
115791dd776cSJohn Birrell 
115891dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
115991dd776cSJohn Birrell 		bufmtp[i] = mtp;
116091dd776cSJohn Birrell 
116191dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
116291dd776cSJohn Birrell 
116391dd776cSJohn Birrell 	for (i = 0; i < count; i++)
116491dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
116591dd776cSJohn Birrell 
116691dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
116791dd776cSJohn Birrell }
116891dd776cSJohn Birrell 
1169909ed16cSRobert Watson #ifdef DDB
1170909ed16cSRobert Watson DB_SHOW_COMMAND(malloc, db_show_malloc)
1171909ed16cSRobert Watson {
1172909ed16cSRobert Watson 	struct malloc_type_internal *mtip;
1173909ed16cSRobert Watson 	struct malloc_type *mtp;
117460ae52f7SEd Schouten 	uint64_t allocs, frees;
117560ae52f7SEd Schouten 	uint64_t alloced, freed;
1176909ed16cSRobert Watson 	int i;
1177909ed16cSRobert Watson 
117824076d13SRobert Watson 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
117924076d13SRobert Watson 	    "Requests");
1180909ed16cSRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1181909ed16cSRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1182909ed16cSRobert Watson 		allocs = 0;
1183909ed16cSRobert Watson 		frees = 0;
118424076d13SRobert Watson 		alloced = 0;
118524076d13SRobert Watson 		freed = 0;
1186909ed16cSRobert Watson 		for (i = 0; i < MAXCPU; i++) {
1187909ed16cSRobert Watson 			allocs += mtip->mti_stats[i].mts_numallocs;
1188909ed16cSRobert Watson 			frees += mtip->mti_stats[i].mts_numfrees;
118924076d13SRobert Watson 			alloced += mtip->mti_stats[i].mts_memalloced;
119024076d13SRobert Watson 			freed += mtip->mti_stats[i].mts_memfreed;
1191909ed16cSRobert Watson 		}
119224076d13SRobert Watson 		db_printf("%18s %12ju %12juK %12ju\n",
119324076d13SRobert Watson 		    mtp->ks_shortdesc, allocs - frees,
119424076d13SRobert Watson 		    (alloced - freed + 1023) / 1024, allocs);
1195687c94aaSJohn Baldwin 		if (db_pager_quit)
1196687c94aaSJohn Baldwin 			break;
1197909ed16cSRobert Watson 	}
1198909ed16cSRobert Watson }
1199d7854da1SMatthew D Fleming 
1200d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1201d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1202d7854da1SMatthew D Fleming {
1203d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1204d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1205d7854da1SMatthew D Fleming 	u_int subzone;
1206d7854da1SMatthew D Fleming 
1207d7854da1SMatthew D Fleming 	if (!have_addr) {
1208d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1209d7854da1SMatthew D Fleming 		return;
1210d7854da1SMatthew D Fleming 	}
1211d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1212d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1213d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1214d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1215d7854da1SMatthew D Fleming 		return;
1216d7854da1SMatthew D Fleming 	}
1217d7854da1SMatthew D Fleming 
1218d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1219d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1220d7854da1SMatthew D Fleming 
1221d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1222d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1223d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1224d7854da1SMatthew D Fleming 			continue;
1225d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1226687c94aaSJohn Baldwin 		if (db_pager_quit)
1227687c94aaSJohn Baldwin 			break;
1228d7854da1SMatthew D Fleming 	}
1229d7854da1SMatthew D Fleming }
1230d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1231d7854da1SMatthew D Fleming #endif /* DDB */
1232909ed16cSRobert Watson 
12335e914b96SJeff Roberson #ifdef MALLOC_PROFILE
12345e914b96SJeff Roberson 
12355e914b96SJeff Roberson static int
12365e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
12375e914b96SJeff Roberson {
123863a7e0a3SRobert Watson 	struct sbuf sbuf;
12395e914b96SJeff Roberson 	uint64_t count;
12405e914b96SJeff Roberson 	uint64_t waste;
12415e914b96SJeff Roberson 	uint64_t mem;
12425e914b96SJeff Roberson 	int error;
12435e914b96SJeff Roberson 	int rsize;
12445e914b96SJeff Roberson 	int size;
12455e914b96SJeff Roberson 	int i;
12465e914b96SJeff Roberson 
12475e914b96SJeff Roberson 	waste = 0;
12485e914b96SJeff Roberson 	mem = 0;
12495e914b96SJeff Roberson 
125000f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
125100f0e671SMatthew D Fleming 	if (error != 0)
125200f0e671SMatthew D Fleming 		return (error);
12534e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
125463a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12555e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
12565e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
12575e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
12585e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
12595e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
12605e914b96SJeff Roberson 
126163a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
126263a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
12635e914b96SJeff Roberson 
12645e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
12655e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
12665e914b96SJeff Roberson 		mem += (rsize * count);
12675e914b96SJeff Roberson 	}
126863a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12695e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
12705e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
12714e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
127263a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
12735e914b96SJeff Roberson 	return (error);
12745e914b96SJeff Roberson }
12755e914b96SJeff Roberson 
12765e914b96SJeff Roberson SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
12775e914b96SJeff Roberson     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
12785e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1279