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;
189 static vm_offset_t vm_min_kernel_address = VM_MIN_KERNEL_ADDRESS;
190 SYSCTL_ULONG(_vm, OID_AUTO, min_kernel_address, CTLFLAG_RD,
191 &vm_min_kernel_address, 0, "Min kernel address");
194 static vm_offset_t vm_max_kernel_address = VM_MAX_KERNEL_ADDRESS;
196 SYSCTL_ULONG(_vm, OID_AUTO, max_kernel_address, CTLFLAG_RD,
197 &vm_max_kernel_address, 0, "Max kernel address");
200 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
201 "Size of kernel memory");
203 static u_long vm_kmem_size_min;
204 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
205 "Minimum size of kernel memory");
207 static u_long vm_kmem_size_max;
208 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
209 "Maximum size of kernel memory");
211 static u_int vm_kmem_size_scale;
212 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
213 "Scale factor for kernel memory size");
215 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
216 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
217 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
218 sysctl_kmem_map_size, "LU", "Current kmem_map allocation size");
220 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
221 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
222 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
223 sysctl_kmem_map_free, "LU", "Largest contiguous free range in kmem_map");
226 * The malloc_mtx protects the kmemstatistics linked list.
228 struct mtx malloc_mtx;
230 #ifdef MALLOC_PROFILE
231 uint64_t krequests[KMEM_ZSIZE + 1];
233 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
236 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
239 * time_uptime of the last malloc(9) failure (induced or real).
241 static time_t t_malloc_fail;
243 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
244 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
245 "Kernel malloc debugging options");
249 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
250 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
252 #ifdef MALLOC_MAKE_FAILURES
253 static int malloc_failure_rate;
254 static int malloc_nowait_count;
255 static int malloc_failure_count;
256 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
257 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
258 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
259 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
260 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
264 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
268 size = kmem_map->size;
269 return (sysctl_handle_long(oidp, &size, 0, req));
273 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
277 vm_map_lock_read(kmem_map);
278 size = kmem_map->root != NULL ? kmem_map->root->max_free :
279 kmem_map->max_offset - kmem_map->min_offset;
280 vm_map_unlock_read(kmem_map);
281 return (sysctl_handle_long(oidp, &size, 0, req));
285 * malloc(9) uma zone separation -- sub-page buffer overruns in one
286 * malloc type will affect only a subset of other malloc types.
288 #if MALLOC_DEBUG_MAXZONES > 1
290 tunable_set_numzones(void)
293 TUNABLE_INT_FETCH("debug.malloc.numzones",
296 /* Sanity check the number of malloc uma zones. */
299 if (numzones > MALLOC_DEBUG_MAXZONES)
300 numzones = MALLOC_DEBUG_MAXZONES;
302 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
303 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
304 &numzones, 0, "Number of malloc uma subzones");
307 * Any number that changes regularly is an okay choice for the
308 * offset. Build numbers are pretty good of you have them.
310 static u_int zone_offset = __FreeBSD_version;
311 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
312 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
313 &zone_offset, 0, "Separate malloc types by examining the "
314 "Nth character in the malloc type short description.");
317 mtp_get_subzone(const char *desc)
322 if (desc == NULL || (len = strlen(desc)) == 0)
324 val = desc[zone_offset % len];
325 return (val % numzones);
327 #elif MALLOC_DEBUG_MAXZONES == 0
328 #error "MALLOC_DEBUG_MAXZONES must be positive."
331 mtp_get_subzone(const char *desc)
336 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
339 malloc_last_fail(void)
342 return (time_uptime - t_malloc_fail);
346 * An allocation has succeeded -- update malloc type statistics for the
347 * amount of bucket size. Occurs within a critical section so that the
348 * thread isn't preempted and doesn't migrate while updating per-PCU
352 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
355 struct malloc_type_internal *mtip;
356 struct malloc_type_stats *mtsp;
359 mtip = mtp->ks_handle;
360 mtsp = &mtip->mti_stats[curcpu];
362 mtsp->mts_memalloced += size;
363 mtsp->mts_numallocs++;
366 mtsp->mts_size |= 1 << zindx;
369 if (dtrace_malloc_probe != NULL) {
370 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
372 (dtrace_malloc_probe)(probe_id,
373 (uintptr_t) mtp, (uintptr_t) mtip,
374 (uintptr_t) mtsp, size, zindx);
382 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
386 malloc_type_zone_allocated(mtp, size, -1);
390 * A free operation has occurred -- update malloc type statistics for the
391 * amount of the bucket size. Occurs within a critical section so that the
392 * thread isn't preempted and doesn't migrate while updating per-CPU
396 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
398 struct malloc_type_internal *mtip;
399 struct malloc_type_stats *mtsp;
402 mtip = mtp->ks_handle;
403 mtsp = &mtip->mti_stats[curcpu];
404 mtsp->mts_memfreed += size;
405 mtsp->mts_numfrees++;
408 if (dtrace_malloc_probe != NULL) {
409 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
411 (dtrace_malloc_probe)(probe_id,
412 (uintptr_t) mtp, (uintptr_t) mtip,
413 (uintptr_t) mtsp, size, 0);
423 * Allocate a block of physically contiguous memory.
425 * If M_NOWAIT is set, this routine will not block and return NULL if
426 * the allocation fails.
429 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
430 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
435 ret = (void *)kmem_alloc_contig(kernel_map, size, flags, low, high,
436 alignment, boundary, VM_MEMATTR_DEFAULT);
438 malloc_type_allocated(type, round_page(size));
445 * Free a block of memory allocated by contigmalloc.
447 * This routine may not block.
450 contigfree(void *addr, unsigned long size, struct malloc_type *type)
453 kmem_free(kernel_map, (vm_offset_t)addr, size);
454 malloc_type_freed(type, round_page(size));
460 * Allocate a block of memory.
462 * If M_NOWAIT is set, this routine will not block and return NULL if
463 * the allocation fails.
466 malloc(unsigned long size, struct malloc_type *mtp, int flags)
469 struct malloc_type_internal *mtip;
472 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
473 unsigned long osize = size;
477 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
479 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
481 indx = flags & (M_WAITOK | M_NOWAIT);
482 if (indx != M_NOWAIT && indx != M_WAITOK) {
483 static struct timeval lasterr;
484 static int curerr, once;
485 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
486 printf("Bad malloc flags: %x\n", indx);
493 #ifdef MALLOC_MAKE_FAILURES
494 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
495 atomic_add_int(&malloc_nowait_count, 1);
496 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
497 atomic_add_int(&malloc_failure_count, 1);
498 t_malloc_fail = time_uptime;
503 if (flags & M_WAITOK)
504 KASSERT(curthread->td_intr_nesting_level == 0,
505 ("malloc(M_WAITOK) in interrupt context"));
507 #ifdef DEBUG_MEMGUARD
508 if (memguard_cmp_mtp(mtp, size)) {
509 va = memguard_alloc(size, flags);
512 /* This is unfortunate but should not be fatal. */
517 size = redzone_size_ntor(size);
520 if (size <= KMEM_ZMAX) {
521 mtip = mtp->ks_handle;
522 if (size & KMEM_ZMASK)
523 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
524 indx = kmemsize[size >> KMEM_ZSHIFT];
525 KASSERT(mtip->mti_zone < numzones,
526 ("mti_zone %u out of range %d",
527 mtip->mti_zone, numzones));
528 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
529 #ifdef MALLOC_PROFILE
530 krequests[size >> KMEM_ZSHIFT]++;
532 va = uma_zalloc(zone, flags);
534 size = zone->uz_size;
535 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
537 size = roundup(size, PAGE_SIZE);
539 va = uma_large_malloc(size, flags);
540 malloc_type_allocated(mtp, va == NULL ? 0 : size);
542 if (flags & M_WAITOK)
543 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
545 t_malloc_fail = time_uptime;
547 if (va != NULL && !(flags & M_ZERO)) {
548 memset(va, 0x70, osize);
553 va = redzone_setup(va, osize);
555 return ((void *) va);
561 * Free a block of memory allocated by malloc.
563 * This routine may not block.
566 free(void *addr, struct malloc_type *mtp)
571 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
573 /* free(NULL, ...) does nothing */
577 #ifdef DEBUG_MEMGUARD
578 if (is_memguard_addr(addr)) {
586 addr = redzone_addr_ntor(addr);
589 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
592 panic("free: address %p(%p) has not been allocated.\n",
593 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
596 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
598 struct malloc_type **mtpp = addr;
600 size = slab->us_keg->uk_size;
603 * Cache a pointer to the malloc_type that most recently freed
604 * this memory here. This way we know who is most likely to
605 * have stepped on it later.
607 * This code assumes that size is a multiple of 8 bytes for
610 mtpp = (struct malloc_type **)
611 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
612 mtpp += (size - sizeof(struct malloc_type *)) /
613 sizeof(struct malloc_type *);
616 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
618 size = slab->us_size;
619 uma_large_free(slab);
621 malloc_type_freed(mtp, size);
625 * realloc: change the size of a memory block
628 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
634 KASSERT(mtp->ks_magic == M_MAGIC,
635 ("realloc: bad malloc type magic"));
637 /* realloc(NULL, ...) is equivalent to malloc(...) */
639 return (malloc(size, mtp, flags));
642 * XXX: Should report free of old memory and alloc of new memory to
646 #ifdef DEBUG_MEMGUARD
647 if (is_memguard_addr(addr))
648 return (memguard_realloc(addr, size, mtp, flags));
653 alloc = redzone_get_size(addr);
655 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
658 KASSERT(slab != NULL,
659 ("realloc: address %p out of range", (void *)addr));
661 /* Get the size of the original block */
662 if (!(slab->us_flags & UMA_SLAB_MALLOC))
663 alloc = slab->us_keg->uk_size;
665 alloc = slab->us_size;
667 /* Reuse the original block if appropriate */
669 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
671 #endif /* !DEBUG_REDZONE */
673 /* Allocate a new, bigger (or smaller) block */
674 if ((newaddr = malloc(size, mtp, flags)) == NULL)
677 /* Copy over original contents */
678 bcopy(addr, newaddr, min(size, alloc));
684 * reallocf: same as realloc() but free memory on failure.
687 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
691 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
697 * Initialize the kernel memory allocator
701 kmeminit(void *dummy)
704 u_long mem_size, tmp;
707 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
710 * Try to auto-tune the kernel memory size, so that it is
711 * more applicable for a wider range of machine sizes. The
712 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
715 * Note that the kmem_map is also used by the zone allocator,
716 * so make sure that there is enough space.
718 vm_kmem_size = VM_KMEM_SIZE + nmbclusters * PAGE_SIZE;
719 mem_size = cnt.v_page_count;
721 #if defined(VM_KMEM_SIZE_SCALE)
722 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
724 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
725 if (vm_kmem_size_scale > 0 &&
726 (mem_size / vm_kmem_size_scale) > (vm_kmem_size / PAGE_SIZE))
727 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
729 #if defined(VM_KMEM_SIZE_MIN)
730 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
732 TUNABLE_ULONG_FETCH("vm.kmem_size_min", &vm_kmem_size_min);
733 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min) {
734 vm_kmem_size = vm_kmem_size_min;
737 #if defined(VM_KMEM_SIZE_MAX)
738 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
740 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
741 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
742 vm_kmem_size = vm_kmem_size_max;
744 /* Allow final override from the kernel environment */
745 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
748 * Limit kmem virtual size to twice the physical memory.
749 * This allows for kmem map sparseness, but limits the size
750 * to something sane. Be careful to not overflow the 32bit
751 * ints while doing the check or the adjustment.
753 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
754 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
756 #ifdef DEBUG_MEMGUARD
757 tmp = memguard_fudge(vm_kmem_size, kernel_map);
761 kmem_map = kmem_suballoc(kernel_map, &kmembase, &kmemlimit,
763 kmem_map->system_map = 1;
765 #ifdef DEBUG_MEMGUARD
767 * Initialize MemGuard if support compiled in. MemGuard is a
768 * replacement allocator used for detecting tamper-after-free
769 * scenarios as they occur. It is only used for debugging.
771 memguard_init(kmem_map);
776 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
778 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
780 NULL, NULL, NULL, NULL,
782 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
783 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
784 int size = kmemzones[indx].kz_size;
785 char *name = kmemzones[indx].kz_name;
788 for (subzone = 0; subzone < numzones; subzone++) {
789 kmemzones[indx].kz_zone[subzone] =
790 uma_zcreate(name, size,
792 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
794 NULL, NULL, NULL, NULL,
796 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
798 for (;i <= size; i+= KMEM_ZBASE)
799 kmemsize[i >> KMEM_ZSHIFT] = indx;
805 malloc_init(void *data)
807 struct malloc_type_internal *mtip;
808 struct malloc_type *mtp;
810 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
813 if (mtp->ks_magic != M_MAGIC)
814 panic("malloc_init: bad malloc type magic");
816 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
817 mtp->ks_handle = mtip;
818 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
820 mtx_lock(&malloc_mtx);
821 mtp->ks_next = kmemstatistics;
822 kmemstatistics = mtp;
824 mtx_unlock(&malloc_mtx);
828 malloc_uninit(void *data)
830 struct malloc_type_internal *mtip;
831 struct malloc_type_stats *mtsp;
832 struct malloc_type *mtp, *temp;
834 long temp_allocs, temp_bytes;
838 KASSERT(mtp->ks_magic == M_MAGIC,
839 ("malloc_uninit: bad malloc type magic"));
840 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
842 mtx_lock(&malloc_mtx);
843 mtip = mtp->ks_handle;
844 mtp->ks_handle = NULL;
845 if (mtp != kmemstatistics) {
846 for (temp = kmemstatistics; temp != NULL;
847 temp = temp->ks_next) {
848 if (temp->ks_next == mtp) {
849 temp->ks_next = mtp->ks_next;
854 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
856 kmemstatistics = mtp->ks_next;
858 mtx_unlock(&malloc_mtx);
861 * Look for memory leaks.
863 temp_allocs = temp_bytes = 0;
864 for (i = 0; i < MAXCPU; i++) {
865 mtsp = &mtip->mti_stats[i];
866 temp_allocs += mtsp->mts_numallocs;
867 temp_allocs -= mtsp->mts_numfrees;
868 temp_bytes += mtsp->mts_memalloced;
869 temp_bytes -= mtsp->mts_memfreed;
871 if (temp_allocs > 0 || temp_bytes > 0) {
872 printf("Warning: memory type %s leaked memory on destroy "
873 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
874 temp_allocs, temp_bytes);
877 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
878 uma_zfree_arg(mt_zone, mtip, slab);
882 malloc_desc2type(const char *desc)
884 struct malloc_type *mtp;
886 mtx_assert(&malloc_mtx, MA_OWNED);
887 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
888 if (strcmp(mtp->ks_shortdesc, desc) == 0)
895 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
897 struct malloc_type_stream_header mtsh;
898 struct malloc_type_internal *mtip;
899 struct malloc_type_header mth;
900 struct malloc_type *mtp;
904 error = sysctl_wire_old_buffer(req, 0);
907 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
908 mtx_lock(&malloc_mtx);
911 * Insert stream header.
913 bzero(&mtsh, sizeof(mtsh));
914 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
915 mtsh.mtsh_maxcpus = MAXCPU;
916 mtsh.mtsh_count = kmemcount;
917 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
920 * Insert alternating sequence of type headers and type statistics.
922 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
923 mtip = (struct malloc_type_internal *)mtp->ks_handle;
926 * Insert type header.
928 bzero(&mth, sizeof(mth));
929 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
930 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
933 * Insert type statistics for each CPU.
935 for (i = 0; i < MAXCPU; i++) {
936 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
937 sizeof(mtip->mti_stats[i]));
940 mtx_unlock(&malloc_mtx);
941 error = sbuf_finish(&sbuf);
946 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
947 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
948 "Return malloc types");
950 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
951 "Count of kernel malloc types");
954 malloc_type_list(malloc_type_list_func_t *func, void *arg)
956 struct malloc_type *mtp, **bufmtp;
960 mtx_lock(&malloc_mtx);
962 mtx_assert(&malloc_mtx, MA_OWNED);
964 mtx_unlock(&malloc_mtx);
966 buflen = sizeof(struct malloc_type *) * count;
967 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
969 mtx_lock(&malloc_mtx);
971 if (count < kmemcount) {
972 free(bufmtp, M_TEMP);
976 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
979 mtx_unlock(&malloc_mtx);
981 for (i = 0; i < count; i++)
982 (func)(bufmtp[i], arg);
984 free(bufmtp, M_TEMP);
988 DB_SHOW_COMMAND(malloc, db_show_malloc)
990 struct malloc_type_internal *mtip;
991 struct malloc_type *mtp;
992 uint64_t allocs, frees;
993 uint64_t alloced, freed;
996 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
998 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
999 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1004 for (i = 0; i < MAXCPU; i++) {
1005 allocs += mtip->mti_stats[i].mts_numallocs;
1006 frees += mtip->mti_stats[i].mts_numfrees;
1007 alloced += mtip->mti_stats[i].mts_memalloced;
1008 freed += mtip->mti_stats[i].mts_memfreed;
1010 db_printf("%18s %12ju %12juK %12ju\n",
1011 mtp->ks_shortdesc, allocs - frees,
1012 (alloced - freed + 1023) / 1024, allocs);
1018 #if MALLOC_DEBUG_MAXZONES > 1
1019 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1021 struct malloc_type_internal *mtip;
1022 struct malloc_type *mtp;
1026 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1030 if (mtp->ks_magic != M_MAGIC) {
1031 db_printf("Magic %lx does not match expected %x\n",
1032 mtp->ks_magic, M_MAGIC);
1036 mtip = mtp->ks_handle;
1037 subzone = mtip->mti_zone;
1039 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1040 mtip = mtp->ks_handle;
1041 if (mtip->mti_zone != subzone)
1043 db_printf("%s\n", mtp->ks_shortdesc);
1048 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1051 #ifdef MALLOC_PROFILE
1054 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1068 error = sysctl_wire_old_buffer(req, 0);
1071 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1073 "\n Size Requests Real Size\n");
1074 for (i = 0; i < KMEM_ZSIZE; i++) {
1075 size = i << KMEM_ZSHIFT;
1076 rsize = kmemzones[kmemsize[i]].kz_size;
1077 count = (long long unsigned)krequests[i];
1079 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1080 (unsigned long long)count, rsize);
1082 if ((rsize * count) > (size * count))
1083 waste += (rsize * count) - (size * count);
1084 mem += (rsize * count);
1087 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1088 (unsigned long long)mem, (unsigned long long)waste);
1089 error = sbuf_finish(&sbuf);
1094 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1095 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1096 #endif /* MALLOC_PROFILE */