malloc.c revision 1.13 1 /* $NetBSD: malloc.c,v 1.13 1998/08/10 02:43:10 perry Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #if defined(LIBC_SCCS) && !defined(lint)
38 #if 0
39 static char sccsid[] = "@(#)malloc.c 8.1 (Berkeley) 6/4/93";
40 #else
41 __RCSID("$NetBSD: malloc.c,v 1.13 1998/08/10 02:43:10 perry Exp $");
42 #endif
43 #endif /* LIBC_SCCS and not lint */
44
45 /*
46 * malloc.c (Caltech) 2/21/82
47 * Chris Kingsley, kingsley@cit-20.
48 *
49 * This is a very fast storage allocator. It allocates blocks of a small
50 * number of different sizes, and keeps free lists of each size. Blocks that
51 * don't exactly fit are passed up to the next larger size. In this
52 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
53 * This is designed for use in a virtual memory environment.
54 */
55
56 #include "namespace.h"
57 #if defined(DEBUG) || defined(RCHECK) || defined(MSTATS)
58 #include <stdio.h>
59 #endif
60 #include <sys/types.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64
65 #define NULL 0
66
67
68 /*
69 * The overhead on a block is at least 4 bytes. When free, this space
70 * contains a pointer to the next free block, and the bottom two bits must
71 * be zero. When in use, the first byte is set to MAGIC, and the second
72 * byte is the size index. The remaining bytes are for alignment.
73 * If range checking is enabled then a second word holds the size of the
74 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
75 * The order of elements is critical: ov_magic must overlay the low order
76 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
77 */
78 union overhead {
79 union overhead *ov_next; /* when free */
80 struct {
81 u_char ovu_magic; /* magic number */
82 u_char ovu_index; /* bucket # */
83 #ifdef RCHECK
84 u_short ovu_rmagic; /* range magic number */
85 u_long ovu_size; /* actual block size */
86 #endif
87 } ovu;
88 #define ov_magic ovu.ovu_magic
89 #define ov_index ovu.ovu_index
90 #define ov_rmagic ovu.ovu_rmagic
91 #define ov_size ovu.ovu_size
92 };
93
94 #define MAGIC 0xef /* magic # on accounting info */
95 #define RMAGIC 0x5555 /* magic # on range info */
96
97 #ifdef RCHECK
98 #define RSLOP sizeof (u_short)
99 #else
100 #define RSLOP 0
101 #endif
102
103 /*
104 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
105 * smallest allocatable block is 8 bytes. The overhead information
106 * precedes the data area returned to the user.
107 */
108 #define NBUCKETS 30
109 static union overhead *nextf[NBUCKETS];
110
111 static int pagesz; /* page size */
112 static int pagebucket; /* page size bucket */
113
114 #ifdef MSTATS
115 /*
116 * nmalloc[i] is the difference between the number of mallocs and frees
117 * for a given block size.
118 */
119 static u_int nmalloc[NBUCKETS];
120 #include <stdio.h>
121 #endif
122
123 static void morecore __P((int));
124 static int findbucket __P((union overhead *, int));
125 #ifdef MSTATS
126 void mstats __P((char *));
127 #endif
128
129 #if defined(DEBUG) || defined(RCHECK)
130 #define ASSERT(p) if (!(p)) botch(__STRING(p))
131
132 static botch __P((char *));
133
134 static
135 botch(s)
136 char *s;
137 {
138 fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
139 (void) fflush(stderr); /* just in case user buffered it */
140 abort();
141 }
142 #else
143 #define ASSERT(p)
144 #endif
145
146 void *
147 malloc(nbytes)
148 size_t nbytes;
149 {
150 union overhead *op;
151 int bucket;
152 long n;
153 unsigned amt;
154
155 /*
156 * First time malloc is called, setup page size and
157 * align break pointer so all data will be page aligned.
158 */
159 if (pagesz == 0) {
160 pagesz = n = getpagesize();
161 op = (union overhead *)sbrk(0);
162 n = n - sizeof (*op) - ((long)op & (n - 1));
163 if (n < 0)
164 n += pagesz;
165 if (n) {
166 if (sbrk(n) == (char *)-1)
167 return (NULL);
168 }
169 bucket = 0;
170 amt = 8;
171 while (pagesz > amt) {
172 amt <<= 1;
173 bucket++;
174 }
175 pagebucket = bucket;
176 }
177 /*
178 * Convert amount of memory requested into closest block size
179 * stored in hash buckets which satisfies request.
180 * Account for space used per block for accounting.
181 */
182 if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
183 #ifndef RCHECK
184 amt = 8; /* size of first bucket */
185 bucket = 0;
186 #else
187 amt = 16; /* size of first bucket */
188 bucket = 1;
189 #endif
190 n = -((long)sizeof (*op) + RSLOP);
191 } else {
192 amt = pagesz;
193 bucket = pagebucket;
194 }
195 while (nbytes > amt + n) {
196 amt <<= 1;
197 if (amt == 0)
198 return (NULL);
199 bucket++;
200 }
201 /*
202 * If nothing in hash bucket right now,
203 * request more memory from the system.
204 */
205 if ((op = nextf[bucket]) == NULL) {
206 morecore(bucket);
207 if ((op = nextf[bucket]) == NULL)
208 return (NULL);
209 }
210 /* remove from linked list */
211 nextf[bucket] = op->ov_next;
212 op->ov_magic = MAGIC;
213 op->ov_index = bucket;
214 #ifdef MSTATS
215 nmalloc[bucket]++;
216 #endif
217 #ifdef RCHECK
218 /*
219 * Record allocated size of block and
220 * bound space with magic numbers.
221 */
222 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
223 op->ov_rmagic = RMAGIC;
224 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
225 #endif
226 return ((char *)(op + 1));
227 }
228
229 /*
230 * Allocate more memory to the indicated bucket.
231 */
232 static void
233 morecore(bucket)
234 int bucket;
235 {
236 union overhead *op;
237 long sz; /* size of desired block */
238 long amt; /* amount to allocate */
239 int nblks; /* how many blocks we get */
240
241 /*
242 * sbrk_size <= 0 only for big, FLUFFY, requests (about
243 * 2^30 bytes on a VAX, I think) or for a negative arg.
244 */
245 sz = 1 << (bucket + 3);
246 #ifdef DEBUG
247 ASSERT(sz > 0);
248 #else
249 if (sz <= 0)
250 return;
251 #endif
252 if (sz < pagesz) {
253 amt = pagesz;
254 nblks = amt / sz;
255 } else {
256 amt = sz + pagesz;
257 nblks = 1;
258 }
259 op = (union overhead *)sbrk(amt);
260 /* no more room! */
261 if ((long)op == -1)
262 return;
263 /*
264 * Add new memory allocated to that on
265 * free list for this hash bucket.
266 */
267 nextf[bucket] = op;
268 while (--nblks > 0) {
269 op->ov_next = (union overhead *)((caddr_t)op + sz);
270 op = (union overhead *)((caddr_t)op + sz);
271 }
272 }
273
274 void
275 free(cp)
276 void *cp;
277 {
278 long size;
279 union overhead *op;
280
281 if (cp == NULL)
282 return;
283 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
284 #ifdef DEBUG
285 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
286 #else
287 if (op->ov_magic != MAGIC)
288 return; /* sanity */
289 #endif
290 #ifdef RCHECK
291 ASSERT(op->ov_rmagic == RMAGIC);
292 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
293 #endif
294 size = op->ov_index;
295 ASSERT(size < NBUCKETS);
296 op->ov_next = nextf[size]; /* also clobbers ov_magic */
297 nextf[size] = op;
298 #ifdef MSTATS
299 nmalloc[size]--;
300 #endif
301 }
302
303 /*
304 * When a program attempts "storage compaction" as mentioned in the
305 * old malloc man page, it realloc's an already freed block. Usually
306 * this is the last block it freed; occasionally it might be farther
307 * back. We have to search all the free lists for the block in order
308 * to determine its bucket: 1st we make one pass thru the lists
309 * checking only the first block in each; if that fails we search
310 * ``__realloc_srchlen'' blocks in each list for a match (the variable
311 * is extern so the caller can modify it). If that fails we just copy
312 * however many bytes was given to realloc() and hope it's not huge.
313 */
314 int __realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
315
316 void *
317 realloc(cp, nbytes)
318 void *cp;
319 size_t nbytes;
320 {
321 u_long onb;
322 long i;
323 union overhead *op;
324 char *res;
325 int was_alloced = 0;
326
327 if (cp == NULL)
328 return (malloc(nbytes));
329 if (nbytes == 0) {
330 free (cp);
331 return NULL;
332 }
333 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
334 if (op->ov_magic == MAGIC) {
335 was_alloced++;
336 i = op->ov_index;
337 } else {
338 /*
339 * Already free, doing "compaction".
340 *
341 * Search for the old block of memory on the
342 * free list. First, check the most common
343 * case (last element free'd), then (this failing)
344 * the last ``__realloc_srchlen'' items free'd.
345 * If all lookups fail, then assume the size of
346 * the memory block being realloc'd is the
347 * largest possible (so that all "nbytes" of new
348 * memory are copied into). Note that this could cause
349 * a memory fault if the old area was tiny, and the moon
350 * is gibbous. However, that is very unlikely.
351 */
352 if ((i = findbucket(op, 1)) < 0 &&
353 (i = findbucket(op, __realloc_srchlen)) < 0)
354 i = NBUCKETS;
355 }
356 onb = 1 << (i + 3);
357 if (onb < pagesz)
358 onb -= sizeof (*op) + RSLOP;
359 else
360 onb += pagesz - sizeof (*op) - RSLOP;
361 /* avoid the copy if same size block */
362 if (was_alloced) {
363 if (i) {
364 i = 1 << (i + 2);
365 if (i < pagesz)
366 i -= sizeof (*op) + RSLOP;
367 else
368 i += pagesz - sizeof (*op) - RSLOP;
369 }
370 if (nbytes <= onb && nbytes > i) {
371 #ifdef RCHECK
372 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
373 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
374 #endif
375 return(cp);
376 } else
377 free(cp);
378 }
379 if ((res = malloc(nbytes)) == NULL)
380 return (NULL);
381 if (cp != res) /* common optimization if "compacting" */
382 memcpy(res, cp, (nbytes < onb) ? nbytes : onb);
383 return (res);
384 }
385
386 /*
387 * Search ``srchlen'' elements of each free list for a block whose
388 * header starts at ``freep''. If srchlen is -1 search the whole list.
389 * Return bucket number, or -1 if not found.
390 */
391 static int
392 findbucket(freep, srchlen)
393 union overhead *freep;
394 int srchlen;
395 {
396 union overhead *p;
397 int i, j;
398
399 for (i = 0; i < NBUCKETS; i++) {
400 j = 0;
401 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
402 if (p == freep)
403 return (i);
404 j++;
405 }
406 }
407 return (-1);
408 }
409
410 #ifdef MSTATS
411 /*
412 * mstats - print out statistics about malloc
413 *
414 * Prints two lines of numbers, one showing the length of the free list
415 * for each size category, the second showing the number of mallocs -
416 * frees for each size category.
417 */
418 void
419 mstats(s)
420 char *s;
421 {
422 int i, j;
423 union overhead *p;
424 int totfree = 0,
425 totused = 0;
426
427 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
428 for (i = 0; i < NBUCKETS; i++) {
429 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
430 ;
431 fprintf(stderr, " %d", j);
432 totfree += j * (1 << (i + 3));
433 }
434 fprintf(stderr, "\nused:\t");
435 for (i = 0; i < NBUCKETS; i++) {
436 fprintf(stderr, " %d", nmalloc[i]);
437 totused += nmalloc[i] * (1 << (i + 3));
438 }
439 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
440 totused, totfree);
441 }
442 #endif
443