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>
57 #include <sys/kernel.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/vmmeter.h>
63 #include <sys/queue.h>
66 #include <sys/sysctl.h>
70 #include <sys/epoch.h>
75 #include <vm/vm_domainset.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_param.h>
78 #include <vm/vm_kern.h>
79 #include <vm/vm_extern.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_phys.h>
83 #include <vm/vm_pagequeue.h>
85 #include <vm/uma_int.h>
86 #include <vm/uma_dbg.h>
89 #include <vm/memguard.h>
92 #include <vm/redzone.h>
95 #if defined(INVARIANTS) && defined(__i386__)
96 #include <machine/cpu.h>
102 #include <sys/dtrace_bsd.h>
104 bool __read_frequently dtrace_malloc_enabled;
105 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
108 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
109 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
110 #define MALLOC_DEBUG 1
114 * When realloc() is called, if the new size is sufficiently smaller than
115 * the old size, realloc() will allocate a new, smaller block to avoid
116 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
117 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
119 #ifndef REALLOC_FRACTION
120 #define REALLOC_FRACTION 1 /* new block if <= half the size */
124 * Centrally define some common malloc types.
126 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
127 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
128 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
130 static struct malloc_type *kmemstatistics;
131 static int kmemcount;
133 #define KMEM_ZSHIFT 4
134 #define KMEM_ZBASE 16
135 #define KMEM_ZMASK (KMEM_ZBASE - 1)
137 #define KMEM_ZMAX 65536
138 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
139 static uint8_t kmemsize[KMEM_ZSIZE + 1];
141 #ifndef MALLOC_DEBUG_MAXZONES
142 #define MALLOC_DEBUG_MAXZONES 1
144 static int numzones = MALLOC_DEBUG_MAXZONES;
147 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
150 * Warning: the layout of the struct is duplicated in libmemstat for KVM support.
152 * XXX: The comment here used to read "These won't be powers of two for
153 * long." It's possible that a significant amount of wasted memory could be
154 * recovered by tuning the sizes of these buckets.
159 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
178 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
179 * types are described by a data structure passed by the declaring code, but
180 * the malloc(9) implementation has its own data structure describing the
181 * type and statistics. This permits the malloc(9)-internal data structures
182 * to be modified without breaking binary-compiled kernel modules that
183 * declare malloc types.
185 static uma_zone_t mt_zone;
186 static uma_zone_t mt_stats_zone;
189 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
190 "Size of kernel memory");
192 static u_long kmem_zmax = KMEM_ZMAX;
193 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
194 "Maximum allocation size that malloc(9) would use UMA as backend");
196 static u_long vm_kmem_size_min;
197 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
198 "Minimum size of kernel memory");
200 static u_long vm_kmem_size_max;
201 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
202 "Maximum size of kernel memory");
204 static u_int vm_kmem_size_scale;
205 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
206 "Scale factor for kernel memory size");
208 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
209 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
210 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
211 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
213 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
214 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
215 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
216 sysctl_kmem_map_free, "LU", "Free space in kmem");
218 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
219 "Malloc information");
221 static u_int vm_malloc_zone_count = nitems(kmemzones);
222 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
223 CTLFLAG_RD, &vm_malloc_zone_count, 0,
224 "Number of malloc zones");
226 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
227 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
228 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
229 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
232 * The malloc_mtx protects the kmemstatistics linked list.
234 struct mtx malloc_mtx;
236 #ifdef MALLOC_PROFILE
237 uint64_t krequests[KMEM_ZSIZE + 1];
239 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
242 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
245 * time_uptime of the last malloc(9) failure (induced or real).
247 static time_t t_malloc_fail;
249 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
250 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
251 "Kernel malloc debugging options");
255 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
256 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
258 #ifdef MALLOC_MAKE_FAILURES
259 static int malloc_failure_rate;
260 static int malloc_nowait_count;
261 static int malloc_failure_count;
262 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
263 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
264 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
265 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
269 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
274 return (sysctl_handle_long(oidp, &size, 0, req));
278 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
282 /* The sysctl is unsigned, implement as a saturation value. */
289 return (sysctl_handle_long(oidp, &size, 0, req));
293 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
295 int sizes[nitems(kmemzones)];
298 for (i = 0; i < nitems(kmemzones); i++) {
299 sizes[i] = kmemzones[i].kz_size;
302 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
306 * malloc(9) uma zone separation -- sub-page buffer overruns in one
307 * malloc type will affect only a subset of other malloc types.
309 #if MALLOC_DEBUG_MAXZONES > 1
311 tunable_set_numzones(void)
314 TUNABLE_INT_FETCH("debug.malloc.numzones",
317 /* Sanity check the number of malloc uma zones. */
320 if (numzones > MALLOC_DEBUG_MAXZONES)
321 numzones = MALLOC_DEBUG_MAXZONES;
323 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
324 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
325 &numzones, 0, "Number of malloc uma subzones");
328 * Any number that changes regularly is an okay choice for the
329 * offset. Build numbers are pretty good of you have them.
331 static u_int zone_offset = __FreeBSD_version;
332 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
333 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
334 &zone_offset, 0, "Separate malloc types by examining the "
335 "Nth character in the malloc type short description.");
338 mtp_set_subzone(struct malloc_type *mtp)
340 struct malloc_type_internal *mtip;
345 mtip = mtp->ks_handle;
346 desc = mtp->ks_shortdesc;
347 if (desc == NULL || (len = strlen(desc)) == 0)
350 val = desc[zone_offset % len];
351 mtip->mti_zone = (val % numzones);
355 mtp_get_subzone(struct malloc_type *mtp)
357 struct malloc_type_internal *mtip;
359 mtip = mtp->ks_handle;
361 KASSERT(mtip->mti_zone < numzones,
362 ("mti_zone %u out of range %d",
363 mtip->mti_zone, numzones));
364 return (mtip->mti_zone);
366 #elif MALLOC_DEBUG_MAXZONES == 0
367 #error "MALLOC_DEBUG_MAXZONES must be positive."
370 mtp_set_subzone(struct malloc_type *mtp)
372 struct malloc_type_internal *mtip;
374 mtip = mtp->ks_handle;
379 mtp_get_subzone(struct malloc_type *mtp)
384 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
387 malloc_last_fail(void)
390 return (time_uptime - t_malloc_fail);
394 * An allocation has succeeded -- update malloc type statistics for the
395 * amount of bucket size. Occurs within a critical section so that the
396 * thread isn't preempted and doesn't migrate while updating per-PCU
400 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
403 struct malloc_type_internal *mtip;
404 struct malloc_type_stats *mtsp;
407 mtip = mtp->ks_handle;
408 mtsp = zpcpu_get(mtip->mti_stats);
410 mtsp->mts_memalloced += size;
411 mtsp->mts_numallocs++;
414 mtsp->mts_size |= 1 << zindx;
417 if (__predict_false(dtrace_malloc_enabled)) {
418 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
420 (dtrace_malloc_probe)(probe_id,
421 (uintptr_t) mtp, (uintptr_t) mtip,
422 (uintptr_t) mtsp, size, zindx);
430 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
434 malloc_type_zone_allocated(mtp, size, -1);
438 * A free operation has occurred -- update malloc type statistics for the
439 * amount of the bucket size. Occurs within a critical section so that the
440 * thread isn't preempted and doesn't migrate while updating per-CPU
444 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
446 struct malloc_type_internal *mtip;
447 struct malloc_type_stats *mtsp;
450 mtip = mtp->ks_handle;
451 mtsp = zpcpu_get(mtip->mti_stats);
452 mtsp->mts_memfreed += size;
453 mtsp->mts_numfrees++;
456 if (__predict_false(dtrace_malloc_enabled)) {
457 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
459 (dtrace_malloc_probe)(probe_id,
460 (uintptr_t) mtp, (uintptr_t) mtip,
461 (uintptr_t) mtsp, size, 0);
471 * Allocate a block of physically contiguous memory.
473 * If M_NOWAIT is set, this routine will not block and return NULL if
474 * the allocation fails.
477 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
478 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
483 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
484 boundary, VM_MEMATTR_DEFAULT);
486 malloc_type_allocated(type, round_page(size));
491 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
492 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
493 unsigned long alignment, vm_paddr_t boundary)
497 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
498 alignment, boundary, VM_MEMATTR_DEFAULT);
500 malloc_type_allocated(type, round_page(size));
507 * Free a block of memory allocated by contigmalloc.
509 * This routine may not block.
512 contigfree(void *addr, unsigned long size, struct malloc_type *type)
515 kmem_free((vm_offset_t)addr, size);
516 malloc_type_freed(type, round_page(size));
521 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
527 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
529 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
531 indx = flags & (M_WAITOK | M_NOWAIT);
532 if (indx != M_NOWAIT && indx != M_WAITOK) {
533 static struct timeval lasterr;
534 static int curerr, once;
535 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
536 printf("Bad malloc flags: %x\n", indx);
543 #ifdef MALLOC_MAKE_FAILURES
544 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
545 atomic_add_int(&malloc_nowait_count, 1);
546 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
547 atomic_add_int(&malloc_failure_count, 1);
548 t_malloc_fail = time_uptime;
550 return (EJUSTRETURN);
554 if (flags & M_WAITOK) {
555 KASSERT(curthread->td_intr_nesting_level == 0,
556 ("malloc(M_WAITOK) in interrupt context"));
557 if (__predict_false(!THREAD_CAN_SLEEP())) {
559 epoch_trace_list(curthread);
562 ("malloc(M_WAITOK) with sleeping prohibited"));
565 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
566 ("malloc: called with spinlock or critical section held"));
568 #ifdef DEBUG_MEMGUARD
569 if (memguard_cmp_mtp(mtp, *sizep)) {
570 *vap = memguard_alloc(*sizep, flags);
572 return (EJUSTRETURN);
573 /* This is unfortunate but should not be fatal. */
578 *sizep = redzone_size_ntor(*sizep);
586 * Handle large allocations and frees by using kmem_malloc directly.
589 malloc_large_slab(uma_slab_t slab)
593 va = (uintptr_t)slab;
594 return ((va & 1) != 0);
598 malloc_large_size(uma_slab_t slab)
602 va = (uintptr_t)slab;
607 malloc_large(size_t *size, struct domainset *policy, int flags)
612 sz = roundup(*size, PAGE_SIZE);
613 va = kmem_malloc_domainset(policy, sz, flags);
615 /* The low bit is unused for slab pointers. */
616 vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
620 return ((caddr_t)va);
624 free_large(void *addr, size_t size)
627 kmem_free((vm_offset_t)addr, size);
634 * Allocate a block of memory.
636 * If M_NOWAIT is set, this routine will not block and return NULL if
637 * the allocation fails.
640 (malloc)(size_t size, struct malloc_type *mtp, int flags)
645 #if defined(DEBUG_REDZONE)
646 unsigned long osize = size;
649 MPASS((flags & M_EXEC) == 0);
652 if (malloc_dbg(&va, &size, mtp, flags) != 0)
656 if (size <= kmem_zmax) {
657 if (size & KMEM_ZMASK)
658 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
659 indx = kmemsize[size >> KMEM_ZSHIFT];
660 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
661 #ifdef MALLOC_PROFILE
662 krequests[size >> KMEM_ZSHIFT]++;
664 va = uma_zalloc(zone, flags);
666 size = zone->uz_size;
667 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
669 va = malloc_large(&size, DOMAINSET_RR(), flags);
670 malloc_type_allocated(mtp, va == NULL ? 0 : size);
672 if (__predict_false(va == NULL)) {
673 KASSERT((flags & M_WAITOK) == 0,
674 ("malloc(M_WAITOK) returned NULL"));
675 t_malloc_fail = time_uptime;
679 va = redzone_setup(va, osize);
681 return ((void *) va);
685 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
694 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
695 ("malloc_domain: Called with bad flag / size combination."));
696 if (size & KMEM_ZMASK)
697 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
698 indx = kmemsize[size >> KMEM_ZSHIFT];
699 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
700 #ifdef MALLOC_PROFILE
701 krequests[size >> KMEM_ZSHIFT]++;
703 va = uma_zalloc_domain(zone, NULL, domain, flags);
705 *sizep = zone->uz_size;
711 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
714 struct vm_domainset_iter di;
719 #if defined(DEBUG_REDZONE)
720 unsigned long osize = size;
722 MPASS((flags & M_EXEC) == 0);
725 if (malloc_dbg(&va, &size, mtp, flags) != 0)
728 if (size <= kmem_zmax) {
729 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
731 va = malloc_domain(&size, &indx, mtp, domain, flags);
732 } while (va == NULL &&
733 vm_domainset_iter_policy(&di, &domain) == 0);
734 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
736 /* Policy is handled by kmem. */
737 va = malloc_large(&size, ds, flags);
738 malloc_type_allocated(mtp, va == NULL ? 0 : size);
740 if (__predict_false(va == NULL)) {
741 KASSERT((flags & M_WAITOK) == 0,
742 ("malloc(M_WAITOK) returned NULL"));
743 t_malloc_fail = time_uptime;
747 va = redzone_setup(va, osize);
753 * Allocate an executable area.
756 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
759 #if defined(DEBUG_REDZONE)
760 unsigned long osize = size;
766 if (malloc_dbg(&va, &size, mtp, flags) != 0)
769 va = malloc_large(&size, DOMAINSET_RR(), flags);
770 malloc_type_allocated(mtp, va == NULL ? 0 : size);
771 if (__predict_false(va == NULL)) {
772 KASSERT((flags & M_WAITOK) == 0,
773 ("malloc(M_WAITOK) returned NULL"));
774 t_malloc_fail = time_uptime;
778 va = redzone_setup(va, osize);
780 return ((void *) va);
784 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
788 #if defined(DEBUG_REDZONE)
789 unsigned long osize = size;
795 if (malloc_dbg(&va, &size, mtp, flags) != 0)
798 /* Policy is handled by kmem. */
799 va = malloc_large(&size, ds, flags);
800 malloc_type_allocated(mtp, va == NULL ? 0 : size);
801 if (__predict_false(va == NULL)) {
802 KASSERT((flags & M_WAITOK) == 0,
803 ("malloc(M_WAITOK) returned NULL"));
804 t_malloc_fail = time_uptime;
808 va = redzone_setup(va, osize);
814 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
817 if (WOULD_OVERFLOW(nmemb, size))
818 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
820 return (malloc(size * nmemb, type, flags));
825 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
827 struct malloc_type **mtpp = addr;
830 * Cache a pointer to the malloc_type that most recently freed
831 * this memory here. This way we know who is most likely to
832 * have stepped on it later.
834 * This code assumes that size is a multiple of 8 bytes for
837 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
838 mtpp += (size - sizeof(struct malloc_type *)) /
839 sizeof(struct malloc_type *);
846 free_dbg(void **addrp, struct malloc_type *mtp)
851 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
852 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
853 ("free: called with spinlock or critical section held"));
855 /* free(NULL, ...) does nothing */
857 return (EJUSTRETURN);
859 #ifdef DEBUG_MEMGUARD
860 if (is_memguard_addr(addr)) {
862 return (EJUSTRETURN);
868 *addrp = redzone_addr_ntor(addr);
878 * Free a block of memory allocated by malloc.
880 * This routine may not block.
883 free(void *addr, struct malloc_type *mtp)
890 if (free_dbg(&addr, mtp) != 0)
893 /* free(NULL, ...) does nothing */
897 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
899 panic("free: address %p(%p) has not been allocated.\n",
900 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
902 if (__predict_true(!malloc_large_slab(slab))) {
903 size = zone->uz_size;
905 free_save_type(addr, mtp, size);
907 uma_zfree_arg(zone, addr, slab);
909 size = malloc_large_size(slab);
910 free_large(addr, size);
912 malloc_type_freed(mtp, size);
918 * Zero then free a block of memory allocated by malloc.
920 * This routine may not block.
923 zfree(void *addr, struct malloc_type *mtp)
930 if (free_dbg(&addr, mtp) != 0)
933 /* free(NULL, ...) does nothing */
937 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
939 panic("free: address %p(%p) has not been allocated.\n",
940 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
942 if (__predict_true(!malloc_large_slab(slab))) {
943 size = zone->uz_size;
945 free_save_type(addr, mtp, size);
947 explicit_bzero(addr, size);
948 uma_zfree_arg(zone, addr, slab);
950 size = malloc_large_size(slab);
951 explicit_bzero(addr, size);
952 free_large(addr, size);
954 malloc_type_freed(mtp, size);
958 * realloc: change the size of a memory block
961 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
968 KASSERT(mtp->ks_magic == M_MAGIC,
969 ("realloc: bad malloc type magic"));
970 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
971 ("realloc: called with spinlock or critical section held"));
973 /* realloc(NULL, ...) is equivalent to malloc(...) */
975 return (malloc(size, mtp, flags));
978 * XXX: Should report free of old memory and alloc of new memory to
982 #ifdef DEBUG_MEMGUARD
983 if (is_memguard_addr(addr))
984 return (memguard_realloc(addr, size, mtp, flags));
990 alloc = redzone_get_size(addr);
992 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
995 KASSERT(slab != NULL,
996 ("realloc: address %p out of range", (void *)addr));
998 /* Get the size of the original block */
999 if (!malloc_large_slab(slab))
1000 alloc = zone->uz_size;
1002 alloc = malloc_large_size(slab);
1004 /* Reuse the original block if appropriate */
1006 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
1008 #endif /* !DEBUG_REDZONE */
1010 /* Allocate a new, bigger (or smaller) block */
1011 if ((newaddr = malloc(size, mtp, flags)) == NULL)
1014 /* Copy over original contents */
1015 bcopy(addr, newaddr, min(size, alloc));
1021 * reallocf: same as realloc() but free memory on failure.
1024 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1028 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1034 * malloc_usable_size: returns the usable size of the allocation.
1037 malloc_usable_size(const void *addr)
1039 #ifndef DEBUG_REDZONE
1048 #ifdef DEBUG_MEMGUARD
1049 if (is_memguard_addr(__DECONST(void *, addr)))
1050 return (memguard_get_req_size(addr));
1053 #ifdef DEBUG_REDZONE
1054 size = redzone_get_size(__DECONST(void *, addr));
1056 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1058 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1059 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1061 if (!malloc_large_slab(slab))
1062 size = zone->uz_size;
1064 size = malloc_large_size(slab);
1069 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1072 * Initialize the kernel memory (kmem) arena.
1081 if (vm_kmem_size == 0)
1082 vm_kmem_size = VM_KMEM_SIZE;
1084 #ifdef VM_KMEM_SIZE_MIN
1085 if (vm_kmem_size_min == 0)
1086 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1088 #ifdef VM_KMEM_SIZE_MAX
1089 if (vm_kmem_size_max == 0)
1090 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1093 * Calculate the amount of kernel virtual address (KVA) space that is
1094 * preallocated to the kmem arena. In order to support a wide range
1095 * of machines, it is a function of the physical memory size,
1098 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1099 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1101 * Every architecture must define an integral value for
1102 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1103 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1104 * ceiling on this preallocation, are optional. Typically,
1105 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1106 * a given architecture.
1108 mem_size = vm_cnt.v_page_count;
1109 if (mem_size <= 32768) /* delphij XXX 128MB */
1110 kmem_zmax = PAGE_SIZE;
1112 if (vm_kmem_size_scale < 1)
1113 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1116 * Check if we should use defaults for the "vm_kmem_size"
1119 if (vm_kmem_size == 0) {
1120 vm_kmem_size = mem_size / vm_kmem_size_scale;
1121 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1122 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1123 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1124 vm_kmem_size = vm_kmem_size_min;
1125 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1126 vm_kmem_size = vm_kmem_size_max;
1128 if (vm_kmem_size == 0)
1129 panic("Tune VM_KMEM_SIZE_* for the platform");
1132 * The amount of KVA space that is preallocated to the
1133 * kmem arena can be set statically at compile-time or manually
1134 * through the kernel environment. However, it is still limited to
1135 * twice the physical memory size, which has been sufficient to handle
1136 * the most severe cases of external fragmentation in the kmem arena.
1138 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1139 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1141 vm_kmem_size = round_page(vm_kmem_size);
1142 #ifdef DEBUG_MEMGUARD
1143 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1149 #ifdef DEBUG_MEMGUARD
1151 * Initialize MemGuard if support compiled in. MemGuard is a
1152 * replacement allocator used for detecting tamper-after-free
1153 * scenarios as they occur. It is only used for debugging.
1155 memguard_init(kernel_arena);
1160 * Initialize the kernel memory allocator
1164 mallocinit(void *dummy)
1169 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1173 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1174 kmem_zmax = KMEM_ZMAX;
1176 mt_stats_zone = uma_zcreate("mt_stats_zone",
1177 sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
1178 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
1179 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
1181 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1183 NULL, NULL, NULL, NULL,
1185 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1186 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1187 int size = kmemzones[indx].kz_size;
1188 const char *name = kmemzones[indx].kz_name;
1191 for (subzone = 0; subzone < numzones; subzone++) {
1192 kmemzones[indx].kz_zone[subzone] =
1193 uma_zcreate(name, size,
1195 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1197 NULL, NULL, NULL, NULL,
1199 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1201 for (;i <= size; i+= KMEM_ZBASE)
1202 kmemsize[i >> KMEM_ZSHIFT] = indx;
1205 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1208 malloc_init(void *data)
1210 struct malloc_type_internal *mtip;
1211 struct malloc_type *mtp;
1213 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1216 if (mtp->ks_magic != M_MAGIC)
1217 panic("malloc_init: bad malloc type magic");
1219 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1220 mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1221 mtp->ks_handle = mtip;
1222 mtp_set_subzone(mtp);
1224 mtx_lock(&malloc_mtx);
1225 mtp->ks_next = kmemstatistics;
1226 kmemstatistics = mtp;
1228 mtx_unlock(&malloc_mtx);
1232 malloc_uninit(void *data)
1234 struct malloc_type_internal *mtip;
1235 struct malloc_type_stats *mtsp;
1236 struct malloc_type *mtp, *temp;
1238 long temp_allocs, temp_bytes;
1242 KASSERT(mtp->ks_magic == M_MAGIC,
1243 ("malloc_uninit: bad malloc type magic"));
1244 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1246 mtx_lock(&malloc_mtx);
1247 mtip = mtp->ks_handle;
1248 mtp->ks_handle = NULL;
1249 if (mtp != kmemstatistics) {
1250 for (temp = kmemstatistics; temp != NULL;
1251 temp = temp->ks_next) {
1252 if (temp->ks_next == mtp) {
1253 temp->ks_next = mtp->ks_next;
1258 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1260 kmemstatistics = mtp->ks_next;
1262 mtx_unlock(&malloc_mtx);
1265 * Look for memory leaks.
1267 temp_allocs = temp_bytes = 0;
1268 for (i = 0; i <= mp_maxid; i++) {
1269 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1270 temp_allocs += mtsp->mts_numallocs;
1271 temp_allocs -= mtsp->mts_numfrees;
1272 temp_bytes += mtsp->mts_memalloced;
1273 temp_bytes -= mtsp->mts_memfreed;
1275 if (temp_allocs > 0 || temp_bytes > 0) {
1276 printf("Warning: memory type %s leaked memory on destroy "
1277 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1278 temp_allocs, temp_bytes);
1281 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1282 uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1283 uma_zfree_arg(mt_zone, mtip, slab);
1286 struct malloc_type *
1287 malloc_desc2type(const char *desc)
1289 struct malloc_type *mtp;
1291 mtx_assert(&malloc_mtx, MA_OWNED);
1292 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1293 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1300 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1302 struct malloc_type_stream_header mtsh;
1303 struct malloc_type_internal *mtip;
1304 struct malloc_type_stats *mtsp, zeromts;
1305 struct malloc_type_header mth;
1306 struct malloc_type *mtp;
1310 error = sysctl_wire_old_buffer(req, 0);
1313 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1314 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1315 mtx_lock(&malloc_mtx);
1317 bzero(&zeromts, sizeof(zeromts));
1320 * Insert stream header.
1322 bzero(&mtsh, sizeof(mtsh));
1323 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1324 mtsh.mtsh_maxcpus = MAXCPU;
1325 mtsh.mtsh_count = kmemcount;
1326 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1329 * Insert alternating sequence of type headers and type statistics.
1331 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1332 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1335 * Insert type header.
1337 bzero(&mth, sizeof(mth));
1338 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1339 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1342 * Insert type statistics for each CPU.
1344 for (i = 0; i <= mp_maxid; i++) {
1345 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1346 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1349 * Fill in the missing CPUs.
1351 for (; i < MAXCPU; i++) {
1352 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1355 mtx_unlock(&malloc_mtx);
1356 error = sbuf_finish(&sbuf);
1361 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1362 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1363 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1364 "Return malloc types");
1366 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1367 "Count of kernel malloc types");
1370 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1372 struct malloc_type *mtp, **bufmtp;
1376 mtx_lock(&malloc_mtx);
1378 mtx_assert(&malloc_mtx, MA_OWNED);
1380 mtx_unlock(&malloc_mtx);
1382 buflen = sizeof(struct malloc_type *) * count;
1383 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1385 mtx_lock(&malloc_mtx);
1387 if (count < kmemcount) {
1388 free(bufmtp, M_TEMP);
1392 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1395 mtx_unlock(&malloc_mtx);
1397 for (i = 0; i < count; i++)
1398 (func)(bufmtp[i], arg);
1400 free(bufmtp, M_TEMP);
1405 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1408 const struct malloc_type_stats *mtsp;
1409 uint64_t frees, alloced, freed;
1416 for (i = 0; i <= mp_maxid; i++) {
1417 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1419 *allocs += mtsp->mts_numallocs;
1420 frees += mtsp->mts_numfrees;
1421 alloced += mtsp->mts_memalloced;
1422 freed += mtsp->mts_memfreed;
1424 *inuse = *allocs - frees;
1425 return (alloced - freed);
1428 DB_SHOW_COMMAND(malloc, db_show_malloc)
1430 const char *fmt_hdr, *fmt_entry;
1431 struct malloc_type *mtp;
1432 uint64_t allocs, inuse;
1434 /* variables for sorting */
1435 struct malloc_type *last_mtype, *cur_mtype;
1436 int64_t cur_size, last_size;
1439 if (modif[0] == 'i') {
1440 fmt_hdr = "%s,%s,%s,%s\n";
1441 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1443 fmt_hdr = "%18s %12s %12s %12s\n";
1444 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1447 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1449 /* Select sort, largest size first. */
1451 last_size = INT64_MAX;
1457 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1459 * In the case of size ties, print out mtypes
1460 * in the order they are encountered. That is,
1461 * when we encounter the most recently output
1462 * mtype, we have already printed all preceding
1463 * ties, and we must print all following ties.
1465 if (mtp == last_mtype) {
1469 size = get_malloc_stats(mtp->ks_handle, &allocs,
1471 if (size > cur_size && size < last_size + ties) {
1476 if (cur_mtype == NULL)
1479 size = get_malloc_stats(cur_mtype->ks_handle, &allocs, &inuse);
1480 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1481 howmany(size, 1024), allocs);
1486 last_mtype = cur_mtype;
1487 last_size = cur_size;
1491 #if MALLOC_DEBUG_MAXZONES > 1
1492 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1494 struct malloc_type_internal *mtip;
1495 struct malloc_type *mtp;
1499 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1503 if (mtp->ks_magic != M_MAGIC) {
1504 db_printf("Magic %lx does not match expected %x\n",
1505 mtp->ks_magic, M_MAGIC);
1509 mtip = mtp->ks_handle;
1510 subzone = mtip->mti_zone;
1512 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1513 mtip = mtp->ks_handle;
1514 if (mtip->mti_zone != subzone)
1516 db_printf("%s\n", mtp->ks_shortdesc);
1521 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1524 #ifdef MALLOC_PROFILE
1527 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1541 error = sysctl_wire_old_buffer(req, 0);
1544 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1546 "\n Size Requests Real Size\n");
1547 for (i = 0; i < KMEM_ZSIZE; i++) {
1548 size = i << KMEM_ZSHIFT;
1549 rsize = kmemzones[kmemsize[i]].kz_size;
1550 count = (long long unsigned)krequests[i];
1552 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1553 (unsigned long long)count, rsize);
1555 if ((rsize * count) > (size * count))
1556 waste += (rsize * count) - (size * count);
1557 mem += (rsize * count);
1560 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1561 (unsigned long long)mem, (unsigned long long)waste);
1562 error = sbuf_finish(&sbuf);
1567 SYSCTL_OID(_kern, OID_AUTO, mprof,
1568 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1569 sysctl_kern_mprof, "A",
1570 "Malloc Profiling");
1571 #endif /* MALLOC_PROFILE */