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
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94
37 * Kernel malloc(9) implementation -- general purpose kernel memory allocator
38 * based on memory types. Back end is implemented using the UMA(9) zone
39 * allocator. A set of fixed-size buckets are used for smaller allocations,
40 * and a special UMA allocation interface is used for larger allocations.
41 * Callers declare memory types, and statistics are maintained independently
42 * for each memory type. Statistics are maintained per-CPU for performance
43 * reasons. See malloc(9) and comments in malloc.h for a detailed
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
53 #include <sys/param.h>
54 #include <sys/systm.h>
56 #include <sys/kernel.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/vmmeter.h>
63 #include <sys/sysctl.h>
69 #include <vm/vm_pageout.h>
70 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_extern.h>
73 #include <vm/vm_map.h>
74 #include <vm/vm_page.h>
76 #include <vm/uma_int.h>
77 #include <vm/uma_dbg.h>
80 #include <vm/memguard.h>
83 #include <vm/redzone.h>
86 #if defined(INVARIANTS) && defined(__i386__)
87 #include <machine/cpu.h>
93 #include <sys/dtrace_bsd.h>
95 dtrace_malloc_probe_func_t dtrace_malloc_probe;
99 * When realloc() is called, if the new size is sufficiently smaller than
100 * the old size, realloc() will allocate a new, smaller block to avoid
101 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
102 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
104 #ifndef REALLOC_FRACTION
105 #define REALLOC_FRACTION 1 /* new block if <= half the size */
109 * Centrally define some common malloc types.
111 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
112 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
113 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
115 static struct malloc_type *kmemstatistics;
116 static int kmemcount;
118 #define KMEM_ZSHIFT 4
119 #define KMEM_ZBASE 16
120 #define KMEM_ZMASK (KMEM_ZBASE - 1)
122 #define KMEM_ZMAX 65536
123 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
124 static uint8_t kmemsize[KMEM_ZSIZE + 1];
126 #ifndef MALLOC_DEBUG_MAXZONES
127 #define MALLOC_DEBUG_MAXZONES 1
129 static int numzones = MALLOC_DEBUG_MAXZONES;
132 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
135 * XXX: The comment here used to read "These won't be powers of two for
136 * long." It's possible that a significant amount of wasted memory could be
137 * recovered by tuning the sizes of these buckets.
142 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
161 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
162 * types are described by a data structure passed by the declaring code, but
163 * the malloc(9) implementation has its own data structure describing the
164 * type and statistics. This permits the malloc(9)-internal data structures
165 * to be modified without breaking binary-compiled kernel modules that
166 * declare malloc types.
168 static uma_zone_t mt_zone;
171 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
172 "Size of kernel memory");
174 static u_long kmem_zmax = KMEM_ZMAX;
175 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
176 "Maximum allocation size that malloc(9) would use UMA as backend");
178 static u_long vm_kmem_size_min;
179 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
180 "Minimum size of kernel memory");
182 static u_long vm_kmem_size_max;
183 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
184 "Maximum size of kernel memory");
186 static u_int vm_kmem_size_scale;
187 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
188 "Scale factor for kernel memory size");
190 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
191 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
192 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
193 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
195 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
196 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
197 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
198 sysctl_kmem_map_free, "LU", "Free space in kmem");
201 * The malloc_mtx protects the kmemstatistics linked list.
203 struct mtx malloc_mtx;
205 #ifdef MALLOC_PROFILE
206 uint64_t krequests[KMEM_ZSIZE + 1];
208 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
211 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
214 * time_uptime of the last malloc(9) failure (induced or real).
216 static time_t t_malloc_fail;
218 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
219 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
220 "Kernel malloc debugging options");
224 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
225 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
227 #ifdef MALLOC_MAKE_FAILURES
228 static int malloc_failure_rate;
229 static int malloc_nowait_count;
230 static int malloc_failure_count;
231 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
232 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
233 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
234 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
238 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
243 return (sysctl_handle_long(oidp, &size, 0, req));
247 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
251 /* The sysctl is unsigned, implement as a saturation value. */
258 return (sysctl_handle_long(oidp, &size, 0, req));
262 * malloc(9) uma zone separation -- sub-page buffer overruns in one
263 * malloc type will affect only a subset of other malloc types.
265 #if MALLOC_DEBUG_MAXZONES > 1
267 tunable_set_numzones(void)
270 TUNABLE_INT_FETCH("debug.malloc.numzones",
273 /* Sanity check the number of malloc uma zones. */
276 if (numzones > MALLOC_DEBUG_MAXZONES)
277 numzones = MALLOC_DEBUG_MAXZONES;
279 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
280 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
281 &numzones, 0, "Number of malloc uma subzones");
284 * Any number that changes regularly is an okay choice for the
285 * offset. Build numbers are pretty good of you have them.
287 static u_int zone_offset = __FreeBSD_version;
288 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
289 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
290 &zone_offset, 0, "Separate malloc types by examining the "
291 "Nth character in the malloc type short description.");
294 mtp_get_subzone(const char *desc)
299 if (desc == NULL || (len = strlen(desc)) == 0)
301 val = desc[zone_offset % len];
302 return (val % numzones);
304 #elif MALLOC_DEBUG_MAXZONES == 0
305 #error "MALLOC_DEBUG_MAXZONES must be positive."
308 mtp_get_subzone(const char *desc)
313 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
316 malloc_last_fail(void)
319 return (time_uptime - t_malloc_fail);
323 * An allocation has succeeded -- update malloc type statistics for the
324 * amount of bucket size. Occurs within a critical section so that the
325 * thread isn't preempted and doesn't migrate while updating per-PCU
329 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
332 struct malloc_type_internal *mtip;
333 struct malloc_type_stats *mtsp;
336 mtip = mtp->ks_handle;
337 mtsp = &mtip->mti_stats[curcpu];
339 mtsp->mts_memalloced += size;
340 mtsp->mts_numallocs++;
343 mtsp->mts_size |= 1 << zindx;
346 if (dtrace_malloc_probe != NULL) {
347 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
349 (dtrace_malloc_probe)(probe_id,
350 (uintptr_t) mtp, (uintptr_t) mtip,
351 (uintptr_t) mtsp, size, zindx);
359 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
363 malloc_type_zone_allocated(mtp, size, -1);
367 * A free operation has occurred -- update malloc type statistics for the
368 * amount of the bucket size. Occurs within a critical section so that the
369 * thread isn't preempted and doesn't migrate while updating per-CPU
373 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
375 struct malloc_type_internal *mtip;
376 struct malloc_type_stats *mtsp;
379 mtip = mtp->ks_handle;
380 mtsp = &mtip->mti_stats[curcpu];
381 mtsp->mts_memfreed += size;
382 mtsp->mts_numfrees++;
385 if (dtrace_malloc_probe != NULL) {
386 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
388 (dtrace_malloc_probe)(probe_id,
389 (uintptr_t) mtp, (uintptr_t) mtip,
390 (uintptr_t) mtsp, size, 0);
400 * Allocate a block of physically contiguous memory.
402 * If M_NOWAIT is set, this routine will not block and return NULL if
403 * the allocation fails.
406 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
407 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
412 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
413 alignment, boundary, VM_MEMATTR_DEFAULT);
415 malloc_type_allocated(type, round_page(size));
422 * Free a block of memory allocated by contigmalloc.
424 * This routine may not block.
427 contigfree(void *addr, unsigned long size, struct malloc_type *type)
430 kmem_free(kernel_arena, (vm_offset_t)addr, size);
431 malloc_type_freed(type, round_page(size));
437 * Allocate a block of memory.
439 * If M_NOWAIT is set, this routine will not block and return NULL if
440 * the allocation fails.
443 malloc(unsigned long size, struct malloc_type *mtp, int flags)
446 struct malloc_type_internal *mtip;
449 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
450 unsigned long osize = size;
454 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
456 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
458 indx = flags & (M_WAITOK | M_NOWAIT);
459 if (indx != M_NOWAIT && indx != M_WAITOK) {
460 static struct timeval lasterr;
461 static int curerr, once;
462 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
463 printf("Bad malloc flags: %x\n", indx);
470 #ifdef MALLOC_MAKE_FAILURES
471 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
472 atomic_add_int(&malloc_nowait_count, 1);
473 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
474 atomic_add_int(&malloc_failure_count, 1);
475 t_malloc_fail = time_uptime;
480 if (flags & M_WAITOK)
481 KASSERT(curthread->td_intr_nesting_level == 0,
482 ("malloc(M_WAITOK) in interrupt context"));
483 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
484 ("malloc: called with spinlock or critical section held"));
486 #ifdef DEBUG_MEMGUARD
487 if (memguard_cmp_mtp(mtp, size)) {
488 va = memguard_alloc(size, flags);
491 /* This is unfortunate but should not be fatal. */
496 size = redzone_size_ntor(size);
499 if (size <= kmem_zmax) {
500 mtip = mtp->ks_handle;
501 if (size & KMEM_ZMASK)
502 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
503 indx = kmemsize[size >> KMEM_ZSHIFT];
504 KASSERT(mtip->mti_zone < numzones,
505 ("mti_zone %u out of range %d",
506 mtip->mti_zone, numzones));
507 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
508 #ifdef MALLOC_PROFILE
509 krequests[size >> KMEM_ZSHIFT]++;
511 va = uma_zalloc(zone, flags);
513 size = zone->uz_size;
514 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
516 size = roundup(size, PAGE_SIZE);
518 va = uma_large_malloc(size, flags);
519 malloc_type_allocated(mtp, va == NULL ? 0 : size);
521 if (flags & M_WAITOK)
522 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
524 t_malloc_fail = time_uptime;
526 if (va != NULL && !(flags & M_ZERO)) {
527 memset(va, 0x70, osize);
532 va = redzone_setup(va, osize);
534 return ((void *) va);
540 * Free a block of memory allocated by malloc.
542 * This routine may not block.
545 free(void *addr, struct malloc_type *mtp)
550 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
551 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
552 ("free: called with spinlock or critical section held"));
554 /* free(NULL, ...) does nothing */
558 #ifdef DEBUG_MEMGUARD
559 if (is_memguard_addr(addr)) {
567 addr = redzone_addr_ntor(addr);
570 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
573 panic("free: address %p(%p) has not been allocated.\n",
574 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
576 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
578 struct malloc_type **mtpp = addr;
580 size = slab->us_keg->uk_size;
583 * Cache a pointer to the malloc_type that most recently freed
584 * this memory here. This way we know who is most likely to
585 * have stepped on it later.
587 * This code assumes that size is a multiple of 8 bytes for
590 mtpp = (struct malloc_type **)
591 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
592 mtpp += (size - sizeof(struct malloc_type *)) /
593 sizeof(struct malloc_type *);
596 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
598 size = slab->us_size;
599 uma_large_free(slab);
601 malloc_type_freed(mtp, size);
605 * realloc: change the size of a memory block
608 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
614 KASSERT(mtp->ks_magic == M_MAGIC,
615 ("realloc: bad malloc type magic"));
616 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
617 ("realloc: called with spinlock or critical section held"));
619 /* realloc(NULL, ...) is equivalent to malloc(...) */
621 return (malloc(size, mtp, flags));
624 * XXX: Should report free of old memory and alloc of new memory to
628 #ifdef DEBUG_MEMGUARD
629 if (is_memguard_addr(addr))
630 return (memguard_realloc(addr, size, mtp, flags));
635 alloc = redzone_get_size(addr);
637 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
640 KASSERT(slab != NULL,
641 ("realloc: address %p out of range", (void *)addr));
643 /* Get the size of the original block */
644 if (!(slab->us_flags & UMA_SLAB_MALLOC))
645 alloc = slab->us_keg->uk_size;
647 alloc = slab->us_size;
649 /* Reuse the original block if appropriate */
651 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
653 #endif /* !DEBUG_REDZONE */
655 /* Allocate a new, bigger (or smaller) block */
656 if ((newaddr = malloc(size, mtp, flags)) == NULL)
659 /* Copy over original contents */
660 bcopy(addr, newaddr, min(size, alloc));
666 * reallocf: same as realloc() but free memory on failure.
669 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
673 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
679 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
683 * Initialize the kernel memory (kmem) arena.
692 if (vm_kmem_size == 0)
693 vm_kmem_size = VM_KMEM_SIZE;
695 #ifdef VM_KMEM_SIZE_MIN
696 if (vm_kmem_size_min == 0)
697 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
699 #ifdef VM_KMEM_SIZE_MAX
700 if (vm_kmem_size_max == 0)
701 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
704 * Calculate the amount of kernel virtual address (KVA) space that is
705 * preallocated to the kmem arena. In order to support a wide range
706 * of machines, it is a function of the physical memory size,
709 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
710 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
712 * Every architecture must define an integral value for
713 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
714 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
715 * ceiling on this preallocation, are optional. Typically,
716 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
717 * a given architecture.
719 mem_size = vm_cnt.v_page_count;
720 if (mem_size <= 32768) /* delphij XXX 128MB */
721 kmem_zmax = PAGE_SIZE;
723 if (vm_kmem_size_scale < 1)
724 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
727 * Check if we should use defaults for the "vm_kmem_size"
730 if (vm_kmem_size == 0) {
731 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
733 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
734 vm_kmem_size = vm_kmem_size_min;
735 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
736 vm_kmem_size = vm_kmem_size_max;
740 * The amount of KVA space that is preallocated to the
741 * kmem arena can be set statically at compile-time or manually
742 * through the kernel environment. However, it is still limited to
743 * twice the physical memory size, which has been sufficient to handle
744 * the most severe cases of external fragmentation in the kmem arena.
746 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
747 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
749 vm_kmem_size = round_page(vm_kmem_size);
750 #ifdef DEBUG_MEMGUARD
751 tmp = memguard_fudge(vm_kmem_size, kernel_map);
757 #ifdef DEBUG_MEMGUARD
759 * Initialize MemGuard if support compiled in. MemGuard is a
760 * replacement allocator used for detecting tamper-after-free
761 * scenarios as they occur. It is only used for debugging.
763 memguard_init(kernel_arena);
768 * Initialize the kernel memory allocator
772 mallocinit(void *dummy)
777 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
783 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
784 kmem_zmax = KMEM_ZMAX;
786 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
788 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
790 NULL, NULL, NULL, NULL,
792 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
793 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
794 int size = kmemzones[indx].kz_size;
795 char *name = kmemzones[indx].kz_name;
798 for (subzone = 0; subzone < numzones; subzone++) {
799 kmemzones[indx].kz_zone[subzone] =
800 uma_zcreate(name, size,
802 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
804 NULL, NULL, NULL, NULL,
806 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
808 for (;i <= size; i+= KMEM_ZBASE)
809 kmemsize[i >> KMEM_ZSHIFT] = indx;
813 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
816 malloc_init(void *data)
818 struct malloc_type_internal *mtip;
819 struct malloc_type *mtp;
821 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
824 if (mtp->ks_magic != M_MAGIC)
825 panic("malloc_init: bad malloc type magic");
827 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
828 mtp->ks_handle = mtip;
829 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
831 mtx_lock(&malloc_mtx);
832 mtp->ks_next = kmemstatistics;
833 kmemstatistics = mtp;
835 mtx_unlock(&malloc_mtx);
839 malloc_uninit(void *data)
841 struct malloc_type_internal *mtip;
842 struct malloc_type_stats *mtsp;
843 struct malloc_type *mtp, *temp;
845 long temp_allocs, temp_bytes;
849 KASSERT(mtp->ks_magic == M_MAGIC,
850 ("malloc_uninit: bad malloc type magic"));
851 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
853 mtx_lock(&malloc_mtx);
854 mtip = mtp->ks_handle;
855 mtp->ks_handle = NULL;
856 if (mtp != kmemstatistics) {
857 for (temp = kmemstatistics; temp != NULL;
858 temp = temp->ks_next) {
859 if (temp->ks_next == mtp) {
860 temp->ks_next = mtp->ks_next;
865 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
867 kmemstatistics = mtp->ks_next;
869 mtx_unlock(&malloc_mtx);
872 * Look for memory leaks.
874 temp_allocs = temp_bytes = 0;
875 for (i = 0; i < MAXCPU; i++) {
876 mtsp = &mtip->mti_stats[i];
877 temp_allocs += mtsp->mts_numallocs;
878 temp_allocs -= mtsp->mts_numfrees;
879 temp_bytes += mtsp->mts_memalloced;
880 temp_bytes -= mtsp->mts_memfreed;
882 if (temp_allocs > 0 || temp_bytes > 0) {
883 printf("Warning: memory type %s leaked memory on destroy "
884 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
885 temp_allocs, temp_bytes);
888 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
889 uma_zfree_arg(mt_zone, mtip, slab);
893 malloc_desc2type(const char *desc)
895 struct malloc_type *mtp;
897 mtx_assert(&malloc_mtx, MA_OWNED);
898 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
899 if (strcmp(mtp->ks_shortdesc, desc) == 0)
906 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
908 struct malloc_type_stream_header mtsh;
909 struct malloc_type_internal *mtip;
910 struct malloc_type_header mth;
911 struct malloc_type *mtp;
915 error = sysctl_wire_old_buffer(req, 0);
918 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
919 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
920 mtx_lock(&malloc_mtx);
923 * Insert stream header.
925 bzero(&mtsh, sizeof(mtsh));
926 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
927 mtsh.mtsh_maxcpus = MAXCPU;
928 mtsh.mtsh_count = kmemcount;
929 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
932 * Insert alternating sequence of type headers and type statistics.
934 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
935 mtip = (struct malloc_type_internal *)mtp->ks_handle;
938 * Insert type header.
940 bzero(&mth, sizeof(mth));
941 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
942 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
945 * Insert type statistics for each CPU.
947 for (i = 0; i < MAXCPU; i++) {
948 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
949 sizeof(mtip->mti_stats[i]));
952 mtx_unlock(&malloc_mtx);
953 error = sbuf_finish(&sbuf);
958 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
959 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
960 "Return malloc types");
962 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
963 "Count of kernel malloc types");
966 malloc_type_list(malloc_type_list_func_t *func, void *arg)
968 struct malloc_type *mtp, **bufmtp;
972 mtx_lock(&malloc_mtx);
974 mtx_assert(&malloc_mtx, MA_OWNED);
976 mtx_unlock(&malloc_mtx);
978 buflen = sizeof(struct malloc_type *) * count;
979 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
981 mtx_lock(&malloc_mtx);
983 if (count < kmemcount) {
984 free(bufmtp, M_TEMP);
988 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
991 mtx_unlock(&malloc_mtx);
993 for (i = 0; i < count; i++)
994 (func)(bufmtp[i], arg);
996 free(bufmtp, M_TEMP);
1000 DB_SHOW_COMMAND(malloc, db_show_malloc)
1002 struct malloc_type_internal *mtip;
1003 struct malloc_type *mtp;
1004 uint64_t allocs, frees;
1005 uint64_t alloced, freed;
1008 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1010 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1011 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1016 for (i = 0; i < MAXCPU; i++) {
1017 allocs += mtip->mti_stats[i].mts_numallocs;
1018 frees += mtip->mti_stats[i].mts_numfrees;
1019 alloced += mtip->mti_stats[i].mts_memalloced;
1020 freed += mtip->mti_stats[i].mts_memfreed;
1022 db_printf("%18s %12ju %12juK %12ju\n",
1023 mtp->ks_shortdesc, allocs - frees,
1024 (alloced - freed + 1023) / 1024, allocs);
1030 #if MALLOC_DEBUG_MAXZONES > 1
1031 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1033 struct malloc_type_internal *mtip;
1034 struct malloc_type *mtp;
1038 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1042 if (mtp->ks_magic != M_MAGIC) {
1043 db_printf("Magic %lx does not match expected %x\n",
1044 mtp->ks_magic, M_MAGIC);
1048 mtip = mtp->ks_handle;
1049 subzone = mtip->mti_zone;
1051 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1052 mtip = mtp->ks_handle;
1053 if (mtip->mti_zone != subzone)
1055 db_printf("%s\n", mtp->ks_shortdesc);
1060 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1063 #ifdef MALLOC_PROFILE
1066 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1080 error = sysctl_wire_old_buffer(req, 0);
1083 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1085 "\n Size Requests Real Size\n");
1086 for (i = 0; i < KMEM_ZSIZE; i++) {
1087 size = i << KMEM_ZSHIFT;
1088 rsize = kmemzones[kmemsize[i]].kz_size;
1089 count = (long long unsigned)krequests[i];
1091 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1092 (unsigned long long)count, rsize);
1094 if ((rsize * count) > (size * count))
1095 waste += (rsize * count) - (size * count);
1096 mem += (rsize * count);
1099 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1100 (unsigned long long)mem, (unsigned long long)waste);
1101 error = sbuf_finish(&sbuf);
1106 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1107 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1108 #endif /* MALLOC_PROFILE */