xref: /csrg-svn/lib/libc/stdlib/malloc.c (revision 26569)
121347Sdist /*
225177Smckusick  * Copyright (c) 1983 Regents of the University of California.
321347Sdist  * All rights reserved.  The Berkeley software License Agreement
421347Sdist  * specifies the terms and conditions for redistribution.
521347Sdist  */
621347Sdist 
7*26569Sdonn #if defined(LIBC_SCCS) && !defined(lint)
8*26569Sdonn static char sccsid[] = "@(#)malloc.c	5.6 (Berkeley) 03/09/86";
9*26569Sdonn #endif LIBC_SCCS and not lint
1014953Skarels 
1114953Skarels /*
1214953Skarels  * malloc.c (Caltech) 2/21/82
1314953Skarels  * Chris Kingsley, kingsley@cit-20.
1414953Skarels  *
1514953Skarels  * This is a very fast storage allocator.  It allocates blocks of a small
1614953Skarels  * number of different sizes, and keeps free lists of each size.  Blocks that
1714953Skarels  * don't exactly fit are passed up to the next larger size.  In this
1826410Slepreau  * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long.
1926410Slepreau  * This is designed for use in a virtual memory environment.
2014953Skarels  */
2114953Skarels 
2214953Skarels #include <sys/types.h>
2314953Skarels 
2414953Skarels #define	NULL 0
2514953Skarels 
2614953Skarels /*
2714953Skarels  * The overhead on a block is at least 4 bytes.  When free, this space
2814953Skarels  * contains a pointer to the next free block, and the bottom two bits must
2914953Skarels  * be zero.  When in use, the first byte is set to MAGIC, and the second
3014953Skarels  * byte is the size index.  The remaining bytes are for alignment.
3126410Slepreau  * If range checking is enabled then a second word holds the size of the
3226410Slepreau  * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC).
3326410Slepreau  * The order of elements is critical: ov_magic must overlay the low order
3426410Slepreau  * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern.
3514953Skarels  */
3614953Skarels union	overhead {
3714953Skarels 	union	overhead *ov_next;	/* when free */
3814953Skarels 	struct {
3914953Skarels 		u_char	ovu_magic;	/* magic number */
4014953Skarels 		u_char	ovu_index;	/* bucket # */
4126410Slepreau #ifdef RCHECK
4226410Slepreau 		u_short	ovu_rmagic;	/* range magic number */
4317333Sralph 		u_int	ovu_size;	/* actual block size */
4414953Skarels #endif
4514953Skarels 	} ovu;
4614953Skarels #define	ov_magic	ovu.ovu_magic
4714953Skarels #define	ov_index	ovu.ovu_index
4817333Sralph #define	ov_rmagic	ovu.ovu_rmagic
4914953Skarels #define	ov_size		ovu.ovu_size
5014953Skarels };
5114953Skarels 
5217333Sralph #define	MAGIC		0xef		/* magic # on accounting info */
5317333Sralph #define RMAGIC		0x5555		/* magic # on range info */
5417333Sralph 
5514953Skarels #ifdef RCHECK
5617333Sralph #define	RSLOP		sizeof (u_short)
5714953Skarels #else
5814953Skarels #define	RSLOP		0
5914953Skarels #endif
6014953Skarels 
6114953Skarels /*
6214953Skarels  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
6314953Skarels  * smallest allocatable block is 8 bytes.  The overhead information
6414953Skarels  * precedes the data area returned to the user.
6514953Skarels  */
6614953Skarels #define	NBUCKETS 30
6714953Skarels static	union overhead *nextf[NBUCKETS];
6814953Skarels extern	char *sbrk();
6914953Skarels 
7017333Sralph static	int pagesz;			/* page size */
7117333Sralph static	int pagebucket;			/* page size bucket */
7217333Sralph 
7314953Skarels #ifdef MSTATS
7414953Skarels /*
7514953Skarels  * nmalloc[i] is the difference between the number of mallocs and frees
7614953Skarels  * for a given block size.
7714953Skarels  */
7814953Skarels static	u_int nmalloc[NBUCKETS];
7914953Skarels #include <stdio.h>
8014953Skarels #endif
8114953Skarels 
8225799Slepreau #if defined(DEBUG) || defined(RCHECK)
8317333Sralph #define	ASSERT(p)   if (!(p)) botch("p")
8425799Slepreau #include <stdio.h>
8514953Skarels static
8613259Sroot botch(s)
8715003Ssam 	char *s;
8813259Sroot {
8925799Slepreau 	fprintf(stderr, "\r\nassertion botched: %s\r\n", s);
9025799Slepreau  	(void) fflush(stderr);		/* just in case user buffered it */
9113259Sroot 	abort();
9213259Sroot }
9313259Sroot #else
9414953Skarels #define	ASSERT(p)
9513259Sroot #endif
9613259Sroot 
9713259Sroot char *
9813259Sroot malloc(nbytes)
9917333Sralph 	unsigned nbytes;
10013259Sroot {
10117333Sralph   	register union overhead *op;
10217333Sralph   	register int bucket;
10317333Sralph 	register unsigned amt, n;
10413259Sroot 
10514953Skarels 	/*
10617333Sralph 	 * First time malloc is called, setup page size and
10717333Sralph 	 * align break pointer so all data will be page aligned.
10814953Skarels 	 */
10917333Sralph 	if (pagesz == 0) {
11017333Sralph 		pagesz = n = getpagesize();
11117333Sralph 		op = (union overhead *)sbrk(0);
11217333Sralph   		n = n - sizeof (*op) - ((int)op & (n - 1));
11317333Sralph 		if (n < 0)
11417333Sralph 			n += pagesz;
11517333Sralph   		if (n) {
11617333Sralph   			if (sbrk(n) == (char *)-1)
11717333Sralph 				return (NULL);
11817333Sralph 		}
11917333Sralph 		bucket = 0;
12017333Sralph 		amt = 8;
12117333Sralph 		while (pagesz > amt) {
12217333Sralph 			amt <<= 1;
12317333Sralph 			bucket++;
12417333Sralph 		}
12517333Sralph 		pagebucket = bucket;
12617333Sralph 	}
12714953Skarels 	/*
12817333Sralph 	 * Convert amount of memory requested into closest block size
12917333Sralph 	 * stored in hash buckets which satisfies request.
13017333Sralph 	 * Account for space used per block for accounting.
13117333Sralph 	 */
13217333Sralph 	if (nbytes <= (n = pagesz - sizeof (*op) - RSLOP)) {
13317333Sralph #ifndef RCHECK
13417333Sralph 		amt = 8;	/* size of first bucket */
13517333Sralph 		bucket = 0;
13617333Sralph #else
13717333Sralph 		amt = 16;	/* size of first bucket */
13817333Sralph 		bucket = 1;
13917333Sralph #endif
14017333Sralph 		n = -(sizeof (*op) + RSLOP);
14117333Sralph 	} else {
14217333Sralph 		amt = pagesz;
14317333Sralph 		bucket = pagebucket;
14417333Sralph 	}
14517333Sralph 	while (nbytes > amt + n) {
14617333Sralph 		amt <<= 1;
14725793Smckusick 		if (amt == 0)
14825793Smckusick 			return (NULL);
14917333Sralph 		bucket++;
15017333Sralph 	}
15117333Sralph 	/*
15214953Skarels 	 * If nothing in hash bucket right now,
15314953Skarels 	 * request more memory from the system.
15414953Skarels 	 */
15517333Sralph   	if ((op = nextf[bucket]) == NULL) {
15614953Skarels   		morecore(bucket);
15717333Sralph   		if ((op = nextf[bucket]) == NULL)
15817333Sralph   			return (NULL);
15917333Sralph 	}
16014953Skarels 	/* remove from linked list */
16117333Sralph   	nextf[bucket] = op->ov_next;
16217333Sralph 	op->ov_magic = MAGIC;
16317333Sralph 	op->ov_index = bucket;
16414953Skarels #ifdef MSTATS
16514953Skarels   	nmalloc[bucket]++;
16614953Skarels #endif
16714953Skarels #ifdef RCHECK
16814953Skarels 	/*
16914953Skarels 	 * Record allocated size of block and
17014953Skarels 	 * bound space with magic numbers.
17114953Skarels 	 */
17217438Sralph 	op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
17317333Sralph 	op->ov_rmagic = RMAGIC;
17417438Sralph   	*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
17514953Skarels #endif
17617333Sralph   	return ((char *)(op + 1));
17713259Sroot }
17813259Sroot 
17914953Skarels /*
18014953Skarels  * Allocate more memory to the indicated bucket.
18114953Skarels  */
18214953Skarels morecore(bucket)
18317333Sralph 	int bucket;
18413259Sroot {
18514953Skarels   	register union overhead *op;
18617333Sralph 	register int sz;		/* size of desired block */
18725793Smckusick   	int amt;			/* amount to allocate */
18825793Smckusick   	int nblks;			/* how many blocks we get */
18913259Sroot 
19025793Smckusick 	/*
19125793Smckusick 	 * sbrk_size <= 0 only for big, FLUFFY, requests (about
19225793Smckusick 	 * 2^30 bytes on a VAX, I think) or for a negative arg.
19325793Smckusick 	 */
19417333Sralph 	sz = 1 << (bucket + 3);
19526410Slepreau #ifdef DEBUG
19626410Slepreau 	ASSERT(sz > 0);
19726410Slepreau #else
19825793Smckusick 	if (sz <= 0)
19925793Smckusick 		return;
20026410Slepreau #endif
20117333Sralph 	if (sz < pagesz) {
20217333Sralph 		amt = pagesz;
20317333Sralph   		nblks = amt / sz;
20417333Sralph 	} else {
20517333Sralph 		amt = sz + pagesz;
20617333Sralph 		nblks = 1;
20717333Sralph 	}
20817333Sralph 	op = (union overhead *)sbrk(amt);
20914953Skarels 	/* no more room! */
21014953Skarels   	if ((int)op == -1)
21114953Skarels   		return;
21214953Skarels 	/*
21314953Skarels 	 * Add new memory allocated to that on
21414953Skarels 	 * free list for this hash bucket.
21514953Skarels 	 */
21614953Skarels   	nextf[bucket] = op;
21714953Skarels   	while (--nblks > 0) {
21817333Sralph 		op->ov_next = (union overhead *)((caddr_t)op + sz);
21917333Sralph 		op = (union overhead *)((caddr_t)op + sz);
22014953Skarels   	}
22113259Sroot }
22213259Sroot 
22314953Skarels free(cp)
22414953Skarels 	char *cp;
22514953Skarels {
22614953Skarels   	register int size;
22714953Skarels 	register union overhead *op;
22813259Sroot 
22914953Skarels   	if (cp == NULL)
23014953Skarels   		return;
23114953Skarels 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
23217333Sralph #ifdef DEBUG
23314953Skarels   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
23414953Skarels #else
23514953Skarels 	if (op->ov_magic != MAGIC)
23614953Skarels 		return;				/* sanity */
23714953Skarels #endif
23814953Skarels #ifdef RCHECK
23914953Skarels   	ASSERT(op->ov_rmagic == RMAGIC);
24017333Sralph 	ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC);
24114953Skarels #endif
24214953Skarels   	size = op->ov_index;
24317333Sralph   	ASSERT(size < NBUCKETS);
24426410Slepreau 	op->ov_next = nextf[size];	/* also clobbers ov_magic */
24514953Skarels   	nextf[size] = op;
24614953Skarels #ifdef MSTATS
24714953Skarels   	nmalloc[size]--;
24814953Skarels #endif
24914953Skarels }
25014953Skarels 
25114953Skarels /*
25214953Skarels  * When a program attempts "storage compaction" as mentioned in the
25314953Skarels  * old malloc man page, it realloc's an already freed block.  Usually
25414953Skarels  * this is the last block it freed; occasionally it might be farther
25514953Skarels  * back.  We have to search all the free lists for the block in order
25614953Skarels  * to determine its bucket: 1st we make one pass thru the lists
25714953Skarels  * checking only the first block in each; if that fails we search
25814953Skarels  * ``realloc_srchlen'' blocks in each list for a match (the variable
25914953Skarels  * is extern so the caller can modify it).  If that fails we just copy
26014953Skarels  * however many bytes was given to realloc() and hope it's not huge.
26114953Skarels  */
26215003Ssam int realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
26314953Skarels 
26413259Sroot char *
26514953Skarels realloc(cp, nbytes)
26614953Skarels 	char *cp;
26714953Skarels 	unsigned nbytes;
26814953Skarels {
26917333Sralph   	register u_int onb, i;
27014953Skarels 	union overhead *op;
27114953Skarels   	char *res;
27214953Skarels 	int was_alloced = 0;
27314953Skarels 
27414953Skarels   	if (cp == NULL)
27514953Skarels   		return (malloc(nbytes));
27614953Skarels 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
27714953Skarels 	if (op->ov_magic == MAGIC) {
27814953Skarels 		was_alloced++;
27914953Skarels 		i = op->ov_index;
28015003Ssam 	} else {
28115003Ssam 		/*
28215003Ssam 		 * Already free, doing "compaction".
28315003Ssam 		 *
28415003Ssam 		 * Search for the old block of memory on the
28515003Ssam 		 * free list.  First, check the most common
28615003Ssam 		 * case (last element free'd), then (this failing)
28715003Ssam 		 * the last ``realloc_srchlen'' items free'd.
28815003Ssam 		 * If all lookups fail, then assume the size of
28915003Ssam 		 * the memory block being realloc'd is the
29025799Slepreau 		 * largest possible (so that all "nbytes" of new
29125799Slepreau 		 * memory are copied into).  Note that this could cause
29225799Slepreau 		 * a memory fault if the old area was tiny, and the moon
29325799Slepreau 		 * is gibbous.  However, that is very unlikely.
29415003Ssam 		 */
29514953Skarels 		if ((i = findbucket(op, 1)) < 0 &&
29614953Skarels 		    (i = findbucket(op, realloc_srchlen)) < 0)
29725799Slepreau 			i = NBUCKETS;
29814953Skarels 	}
29917333Sralph 	onb = 1 << (i + 3);
30017333Sralph 	if (onb < pagesz)
30117333Sralph 		onb -= sizeof (*op) + RSLOP;
30217333Sralph 	else
30317333Sralph 		onb += pagesz - sizeof (*op) - RSLOP;
30415003Ssam 	/* avoid the copy if same size block */
30517333Sralph 	if (was_alloced) {
30617333Sralph 		if (i) {
30717333Sralph 			i = 1 << (i + 2);
30817333Sralph 			if (i < pagesz)
30917333Sralph 				i -= sizeof (*op) + RSLOP;
31017333Sralph 			else
31117333Sralph 				i += pagesz - sizeof (*op) - RSLOP;
31217333Sralph 		}
31317333Sralph 		if (nbytes <= onb && nbytes > i) {
31417332Sralph #ifdef RCHECK
31517438Sralph 			op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1);
31617333Sralph 			*(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC;
31717332Sralph #endif
31817333Sralph 			return(cp);
31917333Sralph 		} else
32017333Sralph 			free(cp);
32117332Sralph 	}
32214953Skarels   	if ((res = malloc(nbytes)) == NULL)
32314953Skarels   		return (NULL);
32425799Slepreau   	if (cp != res)		/* common optimization if "compacting" */
32514953Skarels 		bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
32614953Skarels   	return (res);
32714953Skarels }
32814953Skarels 
32914953Skarels /*
33014953Skarels  * Search ``srchlen'' elements of each free list for a block whose
33114953Skarels  * header starts at ``freep''.  If srchlen is -1 search the whole list.
33214953Skarels  * Return bucket number, or -1 if not found.
33314953Skarels  */
33414953Skarels static
33514953Skarels findbucket(freep, srchlen)
33615003Ssam 	union overhead *freep;
33715003Ssam 	int srchlen;
33813259Sroot {
33914953Skarels 	register union overhead *p;
34014953Skarels 	register int i, j;
34113259Sroot 
34215003Ssam 	for (i = 0; i < NBUCKETS; i++) {
34315003Ssam 		j = 0;
34415003Ssam 		for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
34514953Skarels 			if (p == freep)
34614953Skarels 				return (i);
34715003Ssam 			j++;
34815003Ssam 		}
34915003Ssam 	}
35014953Skarels 	return (-1);
35113259Sroot }
35213259Sroot 
35314953Skarels #ifdef MSTATS
35414953Skarels /*
35514953Skarels  * mstats - print out statistics about malloc
35614953Skarels  *
35714953Skarels  * Prints two lines of numbers, one showing the length of the free list
35814953Skarels  * for each size category, the second showing the number of mallocs -
35914953Skarels  * frees for each size category.
36014953Skarels  */
36114953Skarels mstats(s)
36214953Skarels 	char *s;
36313259Sroot {
36414953Skarels   	register int i, j;
36514953Skarels   	register union overhead *p;
36614953Skarels   	int totfree = 0,
36714953Skarels   	totused = 0;
36814953Skarels 
36914953Skarels   	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
37014953Skarels   	for (i = 0; i < NBUCKETS; i++) {
37114953Skarels   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
37214953Skarels   			;
37314953Skarels   		fprintf(stderr, " %d", j);
37414953Skarels   		totfree += j * (1 << (i + 3));
37514953Skarels   	}
37614953Skarels   	fprintf(stderr, "\nused:\t");
37714953Skarels   	for (i = 0; i < NBUCKETS; i++) {
37814953Skarels   		fprintf(stderr, " %d", nmalloc[i]);
37914953Skarels   		totused += nmalloc[i] * (1 << (i + 3));
38014953Skarels   	}
38115003Ssam   	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
38215003Ssam 	    totused, totfree);
38313259Sroot }
38413259Sroot #endif
385