No empty .Rs/.Re
[netbsd-mini2440.git] / libexec / ld.aout_so / malloc.c
blobd5004b1b1b33257c6fa7b4e45051965151240cf7
1 /* $NetBSD: malloc.c,v 1.7 2000/11/28 06:01:34 mycroft Exp $ */
3 /*
4 * Copyright (c) 1983 Regents of the University of California.
5 * All rights reserved.
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. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
32 #include <sys/cdefs.h>
33 #if defined(LIBC_SCCS) && !defined(lint)
34 #if 0
35 static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";
36 #else
37 __RCSID("$NetBSD: malloc.c,v 1.7 2000/11/28 06:01:34 mycroft Exp $");
38 #endif
39 #endif /* LIBC_SCCS and not lint */
42 * malloc.c (Caltech) 2/21/82
43 * Chris Kingsley, kingsley@cit-20.
45 * This is a very fast storage allocator. It allocates blocks of a small
46 * number of different sizes, and keeps free lists of each size. Blocks that
47 * don't exactly fit are passed up to the next larger size. In this
48 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
49 * This is designed for use in a virtual memory environment.
52 #include <sys/types.h>
53 #include <err.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <sys/param.h>
58 #include <sys/mman.h>
59 #ifndef BSD
60 #define MAP_FILE 0
61 #define MAP_ANON 0
62 #endif
64 #ifndef BSD /* Need do better than this */
65 #define NEED_DEV_ZERO 1
66 #endif
68 #define NULL 0
71 * The overhead on a block is at least 4 bytes. When free, this space
72 * contains a pointer to the next free block, and the bottom two bits must
73 * be zero. When in use, the first byte is set to MAGIC, and the second
74 * byte is the size index. The remaining bytes are for alignment.
75 * If range checking is enabled then a second word holds the size of the
76 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
77 * The order of elements is critical: ov_magic must overlay the low order
78 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
80 union overhead {
81 union overhead *ov_next; /* when free */
82 struct {
83 u_char ovu_magic; /* magic number */
84 u_char ovu_index; /* bucket # */
85 #ifdef RCHECK
86 u_short ovu_rmagic; /* range magic number */
87 u_int ovu_size; /* actual block size */
88 #endif
89 } ovu;
90 #define ov_magic ovu.ovu_magic
91 #define ov_index ovu.ovu_index
92 #define ov_rmagic ovu.ovu_rmagic
93 #define ov_size ovu.ovu_size
96 #define MAGIC 0xef /* magic # on accounting info */
97 #define RMAGIC 0x5555 /* magic # on range info */
99 #ifdef RCHECK
100 #define RSLOP sizeof (u_short)
101 #else
102 #define RSLOP 0
103 #endif
106 * Pre-allocate mmap'ed pages
108 #define NPOOLPAGES (32*1024/pagesz)
109 static caddr_t pagepool_start, pagepool_end;
110 static int morepages __P((int));
111 static void morecore __P((int));
112 static int findbucket __P((union overhead *, int));
115 * nextf[i] is the pointer to the next free block of size 2^(i+3). The
116 * smallest allocatable block is 8 bytes. The overhead information
117 * precedes the data area returned to the user.
119 #define NBUCKETS 30
120 static union overhead *nextf[NBUCKETS];
122 static int pagesz; /* page size */
123 static int pagebucket; /* page size bucket */
125 #ifdef MSTATS
127 * nmalloc[i] is the difference between the number of mallocs and frees
128 * for a given block size.
130 static u_int nmalloc[NBUCKETS];
131 #include <stdio.h>
132 #endif
134 #if defined(DEBUG) || defined(RCHECK)
135 #define ASSERT(p) if (!(p)) botch("p")
136 #include <stdio.h>
137 static void botch __P((char *));
138 static void
139 botch(s)
140 char *s;
142 fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
143 (void) fflush(stderr); /* just in case user buffered it */
144 abort();
146 #else
147 #define ASSERT(p)
148 #endif
150 void *
151 malloc(nbytes)
152 size_t nbytes;
154 register union overhead *op;
155 register int bucket, n;
156 register unsigned amt;
159 * First time malloc is called, setup page size and
160 * align break pointer so all data will be page aligned.
162 if (pagesz == 0) {
163 pagesz = n = getpagesize();
164 if (morepages(NPOOLPAGES) == 0)
165 return NULL;
166 op = (union overhead *)(pagepool_start);
167 n = n - sizeof (*op) - ((int)op & (n - 1));
168 if (n < 0)
169 n += pagesz;
170 if (n) {
171 pagepool_start += n;
173 bucket = 0;
174 amt = 8;
175 while (pagesz > amt) {
176 amt <<= 1;
177 bucket++;
179 pagebucket = bucket;
182 * Convert amount of memory requested into closest block size
183 * stored in hash buckets which satisfies request.
184 * Account for space used per block for accounting.
186 if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
187 #ifndef RCHECK
188 amt = 8; /* size of first bucket */
189 bucket = 0;
190 #else
191 amt = 16; /* size of first bucket */
192 bucket = 1;
193 #endif
194 n = -(sizeof (*op) + RSLOP);
195 } else {
196 amt = pagesz;
197 bucket = pagebucket;
199 while (nbytes > amt + n) {
200 amt <<= 1;
201 if (amt == 0)
202 return (NULL);
203 bucket++;
206 * If nothing in hash bucket right now,
207 * request more memory from the system.
209 if ((op = nextf[bucket]) == NULL) {
210 morecore(bucket);
211 if ((op = nextf[bucket]) == NULL)
212 return (NULL);
214 /* remove from linked list */
215 nextf[bucket] = op->ov_next;
216 op->ov_magic = MAGIC;
217 op->ov_index = bucket;
218 #ifdef MSTATS
219 nmalloc[bucket]++;
220 #endif
221 #ifdef RCHECK
223 * Record allocated size of block and
224 * bound space with magic numbers.
226 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
227 op->ov_rmagic = RMAGIC;
228 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
229 #endif
230 return ((char *)(op + 1));
234 * Allocate more memory to the indicated bucket.
236 static void
237 morecore(bucket)
238 int bucket;
240 register union overhead *op;
241 register int sz; /* size of desired block */
242 int amt; /* amount to allocate */
243 int nblks; /* how many blocks we get */
245 /* Map bucket number to size */
246 sz = 1 << (bucket + 3);
247 #ifdef DEBUG
248 ASSERT(sz > 0);
249 #else
250 if (sz <= 0)
251 return;
252 #endif
253 if (sz < pagesz) {
254 amt = pagesz;
255 nblks = amt / sz;
256 } else {
257 amt = sz + pagesz;
258 nblks = 1;
260 if (amt > pagepool_end - pagepool_start)
261 if (morepages(amt/pagesz + NPOOLPAGES) == 0)
262 return;
263 op = (union overhead *)pagepool_start;
264 pagepool_start += amt;
267 * Add new memory allocated to that on
268 * free list for this hash bucket.
270 nextf[bucket] = op;
271 while (--nblks > 0) {
272 op->ov_next = (union overhead *)((caddr_t)op + sz);
273 op = (union overhead *)((caddr_t)op + sz);
277 void
278 free(cp)
279 void *cp;
281 register int size;
282 register union overhead *op;
284 if (cp == NULL)
285 return;
286 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
287 #ifdef DEBUG
288 ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */
289 #else
290 if (op->ov_magic != MAGIC)
291 return; /* sanity */
292 #endif
293 #ifdef RCHECK
294 ASSERT(op->ov_rmagic == RMAGIC);
295 ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
296 #endif
297 size = op->ov_index;
298 ASSERT(size < NBUCKETS);
299 op->ov_next = nextf[size]; /* also clobbers ov_magic */
300 nextf[size] = op;
301 #ifdef MSTATS
302 nmalloc[size]--;
303 #endif
307 * When a program attempts "storage compaction" as mentioned in the
308 * old malloc man page, it realloc's an already freed block. Usually
309 * this is the last block it freed; occasionally it might be farther
310 * back. We have to search all the free lists for the block in order
311 * to determine its bucket: 1st we make one pass thru the lists
312 * checking only the first block in each; if that fails we search
313 * ``realloc_srchlen'' blocks in each list for a match (the variable
314 * is extern so the caller can modify it). If that fails we just copy
315 * however many bytes was given to realloc() and hope it's not huge.
317 int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */
319 void *
320 realloc(cp, nbytes)
321 void *cp;
322 size_t nbytes;
324 register u_int onb;
325 register int i;
326 union overhead *op;
327 char *res;
328 int was_alloced = 0;
330 if (cp == NULL)
331 return (malloc(nbytes));
332 op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
333 if (op->ov_magic == MAGIC) {
334 was_alloced++;
335 i = op->ov_index;
336 } else {
338 * Already free, doing "compaction".
340 * Search for the old block of memory on the
341 * free list. First, check the most common
342 * case (last element free'd), then (this failing)
343 * the last ``realloc_srchlen'' items free'd.
344 * If all lookups fail, then assume the size of
345 * the memory block being realloc'd is the
346 * largest possible (so that all "nbytes" of new
347 * memory are copied into). Note that this could cause
348 * a memory fault if the old area was tiny, and the moon
349 * is gibbous. However, that is very unlikely.
351 if ((i = findbucket(op, 1)) < 0 &&
352 (i = findbucket(op, realloc_srchlen)) < 0)
353 i = NBUCKETS;
355 onb = 1 << (i + 3);
356 if (onb < pagesz)
357 onb -= sizeof (*op) + RSLOP;
358 else
359 onb += pagesz - sizeof (*op) - RSLOP;
360 /* avoid the copy if same size block */
361 if (was_alloced) {
362 if (i) {
363 i = 1 << (i + 2);
364 if (i < pagesz)
365 i -= sizeof (*op) + RSLOP;
366 else
367 i += pagesz - sizeof (*op) - RSLOP;
369 if (nbytes <= onb && nbytes > i) {
370 #ifdef RCHECK
371 op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
372 *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
373 #endif
374 return(cp);
375 } else
376 free(cp);
378 if ((res = malloc(nbytes)) == NULL)
379 return (NULL);
380 if (cp != res) /* common optimization if "compacting" */
381 bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
382 return (res);
386 * Search ``srchlen'' elements of each free list for a block whose
387 * header starts at ``freep''. If srchlen is -1 search the whole list.
388 * Return bucket number, or -1 if not found.
390 static int
391 findbucket(freep, srchlen)
392 union overhead *freep;
393 int srchlen;
395 register union overhead *p;
396 register int i, j;
398 for (i = 0; i < NBUCKETS; i++) {
399 j = 0;
400 for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
401 if (p == freep)
402 return (i);
403 j++;
406 return (-1);
409 #ifdef MSTATS
411 * mstats - print out statistics about malloc
413 * Prints two lines of numbers, one showing the length of the free list
414 * for each size category, the second showing the number of mallocs -
415 * frees for each size category.
417 mstats(s)
418 char *s;
420 register int i, j;
421 register union overhead *p;
422 int totfree = 0,
423 totused = 0;
425 fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
426 for (i = 0; i < NBUCKETS; i++) {
427 for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
429 fprintf(stderr, " %d", j);
430 totfree += j * (1 << (i + 3));
432 fprintf(stderr, "\nused:\t");
433 for (i = 0; i < NBUCKETS; i++) {
434 fprintf(stderr, " %d", nmalloc[i]);
435 totused += nmalloc[i] * (1 << (i + 3));
437 fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
438 totused, totfree);
440 #endif
443 static int
444 morepages(n)
445 int n;
447 int fd = -1;
448 int offset;
450 #ifdef NEED_DEV_ZERO
451 fd = open("/dev/zero", O_RDWR, 0);
452 if (fd == -1)
453 perror("/dev/zero");
454 #endif
456 if (pagepool_end - pagepool_start > pagesz) {
457 caddr_t addr = (caddr_t)
458 (((int)pagepool_start + pagesz - 1) & ~(pagesz - 1));
459 if (munmap(addr, pagepool_end - addr) != 0)
460 warn("morepages: munmap %p", addr);
463 offset = (int)pagepool_start - ((int)pagepool_start & ~(pagesz - 1));
465 if ((pagepool_start = mmap(0, n * pagesz,
466 PROT_READ|PROT_WRITE,
467 MAP_ANON|MAP_PRIVATE, fd, 0)) == (caddr_t)-1) {
468 char *str = "ld.so: malloc: cannot map pages\n";
469 (void)write(2, str, strlen(str));
470 return 0;
472 pagepool_end = pagepool_start + n * pagesz;
473 pagepool_start += offset;
475 #ifdef NEED_DEV_ZERO
476 close(fd);
477 #endif
478 return n;