xref: /csrg-svn/lib/libc/stdlib/malloc.c (revision 17332)
113259Sroot #ifndef lint
2*17332Sralph static char sccsid[] = "@(#)malloc.c	4.4 (Berkeley) 11/02/84";
313259Sroot #endif
414953Skarels 
514953Skarels /*
614953Skarels  * malloc.c (Caltech) 2/21/82
714953Skarels  * Chris Kingsley, kingsley@cit-20.
814953Skarels  *
914953Skarels  * This is a very fast storage allocator.  It allocates blocks of a small
1014953Skarels  * number of different sizes, and keeps free lists of each size.  Blocks that
1114953Skarels  * don't exactly fit are passed up to the next larger size.  In this
1214953Skarels  * implementation, the available sizes are 2^n-4 (or 2^n-12) bytes long.
1314953Skarels  * This is designed for use in a program that uses vast quantities of memory,
1414953Skarels  * but bombs when it runs out.
1514953Skarels  */
1614953Skarels 
1714953Skarels #include <sys/types.h>
1814953Skarels 
1914953Skarels #define	NULL 0
2014953Skarels 
2114953Skarels /*
2214953Skarels  * The overhead on a block is at least 4 bytes.  When free, this space
2314953Skarels  * contains a pointer to the next free block, and the bottom two bits must
2414953Skarels  * be zero.  When in use, the first byte is set to MAGIC, and the second
2514953Skarels  * byte is the size index.  The remaining bytes are for alignment.
2614953Skarels  * If range checking is enabled and the size of the block fits
2714953Skarels  * in two bytes, then the top two bytes hold the size of the requested block
2814953Skarels  * plus the range checking words, and the header word MINUS ONE.
2914953Skarels  */
3014953Skarels union	overhead {
3114953Skarels 	union	overhead *ov_next;	/* when free */
3214953Skarels 	struct {
3314953Skarels 		u_char	ovu_magic;	/* magic number */
3414953Skarels 		u_char	ovu_index;	/* bucket # */
3514953Skarels #ifdef RCHECK
3614953Skarels 		u_short	ovu_size;	/* actual block size */
3714953Skarels 		u_int	ovu_rmagic;	/* range magic number */
3814953Skarels #endif
3914953Skarels 	} ovu;
4014953Skarels #define	ov_magic	ovu.ovu_magic
4114953Skarels #define	ov_index	ovu.ovu_index
4214953Skarels #define	ov_size		ovu.ovu_size
4314953Skarels #define	ov_rmagic	ovu.ovu_rmagic
4414953Skarels };
4514953Skarels 
4614953Skarels #define	MAGIC		0xff		/* magic # on accounting info */
4714953Skarels #define RMAGIC		0x55555555	/* magic # on range info */
4814953Skarels #ifdef RCHECK
4914953Skarels #define	RSLOP		sizeof (u_int)
5014953Skarels #else
5114953Skarels #define	RSLOP		0
5214953Skarels #endif
5314953Skarels 
5414953Skarels /*
5514953Skarels  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
5614953Skarels  * smallest allocatable block is 8 bytes.  The overhead information
5714953Skarels  * precedes the data area returned to the user.
5814953Skarels  */
5914953Skarels #define	NBUCKETS 30
6014953Skarels static	union overhead *nextf[NBUCKETS];
6114953Skarels extern	char *sbrk();
6214953Skarels 
6314953Skarels #ifdef MSTATS
6414953Skarels /*
6514953Skarels  * nmalloc[i] is the difference between the number of mallocs and frees
6614953Skarels  * for a given block size.
6714953Skarels  */
6814953Skarels static	u_int nmalloc[NBUCKETS];
6914953Skarels #include <stdio.h>
7014953Skarels #endif
7114953Skarels 
7213259Sroot #ifdef debug
7314953Skarels #define	ASSERT(p)   if (!(p)) botch("p"); else
7414953Skarels static
7513259Sroot botch(s)
7615003Ssam 	char *s;
7713259Sroot {
7815003Ssam 
7915003Ssam 	printf("assertion botched: %s\n", s);
8013259Sroot 	abort();
8113259Sroot }
8213259Sroot #else
8314953Skarels #define	ASSERT(p)
8413259Sroot #endif
8513259Sroot 
8613259Sroot char *
8713259Sroot malloc(nbytes)
8814953Skarels 	register unsigned nbytes;
8913259Sroot {
9014953Skarels   	register union overhead *p;
9114953Skarels   	register int bucket = 0;
9214953Skarels   	register unsigned shiftr;
9313259Sroot 
9414953Skarels 	/*
9514953Skarels 	 * Convert amount of memory requested into
9614953Skarels 	 * closest block size stored in hash buckets
9714953Skarels 	 * which satisfies request.  Account for
9814953Skarels 	 * space used per block for accounting.
9914953Skarels 	 */
10014953Skarels   	nbytes += sizeof (union overhead) + RSLOP;
10114953Skarels   	nbytes = (nbytes + 3) &~ 3;
10214953Skarels   	shiftr = (nbytes - 1) >> 2;
10314953Skarels 	/* apart from this loop, this is O(1) */
10414953Skarels   	while (shiftr >>= 1)
10514953Skarels   		bucket++;
10614953Skarels 	/*
10714953Skarels 	 * If nothing in hash bucket right now,
10814953Skarels 	 * request more memory from the system.
10914953Skarels 	 */
11014953Skarels   	if (nextf[bucket] == NULL)
11114953Skarels   		morecore(bucket);
11214953Skarels   	if ((p = (union overhead *)nextf[bucket]) == NULL)
11314953Skarels   		return (NULL);
11414953Skarels 	/* remove from linked list */
11514953Skarels   	nextf[bucket] = nextf[bucket]->ov_next;
11614953Skarels 	p->ov_magic = MAGIC;
11714953Skarels 	p->ov_index= bucket;
11814953Skarels #ifdef MSTATS
11914953Skarels   	nmalloc[bucket]++;
12014953Skarels #endif
12114953Skarels #ifdef RCHECK
12214953Skarels 	/*
12314953Skarels 	 * Record allocated size of block and
12414953Skarels 	 * bound space with magic numbers.
12514953Skarels 	 */
126*17332Sralph 	p->ov_rmagic = RMAGIC;
127*17332Sralph   	if (bucket <= 13) {
12814953Skarels 		p->ov_size = nbytes - 1;
129*17332Sralph   		*((u_int *)((caddr_t)p + nbytes - RSLOP)) = RMAGIC;
130*17332Sralph 	}
13114953Skarels #endif
13214953Skarels   	return ((char *)(p + 1));
13313259Sroot }
13413259Sroot 
13514953Skarels /*
13614953Skarels  * Allocate more memory to the indicated bucket.
13714953Skarels  */
13814953Skarels static
13914953Skarels morecore(bucket)
14014953Skarels 	register bucket;
14113259Sroot {
14214953Skarels   	register union overhead *op;
14314953Skarels   	register int rnu;       /* 2^rnu bytes will be requested */
14414953Skarels   	register int nblks;     /* become nblks blocks of the desired size */
14514953Skarels 	register int siz;
14613259Sroot 
14714953Skarels   	if (nextf[bucket])
14814953Skarels   		return;
14914953Skarels 	/*
15014953Skarels 	 * Insure memory is allocated
15114953Skarels 	 * on a page boundary.  Should
15214953Skarels 	 * make getpageize call?
15314953Skarels 	 */
15414953Skarels   	op = (union overhead *)sbrk(0);
15514953Skarels   	if ((int)op & 0x3ff)
15614953Skarels   		sbrk(1024 - ((int)op & 0x3ff));
15714953Skarels 	/* take 2k unless the block is bigger than that */
15814953Skarels   	rnu = (bucket <= 8) ? 11 : bucket + 3;
15914953Skarels   	nblks = 1 << (rnu - (bucket + 3));  /* how many blocks to get */
16014953Skarels   	if (rnu < bucket)
16114953Skarels 		rnu = bucket;
16214953Skarels 	op = (union overhead *)sbrk(1 << rnu);
16314953Skarels 	/* no more room! */
16414953Skarels   	if ((int)op == -1)
16514953Skarels   		return;
16614953Skarels 	/*
16714953Skarels 	 * Round up to minimum allocation size boundary
16814953Skarels 	 * and deduct from block count to reflect.
16914953Skarels 	 */
17014953Skarels   	if ((int)op & 7) {
17114953Skarels   		op = (union overhead *)(((int)op + 8) &~ 7);
17214953Skarels   		nblks--;
17314953Skarels   	}
17414953Skarels 	/*
17514953Skarels 	 * Add new memory allocated to that on
17614953Skarels 	 * free list for this hash bucket.
17714953Skarels 	 */
17814953Skarels   	nextf[bucket] = op;
17914953Skarels   	siz = 1 << (bucket + 3);
18014953Skarels   	while (--nblks > 0) {
18114953Skarels 		op->ov_next = (union overhead *)((caddr_t)op + siz);
18214953Skarels 		op = (union overhead *)((caddr_t)op + siz);
18314953Skarels   	}
18413259Sroot }
18513259Sroot 
18614953Skarels free(cp)
18714953Skarels 	char *cp;
18814953Skarels {
18914953Skarels   	register int size;
19014953Skarels 	register union overhead *op;
19113259Sroot 
19214953Skarels   	if (cp == NULL)
19314953Skarels   		return;
19414953Skarels 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
19514953Skarels #ifdef debug
19614953Skarels   	ASSERT(op->ov_magic == MAGIC);		/* make sure it was in use */
19714953Skarels #else
19814953Skarels 	if (op->ov_magic != MAGIC)
19914953Skarels 		return;				/* sanity */
20014953Skarels #endif
20114953Skarels #ifdef RCHECK
20214953Skarels   	ASSERT(op->ov_rmagic == RMAGIC);
20314953Skarels 	if (op->ov_index <= 13)
20414953Skarels 		ASSERT(*(u_int *)((caddr_t)op + op->ov_size + 1 - RSLOP) == RMAGIC);
20514953Skarels #endif
20614953Skarels   	ASSERT(op->ov_index < NBUCKETS);
20714953Skarels   	size = op->ov_index;
20814953Skarels 	op->ov_next = nextf[size];
20914953Skarels   	nextf[size] = op;
21014953Skarels #ifdef MSTATS
21114953Skarels   	nmalloc[size]--;
21214953Skarels #endif
21314953Skarels }
21414953Skarels 
21514953Skarels /*
21614953Skarels  * When a program attempts "storage compaction" as mentioned in the
21714953Skarels  * old malloc man page, it realloc's an already freed block.  Usually
21814953Skarels  * this is the last block it freed; occasionally it might be farther
21914953Skarels  * back.  We have to search all the free lists for the block in order
22014953Skarels  * to determine its bucket: 1st we make one pass thru the lists
22114953Skarels  * checking only the first block in each; if that fails we search
22214953Skarels  * ``realloc_srchlen'' blocks in each list for a match (the variable
22314953Skarels  * is extern so the caller can modify it).  If that fails we just copy
22414953Skarels  * however many bytes was given to realloc() and hope it's not huge.
22514953Skarels  */
22615003Ssam int realloc_srchlen = 4;	/* 4 should be plenty, -1 =>'s whole list */
22714953Skarels 
22813259Sroot char *
22914953Skarels realloc(cp, nbytes)
23014953Skarels 	char *cp;
23114953Skarels 	unsigned nbytes;
23214953Skarels {
23314953Skarels   	register u_int onb;
23414953Skarels 	union overhead *op;
23514953Skarels   	char *res;
23614953Skarels 	register int i;
23714953Skarels 	int was_alloced = 0;
23814953Skarels 
23914953Skarels   	if (cp == NULL)
24014953Skarels   		return (malloc(nbytes));
24114953Skarels 	op = (union overhead *)((caddr_t)cp - sizeof (union overhead));
24214953Skarels 	if (op->ov_magic == MAGIC) {
24314953Skarels 		was_alloced++;
24414953Skarels 		i = op->ov_index;
24515003Ssam 	} else {
24615003Ssam 		/*
24715003Ssam 		 * Already free, doing "compaction".
24815003Ssam 		 *
24915003Ssam 		 * Search for the old block of memory on the
25015003Ssam 		 * free list.  First, check the most common
25115003Ssam 		 * case (last element free'd), then (this failing)
25215003Ssam 		 * the last ``realloc_srchlen'' items free'd.
25315003Ssam 		 * If all lookups fail, then assume the size of
25415003Ssam 		 * the memory block being realloc'd is the
25515003Ssam 		 * smallest possible.
25615003Ssam 		 */
25714953Skarels 		if ((i = findbucket(op, 1)) < 0 &&
25814953Skarels 		    (i = findbucket(op, realloc_srchlen)) < 0)
25915003Ssam 			i = 0;
26014953Skarels 	}
26114953Skarels 	onb = (1 << (i + 3)) - sizeof (*op) - RSLOP;
26215003Ssam 	/* avoid the copy if same size block */
26315003Ssam 	if (was_alloced &&
264*17332Sralph 	    nbytes <= onb && nbytes > (1 << (i + 2)) - sizeof(*op) - RSLOP) {
265*17332Sralph #ifdef RCHECK
266*17332Sralph   		if (i <= 13) {
267*17332Sralph 			op->ov_size = nbytes - 1;
268*17332Sralph   			*((u_int *)((caddr_t)op + nbytes - RSLOP)) = RMAGIC;
269*17332Sralph 		}
270*17332Sralph #endif
27114953Skarels 		return(cp);
272*17332Sralph 	}
27314953Skarels   	if ((res = malloc(nbytes)) == NULL)
27414953Skarels   		return (NULL);
27514953Skarels   	if (cp != res)			/* common optimization */
27614953Skarels 		bcopy(cp, res, (nbytes < onb) ? nbytes : onb);
27714953Skarels   	if (was_alloced)
27814953Skarels 		free(cp);
27914953Skarels   	return (res);
28014953Skarels }
28114953Skarels 
28214953Skarels /*
28314953Skarels  * Search ``srchlen'' elements of each free list for a block whose
28414953Skarels  * header starts at ``freep''.  If srchlen is -1 search the whole list.
28514953Skarels  * Return bucket number, or -1 if not found.
28614953Skarels  */
28714953Skarels static
28814953Skarels findbucket(freep, srchlen)
28915003Ssam 	union overhead *freep;
29015003Ssam 	int srchlen;
29113259Sroot {
29214953Skarels 	register union overhead *p;
29314953Skarels 	register int i, j;
29413259Sroot 
29515003Ssam 	for (i = 0; i < NBUCKETS; i++) {
29615003Ssam 		j = 0;
29715003Ssam 		for (p = nextf[i]; p && j != srchlen; p = p->ov_next) {
29814953Skarels 			if (p == freep)
29914953Skarels 				return (i);
30015003Ssam 			j++;
30115003Ssam 		}
30215003Ssam 	}
30314953Skarels 	return (-1);
30413259Sroot }
30513259Sroot 
30614953Skarels #ifdef MSTATS
30714953Skarels /*
30814953Skarels  * mstats - print out statistics about malloc
30914953Skarels  *
31014953Skarels  * Prints two lines of numbers, one showing the length of the free list
31114953Skarels  * for each size category, the second showing the number of mallocs -
31214953Skarels  * frees for each size category.
31314953Skarels  */
31414953Skarels mstats(s)
31514953Skarels 	char *s;
31613259Sroot {
31714953Skarels   	register int i, j;
31814953Skarels   	register union overhead *p;
31914953Skarels   	int totfree = 0,
32014953Skarels   	totused = 0;
32114953Skarels 
32214953Skarels   	fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s);
32314953Skarels   	for (i = 0; i < NBUCKETS; i++) {
32414953Skarels   		for (j = 0, p = nextf[i]; p; p = p->ov_next, j++)
32514953Skarels   			;
32614953Skarels   		fprintf(stderr, " %d", j);
32714953Skarels   		totfree += j * (1 << (i + 3));
32814953Skarels   	}
32914953Skarels   	fprintf(stderr, "\nused:\t");
33014953Skarels   	for (i = 0; i < NBUCKETS; i++) {
33114953Skarels   		fprintf(stderr, " %d", nmalloc[i]);
33214953Skarels   		totused += nmalloc[i] * (1 << (i + 3));
33314953Skarels   	}
33415003Ssam   	fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n",
33515003Ssam 	    totused, totfree);
33613259Sroot }
33713259Sroot #endif
338