plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

mem.c (1172B)


      1 #include <u.h>
      2 #include <libc.h>
      3 #include <venti.h>
      4 
      5 enum {
      6 	IdealAlignment = 32,
      7 	ChunkSize 	= 128*1024
      8 };
      9 
     10 
     11 void
     12 vtfree(void *p)
     13 {
     14 	if(p == 0)
     15 		return;
     16 	free(p);
     17 }
     18 
     19 void *
     20 vtmalloc(int size)
     21 {
     22 	void *p;
     23 
     24 	p = malloc(size);
     25 	if(p == 0)
     26 		sysfatal("vtmalloc: out of memory");
     27 	setmalloctag(p, getcallerpc(&size));
     28 	return p;
     29 }
     30 
     31 void *
     32 vtmallocz(int size)
     33 {
     34 	void *p = vtmalloc(size);
     35 	memset(p, 0, size);
     36 	setmalloctag(p, getcallerpc(&size));
     37 	return p;
     38 }
     39 
     40 void *
     41 vtrealloc(void *p, int size)
     42 {
     43 	if(p == nil)
     44 		return vtmalloc(size);
     45 	p = realloc(p, size);
     46 	if(p == 0)
     47 		sysfatal("vtMemRealloc: out of memory");
     48 	setrealloctag(p, getcallerpc(&size));
     49 	return p;
     50 }
     51 
     52 void *
     53 vtbrk(int n)
     54 {
     55 	static Lock lk;
     56 	static uchar *buf;
     57 	static int nbuf, nchunk;
     58 	int align, pad;
     59 	void *p;
     60 
     61 	if(n >= IdealAlignment)
     62 		align = IdealAlignment;
     63 	else if(n > 8)
     64 		align = 8;
     65 	else
     66 		align = 4;
     67 
     68 	lock(&lk);
     69 	pad = (align - (uintptr)buf) & (align-1);
     70 	if(n + pad > nbuf) {
     71 		buf = vtmallocz(ChunkSize);
     72 		nbuf = ChunkSize;
     73 		pad = (align - (uintptr)buf) & (align-1);
     74 		nchunk++;
     75 	}
     76 
     77 	assert(n + pad <= nbuf);
     78 
     79 	p = buf + pad;
     80 	buf += pad + n;
     81 	nbuf -= pad + n;
     82 	unlock(&lk);
     83 
     84 	return p;
     85 }