xref: /netbsd-src/lib/libc/stdlib/malloc.c (revision dc306354b0b29af51801a7632f1e95265a68cd81)
1 /*	$NetBSD: malloc.c,v 1.15 1998/11/15 17:13:51 christos 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.15 1998/11/15 17:13:51 christos 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	long 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 *)(void *)sbrk(0);
162   		n = n - sizeof (*op) - ((long)op & (n - 1));
163 		if (n < 0)
164 			n += pagesz;
165   		if (n) {
166   			if (sbrk((int)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 = (unsigned)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 *)(void *)(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   	long 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 *)(void *)sbrk((int)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 =
270 		    (union overhead *)(void *)((caddr_t)(void *)op+(size_t)sz);
271 		op = op->ov_next;
272   	}
273 }
274 
275 void
276 free(cp)
277 	void *cp;
278 {
279   	long size;
280 	union overhead *op;
281 
282   	if (cp == NULL)
283   		return;
284 	op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
285 #ifdef DEBUG
286   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
287 #else
288 	if (op->ov_magic != MAGIC)
289 		return;				/* sanity */
290 #endif
291 #ifdef RCHECK
292   	ASSERT(op->ov_rmagic == RMAGIC);
293 	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
294 #endif
295   	size = op->ov_index;
296   	ASSERT(size < NBUCKETS);
297 	op->ov_next = nextf[(size_t)size];	/* also clobbers ov_magic */
298   	nextf[(size_t)size] = op;
299 #ifdef MSTATS
300   	nmalloc[(size_t)size]--;
301 #endif
302 }
303 
304 /*
305  * When a program attempts "storage compaction" as mentioned in the
306  * old malloc man page, it realloc's an already freed block.  Usually
307  * this is the last block it freed; occasionally it might be farther
308  * back.  We have to search all the free lists for the block in order
309  * to determine its bucket: 1st we make one pass thru the lists
310  * checking only the first block in each; if that fails we search
311  * ``__realloc_srchlen'' blocks in each list for a match (the variable
312  * is extern so the caller can modify it).  If that fails we just copy
313  * however many bytes was given to realloc() and hope it's not huge.
314  */
315 int __realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
316 
317 void *
318 realloc(cp, nbytes)
319 	void *cp;
320 	size_t nbytes;
321 {
322   	u_long onb;
323 	long i;
324 	union overhead *op;
325   	char *res;
326 	int was_alloced = 0;
327 
328   	if (cp == NULL)
329   		return (malloc(nbytes));
330 	if (nbytes == 0) {
331 		free (cp);
332 		return NULL;
333 	}
334 	op = (union overhead *)(void *)((caddr_t)cp - sizeof (union overhead));
335 	if (op->ov_magic == MAGIC) {
336 		was_alloced++;
337 		i = op->ov_index;
338 	} else {
339 		/*
340 		 * Already free, doing "compaction".
341 		 *
342 		 * Search for the old block of memory on the
343 		 * free list.  First, check the most common
344 		 * case (last element free'd), then (this failing)
345 		 * the last ``__realloc_srchlen'' items free'd.
346 		 * If all lookups fail, then assume the size of
347 		 * the memory block being realloc'd is the
348 		 * largest possible (so that all "nbytes" of new
349 		 * memory are copied into).  Note that this could cause
350 		 * a memory fault if the old area was tiny, and the moon
351 		 * is gibbous.  However, that is very unlikely.
352 		 */
353 		if ((i = findbucket(op, 1)) < 0 &&
354 		    (i = findbucket(op, __realloc_srchlen)) < 0)
355 			i = NBUCKETS;
356 	}
357 	onb = (u_long)1 << (u_long)(i + 3);
358 	if (onb < pagesz)
359 		onb -= sizeof (*op) + RSLOP;
360 	else
361 		onb += pagesz - sizeof (*op) - RSLOP;
362 	/* avoid the copy if same size block */
363 	if (was_alloced) {
364 		if (i) {
365 			i = (long)1 << (long)(i + 2);
366 			if (i < pagesz)
367 				i -= sizeof (*op) + RSLOP;
368 			else
369 				i += pagesz - sizeof (*op) - RSLOP;
370 		}
371 		if (nbytes <= onb && nbytes > i) {
372 #ifdef RCHECK
373 			op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
374 			*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
375 #endif
376 			return(cp);
377 		} else
378 			free(cp);
379 	}
380   	if ((res = malloc(nbytes)) == NULL)
381   		return (NULL);
382   	if (cp != res)		/* common optimization if "compacting" */
383 		memmove(res, cp, (size_t)((nbytes < onb) ? nbytes : onb));
384   	return (res);
385 }
386 
387 /*
388  * Search ``srchlen'' elements of each free list for a block whose
389  * header starts at ``freep''.  If srchlen is -1 search the whole list.
390  * Return bucket number, or -1 if not found.
391  */
392 static int
393 findbucket(freep, srchlen)
394 	union overhead *freep;
395 	int srchlen;
396 {
397 	union overhead *p;
398 	int i, j;
399 
400 	for (i = 0; i < NBUCKETS; i++) {
401 		j = 0;
402 		for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
403 			if (p == freep)
404 				return (i);
405 			j++;
406 		}
407 	}
408 	return (-1);
409 }
410 
411 #ifdef MSTATS
412 /*
413  * mstats - print out statistics about malloc
414  *
415  * Prints two lines of numbers, one showing the length of the free list
416  * for each size category, the second showing the number of mallocs -
417  * frees for each size category.
418  */
419 void
420 mstats(s)
421 	char *s;
422 {
423   	int i, j;
424   	union overhead *p;
425   	int totfree = 0,
426   	totused = 0;
427 
428   	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
429   	for (i = 0; i < NBUCKETS; i++) {
430   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
431   			;
432   		fprintf(stderr, " %d", j);
433   		totfree += j * (1 << (i + 3));
434   	}
435   	fprintf(stderr, "\nused:\t");
436   	for (i = 0; i < NBUCKETS; i++) {
437   		fprintf(stderr, " %d", nmalloc[i]);
438   		totused += nmalloc[i] * (1 << (i + 3));
439   	}
440   	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
441 	    totused, totfree);
442 }
443 #endif
444