xref: /csrg-svn/bin/csh/alloc.c (revision 15537)
1 #ifndef lint
2 static	char *sccsid = "@(#)alloc.c 4.3 (Berkeley from Caltech) 11/13/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 debug
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 #endif
70 
71 #ifdef debug
72 #define	ASSERT(p)   if (!(p)) botch("p"); else
73 static
74 botch(s)
75 char *s;
76 {
77 	printf("assertion botched: %s\n",s);
78 	abort();
79 }
80 #else
81 #define	ASSERT(p)
82 #endif
83 
84 char *
85 malloc(nbytes)
86 	register unsigned nbytes;
87 {
88   	register union overhead *p;
89   	register int bucket = 0;
90   	register unsigned shiftr;
91 
92 	/*
93 	 * Convert amount of memory requested into
94 	 * closest block size stored in hash buckets
95 	 * which satisfies request.  Account for
96 	 * space used per block for accounting.
97 	 */
98   	nbytes += sizeof (union overhead) + RSLOP;
99   	nbytes = (nbytes + 3) &~ 3;
100   	shiftr = (nbytes - 1) >> 2;
101 	/* apart from this loop, this is O(1) */
102   	while (shiftr >>= 1)
103   		bucket++;
104 	/*
105 	 * If nothing in hash bucket right now,
106 	 * request more memory from the system.
107 	 */
108   	if (nextf[bucket] == NULL)
109   		morecore(bucket);
110   	if ((p = (union overhead *)nextf[bucket]) == NULL)
111   		return (NULL);
112 	/* remove from linked list */
113   	nextf[bucket] = nextf[bucket]->ov_next;
114 	p->ov_magic = MAGIC;
115 	p->ov_index= bucket;
116 #ifdef debug
117   	nmalloc[bucket]++;
118 #endif
119 #ifdef RCHECK
120 	/*
121 	 * Record allocated size of block and
122 	 * bound space with magic numbers.
123 	 */
124   	if (nbytes <= 0x10000)
125 		p->ov_size = nbytes - 1;
126 	p->ov_rmagic = RMAGIC;
127   	*((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
128 #endif
129   	return ((char *)(p + 1));
130 }
131 
132 /*
133  * Allocate more memory to the indicated bucket.
134  */
135 static
136 morecore(bucket)
137 	register bucket;
138 {
139   	register union overhead *op;
140   	register int rnu;       /* 2^rnu bytes will be requested */
141   	register int nblks;     /* become nblks blocks of the desired size */
142 	register int siz;
143 
144   	if (nextf[bucket])
145   		return;
146 	/*
147 	 * Insure memory is allocated
148 	 * on a page boundary.  Should
149 	 * make getpageize call?
150 	 */
151   	op = (union overhead *)sbrk(0);
152   	if ((int)op & 0x3ff)
153   		sbrk(1024 - ((int)op & 0x3ff));
154 	/* take 2k unless the block is bigger than that */
155   	rnu = (bucket <= 8) ? 11 : bucket + 3;
156   	nblks = 1 << (rnu - (bucket + 3));  /* how many blocks to get */
157   	if (rnu < bucket)
158 		rnu = bucket;
159 	op = (union overhead *)sbrk(1 << rnu);
160 	/* no more room! */
161   	if ((int)op == -1)
162   		return;
163 	/*
164 	 * Round up to minimum allocation size boundary
165 	 * and deduct from block count to reflect.
166 	 */
167   	if ((int)op & 7) {
168   		op = (union overhead *)(((int)op + 8) &~ 7);
169   		nblks--;
170   	}
171 	/*
172 	 * Add new memory allocated to that on
173 	 * free list for this hash bucket.
174 	 */
175   	nextf[bucket] = op;
176   	siz = 1 << (bucket + 3);
177   	while (--nblks > 0) {
178 		op->ov_next = (union overhead *)((caddr_t)op + siz);
179 		op = (union overhead *)((caddr_t)op + siz);
180   	}
181 }
182 
183 free(cp)
184 	char *cp;
185 {
186   	register int size;
187 	register union overhead *op;
188 
189   	if (cp == NULL)
190   		return;
191 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
192 
193 	/*
194 	** The following botch is because csh tries to free a free block
195 	** when processing the =~ or !~ operators. -- layer@ucbmonet
196 	*/
197 #ifdef CSHbotch /* was debug */
198   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
199 #else
200 	if (op->ov_magic != MAGIC)
201 		return;				/* sanity */
202 #endif
203 
204 #ifdef RCHECK
205   	ASSERT(op->ov_rmagic == RMAGIC);
206 	if (op->ov_index <= 13)
207 		ASSERT(*(u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP) == RMAGIC);
208 #endif
209   	ASSERT(op->ov_index < NBUCKETS);
210   	size = op->ov_index;
211 	op->ov_next = nextf[size];
212   	nextf[size] = op;
213 #ifdef debug
214   	nmalloc[size]--;
215 #endif
216 }
217 
218 /*
219  * When a program attempts "storage compaction" as mentioned in the
220  * old malloc man page, it realloc's an already freed block.  Usually
221  * this is the last block it freed; occasionally it might be farther
222  * back.  We have to search all the free lists for the block in order
223  * to determine its bucket: 1st we make one pass thru the lists
224  * checking only the first block in each; if that fails we search
225  * ``realloc_srchlen'' blocks in each list for a match (the variable
226  * is extern so the caller can modify it).  If that fails we just copy
227  * however many bytes was given to realloc() and hope it's not huge.
228  */
229 int realloc_srchlen = 4;	/* 4 should be plenty.  -1 means whole list */
230 
231 char *
232 realloc(cp, nbytes)
233 	char *cp;
234 	unsigned nbytes;
235 {
236   	register u_int onb;
237 	union overhead *op;
238   	char *res;
239 	register int i;
240 	int was_alloced = 0;
241 
242   	if (cp == NULL)
243   		return (malloc(nbytes));
244 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
245 	if (op->ov_magic == MAGIC) {
246 		was_alloced++;
247 		i = op->ov_index;
248 	}
249 	else {		/* already free: he is doing "compaction" (tee hee) */
250 		if ((i = findbucket(op, 1)) < 0 &&
251 		    (i = findbucket(op, realloc_srchlen)) < 0)
252 			i = 0;		/* assume smallest possible */
253 	}
254 	onb = (1 << (i + 3)) - sizeof (*op) - RSLOP;
255 	if (was_alloced &&		/* avoid the copy if same size block */
256 	    nbytes <= onb && nbytes > (onb >> 1) - sizeof(*op) - RSLOP)
257 		return(cp);
258   	if ((res = malloc(nbytes)) == NULL)
259   		return (NULL);
260   	if (cp != res)			/* common optimization */
261 		bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
262   	if (was_alloced)
263 		free(cp);
264   	return (res);
265 }
266 
267 /*
268  * Search ``srchlen'' elements of each free list for a block whose
269  * header starts at ``freep''.  If srchlen is -1 search the whole list.
270  * Return bucket number, or -1 if not found.
271  */
272 static
273 findbucket(freep, srchlen)
274 union overhead *freep;
275 int srchlen;
276 {
277 	register union overhead *p;
278 	register int i, j;
279 
280 	for (i = 0; i < NBUCKETS; i++)
281 		for (j = 0, p = nextf[i]; p && j != srchlen; j++, p = p->ov_next)
282 			if (p == freep)
283 				return (i);
284 	return (-1);
285 }
286 
287 #ifdef debug
288 /*
289  * mstats - print out statistics about malloc
290  *
291  * Prints two lines of numbers, one showing the length of the free list
292  * for each size category, the second showing the number of mallocs -
293  * frees for each size category.
294  */
295 showall(s)
296 	char **s;
297 {
298   	register int i, j;
299   	register union overhead *p;
300   	int totfree = 0,
301   	totused = 0;
302 
303 	if (s[1])
304 	    printf("Memory allocation statistics %s\nfree:\t", s[1]);
305   	for (i = 0; i < NBUCKETS; i++) {
306   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
307   			;
308 
309   		if (s[1])
310 		    printf(" %d", j);
311   		totfree += j * (1 << (i + 3));
312   	}
313 	if (s[1])
314   	    printf("\nused:\t");
315   	for (i = 0; i < NBUCKETS; i++) {
316   		if (s[1])
317 		    printf(" %d", nmalloc[i]);
318   		totused += nmalloc[i] * (1 << (i + 3));
319   	}
320 	if (s[1])
321 	    printf("\n\t");
322   	printf("Total in use: %d, total free: %d\n", totused, totfree);
323 }
324 #endif
325