xref: /freebsd/sys/kern/kern_malloc.c (revision 1067a2ba6825b8f14707f61da3aefdc6b040e895)
19454b2d8SWarner Losh /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1991, 1993
363a7e0a3SRobert Watson  *	The Regents of the University of California.
4bb1c7df8SRobert Watson  * Copyright (c) 2005-2009 Robert N. M. Watson
563a7e0a3SRobert Watson  * All rights reserved.
6df8bae1dSRodney W. Grimes  *
7df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
8df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
9df8bae1dSRodney W. Grimes  * are met:
10df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
11df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
12df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
13df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
14df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
15df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
16df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
17df8bae1dSRodney W. Grimes  *    without specific prior written permission.
18df8bae1dSRodney W. Grimes  *
19df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
30df8bae1dSRodney W. Grimes  *
31df8bae1dSRodney W. Grimes  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
32df8bae1dSRodney W. Grimes  */
33df8bae1dSRodney W. Grimes 
340ce3f16dSRobert Watson /*
350ce3f16dSRobert Watson  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
360ce3f16dSRobert Watson  * based on memory types.  Back end is implemented using the UMA(9) zone
370ce3f16dSRobert Watson  * allocator.  A set of fixed-size buckets are used for smaller allocations,
380ce3f16dSRobert Watson  * and a special UMA allocation interface is used for larger allocations.
390ce3f16dSRobert Watson  * Callers declare memory types, and statistics are maintained independently
400ce3f16dSRobert Watson  * for each memory type.  Statistics are maintained per-CPU for performance
410ce3f16dSRobert Watson  * reasons.  See malloc(9) and comments in malloc.h for a detailed
420ce3f16dSRobert Watson  * description.
430ce3f16dSRobert Watson  */
440ce3f16dSRobert Watson 
45677b542eSDavid E. O'Brien #include <sys/cdefs.h>
46677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
47677b542eSDavid E. O'Brien 
48909ed16cSRobert Watson #include "opt_ddb.h"
498a58a9f6SJohn Dyson #include "opt_vm.h"
508a58a9f6SJohn Dyson 
51df8bae1dSRodney W. Grimes #include <sys/param.h>
5226f9a767SRodney W. Grimes #include <sys/systm.h>
532d50560aSMarcel Moolenaar #include <sys/kdb.h>
54df8bae1dSRodney W. Grimes #include <sys/kernel.h>
55fb919e4dSMark Murray #include <sys/lock.h>
56df8bae1dSRodney W. Grimes #include <sys/malloc.h>
57eec258d2SJohn Baldwin #include <sys/mutex.h>
58efeaf95aSDavid Greenman #include <sys/vmmeter.h>
59a448b62aSJake Burkholder #include <sys/proc.h>
6063a7e0a3SRobert Watson #include <sys/sbuf.h>
616f267175SJeff Roberson #include <sys/sysctl.h>
621fb14a47SPoul-Henning Kamp #include <sys/time.h>
635df87b21SJeff Roberson #include <sys/vmem.h>
649a02e8c6SJason Evans 
65df8bae1dSRodney W. Grimes #include <vm/vm.h>
6699571dc3SJeff Roberson #include <vm/pmap.h>
675df87b21SJeff Roberson #include <vm/vm_pageout.h>
68efeaf95aSDavid Greenman #include <vm/vm_param.h>
69df8bae1dSRodney W. Grimes #include <vm/vm_kern.h>
70efeaf95aSDavid Greenman #include <vm/vm_extern.h>
713075778bSJohn Dyson #include <vm/vm_map.h>
7299571dc3SJeff Roberson #include <vm/vm_page.h>
738355f576SJeff Roberson #include <vm/uma.h>
748355f576SJeff Roberson #include <vm/uma_int.h>
758efc4effSJeff Roberson #include <vm/uma_dbg.h>
76df8bae1dSRodney W. Grimes 
77e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
78e4eb384bSBosko Milekic #include <vm/memguard.h>
79e4eb384bSBosko Milekic #endif
80847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
81847a2a17SPawel Jakub Dawidek #include <vm/redzone.h>
82847a2a17SPawel Jakub Dawidek #endif
83e4eb384bSBosko Milekic 
84984982d6SPoul-Henning Kamp #if defined(INVARIANTS) && defined(__i386__)
85984982d6SPoul-Henning Kamp #include <machine/cpu.h>
86984982d6SPoul-Henning Kamp #endif
87984982d6SPoul-Henning Kamp 
88909ed16cSRobert Watson #include <ddb/ddb.h>
89909ed16cSRobert Watson 
9091dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
9191dd776cSJohn Birrell #include <sys/dtrace_bsd.h>
9291dd776cSJohn Birrell 
9391dd776cSJohn Birrell dtrace_malloc_probe_func_t	dtrace_malloc_probe;
9491dd776cSJohn Birrell #endif
9591dd776cSJohn Birrell 
9644a8ff31SArchie Cobbs /*
9744a8ff31SArchie Cobbs  * When realloc() is called, if the new size is sufficiently smaller than
9844a8ff31SArchie Cobbs  * the old size, realloc() will allocate a new, smaller block to avoid
9944a8ff31SArchie Cobbs  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
10044a8ff31SArchie Cobbs  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
10144a8ff31SArchie Cobbs  */
10244a8ff31SArchie Cobbs #ifndef REALLOC_FRACTION
10344a8ff31SArchie Cobbs #define	REALLOC_FRACTION	1	/* new block if <= half the size */
10444a8ff31SArchie Cobbs #endif
10544a8ff31SArchie Cobbs 
1060ce3f16dSRobert Watson /*
1070ce3f16dSRobert Watson  * Centrally define some common malloc types.
1080ce3f16dSRobert Watson  */
1093b6fb885SPoul-Henning Kamp MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
1109ef246c6SBruce Evans MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
1119ef246c6SBruce Evans MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
1129ef246c6SBruce Evans 
11382cd038dSYoshinobu Inoue MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
11482cd038dSYoshinobu Inoue MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
11582cd038dSYoshinobu Inoue 
116db669378SPeter Wemm static struct malloc_type *kmemstatistics;
117cd814b26SRobert Watson static int kmemcount;
1181f6889a1SMatthew Dillon 
1198355f576SJeff Roberson #define KMEM_ZSHIFT	4
1208355f576SJeff Roberson #define KMEM_ZBASE	16
1218355f576SJeff Roberson #define KMEM_ZMASK	(KMEM_ZBASE - 1)
1228355f576SJeff Roberson 
123bda06553SXin LI #define KMEM_ZMAX	65536
1248355f576SJeff Roberson #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
12560ae52f7SEd Schouten static uint8_t kmemsize[KMEM_ZSIZE + 1];
1266f267175SJeff Roberson 
127d7854da1SMatthew D Fleming #ifndef MALLOC_DEBUG_MAXZONES
128d7854da1SMatthew D Fleming #define	MALLOC_DEBUG_MAXZONES	1
129d7854da1SMatthew D Fleming #endif
130d7854da1SMatthew D Fleming static int numzones = MALLOC_DEBUG_MAXZONES;
131d7854da1SMatthew D Fleming 
1320ce3f16dSRobert Watson /*
1330ce3f16dSRobert Watson  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
1340ce3f16dSRobert Watson  * of various sizes.
1350ce3f16dSRobert Watson  *
1360ce3f16dSRobert Watson  * XXX: The comment here used to read "These won't be powers of two for
1370ce3f16dSRobert Watson  * long."  It's possible that a significant amount of wasted memory could be
1380ce3f16dSRobert Watson  * recovered by tuning the sizes of these buckets.
1390ce3f16dSRobert Watson  */
1408355f576SJeff Roberson struct {
1416f267175SJeff Roberson 	int kz_size;
1426f267175SJeff Roberson 	char *kz_name;
143d7854da1SMatthew D Fleming 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
1446f267175SJeff Roberson } kmemzones[] = {
145d7854da1SMatthew D Fleming 	{16, "16", },
146d7854da1SMatthew D Fleming 	{32, "32", },
147d7854da1SMatthew D Fleming 	{64, "64", },
148d7854da1SMatthew D Fleming 	{128, "128", },
149d7854da1SMatthew D Fleming 	{256, "256", },
150d7854da1SMatthew D Fleming 	{512, "512", },
151d7854da1SMatthew D Fleming 	{1024, "1024", },
152d7854da1SMatthew D Fleming 	{2048, "2048", },
153d7854da1SMatthew D Fleming 	{4096, "4096", },
154d7854da1SMatthew D Fleming 	{8192, "8192", },
155d7854da1SMatthew D Fleming 	{16384, "16384", },
156d7854da1SMatthew D Fleming 	{32768, "32768", },
157d7854da1SMatthew D Fleming 	{65536, "65536", },
1588355f576SJeff Roberson 	{0, NULL},
1598355f576SJeff Roberson };
1608355f576SJeff Roberson 
1610ce3f16dSRobert Watson /*
1620ce3f16dSRobert Watson  * Zone to allocate malloc type descriptions from.  For ABI reasons, memory
1630ce3f16dSRobert Watson  * types are described by a data structure passed by the declaring code, but
1640ce3f16dSRobert Watson  * the malloc(9) implementation has its own data structure describing the
1650ce3f16dSRobert Watson  * type and statistics.  This permits the malloc(9)-internal data structures
1660ce3f16dSRobert Watson  * to be modified without breaking binary-compiled kernel modules that
1670ce3f16dSRobert Watson  * declare malloc types.
1680ce3f16dSRobert Watson  */
16963a7e0a3SRobert Watson static uma_zone_t mt_zone;
17063a7e0a3SRobert Watson 
171b89eaf4eSAlan Cox u_long vm_kmem_size;
172d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
17384344f9fSDag-Erling Smørgrav     "Size of kernel memory");
1745a34a9f0SJeff Roberson 
1757001d850SXin LI static u_long kmem_zmax = KMEM_ZMAX;
1767001d850SXin LI SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
1777001d850SXin LI     "Maximum allocation size that malloc(9) would use UMA as backend");
1787001d850SXin LI 
179b89eaf4eSAlan Cox static u_long vm_kmem_size_min;
180d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
1810e5179e4SStephane E. Potvin     "Minimum size of kernel memory");
1820e5179e4SStephane E. Potvin 
183b89eaf4eSAlan Cox static u_long vm_kmem_size_max;
184d801e824SAndriy Gapon SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
185479439b4SDag-Erling Smørgrav     "Maximum size of kernel memory");
186479439b4SDag-Erling Smørgrav 
1874813ad54SHans Petter Selasky static u_int vm_kmem_size_scale;
188d801e824SAndriy Gapon SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
189479439b4SDag-Erling Smørgrav     "Scale factor for kernel memory size");
190479439b4SDag-Erling Smørgrav 
1917814c80aSAndriy Gapon static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
1927814c80aSAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
1937814c80aSAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
1945df87b21SJeff Roberson     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
1957814c80aSAndriy Gapon 
19695bb9d38SAndriy Gapon static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
19795bb9d38SAndriy Gapon SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
19895bb9d38SAndriy Gapon     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
1995df87b21SJeff Roberson     sysctl_kmem_map_free, "LU", "Free space in kmem");
20095bb9d38SAndriy Gapon 
2015a34a9f0SJeff Roberson /*
20299571dc3SJeff Roberson  * The malloc_mtx protects the kmemstatistics linked list.
2035a34a9f0SJeff Roberson  */
2045a34a9f0SJeff Roberson struct mtx malloc_mtx;
20569ef67f9SJason Evans 
2065e914b96SJeff Roberson #ifdef MALLOC_PROFILE
2075e914b96SJeff Roberson uint64_t krequests[KMEM_ZSIZE + 1];
2086f267175SJeff Roberson 
2095e914b96SJeff Roberson static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
2105e914b96SJeff Roberson #endif
2115e914b96SJeff Roberson 
212cd814b26SRobert Watson static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
213df8bae1dSRodney W. Grimes 
2140ce3f16dSRobert Watson /*
2150ce3f16dSRobert Watson  * time_uptime of the last malloc(9) failure (induced or real).
2160ce3f16dSRobert Watson  */
2171fb14a47SPoul-Henning Kamp static time_t t_malloc_fail;
2181fb14a47SPoul-Henning Kamp 
219d7854da1SMatthew D Fleming #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
2206472ac3dSEd Schouten static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
221d7854da1SMatthew D Fleming     "Kernel malloc debugging options");
222d7854da1SMatthew D Fleming #endif
223d7854da1SMatthew D Fleming 
224eae870cdSRobert Watson /*
2250ce3f16dSRobert Watson  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
2260ce3f16dSRobert Watson  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
227eae870cdSRobert Watson  */
2280ce3f16dSRobert Watson #ifdef MALLOC_MAKE_FAILURES
229eae870cdSRobert Watson static int malloc_failure_rate;
230eae870cdSRobert Watson static int malloc_nowait_count;
231eae870cdSRobert Watson static int malloc_failure_count;
232af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
233eae870cdSRobert Watson     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
234eae870cdSRobert Watson SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
235eae870cdSRobert Watson     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
236eae870cdSRobert Watson #endif
237eae870cdSRobert Watson 
2387814c80aSAndriy Gapon static int
2397814c80aSAndriy Gapon sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
2407814c80aSAndriy Gapon {
2417814c80aSAndriy Gapon 	u_long size;
2427814c80aSAndriy Gapon 
2435df87b21SJeff Roberson 	size = vmem_size(kmem_arena, VMEM_ALLOC);
2447814c80aSAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
2457814c80aSAndriy Gapon }
2467814c80aSAndriy Gapon 
24795bb9d38SAndriy Gapon static int
24895bb9d38SAndriy Gapon sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
24995bb9d38SAndriy Gapon {
25095bb9d38SAndriy Gapon 	u_long size;
25195bb9d38SAndriy Gapon 
2525df87b21SJeff Roberson 	size = vmem_size(kmem_arena, VMEM_FREE);
25395bb9d38SAndriy Gapon 	return (sysctl_handle_long(oidp, &size, 0, req));
25495bb9d38SAndriy Gapon }
25595bb9d38SAndriy Gapon 
256d7854da1SMatthew D Fleming /*
257d7854da1SMatthew D Fleming  * malloc(9) uma zone separation -- sub-page buffer overruns in one
258d7854da1SMatthew D Fleming  * malloc type will affect only a subset of other malloc types.
259d7854da1SMatthew D Fleming  */
260d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
261d7854da1SMatthew D Fleming static void
262d7854da1SMatthew D Fleming tunable_set_numzones(void)
263d7854da1SMatthew D Fleming {
264d7854da1SMatthew D Fleming 
265d7854da1SMatthew D Fleming 	TUNABLE_INT_FETCH("debug.malloc.numzones",
266d7854da1SMatthew D Fleming 	    &numzones);
267d7854da1SMatthew D Fleming 
268d7854da1SMatthew D Fleming 	/* Sanity check the number of malloc uma zones. */
269d7854da1SMatthew D Fleming 	if (numzones <= 0)
270d7854da1SMatthew D Fleming 		numzones = 1;
271d7854da1SMatthew D Fleming 	if (numzones > MALLOC_DEBUG_MAXZONES)
272d7854da1SMatthew D Fleming 		numzones = MALLOC_DEBUG_MAXZONES;
273d7854da1SMatthew D Fleming }
274d7854da1SMatthew D Fleming SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
275af3b2549SHans Petter Selasky SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
276d7854da1SMatthew D Fleming     &numzones, 0, "Number of malloc uma subzones");
277d7854da1SMatthew D Fleming 
278d7854da1SMatthew D Fleming /*
279d7854da1SMatthew D Fleming  * Any number that changes regularly is an okay choice for the
280d7854da1SMatthew D Fleming  * offset.  Build numbers are pretty good of you have them.
281d7854da1SMatthew D Fleming  */
282d7854da1SMatthew D Fleming static u_int zone_offset = __FreeBSD_version;
283d7854da1SMatthew D Fleming TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
284d7854da1SMatthew D Fleming SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
285d7854da1SMatthew D Fleming     &zone_offset, 0, "Separate malloc types by examining the "
286d7854da1SMatthew D Fleming     "Nth character in the malloc type short description.");
287d7854da1SMatthew D Fleming 
288d7854da1SMatthew D Fleming static u_int
289d7854da1SMatthew D Fleming mtp_get_subzone(const char *desc)
290d7854da1SMatthew D Fleming {
291d7854da1SMatthew D Fleming 	size_t len;
292d7854da1SMatthew D Fleming 	u_int val;
293d7854da1SMatthew D Fleming 
294d7854da1SMatthew D Fleming 	if (desc == NULL || (len = strlen(desc)) == 0)
295d7854da1SMatthew D Fleming 		return (0);
296d7854da1SMatthew D Fleming 	val = desc[zone_offset % len];
297d7854da1SMatthew D Fleming 	return (val % numzones);
298d7854da1SMatthew D Fleming }
299d7854da1SMatthew D Fleming #elif MALLOC_DEBUG_MAXZONES == 0
300d7854da1SMatthew D Fleming #error "MALLOC_DEBUG_MAXZONES must be positive."
301d7854da1SMatthew D Fleming #else
302d7854da1SMatthew D Fleming static inline u_int
303d7854da1SMatthew D Fleming mtp_get_subzone(const char *desc)
304d7854da1SMatthew D Fleming {
305d7854da1SMatthew D Fleming 
306d7854da1SMatthew D Fleming 	return (0);
307d7854da1SMatthew D Fleming }
308d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
309d7854da1SMatthew D Fleming 
3101fb14a47SPoul-Henning Kamp int
3111fb14a47SPoul-Henning Kamp malloc_last_fail(void)
3121fb14a47SPoul-Henning Kamp {
3131fb14a47SPoul-Henning Kamp 
3141fb14a47SPoul-Henning Kamp 	return (time_uptime - t_malloc_fail);
3151fb14a47SPoul-Henning Kamp }
3161fb14a47SPoul-Henning Kamp 
317df8bae1dSRodney W. Grimes /*
3180ce3f16dSRobert Watson  * An allocation has succeeded -- update malloc type statistics for the
3190ce3f16dSRobert Watson  * amount of bucket size.  Occurs within a critical section so that the
3200ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-PCU
3210ce3f16dSRobert Watson  * statistics.
3224362fadaSBrian Feldman  */
3234362fadaSBrian Feldman static void
32463a7e0a3SRobert Watson malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
3254362fadaSBrian Feldman     int zindx)
3264362fadaSBrian Feldman {
32763a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
32863a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
32963a7e0a3SRobert Watson 
33063a7e0a3SRobert Watson 	critical_enter();
33163a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
33263a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
33373864adbSPawel Jakub Dawidek 	if (size > 0) {
33463a7e0a3SRobert Watson 		mtsp->mts_memalloced += size;
33563a7e0a3SRobert Watson 		mtsp->mts_numallocs++;
33673864adbSPawel Jakub Dawidek 	}
3374362fadaSBrian Feldman 	if (zindx != -1)
33863a7e0a3SRobert Watson 		mtsp->mts_size |= 1 << zindx;
33991dd776cSJohn Birrell 
34091dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
34191dd776cSJohn Birrell 	if (dtrace_malloc_probe != NULL) {
34291dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
34391dd776cSJohn Birrell 		if (probe_id != 0)
34491dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
34591dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
34691dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, zindx);
34791dd776cSJohn Birrell 	}
34891dd776cSJohn Birrell #endif
34991dd776cSJohn Birrell 
35063a7e0a3SRobert Watson 	critical_exit();
3514362fadaSBrian Feldman }
3524362fadaSBrian Feldman 
3534362fadaSBrian Feldman void
35463a7e0a3SRobert Watson malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
3554362fadaSBrian Feldman {
35663a7e0a3SRobert Watson 
35773864adbSPawel Jakub Dawidek 	if (size > 0)
35863a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, size, -1);
3594362fadaSBrian Feldman }
3604362fadaSBrian Feldman 
3614362fadaSBrian Feldman /*
3623805385eSRobert Watson  * A free operation has occurred -- update malloc type statistics for the
3630ce3f16dSRobert Watson  * amount of the bucket size.  Occurs within a critical section so that the
3640ce3f16dSRobert Watson  * thread isn't preempted and doesn't migrate while updating per-CPU
3650ce3f16dSRobert Watson  * statistics.
3664362fadaSBrian Feldman  */
3674362fadaSBrian Feldman void
36863a7e0a3SRobert Watson malloc_type_freed(struct malloc_type *mtp, unsigned long size)
3694362fadaSBrian Feldman {
37063a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
37163a7e0a3SRobert Watson 	struct malloc_type_stats *mtsp;
37263a7e0a3SRobert Watson 
37363a7e0a3SRobert Watson 	critical_enter();
37463a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
37563a7e0a3SRobert Watson 	mtsp = &mtip->mti_stats[curcpu];
37663a7e0a3SRobert Watson 	mtsp->mts_memfreed += size;
37763a7e0a3SRobert Watson 	mtsp->mts_numfrees++;
37891dd776cSJohn Birrell 
37991dd776cSJohn Birrell #ifdef KDTRACE_HOOKS
38091dd776cSJohn Birrell 	if (dtrace_malloc_probe != NULL) {
38191dd776cSJohn Birrell 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
38291dd776cSJohn Birrell 		if (probe_id != 0)
38391dd776cSJohn Birrell 			(dtrace_malloc_probe)(probe_id,
38491dd776cSJohn Birrell 			    (uintptr_t) mtp, (uintptr_t) mtip,
38591dd776cSJohn Birrell 			    (uintptr_t) mtsp, size, 0);
38691dd776cSJohn Birrell 	}
38791dd776cSJohn Birrell #endif
38891dd776cSJohn Birrell 
38963a7e0a3SRobert Watson 	critical_exit();
3904362fadaSBrian Feldman }
3914362fadaSBrian Feldman 
3924362fadaSBrian Feldman /*
393f346986bSAlan Cox  *	contigmalloc:
394f346986bSAlan Cox  *
395f346986bSAlan Cox  *	Allocate a block of physically contiguous memory.
396f346986bSAlan Cox  *
397f346986bSAlan Cox  *	If M_NOWAIT is set, this routine will not block and return NULL if
398f346986bSAlan Cox  *	the allocation fails.
399f346986bSAlan Cox  */
400f346986bSAlan Cox void *
401f346986bSAlan Cox contigmalloc(unsigned long size, struct malloc_type *type, int flags,
402f346986bSAlan Cox     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
403831ce4cbSJohn Baldwin     vm_paddr_t boundary)
404f346986bSAlan Cox {
405f346986bSAlan Cox 	void *ret;
406f346986bSAlan Cox 
4075df87b21SJeff Roberson 	ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
408f346986bSAlan Cox 	    alignment, boundary, VM_MEMATTR_DEFAULT);
409f346986bSAlan Cox 	if (ret != NULL)
410f346986bSAlan Cox 		malloc_type_allocated(type, round_page(size));
411f346986bSAlan Cox 	return (ret);
412f346986bSAlan Cox }
413f346986bSAlan Cox 
414f346986bSAlan Cox /*
415f346986bSAlan Cox  *	contigfree:
416f346986bSAlan Cox  *
417f346986bSAlan Cox  *	Free a block of memory allocated by contigmalloc.
418f346986bSAlan Cox  *
419f346986bSAlan Cox  *	This routine may not block.
420f346986bSAlan Cox  */
421f346986bSAlan Cox void
422f346986bSAlan Cox contigfree(void *addr, unsigned long size, struct malloc_type *type)
423f346986bSAlan Cox {
424f346986bSAlan Cox 
4255df87b21SJeff Roberson 	kmem_free(kernel_arena, (vm_offset_t)addr, size);
426f346986bSAlan Cox 	malloc_type_freed(type, round_page(size));
427f346986bSAlan Cox }
428f346986bSAlan Cox 
429f346986bSAlan Cox /*
4301c7c3c6aSMatthew Dillon  *	malloc:
4311c7c3c6aSMatthew Dillon  *
4321c7c3c6aSMatthew Dillon  *	Allocate a block of memory.
4331c7c3c6aSMatthew Dillon  *
4341c7c3c6aSMatthew Dillon  *	If M_NOWAIT is set, this routine will not block and return NULL if
4351c7c3c6aSMatthew Dillon  *	the allocation fails.
436df8bae1dSRodney W. Grimes  */
437df8bae1dSRodney W. Grimes void *
43863a7e0a3SRobert Watson malloc(unsigned long size, struct malloc_type *mtp, int flags)
439df8bae1dSRodney W. Grimes {
4406f267175SJeff Roberson 	int indx;
441d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
4428355f576SJeff Roberson 	caddr_t va;
4438355f576SJeff Roberson 	uma_zone_t zone;
444847a2a17SPawel Jakub Dawidek #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
4454db4f5c8SPoul-Henning Kamp 	unsigned long osize = size;
4464db4f5c8SPoul-Henning Kamp #endif
447df8bae1dSRodney W. Grimes 
448194a0abfSPoul-Henning Kamp #ifdef INVARIANTS
449bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
450d3c11994SPoul-Henning Kamp 	/*
45123198357SRuslan Ermilov 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
452d3c11994SPoul-Henning Kamp 	 */
45323198357SRuslan Ermilov 	indx = flags & (M_WAITOK | M_NOWAIT);
454d3c11994SPoul-Henning Kamp 	if (indx != M_NOWAIT && indx != M_WAITOK) {
455d3c11994SPoul-Henning Kamp 		static	struct timeval lasterr;
456d3c11994SPoul-Henning Kamp 		static	int curerr, once;
457d3c11994SPoul-Henning Kamp 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
458d3c11994SPoul-Henning Kamp 			printf("Bad malloc flags: %x\n", indx);
4592d50560aSMarcel Moolenaar 			kdb_backtrace();
460d3c11994SPoul-Henning Kamp 			flags |= M_WAITOK;
461d3c11994SPoul-Henning Kamp 			once++;
462d3c11994SPoul-Henning Kamp 		}
463d3c11994SPoul-Henning Kamp 	}
464194a0abfSPoul-Henning Kamp #endif
465eae870cdSRobert Watson #ifdef MALLOC_MAKE_FAILURES
466eae870cdSRobert Watson 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
467eae870cdSRobert Watson 		atomic_add_int(&malloc_nowait_count, 1);
468eae870cdSRobert Watson 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
469eae870cdSRobert Watson 			atomic_add_int(&malloc_failure_count, 1);
4703f6ee876SPoul-Henning Kamp 			t_malloc_fail = time_uptime;
471eae870cdSRobert Watson 			return (NULL);
472eae870cdSRobert Watson 		}
473eae870cdSRobert Watson 	}
474eae870cdSRobert Watson #endif
475d3c11994SPoul-Henning Kamp 	if (flags & M_WAITOK)
476b40ce416SJulian Elischer 		KASSERT(curthread->td_intr_nesting_level == 0,
477a163d034SWarner Losh 		   ("malloc(M_WAITOK) in interrupt context"));
478e4eb384bSBosko Milekic 
479*1067a2baSJonathan T. Looney 	KASSERT(curthread->td_critnest == 0,
480*1067a2baSJonathan T. Looney 	    ("malloc: called with spinlock or critical section held"));
481*1067a2baSJonathan T. Looney 
482e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
4838d689e04SGleb Smirnoff 	if (memguard_cmp_mtp(mtp, size)) {
484e3813573SMatthew D Fleming 		va = memguard_alloc(size, flags);
485e3813573SMatthew D Fleming 		if (va != NULL)
486e3813573SMatthew D Fleming 			return (va);
487e3813573SMatthew D Fleming 		/* This is unfortunate but should not be fatal. */
488e3813573SMatthew D Fleming 	}
489e4eb384bSBosko Milekic #endif
490e4eb384bSBosko Milekic 
491847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
492847a2a17SPawel Jakub Dawidek 	size = redzone_size_ntor(size);
493847a2a17SPawel Jakub Dawidek #endif
494847a2a17SPawel Jakub Dawidek 
4957001d850SXin LI 	if (size <= kmem_zmax) {
496d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
4976f267175SJeff Roberson 		if (size & KMEM_ZMASK)
4986f267175SJeff Roberson 			size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
4996f267175SJeff Roberson 		indx = kmemsize[size >> KMEM_ZSHIFT];
500d7854da1SMatthew D Fleming 		KASSERT(mtip->mti_zone < numzones,
501d7854da1SMatthew D Fleming 		    ("mti_zone %u out of range %d",
502d7854da1SMatthew D Fleming 		    mtip->mti_zone, numzones));
503d7854da1SMatthew D Fleming 		zone = kmemzones[indx].kz_zone[mtip->mti_zone];
5046f267175SJeff Roberson #ifdef MALLOC_PROFILE
5056f267175SJeff Roberson 		krequests[size >> KMEM_ZSHIFT]++;
5066f267175SJeff Roberson #endif
5078355f576SJeff Roberson 		va = uma_zalloc(zone, flags);
5084362fadaSBrian Feldman 		if (va != NULL)
509e20a199fSJeff Roberson 			size = zone->uz_size;
51063a7e0a3SRobert Watson 		malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
5118355f576SJeff Roberson 	} else {
5126f267175SJeff Roberson 		size = roundup(size, PAGE_SIZE);
5138355f576SJeff Roberson 		zone = NULL;
5148355f576SJeff Roberson 		va = uma_large_malloc(size, flags);
51563a7e0a3SRobert Watson 		malloc_type_allocated(mtp, va == NULL ? 0 : size);
516df8bae1dSRodney W. Grimes 	}
5171282e9acSPoul-Henning Kamp 	if (flags & M_WAITOK)
518a163d034SWarner Losh 		KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
5191282e9acSPoul-Henning Kamp 	else if (va == NULL)
5201fb14a47SPoul-Henning Kamp 		t_malloc_fail = time_uptime;
5214db4f5c8SPoul-Henning Kamp #ifdef DIAGNOSTIC
5221282e9acSPoul-Henning Kamp 	if (va != NULL && !(flags & M_ZERO)) {
5234db4f5c8SPoul-Henning Kamp 		memset(va, 0x70, osize);
5244db4f5c8SPoul-Henning Kamp 	}
5254db4f5c8SPoul-Henning Kamp #endif
526847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
527847a2a17SPawel Jakub Dawidek 	if (va != NULL)
528847a2a17SPawel Jakub Dawidek 		va = redzone_setup(va, osize);
529847a2a17SPawel Jakub Dawidek #endif
530df8bae1dSRodney W. Grimes 	return ((void *) va);
531df8bae1dSRodney W. Grimes }
532df8bae1dSRodney W. Grimes 
533df8bae1dSRodney W. Grimes /*
5341c7c3c6aSMatthew Dillon  *	free:
5351c7c3c6aSMatthew Dillon  *
536df8bae1dSRodney W. Grimes  *	Free a block of memory allocated by malloc.
5371c7c3c6aSMatthew Dillon  *
5381c7c3c6aSMatthew Dillon  *	This routine may not block.
539df8bae1dSRodney W. Grimes  */
540df8bae1dSRodney W. Grimes void
54163a7e0a3SRobert Watson free(void *addr, struct malloc_type *mtp)
542df8bae1dSRodney W. Grimes {
54399571dc3SJeff Roberson 	uma_slab_t slab;
54499571dc3SJeff Roberson 	u_long size;
545254c6cb3SPoul-Henning Kamp 
546bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
547bb1c7df8SRobert Watson 
548*1067a2baSJonathan T. Looney 	KASSERT(curthread->td_critnest == 0,
549*1067a2baSJonathan T. Looney 	    ("free: called with spinlock or critical section held"));
550*1067a2baSJonathan T. Looney 
55144a8ff31SArchie Cobbs 	/* free(NULL, ...) does nothing */
55244a8ff31SArchie Cobbs 	if (addr == NULL)
55344a8ff31SArchie Cobbs 		return;
55444a8ff31SArchie Cobbs 
555e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
556e3813573SMatthew D Fleming 	if (is_memguard_addr(addr)) {
557e4eb384bSBosko Milekic 		memguard_free(addr);
558e4eb384bSBosko Milekic 		return;
559e4eb384bSBosko Milekic 	}
560e4eb384bSBosko Milekic #endif
561e4eb384bSBosko Milekic 
562847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
563847a2a17SPawel Jakub Dawidek 	redzone_check(addr);
564847a2a17SPawel Jakub Dawidek 	addr = redzone_addr_ntor(addr);
565847a2a17SPawel Jakub Dawidek #endif
566847a2a17SPawel Jakub Dawidek 
56799571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
5688355f576SJeff Roberson 
5698355f576SJeff Roberson 	if (slab == NULL)
5706f267175SJeff Roberson 		panic("free: address %p(%p) has not been allocated.\n",
57199571dc3SJeff Roberson 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
57299571dc3SJeff Roberson 
5738355f576SJeff Roberson 	if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
5748f70816cSJeff Roberson #ifdef INVARIANTS
57563a7e0a3SRobert Watson 		struct malloc_type **mtpp = addr;
5768f70816cSJeff Roberson #endif
577099a0e58SBosko Milekic 		size = slab->us_keg->uk_size;
5788f70816cSJeff Roberson #ifdef INVARIANTS
5798f70816cSJeff Roberson 		/*
5808f70816cSJeff Roberson 		 * Cache a pointer to the malloc_type that most recently freed
5818f70816cSJeff Roberson 		 * this memory here.  This way we know who is most likely to
5828f70816cSJeff Roberson 		 * have stepped on it later.
5838f70816cSJeff Roberson 		 *
5848f70816cSJeff Roberson 		 * This code assumes that size is a multiple of 8 bytes for
5858f70816cSJeff Roberson 		 * 64 bit machines
5868f70816cSJeff Roberson 		 */
58763a7e0a3SRobert Watson 		mtpp = (struct malloc_type **)
58863a7e0a3SRobert Watson 		    ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
58963a7e0a3SRobert Watson 		mtpp += (size - sizeof(struct malloc_type *)) /
5908f70816cSJeff Roberson 		    sizeof(struct malloc_type *);
59163a7e0a3SRobert Watson 		*mtpp = mtp;
5928f70816cSJeff Roberson #endif
593099a0e58SBosko Milekic 		uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
59414bf02f8SJohn Dyson 	} else {
5958355f576SJeff Roberson 		size = slab->us_size;
5968355f576SJeff Roberson 		uma_large_free(slab);
59714bf02f8SJohn Dyson 	}
59863a7e0a3SRobert Watson 	malloc_type_freed(mtp, size);
599df8bae1dSRodney W. Grimes }
600df8bae1dSRodney W. Grimes 
601df8bae1dSRodney W. Grimes /*
60244a8ff31SArchie Cobbs  *	realloc: change the size of a memory block
60344a8ff31SArchie Cobbs  */
60444a8ff31SArchie Cobbs void *
60563a7e0a3SRobert Watson realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
60644a8ff31SArchie Cobbs {
6078355f576SJeff Roberson 	uma_slab_t slab;
60844a8ff31SArchie Cobbs 	unsigned long alloc;
60944a8ff31SArchie Cobbs 	void *newaddr;
61044a8ff31SArchie Cobbs 
611bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
612bb1c7df8SRobert Watson 	    ("realloc: bad malloc type magic"));
613bb1c7df8SRobert Watson 
614*1067a2baSJonathan T. Looney 	KASSERT(curthread->td_critnest == 0,
615*1067a2baSJonathan T. Looney 	    ("realloc: called with spinlock or critical section held"));
616*1067a2baSJonathan T. Looney 
61744a8ff31SArchie Cobbs 	/* realloc(NULL, ...) is equivalent to malloc(...) */
61844a8ff31SArchie Cobbs 	if (addr == NULL)
61963a7e0a3SRobert Watson 		return (malloc(size, mtp, flags));
62063a7e0a3SRobert Watson 
62163a7e0a3SRobert Watson 	/*
62263a7e0a3SRobert Watson 	 * XXX: Should report free of old memory and alloc of new memory to
62363a7e0a3SRobert Watson 	 * per-CPU stats.
62463a7e0a3SRobert Watson 	 */
62544a8ff31SArchie Cobbs 
626e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
6276d3ed393SMatthew D Fleming 	if (is_memguard_addr(addr))
6286d3ed393SMatthew D Fleming 		return (memguard_realloc(addr, size, mtp, flags));
629e4eb384bSBosko Milekic #endif
630e4eb384bSBosko Milekic 
631847a2a17SPawel Jakub Dawidek #ifdef DEBUG_REDZONE
632847a2a17SPawel Jakub Dawidek 	slab = NULL;
633847a2a17SPawel Jakub Dawidek 	alloc = redzone_get_size(addr);
634847a2a17SPawel Jakub Dawidek #else
63599571dc3SJeff Roberson 	slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
6368355f576SJeff Roberson 
63744a8ff31SArchie Cobbs 	/* Sanity check */
6388355f576SJeff Roberson 	KASSERT(slab != NULL,
63944a8ff31SArchie Cobbs 	    ("realloc: address %p out of range", (void *)addr));
64044a8ff31SArchie Cobbs 
64144a8ff31SArchie Cobbs 	/* Get the size of the original block */
642619f2841SPawel Jakub Dawidek 	if (!(slab->us_flags & UMA_SLAB_MALLOC))
643099a0e58SBosko Milekic 		alloc = slab->us_keg->uk_size;
6448355f576SJeff Roberson 	else
6458355f576SJeff Roberson 		alloc = slab->us_size;
64644a8ff31SArchie Cobbs 
64744a8ff31SArchie Cobbs 	/* Reuse the original block if appropriate */
64844a8ff31SArchie Cobbs 	if (size <= alloc
64944a8ff31SArchie Cobbs 	    && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
65044a8ff31SArchie Cobbs 		return (addr);
651847a2a17SPawel Jakub Dawidek #endif /* !DEBUG_REDZONE */
65244a8ff31SArchie Cobbs 
65344a8ff31SArchie Cobbs 	/* Allocate a new, bigger (or smaller) block */
65463a7e0a3SRobert Watson 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
65544a8ff31SArchie Cobbs 		return (NULL);
65644a8ff31SArchie Cobbs 
65744a8ff31SArchie Cobbs 	/* Copy over original contents */
65844a8ff31SArchie Cobbs 	bcopy(addr, newaddr, min(size, alloc));
65963a7e0a3SRobert Watson 	free(addr, mtp);
66044a8ff31SArchie Cobbs 	return (newaddr);
66144a8ff31SArchie Cobbs }
66244a8ff31SArchie Cobbs 
66344a8ff31SArchie Cobbs /*
66444a8ff31SArchie Cobbs  *	reallocf: same as realloc() but free memory on failure.
66544a8ff31SArchie Cobbs  */
66644a8ff31SArchie Cobbs void *
66763a7e0a3SRobert Watson reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
66844a8ff31SArchie Cobbs {
66944a8ff31SArchie Cobbs 	void *mem;
67044a8ff31SArchie Cobbs 
67163a7e0a3SRobert Watson 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
67263a7e0a3SRobert Watson 		free(addr, mtp);
67344a8ff31SArchie Cobbs 	return (mem);
67444a8ff31SArchie Cobbs }
67544a8ff31SArchie Cobbs 
67644a8ff31SArchie Cobbs /*
67744ec2b63SKonstantin Belousov  * Wake the uma reclamation pagedaemon thread when we exhaust KVA.  It
67844ec2b63SKonstantin Belousov  * will call the lowmem handler and uma_reclaim() callbacks in a
67944ec2b63SKonstantin Belousov  * context that is safe.
680df8bae1dSRodney W. Grimes  */
6812b14f991SJulian Elischer static void
6825df87b21SJeff Roberson kmem_reclaim(vmem_t *vm, int flags)
683df8bae1dSRodney W. Grimes {
6848a58a9f6SJohn Dyson 
68544ec2b63SKonstantin Belousov 	uma_reclaim_wakeup();
6865df87b21SJeff Roberson 	pagedaemon_wakeup();
6875df87b21SJeff Roberson }
6885df87b21SJeff Roberson 
689f9d498adSDimitry Andric #ifndef __sparc64__
690c70af487SAlan Cox CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
691f9d498adSDimitry Andric #endif
692c70af487SAlan Cox 
6935df87b21SJeff Roberson /*
694c70af487SAlan Cox  * Initialize the kernel memory (kmem) arena.
6955df87b21SJeff Roberson  */
6965df87b21SJeff Roberson void
6975df87b21SJeff Roberson kmeminit(void)
6985df87b21SJeff Roberson {
699af3b2549SHans Petter Selasky 	u_long mem_size;
700af3b2549SHans Petter Selasky 	u_long tmp;
70169ef67f9SJason Evans 
702af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE
703af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0)
704af3b2549SHans Petter Selasky 		vm_kmem_size = VM_KMEM_SIZE;
705af3b2549SHans Petter Selasky #endif
706af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MIN
707af3b2549SHans Petter Selasky 	if (vm_kmem_size_min == 0)
708af3b2549SHans Petter Selasky 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
709af3b2549SHans Petter Selasky #endif
710af3b2549SHans Petter Selasky #ifdef VM_KMEM_SIZE_MAX
711af3b2549SHans Petter Selasky 	if (vm_kmem_size_max == 0)
712af3b2549SHans Petter Selasky 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
713af3b2549SHans Petter Selasky #endif
7148a58a9f6SJohn Dyson 	/*
715c70af487SAlan Cox 	 * Calculate the amount of kernel virtual address (KVA) space that is
716c70af487SAlan Cox 	 * preallocated to the kmem arena.  In order to support a wide range
717c70af487SAlan Cox 	 * of machines, it is a function of the physical memory size,
718c70af487SAlan Cox 	 * specifically,
7198a58a9f6SJohn Dyson 	 *
720c70af487SAlan Cox 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
721c70af487SAlan Cox 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
722c70af487SAlan Cox 	 *
723c70af487SAlan Cox 	 * Every architecture must define an integral value for
724c70af487SAlan Cox 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
725c70af487SAlan Cox 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
726c70af487SAlan Cox 	 * ceiling on this preallocation, are optional.  Typically,
727c70af487SAlan Cox 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
728c70af487SAlan Cox 	 * a given architecture.
7298a58a9f6SJohn Dyson 	 */
73044f1c916SBryan Drewery 	mem_size = vm_cnt.v_page_count;
7317c51714eSSean Bruno 	if (mem_size <= 32768) /* delphij XXX 128MB */
7327c51714eSSean Bruno 		kmem_zmax = PAGE_SIZE;
7338a58a9f6SJohn Dyson 
734c70af487SAlan Cox 	if (vm_kmem_size_scale < 1)
735c70af487SAlan Cox 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
736c70af487SAlan Cox 
737af3b2549SHans Petter Selasky 	/*
738af3b2549SHans Petter Selasky 	 * Check if we should use defaults for the "vm_kmem_size"
739af3b2549SHans Petter Selasky 	 * variable:
740af3b2549SHans Petter Selasky 	 */
741af3b2549SHans Petter Selasky 	if (vm_kmem_size == 0) {
742479439b4SDag-Erling Smørgrav 		vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
7438a58a9f6SJohn Dyson 
744c70af487SAlan Cox 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
7450e5179e4SStephane E. Potvin 			vm_kmem_size = vm_kmem_size_min;
746479439b4SDag-Erling Smørgrav 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
747479439b4SDag-Erling Smørgrav 			vm_kmem_size = vm_kmem_size_max;
748af3b2549SHans Petter Selasky 	}
7498a58a9f6SJohn Dyson 
75027b8623fSDavid Greenman 	/*
751af3b2549SHans Petter Selasky 	 * The amount of KVA space that is preallocated to the
752c70af487SAlan Cox 	 * kmem arena can be set statically at compile-time or manually
753c70af487SAlan Cox 	 * through the kernel environment.  However, it is still limited to
754c70af487SAlan Cox 	 * twice the physical memory size, which has been sufficient to handle
755c70af487SAlan Cox 	 * the most severe cases of external fragmentation in the kmem arena.
75627b8623fSDavid Greenman 	 */
757c749c003SAlan Cox 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
758c749c003SAlan Cox 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
7598a58a9f6SJohn Dyson 
760e137643eSOlivier Houchard 	vm_kmem_size = round_page(vm_kmem_size);
761e3813573SMatthew D Fleming #ifdef DEBUG_MEMGUARD
762f806cdcfSMatthew D Fleming 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
763e3813573SMatthew D Fleming #else
764e3813573SMatthew D Fleming 	tmp = vm_kmem_size;
765e3813573SMatthew D Fleming #endif
7665df87b21SJeff Roberson 	vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE,
76799de9af2SJeff Roberson 	    0, 0);
7685df87b21SJeff Roberson 	vmem_set_reclaim(kmem_arena, kmem_reclaim);
7698355f576SJeff Roberson 
770e4eb384bSBosko Milekic #ifdef DEBUG_MEMGUARD
771e4eb384bSBosko Milekic 	/*
772e4eb384bSBosko Milekic 	 * Initialize MemGuard if support compiled in.  MemGuard is a
773e4eb384bSBosko Milekic 	 * replacement allocator used for detecting tamper-after-free
774e4eb384bSBosko Milekic 	 * scenarios as they occur.  It is only used for debugging.
775e4eb384bSBosko Milekic 	 */
7765df87b21SJeff Roberson 	memguard_init(kmem_arena);
777e4eb384bSBosko Milekic #endif
7785df87b21SJeff Roberson }
7795df87b21SJeff Roberson 
7805df87b21SJeff Roberson /*
7815df87b21SJeff Roberson  * Initialize the kernel memory allocator
7825df87b21SJeff Roberson  */
7835df87b21SJeff Roberson /* ARGSUSED*/
7845df87b21SJeff Roberson static void
7855df87b21SJeff Roberson mallocinit(void *dummy)
7865df87b21SJeff Roberson {
7875df87b21SJeff Roberson 	int i;
7885df87b21SJeff Roberson 	uint8_t indx;
7895df87b21SJeff Roberson 
7905df87b21SJeff Roberson 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
7915df87b21SJeff Roberson 
7925df87b21SJeff Roberson 	kmeminit();
793e4eb384bSBosko Milekic 
79499571dc3SJeff Roberson 	uma_startup2();
7958355f576SJeff Roberson 
7967001d850SXin LI 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
7977001d850SXin LI 		kmem_zmax = KMEM_ZMAX;
7987001d850SXin LI 
79963a7e0a3SRobert Watson 	mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
80063a7e0a3SRobert Watson #ifdef INVARIANTS
80163a7e0a3SRobert Watson 	    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
80263a7e0a3SRobert Watson #else
80363a7e0a3SRobert Watson 	    NULL, NULL, NULL, NULL,
80463a7e0a3SRobert Watson #endif
80563a7e0a3SRobert Watson 	    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
8066f267175SJeff Roberson 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
8076f267175SJeff Roberson 		int size = kmemzones[indx].kz_size;
8086f267175SJeff Roberson 		char *name = kmemzones[indx].kz_name;
809d7854da1SMatthew D Fleming 		int subzone;
8108355f576SJeff Roberson 
811d7854da1SMatthew D Fleming 		for (subzone = 0; subzone < numzones; subzone++) {
812d7854da1SMatthew D Fleming 			kmemzones[indx].kz_zone[subzone] =
813d7854da1SMatthew D Fleming 			    uma_zcreate(name, size,
8148efc4effSJeff Roberson #ifdef INVARIANTS
8158f70816cSJeff Roberson 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
8168efc4effSJeff Roberson #else
8178efc4effSJeff Roberson 			    NULL, NULL, NULL, NULL,
8188efc4effSJeff Roberson #endif
8198efc4effSJeff Roberson 			    UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
820d7854da1SMatthew D Fleming 		}
8218355f576SJeff Roberson 		for (;i <= size; i+= KMEM_ZBASE)
8226f267175SJeff Roberson 			kmemsize[i >> KMEM_ZSHIFT] = indx;
8238355f576SJeff Roberson 
824df8bae1dSRodney W. Grimes 	}
825254c6cb3SPoul-Henning Kamp }
826af3b2549SHans Petter Selasky SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
827254c6cb3SPoul-Henning Kamp 
828db669378SPeter Wemm void
82987efd4d5SRobert Watson malloc_init(void *data)
830254c6cb3SPoul-Henning Kamp {
83163a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
83263a7e0a3SRobert Watson 	struct malloc_type *mtp;
83363a7e0a3SRobert Watson 
83444f1c916SBryan Drewery 	KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
83563a7e0a3SRobert Watson 
83663a7e0a3SRobert Watson 	mtp = data;
837f121baaaSBrian Somers 	if (mtp->ks_magic != M_MAGIC)
838f121baaaSBrian Somers 		panic("malloc_init: bad malloc type magic");
839bb1c7df8SRobert Watson 
84063a7e0a3SRobert Watson 	mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
84163a7e0a3SRobert Watson 	mtp->ks_handle = mtip;
842d7854da1SMatthew D Fleming 	mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
843254c6cb3SPoul-Henning Kamp 
8446f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
84563a7e0a3SRobert Watson 	mtp->ks_next = kmemstatistics;
84663a7e0a3SRobert Watson 	kmemstatistics = mtp;
847cd814b26SRobert Watson 	kmemcount++;
8486f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
849df8bae1dSRodney W. Grimes }
850db669378SPeter Wemm 
851db669378SPeter Wemm void
85287efd4d5SRobert Watson malloc_uninit(void *data)
853db669378SPeter Wemm {
85463a7e0a3SRobert Watson 	struct malloc_type_internal *mtip;
8552a143d5bSPawel Jakub Dawidek 	struct malloc_type_stats *mtsp;
85663a7e0a3SRobert Watson 	struct malloc_type *mtp, *temp;
85745d48bdaSPaul Saab 	uma_slab_t slab;
8582a143d5bSPawel Jakub Dawidek 	long temp_allocs, temp_bytes;
8592a143d5bSPawel Jakub Dawidek 	int i;
860db669378SPeter Wemm 
86163a7e0a3SRobert Watson 	mtp = data;
862bb1c7df8SRobert Watson 	KASSERT(mtp->ks_magic == M_MAGIC,
863bb1c7df8SRobert Watson 	    ("malloc_uninit: bad malloc type magic"));
86463a7e0a3SRobert Watson 	KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
865bb1c7df8SRobert Watson 
8666f267175SJeff Roberson 	mtx_lock(&malloc_mtx);
86763a7e0a3SRobert Watson 	mtip = mtp->ks_handle;
86863a7e0a3SRobert Watson 	mtp->ks_handle = NULL;
86963a7e0a3SRobert Watson 	if (mtp != kmemstatistics) {
87063a7e0a3SRobert Watson 		for (temp = kmemstatistics; temp != NULL;
87163a7e0a3SRobert Watson 		    temp = temp->ks_next) {
872f121baaaSBrian Somers 			if (temp->ks_next == mtp) {
87363a7e0a3SRobert Watson 				temp->ks_next = mtp->ks_next;
874f121baaaSBrian Somers 				break;
875db669378SPeter Wemm 			}
876f121baaaSBrian Somers 		}
877f121baaaSBrian Somers 		KASSERT(temp,
878f121baaaSBrian Somers 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
87963a7e0a3SRobert Watson 	} else
88063a7e0a3SRobert Watson 		kmemstatistics = mtp->ks_next;
881cd814b26SRobert Watson 	kmemcount--;
8826f267175SJeff Roberson 	mtx_unlock(&malloc_mtx);
8832a143d5bSPawel Jakub Dawidek 
8842a143d5bSPawel Jakub Dawidek 	/*
8852a143d5bSPawel Jakub Dawidek 	 * Look for memory leaks.
8862a143d5bSPawel Jakub Dawidek 	 */
8872a143d5bSPawel Jakub Dawidek 	temp_allocs = temp_bytes = 0;
8882a143d5bSPawel Jakub Dawidek 	for (i = 0; i < MAXCPU; i++) {
8892a143d5bSPawel Jakub Dawidek 		mtsp = &mtip->mti_stats[i];
8902a143d5bSPawel Jakub Dawidek 		temp_allocs += mtsp->mts_numallocs;
8912a143d5bSPawel Jakub Dawidek 		temp_allocs -= mtsp->mts_numfrees;
8922a143d5bSPawel Jakub Dawidek 		temp_bytes += mtsp->mts_memalloced;
8932a143d5bSPawel Jakub Dawidek 		temp_bytes -= mtsp->mts_memfreed;
8942a143d5bSPawel Jakub Dawidek 	}
8952a143d5bSPawel Jakub Dawidek 	if (temp_allocs > 0 || temp_bytes > 0) {
8962a143d5bSPawel Jakub Dawidek 		printf("Warning: memory type %s leaked memory on destroy "
8972a143d5bSPawel Jakub Dawidek 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
8982a143d5bSPawel Jakub Dawidek 		    temp_allocs, temp_bytes);
8992a143d5bSPawel Jakub Dawidek 	}
9002a143d5bSPawel Jakub Dawidek 
90145d48bdaSPaul Saab 	slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
90245d48bdaSPaul Saab 	uma_zfree_arg(mt_zone, mtip, slab);
903db669378SPeter Wemm }
9046f267175SJeff Roberson 
905d362c40dSPawel Jakub Dawidek struct malloc_type *
906d362c40dSPawel Jakub Dawidek malloc_desc2type(const char *desc)
907d362c40dSPawel Jakub Dawidek {
908d362c40dSPawel Jakub Dawidek 	struct malloc_type *mtp;
909d362c40dSPawel Jakub Dawidek 
910d362c40dSPawel Jakub Dawidek 	mtx_assert(&malloc_mtx, MA_OWNED);
911d362c40dSPawel Jakub Dawidek 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
912d362c40dSPawel Jakub Dawidek 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
913d362c40dSPawel Jakub Dawidek 			return (mtp);
914d362c40dSPawel Jakub Dawidek 	}
915d362c40dSPawel Jakub Dawidek 	return (NULL);
916d362c40dSPawel Jakub Dawidek }
917d362c40dSPawel Jakub Dawidek 
9186f267175SJeff Roberson static int
919cd814b26SRobert Watson sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
920cd814b26SRobert Watson {
921cd814b26SRobert Watson 	struct malloc_type_stream_header mtsh;
922cd814b26SRobert Watson 	struct malloc_type_internal *mtip;
923cd814b26SRobert Watson 	struct malloc_type_header mth;
924cd814b26SRobert Watson 	struct malloc_type *mtp;
9254e657159SMatthew D Fleming 	int error, i;
926cd814b26SRobert Watson 	struct sbuf sbuf;
927cd814b26SRobert Watson 
92800f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
92900f0e671SMatthew D Fleming 	if (error != 0)
93000f0e671SMatthew D Fleming 		return (error);
9314e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
9321eafc078SIan Lepore 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
933cd814b26SRobert Watson 	mtx_lock(&malloc_mtx);
934cd814b26SRobert Watson 
935cd814b26SRobert Watson 	/*
936cd814b26SRobert Watson 	 * Insert stream header.
937cd814b26SRobert Watson 	 */
938cd814b26SRobert Watson 	bzero(&mtsh, sizeof(mtsh));
939cd814b26SRobert Watson 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
940cd814b26SRobert Watson 	mtsh.mtsh_maxcpus = MAXCPU;
941cd814b26SRobert Watson 	mtsh.mtsh_count = kmemcount;
9424e657159SMatthew D Fleming 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
943cd814b26SRobert Watson 
944cd814b26SRobert Watson 	/*
945cd814b26SRobert Watson 	 * Insert alternating sequence of type headers and type statistics.
946cd814b26SRobert Watson 	 */
947cd814b26SRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
948cd814b26SRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
949cd814b26SRobert Watson 
950cd814b26SRobert Watson 		/*
951cd814b26SRobert Watson 		 * Insert type header.
952cd814b26SRobert Watson 		 */
953cd814b26SRobert Watson 		bzero(&mth, sizeof(mth));
954cd814b26SRobert Watson 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
9554e657159SMatthew D Fleming 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
956cd814b26SRobert Watson 
957cd814b26SRobert Watson 		/*
958cd814b26SRobert Watson 		 * Insert type statistics for each CPU.
959cd814b26SRobert Watson 		 */
960cd814b26SRobert Watson 		for (i = 0; i < MAXCPU; i++) {
9614e657159SMatthew D Fleming 			(void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
9624e657159SMatthew D Fleming 			    sizeof(mtip->mti_stats[i]));
963cd814b26SRobert Watson 		}
964cd814b26SRobert Watson 	}
965cd814b26SRobert Watson 	mtx_unlock(&malloc_mtx);
9664e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
967cd814b26SRobert Watson 	sbuf_delete(&sbuf);
968cd814b26SRobert Watson 	return (error);
969cd814b26SRobert Watson }
970cd814b26SRobert Watson 
971cd814b26SRobert Watson SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
972cd814b26SRobert Watson     0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
973cd814b26SRobert Watson     "Return malloc types");
974cd814b26SRobert Watson 
975cd814b26SRobert Watson SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
976cd814b26SRobert Watson     "Count of kernel malloc types");
977cd814b26SRobert Watson 
97891dd776cSJohn Birrell void
97991dd776cSJohn Birrell malloc_type_list(malloc_type_list_func_t *func, void *arg)
98091dd776cSJohn Birrell {
98191dd776cSJohn Birrell 	struct malloc_type *mtp, **bufmtp;
98291dd776cSJohn Birrell 	int count, i;
98391dd776cSJohn Birrell 	size_t buflen;
98491dd776cSJohn Birrell 
98591dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
98691dd776cSJohn Birrell restart:
98791dd776cSJohn Birrell 	mtx_assert(&malloc_mtx, MA_OWNED);
98891dd776cSJohn Birrell 	count = kmemcount;
98991dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
99091dd776cSJohn Birrell 
99191dd776cSJohn Birrell 	buflen = sizeof(struct malloc_type *) * count;
99291dd776cSJohn Birrell 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
99391dd776cSJohn Birrell 
99491dd776cSJohn Birrell 	mtx_lock(&malloc_mtx);
99591dd776cSJohn Birrell 
99691dd776cSJohn Birrell 	if (count < kmemcount) {
99791dd776cSJohn Birrell 		free(bufmtp, M_TEMP);
99891dd776cSJohn Birrell 		goto restart;
99991dd776cSJohn Birrell 	}
100091dd776cSJohn Birrell 
100191dd776cSJohn Birrell 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
100291dd776cSJohn Birrell 		bufmtp[i] = mtp;
100391dd776cSJohn Birrell 
100491dd776cSJohn Birrell 	mtx_unlock(&malloc_mtx);
100591dd776cSJohn Birrell 
100691dd776cSJohn Birrell 	for (i = 0; i < count; i++)
100791dd776cSJohn Birrell 		(func)(bufmtp[i], arg);
100891dd776cSJohn Birrell 
100991dd776cSJohn Birrell 	free(bufmtp, M_TEMP);
101091dd776cSJohn Birrell }
101191dd776cSJohn Birrell 
1012909ed16cSRobert Watson #ifdef DDB
1013909ed16cSRobert Watson DB_SHOW_COMMAND(malloc, db_show_malloc)
1014909ed16cSRobert Watson {
1015909ed16cSRobert Watson 	struct malloc_type_internal *mtip;
1016909ed16cSRobert Watson 	struct malloc_type *mtp;
101760ae52f7SEd Schouten 	uint64_t allocs, frees;
101860ae52f7SEd Schouten 	uint64_t alloced, freed;
1019909ed16cSRobert Watson 	int i;
1020909ed16cSRobert Watson 
102124076d13SRobert Watson 	db_printf("%18s %12s  %12s %12s\n", "Type", "InUse", "MemUse",
102224076d13SRobert Watson 	    "Requests");
1023909ed16cSRobert Watson 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1024909ed16cSRobert Watson 		mtip = (struct malloc_type_internal *)mtp->ks_handle;
1025909ed16cSRobert Watson 		allocs = 0;
1026909ed16cSRobert Watson 		frees = 0;
102724076d13SRobert Watson 		alloced = 0;
102824076d13SRobert Watson 		freed = 0;
1029909ed16cSRobert Watson 		for (i = 0; i < MAXCPU; i++) {
1030909ed16cSRobert Watson 			allocs += mtip->mti_stats[i].mts_numallocs;
1031909ed16cSRobert Watson 			frees += mtip->mti_stats[i].mts_numfrees;
103224076d13SRobert Watson 			alloced += mtip->mti_stats[i].mts_memalloced;
103324076d13SRobert Watson 			freed += mtip->mti_stats[i].mts_memfreed;
1034909ed16cSRobert Watson 		}
103524076d13SRobert Watson 		db_printf("%18s %12ju %12juK %12ju\n",
103624076d13SRobert Watson 		    mtp->ks_shortdesc, allocs - frees,
103724076d13SRobert Watson 		    (alloced - freed + 1023) / 1024, allocs);
1038687c94aaSJohn Baldwin 		if (db_pager_quit)
1039687c94aaSJohn Baldwin 			break;
1040909ed16cSRobert Watson 	}
1041909ed16cSRobert Watson }
1042d7854da1SMatthew D Fleming 
1043d7854da1SMatthew D Fleming #if MALLOC_DEBUG_MAXZONES > 1
1044d7854da1SMatthew D Fleming DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1045d7854da1SMatthew D Fleming {
1046d7854da1SMatthew D Fleming 	struct malloc_type_internal *mtip;
1047d7854da1SMatthew D Fleming 	struct malloc_type *mtp;
1048d7854da1SMatthew D Fleming 	u_int subzone;
1049d7854da1SMatthew D Fleming 
1050d7854da1SMatthew D Fleming 	if (!have_addr) {
1051d7854da1SMatthew D Fleming 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1052d7854da1SMatthew D Fleming 		return;
1053d7854da1SMatthew D Fleming 	}
1054d7854da1SMatthew D Fleming 	mtp = (void *)addr;
1055d7854da1SMatthew D Fleming 	if (mtp->ks_magic != M_MAGIC) {
1056d7854da1SMatthew D Fleming 		db_printf("Magic %lx does not match expected %x\n",
1057d7854da1SMatthew D Fleming 		    mtp->ks_magic, M_MAGIC);
1058d7854da1SMatthew D Fleming 		return;
1059d7854da1SMatthew D Fleming 	}
1060d7854da1SMatthew D Fleming 
1061d7854da1SMatthew D Fleming 	mtip = mtp->ks_handle;
1062d7854da1SMatthew D Fleming 	subzone = mtip->mti_zone;
1063d7854da1SMatthew D Fleming 
1064d7854da1SMatthew D Fleming 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1065d7854da1SMatthew D Fleming 		mtip = mtp->ks_handle;
1066d7854da1SMatthew D Fleming 		if (mtip->mti_zone != subzone)
1067d7854da1SMatthew D Fleming 			continue;
1068d7854da1SMatthew D Fleming 		db_printf("%s\n", mtp->ks_shortdesc);
1069687c94aaSJohn Baldwin 		if (db_pager_quit)
1070687c94aaSJohn Baldwin 			break;
1071d7854da1SMatthew D Fleming 	}
1072d7854da1SMatthew D Fleming }
1073d7854da1SMatthew D Fleming #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1074d7854da1SMatthew D Fleming #endif /* DDB */
1075909ed16cSRobert Watson 
10765e914b96SJeff Roberson #ifdef MALLOC_PROFILE
10775e914b96SJeff Roberson 
10785e914b96SJeff Roberson static int
10795e914b96SJeff Roberson sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
10805e914b96SJeff Roberson {
108163a7e0a3SRobert Watson 	struct sbuf sbuf;
10825e914b96SJeff Roberson 	uint64_t count;
10835e914b96SJeff Roberson 	uint64_t waste;
10845e914b96SJeff Roberson 	uint64_t mem;
10855e914b96SJeff Roberson 	int error;
10865e914b96SJeff Roberson 	int rsize;
10875e914b96SJeff Roberson 	int size;
10885e914b96SJeff Roberson 	int i;
10895e914b96SJeff Roberson 
10905e914b96SJeff Roberson 	waste = 0;
10915e914b96SJeff Roberson 	mem = 0;
10925e914b96SJeff Roberson 
109300f0e671SMatthew D Fleming 	error = sysctl_wire_old_buffer(req, 0);
109400f0e671SMatthew D Fleming 	if (error != 0)
109500f0e671SMatthew D Fleming 		return (error);
10964e657159SMatthew D Fleming 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
109763a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
10985e914b96SJeff Roberson 	    "\n  Size                    Requests  Real Size\n");
10995e914b96SJeff Roberson 	for (i = 0; i < KMEM_ZSIZE; i++) {
11005e914b96SJeff Roberson 		size = i << KMEM_ZSHIFT;
11015e914b96SJeff Roberson 		rsize = kmemzones[kmemsize[i]].kz_size;
11025e914b96SJeff Roberson 		count = (long long unsigned)krequests[i];
11035e914b96SJeff Roberson 
110463a7e0a3SRobert Watson 		sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
110563a7e0a3SRobert Watson 		    (unsigned long long)count, rsize);
11065e914b96SJeff Roberson 
11075e914b96SJeff Roberson 		if ((rsize * count) > (size * count))
11085e914b96SJeff Roberson 			waste += (rsize * count) - (size * count);
11095e914b96SJeff Roberson 		mem += (rsize * count);
11105e914b96SJeff Roberson 	}
111163a7e0a3SRobert Watson 	sbuf_printf(&sbuf,
11125e914b96SJeff Roberson 	    "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
11135e914b96SJeff Roberson 	    (unsigned long long)mem, (unsigned long long)waste);
11144e657159SMatthew D Fleming 	error = sbuf_finish(&sbuf);
111563a7e0a3SRobert Watson 	sbuf_delete(&sbuf);
11165e914b96SJeff Roberson 	return (error);
11175e914b96SJeff Roberson }
11185e914b96SJeff Roberson 
11195e914b96SJeff Roberson SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
11205e914b96SJeff Roberson     NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
11215e914b96SJeff Roberson #endif /* MALLOC_PROFILE */
1122