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 bool __read_frequently dtrace_malloc_enabled;
97 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
100 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
101 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
102 #define MALLOC_DEBUG 1
106 * When realloc() is called, if the new size is sufficiently smaller than
107 * the old size, realloc() will allocate a new, smaller block to avoid
108 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
109 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
111 #ifndef REALLOC_FRACTION
112 #define REALLOC_FRACTION 1 /* new block if <= half the size */
116 * Centrally define some common malloc types.
118 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
119 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
120 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
122 static struct malloc_type *kmemstatistics;
123 static int kmemcount;
125 #define KMEM_ZSHIFT 4
126 #define KMEM_ZBASE 16
127 #define KMEM_ZMASK (KMEM_ZBASE - 1)
129 #define KMEM_ZMAX 65536
130 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
131 static uint8_t kmemsize[KMEM_ZSIZE + 1];
133 #ifndef MALLOC_DEBUG_MAXZONES
134 #define MALLOC_DEBUG_MAXZONES 1
136 static int numzones = MALLOC_DEBUG_MAXZONES;
139 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
142 * XXX: The comment here used to read "These won't be powers of two for
143 * long." It's possible that a significant amount of wasted memory could be
144 * recovered by tuning the sizes of these buckets.
149 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
168 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
169 * types are described by a data structure passed by the declaring code, but
170 * the malloc(9) implementation has its own data structure describing the
171 * type and statistics. This permits the malloc(9)-internal data structures
172 * to be modified without breaking binary-compiled kernel modules that
173 * declare malloc types.
175 static uma_zone_t mt_zone;
178 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
179 "Size of kernel memory");
181 static u_long kmem_zmax = KMEM_ZMAX;
182 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
183 "Maximum allocation size that malloc(9) would use UMA as backend");
185 static u_long vm_kmem_size_min;
186 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
187 "Minimum size of kernel memory");
189 static u_long vm_kmem_size_max;
190 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
191 "Maximum size of kernel memory");
193 static u_int vm_kmem_size_scale;
194 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
195 "Scale factor for kernel memory size");
197 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
198 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
199 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
200 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
202 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
203 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
204 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
205 sysctl_kmem_map_free, "LU", "Free space in kmem");
208 * The malloc_mtx protects the kmemstatistics linked list.
210 struct mtx malloc_mtx;
212 #ifdef MALLOC_PROFILE
213 uint64_t krequests[KMEM_ZSIZE + 1];
215 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
218 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
221 * time_uptime of the last malloc(9) failure (induced or real).
223 static time_t t_malloc_fail;
225 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
226 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
227 "Kernel malloc debugging options");
231 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
232 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
234 #ifdef MALLOC_MAKE_FAILURES
235 static int malloc_failure_rate;
236 static int malloc_nowait_count;
237 static int malloc_failure_count;
238 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
239 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
240 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
241 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
245 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
250 return (sysctl_handle_long(oidp, &size, 0, req));
254 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
258 /* The sysctl is unsigned, implement as a saturation value. */
265 return (sysctl_handle_long(oidp, &size, 0, req));
269 * malloc(9) uma zone separation -- sub-page buffer overruns in one
270 * malloc type will affect only a subset of other malloc types.
272 #if MALLOC_DEBUG_MAXZONES > 1
274 tunable_set_numzones(void)
277 TUNABLE_INT_FETCH("debug.malloc.numzones",
280 /* Sanity check the number of malloc uma zones. */
283 if (numzones > MALLOC_DEBUG_MAXZONES)
284 numzones = MALLOC_DEBUG_MAXZONES;
286 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
287 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
288 &numzones, 0, "Number of malloc uma subzones");
291 * Any number that changes regularly is an okay choice for the
292 * offset. Build numbers are pretty good of you have them.
294 static u_int zone_offset = __FreeBSD_version;
295 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
296 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
297 &zone_offset, 0, "Separate malloc types by examining the "
298 "Nth character in the malloc type short description.");
301 mtp_set_subzone(struct malloc_type *mtp)
303 struct malloc_type_internal *mtip;
308 mtip = mtp->ks_handle;
309 desc = mtp->ks_shortdesc;
310 if (desc == NULL || (len = strlen(desc)) == 0)
313 val = desc[zone_offset % len];
314 mtip->mti_zone = (val % numzones);
318 mtp_get_subzone(struct malloc_type *mtp)
320 struct malloc_type_internal *mtip;
322 mtip = mtp->ks_handle;
324 KASSERT(mtip->mti_zone < numzones,
325 ("mti_zone %u out of range %d",
326 mtip->mti_zone, numzones));
327 return (mtip->mti_zone);
329 #elif MALLOC_DEBUG_MAXZONES == 0
330 #error "MALLOC_DEBUG_MAXZONES must be positive."
333 mtp_set_subzone(struct malloc_type *mtp)
335 struct malloc_type_internal *mtip;
337 mtip = mtp->ks_handle;
342 mtp_get_subzone(struct malloc_type *mtp)
347 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
350 malloc_last_fail(void)
353 return (time_uptime - t_malloc_fail);
357 * An allocation has succeeded -- update malloc type statistics for the
358 * amount of bucket size. Occurs within a critical section so that the
359 * thread isn't preempted and doesn't migrate while updating per-PCU
363 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
366 struct malloc_type_internal *mtip;
367 struct malloc_type_stats *mtsp;
370 mtip = mtp->ks_handle;
371 mtsp = &mtip->mti_stats[curcpu];
373 mtsp->mts_memalloced += size;
374 mtsp->mts_numallocs++;
377 mtsp->mts_size |= 1 << zindx;
380 if (__predict_false(dtrace_malloc_enabled)) {
381 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
383 (dtrace_malloc_probe)(probe_id,
384 (uintptr_t) mtp, (uintptr_t) mtip,
385 (uintptr_t) mtsp, size, zindx);
393 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
397 malloc_type_zone_allocated(mtp, size, -1);
401 * A free operation has occurred -- update malloc type statistics for the
402 * amount of the bucket size. Occurs within a critical section so that the
403 * thread isn't preempted and doesn't migrate while updating per-CPU
407 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
409 struct malloc_type_internal *mtip;
410 struct malloc_type_stats *mtsp;
413 mtip = mtp->ks_handle;
414 mtsp = &mtip->mti_stats[curcpu];
415 mtsp->mts_memfreed += size;
416 mtsp->mts_numfrees++;
419 if (__predict_false(dtrace_malloc_enabled)) {
420 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
422 (dtrace_malloc_probe)(probe_id,
423 (uintptr_t) mtp, (uintptr_t) mtip,
424 (uintptr_t) mtsp, size, 0);
434 * Allocate a block of physically contiguous memory.
436 * If M_NOWAIT is set, this routine will not block and return NULL if
437 * the allocation fails.
440 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
441 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
446 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
447 alignment, boundary, VM_MEMATTR_DEFAULT);
449 malloc_type_allocated(type, round_page(size));
454 contigmalloc_domain(unsigned long size, struct malloc_type *type,
455 int domain, int flags, vm_paddr_t low, vm_paddr_t high,
456 unsigned long alignment, vm_paddr_t boundary)
460 ret = (void *)kmem_alloc_contig_domain(domain, size, flags, low, high,
461 alignment, boundary, VM_MEMATTR_DEFAULT);
463 malloc_type_allocated(type, round_page(size));
470 * Free a block of memory allocated by contigmalloc.
472 * This routine may not block.
475 contigfree(void *addr, unsigned long size, struct malloc_type *type)
478 kmem_free(kernel_arena, (vm_offset_t)addr, size);
479 malloc_type_freed(type, round_page(size));
484 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
490 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
492 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
494 indx = flags & (M_WAITOK | M_NOWAIT);
495 if (indx != M_NOWAIT && indx != M_WAITOK) {
496 static struct timeval lasterr;
497 static int curerr, once;
498 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
499 printf("Bad malloc flags: %x\n", indx);
506 #ifdef MALLOC_MAKE_FAILURES
507 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
508 atomic_add_int(&malloc_nowait_count, 1);
509 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
510 atomic_add_int(&malloc_failure_count, 1);
511 t_malloc_fail = time_uptime;
513 return (EJUSTRETURN);
517 if (flags & M_WAITOK)
518 KASSERT(curthread->td_intr_nesting_level == 0,
519 ("malloc(M_WAITOK) in interrupt context"));
520 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
521 ("malloc: called with spinlock or critical section held"));
523 #ifdef DEBUG_MEMGUARD
524 if (memguard_cmp_mtp(mtp, *sizep)) {
525 *vap = memguard_alloc(*sizep, flags);
527 return (EJUSTRETURN);
528 /* This is unfortunate but should not be fatal. */
533 *sizep = redzone_size_ntor(*sizep);
543 * Allocate a block of memory.
545 * If M_NOWAIT is set, this routine will not block and return NULL if
546 * the allocation fails.
549 malloc(size_t size, struct malloc_type *mtp, int flags)
554 #if defined(DEBUG_REDZONE)
555 unsigned long osize = size;
559 if (malloc_dbg(&va, &size, mtp, flags) != 0)
563 if (size <= kmem_zmax) {
564 if (size & KMEM_ZMASK)
565 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
566 indx = kmemsize[size >> KMEM_ZSHIFT];
567 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
568 #ifdef MALLOC_PROFILE
569 krequests[size >> KMEM_ZSHIFT]++;
571 va = uma_zalloc(zone, flags);
573 size = zone->uz_size;
574 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
576 size = roundup(size, PAGE_SIZE);
578 va = uma_large_malloc(size, flags);
579 malloc_type_allocated(mtp, va == NULL ? 0 : size);
581 if (flags & M_WAITOK)
582 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
584 t_malloc_fail = time_uptime;
587 va = redzone_setup(va, osize);
589 return ((void *) va);
593 malloc_domain(size_t size, struct malloc_type *mtp, int domain,
599 #if defined(DEBUG_REDZONE)
600 unsigned long osize = size;
604 if (malloc_dbg(&va, &size, mtp, flags) != 0)
607 if (size <= kmem_zmax) {
608 if (size & KMEM_ZMASK)
609 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
610 indx = kmemsize[size >> KMEM_ZSHIFT];
611 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
612 #ifdef MALLOC_PROFILE
613 krequests[size >> KMEM_ZSHIFT]++;
615 va = uma_zalloc_domain(zone, NULL, domain, flags);
617 size = zone->uz_size;
618 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
620 size = roundup(size, PAGE_SIZE);
622 va = uma_large_malloc_domain(size, domain, flags);
623 malloc_type_allocated(mtp, va == NULL ? 0 : size);
625 if (flags & M_WAITOK)
626 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
628 t_malloc_fail = time_uptime;
631 va = redzone_setup(va, osize);
633 return ((void *) va);
637 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
640 if (WOULD_OVERFLOW(nmemb, size))
641 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
643 return (malloc(size * nmemb, type, flags));
648 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
650 struct malloc_type **mtpp = addr;
653 * Cache a pointer to the malloc_type that most recently freed
654 * this memory here. This way we know who is most likely to
655 * have stepped on it later.
657 * This code assumes that size is a multiple of 8 bytes for
660 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
661 mtpp += (size - sizeof(struct malloc_type *)) /
662 sizeof(struct malloc_type *);
669 free_dbg(void **addrp, struct malloc_type *mtp)
674 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
675 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
676 ("free: called with spinlock or critical section held"));
678 /* free(NULL, ...) does nothing */
680 return (EJUSTRETURN);
682 #ifdef DEBUG_MEMGUARD
683 if (is_memguard_addr(addr)) {
685 return (EJUSTRETURN);
691 *addrp = redzone_addr_ntor(addr);
701 * Free a block of memory allocated by malloc.
703 * This routine may not block.
706 free(void *addr, struct malloc_type *mtp)
712 if (free_dbg(&addr, mtp) != 0)
715 /* free(NULL, ...) does nothing */
719 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
721 panic("free: address %p(%p) has not been allocated.\n",
722 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
724 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
725 size = slab->us_keg->uk_size;
727 free_save_type(addr, mtp, size);
729 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
731 size = slab->us_size;
732 uma_large_free(slab);
734 malloc_type_freed(mtp, size);
738 free_domain(void *addr, struct malloc_type *mtp)
744 if (free_dbg(&addr, mtp) != 0)
748 /* free(NULL, ...) does nothing */
752 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
754 panic("free_domain: address %p(%p) has not been allocated.\n",
755 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
757 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
758 size = slab->us_keg->uk_size;
760 free_save_type(addr, mtp, size);
762 uma_zfree_domain(LIST_FIRST(&slab->us_keg->uk_zones),
765 size = slab->us_size;
766 uma_large_free(slab);
768 malloc_type_freed(mtp, size);
772 * realloc: change the size of a memory block
775 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
781 KASSERT(mtp->ks_magic == M_MAGIC,
782 ("realloc: bad malloc type magic"));
783 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
784 ("realloc: called with spinlock or critical section held"));
786 /* realloc(NULL, ...) is equivalent to malloc(...) */
788 return (malloc(size, mtp, flags));
791 * XXX: Should report free of old memory and alloc of new memory to
795 #ifdef DEBUG_MEMGUARD
796 if (is_memguard_addr(addr))
797 return (memguard_realloc(addr, size, mtp, flags));
802 alloc = redzone_get_size(addr);
804 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
807 KASSERT(slab != NULL,
808 ("realloc: address %p out of range", (void *)addr));
810 /* Get the size of the original block */
811 if (!(slab->us_flags & UMA_SLAB_MALLOC))
812 alloc = slab->us_keg->uk_size;
814 alloc = slab->us_size;
816 /* Reuse the original block if appropriate */
818 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
820 #endif /* !DEBUG_REDZONE */
822 /* Allocate a new, bigger (or smaller) block */
823 if ((newaddr = malloc(size, mtp, flags)) == NULL)
826 /* Copy over original contents */
827 bcopy(addr, newaddr, min(size, alloc));
833 * reallocf: same as realloc() but free memory on failure.
836 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
840 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
846 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
850 * Initialize the kernel memory (kmem) arena.
859 if (vm_kmem_size == 0)
860 vm_kmem_size = VM_KMEM_SIZE;
862 #ifdef VM_KMEM_SIZE_MIN
863 if (vm_kmem_size_min == 0)
864 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
866 #ifdef VM_KMEM_SIZE_MAX
867 if (vm_kmem_size_max == 0)
868 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
871 * Calculate the amount of kernel virtual address (KVA) space that is
872 * preallocated to the kmem arena. In order to support a wide range
873 * of machines, it is a function of the physical memory size,
876 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
877 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
879 * Every architecture must define an integral value for
880 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
881 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
882 * ceiling on this preallocation, are optional. Typically,
883 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
884 * a given architecture.
886 mem_size = vm_cnt.v_page_count;
887 if (mem_size <= 32768) /* delphij XXX 128MB */
888 kmem_zmax = PAGE_SIZE;
890 if (vm_kmem_size_scale < 1)
891 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
894 * Check if we should use defaults for the "vm_kmem_size"
897 if (vm_kmem_size == 0) {
898 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
900 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
901 vm_kmem_size = vm_kmem_size_min;
902 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
903 vm_kmem_size = vm_kmem_size_max;
907 * The amount of KVA space that is preallocated to the
908 * kmem arena can be set statically at compile-time or manually
909 * through the kernel environment. However, it is still limited to
910 * twice the physical memory size, which has been sufficient to handle
911 * the most severe cases of external fragmentation in the kmem arena.
913 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
914 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
916 vm_kmem_size = round_page(vm_kmem_size);
917 #ifdef DEBUG_MEMGUARD
918 tmp = memguard_fudge(vm_kmem_size, kernel_map);
924 #ifdef DEBUG_MEMGUARD
926 * Initialize MemGuard if support compiled in. MemGuard is a
927 * replacement allocator used for detecting tamper-after-free
928 * scenarios as they occur. It is only used for debugging.
930 memguard_init(kernel_arena);
935 * Initialize the kernel memory allocator
939 mallocinit(void *dummy)
944 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
948 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
949 kmem_zmax = KMEM_ZMAX;
951 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
953 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
955 NULL, NULL, NULL, NULL,
957 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
958 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
959 int size = kmemzones[indx].kz_size;
960 char *name = kmemzones[indx].kz_name;
963 for (subzone = 0; subzone < numzones; subzone++) {
964 kmemzones[indx].kz_zone[subzone] =
965 uma_zcreate(name, size,
967 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
969 NULL, NULL, NULL, NULL,
971 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
973 for (;i <= size; i+= KMEM_ZBASE)
974 kmemsize[i >> KMEM_ZSHIFT] = indx;
978 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
981 malloc_init(void *data)
983 struct malloc_type_internal *mtip;
984 struct malloc_type *mtp;
986 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
989 if (mtp->ks_magic != M_MAGIC)
990 panic("malloc_init: bad malloc type magic");
992 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
993 mtp->ks_handle = mtip;
994 mtp_set_subzone(mtp);
996 mtx_lock(&malloc_mtx);
997 mtp->ks_next = kmemstatistics;
998 kmemstatistics = mtp;
1000 mtx_unlock(&malloc_mtx);
1004 malloc_uninit(void *data)
1006 struct malloc_type_internal *mtip;
1007 struct malloc_type_stats *mtsp;
1008 struct malloc_type *mtp, *temp;
1010 long temp_allocs, temp_bytes;
1014 KASSERT(mtp->ks_magic == M_MAGIC,
1015 ("malloc_uninit: bad malloc type magic"));
1016 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1018 mtx_lock(&malloc_mtx);
1019 mtip = mtp->ks_handle;
1020 mtp->ks_handle = NULL;
1021 if (mtp != kmemstatistics) {
1022 for (temp = kmemstatistics; temp != NULL;
1023 temp = temp->ks_next) {
1024 if (temp->ks_next == mtp) {
1025 temp->ks_next = mtp->ks_next;
1030 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1032 kmemstatistics = mtp->ks_next;
1034 mtx_unlock(&malloc_mtx);
1037 * Look for memory leaks.
1039 temp_allocs = temp_bytes = 0;
1040 for (i = 0; i < MAXCPU; i++) {
1041 mtsp = &mtip->mti_stats[i];
1042 temp_allocs += mtsp->mts_numallocs;
1043 temp_allocs -= mtsp->mts_numfrees;
1044 temp_bytes += mtsp->mts_memalloced;
1045 temp_bytes -= mtsp->mts_memfreed;
1047 if (temp_allocs > 0 || temp_bytes > 0) {
1048 printf("Warning: memory type %s leaked memory on destroy "
1049 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1050 temp_allocs, temp_bytes);
1053 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1054 uma_zfree_arg(mt_zone, mtip, slab);
1057 struct malloc_type *
1058 malloc_desc2type(const char *desc)
1060 struct malloc_type *mtp;
1062 mtx_assert(&malloc_mtx, MA_OWNED);
1063 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1064 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1071 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1073 struct malloc_type_stream_header mtsh;
1074 struct malloc_type_internal *mtip;
1075 struct malloc_type_header mth;
1076 struct malloc_type *mtp;
1080 error = sysctl_wire_old_buffer(req, 0);
1083 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1084 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1085 mtx_lock(&malloc_mtx);
1088 * Insert stream header.
1090 bzero(&mtsh, sizeof(mtsh));
1091 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1092 mtsh.mtsh_maxcpus = MAXCPU;
1093 mtsh.mtsh_count = kmemcount;
1094 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1097 * Insert alternating sequence of type headers and type statistics.
1099 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1100 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1103 * Insert type header.
1105 bzero(&mth, sizeof(mth));
1106 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1107 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1110 * Insert type statistics for each CPU.
1112 for (i = 0; i < MAXCPU; i++) {
1113 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
1114 sizeof(mtip->mti_stats[i]));
1117 mtx_unlock(&malloc_mtx);
1118 error = sbuf_finish(&sbuf);
1123 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
1124 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1125 "Return malloc types");
1127 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1128 "Count of kernel malloc types");
1131 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1133 struct malloc_type *mtp, **bufmtp;
1137 mtx_lock(&malloc_mtx);
1139 mtx_assert(&malloc_mtx, MA_OWNED);
1141 mtx_unlock(&malloc_mtx);
1143 buflen = sizeof(struct malloc_type *) * count;
1144 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1146 mtx_lock(&malloc_mtx);
1148 if (count < kmemcount) {
1149 free(bufmtp, M_TEMP);
1153 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1156 mtx_unlock(&malloc_mtx);
1158 for (i = 0; i < count; i++)
1159 (func)(bufmtp[i], arg);
1161 free(bufmtp, M_TEMP);
1165 DB_SHOW_COMMAND(malloc, db_show_malloc)
1167 struct malloc_type_internal *mtip;
1168 struct malloc_type *mtp;
1169 uint64_t allocs, frees;
1170 uint64_t alloced, freed;
1173 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1175 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1176 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1181 for (i = 0; i < MAXCPU; i++) {
1182 allocs += mtip->mti_stats[i].mts_numallocs;
1183 frees += mtip->mti_stats[i].mts_numfrees;
1184 alloced += mtip->mti_stats[i].mts_memalloced;
1185 freed += mtip->mti_stats[i].mts_memfreed;
1187 db_printf("%18s %12ju %12juK %12ju\n",
1188 mtp->ks_shortdesc, allocs - frees,
1189 (alloced - freed + 1023) / 1024, allocs);
1195 #if MALLOC_DEBUG_MAXZONES > 1
1196 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1198 struct malloc_type_internal *mtip;
1199 struct malloc_type *mtp;
1203 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1207 if (mtp->ks_magic != M_MAGIC) {
1208 db_printf("Magic %lx does not match expected %x\n",
1209 mtp->ks_magic, M_MAGIC);
1213 mtip = mtp->ks_handle;
1214 subzone = mtip->mti_zone;
1216 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1217 mtip = mtp->ks_handle;
1218 if (mtip->mti_zone != subzone)
1220 db_printf("%s\n", mtp->ks_shortdesc);
1225 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1228 #ifdef MALLOC_PROFILE
1231 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1245 error = sysctl_wire_old_buffer(req, 0);
1248 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1250 "\n Size Requests Real Size\n");
1251 for (i = 0; i < KMEM_ZSIZE; i++) {
1252 size = i << KMEM_ZSHIFT;
1253 rsize = kmemzones[kmemsize[i]].kz_size;
1254 count = (long long unsigned)krequests[i];
1256 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1257 (unsigned long long)count, rsize);
1259 if ((rsize * count) > (size * count))
1260 waste += (rsize * count) - (size * count);
1261 mem += (rsize * count);
1264 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1265 (unsigned long long)mem, (unsigned long long)waste);
1266 error = sbuf_finish(&sbuf);
1271 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1272 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1273 #endif /* MALLOC_PROFILE */