xref: /csrg-svn/lib/libc/stdlib/malloc.c (revision 25793)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #ifndef lint
8 static char sccsid[] = "@(#)malloc.c	5.3 (Berkeley) 01/09/86";
9 #endif not lint
10 
11 /*
12  * malloc.c (Caltech) 2/21/82
13  * Chris Kingsley, kingsley@cit-20.
14  *
15  * This is a very fast storage allocator.  It allocates blocks of a small
16  * number of different sizes, and keeps free lists of each size.  Blocks that
17  * don't exactly fit are passed up to the next larger size.  In this
18  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
19  * This is designed for use in a program that uses vast quantities of memory,
20  * but bombs when it runs out.
21  */
22 
23 #include <sys/types.h>
24 
25 #define	NULL 0
26 
27 /*
28  * The overhead on a block is at least 4 bytes.  When free, this space
29  * contains a pointer to the next free block, and the bottom two bits must
30  * be zero.  When in use, the first byte is set to MAGIC, and the second
31  * byte is the size index.  The remaining bytes are for alignment.
32  * If range checking is enabled and the size of the block fits
33  * in two bytes, then the top two bytes hold the size of the requested block
34  * plus the range checking words, and the header word MINUS ONE.
35  */
36 union	overhead {
37 	union	overhead *ov_next;	/* when free */
38 	struct {
39 #ifndef RCHECK
40 		u_char	ovu_magic;	/* magic number */
41 		u_char	ovu_index;	/* bucket # */
42 #else
43 		u_int	ovu_size;	/* actual block size */
44 		u_char	ovu_magic;	/* magic number */
45 		u_char	ovu_index;	/* bucket # */
46 		u_short	ovu_rmagic;	/* range magic number */
47 #endif
48 	} ovu;
49 #define	ov_magic	ovu.ovu_magic
50 #define	ov_index	ovu.ovu_index
51 #define	ov_rmagic	ovu.ovu_rmagic
52 #define	ov_size		ovu.ovu_size
53 };
54 
55 #define	MAGIC		0xef		/* magic # on accounting info */
56 #define RMAGIC		0x5555		/* magic # on range info */
57 
58 #ifdef RCHECK
59 #define	RSLOP		sizeof (u_short)
60 #else
61 #define	RSLOP		0
62 #endif
63 
64 /*
65  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
66  * smallest allocatable block is 8 bytes.  The overhead information
67  * precedes the data area returned to the user.
68  */
69 #define	NBUCKETS 30
70 static	union overhead *nextf[NBUCKETS];
71 extern	char *sbrk();
72 
73 static	int pagesz;			/* page size */
74 static	int pagebucket;			/* page size bucket */
75 
76 #ifdef MSTATS
77 /*
78  * nmalloc[i] is the difference between the number of mallocs and frees
79  * for a given block size.
80  */
81 static	u_int nmalloc[NBUCKETS];
82 #include <stdio.h>
83 #endif
84 
85 #ifdef DEBUG
86 #define	ASSERT(p)   if (!(p)) botch("p")
87 static
88 botch(s)
89 	char *s;
90 {
91 
92 	printf("assertion botched: %s\n", s);
93 	abort();
94 }
95 #else
96 #define	ASSERT(p)
97 #endif
98 
99 char *
100 malloc(nbytes)
101 	unsigned nbytes;
102 {
103   	register union overhead *op;
104   	register int bucket;
105 	register unsigned amt, n;
106 
107 	/*
108 	 * First time malloc is called, setup page size and
109 	 * align break pointer so all data will be page aligned.
110 	 */
111 	if (pagesz == 0) {
112 		pagesz = n = getpagesize();
113 		op = (union overhead *)sbrk(0);
114   		n = n - sizeof (*op) - ((int)op & (n - 1));
115 		if (n < 0)
116 			n += pagesz;
117   		if (n) {
118   			if (sbrk(n) == (char *)-1)
119 				return (NULL);
120 		}
121 		bucket = 0;
122 		amt = 8;
123 		while (pagesz > amt) {
124 			amt <<= 1;
125 			bucket++;
126 		}
127 		pagebucket = bucket;
128 	}
129 	/*
130 	 * Convert amount of memory requested into closest block size
131 	 * stored in hash buckets which satisfies request.
132 	 * Account for space used per block for accounting.
133 	 */
134 	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
135 #ifndef RCHECK
136 		amt = 8;	/* size of first bucket */
137 		bucket = 0;
138 #else
139 		amt = 16;	/* size of first bucket */
140 		bucket = 1;
141 #endif
142 		n = -(sizeof (*op) + RSLOP);
143 	} else {
144 		amt = pagesz;
145 		bucket = pagebucket;
146 	}
147 	while (nbytes > amt + n) {
148 		amt <<= 1;
149 		if (amt == 0)
150 			return (NULL);
151 		bucket++;
152 	}
153 	/*
154 	 * If nothing in hash bucket right now,
155 	 * request more memory from the system.
156 	 */
157   	if ((op = nextf[bucket]) == NULL) {
158   		morecore(bucket);
159   		if ((op = nextf[bucket]) == NULL)
160   			return (NULL);
161 	}
162 	/* remove from linked list */
163   	nextf[bucket] = op->ov_next;
164 	op->ov_magic = MAGIC;
165 	op->ov_index = bucket;
166 #ifdef MSTATS
167   	nmalloc[bucket]++;
168 #endif
169 #ifdef RCHECK
170 	/*
171 	 * Record allocated size of block and
172 	 * bound space with magic numbers.
173 	 */
174 	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
175 	op->ov_rmagic = RMAGIC;
176   	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
177 #endif
178   	return ((char *)(op + 1));
179 }
180 
181 /*
182  * Allocate more memory to the indicated bucket.
183  */
184 morecore(bucket)
185 	int bucket;
186 {
187   	register union overhead *op;
188 	register int sz;		/* size of desired block */
189   	int amt;			/* amount to allocate */
190   	int nblks;			/* how many blocks we get */
191 
192 	/*
193 	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
194 	 * 2^30 bytes on a VAX, I think) or for a negative arg.
195 	 */
196 	sz = 1 << (bucket + 3);
197 	if (sz <= 0)
198 		return;
199 	if (sz < pagesz) {
200 		amt = pagesz;
201   		nblks = amt / sz;
202 	} else {
203 		amt = sz + pagesz;
204 		nblks = 1;
205 	}
206 	op = (union overhead *)sbrk(amt);
207 	/* no more room! */
208   	if ((int)op == -1)
209   		return;
210 	/*
211 	 * Add new memory allocated to that on
212 	 * free list for this hash bucket.
213 	 */
214   	nextf[bucket] = op;
215   	while (--nblks > 0) {
216 		op->ov_next = (union overhead *)((caddr_t)op + sz);
217 		op = (union overhead *)((caddr_t)op + sz);
218   	}
219 }
220 
221 free(cp)
222 	char *cp;
223 {
224   	register int size;
225 	register union overhead *op;
226 
227   	if (cp == NULL)
228   		return;
229 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
230 #ifdef DEBUG
231   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
232 #else
233 	if (op->ov_magic != MAGIC)
234 		return;				/* sanity */
235 #endif
236 #ifdef RCHECK
237   	ASSERT(op->ov_rmagic == RMAGIC);
238 	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
239 #endif
240   	size = op->ov_index;
241   	ASSERT(size < NBUCKETS);
242 	op->ov_next = nextf[size];
243   	nextf[size] = op;
244 #ifdef MSTATS
245   	nmalloc[size]--;
246 #endif
247 }
248 
249 /*
250  * When a program attempts "storage compaction" as mentioned in the
251  * old malloc man page, it realloc's an already freed block.  Usually
252  * this is the last block it freed; occasionally it might be farther
253  * back.  We have to search all the free lists for the block in order
254  * to determine its bucket: 1st we make one pass thru the lists
255  * checking only the first block in each; if that fails we search
256  * ``realloc_srchlen'' blocks in each list for a match (the variable
257  * is extern so the caller can modify it).  If that fails we just copy
258  * however many bytes was given to realloc() and hope it's not huge.
259  */
260 int realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
261 
262 char *
263 realloc(cp, nbytes)
264 	char *cp;
265 	unsigned nbytes;
266 {
267   	register u_int onb, i;
268 	union overhead *op;
269   	char *res;
270 	int was_alloced = 0;
271 
272   	if (cp == NULL)
273   		return (malloc(nbytes));
274 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
275 	if (op->ov_magic == MAGIC) {
276 		was_alloced++;
277 		i = op->ov_index;
278 	} else {
279 		/*
280 		 * Already free, doing "compaction".
281 		 *
282 		 * Search for the old block of memory on the
283 		 * free list.  First, check the most common
284 		 * case (last element free'd), then (this failing)
285 		 * the last ``realloc_srchlen'' items free'd.
286 		 * If all lookups fail, then assume the size of
287 		 * the memory block being realloc'd is the
288 		 * smallest possible.
289 		 */
290 		if ((i = findbucket(op, 1)) < 0 &&
291 		    (i = findbucket(op, realloc_srchlen)) < 0)
292 #ifndef RCHECK
293 			i = 0;
294 #else
295 			i = 1;	/* smallest possible w/ RCHECK */
296 #endif
297 	}
298 	onb = 1 << (i + 3);
299 	if (onb < pagesz)
300 		onb -= sizeof (*op) + RSLOP;
301 	else
302 		onb += pagesz - sizeof (*op) - RSLOP;
303 	/* avoid the copy if same size block */
304 	if (was_alloced) {
305 		if (i) {
306 			i = 1 << (i + 2);
307 			if (i < pagesz)
308 				i -= sizeof (*op) + RSLOP;
309 			else
310 				i += pagesz - sizeof (*op) - RSLOP;
311 		}
312 		if (nbytes <= onb && nbytes > i) {
313 #ifdef RCHECK
314 			op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
315 			*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
316 #endif
317 			return(cp);
318 		} else
319 			free(cp);
320 	}
321   	if ((res = malloc(nbytes)) == NULL)
322   		return (NULL);
323   	if (cp != res)			/* common optimization */
324 		bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
325   	return (res);
326 }
327 
328 /*
329  * Search ``srchlen'' elements of each free list for a block whose
330  * header starts at ``freep''.  If srchlen is -1 search the whole list.
331  * Return bucket number, or -1 if not found.
332  */
333 static
334 findbucket(freep, srchlen)
335 	union overhead *freep;
336 	int srchlen;
337 {
338 	register union overhead *p;
339 	register int i, j;
340 
341 	for (i = 0; i < NBUCKETS; i++) {
342 		j = 0;
343 		for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
344 			if (p == freep)
345 				return (i);
346 			j++;
347 		}
348 	}
349 	return (-1);
350 }
351 
352 #ifdef MSTATS
353 /*
354  * mstats - print out statistics about malloc
355  *
356  * Prints two lines of numbers, one showing the length of the free list
357  * for each size category, the second showing the number of mallocs -
358  * frees for each size category.
359  */
360 mstats(s)
361 	char *s;
362 {
363   	register int i, j;
364   	register union overhead *p;
365   	int totfree = 0,
366   	totused = 0;
367 
368   	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
369   	for (i = 0; i < NBUCKETS; i++) {
370   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
371   			;
372   		fprintf(stderr, " %d", j);
373   		totfree += j * (1 << (i + 3));
374   	}
375   	fprintf(stderr, "\nused:\t");
376   	for (i = 0; i < NBUCKETS; i++) {
377   		fprintf(stderr, " %d", nmalloc[i]);
378   		totused += nmalloc[i] * (1 << (i + 3));
379   	}
380   	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
381 	    totused, totfree);
382 }
383 #endif
384