xref: /freebsd/sys/kern/kern_malloc.c (revision c9e05ccd6290c127204a7dab735c39b56020fec5)
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 
9691dd776cSJohn Birrell dtrace_malloc_probe_func_t	dtrace_malloc_probe;
9791dd776cSJohn Birrell #endif
9891dd776cSJohn Birrell 
99ab3185d1SJeff Roberson #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
100ab3185d1SJeff Roberson     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
101ab3185d1SJeff Roberson #define	MALLOC_DEBUG	1
102ab3185d1SJeff Roberson #endif
103ab3185d1SJeff Roberson 
10444a8ff31SArchie Cobbs /*
10544a8ff31SArchie Cobbs  * When realloc() is called, if the new size is sufficiently smaller than
10644a8ff31SArchie Cobbs  * the old size, realloc() will allocate a new, smaller block to avoid
10744a8ff31SArchie Cobbs  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
10844a8ff31SArchie Cobbs  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
10944a8ff31SArchie Cobbs  */
11044a8ff31SArchie Cobbs #ifndef REALLOC_FRACTION
11144a8ff31SArchie Cobbs #define	REALLOC_FRACTION	1	/* new block if <= half the size */
11244a8ff31SArchie Cobbs #endif
11344a8ff31SArchie Cobbs 
1140ce3f16dSRobert Watson /*
1150ce3f16dSRobert Watson  * Centrally define some common malloc types.
1160ce3f16dSRobert Watson  */
1173b6fb885SPoul-Henning Kamp MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
1189ef246c6SBruce Evans MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
1199ef246c6SBruce Evans MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
1209ef246c6SBruce Evans 
121db669378SPeter Wemm static struct malloc_type *kmemstatistics;
122cd814b26SRobert Watson static int kmemcount;
1231f6889a1SMatthew Dillon 
1248355f576SJeff Roberson #define KMEM_ZSHIFT	4
1258355f576SJeff Roberson #define KMEM_ZBASE	16
1268355f576SJeff Roberson #define KMEM_ZMASK	(KMEM_ZBASE - 1)
1278355f576SJeff Roberson 
128bda06553SXin LI #define KMEM_ZMAX	65536
1298355f576SJeff Roberson #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
13060ae52f7SEd Schouten static uint8_t kmemsize[KMEM_ZSIZE + 1];
1316f267175SJeff Roberson 
132d7854da1SMatthew D Fleming #ifndef MALLOC_DEBUG_MAXZONES
133d7854da1SMatthew D Fleming #define	MALLOC_DEBUG_MAXZONES	1
134d7854da1SMatthew D Fleming #endif
135d7854da1SMatthew D Fleming static int numzones = MALLOC_DEBUG_MAXZONES;
136d7854da1SMatthew D Fleming 
1370ce3f16dSRobert Watson /*
1380ce3f16dSRobert Watson  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
1390ce3f16dSRobert Watson  * of various sizes.
1400ce3f16dSRobert Watson  *
1410ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1420ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1430ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1440ce3f16dSRobert Watson  */
1458355f576SJeff Roberson struct {
1466f267175SJeff Roberson 	int kz_size;
1476f267175SJeff Roberson 	char *kz_name;
148d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1496f267175SJeff Roberson } kmemzones[] = {
150d7854da1SMatthew D Fleming 	{16, "16", },
151d7854da1SMatthew D Fleming 	{32, "32", },
152d7854da1SMatthew D Fleming 	{64, "64", },
153d7854da1SMatthew D Fleming 	{128, "128", },
154d7854da1SMatthew D Fleming 	{256, "256", },
155d7854da1SMatthew D Fleming 	{512, "512", },
156d7854da1SMatthew D Fleming 	{1024, "1024", },
157d7854da1SMatthew D Fleming 	{2048, "2048", },
158d7854da1SMatthew D Fleming 	{4096, "4096", },
159d7854da1SMatthew D Fleming 	{8192, "8192", },
160d7854da1SMatthew D Fleming 	{16384, "16384", },
161d7854da1SMatthew D Fleming 	{32768, "32768", },
162d7854da1SMatthew D Fleming 	{65536, "65536", },
1638355f576SJeff Roberson 	{0, NULL},
1648355f576SJeff Roberson };
1658355f576SJeff Roberson 
1660ce3f16dSRobert Watson /*
1670ce3f16dSRobert Watson  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
1680ce3f16dSRobert Watson  * types are described by a data structure passed by the declaring code, but
1690ce3f16dSRobert Watson  * the malloc(9) implementation has its own data structure describing the
1700ce3f16dSRobert Watson  * type and statistics.  This permits the malloc(9)-internal data structures
1710ce3f16dSRobert Watson  * to be modified without breaking binary-compiled kernel modules that
1720ce3f16dSRobert Watson  * declare malloc types.
1730ce3f16dSRobert Watson  */
17463a7e0a3SRobert Watson static uma_zone_t mt_zone;
17563a7e0a3SRobert Watson 
176b89eaf4eSAlan Cox u_long vm_kmem_size;
177d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
17884344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1795a34a9f0SJeff Roberson 
1807001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1817001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1827001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1837001d850SXin LI 
184b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
185d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1860e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1870e5179e4SStephane E. Potvin 
188b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
189d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
190479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
191479439b4SDag-Erling Smørgrav 
1924813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
193d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
194479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
195479439b4SDag-Erling Smørgrav 
1967814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
1977814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
1987814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
1995df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
2007814c80aSAndriy Gapon 
20195bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
20295bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
20395bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2045df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
20595bb9d38SAndriy Gapon 
2065a34a9f0SJeff Roberson /*
20799571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2085a34a9f0SJeff Roberson  */
2095a34a9f0SJeff Roberson struct mtx malloc_mtx;
21069ef67f9SJason Evans 
2115e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2125e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2136f267175SJeff Roberson 
2145e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2155e914b96SJeff Roberson #endif
2165e914b96SJeff Roberson 
217cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
218df8bae1dSRodney W. Grimes 
2190ce3f16dSRobert Watson /*
2200ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2210ce3f16dSRobert Watson  */
2221fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2231fb14a47SPoul-Henning Kamp 
224d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2256472ac3dSEd Schouten static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
226d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
227d7854da1SMatthew D Fleming #endif
228d7854da1SMatthew D Fleming 
229eae870cdSRobert Watson /*
2300ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2310ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
232eae870cdSRobert Watson  */
2330ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
234eae870cdSRobert Watson static int malloc_failure_rate;
235eae870cdSRobert Watson static int malloc_nowait_count;
236eae870cdSRobert Watson static int malloc_failure_count;
237af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
238eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
239eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
240eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
241eae870cdSRobert Watson #endif
242eae870cdSRobert Watson 
2437814c80aSAndriy Gapon static int
2447814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2457814c80aSAndriy Gapon {
2467814c80aSAndriy Gapon 	u_long size;
2477814c80aSAndriy Gapon 
2482e47807cSJeff Roberson 	size = uma_size();
2497814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2507814c80aSAndriy Gapon }
2517814c80aSAndriy Gapon 
25295bb9d38SAndriy Gapon static int
25395bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
25495bb9d38SAndriy Gapon {
2552e47807cSJeff Roberson 	u_long size, limit;
25695bb9d38SAndriy Gapon 
2572e47807cSJeff Roberson 	/* The sysctl is unsigned, implement as a saturation value. */
2582e47807cSJeff Roberson 	size = uma_size();
2592e47807cSJeff Roberson 	limit = uma_limit();
2602e47807cSJeff Roberson 	if (size > limit)
2612e47807cSJeff Roberson 		size = 0;
2622e47807cSJeff Roberson 	else
2632e47807cSJeff Roberson 		size = limit - size;
26495bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
26595bb9d38SAndriy Gapon }
26695bb9d38SAndriy Gapon 
267d7854da1SMatthew D Fleming /*
268d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
269d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
270d7854da1SMatthew D Fleming  */
271d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
272d7854da1SMatthew D Fleming static void
273d7854da1SMatthew D Fleming tunable_set_numzones(void)
274d7854da1SMatthew D Fleming {
275d7854da1SMatthew D Fleming 
276d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
277d7854da1SMatthew D Fleming 	    &numzones);
278d7854da1SMatthew D Fleming 
279d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
280d7854da1SMatthew D Fleming 	if (numzones <= 0)
281d7854da1SMatthew D Fleming 		numzones = 1;
282d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
283d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
284d7854da1SMatthew D Fleming }
285d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
286af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
287d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
288d7854da1SMatthew D Fleming 
289d7854da1SMatthew D Fleming /*
290d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
291d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
292d7854da1SMatthew D Fleming  */
293d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
294d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
295d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
296d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
297d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
298d7854da1SMatthew D Fleming 
299*c9e05ccdSMateusz Guzik static void
300*c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
301d7854da1SMatthew D Fleming {
302*c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
303*c9e05ccdSMateusz Guzik 	const char *desc;
304d7854da1SMatthew D Fleming 	size_t len;
305d7854da1SMatthew D Fleming 	u_int val;
306d7854da1SMatthew D Fleming 
307*c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
308*c9e05ccdSMateusz Guzik 	desc = mtp->ks_shortdesc;
309d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
310*c9e05ccdSMateusz Guzik 		val = 0;
311*c9e05ccdSMateusz Guzik 	else
312d7854da1SMatthew D Fleming 		val = desc[zone_offset % len];
313*c9e05ccdSMateusz Guzik 	mtip->mti_zone = (val % numzones);
314*c9e05ccdSMateusz Guzik }
315*c9e05ccdSMateusz Guzik 
316*c9e05ccdSMateusz Guzik static inline u_int
317*c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
318*c9e05ccdSMateusz Guzik {
319*c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
320*c9e05ccdSMateusz Guzik 
321*c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
322*c9e05ccdSMateusz Guzik 
323*c9e05ccdSMateusz Guzik 	KASSERT(mtip->mti_zone < numzones,
324*c9e05ccdSMateusz Guzik 	    ("mti_zone %u out of range %d",
325*c9e05ccdSMateusz Guzik 	    mtip->mti_zone, numzones));
326*c9e05ccdSMateusz Guzik 	return (mtip->mti_zone);
327d7854da1SMatthew D Fleming }
328d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
329d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
330d7854da1SMatthew D Fleming #else
331*c9e05ccdSMateusz Guzik static void
332*c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
333*c9e05ccdSMateusz Guzik {
334*c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
335*c9e05ccdSMateusz Guzik 
336*c9e05ccdSMateusz Guzik 	mtip = mtp->ks_handle;
337*c9e05ccdSMateusz Guzik 	mtip->mti_zone = 0;
338*c9e05ccdSMateusz Guzik }
339*c9e05ccdSMateusz Guzik 
340d7854da1SMatthew D Fleming static inline u_int
341*c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
342d7854da1SMatthew D Fleming {
343d7854da1SMatthew D Fleming 
344d7854da1SMatthew D Fleming 	return (0);
345d7854da1SMatthew D Fleming }
346d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
347d7854da1SMatthew D Fleming 
3481fb14a47SPoul-Henning Kamp int
3491fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3501fb14a47SPoul-Henning Kamp {
3511fb14a47SPoul-Henning Kamp 
3521fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3531fb14a47SPoul-Henning Kamp }
3541fb14a47SPoul-Henning Kamp 
355df8bae1dSRodney W. Grimes /*
3560ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3570ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3580ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3590ce3f16dSRobert Watson  * statistics.
3604362fadaSBrian Feldman  */
3614362fadaSBrian Feldman static void
36263a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
3634362fadaSBrian Feldman     int zindx)
3644362fadaSBrian Feldman {
36563a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
36663a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
36763a7e0a3SRobert Watson 
36863a7e0a3SRobert Watson 	critical_enter();
36963a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
37063a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
37173864adbSPawel Jakub Dawidek 	if (size > 0) {
37263a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
37363a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
37473864adbSPawel Jakub Dawidek 	}
3754362fadaSBrian Feldman 	if (zindx != -1)
37663a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
37791dd776cSJohn Birrell 
37891dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
37991dd776cSJohn Birrell 	if (dtrace_malloc_probe != NULL) {
38091dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
38191dd776cSJohn Birrell 		if (probe_id != 0)
38291dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
38391dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
38491dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
38591dd776cSJohn Birrell 	}
38691dd776cSJohn Birrell #endif
38791dd776cSJohn Birrell 
38863a7e0a3SRobert Watson 	critical_exit();
3894362fadaSBrian Feldman }
3904362fadaSBrian Feldman 
3914362fadaSBrian Feldman void
39263a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
3934362fadaSBrian Feldman {
39463a7e0a3SRobert Watson 
39573864adbSPawel Jakub Dawidek 	if (size > 0)
39663a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
3974362fadaSBrian Feldman }
3984362fadaSBrian Feldman 
3994362fadaSBrian Feldman /*
4003805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
4010ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
4020ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
4030ce3f16dSRobert Watson  * statistics.
4044362fadaSBrian Feldman  */
4054362fadaSBrian Feldman void
40663a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
4074362fadaSBrian Feldman {
40863a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
40963a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
41063a7e0a3SRobert Watson 
41163a7e0a3SRobert Watson 	critical_enter();
41263a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
41363a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
41463a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
41563a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
41691dd776cSJohn Birrell 
41791dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
41891dd776cSJohn Birrell 	if (dtrace_malloc_probe != NULL) {
41991dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
42091dd776cSJohn Birrell 		if (probe_id != 0)
42191dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
42291dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
42391dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
42491dd776cSJohn Birrell 	}
42591dd776cSJohn Birrell #endif
42691dd776cSJohn Birrell 
42763a7e0a3SRobert Watson 	critical_exit();
4284362fadaSBrian Feldman }
4294362fadaSBrian Feldman 
4304362fadaSBrian Feldman /*
431f346986bSAlan Cox  *	contigmalloc:
432f346986bSAlan Cox  *
433f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
434f346986bSAlan Cox  *
435f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
436f346986bSAlan Cox  *	the allocation fails.
437f346986bSAlan Cox  */
438f346986bSAlan Cox void *
439f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
440f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
441831ce4cbSJohn Baldwin     vm_paddr_t boundary)
442f346986bSAlan Cox {
443f346986bSAlan Cox 	void *ret;
444f346986bSAlan Cox 
4455df87b21SJeff Roberson 	ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
446f346986bSAlan Cox 	    alignment, boundary, VM_MEMATTR_DEFAULT);
447f346986bSAlan Cox 	if (ret != NULL)
448f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
449f346986bSAlan Cox 	return (ret);
450f346986bSAlan Cox }
451f346986bSAlan Cox 
452ab3185d1SJeff Roberson void *
453ab3185d1SJeff Roberson contigmalloc_domain(unsigned long size, struct malloc_type *type,
454ab3185d1SJeff Roberson     int domain, int flags, vm_paddr_t low, vm_paddr_t high,
455ab3185d1SJeff Roberson     unsigned long alignment, vm_paddr_t boundary)
456ab3185d1SJeff Roberson {
457ab3185d1SJeff Roberson 	void *ret;
458ab3185d1SJeff Roberson 
459ab3185d1SJeff Roberson 	ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
460ab3185d1SJeff Roberson 	    alignment, boundary, VM_MEMATTR_DEFAULT);
461ab3185d1SJeff Roberson 	if (ret != NULL)
462ab3185d1SJeff Roberson 		malloc_type_allocated(type, round_page(size));
463ab3185d1SJeff Roberson 	return (ret);
464ab3185d1SJeff Roberson }
465ab3185d1SJeff Roberson 
466f346986bSAlan Cox /*
467f346986bSAlan Cox  *	contigfree:
468f346986bSAlan Cox  *
469f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
470f346986bSAlan Cox  *
471f346986bSAlan Cox  *	This routine may not block.
472f346986bSAlan Cox  */
473f346986bSAlan Cox void
474f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
475f346986bSAlan Cox {
476f346986bSAlan Cox 
4775df87b21SJeff Roberson 	kmem_free(kernel_arena, (vm_offset_t)addr, size);
478f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
479f346986bSAlan Cox }
480f346986bSAlan Cox 
481ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
482ab3185d1SJeff Roberson static int
4835a70796aSLi-Wen Hsu malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
484ab3185d1SJeff Roberson     int flags)
485df8bae1dSRodney W. Grimes {
486194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
487ab3185d1SJeff Roberson 	int indx;
488ab3185d1SJeff Roberson 
489bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
490d3c11994SPoul-Henning Kamp 	/*
49123198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
492d3c11994SPoul-Henning Kamp 	 */
49323198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
494d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
495d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
496d3c11994SPoul-Henning Kamp 		static	int curerr, once;
497d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
498d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
4992d50560aSMarcel Moolenaar 			kdb_backtrace();
500d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
501d3c11994SPoul-Henning Kamp 			once++;
502d3c11994SPoul-Henning Kamp 		}
503d3c11994SPoul-Henning Kamp 	}
504194a0abfSPoul-Henning Kamp #endif
505eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
506eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
507eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
508eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
509eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
5103f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
511ab3185d1SJeff Roberson 			*vap = NULL;
512ab3185d1SJeff Roberson 			return (EJUSTRETURN);
513eae870cdSRobert Watson 		}
514eae870cdSRobert Watson 	}
515eae870cdSRobert Watson #endif
516d3c11994SPoul-Henning Kamp 	if (flags & M_WAITOK)
517b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
518a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
519d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
5201067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
5211067a2baSJonathan T. Looney 
522e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
523ab3185d1SJeff Roberson 	if (memguard_cmp_mtp(mtp, *sizep)) {
524ab3185d1SJeff Roberson 		*vap = memguard_alloc(*sizep, flags);
525ab3185d1SJeff Roberson 		if (*vap != NULL)
526ab3185d1SJeff Roberson 			return (EJUSTRETURN);
527e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
528e3813573SMatthew D Fleming 	}
529e4eb384bSBosko Milekic #endif
530e4eb384bSBosko Milekic 
531847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
532ab3185d1SJeff Roberson 	*sizep = redzone_size_ntor(*sizep);
533ab3185d1SJeff Roberson #endif
534ab3185d1SJeff Roberson 
535ab3185d1SJeff Roberson 	return (0);
536ab3185d1SJeff Roberson }
537ab3185d1SJeff Roberson #endif
538ab3185d1SJeff Roberson 
539ab3185d1SJeff Roberson /*
540ab3185d1SJeff Roberson  *	malloc:
541ab3185d1SJeff Roberson  *
542ab3185d1SJeff Roberson  *	Allocate a block of memory.
543ab3185d1SJeff Roberson  *
544ab3185d1SJeff Roberson  *	If M_NOWAIT is set, this routine will not block and return NULL if
545ab3185d1SJeff Roberson  *	the allocation fails.
546ab3185d1SJeff Roberson  */
547ab3185d1SJeff Roberson void *
548bd555da9SConrad Meyer malloc(size_t size, struct malloc_type *mtp, int flags)
549ab3185d1SJeff Roberson {
550ab3185d1SJeff Roberson 	int indx;
551ab3185d1SJeff Roberson 	caddr_t va;
552ab3185d1SJeff Roberson 	uma_zone_t zone;
553ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
554ab3185d1SJeff Roberson 	unsigned long osize = size;
555ab3185d1SJeff Roberson #endif
556ab3185d1SJeff Roberson 
557ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
558ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
559ab3185d1SJeff Roberson 		return (va);
560847a2a17SPawel Jakub Dawidek #endif
561847a2a17SPawel Jakub Dawidek 
5627001d850SXin LI 	if (size <= kmem_zmax) {
5636f267175SJeff Roberson 		if (size & KMEM_ZMASK)
5646f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
5656f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
566*c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
5676f267175SJeff Roberson #ifdef MALLOC_PROFILE
5686f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
5696f267175SJeff Roberson #endif
5708355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
5714362fadaSBrian Feldman 		if (va != NULL)
572e20a199fSJeff Roberson 			size = zone->uz_size;
57363a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
5748355f576SJeff Roberson 	} else {
5756f267175SJeff Roberson 		size = roundup(size, PAGE_SIZE);
5768355f576SJeff Roberson 		zone = NULL;
5778355f576SJeff Roberson 		va = uma_large_malloc(size, flags);
57863a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
579df8bae1dSRodney W. Grimes 	}
5801282e9acSPoul-Henning Kamp 	if (flags & M_WAITOK)
581a163d034SWarner Losh 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
5821282e9acSPoul-Henning Kamp 	else if (va == NULL)
5831fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
584ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
585ab3185d1SJeff Roberson 	if (va != NULL)
586ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
5874db4f5c8SPoul-Henning Kamp #endif
588ab3185d1SJeff Roberson 	return ((void *) va);
589ab3185d1SJeff Roberson }
590ab3185d1SJeff Roberson 
591ab3185d1SJeff Roberson void *
592bd555da9SConrad Meyer malloc_domain(size_t size, struct malloc_type *mtp, int domain,
593ab3185d1SJeff Roberson     int flags)
594ab3185d1SJeff Roberson {
595ab3185d1SJeff Roberson 	int indx;
596ab3185d1SJeff Roberson 	caddr_t va;
597ab3185d1SJeff Roberson 	uma_zone_t zone;
598ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
599ab3185d1SJeff Roberson 	unsigned long osize = size;
600ab3185d1SJeff Roberson #endif
601ab3185d1SJeff Roberson 
602ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
603ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
604ab3185d1SJeff Roberson 		return (va);
605ab3185d1SJeff Roberson #endif
606ab3185d1SJeff Roberson 	if (size <= kmem_zmax) {
607ab3185d1SJeff Roberson 		if (size & KMEM_ZMASK)
608ab3185d1SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
609ab3185d1SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
610*c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
611ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
612ab3185d1SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
613ab3185d1SJeff Roberson #endif
614ab3185d1SJeff Roberson 		va = uma_zalloc_domain(zone, NULL, domain, flags);
615ab3185d1SJeff Roberson 		if (va != NULL)
616ab3185d1SJeff Roberson 			size = zone->uz_size;
617ab3185d1SJeff Roberson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
618ab3185d1SJeff Roberson 	} else {
619ab3185d1SJeff Roberson 		size = roundup(size, PAGE_SIZE);
620ab3185d1SJeff Roberson 		zone = NULL;
621ab3185d1SJeff Roberson 		va = uma_large_malloc_domain(size, domain, flags);
622ab3185d1SJeff Roberson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
623ab3185d1SJeff Roberson 	}
624ab3185d1SJeff Roberson 	if (flags & M_WAITOK)
625ab3185d1SJeff Roberson 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
626ab3185d1SJeff Roberson 	else if (va == NULL)
627ab3185d1SJeff Roberson 		t_malloc_fail = time_uptime;
628847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
629847a2a17SPawel Jakub Dawidek 	if (va != NULL)
630847a2a17SPawel Jakub Dawidek 		va = redzone_setup(va, osize);
631847a2a17SPawel Jakub Dawidek #endif
632df8bae1dSRodney W. Grimes 	return ((void *) va);
633df8bae1dSRodney W. Grimes }
634df8bae1dSRodney W. Grimes 
635fd91e076SKristof Provost void *
636fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
637fd91e076SKristof Provost {
638fd91e076SKristof Provost 
639c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
640c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
641fd91e076SKristof Provost 
642fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
643fd91e076SKristof Provost }
644fd91e076SKristof Provost 
645ab3185d1SJeff Roberson #ifdef INVARIANTS
646ab3185d1SJeff Roberson static void
647ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
648ab3185d1SJeff Roberson {
649ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
650ab3185d1SJeff Roberson 
651ab3185d1SJeff Roberson 	/*
652ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
653ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
654ab3185d1SJeff Roberson 	 * have stepped on it later.
655ab3185d1SJeff Roberson 	 *
656ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
657ab3185d1SJeff Roberson 	 * 64 bit machines
658ab3185d1SJeff Roberson 	 */
659ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
660ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
661ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
662ab3185d1SJeff Roberson 	*mtpp = mtp;
663ab3185d1SJeff Roberson }
664ab3185d1SJeff Roberson #endif
665ab3185d1SJeff Roberson 
666ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
667ab3185d1SJeff Roberson static int
668ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
669ab3185d1SJeff Roberson {
670ab3185d1SJeff Roberson 	void *addr;
671ab3185d1SJeff Roberson 
672ab3185d1SJeff Roberson 	addr = *addrp;
673ab3185d1SJeff Roberson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
674ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
675ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
676ab3185d1SJeff Roberson 
677ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
678ab3185d1SJeff Roberson 	if (addr == NULL)
679ab3185d1SJeff Roberson 		return (EJUSTRETURN);
680ab3185d1SJeff Roberson 
681ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
682ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
683ab3185d1SJeff Roberson 		memguard_free(addr);
684ab3185d1SJeff Roberson 		return (EJUSTRETURN);
685ab3185d1SJeff Roberson 	}
686ab3185d1SJeff Roberson #endif
687ab3185d1SJeff Roberson 
688ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
689ab3185d1SJeff Roberson 	redzone_check(addr);
690ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
691ab3185d1SJeff Roberson #endif
692ab3185d1SJeff Roberson 
693ab3185d1SJeff Roberson 	return (0);
694ab3185d1SJeff Roberson }
695ab3185d1SJeff Roberson #endif
696ab3185d1SJeff Roberson 
697fd91e076SKristof Provost /*
6981c7c3c6aSMatthew Dillon  *	free:
6991c7c3c6aSMatthew Dillon  *
700df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
7011c7c3c6aSMatthew Dillon  *
7021c7c3c6aSMatthew Dillon  *	This routine may not block.
703df8bae1dSRodney W. Grimes  */
704df8bae1dSRodney W. Grimes void
70563a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
706df8bae1dSRodney W. Grimes {
70799571dc3SJeff Roberson 	uma_slab_t slab;
70899571dc3SJeff Roberson 	u_long size;
709254c6cb3SPoul-Henning Kamp 
710ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
711ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
712ab3185d1SJeff Roberson 		return;
713ab3185d1SJeff Roberson #endif
71444a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
71544a8ff31SArchie Cobbs 	if (addr == NULL)
71644a8ff31SArchie Cobbs 		return;
71744a8ff31SArchie Cobbs 
71899571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
7198355f576SJeff Roberson 	if (slab == NULL)
7206f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
72199571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
72299571dc3SJeff Roberson 
7238355f576SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
724099a0e58SBosko Milekic 		size = slab->us_keg->uk_size;
7258f70816cSJeff Roberson #ifdef INVARIANTS
726ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
7278f70816cSJeff Roberson #endif
728099a0e58SBosko Milekic 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
72914bf02f8SJohn Dyson 	} else {
7308355f576SJeff Roberson 		size = slab->us_size;
7318355f576SJeff Roberson 		uma_large_free(slab);
73214bf02f8SJohn Dyson 	}
73363a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
734df8bae1dSRodney W. Grimes }
735df8bae1dSRodney W. Grimes 
736ab3185d1SJeff Roberson void
737ab3185d1SJeff Roberson free_domain(void *addr, struct malloc_type *mtp)
738ab3185d1SJeff Roberson {
739ab3185d1SJeff Roberson 	uma_slab_t slab;
740ab3185d1SJeff Roberson 	u_long size;
741ab3185d1SJeff Roberson 
742ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
743ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
744ab3185d1SJeff Roberson 		return;
745ab3185d1SJeff Roberson #endif
746ab3185d1SJeff Roberson 
747ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
748ab3185d1SJeff Roberson 	if (addr == NULL)
749ab3185d1SJeff Roberson 		return;
750ab3185d1SJeff Roberson 
751ab3185d1SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
752ab3185d1SJeff Roberson 	if (slab == NULL)
753ab3185d1SJeff Roberson 		panic("free_domain: address %p(%p) has not been allocated.\n",
754ab3185d1SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
755ab3185d1SJeff Roberson 
756ab3185d1SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
757ab3185d1SJeff Roberson 		size = slab->us_keg->uk_size;
758ab3185d1SJeff Roberson #ifdef INVARIANTS
759ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
760ab3185d1SJeff Roberson #endif
761ab3185d1SJeff Roberson 		uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
762ab3185d1SJeff Roberson 		    addr, slab);
763ab3185d1SJeff Roberson 	} else {
764ab3185d1SJeff Roberson 		size = slab->us_size;
765ab3185d1SJeff Roberson 		uma_large_free(slab);
766ab3185d1SJeff Roberson 	}
767ab3185d1SJeff Roberson 	malloc_type_freed(mtp, size);
768ab3185d1SJeff Roberson }
769ab3185d1SJeff Roberson 
770df8bae1dSRodney W. Grimes /*
77144a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
77244a8ff31SArchie Cobbs  */
77344a8ff31SArchie Cobbs void *
774bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
77544a8ff31SArchie Cobbs {
7768355f576SJeff Roberson 	uma_slab_t slab;
77744a8ff31SArchie Cobbs 	unsigned long alloc;
77844a8ff31SArchie Cobbs 	void *newaddr;
77944a8ff31SArchie Cobbs 
780bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
781bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
782d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
7831067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
7841067a2baSJonathan T. Looney 
78544a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
78644a8ff31SArchie Cobbs 	if (addr == NULL)
78763a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
78863a7e0a3SRobert Watson 
78963a7e0a3SRobert Watson 	/*
79063a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
79163a7e0a3SRobert Watson 	 * per-CPU stats.
79263a7e0a3SRobert Watson 	 */
79344a8ff31SArchie Cobbs 
794e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
7956d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
7966d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
797e4eb384bSBosko Milekic #endif
798e4eb384bSBosko Milekic 
799847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
800847a2a17SPawel Jakub Dawidek 	slab = NULL;
801847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
802847a2a17SPawel Jakub Dawidek #else
80399571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
8048355f576SJeff Roberson 
80544a8ff31SArchie Cobbs 	/* Sanity check */
8068355f576SJeff Roberson 	KASSERT(slab != NULL,
80744a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
80844a8ff31SArchie Cobbs 
80944a8ff31SArchie Cobbs 	/* Get the size of the original block */
810619f2841SPawel Jakub Dawidek 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
811099a0e58SBosko Milekic 		alloc = slab->us_keg->uk_size;
8128355f576SJeff Roberson 	else
8138355f576SJeff Roberson 		alloc = slab->us_size;
81444a8ff31SArchie Cobbs 
81544a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
81644a8ff31SArchie Cobbs 	if (size <= alloc
81744a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
81844a8ff31SArchie Cobbs 		return (addr);
819847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
82044a8ff31SArchie Cobbs 
82144a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
82263a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
82344a8ff31SArchie Cobbs 		return (NULL);
82444a8ff31SArchie Cobbs 
82544a8ff31SArchie Cobbs 	/* Copy over original contents */
82644a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
82763a7e0a3SRobert Watson 	free(addr, mtp);
82844a8ff31SArchie Cobbs 	return (newaddr);
82944a8ff31SArchie Cobbs }
83044a8ff31SArchie Cobbs 
83144a8ff31SArchie Cobbs /*
83244a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
83344a8ff31SArchie Cobbs  */
83444a8ff31SArchie Cobbs void *
835bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
83644a8ff31SArchie Cobbs {
83744a8ff31SArchie Cobbs 	void *mem;
83844a8ff31SArchie Cobbs 
83963a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
84063a7e0a3SRobert Watson 		free(addr, mtp);
84144a8ff31SArchie Cobbs 	return (mem);
84244a8ff31SArchie Cobbs }
84344a8ff31SArchie Cobbs 
844f9d498adSDimitry Andric #ifndef __sparc64__
845c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
846f9d498adSDimitry Andric #endif
847c70af487SAlan Cox 
8485df87b21SJeff Roberson /*
849c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
8505df87b21SJeff Roberson  */
8515df87b21SJeff Roberson void
8525df87b21SJeff Roberson kmeminit(void)
8535df87b21SJeff Roberson {
854af3b2549SHans Petter Selasky 	u_long mem_size;
855af3b2549SHans Petter Selasky 	u_long tmp;
85669ef67f9SJason Evans 
857af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
858af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
859af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
860af3b2549SHans Petter Selasky #endif
861af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
862af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
863af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
864af3b2549SHans Petter Selasky #endif
865af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
866af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
867af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
868af3b2549SHans Petter Selasky #endif
8698a58a9f6SJohn Dyson 	/*
870c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
871c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
872c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
873c70af487SAlan Cox 	 * specifically,
8748a58a9f6SJohn Dyson 	 *
875c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
876c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
877c70af487SAlan Cox 	 *
878c70af487SAlan Cox 	 * Every architecture must define an integral value for
879c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
880c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
881c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
882c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
883c70af487SAlan Cox 	 * a given architecture.
8848a58a9f6SJohn Dyson 	 */
88544f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
8867c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
8877c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
8888a58a9f6SJohn Dyson 
889c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
890c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
891c70af487SAlan Cox 
892af3b2549SHans Petter Selasky 	/*
893af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
894af3b2549SHans Petter Selasky 	 * variable:
895af3b2549SHans Petter Selasky 	 */
896af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
897479439b4SDag-Erling Smørgrav 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
8988a58a9f6SJohn Dyson 
899c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
9000e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
901479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
902479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
903af3b2549SHans Petter Selasky 	}
9048a58a9f6SJohn Dyson 
90527b8623fSDavid Greenman 	/*
906af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
907c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
908c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
909c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
910c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
91127b8623fSDavid Greenman 	 */
912c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
913c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
9148a58a9f6SJohn Dyson 
915e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
916e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
917f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
918e3813573SMatthew D Fleming #else
919e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
920e3813573SMatthew D Fleming #endif
9212e47807cSJeff Roberson 	uma_set_limit(tmp);
9228355f576SJeff Roberson 
923e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
924e4eb384bSBosko Milekic 	/*
925e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
926e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
927e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
928e4eb384bSBosko Milekic 	 */
9292e47807cSJeff Roberson 	memguard_init(kernel_arena);
930e4eb384bSBosko Milekic #endif
9315df87b21SJeff Roberson }
9325df87b21SJeff Roberson 
9335df87b21SJeff Roberson /*
9345df87b21SJeff Roberson  * Initialize the kernel memory allocator
9355df87b21SJeff Roberson  */
9365df87b21SJeff Roberson /* ARGSUSED*/
9375df87b21SJeff Roberson static void
9385df87b21SJeff Roberson mallocinit(void *dummy)
9395df87b21SJeff Roberson {
9405df87b21SJeff Roberson 	int i;
9415df87b21SJeff Roberson 	uint8_t indx;
9425df87b21SJeff Roberson 
9435df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
9445df87b21SJeff Roberson 
9455df87b21SJeff Roberson 	kmeminit();
946e4eb384bSBosko Milekic 
9477001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
9487001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
9497001d850SXin LI 
95063a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
95163a7e0a3SRobert Watson #ifdef INVARIANTS
95263a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
95363a7e0a3SRobert Watson #else
95463a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
95563a7e0a3SRobert Watson #endif
95663a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
9576f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
9586f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
9596f267175SJeff Roberson 		char *name = kmemzones[indx].kz_name;
960d7854da1SMatthew D Fleming 		int subzone;
9618355f576SJeff Roberson 
962d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
963d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
964d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
9658efc4effSJeff Roberson #ifdef INVARIANTS
9668f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
9678efc4effSJeff Roberson #else
9688efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
9698efc4effSJeff Roberson #endif
9708efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
971d7854da1SMatthew D Fleming 		}
9728355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
9736f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
9748355f576SJeff Roberson 
975df8bae1dSRodney W. Grimes 	}
976254c6cb3SPoul-Henning Kamp }
977af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
978254c6cb3SPoul-Henning Kamp 
979db669378SPeter Wemm void
98087efd4d5SRobert Watson malloc_init(void *data)
981254c6cb3SPoul-Henning Kamp {
98263a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
98363a7e0a3SRobert Watson 	struct malloc_type *mtp;
98463a7e0a3SRobert Watson 
98544f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
98663a7e0a3SRobert Watson 
98763a7e0a3SRobert Watson 	mtp = data;
988f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
989f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
990bb1c7df8SRobert Watson 
99163a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
99263a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
993*c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
994254c6cb3SPoul-Henning Kamp 
9956f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
99663a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
99763a7e0a3SRobert Watson 	kmemstatistics = mtp;
998cd814b26SRobert Watson 	kmemcount++;
9996f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1000df8bae1dSRodney W. Grimes }
1001db669378SPeter Wemm 
1002db669378SPeter Wemm void
100387efd4d5SRobert Watson malloc_uninit(void *data)
1004db669378SPeter Wemm {
100563a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
10062a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
100763a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
100845d48bdaSPaul Saab 	uma_slab_t slab;
10092a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
10102a143d5bSPawel Jakub Dawidek 	int i;
1011db669378SPeter Wemm 
101263a7e0a3SRobert Watson 	mtp = data;
1013bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
1014bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
101563a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1016bb1c7df8SRobert Watson 
10176f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
101863a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
101963a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
102063a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
102163a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
102263a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1023f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
102463a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1025f121baaaSBrian Somers 				break;
1026db669378SPeter Wemm 			}
1027f121baaaSBrian Somers 		}
1028f121baaaSBrian Somers 		KASSERT(temp,
1029f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
103063a7e0a3SRobert Watson 	} else
103163a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1032cd814b26SRobert Watson 	kmemcount--;
10336f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
10342a143d5bSPawel Jakub Dawidek 
10352a143d5bSPawel Jakub Dawidek 	/*
10362a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
10372a143d5bSPawel Jakub Dawidek 	 */
10382a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
10392a143d5bSPawel Jakub Dawidek 	for (i = 0; i < MAXCPU; i++) {
10402a143d5bSPawel Jakub Dawidek 		mtsp = &mtip->mti_stats[i];
10412a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
10422a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
10432a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
10442a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
10452a143d5bSPawel Jakub Dawidek 	}
10462a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
10472a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
10482a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
10492a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
10502a143d5bSPawel Jakub Dawidek 	}
10512a143d5bSPawel Jakub Dawidek 
105245d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
105345d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
1054db669378SPeter Wemm }
10556f267175SJeff Roberson 
1056d362c40dSPawel Jakub Dawidek struct malloc_type *
1057d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1058d362c40dSPawel Jakub Dawidek {
1059d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1060d362c40dSPawel Jakub Dawidek 
1061d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1062d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1063d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1064d362c40dSPawel Jakub Dawidek 			return (mtp);
1065d362c40dSPawel Jakub Dawidek 	}
1066d362c40dSPawel Jakub Dawidek 	return (NULL);
1067d362c40dSPawel Jakub Dawidek }
1068d362c40dSPawel Jakub Dawidek 
10696f267175SJeff Roberson static int
1070cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1071cd814b26SRobert Watson {
1072cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1073cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
1074cd814b26SRobert Watson 	struct malloc_type_header mth;
1075cd814b26SRobert Watson 	struct malloc_type *mtp;
10764e657159SMatthew D Fleming 	int error, i;
1077cd814b26SRobert Watson 	struct sbuf sbuf;
1078cd814b26SRobert Watson 
107900f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
108000f0e671SMatthew D Fleming 	if (error != 0)
108100f0e671SMatthew D Fleming 		return (error);
10824e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
10831eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1084cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1085cd814b26SRobert Watson 
1086cd814b26SRobert Watson 	/*
1087cd814b26SRobert Watson 	 * Insert stream header.
1088cd814b26SRobert Watson 	 */
1089cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1090cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1091cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1092cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
10934e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1094cd814b26SRobert Watson 
1095cd814b26SRobert Watson 	/*
1096cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1097cd814b26SRobert Watson 	 */
1098cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1099cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1100cd814b26SRobert Watson 
1101cd814b26SRobert Watson 		/*
1102cd814b26SRobert Watson 		 * Insert type header.
1103cd814b26SRobert Watson 		 */
1104cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1105cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
11064e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1107cd814b26SRobert Watson 
1108cd814b26SRobert Watson 		/*
1109cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1110cd814b26SRobert Watson 		 */
1111cd814b26SRobert Watson 		for (i = 0; i < MAXCPU; i++) {
11124e657159SMatthew D Fleming 			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
11134e657159SMatthew D Fleming 			    sizeof(mtip->mti_stats[i]));
1114cd814b26SRobert Watson 		}
1115cd814b26SRobert Watson 	}
1116cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
11174e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1118cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1119cd814b26SRobert Watson 	return (error);
1120cd814b26SRobert Watson }
1121cd814b26SRobert Watson 
1122cd814b26SRobert Watson SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1123cd814b26SRobert Watson     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1124cd814b26SRobert Watson     "Return malloc types");
1125cd814b26SRobert Watson 
1126cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1127cd814b26SRobert Watson     "Count of kernel malloc types");
1128cd814b26SRobert Watson 
112991dd776cSJohn Birrell void
113091dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
113191dd776cSJohn Birrell {
113291dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
113391dd776cSJohn Birrell 	int count, i;
113491dd776cSJohn Birrell 	size_t buflen;
113591dd776cSJohn Birrell 
113691dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
113791dd776cSJohn Birrell restart:
113891dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
113991dd776cSJohn Birrell 	count = kmemcount;
114091dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
114191dd776cSJohn Birrell 
114291dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
114391dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
114491dd776cSJohn Birrell 
114591dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
114691dd776cSJohn Birrell 
114791dd776cSJohn Birrell 	if (count < kmemcount) {
114891dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
114991dd776cSJohn Birrell 		goto restart;
115091dd776cSJohn Birrell 	}
115191dd776cSJohn Birrell 
115291dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
115391dd776cSJohn Birrell 		bufmtp[i] = mtp;
115491dd776cSJohn Birrell 
115591dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
115691dd776cSJohn Birrell 
115791dd776cSJohn Birrell 	for (i = 0; i < count; i++)
115891dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
115991dd776cSJohn Birrell 
116091dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
116191dd776cSJohn Birrell }
116291dd776cSJohn Birrell 
1163909ed16cSRobert Watson #ifdef DDB
1164909ed16cSRobert Watson DB_SHOW_COMMAND(malloc, db_show_malloc)
1165909ed16cSRobert Watson {
1166909ed16cSRobert Watson 	struct malloc_type_internal *mtip;
1167909ed16cSRobert Watson 	struct malloc_type *mtp;
116860ae52f7SEd Schouten 	uint64_t allocs, frees;
116960ae52f7SEd Schouten 	uint64_t alloced, freed;
1170909ed16cSRobert Watson 	int i;
1171909ed16cSRobert Watson 
117224076d13SRobert Watson 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
117324076d13SRobert Watson 	    "Requests");
1174909ed16cSRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1175909ed16cSRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1176909ed16cSRobert Watson 		allocs = 0;
1177909ed16cSRobert Watson 		frees = 0;
117824076d13SRobert Watson 		alloced = 0;
117924076d13SRobert Watson 		freed = 0;
1180909ed16cSRobert Watson 		for (i = 0; i < MAXCPU; i++) {
1181909ed16cSRobert Watson 			allocs += mtip->mti_stats[i].mts_numallocs;
1182909ed16cSRobert Watson 			frees += mtip->mti_stats[i].mts_numfrees;
118324076d13SRobert Watson 			alloced += mtip->mti_stats[i].mts_memalloced;
118424076d13SRobert Watson 			freed += mtip->mti_stats[i].mts_memfreed;
1185909ed16cSRobert Watson 		}
118624076d13SRobert Watson 		db_printf("%18s %12ju %12juK %12ju\n",
118724076d13SRobert Watson 		    mtp->ks_shortdesc, allocs - frees,
118824076d13SRobert Watson 		    (alloced - freed + 1023) / 1024, allocs);
1189687c94aaSJohn Baldwin 		if (db_pager_quit)
1190687c94aaSJohn Baldwin 			break;
1191909ed16cSRobert Watson 	}
1192909ed16cSRobert Watson }
1193d7854da1SMatthew D Fleming 
1194d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1195d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1196d7854da1SMatthew D Fleming {
1197d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1198d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1199d7854da1SMatthew D Fleming 	u_int subzone;
1200d7854da1SMatthew D Fleming 
1201d7854da1SMatthew D Fleming 	if (!have_addr) {
1202d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1203d7854da1SMatthew D Fleming 		return;
1204d7854da1SMatthew D Fleming 	}
1205d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1206d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1207d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1208d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1209d7854da1SMatthew D Fleming 		return;
1210d7854da1SMatthew D Fleming 	}
1211d7854da1SMatthew D Fleming 
1212d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1213d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1214d7854da1SMatthew D Fleming 
1215d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1216d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1217d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1218d7854da1SMatthew D Fleming 			continue;
1219d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1220687c94aaSJohn Baldwin 		if (db_pager_quit)
1221687c94aaSJohn Baldwin 			break;
1222d7854da1SMatthew D Fleming 	}
1223d7854da1SMatthew D Fleming }
1224d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1225d7854da1SMatthew D Fleming #endif /* DDB */
1226909ed16cSRobert Watson 
12275e914b96SJeff Roberson #ifdef MALLOC_PROFILE
12285e914b96SJeff Roberson 
12295e914b96SJeff Roberson static int
12305e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
12315e914b96SJeff Roberson {
123263a7e0a3SRobert Watson 	struct sbuf sbuf;
12335e914b96SJeff Roberson 	uint64_t count;
12345e914b96SJeff Roberson 	uint64_t waste;
12355e914b96SJeff Roberson 	uint64_t mem;
12365e914b96SJeff Roberson 	int error;
12375e914b96SJeff Roberson 	int rsize;
12385e914b96SJeff Roberson 	int size;
12395e914b96SJeff Roberson 	int i;
12405e914b96SJeff Roberson 
12415e914b96SJeff Roberson 	waste = 0;
12425e914b96SJeff Roberson 	mem = 0;
12435e914b96SJeff Roberson 
124400f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
124500f0e671SMatthew D Fleming 	if (error != 0)
124600f0e671SMatthew D Fleming 		return (error);
12474e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
124863a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12495e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
12505e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
12515e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
12525e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
12535e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
12545e914b96SJeff Roberson 
125563a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
125663a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
12575e914b96SJeff Roberson 
12585e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
12595e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
12605e914b96SJeff Roberson 		mem += (rsize * count);
12615e914b96SJeff Roberson 	}
126263a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
12635e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
12645e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
12654e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
126663a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
12675e914b96SJeff Roberson 	return (error);
12685e914b96SJeff Roberson }
12695e914b96SJeff Roberson 
12705e914b96SJeff Roberson SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
12715e914b96SJeff Roberson     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
12725e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1273