Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[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  * $DragonFly: src/sys/kern/Attic/kern_malloc.c,v 1.2 2003/06/17 04:28:41 dillon Exp $
36  */
37
38 #include "opt_vm.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/vmmeter.h>
46 #include <sys/lock.h>
47
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_extern.h>
52 #include <vm/pmap.h>
53 #include <vm/vm_map.h>
54
55 #if defined(INVARIANTS) && defined(__i386__)
56 #include <machine/cpu.h>
57 #endif
58
59 /*
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'.
64  */
65 #ifndef REALLOC_FRACTION
66 #define REALLOC_FRACTION        1       /* new block if <= half the size */
67 #endif
68
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");
72
73 MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
74 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
75
76 static void kmeminit __P((void *));
77 SYSINIT(kmem, SI_SUB_KMEM, SI_ORDER_FIRST, kmeminit, NULL)
78
79 static MALLOC_DEFINE(M_FREE, "free", "should be on free list");
80
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;
86
87 u_int vm_kmem_size;
88
89 #ifdef INVARIANTS
90 /*
91  * This structure provides a set of masks to catch unaligned frees.
92  */
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,
98 };
99
100 /*
101  * The WEIRD_ADDR is used as known text to copy into free objects so
102  * that modifications after frees can be detected.
103  */
104 #define WEIRD_ADDR      0xdeadc0de
105 #define MAX_COPY        64
106
107 /*
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.
112  */
113 struct freelist {
114         long    spare0;
115         struct malloc_type *type;
116         long    spare1;
117         caddr_t next;
118 };
119 #else /* !INVARIANTS */
120 struct freelist {
121         caddr_t next;
122 };
123 #endif /* INVARIANTS */
124
125 /*
126  *      malloc:
127  *
128  *      Allocate a block of memory.
129  *
130  *      If M_NOWAIT is set, this routine will not block and return NULL if
131  *      the allocation fails.
132  *
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.
136  */
137 void *
138 malloc(size, type, flags)
139         unsigned long size;
140         struct malloc_type *type;
141         int flags;
142 {
143         register struct kmembuckets *kbp;
144         register struct kmemusage *kup;
145         register struct freelist *freep;
146         long indx, npg, allocsize;
147         int s;
148         caddr_t va, cp, savedlist;
149 #ifdef INVARIANTS
150         long *end, *lp;
151         int copysize;
152         const char *savedtype;
153 #endif
154         register struct malloc_type *ksp = type;
155
156 #if defined(INVARIANTS) && defined(__i386__)
157         if (flags == M_WAITOK)
158                 KASSERT(intr_nesting_level == 0,
159                    ("malloc(M_WAITOK) in interrupt context"));
160 #endif
161         /*
162          * Must be at splmem() prior to initializing segment to handle
163          * potential initialization race.
164          */
165
166         s = splmem();
167
168         if (type->ks_limit == 0)
169                 malloc_init(type);
170
171         indx = BUCKETINDX(size);
172         kbp = &bucket[indx];
173
174         while (ksp->ks_memuse >= ksp->ks_limit) {
175                 if (flags & M_ASLEEP) {
176                         if (ksp->ks_limblocks < 65535)
177                                 ksp->ks_limblocks++;
178                         asleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
179                 }
180                 if (flags & M_NOWAIT) {
181                         splx(s);
182                         return ((void *) NULL);
183                 }
184                 if (ksp->ks_limblocks < 65535)
185                         ksp->ks_limblocks++;
186                 tsleep((caddr_t)ksp, PSWP+2, type->ks_shortdesc, 0);
187         }
188         ksp->ks_size |= 1 << indx;
189 #ifdef INVARIANTS
190         copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
191 #endif
192         if (kbp->kb_next == NULL) {
193                 kbp->kb_last = NULL;
194                 if (size > MAXALLOCSAVE)
195                         allocsize = roundup(size, PAGE_SIZE);
196                 else
197                         allocsize = 1 << indx;
198                 npg = btoc(allocsize);
199                 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg), flags);
200                 if (va == NULL) {
201                         splx(s);
202                         return ((void *) NULL);
203                 }
204                 kbp->kb_total += kbp->kb_elmpercl;
205                 kup = btokup(va);
206                 kup->ku_indx = indx;
207                 if (allocsize > MAXALLOCSAVE) {
208                         if (npg > 65535)
209                                 panic("malloc: allocation too large");
210                         kup->ku_pagecnt = npg;
211                         ksp->ks_memuse += allocsize;
212                         goto out;
213                 }
214                 kup->ku_freecnt = kbp->kb_elmpercl;
215                 kbp->kb_totalfree += kbp->kb_elmpercl;
216                 /*
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.
220                  */
221                 savedlist = kbp->kb_next;
222                 kbp->kb_next = cp = va + (npg * PAGE_SIZE) - allocsize;
223                 for (;;) {
224                         freep = (struct freelist *)cp;
225 #ifdef INVARIANTS
226                         /*
227                          * Copy in known text to detect modification
228                          * after freeing.
229                          */
230                         end = (long *)&cp[copysize];
231                         for (lp = (long *)cp; lp < end; lp++)
232                                 *lp = WEIRD_ADDR;
233                         freep->type = M_FREE;
234 #endif /* INVARIANTS */
235                         if (cp <= va)
236                                 break;
237                         cp -= allocsize;
238                         freep->next = cp;
239                 }
240                 freep->next = savedlist;
241                 if (kbp->kb_last == NULL)
242                         kbp->kb_last = (caddr_t)freep;
243         }
244         va = kbp->kb_next;
245         kbp->kb_next = ((struct freelist *)va)->next;
246 #ifdef INVARIANTS
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;
251 #endif
252 #if BYTE_ORDER == LITTLE_ENDIAN
253         freep->type = (struct malloc_type *)WEIRD_ADDR;
254 #endif
255         if ((intptr_t)(void *)&freep->next & 0x2)
256                 freep->next = (caddr_t)((WEIRD_ADDR >> 16)|(WEIRD_ADDR << 16));
257         else
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)
262                         continue;
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);
267                 break;
268         }
269         freep->spare0 = 0;
270 #endif /* INVARIANTS */
271         kup = btokup(va);
272         if (kup->ku_indx != indx)
273                 panic("malloc: wrong bucket");
274         if (kup->ku_freecnt == 0)
275                 panic("malloc: lost data");
276         kup->ku_freecnt--;
277         kbp->kb_totalfree--;
278         ksp->ks_memuse += 1 << indx;
279 out:
280         kbp->kb_calls++;
281         ksp->ks_inuse++;
282         ksp->ks_calls++;
283         if (ksp->ks_memuse > ksp->ks_maxused)
284                 ksp->ks_maxused = ksp->ks_memuse;
285         splx(s);
286         /* XXX: Do idle pre-zeroing.  */
287         if (va != NULL && (flags & M_ZERO))
288                 bzero(va, size);
289         return ((void *) va);
290 }
291
292 /*
293  *      free:
294  *
295  *      Free a block of memory allocated by malloc.
296  *
297  *      This routine may not block.
298  */
299 void
300 free(addr, type)
301         void *addr;
302         struct malloc_type *type;
303 {
304         register struct kmembuckets *kbp;
305         register struct kmemusage *kup;
306         register struct freelist *freep;
307         long size;
308         int s;
309 #ifdef INVARIANTS
310         struct freelist *fp;
311         long *end, *lp, alloc, copysize;
312 #endif
313         register struct malloc_type *ksp = type;
314
315         if (type->ks_limit == 0)
316                 panic("freeing with unknown type (%s)", type->ks_shortdesc);
317
318         /* free(NULL, ...) does nothing */
319         if (addr == NULL)
320                 return;
321
322         KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
323             ("free: address %p out of range", (void *)addr));
324         kup = btokup(addr);
325         size = 1 << kup->ku_indx;
326         kbp = &bucket[kup->ku_indx];
327         s = splmem();
328 #ifdef INVARIANTS
329         /*
330          * Check for returns of data that do not point to the
331          * beginning of the allocation.
332          */
333         if (size > PAGE_SIZE)
334                 alloc = addrmask[BUCKETINDX(PAGE_SIZE)];
335         else
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;
345                 kup->ku_indx = 0;
346                 kup->ku_pagecnt = 0;
347                 if (ksp->ks_memuse + size >= ksp->ks_limit &&
348                     ksp->ks_memuse < ksp->ks_limit)
349                         wakeup((caddr_t)ksp);
350                 ksp->ks_inuse--;
351                 kbp->kb_total -= 1;
352                 splx(s);
353                 return;
354         }
355         freep = (struct freelist *)addr;
356 #ifdef INVARIANTS
357         /*
358          * Check for multiple frees. Use a quick check to see if
359          * it looks free before laboriously searching the freelist.
360          */
361         if (freep->spare0 == WEIRD_ADDR) {
362                 fp = (struct freelist *)kbp->kb_next;
363                 while (fp) {
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;
369                 }
370         }
371         /*
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.
376          */
377         copysize = size < MAX_COPY ? size : MAX_COPY;
378         end = (long *)&((caddr_t)addr)[copysize];
379         for (lp = (long *)addr; lp < end; lp++)
380                 *lp = WEIRD_ADDR;
381         freep->type = type;
382 #endif /* INVARIANTS */
383         kup->ku_freecnt++;
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)
388                         kbp->kb_couldfree++;
389         }
390         kbp->kb_totalfree++;
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);
395         ksp->ks_inuse--;
396 #ifdef OLD_MALLOC_MEMORY_POLICY
397         if (kbp->kb_next == NULL)
398                 kbp->kb_next = addr;
399         else
400                 ((struct freelist *)kbp->kb_last)->next = addr;
401         freep->next = NULL;
402         kbp->kb_last = addr;
403 #else
404         /*
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.
408          */
409         if (kbp->kb_next == NULL) {
410                 kbp->kb_next = addr;
411                 kbp->kb_last = addr;
412                 freep->next = NULL;
413         } else {
414                 freep->next = kbp->kb_next;
415                 kbp->kb_next = addr;
416         }
417 #endif
418         splx(s);
419 }
420
421 /*
422  *      realloc: change the size of a memory block
423  */
424 void *
425 realloc(addr, size, type, flags)
426         void *addr;
427         unsigned long size;
428         struct malloc_type *type;
429         int flags;
430 {
431         struct kmemusage *kup;
432         unsigned long alloc;
433         void *newaddr;
434
435         /* realloc(NULL, ...) is equivalent to malloc(...) */
436         if (addr == NULL)
437                 return (malloc(size, type, flags));
438
439         /* Sanity check */
440         KASSERT(kmembase <= (char *)addr && (char *)addr < kmemlimit,
441             ("realloc: address %p out of range", (void *)addr));
442
443         /* Get the size of the original block */
444         kup = btokup(addr);
445         alloc = 1 << kup->ku_indx;
446         if (alloc > MAXALLOCSAVE)
447                 alloc = kup->ku_pagecnt << PAGE_SHIFT;
448
449         /* Reuse the original block if appropriate */
450         if (size <= alloc
451             && (size > (alloc >> REALLOC_FRACTION) || alloc == MINALLOCSIZE))
452                 return (addr);
453
454         /* Allocate a new, bigger (or smaller) block */
455         if ((newaddr = malloc(size, type, flags)) == NULL)
456                 return (NULL);
457
458         /* Copy over original contents */
459         bcopy(addr, newaddr, min(size, alloc));
460         free(addr, type);
461         return (newaddr);
462 }
463
464 /*
465  *      reallocf: same as realloc() but free memory on failure.
466  */
467 void *
468 reallocf(addr, size, type, flags)
469         void *addr;
470         unsigned long size;
471         struct malloc_type *type;
472         int flags;
473 {
474         void *mem;
475
476         if ((mem = realloc(addr, size, type, flags)) == NULL)
477                 free(addr, type);
478         return (mem);
479 }
480
481 /*
482  * Initialize the kernel memory allocator
483  */
484 /* ARGSUSED*/
485 static void
486 kmeminit(dummy)
487         void *dummy;
488 {
489         register long indx;
490         u_long npg;
491         u_long mem_size;
492
493 #if     ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
494 #error "kmeminit: MAXALLOCSAVE not power of 2"
495 #endif
496 #if     (MAXALLOCSAVE > MINALLOCSIZE * 32768)
497 #error "kmeminit: MAXALLOCSAVE too big"
498 #endif
499 #if     (MAXALLOCSAVE < PAGE_SIZE)
500 #error "kmeminit: MAXALLOCSAVE too small"
501 #endif
502
503         /*
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.
511          *
512          * Note that the kmem_map is also used by the zone allocator,
513          * so make sure that there is enough space.
514          */
515         vm_kmem_size = VM_KMEM_SIZE;
516         mem_size = cnt.v_page_count * PAGE_SIZE;
517
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;
521 #endif
522
523 #if defined(VM_KMEM_SIZE_MAX)
524         if (vm_kmem_size >= VM_KMEM_SIZE_MAX)
525                 vm_kmem_size = VM_KMEM_SIZE_MAX;
526 #endif
527
528         /* Allow final override from the kernel environment */
529         TUNABLE_INT_FETCH("kern.vm.kmem.size", &vm_kmem_size);
530
531         /*
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.
536          */
537         if ((vm_kmem_size / 2) > (cnt.v_page_count * PAGE_SIZE))
538                 vm_kmem_size = 2 * cnt.v_page_count * PAGE_SIZE;
539
540         npg = (nmbufs * MSIZE + nmbclusters * MCLBYTES + vm_kmem_size)
541                 / PAGE_SIZE;
542
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;
551                 else
552                         bucket[indx].kb_elmpercl = PAGE_SIZE / (1 << indx);
553                 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
554         }
555 }
556
557 void
558 malloc_init(data)
559         void *data;
560 {
561         struct malloc_type *type = (struct malloc_type *)data;
562
563         if (type->ks_magic != M_MAGIC)
564                 panic("malloc type lacks magic");
565
566         if (type->ks_limit != 0)
567                 return;
568
569         if (cnt.v_page_count == 0)
570                 panic("malloc_init not allowed before vm init");
571
572         /*
573          * The default limits for each malloc region is 1/2 of the
574          * malloc portion of the kmem map size.
575          */
576         type->ks_limit = vm_kmem_size / 2;
577         type->ks_next = kmemstatistics; 
578         kmemstatistics = type;
579 }
580
581 void
582 malloc_uninit(data)
583         void *data;
584 {
585         struct malloc_type *type = (struct malloc_type *)data;
586         struct malloc_type *t;
587 #ifdef INVARIANTS
588         struct kmembuckets *kbp;
589         struct freelist *freep;
590         long indx;
591         int s;
592 #endif
593
594         if (type->ks_magic != M_MAGIC)
595                 panic("malloc type lacks magic");
596
597         if (cnt.v_page_count == 0)
598                 panic("malloc_uninit not allowed before vm init");
599
600         if (type->ks_limit == 0)
601                 panic("malloc_uninit on uninitialized type");
602
603 #ifdef INVARIANTS
604         s = splmem();
605         for (indx = 0; indx < MINBUCKET + 16; indx++) {
606                 kbp = bucket + indx;
607                 freep = (struct freelist*)kbp->kb_next;
608                 while (freep) {
609                         if (freep->type == type)
610                                 freep->type = M_FREE;
611                         freep = (struct freelist*)freep->next;
612                 }
613         }
614         splx(s);
615
616         if (type->ks_memuse != 0)
617                 printf("malloc_uninit: %ld bytes of '%s' still allocated\n",
618                     type->ks_memuse, type->ks_shortdesc);
619 #endif
620
621         if (type == kmemstatistics)
622                 kmemstatistics = type->ks_next;
623         else {
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;
627                                 break;
628                         }
629                 }
630         }
631         type->ks_next = NULL;
632         type->ks_limit = 0;
633 }