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