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.4 2003/06/29 03:28:44 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>
50 #include <vm/vm_param.h>
51 #include <vm/vm_kern.h>
52 #include <vm/vm_extern.h>
54 #include <vm/vm_map.h>
56 #if defined(INVARIANTS) && defined(__i386__)
57 #include <machine/cpu.h>
61 * When realloc() is called, if the new size is sufficiently smaller than
62 * the old size, realloc() will allocate a new, smaller block to avoid
63 * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
64 * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
66 #ifndef REALLOC_FRACTION
67 #define REALLOC_FRACTION 1 /* new block if <= half the size */
70 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
71 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
72 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
74 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
75 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
77 static void kmeminit __P((void *));
78 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
80 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
82 static struct malloc_type *kmemstatistics;
83 static struct kmembuckets bucket[MINBUCKET + 16];
84 static struct kmemusage *kmemusage;
85 static char *kmembase;
86 static char *kmemlimit;
92 * This structure provides a set of masks to catch unaligned frees.
94 static long addrmask[] = { 0,
95 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
96 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
97 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
98 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
102 * The WEIRD_ADDR is used as known text to copy into free objects so
103 * that modifications after frees can be detected.
105 #define WEIRD_ADDR 0xdeadc0de
109 * Normally the first word of the structure is used to hold the list
110 * pointer for free objects. However, when running with diagnostics,
111 * we use the third and fourth fields, so as to catch modifications
112 * in the most commonly trashed first two words.
116 struct malloc_type *type;
120 #else /* !INVARIANTS */
124 #endif /* INVARIANTS */
129 * Allocate a block of memory.
131 * If M_NOWAIT is set, this routine will not block and return NULL if
132 * the allocation fails.
135 malloc(size, type, flags)
137 struct malloc_type *type;
140 register struct kmembuckets *kbp;
141 register struct kmemusage *kup;
142 register struct freelist *freep;
143 long indx, npg, allocsize;
145 caddr_t va, cp, savedlist;
149 const char *savedtype;
151 register struct malloc_type *ksp = type;
153 #if defined(INVARIANTS) && defined(__i386__)
154 if (flags == M_WAITOK)
155 KASSERT(mycpu->gd_intr_nesting_level == 0,
156 ("malloc(M_WAITOK) in interrupt context"));
159 * Must be at splmem() prior to initializing segment to handle
160 * potential initialization race.
165 if (type->ks_limit == 0)
168 indx = BUCKETINDX(size);
171 while (ksp->ks_memuse >= ksp->ks_limit) {
172 if (flags & M_NOWAIT) {
174 return ((void *) NULL);
176 if (ksp->ks_limblocks < 65535)
178 tsleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
180 ksp->ks_size |= 1 << indx;
182 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
184 if (kbp->kb_next == NULL) {
186 if (size > MAXALLOCSAVE)
187 allocsize = roundup(size, PAGE_SIZE);
189 allocsize = 1 << indx;
190 npg = btoc(allocsize);
191 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
194 return ((void *) NULL);
196 kbp->kb_total += kbp->kb_elmpercl;
199 if (allocsize > MAXALLOCSAVE) {
201 panic("malloc: allocation too large");
202 kup->ku_pagecnt = npg;
203 ksp->ks_memuse += allocsize;
206 kup->ku_freecnt = kbp->kb_elmpercl;
207 kbp->kb_totalfree += kbp->kb_elmpercl;
209 * Just in case we blocked while allocating memory,
210 * and someone else also allocated memory for this
211 * bucket, don't assume the list is still empty.
213 savedlist = kbp->kb_next;
214 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
216 freep = (struct freelist *)cp;
219 * Copy in known text to detect modification
222 end = (long *)&cp[copysize];
223 for (lp = (long *)cp; lp < end; lp++)
225 freep->type = M_FREE;
226 #endif /* INVARIANTS */
232 freep->next = savedlist;
233 if (kbp->kb_last == NULL)
234 kbp->kb_last = (caddr_t)freep;
237 kbp->kb_next = ((struct freelist *)va)->next;
239 freep = (struct freelist *)va;
240 savedtype = (const char *) freep->type->ks_shortdesc;
241 #if BYTE_ORDER == BIG_ENDIAN
242 freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
244 #if BYTE_ORDER == LITTLE_ENDIAN
245 freep->type = (struct malloc_type *)WEIRD_ADDR;
247 if ((intptr_t)(void *)&freep->next & 0x2)
248 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
250 freep->next = (caddr_t)WEIRD_ADDR;
251 end = (long *)&va[copysize];
252 for (lp = (long *)va; lp < end; lp++) {
253 if (*lp == WEIRD_ADDR)
255 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
256 "Data modified on freelist: word",
257 (long)(lp - (long *)va), (void *)va, size,
258 "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
262 #endif /* INVARIANTS */
264 if (kup->ku_indx != indx)
265 panic("malloc: wrong bucket");
266 if (kup->ku_freecnt == 0)
267 panic("malloc: lost data");
270 ksp->ks_memuse += 1 << indx;
275 if (ksp->ks_memuse > ksp->ks_maxused)
276 ksp->ks_maxused = ksp->ks_memuse;
278 /* XXX: Do idle pre-zeroing. */
279 if (va != NULL && (flags & M_ZERO))
281 return ((void *) va);
287 * Free a block of memory allocated by malloc.
289 * This routine may not block.
294 struct malloc_type *type;
296 register struct kmembuckets *kbp;
297 register struct kmemusage *kup;
298 register struct freelist *freep;
303 long *end, *lp, alloc, copysize;
305 register struct malloc_type *ksp = type;
307 if (type->ks_limit == 0)
308 panic("freeing with unknown type (%s)", type->ks_shortdesc);
310 /* free(NULL, ...) does nothing */
314 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
315 ("free: address %p out of range", (void *)addr));
317 size = 1 << kup->ku_indx;
318 kbp = &bucket[kup->ku_indx];
322 * Check for returns of data that do not point to the
323 * beginning of the allocation.
325 if (size > PAGE_SIZE)
326 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
328 alloc = addrmask[kup->ku_indx];
329 if (((uintptr_t)(void *)addr & alloc) != 0)
330 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
331 (void *)addr, size, type->ks_shortdesc, alloc);
332 #endif /* INVARIANTS */
333 if (size > MAXALLOCSAVE) {
334 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
335 size = kup->ku_pagecnt << PAGE_SHIFT;
336 ksp->ks_memuse -= size;
339 if (ksp->ks_memuse + size >= ksp->ks_limit &&
340 ksp->ks_memuse < ksp->ks_limit)
341 wakeup((caddr_t)ksp);
347 freep = (struct freelist *)addr;
350 * Check for multiple frees. Use a quick check to see if
351 * it looks free before laboriously searching the freelist.
353 if (freep->spare0 == WEIRD_ADDR) {
354 fp = (struct freelist *)kbp->kb_next;
356 if (fp->spare0 != WEIRD_ADDR)
357 panic("free: free item %p modified", fp);
358 else if (addr == (caddr_t)fp)
359 panic("free: multiple freed item %p", addr);
360 fp = (struct freelist *)fp->next;
364 * Copy in known text to detect modification after freeing
365 * and to make it look free. Also, save the type being freed
366 * so we can list likely culprit if modification is detected
367 * when the object is reallocated.
369 copysize = size < MAX_COPY ? size : MAX_COPY;
370 end = (long *)&((caddr_t)addr)[copysize];
371 for (lp = (long *)addr; lp < end; lp++)
374 #endif /* INVARIANTS */
376 if (kup->ku_freecnt >= kbp->kb_elmpercl) {
377 if (kup->ku_freecnt > kbp->kb_elmpercl)
378 panic("free: multiple frees");
379 else if (kbp->kb_totalfree > kbp->kb_highwat)
383 ksp->ks_memuse -= size;
384 if (ksp->ks_memuse + size >= ksp->ks_limit &&
385 ksp->ks_memuse < ksp->ks_limit)
386 wakeup((caddr_t)ksp);
388 #ifdef OLD_MALLOC_MEMORY_POLICY
389 if (kbp->kb_next == NULL)
392 ((struct freelist *)kbp->kb_last)->next = addr;
397 * Return memory to the head of the queue for quick reuse. This
398 * can improve performance by improving the probability of the
399 * item being in the cache when it is reused.
401 if (kbp->kb_next == NULL) {
406 freep->next = kbp->kb_next;
414 * realloc: change the size of a memory block
417 realloc(addr, size, type, flags)
420 struct malloc_type *type;
423 struct kmemusage *kup;
427 /* realloc(NULL, ...) is equivalent to malloc(...) */
429 return (malloc(size, type, flags));
432 KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
433 ("realloc: address %p out of range", (void *)addr));
435 /* Get the size of the original block */
437 alloc = 1 << kup->ku_indx;
438 if (alloc > MAXALLOCSAVE)
439 alloc = kup->ku_pagecnt << PAGE_SHIFT;
441 /* Reuse the original block if appropriate */
443 && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
446 /* Allocate a new, bigger (or smaller) block */
447 if ((newaddr = malloc(size, type, flags)) == NULL)
450 /* Copy over original contents */
451 bcopy(addr, newaddr, min(size, alloc));
457 * reallocf: same as realloc() but free memory on failure.
460 reallocf(addr, size, type, flags)
463 struct malloc_type *type;
468 if ((mem = realloc(addr, size, type, flags)) == NULL)
474 * Initialize the kernel memory allocator
485 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
486 #error "kmeminit: MAXALLOCSAVE not power of 2"
488 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
489 #error "kmeminit: MAXALLOCSAVE too big"
491 #if (MAXALLOCSAVE < PAGE_SIZE)
492 #error "kmeminit: MAXALLOCSAVE too small"
496 * Try to auto-tune the kernel memory size, so that it is
497 * more applicable for a wider range of machine sizes.
498 * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
499 * a VM_KMEM_SIZE of 12MB is a fair compromise. The
500 * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
501 * available, and on an X86 with a total KVA space of 256MB,
502 * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
504 * Note that the kmem_map is also used by the zone allocator,
505 * so make sure that there is enough space.
507 vm_kmem_size = VM_KMEM_SIZE;
508 mem_size = cnt.v_page_count * PAGE_SIZE;
510 #if defined(VM_KMEM_SIZE_SCALE)
511 if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
512 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
515 #if defined(VM_KMEM_SIZE_MAX)
516 if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
517 vm_kmem_size = VM_KMEM_SIZE_MAX;
520 /* Allow final override from the kernel environment */
521 TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
524 * Limit kmem virtual size to twice the physical memory.
525 * This allows for kmem map sparseness, but limits the size
526 * to something sane. Be careful to not overflow the 32bit
527 * ints while doing the check.
529 if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
530 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
532 npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
535 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
536 (vm_size_t)(npg * sizeof(struct kmemusage)));
537 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
538 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
539 kmem_map->system_map = 1;
540 for (indx = 0; indx < MINBUCKET + 16; indx++) {
541 if (1 << indx >= PAGE_SIZE)
542 bucket[indx].kb_elmpercl = 1;
544 bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
545 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
553 struct malloc_type *type = (struct malloc_type *)data;
555 if (type->ks_magic != M_MAGIC)
556 panic("malloc type lacks magic");
558 if (type->ks_limit != 0)
561 if (cnt.v_page_count == 0)
562 panic("malloc_init not allowed before vm init");
565 * The default limits for each malloc region is 1/2 of the
566 * malloc portion of the kmem map size.
568 type->ks_limit = vm_kmem_size / 2;
569 type->ks_next = kmemstatistics;
570 kmemstatistics = type;
577 struct malloc_type *type = (struct malloc_type *)data;
578 struct malloc_type *t;
580 struct kmembuckets *kbp;
581 struct freelist *freep;
586 if (type->ks_magic != M_MAGIC)
587 panic("malloc type lacks magic");
589 if (cnt.v_page_count == 0)
590 panic("malloc_uninit not allowed before vm init");
592 if (type->ks_limit == 0)
593 panic("malloc_uninit on uninitialized type");
597 for (indx = 0; indx < MINBUCKET + 16; indx++) {
599 freep = (struct freelist*)kbp->kb_next;
601 if (freep->type == type)
602 freep->type = M_FREE;
603 freep = (struct freelist*)freep->next;
608 if (type->ks_memuse != 0)
609 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
610 type->ks_memuse, type->ks_shortdesc);
613 if (type == kmemstatistics)
614 kmemstatistics = type->ks_next;
616 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
617 if (t->ks_next == type) {
618 t->ks_next = type->ks_next;
623 type->ks_next = NULL;