plan 9 kernel history: overview | file list | diff list

1992/0612/port/malloc.c (diff list | history)

port/malloc.c on 1992/0612
1992/0612    
#include <u.h> 
#include <libc.h> 
1990/1210    
 
1992/0612    
enum 
{ 
	MAGIC		= 0xDEADBABE, 
	MAX2SIZE	= 20 
}; 
1990/1210    
 
1992/0612    
typedef struct Bucket Bucket; 
struct Bucket 
1990/1210    
{ 
1992/0612    
	int	size; 
	int	magic; 
	Bucket	*next; 
	char	data[1]; 
}; 
1990/1210    
 
1992/0612    
typedef struct Arena Arena; 
struct Arena 
1990/1210    
{ 
1992/0612    
	Lock; 
	Bucket	*btab[MAX2SIZE];	 
}; 
1990/1210    
 
1992/0612    
static Arena arena; 
#define datoff		((int)&((Bucket*)0)->data) 
1990/1210    
 
void* 
1992/0612    
malloc(uint size) 
1990/1210    
{ 
1992/0612    
	int pow; 
	Bucket *bp; 
1990/1210    
 
1992/0612    
	for(pow = 1; pow < MAX2SIZE; pow++) { 
		if(size <= (1<<pow)) 
			goto good; 
1990/1210    
	} 
 
1992/0612    
	return nil; 
good: 
	/* Allocate off this list */ 
	lock(&arena); 
	bp = arena.btab[pow]; 
	if(bp) { 
		arena.btab[pow] = bp->next; 
		arena.unlock(); 
1990/1210    
 
1992/0612    
		if(bp->magic != 0) 
			abort(); 
1990/1210    
 
1992/0612    
		bp->magic = MAGIC; 
1990/1210    
 
1992/0612    
		memset(bp->data, 0,  size); 
		return  bp->data; 
1990/1210    
	} 
1992/0612    
	unlock(&arena); 
	size = sizeof(Bucket)+(1<<pow); 
	bp = sbrk(size); 
	if((int)bp < 0) 
		return nil; 
1990/1210    
 
1992/0612    
	bp->size = pow; 
	bp->magic = MAGIC; 
1990/1210    
 
1992/0612    
	return bp->data; 
1990/1210    
} 
 
void 
1992/0612    
free(void *ptr) 
1990/1210    
{ 
1992/0612    
	Bucket *bp, **l; 
1990/1210    
 
1992/0612    
	/* Find the start of the structure */ 
	bp = (Bucket*)((uint)ptr - datoff); 
1990/1210    
 
1992/0612    
	if(bp->magic != MAGIC) 
		panic("free"); 
1990/1210    
 
1992/0612    
	bp->magic = 0; 
	lock(&arena); 
	l = &arena.btab[bp->size]; 
	bp->next = *l; 
	*l = bp; 
	unlock(&arena); 
1990/1210    
} 


source code copyright © 1990-2005 Lucent Technologies; see license
Plan 9 distribution
comments to russ cox (rsc@swtch.com)