comparison cos/kernel/malloc.c @ 24:d8627924d40d

Split up in more files and reboot command
author windel
date Fri, 02 Dec 2011 14:00:02 +0100
parents
children d3c4bf3720a3
comparison
equal deleted inserted replaced
23:5dd47d6eebac 24:d8627924d40d
1 #include "kernel.h"
2
3 #define HEAP_MAGIC 0xc0ffee
4 #define HEAP_START 0x400000
5 #define HEAP_SIZE 0x200000
6 #define HEAP_INUSE 1
7 #define HEAP_FREE 0
8
9 typedef struct {
10 uint64_t magic;
11 uint64_t state;
12 uint64_t size;
13 } heap_t;
14
15 /*
16 malloc and free divide the chunks of memory present at the heap
17 of the kernel into smaller parts.
18 The heap is located at: 0x
19 */
20 static heap_t* kernel_heap = (heap_t*) 0x400000; // 4 MB - 6 MB is heap
21 /* Allocates 'size' bytes and returns the pointer if succesfull.
22 Kernelpanic in case of failure..
23 */
24
25 void* kmalloc(uint64_t size) {
26 // printf("Malloc %d bytes\n", size);
27
28 // Start at the beginning of our heap and search a free block:
29 heap_t *current = kernel_heap;
30 while (current->magic == HEAP_MAGIC)
31 {
32 if ((current->state == HEAP_FREE) && (current->size >= size))
33 {
34 // Mark block as used:
35 current->state = HEAP_INUSE;
36
37 // Insert a heap header if required:
38 if (current->size > size + sizeof(heap_t) + 1)
39 {
40 // Calculate location of the inserted header:
41 heap_t *newheader = (heap_t*) (((char*)current)+size+sizeof(heap_t));
42
43 // Set the new header fields:
44 newheader->size = current->size - size - sizeof(heap_t);
45 newheader->state = HEAP_FREE;
46 newheader->magic = HEAP_MAGIC;
47
48 // Set the size of this block
49 current->size = size;
50 }
51 else
52 {
53 // We allocate this whole block
54 }
55 // Calculate the size of the block:
56 char *address = ((char*)current)+sizeof(heap_t);
57 return address;
58
59 }
60 // Goto next heap block:
61 current = (heap_t*)(((char*) current) + current->size + sizeof(heap_t));
62 }
63 return 0x0;
64 }
65
66 void kfree(void* ptr) {
67 printf("Free address %x\n", ptr);
68 }
69
70 void init_heap(void)
71 {
72 // Initialize the kernel heap:
73 kernel_heap->magic = HEAP_MAGIC;
74 kernel_heap->state = HEAP_FREE;
75 kernel_heap->size = HEAP_SIZE - sizeof(heap_t);
76 }