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