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 * 3. 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$");
51 #include <sys/param.h>
52 #include <sys/systm.h>
54 #include <sys/kernel.h>
56 #include <sys/malloc.h>
57 #include <sys/mutex.h>
58 #include <sys/vmmeter.h>
61 #include <sys/sysctl.h>
67 #include <vm/vm_pageout.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 static struct malloc_type *kmemstatistics;
114 static int kmemcount;
116 #define KMEM_ZSHIFT 4
117 #define KMEM_ZBASE 16
118 #define KMEM_ZMASK (KMEM_ZBASE - 1)
120 #define KMEM_ZMAX 65536
121 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
122 static uint8_t kmemsize[KMEM_ZSIZE + 1];
124 #ifndef MALLOC_DEBUG_MAXZONES
125 #define MALLOC_DEBUG_MAXZONES 1
127 static int numzones = MALLOC_DEBUG_MAXZONES;
130 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
133 * XXX: The comment here used to read "These won't be powers of two for
134 * long." It's possible that a significant amount of wasted memory could be
135 * recovered by tuning the sizes of these buckets.
140 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
159 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
160 * types are described by a data structure passed by the declaring code, but
161 * the malloc(9) implementation has its own data structure describing the
162 * type and statistics. This permits the malloc(9)-internal data structures
163 * to be modified without breaking binary-compiled kernel modules that
164 * declare malloc types.
166 static uma_zone_t mt_zone;
169 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
170 "Size of kernel memory");
172 static u_long kmem_zmax = KMEM_ZMAX;
173 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
174 "Maximum allocation size that malloc(9) would use UMA as backend");
176 static u_long vm_kmem_size_min;
177 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
178 "Minimum size of kernel memory");
180 static u_long vm_kmem_size_max;
181 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
182 "Maximum size of kernel memory");
184 static u_int vm_kmem_size_scale;
185 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
186 "Scale factor for kernel memory size");
188 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
189 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
190 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
191 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
193 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
194 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
195 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
196 sysctl_kmem_map_free, "LU", "Free space in kmem");
199 * The malloc_mtx protects the kmemstatistics linked list.
201 struct mtx malloc_mtx;
203 #ifdef MALLOC_PROFILE
204 uint64_t krequests[KMEM_ZSIZE + 1];
206 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
209 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
212 * time_uptime of the last malloc(9) failure (induced or real).
214 static time_t t_malloc_fail;
216 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
217 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD, 0,
218 "Kernel malloc debugging options");
222 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
223 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
225 #ifdef MALLOC_MAKE_FAILURES
226 static int malloc_failure_rate;
227 static int malloc_nowait_count;
228 static int malloc_failure_count;
229 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
230 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
231 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
232 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
236 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
240 size = vmem_size(kmem_arena, VMEM_ALLOC);
241 return (sysctl_handle_long(oidp, &size, 0, req));
245 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
249 size = vmem_size(kmem_arena, VMEM_FREE);
250 return (sysctl_handle_long(oidp, &size, 0, req));
254 * malloc(9) uma zone separation -- sub-page buffer overruns in one
255 * malloc type will affect only a subset of other malloc types.
257 #if MALLOC_DEBUG_MAXZONES > 1
259 tunable_set_numzones(void)
262 TUNABLE_INT_FETCH("debug.malloc.numzones",
265 /* Sanity check the number of malloc uma zones. */
268 if (numzones > MALLOC_DEBUG_MAXZONES)
269 numzones = MALLOC_DEBUG_MAXZONES;
271 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
272 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
273 &numzones, 0, "Number of malloc uma subzones");
276 * Any number that changes regularly is an okay choice for the
277 * offset. Build numbers are pretty good of you have them.
279 static u_int zone_offset = __FreeBSD_version;
280 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
281 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
282 &zone_offset, 0, "Separate malloc types by examining the "
283 "Nth character in the malloc type short description.");
286 mtp_get_subzone(const char *desc)
291 if (desc == NULL || (len = strlen(desc)) == 0)
293 val = desc[zone_offset % len];
294 return (val % numzones);
296 #elif MALLOC_DEBUG_MAXZONES == 0
297 #error "MALLOC_DEBUG_MAXZONES must be positive."
300 mtp_get_subzone(const char *desc)
305 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
308 malloc_last_fail(void)
311 return (time_uptime - t_malloc_fail);
315 * An allocation has succeeded -- update malloc type statistics for the
316 * amount of bucket size. Occurs within a critical section so that the
317 * thread isn't preempted and doesn't migrate while updating per-PCU
321 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
324 struct malloc_type_internal *mtip;
325 struct malloc_type_stats *mtsp;
328 mtip = mtp->ks_handle;
329 mtsp = &mtip->mti_stats[curcpu];
331 mtsp->mts_memalloced += size;
332 mtsp->mts_numallocs++;
335 mtsp->mts_size |= 1 << zindx;
338 if (dtrace_malloc_probe != NULL) {
339 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
341 (dtrace_malloc_probe)(probe_id,
342 (uintptr_t) mtp, (uintptr_t) mtip,
343 (uintptr_t) mtsp, size, zindx);
351 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
355 malloc_type_zone_allocated(mtp, size, -1);
359 * A free operation has occurred -- update malloc type statistics for the
360 * amount of the bucket size. Occurs within a critical section so that the
361 * thread isn't preempted and doesn't migrate while updating per-CPU
365 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
367 struct malloc_type_internal *mtip;
368 struct malloc_type_stats *mtsp;
371 mtip = mtp->ks_handle;
372 mtsp = &mtip->mti_stats[curcpu];
373 mtsp->mts_memfreed += size;
374 mtsp->mts_numfrees++;
377 if (dtrace_malloc_probe != NULL) {
378 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
380 (dtrace_malloc_probe)(probe_id,
381 (uintptr_t) mtp, (uintptr_t) mtip,
382 (uintptr_t) mtsp, size, 0);
392 * Allocate a block of physically contiguous memory.
394 * If M_NOWAIT is set, this routine will not block and return NULL if
395 * the allocation fails.
398 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
399 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
404 ret = (void *)kmem_alloc_contig(kernel_arena, size, flags, low, high,
405 alignment, boundary, VM_MEMATTR_DEFAULT);
407 malloc_type_allocated(type, round_page(size));
414 * Free a block of memory allocated by contigmalloc.
416 * This routine may not block.
419 contigfree(void *addr, unsigned long size, struct malloc_type *type)
422 kmem_free(kernel_arena, (vm_offset_t)addr, size);
423 malloc_type_freed(type, round_page(size));
429 * Allocate a block of memory.
431 * If M_NOWAIT is set, this routine will not block and return NULL if
432 * the allocation fails.
435 malloc(unsigned long size, struct malloc_type *mtp, int flags)
438 struct malloc_type_internal *mtip;
441 #if defined(DIAGNOSTIC) || defined(DEBUG_REDZONE)
442 unsigned long osize = size;
446 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
448 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
450 indx = flags & (M_WAITOK | M_NOWAIT);
451 if (indx != M_NOWAIT && indx != M_WAITOK) {
452 static struct timeval lasterr;
453 static int curerr, once;
454 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
455 printf("Bad malloc flags: %x\n", indx);
462 #ifdef MALLOC_MAKE_FAILURES
463 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
464 atomic_add_int(&malloc_nowait_count, 1);
465 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
466 atomic_add_int(&malloc_failure_count, 1);
467 t_malloc_fail = time_uptime;
472 if (flags & M_WAITOK)
473 KASSERT(curthread->td_intr_nesting_level == 0,
474 ("malloc(M_WAITOK) in interrupt context"));
475 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
476 ("malloc: called with spinlock or critical section held"));
478 #ifdef DEBUG_MEMGUARD
479 if (memguard_cmp_mtp(mtp, size)) {
480 va = memguard_alloc(size, flags);
483 /* This is unfortunate but should not be fatal. */
488 size = redzone_size_ntor(size);
491 if (size <= kmem_zmax) {
492 mtip = mtp->ks_handle;
493 if (size & KMEM_ZMASK)
494 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
495 indx = kmemsize[size >> KMEM_ZSHIFT];
496 KASSERT(mtip->mti_zone < numzones,
497 ("mti_zone %u out of range %d",
498 mtip->mti_zone, numzones));
499 zone = kmemzones[indx].kz_zone[mtip->mti_zone];
500 #ifdef MALLOC_PROFILE
501 krequests[size >> KMEM_ZSHIFT]++;
503 va = uma_zalloc(zone, flags);
505 size = zone->uz_size;
506 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
508 size = roundup(size, PAGE_SIZE);
510 va = uma_large_malloc(size, flags);
511 malloc_type_allocated(mtp, va == NULL ? 0 : size);
513 if (flags & M_WAITOK)
514 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
516 t_malloc_fail = time_uptime;
518 if (va != NULL && !(flags & M_ZERO)) {
519 memset(va, 0x70, osize);
524 va = redzone_setup(va, osize);
526 return ((void *) va);
532 * Free a block of memory allocated by malloc.
534 * This routine may not block.
537 free(void *addr, struct malloc_type *mtp)
542 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
543 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
544 ("free: called with spinlock or critical section held"));
546 /* free(NULL, ...) does nothing */
550 #ifdef DEBUG_MEMGUARD
551 if (is_memguard_addr(addr)) {
559 addr = redzone_addr_ntor(addr);
562 slab = vtoslab((vm_offset_t)addr & (~UMA_SLAB_MASK));
565 panic("free: address %p(%p) has not been allocated.\n",
566 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
568 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
570 struct malloc_type **mtpp = addr;
572 size = slab->us_keg->uk_size;
575 * Cache a pointer to the malloc_type that most recently freed
576 * this memory here. This way we know who is most likely to
577 * have stepped on it later.
579 * This code assumes that size is a multiple of 8 bytes for
582 mtpp = (struct malloc_type **)
583 ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
584 mtpp += (size - sizeof(struct malloc_type *)) /
585 sizeof(struct malloc_type *);
588 uma_zfree_arg(LIST_FIRST(&slab->us_keg->uk_zones), addr, slab);
590 size = slab->us_size;
591 uma_large_free(slab);
593 malloc_type_freed(mtp, size);
597 * realloc: change the size of a memory block
600 realloc(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
606 KASSERT(mtp->ks_magic == M_MAGIC,
607 ("realloc: bad malloc type magic"));
608 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
609 ("realloc: called with spinlock or critical section held"));
611 /* realloc(NULL, ...) is equivalent to malloc(...) */
613 return (malloc(size, mtp, flags));
616 * XXX: Should report free of old memory and alloc of new memory to
620 #ifdef DEBUG_MEMGUARD
621 if (is_memguard_addr(addr))
622 return (memguard_realloc(addr, size, mtp, flags));
627 alloc = redzone_get_size(addr);
629 slab = vtoslab((vm_offset_t)addr & ~(UMA_SLAB_MASK));
632 KASSERT(slab != NULL,
633 ("realloc: address %p out of range", (void *)addr));
635 /* Get the size of the original block */
636 if (!(slab->us_flags & UMA_SLAB_MALLOC))
637 alloc = slab->us_keg->uk_size;
639 alloc = slab->us_size;
641 /* Reuse the original block if appropriate */
643 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
645 #endif /* !DEBUG_REDZONE */
647 /* Allocate a new, bigger (or smaller) block */
648 if ((newaddr = malloc(size, mtp, flags)) == NULL)
651 /* Copy over original contents */
652 bcopy(addr, newaddr, min(size, alloc));
658 * reallocf: same as realloc() but free memory on failure.
661 reallocf(void *addr, unsigned long size, struct malloc_type *mtp, int flags)
665 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
671 * Wake the uma reclamation pagedaemon thread when we exhaust KVA. It
672 * will call the lowmem handler and uma_reclaim() callbacks in a
673 * context that is safe.
676 kmem_reclaim(vmem_t *vm, int flags)
679 uma_reclaim_wakeup();
684 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
688 * Initialize the kernel memory (kmem) arena.
697 if (vm_kmem_size == 0)
698 vm_kmem_size = VM_KMEM_SIZE;
700 #ifdef VM_KMEM_SIZE_MIN
701 if (vm_kmem_size_min == 0)
702 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
704 #ifdef VM_KMEM_SIZE_MAX
705 if (vm_kmem_size_max == 0)
706 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
709 * Calculate the amount of kernel virtual address (KVA) space that is
710 * preallocated to the kmem arena. In order to support a wide range
711 * of machines, it is a function of the physical memory size,
714 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
715 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
717 * Every architecture must define an integral value for
718 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
719 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
720 * ceiling on this preallocation, are optional. Typically,
721 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
722 * a given architecture.
724 mem_size = vm_cnt.v_page_count;
725 if (mem_size <= 32768) /* delphij XXX 128MB */
726 kmem_zmax = PAGE_SIZE;
728 if (vm_kmem_size_scale < 1)
729 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
732 * Check if we should use defaults for the "vm_kmem_size"
735 if (vm_kmem_size == 0) {
736 vm_kmem_size = (mem_size / vm_kmem_size_scale) * PAGE_SIZE;
738 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
739 vm_kmem_size = vm_kmem_size_min;
740 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
741 vm_kmem_size = vm_kmem_size_max;
745 * The amount of KVA space that is preallocated to the
746 * kmem arena can be set statically at compile-time or manually
747 * through the kernel environment. However, it is still limited to
748 * twice the physical memory size, which has been sufficient to handle
749 * the most severe cases of external fragmentation in the kmem arena.
751 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
752 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
754 vm_kmem_size = round_page(vm_kmem_size);
755 #ifdef DEBUG_MEMGUARD
756 tmp = memguard_fudge(vm_kmem_size, kernel_map);
760 vmem_init(kmem_arena, "kmem arena", kva_alloc(tmp), tmp, PAGE_SIZE,
762 vmem_set_reclaim(kmem_arena, kmem_reclaim);
764 #ifdef DEBUG_MEMGUARD
766 * Initialize MemGuard if support compiled in. MemGuard is a
767 * replacement allocator used for detecting tamper-after-free
768 * scenarios as they occur. It is only used for debugging.
770 memguard_init(kmem_arena);
775 * Initialize the kernel memory allocator
779 mallocinit(void *dummy)
784 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
790 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
791 kmem_zmax = KMEM_ZMAX;
793 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
795 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
797 NULL, NULL, NULL, NULL,
799 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
800 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
801 int size = kmemzones[indx].kz_size;
802 char *name = kmemzones[indx].kz_name;
805 for (subzone = 0; subzone < numzones; subzone++) {
806 kmemzones[indx].kz_zone[subzone] =
807 uma_zcreate(name, size,
809 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
811 NULL, NULL, NULL, NULL,
813 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
815 for (;i <= size; i+= KMEM_ZBASE)
816 kmemsize[i >> KMEM_ZSHIFT] = indx;
820 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
823 malloc_init(void *data)
825 struct malloc_type_internal *mtip;
826 struct malloc_type *mtp;
828 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
831 if (mtp->ks_magic != M_MAGIC)
832 panic("malloc_init: bad malloc type magic");
834 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
835 mtp->ks_handle = mtip;
836 mtip->mti_zone = mtp_get_subzone(mtp->ks_shortdesc);
838 mtx_lock(&malloc_mtx);
839 mtp->ks_next = kmemstatistics;
840 kmemstatistics = mtp;
842 mtx_unlock(&malloc_mtx);
846 malloc_uninit(void *data)
848 struct malloc_type_internal *mtip;
849 struct malloc_type_stats *mtsp;
850 struct malloc_type *mtp, *temp;
852 long temp_allocs, temp_bytes;
856 KASSERT(mtp->ks_magic == M_MAGIC,
857 ("malloc_uninit: bad malloc type magic"));
858 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
860 mtx_lock(&malloc_mtx);
861 mtip = mtp->ks_handle;
862 mtp->ks_handle = NULL;
863 if (mtp != kmemstatistics) {
864 for (temp = kmemstatistics; temp != NULL;
865 temp = temp->ks_next) {
866 if (temp->ks_next == mtp) {
867 temp->ks_next = mtp->ks_next;
872 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
874 kmemstatistics = mtp->ks_next;
876 mtx_unlock(&malloc_mtx);
879 * Look for memory leaks.
881 temp_allocs = temp_bytes = 0;
882 for (i = 0; i < MAXCPU; i++) {
883 mtsp = &mtip->mti_stats[i];
884 temp_allocs += mtsp->mts_numallocs;
885 temp_allocs -= mtsp->mts_numfrees;
886 temp_bytes += mtsp->mts_memalloced;
887 temp_bytes -= mtsp->mts_memfreed;
889 if (temp_allocs > 0 || temp_bytes > 0) {
890 printf("Warning: memory type %s leaked memory on destroy "
891 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
892 temp_allocs, temp_bytes);
895 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
896 uma_zfree_arg(mt_zone, mtip, slab);
900 malloc_desc2type(const char *desc)
902 struct malloc_type *mtp;
904 mtx_assert(&malloc_mtx, MA_OWNED);
905 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
906 if (strcmp(mtp->ks_shortdesc, desc) == 0)
913 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
915 struct malloc_type_stream_header mtsh;
916 struct malloc_type_internal *mtip;
917 struct malloc_type_header mth;
918 struct malloc_type *mtp;
922 error = sysctl_wire_old_buffer(req, 0);
925 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
926 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
927 mtx_lock(&malloc_mtx);
930 * Insert stream header.
932 bzero(&mtsh, sizeof(mtsh));
933 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
934 mtsh.mtsh_maxcpus = MAXCPU;
935 mtsh.mtsh_count = kmemcount;
936 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
939 * Insert alternating sequence of type headers and type statistics.
941 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
942 mtip = (struct malloc_type_internal *)mtp->ks_handle;
945 * Insert type header.
947 bzero(&mth, sizeof(mth));
948 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
949 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
952 * Insert type statistics for each CPU.
954 for (i = 0; i < MAXCPU; i++) {
955 (void)sbuf_bcat(&sbuf, &mtip->mti_stats[i],
956 sizeof(mtip->mti_stats[i]));
959 mtx_unlock(&malloc_mtx);
960 error = sbuf_finish(&sbuf);
965 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats, CTLFLAG_RD|CTLTYPE_STRUCT,
966 0, 0, sysctl_kern_malloc_stats, "s,malloc_type_ustats",
967 "Return malloc types");
969 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
970 "Count of kernel malloc types");
973 malloc_type_list(malloc_type_list_func_t *func, void *arg)
975 struct malloc_type *mtp, **bufmtp;
979 mtx_lock(&malloc_mtx);
981 mtx_assert(&malloc_mtx, MA_OWNED);
983 mtx_unlock(&malloc_mtx);
985 buflen = sizeof(struct malloc_type *) * count;
986 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
988 mtx_lock(&malloc_mtx);
990 if (count < kmemcount) {
991 free(bufmtp, M_TEMP);
995 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
998 mtx_unlock(&malloc_mtx);
1000 for (i = 0; i < count; i++)
1001 (func)(bufmtp[i], arg);
1003 free(bufmtp, M_TEMP);
1007 DB_SHOW_COMMAND(malloc, db_show_malloc)
1009 struct malloc_type_internal *mtip;
1010 struct malloc_type *mtp;
1011 uint64_t allocs, frees;
1012 uint64_t alloced, freed;
1015 db_printf("%18s %12s %12s %12s\n", "Type", "InUse", "MemUse",
1017 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1018 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1023 for (i = 0; i < MAXCPU; i++) {
1024 allocs += mtip->mti_stats[i].mts_numallocs;
1025 frees += mtip->mti_stats[i].mts_numfrees;
1026 alloced += mtip->mti_stats[i].mts_memalloced;
1027 freed += mtip->mti_stats[i].mts_memfreed;
1029 db_printf("%18s %12ju %12juK %12ju\n",
1030 mtp->ks_shortdesc, allocs - frees,
1031 (alloced - freed + 1023) / 1024, allocs);
1037 #if MALLOC_DEBUG_MAXZONES > 1
1038 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1040 struct malloc_type_internal *mtip;
1041 struct malloc_type *mtp;
1045 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1049 if (mtp->ks_magic != M_MAGIC) {
1050 db_printf("Magic %lx does not match expected %x\n",
1051 mtp->ks_magic, M_MAGIC);
1055 mtip = mtp->ks_handle;
1056 subzone = mtip->mti_zone;
1058 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1059 mtip = mtp->ks_handle;
1060 if (mtip->mti_zone != subzone)
1062 db_printf("%s\n", mtp->ks_shortdesc);
1067 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1070 #ifdef MALLOC_PROFILE
1073 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1087 error = sysctl_wire_old_buffer(req, 0);
1090 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1092 "\n Size Requests Real Size\n");
1093 for (i = 0; i < KMEM_ZSIZE; i++) {
1094 size = i << KMEM_ZSHIFT;
1095 rsize = kmemzones[kmemsize[i]].kz_size;
1096 count = (long long unsigned)krequests[i];
1098 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1099 (unsigned long long)count, rsize);
1101 if ((rsize * count) > (size * count))
1102 waste += (rsize * count) - (size * count);
1103 mem += (rsize * count);
1106 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1107 (unsigned long long)mem, (unsigned long long)waste);
1108 error = sbuf_finish(&sbuf);
1113 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
1114 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
1115 #endif /* MALLOC_PROFILE */