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];
164 {128, "malloc-128", },
165 {256, "malloc-256", },
166 {512, "malloc-512", },
167 {1024, "malloc-1024", },
168 {2048, "malloc-2048", },
169 {4096, "malloc-4096", },
170 {8192, "malloc-8192", },
171 {16384, "malloc-16384", },
172 {32768, "malloc-32768", },
173 {65536, "malloc-65536", },
178 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
179 "Size of kernel memory");
181 static u_long kmem_zmax = KMEM_ZMAX;
182 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
183 "Maximum allocation size that malloc(9) would use UMA as backend");
185 static u_long vm_kmem_size_min;
186 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
187 "Minimum size of kernel memory");
189 static u_long vm_kmem_size_max;
190 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
191 "Maximum size of kernel memory");
193 static u_int vm_kmem_size_scale;
194 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
195 "Scale factor for kernel memory size");
197 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
198 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
199 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
200 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
202 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
203 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
204 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
205 sysctl_kmem_map_free, "LU", "Free space in kmem");
207 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
208 "Malloc information");
210 static u_int vm_malloc_zone_count = nitems(kmemzones);
211 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
212 CTLFLAG_RD, &vm_malloc_zone_count, 0,
213 "Number of malloc zones");
215 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
216 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
217 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
218 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
221 * The malloc_mtx protects the kmemstatistics linked list.
223 struct mtx malloc_mtx;
225 #ifdef MALLOC_PROFILE
226 uint64_t krequests[KMEM_ZSIZE + 1];
228 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
231 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
234 * time_uptime of the last malloc(9) failure (induced or real).
236 static time_t t_malloc_fail;
238 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
239 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
240 "Kernel malloc debugging options");
244 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
245 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
247 #ifdef MALLOC_MAKE_FAILURES
248 static int malloc_failure_rate;
249 static int malloc_nowait_count;
250 static int malloc_failure_count;
251 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
252 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
253 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
254 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
258 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
263 return (sysctl_handle_long(oidp, &size, 0, req));
267 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
271 /* The sysctl is unsigned, implement as a saturation value. */
278 return (sysctl_handle_long(oidp, &size, 0, req));
282 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
284 int sizes[nitems(kmemzones)];
287 for (i = 0; i < nitems(kmemzones); i++) {
288 sizes[i] = kmemzones[i].kz_size;
291 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
295 * malloc(9) uma zone separation -- sub-page buffer overruns in one
296 * malloc type will affect only a subset of other malloc types.
298 #if MALLOC_DEBUG_MAXZONES > 1
300 tunable_set_numzones(void)
303 TUNABLE_INT_FETCH("debug.malloc.numzones",
306 /* Sanity check the number of malloc uma zones. */
309 if (numzones > MALLOC_DEBUG_MAXZONES)
310 numzones = MALLOC_DEBUG_MAXZONES;
312 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
313 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
314 &numzones, 0, "Number of malloc uma subzones");
317 * Any number that changes regularly is an okay choice for the
318 * offset. Build numbers are pretty good of you have them.
320 static u_int zone_offset = __FreeBSD_version;
321 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
322 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
323 &zone_offset, 0, "Separate malloc types by examining the "
324 "Nth character in the malloc type short description.");
327 mtp_set_subzone(struct malloc_type *mtp)
329 struct malloc_type_internal *mtip;
335 desc = mtp->ks_shortdesc;
336 if (desc == NULL || (len = strlen(desc)) == 0)
339 val = desc[zone_offset % len];
340 mtip->mti_zone = (val % numzones);
344 mtp_get_subzone(struct malloc_type *mtp)
346 struct malloc_type_internal *mtip;
350 KASSERT(mtip->mti_zone < numzones,
351 ("mti_zone %u out of range %d",
352 mtip->mti_zone, numzones));
353 return (mtip->mti_zone);
355 #elif MALLOC_DEBUG_MAXZONES == 0
356 #error "MALLOC_DEBUG_MAXZONES must be positive."
359 mtp_set_subzone(struct malloc_type *mtp)
361 struct malloc_type_internal *mtip;
368 mtp_get_subzone(struct malloc_type *mtp)
373 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
376 malloc_last_fail(void)
379 return (time_uptime - t_malloc_fail);
383 * An allocation has succeeded -- update malloc type statistics for the
384 * amount of bucket size. Occurs within a critical section so that the
385 * thread isn't preempted and doesn't migrate while updating per-PCU
389 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
392 struct malloc_type_internal *mtip;
393 struct malloc_type_stats *mtsp;
397 mtsp = zpcpu_get(mtip->mti_stats);
399 mtsp->mts_memalloced += size;
400 mtsp->mts_numallocs++;
403 mtsp->mts_size |= 1 << zindx;
406 if (__predict_false(dtrace_malloc_enabled)) {
407 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
409 (dtrace_malloc_probe)(probe_id,
410 (uintptr_t) mtp, (uintptr_t) mtip,
411 (uintptr_t) mtsp, size, zindx);
419 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
423 malloc_type_zone_allocated(mtp, size, -1);
427 * A free operation has occurred -- update malloc type statistics for the
428 * amount of the bucket size. Occurs within a critical section so that the
429 * thread isn't preempted and doesn't migrate while updating per-CPU
433 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
435 struct malloc_type_internal *mtip;
436 struct malloc_type_stats *mtsp;
440 mtsp = zpcpu_get(mtip->mti_stats);
441 mtsp->mts_memfreed += size;
442 mtsp->mts_numfrees++;
445 if (__predict_false(dtrace_malloc_enabled)) {
446 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
448 (dtrace_malloc_probe)(probe_id,
449 (uintptr_t) mtp, (uintptr_t) mtip,
450 (uintptr_t) mtsp, size, 0);
460 * Allocate a block of physically contiguous memory.
462 * If M_NOWAIT is set, this routine will not block and return NULL if
463 * the allocation fails.
466 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
467 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
472 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
473 boundary, VM_MEMATTR_DEFAULT);
475 malloc_type_allocated(type, round_page(size));
480 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
481 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
482 unsigned long alignment, vm_paddr_t boundary)
486 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
487 alignment, boundary, VM_MEMATTR_DEFAULT);
489 malloc_type_allocated(type, round_page(size));
496 * Free a block of memory allocated by contigmalloc.
498 * This routine may not block.
501 contigfree(void *addr, unsigned long size, struct malloc_type *type)
504 kmem_free((vm_offset_t)addr, size);
505 malloc_type_freed(type, round_page(size));
510 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
516 KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
518 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
520 indx = flags & (M_WAITOK | M_NOWAIT);
521 if (indx != M_NOWAIT && indx != M_WAITOK) {
522 static struct timeval lasterr;
523 static int curerr, once;
524 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
525 printf("Bad malloc flags: %x\n", indx);
532 #ifdef MALLOC_MAKE_FAILURES
533 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
534 atomic_add_int(&malloc_nowait_count, 1);
535 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
536 atomic_add_int(&malloc_failure_count, 1);
537 t_malloc_fail = time_uptime;
539 return (EJUSTRETURN);
543 if (flags & M_WAITOK) {
544 KASSERT(curthread->td_intr_nesting_level == 0,
545 ("malloc(M_WAITOK) in interrupt context"));
546 if (__predict_false(!THREAD_CAN_SLEEP())) {
548 epoch_trace_list(curthread);
551 ("malloc(M_WAITOK) with sleeping prohibited"));
554 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
555 ("malloc: called with spinlock or critical section held"));
557 #ifdef DEBUG_MEMGUARD
558 if (memguard_cmp_mtp(mtp, *sizep)) {
559 *vap = memguard_alloc(*sizep, flags);
561 return (EJUSTRETURN);
562 /* This is unfortunate but should not be fatal. */
567 *sizep = redzone_size_ntor(*sizep);
575 * Handle large allocations and frees by using kmem_malloc directly.
578 malloc_large_slab(uma_slab_t slab)
582 va = (uintptr_t)slab;
583 return ((va & 1) != 0);
587 malloc_large_size(uma_slab_t slab)
591 va = (uintptr_t)slab;
596 malloc_large(size_t *size, struct domainset *policy, int flags)
601 sz = roundup(*size, PAGE_SIZE);
602 va = kmem_malloc_domainset(policy, sz, flags);
604 /* The low bit is unused for slab pointers. */
605 vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
609 return ((caddr_t)va);
613 free_large(void *addr, size_t size)
616 kmem_free((vm_offset_t)addr, size);
623 * Allocate a block of memory.
625 * If M_NOWAIT is set, this routine will not block and return NULL if
626 * the allocation fails.
629 (malloc)(size_t size, struct malloc_type *mtp, int flags)
634 #if defined(DEBUG_REDZONE)
635 unsigned long osize = size;
638 MPASS((flags & M_EXEC) == 0);
641 if (malloc_dbg(&va, &size, mtp, flags) != 0)
645 if (size <= kmem_zmax) {
646 if (size & KMEM_ZMASK)
647 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
648 indx = kmemsize[size >> KMEM_ZSHIFT];
649 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
650 #ifdef MALLOC_PROFILE
651 krequests[size >> KMEM_ZSHIFT]++;
653 va = uma_zalloc(zone, flags);
655 size = zone->uz_size;
656 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
658 va = malloc_large(&size, DOMAINSET_RR(), flags);
659 malloc_type_allocated(mtp, va == NULL ? 0 : size);
661 if (__predict_false(va == NULL)) {
662 KASSERT((flags & M_WAITOK) == 0,
663 ("malloc(M_WAITOK) returned NULL"));
664 t_malloc_fail = time_uptime;
668 va = redzone_setup(va, osize);
670 return ((void *) va);
674 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
683 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
684 ("malloc_domain: Called with bad flag / size combination."));
685 if (size & KMEM_ZMASK)
686 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
687 indx = kmemsize[size >> KMEM_ZSHIFT];
688 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
689 #ifdef MALLOC_PROFILE
690 krequests[size >> KMEM_ZSHIFT]++;
692 va = uma_zalloc_domain(zone, NULL, domain, flags);
694 *sizep = zone->uz_size;
700 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
703 struct vm_domainset_iter di;
708 #if defined(DEBUG_REDZONE)
709 unsigned long osize = size;
711 MPASS((flags & M_EXEC) == 0);
714 if (malloc_dbg(&va, &size, mtp, flags) != 0)
717 if (size <= kmem_zmax) {
718 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
720 va = malloc_domain(&size, &indx, mtp, domain, flags);
721 } while (va == NULL &&
722 vm_domainset_iter_policy(&di, &domain) == 0);
723 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
725 /* Policy is handled by kmem. */
726 va = malloc_large(&size, ds, flags);
727 malloc_type_allocated(mtp, va == NULL ? 0 : size);
729 if (__predict_false(va == NULL)) {
730 KASSERT((flags & M_WAITOK) == 0,
731 ("malloc(M_WAITOK) returned NULL"));
732 t_malloc_fail = time_uptime;
736 va = redzone_setup(va, osize);
742 * Allocate an executable area.
745 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
748 #if defined(DEBUG_REDZONE)
749 unsigned long osize = size;
755 if (malloc_dbg(&va, &size, mtp, flags) != 0)
758 va = malloc_large(&size, DOMAINSET_RR(), flags);
759 malloc_type_allocated(mtp, va == NULL ? 0 : size);
760 if (__predict_false(va == NULL)) {
761 KASSERT((flags & M_WAITOK) == 0,
762 ("malloc(M_WAITOK) returned NULL"));
763 t_malloc_fail = time_uptime;
767 va = redzone_setup(va, osize);
769 return ((void *) va);
773 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
777 #if defined(DEBUG_REDZONE)
778 unsigned long osize = size;
784 if (malloc_dbg(&va, &size, mtp, flags) != 0)
787 /* Policy is handled by kmem. */
788 va = malloc_large(&size, ds, flags);
789 malloc_type_allocated(mtp, va == NULL ? 0 : size);
790 if (__predict_false(va == NULL)) {
791 KASSERT((flags & M_WAITOK) == 0,
792 ("malloc(M_WAITOK) returned NULL"));
793 t_malloc_fail = time_uptime;
797 va = redzone_setup(va, osize);
803 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
806 if (WOULD_OVERFLOW(nmemb, size))
807 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
809 return (malloc(size * nmemb, type, flags));
814 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
816 struct malloc_type **mtpp = addr;
819 * Cache a pointer to the malloc_type that most recently freed
820 * this memory here. This way we know who is most likely to
821 * have stepped on it later.
823 * This code assumes that size is a multiple of 8 bytes for
826 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
827 mtpp += (size - sizeof(struct malloc_type *)) /
828 sizeof(struct malloc_type *);
835 free_dbg(void **addrp, struct malloc_type *mtp)
840 KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
841 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
842 ("free: called with spinlock or critical section held"));
844 /* free(NULL, ...) does nothing */
846 return (EJUSTRETURN);
848 #ifdef DEBUG_MEMGUARD
849 if (is_memguard_addr(addr)) {
851 return (EJUSTRETURN);
857 *addrp = redzone_addr_ntor(addr);
867 * Free a block of memory allocated by malloc.
869 * This routine may not block.
872 free(void *addr, struct malloc_type *mtp)
879 if (free_dbg(&addr, mtp) != 0)
882 /* free(NULL, ...) does nothing */
886 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
888 panic("free: address %p(%p) has not been allocated.\n",
889 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
891 if (__predict_true(!malloc_large_slab(slab))) {
892 size = zone->uz_size;
894 free_save_type(addr, mtp, size);
896 uma_zfree_arg(zone, addr, slab);
898 size = malloc_large_size(slab);
899 free_large(addr, size);
901 malloc_type_freed(mtp, size);
907 * Zero then free a block of memory allocated by malloc.
909 * This routine may not block.
912 zfree(void *addr, struct malloc_type *mtp)
919 if (free_dbg(&addr, mtp) != 0)
922 /* free(NULL, ...) does nothing */
926 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
928 panic("free: address %p(%p) has not been allocated.\n",
929 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
931 if (__predict_true(!malloc_large_slab(slab))) {
932 size = zone->uz_size;
934 free_save_type(addr, mtp, size);
936 explicit_bzero(addr, size);
937 uma_zfree_arg(zone, addr, slab);
939 size = malloc_large_size(slab);
940 explicit_bzero(addr, size);
941 free_large(addr, size);
943 malloc_type_freed(mtp, size);
947 * realloc: change the size of a memory block
950 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
957 KASSERT(mtp->ks_version == M_VERSION,
958 ("realloc: bad malloc type version"));
959 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
960 ("realloc: called with spinlock or critical section held"));
962 /* realloc(NULL, ...) is equivalent to malloc(...) */
964 return (malloc(size, mtp, flags));
967 * XXX: Should report free of old memory and alloc of new memory to
971 #ifdef DEBUG_MEMGUARD
972 if (is_memguard_addr(addr))
973 return (memguard_realloc(addr, size, mtp, flags));
979 alloc = redzone_get_size(addr);
981 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
984 KASSERT(slab != NULL,
985 ("realloc: address %p out of range", (void *)addr));
987 /* Get the size of the original block */
988 if (!malloc_large_slab(slab))
989 alloc = zone->uz_size;
991 alloc = malloc_large_size(slab);
993 /* Reuse the original block if appropriate */
995 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
997 #endif /* !DEBUG_REDZONE */
999 /* Allocate a new, bigger (or smaller) block */
1000 if ((newaddr = malloc(size, mtp, flags)) == NULL)
1003 /* Copy over original contents */
1004 bcopy(addr, newaddr, min(size, alloc));
1010 * reallocf: same as realloc() but free memory on failure.
1013 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1017 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1023 * malloc_size: returns the number of bytes allocated for a request of the
1027 malloc_size(size_t size)
1031 if (size > kmem_zmax)
1033 if (size & KMEM_ZMASK)
1034 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1035 indx = kmemsize[size >> KMEM_ZSHIFT];
1036 return (kmemzones[indx].kz_size);
1040 * malloc_usable_size: returns the usable size of the allocation.
1043 malloc_usable_size(const void *addr)
1045 #ifndef DEBUG_REDZONE
1054 #ifdef DEBUG_MEMGUARD
1055 if (is_memguard_addr(__DECONST(void *, addr)))
1056 return (memguard_get_req_size(addr));
1059 #ifdef DEBUG_REDZONE
1060 size = redzone_get_size(__DECONST(void *, addr));
1062 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1064 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1065 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1067 if (!malloc_large_slab(slab))
1068 size = zone->uz_size;
1070 size = malloc_large_size(slab);
1075 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1078 * Initialize the kernel memory (kmem) arena.
1087 if (vm_kmem_size == 0)
1088 vm_kmem_size = VM_KMEM_SIZE;
1090 #ifdef VM_KMEM_SIZE_MIN
1091 if (vm_kmem_size_min == 0)
1092 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1094 #ifdef VM_KMEM_SIZE_MAX
1095 if (vm_kmem_size_max == 0)
1096 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1099 * Calculate the amount of kernel virtual address (KVA) space that is
1100 * preallocated to the kmem arena. In order to support a wide range
1101 * of machines, it is a function of the physical memory size,
1104 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1105 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1107 * Every architecture must define an integral value for
1108 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1109 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1110 * ceiling on this preallocation, are optional. Typically,
1111 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1112 * a given architecture.
1114 mem_size = vm_cnt.v_page_count;
1115 if (mem_size <= 32768) /* delphij XXX 128MB */
1116 kmem_zmax = PAGE_SIZE;
1118 if (vm_kmem_size_scale < 1)
1119 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1122 * Check if we should use defaults for the "vm_kmem_size"
1125 if (vm_kmem_size == 0) {
1126 vm_kmem_size = mem_size / vm_kmem_size_scale;
1127 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1128 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1129 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1130 vm_kmem_size = vm_kmem_size_min;
1131 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1132 vm_kmem_size = vm_kmem_size_max;
1134 if (vm_kmem_size == 0)
1135 panic("Tune VM_KMEM_SIZE_* for the platform");
1138 * The amount of KVA space that is preallocated to the
1139 * kmem arena can be set statically at compile-time or manually
1140 * through the kernel environment. However, it is still limited to
1141 * twice the physical memory size, which has been sufficient to handle
1142 * the most severe cases of external fragmentation in the kmem arena.
1144 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1145 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1147 vm_kmem_size = round_page(vm_kmem_size);
1148 #ifdef DEBUG_MEMGUARD
1149 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1155 #ifdef DEBUG_MEMGUARD
1157 * Initialize MemGuard if support compiled in. MemGuard is a
1158 * replacement allocator used for detecting tamper-after-free
1159 * scenarios as they occur. It is only used for debugging.
1161 memguard_init(kernel_arena);
1166 * Initialize the kernel memory allocator
1170 mallocinit(void *dummy)
1175 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1179 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1180 kmem_zmax = KMEM_ZMAX;
1182 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1183 int size = kmemzones[indx].kz_size;
1184 const char *name = kmemzones[indx].kz_name;
1187 for (subzone = 0; subzone < numzones; subzone++) {
1188 kmemzones[indx].kz_zone[subzone] =
1189 uma_zcreate(name, size,
1191 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1193 NULL, NULL, NULL, NULL,
1195 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1197 for (;i <= size; i+= KMEM_ZBASE)
1198 kmemsize[i >> KMEM_ZSHIFT] = indx;
1201 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1204 malloc_init(void *data)
1206 struct malloc_type_internal *mtip;
1207 struct malloc_type *mtp;
1209 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1212 if (mtp->ks_version != M_VERSION)
1213 panic("malloc_init: type %s with unsupported version %lu",
1214 mtp->ks_shortdesc, mtp->ks_version);
1216 mtip = &mtp->ks_mti;
1217 mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1218 mtp_set_subzone(mtp);
1220 mtx_lock(&malloc_mtx);
1221 mtp->ks_next = kmemstatistics;
1222 kmemstatistics = mtp;
1224 mtx_unlock(&malloc_mtx);
1228 malloc_uninit(void *data)
1230 struct malloc_type_internal *mtip;
1231 struct malloc_type_stats *mtsp;
1232 struct malloc_type *mtp, *temp;
1233 long temp_allocs, temp_bytes;
1237 KASSERT(mtp->ks_version == M_VERSION,
1238 ("malloc_uninit: bad malloc type version"));
1240 mtx_lock(&malloc_mtx);
1241 mtip = &mtp->ks_mti;
1242 if (mtp != kmemstatistics) {
1243 for (temp = kmemstatistics; temp != NULL;
1244 temp = temp->ks_next) {
1245 if (temp->ks_next == mtp) {
1246 temp->ks_next = mtp->ks_next;
1251 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1253 kmemstatistics = mtp->ks_next;
1255 mtx_unlock(&malloc_mtx);
1258 * Look for memory leaks.
1260 temp_allocs = temp_bytes = 0;
1261 for (i = 0; i <= mp_maxid; i++) {
1262 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1263 temp_allocs += mtsp->mts_numallocs;
1264 temp_allocs -= mtsp->mts_numfrees;
1265 temp_bytes += mtsp->mts_memalloced;
1266 temp_bytes -= mtsp->mts_memfreed;
1268 if (temp_allocs > 0 || temp_bytes > 0) {
1269 printf("Warning: memory type %s leaked memory on destroy "
1270 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1271 temp_allocs, temp_bytes);
1274 uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1277 struct malloc_type *
1278 malloc_desc2type(const char *desc)
1280 struct malloc_type *mtp;
1282 mtx_assert(&malloc_mtx, MA_OWNED);
1283 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1284 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1291 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1293 struct malloc_type_stream_header mtsh;
1294 struct malloc_type_internal *mtip;
1295 struct malloc_type_stats *mtsp, zeromts;
1296 struct malloc_type_header mth;
1297 struct malloc_type *mtp;
1301 error = sysctl_wire_old_buffer(req, 0);
1304 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1305 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1306 mtx_lock(&malloc_mtx);
1308 bzero(&zeromts, sizeof(zeromts));
1311 * Insert stream header.
1313 bzero(&mtsh, sizeof(mtsh));
1314 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1315 mtsh.mtsh_maxcpus = MAXCPU;
1316 mtsh.mtsh_count = kmemcount;
1317 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1320 * Insert alternating sequence of type headers and type statistics.
1322 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1323 mtip = &mtp->ks_mti;
1326 * Insert type header.
1328 bzero(&mth, sizeof(mth));
1329 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1330 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1333 * Insert type statistics for each CPU.
1335 for (i = 0; i <= mp_maxid; i++) {
1336 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1337 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1340 * Fill in the missing CPUs.
1342 for (; i < MAXCPU; i++) {
1343 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1346 mtx_unlock(&malloc_mtx);
1347 error = sbuf_finish(&sbuf);
1352 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1353 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1354 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1355 "Return malloc types");
1357 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1358 "Count of kernel malloc types");
1361 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1363 struct malloc_type *mtp, **bufmtp;
1367 mtx_lock(&malloc_mtx);
1369 mtx_assert(&malloc_mtx, MA_OWNED);
1371 mtx_unlock(&malloc_mtx);
1373 buflen = sizeof(struct malloc_type *) * count;
1374 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1376 mtx_lock(&malloc_mtx);
1378 if (count < kmemcount) {
1379 free(bufmtp, M_TEMP);
1383 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1386 mtx_unlock(&malloc_mtx);
1388 for (i = 0; i < count; i++)
1389 (func)(bufmtp[i], arg);
1391 free(bufmtp, M_TEMP);
1396 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1399 const struct malloc_type_stats *mtsp;
1400 uint64_t frees, alloced, freed;
1407 for (i = 0; i <= mp_maxid; i++) {
1408 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1410 *allocs += mtsp->mts_numallocs;
1411 frees += mtsp->mts_numfrees;
1412 alloced += mtsp->mts_memalloced;
1413 freed += mtsp->mts_memfreed;
1415 *inuse = *allocs - frees;
1416 return (alloced - freed);
1419 DB_SHOW_COMMAND(malloc, db_show_malloc)
1421 const char *fmt_hdr, *fmt_entry;
1422 struct malloc_type *mtp;
1423 uint64_t allocs, inuse;
1425 /* variables for sorting */
1426 struct malloc_type *last_mtype, *cur_mtype;
1427 int64_t cur_size, last_size;
1430 if (modif[0] == 'i') {
1431 fmt_hdr = "%s,%s,%s,%s\n";
1432 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1434 fmt_hdr = "%18s %12s %12s %12s\n";
1435 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1438 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1440 /* Select sort, largest size first. */
1442 last_size = INT64_MAX;
1448 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1450 * In the case of size ties, print out mtypes
1451 * in the order they are encountered. That is,
1452 * when we encounter the most recently output
1453 * mtype, we have already printed all preceding
1454 * ties, and we must print all following ties.
1456 if (mtp == last_mtype) {
1460 size = get_malloc_stats(&mtp->ks_mti, &allocs,
1462 if (size > cur_size && size < last_size + ties) {
1467 if (cur_mtype == NULL)
1470 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1471 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1472 howmany(size, 1024), allocs);
1477 last_mtype = cur_mtype;
1478 last_size = cur_size;
1482 #if MALLOC_DEBUG_MAXZONES > 1
1483 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1485 struct malloc_type_internal *mtip;
1486 struct malloc_type *mtp;
1490 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1494 if (mtp->ks_version != M_VERSION) {
1495 db_printf("Version %lx does not match expected %x\n",
1496 mtp->ks_version, M_VERSION);
1500 mtip = &mtp->ks_mti;
1501 subzone = mtip->mti_zone;
1503 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1504 mtip = &mtp->ks_mti;
1505 if (mtip->mti_zone != subzone)
1507 db_printf("%s\n", mtp->ks_shortdesc);
1512 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1515 #ifdef MALLOC_PROFILE
1518 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1532 error = sysctl_wire_old_buffer(req, 0);
1535 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1537 "\n Size Requests Real Size\n");
1538 for (i = 0; i < KMEM_ZSIZE; i++) {
1539 size = i << KMEM_ZSHIFT;
1540 rsize = kmemzones[kmemsize[i]].kz_size;
1541 count = (long long unsigned)krequests[i];
1543 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1544 (unsigned long long)count, rsize);
1546 if ((rsize * count) > (size * count))
1547 waste += (rsize * count) - (size * count);
1548 mem += (rsize * count);
1551 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1552 (unsigned long long)mem, (unsigned long long)waste);
1553 error = sbuf_finish(&sbuf);
1558 SYSCTL_OID(_kern, OID_AUTO, mprof,
1559 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1560 sysctl_kern_mprof, "A",
1561 "Malloc Profiling");
1562 #endif /* MALLOC_PROFILE */