2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1987, 1991, 1993
5 * The Regents of the University of California.
6 * Copyright (c) 2005-2009 Robert N. M. Watson
7 * Copyright (c) 2008 Otto Moerbeek <otto@drijf.net> (mallocarray)
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94
38 * Kernel malloc(9) implementation -- general purpose kernel memory allocator
39 * based on memory types. Back end is implemented using the UMA(9) zone
40 * allocator. A set of fixed-size buckets are used for smaller allocations,
41 * and a special UMA allocation interface is used for larger allocations.
42 * Callers declare memory types, and statistics are maintained independently
43 * for each memory type. Statistics are maintained per-CPU for performance
44 * reasons. See malloc(9) and comments in malloc.h for a detailed
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
54 #include <sys/param.h>
55 #include <sys/systm.h>
57 #include <sys/kernel.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/vmmeter.h>
63 #include <sys/queue.h>
66 #include <sys/sysctl.h>
70 #include <sys/epoch.h>
75 #include <vm/vm_domainset.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_param.h>
78 #include <vm/vm_kern.h>
79 #include <vm/vm_extern.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_phys.h>
83 #include <vm/vm_pagequeue.h>
85 #include <vm/uma_int.h>
86 #include <vm/uma_dbg.h>
89 #include <vm/memguard.h>
92 #include <vm/redzone.h>
95 #if defined(INVARIANTS) && defined(__i386__)
96 #include <machine/cpu.h>
102 #include <sys/dtrace_bsd.h>
104 bool __read_frequently dtrace_malloc_enabled;
105 dtrace_malloc_probe_func_t __read_mostly dtrace_malloc_probe;
108 #if defined(INVARIANTS) || defined(MALLOC_MAKE_FAILURES) || \
109 defined(DEBUG_MEMGUARD) || defined(DEBUG_REDZONE)
110 #define MALLOC_DEBUG 1
114 * When realloc() is called, if the new size is sufficiently smaller than
115 * the old size, realloc() will allocate a new, smaller block to avoid
116 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
117 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
119 #ifndef REALLOC_FRACTION
120 #define REALLOC_FRACTION 1 /* new block if <= half the size */
124 * Centrally define some common malloc types.
126 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
127 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
128 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
130 static struct malloc_type *kmemstatistics;
131 static int kmemcount;
133 #define KMEM_ZSHIFT 4
134 #define KMEM_ZBASE 16
135 #define KMEM_ZMASK (KMEM_ZBASE - 1)
137 #define KMEM_ZMAX 65536
138 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
139 static uint8_t kmemsize[KMEM_ZSIZE + 1];
141 #ifndef MALLOC_DEBUG_MAXZONES
142 #define MALLOC_DEBUG_MAXZONES 1
144 static int numzones = MALLOC_DEBUG_MAXZONES;
147 * Small malloc(9) memory allocations are allocated from a set of UMA buckets
150 * XXX: The comment here used to read "These won't be powers of two for
151 * long." It's possible that a significant amount of wasted memory could be
152 * recovered by tuning the sizes of these buckets.
157 uma_zone_t kz_zone[MALLOC_DEBUG_MAXZONES];
176 * Zone to allocate malloc type descriptions from. For ABI reasons, memory
177 * types are described by a data structure passed by the declaring code, but
178 * the malloc(9) implementation has its own data structure describing the
179 * type and statistics. This permits the malloc(9)-internal data structures
180 * to be modified without breaking binary-compiled kernel modules that
181 * declare malloc types.
183 static uma_zone_t mt_zone;
184 static uma_zone_t mt_stats_zone;
187 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size, CTLFLAG_RDTUN, &vm_kmem_size, 0,
188 "Size of kernel memory");
190 static u_long kmem_zmax = KMEM_ZMAX;
191 SYSCTL_ULONG(_vm, OID_AUTO, kmem_zmax, CTLFLAG_RDTUN, &kmem_zmax, 0,
192 "Maximum allocation size that malloc(9) would use UMA as backend");
194 static u_long vm_kmem_size_min;
195 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_min, CTLFLAG_RDTUN, &vm_kmem_size_min, 0,
196 "Minimum size of kernel memory");
198 static u_long vm_kmem_size_max;
199 SYSCTL_ULONG(_vm, OID_AUTO, kmem_size_max, CTLFLAG_RDTUN, &vm_kmem_size_max, 0,
200 "Maximum size of kernel memory");
202 static u_int vm_kmem_size_scale;
203 SYSCTL_UINT(_vm, OID_AUTO, kmem_size_scale, CTLFLAG_RDTUN, &vm_kmem_size_scale, 0,
204 "Scale factor for kernel memory size");
206 static int sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS);
207 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_size,
208 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
209 sysctl_kmem_map_size, "LU", "Current kmem allocation size");
211 static int sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS);
212 SYSCTL_PROC(_vm, OID_AUTO, kmem_map_free,
213 CTLFLAG_RD | CTLTYPE_ULONG | CTLFLAG_MPSAFE, NULL, 0,
214 sysctl_kmem_map_free, "LU", "Free space in kmem");
217 * The malloc_mtx protects the kmemstatistics linked list.
219 struct mtx malloc_mtx;
221 #ifdef MALLOC_PROFILE
222 uint64_t krequests[KMEM_ZSIZE + 1];
224 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
227 static int sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS);
230 * time_uptime of the last malloc(9) failure (induced or real).
232 static time_t t_malloc_fail;
234 #if defined(MALLOC_MAKE_FAILURES) || (MALLOC_DEBUG_MAXZONES > 1)
235 static SYSCTL_NODE(_debug, OID_AUTO, malloc, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
236 "Kernel malloc debugging options");
240 * malloc(9) fault injection -- cause malloc failures every (n) mallocs when
241 * the caller specifies M_NOWAIT. If set to 0, no failures are caused.
243 #ifdef MALLOC_MAKE_FAILURES
244 static int malloc_failure_rate;
245 static int malloc_nowait_count;
246 static int malloc_failure_count;
247 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_rate, CTLFLAG_RWTUN,
248 &malloc_failure_rate, 0, "Every (n) mallocs with M_NOWAIT will fail");
249 SYSCTL_INT(_debug_malloc, OID_AUTO, failure_count, CTLFLAG_RD,
250 &malloc_failure_count, 0, "Number of imposed M_NOWAIT malloc failures");
254 sysctl_kmem_map_size(SYSCTL_HANDLER_ARGS)
259 return (sysctl_handle_long(oidp, &size, 0, req));
263 sysctl_kmem_map_free(SYSCTL_HANDLER_ARGS)
267 /* The sysctl is unsigned, implement as a saturation value. */
274 return (sysctl_handle_long(oidp, &size, 0, req));
278 * malloc(9) uma zone separation -- sub-page buffer overruns in one
279 * malloc type will affect only a subset of other malloc types.
281 #if MALLOC_DEBUG_MAXZONES > 1
283 tunable_set_numzones(void)
286 TUNABLE_INT_FETCH("debug.malloc.numzones",
289 /* Sanity check the number of malloc uma zones. */
292 if (numzones > MALLOC_DEBUG_MAXZONES)
293 numzones = MALLOC_DEBUG_MAXZONES;
295 SYSINIT(numzones, SI_SUB_TUNABLES, SI_ORDER_ANY, tunable_set_numzones, NULL);
296 SYSCTL_INT(_debug_malloc, OID_AUTO, numzones, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
297 &numzones, 0, "Number of malloc uma subzones");
300 * Any number that changes regularly is an okay choice for the
301 * offset. Build numbers are pretty good of you have them.
303 static u_int zone_offset = __FreeBSD_version;
304 TUNABLE_INT("debug.malloc.zone_offset", &zone_offset);
305 SYSCTL_UINT(_debug_malloc, OID_AUTO, zone_offset, CTLFLAG_RDTUN,
306 &zone_offset, 0, "Separate malloc types by examining the "
307 "Nth character in the malloc type short description.");
310 mtp_set_subzone(struct malloc_type *mtp)
312 struct malloc_type_internal *mtip;
317 mtip = mtp->ks_handle;
318 desc = mtp->ks_shortdesc;
319 if (desc == NULL || (len = strlen(desc)) == 0)
322 val = desc[zone_offset % len];
323 mtip->mti_zone = (val % numzones);
327 mtp_get_subzone(struct malloc_type *mtp)
329 struct malloc_type_internal *mtip;
331 mtip = mtp->ks_handle;
333 KASSERT(mtip->mti_zone < numzones,
334 ("mti_zone %u out of range %d",
335 mtip->mti_zone, numzones));
336 return (mtip->mti_zone);
338 #elif MALLOC_DEBUG_MAXZONES == 0
339 #error "MALLOC_DEBUG_MAXZONES must be positive."
342 mtp_set_subzone(struct malloc_type *mtp)
344 struct malloc_type_internal *mtip;
346 mtip = mtp->ks_handle;
351 mtp_get_subzone(struct malloc_type *mtp)
356 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
359 malloc_last_fail(void)
362 return (time_uptime - t_malloc_fail);
366 * An allocation has succeeded -- update malloc type statistics for the
367 * amount of bucket size. Occurs within a critical section so that the
368 * thread isn't preempted and doesn't migrate while updating per-PCU
372 malloc_type_zone_allocated(struct malloc_type *mtp, unsigned long size,
375 struct malloc_type_internal *mtip;
376 struct malloc_type_stats *mtsp;
379 mtip = mtp->ks_handle;
380 mtsp = zpcpu_get(mtip->mti_stats);
382 mtsp->mts_memalloced += size;
383 mtsp->mts_numallocs++;
386 mtsp->mts_size |= 1 << zindx;
389 if (__predict_false(dtrace_malloc_enabled)) {
390 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_MALLOC];
392 (dtrace_malloc_probe)(probe_id,
393 (uintptr_t) mtp, (uintptr_t) mtip,
394 (uintptr_t) mtsp, size, zindx);
402 malloc_type_allocated(struct malloc_type *mtp, unsigned long size)
406 malloc_type_zone_allocated(mtp, size, -1);
410 * A free operation has occurred -- update malloc type statistics for the
411 * amount of the bucket size. Occurs within a critical section so that the
412 * thread isn't preempted and doesn't migrate while updating per-CPU
416 malloc_type_freed(struct malloc_type *mtp, unsigned long size)
418 struct malloc_type_internal *mtip;
419 struct malloc_type_stats *mtsp;
422 mtip = mtp->ks_handle;
423 mtsp = zpcpu_get(mtip->mti_stats);
424 mtsp->mts_memfreed += size;
425 mtsp->mts_numfrees++;
428 if (__predict_false(dtrace_malloc_enabled)) {
429 uint32_t probe_id = mtip->mti_probes[DTMALLOC_PROBE_FREE];
431 (dtrace_malloc_probe)(probe_id,
432 (uintptr_t) mtp, (uintptr_t) mtip,
433 (uintptr_t) mtsp, size, 0);
443 * Allocate a block of physically contiguous memory.
445 * If M_NOWAIT is set, this routine will not block and return NULL if
446 * the allocation fails.
449 contigmalloc(unsigned long size, struct malloc_type *type, int flags,
450 vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
455 ret = (void *)kmem_alloc_contig(size, flags, low, high, alignment,
456 boundary, VM_MEMATTR_DEFAULT);
458 malloc_type_allocated(type, round_page(size));
463 contigmalloc_domainset(unsigned long size, struct malloc_type *type,
464 struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
465 unsigned long alignment, vm_paddr_t boundary)
469 ret = (void *)kmem_alloc_contig_domainset(ds, size, flags, low, high,
470 alignment, boundary, VM_MEMATTR_DEFAULT);
472 malloc_type_allocated(type, round_page(size));
479 * Free a block of memory allocated by contigmalloc.
481 * This routine may not block.
484 contigfree(void *addr, unsigned long size, struct malloc_type *type)
487 kmem_free((vm_offset_t)addr, size);
488 malloc_type_freed(type, round_page(size));
493 malloc_dbg(caddr_t *vap, size_t *sizep, struct malloc_type *mtp,
499 KASSERT(mtp->ks_magic == M_MAGIC, ("malloc: bad malloc type magic"));
501 * Check that exactly one of M_WAITOK or M_NOWAIT is specified.
503 indx = flags & (M_WAITOK | M_NOWAIT);
504 if (indx != M_NOWAIT && indx != M_WAITOK) {
505 static struct timeval lasterr;
506 static int curerr, once;
507 if (once == 0 && ppsratecheck(&lasterr, &curerr, 1)) {
508 printf("Bad malloc flags: %x\n", indx);
515 #ifdef MALLOC_MAKE_FAILURES
516 if ((flags & M_NOWAIT) && (malloc_failure_rate != 0)) {
517 atomic_add_int(&malloc_nowait_count, 1);
518 if ((malloc_nowait_count % malloc_failure_rate) == 0) {
519 atomic_add_int(&malloc_failure_count, 1);
520 t_malloc_fail = time_uptime;
522 return (EJUSTRETURN);
526 if (flags & M_WAITOK) {
527 KASSERT(curthread->td_intr_nesting_level == 0,
528 ("malloc(M_WAITOK) in interrupt context"));
529 if (__predict_false(!THREAD_CAN_SLEEP())) {
531 epoch_trace_list(curthread);
534 ("malloc(M_WAITOK) with sleeping prohibited"));
537 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
538 ("malloc: called with spinlock or critical section held"));
540 #ifdef DEBUG_MEMGUARD
541 if (memguard_cmp_mtp(mtp, *sizep)) {
542 *vap = memguard_alloc(*sizep, flags);
544 return (EJUSTRETURN);
545 /* This is unfortunate but should not be fatal. */
550 *sizep = redzone_size_ntor(*sizep);
558 * Handle large allocations and frees by using kmem_malloc directly.
561 malloc_large_slab(uma_slab_t slab)
565 va = (uintptr_t)slab;
566 return ((va & 1) != 0);
570 malloc_large_size(uma_slab_t slab)
574 va = (uintptr_t)slab;
579 malloc_large(size_t *size, struct domainset *policy, int flags)
584 sz = roundup(*size, PAGE_SIZE);
585 va = kmem_malloc_domainset(policy, sz, flags);
587 /* The low bit is unused for slab pointers. */
588 vsetzoneslab(va, NULL, (void *)((sz << 1) | 1));
592 return ((caddr_t)va);
596 free_large(void *addr, size_t size)
599 kmem_free((vm_offset_t)addr, size);
606 * Allocate a block of memory.
608 * If M_NOWAIT is set, this routine will not block and return NULL if
609 * the allocation fails.
612 (malloc)(size_t size, struct malloc_type *mtp, int flags)
617 #if defined(DEBUG_REDZONE)
618 unsigned long osize = size;
621 KASSERT((flags & M_WAITOK) == 0 || THREAD_CAN_SLEEP(),
622 ("malloc(M_WAITOK) in non-sleepable context"));
626 if (malloc_dbg(&va, &size, mtp, flags) != 0)
630 if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
631 if (size & KMEM_ZMASK)
632 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
633 indx = kmemsize[size >> KMEM_ZSHIFT];
634 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
635 #ifdef MALLOC_PROFILE
636 krequests[size >> KMEM_ZSHIFT]++;
638 va = uma_zalloc(zone, flags);
640 size = zone->uz_size;
641 malloc_type_zone_allocated(mtp, va == NULL ? 0 : size, indx);
643 va = malloc_large(&size, DOMAINSET_RR(), flags);
644 malloc_type_allocated(mtp, va == NULL ? 0 : size);
646 if (flags & M_WAITOK)
647 KASSERT(va != NULL, ("malloc(M_WAITOK) returned NULL"));
649 t_malloc_fail = time_uptime;
652 va = redzone_setup(va, osize);
654 return ((void *) va);
658 malloc_domain(size_t *sizep, int *indxp, struct malloc_type *mtp, int domain,
667 KASSERT(size <= kmem_zmax && (flags & M_EXEC) == 0,
668 ("malloc_domain: Called with bad flag / size combination."));
669 if (size & KMEM_ZMASK)
670 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
671 indx = kmemsize[size >> KMEM_ZSHIFT];
672 zone = kmemzones[indx].kz_zone[mtp_get_subzone(mtp)];
673 #ifdef MALLOC_PROFILE
674 krequests[size >> KMEM_ZSHIFT]++;
676 va = uma_zalloc_domain(zone, NULL, domain, flags);
678 *sizep = zone->uz_size;
684 malloc_domainset(size_t size, struct malloc_type *mtp, struct domainset *ds,
687 struct vm_domainset_iter di;
692 #if defined(DEBUG_REDZONE)
693 unsigned long osize = size;
697 if (malloc_dbg(&ret, &size, mtp, flags) != 0)
700 if (size <= kmem_zmax && (flags & M_EXEC) == 0) {
701 vm_domainset_iter_policy_init(&di, ds, &domain, &flags);
703 ret = malloc_domain(&size, &indx, mtp, domain, flags);
704 } while (ret == NULL &&
705 vm_domainset_iter_policy(&di, &domain) == 0);
706 malloc_type_zone_allocated(mtp, ret == NULL ? 0 : size, indx);
708 /* Policy is handled by kmem. */
709 ret = malloc_large(&size, ds, flags);
710 malloc_type_allocated(mtp, ret == NULL ? 0 : size);
713 if (flags & M_WAITOK)
714 KASSERT(ret != NULL, ("malloc(M_WAITOK) returned NULL"));
715 else if (ret == NULL)
716 t_malloc_fail = time_uptime;
719 ret = redzone_setup(ret, osize);
725 mallocarray(size_t nmemb, size_t size, struct malloc_type *type, int flags)
728 if (WOULD_OVERFLOW(nmemb, size))
729 panic("mallocarray: %zu * %zu overflowed", nmemb, size);
731 return (malloc(size * nmemb, type, flags));
736 free_save_type(void *addr, struct malloc_type *mtp, u_long size)
738 struct malloc_type **mtpp = addr;
741 * Cache a pointer to the malloc_type that most recently freed
742 * this memory here. This way we know who is most likely to
743 * have stepped on it later.
745 * This code assumes that size is a multiple of 8 bytes for
748 mtpp = (struct malloc_type **) ((unsigned long)mtpp & ~UMA_ALIGN_PTR);
749 mtpp += (size - sizeof(struct malloc_type *)) /
750 sizeof(struct malloc_type *);
757 free_dbg(void **addrp, struct malloc_type *mtp)
762 KASSERT(mtp->ks_magic == M_MAGIC, ("free: bad malloc type magic"));
763 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
764 ("free: called with spinlock or critical section held"));
766 /* free(NULL, ...) does nothing */
768 return (EJUSTRETURN);
770 #ifdef DEBUG_MEMGUARD
771 if (is_memguard_addr(addr)) {
773 return (EJUSTRETURN);
779 *addrp = redzone_addr_ntor(addr);
789 * Free a block of memory allocated by malloc.
791 * This routine may not block.
794 free(void *addr, struct malloc_type *mtp)
801 if (free_dbg(&addr, mtp) != 0)
804 /* free(NULL, ...) does nothing */
808 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
810 panic("free: address %p(%p) has not been allocated.\n",
811 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
813 if (__predict_true(!malloc_large_slab(slab))) {
814 size = zone->uz_size;
816 free_save_type(addr, mtp, size);
818 uma_zfree_arg(zone, addr, slab);
820 size = malloc_large_size(slab);
821 free_large(addr, size);
823 malloc_type_freed(mtp, size);
829 * Zero then free a block of memory allocated by malloc.
831 * This routine may not block.
834 zfree(void *addr, struct malloc_type *mtp)
841 if (free_dbg(&addr, mtp) != 0)
844 /* free(NULL, ...) does nothing */
848 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
850 panic("free: address %p(%p) has not been allocated.\n",
851 addr, (void *)((u_long)addr & (~UMA_SLAB_MASK)));
853 if (__predict_true(!malloc_large_slab(slab))) {
854 size = zone->uz_size;
856 free_save_type(addr, mtp, size);
858 explicit_bzero(addr, size);
859 uma_zfree_arg(zone, addr, slab);
861 size = malloc_large_size(slab);
862 explicit_bzero(addr, size);
863 free_large(addr, size);
865 malloc_type_freed(mtp, size);
869 * realloc: change the size of a memory block
872 realloc(void *addr, size_t size, struct malloc_type *mtp, int flags)
879 KASSERT(mtp->ks_magic == M_MAGIC,
880 ("realloc: bad malloc type magic"));
881 KASSERT(curthread->td_critnest == 0 || SCHEDULER_STOPPED(),
882 ("realloc: called with spinlock or critical section held"));
884 /* realloc(NULL, ...) is equivalent to malloc(...) */
886 return (malloc(size, mtp, flags));
889 * XXX: Should report free of old memory and alloc of new memory to
893 #ifdef DEBUG_MEMGUARD
894 if (is_memguard_addr(addr))
895 return (memguard_realloc(addr, size, mtp, flags));
901 alloc = redzone_get_size(addr);
903 vtozoneslab((vm_offset_t)addr & (~UMA_SLAB_MASK), &zone, &slab);
906 KASSERT(slab != NULL,
907 ("realloc: address %p out of range", (void *)addr));
909 /* Get the size of the original block */
910 if (!malloc_large_slab(slab))
911 alloc = zone->uz_size;
913 alloc = malloc_large_size(slab);
915 /* Reuse the original block if appropriate */
917 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
919 #endif /* !DEBUG_REDZONE */
921 /* Allocate a new, bigger (or smaller) block */
922 if ((newaddr = malloc(size, mtp, flags)) == NULL)
925 /* Copy over original contents */
926 bcopy(addr, newaddr, min(size, alloc));
932 * reallocf: same as realloc() but free memory on failure.
935 reallocf(void *addr, size_t size, struct malloc_type *mtp, int flags)
939 if ((mem = realloc(addr, size, mtp, flags)) == NULL)
944 CTASSERT(VM_KMEM_SIZE_SCALE >= 1);
947 * Initialize the kernel memory (kmem) arena.
956 if (vm_kmem_size == 0)
957 vm_kmem_size = VM_KMEM_SIZE;
959 #ifdef VM_KMEM_SIZE_MIN
960 if (vm_kmem_size_min == 0)
961 vm_kmem_size_min = VM_KMEM_SIZE_MIN;
963 #ifdef VM_KMEM_SIZE_MAX
964 if (vm_kmem_size_max == 0)
965 vm_kmem_size_max = VM_KMEM_SIZE_MAX;
968 * Calculate the amount of kernel virtual address (KVA) space that is
969 * preallocated to the kmem arena. In order to support a wide range
970 * of machines, it is a function of the physical memory size,
973 * min(max(physical memory size / VM_KMEM_SIZE_SCALE,
974 * VM_KMEM_SIZE_MIN), VM_KMEM_SIZE_MAX)
976 * Every architecture must define an integral value for
977 * VM_KMEM_SIZE_SCALE. However, the definitions of VM_KMEM_SIZE_MIN
978 * and VM_KMEM_SIZE_MAX, which represent respectively the floor and
979 * ceiling on this preallocation, are optional. Typically,
980 * VM_KMEM_SIZE_MAX is itself a function of the available KVA space on
981 * a given architecture.
983 mem_size = vm_cnt.v_page_count;
984 if (mem_size <= 32768) /* delphij XXX 128MB */
985 kmem_zmax = PAGE_SIZE;
987 if (vm_kmem_size_scale < 1)
988 vm_kmem_size_scale = VM_KMEM_SIZE_SCALE;
991 * Check if we should use defaults for the "vm_kmem_size"
994 if (vm_kmem_size == 0) {
995 vm_kmem_size = mem_size / vm_kmem_size_scale;
996 vm_kmem_size = vm_kmem_size * PAGE_SIZE < vm_kmem_size ?
997 vm_kmem_size_max : vm_kmem_size * PAGE_SIZE;
998 if (vm_kmem_size_min > 0 && vm_kmem_size < vm_kmem_size_min)
999 vm_kmem_size = vm_kmem_size_min;
1000 if (vm_kmem_size_max > 0 && vm_kmem_size >= vm_kmem_size_max)
1001 vm_kmem_size = vm_kmem_size_max;
1003 if (vm_kmem_size == 0)
1004 panic("Tune VM_KMEM_SIZE_* for the platform");
1007 * The amount of KVA space that is preallocated to the
1008 * kmem arena can be set statically at compile-time or manually
1009 * through the kernel environment. However, it is still limited to
1010 * twice the physical memory size, which has been sufficient to handle
1011 * the most severe cases of external fragmentation in the kmem arena.
1013 if (vm_kmem_size / 2 / PAGE_SIZE > mem_size)
1014 vm_kmem_size = 2 * mem_size * PAGE_SIZE;
1016 vm_kmem_size = round_page(vm_kmem_size);
1017 #ifdef DEBUG_MEMGUARD
1018 tmp = memguard_fudge(vm_kmem_size, kernel_map);
1024 #ifdef DEBUG_MEMGUARD
1026 * Initialize MemGuard if support compiled in. MemGuard is a
1027 * replacement allocator used for detecting tamper-after-free
1028 * scenarios as they occur. It is only used for debugging.
1030 memguard_init(kernel_arena);
1035 * Initialize the kernel memory allocator
1039 mallocinit(void *dummy)
1044 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
1048 if (kmem_zmax < PAGE_SIZE || kmem_zmax > KMEM_ZMAX)
1049 kmem_zmax = KMEM_ZMAX;
1051 mt_stats_zone = uma_zcreate("mt_stats_zone",
1052 sizeof(struct malloc_type_stats), NULL, NULL, NULL, NULL,
1053 UMA_ALIGN_PTR, UMA_ZONE_PCPU);
1054 mt_zone = uma_zcreate("mt_zone", sizeof(struct malloc_type_internal),
1056 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1058 NULL, NULL, NULL, NULL,
1060 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1061 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
1062 int size = kmemzones[indx].kz_size;
1063 const char *name = kmemzones[indx].kz_name;
1066 for (subzone = 0; subzone < numzones; subzone++) {
1067 kmemzones[indx].kz_zone[subzone] =
1068 uma_zcreate(name, size,
1070 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
1072 NULL, NULL, NULL, NULL,
1074 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
1076 for (;i <= size; i+= KMEM_ZBASE)
1077 kmemsize[i >> KMEM_ZSHIFT] = indx;
1081 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_SECOND, mallocinit, NULL);
1084 malloc_init(void *data)
1086 struct malloc_type_internal *mtip;
1087 struct malloc_type *mtp;
1089 KASSERT(vm_cnt.v_page_count != 0, ("malloc_register before vm_init"));
1092 if (mtp->ks_magic != M_MAGIC)
1093 panic("malloc_init: bad malloc type magic");
1095 mtip = uma_zalloc(mt_zone, M_WAITOK | M_ZERO);
1096 mtip->mti_stats = uma_zalloc_pcpu(mt_stats_zone, M_WAITOK | M_ZERO);
1097 mtp->ks_handle = mtip;
1098 mtp_set_subzone(mtp);
1100 mtx_lock(&malloc_mtx);
1101 mtp->ks_next = kmemstatistics;
1102 kmemstatistics = mtp;
1104 mtx_unlock(&malloc_mtx);
1108 malloc_uninit(void *data)
1110 struct malloc_type_internal *mtip;
1111 struct malloc_type_stats *mtsp;
1112 struct malloc_type *mtp, *temp;
1114 long temp_allocs, temp_bytes;
1118 KASSERT(mtp->ks_magic == M_MAGIC,
1119 ("malloc_uninit: bad malloc type magic"));
1120 KASSERT(mtp->ks_handle != NULL, ("malloc_deregister: cookie NULL"));
1122 mtx_lock(&malloc_mtx);
1123 mtip = mtp->ks_handle;
1124 mtp->ks_handle = NULL;
1125 if (mtp != kmemstatistics) {
1126 for (temp = kmemstatistics; temp != NULL;
1127 temp = temp->ks_next) {
1128 if (temp->ks_next == mtp) {
1129 temp->ks_next = mtp->ks_next;
1134 ("malloc_uninit: type '%s' not found", mtp->ks_shortdesc));
1136 kmemstatistics = mtp->ks_next;
1138 mtx_unlock(&malloc_mtx);
1141 * Look for memory leaks.
1143 temp_allocs = temp_bytes = 0;
1144 for (i = 0; i <= mp_maxid; i++) {
1145 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1146 temp_allocs += mtsp->mts_numallocs;
1147 temp_allocs -= mtsp->mts_numfrees;
1148 temp_bytes += mtsp->mts_memalloced;
1149 temp_bytes -= mtsp->mts_memfreed;
1151 if (temp_allocs > 0 || temp_bytes > 0) {
1152 printf("Warning: memory type %s leaked memory on destroy "
1153 "(%ld allocations, %ld bytes leaked).\n", mtp->ks_shortdesc,
1154 temp_allocs, temp_bytes);
1157 slab = vtoslab((vm_offset_t) mtip & (~UMA_SLAB_MASK));
1158 uma_zfree_pcpu(mt_stats_zone, mtip->mti_stats);
1159 uma_zfree_arg(mt_zone, mtip, slab);
1162 struct malloc_type *
1163 malloc_desc2type(const char *desc)
1165 struct malloc_type *mtp;
1167 mtx_assert(&malloc_mtx, MA_OWNED);
1168 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1169 if (strcmp(mtp->ks_shortdesc, desc) == 0)
1176 sysctl_kern_malloc_stats(SYSCTL_HANDLER_ARGS)
1178 struct malloc_type_stream_header mtsh;
1179 struct malloc_type_internal *mtip;
1180 struct malloc_type_stats *mtsp, zeromts;
1181 struct malloc_type_header mth;
1182 struct malloc_type *mtp;
1186 error = sysctl_wire_old_buffer(req, 0);
1189 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1190 sbuf_clear_flags(&sbuf, SBUF_INCLUDENUL);
1191 mtx_lock(&malloc_mtx);
1193 bzero(&zeromts, sizeof(zeromts));
1196 * Insert stream header.
1198 bzero(&mtsh, sizeof(mtsh));
1199 mtsh.mtsh_version = MALLOC_TYPE_STREAM_VERSION;
1200 mtsh.mtsh_maxcpus = MAXCPU;
1201 mtsh.mtsh_count = kmemcount;
1202 (void)sbuf_bcat(&sbuf, &mtsh, sizeof(mtsh));
1205 * Insert alternating sequence of type headers and type statistics.
1207 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1208 mtip = (struct malloc_type_internal *)mtp->ks_handle;
1211 * Insert type header.
1213 bzero(&mth, sizeof(mth));
1214 strlcpy(mth.mth_name, mtp->ks_shortdesc, MALLOC_MAX_NAME);
1215 (void)sbuf_bcat(&sbuf, &mth, sizeof(mth));
1218 * Insert type statistics for each CPU.
1220 for (i = 0; i <= mp_maxid; i++) {
1221 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1222 (void)sbuf_bcat(&sbuf, mtsp, sizeof(*mtsp));
1225 * Fill in the missing CPUs.
1227 for (; i < MAXCPU; i++) {
1228 (void)sbuf_bcat(&sbuf, &zeromts, sizeof(zeromts));
1232 mtx_unlock(&malloc_mtx);
1233 error = sbuf_finish(&sbuf);
1238 SYSCTL_PROC(_kern, OID_AUTO, malloc_stats,
1239 CTLFLAG_RD | CTLTYPE_STRUCT | CTLFLAG_MPSAFE, 0, 0,
1240 sysctl_kern_malloc_stats, "s,malloc_type_ustats",
1241 "Return malloc types");
1243 SYSCTL_INT(_kern, OID_AUTO, malloc_count, CTLFLAG_RD, &kmemcount, 0,
1244 "Count of kernel malloc types");
1247 malloc_type_list(malloc_type_list_func_t *func, void *arg)
1249 struct malloc_type *mtp, **bufmtp;
1253 mtx_lock(&malloc_mtx);
1255 mtx_assert(&malloc_mtx, MA_OWNED);
1257 mtx_unlock(&malloc_mtx);
1259 buflen = sizeof(struct malloc_type *) * count;
1260 bufmtp = malloc(buflen, M_TEMP, M_WAITOK);
1262 mtx_lock(&malloc_mtx);
1264 if (count < kmemcount) {
1265 free(bufmtp, M_TEMP);
1269 for (mtp = kmemstatistics, i = 0; mtp != NULL; mtp = mtp->ks_next, i++)
1272 mtx_unlock(&malloc_mtx);
1274 for (i = 0; i < count; i++)
1275 (func)(bufmtp[i], arg);
1277 free(bufmtp, M_TEMP);
1282 get_malloc_stats(const struct malloc_type_internal *mtip, uint64_t *allocs,
1285 const struct malloc_type_stats *mtsp;
1286 uint64_t frees, alloced, freed;
1293 for (i = 0; i <= mp_maxid; i++) {
1294 mtsp = zpcpu_get_cpu(mtip->mti_stats, i);
1296 *allocs += mtsp->mts_numallocs;
1297 frees += mtsp->mts_numfrees;
1298 alloced += mtsp->mts_memalloced;
1299 freed += mtsp->mts_memfreed;
1301 *inuse = *allocs - frees;
1302 return (alloced - freed);
1305 DB_SHOW_COMMAND(malloc, db_show_malloc)
1307 const char *fmt_hdr, *fmt_entry;
1308 struct malloc_type *mtp;
1309 uint64_t allocs, inuse;
1311 /* variables for sorting */
1312 struct malloc_type *last_mtype, *cur_mtype;
1313 int64_t cur_size, last_size;
1316 if (modif[0] == 'i') {
1317 fmt_hdr = "%s,%s,%s,%s\n";
1318 fmt_entry = "\"%s\",%ju,%jdK,%ju\n";
1320 fmt_hdr = "%18s %12s %12s %12s\n";
1321 fmt_entry = "%18s %12ju %12jdK %12ju\n";
1324 db_printf(fmt_hdr, "Type", "InUse", "MemUse", "Requests");
1326 /* Select sort, largest size first. */
1328 last_size = INT64_MAX;
1334 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1336 * In the case of size ties, print out mtypes
1337 * in the order they are encountered. That is,
1338 * when we encounter the most recently output
1339 * mtype, we have already printed all preceding
1340 * ties, and we must print all following ties.
1342 if (mtp == last_mtype) {
1346 size = get_malloc_stats(mtp->ks_handle, &allocs,
1348 if (size > cur_size && size < last_size + ties) {
1353 if (cur_mtype == NULL)
1356 size = get_malloc_stats(cur_mtype->ks_handle, &allocs, &inuse);
1357 db_printf(fmt_entry, cur_mtype->ks_shortdesc, inuse,
1358 howmany(size, 1024), allocs);
1363 last_mtype = cur_mtype;
1364 last_size = cur_size;
1368 #if MALLOC_DEBUG_MAXZONES > 1
1369 DB_SHOW_COMMAND(multizone_matches, db_show_multizone_matches)
1371 struct malloc_type_internal *mtip;
1372 struct malloc_type *mtp;
1376 db_printf("Usage: show multizone_matches <malloc type/addr>\n");
1380 if (mtp->ks_magic != M_MAGIC) {
1381 db_printf("Magic %lx does not match expected %x\n",
1382 mtp->ks_magic, M_MAGIC);
1386 mtip = mtp->ks_handle;
1387 subzone = mtip->mti_zone;
1389 for (mtp = kmemstatistics; mtp != NULL; mtp = mtp->ks_next) {
1390 mtip = mtp->ks_handle;
1391 if (mtip->mti_zone != subzone)
1393 db_printf("%s\n", mtp->ks_shortdesc);
1398 #endif /* MALLOC_DEBUG_MAXZONES > 1 */
1401 #ifdef MALLOC_PROFILE
1404 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
1418 error = sysctl_wire_old_buffer(req, 0);
1421 sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
1423 "\n Size Requests Real Size\n");
1424 for (i = 0; i < KMEM_ZSIZE; i++) {
1425 size = i << KMEM_ZSHIFT;
1426 rsize = kmemzones[kmemsize[i]].kz_size;
1427 count = (long long unsigned)krequests[i];
1429 sbuf_printf(&sbuf, "%6d%28llu%11d\n", size,
1430 (unsigned long long)count, rsize);
1432 if ((rsize * count) > (size * count))
1433 waste += (rsize * count) - (size * count);
1434 mem += (rsize * count);
1437 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
1438 (unsigned long long)mem, (unsigned long long)waste);
1439 error = sbuf_finish(&sbuf);
1444 SYSCTL_OID(_kern, OID_AUTO, mprof,
1445 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT, NULL, 0,
1446 sysctl_kern_mprof, "A",
1447 "Malloc Profiling");
1448 #endif /* MALLOC_PROFILE */