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
34 * $FreeBSD: src/sys/kern/kern_malloc.c,v 1.64.2.5 2002/03/16 02:19:51 archie Exp $
35 * $DragonFly: src/sys/kern/Attic/kern_malloc.c,v 1.9 2003/07/29 21:51:07 drhodus Exp $
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
45 #include <sys/vmmeter.h>
47 #include <sys/thread.h>
48 #include <sys/globaldata.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 #if defined(INVARIANTS) && defined(__i386__)
58 #include <machine/cpu.h>
62 * When realloc() is called, if the new size is sufficiently smaller than
63 * the old size, realloc() will allocate a new, smaller block to avoid
64 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
65 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
67 #ifndef REALLOC_FRACTION
68 #define REALLOC_FRACTION 1 /* new block if <= half the size */
71 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
72 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
73 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
75 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
76 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
78 static void kmeminit __P((void *));
79 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
81 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
83 static struct malloc_type *kmemstatistics;
84 static struct kmembuckets bucket[MINBUCKET + 16];
85 static struct kmemusage *kmemusage;
86 static char *kmembase;
87 static char *kmemlimit;
93 * This structure provides a set of masks to catch unaligned frees.
95 static long addrmask[] = { 0,
96 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
97 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
98 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
99 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
103 * The WEIRD_ADDR is used as known text to copy into free objects so
104 * that modifications after frees can be detected.
106 #define WEIRD_ADDR 0xdeadc0de
110 * Normally the first word of the structure is used to hold the list
111 * pointer for free objects. However, when running with diagnostics,
112 * we use the third and fourth fields, so as to catch modifications
113 * in the most commonly trashed first two words.
117 struct malloc_type *type;
121 #else /* !INVARIANTS */
125 #endif /* INVARIANTS */
130 * Allocate a block of memory.
132 * If M_NOWAIT is set, this routine will not block and return NULL if
133 * the allocation fails.
136 malloc(size, type, flags)
138 struct malloc_type *type;
141 struct kmembuckets *kbp;
142 struct kmemusage *kup;
143 struct freelist *freep;
144 long indx, npg, allocsize;
146 caddr_t va, cp, savedlist;
150 const char *savedtype;
152 struct malloc_type *ksp = type;
154 #if defined(INVARIANTS) && defined(__i386__)
155 if (flags == M_WAITOK)
156 KASSERT(mycpu->gd_intr_nesting_level == 0,
157 ("malloc(M_WAITOK) in interrupt context"));
160 * Must be at splmem() prior to initializing segment to handle
161 * potential initialization race.
166 if (type->ks_limit == 0)
169 indx = BUCKETINDX(size);
173 while (ksp->ks_memuse >= ksp->ks_limit) {
174 if (flags & M_NOWAIT) {
176 return ((void *) NULL);
178 if (ksp->ks_limblocks < 65535)
180 tsleep((caddr_t)ksp, 0, type->ks_shortdesc, 0);
182 ksp->ks_size |= 1 << indx;
184 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
186 if (kbp->kb_next == NULL) {
188 if (size > MAXALLOCSAVE)
189 allocsize = roundup(size, PAGE_SIZE);
191 allocsize = 1 << indx;
192 npg = btoc(allocsize);
193 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
196 return ((void *) NULL);
198 kbp->kb_total += kbp->kb_elmpercl;
201 if (allocsize > MAXALLOCSAVE) {
203 panic("malloc: allocation too large");
204 kup->ku_pagecnt = npg;
205 ksp->ks_memuse += allocsize;
208 kup->ku_freecnt = kbp->kb_elmpercl;
209 kbp->kb_totalfree += kbp->kb_elmpercl;
211 * Just in case we blocked while allocating memory,
212 * and someone else also allocated memory for this
213 * bucket, don't assume the list is still empty.
215 savedlist = kbp->kb_next;
216 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
218 freep = (struct freelist *)cp;
221 * Copy in known text to detect modification
224 end = (long *)&cp[copysize];
225 for (lp = (long *)cp; lp < end; lp++)
227 freep->type = M_FREE;
228 #endif /* INVARIANTS */
234 freep->next = savedlist;
235 if (kbp->kb_last == NULL)
236 kbp->kb_last = (caddr_t)freep;
240 if (flags & M_NOWAIT) {
242 return ((void *) NULL);
246 kbp->kb_next = ((struct freelist *)va)->next;
248 freep = (struct freelist *)va;
249 savedtype = (const char *) freep->type->ks_shortdesc;
250 #if BYTE_ORDER == BIG_ENDIAN
251 freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
253 #if BYTE_ORDER == LITTLE_ENDIAN
254 freep->type = (struct malloc_type *)WEIRD_ADDR;
256 if ((intptr_t)(void *)&freep->next & 0x2)
257 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
259 freep->next = (caddr_t)WEIRD_ADDR;
260 end = (long *)&va[copysize];
261 for (lp = (long *)va; lp < end; lp++) {
262 if (*lp == WEIRD_ADDR)
264 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
265 "Data modified on freelist: word",
266 (long)(lp - (long *)va), (void *)va, size,
267 "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
271 #endif /* INVARIANTS */
273 if (kup->ku_indx != indx)
274 panic("malloc: wrong bucket");
275 if (kup->ku_freecnt == 0)
276 panic("malloc: lost data");
279 ksp->ks_memuse += 1 << indx;
284 if (ksp->ks_memuse > ksp->ks_maxused)
285 ksp->ks_maxused = ksp->ks_memuse;
287 /* XXX: Do idle pre-zeroing. */
288 if (va != NULL && (flags & M_ZERO))
290 return ((void *) va);
296 * Free a block of memory allocated by malloc.
298 * This routine may not block.
303 struct malloc_type *type;
305 struct kmembuckets *kbp;
306 struct kmemusage *kup;
307 struct freelist *freep;
312 long *end, *lp, alloc, copysize;
314 struct malloc_type *ksp = type;
316 if (type->ks_limit == 0)
317 panic("freeing with unknown type (%s)", type->ks_shortdesc);
319 /* free(NULL, ...) does nothing */
323 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
324 ("free: address %p out of range", (void *)addr));
326 size = 1 << kup->ku_indx;
327 kbp = &bucket[kup->ku_indx];
331 * Check for returns of data that do not point to the
332 * beginning of the allocation.
334 if (size > PAGE_SIZE)
335 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
337 alloc = addrmask[kup->ku_indx];
338 if (((uintptr_t)(void *)addr & alloc) != 0)
339 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
340 (void *)addr, size, type->ks_shortdesc, alloc);
341 #endif /* INVARIANTS */
342 if (size > MAXALLOCSAVE) {
343 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
344 size = kup->ku_pagecnt << PAGE_SHIFT;
345 ksp->ks_memuse -= size;
348 if (ksp->ks_memuse + size >= ksp->ks_limit &&
349 ksp->ks_memuse < ksp->ks_limit)
350 wakeup((caddr_t)ksp);
356 freep = (struct freelist *)addr;
359 * Check for multiple frees. Use a quick check to see if
360 * it looks free before laboriously searching the freelist.
362 if (freep->spare0 == WEIRD_ADDR) {
363 fp = (struct freelist *)kbp->kb_next;
365 if (fp->spare0 != WEIRD_ADDR)
366 panic("free: free item %p modified", fp);
367 else if (addr == (caddr_t)fp)
368 panic("free: multiple freed item %p", addr);
369 fp = (struct freelist *)fp->next;
373 * Copy in known text to detect modification after freeing
374 * and to make it look free. Also, save the type being freed
375 * so we can list likely culprit if modification is detected
376 * when the object is reallocated.
378 copysize = size < MAX_COPY ? size : MAX_COPY;
379 end = (long *)&((caddr_t)addr)[copysize];
380 for (lp = (long *)addr; lp < end; lp++)
383 #endif /* INVARIANTS */
385 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
386 if (kup->ku_freecnt > kbp->kb_elmpercl)
387 panic("free: multiple frees");
388 else if (kbp->kb_totalfree > kbp->kb_highwat)
392 ksp->ks_memuse -= size;
393 if (ksp->ks_memuse + size >= ksp->ks_limit &&
394 ksp->ks_memuse < ksp->ks_limit)
395 wakeup((caddr_t)ksp);
397 #ifdef OLD_MALLOC_MEMORY_POLICY
398 if (kbp->kb_next == NULL)
401 ((struct freelist *)kbp->kb_last)->next = addr;
406 * Return memory to the head of the queue for quick reuse. This
407 * can improve performance by improving the probability of the
408 * item being in the cache when it is reused.
410 if (kbp->kb_next == NULL) {
415 freep->next = kbp->kb_next;
423 * realloc: change the size of a memory block
426 realloc(addr, size, type, flags)
429 struct malloc_type *type;
432 struct kmemusage *kup;
436 /* realloc(NULL, ...) is equivalent to malloc(...) */
438 return (malloc(size, type, flags));
441 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
442 ("realloc: address %p out of range", (void *)addr));
444 /* Get the size of the original block */
446 alloc = 1 << kup->ku_indx;
447 if (alloc > MAXALLOCSAVE)
448 alloc = kup->ku_pagecnt << PAGE_SHIFT;
450 /* Reuse the original block if appropriate */
452 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
455 /* Allocate a new, bigger (or smaller) block */
456 if ((newaddr = malloc(size, type, flags)) == NULL)
459 /* Copy over original contents */
460 bcopy(addr, newaddr, min(size, alloc));
466 * reallocf: same as realloc() but free memory on failure.
469 reallocf(addr, size, type, flags)
472 struct malloc_type *type;
477 if ((mem = realloc(addr, size, type, flags)) == NULL)
483 * Initialize the kernel memory allocator
494 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
495 #error "kmeminit: MAXALLOCSAVE not power of 2"
497 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
498 #error "kmeminit: MAXALLOCSAVE too big"
500 #if (MAXALLOCSAVE < PAGE_SIZE)
501 #error "kmeminit: MAXALLOCSAVE too small"
505 * Try to auto-tune the kernel memory size, so that it is
506 * more applicable for a wider range of machine sizes.
507 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
508 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
509 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
510 * available, and on an X86 with a total KVA space of 256MB,
511 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
513 * Note that the kmem_map is also used by the zone allocator,
514 * so make sure that there is enough space.
516 vm_kmem_size = VM_KMEM_SIZE;
517 mem_size = vmstats.v_page_count * PAGE_SIZE;
519 #if defined(VM_KMEM_SIZE_SCALE)
520 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
521 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
524 #if defined(VM_KMEM_SIZE_MAX)
525 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
526 vm_kmem_size = VM_KMEM_SIZE_MAX;
529 /* Allow final override from the kernel environment */
530 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
533 * Limit kmem virtual size to twice the physical memory.
534 * This allows for kmem map sparseness, but limits the size
535 * to something sane. Be careful to not overflow the 32bit
536 * ints while doing the check.
538 if ((vm_kmem_size / 2) > (vmstats.v_page_count * PAGE_SIZE))
539 vm_kmem_size = 2 * vmstats.v_page_count * PAGE_SIZE;
541 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
544 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
545 (vm_size_t)(npg * sizeof(struct kmemusage)));
546 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
547 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
548 kmem_map->system_map = 1;
549 for (indx = 0; indx < MINBUCKET + 16; indx++) {
550 if (1 << indx >= PAGE_SIZE)
551 bucket[indx].kb_elmpercl = 1;
553 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
554 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
562 struct malloc_type *type = (struct malloc_type *)data;
564 if (type->ks_magic != M_MAGIC)
565 panic("malloc type lacks magic");
567 if (type->ks_limit != 0)
570 if (vmstats.v_page_count == 0)
571 panic("malloc_init not allowed before vm init");
574 * The default limits for each malloc region is 1/2 of the
575 * malloc portion of the kmem map size.
577 type->ks_limit = vm_kmem_size / 2;
578 type->ks_next = kmemstatistics;
579 kmemstatistics = type;
586 struct malloc_type *type = (struct malloc_type *)data;
587 struct malloc_type *t;
589 struct kmembuckets *kbp;
590 struct freelist *freep;
595 if (type->ks_magic != M_MAGIC)
596 panic("malloc type lacks magic");
598 if (vmstats.v_page_count == 0)
599 panic("malloc_uninit not allowed before vm init");
601 if (type->ks_limit == 0)
602 panic("malloc_uninit on uninitialized type");
606 for (indx = 0; indx < MINBUCKET + 16; indx++) {
608 freep = (struct freelist*)kbp->kb_next;
610 if (freep->type == type)
611 freep->type = M_FREE;
612 freep = (struct freelist*)freep->next;
617 if (type->ks_memuse != 0)
618 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
619 type->ks_memuse, type->ks_shortdesc);
622 if (type == kmemstatistics)
623 kmemstatistics = type->ks_next;
625 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
626 if (t->ks_next == type) {
627 t->ks_next = type->ks_next;
632 type->ks_next = NULL;