malloc.c revision 34193
1/*-
2 * Copyright (c) 1983 Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#if defined(LIBC_SCCS) && !defined(lint)
35/*static char *sccsid = "from: @(#)malloc.c	5.11 (Berkeley) 2/23/91";*/
36static char *rcsid = "$Id: malloc.c,v 1.2 1996/01/19 18:36:54 jdp Exp $";
37#endif /* LIBC_SCCS and not lint */
38
39/*
40 * malloc.c (Caltech) 2/21/82
41 * Chris Kingsley, kingsley@cit-20.
42 *
43 * This is a very fast storage allocator.  It allocates blocks of a small
44 * number of different sizes, and keeps free lists of each size.  Blocks that
45 * don't exactly fit are passed up to the next larger size.  In this
46 * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
47 * This is designed for use in a virtual memory environment.
48 */
49
50#include <sys/types.h>
51#include <err.h>
52#include <stdlib.h>
53#include <string.h>
54#include <unistd.h>
55#include <sys/param.h>
56#include <sys/mman.h>
57#ifndef BSD
58#define MAP_COPY	MAP_PRIVATE
59#define MAP_FILE	0
60#define MAP_ANON	0
61#endif
62
63#ifndef BSD		/* Need do better than this */
64#define NEED_DEV_ZERO	1
65#endif
66
67#define	NULL 0
68
69static void morecore();
70static int findbucket();
71
72/*
73 * Pre-allocate mmap'ed pages
74 */
75#define	NPOOLPAGES	(32*1024/pagesz)
76static caddr_t		pagepool_start, pagepool_end;
77static int		morepages();
78
79/*
80 * The overhead on a block is at least 4 bytes.  When free, this space
81 * contains a pointer to the next free block, and the bottom two bits must
82 * be zero.  When in use, the first byte is set to MAGIC, and the second
83 * byte is the size index.  The remaining bytes are for alignment.
84 * If range checking is enabled then a second word holds the size of the
85 * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
86 * The order of elements is critical: ov_magic must overlay the low order
87 * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
88 */
89union	overhead {
90	union	overhead *ov_next;	/* when free */
91	struct {
92		u_char	ovu_magic;	/* magic number */
93		u_char	ovu_index;	/* bucket # */
94#ifdef RCHECK
95		u_short	ovu_rmagic;	/* range magic number */
96		u_int	ovu_size;	/* actual block size */
97#endif
98	} ovu;
99#define	ov_magic	ovu.ovu_magic
100#define	ov_index	ovu.ovu_index
101#define	ov_rmagic	ovu.ovu_rmagic
102#define	ov_size		ovu.ovu_size
103};
104
105#define	MAGIC		0xef		/* magic # on accounting info */
106#define RMAGIC		0x5555		/* magic # on range info */
107
108#ifdef RCHECK
109#define	RSLOP		sizeof (u_short)
110#else
111#define	RSLOP		0
112#endif
113
114/*
115 * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
116 * smallest allocatable block is 8 bytes.  The overhead information
117 * precedes the data area returned to the user.
118 */
119#define	NBUCKETS 30
120static	union overhead *nextf[NBUCKETS];
121extern	char *sbrk();
122
123static	int pagesz;			/* page size */
124static	int pagebucket;			/* page size bucket */
125
126#ifdef MSTATS
127/*
128 * nmalloc[i] is the difference between the number of mallocs and frees
129 * for a given block size.
130 */
131static	u_int nmalloc[NBUCKETS];
132#include <stdio.h>
133#endif
134
135#if defined(MALLOC_DEBUG) || defined(RCHECK)
136#define	ASSERT(p)   if (!(p)) botch("p")
137#include <stdio.h>
138static void
139botch(s)
140	char *s;
141{
142	fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
143 	(void) fflush(stderr);		/* just in case user buffered it */
144	abort();
145}
146#else
147#define	ASSERT(p)
148#endif
149
150/* Debugging stuff */
151extern void xprintf(const char *, ...);
152#define TRACE()	xprintf("TRACE %s:%d\n", __FILE__, __LINE__)
153
154void *
155malloc(nbytes)
156	size_t nbytes;
157{
158  	register union overhead *op;
159  	register int bucket, n;
160	register unsigned amt;
161
162	/*
163	 * First time malloc is called, setup page size and
164	 * align break pointer so all data will be page aligned.
165	 */
166	if (pagesz == 0) {
167		pagesz = n = getpagesize();
168		if (morepages(NPOOLPAGES) == 0)
169			return NULL;
170		op = (union overhead *)(pagepool_start);
171  		n = n - sizeof (*op) - ((int)op & (n - 1));
172		if (n < 0)
173			n += pagesz;
174  		if (n) {
175			pagepool_start += n;
176		}
177		bucket = 0;
178		amt = 8;
179		while (pagesz > amt) {
180			amt <<= 1;
181			bucket++;
182		}
183		pagebucket = bucket;
184	}
185	/*
186	 * Convert amount of memory requested into closest block size
187	 * stored in hash buckets which satisfies request.
188	 * Account for space used per block for accounting.
189	 */
190	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
191#ifndef RCHECK
192		amt = 8;	/* size of first bucket */
193		bucket = 0;
194#else
195		amt = 16;	/* size of first bucket */
196		bucket = 1;
197#endif
198		n = -(sizeof (*op) + RSLOP);
199	} else {
200		amt = pagesz;
201		bucket = pagebucket;
202	}
203	while (nbytes > amt + n) {
204		amt <<= 1;
205		if (amt == 0)
206			return (NULL);
207		bucket++;
208	}
209	/*
210	 * If nothing in hash bucket right now,
211	 * request more memory from the system.
212	 */
213  	if ((op = nextf[bucket]) == NULL) {
214  		morecore(bucket);
215  		if ((op = nextf[bucket]) == NULL)
216  			return (NULL);
217	}
218	/* remove from linked list */
219  	nextf[bucket] = op->ov_next;
220	op->ov_magic = MAGIC;
221	op->ov_index = bucket;
222#ifdef MSTATS
223  	nmalloc[bucket]++;
224#endif
225#ifdef RCHECK
226	/*
227	 * Record allocated size of block and
228	 * bound space with magic numbers.
229	 */
230	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
231	op->ov_rmagic = RMAGIC;
232  	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
233#endif
234  	return ((char *)(op + 1));
235}
236
237/*
238 * Allocate more memory to the indicated bucket.
239 */
240static void
241morecore(bucket)
242	int bucket;
243{
244  	register union overhead *op;
245	register int sz;		/* size of desired block */
246  	int amt;			/* amount to allocate */
247  	int nblks;			/* how many blocks we get */
248
249	/*
250	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
251	 * 2^30 bytes on a VAX, I think) or for a negative arg.
252	 */
253	sz = 1 << (bucket + 3);
254#ifdef MALLOC_DEBUG
255	ASSERT(sz > 0);
256#else
257	if (sz <= 0)
258		return;
259#endif
260	if (sz < pagesz) {
261		amt = pagesz;
262  		nblks = amt / sz;
263	} else {
264		amt = sz + pagesz;
265		nblks = 1;
266	}
267	if (amt > pagepool_end - pagepool_start)
268		if (morepages(amt/pagesz + NPOOLPAGES) == 0)
269			return;
270	op = (union overhead *)pagepool_start;
271	pagepool_start += amt;
272
273	/*
274	 * Add new memory allocated to that on
275	 * free list for this hash bucket.
276	 */
277  	nextf[bucket] = op;
278  	while (--nblks > 0) {
279		op->ov_next = (union overhead *)((caddr_t)op + sz);
280		op = (union overhead *)((caddr_t)op + sz);
281  	}
282}
283
284void
285free(cp)
286	void *cp;
287{
288  	register int size;
289	register union overhead *op;
290
291  	if (cp == NULL)
292  		return;
293	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
294#ifdef MALLOC_DEBUG
295  	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
296#else
297	if (op->ov_magic != MAGIC)
298		return;				/* sanity */
299#endif
300#ifdef RCHECK
301  	ASSERT(op->ov_rmagic == RMAGIC);
302	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
303#endif
304  	size = op->ov_index;
305  	ASSERT(size < NBUCKETS);
306	op->ov_next = nextf[size];	/* also clobbers ov_magic */
307  	nextf[size] = op;
308#ifdef MSTATS
309  	nmalloc[size]--;
310#endif
311}
312
313/*
314 * When a program attempts "storage compaction" as mentioned in the
315 * old malloc man page, it realloc's an already freed block.  Usually
316 * this is the last block it freed; occasionally it might be farther
317 * back.  We have to search all the free lists for the block in order
318 * to determine its bucket: 1st we make one pass thru the lists
319 * checking only the first block in each; if that fails we search
320 * ``realloc_srchlen'' blocks in each list for a match (the variable
321 * is extern so the caller can modify it).  If that fails we just copy
322 * however many bytes was given to realloc() and hope it's not huge.
323 */
324int realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
325
326void *
327realloc(cp, nbytes)
328	void *cp;
329	size_t nbytes;
330{
331  	register u_int onb;
332	register int i;
333	union overhead *op;
334  	char *res;
335	int was_alloced = 0;
336
337  	if (cp == NULL)
338  		return (malloc(nbytes));
339	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
340	if (op->ov_magic == MAGIC) {
341		was_alloced++;
342		i = op->ov_index;
343	} else {
344		/*
345		 * Already free, doing "compaction".
346		 *
347		 * Search for the old block of memory on the
348		 * free list.  First, check the most common
349		 * case (last element free'd), then (this failing)
350		 * the last ``realloc_srchlen'' items free'd.
351		 * If all lookups fail, then assume the size of
352		 * the memory block being realloc'd is the
353		 * largest possible (so that all "nbytes" of new
354		 * memory are copied into).  Note that this could cause
355		 * a memory fault if the old area was tiny, and the moon
356		 * is gibbous.  However, that is very unlikely.
357		 */
358		if ((i = findbucket(op, 1)) < 0 &&
359		    (i = findbucket(op, realloc_srchlen)) < 0)
360			i = NBUCKETS;
361	}
362	onb = 1 << (i + 3);
363	if (onb < pagesz)
364		onb -= sizeof (*op) + RSLOP;
365	else
366		onb += pagesz - sizeof (*op) - RSLOP;
367	/* avoid the copy if same size block */
368	if (was_alloced) {
369		if (i) {
370			i = 1 << (i + 2);
371			if (i < pagesz)
372				i -= sizeof (*op) + RSLOP;
373			else
374				i += pagesz - sizeof (*op) - RSLOP;
375		}
376		if (nbytes <= onb && nbytes > i) {
377#ifdef RCHECK
378			op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
379			*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
380#endif
381			return(cp);
382		} else
383			free(cp);
384	}
385  	if ((res = malloc(nbytes)) == NULL)
386  		return (NULL);
387  	if (cp != res)		/* common optimization if "compacting" */
388		bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
389  	return (res);
390}
391
392/*
393 * Search ``srchlen'' elements of each free list for a block whose
394 * header starts at ``freep''.  If srchlen is -1 search the whole list.
395 * Return bucket number, or -1 if not found.
396 */
397static int
398findbucket(freep, srchlen)
399	union overhead *freep;
400	int srchlen;
401{
402	register union overhead *p;
403	register int i, j;
404
405	for (i = 0; i < NBUCKETS; i++) {
406		j = 0;
407		for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
408			if (p == freep)
409				return (i);
410			j++;
411		}
412	}
413	return (-1);
414}
415
416#ifdef MSTATS
417/*
418 * mstats - print out statistics about malloc
419 *
420 * Prints two lines of numbers, one showing the length of the free list
421 * for each size category, the second showing the number of mallocs -
422 * frees for each size category.
423 */
424mstats(s)
425	char *s;
426{
427  	register int i, j;
428  	register union overhead *p;
429  	int totfree = 0,
430  	totused = 0;
431
432  	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
433  	for (i = 0; i < NBUCKETS; i++) {
434  		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
435  			;
436  		fprintf(stderr, " %d", j);
437  		totfree += j * (1 << (i + 3));
438  	}
439  	fprintf(stderr, "\nused:\t");
440  	for (i = 0; i < NBUCKETS; i++) {
441  		fprintf(stderr, " %d", nmalloc[i]);
442  		totused += nmalloc[i] * (1 << (i + 3));
443  	}
444  	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
445	    totused, totfree);
446}
447#endif
448
449
450static int
451morepages(n)
452int	n;
453{
454	int	fd = -1;
455	int	offset;
456
457#ifdef NEED_DEV_ZERO
458	fd = open("/dev/zero", O_RDWR, 0);
459	if (fd == -1)
460		perror("/dev/zero");
461#endif
462
463	if (pagepool_end - pagepool_start > pagesz) {
464		caddr_t	addr = (caddr_t)
465			(((int)pagepool_start + pagesz - 1) & ~(pagesz - 1));
466		if (munmap(addr, pagepool_end - addr) != 0)
467			warn("morepages: munmap %p", addr);
468	}
469
470	offset = (int)pagepool_start - ((int)pagepool_start & ~(pagesz - 1));
471
472	if ((pagepool_start = mmap(0, n * pagesz,
473			PROT_READ|PROT_WRITE,
474			MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) {
475		xprintf("Cannot map anonymous memory");
476		return 0;
477	}
478	pagepool_end = pagepool_start + n * pagesz;
479	pagepool_start += offset;
480
481#ifdef NEED_DEV_ZERO
482	close(fd);
483#endif
484	return n;
485}
486