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.7 2003/07/19 21:14:38 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>
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 register struct kmembuckets *kbp;
142 register struct kmemusage *kup;
143 register struct freelist *freep;
144 long indx, npg, allocsize;
146 caddr_t va, cp, savedlist;
150 const char *savedtype;
152 register 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);
172 while (ksp->ks_memuse >= ksp->ks_limit) {
173 if (flags & M_NOWAIT) {
175 return ((void *) NULL);
177 if (ksp->ks_limblocks < 65535)
179 tsleep((caddr_t)ksp, 0, type->ks_shortdesc, 0);
181 ksp->ks_size |= 1 << indx;
183 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
185 if (kbp->kb_next == NULL) {
187 if (size > MAXALLOCSAVE)
188 allocsize = roundup(size, PAGE_SIZE);
190 allocsize = 1 << indx;
191 npg = btoc(allocsize);
192 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
195 return ((void *) NULL);
197 kbp->kb_total += kbp->kb_elmpercl;
200 if (allocsize > MAXALLOCSAVE) {
202 panic("malloc: allocation too large");
203 kup->ku_pagecnt = npg;
204 ksp->ks_memuse += allocsize;
207 kup->ku_freecnt = kbp->kb_elmpercl;
208 kbp->kb_totalfree += kbp->kb_elmpercl;
210 * Just in case we blocked while allocating memory,
211 * and someone else also allocated memory for this
212 * bucket, don't assume the list is still empty.
214 savedlist = kbp->kb_next;
215 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
217 freep = (struct freelist *)cp;
220 * Copy in known text to detect modification
223 end = (long *)&cp[copysize];
224 for (lp = (long *)cp; lp < end; lp++)
226 freep->type = M_FREE;
227 #endif /* INVARIANTS */
233 freep->next = savedlist;
234 if (kbp->kb_last == NULL)
235 kbp->kb_last = (caddr_t)freep;
238 kbp->kb_next = ((struct freelist *)va)->next;
240 freep = (struct freelist *)va;
241 savedtype = (const char *) freep->type->ks_shortdesc;
242 #if BYTE_ORDER == BIG_ENDIAN
243 freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
245 #if BYTE_ORDER == LITTLE_ENDIAN
246 freep->type = (struct malloc_type *)WEIRD_ADDR;
248 if ((intptr_t)(void *)&freep->next & 0x2)
249 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
251 freep->next = (caddr_t)WEIRD_ADDR;
252 end = (long *)&va[copysize];
253 for (lp = (long *)va; lp < end; lp++) {
254 if (*lp == WEIRD_ADDR)
256 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
257 "Data modified on freelist: word",
258 (long)(lp - (long *)va), (void *)va, size,
259 "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
263 #endif /* INVARIANTS */
265 if (kup->ku_indx != indx)
266 panic("malloc: wrong bucket");
267 if (kup->ku_freecnt == 0)
268 panic("malloc: lost data");
271 ksp->ks_memuse += 1 << indx;
276 if (ksp->ks_memuse > ksp->ks_maxused)
277 ksp->ks_maxused = ksp->ks_memuse;
279 /* XXX: Do idle pre-zeroing. */
280 if (va != NULL && (flags & M_ZERO))
282 return ((void *) va);
288 * Free a block of memory allocated by malloc.
290 * This routine may not block.
295 struct malloc_type *type;
297 register struct kmembuckets *kbp;
298 register struct kmemusage *kup;
299 register struct freelist *freep;
304 long *end, *lp, alloc, copysize;
306 register struct malloc_type *ksp = type;
308 if (type->ks_limit == 0)
309 panic("freeing with unknown type (%s)", type->ks_shortdesc);
311 /* free(NULL, ...) does nothing */
315 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
316 ("free: address %p out of range", (void *)addr));
318 size = 1 << kup->ku_indx;
319 kbp = &bucket[kup->ku_indx];
323 * Check for returns of data that do not point to the
324 * beginning of the allocation.
326 if (size > PAGE_SIZE)
327 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
329 alloc = addrmask[kup->ku_indx];
330 if (((uintptr_t)(void *)addr & alloc) != 0)
331 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
332 (void *)addr, size, type->ks_shortdesc, alloc);
333 #endif /* INVARIANTS */
334 if (size > MAXALLOCSAVE) {
335 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
336 size = kup->ku_pagecnt << PAGE_SHIFT;
337 ksp->ks_memuse -= size;
340 if (ksp->ks_memuse + size >= ksp->ks_limit &&
341 ksp->ks_memuse < ksp->ks_limit)
342 wakeup((caddr_t)ksp);
348 freep = (struct freelist *)addr;
351 * Check for multiple frees. Use a quick check to see if
352 * it looks free before laboriously searching the freelist.
354 if (freep->spare0 == WEIRD_ADDR) {
355 fp = (struct freelist *)kbp->kb_next;
357 if (fp->spare0 != WEIRD_ADDR)
358 panic("free: free item %p modified", fp);
359 else if (addr == (caddr_t)fp)
360 panic("free: multiple freed item %p", addr);
361 fp = (struct freelist *)fp->next;
365 * Copy in known text to detect modification after freeing
366 * and to make it look free. Also, save the type being freed
367 * so we can list likely culprit if modification is detected
368 * when the object is reallocated.
370 copysize = size < MAX_COPY ? size : MAX_COPY;
371 end = (long *)&((caddr_t)addr)[copysize];
372 for (lp = (long *)addr; lp < end; lp++)
375 #endif /* INVARIANTS */
377 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
378 if (kup->ku_freecnt > kbp->kb_elmpercl)
379 panic("free: multiple frees");
380 else if (kbp->kb_totalfree > kbp->kb_highwat)
384 ksp->ks_memuse -= size;
385 if (ksp->ks_memuse + size >= ksp->ks_limit &&
386 ksp->ks_memuse < ksp->ks_limit)
387 wakeup((caddr_t)ksp);
389 #ifdef OLD_MALLOC_MEMORY_POLICY
390 if (kbp->kb_next == NULL)
393 ((struct freelist *)kbp->kb_last)->next = addr;
398 * Return memory to the head of the queue for quick reuse. This
399 * can improve performance by improving the probability of the
400 * item being in the cache when it is reused.
402 if (kbp->kb_next == NULL) {
407 freep->next = kbp->kb_next;
415 * realloc: change the size of a memory block
418 realloc(addr, size, type, flags)
421 struct malloc_type *type;
424 struct kmemusage *kup;
428 /* realloc(NULL, ...) is equivalent to malloc(...) */
430 return (malloc(size, type, flags));
433 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
434 ("realloc: address %p out of range", (void *)addr));
436 /* Get the size of the original block */
438 alloc = 1 << kup->ku_indx;
439 if (alloc > MAXALLOCSAVE)
440 alloc = kup->ku_pagecnt << PAGE_SHIFT;
442 /* Reuse the original block if appropriate */
444 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
447 /* Allocate a new, bigger (or smaller) block */
448 if ((newaddr = malloc(size, type, flags)) == NULL)
451 /* Copy over original contents */
452 bcopy(addr, newaddr, min(size, alloc));
458 * reallocf: same as realloc() but free memory on failure.
461 reallocf(addr, size, type, flags)
464 struct malloc_type *type;
469 if ((mem = realloc(addr, size, type, flags)) == NULL)
475 * Initialize the kernel memory allocator
486 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
487 #error "kmeminit: MAXALLOCSAVE not power of 2"
489 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
490 #error "kmeminit: MAXALLOCSAVE too big"
492 #if (MAXALLOCSAVE < PAGE_SIZE)
493 #error "kmeminit: MAXALLOCSAVE too small"
497 * Try to auto-tune the kernel memory size, so that it is
498 * more applicable for a wider range of machine sizes.
499 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
500 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
501 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
502 * available, and on an X86 with a total KVA space of 256MB,
503 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
505 * Note that the kmem_map is also used by the zone allocator,
506 * so make sure that there is enough space.
508 vm_kmem_size = VM_KMEM_SIZE;
509 mem_size = vmstats.v_page_count * PAGE_SIZE;
511 #if defined(VM_KMEM_SIZE_SCALE)
512 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
513 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
516 #if defined(VM_KMEM_SIZE_MAX)
517 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
518 vm_kmem_size = VM_KMEM_SIZE_MAX;
521 /* Allow final override from the kernel environment */
522 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
525 * Limit kmem virtual size to twice the physical memory.
526 * This allows for kmem map sparseness, but limits the size
527 * to something sane. Be careful to not overflow the 32bit
528 * ints while doing the check.
530 if ((vm_kmem_size / 2) > (vmstats.v_page_count * PAGE_SIZE))
531 vm_kmem_size = 2 * vmstats.v_page_count * PAGE_SIZE;
533 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
536 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
537 (vm_size_t)(npg * sizeof(struct kmemusage)));
538 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
539 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
540 kmem_map->system_map = 1;
541 for (indx = 0; indx < MINBUCKET + 16; indx++) {
542 if (1 << indx >= PAGE_SIZE)
543 bucket[indx].kb_elmpercl = 1;
545 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
546 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
554 struct malloc_type *type = (struct malloc_type *)data;
556 if (type->ks_magic != M_MAGIC)
557 panic("malloc type lacks magic");
559 if (type->ks_limit != 0)
562 if (vmstats.v_page_count == 0)
563 panic("malloc_init not allowed before vm init");
566 * The default limits for each malloc region is 1/2 of the
567 * malloc portion of the kmem map size.
569 type->ks_limit = vm_kmem_size / 2;
570 type->ks_next = kmemstatistics;
571 kmemstatistics = type;
578 struct malloc_type *type = (struct malloc_type *)data;
579 struct malloc_type *t;
581 struct kmembuckets *kbp;
582 struct freelist *freep;
587 if (type->ks_magic != M_MAGIC)
588 panic("malloc type lacks magic");
590 if (vmstats.v_page_count == 0)
591 panic("malloc_uninit not allowed before vm init");
593 if (type->ks_limit == 0)
594 panic("malloc_uninit on uninitialized type");
598 for (indx = 0; indx < MINBUCKET + 16; indx++) {
600 freep = (struct freelist*)kbp->kb_next;
602 if (freep->type == type)
603 freep->type = M_FREE;
604 freep = (struct freelist*)freep->next;
609 if (type->ks_memuse != 0)
610 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
611 type->ks_memuse, type->ks_shortdesc);
614 if (type == kmemstatistics)
615 kmemstatistics = type->ks_next;
617 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
618 if (t->ks_next == type) {
619 t->ks_next = type->ks_next;
624 type->ks_next = NULL;