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 struct malloc_type *kmemstatistics;
120 static vm_offset_t kmembase;
121 static vm_offset_t kmemlimit;
122 static int kmemcount;
124 #define KMEM_ZSHIFT 4
125 #define KMEM_ZBASE 16
126 #define KMEM_ZMASK (KMEM_ZBASE - 1)
128 #define KMEM_ZMAX PAGE_SIZE
129 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
130 static uint8_t kmemsize[KMEM_ZSIZE + 1];
132 #ifndef MALLOC_DEBUG_MAXZONES
133 #define MALLOC_DEBUG_MAXZONES 1
135 static int numzones = MALLOC_DEBUG_MAXZONES;
138 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
141 * XXX: The comment here used to read "These won't be powers of two for
142 * long." It's possible that a significant amount of wasted memory could be
143 * recovered by tuning the sizes of these buckets.
148 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
163 #if PAGE_SIZE > 16384
165 #if PAGE_SIZE > 32768
167 #if PAGE_SIZE > 65536
168 #error "Unsupported PAGE_SIZE"
178 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
179 * types are described by a data structure passed by the declaring code, but
180 * the malloc(9) implementation has its own data structure describing the
181 * type and statistics. This permits the malloc(9)-internal data structures
182 * to be modified without breaking binary-compiled kernel modules that
183 * declare malloc types.
185 static uma_zone_t mt_zone;
188 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
189 "Size of kernel memory");
191 static u_long vm_kmem_size_min;
192 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
193 "Minimum size of kernel memory");
195 static u_long vm_kmem_size_max;
196 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
197 "Maximum size of kernel memory");
199 static u_int vm_kmem_size_scale;
200 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
201 "Scale factor for kernel memory size");
203 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
204 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
205 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
206 sysctl_kmem_map_size, "LU", "Current kmem_map allocation size");
208 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
209 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
210 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
211 sysctl_kmem_map_free, "LU", "Largest contiguous free range in kmem_map");
214 * The malloc_mtx protects the kmemstatistics linked list.
216 struct mtx malloc_mtx;
218 #ifdef MALLOC_PROFILE
219 uint64_t krequests[KMEM_ZSIZE + 1];
221 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
224 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
227 * time_uptime of the last malloc(9) failure (induced or real).
229 static time_t t_malloc_fail;
231 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
232 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
233 "Kernel malloc debugging options");
237 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
238 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
240 #ifdef MALLOC_MAKE_FAILURES
241 static int malloc_failure_rate;
242 static int malloc_nowait_count;
243 static int malloc_failure_count;
244 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
245 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
246 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
247 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
248 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
252 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
256 size = kmem_map->size;
257 return (sysctl_handle_long(oidp, &size, 0, req));
261 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
265 vm_map_lock_read(kmem_map);
266 size = kmem_map->root != NULL ? kmem_map->root->max_free :
267 kmem_map->max_offset - kmem_map->min_offset;
268 vm_map_unlock_read(kmem_map);
269 return (sysctl_handle_long(oidp, &size, 0, req));
273 * malloc(9) uma zone separation -- sub-page buffer overruns in one
274 * malloc type will affect only a subset of other malloc types.
276 #if MALLOC_DEBUG_MAXZONES > 1
278 tunable_set_numzones(void)
281 TUNABLE_INT_FETCH("debug.malloc.numzones",
284 /* Sanity check the number of malloc uma zones. */
287 if (numzones > MALLOC_DEBUG_MAXZONES)
288 numzones = MALLOC_DEBUG_MAXZONES;
290 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
291 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
292 &numzones, 0, "Number of malloc uma subzones");
295 * Any number that changes regularly is an okay choice for the
296 * offset. Build numbers are pretty good of you have them.
298 static u_int zone_offset = __FreeBSD_version;
299 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
300 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
301 &zone_offset, 0, "Separate malloc types by examining the "
302 "Nth character in the malloc type short description.");
305 mtp_get_subzone(const char *desc)
310 if (desc == NULL || (len = strlen(desc)) == 0)
312 val = desc[zone_offset % len];
313 return (val % numzones);
315 #elif MALLOC_DEBUG_MAXZONES == 0
316 #error "MALLOC_DEBUG_MAXZONES must be positive."
319 mtp_get_subzone(const char *desc)
324 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
327 malloc_last_fail(void)
330 return (time_uptime - t_malloc_fail);
334 * An allocation has succeeded -- update malloc type statistics for the
335 * amount of bucket size. Occurs within a critical section so that the
336 * thread isn't preempted and doesn't migrate while updating per-PCU
340 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
343 struct malloc_type_internal *mtip;
344 struct malloc_type_stats *mtsp;
347 mtip = mtp->ks_handle;
348 mtsp = &mtip->mti_stats[curcpu];
350 mtsp->mts_memalloced += size;
351 mtsp->mts_numallocs++;
354 mtsp->mts_size |= 1 << zindx;
357 if (dtrace_malloc_probe != NULL) {
358 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
360 (dtrace_malloc_probe)(probe_id,
361 (uintptr_t) mtp, (uintptr_t) mtip,
362 (uintptr_t) mtsp, size, zindx);
370 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
374 malloc_type_zone_allocated(mtp, size, -1);
378 * A free operation has occurred -- update malloc type statistics for the
379 * amount of the bucket size. Occurs within a critical section so that the
380 * thread isn't preempted and doesn't migrate while updating per-CPU
384 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
386 struct malloc_type_internal *mtip;
387 struct malloc_type_stats *mtsp;
390 mtip = mtp->ks_handle;
391 mtsp = &mtip->mti_stats[curcpu];
392 mtsp->mts_memfreed += size;
393 mtsp->mts_numfrees++;
396 if (dtrace_malloc_probe != NULL) {
397 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
399 (dtrace_malloc_probe)(probe_id,
400 (uintptr_t) mtp, (uintptr_t) mtip,
401 (uintptr_t) mtsp, size, 0);
411 * Allocate a block of memory.
413 * If M_NOWAIT is set, this routine will not block and return NULL if
414 * the allocation fails.
417 malloc(unsigned long size, struct malloc_type *mtp, int flags)
420 struct malloc_type_internal *mtip;
423 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
424 unsigned long osize = size;
428 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
430 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
432 indx = flags & (M_WAITOK | M_NOWAIT);
433 if (indx != M_NOWAIT && indx != M_WAITOK) {
434 static struct timeval lasterr;
435 static int curerr, once;
436 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
437 printf("Bad malloc flags: %x\n", indx);
444 #ifdef MALLOC_MAKE_FAILURES
445 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
446 atomic_add_int(&malloc_nowait_count, 1);
447 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
448 atomic_add_int(&malloc_failure_count, 1);
449 t_malloc_fail = time_uptime;
454 if (flags & M_WAITOK)
455 KASSERT(curthread->td_intr_nesting_level == 0,
456 ("malloc(M_WAITOK) in interrupt context"));
458 #ifdef DEBUG_MEMGUARD
459 if (memguard_cmp(mtp, size)) {
460 va = memguard_alloc(size, flags);
463 /* This is unfortunate but should not be fatal. */
468 size = redzone_size_ntor(size);
471 if (size <= KMEM_ZMAX) {
472 mtip = mtp->ks_handle;
473 if (size & KMEM_ZMASK)
474 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
475 indx = kmemsize[size >> KMEM_ZSHIFT];
476 KASSERT(mtip->mti_zone < numzones,
477 ("mti_zone %u out of range %d",
478 mtip->mti_zone, numzones));
479 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
480 #ifdef MALLOC_PROFILE
481 krequests[size >> KMEM_ZSHIFT]++;
483 va = uma_zalloc(zone, flags);
485 size = zone->uz_size;
486 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
488 size = roundup(size, PAGE_SIZE);
490 va = uma_large_malloc(size, flags);
491 malloc_type_allocated(mtp, va == NULL ? 0 : size);
493 if (flags & M_WAITOK)
494 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
496 t_malloc_fail = time_uptime;
498 if (va != NULL && !(flags & M_ZERO)) {
499 memset(va, 0x70, osize);
504 va = redzone_setup(va, osize);
506 return ((void *) va);
512 * Free a block of memory allocated by malloc.
514 * This routine may not block.
517 free(void *addr, struct malloc_type *mtp)
522 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
524 /* free(NULL, ...) does nothing */
528 #ifdef DEBUG_MEMGUARD
529 if (is_memguard_addr(addr)) {
537 addr = redzone_addr_ntor(addr);
540 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
543 panic("free: address %p(%p) has not been allocated.\n",
544 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
547 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
549 struct malloc_type **mtpp = addr;
551 size = slab->us_keg->uk_size;
554 * Cache a pointer to the malloc_type that most recently freed
555 * this memory here. This way we know who is most likely to
556 * have stepped on it later.
558 * This code assumes that size is a multiple of 8 bytes for
561 mtpp = (struct malloc_type **)
562 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
563 mtpp += (size - sizeof(struct malloc_type *)) /
564 sizeof(struct malloc_type *);
567 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
569 size = slab->us_size;
570 uma_large_free(slab);
572 malloc_type_freed(mtp, size);
576 * realloc: change the size of a memory block
579 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
585 KASSERT(mtp->ks_magic == M_MAGIC,
586 ("realloc: bad malloc type magic"));
588 /* realloc(NULL, ...) is equivalent to malloc(...) */
590 return (malloc(size, mtp, flags));
593 * XXX: Should report free of old memory and alloc of new memory to
597 #ifdef DEBUG_MEMGUARD
598 if (is_memguard_addr(addr))
599 return (memguard_realloc(addr, size, mtp, flags));
604 alloc = redzone_get_size(addr);
606 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
609 KASSERT(slab != NULL,
610 ("realloc: address %p out of range", (void *)addr));
612 /* Get the size of the original block */
613 if (!(slab->us_flags & UMA_SLAB_MALLOC))
614 alloc = slab->us_keg->uk_size;
616 alloc = slab->us_size;
618 /* Reuse the original block if appropriate */
620 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
622 #endif /* !DEBUG_REDZONE */
624 /* Allocate a new, bigger (or smaller) block */
625 if ((newaddr = malloc(size, mtp, flags)) == NULL)
628 /* Copy over original contents */
629 bcopy(addr, newaddr, min(size, alloc));
635 * reallocf: same as realloc() but free memory on failure.
638 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
642 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
648 * Initialize the kernel memory allocator
652 kmeminit(void *dummy)
655 u_long mem_size, tmp;
658 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
661 * Try to auto-tune the kernel memory size, so that it is
662 * more applicable for a wider range of machine sizes. The
663 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
666 * Note that the kmem_map is also used by the zone allocator,
667 * so make sure that there is enough space.
669 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
670 mem_size = cnt.v_page_count;
672 #if defined(VM_KMEM_SIZE_SCALE)
673 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
675 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
676 if (vm_kmem_size_scale > 0 &&
677 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
678 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
680 #if defined(VM_KMEM_SIZE_MIN)
681 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
683 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
684 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
685 vm_kmem_size = vm_kmem_size_min;
688 #if defined(VM_KMEM_SIZE_MAX)
689 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
691 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
692 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
693 vm_kmem_size = vm_kmem_size_max;
695 /* Allow final override from the kernel environment */
696 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
699 * Limit kmem virtual size to twice the physical memory.
700 * This allows for kmem map sparseness, but limits the size
701 * to something sane. Be careful to not overflow the 32bit
702 * ints while doing the check or the adjustment.
704 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
705 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
707 #ifdef DEBUG_MEMGUARD
708 tmp = memguard_fudge(vm_kmem_size, kernel_map);
712 kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
714 kmem_map->system_map = 1;
716 #ifdef DEBUG_MEMGUARD
718 * Initialize MemGuard if support compiled in. MemGuard is a
719 * replacement allocator used for detecting tamper-after-free
720 * scenarios as they occur. It is only used for debugging.
722 memguard_init(kmem_map);
727 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
729 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
731 NULL, NULL, NULL, NULL,
733 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
734 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
735 int size = kmemzones[indx].kz_size;
736 char *name = kmemzones[indx].kz_name;
739 for (subzone = 0; subzone < numzones; subzone++) {
740 kmemzones[indx].kz_zone[subzone] =
741 uma_zcreate(name, size,
743 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
745 NULL, NULL, NULL, NULL,
747 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
749 for (;i <= size; i+= KMEM_ZBASE)
750 kmemsize[i >> KMEM_ZSHIFT] = indx;
756 malloc_init(void *data)
758 struct malloc_type_internal *mtip;
759 struct malloc_type *mtp;
761 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
764 if (mtp->ks_magic != M_MAGIC)
765 panic("malloc_init: bad malloc type magic");
767 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
768 mtp->ks_handle = mtip;
769 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
771 mtx_lock(&malloc_mtx);
772 mtp->ks_next = kmemstatistics;
773 kmemstatistics = mtp;
775 mtx_unlock(&malloc_mtx);
779 malloc_uninit(void *data)
781 struct malloc_type_internal *mtip;
782 struct malloc_type_stats *mtsp;
783 struct malloc_type *mtp, *temp;
785 long temp_allocs, temp_bytes;
789 KASSERT(mtp->ks_magic == M_MAGIC,
790 ("malloc_uninit: bad malloc type magic"));
791 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
793 mtx_lock(&malloc_mtx);
794 mtip = mtp->ks_handle;
795 mtp->ks_handle = NULL;
796 if (mtp != kmemstatistics) {
797 for (temp = kmemstatistics; temp != NULL;
798 temp = temp->ks_next) {
799 if (temp->ks_next == mtp) {
800 temp->ks_next = mtp->ks_next;
805 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
807 kmemstatistics = mtp->ks_next;
809 mtx_unlock(&malloc_mtx);
812 * Look for memory leaks.
814 temp_allocs = temp_bytes = 0;
815 for (i = 0; i < MAXCPU; i++) {
816 mtsp = &mtip->mti_stats[i];
817 temp_allocs += mtsp->mts_numallocs;
818 temp_allocs -= mtsp->mts_numfrees;
819 temp_bytes += mtsp->mts_memalloced;
820 temp_bytes -= mtsp->mts_memfreed;
822 if (temp_allocs > 0 || temp_bytes > 0) {
823 printf("Warning: memory type %s leaked memory on destroy "
824 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
825 temp_allocs, temp_bytes);
828 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
829 uma_zfree_arg(mt_zone, mtip, slab);
833 malloc_desc2type(const char *desc)
835 struct malloc_type *mtp;
837 mtx_assert(&malloc_mtx, MA_OWNED);
838 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
839 if (strcmp(mtp->ks_shortdesc, desc) == 0)
846 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
848 struct malloc_type_stream_header mtsh;
849 struct malloc_type_internal *mtip;
850 struct malloc_type_header mth;
851 struct malloc_type *mtp;
855 error = sysctl_wire_old_buffer(req, 0);
858 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
859 mtx_lock(&malloc_mtx);
862 * Insert stream header.
864 bzero(&mtsh, sizeof(mtsh));
865 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
866 mtsh.mtsh_maxcpus = MAXCPU;
867 mtsh.mtsh_count = kmemcount;
868 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
871 * Insert alternating sequence of type headers and type statistics.
873 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
874 mtip = (struct malloc_type_internal *)mtp->ks_handle;
877 * Insert type header.
879 bzero(&mth, sizeof(mth));
880 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
881 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
884 * Insert type statistics for each CPU.
886 for (i = 0; i < MAXCPU; i++) {
887 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
888 sizeof(mtip->mti_stats[i]));
891 mtx_unlock(&malloc_mtx);
892 error = sbuf_finish(&sbuf);
897 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
898 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
899 "Return malloc types");
901 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
902 "Count of kernel malloc types");
905 malloc_type_list(malloc_type_list_func_t *func, void *arg)
907 struct malloc_type *mtp, **bufmtp;
911 mtx_lock(&malloc_mtx);
913 mtx_assert(&malloc_mtx, MA_OWNED);
915 mtx_unlock(&malloc_mtx);
917 buflen = sizeof(struct malloc_type *) * count;
918 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
920 mtx_lock(&malloc_mtx);
922 if (count < kmemcount) {
923 free(bufmtp, M_TEMP);
927 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
930 mtx_unlock(&malloc_mtx);
932 for (i = 0; i < count; i++)
933 (func)(bufmtp[i], arg);
935 free(bufmtp, M_TEMP);
939 DB_SHOW_COMMAND(malloc, db_show_malloc)
941 struct malloc_type_internal *mtip;
942 struct malloc_type *mtp;
943 uint64_t allocs, frees;
944 uint64_t alloced, freed;
947 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
949 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
950 mtip = (struct malloc_type_internal *)mtp->ks_handle;
955 for (i = 0; i < MAXCPU; i++) {
956 allocs += mtip->mti_stats[i].mts_numallocs;
957 frees += mtip->mti_stats[i].mts_numfrees;
958 alloced += mtip->mti_stats[i].mts_memalloced;
959 freed += mtip->mti_stats[i].mts_memfreed;
961 db_printf("%18s %12ju %12juK %12ju\n",
962 mtp->ks_shortdesc, allocs - frees,
963 (alloced - freed + 1023) / 1024, allocs);
969 #if MALLOC_DEBUG_MAXZONES > 1
970 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
972 struct malloc_type_internal *mtip;
973 struct malloc_type *mtp;
977 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
981 if (mtp->ks_magic != M_MAGIC) {
982 db_printf("Magic %lx does not match expected %x\n",
983 mtp->ks_magic, M_MAGIC);
987 mtip = mtp->ks_handle;
988 subzone = mtip->mti_zone;
990 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
991 mtip = mtp->ks_handle;
992 if (mtip->mti_zone != subzone)
994 db_printf("%s\n", mtp->ks_shortdesc);
999 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1002 #ifdef MALLOC_PROFILE
1005 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1019 error = sysctl_wire_old_buffer(req, 0);
1022 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1024 "\n Size Requests Real Size\n");
1025 for (i = 0; i < KMEM_ZSIZE; i++) {
1026 size = i << KMEM_ZSHIFT;
1027 rsize = kmemzones[kmemsize[i]].kz_size;
1028 count = (long long unsigned)krequests[i];
1030 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1031 (unsigned long long)count, rsize);
1033 if ((rsize * count) > (size * count))
1034 waste += (rsize * count) - (size * count);
1035 mem += (rsize * count);
1038 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1039 (unsigned long long)mem, (unsigned long long)waste);
1040 error = sbuf_finish(&sbuf);
1045 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1046 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1047 #endif /* MALLOC_PROFILE */