2 * Copyright (c) 1987, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2005-2009 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94
35 * Kernel malloc(9) implementation -- general purpose kernel memory allocator
36 * based on memory types. Back end is implemented using the UMA(9) zone
37 * allocator. A set of fixed-size buckets are used for smaller allocations,
38 * and a special UMA allocation interface is used for larger allocations.
39 * Callers declare memory types, and statistics are maintained independently
40 * for each memory type. Statistics are maintained per-CPU for performance
41 * reasons. See malloc(9) and comments in malloc.h for a detailed
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
49 #include "opt_kdtrace.h"
52 #include <sys/param.h>
53 #include <sys/systm.h>
55 #include <sys/kernel.h>
57 #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 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
116 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
118 static struct malloc_type *kmemstatistics;
119 static int kmemcount;
121 #define KMEM_ZSHIFT 4
122 #define KMEM_ZBASE 16
123 #define KMEM_ZMASK (KMEM_ZBASE - 1)
125 #define KMEM_ZMAX PAGE_SIZE
126 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
127 static uint8_t kmemsize[KMEM_ZSIZE + 1];
129 #ifndef MALLOC_DEBUG_MAXZONES
130 #define MALLOC_DEBUG_MAXZONES 1
132 static int numzones = MALLOC_DEBUG_MAXZONES;
135 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
138 * XXX: The comment here used to read "These won't be powers of two for
139 * long." It's possible that a significant amount of wasted memory could be
140 * recovered by tuning the sizes of these buckets.
145 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
160 #if PAGE_SIZE > 16384
162 #if PAGE_SIZE > 32768
164 #if PAGE_SIZE > 65536
165 #error "Unsupported PAGE_SIZE"
175 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
176 * types are described by a data structure passed by the declaring code, but
177 * the malloc(9) implementation has its own data structure describing the
178 * type and statistics. This permits the malloc(9)-internal data structures
179 * to be modified without breaking binary-compiled kernel modules that
180 * declare malloc types.
182 static uma_zone_t mt_zone;
185 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
186 "Size of kernel memory");
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_RW,
242 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
243 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
244 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
245 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
249 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
253 size = vmem_size(kmem_arena, VMEM_ALLOC);
254 return (sysctl_handle_long(oidp, &size, 0, req));
258 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
262 size = vmem_size(kmem_arena, VMEM_FREE);
263 return (sysctl_handle_long(oidp, &size, 0, req));
267 * malloc(9) uma zone separation -- sub-page buffer overruns in one
268 * malloc type will affect only a subset of other malloc types.
270 #if MALLOC_DEBUG_MAXZONES > 1
272 tunable_set_numzones(void)
275 TUNABLE_INT_FETCH("debug.malloc.numzones",
278 /* Sanity check the number of malloc uma zones. */
281 if (numzones > MALLOC_DEBUG_MAXZONES)
282 numzones = MALLOC_DEBUG_MAXZONES;
284 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
285 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
286 &numzones, 0, "Number of malloc uma subzones");
289 * Any number that changes regularly is an okay choice for the
290 * offset. Build numbers are pretty good of you have them.
292 static u_int zone_offset = __FreeBSD_version;
293 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
294 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
295 &zone_offset, 0, "Separate malloc types by examining the "
296 "Nth character in the malloc type short description.");
299 mtp_get_subzone(const char *desc)
304 if (desc == NULL || (len = strlen(desc)) == 0)
306 val = desc[zone_offset % len];
307 return (val % numzones);
309 #elif MALLOC_DEBUG_MAXZONES == 0
310 #error "MALLOC_DEBUG_MAXZONES must be positive."
313 mtp_get_subzone(const char *desc)
318 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
321 malloc_last_fail(void)
324 return (time_uptime - t_malloc_fail);
328 * An allocation has succeeded -- update malloc type statistics for the
329 * amount of bucket size. Occurs within a critical section so that the
330 * thread isn't preempted and doesn't migrate while updating per-PCU
334 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
337 struct malloc_type_internal *mtip;
338 struct malloc_type_stats *mtsp;
341 mtip = mtp->ks_handle;
342 mtsp = &mtip->mti_stats[curcpu];
344 mtsp->mts_memalloced += size;
345 mtsp->mts_numallocs++;
348 mtsp->mts_size |= 1 << zindx;
351 if (dtrace_malloc_probe != NULL) {
352 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
354 (dtrace_malloc_probe)(probe_id,
355 (uintptr_t) mtp, (uintptr_t) mtip,
356 (uintptr_t) mtsp, size, zindx);
364 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
368 malloc_type_zone_allocated(mtp, size, -1);
372 * A free operation has occurred -- update malloc type statistics for the
373 * amount of the bucket size. Occurs within a critical section so that the
374 * thread isn't preempted and doesn't migrate while updating per-CPU
378 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
380 struct malloc_type_internal *mtip;
381 struct malloc_type_stats *mtsp;
384 mtip = mtp->ks_handle;
385 mtsp = &mtip->mti_stats[curcpu];
386 mtsp->mts_memfreed += size;
387 mtsp->mts_numfrees++;
390 if (dtrace_malloc_probe != NULL) {
391 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
393 (dtrace_malloc_probe)(probe_id,
394 (uintptr_t) mtp, (uintptr_t) mtip,
395 (uintptr_t) mtsp, size, 0);
405 * Allocate a block of physically contiguous memory.
407 * If M_NOWAIT is set, this routine will not block and return NULL if
408 * the allocation fails.
411 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
412 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
417 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
418 alignment, boundary, VM_MEMATTR_DEFAULT);
420 malloc_type_allocated(type, round_page(size));
427 * Free a block of memory allocated by contigmalloc.
429 * This routine may not block.
432 contigfree(void *addr, unsigned long size, struct malloc_type *type)
435 kmem_free(kernel_arena, (vm_offset_t)addr, size);
436 malloc_type_freed(type, round_page(size));
442 * Allocate a block of memory.
444 * If M_NOWAIT is set, this routine will not block and return NULL if
445 * the allocation fails.
448 malloc(unsigned long size, struct malloc_type *mtp, int flags)
451 struct malloc_type_internal *mtip;
454 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
455 unsigned long osize = size;
459 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
461 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
463 indx = flags & (M_WAITOK | M_NOWAIT);
464 if (indx != M_NOWAIT && indx != M_WAITOK) {
465 static struct timeval lasterr;
466 static int curerr, once;
467 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
468 printf("Bad malloc flags: %x\n", indx);
475 #ifdef MALLOC_MAKE_FAILURES
476 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
477 atomic_add_int(&malloc_nowait_count, 1);
478 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
479 atomic_add_int(&malloc_failure_count, 1);
480 t_malloc_fail = time_uptime;
485 if (flags & M_WAITOK)
486 KASSERT(curthread->td_intr_nesting_level == 0,
487 ("malloc(M_WAITOK) in interrupt context"));
489 #ifdef DEBUG_MEMGUARD
490 if (memguard_cmp_mtp(mtp, size)) {
491 va = memguard_alloc(size, flags);
494 /* This is unfortunate but should not be fatal. */
499 size = redzone_size_ntor(size);
502 if (size <= KMEM_ZMAX) {
503 mtip = mtp->ks_handle;
504 if (size & KMEM_ZMASK)
505 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
506 indx = kmemsize[size >> KMEM_ZSHIFT];
507 KASSERT(mtip->mti_zone < numzones,
508 ("mti_zone %u out of range %d",
509 mtip->mti_zone, numzones));
510 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
511 #ifdef MALLOC_PROFILE
512 krequests[size >> KMEM_ZSHIFT]++;
514 va = uma_zalloc(zone, flags);
516 size = zone->uz_size;
517 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
519 size = roundup(size, PAGE_SIZE);
521 va = uma_large_malloc(size, flags);
522 malloc_type_allocated(mtp, va == NULL ? 0 : size);
524 if (flags & M_WAITOK)
525 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
527 t_malloc_fail = time_uptime;
529 if (va != NULL && !(flags & M_ZERO)) {
530 memset(va, 0x70, osize);
535 va = redzone_setup(va, osize);
537 return ((void *) va);
543 * Free a block of memory allocated by malloc.
545 * This routine may not block.
548 free(void *addr, struct malloc_type *mtp)
553 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
555 /* free(NULL, ...) does nothing */
559 #ifdef DEBUG_MEMGUARD
560 if (is_memguard_addr(addr)) {
568 addr = redzone_addr_ntor(addr);
571 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
574 panic("free: address %p(%p) has not been allocated.\n",
575 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
577 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
579 struct malloc_type **mtpp = addr;
581 size = slab->us_keg->uk_size;
584 * Cache a pointer to the malloc_type that most recently freed
585 * this memory here. This way we know who is most likely to
586 * have stepped on it later.
588 * This code assumes that size is a multiple of 8 bytes for
591 mtpp = (struct malloc_type **)
592 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
593 mtpp += (size - sizeof(struct malloc_type *)) /
594 sizeof(struct malloc_type *);
597 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
599 size = slab->us_size;
600 uma_large_free(slab);
602 malloc_type_freed(mtp, size);
606 * realloc: change the size of a memory block
609 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
615 KASSERT(mtp->ks_magic == M_MAGIC,
616 ("realloc: bad malloc type magic"));
618 /* realloc(NULL, ...) is equivalent to malloc(...) */
620 return (malloc(size, mtp, flags));
623 * XXX: Should report free of old memory and alloc of new memory to
627 #ifdef DEBUG_MEMGUARD
628 if (is_memguard_addr(addr))
629 return (memguard_realloc(addr, size, mtp, flags));
634 alloc = redzone_get_size(addr);
636 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
639 KASSERT(slab != NULL,
640 ("realloc: address %p out of range", (void *)addr));
642 /* Get the size of the original block */
643 if (!(slab->us_flags & UMA_SLAB_MALLOC))
644 alloc = slab->us_keg->uk_size;
646 alloc = slab->us_size;
648 /* Reuse the original block if appropriate */
650 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
652 #endif /* !DEBUG_REDZONE */
654 /* Allocate a new, bigger (or smaller) block */
655 if ((newaddr = malloc(size, mtp, flags)) == NULL)
658 /* Copy over original contents */
659 bcopy(addr, newaddr, min(size, alloc));
665 * reallocf: same as realloc() but free memory on failure.
668 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
672 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
678 * Wake the page daemon when we exhaust KVA. It will call the lowmem handler
679 * and uma_reclaim() callbacks in a context that is safe.
682 kmem_reclaim(vmem_t *vm, int flags)
689 * Initialize the kernel memory arena.
694 u_long mem_size, tmp;
697 * Try to auto-tune the kernel memory size, so that it is
698 * more applicable for a wider range of machine sizes. The
699 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
702 * Note that the kmem_map is also used by the zone allocator,
703 * so make sure that there is enough space.
705 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
706 mem_size = cnt.v_page_count;
708 #if defined(VM_KMEM_SIZE_SCALE)
709 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
711 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
712 if (vm_kmem_size_scale > 0 &&
713 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
714 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
716 #if defined(VM_KMEM_SIZE_MIN)
717 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
719 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
720 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
721 vm_kmem_size = vm_kmem_size_min;
724 #if defined(VM_KMEM_SIZE_MAX)
725 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
727 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
728 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
729 vm_kmem_size = vm_kmem_size_max;
731 /* Allow final override from the kernel environment */
732 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
735 * Limit kmem virtual size to twice the physical memory.
736 * This allows for kmem map sparseness, but limits the size
737 * to something sane. Be careful to not overflow the 32bit
738 * ints while doing the check or the adjustment.
740 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
741 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
743 vm_kmem_size = round_page(vm_kmem_size);
744 #ifdef DEBUG_MEMGUARD
745 tmp = memguard_fudge(vm_kmem_size, kernel_map);
749 vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE,
751 vmem_set_reclaim(kmem_arena, kmem_reclaim);
753 #ifdef DEBUG_MEMGUARD
755 * Initialize MemGuard if support compiled in. MemGuard is a
756 * replacement allocator used for detecting tamper-after-free
757 * scenarios as they occur. It is only used for debugging.
759 memguard_init(kmem_arena);
764 * Initialize the kernel memory allocator
768 mallocinit(void *dummy)
773 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
779 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
781 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
783 NULL, NULL, NULL, NULL,
785 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
786 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
787 int size = kmemzones[indx].kz_size;
788 char *name = kmemzones[indx].kz_name;
791 for (subzone = 0; subzone < numzones; subzone++) {
792 kmemzones[indx].kz_zone[subzone] =
793 uma_zcreate(name, size,
795 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
797 NULL, NULL, NULL, NULL,
799 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
801 for (;i <= size; i+= KMEM_ZBASE)
802 kmemsize[i >> KMEM_ZSHIFT] = indx;
806 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, mallocinit, NULL);
809 malloc_init(void *data)
811 struct malloc_type_internal *mtip;
812 struct malloc_type *mtp;
814 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
817 if (mtp->ks_magic != M_MAGIC)
818 panic("malloc_init: bad malloc type magic");
820 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
821 mtp->ks_handle = mtip;
822 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
824 mtx_lock(&malloc_mtx);
825 mtp->ks_next = kmemstatistics;
826 kmemstatistics = mtp;
828 mtx_unlock(&malloc_mtx);
832 malloc_uninit(void *data)
834 struct malloc_type_internal *mtip;
835 struct malloc_type_stats *mtsp;
836 struct malloc_type *mtp, *temp;
838 long temp_allocs, temp_bytes;
842 KASSERT(mtp->ks_magic == M_MAGIC,
843 ("malloc_uninit: bad malloc type magic"));
844 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
846 mtx_lock(&malloc_mtx);
847 mtip = mtp->ks_handle;
848 mtp->ks_handle = NULL;
849 if (mtp != kmemstatistics) {
850 for (temp = kmemstatistics; temp != NULL;
851 temp = temp->ks_next) {
852 if (temp->ks_next == mtp) {
853 temp->ks_next = mtp->ks_next;
858 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
860 kmemstatistics = mtp->ks_next;
862 mtx_unlock(&malloc_mtx);
865 * Look for memory leaks.
867 temp_allocs = temp_bytes = 0;
868 for (i = 0; i < MAXCPU; i++) {
869 mtsp = &mtip->mti_stats[i];
870 temp_allocs += mtsp->mts_numallocs;
871 temp_allocs -= mtsp->mts_numfrees;
872 temp_bytes += mtsp->mts_memalloced;
873 temp_bytes -= mtsp->mts_memfreed;
875 if (temp_allocs > 0 || temp_bytes > 0) {
876 printf("Warning: memory type %s leaked memory on destroy "
877 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
878 temp_allocs, temp_bytes);
881 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
882 uma_zfree_arg(mt_zone, mtip, slab);
886 malloc_desc2type(const char *desc)
888 struct malloc_type *mtp;
890 mtx_assert(&malloc_mtx, MA_OWNED);
891 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
892 if (strcmp(mtp->ks_shortdesc, desc) == 0)
899 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
901 struct malloc_type_stream_header mtsh;
902 struct malloc_type_internal *mtip;
903 struct malloc_type_header mth;
904 struct malloc_type *mtp;
908 error = sysctl_wire_old_buffer(req, 0);
911 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
912 mtx_lock(&malloc_mtx);
915 * Insert stream header.
917 bzero(&mtsh, sizeof(mtsh));
918 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
919 mtsh.mtsh_maxcpus = MAXCPU;
920 mtsh.mtsh_count = kmemcount;
921 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
924 * Insert alternating sequence of type headers and type statistics.
926 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
927 mtip = (struct malloc_type_internal *)mtp->ks_handle;
930 * Insert type header.
932 bzero(&mth, sizeof(mth));
933 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
934 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
937 * Insert type statistics for each CPU.
939 for (i = 0; i < MAXCPU; i++) {
940 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
941 sizeof(mtip->mti_stats[i]));
944 mtx_unlock(&malloc_mtx);
945 error = sbuf_finish(&sbuf);
950 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
951 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
952 "Return malloc types");
954 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
955 "Count of kernel malloc types");
958 malloc_type_list(malloc_type_list_func_t *func, void *arg)
960 struct malloc_type *mtp, **bufmtp;
964 mtx_lock(&malloc_mtx);
966 mtx_assert(&malloc_mtx, MA_OWNED);
968 mtx_unlock(&malloc_mtx);
970 buflen = sizeof(struct malloc_type *) * count;
971 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
973 mtx_lock(&malloc_mtx);
975 if (count < kmemcount) {
976 free(bufmtp, M_TEMP);
980 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
983 mtx_unlock(&malloc_mtx);
985 for (i = 0; i < count; i++)
986 (func)(bufmtp[i], arg);
988 free(bufmtp, M_TEMP);
992 DB_SHOW_COMMAND(malloc, db_show_malloc)
994 struct malloc_type_internal *mtip;
995 struct malloc_type *mtp;
996 uint64_t allocs, frees;
997 uint64_t alloced, freed;
1000 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1002 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1003 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1008 for (i = 0; i < MAXCPU; i++) {
1009 allocs += mtip->mti_stats[i].mts_numallocs;
1010 frees += mtip->mti_stats[i].mts_numfrees;
1011 alloced += mtip->mti_stats[i].mts_memalloced;
1012 freed += mtip->mti_stats[i].mts_memfreed;
1014 db_printf("%18s %12ju %12juK %12ju\n",
1015 mtp->ks_shortdesc, allocs - frees,
1016 (alloced - freed + 1023) / 1024, allocs);
1022 #if MALLOC_DEBUG_MAXZONES > 1
1023 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1025 struct malloc_type_internal *mtip;
1026 struct malloc_type *mtp;
1030 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1034 if (mtp->ks_magic != M_MAGIC) {
1035 db_printf("Magic %lx does not match expected %x\n",
1036 mtp->ks_magic, M_MAGIC);
1040 mtip = mtp->ks_handle;
1041 subzone = mtip->mti_zone;
1043 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1044 mtip = mtp->ks_handle;
1045 if (mtip->mti_zone != subzone)
1047 db_printf("%s\n", mtp->ks_shortdesc);
1052 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1055 #ifdef MALLOC_PROFILE
1058 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1072 error = sysctl_wire_old_buffer(req, 0);
1075 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1077 "\n Size Requests Real Size\n");
1078 for (i = 0; i < KMEM_ZSIZE; i++) {
1079 size = i << KMEM_ZSHIFT;
1080 rsize = kmemzones[kmemsize[i]].kz_size;
1081 count = (long long unsigned)krequests[i];
1083 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1084 (unsigned long long)count, rsize);
1086 if ((rsize * count) > (size * count))
1087 waste += (rsize * count) - (size * count);
1088 mem += (rsize * count);
1091 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1092 (unsigned long long)mem, (unsigned long long)waste);
1093 error = sbuf_finish(&sbuf);
1098 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1099 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1100 #endif /* MALLOC_PROFILE */