2 * Copyright (c) 1987, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)kern_malloc.c 8.3 (Berkeley) 1/4/94
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
43 #include <sys/malloc.h>
45 #include <sys/mutex.h>
46 #include <sys/vmmeter.h>
48 #include <sys/sysctl.h>
51 #include <vm/vm_param.h>
52 #include <vm/vm_kern.h>
53 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
57 #include <vm/uma_int.h>
58 #include <vm/uma_dbg.h>
60 #if defined(INVARIANTS) && defined(__i386__)
61 #include <machine/cpu.h>
65 * When realloc() is called, if the new size is sufficiently smaller than
66 * the old size, realloc() will allocate a new, smaller block to avoid
67 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
68 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
70 #ifndef REALLOC_FRACTION
71 #define REALLOC_FRACTION 1 /* new block if <= half the size */
74 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
75 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
76 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
78 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
79 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
81 static void kmeminit(void *);
82 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
84 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
86 static struct malloc_type *kmemstatistics;
87 static char *kmembase;
88 static char *kmemlimit;
92 #define KMEM_ZMASK (KMEM_ZBASE - 1)
94 #define KMEM_ZMAX 65536
95 #define KMEM_ZSIZE (KMEM_ZMAX >> KMEM_ZSHIFT)
96 static u_int8_t kmemsize[KMEM_ZSIZE + 1];
98 /* These won't be powers of two for long */
110 {1024, "1024", NULL},
111 {2048, "2048", NULL},
112 {4096, "4096", NULL},
113 {8192, "8192", NULL},
114 {16384, "16384", NULL},
115 {32768, "32768", NULL},
116 {65536, "65536", NULL},
123 * The malloc_mtx protects the kmemstatistics linked list as well as the
127 struct mtx malloc_mtx;
129 #ifdef MALLOC_PROFILE
130 uint64_t krequests[KMEM_ZSIZE + 1];
132 static int sysctl_kern_mprof(SYSCTL_HANDLER_ARGS);
135 static int sysctl_kern_malloc(SYSCTL_HANDLER_ARGS);
140 * Allocate a block of memory.
142 * If M_NOWAIT is set, this routine will not block and return NULL if
143 * the allocation fails.
146 malloc(size, type, flags)
148 struct malloc_type *type;
154 register struct malloc_type *ksp = type;
158 Debugger("zero size malloc");
160 if (!(flags & M_NOWAIT))
161 KASSERT(curthread->td_intr_nesting_level == 0,
162 ("malloc(M_WAITOK) in interrupt context"));
163 if (size <= KMEM_ZMAX) {
164 if (size & KMEM_ZMASK)
165 size = (size & ~KMEM_ZMASK) + KMEM_ZBASE;
166 indx = kmemsize[size >> KMEM_ZSHIFT];
167 zone = kmemzones[indx].kz_zone;
168 #ifdef MALLOC_PROFILE
169 krequests[size >> KMEM_ZSHIFT]++;
171 va = uma_zalloc(zone, flags);
172 mtx_lock(&ksp->ks_mtx);
176 ksp->ks_size |= 1 << indx;
177 size = zone->uz_size;
179 size = roundup(size, PAGE_SIZE);
181 va = uma_large_malloc(size, flags);
182 mtx_lock(&ksp->ks_mtx);
186 ksp->ks_memuse += size;
190 if (ksp->ks_memuse > ksp->ks_maxused)
191 ksp->ks_maxused = ksp->ks_memuse;
193 mtx_unlock(&ksp->ks_mtx);
194 return ((void *) va);
200 * Free a block of memory allocated by malloc.
202 * This routine may not block.
207 struct malloc_type *type;
212 register struct malloc_type *ksp = type;
214 /* free(NULL, ...) does nothing */
220 mem = (void *)((u_long)addr & (~UMA_SLAB_MASK));
221 mtx_lock(&malloc_mtx);
222 slab = hash_sfind(mallochash, mem);
223 mtx_unlock(&malloc_mtx);
226 panic("free: address %p(%p) has not been allocated.\n",
229 if (!(slab->us_flags & UMA_SLAB_MALLOC)) {
231 struct malloc_type **mtp = addr;
233 size = slab->us_zone->uz_size;
236 * Cache a pointer to the malloc_type that most recently freed
237 * this memory here. This way we know who is most likely to
238 * have stepped on it later.
240 * This code assumes that size is a multiple of 8 bytes for
243 mtp = (struct malloc_type **)
244 ((unsigned long)mtp & ~UMA_ALIGN_PTR);
245 mtp += (size - sizeof(struct malloc_type *)) /
246 sizeof(struct malloc_type *);
249 uma_zfree_arg(slab->us_zone, addr, slab);
251 size = slab->us_size;
252 uma_large_free(slab);
254 mtx_lock(&ksp->ks_mtx);
255 ksp->ks_memuse -= size;
257 mtx_unlock(&ksp->ks_mtx);
261 * realloc: change the size of a memory block
264 realloc(addr, size, type, flags)
267 struct malloc_type *type;
274 /* realloc(NULL, ...) is equivalent to malloc(...) */
276 return (malloc(size, type, flags));
278 mtx_lock(&malloc_mtx);
279 slab = hash_sfind(mallochash,
280 (void *)((u_long)addr & ~(UMA_SLAB_MASK)));
281 mtx_unlock(&malloc_mtx);
284 KASSERT(slab != NULL,
285 ("realloc: address %p out of range", (void *)addr));
287 /* Get the size of the original block */
289 alloc = slab->us_zone->uz_size;
291 alloc = slab->us_size;
293 /* Reuse the original block if appropriate */
295 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
298 /* Allocate a new, bigger (or smaller) block */
299 if ((newaddr = malloc(size, type, flags)) == NULL)
302 /* Copy over original contents */
303 bcopy(addr, newaddr, min(size, alloc));
309 * reallocf: same as realloc() but free memory on failure.
312 reallocf(addr, size, type, flags)
315 struct malloc_type *type;
320 if ((mem = realloc(addr, size, type, flags)) == NULL)
326 * Initialize the kernel memory allocator
342 mtx_init(&malloc_mtx, "malloc", NULL, MTX_DEF);
345 * Try to auto-tune the kernel memory size, so that it is
346 * more applicable for a wider range of machine sizes.
347 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
348 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
349 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
350 * available, and on an X86 with a total KVA space of 256MB,
351 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
353 * Note that the kmem_map is also used by the zone allocator,
354 * so make sure that there is enough space.
356 vm_kmem_size = VM_KMEM_SIZE;
357 mem_size = cnt.v_page_count * PAGE_SIZE;
359 #if defined(VM_KMEM_SIZE_SCALE)
360 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
361 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
364 #if defined(VM_KMEM_SIZE_MAX)
365 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
366 vm_kmem_size = VM_KMEM_SIZE_MAX;
369 /* Allow final override from the kernel environment */
370 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
373 * Limit kmem virtual size to twice the physical memory.
374 * This allows for kmem map sparseness, but limits the size
375 * to something sane. Be careful to not overflow the 32bit
376 * ints while doing the check.
378 if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
379 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
382 * In mbuf_init(), we set up submaps for mbufs and clusters, in which
383 * case we rounddown() (nmbufs * MSIZE) and (nmbclusters * MCLBYTES),
384 * respectively. Mathematically, this means that what we do here may
385 * amount to slightly more address space than we need for the submaps,
386 * but it never hurts to have an extra page in kmem_map.
388 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + nmbcnt *
389 sizeof(u_int) + vm_kmem_size) / PAGE_SIZE;
391 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
392 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
393 kmem_map->system_map = 1;
395 hashsize = npg * sizeof(void *);
399 /* The hash size must be a power of two */
400 for (i = 0; i < 8 * sizeof(hashsize); i++)
401 if (hashsize & (1 << i)) {
406 hashsize = 1 << (highbit);
408 hashmem = (void *)kmem_alloc(kernel_map, (vm_size_t)hashsize);
409 uma_startup2(hashmem, hashsize / sizeof(void *));
411 for (i = 0, indx = 0; kmemzones[indx].kz_size != 0; indx++) {
412 int size = kmemzones[indx].kz_size;
413 char *name = kmemzones[indx].kz_name;
415 kmemzones[indx].kz_zone = uma_zcreate(name, size,
417 mtrash_ctor, mtrash_dtor, mtrash_init, mtrash_fini,
419 NULL, NULL, NULL, NULL,
421 UMA_ALIGN_PTR, UMA_ZONE_MALLOC);
423 for (;i <= size; i+= KMEM_ZBASE)
424 kmemsize[i >> KMEM_ZSHIFT] = indx;
433 struct malloc_type *type = (struct malloc_type *)data;
435 mtx_lock(&malloc_mtx);
436 if (type->ks_magic != M_MAGIC)
437 panic("malloc type lacks magic");
439 if (cnt.v_page_count == 0)
440 panic("malloc_init not allowed before vm init");
442 if (type->ks_next != NULL)
445 type->ks_next = kmemstatistics;
446 kmemstatistics = type;
447 mtx_init(&type->ks_mtx, type->ks_shortdesc, "Malloc Stats", MTX_DEF);
448 mtx_unlock(&malloc_mtx);
455 struct malloc_type *type = (struct malloc_type *)data;
456 struct malloc_type *t;
458 mtx_lock(&malloc_mtx);
459 mtx_lock(&type->ks_mtx);
460 if (type->ks_magic != M_MAGIC)
461 panic("malloc type lacks magic");
463 if (cnt.v_page_count == 0)
464 panic("malloc_uninit not allowed before vm init");
466 if (type == kmemstatistics)
467 kmemstatistics = type->ks_next;
469 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
470 if (t->ks_next == type) {
471 t->ks_next = type->ks_next;
476 type->ks_next = NULL;
477 mtx_destroy(&type->ks_mtx);
478 mtx_unlock(&malloc_mtx);
482 sysctl_kern_malloc(SYSCTL_HANDLER_ARGS)
484 struct malloc_type *type;
498 mtx_lock(&malloc_mtx);
499 for (type = kmemstatistics; type != NULL; type = type->ks_next)
502 mtx_unlock(&malloc_mtx);
503 bufsize = linesize * (cnt + 1);
504 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
505 mtx_lock(&malloc_mtx);
507 len = snprintf(p, linesize,
508 "\n Type InUse MemUse HighUse Requests Size(s)\n");
511 for (type = kmemstatistics; cnt != 0 && type != NULL;
512 type = type->ks_next, cnt--) {
513 if (type->ks_calls == 0)
516 curline = linesize - 2; /* Leave room for the \n */
517 len = snprintf(p, curline, "%13s%6lu%6luK%7luK%9llu",
520 (type->ks_memuse + 1023) / 1024,
521 (type->ks_maxused + 1023) / 1024,
522 (long long unsigned)type->ks_calls);
527 for (i = 0; i < sizeof(kmemzones) / sizeof(kmemzones[0]) - 1;
529 if (type->ks_size & (1 << i)) {
531 len = snprintf(p, curline, " ");
533 len = snprintf(p, curline, ",");
537 len = snprintf(p, curline,
538 "%s", kmemzones[i].kz_name);
546 len = snprintf(p, 2, "\n");
550 mtx_unlock(&malloc_mtx);
551 error = SYSCTL_OUT(req, buf, p - buf);
557 SYSCTL_OID(_kern, OID_AUTO, malloc, CTLTYPE_STRING|CTLFLAG_RD,
558 NULL, 0, sysctl_kern_malloc, "A", "Malloc Stats");
560 #ifdef MALLOC_PROFILE
563 sysctl_kern_mprof(SYSCTL_HANDLER_ARGS)
578 bufsize = linesize * (KMEM_ZSIZE + 1);
579 bufsize += 128; /* For the stats line */
580 bufsize += 128; /* For the banner line */
584 p = buf = (char *)malloc(bufsize, M_TEMP, M_WAITOK|M_ZERO);
585 len = snprintf(p, bufsize,
586 "\n Size Requests Real Size\n");
590 for (i = 0; i < KMEM_ZSIZE; i++) {
591 size = i << KMEM_ZSHIFT;
592 rsize = kmemzones[kmemsize[i]].kz_size;
593 count = (long long unsigned)krequests[i];
595 len = snprintf(p, bufsize, "%6d%28llu%11d\n",
596 size, (unsigned long long)count, rsize);
600 if ((rsize * count) > (size * count))
601 waste += (rsize * count) - (size * count);
602 mem += (rsize * count);
605 len = snprintf(p, bufsize,
606 "\nTotal memory used:\t%30llu\nTotal Memory wasted:\t%30llu\n",
607 (unsigned long long)mem, (unsigned long long)waste);
610 error = SYSCTL_OUT(req, buf, p - buf);
616 SYSCTL_OID(_kern, OID_AUTO, mprof, CTLTYPE_STRING|CTLFLAG_RD,
617 NULL, 0, sysctl_kern_mprof, "A", "Malloc Profiling");
618 #endif /* MALLOC_PROFILE */