kern_malloc.c revision 1.33.2.1 1 /* $NetBSD: kern_malloc.c,v 1.33.2.1 1998/07/30 14:04:04 eeh Exp $ */
2
3 /*
4 * Copyright 1996 Christopher G. Demetriou. All rights reserved.
5 * Copyright (c) 1987, 1991, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)kern_malloc.c 8.4 (Berkeley) 5/20/95
37 */
38
39 #include "opt_lockdebug.h"
40 #include "opt_uvm.h"
41
42 #include <sys/param.h>
43 #include <sys/proc.h>
44 #include <sys/map.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
47 #include <sys/systm.h>
48
49 #include <vm/vm.h>
50 #include <vm/vm_kern.h>
51
52 #if defined(UVM)
53 #include <uvm/uvm_extern.h>
54
55 static struct vm_map kmem_map_store;
56 vm_map_t kmem_map = NULL;
57 #endif
58
59 #include "opt_kmemstats.h"
60 #include "opt_malloclog.h"
61
62 struct kmembuckets bucket[MINBUCKET + 16];
63 struct kmemstats kmemstats[M_LAST];
64 struct kmemusage *kmemusage;
65 char *kmembase, *kmemlimit;
66 const char *memname[] = INITKMEMNAMES;
67
68 #ifdef MALLOCLOG
69 #ifndef MALLOCLOGSIZE
70 #define MALLOCLOGSIZE 100000
71 #endif
72
73 struct malloclog {
74 void *addr;
75 long size;
76 int type;
77 int action;
78 const char *file;
79 long line;
80 } malloclog[MALLOCLOGSIZE];
81
82 long malloclogptr;
83
84 static void domlog __P((void *a, long size, int type, int action,
85 const char *file, long line));
86 static void hitmlog __P((void *a));
87
88 static void
89 domlog(a, size, type, action, file, line)
90 void *a;
91 long size;
92 int type;
93 int action;
94 const char *file;
95 long line;
96 {
97
98 malloclog[malloclogptr].addr = a;
99 malloclog[malloclogptr].size = size;
100 malloclog[malloclogptr].type = type;
101 malloclog[malloclogptr].action = action;
102 malloclog[malloclogptr].file = file;
103 malloclog[malloclogptr].line = line;
104 malloclogptr++;
105 if (malloclogptr >= MALLOCLOGSIZE)
106 malloclogptr = 0;
107 }
108
109 static void
110 hitmlog(a)
111 void *a;
112 {
113 struct malloclog *lp;
114 long l;
115
116 #define PRT \
117 if (malloclog[l].addr == a && malloclog[l].action) { \
118 lp = &malloclog[l]; \
119 printf("malloc log entry %ld:\n", l); \
120 printf("\taddr = %p\n", lp->addr); \
121 printf("\tsize = %ld\n", lp->size); \
122 printf("\ttype = %s\n", memname[lp->type]); \
123 printf("\taction = %s\n", lp->action == 1 ? "alloc" : "free"); \
124 printf("\tfile = %s\n", lp->file); \
125 printf("\tline = %ld\n", lp->line); \
126 }
127
128 for (l = malloclogptr; l < MALLOCLOGSIZE; l++)
129 PRT
130
131 for (l = 0; l < malloclogptr; l++)
132 PRT
133 }
134 #endif /* MALLOCLOG */
135
136 #ifdef DIAGNOSTIC
137 /*
138 * This structure provides a set of masks to catch unaligned frees.
139 */
140 long addrmask[] = { 0,
141 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
142 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
143 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
144 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
145 };
146
147 /*
148 * The WEIRD_ADDR is used as known text to copy into free objects so
149 * that modifications after frees can be detected.
150 */
151 #define WEIRD_ADDR ((unsigned) 0xdeadbeef)
152 #define MAX_COPY 32
153
154 /*
155 * Normally the freelist structure is used only to hold the list pointer
156 * for free objects. However, when running with diagnostics, the first
157 * 8 bytes of the structure is unused except for diagnostic information,
158 * and the free list pointer is at offst 8 in the structure. Since the
159 * first 8 bytes is the portion of the structure most often modified, this
160 * helps to detect memory reuse problems and avoid free list corruption.
161 */
162 struct freelist {
163 int32_t spare0;
164 int16_t type;
165 int16_t spare1;
166 caddr_t next;
167 };
168 #else /* !DIAGNOSTIC */
169 struct freelist {
170 caddr_t next;
171 };
172 #endif /* DIAGNOSTIC */
173
174 /*
175 * Allocate a block of memory
176 */
177 #ifdef MALLOCLOG
178 void *
179 _malloc(size, type, flags, file, line)
180 unsigned long size;
181 int type, flags;
182 const char *file;
183 long line;
184 #else
185 void *
186 malloc(size, type, flags)
187 unsigned long size;
188 int type, flags;
189 #endif /* MALLOCLOG */
190 {
191 register struct kmembuckets *kbp;
192 register struct kmemusage *kup;
193 register struct freelist *freep;
194 long indx, npg, allocsize;
195 int s;
196 caddr_t va, cp, savedlist;
197 #ifdef DIAGNOSTIC
198 int32_t *end, *lp;
199 int copysize;
200 const char *savedtype;
201 #endif
202 #ifdef LOCKDEBUG
203 extern int simplelockrecurse;
204 #endif
205 #ifdef KMEMSTATS
206 register struct kmemstats *ksp = &kmemstats[type];
207
208 if (((unsigned long)type) > M_LAST)
209 panic("malloc - bogus type");
210 #endif
211 indx = BUCKETINDX(size);
212 kbp = &bucket[indx];
213 s = splimp();
214 #ifdef KMEMSTATS
215 while (ksp->ks_memuse >= ksp->ks_limit) {
216 if (flags & M_NOWAIT) {
217 splx(s);
218 return ((void *) NULL);
219 }
220 if (ksp->ks_limblocks < 65535)
221 ksp->ks_limblocks++;
222 tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
223 }
224 ksp->ks_size |= 1 << indx;
225 #endif
226 #ifdef DIAGNOSTIC
227 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
228 #endif
229 #ifdef LOCKDEBUG
230 if (flags & M_NOWAIT)
231 simplelockrecurse++;
232 #endif
233 if (kbp->kb_next == NULL) {
234 kbp->kb_last = NULL;
235 if (size > MAXALLOCSAVE)
236 allocsize = roundup(size, CLBYTES);
237 else
238 allocsize = 1 << indx;
239 npg = clrnd(btoc(allocsize));
240 #if defined(UVM)
241 va = (caddr_t) uvm_km_kmemalloc(kmem_map, uvmexp.kmem_object,
242 (vsize_t)ctob(npg),
243 (flags & M_NOWAIT) ? UVM_KMF_NOWAIT : 0);
244 #else
245 va = (caddr_t) kmem_malloc(kmem_map, (vsize_t)ctob(npg),
246 !(flags & M_NOWAIT));
247 #endif
248 if (va == NULL) {
249 /*
250 * Kmem_malloc() can return NULL, even if it can
251 * wait, if there is no map space avaiable, because
252 * it can't fix that problem. Neither can we,
253 * right now. (We should release pages which
254 * are completely free and which are in buckets
255 * with too many free elements.)
256 */
257 if ((flags & M_NOWAIT) == 0)
258 panic("malloc: out of space in kmem_map");
259 #ifdef LOCKDEBUG
260 simplelockrecurse--;
261 #endif
262 splx(s);
263 return ((void *) NULL);
264 }
265 #ifdef KMEMSTATS
266 kbp->kb_total += kbp->kb_elmpercl;
267 #endif
268 kup = btokup(va);
269 kup->ku_indx = indx;
270 if (allocsize > MAXALLOCSAVE) {
271 if (npg > 65535)
272 panic("malloc: allocation too large");
273 kup->ku_pagecnt = npg;
274 #ifdef KMEMSTATS
275 ksp->ks_memuse += allocsize;
276 #endif
277 goto out;
278 }
279 #ifdef KMEMSTATS
280 kup->ku_freecnt = kbp->kb_elmpercl;
281 kbp->kb_totalfree += kbp->kb_elmpercl;
282 #endif
283 /*
284 * Just in case we blocked while allocating memory,
285 * and someone else also allocated memory for this
286 * bucket, don't assume the list is still empty.
287 */
288 savedlist = kbp->kb_next;
289 kbp->kb_next = cp = va + (npg * NBPG) - allocsize;
290 for (;;) {
291 freep = (struct freelist *)cp;
292 #ifdef DIAGNOSTIC
293 /*
294 * Copy in known text to detect modification
295 * after freeing.
296 */
297 end = (int32_t *)&cp[copysize];
298 for (lp = (int32_t *)cp; lp < end; lp++)
299 *lp = WEIRD_ADDR;
300 freep->type = M_FREE;
301 #endif /* DIAGNOSTIC */
302 if (cp <= va)
303 break;
304 cp -= allocsize;
305 freep->next = cp;
306 }
307 freep->next = savedlist;
308 if (kbp->kb_last == NULL)
309 kbp->kb_last = (caddr_t)freep;
310 }
311 va = kbp->kb_next;
312 kbp->kb_next = ((struct freelist *)va)->next;
313 #ifdef DIAGNOSTIC
314 freep = (struct freelist *)va;
315 savedtype = (unsigned)freep->type < M_LAST ?
316 memname[freep->type] : "???";
317 #if defined(UVM)
318 if (kbp->kb_next) {
319 int rv;
320 vaddr_t addr = (vaddr_t)kbp->kb_next;
321
322 vm_map_lock_read(kmem_map);
323 rv = uvm_map_checkprot(kmem_map, addr,
324 addr + sizeof(struct freelist),
325 VM_PROT_WRITE);
326 vm_map_unlock_read(kmem_map);
327
328 if (!rv)
329 #else
330 if (kbp->kb_next &&
331 !kernacc(kbp->kb_next, sizeof(struct freelist), 0))
332 #endif
333 {
334 printf(
335 "%s %ld of object %p size %ld %s %s (invalid addr %p)\n",
336 "Data modified on freelist: word",
337 (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
338 va, size, "previous type", savedtype, kbp->kb_next);
339 #ifdef MALLOCLOG
340 hitmlog(va);
341 #endif
342 kbp->kb_next = NULL;
343 #if defined(UVM)
344 }
345 #endif
346 }
347
348 /* Fill the fields that we've used with WEIRD_ADDR */
349 #if BYTE_ORDER == BIG_ENDIAN
350 freep->type = WEIRD_ADDR >> 16;
351 #endif
352 #if BYTE_ORDER == LITTLE_ENDIAN
353 freep->type = (short)WEIRD_ADDR;
354 #endif
355 end = (int32_t *)&freep->next +
356 (sizeof(freep->next) / sizeof(int32_t));
357 for (lp = (int32_t *)&freep->next; lp < end; lp++)
358 *lp = WEIRD_ADDR;
359
360 /* and check that the data hasn't been modified. */
361 end = (int32_t *)&va[copysize];
362 for (lp = (int32_t *)va; lp < end; lp++) {
363 if (*lp == WEIRD_ADDR)
364 continue;
365 printf("%s %ld of object %p size %ld %s %s (0x%x != 0x%x)\n",
366 "Data modified on freelist: word",
367 (long)(lp - (int32_t *)va), va, size, "previous type",
368 savedtype, *lp, WEIRD_ADDR);
369 #ifdef MALLOCLOG
370 hitmlog(va);
371 #endif
372 break;
373 }
374
375 freep->spare0 = 0;
376 #endif /* DIAGNOSTIC */
377 #ifdef KMEMSTATS
378 kup = btokup(va);
379 if (kup->ku_indx != indx)
380 panic("malloc: wrong bucket");
381 if (kup->ku_freecnt == 0)
382 panic("malloc: lost data");
383 kup->ku_freecnt--;
384 kbp->kb_totalfree--;
385 ksp->ks_memuse += 1 << indx;
386 out:
387 kbp->kb_calls++;
388 ksp->ks_inuse++;
389 ksp->ks_calls++;
390 if (ksp->ks_memuse > ksp->ks_maxused)
391 ksp->ks_maxused = ksp->ks_memuse;
392 #else
393 out:
394 #endif
395 #ifdef MALLOCLOG
396 domlog(va, size, type, 1, file, line);
397 #endif
398 splx(s);
399 #ifdef LOCKDEBUG
400 if (flags & M_NOWAIT)
401 simplelockrecurse--;
402 #endif
403 return ((void *) va);
404 }
405
406 /*
407 * Free a block of memory allocated by malloc.
408 */
409 #ifdef MALLOCLOG
410 void
411 _free(addr, type, file, line)
412 void *addr;
413 int type;
414 const char *file;
415 long line;
416 #else
417 void
418 free(addr, type)
419 void *addr;
420 int type;
421 #endif /* MALLOCLOG */
422 {
423 register struct kmembuckets *kbp;
424 register struct kmemusage *kup;
425 register struct freelist *freep;
426 long size;
427 int s;
428 #ifdef DIAGNOSTIC
429 caddr_t cp;
430 int32_t *end, *lp;
431 long alloc, copysize;
432 #endif
433 #ifdef KMEMSTATS
434 register struct kmemstats *ksp = &kmemstats[type];
435 #endif
436
437 kup = btokup(addr);
438 size = 1 << kup->ku_indx;
439 kbp = &bucket[kup->ku_indx];
440 s = splimp();
441 #ifdef MALLOCLOG
442 domlog(addr, 0, type, 2, file, line);
443 #endif
444 #ifdef DIAGNOSTIC
445 /*
446 * Check for returns of data that do not point to the
447 * beginning of the allocation.
448 */
449 if (size > NBPG * CLSIZE)
450 alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
451 else
452 alloc = addrmask[kup->ku_indx];
453 if (((u_long)addr & alloc) != 0)
454 panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
455 addr, size, memname[type], alloc);
456 #endif /* DIAGNOSTIC */
457 if (size > MAXALLOCSAVE) {
458 #if defined(UVM)
459 uvm_km_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
460 #else
461 kmem_free(kmem_map, (vaddr_t)addr, ctob(kup->ku_pagecnt));
462 #endif
463 #ifdef KMEMSTATS
464 size = kup->ku_pagecnt << PGSHIFT;
465 ksp->ks_memuse -= size;
466 kup->ku_indx = 0;
467 kup->ku_pagecnt = 0;
468 if (ksp->ks_memuse + size >= ksp->ks_limit &&
469 ksp->ks_memuse < ksp->ks_limit)
470 wakeup((caddr_t)ksp);
471 ksp->ks_inuse--;
472 kbp->kb_total -= 1;
473 #endif
474 splx(s);
475 return;
476 }
477 freep = (struct freelist *)addr;
478 #ifdef DIAGNOSTIC
479 /*
480 * Check for multiple frees. Use a quick check to see if
481 * it looks free before laboriously searching the freelist.
482 */
483 if (freep->spare0 == WEIRD_ADDR) {
484 for (cp = kbp->kb_next; cp;
485 cp = ((struct freelist *)cp)->next) {
486 if (addr != cp)
487 continue;
488 printf("multiply freed item %p\n", addr);
489 #ifdef MALLOCLOG
490 hitmlog(addr);
491 #endif
492 panic("free: duplicated free");
493 }
494 }
495 /*
496 * Copy in known text to detect modification after freeing
497 * and to make it look free. Also, save the type being freed
498 * so we can list likely culprit if modification is detected
499 * when the object is reallocated.
500 */
501 copysize = size < MAX_COPY ? size : MAX_COPY;
502 end = (int32_t *)&((caddr_t)addr)[copysize];
503 for (lp = (int32_t *)addr; lp < end; lp++)
504 *lp = WEIRD_ADDR;
505 freep->type = type;
506 #endif /* DIAGNOSTIC */
507 #ifdef KMEMSTATS
508 kup->ku_freecnt++;
509 if (kup->ku_freecnt >= kbp->kb_elmpercl)
510 if (kup->ku_freecnt > kbp->kb_elmpercl)
511 panic("free: multiple frees");
512 else if (kbp->kb_totalfree > kbp->kb_highwat)
513 kbp->kb_couldfree++;
514 kbp->kb_totalfree++;
515 ksp->ks_memuse -= size;
516 if (ksp->ks_memuse + size >= ksp->ks_limit &&
517 ksp->ks_memuse < ksp->ks_limit)
518 wakeup((caddr_t)ksp);
519 ksp->ks_inuse--;
520 #endif
521 if (kbp->kb_next == NULL)
522 kbp->kb_next = addr;
523 else
524 ((struct freelist *)kbp->kb_last)->next = addr;
525 freep->next = NULL;
526 kbp->kb_last = addr;
527 splx(s);
528 }
529
530 /*
531 * Change the size of a block of memory.
532 */
533 void *
534 realloc(curaddr, newsize, type, flags)
535 void *curaddr;
536 unsigned long newsize;
537 int type, flags;
538 {
539 register struct kmemusage *kup;
540 long cursize;
541 void *newaddr;
542 #ifdef DIAGNOSTIC
543 long alloc;
544 #endif
545
546 /*
547 * Realloc() with a NULL pointer is the same as malloc().
548 */
549 if (curaddr == NULL)
550 return (malloc(newsize, type, flags));
551
552 /*
553 * Realloc() with zero size is the same as free().
554 */
555 if (newsize == 0) {
556 free(curaddr, type);
557 return (NULL);
558 }
559
560 /*
561 * Find out how large the old allocation was (and do some
562 * sanity checking).
563 */
564 kup = btokup(curaddr);
565 cursize = 1 << kup->ku_indx;
566
567 #ifdef DIAGNOSTIC
568 /*
569 * Check for returns of data that do not point to the
570 * beginning of the allocation.
571 */
572 if (cursize > NBPG * CLSIZE)
573 alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
574 else
575 alloc = addrmask[kup->ku_indx];
576 if (((u_long)curaddr & alloc) != 0)
577 panic("realloc: unaligned addr %p, size %ld, type %s, mask %ld\n",
578 curaddr, cursize, memname[type], alloc);
579 #endif /* DIAGNOSTIC */
580
581 if (cursize > MAXALLOCSAVE)
582 cursize = ctob(kup->ku_pagecnt);
583
584 /*
585 * If we already actually have as much as they want, we're done.
586 */
587 if (newsize <= cursize)
588 return (curaddr);
589
590 /*
591 * Can't satisfy the allocation with the existing block.
592 * Allocate a new one and copy the data.
593 */
594 newaddr = malloc(newsize, type, flags);
595 if (newaddr == NULL) {
596 /*
597 * Malloc() failed, because flags included M_NOWAIT.
598 * Return NULL to indicate that failure. The old
599 * pointer is still valid.
600 */
601 return NULL;
602 }
603 bcopy(curaddr, newaddr, cursize);
604
605 /*
606 * We were successful: free the old allocation and return
607 * the new one.
608 */
609 free(curaddr, type);
610 return (newaddr);
611 }
612
613 /*
614 * Initialize the kernel memory allocator
615 */
616 void
617 kmeminit()
618 {
619 #ifdef KMEMSTATS
620 register long indx;
621 #endif
622 int npg;
623
624 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
625 ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
626 #endif
627 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
628 ERROR!_kmeminit:_MAXALLOCSAVE_too_big
629 #endif
630 #if (MAXALLOCSAVE < CLBYTES)
631 ERROR!_kmeminit:_MAXALLOCSAVE_too_small
632 #endif
633
634 if (sizeof(struct freelist) > (1 << MINBUCKET))
635 panic("minbucket too small/struct freelist too big");
636
637 npg = VM_KMEM_SIZE/ NBPG;
638 #if defined(UVM)
639 kmemusage = (struct kmemusage *) uvm_km_zalloc(kernel_map,
640 (vsize_t)(npg * sizeof(struct kmemusage)));
641 kmem_map = uvm_km_suballoc(kernel_map, (vaddr_t *)&kmembase,
642 (vaddr_t *)&kmemlimit, (vsize_t)(npg * NBPG),
643 FALSE, FALSE, &kmem_map_store);
644 #else
645 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
646 (vsize_t)(npg * sizeof(struct kmemusage)));
647 kmem_map = kmem_suballoc(kernel_map, (vaddr_t *)&kmembase,
648 (vaddr_t *)&kmemlimit, (vsize_t)(npg * NBPG), FALSE);
649 #endif
650 #ifdef KMEMSTATS
651 for (indx = 0; indx < MINBUCKET + 16; indx++) {
652 if (1 << indx >= CLBYTES)
653 bucket[indx].kb_elmpercl = 1;
654 else
655 bucket[indx].kb_elmpercl = CLBYTES / (1 << indx);
656 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
657 }
658 for (indx = 0; indx < M_LAST; indx++)
659 kmemstats[indx].ks_limit = npg * NBPG * 6 / 10;
660 #endif
661 }
662