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>
64 #include <sys/sysctl.h>
70 #include <vm/vm_pageout.h>
71 #include <vm/vm_param.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_page.h>
77 #include <vm/uma_int.h>
78 #include <vm/uma_dbg.h>
81 #include <vm/memguard.h>
84 #include <vm/redzone.h>
87 #if defined(INVARIANTS) && defined(__i386__)
88 #include <machine/cpu.h>
94 #include <sys/dtrace_bsd.h>
96 dtrace_malloc_probe_func_t dtrace_malloc_probe;
99 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
100 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
101 #define MALLOC_DEBUG 1
105 * When realloc() is called, if the new size is sufficiently smaller than
106 * the old size, realloc() will allocate a new, smaller block to avoid
107 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
108 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
110 #ifndef REALLOC_FRACTION
111 #define REALLOC_FRACTION 1 /* new block if <= half the size */
115 * Centrally define some common malloc types.
117 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
118 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
119 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
121 static struct malloc_type *kmemstatistics;
122 static int kmemcount;
124 #define KMEM_ZSHIFT 4
125 #define KMEM_ZBASE 16
126 #define KMEM_ZMASK (KMEM_ZBASE - 1)
128 #define KMEM_ZMAX 65536
129 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
130 static uint8_t kmemsize[KMEM_ZSIZE + 1];
132 #ifndef MALLOC_DEBUG_MAXZONES
133 #define MALLOC_DEBUG_MAXZONES 1
135 static int numzones = MALLOC_DEBUG_MAXZONES;
138 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
141 * XXX: The comment here used to read "These won't be powers of two for
142 * long." It's possible that a significant amount of wasted memory could be
143 * recovered by tuning the sizes of these buckets.
148 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
167 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
168 * types are described by a data structure passed by the declaring code, but
169 * the malloc(9) implementation has its own data structure describing the
170 * type and statistics. This permits the malloc(9)-internal data structures
171 * to be modified without breaking binary-compiled kernel modules that
172 * declare malloc types.
174 static uma_zone_t mt_zone;
177 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
178 "Size of kernel memory");
180 static u_long kmem_zmax = KMEM_ZMAX;
181 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
182 "Maximum allocation size that malloc(9) would use UMA as backend");
184 static u_long vm_kmem_size_min;
185 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
186 "Minimum size of kernel memory");
188 static u_long vm_kmem_size_max;
189 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
190 "Maximum size of kernel memory");
192 static u_int vm_kmem_size_scale;
193 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
194 "Scale factor for kernel memory size");
196 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
197 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
198 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
199 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
201 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
202 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
203 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
204 sysctl_kmem_map_free, "LU", "Free space in kmem");
207 * The malloc_mtx protects the kmemstatistics linked list.
209 struct mtx malloc_mtx;
211 #ifdef MALLOC_PROFILE
212 uint64_t krequests[KMEM_ZSIZE + 1];
214 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
217 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
220 * time_uptime of the last malloc(9) failure (induced or real).
222 static time_t t_malloc_fail;
224 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
225 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
226 "Kernel malloc debugging options");
230 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
231 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
233 #ifdef MALLOC_MAKE_FAILURES
234 static int malloc_failure_rate;
235 static int malloc_nowait_count;
236 static int malloc_failure_count;
237 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
238 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
239 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
240 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
244 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
249 return (sysctl_handle_long(oidp, &size, 0, req));
253 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
257 /* The sysctl is unsigned, implement as a saturation value. */
264 return (sysctl_handle_long(oidp, &size, 0, req));
268 * malloc(9) uma zone separation -- sub-page buffer overruns in one
269 * malloc type will affect only a subset of other malloc types.
271 #if MALLOC_DEBUG_MAXZONES > 1
273 tunable_set_numzones(void)
276 TUNABLE_INT_FETCH("debug.malloc.numzones",
279 /* Sanity check the number of malloc uma zones. */
282 if (numzones > MALLOC_DEBUG_MAXZONES)
283 numzones = MALLOC_DEBUG_MAXZONES;
285 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
286 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
287 &numzones, 0, "Number of malloc uma subzones");
290 * Any number that changes regularly is an okay choice for the
291 * offset. Build numbers are pretty good of you have them.
293 static u_int zone_offset = __FreeBSD_version;
294 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
295 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
296 &zone_offset, 0, "Separate malloc types by examining the "
297 "Nth character in the malloc type short description.");
300 mtp_get_subzone(const char *desc)
305 if (desc == NULL || (len = strlen(desc)) == 0)
307 val = desc[zone_offset % len];
308 return (val % numzones);
310 #elif MALLOC_DEBUG_MAXZONES == 0
311 #error "MALLOC_DEBUG_MAXZONES must be positive."
314 mtp_get_subzone(const char *desc)
319 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
322 malloc_last_fail(void)
325 return (time_uptime - t_malloc_fail);
329 * An allocation has succeeded -- update malloc type statistics for the
330 * amount of bucket size. Occurs within a critical section so that the
331 * thread isn't preempted and doesn't migrate while updating per-PCU
335 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
338 struct malloc_type_internal *mtip;
339 struct malloc_type_stats *mtsp;
342 mtip = mtp->ks_handle;
343 mtsp = &mtip->mti_stats[curcpu];
345 mtsp->mts_memalloced += size;
346 mtsp->mts_numallocs++;
349 mtsp->mts_size |= 1 << zindx;
352 if (dtrace_malloc_probe != NULL) {
353 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
355 (dtrace_malloc_probe)(probe_id,
356 (uintptr_t) mtp, (uintptr_t) mtip,
357 (uintptr_t) mtsp, size, zindx);
365 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
369 malloc_type_zone_allocated(mtp, size, -1);
373 * A free operation has occurred -- update malloc type statistics for the
374 * amount of the bucket size. Occurs within a critical section so that the
375 * thread isn't preempted and doesn't migrate while updating per-CPU
379 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
381 struct malloc_type_internal *mtip;
382 struct malloc_type_stats *mtsp;
385 mtip = mtp->ks_handle;
386 mtsp = &mtip->mti_stats[curcpu];
387 mtsp->mts_memfreed += size;
388 mtsp->mts_numfrees++;
391 if (dtrace_malloc_probe != NULL) {
392 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
394 (dtrace_malloc_probe)(probe_id,
395 (uintptr_t) mtp, (uintptr_t) mtip,
396 (uintptr_t) mtsp, size, 0);
406 * Allocate a block of physically contiguous memory.
408 * If M_NOWAIT is set, this routine will not block and return NULL if
409 * the allocation fails.
412 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
413 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
418 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
419 alignment, boundary, VM_MEMATTR_DEFAULT);
421 malloc_type_allocated(type, round_page(size));
426 contigmalloc_domain(unsigned long size, struct malloc_type *type,
427 int domain, int flags, vm_paddr_t low, vm_paddr_t high,
428 unsigned long alignment, vm_paddr_t boundary)
432 ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
433 alignment, boundary, VM_MEMATTR_DEFAULT);
435 malloc_type_allocated(type, round_page(size));
442 * Free a block of memory allocated by contigmalloc.
444 * This routine may not block.
447 contigfree(void *addr, unsigned long size, struct malloc_type *type)
450 kmem_free(kernel_arena, (vm_offset_t)addr, size);
451 malloc_type_freed(type, round_page(size));
456 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
462 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
464 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
466 indx = flags & (M_WAITOK | M_NOWAIT);
467 if (indx != M_NOWAIT && indx != M_WAITOK) {
468 static struct timeval lasterr;
469 static int curerr, once;
470 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
471 printf("Bad malloc flags: %x\n", indx);
478 #ifdef MALLOC_MAKE_FAILURES
479 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
480 atomic_add_int(&malloc_nowait_count, 1);
481 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
482 atomic_add_int(&malloc_failure_count, 1);
483 t_malloc_fail = time_uptime;
485 return (EJUSTRETURN);
489 if (flags & M_WAITOK)
490 KASSERT(curthread->td_intr_nesting_level == 0,
491 ("malloc(M_WAITOK) in interrupt context"));
492 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
493 ("malloc: called with spinlock or critical section held"));
495 #ifdef DEBUG_MEMGUARD
496 if (memguard_cmp_mtp(mtp, *sizep)) {
497 *vap = memguard_alloc(*sizep, flags);
499 return (EJUSTRETURN);
500 /* This is unfortunate but should not be fatal. */
505 *sizep = redzone_size_ntor(*sizep);
515 * Allocate a block of memory.
517 * If M_NOWAIT is set, this routine will not block and return NULL if
518 * the allocation fails.
521 malloc(size_t size, struct malloc_type *mtp, int flags)
524 struct malloc_type_internal *mtip;
527 #if defined(DEBUG_REDZONE)
528 unsigned long osize = size;
532 if (malloc_dbg(&va, &size, mtp, flags) != 0)
536 if (size <= kmem_zmax) {
537 mtip = mtp->ks_handle;
538 if (size & KMEM_ZMASK)
539 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
540 indx = kmemsize[size >> KMEM_ZSHIFT];
541 KASSERT(mtip->mti_zone < numzones,
542 ("mti_zone %u out of range %d",
543 mtip->mti_zone, numzones));
544 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
545 #ifdef MALLOC_PROFILE
546 krequests[size >> KMEM_ZSHIFT]++;
548 va = uma_zalloc(zone, flags);
550 size = zone->uz_size;
551 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
553 size = roundup(size, PAGE_SIZE);
555 va = uma_large_malloc(size, flags);
556 malloc_type_allocated(mtp, va == NULL ? 0 : size);
558 if (flags & M_WAITOK)
559 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
561 t_malloc_fail = time_uptime;
564 va = redzone_setup(va, osize);
566 return ((void *) va);
570 malloc_domain(size_t size, struct malloc_type *mtp, int domain,
574 struct malloc_type_internal *mtip;
577 #if defined(DEBUG_REDZONE)
578 unsigned long osize = size;
582 if (malloc_dbg(&va, &size, mtp, flags) != 0)
585 if (size <= kmem_zmax) {
586 mtip = mtp->ks_handle;
587 if (size & KMEM_ZMASK)
588 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
589 indx = kmemsize[size >> KMEM_ZSHIFT];
590 KASSERT(mtip->mti_zone < numzones,
591 ("mti_zone %u out of range %d",
592 mtip->mti_zone, numzones));
593 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
594 #ifdef MALLOC_PROFILE
595 krequests[size >> KMEM_ZSHIFT]++;
597 va = uma_zalloc_domain(zone, NULL, domain, flags);
599 size = zone->uz_size;
600 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
602 size = roundup(size, PAGE_SIZE);
604 va = uma_large_malloc_domain(size, domain, flags);
605 malloc_type_allocated(mtp, va == NULL ? 0 : size);
607 if (flags & M_WAITOK)
608 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
610 t_malloc_fail = time_uptime;
613 va = redzone_setup(va, osize);
615 return ((void *) va);
619 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
622 if (WOULD_OVERFLOW(nmemb, size))
623 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
625 return (malloc(size * nmemb, type, flags));
630 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
632 struct malloc_type **mtpp = addr;
635 * Cache a pointer to the malloc_type that most recently freed
636 * this memory here. This way we know who is most likely to
637 * have stepped on it later.
639 * This code assumes that size is a multiple of 8 bytes for
642 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
643 mtpp += (size - sizeof(struct malloc_type *)) /
644 sizeof(struct malloc_type *);
651 free_dbg(void **addrp, struct malloc_type *mtp)
656 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
657 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
658 ("free: called with spinlock or critical section held"));
660 /* free(NULL, ...) does nothing */
662 return (EJUSTRETURN);
664 #ifdef DEBUG_MEMGUARD
665 if (is_memguard_addr(addr)) {
667 return (EJUSTRETURN);
673 *addrp = redzone_addr_ntor(addr);
683 * Free a block of memory allocated by malloc.
685 * This routine may not block.
688 free(void *addr, struct malloc_type *mtp)
694 if (free_dbg(&addr, mtp) != 0)
697 /* free(NULL, ...) does nothing */
701 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
703 panic("free: address %p(%p) has not been allocated.\n",
704 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
706 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
707 size = slab->us_keg->uk_size;
709 free_save_type(addr, mtp, size);
711 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
713 size = slab->us_size;
714 uma_large_free(slab);
716 malloc_type_freed(mtp, size);
720 free_domain(void *addr, struct malloc_type *mtp)
726 if (free_dbg(&addr, mtp) != 0)
730 /* free(NULL, ...) does nothing */
734 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
736 panic("free_domain: address %p(%p) has not been allocated.\n",
737 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
739 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
740 size = slab->us_keg->uk_size;
742 free_save_type(addr, mtp, size);
744 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
747 size = slab->us_size;
748 uma_large_free(slab);
750 malloc_type_freed(mtp, size);
754 * realloc: change the size of a memory block
757 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
763 KASSERT(mtp->ks_magic == M_MAGIC,
764 ("realloc: bad malloc type magic"));
765 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
766 ("realloc: called with spinlock or critical section held"));
768 /* realloc(NULL, ...) is equivalent to malloc(...) */
770 return (malloc(size, mtp, flags));
773 * XXX: Should report free of old memory and alloc of new memory to
777 #ifdef DEBUG_MEMGUARD
778 if (is_memguard_addr(addr))
779 return (memguard_realloc(addr, size, mtp, flags));
784 alloc = redzone_get_size(addr);
786 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
789 KASSERT(slab != NULL,
790 ("realloc: address %p out of range", (void *)addr));
792 /* Get the size of the original block */
793 if (!(slab->us_flags & UMA_SLAB_MALLOC))
794 alloc = slab->us_keg->uk_size;
796 alloc = slab->us_size;
798 /* Reuse the original block if appropriate */
800 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
802 #endif /* !DEBUG_REDZONE */
804 /* Allocate a new, bigger (or smaller) block */
805 if ((newaddr = malloc(size, mtp, flags)) == NULL)
808 /* Copy over original contents */
809 bcopy(addr, newaddr, min(size, alloc));
815 * reallocf: same as realloc() but free memory on failure.
818 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
822 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
828 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
832 * Initialize the kernel memory (kmem) arena.
841 if (vm_kmem_size == 0)
842 vm_kmem_size = VM_KMEM_SIZE;
844 #ifdef VM_KMEM_SIZE_MIN
845 if (vm_kmem_size_min == 0)
846 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
848 #ifdef VM_KMEM_SIZE_MAX
849 if (vm_kmem_size_max == 0)
850 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
853 * Calculate the amount of kernel virtual address (KVA) space that is
854 * preallocated to the kmem arena. In order to support a wide range
855 * of machines, it is a function of the physical memory size,
858 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
859 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
861 * Every architecture must define an integral value for
862 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
863 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
864 * ceiling on this preallocation, are optional. Typically,
865 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
866 * a given architecture.
868 mem_size = vm_cnt.v_page_count;
869 if (mem_size <= 32768) /* delphij XXX 128MB */
870 kmem_zmax = PAGE_SIZE;
872 if (vm_kmem_size_scale < 1)
873 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
876 * Check if we should use defaults for the "vm_kmem_size"
879 if (vm_kmem_size == 0) {
880 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
882 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
883 vm_kmem_size = vm_kmem_size_min;
884 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
885 vm_kmem_size = vm_kmem_size_max;
889 * The amount of KVA space that is preallocated to the
890 * kmem arena can be set statically at compile-time or manually
891 * through the kernel environment. However, it is still limited to
892 * twice the physical memory size, which has been sufficient to handle
893 * the most severe cases of external fragmentation in the kmem arena.
895 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
896 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
898 vm_kmem_size = round_page(vm_kmem_size);
899 #ifdef DEBUG_MEMGUARD
900 tmp = memguard_fudge(vm_kmem_size, kernel_map);
906 #ifdef DEBUG_MEMGUARD
908 * Initialize MemGuard if support compiled in. MemGuard is a
909 * replacement allocator used for detecting tamper-after-free
910 * scenarios as they occur. It is only used for debugging.
912 memguard_init(kernel_arena);
917 * Initialize the kernel memory allocator
921 mallocinit(void *dummy)
926 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
930 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
931 kmem_zmax = KMEM_ZMAX;
933 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
935 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
937 NULL, NULL, NULL, NULL,
939 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
940 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
941 int size = kmemzones[indx].kz_size;
942 char *name = kmemzones[indx].kz_name;
945 for (subzone = 0; subzone < numzones; subzone++) {
946 kmemzones[indx].kz_zone[subzone] =
947 uma_zcreate(name, size,
949 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
951 NULL, NULL, NULL, NULL,
953 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
955 for (;i <= size; i+= KMEM_ZBASE)
956 kmemsize[i >> KMEM_ZSHIFT] = indx;
960 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
963 malloc_init(void *data)
965 struct malloc_type_internal *mtip;
966 struct malloc_type *mtp;
968 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
971 if (mtp->ks_magic != M_MAGIC)
972 panic("malloc_init: bad malloc type magic");
974 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
975 mtp->ks_handle = mtip;
976 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
978 mtx_lock(&malloc_mtx);
979 mtp->ks_next = kmemstatistics;
980 kmemstatistics = mtp;
982 mtx_unlock(&malloc_mtx);
986 malloc_uninit(void *data)
988 struct malloc_type_internal *mtip;
989 struct malloc_type_stats *mtsp;
990 struct malloc_type *mtp, *temp;
992 long temp_allocs, temp_bytes;
996 KASSERT(mtp->ks_magic == M_MAGIC,
997 ("malloc_uninit: bad malloc type magic"));
998 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1000 mtx_lock(&malloc_mtx);
1001 mtip = mtp->ks_handle;
1002 mtp->ks_handle = NULL;
1003 if (mtp != kmemstatistics) {
1004 for (temp = kmemstatistics; temp != NULL;
1005 temp = temp->ks_next) {
1006 if (temp->ks_next == mtp) {
1007 temp->ks_next = mtp->ks_next;
1012 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1014 kmemstatistics = mtp->ks_next;
1016 mtx_unlock(&malloc_mtx);
1019 * Look for memory leaks.
1021 temp_allocs = temp_bytes = 0;
1022 for (i = 0; i < MAXCPU; i++) {
1023 mtsp = &mtip->mti_stats[i];
1024 temp_allocs += mtsp->mts_numallocs;
1025 temp_allocs -= mtsp->mts_numfrees;
1026 temp_bytes += mtsp->mts_memalloced;
1027 temp_bytes -= mtsp->mts_memfreed;
1029 if (temp_allocs > 0 || temp_bytes > 0) {
1030 printf("Warning: memory type %s leaked memory on destroy "
1031 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1032 temp_allocs, temp_bytes);
1035 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1036 uma_zfree_arg(mt_zone, mtip, slab);
1039 struct malloc_type *
1040 malloc_desc2type(const char *desc)
1042 struct malloc_type *mtp;
1044 mtx_assert(&malloc_mtx, MA_OWNED);
1045 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1046 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1053 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1055 struct malloc_type_stream_header mtsh;
1056 struct malloc_type_internal *mtip;
1057 struct malloc_type_header mth;
1058 struct malloc_type *mtp;
1062 error = sysctl_wire_old_buffer(req, 0);
1065 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1066 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1067 mtx_lock(&malloc_mtx);
1070 * Insert stream header.
1072 bzero(&mtsh, sizeof(mtsh));
1073 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1074 mtsh.mtsh_maxcpus = MAXCPU;
1075 mtsh.mtsh_count = kmemcount;
1076 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1079 * Insert alternating sequence of type headers and type statistics.
1081 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1082 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1085 * Insert type header.
1087 bzero(&mth, sizeof(mth));
1088 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1089 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1092 * Insert type statistics for each CPU.
1094 for (i = 0; i < MAXCPU; i++) {
1095 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
1096 sizeof(mtip->mti_stats[i]));
1099 mtx_unlock(&malloc_mtx);
1100 error = sbuf_finish(&sbuf);
1105 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1106 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1107 "Return malloc types");
1109 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1110 "Count of kernel malloc types");
1113 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1115 struct malloc_type *mtp, **bufmtp;
1119 mtx_lock(&malloc_mtx);
1121 mtx_assert(&malloc_mtx, MA_OWNED);
1123 mtx_unlock(&malloc_mtx);
1125 buflen = sizeof(struct malloc_type *) * count;
1126 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1128 mtx_lock(&malloc_mtx);
1130 if (count < kmemcount) {
1131 free(bufmtp, M_TEMP);
1135 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1138 mtx_unlock(&malloc_mtx);
1140 for (i = 0; i < count; i++)
1141 (func)(bufmtp[i], arg);
1143 free(bufmtp, M_TEMP);
1147 DB_SHOW_COMMAND(malloc, db_show_malloc)
1149 struct malloc_type_internal *mtip;
1150 struct malloc_type *mtp;
1151 uint64_t allocs, frees;
1152 uint64_t alloced, freed;
1155 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1157 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1158 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1163 for (i = 0; i < MAXCPU; i++) {
1164 allocs += mtip->mti_stats[i].mts_numallocs;
1165 frees += mtip->mti_stats[i].mts_numfrees;
1166 alloced += mtip->mti_stats[i].mts_memalloced;
1167 freed += mtip->mti_stats[i].mts_memfreed;
1169 db_printf("%18s %12ju %12juK %12ju\n",
1170 mtp->ks_shortdesc, allocs - frees,
1171 (alloced - freed + 1023) / 1024, allocs);
1177 #if MALLOC_DEBUG_MAXZONES > 1
1178 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1180 struct malloc_type_internal *mtip;
1181 struct malloc_type *mtp;
1185 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1189 if (mtp->ks_magic != M_MAGIC) {
1190 db_printf("Magic %lx does not match expected %x\n",
1191 mtp->ks_magic, M_MAGIC);
1195 mtip = mtp->ks_handle;
1196 subzone = mtip->mti_zone;
1198 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1199 mtip = mtp->ks_handle;
1200 if (mtip->mti_zone != subzone)
1202 db_printf("%s\n", mtp->ks_shortdesc);
1207 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1210 #ifdef MALLOC_PROFILE
1213 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1227 error = sysctl_wire_old_buffer(req, 0);
1230 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1232 "\n Size Requests Real Size\n");
1233 for (i = 0; i < KMEM_ZSIZE; i++) {
1234 size = i << KMEM_ZSHIFT;
1235 rsize = kmemzones[kmemsize[i]].kz_size;
1236 count = (long long unsigned)krequests[i];
1238 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1239 (unsigned long long)count, rsize);
1241 if ((rsize * count) > (size * count))
1242 waste += (rsize * count) - (size * count);
1243 mem += (rsize * count);
1246 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1247 (unsigned long long)mem, (unsigned long long)waste);
1248 error = sbuf_finish(&sbuf);
1253 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1254 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1255 #endif /* MALLOC_PROFILE */