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