#include
#define MALLOC_MAGIC 0x6D92 /* must be < 0x8000 */
typedef struct _malloc
{
size_t size;
struct _malloc *next;
unsigned magic : 15;
unsigned used : 1;
} malloc_t;
static unsigned char *heap_bot,*heap_top;
void *kmalloc(size_t size)
{
size_t required;
malloc_t* n;
required=size+sizeof(malloc_t);
malloc_t* m=(malloc_t*)heap_bot;
if(m)
{
if(m->magic!=MALLOC_MAGIC)
{
KPRINTF("Corrupted Heap\n");
return NULL;
}
while(m)
{
if(m->used==1)
{
m=m->next;
continue;
}
if(m->size
{
m=m->next;
continue;
}
//we can allocate
n=m+sizeof(malloc_t)+size;
n->magic=MALLOC_MAGIC;
n->used=0;
n->next=m->next;
n->size=m->size-size-sizeof(malloc_t);
m->used=1;
m->next=n;
m->size=size;
return ((char*)m+sizeof(malloc_t));
}
}
KPRINTF("No Memory for allocation\n");
return NULL;
}
void kfree(void *p)
{
malloc_t *m;
m = (malloc_t *)((char *)p - sizeof(malloc_t));
if(((unsigned char*)p< heap_bot)||((unsigned char *)p>heap_top))
{
KPRINTF("Illegal memory area [%x]\n", (unsigned int)p);
return;
}
//so p is within our limit
if(m->magic!=MALLOC_MAGIC)
{
KPRINTF("*** Bad Magic / corrupted heap\n");
return;
}
if(m->used==0)
{
//unused memory
KPRINTF("***Trying to free unused Unused memory\n");
return;
}
//if we reached here means we are to mark the block as free
m->used=0;
//try unfragment the heap
m=(malloc_t*)heap_bot;
for(; m!=NULL; m=m->next)
{
while(!m->used && m->next != NULL && !m->next->used)
{
/* resize this block */
m->size += sizeof(malloc_t) + m->next->size;
/* merge with next block */
m->next = m->next->next;
}
}
}
void kmemdump()
{
unsigned blks_used = 0, blks_free = 0;
size_t bytes_used = 0, bytes_free = 0;
malloc_t *m;
int total;
KPRINTF("===============================================\n");
for(m = (malloc_t *)heap_bot; m != NULL; m = m->next)
{
KPRINTF("blk %x: %d bytes", (unsigned int)m, m->size);
if(m->used)
{
blks_used++;
bytes_used += m->size;
KPRINTF(" used\n");
}
else
{
blks_free++;
bytes_free += m->size;
KPRINTF(" free\n");
}
}
KPRINTF("blks: %d used, %d free, %d total\n", blks_used , blks_free, blks_used + blks_free);
KPRINTF("bytes: %d used, %d free, %d total\n", bytes_used, bytes_free, bytes_used + bytes_free);
total = (bytes_used + bytes_free) + (blks_used + blks_free) * sizeof(malloc_t);
if(total != heap_top - heap_bot)
KPRINTF("*** some heap memory is not accounted for\n");
KPRINTF("===============================================\n");
}
static void mem_init()
{
heap_bot=(unsigned char*)&kernelEnd;
heap_top=(unsigned char*)(bootInfo.memUpper*1024);
KPRINTF("Memory :%x --- %x\n", heap_bot, heap_top);
if(heap_top<=heap_bot)
{
KPRINTF("Memory Error\n");
halt();
}
malloc_t* m=(malloc_t*)heap_bot;
//claim all the available memory after kernel end.
m->magic= MALLOC_MAGIC;
m->next=NULL; //nothing after this block
m->size=heap_top-heap_bot-sizeof(malloc_t); //total memory available
m->used=0; //not used free/available
}
INITFUNC(mem_init, INIT_MEM);
阅读(1494) | 评论(0) | 转发(0) |