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