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>
52 #include <sys/param.h>
53 #include <sys/systm.h>
56 #include <sys/kernel.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/vmmeter.h>
62 #include <sys/queue.h>
65 #include <sys/sysctl.h>
69 #include <sys/epoch.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>
84 #include <vm/uma_int.h>
85 #include <vm/uma_dbg.h>
88 #include <vm/memguard.h>
91 #include <vm/redzone.h>
94 #if defined(INVARIANTS) && defined(__i386__)
95 #include <machine/cpu.h>
101 #include <sys/dtrace_bsd.h>
103 bool __read_frequently dtrace_malloc_enabled;
104 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
107 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
108 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
109 #define MALLOC_DEBUG 1
112 #if defined(KASAN) || defined(DEBUG_REDZONE)
113 #define DEBUG_REDZONE_ARG_DEF , unsigned long osize
114 #define DEBUG_REDZONE_ARG , osize
116 #define DEBUG_REDZONE_ARG_DEF
117 #define DEBUG_REDZONE_ARG
121 * When realloc() is called, if the new size is sufficiently smaller than
122 * the old size, realloc() will allocate a new, smaller block to avoid
123 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
124 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
126 #ifndef REALLOC_FRACTION
127 #define REALLOC_FRACTION 1 /* new block if <= half the size */
131 * Centrally define some common malloc types.
133 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
134 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
135 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
137 static struct malloc_type *kmemstatistics;
138 static int kmemcount;
140 #define KMEM_ZSHIFT 4
141 #define KMEM_ZBASE 16
142 #define KMEM_ZMASK (KMEM_ZBASE - 1)
144 #define KMEM_ZMAX 65536
145 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
146 static uint8_t kmemsize[KMEM_ZSIZE + 1];
148 #ifndef MALLOC_DEBUG_MAXZONES
149 #define MALLOC_DEBUG_MAXZONES 1
151 static int numzones = MALLOC_DEBUG_MAXZONES;
154 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
157 * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
159 * XXX: The comment here used to read "These won't be powers of two for
160 * long." It's possible that a significant amount of wasted memory could be
161 * recovered by tuning the sizes of these buckets.
166 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
171 {128, "malloc-128", },
172 {256, "malloc-256", },
173 {384, "malloc-384", },
174 {512, "malloc-512", },
175 {1024, "malloc-1024", },
176 {2048, "malloc-2048", },
177 {4096, "malloc-4096", },
178 {8192, "malloc-8192", },
179 {16384, "malloc-16384", },
180 {32768, "malloc-32768", },
181 {65536, "malloc-65536", },
186 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
187 "Size of kernel memory");
189 static u_long kmem_zmax = KMEM_ZMAX;
190 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
191 "Maximum allocation size that malloc(9) would use UMA as backend");
193 static u_long vm_kmem_size_min;
194 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
195 "Minimum size of kernel memory");
197 static u_long vm_kmem_size_max;
198 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
199 "Maximum size of kernel memory");
201 static u_int vm_kmem_size_scale;
202 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
203 "Scale factor for kernel memory size");
205 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
206 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
207 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
208 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
210 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
211 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
212 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
213 sysctl_kmem_map_free, "LU", "Free space in kmem");
215 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
216 "Malloc information");
218 static u_int vm_malloc_zone_count = nitems(kmemzones);
219 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
220 CTLFLAG_RD, &vm_malloc_zone_count, 0,
221 "Number of malloc zones");
223 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
224 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
225 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
226 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
229 * The malloc_mtx protects the kmemstatistics linked list.
231 struct mtx malloc_mtx;
233 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
235 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
236 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
237 "Kernel malloc debugging options");
241 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
242 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
244 #ifdef MALLOC_MAKE_FAILURES
245 static int malloc_failure_rate;
246 static int malloc_nowait_count;
247 static int malloc_failure_count;
248 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
249 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
250 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
251 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
255 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
260 return (sysctl_handle_long(oidp, &size, 0, req));
264 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
268 /* The sysctl is unsigned, implement as a saturation value. */
275 return (sysctl_handle_long(oidp, &size, 0, req));
279 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
281 int sizes[nitems(kmemzones)];
284 for (i = 0; i < nitems(kmemzones); i++) {
285 sizes[i] = kmemzones[i].kz_size;
288 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
292 * malloc(9) uma zone separation -- sub-page buffer overruns in one
293 * malloc type will affect only a subset of other malloc types.
295 #if MALLOC_DEBUG_MAXZONES > 1
297 tunable_set_numzones(void)
300 TUNABLE_INT_FETCH("debug.malloc.numzones",
303 /* Sanity check the number of malloc uma zones. */
306 if (numzones > MALLOC_DEBUG_MAXZONES)
307 numzones = MALLOC_DEBUG_MAXZONES;
309 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
310 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
311 &numzones, 0, "Number of malloc uma subzones");
314 * Any number that changes regularly is an okay choice for the
315 * offset. Build numbers are pretty good of you have them.
317 static u_int zone_offset = __FreeBSD_version;
318 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
319 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
320 &zone_offset, 0, "Separate malloc types by examining the "
321 "Nth character in the malloc type short description.");
324 mtp_set_subzone(struct malloc_type *mtp)
326 struct malloc_type_internal *mtip;
332 desc = mtp->ks_shortdesc;
333 if (desc == NULL || (len = strlen(desc)) == 0)
336 val = desc[zone_offset % len];
337 mtip->mti_zone = (val % numzones);
341 mtp_get_subzone(struct malloc_type *mtp)
343 struct malloc_type_internal *mtip;
347 KASSERT(mtip->mti_zone < numzones,
348 ("mti_zone %u out of range %d",
349 mtip->mti_zone, numzones));
350 return (mtip->mti_zone);
352 #elif MALLOC_DEBUG_MAXZONES == 0
353 #error "MALLOC_DEBUG_MAXZONES must be positive."
356 mtp_set_subzone(struct malloc_type *mtp)
358 struct malloc_type_internal *mtip;
365 mtp_get_subzone(struct malloc_type *mtp)
370 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
373 * An allocation has succeeded -- update malloc type statistics for the
374 * amount of bucket size. Occurs within a critical section so that the
375 * thread isn't preempted and doesn't migrate while updating per-PCU
379 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
382 struct malloc_type_internal *mtip;
383 struct malloc_type_stats *mtsp;
387 mtsp = zpcpu_get(mtip->mti_stats);
389 mtsp->mts_memalloced += size;
390 mtsp->mts_numallocs++;
393 mtsp->mts_size |= 1 << zindx;
396 if (__predict_false(dtrace_malloc_enabled)) {
397 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
399 (dtrace_malloc_probe)(probe_id,
400 (uintptr_t) mtp, (uintptr_t) mtip,
401 (uintptr_t) mtsp, size, zindx);
409 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
413 malloc_type_zone_allocated(mtp, size, -1);
417 * A free operation has occurred -- update malloc type statistics for the
418 * amount of the bucket size. Occurs within a critical section so that the
419 * thread isn't preempted and doesn't migrate while updating per-CPU
423 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
425 struct malloc_type_internal *mtip;
426 struct malloc_type_stats *mtsp;
430 mtsp = zpcpu_get(mtip->mti_stats);
431 mtsp->mts_memfreed += size;
432 mtsp->mts_numfrees++;
435 if (__predict_false(dtrace_malloc_enabled)) {
436 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
438 (dtrace_malloc_probe)(probe_id,
439 (uintptr_t) mtp, (uintptr_t) mtip,
440 (uintptr_t) mtsp, size, 0);
450 * Allocate a block of physically contiguous memory.
452 * If M_NOWAIT is set, this routine will not block and return NULL if
453 * the allocation fails.
456 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
457 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
462 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
463 boundary, VM_MEMATTR_DEFAULT);
465 malloc_type_allocated(type, round_page(size));
470 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
471 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
472 unsigned long alignment, vm_paddr_t boundary)
476 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
477 alignment, boundary, VM_MEMATTR_DEFAULT);
479 malloc_type_allocated(type, round_page(size));
486 * Free a block of memory allocated by contigmalloc.
488 * This routine may not block.
491 contigfree(void *addr, unsigned long size, struct malloc_type *type)
494 kmem_free((vm_offset_t)addr, size);
495 malloc_type_freed(type, round_page(size));
500 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
506 KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
508 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
510 indx = flags & (M_WAITOK | M_NOWAIT);
511 if (indx != M_NOWAIT && indx != M_WAITOK) {
512 static struct timeval lasterr;
513 static int curerr, once;
514 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
515 printf("Bad malloc flags: %x\n", indx);
522 #ifdef MALLOC_MAKE_FAILURES
523 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
524 atomic_add_int(&malloc_nowait_count, 1);
525 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
526 atomic_add_int(&malloc_failure_count, 1);
528 return (EJUSTRETURN);
532 if (flags & M_WAITOK) {
533 KASSERT(curthread->td_intr_nesting_level == 0,
534 ("malloc(M_WAITOK) in interrupt context"));
535 if (__predict_false(!THREAD_CAN_SLEEP())) {
537 epoch_trace_list(curthread);
540 ("malloc(M_WAITOK) with sleeping prohibited"));
543 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
544 ("malloc: called with spinlock or critical section held"));
546 #ifdef DEBUG_MEMGUARD
547 if (memguard_cmp_mtp(mtp, *sizep)) {
548 *vap = memguard_alloc(*sizep, flags);
550 return (EJUSTRETURN);
551 /* This is unfortunate but should not be fatal. */
556 *sizep = redzone_size_ntor(*sizep);
564 * Handle large allocations and frees by using kmem_malloc directly.
567 malloc_large_slab(uma_slab_t slab)
571 va = (uintptr_t)slab;
572 return ((va & 1) != 0);
576 malloc_large_size(uma_slab_t slab)
580 va = (uintptr_t)slab;
584 static caddr_t __noinline
585 malloc_large(size_t *size, struct malloc_type *mtp, struct domainset *policy,
586 int flags DEBUG_REDZONE_ARG_DEF)
592 sz = roundup(*size, PAGE_SIZE);
593 kva = kmem_malloc_domainset(policy, sz, flags);
595 /* The low bit is unused for slab pointers. */
596 vsetzoneslab(kva, NULL, (void *)((sz << 1) | 1));
601 malloc_type_allocated(mtp, va == NULL ? 0 : sz);
602 if (__predict_false(va == NULL)) {
603 KASSERT((flags & M_WAITOK) == 0,
604 ("malloc(M_WAITOK) returned NULL"));
607 va = redzone_setup(va, osize);
609 kasan_mark((void *)va, osize, sz, KASAN_MALLOC_REDZONE);
615 free_large(void *addr, size_t size)
618 kmem_free((vm_offset_t)addr, size);
625 * Allocate a block of memory.
627 * If M_NOWAIT is set, this routine will not block and return NULL if
628 * the allocation fails.
631 (malloc)(size_t size, struct malloc_type *mtp, int flags)
636 #if defined(DEBUG_REDZONE) || defined(KASAN)
637 unsigned long osize = size;
640 MPASS((flags & M_EXEC) == 0);
644 if (malloc_dbg(&va, &size, mtp, flags) != 0)
648 if (__predict_false(size > kmem_zmax))
649 return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
652 if (size & KMEM_ZMASK)
653 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
654 indx = kmemsize[size >> KMEM_ZSHIFT];
655 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
656 va = uma_zalloc(zone, flags);
658 size = zone->uz_size;
659 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
660 if (__predict_false(va == NULL)) {
661 KASSERT((flags & M_WAITOK) == 0,
662 ("malloc(M_WAITOK) returned NULL"));
666 va = redzone_setup(va, osize);
670 kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
672 return ((void *) va);
676 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
685 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
686 ("malloc_domain: Called with bad flag / size combination."));
687 if (size & KMEM_ZMASK)
688 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
689 indx = kmemsize[size >> KMEM_ZSHIFT];
690 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
691 va = uma_zalloc_domain(zone, NULL, domain, flags);
693 *sizep = zone->uz_size;
699 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
702 struct vm_domainset_iter di;
706 #if defined(KASAN) || defined(DEBUG_REDZONE)
707 unsigned long osize = size;
710 MPASS((flags & M_EXEC) == 0);
714 if (malloc_dbg(&va, &size, mtp, flags) != 0)
718 if (__predict_false(size > kmem_zmax))
719 return (malloc_large(&size, mtp, DOMAINSET_RR(), flags
722 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
724 va = malloc_domain(&size, &indx, mtp, domain, flags);
725 } while (va == NULL && vm_domainset_iter_policy(&di, &domain) == 0);
726 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
727 if (__predict_false(va == NULL)) {
728 KASSERT((flags & M_WAITOK) == 0,
729 ("malloc(M_WAITOK) returned NULL"));
733 va = redzone_setup(va, osize);
737 kasan_mark((void *)va, osize, size, KASAN_MALLOC_REDZONE);
743 * Allocate an executable area.
746 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
749 return (malloc_domainset_exec(size, mtp, DOMAINSET_RR(), flags));
753 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
756 #if defined(DEBUG_REDZONE) || defined(KASAN)
757 unsigned long osize = size;
767 if (malloc_dbg(&va, &size, mtp, flags) != 0)
771 return (malloc_large(&size, mtp, ds, flags DEBUG_REDZONE_ARG));
775 malloc_aligned(size_t size, size_t align, struct malloc_type *type, int flags)
777 return (malloc_domainset_aligned(size, align, type, DOMAINSET_RR(),
782 malloc_domainset_aligned(size_t size, size_t align,
783 struct malloc_type *mtp, struct domainset *ds, int flags)
788 KASSERT(powerof2(align),
789 ("malloc_domainset_aligned: wrong align %#zx size %#zx",
791 KASSERT(align <= PAGE_SIZE,
792 ("malloc_domainset_aligned: align %#zx (size %#zx) too large",
796 * Round the allocation size up to the next power of 2,
797 * because we can only guarantee alignment for
798 * power-of-2-sized allocations. Further increase the
799 * allocation size to align if the rounded size is less than
800 * align, since malloc zones provide alignment equal to their
805 asize = size <= align ? align : 1UL << flsl(size - 1);
807 res = malloc_domainset(asize, mtp, ds, flags);
808 KASSERT(res == NULL || ((uintptr_t)res & (align - 1)) == 0,
809 ("malloc_domainset_aligned: result not aligned %p size %#zx "
810 "allocsize %#zx align %#zx", res, size, asize, align));
815 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
818 if (WOULD_OVERFLOW(nmemb, size))
819 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
821 return (malloc(size * nmemb, type, flags));
825 mallocarray_domainset(size_t nmemb, size_t size, struct malloc_type *type,
826 struct domainset *ds, int flags)
829 if (WOULD_OVERFLOW(nmemb, size))
830 panic("mallocarray_domainset: %zu * %zu overflowed", nmemb, size);
832 return (malloc_domainset(size * nmemb, type, ds, flags));
835 #if defined(INVARIANTS) && !defined(KASAN)
837 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
839 struct malloc_type **mtpp = addr;
842 * Cache a pointer to the malloc_type that most recently freed
843 * this memory here. This way we know who is most likely to
844 * have stepped on it later.
846 * This code assumes that size is a multiple of 8 bytes for
849 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
850 mtpp += (size - sizeof(struct malloc_type *)) /
851 sizeof(struct malloc_type *);
858 free_dbg(void **addrp, struct malloc_type *mtp)
863 KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
864 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
865 ("free: called with spinlock or critical section held"));
867 /* free(NULL, ...) does nothing */
869 return (EJUSTRETURN);
871 #ifdef DEBUG_MEMGUARD
872 if (is_memguard_addr(addr)) {
874 return (EJUSTRETURN);
880 *addrp = redzone_addr_ntor(addr);
890 * Free a block of memory allocated by malloc.
892 * This routine may not block.
895 free(void *addr, struct malloc_type *mtp)
902 if (free_dbg(&addr, mtp) != 0)
905 /* free(NULL, ...) does nothing */
909 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
911 panic("free: address %p(%p) has not been allocated.\n",
912 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
914 if (__predict_true(!malloc_large_slab(slab))) {
915 size = zone->uz_size;
916 #if defined(INVARIANTS) && !defined(KASAN)
917 free_save_type(addr, mtp, size);
919 uma_zfree_arg(zone, addr, slab);
921 size = malloc_large_size(slab);
922 free_large(addr, size);
924 malloc_type_freed(mtp, size);
930 * Zero then free a block of memory allocated by malloc.
932 * This routine may not block.
935 zfree(void *addr, struct malloc_type *mtp)
942 if (free_dbg(&addr, mtp) != 0)
945 /* free(NULL, ...) does nothing */
949 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
951 panic("free: address %p(%p) has not been allocated.\n",
952 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
954 if (__predict_true(!malloc_large_slab(slab))) {
955 size = zone->uz_size;
956 #if defined(INVARIANTS) && !defined(KASAN)
957 free_save_type(addr, mtp, size);
959 kasan_mark(addr, size, size, 0);
960 explicit_bzero(addr, size);
961 uma_zfree_arg(zone, addr, slab);
963 size = malloc_large_size(slab);
964 kasan_mark(addr, size, size, 0);
965 explicit_bzero(addr, size);
966 free_large(addr, size);
968 malloc_type_freed(mtp, size);
972 * realloc: change the size of a memory block
975 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
982 KASSERT(mtp->ks_version == M_VERSION,
983 ("realloc: bad malloc type version"));
984 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
985 ("realloc: called with spinlock or critical section held"));
987 /* realloc(NULL, ...) is equivalent to malloc(...) */
989 return (malloc(size, mtp, flags));
992 * XXX: Should report free of old memory and alloc of new memory to
996 #ifdef DEBUG_MEMGUARD
997 if (is_memguard_addr(addr))
998 return (memguard_realloc(addr, size, mtp, flags));
1001 #ifdef DEBUG_REDZONE
1004 alloc = redzone_get_size(addr);
1006 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1009 KASSERT(slab != NULL,
1010 ("realloc: address %p out of range", (void *)addr));
1012 /* Get the size of the original block */
1013 if (!malloc_large_slab(slab))
1014 alloc = zone->uz_size;
1016 alloc = malloc_large_size(slab);
1018 /* Reuse the original block if appropriate */
1019 if (size <= alloc &&
1020 (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE)) {
1021 kasan_mark((void *)addr, size, alloc, KASAN_MALLOC_REDZONE);
1024 #endif /* !DEBUG_REDZONE */
1026 /* Allocate a new, bigger (or smaller) block */
1027 if ((newaddr = malloc(size, mtp, flags)) == NULL)
1031 * Copy over original contents. For KASAN, the redzone must be marked
1032 * valid before performing the copy.
1034 kasan_mark(addr, alloc, alloc, 0);
1035 bcopy(addr, newaddr, min(size, alloc));
1041 * reallocf: same as realloc() but free memory on failure.
1044 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1048 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1054 * malloc_size: returns the number of bytes allocated for a request of the
1058 malloc_size(size_t size)
1062 if (size > kmem_zmax)
1064 if (size & KMEM_ZMASK)
1065 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1066 indx = kmemsize[size >> KMEM_ZSHIFT];
1067 return (kmemzones[indx].kz_size);
1071 * malloc_usable_size: returns the usable size of the allocation.
1074 malloc_usable_size(const void *addr)
1076 #ifndef DEBUG_REDZONE
1085 #ifdef DEBUG_MEMGUARD
1086 if (is_memguard_addr(__DECONST(void *, addr)))
1087 return (memguard_get_req_size(addr));
1090 #ifdef DEBUG_REDZONE
1091 size = redzone_get_size(__DECONST(void *, addr));
1093 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1095 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1096 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1098 if (!malloc_large_slab(slab))
1099 size = zone->uz_size;
1101 size = malloc_large_size(slab);
1106 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1109 * Initialize the kernel memory (kmem) arena.
1118 if (vm_kmem_size == 0)
1119 vm_kmem_size = VM_KMEM_SIZE;
1121 #ifdef VM_KMEM_SIZE_MIN
1122 if (vm_kmem_size_min == 0)
1123 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1125 #ifdef VM_KMEM_SIZE_MAX
1126 if (vm_kmem_size_max == 0)
1127 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1130 * Calculate the amount of kernel virtual address (KVA) space that is
1131 * preallocated to the kmem arena. In order to support a wide range
1132 * of machines, it is a function of the physical memory size,
1135 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1136 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1138 * Every architecture must define an integral value for
1139 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1140 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1141 * ceiling on this preallocation, are optional. Typically,
1142 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1143 * a given architecture.
1145 mem_size = vm_cnt.v_page_count;
1146 if (mem_size <= 32768) /* delphij XXX 128MB */
1147 kmem_zmax = PAGE_SIZE;
1149 if (vm_kmem_size_scale < 1)
1150 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1153 * Check if we should use defaults for the "vm_kmem_size"
1156 if (vm_kmem_size == 0) {
1157 vm_kmem_size = mem_size / vm_kmem_size_scale;
1158 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1159 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1160 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1161 vm_kmem_size = vm_kmem_size_min;
1162 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1163 vm_kmem_size = vm_kmem_size_max;
1165 if (vm_kmem_size == 0)
1166 panic("Tune VM_KMEM_SIZE_* for the platform");
1169 * The amount of KVA space that is preallocated to the
1170 * kmem arena can be set statically at compile-time or manually
1171 * through the kernel environment. However, it is still limited to
1172 * twice the physical memory size, which has been sufficient to handle
1173 * the most severe cases of external fragmentation in the kmem arena.
1175 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1176 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1178 vm_kmem_size = round_page(vm_kmem_size);
1182 * With KASAN enabled, dynamically allocated kernel memory is shadowed.
1183 * Account for this when setting the UMA limit.
1185 vm_kmem_size = (vm_kmem_size * KASAN_SHADOW_SCALE) /
1186 (KASAN_SHADOW_SCALE + 1);
1189 #ifdef DEBUG_MEMGUARD
1190 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1196 #ifdef DEBUG_MEMGUARD
1198 * Initialize MemGuard if support compiled in. MemGuard is a
1199 * replacement allocator used for detecting tamper-after-free
1200 * scenarios as they occur. It is only used for debugging.
1202 memguard_init(kernel_arena);
1207 * Initialize the kernel memory allocator
1211 mallocinit(void *dummy)
1216 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1220 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1221 kmem_zmax = KMEM_ZMAX;
1223 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1224 int size = kmemzones[indx].kz_size;
1225 const char *name = kmemzones[indx].kz_name;
1229 align = UMA_ALIGN_PTR;
1230 if (powerof2(size) && size > sizeof(void *))
1231 align = MIN(size, PAGE_SIZE) - 1;
1232 for (subzone = 0; subzone < numzones; subzone++) {
1233 kmemzones[indx].kz_zone[subzone] =
1234 uma_zcreate(name, size,
1235 #if defined(INVARIANTS) && !defined(KASAN)
1236 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1238 NULL, NULL, NULL, NULL,
1240 align, UMA_ZONE_MALLOC);
1242 for (;i <= size; i+= KMEM_ZBASE)
1243 kmemsize[i >> KMEM_ZSHIFT] = indx;
1246 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1249 malloc_init(void *data)
1251 struct malloc_type_internal *mtip;
1252 struct malloc_type *mtp;
1254 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1257 if (mtp->ks_version != M_VERSION)
1258 panic("malloc_init: type %s with unsupported version %lu",
1259 mtp->ks_shortdesc, mtp->ks_version);
1261 mtip = &mtp->ks_mti;
1262 mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1263 mtp_set_subzone(mtp);
1265 mtx_lock(&malloc_mtx);
1266 mtp->ks_next = kmemstatistics;
1267 kmemstatistics = mtp;
1269 mtx_unlock(&malloc_mtx);
1273 malloc_uninit(void *data)
1275 struct malloc_type_internal *mtip;
1276 struct malloc_type_stats *mtsp;
1277 struct malloc_type *mtp, *temp;
1278 long temp_allocs, temp_bytes;
1282 KASSERT(mtp->ks_version == M_VERSION,
1283 ("malloc_uninit: bad malloc type version"));
1285 mtx_lock(&malloc_mtx);
1286 mtip = &mtp->ks_mti;
1287 if (mtp != kmemstatistics) {
1288 for (temp = kmemstatistics; temp != NULL;
1289 temp = temp->ks_next) {
1290 if (temp->ks_next == mtp) {
1291 temp->ks_next = mtp->ks_next;
1296 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1298 kmemstatistics = mtp->ks_next;
1300 mtx_unlock(&malloc_mtx);
1303 * Look for memory leaks.
1305 temp_allocs = temp_bytes = 0;
1306 for (i = 0; i <= mp_maxid; i++) {
1307 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1308 temp_allocs += mtsp->mts_numallocs;
1309 temp_allocs -= mtsp->mts_numfrees;
1310 temp_bytes += mtsp->mts_memalloced;
1311 temp_bytes -= mtsp->mts_memfreed;
1313 if (temp_allocs > 0 || temp_bytes > 0) {
1314 printf("Warning: memory type %s leaked memory on destroy "
1315 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1316 temp_allocs, temp_bytes);
1319 uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1322 struct malloc_type *
1323 malloc_desc2type(const char *desc)
1325 struct malloc_type *mtp;
1327 mtx_assert(&malloc_mtx, MA_OWNED);
1328 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1329 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1336 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1338 struct malloc_type_stream_header mtsh;
1339 struct malloc_type_internal *mtip;
1340 struct malloc_type_stats *mtsp, zeromts;
1341 struct malloc_type_header mth;
1342 struct malloc_type *mtp;
1346 error = sysctl_wire_old_buffer(req, 0);
1349 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1350 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1351 mtx_lock(&malloc_mtx);
1353 bzero(&zeromts, sizeof(zeromts));
1356 * Insert stream header.
1358 bzero(&mtsh, sizeof(mtsh));
1359 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1360 mtsh.mtsh_maxcpus = MAXCPU;
1361 mtsh.mtsh_count = kmemcount;
1362 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1365 * Insert alternating sequence of type headers and type statistics.
1367 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1368 mtip = &mtp->ks_mti;
1371 * Insert type header.
1373 bzero(&mth, sizeof(mth));
1374 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1375 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1378 * Insert type statistics for each CPU.
1380 for (i = 0; i <= mp_maxid; i++) {
1381 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1382 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1385 * Fill in the missing CPUs.
1387 for (; i < MAXCPU; i++) {
1388 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1391 mtx_unlock(&malloc_mtx);
1392 error = sbuf_finish(&sbuf);
1397 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1398 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1399 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1400 "Return malloc types");
1402 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1403 "Count of kernel malloc types");
1406 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1408 struct malloc_type *mtp, **bufmtp;
1412 mtx_lock(&malloc_mtx);
1414 mtx_assert(&malloc_mtx, MA_OWNED);
1416 mtx_unlock(&malloc_mtx);
1418 buflen = sizeof(struct malloc_type *) * count;
1419 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1421 mtx_lock(&malloc_mtx);
1423 if (count < kmemcount) {
1424 free(bufmtp, M_TEMP);
1428 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1431 mtx_unlock(&malloc_mtx);
1433 for (i = 0; i < count; i++)
1434 (func)(bufmtp[i], arg);
1436 free(bufmtp, M_TEMP);
1441 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1444 const struct malloc_type_stats *mtsp;
1445 uint64_t frees, alloced, freed;
1452 for (i = 0; i <= mp_maxid; i++) {
1453 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1455 *allocs += mtsp->mts_numallocs;
1456 frees += mtsp->mts_numfrees;
1457 alloced += mtsp->mts_memalloced;
1458 freed += mtsp->mts_memfreed;
1460 *inuse = *allocs - frees;
1461 return (alloced - freed);
1464 DB_SHOW_COMMAND(malloc, db_show_malloc)
1466 const char *fmt_hdr, *fmt_entry;
1467 struct malloc_type *mtp;
1468 uint64_t allocs, inuse;
1470 /* variables for sorting */
1471 struct malloc_type *last_mtype, *cur_mtype;
1472 int64_t cur_size, last_size;
1475 if (modif[0] == 'i') {
1476 fmt_hdr = "%s,%s,%s,%s\n";
1477 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1479 fmt_hdr = "%18s %12s %12s %12s\n";
1480 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1483 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1485 /* Select sort, largest size first. */
1487 last_size = INT64_MAX;
1493 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1495 * In the case of size ties, print out mtypes
1496 * in the order they are encountered. That is,
1497 * when we encounter the most recently output
1498 * mtype, we have already printed all preceding
1499 * ties, and we must print all following ties.
1501 if (mtp == last_mtype) {
1505 size = get_malloc_stats(&mtp->ks_mti, &allocs,
1507 if (size > cur_size && size < last_size + ties) {
1512 if (cur_mtype == NULL)
1515 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1516 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1517 howmany(size, 1024), allocs);
1522 last_mtype = cur_mtype;
1523 last_size = cur_size;
1527 #if MALLOC_DEBUG_MAXZONES > 1
1528 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1530 struct malloc_type_internal *mtip;
1531 struct malloc_type *mtp;
1535 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1539 if (mtp->ks_version != M_VERSION) {
1540 db_printf("Version %lx does not match expected %x\n",
1541 mtp->ks_version, M_VERSION);
1545 mtip = &mtp->ks_mti;
1546 subzone = mtip->mti_zone;
1548 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1549 mtip = &mtp->ks_mti;
1550 if (mtip->mti_zone != subzone)
1552 db_printf("%s\n", mtp->ks_shortdesc);
1557 #endif /* MALLOC_DEBUG_MAXZONES > 1 */