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.13 2003/09/26 19:23:31 dillon Exp $
40 #if defined(NO_SLAB_ALLOCATOR)
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
47 #include <sys/vmmeter.h>
49 #include <sys/thread.h>
50 #include <sys/globaldata.h>
53 #include <vm/vm_param.h>
54 #include <vm/vm_kern.h>
55 #include <vm/vm_extern.h>
57 #include <vm/vm_map.h>
59 #if defined(INVARIANTS) && defined(__i386__)
60 #include <machine/cpu.h>
64 * When realloc() is called, if the new size is sufficiently smaller than
65 * the old size, realloc() will allocate a new, smaller block to avoid
66 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
67 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
69 #ifndef REALLOC_FRACTION
70 #define REALLOC_FRACTION 1 /* new block if <= half the size */
73 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
74 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
75 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
77 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
78 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
80 static void kmeminit (void *);
81 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
83 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
85 static struct malloc_type *kmemstatistics;
86 static struct kmembuckets bucket[MINBUCKET + 16];
87 static struct kmemusage *kmemusage;
88 #if defined(USE_KMEM_MAP)
89 static char *kmembase;
90 static char *kmemlimit;
92 static const char *kmembase = (char *)VM_MIN_KERNEL_ADDRESS;
93 static const char *kmemlimit = (char *)VM_MAX_KERNEL_ADDRESS;
96 #if defined(USE_KMEM_MAP)
102 * This structure provides a set of masks to catch unaligned frees.
104 static long addrmask[] = { 0,
105 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
106 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
107 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
108 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
112 * The WEIRD_ADDR is used as known text to copy into free objects so
113 * that modifications after frees can be detected.
115 #define WEIRD_ADDR 0xdeadc0de
119 * Normally the first word of the structure is used to hold the list
120 * pointer for free objects. However, when running with diagnostics,
121 * we use the third and fourth fields, so as to catch modifications
122 * in the most commonly trashed first two words.
126 struct malloc_type *type;
130 #else /* !INVARIANTS */
134 #endif /* INVARIANTS */
139 * Allocate a block of memory.
141 * If M_NOWAIT is set, this routine will not block and return NULL if
142 * the allocation fails.
145 malloc(size, type, flags)
147 struct malloc_type *type;
150 struct kmembuckets *kbp;
151 struct kmemusage *kup;
152 struct freelist *freep;
153 long indx, npg, allocsize;
155 caddr_t va, cp, savedlist;
159 const char *savedtype;
161 struct malloc_type *ksp = type;
163 #if defined(INVARIANTS)
164 if (mycpu->gd_intr_nesting_level)
165 printf("WARNING: malloc() called from FASTint or ipiq, from %p\n", ((int **)&size)[-1]);
166 if (flags == M_WAITOK) {
167 KASSERT(mycpu->gd_intr_nesting_level == 0,
168 ("malloc(M_WAITOK) in interrupt context"));
172 * Must be at splmem() prior to initializing segment to handle
173 * potential initialization race.
178 if (type->ks_limit == 0)
181 indx = BUCKETINDX(size);
185 while (ksp->ks_memuse >= ksp->ks_limit) {
186 if (flags & M_NOWAIT) {
188 return ((void *) NULL);
190 if (ksp->ks_limblocks < 65535)
192 tsleep((caddr_t)ksp, 0, type->ks_shortdesc, 0);
194 ksp->ks_size |= 1 << indx;
196 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
198 if (kbp->kb_next == NULL) {
200 if (size > MAXALLOCSAVE)
201 allocsize = roundup(size, PAGE_SIZE);
203 allocsize = 1 << indx;
204 npg = btoc(allocsize);
205 #if defined(USE_KMEM_MAP)
206 va = (caddr_t) kmem_malloc(kmem_map,
207 (vm_size_t)ctob(npg), flags);
209 va = (caddr_t) kmem_malloc(kernel_map,
210 (vm_size_t)ctob(npg), flags);
214 return ((void *) NULL);
216 kbp->kb_total += kbp->kb_elmpercl;
219 if (allocsize > MAXALLOCSAVE) {
221 panic("malloc: allocation too large");
222 kup->ku_pagecnt = npg;
223 ksp->ks_memuse += allocsize;
226 kup->ku_freecnt = kbp->kb_elmpercl;
227 kbp->kb_totalfree += kbp->kb_elmpercl;
229 * Just in case we blocked while allocating memory,
230 * and someone else also allocated memory for this
231 * bucket, don't assume the list is still empty.
233 savedlist = kbp->kb_next;
234 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
236 freep = (struct freelist *)cp;
239 * Copy in known text to detect modification
242 end = (long *)&cp[copysize];
243 for (lp = (long *)cp; lp < end; lp++)
245 freep->type = M_FREE;
246 #endif /* INVARIANTS */
252 freep->next = savedlist;
253 if (kbp->kb_last == NULL)
254 kbp->kb_last = (caddr_t)freep;
258 if (flags & M_NOWAIT) {
260 return ((void *) NULL);
264 kbp->kb_next = ((struct freelist *)va)->next;
266 freep = (struct freelist *)va;
267 savedtype = (const char *) freep->type->ks_shortdesc;
268 #if BYTE_ORDER == BIG_ENDIAN
269 freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
271 #if BYTE_ORDER == LITTLE_ENDIAN
272 freep->type = (struct malloc_type *)WEIRD_ADDR;
274 if ((intptr_t)(void *)&freep->next & 0x2)
275 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
277 freep->next = (caddr_t)WEIRD_ADDR;
278 end = (long *)&va[copysize];
279 for (lp = (long *)va; lp < end; lp++) {
280 if (*lp == WEIRD_ADDR)
282 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
283 "Data modified on freelist: word",
284 (long)(lp - (long *)va), (void *)va, size,
285 "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
289 #endif /* INVARIANTS */
291 if (kup->ku_indx != indx)
292 panic("malloc: wrong bucket");
293 if (kup->ku_freecnt == 0)
294 panic("malloc: lost data");
297 ksp->ks_memuse += 1 << indx;
302 if (ksp->ks_memuse > ksp->ks_maxused)
303 ksp->ks_maxused = ksp->ks_memuse;
305 /* XXX: Do idle pre-zeroing. */
306 if (va != NULL && (flags & M_ZERO))
308 return ((void *) va);
314 * Free a block of memory allocated by malloc.
316 * This routine may not block.
321 struct malloc_type *type;
323 struct kmembuckets *kbp;
324 struct kmemusage *kup;
325 struct freelist *freep;
330 long *end, *lp, alloc, copysize;
332 struct malloc_type *ksp = type;
334 if (type->ks_limit == 0)
335 panic("freeing with unknown type (%s)", type->ks_shortdesc);
337 /* free(NULL, ...) does nothing */
341 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
342 ("free: address %p out of range", (void *)addr));
344 size = 1 << kup->ku_indx;
345 kbp = &bucket[kup->ku_indx];
349 * Check for returns of data that do not point to the
350 * beginning of the allocation.
352 if (size > PAGE_SIZE)
353 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
355 alloc = addrmask[kup->ku_indx];
356 if (((uintptr_t)(void *)addr & alloc) != 0)
357 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
358 (void *)addr, size, type->ks_shortdesc, alloc);
359 #endif /* INVARIANTS */
360 if (size > MAXALLOCSAVE) {
361 #if defined(USE_KMEM_MAP)
362 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
364 kmem_free(kernel_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
366 size = kup->ku_pagecnt << PAGE_SHIFT;
367 ksp->ks_memuse -= size;
370 if (ksp->ks_memuse + size >= ksp->ks_limit &&
371 ksp->ks_memuse < ksp->ks_limit)
372 wakeup((caddr_t)ksp);
378 freep = (struct freelist *)addr;
381 * Check for multiple frees. Use a quick check to see if
382 * it looks free before laboriously searching the freelist.
384 if (freep->spare0 == WEIRD_ADDR) {
385 fp = (struct freelist *)kbp->kb_next;
387 if (fp->spare0 != WEIRD_ADDR)
388 panic("free: free item %p modified", fp);
389 else if (addr == (caddr_t)fp)
390 panic("free: multiple freed item %p", addr);
391 fp = (struct freelist *)fp->next;
395 * Copy in known text to detect modification after freeing
396 * and to make it look free. Also, save the type being freed
397 * so we can list likely culprit if modification is detected
398 * when the object is reallocated.
400 copysize = size < MAX_COPY ? size : MAX_COPY;
401 end = (long *)&((caddr_t)addr)[copysize];
402 for (lp = (long *)addr; lp < end; lp++)
405 #endif /* INVARIANTS */
407 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
408 if (kup->ku_freecnt > kbp->kb_elmpercl)
409 panic("free: multiple frees");
410 else if (kbp->kb_totalfree > kbp->kb_highwat)
414 ksp->ks_memuse -= size;
415 if (ksp->ks_memuse + size >= ksp->ks_limit &&
416 ksp->ks_memuse < ksp->ks_limit)
417 wakeup((caddr_t)ksp);
419 #ifdef OLD_MALLOC_MEMORY_POLICY
420 if (kbp->kb_next == NULL)
423 ((struct freelist *)kbp->kb_last)->next = addr;
428 * Return memory to the head of the queue for quick reuse. This
429 * can improve performance by improving the probability of the
430 * item being in the cache when it is reused.
432 if (kbp->kb_next == NULL) {
437 freep->next = kbp->kb_next;
445 * realloc: change the size of a memory block
448 realloc(addr, size, type, flags)
451 struct malloc_type *type;
454 struct kmemusage *kup;
458 /* realloc(NULL, ...) is equivalent to malloc(...) */
460 return (malloc(size, type, flags));
463 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
464 ("realloc: address %p out of range", (void *)addr));
466 /* Get the size of the original block */
468 alloc = 1 << kup->ku_indx;
469 if (alloc > MAXALLOCSAVE)
470 alloc = kup->ku_pagecnt << PAGE_SHIFT;
472 /* Reuse the original block if appropriate */
474 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
477 /* Allocate a new, bigger (or smaller) block */
478 if ((newaddr = malloc(size, type, flags)) == NULL)
481 /* Copy over original contents */
482 bcopy(addr, newaddr, min(size, alloc));
488 * reallocf: same as realloc() but free memory on failure.
491 reallocf(addr, size, type, flags)
494 struct malloc_type *type;
499 if ((mem = realloc(addr, size, type, flags)) == NULL)
505 * Initialize the kernel memory allocator
516 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
517 #error "kmeminit: MAXALLOCSAVE not power of 2"
519 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
520 #error "kmeminit: MAXALLOCSAVE too big"
522 #if (MAXALLOCSAVE < PAGE_SIZE)
523 #error "kmeminit: MAXALLOCSAVE too small"
527 * Try to auto-tune the kernel memory size, so that it is
528 * more applicable for a wider range of machine sizes.
529 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
530 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
531 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
532 * available, and on an X86 with a total KVA space of 256MB,
533 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
535 * Note that the kmem_map is also used by the zone allocator,
536 * so make sure that there is enough space.
538 mem_size = vmstats.v_page_count * PAGE_SIZE;
540 #if defined(USE_KMEM_MAP)
541 vm_kmem_size = VM_KMEM_SIZE;
542 #if defined(VM_KMEM_SIZE_SCALE)
543 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
544 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
547 #if defined(VM_KMEM_SIZE_MAX)
548 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
549 vm_kmem_size = VM_KMEM_SIZE_MAX;
552 /* Allow final override from the kernel environment */
553 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
556 * Limit kmem virtual size to twice the physical memory.
557 * This allows for kmem map sparseness, but limits the size
558 * to something sane. Be careful to not overflow the 32bit
559 * ints while doing the check.
561 if ((vm_kmem_size / 2) > (vmstats.v_page_count * PAGE_SIZE))
562 vm_kmem_size = 2 * vmstats.v_page_count * PAGE_SIZE;
564 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
567 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
568 (vm_size_t)(npg * sizeof(struct kmemusage)));
569 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
570 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
571 kmem_map->system_map = 1;
573 npg = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
574 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
575 (vm_size_t)(npg * sizeof(struct kmemusage)));
577 for (indx = 0; indx < MINBUCKET + 16; indx++) {
578 if (1 << indx >= PAGE_SIZE)
579 bucket[indx].kb_elmpercl = 1;
581 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
582 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
590 struct malloc_type *type = (struct malloc_type *)data;
591 #if !defined(USE_KMEM_MAP)
595 if (type->ks_magic != M_MAGIC)
596 panic("malloc type lacks magic");
598 if (type->ks_limit != 0)
601 if (vmstats.v_page_count == 0)
602 panic("malloc_init not allowed before vm init");
605 * The default limits for each malloc region is 1/10 of available
606 * memory or 1/10 of our KVA space, whichever is lower.
608 #if defined(USE_KMEM_MAP)
609 type->ks_limit = vm_kmem_size / 2;
611 limsize = (vm_poff_t)vmstats.v_page_count * PAGE_SIZE;
612 if (limsize > VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS)
613 limsize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
614 type->ks_limit = limsize / 10;
616 type->ks_next = kmemstatistics;
617 kmemstatistics = type;
624 struct malloc_type *type = (struct malloc_type *)data;
625 struct malloc_type *t;
627 struct kmembuckets *kbp;
628 struct freelist *freep;
633 if (type->ks_magic != M_MAGIC)
634 panic("malloc type lacks magic");
636 if (vmstats.v_page_count == 0)
637 panic("malloc_uninit not allowed before vm init");
639 if (type->ks_limit == 0)
640 panic("malloc_uninit on uninitialized type");
644 for (indx = 0; indx < MINBUCKET + 16; indx++) {
646 freep = (struct freelist*)kbp->kb_next;
648 if (freep->type == type)
649 freep->type = M_FREE;
650 freep = (struct freelist*)freep->next;
655 if (type->ks_memuse != 0)
656 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
657 type->ks_memuse, type->ks_shortdesc);
660 if (type == kmemstatistics)
661 kmemstatistics = type->ks_next;
663 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
664 if (t->ks_next == type) {
665 t->ks_next = type->ks_next;
670 type->ks_next = NULL;