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