xref: /freebsd/sys/kern/kern_malloc.c (revision f0c90a0931412a94972c264c9a46cfc9354db252)
19454b2d8SWarner Losh /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1991, 1993
563a7e0a3SRobert Watson  *	The Regents of the University of California.
6bb1c7df8SRobert Watson  * Copyright (c) 2005-2009 Robert N. M. Watson
7fd91e076SKristof Provost  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
863a7e0a3SRobert Watson  * All rights reserved.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
1869a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
34df8bae1dSRodney W. Grimes  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
370ce3f16dSRobert Watson /*
380ce3f16dSRobert Watson  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
390ce3f16dSRobert Watson  * based on memory types.  Back end is implemented using the UMA(9) zone
400ce3f16dSRobert Watson  * allocator.  A set of fixed-size buckets are used for smaller allocations,
410ce3f16dSRobert Watson  * and a special UMA allocation interface is used for larger allocations.
420ce3f16dSRobert Watson  * Callers declare memory types, and statistics are maintained independently
430ce3f16dSRobert Watson  * for each memory type.  Statistics are maintained per-CPU for performance
440ce3f16dSRobert Watson  * reasons.  See malloc(9) and comments in malloc.h for a detailed
450ce3f16dSRobert Watson  * description.
460ce3f16dSRobert Watson  */
470ce3f16dSRobert Watson 
48677b542eSDavid E. O'Brien #include <sys/cdefs.h>
49677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
50677b542eSDavid E. O'Brien 
51909ed16cSRobert Watson #include "opt_ddb.h"
528a58a9f6SJohn Dyson #include "opt_vm.h"
538a58a9f6SJohn Dyson 
54df8bae1dSRodney W. Grimes #include <sys/param.h>
5526f9a767SRodney W. Grimes #include <sys/systm.h>
562d50560aSMarcel Moolenaar #include <sys/kdb.h>
57df8bae1dSRodney W. Grimes #include <sys/kernel.h>
58fb919e4dSMark Murray #include <sys/lock.h>
59df8bae1dSRodney W. Grimes #include <sys/malloc.h>
60eec258d2SJohn Baldwin #include <sys/mutex.h>
61efeaf95aSDavid Greenman #include <sys/vmmeter.h>
62a448b62aSJake Burkholder #include <sys/proc.h>
636d6a03d7SJeff Roberson #include <sys/queue.h>
6463a7e0a3SRobert Watson #include <sys/sbuf.h>
659afff6b1SMateusz Guzik #include <sys/smp.h>
666f267175SJeff Roberson #include <sys/sysctl.h>
671fb14a47SPoul-Henning Kamp #include <sys/time.h>
685df87b21SJeff Roberson #include <sys/vmem.h>
694b25d1f2SGleb Smirnoff #ifdef EPOCH_TRACE
704b25d1f2SGleb Smirnoff #include <sys/epoch.h>
714b25d1f2SGleb Smirnoff #endif
729a02e8c6SJason Evans 
73df8bae1dSRodney W. Grimes #include <vm/vm.h>
7499571dc3SJeff Roberson #include <vm/pmap.h>
759978bd99SMark Johnston #include <vm/vm_domainset.h>
765df87b21SJeff Roberson #include <vm/vm_pageout.h>
77efeaf95aSDavid Greenman #include <vm/vm_param.h>
78df8bae1dSRodney W. Grimes #include <vm/vm_kern.h>
79efeaf95aSDavid Greenman #include <vm/vm_extern.h>
803075778bSJohn Dyson #include <vm/vm_map.h>
8199571dc3SJeff Roberson #include <vm/vm_page.h>
826d6a03d7SJeff Roberson #include <vm/vm_phys.h>
836d6a03d7SJeff Roberson #include <vm/vm_pagequeue.h>
848355f576SJeff Roberson #include <vm/uma.h>
858355f576SJeff Roberson #include <vm/uma_int.h>
868efc4effSJeff Roberson #include <vm/uma_dbg.h>
87df8bae1dSRodney W. Grimes 
88e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
89e4eb384bSBosko Milekic #include <vm/memguard.h>
90e4eb384bSBosko Milekic #endif
91847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
92847a2a17SPawel Jakub Dawidek #include <vm/redzone.h>
93847a2a17SPawel Jakub Dawidek #endif
94e4eb384bSBosko Milekic 
95984982d6SPoul-Henning Kamp #if defined(INVARIANTS) && defined(__i386__)
96984982d6SPoul-Henning Kamp #include <machine/cpu.h>
97984982d6SPoul-Henning Kamp #endif
98984982d6SPoul-Henning Kamp 
99909ed16cSRobert Watson #include <ddb/ddb.h>
100909ed16cSRobert Watson 
10191dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
10291dd776cSJohn Birrell #include <sys/dtrace_bsd.h>
10391dd776cSJohn Birrell 
1047cd79421SMateusz Guzik bool	__read_frequently			dtrace_malloc_enabled;
1057cd79421SMateusz Guzik dtrace_malloc_probe_func_t __read_mostly	dtrace_malloc_probe;
10691dd776cSJohn Birrell #endif
10791dd776cSJohn Birrell 
108ab3185d1SJeff Roberson #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
109ab3185d1SJeff Roberson     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
110ab3185d1SJeff Roberson #define	MALLOC_DEBUG	1
111ab3185d1SJeff Roberson #endif
112ab3185d1SJeff Roberson 
11344a8ff31SArchie Cobbs /*
11444a8ff31SArchie Cobbs  * When realloc() is called, if the new size is sufficiently smaller than
11544a8ff31SArchie Cobbs  * the old size, realloc() will allocate a new, smaller block to avoid
11644a8ff31SArchie Cobbs  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
11744a8ff31SArchie Cobbs  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
11844a8ff31SArchie Cobbs  */
11944a8ff31SArchie Cobbs #ifndef REALLOC_FRACTION
12044a8ff31SArchie Cobbs #define	REALLOC_FRACTION	1	/* new block if <= half the size */
12144a8ff31SArchie Cobbs #endif
12244a8ff31SArchie Cobbs 
1230ce3f16dSRobert Watson /*
1240ce3f16dSRobert Watson  * Centrally define some common malloc types.
1250ce3f16dSRobert Watson  */
1263b6fb885SPoul-Henning Kamp MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
1279ef246c6SBruce Evans MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
1289ef246c6SBruce Evans MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
1299ef246c6SBruce Evans 
130db669378SPeter Wemm static struct malloc_type *kmemstatistics;
131cd814b26SRobert Watson static int kmemcount;
1321f6889a1SMatthew Dillon 
1338355f576SJeff Roberson #define KMEM_ZSHIFT	4
1348355f576SJeff Roberson #define KMEM_ZBASE	16
1358355f576SJeff Roberson #define KMEM_ZMASK	(KMEM_ZBASE - 1)
1368355f576SJeff Roberson 
137bda06553SXin LI #define KMEM_ZMAX	65536
1388355f576SJeff Roberson #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
13960ae52f7SEd Schouten static uint8_t kmemsize[KMEM_ZSIZE + 1];
1406f267175SJeff Roberson 
141d7854da1SMatthew D Fleming #ifndef MALLOC_DEBUG_MAXZONES
142d7854da1SMatthew D Fleming #define	MALLOC_DEBUG_MAXZONES	1
143d7854da1SMatthew D Fleming #endif
144d7854da1SMatthew D Fleming static int numzones = MALLOC_DEBUG_MAXZONES;
145d7854da1SMatthew D Fleming 
1460ce3f16dSRobert Watson /*
1470ce3f16dSRobert Watson  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
1480ce3f16dSRobert Watson  * of various sizes.
1490ce3f16dSRobert Watson  *
150828afddaSMateusz Guzik  * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
151828afddaSMateusz Guzik  *
1520ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1530ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1540ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1550ce3f16dSRobert Watson  */
1568355f576SJeff Roberson struct {
1576f267175SJeff Roberson 	int kz_size;
158eaa17d42SRyan Libby 	const char *kz_name;
159d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1606f267175SJeff Roberson } kmemzones[] = {
161e1b6a7f8SMateusz Guzik 	{16, "malloc-16", },
162e1b6a7f8SMateusz Guzik 	{32, "malloc-32", },
163e1b6a7f8SMateusz Guzik 	{64, "malloc-64", },
164e1b6a7f8SMateusz Guzik 	{128, "malloc-128", },
165e1b6a7f8SMateusz Guzik 	{256, "malloc-256", },
166*f0c90a09SMateusz Guzik 	{384, "malloc-384", },
167e1b6a7f8SMateusz Guzik 	{512, "malloc-512", },
168e1b6a7f8SMateusz Guzik 	{1024, "malloc-1024", },
169e1b6a7f8SMateusz Guzik 	{2048, "malloc-2048", },
170e1b6a7f8SMateusz Guzik 	{4096, "malloc-4096", },
171e1b6a7f8SMateusz Guzik 	{8192, "malloc-8192", },
172e1b6a7f8SMateusz Guzik 	{16384, "malloc-16384", },
173e1b6a7f8SMateusz Guzik 	{32768, "malloc-32768", },
174e1b6a7f8SMateusz Guzik 	{65536, "malloc-65536", },
1758355f576SJeff Roberson 	{0, NULL},
1768355f576SJeff Roberson };
1778355f576SJeff Roberson 
178b89eaf4eSAlan Cox u_long vm_kmem_size;
179d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
18084344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1815a34a9f0SJeff Roberson 
1827001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1837001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1847001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1857001d850SXin LI 
186b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
187d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1880e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1890e5179e4SStephane E. Potvin 
190b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
191d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
192479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
193479439b4SDag-Erling Smørgrav 
1944813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
195d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
196479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
197479439b4SDag-Erling Smørgrav 
1987814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
1997814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
2007814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2015df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
2027814c80aSAndriy Gapon 
20395bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
20495bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
20595bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
2065df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
20795bb9d38SAndriy Gapon 
208828afddaSMateusz Guzik static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
209828afddaSMateusz Guzik     "Malloc information");
210828afddaSMateusz Guzik 
211828afddaSMateusz Guzik static u_int vm_malloc_zone_count = nitems(kmemzones);
212828afddaSMateusz Guzik SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
213828afddaSMateusz Guzik     CTLFLAG_RD, &vm_malloc_zone_count, 0,
214828afddaSMateusz Guzik     "Number of malloc zones");
215828afddaSMateusz Guzik 
216828afddaSMateusz Guzik static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
217828afddaSMateusz Guzik SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
218828afddaSMateusz Guzik     CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
219828afddaSMateusz Guzik     sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
220828afddaSMateusz Guzik 
2215a34a9f0SJeff Roberson /*
22299571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2235a34a9f0SJeff Roberson  */
2245a34a9f0SJeff Roberson struct mtx malloc_mtx;
22569ef67f9SJason Evans 
2265e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2275e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2286f267175SJeff Roberson 
2295e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2305e914b96SJeff Roberson #endif
2315e914b96SJeff Roberson 
232cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
233df8bae1dSRodney W. Grimes 
2340ce3f16dSRobert Watson /*
2350ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2360ce3f16dSRobert Watson  */
2371fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2381fb14a47SPoul-Henning Kamp 
239d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2407029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
241d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
242d7854da1SMatthew D Fleming #endif
243d7854da1SMatthew D Fleming 
244eae870cdSRobert Watson /*
2450ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2460ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
247eae870cdSRobert Watson  */
2480ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
249eae870cdSRobert Watson static int malloc_failure_rate;
250eae870cdSRobert Watson static int malloc_nowait_count;
251eae870cdSRobert Watson static int malloc_failure_count;
252af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
253eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
254eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
255eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
256eae870cdSRobert Watson #endif
257eae870cdSRobert Watson 
2587814c80aSAndriy Gapon static int
2597814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2607814c80aSAndriy Gapon {
2617814c80aSAndriy Gapon 	u_long size;
2627814c80aSAndriy Gapon 
2632e47807cSJeff Roberson 	size = uma_size();
2647814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2657814c80aSAndriy Gapon }
2667814c80aSAndriy Gapon 
26795bb9d38SAndriy Gapon static int
26895bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
26995bb9d38SAndriy Gapon {
2702e47807cSJeff Roberson 	u_long size, limit;
27195bb9d38SAndriy Gapon 
2722e47807cSJeff Roberson 	/* The sysctl is unsigned, implement as a saturation value. */
2732e47807cSJeff Roberson 	size = uma_size();
2742e47807cSJeff Roberson 	limit = uma_limit();
2752e47807cSJeff Roberson 	if (size > limit)
2762e47807cSJeff Roberson 		size = 0;
2772e47807cSJeff Roberson 	else
2782e47807cSJeff Roberson 		size = limit - size;
27995bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
28095bb9d38SAndriy Gapon }
28195bb9d38SAndriy Gapon 
282828afddaSMateusz Guzik static int
283828afddaSMateusz Guzik sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
284828afddaSMateusz Guzik {
285828afddaSMateusz Guzik 	int sizes[nitems(kmemzones)];
286828afddaSMateusz Guzik 	int i;
287828afddaSMateusz Guzik 
288828afddaSMateusz Guzik 	for (i = 0; i < nitems(kmemzones); i++) {
289828afddaSMateusz Guzik 		sizes[i] = kmemzones[i].kz_size;
290828afddaSMateusz Guzik 	}
291828afddaSMateusz Guzik 
292828afddaSMateusz Guzik 	return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
293828afddaSMateusz Guzik }
294828afddaSMateusz Guzik 
295d7854da1SMatthew D Fleming /*
296d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
297d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
298d7854da1SMatthew D Fleming  */
299d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
300d7854da1SMatthew D Fleming static void
301d7854da1SMatthew D Fleming tunable_set_numzones(void)
302d7854da1SMatthew D Fleming {
303d7854da1SMatthew D Fleming 
304d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
305d7854da1SMatthew D Fleming 	    &numzones);
306d7854da1SMatthew D Fleming 
307d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
308d7854da1SMatthew D Fleming 	if (numzones <= 0)
309d7854da1SMatthew D Fleming 		numzones = 1;
310d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
311d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
312d7854da1SMatthew D Fleming }
313d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
314af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
315d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
316d7854da1SMatthew D Fleming 
317d7854da1SMatthew D Fleming /*
318d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
319d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
320d7854da1SMatthew D Fleming  */
321d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
322d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
323d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
324d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
325d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
326d7854da1SMatthew D Fleming 
327c9e05ccdSMateusz Guzik static void
328c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
329d7854da1SMatthew D Fleming {
330c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
331c9e05ccdSMateusz Guzik 	const char *desc;
332d7854da1SMatthew D Fleming 	size_t len;
333d7854da1SMatthew D Fleming 	u_int val;
334d7854da1SMatthew D Fleming 
335bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
336c9e05ccdSMateusz Guzik 	desc = mtp->ks_shortdesc;
337d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
338c9e05ccdSMateusz Guzik 		val = 0;
339c9e05ccdSMateusz Guzik 	else
340d7854da1SMatthew D Fleming 		val = desc[zone_offset % len];
341c9e05ccdSMateusz Guzik 	mtip->mti_zone = (val % numzones);
342c9e05ccdSMateusz Guzik }
343c9e05ccdSMateusz Guzik 
344c9e05ccdSMateusz Guzik static inline u_int
345c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
346c9e05ccdSMateusz Guzik {
347c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
348c9e05ccdSMateusz Guzik 
349bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
350c9e05ccdSMateusz Guzik 
351c9e05ccdSMateusz Guzik 	KASSERT(mtip->mti_zone < numzones,
352c9e05ccdSMateusz Guzik 	    ("mti_zone %u out of range %d",
353c9e05ccdSMateusz Guzik 	    mtip->mti_zone, numzones));
354c9e05ccdSMateusz Guzik 	return (mtip->mti_zone);
355d7854da1SMatthew D Fleming }
356d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
357d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
358d7854da1SMatthew D Fleming #else
359c9e05ccdSMateusz Guzik static void
360c9e05ccdSMateusz Guzik mtp_set_subzone(struct malloc_type *mtp)
361c9e05ccdSMateusz Guzik {
362c9e05ccdSMateusz Guzik 	struct malloc_type_internal *mtip;
363c9e05ccdSMateusz Guzik 
364bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
365c9e05ccdSMateusz Guzik 	mtip->mti_zone = 0;
366c9e05ccdSMateusz Guzik }
367c9e05ccdSMateusz Guzik 
368d7854da1SMatthew D Fleming static inline u_int
369c9e05ccdSMateusz Guzik mtp_get_subzone(struct malloc_type *mtp)
370d7854da1SMatthew D Fleming {
371d7854da1SMatthew D Fleming 
372d7854da1SMatthew D Fleming 	return (0);
373d7854da1SMatthew D Fleming }
374d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
375d7854da1SMatthew D Fleming 
3761fb14a47SPoul-Henning Kamp int
3771fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3781fb14a47SPoul-Henning Kamp {
3791fb14a47SPoul-Henning Kamp 
3801fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3811fb14a47SPoul-Henning Kamp }
3821fb14a47SPoul-Henning Kamp 
383df8bae1dSRodney W. Grimes /*
3840ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3850ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3860ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3870ce3f16dSRobert Watson  * statistics.
3884362fadaSBrian Feldman  */
3894362fadaSBrian Feldman static void
39063a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
3914362fadaSBrian Feldman     int zindx)
3924362fadaSBrian Feldman {
39363a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
39463a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
39563a7e0a3SRobert Watson 
39663a7e0a3SRobert Watson 	critical_enter();
397bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
3989afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
39973864adbSPawel Jakub Dawidek 	if (size > 0) {
40063a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
40163a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
40273864adbSPawel Jakub Dawidek 	}
4034362fadaSBrian Feldman 	if (zindx != -1)
40463a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
40591dd776cSJohn Birrell 
40691dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4077cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
40891dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
40991dd776cSJohn Birrell 		if (probe_id != 0)
41091dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
41191dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
41291dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
41391dd776cSJohn Birrell 	}
41491dd776cSJohn Birrell #endif
41591dd776cSJohn Birrell 
41663a7e0a3SRobert Watson 	critical_exit();
4174362fadaSBrian Feldman }
4184362fadaSBrian Feldman 
4194362fadaSBrian Feldman void
42063a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
4214362fadaSBrian Feldman {
42263a7e0a3SRobert Watson 
42373864adbSPawel Jakub Dawidek 	if (size > 0)
42463a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
4254362fadaSBrian Feldman }
4264362fadaSBrian Feldman 
4274362fadaSBrian Feldman /*
4283805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
4290ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
4300ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
4310ce3f16dSRobert Watson  * statistics.
4324362fadaSBrian Feldman  */
4334362fadaSBrian Feldman void
43463a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
4354362fadaSBrian Feldman {
43663a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
43763a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
43863a7e0a3SRobert Watson 
43963a7e0a3SRobert Watson 	critical_enter();
440bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
4419afff6b1SMateusz Guzik 	mtsp = zpcpu_get(mtip->mti_stats);
44263a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
44363a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
44491dd776cSJohn Birrell 
44591dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
4467cd79421SMateusz Guzik 	if (__predict_false(dtrace_malloc_enabled)) {
44791dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
44891dd776cSJohn Birrell 		if (probe_id != 0)
44991dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
45091dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
45191dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
45291dd776cSJohn Birrell 	}
45391dd776cSJohn Birrell #endif
45491dd776cSJohn Birrell 
45563a7e0a3SRobert Watson 	critical_exit();
4564362fadaSBrian Feldman }
4574362fadaSBrian Feldman 
4584362fadaSBrian Feldman /*
459f346986bSAlan Cox  *	contigmalloc:
460f346986bSAlan Cox  *
461f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
462f346986bSAlan Cox  *
463f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
464f346986bSAlan Cox  *	the allocation fails.
465f346986bSAlan Cox  */
466f346986bSAlan Cox void *
467f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
468f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
469831ce4cbSJohn Baldwin     vm_paddr_t boundary)
470f346986bSAlan Cox {
471f346986bSAlan Cox 	void *ret;
472f346986bSAlan Cox 
47344d0efb2SAlan Cox 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
47444d0efb2SAlan Cox 	    boundary, VM_MEMATTR_DEFAULT);
475f346986bSAlan Cox 	if (ret != NULL)
476f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
477f346986bSAlan Cox 	return (ret);
478f346986bSAlan Cox }
479f346986bSAlan Cox 
480ab3185d1SJeff Roberson void *
4819978bd99SMark Johnston contigmalloc_domainset(unsigned long size, struct malloc_type *type,
4829978bd99SMark Johnston     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
483ab3185d1SJeff Roberson     unsigned long alignment, vm_paddr_t boundary)
484ab3185d1SJeff Roberson {
485ab3185d1SJeff Roberson 	void *ret;
486ab3185d1SJeff Roberson 
4879978bd99SMark Johnston 	ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
488ab3185d1SJeff Roberson 	    alignment, boundary, VM_MEMATTR_DEFAULT);
489ab3185d1SJeff Roberson 	if (ret != NULL)
490ab3185d1SJeff Roberson 		malloc_type_allocated(type, round_page(size));
491ab3185d1SJeff Roberson 	return (ret);
492ab3185d1SJeff Roberson }
493ab3185d1SJeff Roberson 
494f346986bSAlan Cox /*
495f346986bSAlan Cox  *	contigfree:
496f346986bSAlan Cox  *
497f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
498f346986bSAlan Cox  *
499f346986bSAlan Cox  *	This routine may not block.
500f346986bSAlan Cox  */
501f346986bSAlan Cox void
502f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
503f346986bSAlan Cox {
504f346986bSAlan Cox 
50549bfa624SAlan Cox 	kmem_free((vm_offset_t)addr, size);
506f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
507f346986bSAlan Cox }
508f346986bSAlan Cox 
509ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
510ab3185d1SJeff Roberson static int
5115a70796aSLi-Wen Hsu malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
512ab3185d1SJeff Roberson     int flags)
513df8bae1dSRodney W. Grimes {
514194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
515ab3185d1SJeff Roberson 	int indx;
516ab3185d1SJeff Roberson 
517bdcc2226SMateusz Guzik 	KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
518d3c11994SPoul-Henning Kamp 	/*
51923198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
520d3c11994SPoul-Henning Kamp 	 */
52123198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
522d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
523d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
524d3c11994SPoul-Henning Kamp 		static	int curerr, once;
525d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
526d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
5272d50560aSMarcel Moolenaar 			kdb_backtrace();
528d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
529d3c11994SPoul-Henning Kamp 			once++;
530d3c11994SPoul-Henning Kamp 		}
531d3c11994SPoul-Henning Kamp 	}
532194a0abfSPoul-Henning Kamp #endif
533eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
534eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
535eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
536eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
537eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
5383f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
539ab3185d1SJeff Roberson 			*vap = NULL;
540ab3185d1SJeff Roberson 			return (EJUSTRETURN);
541eae870cdSRobert Watson 		}
542eae870cdSRobert Watson 	}
543eae870cdSRobert Watson #endif
54406bf2a6aSMatt Macy 	if (flags & M_WAITOK) {
545b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
546a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
5475757b59fSGleb Smirnoff 		if (__predict_false(!THREAD_CAN_SLEEP())) {
548bac06038SGleb Smirnoff #ifdef EPOCH_TRACE
549bac06038SGleb Smirnoff 			epoch_trace_list(curthread);
550bac06038SGleb Smirnoff #endif
5515757b59fSGleb Smirnoff 			KASSERT(1,
5525757b59fSGleb Smirnoff 			    ("malloc(M_WAITOK) with sleeping prohibited"));
5535757b59fSGleb Smirnoff 		}
55406bf2a6aSMatt Macy 	}
555d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
5561067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
5571067a2baSJonathan T. Looney 
558e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
559ab3185d1SJeff Roberson 	if (memguard_cmp_mtp(mtp, *sizep)) {
560ab3185d1SJeff Roberson 		*vap = memguard_alloc(*sizep, flags);
561ab3185d1SJeff Roberson 		if (*vap != NULL)
562ab3185d1SJeff Roberson 			return (EJUSTRETURN);
563e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
564e3813573SMatthew D Fleming 	}
565e4eb384bSBosko Milekic #endif
566e4eb384bSBosko Milekic 
567847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
568ab3185d1SJeff Roberson 	*sizep = redzone_size_ntor(*sizep);
569ab3185d1SJeff Roberson #endif
570ab3185d1SJeff Roberson 
571ab3185d1SJeff Roberson 	return (0);
572ab3185d1SJeff Roberson }
573ab3185d1SJeff Roberson #endif
574ab3185d1SJeff Roberson 
575ab3185d1SJeff Roberson /*
5766d6a03d7SJeff Roberson  * Handle large allocations and frees by using kmem_malloc directly.
5776d6a03d7SJeff Roberson  */
5786d6a03d7SJeff Roberson static inline bool
5796d6a03d7SJeff Roberson malloc_large_slab(uma_slab_t slab)
5806d6a03d7SJeff Roberson {
5816d6a03d7SJeff Roberson 	uintptr_t va;
5826d6a03d7SJeff Roberson 
5836d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
5846d6a03d7SJeff Roberson 	return ((va & 1) != 0);
5856d6a03d7SJeff Roberson }
5866d6a03d7SJeff Roberson 
5876d6a03d7SJeff Roberson static inline size_t
5886d6a03d7SJeff Roberson malloc_large_size(uma_slab_t slab)
5896d6a03d7SJeff Roberson {
5906d6a03d7SJeff Roberson 	uintptr_t va;
5916d6a03d7SJeff Roberson 
5926d6a03d7SJeff Roberson 	va = (uintptr_t)slab;
5936d6a03d7SJeff Roberson 	return (va >> 1);
5946d6a03d7SJeff Roberson }
5956d6a03d7SJeff Roberson 
5966d6a03d7SJeff Roberson static caddr_t
5976d6a03d7SJeff Roberson malloc_large(size_t *size, struct domainset *policy, int flags)
5986d6a03d7SJeff Roberson {
5996d6a03d7SJeff Roberson 	vm_offset_t va;
6006d6a03d7SJeff Roberson 	size_t sz;
6016d6a03d7SJeff Roberson 
6026d6a03d7SJeff Roberson 	sz = roundup(*size, PAGE_SIZE);
6036d6a03d7SJeff Roberson 	va = kmem_malloc_domainset(policy, sz, flags);
6046d6a03d7SJeff Roberson 	if (va != 0) {
6056d6a03d7SJeff Roberson 		/* The low bit is unused for slab pointers. */
6066d6a03d7SJeff Roberson 		vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
6076d6a03d7SJeff Roberson 		uma_total_inc(sz);
6086d6a03d7SJeff Roberson 		*size = sz;
6096d6a03d7SJeff Roberson 	}
6106d6a03d7SJeff Roberson 	return ((caddr_t)va);
6116d6a03d7SJeff Roberson }
6126d6a03d7SJeff Roberson 
6136d6a03d7SJeff Roberson static void
6146d6a03d7SJeff Roberson free_large(void *addr, size_t size)
6156d6a03d7SJeff Roberson {
6166d6a03d7SJeff Roberson 
6176d6a03d7SJeff Roberson 	kmem_free((vm_offset_t)addr, size);
6186d6a03d7SJeff Roberson 	uma_total_dec(size);
6196d6a03d7SJeff Roberson }
6206d6a03d7SJeff Roberson 
6216d6a03d7SJeff Roberson /*
622ab3185d1SJeff Roberson  *	malloc:
623ab3185d1SJeff Roberson  *
624ab3185d1SJeff Roberson  *	Allocate a block of memory.
625ab3185d1SJeff Roberson  *
626ab3185d1SJeff Roberson  *	If M_NOWAIT is set, this routine will not block and return NULL if
627ab3185d1SJeff Roberson  *	the allocation fails.
628ab3185d1SJeff Roberson  */
629ab3185d1SJeff Roberson void *
63034c538c3SMateusz Guzik (malloc)(size_t size, struct malloc_type *mtp, int flags)
631ab3185d1SJeff Roberson {
632ab3185d1SJeff Roberson 	int indx;
633ab3185d1SJeff Roberson 	caddr_t va;
634ab3185d1SJeff Roberson 	uma_zone_t zone;
635ab3185d1SJeff Roberson #if defined(DEBUG_REDZONE)
636ab3185d1SJeff Roberson 	unsigned long osize = size;
637ab3185d1SJeff Roberson #endif
638ab3185d1SJeff Roberson 
63982c174a3SMateusz Guzik 	MPASS((flags & M_EXEC) == 0);
640ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
6415072a5f4SMatt Macy 	va = NULL;
642ab3185d1SJeff Roberson 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
643ab3185d1SJeff Roberson 		return (va);
644847a2a17SPawel Jakub Dawidek #endif
645847a2a17SPawel Jakub Dawidek 
64682c174a3SMateusz Guzik 	if (size <= kmem_zmax) {
6476f267175SJeff Roberson 		if (size & KMEM_ZMASK)
6486f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
6496f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
650c9e05ccdSMateusz Guzik 		zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
6516f267175SJeff Roberson #ifdef MALLOC_PROFILE
6526f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
6536f267175SJeff Roberson #endif
6548355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
6554362fadaSBrian Feldman 		if (va != NULL)
656e20a199fSJeff Roberson 			size = zone->uz_size;
65763a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
6588355f576SJeff Roberson 	} else {
6596d6a03d7SJeff Roberson 		va = malloc_large(&size, DOMAINSET_RR(), flags);
66063a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
661df8bae1dSRodney W. Grimes 	}
66282c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
66382c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
66482c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
6651fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
66682c174a3SMateusz Guzik 	}
667ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
668ab3185d1SJeff Roberson 	if (va != NULL)
669ab3185d1SJeff Roberson 		va = redzone_setup(va, osize);
6704db4f5c8SPoul-Henning Kamp #endif
671ab3185d1SJeff Roberson 	return ((void *) va);
672ab3185d1SJeff Roberson }
673ab3185d1SJeff Roberson 
6749978bd99SMark Johnston static void *
675dc727127SMark Johnston malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
6766d6a03d7SJeff Roberson     int flags)
677ab3185d1SJeff Roberson {
678ab3185d1SJeff Roberson 	uma_zone_t zone;
679dc727127SMark Johnston 	caddr_t va;
680dc727127SMark Johnston 	size_t size;
681dc727127SMark Johnston 	int indx;
682ab3185d1SJeff Roberson 
683dc727127SMark Johnston 	size = *sizep;
6846d6a03d7SJeff Roberson 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
6856d6a03d7SJeff Roberson 	    ("malloc_domain: Called with bad flag / size combination."));
686ab3185d1SJeff Roberson 	if (size & KMEM_ZMASK)
687ab3185d1SJeff Roberson 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
688ab3185d1SJeff Roberson 	indx = kmemsize[size >> KMEM_ZSHIFT];
689c9e05ccdSMateusz Guzik 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
690ab3185d1SJeff Roberson #ifdef MALLOC_PROFILE
691ab3185d1SJeff Roberson 	krequests[size >> KMEM_ZSHIFT]++;
692ab3185d1SJeff Roberson #endif
693ab3185d1SJeff Roberson 	va = uma_zalloc_domain(zone, NULL, domain, flags);
694ab3185d1SJeff Roberson 	if (va != NULL)
695dc727127SMark Johnston 		*sizep = zone->uz_size;
6966d6a03d7SJeff Roberson 	*indxp = indx;
697df8bae1dSRodney W. Grimes 	return ((void *)va);
698df8bae1dSRodney W. Grimes }
699df8bae1dSRodney W. Grimes 
700fd91e076SKristof Provost void *
7019978bd99SMark Johnston malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
7029978bd99SMark Johnston     int flags)
7039978bd99SMark Johnston {
7049978bd99SMark Johnston 	struct vm_domainset_iter di;
70582c174a3SMateusz Guzik 	caddr_t va;
7069978bd99SMark Johnston 	int domain;
7076d6a03d7SJeff Roberson 	int indx;
7089978bd99SMark Johnston 
7096d6a03d7SJeff Roberson #if defined(DEBUG_REDZONE)
7106d6a03d7SJeff Roberson 	unsigned long osize = size;
7116d6a03d7SJeff Roberson #endif
71282c174a3SMateusz Guzik 	MPASS((flags & M_EXEC) == 0);
7136d6a03d7SJeff Roberson #ifdef MALLOC_DEBUG
71482c174a3SMateusz Guzik 	va = NULL;
71582c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
71682c174a3SMateusz Guzik 		return (va);
7176d6a03d7SJeff Roberson #endif
71882c174a3SMateusz Guzik 	if (size <= kmem_zmax) {
7199978bd99SMark Johnston 		vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
7209978bd99SMark Johnston 		do {
72182c174a3SMateusz Guzik 			va = malloc_domain(&size, &indx, mtp, domain, flags);
72282c174a3SMateusz Guzik 		} while (va == NULL &&
7236d6a03d7SJeff Roberson 		    vm_domainset_iter_policy(&di, &domain) == 0);
72482c174a3SMateusz Guzik 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
7256d6a03d7SJeff Roberson 	} else {
7266d6a03d7SJeff Roberson 		/* Policy is handled by kmem. */
72782c174a3SMateusz Guzik 		va = malloc_large(&size, ds, flags);
72882c174a3SMateusz Guzik 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
72982c174a3SMateusz Guzik 	}
73082c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
73182c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
73282c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
73382c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
73482c174a3SMateusz Guzik 	}
73582c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
73682c174a3SMateusz Guzik 	if (va != NULL)
73782c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
73882c174a3SMateusz Guzik #endif
73982c174a3SMateusz Guzik 	return (va);
7406d6a03d7SJeff Roberson }
7419978bd99SMark Johnston 
74282c174a3SMateusz Guzik /*
74382c174a3SMateusz Guzik  * Allocate an executable area.
74482c174a3SMateusz Guzik  */
74582c174a3SMateusz Guzik void *
74682c174a3SMateusz Guzik malloc_exec(size_t size, struct malloc_type *mtp, int flags)
74782c174a3SMateusz Guzik {
74882c174a3SMateusz Guzik 	caddr_t va;
74982c174a3SMateusz Guzik #if defined(DEBUG_REDZONE)
75082c174a3SMateusz Guzik 	unsigned long osize = size;
7516d6a03d7SJeff Roberson #endif
75282c174a3SMateusz Guzik 
75382c174a3SMateusz Guzik 	flags |= M_EXEC;
75482c174a3SMateusz Guzik #ifdef MALLOC_DEBUG
75582c174a3SMateusz Guzik 	va = NULL;
75682c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
75782c174a3SMateusz Guzik 		return (va);
75882c174a3SMateusz Guzik #endif
75982c174a3SMateusz Guzik 	va = malloc_large(&size, DOMAINSET_RR(), flags);
76082c174a3SMateusz Guzik 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
76182c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
76282c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
76382c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
76482c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
76582c174a3SMateusz Guzik 	}
76682c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
76782c174a3SMateusz Guzik 	if (va != NULL)
76882c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
76982c174a3SMateusz Guzik #endif
77082c174a3SMateusz Guzik 	return ((void *) va);
77182c174a3SMateusz Guzik }
77282c174a3SMateusz Guzik 
77382c174a3SMateusz Guzik void *
77482c174a3SMateusz Guzik malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
77582c174a3SMateusz Guzik     int flags)
77682c174a3SMateusz Guzik {
77782c174a3SMateusz Guzik 	caddr_t va;
77882c174a3SMateusz Guzik #if defined(DEBUG_REDZONE)
77982c174a3SMateusz Guzik 	unsigned long osize = size;
78082c174a3SMateusz Guzik #endif
78182c174a3SMateusz Guzik 
78282c174a3SMateusz Guzik 	flags |= M_EXEC;
78382c174a3SMateusz Guzik #ifdef MALLOC_DEBUG
78482c174a3SMateusz Guzik 	va = NULL;
78582c174a3SMateusz Guzik 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
78682c174a3SMateusz Guzik 		return (va);
78782c174a3SMateusz Guzik #endif
78882c174a3SMateusz Guzik 	/* Policy is handled by kmem. */
78982c174a3SMateusz Guzik 	va = malloc_large(&size, ds, flags);
79082c174a3SMateusz Guzik 	malloc_type_allocated(mtp, va == NULL ? 0 : size);
79182c174a3SMateusz Guzik 	if (__predict_false(va == NULL)) {
79282c174a3SMateusz Guzik 		KASSERT((flags & M_WAITOK) == 0,
79382c174a3SMateusz Guzik 		    ("malloc(M_WAITOK) returned NULL"));
79482c174a3SMateusz Guzik 		t_malloc_fail = time_uptime;
79582c174a3SMateusz Guzik 	}
79682c174a3SMateusz Guzik #ifdef DEBUG_REDZONE
79782c174a3SMateusz Guzik 	if (va != NULL)
79882c174a3SMateusz Guzik 		va = redzone_setup(va, osize);
79982c174a3SMateusz Guzik #endif
80082c174a3SMateusz Guzik 	return (va);
8019978bd99SMark Johnston }
8029978bd99SMark Johnston 
8039978bd99SMark Johnston void *
804fd91e076SKristof Provost mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
805fd91e076SKristof Provost {
806fd91e076SKristof Provost 
807c02fc960SConrad Meyer 	if (WOULD_OVERFLOW(nmemb, size))
808c02fc960SConrad Meyer 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
809fd91e076SKristof Provost 
810fd91e076SKristof Provost 	return (malloc(size * nmemb, type, flags));
811fd91e076SKristof Provost }
812fd91e076SKristof Provost 
813ab3185d1SJeff Roberson #ifdef INVARIANTS
814ab3185d1SJeff Roberson static void
815ab3185d1SJeff Roberson free_save_type(void *addr, struct malloc_type *mtp, u_long size)
816ab3185d1SJeff Roberson {
817ab3185d1SJeff Roberson 	struct malloc_type **mtpp = addr;
818ab3185d1SJeff Roberson 
819ab3185d1SJeff Roberson 	/*
820ab3185d1SJeff Roberson 	 * Cache a pointer to the malloc_type that most recently freed
821ab3185d1SJeff Roberson 	 * this memory here.  This way we know who is most likely to
822ab3185d1SJeff Roberson 	 * have stepped on it later.
823ab3185d1SJeff Roberson 	 *
824ab3185d1SJeff Roberson 	 * This code assumes that size is a multiple of 8 bytes for
825ab3185d1SJeff Roberson 	 * 64 bit machines
826ab3185d1SJeff Roberson 	 */
827ab3185d1SJeff Roberson 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
828ab3185d1SJeff Roberson 	mtpp += (size - sizeof(struct malloc_type *)) /
829ab3185d1SJeff Roberson 	    sizeof(struct malloc_type *);
830ab3185d1SJeff Roberson 	*mtpp = mtp;
831ab3185d1SJeff Roberson }
832ab3185d1SJeff Roberson #endif
833ab3185d1SJeff Roberson 
834ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
835ab3185d1SJeff Roberson static int
836ab3185d1SJeff Roberson free_dbg(void **addrp, struct malloc_type *mtp)
837ab3185d1SJeff Roberson {
838ab3185d1SJeff Roberson 	void *addr;
839ab3185d1SJeff Roberson 
840ab3185d1SJeff Roberson 	addr = *addrp;
841bdcc2226SMateusz Guzik 	KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
842ab3185d1SJeff Roberson 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
843ab3185d1SJeff Roberson 	    ("free: called with spinlock or critical section held"));
844ab3185d1SJeff Roberson 
845ab3185d1SJeff Roberson 	/* free(NULL, ...) does nothing */
846ab3185d1SJeff Roberson 	if (addr == NULL)
847ab3185d1SJeff Roberson 		return (EJUSTRETURN);
848ab3185d1SJeff Roberson 
849ab3185d1SJeff Roberson #ifdef DEBUG_MEMGUARD
850ab3185d1SJeff Roberson 	if (is_memguard_addr(addr)) {
851ab3185d1SJeff Roberson 		memguard_free(addr);
852ab3185d1SJeff Roberson 		return (EJUSTRETURN);
853ab3185d1SJeff Roberson 	}
854ab3185d1SJeff Roberson #endif
855ab3185d1SJeff Roberson 
856ab3185d1SJeff Roberson #ifdef DEBUG_REDZONE
857ab3185d1SJeff Roberson 	redzone_check(addr);
858ab3185d1SJeff Roberson 	*addrp = redzone_addr_ntor(addr);
859ab3185d1SJeff Roberson #endif
860ab3185d1SJeff Roberson 
861ab3185d1SJeff Roberson 	return (0);
862ab3185d1SJeff Roberson }
863ab3185d1SJeff Roberson #endif
864ab3185d1SJeff Roberson 
865fd91e076SKristof Provost /*
8661c7c3c6aSMatthew Dillon  *	free:
8671c7c3c6aSMatthew Dillon  *
868df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
8691c7c3c6aSMatthew Dillon  *
8701c7c3c6aSMatthew Dillon  *	This routine may not block.
871df8bae1dSRodney W. Grimes  */
872df8bae1dSRodney W. Grimes void
87363a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
874df8bae1dSRodney W. Grimes {
875584061b4SJeff Roberson 	uma_zone_t zone;
87699571dc3SJeff Roberson 	uma_slab_t slab;
87799571dc3SJeff Roberson 	u_long size;
878254c6cb3SPoul-Henning Kamp 
879ab3185d1SJeff Roberson #ifdef MALLOC_DEBUG
880ab3185d1SJeff Roberson 	if (free_dbg(&addr, mtp) != 0)
881ab3185d1SJeff Roberson 		return;
882ab3185d1SJeff Roberson #endif
88344a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
88444a8ff31SArchie Cobbs 	if (addr == NULL)
88544a8ff31SArchie Cobbs 		return;
88644a8ff31SArchie Cobbs 
887584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
8888355f576SJeff Roberson 	if (slab == NULL)
8896f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
89099571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
89199571dc3SJeff Roberson 
8926d6a03d7SJeff Roberson 	if (__predict_true(!malloc_large_slab(slab))) {
893584061b4SJeff Roberson 		size = zone->uz_size;
8948f70816cSJeff Roberson #ifdef INVARIANTS
895ab3185d1SJeff Roberson 		free_save_type(addr, mtp, size);
8968f70816cSJeff Roberson #endif
897584061b4SJeff Roberson 		uma_zfree_arg(zone, addr, slab);
89814bf02f8SJohn Dyson 	} else {
8996d6a03d7SJeff Roberson 		size = malloc_large_size(slab);
9006d6a03d7SJeff Roberson 		free_large(addr, size);
90114bf02f8SJohn Dyson 	}
90263a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
903df8bae1dSRodney W. Grimes }
904df8bae1dSRodney W. Grimes 
90545035becSMatt Macy /*
90645035becSMatt Macy  *	zfree:
90745035becSMatt Macy  *
90845035becSMatt Macy  *	Zero then free a block of memory allocated by malloc.
90945035becSMatt Macy  *
91045035becSMatt Macy  *	This routine may not block.
91145035becSMatt Macy  */
91245035becSMatt Macy void
91345035becSMatt Macy zfree(void *addr, struct malloc_type *mtp)
91445035becSMatt Macy {
91545035becSMatt Macy 	uma_zone_t zone;
91645035becSMatt Macy 	uma_slab_t slab;
91745035becSMatt Macy 	u_long size;
91845035becSMatt Macy 
91945035becSMatt Macy #ifdef MALLOC_DEBUG
92045035becSMatt Macy 	if (free_dbg(&addr, mtp) != 0)
92145035becSMatt Macy 		return;
92245035becSMatt Macy #endif
92345035becSMatt Macy 	/* free(NULL, ...) does nothing */
92445035becSMatt Macy 	if (addr == NULL)
92545035becSMatt Macy 		return;
92645035becSMatt Macy 
92745035becSMatt Macy 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
92845035becSMatt Macy 	if (slab == NULL)
92945035becSMatt Macy 		panic("free: address %p(%p) has not been allocated.\n",
93045035becSMatt Macy 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
93145035becSMatt Macy 
93245035becSMatt Macy 	if (__predict_true(!malloc_large_slab(slab))) {
93345035becSMatt Macy 		size = zone->uz_size;
93445035becSMatt Macy #ifdef INVARIANTS
93545035becSMatt Macy 		free_save_type(addr, mtp, size);
93645035becSMatt Macy #endif
93745035becSMatt Macy 		explicit_bzero(addr, size);
93845035becSMatt Macy 		uma_zfree_arg(zone, addr, slab);
93945035becSMatt Macy 	} else {
94045035becSMatt Macy 		size = malloc_large_size(slab);
94145035becSMatt Macy 		explicit_bzero(addr, size);
94245035becSMatt Macy 		free_large(addr, size);
94345035becSMatt Macy 	}
94445035becSMatt Macy 	malloc_type_freed(mtp, size);
94545035becSMatt Macy }
94645035becSMatt Macy 
947df8bae1dSRodney W. Grimes /*
94844a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
94944a8ff31SArchie Cobbs  */
95044a8ff31SArchie Cobbs void *
951bd555da9SConrad Meyer realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
95244a8ff31SArchie Cobbs {
953584061b4SJeff Roberson 	uma_zone_t zone;
9548355f576SJeff Roberson 	uma_slab_t slab;
95544a8ff31SArchie Cobbs 	unsigned long alloc;
95644a8ff31SArchie Cobbs 	void *newaddr;
95744a8ff31SArchie Cobbs 
958bdcc2226SMateusz Guzik 	KASSERT(mtp->ks_version == M_VERSION,
959bdcc2226SMateusz Guzik 	    ("realloc: bad malloc type version"));
960d9e2e68dSMark Johnston 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
9611067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
9621067a2baSJonathan T. Looney 
96344a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
96444a8ff31SArchie Cobbs 	if (addr == NULL)
96563a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
96663a7e0a3SRobert Watson 
96763a7e0a3SRobert Watson 	/*
96863a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
96963a7e0a3SRobert Watson 	 * per-CPU stats.
97063a7e0a3SRobert Watson 	 */
97144a8ff31SArchie Cobbs 
972e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
9736d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
9746d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
975e4eb384bSBosko Milekic #endif
976e4eb384bSBosko Milekic 
977847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
978847a2a17SPawel Jakub Dawidek 	slab = NULL;
979b476ae7fSJeff Roberson 	zone = NULL;
980847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
981847a2a17SPawel Jakub Dawidek #else
982584061b4SJeff Roberson 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
9838355f576SJeff Roberson 
98444a8ff31SArchie Cobbs 	/* Sanity check */
9858355f576SJeff Roberson 	KASSERT(slab != NULL,
98644a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
98744a8ff31SArchie Cobbs 
98844a8ff31SArchie Cobbs 	/* Get the size of the original block */
9896d6a03d7SJeff Roberson 	if (!malloc_large_slab(slab))
990584061b4SJeff Roberson 		alloc = zone->uz_size;
9918355f576SJeff Roberson 	else
9926d6a03d7SJeff Roberson 		alloc = malloc_large_size(slab);
99344a8ff31SArchie Cobbs 
99444a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
99544a8ff31SArchie Cobbs 	if (size <= alloc
99644a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
99744a8ff31SArchie Cobbs 		return (addr);
998847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
99944a8ff31SArchie Cobbs 
100044a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
100163a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
100244a8ff31SArchie Cobbs 		return (NULL);
100344a8ff31SArchie Cobbs 
100444a8ff31SArchie Cobbs 	/* Copy over original contents */
100544a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
100663a7e0a3SRobert Watson 	free(addr, mtp);
100744a8ff31SArchie Cobbs 	return (newaddr);
100844a8ff31SArchie Cobbs }
100944a8ff31SArchie Cobbs 
101044a8ff31SArchie Cobbs /*
101144a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
101244a8ff31SArchie Cobbs  */
101344a8ff31SArchie Cobbs void *
1014bd555da9SConrad Meyer reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
101544a8ff31SArchie Cobbs {
101644a8ff31SArchie Cobbs 	void *mem;
101744a8ff31SArchie Cobbs 
101863a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
101963a7e0a3SRobert Watson 		free(addr, mtp);
102044a8ff31SArchie Cobbs 	return (mem);
102144a8ff31SArchie Cobbs }
102244a8ff31SArchie Cobbs 
10235d4bf057SVladimir Kondratyev /*
102416b971edSMateusz Guzik  * 	malloc_size: returns the number of bytes allocated for a request of the
102516b971edSMateusz Guzik  * 		     specified size
102616b971edSMateusz Guzik  */
102716b971edSMateusz Guzik size_t
102816b971edSMateusz Guzik malloc_size(size_t size)
102916b971edSMateusz Guzik {
103016b971edSMateusz Guzik 	int indx;
103116b971edSMateusz Guzik 
103216b971edSMateusz Guzik 	if (size > kmem_zmax)
103316b971edSMateusz Guzik 		return (0);
103416b971edSMateusz Guzik 	if (size & KMEM_ZMASK)
103516b971edSMateusz Guzik 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
103616b971edSMateusz Guzik 	indx = kmemsize[size >> KMEM_ZSHIFT];
103716b971edSMateusz Guzik 	return (kmemzones[indx].kz_size);
103816b971edSMateusz Guzik }
103916b971edSMateusz Guzik 
104016b971edSMateusz Guzik /*
10415d4bf057SVladimir Kondratyev  *	malloc_usable_size: returns the usable size of the allocation.
10425d4bf057SVladimir Kondratyev  */
10435d4bf057SVladimir Kondratyev size_t
10445d4bf057SVladimir Kondratyev malloc_usable_size(const void *addr)
10455d4bf057SVladimir Kondratyev {
10465d4bf057SVladimir Kondratyev #ifndef DEBUG_REDZONE
10475d4bf057SVladimir Kondratyev 	uma_zone_t zone;
10485d4bf057SVladimir Kondratyev 	uma_slab_t slab;
10495d4bf057SVladimir Kondratyev #endif
10505d4bf057SVladimir Kondratyev 	u_long size;
10515d4bf057SVladimir Kondratyev 
10525d4bf057SVladimir Kondratyev 	if (addr == NULL)
10535d4bf057SVladimir Kondratyev 		return (0);
10545d4bf057SVladimir Kondratyev 
10555d4bf057SVladimir Kondratyev #ifdef DEBUG_MEMGUARD
10565d4bf057SVladimir Kondratyev 	if (is_memguard_addr(__DECONST(void *, addr)))
10575d4bf057SVladimir Kondratyev 		return (memguard_get_req_size(addr));
10585d4bf057SVladimir Kondratyev #endif
10595d4bf057SVladimir Kondratyev 
10605d4bf057SVladimir Kondratyev #ifdef DEBUG_REDZONE
10615d4bf057SVladimir Kondratyev 	size = redzone_get_size(__DECONST(void *, addr));
10625d4bf057SVladimir Kondratyev #else
10635d4bf057SVladimir Kondratyev 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
10645d4bf057SVladimir Kondratyev 	if (slab == NULL)
10655d4bf057SVladimir Kondratyev 		panic("malloc_usable_size: address %p(%p) is not allocated.\n",
10665d4bf057SVladimir Kondratyev 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
10675d4bf057SVladimir Kondratyev 
10685d4bf057SVladimir Kondratyev 	if (!malloc_large_slab(slab))
10695d4bf057SVladimir Kondratyev 		size = zone->uz_size;
10705d4bf057SVladimir Kondratyev 	else
10715d4bf057SVladimir Kondratyev 		size = malloc_large_size(slab);
10725d4bf057SVladimir Kondratyev #endif
10735d4bf057SVladimir Kondratyev 	return (size);
10745d4bf057SVladimir Kondratyev }
10755d4bf057SVladimir Kondratyev 
1076c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1077c70af487SAlan Cox 
10785df87b21SJeff Roberson /*
1079c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
10805df87b21SJeff Roberson  */
10815df87b21SJeff Roberson void
10825df87b21SJeff Roberson kmeminit(void)
10835df87b21SJeff Roberson {
1084af3b2549SHans Petter Selasky 	u_long mem_size;
1085af3b2549SHans Petter Selasky 	u_long tmp;
108669ef67f9SJason Evans 
1087af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
1088af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
1089af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
1090af3b2549SHans Petter Selasky #endif
1091af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
1092af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
1093af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1094af3b2549SHans Petter Selasky #endif
1095af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
1096af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
1097af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1098af3b2549SHans Petter Selasky #endif
10998a58a9f6SJohn Dyson 	/*
1100c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
1101c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
1102c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
1103c70af487SAlan Cox 	 * specifically,
11048a58a9f6SJohn Dyson 	 *
1105c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1106c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1107c70af487SAlan Cox 	 *
1108c70af487SAlan Cox 	 * Every architecture must define an integral value for
1109c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1110c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1111c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
1112c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1113c70af487SAlan Cox 	 * a given architecture.
11148a58a9f6SJohn Dyson 	 */
111544f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
11167c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
11177c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
11188a58a9f6SJohn Dyson 
1119c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
1120c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1121c70af487SAlan Cox 
1122af3b2549SHans Petter Selasky 	/*
1123af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
1124af3b2549SHans Petter Selasky 	 * variable:
1125af3b2549SHans Petter Selasky 	 */
1126af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
112728b740daSKonstantin Belousov 		vm_kmem_size = mem_size / vm_kmem_size_scale;
112828b740daSKonstantin Belousov 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
112928b740daSKonstantin Belousov 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1130c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
11310e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
1132479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1133479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
1134af3b2549SHans Petter Selasky 	}
113528b740daSKonstantin Belousov 	if (vm_kmem_size == 0)
113628b740daSKonstantin Belousov 		panic("Tune VM_KMEM_SIZE_* for the platform");
11378a58a9f6SJohn Dyson 
113827b8623fSDavid Greenman 	/*
1139af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
1140c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
1141c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
1142c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
1143c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
114427b8623fSDavid Greenman 	 */
1145c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1146c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
11478a58a9f6SJohn Dyson 
1148e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
1149e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
1150f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1151e3813573SMatthew D Fleming #else
1152e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
1153e3813573SMatthew D Fleming #endif
11542e47807cSJeff Roberson 	uma_set_limit(tmp);
11558355f576SJeff Roberson 
1156e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
1157e4eb384bSBosko Milekic 	/*
1158e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1159e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
1160e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
1161e4eb384bSBosko Milekic 	 */
11622e47807cSJeff Roberson 	memguard_init(kernel_arena);
1163e4eb384bSBosko Milekic #endif
11645df87b21SJeff Roberson }
11655df87b21SJeff Roberson 
11665df87b21SJeff Roberson /*
11675df87b21SJeff Roberson  * Initialize the kernel memory allocator
11685df87b21SJeff Roberson  */
11695df87b21SJeff Roberson /* ARGSUSED*/
11705df87b21SJeff Roberson static void
11715df87b21SJeff Roberson mallocinit(void *dummy)
11725df87b21SJeff Roberson {
11735df87b21SJeff Roberson 	int i;
11745df87b21SJeff Roberson 	uint8_t indx;
11755df87b21SJeff Roberson 
11765df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
11775df87b21SJeff Roberson 
11785df87b21SJeff Roberson 	kmeminit();
1179e4eb384bSBosko Milekic 
11807001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
11817001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
11827001d850SXin LI 
11836f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
11846f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
1185eaa17d42SRyan Libby 		const char *name = kmemzones[indx].kz_name;
1186d7854da1SMatthew D Fleming 		int subzone;
11878355f576SJeff Roberson 
1188d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
1189d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
1190d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
11918efc4effSJeff Roberson #ifdef INVARIANTS
11928f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
11938efc4effSJeff Roberson #else
11948efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
11958efc4effSJeff Roberson #endif
11968efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1197d7854da1SMatthew D Fleming 		}
11988355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
11996f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1200df8bae1dSRodney W. Grimes 	}
1201254c6cb3SPoul-Henning Kamp }
1202af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1203254c6cb3SPoul-Henning Kamp 
1204db669378SPeter Wemm void
120587efd4d5SRobert Watson malloc_init(void *data)
1206254c6cb3SPoul-Henning Kamp {
120763a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
120863a7e0a3SRobert Watson 	struct malloc_type *mtp;
120963a7e0a3SRobert Watson 
121044f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
121163a7e0a3SRobert Watson 
121263a7e0a3SRobert Watson 	mtp = data;
1213bdcc2226SMateusz Guzik 	if (mtp->ks_version != M_VERSION)
1214e25d8b67SMateusz Guzik 		panic("malloc_init: type %s with unsupported version %lu",
1215e25d8b67SMateusz Guzik 		    mtp->ks_shortdesc, mtp->ks_version);
1216bb1c7df8SRobert Watson 
1217bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
12188e6526e9SMateusz Guzik 	mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1219c9e05ccdSMateusz Guzik 	mtp_set_subzone(mtp);
1220254c6cb3SPoul-Henning Kamp 
12216f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
122263a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
122363a7e0a3SRobert Watson 	kmemstatistics = mtp;
1224cd814b26SRobert Watson 	kmemcount++;
12256f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
1226df8bae1dSRodney W. Grimes }
1227db669378SPeter Wemm 
1228db669378SPeter Wemm void
122987efd4d5SRobert Watson malloc_uninit(void *data)
1230db669378SPeter Wemm {
123163a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
12322a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
123363a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
12342a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
12352a143d5bSPawel Jakub Dawidek 	int i;
1236db669378SPeter Wemm 
123763a7e0a3SRobert Watson 	mtp = data;
1238bdcc2226SMateusz Guzik 	KASSERT(mtp->ks_version == M_VERSION,
1239bdcc2226SMateusz Guzik 	    ("malloc_uninit: bad malloc type version"));
1240bb1c7df8SRobert Watson 
12416f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
1242bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
124363a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
124463a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
124563a7e0a3SRobert Watson 		    temp = temp->ks_next) {
1246f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
124763a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
1248f121baaaSBrian Somers 				break;
1249db669378SPeter Wemm 			}
1250f121baaaSBrian Somers 		}
1251f121baaaSBrian Somers 		KASSERT(temp,
1252f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
125363a7e0a3SRobert Watson 	} else
125463a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
1255cd814b26SRobert Watson 	kmemcount--;
12566f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
12572a143d5bSPawel Jakub Dawidek 
12582a143d5bSPawel Jakub Dawidek 	/*
12592a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
12602a143d5bSPawel Jakub Dawidek 	 */
12612a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
12629afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
12639afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
12642a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
12652a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
12662a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
12672a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
12682a143d5bSPawel Jakub Dawidek 	}
12692a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
12702a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
12712a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
12722a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
12732a143d5bSPawel Jakub Dawidek 	}
12742a143d5bSPawel Jakub Dawidek 
12758e6526e9SMateusz Guzik 	uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1276db669378SPeter Wemm }
12776f267175SJeff Roberson 
1278d362c40dSPawel Jakub Dawidek struct malloc_type *
1279d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
1280d362c40dSPawel Jakub Dawidek {
1281d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
1282d362c40dSPawel Jakub Dawidek 
1283d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
1284d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1285d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1286d362c40dSPawel Jakub Dawidek 			return (mtp);
1287d362c40dSPawel Jakub Dawidek 	}
1288d362c40dSPawel Jakub Dawidek 	return (NULL);
1289d362c40dSPawel Jakub Dawidek }
1290d362c40dSPawel Jakub Dawidek 
12916f267175SJeff Roberson static int
1292cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1293cd814b26SRobert Watson {
1294cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
1295cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
12969afff6b1SMateusz Guzik 	struct malloc_type_stats *mtsp, zeromts;
1297cd814b26SRobert Watson 	struct malloc_type_header mth;
1298cd814b26SRobert Watson 	struct malloc_type *mtp;
12994e657159SMatthew D Fleming 	int error, i;
1300cd814b26SRobert Watson 	struct sbuf sbuf;
1301cd814b26SRobert Watson 
130200f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
130300f0e671SMatthew D Fleming 	if (error != 0)
130400f0e671SMatthew D Fleming 		return (error);
13054e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
13061eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1307cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
1308cd814b26SRobert Watson 
13099afff6b1SMateusz Guzik 	bzero(&zeromts, sizeof(zeromts));
13109afff6b1SMateusz Guzik 
1311cd814b26SRobert Watson 	/*
1312cd814b26SRobert Watson 	 * Insert stream header.
1313cd814b26SRobert Watson 	 */
1314cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
1315cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1316cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
1317cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
13184e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1319cd814b26SRobert Watson 
1320cd814b26SRobert Watson 	/*
1321cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
1322cd814b26SRobert Watson 	 */
1323cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1324bdcc2226SMateusz Guzik 		mtip = &mtp->ks_mti;
1325cd814b26SRobert Watson 
1326cd814b26SRobert Watson 		/*
1327cd814b26SRobert Watson 		 * Insert type header.
1328cd814b26SRobert Watson 		 */
1329cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
1330cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
13314e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1332cd814b26SRobert Watson 
1333cd814b26SRobert Watson 		/*
1334cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
1335cd814b26SRobert Watson 		 */
13369afff6b1SMateusz Guzik 		for (i = 0; i <= mp_maxid; i++) {
13379afff6b1SMateusz Guzik 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
13389afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1339cd814b26SRobert Watson 		}
13409afff6b1SMateusz Guzik 		/*
13419afff6b1SMateusz Guzik 		 * Fill in the missing CPUs.
13429afff6b1SMateusz Guzik 		 */
13439afff6b1SMateusz Guzik 		for (; i < MAXCPU; i++) {
13449afff6b1SMateusz Guzik 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
13459afff6b1SMateusz Guzik 		}
1346cd814b26SRobert Watson 	}
1347cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
13484e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
1349cd814b26SRobert Watson 	sbuf_delete(&sbuf);
1350cd814b26SRobert Watson 	return (error);
1351cd814b26SRobert Watson }
1352cd814b26SRobert Watson 
13537029da5cSPawel Biernacki SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
13547029da5cSPawel Biernacki     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
13557029da5cSPawel Biernacki     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1356cd814b26SRobert Watson     "Return malloc types");
1357cd814b26SRobert Watson 
1358cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1359cd814b26SRobert Watson     "Count of kernel malloc types");
1360cd814b26SRobert Watson 
136191dd776cSJohn Birrell void
136291dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
136391dd776cSJohn Birrell {
136491dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
136591dd776cSJohn Birrell 	int count, i;
136691dd776cSJohn Birrell 	size_t buflen;
136791dd776cSJohn Birrell 
136891dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
136991dd776cSJohn Birrell restart:
137091dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
137191dd776cSJohn Birrell 	count = kmemcount;
137291dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
137391dd776cSJohn Birrell 
137491dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
137591dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
137691dd776cSJohn Birrell 
137791dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
137891dd776cSJohn Birrell 
137991dd776cSJohn Birrell 	if (count < kmemcount) {
138091dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
138191dd776cSJohn Birrell 		goto restart;
138291dd776cSJohn Birrell 	}
138391dd776cSJohn Birrell 
138491dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
138591dd776cSJohn Birrell 		bufmtp[i] = mtp;
138691dd776cSJohn Birrell 
138791dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
138891dd776cSJohn Birrell 
138991dd776cSJohn Birrell 	for (i = 0; i < count; i++)
139091dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
139191dd776cSJohn Birrell 
139291dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
139391dd776cSJohn Birrell }
139491dd776cSJohn Birrell 
1395909ed16cSRobert Watson #ifdef DDB
139646d70077SConrad Meyer static int64_t
139746d70077SConrad Meyer get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
139846d70077SConrad Meyer     uint64_t *inuse)
1399909ed16cSRobert Watson {
140046d70077SConrad Meyer 	const struct malloc_type_stats *mtsp;
140146d70077SConrad Meyer 	uint64_t frees, alloced, freed;
1402909ed16cSRobert Watson 	int i;
1403909ed16cSRobert Watson 
140446d70077SConrad Meyer 	*allocs = 0;
1405909ed16cSRobert Watson 	frees = 0;
140624076d13SRobert Watson 	alloced = 0;
140724076d13SRobert Watson 	freed = 0;
14089afff6b1SMateusz Guzik 	for (i = 0; i <= mp_maxid; i++) {
14099afff6b1SMateusz Guzik 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
141046d70077SConrad Meyer 
141146d70077SConrad Meyer 		*allocs += mtsp->mts_numallocs;
141226e9d9b0SMark Johnston 		frees += mtsp->mts_numfrees;
141326e9d9b0SMark Johnston 		alloced += mtsp->mts_memalloced;
141426e9d9b0SMark Johnston 		freed += mtsp->mts_memfreed;
1415909ed16cSRobert Watson 	}
141646d70077SConrad Meyer 	*inuse = *allocs - frees;
141746d70077SConrad Meyer 	return (alloced - freed);
141846d70077SConrad Meyer }
141946d70077SConrad Meyer 
142046d70077SConrad Meyer DB_SHOW_COMMAND(malloc, db_show_malloc)
142146d70077SConrad Meyer {
142246d70077SConrad Meyer 	const char *fmt_hdr, *fmt_entry;
142346d70077SConrad Meyer 	struct malloc_type *mtp;
142446d70077SConrad Meyer 	uint64_t allocs, inuse;
142546d70077SConrad Meyer 	int64_t size;
142646d70077SConrad Meyer 	/* variables for sorting */
142746d70077SConrad Meyer 	struct malloc_type *last_mtype, *cur_mtype;
142846d70077SConrad Meyer 	int64_t cur_size, last_size;
142946d70077SConrad Meyer 	int ties;
143046d70077SConrad Meyer 
143146d70077SConrad Meyer 	if (modif[0] == 'i') {
143246d70077SConrad Meyer 		fmt_hdr = "%s,%s,%s,%s\n";
143346d70077SConrad Meyer 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
143446d70077SConrad Meyer 	} else {
143546d70077SConrad Meyer 		fmt_hdr = "%18s %12s  %12s %12s\n";
143646d70077SConrad Meyer 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
143746d70077SConrad Meyer 	}
143846d70077SConrad Meyer 
143946d70077SConrad Meyer 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
144046d70077SConrad Meyer 
144146d70077SConrad Meyer 	/* Select sort, largest size first. */
144246d70077SConrad Meyer 	last_mtype = NULL;
144346d70077SConrad Meyer 	last_size = INT64_MAX;
144446d70077SConrad Meyer 	for (;;) {
144546d70077SConrad Meyer 		cur_mtype = NULL;
144646d70077SConrad Meyer 		cur_size = -1;
144746d70077SConrad Meyer 		ties = 0;
144846d70077SConrad Meyer 
144946d70077SConrad Meyer 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
145046d70077SConrad Meyer 			/*
145146d70077SConrad Meyer 			 * In the case of size ties, print out mtypes
145246d70077SConrad Meyer 			 * in the order they are encountered.  That is,
145346d70077SConrad Meyer 			 * when we encounter the most recently output
145446d70077SConrad Meyer 			 * mtype, we have already printed all preceding
145546d70077SConrad Meyer 			 * ties, and we must print all following ties.
145646d70077SConrad Meyer 			 */
145746d70077SConrad Meyer 			if (mtp == last_mtype) {
145846d70077SConrad Meyer 				ties = 1;
145946d70077SConrad Meyer 				continue;
146046d70077SConrad Meyer 			}
1461bdcc2226SMateusz Guzik 			size = get_malloc_stats(&mtp->ks_mti, &allocs,
146246d70077SConrad Meyer 			    &inuse);
146346d70077SConrad Meyer 			if (size > cur_size && size < last_size + ties) {
146446d70077SConrad Meyer 				cur_size = size;
146546d70077SConrad Meyer 				cur_mtype = mtp;
146646d70077SConrad Meyer 			}
146746d70077SConrad Meyer 		}
146846d70077SConrad Meyer 		if (cur_mtype == NULL)
146946d70077SConrad Meyer 			break;
147046d70077SConrad Meyer 
1471bdcc2226SMateusz Guzik 		size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
147246d70077SConrad Meyer 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
147346d70077SConrad Meyer 		    howmany(size, 1024), allocs);
147446d70077SConrad Meyer 
1475687c94aaSJohn Baldwin 		if (db_pager_quit)
1476687c94aaSJohn Baldwin 			break;
147746d70077SConrad Meyer 
147846d70077SConrad Meyer 		last_mtype = cur_mtype;
147946d70077SConrad Meyer 		last_size = cur_size;
1480909ed16cSRobert Watson 	}
1481909ed16cSRobert Watson }
1482d7854da1SMatthew D Fleming 
1483d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1484d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1485d7854da1SMatthew D Fleming {
1486d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1487d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1488d7854da1SMatthew D Fleming 	u_int subzone;
1489d7854da1SMatthew D Fleming 
1490d7854da1SMatthew D Fleming 	if (!have_addr) {
1491d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1492d7854da1SMatthew D Fleming 		return;
1493d7854da1SMatthew D Fleming 	}
1494d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1495bdcc2226SMateusz Guzik 	if (mtp->ks_version != M_VERSION) {
1496bdcc2226SMateusz Guzik 		db_printf("Version %lx does not match expected %x\n",
1497bdcc2226SMateusz Guzik 		    mtp->ks_version, M_VERSION);
1498d7854da1SMatthew D Fleming 		return;
1499d7854da1SMatthew D Fleming 	}
1500d7854da1SMatthew D Fleming 
1501bdcc2226SMateusz Guzik 	mtip = &mtp->ks_mti;
1502d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1503d7854da1SMatthew D Fleming 
1504d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1505bdcc2226SMateusz Guzik 		mtip = &mtp->ks_mti;
1506d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1507d7854da1SMatthew D Fleming 			continue;
1508d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1509687c94aaSJohn Baldwin 		if (db_pager_quit)
1510687c94aaSJohn Baldwin 			break;
1511d7854da1SMatthew D Fleming 	}
1512d7854da1SMatthew D Fleming }
1513d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1514d7854da1SMatthew D Fleming #endif /* DDB */
1515909ed16cSRobert Watson 
15165e914b96SJeff Roberson #ifdef MALLOC_PROFILE
15175e914b96SJeff Roberson 
15185e914b96SJeff Roberson static int
15195e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
15205e914b96SJeff Roberson {
152163a7e0a3SRobert Watson 	struct sbuf sbuf;
15225e914b96SJeff Roberson 	uint64_t count;
15235e914b96SJeff Roberson 	uint64_t waste;
15245e914b96SJeff Roberson 	uint64_t mem;
15255e914b96SJeff Roberson 	int error;
15265e914b96SJeff Roberson 	int rsize;
15275e914b96SJeff Roberson 	int size;
15285e914b96SJeff Roberson 	int i;
15295e914b96SJeff Roberson 
15305e914b96SJeff Roberson 	waste = 0;
15315e914b96SJeff Roberson 	mem = 0;
15325e914b96SJeff Roberson 
153300f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
153400f0e671SMatthew D Fleming 	if (error != 0)
153500f0e671SMatthew D Fleming 		return (error);
15364e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
153763a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
15385e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
15395e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
15405e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
15415e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
15425e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
15435e914b96SJeff Roberson 
154463a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
154563a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
15465e914b96SJeff Roberson 
15475e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
15485e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
15495e914b96SJeff Roberson 		mem += (rsize * count);
15505e914b96SJeff Roberson 	}
155163a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
15525e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
15535e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
15544e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
155563a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
15565e914b96SJeff Roberson 	return (error);
15575e914b96SJeff Roberson }
15585e914b96SJeff Roberson 
15597029da5cSPawel Biernacki SYSCTL_OID(_kern, OID_AUTO, mprof,
15607029da5cSPawel Biernacki     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
15617029da5cSPawel Biernacki     sysctl_kern_mprof, "A",
15627029da5cSPawel Biernacki     "Malloc Profiling");
15635e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1564