xref: /netbsd-src/lib/libc/stdlib/malloc.c (revision 1394f01b4a9e99092957ca5d824d67219565d9b5)
1 /*	$NetBSD: malloc.c,v 1.9 1997/07/13 20:16:47 christos 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 #include <sys/cdefs.h>
37 #if defined(LIBC_SCCS) && !defined(lint)
38 #if 0
39 static char *sccsid = "from: @(#)malloc.c	5.11 (Berkeley) 2/23/91";
40 #else
41 __RCSID("$NetBSD: malloc.c,v 1.9 1997/07/13 20:16:47 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 #if defined(DEBUG) || defined(RCHECK) || defined(MSTATS)
57 #include <stdio.h>
58 #endif
59 #include <sys/types.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #define	NULL 0
65 
66 
67 /*
68  * The overhead on a block is at least 4 bytes.  When free, this space
69  * contains a pointer to the next free block, and the bottom two bits must
70  * be zero.  When in use, the first byte is set to MAGIC, and the second
71  * byte is the size index.  The remaining bytes are for alignment.
72  * If range checking is enabled then a second word holds the size of the
73  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
74  * The order of elements is critical: ov_magic must overlay the low order
75  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
76  */
77 union	overhead {
78 	union	overhead *ov_next;	/* when free */
79 	struct {
80 		u_char	ovu_magic;	/* magic number */
81 		u_char	ovu_index;	/* bucket # */
82 #ifdef RCHECK
83 		u_short	ovu_rmagic;	/* range magic number */
84 		u_long	ovu_size;	/* actual block size */
85 #endif
86 	} ovu;
87 #define	ov_magic	ovu.ovu_magic
88 #define	ov_index	ovu.ovu_index
89 #define	ov_rmagic	ovu.ovu_rmagic
90 #define	ov_size		ovu.ovu_size
91 };
92 
93 #define	MAGIC		0xef		/* magic # on accounting info */
94 #define RMAGIC		0x5555		/* magic # on range info */
95 
96 #ifdef RCHECK
97 #define	RSLOP		sizeof (u_short)
98 #else
99 #define	RSLOP		0
100 #endif
101 
102 /*
103  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
104  * smallest allocatable block is 8 bytes.  The overhead information
105  * precedes the data area returned to the user.
106  */
107 #define	NBUCKETS 30
108 static	union overhead *nextf[NBUCKETS];
109 
110 static	int pagesz;			/* page size */
111 static	int pagebucket;			/* page size bucket */
112 
113 #ifdef MSTATS
114 /*
115  * nmalloc[i] is the difference between the number of mallocs and frees
116  * for a given block size.
117  */
118 static	u_int nmalloc[NBUCKETS];
119 #include <stdio.h>
120 #endif
121 
122 static void morecore __P((int));
123 static int findbucket __P((union overhead *, int));
124 #ifdef MSTATS
125 void mstats __P((char *));
126 #endif
127 
128 #if defined(DEBUG) || defined(RCHECK)
129 #define	ASSERT(p)   if (!(p)) botch(__STRING(p))
130 
131 static botch __P((char *));
132 
133 static
134 botch(s)
135 	char *s;
136 {
137 	fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
138  	(void) fflush(stderr);		/* just in case user buffered it */
139 	abort();
140 }
141 #else
142 #define	ASSERT(p)
143 #endif
144 
145 void *
146 malloc(nbytes)
147 	size_t nbytes;
148 {
149   	register union overhead *op;
150 	register int bucket;
151   	register long n;
152 	register unsigned amt;
153 
154 	/*
155 	 * First time malloc is called, setup page size and
156 	 * align break pointer so all data will be page aligned.
157 	 */
158 	if (pagesz == 0) {
159 		pagesz = n = getpagesize();
160 		op = (union overhead *)sbrk(0);
161   		n = n - sizeof (*op) - ((long)op & (n - 1));
162 		if (n < 0)
163 			n += pagesz;
164   		if (n) {
165   			if (sbrk(n) == (char *)-1)
166 				return (NULL);
167 		}
168 		bucket = 0;
169 		amt = 8;
170 		while (pagesz > amt) {
171 			amt <<= 1;
172 			bucket++;
173 		}
174 		pagebucket = bucket;
175 	}
176 	/*
177 	 * Convert amount of memory requested into closest block size
178 	 * stored in hash buckets which satisfies request.
179 	 * Account for space used per block for accounting.
180 	 */
181 	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
182 #ifndef RCHECK
183 		amt = 8;	/* size of first bucket */
184 		bucket = 0;
185 #else
186 		amt = 16;	/* size of first bucket */
187 		bucket = 1;
188 #endif
189 		n = -((long)sizeof (*op) + RSLOP);
190 	} else {
191 		amt = pagesz;
192 		bucket = pagebucket;
193 	}
194 	while (nbytes > amt + n) {
195 		amt <<= 1;
196 		if (amt == 0)
197 			return (NULL);
198 		bucket++;
199 	}
200 	/*
201 	 * If nothing in hash bucket right now,
202 	 * request more memory from the system.
203 	 */
204   	if ((op = nextf[bucket]) == NULL) {
205   		morecore(bucket);
206   		if ((op = nextf[bucket]) == NULL)
207   			return (NULL);
208 	}
209 	/* remove from linked list */
210   	nextf[bucket] = op->ov_next;
211 	op->ov_magic = MAGIC;
212 	op->ov_index = bucket;
213 #ifdef MSTATS
214   	nmalloc[bucket]++;
215 #endif
216 #ifdef RCHECK
217 	/*
218 	 * Record allocated size of block and
219 	 * bound space with magic numbers.
220 	 */
221 	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
222 	op->ov_rmagic = RMAGIC;
223   	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
224 #endif
225   	return ((char *)(op + 1));
226 }
227 
228 /*
229  * Allocate more memory to the indicated bucket.
230  */
231 static void
232 morecore(bucket)
233 	int bucket;
234 {
235   	register union overhead *op;
236 	register long sz;		/* size of desired block */
237   	long amt;			/* amount to allocate */
238   	int nblks;			/* how many blocks we get */
239 
240 	/*
241 	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
242 	 * 2^30 bytes on a VAX, I think) or for a negative arg.
243 	 */
244 	sz = 1 << (bucket + 3);
245 #ifdef DEBUG
246 	ASSERT(sz > 0);
247 #else
248 	if (sz <= 0)
249 		return;
250 #endif
251 	if (sz < pagesz) {
252 		amt = pagesz;
253   		nblks = amt / sz;
254 	} else {
255 		amt = sz + pagesz;
256 		nblks = 1;
257 	}
258 	op = (union overhead *)sbrk(amt);
259 	/* no more room! */
260   	if ((long)op == -1)
261   		return;
262 	/*
263 	 * Add new memory allocated to that on
264 	 * free list for this hash bucket.
265 	 */
266   	nextf[bucket] = op;
267   	while (--nblks > 0) {
268 		op->ov_next = (union overhead *)((caddr_t)op + sz);
269 		op = (union overhead *)((caddr_t)op + sz);
270   	}
271 }
272 
273 void
274 free(cp)
275 	void *cp;
276 {
277   	register long size;
278 	register union overhead *op;
279 
280   	if (cp == NULL)
281   		return;
282 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
283 #ifdef DEBUG
284   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
285 #else
286 	if (op->ov_magic != MAGIC)
287 		return;				/* sanity */
288 #endif
289 #ifdef RCHECK
290   	ASSERT(op->ov_rmagic == RMAGIC);
291 	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
292 #endif
293   	size = op->ov_index;
294   	ASSERT(size < NBUCKETS);
295 	op->ov_next = nextf[size];	/* also clobbers ov_magic */
296   	nextf[size] = op;
297 #ifdef MSTATS
298   	nmalloc[size]--;
299 #endif
300 }
301 
302 /*
303  * When a program attempts "storage compaction" as mentioned in the
304  * old malloc man page, it realloc's an already freed block.  Usually
305  * this is the last block it freed; occasionally it might be farther
306  * back.  We have to search all the free lists for the block in order
307  * to determine its bucket: 1st we make one pass thru the lists
308  * checking only the first block in each; if that fails we search
309  * ``realloc_srchlen'' blocks in each list for a match (the variable
310  * is extern so the caller can modify it).  If that fails we just copy
311  * however many bytes was given to realloc() and hope it's not huge.
312  */
313 int realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
314 
315 void *
316 realloc(cp, nbytes)
317 	void *cp;
318 	size_t nbytes;
319 {
320   	register u_long onb;
321 	register long i;
322 	union overhead *op;
323   	char *res;
324 	int was_alloced = 0;
325 
326   	if (cp == NULL)
327   		return (malloc(nbytes));
328 	if (nbytes == 0) {
329 		free (cp);
330 		return NULL;
331 	}
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 {
337 		/*
338 		 * Already free, doing "compaction".
339 		 *
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.
350 		 */
351 		if ((i = findbucket(op, 1)) < 0 &&
352 		    (i = findbucket(op, realloc_srchlen)) < 0)
353 			i = NBUCKETS;
354 	}
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;
368 		}
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);
377 	}
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);
383 }
384 
385 /*
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.
389  */
390 static int
391 findbucket(freep, srchlen)
392 	union overhead *freep;
393 	int srchlen;
394 {
395 	register union overhead *p;
396 	register int i, j;
397 
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++;
404 		}
405 	}
406 	return (-1);
407 }
408 
409 #ifdef MSTATS
410 /*
411  * mstats - print out statistics about malloc
412  *
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.
416  */
417 void
418 mstats(s)
419 	char *s;
420 {
421   	register int i, j;
422   	register union overhead *p;
423   	int totfree = 0,
424   	totused = 0;
425 
426   	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
427   	for (i = 0; i < NBUCKETS; i++) {
428   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
429   			;
430   		fprintf(stderr, " %d", j);
431   		totfree += j * (1 << (i + 3));
432   	}
433   	fprintf(stderr, "\nused:\t");
434   	for (i = 0; i < NBUCKETS; i++) {
435   		fprintf(stderr, " %d", nmalloc[i]);
436   		totused += nmalloc[i] * (1 << (i + 3));
437   	}
438   	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
439 	    totused, totfree);
440 }
441 #endif
442