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