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>
65 #include <sys/sysctl.h>
71 #include <vm/vm_domainset.h>
72 #include <vm/vm_pageout.h>
73 #include <vm/vm_param.h>
74 #include <vm/vm_kern.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_map.h>
77 #include <vm/vm_page.h>
79 #include <vm/uma_int.h>
80 #include <vm/uma_dbg.h>
83 #include <vm/memguard.h>
86 #include <vm/redzone.h>
89 #if defined(INVARIANTS) && defined(__i386__)
90 #include <machine/cpu.h>
96 #include <sys/dtrace_bsd.h>
98 bool __read_frequently dtrace_malloc_enabled;
99 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
102 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
103 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
104 #define MALLOC_DEBUG 1
108 * When realloc() is called, if the new size is sufficiently smaller than
109 * the old size, realloc() will allocate a new, smaller block to avoid
110 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
111 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
113 #ifndef REALLOC_FRACTION
114 #define REALLOC_FRACTION 1 /* new block if <= half the size */
118 * Centrally define some common malloc types.
120 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
121 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
122 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
124 static struct malloc_type *kmemstatistics;
125 static int kmemcount;
127 #define KMEM_ZSHIFT 4
128 #define KMEM_ZBASE 16
129 #define KMEM_ZMASK (KMEM_ZBASE - 1)
131 #define KMEM_ZMAX 65536
132 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
133 static uint8_t kmemsize[KMEM_ZSIZE + 1];
135 #ifndef MALLOC_DEBUG_MAXZONES
136 #define MALLOC_DEBUG_MAXZONES 1
138 static int numzones = MALLOC_DEBUG_MAXZONES;
141 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
144 * XXX: The comment here used to read "These won't be powers of two for
145 * long." It's possible that a significant amount of wasted memory could be
146 * recovered by tuning the sizes of these buckets.
151 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
170 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
171 * types are described by a data structure passed by the declaring code, but
172 * the malloc(9) implementation has its own data structure describing the
173 * type and statistics. This permits the malloc(9)-internal data structures
174 * to be modified without breaking binary-compiled kernel modules that
175 * declare malloc types.
177 static uma_zone_t mt_zone;
178 static uma_zone_t mt_stats_zone;
181 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
182 "Size of kernel memory");
184 static u_long kmem_zmax = KMEM_ZMAX;
185 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
186 "Maximum allocation size that malloc(9) would use UMA as backend");
188 static u_long vm_kmem_size_min;
189 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
190 "Minimum size of kernel memory");
192 static u_long vm_kmem_size_max;
193 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
194 "Maximum size of kernel memory");
196 static u_int vm_kmem_size_scale;
197 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
198 "Scale factor for kernel memory size");
200 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
201 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
202 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
203 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
205 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
206 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
207 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
208 sysctl_kmem_map_free, "LU", "Free space in kmem");
211 * The malloc_mtx protects the kmemstatistics linked list.
213 struct mtx malloc_mtx;
215 #ifdef MALLOC_PROFILE
216 uint64_t krequests[KMEM_ZSIZE + 1];
218 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
221 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
224 * time_uptime of the last malloc(9) failure (induced or real).
226 static time_t t_malloc_fail;
228 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
229 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
230 "Kernel malloc debugging options");
234 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
235 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
237 #ifdef MALLOC_MAKE_FAILURES
238 static int malloc_failure_rate;
239 static int malloc_nowait_count;
240 static int malloc_failure_count;
241 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
242 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
243 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
244 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
248 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
253 return (sysctl_handle_long(oidp, &size, 0, req));
257 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
261 /* The sysctl is unsigned, implement as a saturation value. */
268 return (sysctl_handle_long(oidp, &size, 0, req));
272 * malloc(9) uma zone separation -- sub-page buffer overruns in one
273 * malloc type will affect only a subset of other malloc types.
275 #if MALLOC_DEBUG_MAXZONES > 1
277 tunable_set_numzones(void)
280 TUNABLE_INT_FETCH("debug.malloc.numzones",
283 /* Sanity check the number of malloc uma zones. */
286 if (numzones > MALLOC_DEBUG_MAXZONES)
287 numzones = MALLOC_DEBUG_MAXZONES;
289 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
290 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
291 &numzones, 0, "Number of malloc uma subzones");
294 * Any number that changes regularly is an okay choice for the
295 * offset. Build numbers are pretty good of you have them.
297 static u_int zone_offset = __FreeBSD_version;
298 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
299 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
300 &zone_offset, 0, "Separate malloc types by examining the "
301 "Nth character in the malloc type short description.");
304 mtp_set_subzone(struct malloc_type *mtp)
306 struct malloc_type_internal *mtip;
311 mtip = mtp->ks_handle;
312 desc = mtp->ks_shortdesc;
313 if (desc == NULL || (len = strlen(desc)) == 0)
316 val = desc[zone_offset % len];
317 mtip->mti_zone = (val % numzones);
321 mtp_get_subzone(struct malloc_type *mtp)
323 struct malloc_type_internal *mtip;
325 mtip = mtp->ks_handle;
327 KASSERT(mtip->mti_zone < numzones,
328 ("mti_zone %u out of range %d",
329 mtip->mti_zone, numzones));
330 return (mtip->mti_zone);
332 #elif MALLOC_DEBUG_MAXZONES == 0
333 #error "MALLOC_DEBUG_MAXZONES must be positive."
336 mtp_set_subzone(struct malloc_type *mtp)
338 struct malloc_type_internal *mtip;
340 mtip = mtp->ks_handle;
345 mtp_get_subzone(struct malloc_type *mtp)
350 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
353 malloc_last_fail(void)
356 return (time_uptime - t_malloc_fail);
360 * An allocation has succeeded -- update malloc type statistics for the
361 * amount of bucket size. Occurs within a critical section so that the
362 * thread isn't preempted and doesn't migrate while updating per-PCU
366 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
369 struct malloc_type_internal *mtip;
370 struct malloc_type_stats *mtsp;
373 mtip = mtp->ks_handle;
374 mtsp = zpcpu_get(mtip->mti_stats);
376 mtsp->mts_memalloced += size;
377 mtsp->mts_numallocs++;
380 mtsp->mts_size |= 1 << zindx;
383 if (__predict_false(dtrace_malloc_enabled)) {
384 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
386 (dtrace_malloc_probe)(probe_id,
387 (uintptr_t) mtp, (uintptr_t) mtip,
388 (uintptr_t) mtsp, size, zindx);
396 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
400 malloc_type_zone_allocated(mtp, size, -1);
404 * A free operation has occurred -- update malloc type statistics for the
405 * amount of the bucket size. Occurs within a critical section so that the
406 * thread isn't preempted and doesn't migrate while updating per-CPU
410 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
412 struct malloc_type_internal *mtip;
413 struct malloc_type_stats *mtsp;
416 mtip = mtp->ks_handle;
417 mtsp = zpcpu_get(mtip->mti_stats);
418 mtsp->mts_memfreed += size;
419 mtsp->mts_numfrees++;
422 if (__predict_false(dtrace_malloc_enabled)) {
423 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
425 (dtrace_malloc_probe)(probe_id,
426 (uintptr_t) mtp, (uintptr_t) mtip,
427 (uintptr_t) mtsp, size, 0);
437 * Allocate a block of physically contiguous memory.
439 * If M_NOWAIT is set, this routine will not block and return NULL if
440 * the allocation fails.
443 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
444 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
449 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
450 boundary, VM_MEMATTR_DEFAULT);
452 malloc_type_allocated(type, round_page(size));
457 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
458 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
459 unsigned long alignment, vm_paddr_t boundary)
463 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
464 alignment, boundary, VM_MEMATTR_DEFAULT);
466 malloc_type_allocated(type, round_page(size));
473 * Free a block of memory allocated by contigmalloc.
475 * This routine may not block.
478 contigfree(void *addr, unsigned long size, struct malloc_type *type)
481 kmem_free((vm_offset_t)addr, size);
482 malloc_type_freed(type, round_page(size));
487 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
493 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
495 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
497 indx = flags & (M_WAITOK | M_NOWAIT);
498 if (indx != M_NOWAIT && indx != M_WAITOK) {
499 static struct timeval lasterr;
500 static int curerr, once;
501 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
502 printf("Bad malloc flags: %x\n", indx);
509 #ifdef MALLOC_MAKE_FAILURES
510 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
511 atomic_add_int(&malloc_nowait_count, 1);
512 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
513 atomic_add_int(&malloc_failure_count, 1);
514 t_malloc_fail = time_uptime;
516 return (EJUSTRETURN);
520 if (flags & M_WAITOK) {
521 KASSERT(curthread->td_intr_nesting_level == 0,
522 ("malloc(M_WAITOK) in interrupt context"));
523 KASSERT(curthread->td_epochnest == 0,
524 ("malloc(M_WAITOK) in epoch context"));
526 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
527 ("malloc: called with spinlock or critical section held"));
529 #ifdef DEBUG_MEMGUARD
530 if (memguard_cmp_mtp(mtp, *sizep)) {
531 *vap = memguard_alloc(*sizep, flags);
533 return (EJUSTRETURN);
534 /* This is unfortunate but should not be fatal. */
539 *sizep = redzone_size_ntor(*sizep);
549 * Allocate a block of memory.
551 * If M_NOWAIT is set, this routine will not block and return NULL if
552 * the allocation fails.
555 (malloc)(size_t size, struct malloc_type *mtp, int flags)
560 #if defined(DEBUG_REDZONE)
561 unsigned long osize = size;
566 if (malloc_dbg(&va, &size, mtp, flags) != 0)
570 if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
571 if (size & KMEM_ZMASK)
572 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
573 indx = kmemsize[size >> KMEM_ZSHIFT];
574 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
575 #ifdef MALLOC_PROFILE
576 krequests[size >> KMEM_ZSHIFT]++;
578 va = uma_zalloc(zone, flags);
580 size = zone->uz_size;
581 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
583 size = roundup(size, PAGE_SIZE);
585 va = uma_large_malloc(size, flags);
586 malloc_type_allocated(mtp, va == NULL ? 0 : size);
588 if (flags & M_WAITOK)
589 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
591 t_malloc_fail = time_uptime;
594 va = redzone_setup(va, osize);
596 return ((void *) va);
600 malloc_domain(size_t size, struct malloc_type *mtp, int domain, int flags)
605 #if defined(DEBUG_REDZONE)
606 unsigned long osize = size;
611 if (malloc_dbg(&va, &size, mtp, flags) != 0)
614 if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
615 if (size & KMEM_ZMASK)
616 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
617 indx = kmemsize[size >> KMEM_ZSHIFT];
618 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
619 #ifdef MALLOC_PROFILE
620 krequests[size >> KMEM_ZSHIFT]++;
622 va = uma_zalloc_domain(zone, NULL, domain, flags);
624 size = zone->uz_size;
625 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
627 size = roundup(size, PAGE_SIZE);
629 va = uma_large_malloc_domain(size, domain, flags);
630 malloc_type_allocated(mtp, va == NULL ? 0 : size);
632 if (flags & M_WAITOK)
633 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
635 t_malloc_fail = time_uptime;
638 va = redzone_setup(va, osize);
640 return ((void *) va);
644 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
647 struct vm_domainset_iter di;
651 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
653 ret = malloc_domain(size, mtp, domain, flags);
656 } while (vm_domainset_iter_policy(&di, &domain) == 0);
662 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
665 if (WOULD_OVERFLOW(nmemb, size))
666 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
668 return (malloc(size * nmemb, type, flags));
673 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
675 struct malloc_type **mtpp = addr;
678 * Cache a pointer to the malloc_type that most recently freed
679 * this memory here. This way we know who is most likely to
680 * have stepped on it later.
682 * This code assumes that size is a multiple of 8 bytes for
685 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
686 mtpp += (size - sizeof(struct malloc_type *)) /
687 sizeof(struct malloc_type *);
694 free_dbg(void **addrp, struct malloc_type *mtp)
699 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
700 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
701 ("free: called with spinlock or critical section held"));
703 /* free(NULL, ...) does nothing */
705 return (EJUSTRETURN);
707 #ifdef DEBUG_MEMGUARD
708 if (is_memguard_addr(addr)) {
710 return (EJUSTRETURN);
716 *addrp = redzone_addr_ntor(addr);
726 * Free a block of memory allocated by malloc.
728 * This routine may not block.
731 free(void *addr, struct malloc_type *mtp)
737 if (free_dbg(&addr, mtp) != 0)
740 /* free(NULL, ...) does nothing */
744 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
746 panic("free: address %p(%p) has not been allocated.\n",
747 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
749 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
750 size = slab->us_keg->uk_size;
752 free_save_type(addr, mtp, size);
754 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
756 size = slab->us_size;
757 uma_large_free(slab);
759 malloc_type_freed(mtp, size);
763 free_domain(void *addr, struct malloc_type *mtp)
769 if (free_dbg(&addr, mtp) != 0)
773 /* free(NULL, ...) does nothing */
777 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
779 panic("free_domain: address %p(%p) has not been allocated.\n",
780 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
782 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
783 size = slab->us_keg->uk_size;
785 free_save_type(addr, mtp, size);
787 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
790 size = slab->us_size;
791 uma_large_free(slab);
793 malloc_type_freed(mtp, size);
797 * realloc: change the size of a memory block
800 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
806 KASSERT(mtp->ks_magic == M_MAGIC,
807 ("realloc: bad malloc type magic"));
808 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
809 ("realloc: called with spinlock or critical section held"));
811 /* realloc(NULL, ...) is equivalent to malloc(...) */
813 return (malloc(size, mtp, flags));
816 * XXX: Should report free of old memory and alloc of new memory to
820 #ifdef DEBUG_MEMGUARD
821 if (is_memguard_addr(addr))
822 return (memguard_realloc(addr, size, mtp, flags));
827 alloc = redzone_get_size(addr);
829 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
832 KASSERT(slab != NULL,
833 ("realloc: address %p out of range", (void *)addr));
835 /* Get the size of the original block */
836 if (!(slab->us_flags & UMA_SLAB_MALLOC))
837 alloc = slab->us_keg->uk_size;
839 alloc = slab->us_size;
841 /* Reuse the original block if appropriate */
843 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
845 #endif /* !DEBUG_REDZONE */
847 /* Allocate a new, bigger (or smaller) block */
848 if ((newaddr = malloc(size, mtp, flags)) == NULL)
851 /* Copy over original contents */
852 bcopy(addr, newaddr, min(size, alloc));
858 * reallocf: same as realloc() but free memory on failure.
861 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
865 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
871 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
875 * Initialize the kernel memory (kmem) arena.
884 if (vm_kmem_size == 0)
885 vm_kmem_size = VM_KMEM_SIZE;
887 #ifdef VM_KMEM_SIZE_MIN
888 if (vm_kmem_size_min == 0)
889 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
891 #ifdef VM_KMEM_SIZE_MAX
892 if (vm_kmem_size_max == 0)
893 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
896 * Calculate the amount of kernel virtual address (KVA) space that is
897 * preallocated to the kmem arena. In order to support a wide range
898 * of machines, it is a function of the physical memory size,
901 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
902 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
904 * Every architecture must define an integral value for
905 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
906 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
907 * ceiling on this preallocation, are optional. Typically,
908 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
909 * a given architecture.
911 mem_size = vm_cnt.v_page_count;
912 if (mem_size <= 32768) /* delphij XXX 128MB */
913 kmem_zmax = PAGE_SIZE;
915 if (vm_kmem_size_scale < 1)
916 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
919 * Check if we should use defaults for the "vm_kmem_size"
922 if (vm_kmem_size == 0) {
923 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
925 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
926 vm_kmem_size = vm_kmem_size_min;
927 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
928 vm_kmem_size = vm_kmem_size_max;
932 * The amount of KVA space that is preallocated to the
933 * kmem arena can be set statically at compile-time or manually
934 * through the kernel environment. However, it is still limited to
935 * twice the physical memory size, which has been sufficient to handle
936 * the most severe cases of external fragmentation in the kmem arena.
938 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
939 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
941 vm_kmem_size = round_page(vm_kmem_size);
942 #ifdef DEBUG_MEMGUARD
943 tmp = memguard_fudge(vm_kmem_size, kernel_map);
949 #ifdef DEBUG_MEMGUARD
951 * Initialize MemGuard if support compiled in. MemGuard is a
952 * replacement allocator used for detecting tamper-after-free
953 * scenarios as they occur. It is only used for debugging.
955 memguard_init(kernel_arena);
960 * Initialize the kernel memory allocator
964 mallocinit(void *dummy)
969 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
973 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
974 kmem_zmax = KMEM_ZMAX;
976 mt_stats_zone = uma_zcreate("mt_stats_zone",
977 sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
978 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
979 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
981 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
983 NULL, NULL, NULL, NULL,
985 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
986 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
987 int size = kmemzones[indx].kz_size;
988 char *name = kmemzones[indx].kz_name;
991 for (subzone = 0; subzone < numzones; subzone++) {
992 kmemzones[indx].kz_zone[subzone] =
993 uma_zcreate(name, size,
995 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
997 NULL, NULL, NULL, NULL,
999 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1001 for (;i <= size; i+= KMEM_ZBASE)
1002 kmemsize[i >> KMEM_ZSHIFT] = indx;
1006 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1009 malloc_init(void *data)
1011 struct malloc_type_internal *mtip;
1012 struct malloc_type *mtp;
1014 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1017 if (mtp->ks_magic != M_MAGIC)
1018 panic("malloc_init: bad malloc type magic");
1020 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1021 mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1022 mtp->ks_handle = mtip;
1023 mtp_set_subzone(mtp);
1025 mtx_lock(&malloc_mtx);
1026 mtp->ks_next = kmemstatistics;
1027 kmemstatistics = mtp;
1029 mtx_unlock(&malloc_mtx);
1033 malloc_uninit(void *data)
1035 struct malloc_type_internal *mtip;
1036 struct malloc_type_stats *mtsp;
1037 struct malloc_type *mtp, *temp;
1039 long temp_allocs, temp_bytes;
1043 KASSERT(mtp->ks_magic == M_MAGIC,
1044 ("malloc_uninit: bad malloc type magic"));
1045 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1047 mtx_lock(&malloc_mtx);
1048 mtip = mtp->ks_handle;
1049 mtp->ks_handle = NULL;
1050 if (mtp != kmemstatistics) {
1051 for (temp = kmemstatistics; temp != NULL;
1052 temp = temp->ks_next) {
1053 if (temp->ks_next == mtp) {
1054 temp->ks_next = mtp->ks_next;
1059 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1061 kmemstatistics = mtp->ks_next;
1063 mtx_unlock(&malloc_mtx);
1066 * Look for memory leaks.
1068 temp_allocs = temp_bytes = 0;
1069 for (i = 0; i <= mp_maxid; i++) {
1070 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1071 temp_allocs += mtsp->mts_numallocs;
1072 temp_allocs -= mtsp->mts_numfrees;
1073 temp_bytes += mtsp->mts_memalloced;
1074 temp_bytes -= mtsp->mts_memfreed;
1076 if (temp_allocs > 0 || temp_bytes > 0) {
1077 printf("Warning: memory type %s leaked memory on destroy "
1078 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1079 temp_allocs, temp_bytes);
1082 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1083 uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1084 uma_zfree_arg(mt_zone, mtip, slab);
1087 struct malloc_type *
1088 malloc_desc2type(const char *desc)
1090 struct malloc_type *mtp;
1092 mtx_assert(&malloc_mtx, MA_OWNED);
1093 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1094 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1101 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1103 struct malloc_type_stream_header mtsh;
1104 struct malloc_type_internal *mtip;
1105 struct malloc_type_stats *mtsp, zeromts;
1106 struct malloc_type_header mth;
1107 struct malloc_type *mtp;
1111 error = sysctl_wire_old_buffer(req, 0);
1114 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1115 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1116 mtx_lock(&malloc_mtx);
1118 bzero(&zeromts, sizeof(zeromts));
1121 * Insert stream header.
1123 bzero(&mtsh, sizeof(mtsh));
1124 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1125 mtsh.mtsh_maxcpus = MAXCPU;
1126 mtsh.mtsh_count = kmemcount;
1127 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1130 * Insert alternating sequence of type headers and type statistics.
1132 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1133 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1136 * Insert type header.
1138 bzero(&mth, sizeof(mth));
1139 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1140 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1143 * Insert type statistics for each CPU.
1145 for (i = 0; i <= mp_maxid; i++) {
1146 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1147 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1150 * Fill in the missing CPUs.
1152 for (; i < MAXCPU; i++) {
1153 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1157 mtx_unlock(&malloc_mtx);
1158 error = sbuf_finish(&sbuf);
1163 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1164 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1165 "Return malloc types");
1167 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1168 "Count of kernel malloc types");
1171 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1173 struct malloc_type *mtp, **bufmtp;
1177 mtx_lock(&malloc_mtx);
1179 mtx_assert(&malloc_mtx, MA_OWNED);
1181 mtx_unlock(&malloc_mtx);
1183 buflen = sizeof(struct malloc_type *) * count;
1184 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1186 mtx_lock(&malloc_mtx);
1188 if (count < kmemcount) {
1189 free(bufmtp, M_TEMP);
1193 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1196 mtx_unlock(&malloc_mtx);
1198 for (i = 0; i < count; i++)
1199 (func)(bufmtp[i], arg);
1201 free(bufmtp, M_TEMP);
1205 DB_SHOW_COMMAND(malloc, db_show_malloc)
1207 struct malloc_type_internal *mtip;
1208 struct malloc_type_internal *mtsp;
1209 struct malloc_type *mtp;
1210 uint64_t allocs, frees;
1211 uint64_t alloced, freed;
1214 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1216 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1217 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1222 for (i = 0; i <= mp_maxid; i++) {
1223 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1224 allocs += mtip->mti_stats[i].mts_numallocs;
1225 frees += mtip->mti_stats[i].mts_numfrees;
1226 alloced += mtip->mti_stats[i].mts_memalloced;
1227 freed += mtip->mti_stats[i].mts_memfreed;
1229 db_printf("%18s %12ju %12juK %12ju\n",
1230 mtp->ks_shortdesc, allocs - frees,
1231 (alloced - freed + 1023) / 1024, allocs);
1237 #if MALLOC_DEBUG_MAXZONES > 1
1238 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1240 struct malloc_type_internal *mtip;
1241 struct malloc_type *mtp;
1245 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1249 if (mtp->ks_magic != M_MAGIC) {
1250 db_printf("Magic %lx does not match expected %x\n",
1251 mtp->ks_magic, M_MAGIC);
1255 mtip = mtp->ks_handle;
1256 subzone = mtip->mti_zone;
1258 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1259 mtip = mtp->ks_handle;
1260 if (mtip->mti_zone != subzone)
1262 db_printf("%s\n", mtp->ks_shortdesc);
1267 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1270 #ifdef MALLOC_PROFILE
1273 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1287 error = sysctl_wire_old_buffer(req, 0);
1290 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1292 "\n Size Requests Real Size\n");
1293 for (i = 0; i < KMEM_ZSIZE; i++) {
1294 size = i << KMEM_ZSHIFT;
1295 rsize = kmemzones[kmemsize[i]].kz_size;
1296 count = (long long unsigned)krequests[i];
1298 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1299 (unsigned long long)count, rsize);
1301 if ((rsize * count) > (size * count))
1302 waste += (rsize * count) - (size * count);
1303 mem += (rsize * count);
1306 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1307 (unsigned long long)mem, (unsigned long long)waste);
1308 error = sbuf_finish(&sbuf);
1313 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1314 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1315 #endif /* MALLOC_PROFILE */