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 physically contiguous memory.
413 * If M_NOWAIT is set, this routine will not block and return NULL if
414 * the allocation fails.
417 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
418 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
419 unsigned long boundary)
423 ret = (void *)kmem_alloc_contig(kernel_map, size, flags, low, high,
424 alignment, boundary, VM_MEMATTR_DEFAULT);
426 malloc_type_allocated(type, round_page(size));
433 * Free a block of memory allocated by contigmalloc.
435 * This routine may not block.
438 contigfree(void *addr, unsigned long size, struct malloc_type *type)
441 kmem_free(kernel_map, (vm_offset_t)addr, size);
442 malloc_type_freed(type, round_page(size));
448 * Allocate a block of memory.
450 * If M_NOWAIT is set, this routine will not block and return NULL if
451 * the allocation fails.
454 malloc(unsigned long size, struct malloc_type *mtp, int flags)
457 struct malloc_type_internal *mtip;
460 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
461 unsigned long osize = size;
465 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
467 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
469 indx = flags & (M_WAITOK | M_NOWAIT);
470 if (indx != M_NOWAIT && indx != M_WAITOK) {
471 static struct timeval lasterr;
472 static int curerr, once;
473 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
474 printf("Bad malloc flags: %x\n", indx);
481 #ifdef MALLOC_MAKE_FAILURES
482 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
483 atomic_add_int(&malloc_nowait_count, 1);
484 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
485 atomic_add_int(&malloc_failure_count, 1);
486 t_malloc_fail = time_uptime;
491 if (flags & M_WAITOK)
492 KASSERT(curthread->td_intr_nesting_level == 0,
493 ("malloc(M_WAITOK) in interrupt context"));
495 #ifdef DEBUG_MEMGUARD
496 if (memguard_cmp(mtp, size)) {
497 va = memguard_alloc(size, flags);
500 /* This is unfortunate but should not be fatal. */
505 size = redzone_size_ntor(size);
508 if (size <= KMEM_ZMAX) {
509 mtip = mtp->ks_handle;
510 if (size & KMEM_ZMASK)
511 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
512 indx = kmemsize[size >> KMEM_ZSHIFT];
513 KASSERT(mtip->mti_zone < numzones,
514 ("mti_zone %u out of range %d",
515 mtip->mti_zone, numzones));
516 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
517 #ifdef MALLOC_PROFILE
518 krequests[size >> KMEM_ZSHIFT]++;
520 va = uma_zalloc(zone, flags);
522 size = zone->uz_size;
523 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
525 size = roundup(size, PAGE_SIZE);
527 va = uma_large_malloc(size, flags);
528 malloc_type_allocated(mtp, va == NULL ? 0 : size);
530 if (flags & M_WAITOK)
531 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
533 t_malloc_fail = time_uptime;
535 if (va != NULL && !(flags & M_ZERO)) {
536 memset(va, 0x70, osize);
541 va = redzone_setup(va, osize);
543 return ((void *) va);
549 * Free a block of memory allocated by malloc.
551 * This routine may not block.
554 free(void *addr, struct malloc_type *mtp)
559 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
561 /* free(NULL, ...) does nothing */
565 #ifdef DEBUG_MEMGUARD
566 if (is_memguard_addr(addr)) {
574 addr = redzone_addr_ntor(addr);
577 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
580 panic("free: address %p(%p) has not been allocated.\n",
581 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
584 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
586 struct malloc_type **mtpp = addr;
588 size = slab->us_keg->uk_size;
591 * Cache a pointer to the malloc_type that most recently freed
592 * this memory here. This way we know who is most likely to
593 * have stepped on it later.
595 * This code assumes that size is a multiple of 8 bytes for
598 mtpp = (struct malloc_type **)
599 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
600 mtpp += (size - sizeof(struct malloc_type *)) /
601 sizeof(struct malloc_type *);
604 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
606 size = slab->us_size;
607 uma_large_free(slab);
609 malloc_type_freed(mtp, size);
613 * realloc: change the size of a memory block
616 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
622 KASSERT(mtp->ks_magic == M_MAGIC,
623 ("realloc: bad malloc type magic"));
625 /* realloc(NULL, ...) is equivalent to malloc(...) */
627 return (malloc(size, mtp, flags));
630 * XXX: Should report free of old memory and alloc of new memory to
634 #ifdef DEBUG_MEMGUARD
635 if (is_memguard_addr(addr))
636 return (memguard_realloc(addr, size, mtp, flags));
641 alloc = redzone_get_size(addr);
643 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
646 KASSERT(slab != NULL,
647 ("realloc: address %p out of range", (void *)addr));
649 /* Get the size of the original block */
650 if (!(slab->us_flags & UMA_SLAB_MALLOC))
651 alloc = slab->us_keg->uk_size;
653 alloc = slab->us_size;
655 /* Reuse the original block if appropriate */
657 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
659 #endif /* !DEBUG_REDZONE */
661 /* Allocate a new, bigger (or smaller) block */
662 if ((newaddr = malloc(size, mtp, flags)) == NULL)
665 /* Copy over original contents */
666 bcopy(addr, newaddr, min(size, alloc));
672 * reallocf: same as realloc() but free memory on failure.
675 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
679 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
685 * Initialize the kernel memory allocator
689 kmeminit(void *dummy)
692 u_long mem_size, tmp;
695 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
698 * Try to auto-tune the kernel memory size, so that it is
699 * more applicable for a wider range of machine sizes. The
700 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
703 * Note that the kmem_map is also used by the zone allocator,
704 * so make sure that there is enough space.
706 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
707 mem_size = cnt.v_page_count;
709 #if defined(VM_KMEM_SIZE_SCALE)
710 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
712 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
713 if (vm_kmem_size_scale > 0 &&
714 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
715 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
717 #if defined(VM_KMEM_SIZE_MIN)
718 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
720 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
721 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
722 vm_kmem_size = vm_kmem_size_min;
725 #if defined(VM_KMEM_SIZE_MAX)
726 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
728 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
729 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
730 vm_kmem_size = vm_kmem_size_max;
732 /* Allow final override from the kernel environment */
733 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
736 * Limit kmem virtual size to twice the physical memory.
737 * This allows for kmem map sparseness, but limits the size
738 * to something sane. Be careful to not overflow the 32bit
739 * ints while doing the check or the adjustment.
741 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
742 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
744 #ifdef DEBUG_MEMGUARD
745 tmp = memguard_fudge(vm_kmem_size, kernel_map);
749 kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
751 kmem_map->system_map = 1;
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_map);
764 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
766 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
768 NULL, NULL, NULL, NULL,
770 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
771 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
772 int size = kmemzones[indx].kz_size;
773 char *name = kmemzones[indx].kz_name;
776 for (subzone = 0; subzone < numzones; subzone++) {
777 kmemzones[indx].kz_zone[subzone] =
778 uma_zcreate(name, size,
780 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
782 NULL, NULL, NULL, NULL,
784 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
786 for (;i <= size; i+= KMEM_ZBASE)
787 kmemsize[i >> KMEM_ZSHIFT] = indx;
793 malloc_init(void *data)
795 struct malloc_type_internal *mtip;
796 struct malloc_type *mtp;
798 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
801 if (mtp->ks_magic != M_MAGIC)
802 panic("malloc_init: bad malloc type magic");
804 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
805 mtp->ks_handle = mtip;
806 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
808 mtx_lock(&malloc_mtx);
809 mtp->ks_next = kmemstatistics;
810 kmemstatistics = mtp;
812 mtx_unlock(&malloc_mtx);
816 malloc_uninit(void *data)
818 struct malloc_type_internal *mtip;
819 struct malloc_type_stats *mtsp;
820 struct malloc_type *mtp, *temp;
822 long temp_allocs, temp_bytes;
826 KASSERT(mtp->ks_magic == M_MAGIC,
827 ("malloc_uninit: bad malloc type magic"));
828 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
830 mtx_lock(&malloc_mtx);
831 mtip = mtp->ks_handle;
832 mtp->ks_handle = NULL;
833 if (mtp != kmemstatistics) {
834 for (temp = kmemstatistics; temp != NULL;
835 temp = temp->ks_next) {
836 if (temp->ks_next == mtp) {
837 temp->ks_next = mtp->ks_next;
842 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
844 kmemstatistics = mtp->ks_next;
846 mtx_unlock(&malloc_mtx);
849 * Look for memory leaks.
851 temp_allocs = temp_bytes = 0;
852 for (i = 0; i < MAXCPU; i++) {
853 mtsp = &mtip->mti_stats[i];
854 temp_allocs += mtsp->mts_numallocs;
855 temp_allocs -= mtsp->mts_numfrees;
856 temp_bytes += mtsp->mts_memalloced;
857 temp_bytes -= mtsp->mts_memfreed;
859 if (temp_allocs > 0 || temp_bytes > 0) {
860 printf("Warning: memory type %s leaked memory on destroy "
861 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
862 temp_allocs, temp_bytes);
865 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
866 uma_zfree_arg(mt_zone, mtip, slab);
870 malloc_desc2type(const char *desc)
872 struct malloc_type *mtp;
874 mtx_assert(&malloc_mtx, MA_OWNED);
875 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
876 if (strcmp(mtp->ks_shortdesc, desc) == 0)
883 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
885 struct malloc_type_stream_header mtsh;
886 struct malloc_type_internal *mtip;
887 struct malloc_type_header mth;
888 struct malloc_type *mtp;
892 error = sysctl_wire_old_buffer(req, 0);
895 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
896 mtx_lock(&malloc_mtx);
899 * Insert stream header.
901 bzero(&mtsh, sizeof(mtsh));
902 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
903 mtsh.mtsh_maxcpus = MAXCPU;
904 mtsh.mtsh_count = kmemcount;
905 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
908 * Insert alternating sequence of type headers and type statistics.
910 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
911 mtip = (struct malloc_type_internal *)mtp->ks_handle;
914 * Insert type header.
916 bzero(&mth, sizeof(mth));
917 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
918 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
921 * Insert type statistics for each CPU.
923 for (i = 0; i < MAXCPU; i++) {
924 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
925 sizeof(mtip->mti_stats[i]));
928 mtx_unlock(&malloc_mtx);
929 error = sbuf_finish(&sbuf);
934 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
935 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
936 "Return malloc types");
938 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
939 "Count of kernel malloc types");
942 malloc_type_list(malloc_type_list_func_t *func, void *arg)
944 struct malloc_type *mtp, **bufmtp;
948 mtx_lock(&malloc_mtx);
950 mtx_assert(&malloc_mtx, MA_OWNED);
952 mtx_unlock(&malloc_mtx);
954 buflen = sizeof(struct malloc_type *) * count;
955 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
957 mtx_lock(&malloc_mtx);
959 if (count < kmemcount) {
960 free(bufmtp, M_TEMP);
964 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
967 mtx_unlock(&malloc_mtx);
969 for (i = 0; i < count; i++)
970 (func)(bufmtp[i], arg);
972 free(bufmtp, M_TEMP);
976 DB_SHOW_COMMAND(malloc, db_show_malloc)
978 struct malloc_type_internal *mtip;
979 struct malloc_type *mtp;
980 uint64_t allocs, frees;
981 uint64_t alloced, freed;
984 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
986 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
987 mtip = (struct malloc_type_internal *)mtp->ks_handle;
992 for (i = 0; i < MAXCPU; i++) {
993 allocs += mtip->mti_stats[i].mts_numallocs;
994 frees += mtip->mti_stats[i].mts_numfrees;
995 alloced += mtip->mti_stats[i].mts_memalloced;
996 freed += mtip->mti_stats[i].mts_memfreed;
998 db_printf("%18s %12ju %12juK %12ju\n",
999 mtp->ks_shortdesc, allocs - frees,
1000 (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);
1036 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1039 #ifdef MALLOC_PROFILE
1042 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1056 error = sysctl_wire_old_buffer(req, 0);
1059 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1061 "\n Size Requests Real Size\n");
1062 for (i = 0; i < KMEM_ZSIZE; i++) {
1063 size = i << KMEM_ZSHIFT;
1064 rsize = kmemzones[kmemsize[i]].kz_size;
1065 count = (long long unsigned)krequests[i];
1067 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1068 (unsigned long long)count, rsize);
1070 if ((rsize * count) > (size * count))
1071 waste += (rsize * count) - (size * count);
1072 mem += (rsize * count);
1075 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1076 (unsigned long long)mem, (unsigned long long)waste);
1077 error = sbuf_finish(&sbuf);
1082 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1083 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1084 #endif /* MALLOC_PROFILE */