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