xref: /original-bsd/bin/csh/alloc.c (revision cba8738a)
1 /*-
2  * Copyright (c) 1983, 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)alloc.c	5.5 (Berkeley) 04/04/91";
10 #endif /* not lint */
11 
12 /* From "@(#)malloc.c	5.5 (Berkeley) 2/25/86"; */
13 
14 /*
15  * malloc.c (Caltech) 2/21/82
16  * Chris Kingsley, kingsley@cit-20.
17  *
18  * This is a very fast storage allocator.  It allocates blocks of a small
19  * number of different sizes, and keeps free lists of each size.  Blocks that
20  * don't exactly fit are passed up to the next larger size.  In this
21  * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
22  * This is designed for use in a virtual memory environment.
23  */
24 
25 #include <sys/types.h>
26 
27 #define	NULL 0
28 
29 /*
30  * The overhead on a block is at least 4 bytes.  When free, this space
31  * contains a pointer to the next free block, and the bottom two bits must
32  * be zero.  When in use, the first byte is set to MAGIC, and the second
33  * byte is the size index.  The remaining bytes are for alignment.
34  * If range checking is enabled then a second word holds the size of the
35  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
36  * The order of elements is critical: ov_magic must overlay the low order
37  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
38  */
39 union	overhead {
40 	union	overhead *ov_next;	/* when free */
41 	struct {
42 		u_char	ovu_magic;	/* magic number */
43 		u_char	ovu_index;	/* bucket # */
44 #ifdef RCHECK
45 		u_short	ovu_rmagic;	/* range magic number */
46 		u_int	ovu_size;	/* actual block size */
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 /*
77  * nmalloc[i] is the difference between the number of mallocs and frees
78  * for a given block size.
79  */
80 static	u_int nmalloc[NBUCKETS];
81 
82 #if defined(DEBUG) || defined(RCHECK)
83 #define	ASSERT(p)   if (!(p)) botch("p")
84 static
85 botch(s)
86 	char *s;
87 {
88 	printf("\r\nassertion botched: %s\r\n", s);
89 	abort();
90 }
91 #else
92 #define	ASSERT(p)
93 #endif
94 
95 char *
96 malloc(nbytes)
97 	unsigned nbytes;
98 {
99   	register union overhead *op;
100   	register int bucket;
101 	register unsigned amt, n;
102 
103 	/*
104 	 * First time malloc is called, setup page size and
105 	 * align break pointer so all data will be page aligned.
106 	 */
107 	if (pagesz == 0) {
108 		pagesz = n = getpagesize();
109 		op = (union overhead *)sbrk(0);
110   		n = n - sizeof (*op) - ((int)op & (n - 1));
111 		if (n < 0)
112 			n += pagesz;
113   		if (n) {
114   			if (sbrk(n) == (char *)-1)
115 				return (NULL);
116 		}
117 		bucket = 0;
118 		amt = 8;
119 		while (pagesz > amt) {
120 			amt <<= 1;
121 			bucket++;
122 		}
123 		pagebucket = bucket;
124 	}
125 	/*
126 	 * Convert amount of memory requested into closest block size
127 	 * stored in hash buckets which satisfies request.
128 	 * Account for space used per block for accounting.
129 	 */
130 	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
131 #ifndef RCHECK
132 		amt = 8;	/* size of first bucket */
133 		bucket = 0;
134 #else
135 		amt = 16;	/* size of first bucket */
136 		bucket = 1;
137 #endif
138 		n = -(sizeof (*op) + RSLOP);
139 	} else {
140 		amt = pagesz;
141 		bucket = pagebucket;
142 	}
143 	while (nbytes > amt + n) {
144 		amt <<= 1;
145 		if (amt == 0)
146 			return (NULL);
147 		bucket++;
148 	}
149 	/*
150 	 * If nothing in hash bucket right now,
151 	 * request more memory from the system.
152 	 */
153   	if ((op = nextf[bucket]) == NULL) {
154   		morecore(bucket);
155   		if ((op = nextf[bucket]) == NULL)
156   			return (NULL);
157 	}
158 	/* remove from linked list */
159   	nextf[bucket] = op->ov_next;
160 	op->ov_magic = MAGIC;
161 	op->ov_index = bucket;
162   	nmalloc[bucket]++;
163 #ifdef RCHECK
164 	/*
165 	 * Record allocated size of block and
166 	 * bound space with magic numbers.
167 	 */
168 	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
169 	op->ov_rmagic = RMAGIC;
170   	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
171 #endif
172   	return ((char *)(op + 1));
173 }
174 
175 /*
176  * Allocate more memory to the indicated bucket.
177  */
178 morecore(bucket)
179 	int bucket;
180 {
181   	register union overhead *op;
182 	register int sz;		/* size of desired block */
183   	int amt;			/* amount to allocate */
184   	int nblks;			/* how many blocks we get */
185 
186 	/*
187 	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
188 	 * 2^30 bytes on a VAX, I think) or for a negative arg.
189 	 */
190 	sz = 1 << (bucket + 3);
191 #ifdef DEBUG
192 	ASSERT(sz > 0);
193 #else
194 	if (sz <= 0)
195 		return;
196 #endif
197 	if (sz < pagesz) {
198 		amt = pagesz;
199   		nblks = amt / sz;
200 	} else {
201 		amt = sz + pagesz;
202 		nblks = 1;
203 	}
204 	op = (union overhead *)sbrk(amt);
205 	/* no more room! */
206   	if ((int)op == -1)
207   		return;
208 	/*
209 	 * Add new memory allocated to that on
210 	 * free list for this hash bucket.
211 	 */
212   	nextf[bucket] = op;
213   	while (--nblks > 0) {
214 		op->ov_next = (union overhead *)((caddr_t)op + sz);
215 		op = (union overhead *)((caddr_t)op + sz);
216   	}
217 }
218 
219 free(cp)
220 	char *cp;
221 {
222   	register int size;
223 	register union overhead *op;
224 
225   	if (cp == NULL)
226   		return;
227 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
228 	/*
229 	 * The following botch is because csh tries to free a free block
230 	 * when processing the =~ or !~ operators. -- layer@ucbmonet
231 	*/
232 #ifdef CSHbotch /* was DEBUG */
233   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
234 #else
235 	if (op->ov_magic != MAGIC)
236 		return;				/* sanity */
237 #endif
238 #ifdef RCHECK
239   	ASSERT(op->ov_rmagic == RMAGIC);
240 	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
241 #endif
242   	size = op->ov_index;
243   	ASSERT(size < NBUCKETS);
244 	op->ov_next = nextf[size];	/* also clobbers ov_magic */
245   	nextf[size] = op;
246   	nmalloc[size]--;
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 	static int findbucket();
272 
273   	if (cp == NULL)
274   		return (malloc(nbytes));
275 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
276 	if (op->ov_magic == MAGIC) {
277 		was_alloced++;
278 		i = op->ov_index;
279 	} else {
280 		/*
281 		 * Already free, doing "compaction".
282 		 *
283 		 * Search for the old block of memory on the
284 		 * free list.  First, check the most common
285 		 * case (last element free'd), then (this failing)
286 		 * the last ``realloc_srchlen'' items free'd.
287 		 * If all lookups fail, then assume the size of
288 		 * the memory block being realloc'd is the
289 		 * largest possible (so that all "nbytes" of new
290 		 * memory are copied into).  Note that this could cause
291 		 * a memory fault if the old area was tiny, and the moon
292 		 * is gibbous.  However, that is very unlikely.
293 		 */
294 		if ((i = findbucket(op, 1)) < 0 &&
295 		    (i = findbucket(op, realloc_srchlen)) < 0)
296 			i = NBUCKETS;
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 if "compacting" */
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 /*
353  * mstats - print out statistics about malloc
354  *
355  * Prints two lines of numbers, one showing the length of the free list
356  * for each size category, the second showing the number of mallocs -
357  * frees for each size category.
358  */
359 showall(s)
360 char **s;
361 {
362 	register int i, j;
363 	register union overhead *p;
364 	int totfree = 0,
365 	totused = 0;
366 
367 	if (s[1])
368 		printf("Memory allocation statistics %s\nfree:", s[1]);
369 	for (i = 0; i < NBUCKETS; i++) {
370 		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
371 			;
372 		if (s[1])
373 			printf(" %d", j);
374 		totfree += j * (1 << (i + 3));
375 	}
376 	if (s[1])
377 		printf("\nused:");
378 	for (i = 0; i < NBUCKETS; i++) {
379 		if (s[1])
380 			printf(" %d", nmalloc[i]);
381 		totused += nmalloc[i] * (1 << (i + 3));
382 	}
383 	if (s[1])
384 		printf("\n");
385 	printf("Total in use: %d, total free: %d\n", totused, totfree);
386 }
387