xref: /freebsd-13-stable/sys/kern/kern_malloc.c (revision d7670d965c3fc3dcb36162a5054356524b3fd4ce)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1987, 1991, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2005-2009 Robert N. M. Watson
7  * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_malloc.c	8.3 (Berkeley) 1/4/94
35  */
36 
37 /*
38  * Kernel malloc(9) implementation -- general purpose kernel memory allocator
39  * based on memory types.  Back end is implemented using the UMA(9) zone
40  * allocator.  A set of fixed-size buckets are used for smaller allocations,
41  * and a special UMA allocation interface is used for larger allocations.
42  * Callers declare memory types, and statistics are maintained independently
43  * for each memory type.  Statistics are maintained per-CPU for performance
44  * reasons.  See malloc(9) and comments in malloc.h for a detailed
45  * description.
46  */
47 
48 #include <sys/cdefs.h>
49 #include "opt_ddb.h"
50 #include "opt_vm.h"
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/asan.h>
55 #include <sys/kdb.h>
56 #include <sys/kernel.h>
57 #include <sys/lock.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/vmmeter.h>
61 #include <sys/proc.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/smp.h>
65 #include <sys/sysctl.h>
66 #include <sys/time.h>
67 #include <sys/vmem.h>
68 #ifdef EPOCH_TRACE
69 #include <sys/epoch.h>
70 #endif
71 
72 #include <vm/vm.h>
73 #include <vm/pmap.h>
74 #include <vm/vm_domainset.h>
75 #include <vm/vm_pageout.h>
76 #include <vm/vm_param.h>
77 #include <vm/vm_kern.h>
78 #include <vm/vm_extern.h>
79 #include <vm/vm_map.h>
80 #include <vm/vm_page.h>
81 #include <vm/vm_phys.h>
82 #include <vm/vm_pagequeue.h>
83 #include <vm/uma.h>
84 #include <vm/uma_int.h>
85 #include <vm/uma_dbg.h>
86 
87 #ifdef DEBUG_MEMGUARD
88 #include <vm/memguard.h>
89 #endif
90 #ifdef DEBUG_REDZONE
91 #include <vm/redzone.h>
92 #endif
93 
94 #if defined(INVARIANTS) && defined(__i386__)
95 #include <machine/cpu.h>
96 #endif
97 
98 #include <ddb/ddb.h>
99 
100 #ifdef KDTRACE_HOOKS
101 #include <sys/dtrace_bsd.h>
102 
103 bool	__read_frequently			dtrace_malloc_enabled;
104 dtrace_malloc_probe_func_t __read_mostly	dtrace_malloc_probe;
105 #endif
106 
107 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) ||		\
108     defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
109 #define	MALLOC_DEBUG	1
110 #endif
111 
112 #if defined(KASAN) || defined(DEBUG_REDZONE)
113 #define	DEBUG_REDZONE_ARG_DEF	, unsigned long osize
114 #define	DEBUG_REDZONE_ARG	, osize
115 #else
116 #define	DEBUG_REDZONE_ARG_DEF
117 #define	DEBUG_REDZONE_ARG
118 #endif
119 
120 typedef	enum {
121 	SLAB_COOKIE_SLAB_PTR		= 0x0,
122 	SLAB_COOKIE_MALLOC_LARGE	= 0x1,
123 	SLAB_COOKIE_CONTIG_MALLOC	= 0x2,
124 } slab_cookie_t;
125 #define	SLAB_COOKIE_MASK		0x3
126 #define	SLAB_COOKIE_SHIFT		2
127 #define	GET_SLAB_COOKIE(_slab)						\
128     ((slab_cookie_t)(uintptr_t)(_slab) & SLAB_COOKIE_MASK)
129 
130 /*
131  * When realloc() is called, if the new size is sufficiently smaller than
132  * the old size, realloc() will allocate a new, smaller block to avoid
133  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
134  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
135  */
136 #ifndef REALLOC_FRACTION
137 #define	REALLOC_FRACTION	1	/* new block if <= half the size */
138 #endif
139 
140 /*
141  * Centrally define some common malloc types.
142  */
143 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
144 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
145 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
146 
147 static struct malloc_type *kmemstatistics;
148 static int kmemcount;
149 
150 #define KMEM_ZSHIFT	4
151 #define KMEM_ZBASE	16
152 #define KMEM_ZMASK	(KMEM_ZBASE - 1)
153 
154 #define KMEM_ZMAX	65536
155 #define KMEM_ZSIZE	(KMEM_ZMAX >> KMEM_ZSHIFT)
156 static uint8_t kmemsize[KMEM_ZSIZE + 1];
157 
158 #ifndef MALLOC_DEBUG_MAXZONES
159 #define	MALLOC_DEBUG_MAXZONES	1
160 #endif
161 static int numzones = MALLOC_DEBUG_MAXZONES;
162 
163 /*
164  * Small malloc(9) memory allocations are allocated from a set of UMA buckets
165  * of various sizes.
166  *
167  * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
168  *
169  * XXX: The comment here used to read "These won't be powers of two for
170  * long."  It's possible that a significant amount of wasted memory could be
171  * recovered by tuning the sizes of these buckets.
172  */
173 struct {
174 	int kz_size;
175 	const char *kz_name;
176 	uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
177 } kmemzones[] = {
178 	{16, "malloc-16", },
179 	{32, "malloc-32", },
180 	{64, "malloc-64", },
181 	{128, "malloc-128", },
182 	{256, "malloc-256", },
183 	{384, "malloc-384", },
184 	{512, "malloc-512", },
185 	{1024, "malloc-1024", },
186 	{2048, "malloc-2048", },
187 	{4096, "malloc-4096", },
188 	{8192, "malloc-8192", },
189 	{16384, "malloc-16384", },
190 	{32768, "malloc-32768", },
191 	{65536, "malloc-65536", },
192 	{0, NULL},
193 };
194 
195 u_long vm_kmem_size;
196 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
197     "Size of kernel memory");
198 
199 static u_long kmem_zmax = KMEM_ZMAX;
200 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
201     "Maximum allocation size that malloc(9) would use UMA as backend");
202 
203 static u_long vm_kmem_size_min;
204 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
205     "Minimum size of kernel memory");
206 
207 static u_long vm_kmem_size_max;
208 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
209     "Maximum size of kernel memory");
210 
211 static u_int vm_kmem_size_scale;
212 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
213     "Scale factor for kernel memory size");
214 
215 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
216 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
217     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
218     sysctl_kmem_map_size, "LU", "Current kmem allocation size");
219 
220 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
221 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
222     CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
223     sysctl_kmem_map_free, "LU", "Free space in kmem");
224 
225 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
226     "Malloc information");
227 
228 static u_int vm_malloc_zone_count = nitems(kmemzones);
229 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
230     CTLFLAG_RD, &vm_malloc_zone_count, 0,
231     "Number of malloc zones");
232 
233 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
234 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
235     CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
236     sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
237 
238 /*
239  * The malloc_mtx protects the kmemstatistics linked list.
240  */
241 struct mtx malloc_mtx;
242 
243 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
244 
245 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
246 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
247     "Kernel malloc debugging options");
248 #endif
249 
250 /*
251  * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
252  * the caller specifies M_NOWAIT.  If set to 0, no failures are caused.
253  */
254 #ifdef MALLOC_MAKE_FAILURES
255 static int malloc_failure_rate;
256 static int malloc_nowait_count;
257 static int malloc_failure_count;
258 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
259     &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
260 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
261     &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
262 #endif
263 
264 static int
sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)265 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
266 {
267 	u_long size;
268 
269 	size = uma_size();
270 	return (sysctl_handle_long(oidp, &size, 0, req));
271 }
272 
273 static int
sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)274 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
275 {
276 	u_long size, limit;
277 
278 	/* The sysctl is unsigned, implement as a saturation value. */
279 	size = uma_size();
280 	limit = uma_limit();
281 	if (size > limit)
282 		size = 0;
283 	else
284 		size = limit - size;
285 	return (sysctl_handle_long(oidp, &size, 0, req));
286 }
287 
288 static int
sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)289 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
290 {
291 	int sizes[nitems(kmemzones)];
292 	int i;
293 
294 	for (i = 0; i < nitems(kmemzones); i++) {
295 		sizes[i] = kmemzones[i].kz_size;
296 	}
297 
298 	return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
299 }
300 
301 /*
302  * malloc(9) uma zone separation -- sub-page buffer overruns in one
303  * malloc type will affect only a subset of other malloc types.
304  */
305 #if MALLOC_DEBUG_MAXZONES > 1
306 static void
tunable_set_numzones(void)307 tunable_set_numzones(void)
308 {
309 
310 	TUNABLE_INT_FETCH("debug.malloc.numzones",
311 	    &numzones);
312 
313 	/* Sanity check the number of malloc uma zones. */
314 	if (numzones <= 0)
315 		numzones = 1;
316 	if (numzones > MALLOC_DEBUG_MAXZONES)
317 		numzones = MALLOC_DEBUG_MAXZONES;
318 }
319 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
320 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
321     &numzones, 0, "Number of malloc uma subzones");
322 
323 /*
324  * Any number that changes regularly is an okay choice for the
325  * offset.  Build numbers are pretty good of you have them.
326  */
327 static u_int zone_offset = __FreeBSD_version;
328 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
329 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
330     &zone_offset, 0, "Separate malloc types by examining the "
331     "Nth character in the malloc type short description.");
332 
333 static void
mtp_set_subzone(struct malloc_type * mtp)334 mtp_set_subzone(struct malloc_type *mtp)
335 {
336 	struct malloc_type_internal *mtip;
337 	const char *desc;
338 	size_t len;
339 	u_int val;
340 
341 	mtip = &mtp->ks_mti;
342 	desc = mtp->ks_shortdesc;
343 	if (desc == NULL || (len = strlen(desc)) == 0)
344 		val = 0;
345 	else
346 		val = desc[zone_offset % len];
347 	mtip->mti_zone = (val % numzones);
348 }
349 
350 static inline u_int
mtp_get_subzone(struct malloc_type * mtp)351 mtp_get_subzone(struct malloc_type *mtp)
352 {
353 	struct malloc_type_internal *mtip;
354 
355 	mtip = &mtp->ks_mti;
356 
357 	KASSERT(mtip->mti_zone < numzones,
358 	    ("mti_zone %u out of range %d",
359 	    mtip->mti_zone, numzones));
360 	return (mtip->mti_zone);
361 }
362 #elif MALLOC_DEBUG_MAXZONES == 0
363 #error "MALLOC_DEBUG_MAXZONES must be positive."
364 #else
365 static void
mtp_set_subzone(struct malloc_type * mtp)366 mtp_set_subzone(struct malloc_type *mtp)
367 {
368 	struct malloc_type_internal *mtip;
369 
370 	mtip = &mtp->ks_mti;
371 	mtip->mti_zone = 0;
372 }
373 
374 static inline u_int
mtp_get_subzone(struct malloc_type * mtp)375 mtp_get_subzone(struct malloc_type *mtp)
376 {
377 
378 	return (0);
379 }
380 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
381 
382 /*
383  * An allocation has succeeded -- update malloc type statistics for the
384  * amount of bucket size.  Occurs within a critical section so that the
385  * thread isn't preempted and doesn't migrate while updating per-PCU
386  * statistics.
387  */
388 static void
malloc_type_zone_allocated(struct malloc_type * mtp,unsigned long size,int zindx)389 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
390     int zindx)
391 {
392 	struct malloc_type_internal *mtip;
393 	struct malloc_type_stats *mtsp;
394 
395 	critical_enter();
396 	mtip = &mtp->ks_mti;
397 	mtsp = zpcpu_get(mtip->mti_stats);
398 	if (size > 0) {
399 		mtsp->mts_memalloced += size;
400 		mtsp->mts_numallocs++;
401 	}
402 	if (zindx != -1)
403 		mtsp->mts_size |= 1 << zindx;
404 
405 #ifdef KDTRACE_HOOKS
406 	if (__predict_false(dtrace_malloc_enabled)) {
407 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
408 		if (probe_id != 0)
409 			(dtrace_malloc_probe)(probe_id,
410 			    (uintptr_t) mtp, (uintptr_t) mtip,
411 			    (uintptr_t) mtsp, size, zindx);
412 	}
413 #endif
414 
415 	critical_exit();
416 }
417 
418 void
malloc_type_allocated(struct malloc_type * mtp,unsigned long size)419 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
420 {
421 
422 	if (size > 0)
423 		malloc_type_zone_allocated(mtp, size, -1);
424 }
425 
426 /*
427  * A free operation has occurred -- update malloc type statistics for the
428  * amount of the bucket size.  Occurs within a critical section so that the
429  * thread isn't preempted and doesn't migrate while updating per-CPU
430  * statistics.
431  */
432 void
malloc_type_freed(struct malloc_type * mtp,unsigned long size)433 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
434 {
435 	struct malloc_type_internal *mtip;
436 	struct malloc_type_stats *mtsp;
437 
438 	critical_enter();
439 	mtip = &mtp->ks_mti;
440 	mtsp = zpcpu_get(mtip->mti_stats);
441 	mtsp->mts_memfreed += size;
442 	mtsp->mts_numfrees++;
443 
444 #ifdef KDTRACE_HOOKS
445 	if (__predict_false(dtrace_malloc_enabled)) {
446 		uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
447 		if (probe_id != 0)
448 			(dtrace_malloc_probe)(probe_id,
449 			    (uintptr_t) mtp, (uintptr_t) mtip,
450 			    (uintptr_t) mtsp, size, 0);
451 	}
452 #endif
453 
454 	critical_exit();
455 }
456 
457 /*
458  *	contigmalloc:
459  *
460  *	Allocate a block of physically contiguous memory.
461  *
462  *	If M_NOWAIT is set, this routine will not block and return NULL if
463  *	the allocation fails.
464  */
465 #define	IS_CONTIG_MALLOC(_slab)						\
466     (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_CONTIG_MALLOC)
467 #define	CONTIG_MALLOC_SLAB(_size)					\
468     ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_CONTIG_MALLOC))
469 static inline size_t
contigmalloc_size(uma_slab_t slab)470 contigmalloc_size(uma_slab_t slab)
471 {
472 	uintptr_t va;
473 
474 	KASSERT(IS_CONTIG_MALLOC(slab),
475 	    ("%s: called on non-contigmalloc allocation: %p", __func__, slab));
476 	va = (uintptr_t)slab;
477 	return (va >> SLAB_COOKIE_SHIFT);
478 }
479 
480 void *
contigmalloc(unsigned long size,struct malloc_type * type,int flags,vm_paddr_t low,vm_paddr_t high,unsigned long alignment,vm_paddr_t boundary)481 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
482     vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
483     vm_paddr_t boundary)
484 {
485 	void *ret;
486 
487 	ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
488 	    boundary, VM_MEMATTR_DEFAULT);
489 	if (ret != NULL) {
490 		/* Use low bits unused for slab pointers. */
491 		vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
492 		malloc_type_allocated(type, round_page(size));
493 	}
494 	return (ret);
495 }
496 
497 void *
contigmalloc_domainset(unsigned long size,struct malloc_type * type,struct domainset * ds,int flags,vm_paddr_t low,vm_paddr_t high,unsigned long alignment,vm_paddr_t boundary)498 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
499     struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
500     unsigned long alignment, vm_paddr_t boundary)
501 {
502 	void *ret;
503 
504 	ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
505 	    alignment, boundary, VM_MEMATTR_DEFAULT);
506 	if (ret != NULL) {
507 		/* Use low bits unused for slab pointers. */
508 		vsetzoneslab((uintptr_t)ret, NULL, CONTIG_MALLOC_SLAB(size));
509 		malloc_type_allocated(type, round_page(size));
510 	}
511 	return (ret);
512 }
513 
514 /*
515  *	contigfree (deprecated).
516  *
517  *	Free a block of memory allocated by contigmalloc.
518  *
519  *	This routine may not block.
520  */
521 void
contigfree(void * addr,unsigned long size __unused,struct malloc_type * type)522 contigfree(void *addr, unsigned long size __unused, struct malloc_type *type)
523 {
524 	free(addr, type);
525 }
526 #undef	IS_CONTIG_MALLOC
527 #undef	CONTIG_MALLOC_SLAB
528 
529 #ifdef MALLOC_DEBUG
530 static int
malloc_dbg(caddr_t * vap,size_t * sizep,struct malloc_type * mtp,int flags)531 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
532     int flags)
533 {
534 #ifdef INVARIANTS
535 	int indx;
536 
537 	KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
538 	/*
539 	 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
540 	 */
541 	indx = flags & (M_WAITOK | M_NOWAIT);
542 	if (indx != M_NOWAIT && indx != M_WAITOK) {
543 		static	struct timeval lasterr;
544 		static	int curerr, once;
545 		if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
546 			printf("Bad malloc flags: %x\n", indx);
547 			kdb_backtrace();
548 			flags |= M_WAITOK;
549 			once++;
550 		}
551 	}
552 #endif
553 #ifdef MALLOC_MAKE_FAILURES
554 	if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
555 		atomic_add_int(&malloc_nowait_count, 1);
556 		if ((malloc_nowait_count % malloc_failure_rate) == 0) {
557 			atomic_add_int(&malloc_failure_count, 1);
558 			*vap = NULL;
559 			return (EJUSTRETURN);
560 		}
561 	}
562 #endif
563 	if (flags & M_WAITOK) {
564 		KASSERT(curthread->td_intr_nesting_level == 0,
565 		   ("malloc(M_WAITOK) in interrupt context"));
566 		if (__predict_false(!THREAD_CAN_SLEEP())) {
567 #ifdef EPOCH_TRACE
568 			epoch_trace_list(curthread);
569 #endif
570 			KASSERT(1,
571 			    ("malloc(M_WAITOK) with sleeping prohibited"));
572 		}
573 	}
574 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
575 	    ("malloc: called with spinlock or critical section held"));
576 
577 #ifdef DEBUG_MEMGUARD
578 	if (memguard_cmp_mtp(mtp, *sizep)) {
579 		*vap = memguard_alloc(*sizep, flags);
580 		if (*vap != NULL)
581 			return (EJUSTRETURN);
582 		/* This is unfortunate but should not be fatal. */
583 	}
584 #endif
585 
586 #ifdef DEBUG_REDZONE
587 	*sizep = redzone_size_ntor(*sizep);
588 #endif
589 
590 	return (0);
591 }
592 #endif
593 
594 /*
595  * Handle large allocations and frees by using kmem_malloc directly.
596  */
597 #define	IS_MALLOC_LARGE(_slab)						\
598     (GET_SLAB_COOKIE(_slab) == SLAB_COOKIE_MALLOC_LARGE)
599 #define	MALLOC_LARGE_SLAB(_size)					\
600     ((void *)(((_size) << SLAB_COOKIE_SHIFT) | SLAB_COOKIE_MALLOC_LARGE))
601 static inline size_t
malloc_large_size(uma_slab_t slab)602 malloc_large_size(uma_slab_t slab)
603 {
604 	uintptr_t va;
605 
606 	va = (uintptr_t)slab;
607 	KASSERT(IS_MALLOC_LARGE(slab),
608 	    ("%s: called on non-malloc_large allocation: %p", __func__, slab));
609 	return (va >> SLAB_COOKIE_SHIFT);
610 }
611 
612 static caddr_t __noinline
malloc_large(size_t * size,struct malloc_type * mtp,struct domainset * policy,int flags DEBUG_REDZONE_ARG_DEF)613 malloc_large(size_t *size, struct malloc_type *mtp, struct domainset *policy,
614     int flags DEBUG_REDZONE_ARG_DEF)
615 {
616 	vm_offset_t kva;
617 	caddr_t va;
618 	size_t sz;
619 
620 	sz = roundup(*size, PAGE_SIZE);
621 	kva = kmem_malloc_domainset(policy, sz, flags);
622 	if (kva != 0) {
623 		/* Use low bits unused for slab pointers. */
624 		vsetzoneslab((uintptr_t)kva, NULL, MALLOC_LARGE_SLAB(sz));
625 		uma_total_inc(sz);
626 		*size = sz;
627 	}
628 	va = (caddr_t)kva;
629 	malloc_type_allocated(mtp, va == NULL ? 0 : sz);
630 	if (__predict_false(va == NULL)) {
631 		KASSERT((flags & M_WAITOK) == 0,
632 		    ("malloc(M_WAITOK) returned NULL"));
633 	} else {
634 #ifdef DEBUG_REDZONE
635 		va = redzone_setup(va, osize);
636 #endif
637 		kasan_mark((void *)va, osize, sz, KASAN_MALLOC_REDZONE);
638 	}
639 	return (va);
640 }
641 
642 static void
free_large(void * addr,size_t size)643 free_large(void *addr, size_t size)
644 {
645 
646 	kmem_free((vm_offset_t)addr, size);
647 	uma_total_dec(size);
648 }
649 #undef	IS_MALLOC_LARGE
650 #undef	MALLOC_LARGE_SLAB
651 
652 /*
653  *	malloc:
654  *
655  *	Allocate a block of memory.
656  *
657  *	If M_NOWAIT is set, this routine will not block and return NULL if
658  *	the allocation fails.
659  */
660 void *
661 (malloc)(size_t size, struct malloc_type *mtp, int flags)
662 {
663 	int indx;
664 	caddr_t va;
665 	uma_zone_t zone;
666 #if defined(DEBUG_REDZONE) || defined(KASAN)
667 	unsigned long osize = size;
668 #endif
669 
670 	MPASS((flags & M_EXEC) == 0);
671 
672 #ifdef MALLOC_DEBUG
673 	va = NULL;
674 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
675 		return (va);
676 #endif
677 
678 	if (__predict_false(size > kmem_zmax))
679 		return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
680 		    DEBUG_REDZONE_ARG));
681 
682 	if (size & KMEM_ZMASK)
683 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
684 	indx = kmemsize[size >> KMEM_ZSHIFT];
685 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
686 	va = uma_zalloc(zone, flags);
687 	if (va != NULL)
688 		size = zone->uz_size;
689 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
690 	if (__predict_false(va == NULL)) {
691 		KASSERT((flags & M_WAITOK) == 0,
692 		    ("malloc(M_WAITOK) returned NULL"));
693 	}
694 #ifdef DEBUG_REDZONE
695 	if (va != NULL)
696 		va = redzone_setup(va, osize);
697 #endif
698 #ifdef KASAN
699 	if (va != NULL)
700 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
701 #endif
702 	return ((void *) va);
703 }
704 
705 static void *
malloc_domain(size_t * sizep,int * indxp,struct malloc_type * mtp,int domain,int flags)706 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
707     int flags)
708 {
709 	uma_zone_t zone;
710 	caddr_t va;
711 	size_t size;
712 	int indx;
713 
714 	size = *sizep;
715 	KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
716 	    ("malloc_domain: Called with bad flag / size combination"));
717 	if (size & KMEM_ZMASK)
718 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
719 	indx = kmemsize[size >> KMEM_ZSHIFT];
720 	zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
721 	va = uma_zalloc_domain(zone, NULL, domain, flags);
722 	if (va != NULL)
723 		*sizep = zone->uz_size;
724 	*indxp = indx;
725 	return ((void *)va);
726 }
727 
728 void *
malloc_domainset(size_t size,struct malloc_type * mtp,struct domainset * ds,int flags)729 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
730     int flags)
731 {
732 	struct vm_domainset_iter di;
733 	caddr_t va;
734 	int domain;
735 	int indx;
736 #if defined(KASAN) || defined(DEBUG_REDZONE)
737 	unsigned long osize = size;
738 #endif
739 
740 	MPASS((flags & M_EXEC) == 0);
741 
742 #ifdef MALLOC_DEBUG
743 	va = NULL;
744 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
745 		return (va);
746 #endif
747 
748 	if (__predict_false(size > kmem_zmax))
749 		return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
750 		    DEBUG_REDZONE_ARG));
751 
752 	vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
753 	do {
754 		va = malloc_domain(&size, &indx, mtp, domain, flags);
755 	} while (va == NULL && vm_domainset_iter_policy(&di, &domain) == 0);
756 	malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
757 	if (__predict_false(va == NULL)) {
758 		KASSERT((flags & M_WAITOK) == 0,
759 		    ("malloc(M_WAITOK) returned NULL"));
760 	}
761 #ifdef DEBUG_REDZONE
762 	if (va != NULL)
763 		va = redzone_setup(va, osize);
764 #endif
765 #ifdef KASAN
766 	if (va != NULL)
767 		kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
768 #endif
769 	return (va);
770 }
771 
772 /*
773  * Allocate an executable area.
774  */
775 void *
malloc_exec(size_t size,struct malloc_type * mtp,int flags)776 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
777 {
778 
779 	return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
780 }
781 
782 void *
malloc_domainset_exec(size_t size,struct malloc_type * mtp,struct domainset * ds,int flags)783 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
784     int flags)
785 {
786 #if defined(DEBUG_REDZONE) || defined(KASAN)
787 	unsigned long osize = size;
788 #endif
789 #ifdef MALLOC_DEBUG
790 	caddr_t va;
791 #endif
792 
793 	flags |= M_EXEC;
794 
795 #ifdef MALLOC_DEBUG
796 	va = NULL;
797 	if (malloc_dbg(&va, &size, mtp, flags) != 0)
798 		return (va);
799 #endif
800 
801 	return (malloc_large(&size, mtp, ds, flags DEBUG_REDZONE_ARG));
802 }
803 
804 void *
malloc_aligned(size_t size,size_t align,struct malloc_type * type,int flags)805 malloc_aligned(size_t size, size_t align, struct malloc_type *type, int flags)
806 {
807 	return (malloc_domainset_aligned(size, align, type, DOMAINSET_RR(),
808 	    flags));
809 }
810 
811 void *
malloc_domainset_aligned(size_t size,size_t align,struct malloc_type * mtp,struct domainset * ds,int flags)812 malloc_domainset_aligned(size_t size, size_t align,
813     struct malloc_type *mtp, struct domainset *ds, int flags)
814 {
815 	void *res;
816 	size_t asize;
817 
818 	KASSERT(powerof2(align),
819 	    ("malloc_domainset_aligned: wrong align %#zx size %#zx",
820 	    align, size));
821 	KASSERT(align <= PAGE_SIZE,
822 	    ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
823 	    align, size));
824 
825 	/*
826 	 * Round the allocation size up to the next power of 2,
827 	 * because we can only guarantee alignment for
828 	 * power-of-2-sized allocations.  Further increase the
829 	 * allocation size to align if the rounded size is less than
830 	 * align, since malloc zones provide alignment equal to their
831 	 * size.
832 	 */
833 	if (size == 0)
834 		size = 1;
835 	asize = size <= align ? align : 1UL << flsl(size - 1);
836 
837 	res = malloc_domainset(asize, mtp, ds, flags);
838 	KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
839 	    ("malloc_domainset_aligned: result not aligned %p size %#zx "
840 	    "allocsize %#zx align %#zx", res, size, asize, align));
841 	return (res);
842 }
843 
844 void *
mallocarray(size_t nmemb,size_t size,struct malloc_type * type,int flags)845 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
846 {
847 
848 	if (WOULD_OVERFLOW(nmemb, size))
849 		panic("mallocarray: %zu * %zu overflowed", nmemb, size);
850 
851 	return (malloc(size * nmemb, type, flags));
852 }
853 
854 void *
mallocarray_domainset(size_t nmemb,size_t size,struct malloc_type * type,struct domainset * ds,int flags)855 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
856     struct domainset *ds, int flags)
857 {
858 
859 	if (WOULD_OVERFLOW(nmemb, size))
860 		panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
861 
862 	return (malloc_domainset(size * nmemb, type, ds, flags));
863 }
864 
865 #if defined(INVARIANTS) && !defined(KASAN)
866 static void
free_save_type(void * addr,struct malloc_type * mtp,u_long size)867 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
868 {
869 	struct malloc_type **mtpp = addr;
870 
871 	/*
872 	 * Cache a pointer to the malloc_type that most recently freed
873 	 * this memory here.  This way we know who is most likely to
874 	 * have stepped on it later.
875 	 *
876 	 * This code assumes that size is a multiple of 8 bytes for
877 	 * 64 bit machines
878 	 */
879 	mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
880 	mtpp += (size - sizeof(struct malloc_type *)) /
881 	    sizeof(struct malloc_type *);
882 	*mtpp = mtp;
883 }
884 #endif
885 
886 #ifdef MALLOC_DEBUG
887 static int
free_dbg(void ** addrp,struct malloc_type * mtp)888 free_dbg(void **addrp, struct malloc_type *mtp)
889 {
890 	void *addr;
891 
892 	addr = *addrp;
893 	KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
894 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
895 	    ("free: called with spinlock or critical section held"));
896 
897 	/* free(NULL, ...) does nothing */
898 	if (addr == NULL)
899 		return (EJUSTRETURN);
900 
901 #ifdef DEBUG_MEMGUARD
902 	if (is_memguard_addr(addr)) {
903 		memguard_free(addr);
904 		return (EJUSTRETURN);
905 	}
906 #endif
907 
908 #ifdef DEBUG_REDZONE
909 	redzone_check(addr);
910 	*addrp = redzone_addr_ntor(addr);
911 #endif
912 
913 	return (0);
914 }
915 #endif
916 
917 static __always_inline void
_free(void * addr,struct malloc_type * mtp,bool dozero)918 _free(void *addr, struct malloc_type *mtp, bool dozero)
919 {
920 	uma_zone_t zone;
921 	uma_slab_t slab;
922 	u_long size;
923 
924 #ifdef MALLOC_DEBUG
925 	if (free_dbg(&addr, mtp) != 0)
926 		return;
927 #endif
928 	/* free(NULL, ...) does nothing */
929 	if (addr == NULL)
930 		return;
931 
932 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
933 	if (slab == NULL)
934 		panic("%s(%d): address %p(%p) has not been allocated", __func__,
935 		    dozero, addr, (void *)((uintptr_t)addr & (~UMA_SLAB_MASK)));
936 
937 	switch (GET_SLAB_COOKIE(slab)) {
938 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
939 		size = zone->uz_size;
940 #if defined(INVARIANTS) && !defined(KASAN)
941 		free_save_type(addr, mtp, size);
942 #endif
943 		if (dozero) {
944 			kasan_mark(addr, size, size, 0);
945 			explicit_bzero(addr, size);
946 		}
947 		uma_zfree_arg(zone, addr, slab);
948 		break;
949 	case SLAB_COOKIE_MALLOC_LARGE:
950 		size = malloc_large_size(slab);
951 		if (dozero) {
952 			kasan_mark(addr, size, size, 0);
953 			explicit_bzero(addr, size);
954 		}
955 		free_large(addr, size);
956 		break;
957 	case SLAB_COOKIE_CONTIG_MALLOC:
958 		size = round_page(contigmalloc_size(slab));
959 		if (dozero)
960 			explicit_bzero(addr, size);
961 		kmem_free((vm_offset_t)addr, size);
962 		break;
963 	default:
964 		panic("%s(%d): addr %p slab %p with unknown cookie %d",
965 		    __func__, dozero, addr, slab, GET_SLAB_COOKIE(slab));
966 		/* NOTREACHED */
967 	}
968 	malloc_type_freed(mtp, size);
969 }
970 
971 /*
972  * free:
973  *	Free a block of memory allocated by malloc/contigmalloc.
974  *	This routine may not block.
975  */
976 void
free(void * addr,struct malloc_type * mtp)977 free(void *addr, struct malloc_type *mtp)
978 {
979 	_free(addr, mtp, false);
980 }
981 
982 /*
983  * zfree:
984  *	Zero then free a block of memory allocated by malloc/contigmalloc.
985  *	This routine may not block.
986  */
987 void
zfree(void * addr,struct malloc_type * mtp)988 zfree(void *addr, struct malloc_type *mtp)
989 {
990 	_free(addr, mtp, true);
991 }
992 
993 /*
994  *	realloc: change the size of a memory block
995  */
996 void *
realloc(void * addr,size_t size,struct malloc_type * mtp,int flags)997 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
998 {
999 	uma_zone_t zone;
1000 	uma_slab_t slab;
1001 	unsigned long alloc;
1002 	void *newaddr;
1003 
1004 	KASSERT(mtp->ks_version == M_VERSION,
1005 	    ("realloc: bad malloc type version"));
1006 	KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
1007 	    ("realloc: called with spinlock or critical section held"));
1008 
1009 	/* realloc(NULL, ...) is equivalent to malloc(...) */
1010 	if (addr == NULL)
1011 		return (malloc(size, mtp, flags));
1012 
1013 	/*
1014 	 * XXX: Should report free of old memory and alloc of new memory to
1015 	 * per-CPU stats.
1016 	 */
1017 
1018 #ifdef DEBUG_MEMGUARD
1019 	if (is_memguard_addr(addr))
1020 		return (memguard_realloc(addr, size, mtp, flags));
1021 #endif
1022 
1023 #ifdef DEBUG_REDZONE
1024 	slab = NULL;
1025 	zone = NULL;
1026 	alloc = redzone_get_size(addr);
1027 #else
1028 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1029 
1030 	/* Sanity check */
1031 	KASSERT(slab != NULL,
1032 	    ("realloc: address %p out of range", (void *)addr));
1033 
1034 	/* Get the size of the original block */
1035 	switch (GET_SLAB_COOKIE(slab)) {
1036 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1037 		alloc = zone->uz_size;
1038 		break;
1039 	case SLAB_COOKIE_MALLOC_LARGE:
1040 		alloc = malloc_large_size(slab);
1041 		break;
1042 	default:
1043 #ifdef INVARIANTS
1044 		panic("%s: called for addr %p of unsupported allocation type; "
1045 		    "slab %p cookie %d", __func__, addr, slab, GET_SLAB_COOKIE(slab));
1046 #endif
1047 		return (NULL);
1048 	}
1049 
1050 	/* Reuse the original block if appropriate */
1051 	if (size <= alloc &&
1052 	    (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1053 		kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1054 		return (addr);
1055 	}
1056 #endif /* !DEBUG_REDZONE */
1057 
1058 	/* Allocate a new, bigger (or smaller) block */
1059 	if ((newaddr = malloc(size, mtp, flags)) == NULL)
1060 		return (NULL);
1061 
1062 	/*
1063 	 * Copy over original contents.  For KASAN, the redzone must be marked
1064 	 * valid before performing the copy.
1065 	 */
1066 	kasan_mark(addr, alloc, alloc, 0);
1067 	bcopy(addr, newaddr, min(size, alloc));
1068 	free(addr, mtp);
1069 	return (newaddr);
1070 }
1071 
1072 /*
1073  *	reallocf: same as realloc() but free memory on failure.
1074  */
1075 void *
reallocf(void * addr,size_t size,struct malloc_type * mtp,int flags)1076 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1077 {
1078 	void *mem;
1079 
1080 	if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1081 		free(addr, mtp);
1082 	return (mem);
1083 }
1084 
1085 /*
1086  * 	malloc_size: returns the number of bytes allocated for a request of the
1087  * 		     specified size
1088  */
1089 size_t
malloc_size(size_t size)1090 malloc_size(size_t size)
1091 {
1092 	int indx;
1093 
1094 	if (size > kmem_zmax)
1095 		return (0);
1096 	if (size & KMEM_ZMASK)
1097 		size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1098 	indx = kmemsize[size >> KMEM_ZSHIFT];
1099 	return (kmemzones[indx].kz_size);
1100 }
1101 
1102 /*
1103  *	malloc_usable_size: returns the usable size of the allocation.
1104  */
1105 size_t
malloc_usable_size(const void * addr)1106 malloc_usable_size(const void *addr)
1107 {
1108 #ifndef DEBUG_REDZONE
1109 	uma_zone_t zone;
1110 	uma_slab_t slab;
1111 #endif
1112 	u_long size;
1113 
1114 	if (addr == NULL)
1115 		return (0);
1116 
1117 #ifdef DEBUG_MEMGUARD
1118 	if (is_memguard_addr(__DECONST(void *, addr)))
1119 		return (memguard_get_req_size(addr));
1120 #endif
1121 
1122 #ifdef DEBUG_REDZONE
1123 	size = redzone_get_size(__DECONST(void *, addr));
1124 #else
1125 	vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1126 	if (slab == NULL)
1127 		panic("malloc_usable_size: address %p(%p) is not allocated",
1128 		    addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1129 
1130 	switch (GET_SLAB_COOKIE(slab)) {
1131 	case __predict_true(SLAB_COOKIE_SLAB_PTR):
1132 		size = zone->uz_size;
1133 		break;
1134 	case SLAB_COOKIE_MALLOC_LARGE:
1135 		size = malloc_large_size(slab);
1136 		break;
1137 	default:
1138 		__assert_unreachable();
1139 		size = 0;
1140 		break;
1141 	}
1142 #endif
1143 	return (size);
1144 }
1145 
1146 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1147 
1148 /*
1149  * Initialize the kernel memory (kmem) arena.
1150  */
1151 void
kmeminit(void)1152 kmeminit(void)
1153 {
1154 	u_long mem_size;
1155 	u_long tmp;
1156 
1157 #ifdef VM_KMEM_SIZE
1158 	if (vm_kmem_size == 0)
1159 		vm_kmem_size = VM_KMEM_SIZE;
1160 #endif
1161 #ifdef VM_KMEM_SIZE_MIN
1162 	if (vm_kmem_size_min == 0)
1163 		vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1164 #endif
1165 #ifdef VM_KMEM_SIZE_MAX
1166 	if (vm_kmem_size_max == 0)
1167 		vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1168 #endif
1169 	/*
1170 	 * Calculate the amount of kernel virtual address (KVA) space that is
1171 	 * preallocated to the kmem arena.  In order to support a wide range
1172 	 * of machines, it is a function of the physical memory size,
1173 	 * specifically,
1174 	 *
1175 	 *	min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1176 	 *	    VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1177 	 *
1178 	 * Every architecture must define an integral value for
1179 	 * VM_KMEM_SIZE_SCALE.  However, the definitions of VM_KMEM_SIZE_MIN
1180 	 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1181 	 * ceiling on this preallocation, are optional.  Typically,
1182 	 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1183 	 * a given architecture.
1184 	 */
1185 	mem_size = vm_cnt.v_page_count;
1186 	if (mem_size <= 32768) /* delphij XXX 128MB */
1187 		kmem_zmax = PAGE_SIZE;
1188 
1189 	if (vm_kmem_size_scale < 1)
1190 		vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1191 
1192 	/*
1193 	 * Check if we should use defaults for the "vm_kmem_size"
1194 	 * variable:
1195 	 */
1196 	if (vm_kmem_size == 0) {
1197 		vm_kmem_size = mem_size / vm_kmem_size_scale;
1198 		vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1199 		    vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1200 		if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1201 			vm_kmem_size = vm_kmem_size_min;
1202 		if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1203 			vm_kmem_size = vm_kmem_size_max;
1204 	}
1205 	if (vm_kmem_size == 0)
1206 		panic("Tune VM_KMEM_SIZE_* for the platform");
1207 
1208 	/*
1209 	 * The amount of KVA space that is preallocated to the
1210 	 * kmem arena can be set statically at compile-time or manually
1211 	 * through the kernel environment.  However, it is still limited to
1212 	 * twice the physical memory size, which has been sufficient to handle
1213 	 * the most severe cases of external fragmentation in the kmem arena.
1214 	 */
1215 	if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1216 		vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1217 
1218 	vm_kmem_size = round_page(vm_kmem_size);
1219 
1220 #ifdef KASAN
1221 	/*
1222 	 * With KASAN enabled, dynamically allocated kernel memory is shadowed.
1223 	 * Account for this when setting the UMA limit.
1224 	 */
1225 	vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1226 	    (KASAN_SHADOW_SCALE + 1);
1227 #endif
1228 
1229 #ifdef DEBUG_MEMGUARD
1230 	tmp = memguard_fudge(vm_kmem_size, kernel_map);
1231 #else
1232 	tmp = vm_kmem_size;
1233 #endif
1234 	uma_set_limit(tmp);
1235 
1236 #ifdef DEBUG_MEMGUARD
1237 	/*
1238 	 * Initialize MemGuard if support compiled in.  MemGuard is a
1239 	 * replacement allocator used for detecting tamper-after-free
1240 	 * scenarios as they occur.  It is only used for debugging.
1241 	 */
1242 	memguard_init(kernel_arena);
1243 #endif
1244 }
1245 
1246 /*
1247  * Initialize the kernel memory allocator
1248  */
1249 /* ARGSUSED*/
1250 static void
mallocinit(void * dummy)1251 mallocinit(void *dummy)
1252 {
1253 	int i;
1254 	uint8_t indx;
1255 
1256 	mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1257 
1258 	kmeminit();
1259 
1260 	if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1261 		kmem_zmax = KMEM_ZMAX;
1262 
1263 	for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1264 		int size = kmemzones[indx].kz_size;
1265 		const char *name = kmemzones[indx].kz_name;
1266 		size_t align;
1267 		int subzone;
1268 
1269 		align = UMA_ALIGN_PTR;
1270 		if (powerof2(size) && size > sizeof(void *))
1271 			align = MIN(size, PAGE_SIZE) - 1;
1272 		for (subzone = 0; subzone < numzones; subzone++) {
1273 			kmemzones[indx].kz_zone[subzone] =
1274 			    uma_zcreate(name, size,
1275 #if defined(INVARIANTS) && !defined(KASAN)
1276 			    mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1277 #else
1278 			    NULL, NULL, NULL, NULL,
1279 #endif
1280 			    align, UMA_ZONE_MALLOC);
1281 		}
1282 		for (;i <= size; i+= KMEM_ZBASE)
1283 			kmemsize[i >> KMEM_ZSHIFT] = indx;
1284 	}
1285 }
1286 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1287 
1288 void
malloc_init(void * data)1289 malloc_init(void *data)
1290 {
1291 	struct malloc_type_internal *mtip;
1292 	struct malloc_type *mtp;
1293 
1294 	KASSERT(vm_cnt.v_page_count != 0,
1295 	    ("malloc_init() called before vm_mem_init()"));
1296 
1297 	mtp = data;
1298 	if (mtp->ks_version != M_VERSION)
1299 		panic("malloc_init: type %s with unsupported version %lu",
1300 		    mtp->ks_shortdesc, mtp->ks_version);
1301 
1302 	mtip = &mtp->ks_mti;
1303 	mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1304 	mtp_set_subzone(mtp);
1305 
1306 	mtx_lock(&malloc_mtx);
1307 	mtp->ks_next = kmemstatistics;
1308 	kmemstatistics = mtp;
1309 	kmemcount++;
1310 	mtx_unlock(&malloc_mtx);
1311 }
1312 
1313 void
malloc_uninit(void * data)1314 malloc_uninit(void *data)
1315 {
1316 	struct malloc_type_internal *mtip;
1317 	struct malloc_type_stats *mtsp;
1318 	struct malloc_type *mtp, *temp;
1319 	long temp_allocs, temp_bytes;
1320 	int i;
1321 
1322 	mtp = data;
1323 	KASSERT(mtp->ks_version == M_VERSION,
1324 	    ("malloc_uninit: bad malloc type version"));
1325 
1326 	mtx_lock(&malloc_mtx);
1327 	mtip = &mtp->ks_mti;
1328 	if (mtp != kmemstatistics) {
1329 		for (temp = kmemstatistics; temp != NULL;
1330 		    temp = temp->ks_next) {
1331 			if (temp->ks_next == mtp) {
1332 				temp->ks_next = mtp->ks_next;
1333 				break;
1334 			}
1335 		}
1336 		KASSERT(temp,
1337 		    ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1338 	} else
1339 		kmemstatistics = mtp->ks_next;
1340 	kmemcount--;
1341 	mtx_unlock(&malloc_mtx);
1342 
1343 	/*
1344 	 * Look for memory leaks.
1345 	 */
1346 	temp_allocs = temp_bytes = 0;
1347 	for (i = 0; i <= mp_maxid; i++) {
1348 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1349 		temp_allocs += mtsp->mts_numallocs;
1350 		temp_allocs -= mtsp->mts_numfrees;
1351 		temp_bytes += mtsp->mts_memalloced;
1352 		temp_bytes -= mtsp->mts_memfreed;
1353 	}
1354 	if (temp_allocs > 0 || temp_bytes > 0) {
1355 		printf("Warning: memory type %s leaked memory on destroy "
1356 		    "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1357 		    temp_allocs, temp_bytes);
1358 	}
1359 
1360 	uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1361 }
1362 
1363 struct malloc_type *
malloc_desc2type(const char * desc)1364 malloc_desc2type(const char *desc)
1365 {
1366 	struct malloc_type *mtp;
1367 
1368 	mtx_assert(&malloc_mtx, MA_OWNED);
1369 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1370 		if (strcmp(mtp->ks_shortdesc, desc) == 0)
1371 			return (mtp);
1372 	}
1373 	return (NULL);
1374 }
1375 
1376 static int
sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)1377 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1378 {
1379 	struct malloc_type_stream_header mtsh;
1380 	struct malloc_type_internal *mtip;
1381 	struct malloc_type_stats *mtsp, zeromts;
1382 	struct malloc_type_header mth;
1383 	struct malloc_type *mtp;
1384 	int error, i;
1385 	struct sbuf sbuf;
1386 
1387 	error = sysctl_wire_old_buffer(req, 0);
1388 	if (error != 0)
1389 		return (error);
1390 	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1391 	sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1392 	mtx_lock(&malloc_mtx);
1393 
1394 	bzero(&zeromts, sizeof(zeromts));
1395 
1396 	/*
1397 	 * Insert stream header.
1398 	 */
1399 	bzero(&mtsh, sizeof(mtsh));
1400 	mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1401 	mtsh.mtsh_maxcpus = MAXCPU;
1402 	mtsh.mtsh_count = kmemcount;
1403 	(void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1404 
1405 	/*
1406 	 * Insert alternating sequence of type headers and type statistics.
1407 	 */
1408 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1409 		mtip = &mtp->ks_mti;
1410 
1411 		/*
1412 		 * Insert type header.
1413 		 */
1414 		bzero(&mth, sizeof(mth));
1415 		strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1416 		(void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1417 
1418 		/*
1419 		 * Insert type statistics for each CPU.
1420 		 */
1421 		for (i = 0; i <= mp_maxid; i++) {
1422 			mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1423 			(void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1424 		}
1425 		/*
1426 		 * Fill in the missing CPUs.
1427 		 */
1428 		for (; i < MAXCPU; i++) {
1429 			(void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1430 		}
1431 	}
1432 	mtx_unlock(&malloc_mtx);
1433 	error = sbuf_finish(&sbuf);
1434 	sbuf_delete(&sbuf);
1435 	return (error);
1436 }
1437 
1438 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1439     CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1440     sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1441     "Return malloc types");
1442 
1443 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1444     "Count of kernel malloc types");
1445 
1446 void
malloc_type_list(malloc_type_list_func_t * func,void * arg)1447 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1448 {
1449 	struct malloc_type *mtp, **bufmtp;
1450 	int count, i;
1451 	size_t buflen;
1452 
1453 	mtx_lock(&malloc_mtx);
1454 restart:
1455 	mtx_assert(&malloc_mtx, MA_OWNED);
1456 	count = kmemcount;
1457 	mtx_unlock(&malloc_mtx);
1458 
1459 	buflen = sizeof(struct malloc_type *) * count;
1460 	bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1461 
1462 	mtx_lock(&malloc_mtx);
1463 
1464 	if (count < kmemcount) {
1465 		free(bufmtp, M_TEMP);
1466 		goto restart;
1467 	}
1468 
1469 	for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1470 		bufmtp[i] = mtp;
1471 
1472 	mtx_unlock(&malloc_mtx);
1473 
1474 	for (i = 0; i < count; i++)
1475 		(func)(bufmtp[i], arg);
1476 
1477 	free(bufmtp, M_TEMP);
1478 }
1479 
1480 #ifdef DDB
1481 static int64_t
get_malloc_stats(const struct malloc_type_internal * mtip,uint64_t * allocs,uint64_t * inuse)1482 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1483     uint64_t *inuse)
1484 {
1485 	const struct malloc_type_stats *mtsp;
1486 	uint64_t frees, alloced, freed;
1487 	int i;
1488 
1489 	*allocs = 0;
1490 	frees = 0;
1491 	alloced = 0;
1492 	freed = 0;
1493 	for (i = 0; i <= mp_maxid; i++) {
1494 		mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1495 
1496 		*allocs += mtsp->mts_numallocs;
1497 		frees += mtsp->mts_numfrees;
1498 		alloced += mtsp->mts_memalloced;
1499 		freed += mtsp->mts_memfreed;
1500 	}
1501 	*inuse = *allocs - frees;
1502 	return (alloced - freed);
1503 }
1504 
DB_SHOW_COMMAND(malloc,db_show_malloc)1505 DB_SHOW_COMMAND(malloc, db_show_malloc)
1506 {
1507 	const char *fmt_hdr, *fmt_entry;
1508 	struct malloc_type *mtp;
1509 	uint64_t allocs, inuse;
1510 	int64_t size;
1511 	/* variables for sorting */
1512 	struct malloc_type *last_mtype, *cur_mtype;
1513 	int64_t cur_size, last_size;
1514 	int ties;
1515 
1516 	if (modif[0] == 'i') {
1517 		fmt_hdr = "%s,%s,%s,%s\n";
1518 		fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1519 	} else {
1520 		fmt_hdr = "%18s %12s  %12s %12s\n";
1521 		fmt_entry = "%18s %12ju %12jdK %12ju\n";
1522 	}
1523 
1524 	db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1525 
1526 	/* Select sort, largest size first. */
1527 	last_mtype = NULL;
1528 	last_size = INT64_MAX;
1529 	for (;;) {
1530 		cur_mtype = NULL;
1531 		cur_size = -1;
1532 		ties = 0;
1533 
1534 		for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1535 			/*
1536 			 * In the case of size ties, print out mtypes
1537 			 * in the order they are encountered.  That is,
1538 			 * when we encounter the most recently output
1539 			 * mtype, we have already printed all preceding
1540 			 * ties, and we must print all following ties.
1541 			 */
1542 			if (mtp == last_mtype) {
1543 				ties = 1;
1544 				continue;
1545 			}
1546 			size = get_malloc_stats(&mtp->ks_mti, &allocs,
1547 			    &inuse);
1548 			if (size > cur_size && size < last_size + ties) {
1549 				cur_size = size;
1550 				cur_mtype = mtp;
1551 			}
1552 		}
1553 		if (cur_mtype == NULL)
1554 			break;
1555 
1556 		size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1557 		db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1558 		    howmany(size, 1024), allocs);
1559 
1560 		if (db_pager_quit)
1561 			break;
1562 
1563 		last_mtype = cur_mtype;
1564 		last_size = cur_size;
1565 	}
1566 }
1567 
1568 #if MALLOC_DEBUG_MAXZONES > 1
DB_SHOW_COMMAND(multizone_matches,db_show_multizone_matches)1569 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1570 {
1571 	struct malloc_type_internal *mtip;
1572 	struct malloc_type *mtp;
1573 	u_int subzone;
1574 
1575 	if (!have_addr) {
1576 		db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1577 		return;
1578 	}
1579 	mtp = (void *)addr;
1580 	if (mtp->ks_version != M_VERSION) {
1581 		db_printf("Version %lx does not match expected %x\n",
1582 		    mtp->ks_version, M_VERSION);
1583 		return;
1584 	}
1585 
1586 	mtip = &mtp->ks_mti;
1587 	subzone = mtip->mti_zone;
1588 
1589 	for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1590 		mtip = &mtp->ks_mti;
1591 		if (mtip->mti_zone != subzone)
1592 			continue;
1593 		db_printf("%s\n", mtp->ks_shortdesc);
1594 		if (db_pager_quit)
1595 			break;
1596 	}
1597 }
1598 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1599 #endif /* DDB */
1600