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