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