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