kern_malloc.c revision 1.23 1 /* $NetBSD: kern_malloc.c,v 1.23 1997/01/30 06:50:46 tls 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 struct kmembuckets bucket[MINBUCKET + 16];
50 struct kmemstats kmemstats[M_LAST];
51 struct kmemusage *kmemusage;
52 char *kmembase, *kmemlimit;
53 char *memname[] = INITKMEMNAMES;
54
55 #ifdef DIAGNOSTIC
56 /*
57 * This structure provides a set of masks to catch unaligned frees.
58 */
59 long addrmask[] = { 0,
60 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
61 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
62 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
63 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
64 };
65
66 /*
67 * The WEIRD_ADDR is used as known text to copy into free objects so
68 * that modifications after frees can be detected.
69 */
70 #define WEIRD_ADDR ((unsigned) 0xdeadbeef)
71 #define MAX_COPY 32
72
73 /*
74 * Normally the freelist structure is used only to hold the list pointer
75 * for free objects. However, when running with diagnostics, the first
76 * 8 bytes of the structure is unused except for diagnostic information,
77 * and the free list pointer is at offst 8 in the structure. Since the
78 * first 8 bytes is the portion of the structure most often modified, this
79 * helps to detect memory reuse problems and avoid free list corruption.
80 */
81 struct freelist {
82 int32_t spare0;
83 int16_t type;
84 int16_t spare1;
85 caddr_t next;
86 };
87 #else /* !DIAGNOSTIC */
88 struct freelist {
89 caddr_t next;
90 };
91 #endif /* DIAGNOSTIC */
92
93 /*
94 * Allocate a block of memory
95 */
96 void *
97 malloc(size, type, flags)
98 unsigned long size;
99 int type, flags;
100 {
101 register struct kmembuckets *kbp;
102 register struct kmemusage *kup;
103 register struct freelist *freep;
104 long indx, npg, allocsize;
105 int s;
106 caddr_t va, cp, savedlist;
107 #ifdef DIAGNOSTIC
108 int32_t *end, *lp;
109 int copysize;
110 char *savedtype;
111 #endif
112 #ifdef KMEMSTATS
113 register struct kmemstats *ksp = &kmemstats[type];
114
115 if (((unsigned long)type) > M_LAST)
116 panic("malloc - bogus type");
117 #endif
118 indx = BUCKETINDX(size);
119 kbp = &bucket[indx];
120 s = splimp();
121 #ifdef KMEMSTATS
122 while (ksp->ks_memuse >= ksp->ks_limit) {
123 if (flags & M_NOWAIT) {
124 splx(s);
125 return ((void *) NULL);
126 }
127 if (ksp->ks_limblocks < 65535)
128 ksp->ks_limblocks++;
129 tsleep((caddr_t)ksp, PSWP+2, memname[type], 0);
130 }
131 ksp->ks_size |= 1 << indx;
132 #endif
133 #ifdef DIAGNOSTIC
134 copysize = 1 << indx < MAX_COPY ? 1 << indx : MAX_COPY;
135 #endif
136 if (kbp->kb_next == NULL) {
137 kbp->kb_last = NULL;
138 if (size > MAXALLOCSAVE)
139 allocsize = roundup(size, CLBYTES);
140 else
141 allocsize = 1 << indx;
142 npg = clrnd(btoc(allocsize));
143 va = (caddr_t) kmem_malloc(kmem_map, (vm_size_t)ctob(npg),
144 !(flags & M_NOWAIT));
145 if (va == NULL) {
146 /*
147 * Kmem_malloc() can return NULL, even if it can
148 * wait, if there is no map space avaiable, because
149 * it can't fix that problem. Neither can we,
150 * right now. (We should release pages which
151 * are completely free and which are in buckets
152 * with too many free elements.)
153 */
154 if ((flags & M_NOWAIT) == 0)
155 panic("malloc: out of space in kmem_map");
156 splx(s);
157 return ((void *) NULL);
158 }
159 #ifdef KMEMSTATS
160 kbp->kb_total += kbp->kb_elmpercl;
161 #endif
162 kup = btokup(va);
163 kup->ku_indx = indx;
164 if (allocsize > MAXALLOCSAVE) {
165 if (npg > 65535)
166 panic("malloc: allocation too large");
167 kup->ku_pagecnt = npg;
168 #ifdef KMEMSTATS
169 ksp->ks_memuse += allocsize;
170 #endif
171 goto out;
172 }
173 #ifdef KMEMSTATS
174 kup->ku_freecnt = kbp->kb_elmpercl;
175 kbp->kb_totalfree += kbp->kb_elmpercl;
176 #endif
177 /*
178 * Just in case we blocked while allocating memory,
179 * and someone else also allocated memory for this
180 * bucket, don't assume the list is still empty.
181 */
182 savedlist = kbp->kb_next;
183 kbp->kb_next = cp = va + (npg * NBPG) - allocsize;
184 for (;;) {
185 freep = (struct freelist *)cp;
186 #ifdef DIAGNOSTIC
187 /*
188 * Copy in known text to detect modification
189 * after freeing.
190 */
191 end = (int32_t *)&cp[copysize];
192 for (lp = (int32_t *)cp; lp < end; lp++)
193 *lp = WEIRD_ADDR;
194 freep->type = M_FREE;
195 #endif /* DIAGNOSTIC */
196 if (cp <= va)
197 break;
198 cp -= allocsize;
199 freep->next = cp;
200 }
201 freep->next = savedlist;
202 if (kbp->kb_last == NULL)
203 kbp->kb_last = (caddr_t)freep;
204 }
205 va = kbp->kb_next;
206 kbp->kb_next = ((struct freelist *)va)->next;
207 #ifdef DIAGNOSTIC
208 freep = (struct freelist *)va;
209 savedtype = (unsigned)freep->type < M_LAST ?
210 memname[freep->type] : "???";
211 if (kbp->kb_next &&
212 !kernacc(kbp->kb_next, sizeof(struct freelist), 0)) {
213 printf(
214 "%s %ld of object %p size %ld %s %s (invalid addr %p)\n",
215 "Data modified on freelist: word",
216 (long)((int32_t *)&kbp->kb_next - (int32_t *)kbp),
217 va, size, "previous type", savedtype, kbp->kb_next);
218 kbp->kb_next = NULL;
219 }
220
221 /* Fill the fields that we've used with WEIRD_ADDR */
222 #if BYTE_ORDER == BIG_ENDIAN
223 freep->type = WEIRD_ADDR >> 16;
224 #endif
225 #if BYTE_ORDER == LITTLE_ENDIAN
226 freep->type = (short)WEIRD_ADDR;
227 #endif
228 end = (int32_t *)&freep->next +
229 (sizeof(freep->next) / sizeof(int32_t));
230 for (lp = (int32_t *)&freep->next; lp < end; lp++)
231 *lp = WEIRD_ADDR;
232
233 /* and check that the data hasn't been modified. */
234 end = (int32_t *)&va[copysize];
235 for (lp = (int32_t *)va; lp < end; lp++) {
236 if (*lp == WEIRD_ADDR)
237 continue;
238 printf("%s %ld of object %p size %ld %s %s (0x%x != 0x%x)\n",
239 "Data modified on freelist: word",
240 (long)(lp - (int32_t *)va), va, size, "previous type",
241 savedtype, *lp, WEIRD_ADDR);
242 break;
243 }
244
245 freep->spare0 = 0;
246 #endif /* DIAGNOSTIC */
247 #ifdef KMEMSTATS
248 kup = btokup(va);
249 if (kup->ku_indx != indx)
250 panic("malloc: wrong bucket");
251 if (kup->ku_freecnt == 0)
252 panic("malloc: lost data");
253 kup->ku_freecnt--;
254 kbp->kb_totalfree--;
255 ksp->ks_memuse += 1 << indx;
256 out:
257 kbp->kb_calls++;
258 ksp->ks_inuse++;
259 ksp->ks_calls++;
260 if (ksp->ks_memuse > ksp->ks_maxused)
261 ksp->ks_maxused = ksp->ks_memuse;
262 #else
263 out:
264 #endif
265 splx(s);
266 return ((void *) va);
267 }
268
269 /*
270 * Free a block of memory allocated by malloc.
271 */
272 void
273 free(addr, type)
274 void *addr;
275 int type;
276 {
277 register struct kmembuckets *kbp;
278 register struct kmemusage *kup;
279 register struct freelist *freep;
280 long size;
281 int s;
282 #ifdef DIAGNOSTIC
283 caddr_t cp;
284 int32_t *end, *lp;
285 long alloc, copysize;
286 #endif
287 #ifdef KMEMSTATS
288 register struct kmemstats *ksp = &kmemstats[type];
289 #endif
290
291 kup = btokup(addr);
292 size = 1 << kup->ku_indx;
293 kbp = &bucket[kup->ku_indx];
294 s = splimp();
295 #ifdef DIAGNOSTIC
296 /*
297 * Check for returns of data that do not point to the
298 * beginning of the allocation.
299 */
300 if (size > NBPG * CLSIZE)
301 alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
302 else
303 alloc = addrmask[kup->ku_indx];
304 if (((u_long)addr & alloc) != 0)
305 panic("free: unaligned addr %p, size %ld, type %s, mask %ld\n",
306 addr, size, memname[type], alloc);
307 #endif /* DIAGNOSTIC */
308 if (size > MAXALLOCSAVE) {
309 kmem_free(kmem_map, (vm_offset_t)addr, ctob(kup->ku_pagecnt));
310 #ifdef KMEMSTATS
311 size = kup->ku_pagecnt << PGSHIFT;
312 ksp->ks_memuse -= size;
313 kup->ku_indx = 0;
314 kup->ku_pagecnt = 0;
315 if (ksp->ks_memuse + size >= ksp->ks_limit &&
316 ksp->ks_memuse < ksp->ks_limit)
317 wakeup((caddr_t)ksp);
318 ksp->ks_inuse--;
319 kbp->kb_total -= 1;
320 #endif
321 splx(s);
322 return;
323 }
324 freep = (struct freelist *)addr;
325 #ifdef DIAGNOSTIC
326 /*
327 * Check for multiple frees. Use a quick check to see if
328 * it looks free before laboriously searching the freelist.
329 */
330 if (freep->spare0 == WEIRD_ADDR) {
331 for (cp = kbp->kb_next; cp;
332 cp = ((struct freelist *)cp)->next) {
333 if (addr != cp)
334 continue;
335 printf("multiply freed item %p\n", addr);
336 panic("free: duplicated free");
337 }
338 }
339 /*
340 * Copy in known text to detect modification after freeing
341 * and to make it look free. Also, save the type being freed
342 * so we can list likely culprit if modification is detected
343 * when the object is reallocated.
344 */
345 copysize = size < MAX_COPY ? size : MAX_COPY;
346 end = (int32_t *)&((caddr_t)addr)[copysize];
347 for (lp = (int32_t *)addr; lp < end; lp++)
348 *lp = WEIRD_ADDR;
349 freep->type = type;
350 #endif /* DIAGNOSTIC */
351 #ifdef KMEMSTATS
352 kup->ku_freecnt++;
353 if (kup->ku_freecnt >= kbp->kb_elmpercl)
354 if (kup->ku_freecnt > kbp->kb_elmpercl)
355 panic("free: multiple frees");
356 else if (kbp->kb_totalfree > kbp->kb_highwat)
357 kbp->kb_couldfree++;
358 kbp->kb_totalfree++;
359 ksp->ks_memuse -= size;
360 if (ksp->ks_memuse + size >= ksp->ks_limit &&
361 ksp->ks_memuse < ksp->ks_limit)
362 wakeup((caddr_t)ksp);
363 ksp->ks_inuse--;
364 #endif
365 if (kbp->kb_next == NULL)
366 kbp->kb_next = addr;
367 else
368 ((struct freelist *)kbp->kb_last)->next = addr;
369 freep->next = NULL;
370 kbp->kb_last = addr;
371 splx(s);
372 }
373
374 /*
375 * Change the size of a block of memory.
376 */
377 void *
378 realloc(curaddr, newsize, type, flags)
379 void *curaddr;
380 unsigned long newsize;
381 int type, flags;
382 {
383 register struct kmemusage *kup;
384 long cursize;
385 void *newaddr;
386 #ifdef DIAGNOSTIC
387 long alloc;
388 #endif
389
390 /*
391 * Realloc() with a NULL pointer is the same as malloc().
392 */
393 if (curaddr == NULL)
394 return (malloc(newsize, type, flags));
395
396 /*
397 * Realloc() with zero size is the same as free().
398 */
399 if (newsize == 0) {
400 free(curaddr, type);
401 return (NULL);
402 }
403
404 /*
405 * Find out how large the old allocation was (and do some
406 * sanity checking).
407 */
408 kup = btokup(curaddr);
409 cursize = 1 << kup->ku_indx;
410
411 #ifdef DIAGNOSTIC
412 /*
413 * Check for returns of data that do not point to the
414 * beginning of the allocation.
415 */
416 if (cursize > NBPG * CLSIZE)
417 alloc = addrmask[BUCKETINDX(NBPG * CLSIZE)];
418 else
419 alloc = addrmask[kup->ku_indx];
420 if (((u_long)curaddr & alloc) != 0)
421 panic("realloc: unaligned addr %p, size %ld, type %s, mask %ld\n",
422 curaddr, cursize, memname[type], alloc);
423 #endif /* DIAGNOSTIC */
424
425 if (cursize > MAXALLOCSAVE)
426 cursize = ctob(kup->ku_pagecnt);
427
428 /*
429 * If we already actually have as much as they want, we're done.
430 */
431 if (newsize <= cursize)
432 return (curaddr);
433
434 /*
435 * Can't satisfy the allocation with the existing block.
436 * Allocate a new one and copy the data.
437 */
438 newaddr = malloc(newsize, type, flags);
439 if (newaddr == NULL) {
440 /*
441 * Malloc() failed, because flags included M_NOWAIT.
442 * Return NULL to indicate that failure. The old
443 * pointer is still valid.
444 */
445 return NULL;
446 }
447 bcopy(curaddr, newaddr, cursize);
448
449 /*
450 * We were successful: free the old allocation and return
451 * the new one.
452 */
453 free(curaddr, type);
454 return (newaddr);
455 }
456
457 /*
458 * Initialize the kernel memory allocator
459 */
460 void
461 kmeminit()
462 {
463 #ifdef KMEMSTATS
464 register long indx;
465 #endif
466 int npg;
467
468 #if ((MAXALLOCSAVE & (MAXALLOCSAVE - 1)) != 0)
469 ERROR!_kmeminit:_MAXALLOCSAVE_not_power_of_2
470 #endif
471 #if (MAXALLOCSAVE > MINALLOCSIZE * 32768)
472 ERROR!_kmeminit:_MAXALLOCSAVE_too_big
473 #endif
474 #if (MAXALLOCSAVE < CLBYTES)
475 ERROR!_kmeminit:_MAXALLOCSAVE_too_small
476 #endif
477
478 if (sizeof(struct freelist) > (1 << MINBUCKET))
479 panic("minbucket too small/struct freelist too big");
480
481 npg = VM_KMEM_SIZE/ NBPG;
482 kmemusage = (struct kmemusage *) kmem_alloc(kernel_map,
483 (vm_size_t)(npg * sizeof(struct kmemusage)));
484 kmem_map = kmem_suballoc(kernel_map, (vm_offset_t *)&kmembase,
485 (vm_offset_t *)&kmemlimit, (vm_size_t)(npg * NBPG), FALSE);
486 #ifdef KMEMSTATS
487 for (indx = 0; indx < MINBUCKET + 16; indx++) {
488 if (1 << indx >= CLBYTES)
489 bucket[indx].kb_elmpercl = 1;
490 else
491 bucket[indx].kb_elmpercl = CLBYTES / (1 << indx);
492 bucket[indx].kb_highwat = 5 * bucket[indx].kb_elmpercl;
493 }
494 for (indx = 0; indx < M_LAST; indx++)
495 kmemstats[indx].ks_limit = npg * NBPG * 6 / 10;
496 #endif
497 }
498