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 * malloc_usable_size: returns the usable size of the allocation.
874 malloc_usable_size(const void *addr)
876 #ifndef DEBUG_REDZONE
884 #ifdef DEBUG_MEMGUARD
885 if (is_memguard_addr(__DECONST(void *, addr)))
886 return (memguard_get_req_size(addr));
890 size = redzone_get_size(__DECONST(void *, addr));
892 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
894 panic("malloc_usable_size: address %p(%p) is not allocated.\n",
895 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
897 if (!(slab->us_flags & UMA_SLAB_MALLOC))
898 size = slab->us_keg->uk_size;
900 size = slab->us_size;
906 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
910 * Initialize the kernel memory (kmem) arena.
919 if (vm_kmem_size == 0)
920 vm_kmem_size = VM_KMEM_SIZE;
922 #ifdef VM_KMEM_SIZE_MIN
923 if (vm_kmem_size_min == 0)
924 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
926 #ifdef VM_KMEM_SIZE_MAX
927 if (vm_kmem_size_max == 0)
928 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
931 * Calculate the amount of kernel virtual address (KVA) space that is
932 * preallocated to the kmem arena. In order to support a wide range
933 * of machines, it is a function of the physical memory size,
936 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
937 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
939 * Every architecture must define an integral value for
940 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
941 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
942 * ceiling on this preallocation, are optional. Typically,
943 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
944 * a given architecture.
946 mem_size = vm_cnt.v_page_count;
947 if (mem_size <= 32768) /* delphij XXX 128MB */
948 kmem_zmax = PAGE_SIZE;
950 if (vm_kmem_size_scale < 1)
951 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
954 * Check if we should use defaults for the "vm_kmem_size"
957 if (vm_kmem_size == 0) {
958 vm_kmem_size = mem_size / vm_kmem_size_scale;
959 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
960 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
961 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
962 vm_kmem_size = vm_kmem_size_min;
963 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
964 vm_kmem_size = vm_kmem_size_max;
966 if (vm_kmem_size == 0)
967 panic("Tune VM_KMEM_SIZE_* for the platform");
970 * The amount of KVA space that is preallocated to the
971 * kmem arena can be set statically at compile-time or manually
972 * through the kernel environment. However, it is still limited to
973 * twice the physical memory size, which has been sufficient to handle
974 * the most severe cases of external fragmentation in the kmem arena.
976 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
977 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
979 vm_kmem_size = round_page(vm_kmem_size);
980 #ifdef DEBUG_MEMGUARD
981 tmp = memguard_fudge(vm_kmem_size, kernel_map);
987 #ifdef DEBUG_MEMGUARD
989 * Initialize MemGuard if support compiled in. MemGuard is a
990 * replacement allocator used for detecting tamper-after-free
991 * scenarios as they occur. It is only used for debugging.
993 memguard_init(kernel_arena);
998 * Initialize the kernel memory allocator
1002 mallocinit(void *dummy)
1007 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1011 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1012 kmem_zmax = KMEM_ZMAX;
1014 mt_stats_zone = uma_zcreate("mt_stats_zone",
1015 sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
1016 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
1017 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
1019 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1021 NULL, NULL, NULL, NULL,
1023 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1024 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1025 int size = kmemzones[indx].kz_size;
1026 char *name = kmemzones[indx].kz_name;
1029 for (subzone = 0; subzone < numzones; subzone++) {
1030 kmemzones[indx].kz_zone[subzone] =
1031 uma_zcreate(name, size,
1033 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1035 NULL, NULL, NULL, NULL,
1037 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1039 for (;i <= size; i+= KMEM_ZBASE)
1040 kmemsize[i >> KMEM_ZSHIFT] = indx;
1044 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1047 malloc_init(void *data)
1049 struct malloc_type_internal *mtip;
1050 struct malloc_type *mtp;
1052 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1055 if (mtp->ks_magic != M_MAGIC)
1056 panic("malloc_init: bad malloc type magic");
1058 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1059 mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1060 mtp->ks_handle = mtip;
1061 mtp_set_subzone(mtp);
1063 mtx_lock(&malloc_mtx);
1064 mtp->ks_next = kmemstatistics;
1065 kmemstatistics = mtp;
1067 mtx_unlock(&malloc_mtx);
1071 malloc_uninit(void *data)
1073 struct malloc_type_internal *mtip;
1074 struct malloc_type_stats *mtsp;
1075 struct malloc_type *mtp, *temp;
1077 long temp_allocs, temp_bytes;
1081 KASSERT(mtp->ks_magic == M_MAGIC,
1082 ("malloc_uninit: bad malloc type magic"));
1083 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1085 mtx_lock(&malloc_mtx);
1086 mtip = mtp->ks_handle;
1087 mtp->ks_handle = NULL;
1088 if (mtp != kmemstatistics) {
1089 for (temp = kmemstatistics; temp != NULL;
1090 temp = temp->ks_next) {
1091 if (temp->ks_next == mtp) {
1092 temp->ks_next = mtp->ks_next;
1097 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1099 kmemstatistics = mtp->ks_next;
1101 mtx_unlock(&malloc_mtx);
1104 * Look for memory leaks.
1106 temp_allocs = temp_bytes = 0;
1107 for (i = 0; i <= mp_maxid; i++) {
1108 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1109 temp_allocs += mtsp->mts_numallocs;
1110 temp_allocs -= mtsp->mts_numfrees;
1111 temp_bytes += mtsp->mts_memalloced;
1112 temp_bytes -= mtsp->mts_memfreed;
1114 if (temp_allocs > 0 || temp_bytes > 0) {
1115 printf("Warning: memory type %s leaked memory on destroy "
1116 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1117 temp_allocs, temp_bytes);
1120 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1121 uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1122 uma_zfree_arg(mt_zone, mtip, slab);
1125 struct malloc_type *
1126 malloc_desc2type(const char *desc)
1128 struct malloc_type *mtp;
1130 mtx_assert(&malloc_mtx, MA_OWNED);
1131 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1132 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1139 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1141 struct malloc_type_stream_header mtsh;
1142 struct malloc_type_internal *mtip;
1143 struct malloc_type_stats *mtsp, zeromts;
1144 struct malloc_type_header mth;
1145 struct malloc_type *mtp;
1149 error = sysctl_wire_old_buffer(req, 0);
1152 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1153 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1154 mtx_lock(&malloc_mtx);
1156 bzero(&zeromts, sizeof(zeromts));
1159 * Insert stream header.
1161 bzero(&mtsh, sizeof(mtsh));
1162 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1163 mtsh.mtsh_maxcpus = MAXCPU;
1164 mtsh.mtsh_count = kmemcount;
1165 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1168 * Insert alternating sequence of type headers and type statistics.
1170 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1171 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1174 * Insert type header.
1176 bzero(&mth, sizeof(mth));
1177 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1178 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1181 * Insert type statistics for each CPU.
1183 for (i = 0; i <= mp_maxid; i++) {
1184 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1185 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1188 * Fill in the missing CPUs.
1190 for (; i < MAXCPU; i++) {
1191 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1195 mtx_unlock(&malloc_mtx);
1196 error = sbuf_finish(&sbuf);
1201 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1202 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1203 "Return malloc types");
1205 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1206 "Count of kernel malloc types");
1209 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1211 struct malloc_type *mtp, **bufmtp;
1215 mtx_lock(&malloc_mtx);
1217 mtx_assert(&malloc_mtx, MA_OWNED);
1219 mtx_unlock(&malloc_mtx);
1221 buflen = sizeof(struct malloc_type *) * count;
1222 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1224 mtx_lock(&malloc_mtx);
1226 if (count < kmemcount) {
1227 free(bufmtp, M_TEMP);
1231 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1234 mtx_unlock(&malloc_mtx);
1236 for (i = 0; i < count; i++)
1237 (func)(bufmtp[i], arg);
1239 free(bufmtp, M_TEMP);
1243 DB_SHOW_COMMAND(malloc, db_show_malloc)
1245 struct malloc_type_internal *mtip;
1246 struct malloc_type_stats *mtsp;
1247 struct malloc_type *mtp;
1248 uint64_t allocs, frees;
1249 uint64_t alloced, freed;
1252 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1254 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1255 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1260 for (i = 0; i <= mp_maxid; i++) {
1261 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1262 allocs += mtsp->mts_numallocs;
1263 frees += mtsp->mts_numfrees;
1264 alloced += mtsp->mts_memalloced;
1265 freed += mtsp->mts_memfreed;
1267 db_printf("%18s %12ju %12juK %12ju\n",
1268 mtp->ks_shortdesc, allocs - frees,
1269 (alloced - freed + 1023) / 1024, allocs);
1275 #if MALLOC_DEBUG_MAXZONES > 1
1276 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1278 struct malloc_type_internal *mtip;
1279 struct malloc_type *mtp;
1283 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1287 if (mtp->ks_magic != M_MAGIC) {
1288 db_printf("Magic %lx does not match expected %x\n",
1289 mtp->ks_magic, M_MAGIC);
1293 mtip = mtp->ks_handle;
1294 subzone = mtip->mti_zone;
1296 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1297 mtip = mtp->ks_handle;
1298 if (mtip->mti_zone != subzone)
1300 db_printf("%s\n", mtp->ks_shortdesc);
1305 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1308 #ifdef MALLOC_PROFILE
1311 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1325 error = sysctl_wire_old_buffer(req, 0);
1328 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1330 "\n Size Requests Real Size\n");
1331 for (i = 0; i < KMEM_ZSIZE; i++) {
1332 size = i << KMEM_ZSHIFT;
1333 rsize = kmemzones[kmemsize[i]].kz_size;
1334 count = (long long unsigned)krequests[i];
1336 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1337 (unsigned long long)count, rsize);
1339 if ((rsize * count) > (size * count))
1340 waste += (rsize * count) - (size * count);
1341 mem += (rsize * count);
1344 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1345 (unsigned long long)mem, (unsigned long long)waste);
1346 error = sbuf_finish(&sbuf);
1351 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1352 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1353 #endif /* MALLOC_PROFILE */