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>
68 #include <vm/vm_param.h>
69 #include <vm/vm_kern.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_page.h>
74 #include <vm/uma_int.h>
75 #include <vm/uma_dbg.h>
78 #include <vm/memguard.h>
81 #include <vm/redzone.h>
84 #if defined(INVARIANTS) && defined(__i386__)
85 #include <machine/cpu.h>
91 #include <sys/dtrace_bsd.h>
93 dtrace_malloc_probe_func_t dtrace_malloc_probe;
97 * When realloc() is called, if the new size is sufficiently smaller than
98 * the old size, realloc() will allocate a new, smaller block to avoid
99 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
100 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
102 #ifndef REALLOC_FRACTION
103 #define REALLOC_FRACTION 1 /* new block if <= half the size */
107 * Centrally define some common malloc types.
109 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
110 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
111 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
113 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
114 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
116 static void kmeminit(void *);
117 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL);
119 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
121 static struct malloc_type *kmemstatistics;
122 static vm_offset_t kmembase;
123 static vm_offset_t kmemlimit;
124 static int kmemcount;
126 #define KMEM_ZSHIFT 4
127 #define KMEM_ZBASE 16
128 #define KMEM_ZMASK (KMEM_ZBASE - 1)
130 #define KMEM_ZMAX PAGE_SIZE
131 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
132 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
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.
153 {1024, "1024", NULL},
154 {2048, "2048", NULL},
155 {4096, "4096", NULL},
157 {8192, "8192", NULL},
159 {16384, "16384", NULL},
160 #if PAGE_SIZE > 16384
161 {32768, "32768", NULL},
162 #if PAGE_SIZE > 32768
163 {65536, "65536", NULL},
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_map 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", "Largest contiguous free range in kmem_map");
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;
229 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
230 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
232 #ifdef MALLOC_MAKE_FAILURES
233 SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
234 "Kernel malloc debugging options");
236 static int malloc_failure_rate;
237 static int malloc_nowait_count;
238 static int malloc_failure_count;
239 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
240 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
241 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
242 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
243 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
247 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
251 size = kmem_map->size;
252 return (sysctl_handle_long(oidp, &size, 0, req));
256 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
260 vm_map_lock_read(kmem_map);
261 size = kmem_map->root != NULL ?
262 kmem_map->root->max_free : kmem_map->size;
263 vm_map_unlock_read(kmem_map);
264 return (sysctl_handle_long(oidp, &size, 0, req));
268 malloc_last_fail(void)
271 return (time_uptime - t_malloc_fail);
275 * An allocation has succeeded -- update malloc type statistics for the
276 * amount of bucket size. Occurs within a critical section so that the
277 * thread isn't preempted and doesn't migrate while updating per-PCU
281 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
284 struct malloc_type_internal *mtip;
285 struct malloc_type_stats *mtsp;
288 mtip = mtp->ks_handle;
289 mtsp = &mtip->mti_stats[curcpu];
291 mtsp->mts_memalloced += size;
292 mtsp->mts_numallocs++;
295 mtsp->mts_size |= 1 << zindx;
298 if (dtrace_malloc_probe != NULL) {
299 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
301 (dtrace_malloc_probe)(probe_id,
302 (uintptr_t) mtp, (uintptr_t) mtip,
303 (uintptr_t) mtsp, size, zindx);
311 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
315 malloc_type_zone_allocated(mtp, size, -1);
319 * A free operation has occurred -- update malloc type statistics for the
320 * amount of the bucket size. Occurs within a critical section so that the
321 * thread isn't preempted and doesn't migrate while updating per-CPU
325 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
327 struct malloc_type_internal *mtip;
328 struct malloc_type_stats *mtsp;
331 mtip = mtp->ks_handle;
332 mtsp = &mtip->mti_stats[curcpu];
333 mtsp->mts_memfreed += size;
334 mtsp->mts_numfrees++;
337 if (dtrace_malloc_probe != NULL) {
338 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
340 (dtrace_malloc_probe)(probe_id,
341 (uintptr_t) mtp, (uintptr_t) mtip,
342 (uintptr_t) mtsp, size, 0);
352 * Allocate a block of memory.
354 * If M_NOWAIT is set, this routine will not block and return NULL if
355 * the allocation fails.
358 malloc(unsigned long size, struct malloc_type *mtp, int flags)
363 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
364 unsigned long osize = size;
368 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
370 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
372 indx = flags & (M_WAITOK | M_NOWAIT);
373 if (indx != M_NOWAIT && indx != M_WAITOK) {
374 static struct timeval lasterr;
375 static int curerr, once;
376 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
377 printf("Bad malloc flags: %x\n", indx);
384 #ifdef MALLOC_MAKE_FAILURES
385 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
386 atomic_add_int(&malloc_nowait_count, 1);
387 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
388 atomic_add_int(&malloc_failure_count, 1);
389 t_malloc_fail = time_uptime;
394 if (flags & M_WAITOK)
395 KASSERT(curthread->td_intr_nesting_level == 0,
396 ("malloc(M_WAITOK) in interrupt context"));
398 #ifdef DEBUG_MEMGUARD
399 if (memguard_cmp(mtp, size)) {
400 va = memguard_alloc(size, flags);
403 /* This is unfortunate but should not be fatal. */
408 size = redzone_size_ntor(size);
411 if (size <= KMEM_ZMAX) {
412 if (size & KMEM_ZMASK)
413 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
414 indx = kmemsize[size >> KMEM_ZSHIFT];
415 zone = kmemzones[indx].kz_zone;
416 #ifdef MALLOC_PROFILE
417 krequests[size >> KMEM_ZSHIFT]++;
419 va = uma_zalloc(zone, flags);
421 size = zone->uz_size;
422 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
424 size = roundup(size, PAGE_SIZE);
426 va = uma_large_malloc(size, flags);
427 malloc_type_allocated(mtp, va == NULL ? 0 : size);
429 if (flags & M_WAITOK)
430 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
432 t_malloc_fail = time_uptime;
434 if (va != NULL && !(flags & M_ZERO)) {
435 memset(va, 0x70, osize);
440 va = redzone_setup(va, osize);
442 return ((void *) va);
448 * Free a block of memory allocated by malloc.
450 * This routine may not block.
453 free(void *addr, struct malloc_type *mtp)
458 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
460 /* free(NULL, ...) does nothing */
464 #ifdef DEBUG_MEMGUARD
465 if (is_memguard_addr(addr)) {
473 addr = redzone_addr_ntor(addr);
476 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
479 panic("free: address %p(%p) has not been allocated.\n",
480 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
483 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
485 struct malloc_type **mtpp = addr;
487 size = slab->us_keg->uk_size;
490 * Cache a pointer to the malloc_type that most recently freed
491 * this memory here. This way we know who is most likely to
492 * have stepped on it later.
494 * This code assumes that size is a multiple of 8 bytes for
497 mtpp = (struct malloc_type **)
498 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
499 mtpp += (size - sizeof(struct malloc_type *)) /
500 sizeof(struct malloc_type *);
503 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
505 size = slab->us_size;
506 uma_large_free(slab);
508 malloc_type_freed(mtp, size);
512 * realloc: change the size of a memory block
515 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
521 KASSERT(mtp->ks_magic == M_MAGIC,
522 ("realloc: bad malloc type magic"));
524 /* realloc(NULL, ...) is equivalent to malloc(...) */
526 return (malloc(size, mtp, flags));
529 * XXX: Should report free of old memory and alloc of new memory to
533 #ifdef DEBUG_MEMGUARD
534 if (is_memguard_addr(addr))
535 return (memguard_realloc(addr, size, mtp, flags));
540 alloc = redzone_get_size(addr);
542 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
545 KASSERT(slab != NULL,
546 ("realloc: address %p out of range", (void *)addr));
548 /* Get the size of the original block */
549 if (!(slab->us_flags & UMA_SLAB_MALLOC))
550 alloc = slab->us_keg->uk_size;
552 alloc = slab->us_size;
554 /* Reuse the original block if appropriate */
556 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
558 #endif /* !DEBUG_REDZONE */
560 /* Allocate a new, bigger (or smaller) block */
561 if ((newaddr = malloc(size, mtp, flags)) == NULL)
564 /* Copy over original contents */
565 bcopy(addr, newaddr, min(size, alloc));
571 * reallocf: same as realloc() but free memory on failure.
574 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
578 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
584 * Initialize the kernel memory allocator
588 kmeminit(void *dummy)
591 u_long mem_size, tmp;
594 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
597 * Try to auto-tune the kernel memory size, so that it is
598 * more applicable for a wider range of machine sizes.
599 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
600 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
601 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
602 * available, and on an X86 with a total KVA space of 256MB,
603 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
605 * Note that the kmem_map is also used by the zone allocator,
606 * so make sure that there is enough space.
608 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
609 mem_size = cnt.v_page_count;
611 #if defined(VM_KMEM_SIZE_SCALE)
612 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
614 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
615 if (vm_kmem_size_scale > 0 &&
616 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
617 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
619 #if defined(VM_KMEM_SIZE_MIN)
620 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
622 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
623 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
624 vm_kmem_size = vm_kmem_size_min;
627 #if defined(VM_KMEM_SIZE_MAX)
628 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
630 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
631 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
632 vm_kmem_size = vm_kmem_size_max;
634 /* Allow final override from the kernel environment */
635 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
638 * Limit kmem virtual size to twice the physical memory.
639 * This allows for kmem map sparseness, but limits the size
640 * to something sane. Be careful to not overflow the 32bit
641 * ints while doing the check.
643 if (((vm_kmem_size / 2) / PAGE_SIZE) > cnt.v_page_count)
644 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
647 * Tune settings based on the kmem map's size at this time.
649 init_param3(vm_kmem_size / PAGE_SIZE);
651 #ifdef DEBUG_MEMGUARD
652 tmp = memguard_fudge(vm_kmem_size, vm_kmem_size_max);
656 kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
658 kmem_map->system_map = 1;
660 #ifdef DEBUG_MEMGUARD
662 * Initialize MemGuard if support compiled in. MemGuard is a
663 * replacement allocator used for detecting tamper-after-free
664 * scenarios as they occur. It is only used for debugging.
666 memguard_init(kmem_map);
671 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
673 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
675 NULL, NULL, NULL, NULL,
677 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
678 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
679 int size = kmemzones[indx].kz_size;
680 char *name = kmemzones[indx].kz_name;
682 kmemzones[indx].kz_zone = uma_zcreate(name, size,
684 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
686 NULL, NULL, NULL, NULL,
688 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
690 for (;i <= size; i+= KMEM_ZBASE)
691 kmemsize[i >> KMEM_ZSHIFT] = indx;
697 malloc_init(void *data)
699 struct malloc_type_internal *mtip;
700 struct malloc_type *mtp;
702 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
705 if (mtp->ks_magic != M_MAGIC)
706 panic("malloc_init: bad malloc type magic");
708 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
709 mtp->ks_handle = mtip;
711 mtx_lock(&malloc_mtx);
712 mtp->ks_next = kmemstatistics;
713 kmemstatistics = mtp;
715 mtx_unlock(&malloc_mtx);
719 malloc_uninit(void *data)
721 struct malloc_type_internal *mtip;
722 struct malloc_type_stats *mtsp;
723 struct malloc_type *mtp, *temp;
725 long temp_allocs, temp_bytes;
729 KASSERT(mtp->ks_magic == M_MAGIC,
730 ("malloc_uninit: bad malloc type magic"));
731 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
733 mtx_lock(&malloc_mtx);
734 mtip = mtp->ks_handle;
735 mtp->ks_handle = NULL;
736 if (mtp != kmemstatistics) {
737 for (temp = kmemstatistics; temp != NULL;
738 temp = temp->ks_next) {
739 if (temp->ks_next == mtp) {
740 temp->ks_next = mtp->ks_next;
745 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
747 kmemstatistics = mtp->ks_next;
749 mtx_unlock(&malloc_mtx);
752 * Look for memory leaks.
754 temp_allocs = temp_bytes = 0;
755 for (i = 0; i < MAXCPU; i++) {
756 mtsp = &mtip->mti_stats[i];
757 temp_allocs += mtsp->mts_numallocs;
758 temp_allocs -= mtsp->mts_numfrees;
759 temp_bytes += mtsp->mts_memalloced;
760 temp_bytes -= mtsp->mts_memfreed;
762 if (temp_allocs > 0 || temp_bytes > 0) {
763 printf("Warning: memory type %s leaked memory on destroy "
764 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
765 temp_allocs, temp_bytes);
768 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
769 uma_zfree_arg(mt_zone, mtip, slab);
773 malloc_desc2type(const char *desc)
775 struct malloc_type *mtp;
777 mtx_assert(&malloc_mtx, MA_OWNED);
778 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
779 if (strcmp(mtp->ks_shortdesc, desc) == 0)
786 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
788 struct malloc_type_stream_header mtsh;
789 struct malloc_type_internal *mtip;
790 struct malloc_type_header mth;
791 struct malloc_type *mtp;
792 int buflen, count, error, i;
796 mtx_lock(&malloc_mtx);
798 mtx_assert(&malloc_mtx, MA_OWNED);
800 mtx_unlock(&malloc_mtx);
801 buflen = sizeof(mtsh) + count * (sizeof(mth) +
802 sizeof(struct malloc_type_stats) * MAXCPU) + 1;
803 buffer = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
804 mtx_lock(&malloc_mtx);
805 if (count < kmemcount) {
806 free(buffer, M_TEMP);
810 sbuf_new(&sbuf, buffer, buflen, SBUF_FIXEDLEN);
813 * Insert stream header.
815 bzero(&mtsh, sizeof(mtsh));
816 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
817 mtsh.mtsh_maxcpus = MAXCPU;
818 mtsh.mtsh_count = kmemcount;
819 if (sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh)) < 0) {
820 mtx_unlock(&malloc_mtx);
826 * Insert alternating sequence of type headers and type statistics.
828 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
829 mtip = (struct malloc_type_internal *)mtp->ks_handle;
832 * Insert type header.
834 bzero(&mth, sizeof(mth));
835 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
836 if (sbuf_bcat(&sbuf, &mth, sizeof(mth)) < 0) {
837 mtx_unlock(&malloc_mtx);
843 * Insert type statistics for each CPU.
845 for (i = 0; i < MAXCPU; i++) {
846 if (sbuf_bcat(&sbuf, &mtip->mti_stats[i],
847 sizeof(mtip->mti_stats[i])) < 0) {
848 mtx_unlock(&malloc_mtx);
854 mtx_unlock(&malloc_mtx);
856 error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
859 free(buffer, M_TEMP);
863 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
864 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
865 "Return malloc types");
867 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
868 "Count of kernel malloc types");
871 malloc_type_list(malloc_type_list_func_t *func, void *arg)
873 struct malloc_type *mtp, **bufmtp;
877 mtx_lock(&malloc_mtx);
879 mtx_assert(&malloc_mtx, MA_OWNED);
881 mtx_unlock(&malloc_mtx);
883 buflen = sizeof(struct malloc_type *) * count;
884 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
886 mtx_lock(&malloc_mtx);
888 if (count < kmemcount) {
889 free(bufmtp, M_TEMP);
893 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
896 mtx_unlock(&malloc_mtx);
898 for (i = 0; i < count; i++)
899 (func)(bufmtp[i], arg);
901 free(bufmtp, M_TEMP);
905 DB_SHOW_COMMAND(malloc, db_show_malloc)
907 struct malloc_type_internal *mtip;
908 struct malloc_type *mtp;
909 u_int64_t allocs, frees;
910 u_int64_t alloced, freed;
913 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
915 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
916 mtip = (struct malloc_type_internal *)mtp->ks_handle;
921 for (i = 0; i < MAXCPU; i++) {
922 allocs += mtip->mti_stats[i].mts_numallocs;
923 frees += mtip->mti_stats[i].mts_numfrees;
924 alloced += mtip->mti_stats[i].mts_memalloced;
925 freed += mtip->mti_stats[i].mts_memfreed;
927 db_printf("%18s %12ju %12juK %12ju\n",
928 mtp->ks_shortdesc, allocs - frees,
929 (alloced - freed + 1023) / 1024, allocs);
934 #ifdef MALLOC_PROFILE
937 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
951 bufsize = linesize * (KMEM_ZSIZE + 1);
952 bufsize += 128; /* For the stats line */
953 bufsize += 128; /* For the banner line */
957 buf = malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
958 sbuf_new(&sbuf, buf, bufsize, SBUF_FIXEDLEN);
960 "\n Size Requests Real Size\n");
961 for (i = 0; i < KMEM_ZSIZE; i++) {
962 size = i << KMEM_ZSHIFT;
963 rsize = kmemzones[kmemsize[i]].kz_size;
964 count = (long long unsigned)krequests[i];
966 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
967 (unsigned long long)count, rsize);
969 if ((rsize * count) > (size * count))
970 waste += (rsize * count) - (size * count);
971 mem += (rsize * count);
974 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
975 (unsigned long long)mem, (unsigned long long)waste);
978 error = SYSCTL_OUT(req, sbuf_data(&sbuf), sbuf_len(&sbuf));
985 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
986 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
987 #endif /* MALLOC_PROFILE */