2 * SPDX-License-Identifier: BSD-3-Clause
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)
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
34 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94
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
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
54 #include <sys/param.h>
55 #include <sys/systm.h>
58 #include <sys/kernel.h>
60 #include <sys/malloc.h>
61 #include <sys/mutex.h>
62 #include <sys/vmmeter.h>
64 #include <sys/queue.h>
67 #include <sys/sysctl.h>
71 #include <sys/epoch.h>
76 #include <vm/vm_domainset.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_param.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_extern.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_phys.h>
84 #include <vm/vm_pagequeue.h>
86 #include <vm/uma_int.h>
87 #include <vm/uma_dbg.h>
90 #include <vm/memguard.h>
93 #include <vm/redzone.h>
96 #if defined(INVARIANTS) && defined(__i386__)
97 #include <machine/cpu.h>
103 #include <sys/dtrace_bsd.h>
105 bool __read_frequently dtrace_malloc_enabled;
106 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
109 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
110 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
111 #define MALLOC_DEBUG 1
114 #if defined(KASAN) || defined(DEBUG_REDZONE)
115 #define DEBUG_REDZONE_ARG_DEF , unsigned long osize
116 #define DEBUG_REDZONE_ARG , osize
118 #define DEBUG_REDZONE_ARG_DEF
119 #define DEBUG_REDZONE_ARG
123 * When realloc() is called, if the new size is sufficiently smaller than
124 * the old size, realloc() will allocate a new, smaller block to avoid
125 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
126 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
128 #ifndef REALLOC_FRACTION
129 #define REALLOC_FRACTION 1 /* new block if <= half the size */
133 * Centrally define some common malloc types.
135 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
136 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
137 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
139 static struct malloc_type *kmemstatistics;
140 static int kmemcount;
142 #define KMEM_ZSHIFT 4
143 #define KMEM_ZBASE 16
144 #define KMEM_ZMASK (KMEM_ZBASE - 1)
146 #define KMEM_ZMAX 65536
147 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
148 static uint8_t kmemsize[KMEM_ZSIZE + 1];
150 #ifndef MALLOC_DEBUG_MAXZONES
151 #define MALLOC_DEBUG_MAXZONES 1
153 static int numzones = MALLOC_DEBUG_MAXZONES;
156 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
159 * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
161 * XXX: The comment here used to read "These won't be powers of two for
162 * long." It's possible that a significant amount of wasted memory could be
163 * recovered by tuning the sizes of these buckets.
168 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
173 {128, "malloc-128", },
174 {256, "malloc-256", },
175 {384, "malloc-384", },
176 {512, "malloc-512", },
177 {1024, "malloc-1024", },
178 {2048, "malloc-2048", },
179 {4096, "malloc-4096", },
180 {8192, "malloc-8192", },
181 {16384, "malloc-16384", },
182 {32768, "malloc-32768", },
183 {65536, "malloc-65536", },
188 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
189 "Size of kernel memory");
191 static u_long kmem_zmax = KMEM_ZMAX;
192 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
193 "Maximum allocation size that malloc(9) would use UMA as backend");
195 static u_long vm_kmem_size_min;
196 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
197 "Minimum size of kernel memory");
199 static u_long vm_kmem_size_max;
200 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
201 "Maximum size of kernel memory");
203 static u_int vm_kmem_size_scale;
204 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
205 "Scale factor for kernel memory size");
207 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
208 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
209 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
210 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
212 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
213 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
214 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
215 sysctl_kmem_map_free, "LU", "Free space in kmem");
217 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
218 "Malloc information");
220 static u_int vm_malloc_zone_count = nitems(kmemzones);
221 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
222 CTLFLAG_RD, &vm_malloc_zone_count, 0,
223 "Number of malloc zones");
225 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
226 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
227 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
228 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
231 * The malloc_mtx protects the kmemstatistics linked list.
233 struct mtx malloc_mtx;
235 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
237 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
238 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
239 "Kernel malloc debugging options");
243 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
244 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
246 #ifdef MALLOC_MAKE_FAILURES
247 static int malloc_failure_rate;
248 static int malloc_nowait_count;
249 static int malloc_failure_count;
250 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
251 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
252 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
253 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
257 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
262 return (sysctl_handle_long(oidp, &size, 0, req));
266 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
270 /* The sysctl is unsigned, implement as a saturation value. */
277 return (sysctl_handle_long(oidp, &size, 0, req));
281 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
283 int sizes[nitems(kmemzones)];
286 for (i = 0; i < nitems(kmemzones); i++) {
287 sizes[i] = kmemzones[i].kz_size;
290 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
294 * malloc(9) uma zone separation -- sub-page buffer overruns in one
295 * malloc type will affect only a subset of other malloc types.
297 #if MALLOC_DEBUG_MAXZONES > 1
299 tunable_set_numzones(void)
302 TUNABLE_INT_FETCH("debug.malloc.numzones",
305 /* Sanity check the number of malloc uma zones. */
308 if (numzones > MALLOC_DEBUG_MAXZONES)
309 numzones = MALLOC_DEBUG_MAXZONES;
311 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
312 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
313 &numzones, 0, "Number of malloc uma subzones");
316 * Any number that changes regularly is an okay choice for the
317 * offset. Build numbers are pretty good of you have them.
319 static u_int zone_offset = __FreeBSD_version;
320 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
321 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
322 &zone_offset, 0, "Separate malloc types by examining the "
323 "Nth character in the malloc type short description.");
326 mtp_set_subzone(struct malloc_type *mtp)
328 struct malloc_type_internal *mtip;
334 desc = mtp->ks_shortdesc;
335 if (desc == NULL || (len = strlen(desc)) == 0)
338 val = desc[zone_offset % len];
339 mtip->mti_zone = (val % numzones);
343 mtp_get_subzone(struct malloc_type *mtp)
345 struct malloc_type_internal *mtip;
349 KASSERT(mtip->mti_zone < numzones,
350 ("mti_zone %u out of range %d",
351 mtip->mti_zone, numzones));
352 return (mtip->mti_zone);
354 #elif MALLOC_DEBUG_MAXZONES == 0
355 #error "MALLOC_DEBUG_MAXZONES must be positive."
358 mtp_set_subzone(struct malloc_type *mtp)
360 struct malloc_type_internal *mtip;
367 mtp_get_subzone(struct malloc_type *mtp)
372 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
375 * An allocation has succeeded -- update malloc type statistics for the
376 * amount of bucket size. Occurs within a critical section so that the
377 * thread isn't preempted and doesn't migrate while updating per-PCU
381 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
384 struct malloc_type_internal *mtip;
385 struct malloc_type_stats *mtsp;
389 mtsp = zpcpu_get(mtip->mti_stats);
391 mtsp->mts_memalloced += size;
392 mtsp->mts_numallocs++;
395 mtsp->mts_size |= 1 << zindx;
398 if (__predict_false(dtrace_malloc_enabled)) {
399 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
401 (dtrace_malloc_probe)(probe_id,
402 (uintptr_t) mtp, (uintptr_t) mtip,
403 (uintptr_t) mtsp, size, zindx);
411 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
415 malloc_type_zone_allocated(mtp, size, -1);
419 * A free operation has occurred -- update malloc type statistics for the
420 * amount of the bucket size. Occurs within a critical section so that the
421 * thread isn't preempted and doesn't migrate while updating per-CPU
425 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
427 struct malloc_type_internal *mtip;
428 struct malloc_type_stats *mtsp;
432 mtsp = zpcpu_get(mtip->mti_stats);
433 mtsp->mts_memfreed += size;
434 mtsp->mts_numfrees++;
437 if (__predict_false(dtrace_malloc_enabled)) {
438 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
440 (dtrace_malloc_probe)(probe_id,
441 (uintptr_t) mtp, (uintptr_t) mtip,
442 (uintptr_t) mtsp, size, 0);
452 * Allocate a block of physically contiguous memory.
454 * If M_NOWAIT is set, this routine will not block and return NULL if
455 * the allocation fails.
458 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
459 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
464 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
465 boundary, VM_MEMATTR_DEFAULT);
467 malloc_type_allocated(type, round_page(size));
472 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
473 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
474 unsigned long alignment, vm_paddr_t boundary)
478 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
479 alignment, boundary, VM_MEMATTR_DEFAULT);
481 malloc_type_allocated(type, round_page(size));
488 * Free a block of memory allocated by contigmalloc.
490 * This routine may not block.
493 contigfree(void *addr, unsigned long size, struct malloc_type *type)
496 kmem_free((vm_offset_t)addr, size);
497 malloc_type_freed(type, round_page(size));
502 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
508 KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
510 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
512 indx = flags & (M_WAITOK | M_NOWAIT);
513 if (indx != M_NOWAIT && indx != M_WAITOK) {
514 static struct timeval lasterr;
515 static int curerr, once;
516 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
517 printf("Bad malloc flags: %x\n", indx);
524 #ifdef MALLOC_MAKE_FAILURES
525 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
526 atomic_add_int(&malloc_nowait_count, 1);
527 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
528 atomic_add_int(&malloc_failure_count, 1);
530 return (EJUSTRETURN);
534 if (flags & M_WAITOK) {
535 KASSERT(curthread->td_intr_nesting_level == 0,
536 ("malloc(M_WAITOK) in interrupt context"));
537 if (__predict_false(!THREAD_CAN_SLEEP())) {
539 epoch_trace_list(curthread);
542 ("malloc(M_WAITOK) with sleeping prohibited"));
545 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
546 ("malloc: called with spinlock or critical section held"));
548 #ifdef DEBUG_MEMGUARD
549 if (memguard_cmp_mtp(mtp, *sizep)) {
550 *vap = memguard_alloc(*sizep, flags);
552 return (EJUSTRETURN);
553 /* This is unfortunate but should not be fatal. */
558 *sizep = redzone_size_ntor(*sizep);
566 * Handle large allocations and frees by using kmem_malloc directly.
569 malloc_large_slab(uma_slab_t slab)
573 va = (uintptr_t)slab;
574 return ((va & 1) != 0);
578 malloc_large_size(uma_slab_t slab)
582 va = (uintptr_t)slab;
586 static caddr_t __noinline
587 malloc_large(size_t *size, struct malloc_type *mtp, struct domainset *policy,
588 int flags DEBUG_REDZONE_ARG_DEF)
594 sz = roundup(*size, PAGE_SIZE);
595 kva = kmem_malloc_domainset(policy, sz, flags);
597 /* The low bit is unused for slab pointers. */
598 vsetzoneslab(kva, NULL, (void *)((sz << 1) | 1));
603 malloc_type_allocated(mtp, va == NULL ? 0 : sz);
604 if (__predict_false(va == NULL)) {
605 KASSERT((flags & M_WAITOK) == 0,
606 ("malloc(M_WAITOK) returned NULL"));
609 va = redzone_setup(va, osize);
611 kasan_mark((void *)va, osize, sz, KASAN_MALLOC_REDZONE);
617 free_large(void *addr, size_t size)
620 kmem_free((vm_offset_t)addr, size);
627 * Allocate a block of memory.
629 * If M_NOWAIT is set, this routine will not block and return NULL if
630 * the allocation fails.
633 (malloc)(size_t size, struct malloc_type *mtp, int flags)
638 #if defined(DEBUG_REDZONE) || defined(KASAN)
639 unsigned long osize = size;
642 MPASS((flags & M_EXEC) == 0);
646 if (malloc_dbg(&va, &size, mtp, flags) != 0)
650 if (__predict_false(size > kmem_zmax))
651 return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
654 if (size & KMEM_ZMASK)
655 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
656 indx = kmemsize[size >> KMEM_ZSHIFT];
657 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
658 va = uma_zalloc(zone, flags);
660 size = zone->uz_size;
661 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
662 if (__predict_false(va == NULL)) {
663 KASSERT((flags & M_WAITOK) == 0,
664 ("malloc(M_WAITOK) returned NULL"));
668 va = redzone_setup(va, osize);
672 kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
674 return ((void *) va);
678 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
687 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
688 ("malloc_domain: Called with bad flag / size combination."));
689 if (size & KMEM_ZMASK)
690 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
691 indx = kmemsize[size >> KMEM_ZSHIFT];
692 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
693 va = uma_zalloc_domain(zone, NULL, domain, flags);
695 *sizep = zone->uz_size;
701 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
704 struct vm_domainset_iter di;
708 #if defined(KASAN) || defined(DEBUG_REDZONE)
709 unsigned long osize = size;
712 MPASS((flags & M_EXEC) == 0);
716 if (malloc_dbg(&va, &size, mtp, flags) != 0)
720 if (__predict_false(size > kmem_zmax))
721 return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
724 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
726 va = malloc_domain(&size, &indx, mtp, domain, flags);
727 } while (va == NULL && vm_domainset_iter_policy(&di, &domain) == 0);
728 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
729 if (__predict_false(va == NULL)) {
730 KASSERT((flags & M_WAITOK) == 0,
731 ("malloc(M_WAITOK) returned NULL"));
735 va = redzone_setup(va, osize);
739 kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
745 * Allocate an executable area.
748 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
751 return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
755 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
758 #if defined(DEBUG_REDZONE) || defined(KASAN)
759 unsigned long osize = size;
769 if (malloc_dbg(&va, &size, mtp, flags) != 0)
773 return (malloc_large(&size, mtp, ds, flags DEBUG_REDZONE_ARG));
777 malloc_domainset_aligned(size_t size, size_t align,
778 struct malloc_type *mtp, struct domainset *ds, int flags)
783 KASSERT(align != 0 && powerof2(align),
784 ("malloc_domainset_aligned: wrong align %#zx size %#zx",
786 KASSERT(align <= PAGE_SIZE,
787 ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
791 * Round the allocation size up to the next power of 2,
792 * because we can only guarantee alignment for
793 * power-of-2-sized allocations. Further increase the
794 * allocation size to align if the rounded size is less than
795 * align, since malloc zones provide alignment equal to their
798 asize = size <= align ? align : 1UL << flsl(size - 1);
800 res = malloc_domainset(asize, mtp, ds, flags);
801 KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
802 ("malloc_domainset_aligned: result not aligned %p size %#zx "
803 "allocsize %#zx align %#zx", res, size, asize, align));
808 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
811 if (WOULD_OVERFLOW(nmemb, size))
812 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
814 return (malloc(size * nmemb, type, flags));
818 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
819 struct domainset *ds, int flags)
822 if (WOULD_OVERFLOW(nmemb, size))
823 panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
825 return (malloc_domainset(size * nmemb, type, ds, flags));
828 #if defined(INVARIANTS) && !defined(KASAN)
830 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
832 struct malloc_type **mtpp = addr;
835 * Cache a pointer to the malloc_type that most recently freed
836 * this memory here. This way we know who is most likely to
837 * have stepped on it later.
839 * This code assumes that size is a multiple of 8 bytes for
842 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
843 mtpp += (size - sizeof(struct malloc_type *)) /
844 sizeof(struct malloc_type *);
851 free_dbg(void **addrp, struct malloc_type *mtp)
856 KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
857 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
858 ("free: called with spinlock or critical section held"));
860 /* free(NULL, ...) does nothing */
862 return (EJUSTRETURN);
864 #ifdef DEBUG_MEMGUARD
865 if (is_memguard_addr(addr)) {
867 return (EJUSTRETURN);
873 *addrp = redzone_addr_ntor(addr);
883 * Free a block of memory allocated by malloc.
885 * This routine may not block.
888 free(void *addr, struct malloc_type *mtp)
895 if (free_dbg(&addr, mtp) != 0)
898 /* free(NULL, ...) does nothing */
902 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
904 panic("free: address %p(%p) has not been allocated.\n",
905 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
907 if (__predict_true(!malloc_large_slab(slab))) {
908 size = zone->uz_size;
909 #if defined(INVARIANTS) && !defined(KASAN)
910 free_save_type(addr, mtp, size);
912 uma_zfree_arg(zone, addr, slab);
914 size = malloc_large_size(slab);
915 free_large(addr, size);
917 malloc_type_freed(mtp, size);
923 * Zero then free a block of memory allocated by malloc.
925 * This routine may not block.
928 zfree(void *addr, struct malloc_type *mtp)
935 if (free_dbg(&addr, mtp) != 0)
938 /* free(NULL, ...) does nothing */
942 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
944 panic("free: address %p(%p) has not been allocated.\n",
945 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
947 if (__predict_true(!malloc_large_slab(slab))) {
948 size = zone->uz_size;
949 #if defined(INVARIANTS) && !defined(KASAN)
950 free_save_type(addr, mtp, size);
952 kasan_mark(addr, size, size, 0);
953 explicit_bzero(addr, size);
954 uma_zfree_arg(zone, addr, slab);
956 size = malloc_large_size(slab);
957 kasan_mark(addr, size, size, 0);
958 explicit_bzero(addr, size);
959 free_large(addr, size);
961 malloc_type_freed(mtp, size);
965 * realloc: change the size of a memory block
968 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
975 KASSERT(mtp->ks_version == M_VERSION,
976 ("realloc: bad malloc type version"));
977 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
978 ("realloc: called with spinlock or critical section held"));
980 /* realloc(NULL, ...) is equivalent to malloc(...) */
982 return (malloc(size, mtp, flags));
985 * XXX: Should report free of old memory and alloc of new memory to
989 #ifdef DEBUG_MEMGUARD
990 if (is_memguard_addr(addr))
991 return (memguard_realloc(addr, size, mtp, flags));
997 alloc = redzone_get_size(addr);
999 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1002 KASSERT(slab != NULL,
1003 ("realloc: address %p out of range", (void *)addr));
1005 /* Get the size of the original block */
1006 if (!malloc_large_slab(slab))
1007 alloc = zone->uz_size;
1009 alloc = malloc_large_size(slab);
1011 /* Reuse the original block if appropriate */
1012 if (size <= alloc &&
1013 (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1014 kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1017 #endif /* !DEBUG_REDZONE */
1019 /* Allocate a new, bigger (or smaller) block */
1020 if ((newaddr = malloc(size, mtp, flags)) == NULL)
1024 * Copy over original contents. For KASAN, the redzone must be marked
1025 * valid before performing the copy.
1027 kasan_mark(addr, size, size, 0);
1028 bcopy(addr, newaddr, min(size, alloc));
1034 * reallocf: same as realloc() but free memory on failure.
1037 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1041 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1047 * malloc_size: returns the number of bytes allocated for a request of the
1051 malloc_size(size_t size)
1055 if (size > kmem_zmax)
1057 if (size & KMEM_ZMASK)
1058 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1059 indx = kmemsize[size >> KMEM_ZSHIFT];
1060 return (kmemzones[indx].kz_size);
1064 * malloc_usable_size: returns the usable size of the allocation.
1067 malloc_usable_size(const void *addr)
1069 #ifndef DEBUG_REDZONE
1078 #ifdef DEBUG_MEMGUARD
1079 if (is_memguard_addr(__DECONST(void *, addr)))
1080 return (memguard_get_req_size(addr));
1083 #ifdef DEBUG_REDZONE
1084 size = redzone_get_size(__DECONST(void *, addr));
1086 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1088 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1089 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1091 if (!malloc_large_slab(slab))
1092 size = zone->uz_size;
1094 size = malloc_large_size(slab);
1099 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1102 * Initialize the kernel memory (kmem) arena.
1111 if (vm_kmem_size == 0)
1112 vm_kmem_size = VM_KMEM_SIZE;
1114 #ifdef VM_KMEM_SIZE_MIN
1115 if (vm_kmem_size_min == 0)
1116 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1118 #ifdef VM_KMEM_SIZE_MAX
1119 if (vm_kmem_size_max == 0)
1120 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1123 * Calculate the amount of kernel virtual address (KVA) space that is
1124 * preallocated to the kmem arena. In order to support a wide range
1125 * of machines, it is a function of the physical memory size,
1128 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1129 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1131 * Every architecture must define an integral value for
1132 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1133 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1134 * ceiling on this preallocation, are optional. Typically,
1135 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1136 * a given architecture.
1138 mem_size = vm_cnt.v_page_count;
1139 if (mem_size <= 32768) /* delphij XXX 128MB */
1140 kmem_zmax = PAGE_SIZE;
1142 if (vm_kmem_size_scale < 1)
1143 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1146 * Check if we should use defaults for the "vm_kmem_size"
1149 if (vm_kmem_size == 0) {
1150 vm_kmem_size = mem_size / vm_kmem_size_scale;
1151 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1152 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1153 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1154 vm_kmem_size = vm_kmem_size_min;
1155 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1156 vm_kmem_size = vm_kmem_size_max;
1158 if (vm_kmem_size == 0)
1159 panic("Tune VM_KMEM_SIZE_* for the platform");
1162 * The amount of KVA space that is preallocated to the
1163 * kmem arena can be set statically at compile-time or manually
1164 * through the kernel environment. However, it is still limited to
1165 * twice the physical memory size, which has been sufficient to handle
1166 * the most severe cases of external fragmentation in the kmem arena.
1168 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1169 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1171 vm_kmem_size = round_page(vm_kmem_size);
1175 * With KASAN enabled, dynamically allocated kernel memory is shadowed.
1176 * Account for this when setting the UMA limit.
1178 vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1179 (KASAN_SHADOW_SCALE + 1);
1182 #ifdef DEBUG_MEMGUARD
1183 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1189 #ifdef DEBUG_MEMGUARD
1191 * Initialize MemGuard if support compiled in. MemGuard is a
1192 * replacement allocator used for detecting tamper-after-free
1193 * scenarios as they occur. It is only used for debugging.
1195 memguard_init(kernel_arena);
1200 * Initialize the kernel memory allocator
1204 mallocinit(void *dummy)
1209 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1213 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1214 kmem_zmax = KMEM_ZMAX;
1216 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1217 int size = kmemzones[indx].kz_size;
1218 const char *name = kmemzones[indx].kz_name;
1222 align = UMA_ALIGN_PTR;
1223 if (powerof2(size) && size > sizeof(void *))
1224 align = MIN(size, PAGE_SIZE) - 1;
1225 for (subzone = 0; subzone < numzones; subzone++) {
1226 kmemzones[indx].kz_zone[subzone] =
1227 uma_zcreate(name, size,
1228 #if defined(INVARIANTS) && !defined(KASAN)
1229 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1231 NULL, NULL, NULL, NULL,
1233 align, UMA_ZONE_MALLOC);
1235 for (;i <= size; i+= KMEM_ZBASE)
1236 kmemsize[i >> KMEM_ZSHIFT] = indx;
1239 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1242 malloc_init(void *data)
1244 struct malloc_type_internal *mtip;
1245 struct malloc_type *mtp;
1247 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1250 if (mtp->ks_version != M_VERSION)
1251 panic("malloc_init: type %s with unsupported version %lu",
1252 mtp->ks_shortdesc, mtp->ks_version);
1254 mtip = &mtp->ks_mti;
1255 mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1256 mtp_set_subzone(mtp);
1258 mtx_lock(&malloc_mtx);
1259 mtp->ks_next = kmemstatistics;
1260 kmemstatistics = mtp;
1262 mtx_unlock(&malloc_mtx);
1266 malloc_uninit(void *data)
1268 struct malloc_type_internal *mtip;
1269 struct malloc_type_stats *mtsp;
1270 struct malloc_type *mtp, *temp;
1271 long temp_allocs, temp_bytes;
1275 KASSERT(mtp->ks_version == M_VERSION,
1276 ("malloc_uninit: bad malloc type version"));
1278 mtx_lock(&malloc_mtx);
1279 mtip = &mtp->ks_mti;
1280 if (mtp != kmemstatistics) {
1281 for (temp = kmemstatistics; temp != NULL;
1282 temp = temp->ks_next) {
1283 if (temp->ks_next == mtp) {
1284 temp->ks_next = mtp->ks_next;
1289 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1291 kmemstatistics = mtp->ks_next;
1293 mtx_unlock(&malloc_mtx);
1296 * Look for memory leaks.
1298 temp_allocs = temp_bytes = 0;
1299 for (i = 0; i <= mp_maxid; i++) {
1300 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1301 temp_allocs += mtsp->mts_numallocs;
1302 temp_allocs -= mtsp->mts_numfrees;
1303 temp_bytes += mtsp->mts_memalloced;
1304 temp_bytes -= mtsp->mts_memfreed;
1306 if (temp_allocs > 0 || temp_bytes > 0) {
1307 printf("Warning: memory type %s leaked memory on destroy "
1308 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1309 temp_allocs, temp_bytes);
1312 uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1315 struct malloc_type *
1316 malloc_desc2type(const char *desc)
1318 struct malloc_type *mtp;
1320 mtx_assert(&malloc_mtx, MA_OWNED);
1321 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1322 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1329 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1331 struct malloc_type_stream_header mtsh;
1332 struct malloc_type_internal *mtip;
1333 struct malloc_type_stats *mtsp, zeromts;
1334 struct malloc_type_header mth;
1335 struct malloc_type *mtp;
1339 error = sysctl_wire_old_buffer(req, 0);
1342 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1343 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1344 mtx_lock(&malloc_mtx);
1346 bzero(&zeromts, sizeof(zeromts));
1349 * Insert stream header.
1351 bzero(&mtsh, sizeof(mtsh));
1352 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1353 mtsh.mtsh_maxcpus = MAXCPU;
1354 mtsh.mtsh_count = kmemcount;
1355 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1358 * Insert alternating sequence of type headers and type statistics.
1360 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1361 mtip = &mtp->ks_mti;
1364 * Insert type header.
1366 bzero(&mth, sizeof(mth));
1367 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1368 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1371 * Insert type statistics for each CPU.
1373 for (i = 0; i <= mp_maxid; i++) {
1374 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1375 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1378 * Fill in the missing CPUs.
1380 for (; i < MAXCPU; i++) {
1381 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1384 mtx_unlock(&malloc_mtx);
1385 error = sbuf_finish(&sbuf);
1390 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1391 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1392 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1393 "Return malloc types");
1395 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1396 "Count of kernel malloc types");
1399 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1401 struct malloc_type *mtp, **bufmtp;
1405 mtx_lock(&malloc_mtx);
1407 mtx_assert(&malloc_mtx, MA_OWNED);
1409 mtx_unlock(&malloc_mtx);
1411 buflen = sizeof(struct malloc_type *) * count;
1412 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1414 mtx_lock(&malloc_mtx);
1416 if (count < kmemcount) {
1417 free(bufmtp, M_TEMP);
1421 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1424 mtx_unlock(&malloc_mtx);
1426 for (i = 0; i < count; i++)
1427 (func)(bufmtp[i], arg);
1429 free(bufmtp, M_TEMP);
1434 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1437 const struct malloc_type_stats *mtsp;
1438 uint64_t frees, alloced, freed;
1445 for (i = 0; i <= mp_maxid; i++) {
1446 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1448 *allocs += mtsp->mts_numallocs;
1449 frees += mtsp->mts_numfrees;
1450 alloced += mtsp->mts_memalloced;
1451 freed += mtsp->mts_memfreed;
1453 *inuse = *allocs - frees;
1454 return (alloced - freed);
1457 DB_SHOW_COMMAND(malloc, db_show_malloc)
1459 const char *fmt_hdr, *fmt_entry;
1460 struct malloc_type *mtp;
1461 uint64_t allocs, inuse;
1463 /* variables for sorting */
1464 struct malloc_type *last_mtype, *cur_mtype;
1465 int64_t cur_size, last_size;
1468 if (modif[0] == 'i') {
1469 fmt_hdr = "%s,%s,%s,%s\n";
1470 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1472 fmt_hdr = "%18s %12s %12s %12s\n";
1473 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1476 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1478 /* Select sort, largest size first. */
1480 last_size = INT64_MAX;
1486 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1488 * In the case of size ties, print out mtypes
1489 * in the order they are encountered. That is,
1490 * when we encounter the most recently output
1491 * mtype, we have already printed all preceding
1492 * ties, and we must print all following ties.
1494 if (mtp == last_mtype) {
1498 size = get_malloc_stats(&mtp->ks_mti, &allocs,
1500 if (size > cur_size && size < last_size + ties) {
1505 if (cur_mtype == NULL)
1508 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1509 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1510 howmany(size, 1024), allocs);
1515 last_mtype = cur_mtype;
1516 last_size = cur_size;
1520 #if MALLOC_DEBUG_MAXZONES > 1
1521 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1523 struct malloc_type_internal *mtip;
1524 struct malloc_type *mtp;
1528 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1532 if (mtp->ks_version != M_VERSION) {
1533 db_printf("Version %lx does not match expected %x\n",
1534 mtp->ks_version, M_VERSION);
1538 mtip = &mtp->ks_mti;
1539 subzone = mtip->mti_zone;
1541 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1542 mtip = &mtp->ks_mti;
1543 if (mtip->mti_zone != subzone)
1545 db_printf("%s\n", mtp->ks_shortdesc);
1550 #endif /* MALLOC_DEBUG_MAXZONES > 1 */