Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / kern / kern_malloc.c
1 /*
2  * Copyright (c) 1987, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
20  *
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
31  * SUCH DAMAGE.
32  *
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  */
36
37 #include "opt_vm.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/vmmeter.h>
45 #include <sys/lock.h>
46
47 #include <vm/vm.h>
48 #include <vm/vm_param.h>
49 #include <vm/vm_kern.h>
50 #include <vm/vm_extern.h>
51 #include <vm/pmap.h>
52 #include <vm/vm_map.h>
53
54 #if defined(INVARIANTS) && defined(__i386__)
55 #include <machine/cpu.h>
56 #endif
57
58 /*
59  * When realloc() is called, if the new size is sufficiently smaller than
60  * the old size, realloc() will allocate a new, smaller block to avoid
61  * wasting memory. 'Sufficiently smaller' is defined as: newsize <=
62  * oldsize / 2^n, where REALLOC_FRACTION defines the value of 'n'.
63  */
64 #ifndef REALLOC_FRACTION
65 #define REALLOC_FRACTION        1       /* new block if <= half the size */
66 #endif
67
68 MALLOC_DEFINE(M_CACHE, "cache", "Various Dynamically allocated caches");
69 MALLOC_DEFINE(M_DEVBUF, "devbuf", "device driver memory");
70 MALLOC_DEFINE(M_TEMP, "temp", "misc temporary data buffers");
71
72 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
73 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
74
75 static void kmeminit __P((void *));
76 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
77
78 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
79
80 static struct malloc_type *kmemstatistics;
81 static struct kmembuckets bucket[MINBUCKET + 16];
82 static struct kmemusage *kmemusage;
83 static char *kmembase;
84 static char *kmemlimit;
85
86 u_int vm_kmem_size;
87
88 #ifdef INVARIANTS
89 /*
90  * This structure provides a set of masks to catch unaligned frees.
91  */
92 static long addrmask[] = { 0,
93         0x00000001, 0x00000003, 0x00000007, 0x0000000f,
94         0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
95         0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
96         0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
97 };
98
99 /*
100  * The WEIRD_ADDR is used as known text to copy into free objects so
101  * that modifications after frees can be detected.
102  */
103 #define WEIRD_ADDR      0xdeadc0de
104 #define MAX_COPY        64
105
106 /*
107  * Normally the first word of the structure is used to hold the list
108  * pointer for free objects. However, when running with diagnostics,
109  * we use the third and fourth fields, so as to catch modifications
110  * in the most commonly trashed first two words.
111  */
112 struct freelist {
113         long    spare0;
114         struct malloc_type *type;
115         long    spare1;
116         caddr_t next;
117 };
118 #else /* !INVARIANTS */
119 struct freelist {
120         caddr_t next;
121 };
122 #endif /* INVARIANTS */
123
124 /*
125  *      malloc:
126  *
127  *      Allocate a block of memory.
128  *
129  *      If M_NOWAIT is set, this routine will not block and return NULL if
130  *      the allocation fails.
131  *
132  *      If M_ASLEEP is set (M_NOWAIT must also be set), this routine
133  *      will have the side effect of calling asleep() if it returns NULL,
134  *      allowing the parent to await() at some future time.
135  */
136 void *
137 malloc(size, type, flags)
138         unsigned long size;
139         struct malloc_type *type;
140         int flags;
141 {
142         register struct kmembuckets *kbp;
143         register struct kmemusage *kup;
144         register struct freelist *freep;
145         long indx, npg, allocsize;
146         int s;
147         caddr_t va, cp, savedlist;
148 #ifdef INVARIANTS
149         long *end, *lp;
150         int copysize;
151         const char *savedtype;
152 #endif
153         register struct malloc_type *ksp = type;
154
155 #if defined(INVARIANTS) && defined(__i386__)
156         if (flags == M_WAITOK)
157                 KASSERT(intr_nesting_level == 0,
158                    ("malloc(M_WAITOK) in interrupt context"));
159 #endif
160         /*
161          * Must be at splmem() prior to initializing segment to handle
162          * potential initialization race.
163          */
164
165         s = splmem();
166
167         if (type->ks_limit == 0)
168                 malloc_init(type);
169
170         indx = BUCKETINDX(size);
171         kbp = &bucket[indx];
172
173         while (ksp->ks_memuse >= ksp->ks_limit) {
174                 if (flags & M_ASLEEP) {
175                         if (ksp->ks_limblocks < 65535)
176                                 ksp->ks_limblocks++;
177                         asleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
178                 }
179                 if (flags & M_NOWAIT) {
180                         splx(s);
181                         return ((void *) NULL);
182                 }
183                 if (ksp->ks_limblocks < 65535)
184                         ksp->ks_limblocks++;
185                 tsleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
186         }
187         ksp->ks_size |= 1 << indx;
188 #ifdef INVARIANTS
189         copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
190 #endif
191         if (kbp->kb_next == NULL) {
192                 kbp->kb_last = NULL;
193                 if (size > MAXALLOCSAVE)
194                         allocsize = roundup(size, PAGE_SIZE);
195                 else
196                         allocsize = 1 << indx;
197                 npg = btoc(allocsize);
198                 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
199                 if (va == NULL) {
200                         splx(s);
201                         return ((void *) NULL);
202                 }
203                 kbp->kb_total += kbp->kb_elmpercl;
204                 kup = btokup(va);
205                 kup->ku_indx = indx;
206                 if (allocsize > MAXALLOCSAVE) {
207                         if (npg > 65535)
208                                 panic("malloc: allocation too large");
209                         kup->ku_pagecnt = npg;
210                         ksp->ks_memuse += allocsize;
211                         goto out;
212                 }
213                 kup->ku_freecnt = kbp->kb_elmpercl;
214                 kbp->kb_totalfree += kbp->kb_elmpercl;
215                 /*
216                  * Just in case we blocked while allocating memory,
217                  * and someone else also allocated memory for this
218                  * bucket, don't assume the list is still empty.
219                  */
220                 savedlist = kbp->kb_next;
221                 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
222                 for (;;) {
223                         freep = (struct freelist *)cp;
224 #ifdef INVARIANTS
225                         /*
226                          * Copy in known text to detect modification
227                          * after freeing.
228                          */
229                         end = (long *)&cp[copysize];
230                         for (lp = (long *)cp; lp < end; lp++)
231                                 *lp = WEIRD_ADDR;
232                         freep->type = M_FREE;
233 #endif /* INVARIANTS */
234                         if (cp <= va)
235                                 break;
236                         cp -= allocsize;
237                         freep->next = cp;
238                 }
239                 freep->next = savedlist;
240                 if (kbp->kb_last == NULL)
241                         kbp->kb_last = (caddr_t)freep;
242         }
243         va = kbp->kb_next;
244         kbp->kb_next = ((struct freelist *)va)->next;
245 #ifdef INVARIANTS
246         freep = (struct freelist *)va;
247         savedtype = (const char *) freep->type->ks_shortdesc;
248 #if BYTE_ORDER == BIG_ENDIAN
249         freep->type = (struct malloc_type *)WEIRD_ADDR >> 16;
250 #endif
251 #if BYTE_ORDER == LITTLE_ENDIAN
252         freep->type = (struct malloc_type *)WEIRD_ADDR;
253 #endif
254         if ((intptr_t)(void *)&freep->next & 0x2)
255                 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
256         else
257                 freep->next = (caddr_t)WEIRD_ADDR;
258         end = (long *)&va[copysize];
259         for (lp = (long *)va; lp < end; lp++) {
260                 if (*lp == WEIRD_ADDR)
261                         continue;
262                 printf("%s %ld of object %p size %lu %s %s (0x%lx != 0x%lx)\n",
263                         "Data modified on freelist: word",
264                         (long)(lp - (long *)va), (void *)va, size,
265                         "previous type", savedtype, *lp, (u_long)WEIRD_ADDR);
266                 break;
267         }
268         freep->spare0 = 0;
269 #endif /* INVARIANTS */
270         kup = btokup(va);
271         if (kup->ku_indx != indx)
272                 panic("malloc: wrong bucket");
273         if (kup->ku_freecnt == 0)
274                 panic("malloc: lost data");
275         kup->ku_freecnt--;
276         kbp->kb_totalfree--;
277         ksp->ks_memuse += 1 << indx;
278 out:
279         kbp->kb_calls++;
280         ksp->ks_inuse++;
281         ksp->ks_calls++;
282         if (ksp->ks_memuse > ksp->ks_maxused)
283                 ksp->ks_maxused = ksp->ks_memuse;
284         splx(s);
285         /* XXX: Do idle pre-zeroing.  */
286         if (va != NULL && (flags & M_ZERO))
287                 bzero(va, size);
288         return ((void *) va);
289 }
290
291 /*
292  *      free:
293  *
294  *      Free a block of memory allocated by malloc.
295  *
296  *      This routine may not block.
297  */
298 void
299 free(addr, type)
300         void *addr;
301         struct malloc_type *type;
302 {
303         register struct kmembuckets *kbp;
304         register struct kmemusage *kup;
305         register struct freelist *freep;
306         long size;
307         int s;
308 #ifdef INVARIANTS
309         struct freelist *fp;
310         long *end, *lp, alloc, copysize;
311 #endif
312         register struct malloc_type *ksp = type;
313
314         if (type->ks_limit == 0)
315                 panic("freeing with unknown type (%s)", type->ks_shortdesc);
316
317         /* free(NULL, ...) does nothing */
318         if (addr == NULL)
319                 return;
320
321         KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
322             ("free: address %p out of range", (void *)addr));
323         kup = btokup(addr);
324         size = 1 << kup->ku_indx;
325         kbp = &bucket[kup->ku_indx];
326         s = splmem();
327 #ifdef INVARIANTS
328         /*
329          * Check for returns of data that do not point to the
330          * beginning of the allocation.
331          */
332         if (size > PAGE_SIZE)
333                 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
334         else
335                 alloc = addrmask[kup->ku_indx];
336         if (((uintptr_t)(void *)addr & alloc) != 0)
337                 panic("free: unaligned addr %p, size %ld, type %s, mask %ld",
338                     (void *)addr, size, type->ks_shortdesc, alloc);
339 #endif /* INVARIANTS */
340         if (size > MAXALLOCSAVE) {
341                 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
342                 size = kup->ku_pagecnt << PAGE_SHIFT;
343                 ksp->ks_memuse -= size;
344                 kup->ku_indx = 0;
345                 kup->ku_pagecnt = 0;
346                 if (ksp->ks_memuse + size >= ksp->ks_limit &&
347                     ksp->ks_memuse < ksp->ks_limit)
348                         wakeup((caddr_t)ksp);
349                 ksp->ks_inuse--;
350                 kbp->kb_total -= 1;
351                 splx(s);
352                 return;
353         }
354         freep = (struct freelist *)addr;
355 #ifdef INVARIANTS
356         /*
357          * Check for multiple frees. Use a quick check to see if
358          * it looks free before laboriously searching the freelist.
359          */
360         if (freep->spare0 == WEIRD_ADDR) {
361                 fp = (struct freelist *)kbp->kb_next;
362                 while (fp) {
363                         if (fp->spare0 != WEIRD_ADDR)
364                                 panic("free: free item %p modified", fp);
365                         else if (addr == (caddr_t)fp)
366                                 panic("free: multiple freed item %p", addr);
367                         fp = (struct freelist *)fp->next;
368                 }
369         }
370         /*
371          * Copy in known text to detect modification after freeing
372          * and to make it look free. Also, save the type being freed
373          * so we can list likely culprit if modification is detected
374          * when the object is reallocated.
375          */
376         copysize = size < MAX_COPY ? size : MAX_COPY;
377         end = (long *)&((caddr_t)addr)[copysize];
378         for (lp = (long *)addr; lp < end; lp++)
379                 *lp = WEIRD_ADDR;
380         freep->type = type;
381 #endif /* INVARIANTS */
382         kup->ku_freecnt++;
383         if (kup->ku_freecnt >= kbp->kb_elmpercl) {
384                 if (kup->ku_freecnt > kbp->kb_elmpercl)
385                         panic("free: multiple frees");
386                 else if (kbp->kb_totalfree > kbp->kb_highwat)
387                         kbp->kb_couldfree++;
388         }
389         kbp->kb_totalfree++;
390         ksp->ks_memuse -= size;
391         if (ksp->ks_memuse + size >= ksp->ks_limit &&
392             ksp->ks_memuse < ksp->ks_limit)
393                 wakeup((caddr_t)ksp);
394         ksp->ks_inuse--;
395 #ifdef OLD_MALLOC_MEMORY_POLICY
396         if (kbp->kb_next == NULL)
397                 kbp->kb_next = addr;
398         else
399                 ((struct freelist *)kbp->kb_last)->next = addr;
400         freep->next = NULL;
401         kbp->kb_last = addr;
402 #else
403         /*
404          * Return memory to the head of the queue for quick reuse.  This
405          * can improve performance by improving the probability of the
406          * item being in the cache when it is reused.
407          */
408         if (kbp->kb_next == NULL) {
409                 kbp->kb_next = addr;
410                 kbp->kb_last = addr;
411                 freep->next = NULL;
412         } else {
413                 freep->next = kbp->kb_next;
414                 kbp->kb_next = addr;
415         }
416 #endif
417         splx(s);
418 }
419
420 /*
421  *      realloc: change the size of a memory block
422  */
423 void *
424 realloc(addr, size, type, flags)
425         void *addr;
426         unsigned long size;
427         struct malloc_type *type;
428         int flags;
429 {
430         struct kmemusage *kup;
431         unsigned long alloc;
432         void *newaddr;
433
434         /* realloc(NULL, ...) is equivalent to malloc(...) */
435         if (addr == NULL)
436                 return (malloc(size, type, flags));
437
438         /* Sanity check */
439         KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
440             ("realloc: address %p out of range", (void *)addr));
441
442         /* Get the size of the original block */
443         kup = btokup(addr);
444         alloc = 1 << kup->ku_indx;
445         if (alloc > MAXALLOCSAVE)
446                 alloc = kup->ku_pagecnt << PAGE_SHIFT;
447
448         /* Reuse the original block if appropriate */
449         if (size <= alloc
450             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
451                 return (addr);
452
453         /* Allocate a new, bigger (or smaller) block */
454         if ((newaddr = malloc(size, type, flags)) == NULL)
455                 return (NULL);
456
457         /* Copy over original contents */
458         bcopy(addr, newaddr, min(size, alloc));
459         free(addr, type);
460         return (newaddr);
461 }
462
463 /*
464  *      reallocf: same as realloc() but free memory on failure.
465  */
466 void *
467 reallocf(addr, size, type, flags)
468         void *addr;
469         unsigned long size;
470         struct malloc_type *type;
471         int flags;
472 {
473         void *mem;
474
475         if ((mem = realloc(addr, size, type, flags)) == NULL)
476                 free(addr, type);
477         return (mem);
478 }
479
480 /*
481  * Initialize the kernel memory allocator
482  */
483 /* ARGSUSED*/
484 static void
485 kmeminit(dummy)
486         void *dummy;
487 {
488         register long indx;
489         u_long npg;
490         u_long mem_size;
491
492 #if     ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
493 #error "kmeminit: MAXALLOCSAVE not power of 2"
494 #endif
495 #if     (MAXALLOCSAVE > MINALLOCSIZE * 32768)
496 #error "kmeminit: MAXALLOCSAVE too big"
497 #endif
498 #if     (MAXALLOCSAVE < PAGE_SIZE)
499 #error "kmeminit: MAXALLOCSAVE too small"
500 #endif
501
502         /*
503          * Try to auto-tune the kernel memory size, so that it is
504          * more applicable for a wider range of machine sizes.
505          * On an X86, a VM_KMEM_SIZE_SCALE value of 4 is good, while
506          * a VM_KMEM_SIZE of 12MB is a fair compromise.  The
507          * VM_KMEM_SIZE_MAX is dependent on the maximum KVA space
508          * available, and on an X86 with a total KVA space of 256MB,
509          * try to keep VM_KMEM_SIZE_MAX at 80MB or below.
510          *
511          * Note that the kmem_map is also used by the zone allocator,
512          * so make sure that there is enough space.
513          */
514         vm_kmem_size = VM_KMEM_SIZE;
515         mem_size = cnt.v_page_count * PAGE_SIZE;
516
517 #if defined(VM_KMEM_SIZE_SCALE)
518         if ((mem_size / VM_KMEM_SIZE_SCALE) > vm_kmem_size)
519                 vm_kmem_size = mem_size / VM_KMEM_SIZE_SCALE;
520 #endif
521
522 #if defined(VM_KMEM_SIZE_MAX)
523         if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
524                 vm_kmem_size = VM_KMEM_SIZE_MAX;
525 #endif
526
527         /* Allow final override from the kernel environment */
528         TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
529
530         /*
531          * Limit kmem virtual size to twice the physical memory.
532          * This allows for kmem map sparseness, but limits the size
533          * to something sane. Be careful to not overflow the 32bit
534          * ints while doing the check.
535          */
536         if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
537                 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
538
539         npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
540                 / PAGE_SIZE;
541
542         kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
543                 (vm_size_t)(npg * sizeof(struct kmemusage)));
544         kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
545                 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * PAGE_SIZE));
546         kmem_map->system_map = 1;
547         for (indx = 0; indx < MINBUCKET + 16; indx++) {
548                 if (1 << indx >= PAGE_SIZE)
549                         bucket[indx].kb_elmpercl = 1;
550                 else
551                         bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
552                 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
553         }
554 }
555
556 void
557 malloc_init(data)
558         void *data;
559 {
560         struct malloc_type *type = (struct malloc_type *)data;
561
562         if (type->ks_magic != M_MAGIC)
563                 panic("malloc type lacks magic");
564
565         if (type->ks_limit != 0)
566                 return;
567
568         if (cnt.v_page_count == 0)
569                 panic("malloc_init not allowed before vm init");
570
571         /*
572          * The default limits for each malloc region is 1/2 of the
573          * malloc portion of the kmem map size.
574          */
575         type->ks_limit = vm_kmem_size / 2;
576         type->ks_next = kmemstatistics; 
577         kmemstatistics = type;
578 }
579
580 void
581 malloc_uninit(data)
582         void *data;
583 {
584         struct malloc_type *type = (struct malloc_type *)data;
585         struct malloc_type *t;
586 #ifdef INVARIANTS
587         struct kmembuckets *kbp;
588         struct freelist *freep;
589         long indx;
590         int s;
591 #endif
592
593         if (type->ks_magic != M_MAGIC)
594                 panic("malloc type lacks magic");
595
596         if (cnt.v_page_count == 0)
597                 panic("malloc_uninit not allowed before vm init");
598
599         if (type->ks_limit == 0)
600                 panic("malloc_uninit on uninitialized type");
601
602 #ifdef INVARIANTS
603         s = splmem();
604         for (indx = 0; indx < MINBUCKET + 16; indx++) {
605                 kbp = bucket + indx;
606                 freep = (struct freelist*)kbp->kb_next;
607                 while (freep) {
608                         if (freep->type == type)
609                                 freep->type = M_FREE;
610                         freep = (struct freelist*)freep->next;
611                 }
612         }
613         splx(s);
614
615         if (type->ks_memuse != 0)
616                 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
617                     type->ks_memuse, type->ks_shortdesc);
618 #endif
619
620         if (type == kmemstatistics)
621                 kmemstatistics = type->ks_next;
622         else {
623                 for (t = kmemstatistics; t->ks_next != NULL; t = t->ks_next) {
624                         if (t->ks_next == type) {
625                                 t->ks_next = type->ks_next;
626                                 break;
627                         }
628                 }
629         }
630         type->ks_next = NULL;
631         type->ks_limit = 0;
632 }