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.2 2003/06/17 04:28:41 dillon 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>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_extern.h>
53 #include <vm/vm_map.h>
55 #if defined(INVARIANTS) && defined(__i386__)
56 #include <machine/cpu.h>
60 * When realloc() is called, if the new size is sufficiently smaller than
61 * the old size, realloc() will allocate a new, smaller block to avoid
62 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
63 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
65 #ifndef REALLOC_FRACTION
66 #define REALLOC_FRACTION 1 /* new block if <= half the size */
69 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
70 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
71 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
73 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
74 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
76 static void kmeminit __P((void *));
77 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
79 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
81 static struct malloc_type *kmemstatistics;
82 static struct kmembuckets bucket[MINBUCKET + 16];
83 static struct kmemusage *kmemusage;
84 static char *kmembase;
85 static char *kmemlimit;
91 * This structure provides a set of masks to catch unaligned frees.
93 static long addrmask[] = { 0,
94 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
95 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
96 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
97 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
101 * The WEIRD_ADDR is used as known text to copy into free objects so
102 * that modifications after frees can be detected.
104 #define WEIRD_ADDR 0xdeadc0de
108 * Normally the first word of the structure is used to hold the list
109 * pointer for free objects. However, when running with diagnostics,
110 * we use the third and fourth fields, so as to catch modifications
111 * in the most commonly trashed first two words.
115 struct malloc_type *type;
119 #else /* !INVARIANTS */
123 #endif /* INVARIANTS */
128 * Allocate a block of memory.
130 * If M_NOWAIT is set, this routine will not block and return NULL if
131 * the allocation fails.
133 * If M_ASLEEP is set (M_NOWAIT must also be set), this routine
134 * will have the side effect of calling asleep() if it returns NULL,
135 * allowing the parent to await() at some future time.
138 malloc(size, type, flags)
140 struct malloc_type *type;
143 register struct kmembuckets *kbp;
144 register struct kmemusage *kup;
145 register struct freelist *freep;
146 long indx, npg, allocsize;
148 caddr_t va, cp, savedlist;
152 const char *savedtype;
154 register struct malloc_type *ksp = type;
156 #if defined(INVARIANTS) && defined(__i386__)
157 if (flags == M_WAITOK)
158 KASSERT(intr_nesting_level == 0,
159 ("malloc(M_WAITOK) in interrupt context"));
162 * Must be at splmem() prior to initializing segment to handle
163 * potential initialization race.
168 if (type->ks_limit == 0)
171 indx = BUCKETINDX(size);
174 while (ksp->ks_memuse >= ksp->ks_limit) {
175 if (flags & M_ASLEEP) {
176 if (ksp->ks_limblocks < 65535)
178 asleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
180 if (flags & M_NOWAIT) {
182 return ((void *) NULL);
184 if (ksp->ks_limblocks < 65535)
186 tsleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
188 ksp->ks_size |= 1 << indx;
190 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
192 if (kbp->kb_next == NULL) {
194 if (size > MAXALLOCSAVE)
195 allocsize = roundup(size, PAGE_SIZE);
197 allocsize = 1 << indx;
198 npg = btoc(allocsize);
199 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
202 return ((void *) NULL);
204 kbp->kb_total += kbp->kb_elmpercl;
207 if (allocsize > MAXALLOCSAVE) {
209 panic("malloc: allocation too large");
210 kup->ku_pagecnt = npg;
211 ksp->ks_memuse += allocsize;
214 kup->ku_freecnt = kbp->kb_elmpercl;
215 kbp->kb_totalfree += kbp->kb_elmpercl;
217 * Just in case we blocked while allocating memory,
218 * and someone else also allocated memory for this
219 * bucket, don't assume the list is still empty.
221 savedlist = kbp->kb_next;
222 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
224 freep = (struct freelist *)cp;
227 * Copy in known text to detect modification
230 end = (long *)&cp[copysize];
231 for (lp = (long *)cp; lp < end; lp++)
233 freep->type = M_FREE;
234 #endif /* INVARIANTS */
240 freep->next = savedlist;
241 if (kbp->kb_last == NULL)
242 kbp->kb_last = (caddr_t)freep;
245 kbp->kb_next = ((struct freelist *)va)->next;
247 freep = (struct freelist *)va;
248 savedtype = (const char *) freep->type->ks_shortdesc;
249 #if BYTE_ORDER == BIG_ENDIAN
250 freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
252 #if BYTE_ORDER == LITTLE_ENDIAN
253 freep->type = (struct malloc_type *)WEIRD_ADDR;
255 if ((intptr_t)(void *)&freep->next & 0x2)
256 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
258 freep->next = (caddr_t)WEIRD_ADDR;
259 end = (long *)&va[copysize];
260 for (lp = (long *)va; lp < end; lp++) {
261 if (*lp == WEIRD_ADDR)
263 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
264 "Data modified on freelist: word",
265 (long)(lp - (long *)va), (void *)va, size,
266 "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
270 #endif /* INVARIANTS */
272 if (kup->ku_indx != indx)
273 panic("malloc: wrong bucket");
274 if (kup->ku_freecnt == 0)
275 panic("malloc: lost data");
278 ksp->ks_memuse += 1 << indx;
283 if (ksp->ks_memuse > ksp->ks_maxused)
284 ksp->ks_maxused = ksp->ks_memuse;
286 /* XXX: Do idle pre-zeroing. */
287 if (va != NULL && (flags & M_ZERO))
289 return ((void *) va);
295 * Free a block of memory allocated by malloc.
297 * This routine may not block.
302 struct malloc_type *type;
304 register struct kmembuckets *kbp;
305 register struct kmemusage *kup;
306 register struct freelist *freep;
311 long *end, *lp, alloc, copysize;
313 register struct malloc_type *ksp = type;
315 if (type->ks_limit == 0)
316 panic("freeing with unknown type (%s)", type->ks_shortdesc);
318 /* free(NULL, ...) does nothing */
322 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
323 ("free: address %p out of range", (void *)addr));
325 size = 1 << kup->ku_indx;
326 kbp = &bucket[kup->ku_indx];
330 * Check for returns of data that do not point to the
331 * beginning of the allocation.
333 if (size > PAGE_SIZE)
334 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
336 alloc = addrmask[kup->ku_indx];
337 if (((uintptr_t)(void *)addr & alloc) != 0)
338 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
339 (void *)addr, size, type->ks_shortdesc, alloc);
340 #endif /* INVARIANTS */
341 if (size > MAXALLOCSAVE) {
342 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
343 size = kup->ku_pagecnt << PAGE_SHIFT;
344 ksp->ks_memuse -= size;
347 if (ksp->ks_memuse + size >= ksp->ks_limit &&
348 ksp->ks_memuse < ksp->ks_limit)
349 wakeup((caddr_t)ksp);
355 freep = (struct freelist *)addr;
358 * Check for multiple frees. Use a quick check to see if
359 * it looks free before laboriously searching the freelist.
361 if (freep->spare0 == WEIRD_ADDR) {
362 fp = (struct freelist *)kbp->kb_next;
364 if (fp->spare0 != WEIRD_ADDR)
365 panic("free: free item %p modified", fp);
366 else if (addr == (caddr_t)fp)
367 panic("free: multiple freed item %p", addr);
368 fp = (struct freelist *)fp->next;
372 * Copy in known text to detect modification after freeing
373 * and to make it look free. Also, save the type being freed
374 * so we can list likely culprit if modification is detected
375 * when the object is reallocated.
377 copysize = size < MAX_COPY ? size : MAX_COPY;
378 end = (long *)&((caddr_t)addr)[copysize];
379 for (lp = (long *)addr; lp < end; lp++)
382 #endif /* INVARIANTS */
384 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
385 if (kup->ku_freecnt > kbp->kb_elmpercl)
386 panic("free: multiple frees");
387 else if (kbp->kb_totalfree > kbp->kb_highwat)
391 ksp->ks_memuse -= size;
392 if (ksp->ks_memuse + size >= ksp->ks_limit &&
393 ksp->ks_memuse < ksp->ks_limit)
394 wakeup((caddr_t)ksp);
396 #ifdef OLD_MALLOC_MEMORY_POLICY
397 if (kbp->kb_next == NULL)
400 ((struct freelist *)kbp->kb_last)->next = addr;
405 * Return memory to the head of the queue for quick reuse. This
406 * can improve performance by improving the probability of the
407 * item being in the cache when it is reused.
409 if (kbp->kb_next == NULL) {
414 freep->next = kbp->kb_next;
422 * realloc: change the size of a memory block
425 realloc(addr, size, type, flags)
428 struct malloc_type *type;
431 struct kmemusage *kup;
435 /* realloc(NULL, ...) is equivalent to malloc(...) */
437 return (malloc(size, type, flags));
440 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
441 ("realloc: address %p out of range", (void *)addr));
443 /* Get the size of the original block */
445 alloc = 1 << kup->ku_indx;
446 if (alloc > MAXALLOCSAVE)
447 alloc = kup->ku_pagecnt << PAGE_SHIFT;
449 /* Reuse the original block if appropriate */
451 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
454 /* Allocate a new, bigger (or smaller) block */
455 if ((newaddr = malloc(size, type, flags)) == NULL)
458 /* Copy over original contents */
459 bcopy(addr, newaddr, min(size, alloc));
465 * reallocf: same as realloc() but free memory on failure.
468 reallocf(addr, size, type, flags)
471 struct malloc_type *type;
476 if ((mem = realloc(addr, size, type, flags)) == NULL)
482 * Initialize the kernel memory allocator
493 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
494 #error "kmeminit: MAXALLOCSAVE not power of 2"
496 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
497 #error "kmeminit: MAXALLOCSAVE too big"
499 #if (MAXALLOCSAVE < PAGE_SIZE)
500 #error "kmeminit: MAXALLOCSAVE too small"
504 * Try to auto-tune the kernel memory size, so that it is
505 * more applicable for a wider range of machine sizes.
506 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
507 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
508 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
509 * available, and on an X86 with a total KVA space of 256MB,
510 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
512 * Note that the kmem_map is also used by the zone allocator,
513 * so make sure that there is enough space.
515 vm_kmem_size = VM_KMEM_SIZE;
516 mem_size = cnt.v_page_count * PAGE_SIZE;
518 #if defined(VM_KMEM_SIZE_SCALE)
519 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
520 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
523 #if defined(VM_KMEM_SIZE_MAX)
524 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
525 vm_kmem_size = VM_KMEM_SIZE_MAX;
528 /* Allow final override from the kernel environment */
529 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
532 * Limit kmem virtual size to twice the physical memory.
533 * This allows for kmem map sparseness, but limits the size
534 * to something sane. Be careful to not overflow the 32bit
535 * ints while doing the check.
537 if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
538 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
540 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
543 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
544 (vm_size_t)(npg * sizeof(struct kmemusage)));
545 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
546 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
547 kmem_map->system_map = 1;
548 for (indx = 0; indx < MINBUCKET + 16; indx++) {
549 if (1 << indx >= PAGE_SIZE)
550 bucket[indx].kb_elmpercl = 1;
552 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
553 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
561 struct malloc_type *type = (struct malloc_type *)data;
563 if (type->ks_magic != M_MAGIC)
564 panic("malloc type lacks magic");
566 if (type->ks_limit != 0)
569 if (cnt.v_page_count == 0)
570 panic("malloc_init not allowed before vm init");
573 * The default limits for each malloc region is 1/2 of the
574 * malloc portion of the kmem map size.
576 type->ks_limit = vm_kmem_size / 2;
577 type->ks_next = kmemstatistics;
578 kmemstatistics = type;
585 struct malloc_type *type = (struct malloc_type *)data;
586 struct malloc_type *t;
588 struct kmembuckets *kbp;
589 struct freelist *freep;
594 if (type->ks_magic != M_MAGIC)
595 panic("malloc type lacks magic");
597 if (cnt.v_page_count == 0)
598 panic("malloc_uninit not allowed before vm init");
600 if (type->ks_limit == 0)
601 panic("malloc_uninit on uninitialized type");
605 for (indx = 0; indx < MINBUCKET + 16; indx++) {
607 freep = (struct freelist*)kbp->kb_next;
609 if (freep->type == type)
610 freep->type = M_FREE;
611 freep = (struct freelist*)freep->next;
616 if (type->ks_memuse != 0)
617 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
618 type->ks_memuse, type->ks_shortdesc);
621 if (type == kmemstatistics)
622 kmemstatistics = type->ks_next;
624 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
625 if (t->ks_next == type) {
626 t->ks_next = type->ks_next;
631 type->ks_next = NULL;