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>
58 #include <sys/mutex.h>
59 #include <sys/vmmeter.h>
62 #include <sys/sysctl.h>
68 #include <vm/vm_pageout.h>
69 #include <vm/vm_param.h>
70 #include <vm/vm_kern.h>
71 #include <vm/vm_extern.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_page.h>
75 #include <vm/uma_int.h>
76 #include <vm/uma_dbg.h>
79 #include <vm/memguard.h>
82 #include <vm/redzone.h>
85 #if defined(INVARIANTS) && defined(__i386__)
86 #include <machine/cpu.h>
92 #include <sys/dtrace_bsd.h>
94 dtrace_malloc_probe_func_t dtrace_malloc_probe;
98 * When realloc() is called, if the new size is sufficiently smaller than
99 * the old size, realloc() will allocate a new, smaller block to avoid
100 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
101 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
103 #ifndef REALLOC_FRACTION
104 #define REALLOC_FRACTION 1 /* new block if <= half the size */
108 * Centrally define some common malloc types.
110 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
111 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
112 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
114 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
115 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
117 static struct malloc_type *kmemstatistics;
118 static int kmemcount;
120 #define KMEM_ZSHIFT 4
121 #define KMEM_ZBASE 16
122 #define KMEM_ZMASK (KMEM_ZBASE - 1)
124 #define KMEM_ZMAX 65536
125 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
126 static uint8_t kmemsize[KMEM_ZSIZE + 1];
128 #ifndef MALLOC_DEBUG_MAXZONES
129 #define MALLOC_DEBUG_MAXZONES 1
131 static int numzones = MALLOC_DEBUG_MAXZONES;
134 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
137 * XXX: The comment here used to read "These won't be powers of two for
138 * long." It's possible that a significant amount of wasted memory could be
139 * recovered by tuning the sizes of these buckets.
144 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
163 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
164 * types are described by a data structure passed by the declaring code, but
165 * the malloc(9) implementation has its own data structure describing the
166 * type and statistics. This permits the malloc(9)-internal data structures
167 * to be modified without breaking binary-compiled kernel modules that
168 * declare malloc types.
170 static uma_zone_t mt_zone;
173 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
174 "Size of kernel memory");
176 static u_long kmem_zmax = KMEM_ZMAX;
177 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
178 "Maximum allocation size that malloc(9) would use UMA as backend");
180 static u_long vm_kmem_size_min;
181 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
182 "Minimum size of kernel memory");
184 static u_long vm_kmem_size_max;
185 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
186 "Maximum size of kernel memory");
188 static u_int vm_kmem_size_scale;
189 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
190 "Scale factor for kernel memory size");
192 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
193 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
194 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
195 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
197 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
198 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
199 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
200 sysctl_kmem_map_free, "LU", "Free space in kmem");
203 * The malloc_mtx protects the kmemstatistics linked list.
205 struct mtx malloc_mtx;
207 #ifdef MALLOC_PROFILE
208 uint64_t krequests[KMEM_ZSIZE + 1];
210 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
213 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
216 * time_uptime of the last malloc(9) failure (induced or real).
218 static time_t t_malloc_fail;
220 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
221 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
222 "Kernel malloc debugging options");
226 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
227 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
229 #ifdef MALLOC_MAKE_FAILURES
230 static int malloc_failure_rate;
231 static int malloc_nowait_count;
232 static int malloc_failure_count;
233 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RW,
234 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
235 TUNABLE_INT("debug.malloc.failure_rate", &malloc_failure_rate);
236 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
237 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
241 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
245 size = vmem_size(kmem_arena, VMEM_ALLOC);
246 return (sysctl_handle_long(oidp, &size, 0, req));
250 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
254 size = vmem_size(kmem_arena, VMEM_FREE);
255 return (sysctl_handle_long(oidp, &size, 0, req));
259 * malloc(9) uma zone separation -- sub-page buffer overruns in one
260 * malloc type will affect only a subset of other malloc types.
262 #if MALLOC_DEBUG_MAXZONES > 1
264 tunable_set_numzones(void)
267 TUNABLE_INT_FETCH("debug.malloc.numzones",
270 /* Sanity check the number of malloc uma zones. */
273 if (numzones > MALLOC_DEBUG_MAXZONES)
274 numzones = MALLOC_DEBUG_MAXZONES;
276 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
277 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN,
278 &numzones, 0, "Number of malloc uma subzones");
281 * Any number that changes regularly is an okay choice for the
282 * offset. Build numbers are pretty good of you have them.
284 static u_int zone_offset = __FreeBSD_version;
285 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
286 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
287 &zone_offset, 0, "Separate malloc types by examining the "
288 "Nth character in the malloc type short description.");
291 mtp_get_subzone(const char *desc)
296 if (desc == NULL || (len = strlen(desc)) == 0)
298 val = desc[zone_offset % len];
299 return (val % numzones);
301 #elif MALLOC_DEBUG_MAXZONES == 0
302 #error "MALLOC_DEBUG_MAXZONES must be positive."
305 mtp_get_subzone(const char *desc)
310 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
313 malloc_last_fail(void)
316 return (time_uptime - t_malloc_fail);
320 * An allocation has succeeded -- update malloc type statistics for the
321 * amount of bucket size. Occurs within a critical section so that the
322 * thread isn't preempted and doesn't migrate while updating per-PCU
326 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
329 struct malloc_type_internal *mtip;
330 struct malloc_type_stats *mtsp;
333 mtip = mtp->ks_handle;
334 mtsp = &mtip->mti_stats[curcpu];
336 mtsp->mts_memalloced += size;
337 mtsp->mts_numallocs++;
340 mtsp->mts_size |= 1 << zindx;
343 if (dtrace_malloc_probe != NULL) {
344 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
346 (dtrace_malloc_probe)(probe_id,
347 (uintptr_t) mtp, (uintptr_t) mtip,
348 (uintptr_t) mtsp, size, zindx);
356 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
360 malloc_type_zone_allocated(mtp, size, -1);
364 * A free operation has occurred -- update malloc type statistics for the
365 * amount of the bucket size. Occurs within a critical section so that the
366 * thread isn't preempted and doesn't migrate while updating per-CPU
370 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
372 struct malloc_type_internal *mtip;
373 struct malloc_type_stats *mtsp;
376 mtip = mtp->ks_handle;
377 mtsp = &mtip->mti_stats[curcpu];
378 mtsp->mts_memfreed += size;
379 mtsp->mts_numfrees++;
382 if (dtrace_malloc_probe != NULL) {
383 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
385 (dtrace_malloc_probe)(probe_id,
386 (uintptr_t) mtp, (uintptr_t) mtip,
387 (uintptr_t) mtsp, size, 0);
397 * Allocate a block of physically contiguous memory.
399 * If M_NOWAIT is set, this routine will not block and return NULL if
400 * the allocation fails.
403 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
404 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
409 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
410 alignment, boundary, VM_MEMATTR_DEFAULT);
412 malloc_type_allocated(type, round_page(size));
419 * Free a block of memory allocated by contigmalloc.
421 * This routine may not block.
424 contigfree(void *addr, unsigned long size, struct malloc_type *type)
427 kmem_free(kernel_arena, (vm_offset_t)addr, size);
428 malloc_type_freed(type, round_page(size));
434 * Allocate a block of memory.
436 * If M_NOWAIT is set, this routine will not block and return NULL if
437 * the allocation fails.
440 malloc(unsigned long size, struct malloc_type *mtp, int flags)
443 struct malloc_type_internal *mtip;
446 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
447 unsigned long osize = size;
451 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
453 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
455 indx = flags & (M_WAITOK | M_NOWAIT);
456 if (indx != M_NOWAIT && indx != M_WAITOK) {
457 static struct timeval lasterr;
458 static int curerr, once;
459 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
460 printf("Bad malloc flags: %x\n", indx);
467 #ifdef MALLOC_MAKE_FAILURES
468 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
469 atomic_add_int(&malloc_nowait_count, 1);
470 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
471 atomic_add_int(&malloc_failure_count, 1);
472 t_malloc_fail = time_uptime;
477 if (flags & M_WAITOK)
478 KASSERT(curthread->td_intr_nesting_level == 0,
479 ("malloc(M_WAITOK) in interrupt context"));
481 #ifdef DEBUG_MEMGUARD
482 if (memguard_cmp_mtp(mtp, size)) {
483 va = memguard_alloc(size, flags);
486 /* This is unfortunate but should not be fatal. */
491 size = redzone_size_ntor(size);
494 if (size <= kmem_zmax) {
495 mtip = mtp->ks_handle;
496 if (size & KMEM_ZMASK)
497 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
498 indx = kmemsize[size >> KMEM_ZSHIFT];
499 KASSERT(mtip->mti_zone < numzones,
500 ("mti_zone %u out of range %d",
501 mtip->mti_zone, numzones));
502 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
503 #ifdef MALLOC_PROFILE
504 krequests[size >> KMEM_ZSHIFT]++;
506 va = uma_zalloc(zone, flags);
508 size = zone->uz_size;
509 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
511 size = roundup(size, PAGE_SIZE);
513 va = uma_large_malloc(size, flags);
514 malloc_type_allocated(mtp, va == NULL ? 0 : size);
516 if (flags & M_WAITOK)
517 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
519 t_malloc_fail = time_uptime;
521 if (va != NULL && !(flags & M_ZERO)) {
522 memset(va, 0x70, osize);
527 va = redzone_setup(va, osize);
529 return ((void *) va);
535 * Free a block of memory allocated by malloc.
537 * This routine may not block.
540 free(void *addr, struct malloc_type *mtp)
545 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
547 /* free(NULL, ...) does nothing */
551 #ifdef DEBUG_MEMGUARD
552 if (is_memguard_addr(addr)) {
560 addr = redzone_addr_ntor(addr);
563 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
566 panic("free: address %p(%p) has not been allocated.\n",
567 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
569 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
571 struct malloc_type **mtpp = addr;
573 size = slab->us_keg->uk_size;
576 * Cache a pointer to the malloc_type that most recently freed
577 * this memory here. This way we know who is most likely to
578 * have stepped on it later.
580 * This code assumes that size is a multiple of 8 bytes for
583 mtpp = (struct malloc_type **)
584 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
585 mtpp += (size - sizeof(struct malloc_type *)) /
586 sizeof(struct malloc_type *);
589 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
591 size = slab->us_size;
592 uma_large_free(slab);
594 malloc_type_freed(mtp, size);
598 * realloc: change the size of a memory block
601 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
607 KASSERT(mtp->ks_magic == M_MAGIC,
608 ("realloc: bad malloc type magic"));
610 /* realloc(NULL, ...) is equivalent to malloc(...) */
612 return (malloc(size, mtp, flags));
615 * XXX: Should report free of old memory and alloc of new memory to
619 #ifdef DEBUG_MEMGUARD
620 if (is_memguard_addr(addr))
621 return (memguard_realloc(addr, size, mtp, flags));
626 alloc = redzone_get_size(addr);
628 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
631 KASSERT(slab != NULL,
632 ("realloc: address %p out of range", (void *)addr));
634 /* Get the size of the original block */
635 if (!(slab->us_flags & UMA_SLAB_MALLOC))
636 alloc = slab->us_keg->uk_size;
638 alloc = slab->us_size;
640 /* Reuse the original block if appropriate */
642 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
644 #endif /* !DEBUG_REDZONE */
646 /* Allocate a new, bigger (or smaller) block */
647 if ((newaddr = malloc(size, mtp, flags)) == NULL)
650 /* Copy over original contents */
651 bcopy(addr, newaddr, min(size, alloc));
657 * reallocf: same as realloc() but free memory on failure.
660 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
664 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
670 * Wake the uma reclamation pagedaemon thread when we exhaust KVA. It
671 * will call the lowmem handler and uma_reclaim() callbacks in a
672 * context that is safe.
675 kmem_reclaim(vmem_t *vm, int flags)
678 uma_reclaim_wakeup();
682 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
685 * Initialize the kernel memory (kmem) arena.
690 u_long mem_size, tmp;
693 * Calculate the amount of kernel virtual address (KVA) space that is
694 * preallocated to the kmem arena. In order to support a wide range
695 * of machines, it is a function of the physical memory size,
698 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
699 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
701 * Every architecture must define an integral value for
702 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
703 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
704 * ceiling on this preallocation, are optional. Typically,
705 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
706 * a given architecture.
708 mem_size = cnt.v_page_count;
710 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
711 TUNABLE_INT_FETCH("vm.kmem_size_scale", &vm_kmem_size_scale);
712 if (vm_kmem_size_scale < 1)
713 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
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;
724 #if defined(VM_KMEM_SIZE_MAX)
725 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
727 TUNABLE_ULONG_FETCH("vm.kmem_size_max", &vm_kmem_size_max);
728 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
729 vm_kmem_size = vm_kmem_size_max;
732 * Alternatively, the amount of KVA space that is preallocated to the
733 * kmem arena can be set statically at compile-time or manually
734 * through the kernel environment. However, it is still limited to
735 * twice the physical memory size, which has been sufficient to handle
736 * the most severe cases of external fragmentation in the kmem arena.
738 #if defined(VM_KMEM_SIZE)
739 vm_kmem_size = VM_KMEM_SIZE;
741 TUNABLE_ULONG_FETCH("vm.kmem_size", &vm_kmem_size);
742 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
743 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
745 vm_kmem_size = round_page(vm_kmem_size);
746 #ifdef DEBUG_MEMGUARD
747 tmp = memguard_fudge(vm_kmem_size, kernel_map);
751 vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE,
753 vmem_set_reclaim(kmem_arena, kmem_reclaim);
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_arena);
766 * Initialize the kernel memory allocator
770 mallocinit(void *dummy)
775 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
781 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
782 kmem_zmax = KMEM_ZMAX;
784 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
786 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
788 NULL, NULL, NULL, NULL,
790 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
791 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
792 int size = kmemzones[indx].kz_size;
793 char *name = kmemzones[indx].kz_name;
796 for (subzone = 0; subzone < numzones; subzone++) {
797 kmemzones[indx].kz_zone[subzone] =
798 uma_zcreate(name, size,
800 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
802 NULL, NULL, NULL, NULL,
804 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
806 for (;i <= size; i+= KMEM_ZBASE)
807 kmemsize[i >> KMEM_ZSHIFT] = indx;
811 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, mallocinit, NULL);
814 malloc_init(void *data)
816 struct malloc_type_internal *mtip;
817 struct malloc_type *mtp;
819 KASSERT(cnt.v_page_count != 0, ("malloc_register before vm_init"));
822 if (mtp->ks_magic != M_MAGIC)
823 panic("malloc_init: bad malloc type magic");
825 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
826 mtp->ks_handle = mtip;
827 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
829 mtx_lock(&malloc_mtx);
830 mtp->ks_next = kmemstatistics;
831 kmemstatistics = mtp;
833 mtx_unlock(&malloc_mtx);
837 malloc_uninit(void *data)
839 struct malloc_type_internal *mtip;
840 struct malloc_type_stats *mtsp;
841 struct malloc_type *mtp, *temp;
843 long temp_allocs, temp_bytes;
847 KASSERT(mtp->ks_magic == M_MAGIC,
848 ("malloc_uninit: bad malloc type magic"));
849 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
851 mtx_lock(&malloc_mtx);
852 mtip = mtp->ks_handle;
853 mtp->ks_handle = NULL;
854 if (mtp != kmemstatistics) {
855 for (temp = kmemstatistics; temp != NULL;
856 temp = temp->ks_next) {
857 if (temp->ks_next == mtp) {
858 temp->ks_next = mtp->ks_next;
863 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
865 kmemstatistics = mtp->ks_next;
867 mtx_unlock(&malloc_mtx);
870 * Look for memory leaks.
872 temp_allocs = temp_bytes = 0;
873 for (i = 0; i < MAXCPU; i++) {
874 mtsp = &mtip->mti_stats[i];
875 temp_allocs += mtsp->mts_numallocs;
876 temp_allocs -= mtsp->mts_numfrees;
877 temp_bytes += mtsp->mts_memalloced;
878 temp_bytes -= mtsp->mts_memfreed;
880 if (temp_allocs > 0 || temp_bytes > 0) {
881 printf("Warning: memory type %s leaked memory on destroy "
882 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
883 temp_allocs, temp_bytes);
886 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
887 uma_zfree_arg(mt_zone, mtip, slab);
891 malloc_desc2type(const char *desc)
893 struct malloc_type *mtp;
895 mtx_assert(&malloc_mtx, MA_OWNED);
896 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
897 if (strcmp(mtp->ks_shortdesc, desc) == 0)
904 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
906 struct malloc_type_stream_header mtsh;
907 struct malloc_type_internal *mtip;
908 struct malloc_type_header mth;
909 struct malloc_type *mtp;
913 error = sysctl_wire_old_buffer(req, 0);
916 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
917 mtx_lock(&malloc_mtx);
920 * Insert stream header.
922 bzero(&mtsh, sizeof(mtsh));
923 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
924 mtsh.mtsh_maxcpus = MAXCPU;
925 mtsh.mtsh_count = kmemcount;
926 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
929 * Insert alternating sequence of type headers and type statistics.
931 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
932 mtip = (struct malloc_type_internal *)mtp->ks_handle;
935 * Insert type header.
937 bzero(&mth, sizeof(mth));
938 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
939 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
942 * Insert type statistics for each CPU.
944 for (i = 0; i < MAXCPU; i++) {
945 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
946 sizeof(mtip->mti_stats[i]));
949 mtx_unlock(&malloc_mtx);
950 error = sbuf_finish(&sbuf);
955 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
956 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
957 "Return malloc types");
959 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
960 "Count of kernel malloc types");
963 malloc_type_list(malloc_type_list_func_t *func, void *arg)
965 struct malloc_type *mtp, **bufmtp;
969 mtx_lock(&malloc_mtx);
971 mtx_assert(&malloc_mtx, MA_OWNED);
973 mtx_unlock(&malloc_mtx);
975 buflen = sizeof(struct malloc_type *) * count;
976 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
978 mtx_lock(&malloc_mtx);
980 if (count < kmemcount) {
981 free(bufmtp, M_TEMP);
985 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
988 mtx_unlock(&malloc_mtx);
990 for (i = 0; i < count; i++)
991 (func)(bufmtp[i], arg);
993 free(bufmtp, M_TEMP);
997 DB_SHOW_COMMAND(malloc, db_show_malloc)
999 struct malloc_type_internal *mtip;
1000 struct malloc_type *mtp;
1001 uint64_t allocs, frees;
1002 uint64_t alloced, freed;
1005 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1007 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1008 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1013 for (i = 0; i < MAXCPU; i++) {
1014 allocs += mtip->mti_stats[i].mts_numallocs;
1015 frees += mtip->mti_stats[i].mts_numfrees;
1016 alloced += mtip->mti_stats[i].mts_memalloced;
1017 freed += mtip->mti_stats[i].mts_memfreed;
1019 db_printf("%18s %12ju %12juK %12ju\n",
1020 mtp->ks_shortdesc, allocs - frees,
1021 (alloced - freed + 1023) / 1024, allocs);
1027 #if MALLOC_DEBUG_MAXZONES > 1
1028 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1030 struct malloc_type_internal *mtip;
1031 struct malloc_type *mtp;
1035 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1039 if (mtp->ks_magic != M_MAGIC) {
1040 db_printf("Magic %lx does not match expected %x\n",
1041 mtp->ks_magic, M_MAGIC);
1045 mtip = mtp->ks_handle;
1046 subzone = mtip->mti_zone;
1048 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1049 mtip = mtp->ks_handle;
1050 if (mtip->mti_zone != subzone)
1052 db_printf("%s\n", mtp->ks_shortdesc);
1057 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1060 #ifdef MALLOC_PROFILE
1063 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1077 error = sysctl_wire_old_buffer(req, 0);
1080 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1082 "\n Size Requests Real Size\n");
1083 for (i = 0; i < KMEM_ZSIZE; i++) {
1084 size = i << KMEM_ZSHIFT;
1085 rsize = kmemzones[kmemsize[i]].kz_size;
1086 count = (long long unsigned)krequests[i];
1088 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1089 (unsigned long long)count, rsize);
1091 if ((rsize * count) > (size * count))
1092 waste += (rsize * count) - (size * count);
1093 mem += (rsize * count);
1096 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1097 (unsigned long long)mem, (unsigned long long)waste);
1098 error = sbuf_finish(&sbuf);
1103 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1104 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1105 #endif /* MALLOC_PROFILE */