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 {384, "malloc-384", },
167 {512, "malloc-512", },
168 {1024, "malloc-1024", },
169 {2048, "malloc-2048", },
170 {4096, "malloc-4096", },
171 {8192, "malloc-8192", },
172 {16384, "malloc-16384", },
173 {32768, "malloc-32768", },
174 {65536, "malloc-65536", },
179 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
180 "Size of kernel memory");
182 static u_long kmem_zmax = KMEM_ZMAX;
183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
184 "Maximum allocation size that malloc(9) would use UMA as backend");
186 static u_long vm_kmem_size_min;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
188 "Minimum size of kernel memory");
190 static u_long vm_kmem_size_max;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
192 "Maximum size of kernel memory");
194 static u_int vm_kmem_size_scale;
195 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
196 "Scale factor for kernel memory size");
198 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
199 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
200 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
201 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
203 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
205 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
206 sysctl_kmem_map_free, "LU", "Free space in kmem");
208 static SYSCTL_NODE(_vm, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
209 "Malloc information");
211 static u_int vm_malloc_zone_count = nitems(kmemzones);
212 SYSCTL_UINT(_vm_malloc, OID_AUTO, zone_count,
213 CTLFLAG_RD, &vm_malloc_zone_count, 0,
214 "Number of malloc zones");
216 static int sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS);
217 SYSCTL_PROC(_vm_malloc, OID_AUTO, zone_sizes,
218 CTLFLAG_RD | CTLTYPE_OPAQUE | CTLFLAG_MPSAFE, NULL, 0,
219 sysctl_vm_malloc_zone_sizes, "S", "Zone sizes used by malloc");
222 * The malloc_mtx protects the kmemstatistics linked list.
224 struct mtx malloc_mtx;
226 #ifdef MALLOC_PROFILE
227 uint64_t krequests[KMEM_ZSIZE + 1];
229 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
232 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
234 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
235 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
236 "Kernel malloc debugging options");
240 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
241 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
243 #ifdef MALLOC_MAKE_FAILURES
244 static int malloc_failure_rate;
245 static int malloc_nowait_count;
246 static int malloc_failure_count;
247 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
248 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
249 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
250 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
254 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
259 return (sysctl_handle_long(oidp, &size, 0, req));
263 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
267 /* The sysctl is unsigned, implement as a saturation value. */
274 return (sysctl_handle_long(oidp, &size, 0, req));
278 sysctl_vm_malloc_zone_sizes(SYSCTL_HANDLER_ARGS)
280 int sizes[nitems(kmemzones)];
283 for (i = 0; i < nitems(kmemzones); i++) {
284 sizes[i] = kmemzones[i].kz_size;
287 return (SYSCTL_OUT(req, &sizes, sizeof(sizes)));
291 * malloc(9) uma zone separation -- sub-page buffer overruns in one
292 * malloc type will affect only a subset of other malloc types.
294 #if MALLOC_DEBUG_MAXZONES > 1
296 tunable_set_numzones(void)
299 TUNABLE_INT_FETCH("debug.malloc.numzones",
302 /* Sanity check the number of malloc uma zones. */
305 if (numzones > MALLOC_DEBUG_MAXZONES)
306 numzones = MALLOC_DEBUG_MAXZONES;
308 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
309 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
310 &numzones, 0, "Number of malloc uma subzones");
313 * Any number that changes regularly is an okay choice for the
314 * offset. Build numbers are pretty good of you have them.
316 static u_int zone_offset = __FreeBSD_version;
317 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
318 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
319 &zone_offset, 0, "Separate malloc types by examining the "
320 "Nth character in the malloc type short description.");
323 mtp_set_subzone(struct malloc_type *mtp)
325 struct malloc_type_internal *mtip;
331 desc = mtp->ks_shortdesc;
332 if (desc == NULL || (len = strlen(desc)) == 0)
335 val = desc[zone_offset % len];
336 mtip->mti_zone = (val % numzones);
340 mtp_get_subzone(struct malloc_type *mtp)
342 struct malloc_type_internal *mtip;
346 KASSERT(mtip->mti_zone < numzones,
347 ("mti_zone %u out of range %d",
348 mtip->mti_zone, numzones));
349 return (mtip->mti_zone);
351 #elif MALLOC_DEBUG_MAXZONES == 0
352 #error "MALLOC_DEBUG_MAXZONES must be positive."
355 mtp_set_subzone(struct malloc_type *mtp)
357 struct malloc_type_internal *mtip;
364 mtp_get_subzone(struct malloc_type *mtp)
369 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
372 * An allocation has succeeded -- update malloc type statistics for the
373 * amount of bucket size. Occurs within a critical section so that the
374 * thread isn't preempted and doesn't migrate while updating per-PCU
378 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
381 struct malloc_type_internal *mtip;
382 struct malloc_type_stats *mtsp;
386 mtsp = zpcpu_get(mtip->mti_stats);
388 mtsp->mts_memalloced += size;
389 mtsp->mts_numallocs++;
392 mtsp->mts_size |= 1 << zindx;
395 if (__predict_false(dtrace_malloc_enabled)) {
396 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
398 (dtrace_malloc_probe)(probe_id,
399 (uintptr_t) mtp, (uintptr_t) mtip,
400 (uintptr_t) mtsp, size, zindx);
408 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
412 malloc_type_zone_allocated(mtp, size, -1);
416 * A free operation has occurred -- update malloc type statistics for the
417 * amount of the bucket size. Occurs within a critical section so that the
418 * thread isn't preempted and doesn't migrate while updating per-CPU
422 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
424 struct malloc_type_internal *mtip;
425 struct malloc_type_stats *mtsp;
429 mtsp = zpcpu_get(mtip->mti_stats);
430 mtsp->mts_memfreed += size;
431 mtsp->mts_numfrees++;
434 if (__predict_false(dtrace_malloc_enabled)) {
435 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
437 (dtrace_malloc_probe)(probe_id,
438 (uintptr_t) mtp, (uintptr_t) mtip,
439 (uintptr_t) mtsp, size, 0);
449 * Allocate a block of physically contiguous memory.
451 * If M_NOWAIT is set, this routine will not block and return NULL if
452 * the allocation fails.
455 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
456 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
461 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
462 boundary, VM_MEMATTR_DEFAULT);
464 malloc_type_allocated(type, round_page(size));
469 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
470 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
471 unsigned long alignment, vm_paddr_t boundary)
475 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
476 alignment, boundary, VM_MEMATTR_DEFAULT);
478 malloc_type_allocated(type, round_page(size));
485 * Free a block of memory allocated by contigmalloc.
487 * This routine may not block.
490 contigfree(void *addr, unsigned long size, struct malloc_type *type)
493 kmem_free((vm_offset_t)addr, size);
494 malloc_type_freed(type, round_page(size));
499 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
505 KASSERT(mtp->ks_version == M_VERSION, ("malloc: bad malloc type version"));
507 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
509 indx = flags & (M_WAITOK | M_NOWAIT);
510 if (indx != M_NOWAIT && indx != M_WAITOK) {
511 static struct timeval lasterr;
512 static int curerr, once;
513 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
514 printf("Bad malloc flags: %x\n", indx);
521 #ifdef MALLOC_MAKE_FAILURES
522 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
523 atomic_add_int(&malloc_nowait_count, 1);
524 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
525 atomic_add_int(&malloc_failure_count, 1);
527 return (EJUSTRETURN);
531 if (flags & M_WAITOK) {
532 KASSERT(curthread->td_intr_nesting_level == 0,
533 ("malloc(M_WAITOK) in interrupt context"));
534 if (__predict_false(!THREAD_CAN_SLEEP())) {
536 epoch_trace_list(curthread);
539 ("malloc(M_WAITOK) with sleeping prohibited"));
542 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
543 ("malloc: called with spinlock or critical section held"));
545 #ifdef DEBUG_MEMGUARD
546 if (memguard_cmp_mtp(mtp, *sizep)) {
547 *vap = memguard_alloc(*sizep, flags);
549 return (EJUSTRETURN);
550 /* This is unfortunate but should not be fatal. */
555 *sizep = redzone_size_ntor(*sizep);
563 * Handle large allocations and frees by using kmem_malloc directly.
566 malloc_large_slab(uma_slab_t slab)
570 va = (uintptr_t)slab;
571 return ((va & 1) != 0);
575 malloc_large_size(uma_slab_t slab)
579 va = (uintptr_t)slab;
584 malloc_large(size_t *size, struct domainset *policy, int flags)
589 sz = roundup(*size, PAGE_SIZE);
590 va = kmem_malloc_domainset(policy, sz, flags);
592 /* The low bit is unused for slab pointers. */
593 vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
597 return ((caddr_t)va);
601 free_large(void *addr, size_t size)
604 kmem_free((vm_offset_t)addr, size);
611 * Allocate a block of memory.
613 * If M_NOWAIT is set, this routine will not block and return NULL if
614 * the allocation fails.
617 (malloc)(size_t size, struct malloc_type *mtp, int flags)
622 #if defined(DEBUG_REDZONE)
623 unsigned long osize = size;
626 MPASS((flags & M_EXEC) == 0);
629 if (malloc_dbg(&va, &size, mtp, flags) != 0)
633 if (size <= kmem_zmax) {
634 if (size & KMEM_ZMASK)
635 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
636 indx = kmemsize[size >> KMEM_ZSHIFT];
637 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
638 #ifdef MALLOC_PROFILE
639 krequests[size >> KMEM_ZSHIFT]++;
641 va = uma_zalloc(zone, flags);
643 size = zone->uz_size;
644 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
646 va = malloc_large(&size, DOMAINSET_RR(), flags);
647 malloc_type_allocated(mtp, va == NULL ? 0 : size);
649 if (__predict_false(va == NULL)) {
650 KASSERT((flags & M_WAITOK) == 0,
651 ("malloc(M_WAITOK) returned NULL"));
655 va = redzone_setup(va, osize);
657 return ((void *) va);
661 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
670 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
671 ("malloc_domain: Called with bad flag / size combination."));
672 if (size & KMEM_ZMASK)
673 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
674 indx = kmemsize[size >> KMEM_ZSHIFT];
675 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
676 #ifdef MALLOC_PROFILE
677 krequests[size >> KMEM_ZSHIFT]++;
679 va = uma_zalloc_domain(zone, NULL, domain, flags);
681 *sizep = zone->uz_size;
687 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
690 struct vm_domainset_iter di;
695 #if defined(DEBUG_REDZONE)
696 unsigned long osize = size;
698 MPASS((flags & M_EXEC) == 0);
701 if (malloc_dbg(&va, &size, mtp, flags) != 0)
704 if (size <= kmem_zmax) {
705 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
707 va = malloc_domain(&size, &indx, mtp, domain, flags);
708 } while (va == NULL &&
709 vm_domainset_iter_policy(&di, &domain) == 0);
710 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
712 /* Policy is handled by kmem. */
713 va = malloc_large(&size, ds, flags);
714 malloc_type_allocated(mtp, va == NULL ? 0 : size);
716 if (__predict_false(va == NULL)) {
717 KASSERT((flags & M_WAITOK) == 0,
718 ("malloc(M_WAITOK) returned NULL"));
722 va = redzone_setup(va, osize);
728 * Allocate an executable area.
731 malloc_exec(size_t size, struct malloc_type *mtp, int flags)
734 #if defined(DEBUG_REDZONE)
735 unsigned long osize = size;
741 if (malloc_dbg(&va, &size, mtp, flags) != 0)
744 va = malloc_large(&size, DOMAINSET_RR(), flags);
745 malloc_type_allocated(mtp, va == NULL ? 0 : size);
746 if (__predict_false(va == NULL)) {
747 KASSERT((flags & M_WAITOK) == 0,
748 ("malloc(M_WAITOK) returned NULL"));
752 va = redzone_setup(va, osize);
754 return ((void *) va);
758 malloc_domainset_exec(size_t size, struct malloc_type *mtp, struct domainset *ds,
762 #if defined(DEBUG_REDZONE)
763 unsigned long osize = size;
769 if (malloc_dbg(&va, &size, mtp, flags) != 0)
772 /* Policy is handled by kmem. */
773 va = malloc_large(&size, ds, flags);
774 malloc_type_allocated(mtp, va == NULL ? 0 : size);
775 if (__predict_false(va == NULL)) {
776 KASSERT((flags & M_WAITOK) == 0,
777 ("malloc(M_WAITOK) returned NULL"));
781 va = redzone_setup(va, osize);
787 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
790 if (WOULD_OVERFLOW(nmemb, size))
791 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
793 return (malloc(size * nmemb, type, flags));
798 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
800 struct malloc_type **mtpp = addr;
803 * Cache a pointer to the malloc_type that most recently freed
804 * this memory here. This way we know who is most likely to
805 * have stepped on it later.
807 * This code assumes that size is a multiple of 8 bytes for
810 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
811 mtpp += (size - sizeof(struct malloc_type *)) /
812 sizeof(struct malloc_type *);
819 free_dbg(void **addrp, struct malloc_type *mtp)
824 KASSERT(mtp->ks_version == M_VERSION, ("free: bad malloc type version"));
825 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
826 ("free: called with spinlock or critical section held"));
828 /* free(NULL, ...) does nothing */
830 return (EJUSTRETURN);
832 #ifdef DEBUG_MEMGUARD
833 if (is_memguard_addr(addr)) {
835 return (EJUSTRETURN);
841 *addrp = redzone_addr_ntor(addr);
851 * Free a block of memory allocated by malloc.
853 * This routine may not block.
856 free(void *addr, struct malloc_type *mtp)
863 if (free_dbg(&addr, mtp) != 0)
866 /* free(NULL, ...) does nothing */
870 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
872 panic("free: address %p(%p) has not been allocated.\n",
873 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
875 if (__predict_true(!malloc_large_slab(slab))) {
876 size = zone->uz_size;
878 free_save_type(addr, mtp, size);
880 uma_zfree_arg(zone, addr, slab);
882 size = malloc_large_size(slab);
883 free_large(addr, size);
885 malloc_type_freed(mtp, size);
891 * Zero then free a block of memory allocated by malloc.
893 * This routine may not block.
896 zfree(void *addr, struct malloc_type *mtp)
903 if (free_dbg(&addr, mtp) != 0)
906 /* free(NULL, ...) does nothing */
910 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
912 panic("free: address %p(%p) has not been allocated.\n",
913 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
915 if (__predict_true(!malloc_large_slab(slab))) {
916 size = zone->uz_size;
918 free_save_type(addr, mtp, size);
920 explicit_bzero(addr, size);
921 uma_zfree_arg(zone, addr, slab);
923 size = malloc_large_size(slab);
924 explicit_bzero(addr, size);
925 free_large(addr, size);
927 malloc_type_freed(mtp, size);
931 * realloc: change the size of a memory block
934 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
941 KASSERT(mtp->ks_version == M_VERSION,
942 ("realloc: bad malloc type version"));
943 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
944 ("realloc: called with spinlock or critical section held"));
946 /* realloc(NULL, ...) is equivalent to malloc(...) */
948 return (malloc(size, mtp, flags));
951 * XXX: Should report free of old memory and alloc of new memory to
955 #ifdef DEBUG_MEMGUARD
956 if (is_memguard_addr(addr))
957 return (memguard_realloc(addr, size, mtp, flags));
963 alloc = redzone_get_size(addr);
965 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
968 KASSERT(slab != NULL,
969 ("realloc: address %p out of range", (void *)addr));
971 /* Get the size of the original block */
972 if (!malloc_large_slab(slab))
973 alloc = zone->uz_size;
975 alloc = malloc_large_size(slab);
977 /* Reuse the original block if appropriate */
979 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
981 #endif /* !DEBUG_REDZONE */
983 /* Allocate a new, bigger (or smaller) block */
984 if ((newaddr = malloc(size, mtp, flags)) == NULL)
987 /* Copy over original contents */
988 bcopy(addr, newaddr, min(size, alloc));
994 * reallocf: same as realloc() but free memory on failure.
997 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
1001 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
1007 * malloc_size: returns the number of bytes allocated for a request of the
1011 malloc_size(size_t size)
1015 if (size > kmem_zmax)
1017 if (size & KMEM_ZMASK)
1018 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
1019 indx = kmemsize[size >> KMEM_ZSHIFT];
1020 return (kmemzones[indx].kz_size);
1024 * malloc_usable_size: returns the usable size of the allocation.
1027 malloc_usable_size(const void *addr)
1029 #ifndef DEBUG_REDZONE
1038 #ifdef DEBUG_MEMGUARD
1039 if (is_memguard_addr(__DECONST(void *, addr)))
1040 return (memguard_get_req_size(addr));
1043 #ifdef DEBUG_REDZONE
1044 size = redzone_get_size(__DECONST(void *, addr));
1046 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
1048 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
1049 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
1051 if (!malloc_large_slab(slab))
1052 size = zone->uz_size;
1054 size = malloc_large_size(slab);
1059 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
1062 * Initialize the kernel memory (kmem) arena.
1071 if (vm_kmem_size == 0)
1072 vm_kmem_size = VM_KMEM_SIZE;
1074 #ifdef VM_KMEM_SIZE_MIN
1075 if (vm_kmem_size_min == 0)
1076 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
1078 #ifdef VM_KMEM_SIZE_MAX
1079 if (vm_kmem_size_max == 0)
1080 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
1083 * Calculate the amount of kernel virtual address (KVA) space that is
1084 * preallocated to the kmem arena. In order to support a wide range
1085 * of machines, it is a function of the physical memory size,
1088 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
1089 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
1091 * Every architecture must define an integral value for
1092 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
1093 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
1094 * ceiling on this preallocation, are optional. Typically,
1095 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
1096 * a given architecture.
1098 mem_size = vm_cnt.v_page_count;
1099 if (mem_size <= 32768) /* delphij XXX 128MB */
1100 kmem_zmax = PAGE_SIZE;
1102 if (vm_kmem_size_scale < 1)
1103 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
1106 * Check if we should use defaults for the "vm_kmem_size"
1109 if (vm_kmem_size == 0) {
1110 vm_kmem_size = mem_size / vm_kmem_size_scale;
1111 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
1112 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
1113 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
1114 vm_kmem_size = vm_kmem_size_min;
1115 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1116 vm_kmem_size = vm_kmem_size_max;
1118 if (vm_kmem_size == 0)
1119 panic("Tune VM_KMEM_SIZE_* for the platform");
1122 * The amount of KVA space that is preallocated to the
1123 * kmem arena can be set statically at compile-time or manually
1124 * through the kernel environment. However, it is still limited to
1125 * twice the physical memory size, which has been sufficient to handle
1126 * the most severe cases of external fragmentation in the kmem arena.
1128 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1129 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1131 vm_kmem_size = round_page(vm_kmem_size);
1132 #ifdef DEBUG_MEMGUARD
1133 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1139 #ifdef DEBUG_MEMGUARD
1141 * Initialize MemGuard if support compiled in. MemGuard is a
1142 * replacement allocator used for detecting tamper-after-free
1143 * scenarios as they occur. It is only used for debugging.
1145 memguard_init(kernel_arena);
1150 * Initialize the kernel memory allocator
1154 mallocinit(void *dummy)
1159 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1163 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1164 kmem_zmax = KMEM_ZMAX;
1166 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1167 int size = kmemzones[indx].kz_size;
1168 const char *name = kmemzones[indx].kz_name;
1171 for (subzone = 0; subzone < numzones; subzone++) {
1172 kmemzones[indx].kz_zone[subzone] =
1173 uma_zcreate(name, size,
1175 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1177 NULL, NULL, NULL, NULL,
1179 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1181 for (;i <= size; i+= KMEM_ZBASE)
1182 kmemsize[i >> KMEM_ZSHIFT] = indx;
1185 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1188 malloc_init(void *data)
1190 struct malloc_type_internal *mtip;
1191 struct malloc_type *mtp;
1193 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1196 if (mtp->ks_version != M_VERSION)
1197 panic("malloc_init: type %s with unsupported version %lu",
1198 mtp->ks_shortdesc, mtp->ks_version);
1200 mtip = &mtp->ks_mti;
1201 mtip->mti_stats = uma_zalloc_pcpu(pcpu_zone_64, M_WAITOK | M_ZERO);
1202 mtp_set_subzone(mtp);
1204 mtx_lock(&malloc_mtx);
1205 mtp->ks_next = kmemstatistics;
1206 kmemstatistics = mtp;
1208 mtx_unlock(&malloc_mtx);
1212 malloc_uninit(void *data)
1214 struct malloc_type_internal *mtip;
1215 struct malloc_type_stats *mtsp;
1216 struct malloc_type *mtp, *temp;
1217 long temp_allocs, temp_bytes;
1221 KASSERT(mtp->ks_version == M_VERSION,
1222 ("malloc_uninit: bad malloc type version"));
1224 mtx_lock(&malloc_mtx);
1225 mtip = &mtp->ks_mti;
1226 if (mtp != kmemstatistics) {
1227 for (temp = kmemstatistics; temp != NULL;
1228 temp = temp->ks_next) {
1229 if (temp->ks_next == mtp) {
1230 temp->ks_next = mtp->ks_next;
1235 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1237 kmemstatistics = mtp->ks_next;
1239 mtx_unlock(&malloc_mtx);
1242 * Look for memory leaks.
1244 temp_allocs = temp_bytes = 0;
1245 for (i = 0; i <= mp_maxid; i++) {
1246 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1247 temp_allocs += mtsp->mts_numallocs;
1248 temp_allocs -= mtsp->mts_numfrees;
1249 temp_bytes += mtsp->mts_memalloced;
1250 temp_bytes -= mtsp->mts_memfreed;
1252 if (temp_allocs > 0 || temp_bytes > 0) {
1253 printf("Warning: memory type %s leaked memory on destroy "
1254 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1255 temp_allocs, temp_bytes);
1258 uma_zfree_pcpu(pcpu_zone_64, mtip->mti_stats);
1261 struct malloc_type *
1262 malloc_desc2type(const char *desc)
1264 struct malloc_type *mtp;
1266 mtx_assert(&malloc_mtx, MA_OWNED);
1267 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1268 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1275 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1277 struct malloc_type_stream_header mtsh;
1278 struct malloc_type_internal *mtip;
1279 struct malloc_type_stats *mtsp, zeromts;
1280 struct malloc_type_header mth;
1281 struct malloc_type *mtp;
1285 error = sysctl_wire_old_buffer(req, 0);
1288 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1289 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1290 mtx_lock(&malloc_mtx);
1292 bzero(&zeromts, sizeof(zeromts));
1295 * Insert stream header.
1297 bzero(&mtsh, sizeof(mtsh));
1298 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1299 mtsh.mtsh_maxcpus = MAXCPU;
1300 mtsh.mtsh_count = kmemcount;
1301 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1304 * Insert alternating sequence of type headers and type statistics.
1306 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1307 mtip = &mtp->ks_mti;
1310 * Insert type header.
1312 bzero(&mth, sizeof(mth));
1313 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1314 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1317 * Insert type statistics for each CPU.
1319 for (i = 0; i <= mp_maxid; i++) {
1320 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1321 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1324 * Fill in the missing CPUs.
1326 for (; i < MAXCPU; i++) {
1327 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1330 mtx_unlock(&malloc_mtx);
1331 error = sbuf_finish(&sbuf);
1336 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1337 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1338 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1339 "Return malloc types");
1341 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1342 "Count of kernel malloc types");
1345 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1347 struct malloc_type *mtp, **bufmtp;
1351 mtx_lock(&malloc_mtx);
1353 mtx_assert(&malloc_mtx, MA_OWNED);
1355 mtx_unlock(&malloc_mtx);
1357 buflen = sizeof(struct malloc_type *) * count;
1358 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1360 mtx_lock(&malloc_mtx);
1362 if (count < kmemcount) {
1363 free(bufmtp, M_TEMP);
1367 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1370 mtx_unlock(&malloc_mtx);
1372 for (i = 0; i < count; i++)
1373 (func)(bufmtp[i], arg);
1375 free(bufmtp, M_TEMP);
1380 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1383 const struct malloc_type_stats *mtsp;
1384 uint64_t frees, alloced, freed;
1391 for (i = 0; i <= mp_maxid; i++) {
1392 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1394 *allocs += mtsp->mts_numallocs;
1395 frees += mtsp->mts_numfrees;
1396 alloced += mtsp->mts_memalloced;
1397 freed += mtsp->mts_memfreed;
1399 *inuse = *allocs - frees;
1400 return (alloced - freed);
1403 DB_SHOW_COMMAND(malloc, db_show_malloc)
1405 const char *fmt_hdr, *fmt_entry;
1406 struct malloc_type *mtp;
1407 uint64_t allocs, inuse;
1409 /* variables for sorting */
1410 struct malloc_type *last_mtype, *cur_mtype;
1411 int64_t cur_size, last_size;
1414 if (modif[0] == 'i') {
1415 fmt_hdr = "%s,%s,%s,%s\n";
1416 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1418 fmt_hdr = "%18s %12s %12s %12s\n";
1419 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1422 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1424 /* Select sort, largest size first. */
1426 last_size = INT64_MAX;
1432 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1434 * In the case of size ties, print out mtypes
1435 * in the order they are encountered. That is,
1436 * when we encounter the most recently output
1437 * mtype, we have already printed all preceding
1438 * ties, and we must print all following ties.
1440 if (mtp == last_mtype) {
1444 size = get_malloc_stats(&mtp->ks_mti, &allocs,
1446 if (size > cur_size && size < last_size + ties) {
1451 if (cur_mtype == NULL)
1454 size = get_malloc_stats(&cur_mtype->ks_mti, &allocs, &inuse);
1455 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1456 howmany(size, 1024), allocs);
1461 last_mtype = cur_mtype;
1462 last_size = cur_size;
1466 #if MALLOC_DEBUG_MAXZONES > 1
1467 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1469 struct malloc_type_internal *mtip;
1470 struct malloc_type *mtp;
1474 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1478 if (mtp->ks_version != M_VERSION) {
1479 db_printf("Version %lx does not match expected %x\n",
1480 mtp->ks_version, M_VERSION);
1484 mtip = &mtp->ks_mti;
1485 subzone = mtip->mti_zone;
1487 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1488 mtip = &mtp->ks_mti;
1489 if (mtip->mti_zone != subzone)
1491 db_printf("%s\n", mtp->ks_shortdesc);
1496 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1499 #ifdef MALLOC_PROFILE
1502 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1516 error = sysctl_wire_old_buffer(req, 0);
1519 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1521 "\n Size Requests Real Size\n");
1522 for (i = 0; i < KMEM_ZSIZE; i++) {
1523 size = i << KMEM_ZSHIFT;
1524 rsize = kmemzones[kmemsize[i]].kz_size;
1525 count = (long long unsigned)krequests[i];
1527 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1528 (unsigned long long)count, rsize);
1530 if ((rsize * count) > (size * count))
1531 waste += (rsize * count) - (size * count);
1532 mem += (rsize * count);
1535 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1536 (unsigned long long)mem, (unsigned long long)waste);
1537 error = sbuf_finish(&sbuf);
1542 SYSCTL_OID(_kern, OID_AUTO, mprof,
1543 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1544 sysctl_kern_mprof, "A",
1545 "Malloc Profiling");
1546 #endif /* MALLOC_PROFILE */