view cos/kernel/malloc.c @ 31:88590c42320f

Changed interrupt handler
author windel
date Tue, 10 Jan 2012 20:40:35 +0100
parents 7e3bdcb391dc
children 24ce177e01e8
line wrap: on
line source

#include "kernel.h"

// ================= Placement malloc:
// Assume here that nothing gets ever kfree'd. This makes it simple!

uint64_t placement_address = (uint64_t)&kernel_end;

void* kmalloc_int(uint64_t size)
{
   uint64_t tmp = placement_address;
   placement_address += size;
   return (void*)tmp;
}

void* kmalloc_aligned_int(uint64_t size)
{
   if ( (placement_address | 0xFFF) != 0 )
   {
      placement_address &= ~(0xFFF);
      placement_address += 0x1000;
   }
   uint64_t tmp = placement_address;
   placement_address += size;
   return (void*)tmp;
}


// ================= Other malloc
// TODO: move this to user space?

#define HEAP_MAGIC 0xc0ffee
#define HEAP_START 0x400000
#define HEAP_SIZE  0x200000
#define HEAP_INUSE 1
#define HEAP_FREE 0

typedef struct {
   uint64_t magic;
   uint64_t state;
   uint64_t size;
} heap_t;

/*
  malloc and free divide the chunks of memory present at the heap
  of the kernel into smaller parts.
  The heap is located at: 0x
*/

static heap_t* kernel_heap = (heap_t*) 0x400000; // 4 MB - 6 MB is heap
/* Allocates 'size' bytes and returns the pointer if succesfull.
   Kernelpanic in case of failure..
*/

void* kmalloc(uint64_t size) 
{
   return kmalloc_int(size);

   // Start at the beginning of our heap and search a free block:
   heap_t *current = kernel_heap;
   while (current->magic == HEAP_MAGIC)
   {
      if ((current->state == HEAP_FREE) && (current->size >= size))
      {
         // Mark block as used:
         current->state = HEAP_INUSE;

         // Insert a heap header if required:
         if (current->size > size + sizeof(heap_t) + 1)
         {
            // Calculate location of the inserted header:
            heap_t *newheader = (heap_t*) (((char*)current)+size+sizeof(heap_t));

            // Set the new header fields:
            newheader->size = current->size - size - sizeof(heap_t);
            newheader->state = HEAP_FREE;
            newheader->magic = HEAP_MAGIC;

            // Set the size of this block
            current->size = size; 
         }
         else
         {
            // We allocate this whole block
         }
         // Calculate the size of the block:
         char *address = ((char*)current)+sizeof(heap_t);
         return address;
         
      }
      // Goto next heap block:
      current = (heap_t*)(((char*) current) + current->size + sizeof(heap_t));
   }
   return 0x0;
}

void kfree(void* ptr) 
{
  printf("Free address %x\n", ptr);
}

void init_heap(void)
{
   // Initialize the kernel heap:
   kernel_heap->magic = HEAP_MAGIC;
   kernel_heap->state = HEAP_FREE;
   kernel_heap->size = HEAP_SIZE - sizeof(heap_t);
}