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 uint8_t kmemsize[KMEM_ZSIZE + 1];
134 #ifndef MALLOC_DEBUG_MAXZONES
135 #define MALLOC_DEBUG_MAXZONES 1
137 static int numzones = MALLOC_DEBUG_MAXZONES;
140 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
143 * XXX: The comment here used to read "These won't be powers of two for
144 * long." It's possible that a significant amount of wasted memory could be
145 * recovered by tuning the sizes of these buckets.
150 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
165 #if PAGE_SIZE > 16384
167 #if PAGE_SIZE > 32768
169 #if PAGE_SIZE > 65536
170 #error "Unsupported PAGE_SIZE"
180 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
181 * types are described by a data structure passed by the declaring code, but
182 * the malloc(9) implementation has its own data structure describing the
183 * type and statistics. This permits the malloc(9)-internal data structures
184 * to be modified without breaking binary-compiled kernel modules that
185 * declare malloc types.
187 static uma_zone_t mt_zone;
190 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
191 "Size of kernel memory");
193 static u_long vm_kmem_size_min;
194 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
195 "Minimum size of kernel memory");
197 static u_long vm_kmem_size_max;
198 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
199 "Maximum size of kernel memory");
201 static u_int vm_kmem_size_scale;
202 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
203 "Scale factor for kernel memory size");
205 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
206 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
207 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
208 sysctl_kmem_map_size, "LU", "Current kmem_map allocation size");
210 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
211 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
212 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
213 sysctl_kmem_map_free, "LU", "Largest contiguous free range in kmem_map");
216 * The malloc_mtx protects the kmemstatistics linked list.
218 struct mtx malloc_mtx;
220 #ifdef MALLOC_PROFILE
221 uint64_t krequests[KMEM_ZSIZE + 1];
223 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
226 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
229 * time_uptime of the last malloc(9) failure (induced or real).
231 static time_t t_malloc_fail;
233 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
234 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
235 "Kernel malloc debugging options");
239 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
240 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
242 #ifdef MALLOC_MAKE_FAILURES
243 static int malloc_failure_rate;
244 static int malloc_nowait_count;
245 static int malloc_failure_count;
246 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
247 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
248 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
249 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
250 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
254 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
258 size = kmem_map->size;
259 return (sysctl_handle_long(oidp, &size, 0, req));
263 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
267 vm_map_lock_read(kmem_map);
268 size = kmem_map->root != NULL ? kmem_map->root->max_free :
269 kmem_map->max_offset - kmem_map->min_offset;
270 vm_map_unlock_read(kmem_map);
271 return (sysctl_handle_long(oidp, &size, 0, req));
275 * malloc(9) uma zone separation -- sub-page buffer overruns in one
276 * malloc type will affect only a subset of other malloc types.
278 #if MALLOC_DEBUG_MAXZONES > 1
280 tunable_set_numzones(void)
283 TUNABLE_INT_FETCH("debug.malloc.numzones",
286 /* Sanity check the number of malloc uma zones. */
289 if (numzones > MALLOC_DEBUG_MAXZONES)
290 numzones = MALLOC_DEBUG_MAXZONES;
292 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
293 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
294 &numzones, 0, "Number of malloc uma subzones");
297 * Any number that changes regularly is an okay choice for the
298 * offset. Build numbers are pretty good of you have them.
300 static u_int zone_offset = __FreeBSD_version;
301 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
302 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
303 &zone_offset, 0, "Separate malloc types by examining the "
304 "Nth character in the malloc type short description.");
307 mtp_get_subzone(const char *desc)
312 if (desc == NULL || (len = strlen(desc)) == 0)
314 val = desc[zone_offset % len];
315 return (val % numzones);
317 #elif MALLOC_DEBUG_MAXZONES == 0
318 #error "MALLOC_DEBUG_MAXZONES must be positive."
321 mtp_get_subzone(const char *desc)
326 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
329 malloc_last_fail(void)
332 return (time_uptime - t_malloc_fail);
336 * An allocation has succeeded -- update malloc type statistics for the
337 * amount of bucket size. Occurs within a critical section so that the
338 * thread isn't preempted and doesn't migrate while updating per-PCU
342 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
345 struct malloc_type_internal *mtip;
346 struct malloc_type_stats *mtsp;
349 mtip = mtp->ks_handle;
350 mtsp = &mtip->mti_stats[curcpu];
352 mtsp->mts_memalloced += size;
353 mtsp->mts_numallocs++;
356 mtsp->mts_size |= 1 << zindx;
359 if (dtrace_malloc_probe != NULL) {
360 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
362 (dtrace_malloc_probe)(probe_id,
363 (uintptr_t) mtp, (uintptr_t) mtip,
364 (uintptr_t) mtsp, size, zindx);
372 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
376 malloc_type_zone_allocated(mtp, size, -1);
380 * A free operation has occurred -- update malloc type statistics for the
381 * amount of the bucket size. Occurs within a critical section so that the
382 * thread isn't preempted and doesn't migrate while updating per-CPU
386 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
388 struct malloc_type_internal *mtip;
389 struct malloc_type_stats *mtsp;
392 mtip = mtp->ks_handle;
393 mtsp = &mtip->mti_stats[curcpu];
394 mtsp->mts_memfreed += size;
395 mtsp->mts_numfrees++;
398 if (dtrace_malloc_probe != NULL) {
399 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
401 (dtrace_malloc_probe)(probe_id,
402 (uintptr_t) mtp, (uintptr_t) mtip,
403 (uintptr_t) mtsp, size, 0);
413 * Allocate a block of physically contiguous memory.
415 * If M_NOWAIT is set, this routine will not block and return NULL if
416 * the allocation fails.
419 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
420 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
425 ret = (void *)kmem_alloc_contig(kernel_map, size, flags, low, high,
426 alignment, boundary, VM_MEMATTR_DEFAULT);
428 malloc_type_allocated(type, round_page(size));
435 * Free a block of memory allocated by contigmalloc.
437 * This routine may not block.
440 contigfree(void *addr, unsigned long size, struct malloc_type *type)
443 kmem_free(kernel_map, (vm_offset_t)addr, size);
444 malloc_type_freed(type, round_page(size));
450 * Allocate a block of memory.
452 * If M_NOWAIT is set, this routine will not block and return NULL if
453 * the allocation fails.
456 malloc(unsigned long size, struct malloc_type *mtp, int flags)
459 struct malloc_type_internal *mtip;
462 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
463 unsigned long osize = size;
467 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
469 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
471 indx = flags & (M_WAITOK | M_NOWAIT);
472 if (indx != M_NOWAIT && indx != M_WAITOK) {
473 static struct timeval lasterr;
474 static int curerr, once;
475 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
476 printf("Bad malloc flags: %x\n", indx);
483 #ifdef MALLOC_MAKE_FAILURES
484 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
485 atomic_add_int(&malloc_nowait_count, 1);
486 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
487 atomic_add_int(&malloc_failure_count, 1);
488 t_malloc_fail = time_uptime;
493 if (flags & M_WAITOK)
494 KASSERT(curthread->td_intr_nesting_level == 0,
495 ("malloc(M_WAITOK) in interrupt context"));
497 #ifdef DEBUG_MEMGUARD
498 if (memguard_cmp_mtp(mtp, size)) {
499 va = memguard_alloc(size, flags);
502 /* This is unfortunate but should not be fatal. */
507 size = redzone_size_ntor(size);
510 if (size <= KMEM_ZMAX) {
511 mtip = mtp->ks_handle;
512 if (size & KMEM_ZMASK)
513 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
514 indx = kmemsize[size >> KMEM_ZSHIFT];
515 KASSERT(mtip->mti_zone < numzones,
516 ("mti_zone %u out of range %d",
517 mtip->mti_zone, numzones));
518 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
519 #ifdef MALLOC_PROFILE
520 krequests[size >> KMEM_ZSHIFT]++;
522 va = uma_zalloc(zone, flags);
524 size = zone->uz_size;
525 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
527 size = roundup(size, PAGE_SIZE);
529 va = uma_large_malloc(size, flags);
530 malloc_type_allocated(mtp, va == NULL ? 0 : size);
532 if (flags & M_WAITOK)
533 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
535 t_malloc_fail = time_uptime;
537 if (va != NULL && !(flags & M_ZERO)) {
538 memset(va, 0x70, osize);
543 va = redzone_setup(va, osize);
545 return ((void *) va);
551 * Free a block of memory allocated by malloc.
553 * This routine may not block.
556 free(void *addr, struct malloc_type *mtp)
561 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
563 /* free(NULL, ...) does nothing */
567 #ifdef DEBUG_MEMGUARD
568 if (is_memguard_addr(addr)) {
576 addr = redzone_addr_ntor(addr);
579 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
582 panic("free: address %p(%p) has not been allocated.\n",
583 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
586 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
588 struct malloc_type **mtpp = addr;
590 size = slab->us_keg->uk_size;
593 * Cache a pointer to the malloc_type that most recently freed
594 * this memory here. This way we know who is most likely to
595 * have stepped on it later.
597 * This code assumes that size is a multiple of 8 bytes for
600 mtpp = (struct malloc_type **)
601 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
602 mtpp += (size - sizeof(struct malloc_type *)) /
603 sizeof(struct malloc_type *);
606 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
608 size = slab->us_size;
609 uma_large_free(slab);
611 malloc_type_freed(mtp, size);
615 * realloc: change the size of a memory block
618 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
624 KASSERT(mtp->ks_magic == M_MAGIC,
625 ("realloc: bad malloc type magic"));
627 /* realloc(NULL, ...) is equivalent to malloc(...) */
629 return (malloc(size, mtp, flags));
632 * XXX: Should report free of old memory and alloc of new memory to
636 #ifdef DEBUG_MEMGUARD
637 if (is_memguard_addr(addr))
638 return (memguard_realloc(addr, size, mtp, flags));
643 alloc = redzone_get_size(addr);
645 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
648 KASSERT(slab != NULL,
649 ("realloc: address %p out of range", (void *)addr));
651 /* Get the size of the original block */
652 if (!(slab->us_flags & UMA_SLAB_MALLOC))
653 alloc = slab->us_keg->uk_size;
655 alloc = slab->us_size;
657 /* Reuse the original block if appropriate */
659 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
661 #endif /* !DEBUG_REDZONE */
663 /* Allocate a new, bigger (or smaller) block */
664 if ((newaddr = malloc(size, mtp, flags)) == NULL)
667 /* Copy over original contents */
668 bcopy(addr, newaddr, min(size, alloc));
674 * reallocf: same as realloc() but free memory on failure.
677 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
681 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
687 * Initialize the kernel memory allocator
691 kmeminit(void *dummy)
694 u_long mem_size, tmp;
697 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
700 * Try to auto-tune the kernel memory size, so that it is
701 * more applicable for a wider range of machine sizes. The
702 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
705 * Note that the kmem_map is also used by the zone allocator,
706 * so make sure that there is enough space.
708 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
709 mem_size = cnt.v_page_count;
711 #if defined(VM_KMEM_SIZE_SCALE)
712 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
714 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
715 if (vm_kmem_size_scale > 0 &&
716 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
717 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
719 #if defined(VM_KMEM_SIZE_MIN)
720 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
722 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
723 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
724 vm_kmem_size = vm_kmem_size_min;
727 #if defined(VM_KMEM_SIZE_MAX)
728 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
730 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
731 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
732 vm_kmem_size = vm_kmem_size_max;
734 /* Allow final override from the kernel environment */
735 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
738 * Limit kmem virtual size to twice the physical memory.
739 * This allows for kmem map sparseness, but limits the size
740 * to something sane. Be careful to not overflow the 32bit
741 * ints while doing the check or the adjustment.
743 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
744 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
746 #ifdef DEBUG_MEMGUARD
747 tmp = memguard_fudge(vm_kmem_size, vm_kmem_size_max);
751 kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
753 kmem_map->system_map = 1;
755 #ifdef DEBUG_MEMGUARD
757 * Initialize MemGuard if support compiled in. MemGuard is a
758 * replacement allocator used for detecting tamper-after-free
759 * scenarios as they occur. It is only used for debugging.
761 memguard_init(kmem_map);
766 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
768 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
770 NULL, NULL, NULL, NULL,
772 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
773 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
774 int size = kmemzones[indx].kz_size;
775 char *name = kmemzones[indx].kz_name;
778 for (subzone = 0; subzone < numzones; subzone++) {
779 kmemzones[indx].kz_zone[subzone] =
780 uma_zcreate(name, size,
782 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
784 NULL, NULL, NULL, NULL,
786 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
788 for (;i <= size; i+= KMEM_ZBASE)
789 kmemsize[i >> KMEM_ZSHIFT] = indx;
795 malloc_init(void *data)
797 struct malloc_type_internal *mtip;
798 struct malloc_type *mtp;
800 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
803 if (mtp->ks_magic != M_MAGIC)
804 panic("malloc_init: bad malloc type magic");
806 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
807 mtp->ks_handle = mtip;
808 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
810 mtx_lock(&malloc_mtx);
811 mtp->ks_next = kmemstatistics;
812 kmemstatistics = mtp;
814 mtx_unlock(&malloc_mtx);
818 malloc_uninit(void *data)
820 struct malloc_type_internal *mtip;
821 struct malloc_type_stats *mtsp;
822 struct malloc_type *mtp, *temp;
824 long temp_allocs, temp_bytes;
828 KASSERT(mtp->ks_magic == M_MAGIC,
829 ("malloc_uninit: bad malloc type magic"));
830 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
832 mtx_lock(&malloc_mtx);
833 mtip = mtp->ks_handle;
834 mtp->ks_handle = NULL;
835 if (mtp != kmemstatistics) {
836 for (temp = kmemstatistics; temp != NULL;
837 temp = temp->ks_next) {
838 if (temp->ks_next == mtp) {
839 temp->ks_next = mtp->ks_next;
844 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
846 kmemstatistics = mtp->ks_next;
848 mtx_unlock(&malloc_mtx);
851 * Look for memory leaks.
853 temp_allocs = temp_bytes = 0;
854 for (i = 0; i < MAXCPU; i++) {
855 mtsp = &mtip->mti_stats[i];
856 temp_allocs += mtsp->mts_numallocs;
857 temp_allocs -= mtsp->mts_numfrees;
858 temp_bytes += mtsp->mts_memalloced;
859 temp_bytes -= mtsp->mts_memfreed;
861 if (temp_allocs > 0 || temp_bytes > 0) {
862 printf("Warning: memory type %s leaked memory on destroy "
863 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
864 temp_allocs, temp_bytes);
867 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
868 uma_zfree_arg(mt_zone, mtip, slab);
872 malloc_desc2type(const char *desc)
874 struct malloc_type *mtp;
876 mtx_assert(&malloc_mtx, MA_OWNED);
877 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
878 if (strcmp(mtp->ks_shortdesc, desc) == 0)
885 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
887 struct malloc_type_stream_header mtsh;
888 struct malloc_type_internal *mtip;
889 struct malloc_type_header mth;
890 struct malloc_type *mtp;
894 error = sysctl_wire_old_buffer(req, 0);
897 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
898 mtx_lock(&malloc_mtx);
901 * Insert stream header.
903 bzero(&mtsh, sizeof(mtsh));
904 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
905 mtsh.mtsh_maxcpus = MAXCPU;
906 mtsh.mtsh_count = kmemcount;
907 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
910 * Insert alternating sequence of type headers and type statistics.
912 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
913 mtip = (struct malloc_type_internal *)mtp->ks_handle;
916 * Insert type header.
918 bzero(&mth, sizeof(mth));
919 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
920 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
923 * Insert type statistics for each CPU.
925 for (i = 0; i < MAXCPU; i++) {
926 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
927 sizeof(mtip->mti_stats[i]));
930 mtx_unlock(&malloc_mtx);
931 error = sbuf_finish(&sbuf);
936 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
937 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
938 "Return malloc types");
940 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
941 "Count of kernel malloc types");
944 malloc_type_list(malloc_type_list_func_t *func, void *arg)
946 struct malloc_type *mtp, **bufmtp;
950 mtx_lock(&malloc_mtx);
952 mtx_assert(&malloc_mtx, MA_OWNED);
954 mtx_unlock(&malloc_mtx);
956 buflen = sizeof(struct malloc_type *) * count;
957 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
959 mtx_lock(&malloc_mtx);
961 if (count < kmemcount) {
962 free(bufmtp, M_TEMP);
966 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
969 mtx_unlock(&malloc_mtx);
971 for (i = 0; i < count; i++)
972 (func)(bufmtp[i], arg);
974 free(bufmtp, M_TEMP);
978 DB_SHOW_COMMAND(malloc, db_show_malloc)
980 struct malloc_type_internal *mtip;
981 struct malloc_type *mtp;
982 uint64_t allocs, frees;
983 uint64_t alloced, freed;
986 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
988 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
989 mtip = (struct malloc_type_internal *)mtp->ks_handle;
994 for (i = 0; i < MAXCPU; i++) {
995 allocs += mtip->mti_stats[i].mts_numallocs;
996 frees += mtip->mti_stats[i].mts_numfrees;
997 alloced += mtip->mti_stats[i].mts_memalloced;
998 freed += mtip->mti_stats[i].mts_memfreed;
1000 db_printf("%18s %12ju %12juK %12ju\n",
1001 mtp->ks_shortdesc, allocs - frees,
1002 (alloced - freed + 1023) / 1024, allocs);
1006 #if MALLOC_DEBUG_MAXZONES > 1
1007 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1009 struct malloc_type_internal *mtip;
1010 struct malloc_type *mtp;
1014 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1018 if (mtp->ks_magic != M_MAGIC) {
1019 db_printf("Magic %lx does not match expected %x\n",
1020 mtp->ks_magic, M_MAGIC);
1024 mtip = mtp->ks_handle;
1025 subzone = mtip->mti_zone;
1027 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1028 mtip = mtp->ks_handle;
1029 if (mtip->mti_zone != subzone)
1031 db_printf("%s\n", mtp->ks_shortdesc);
1034 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1037 #ifdef MALLOC_PROFILE
1040 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1054 error = sysctl_wire_old_buffer(req, 0);
1057 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1059 "\n Size Requests Real Size\n");
1060 for (i = 0; i < KMEM_ZSIZE; i++) {
1061 size = i << KMEM_ZSHIFT;
1062 rsize = kmemzones[kmemsize[i]].kz_size;
1063 count = (long long unsigned)krequests[i];
1065 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1066 (unsigned long long)count, rsize);
1068 if ((rsize * count) > (size * count))
1069 waste += (rsize * count) - (size * count);
1070 mem += (rsize * count);
1073 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1074 (unsigned long long)mem, (unsigned long long)waste);
1075 error = sbuf_finish(&sbuf);
1080 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1081 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1082 #endif /* MALLOC_PROFILE */