4f564594789aa0e67df22697b2072ecf490b23e3
[cortex-from-scratch] / mm.c
1 #include <stdbool.h>
2 #include <stddef.h>
3 #include <stdint.h>
4 #include <stm32.h>
5 #include <mmap.h>
6
7 /* TOTAL SRAM MEMORY: 64kB 
8  * 64 chunks of 1kB 
9  * 128 chunks of 512 bytes
10  * SIMPLE BITMAP IMPLEMENTATION
11  * */
12
13 #define CHUNKS  128
14 #define FREE    0x00
15 #define ALLOC   0x01
16
17 #define BASE 0x20000400
18
19 #define SET_SIZE(s)     (s << 8)
20 #define SET_FLAGS(f)    (f << 24)
21 #define IS_ALLOC(c)     ((c >> 24) & 0x0F )
22 #define PADDR(i)        (0x20000400 + (i * 0x200))
23 #define I_OFFSET(p)     ((p  - 0x20000400))
24
25 uint32_t chunk[CHUNKS];
26
27 /* 
28  * | FLAGS | SIZE   | RESERVED  |
29  * | 0x00  | 0x0000 | 0x00      |
30  *
31  * */
32
33
34 void mm_init() {
35
36         // interrupt vector
37         chunk[0] = SET_SIZE(96) | SET_FLAGS(ALLOC); 
38
39         // test
40         /* uart_puts("ALLOC:\n");
41         int * p = mm_alloc(100);
42         *p = 0x12345678;
43
44         addrtohex(p);
45         addrtohex(*p);
46
47         uart_puts("FREE:\n");
48
49         int * p2 = mm_alloc(100);
50         *p2 = 0xFFFFAAAA;
51         addrtohex(p2);
52         addrtohex(*p2);
53
54         free(p);
55         free(p2); */
56 }
57
58  void test_memory(uint32_t * ptr) {
59
60         *ptr = 0xEEEEEEEE;
61         for (int i = 0; i < 100; i++) {
62                 ptr++;
63                 *ptr = 0xEEEEEEEE;
64         }
65
66
67
68
69 void * mm_alloc(size_t size) { // in bytes
70
71         if (size > 512) {
72                 uart_puts("SYSERROR: WE CAN'T ALLOCATE THAT MUCH!\n");
73                 return NULL; 
74         }
75
76         /* check which chunk is free */
77         for (int i = 1; i < CHUNKS; i++) {
78                 if (!IS_ALLOC(chunk[i])) {
79                         chunk[i] = SET_SIZE(size) | SET_FLAGS(ALLOC);
80                         return (void *) PADDR(i);
81                 }
82         }
83         
84         uart_puts("SYSERROR: OUT OF MEMORY\n");
85         return NULL;
86 }
87
88 void free(void *ptr) {
89
90         uint32_t index = (uint32_t) I_OFFSET(ptr) / 0x200;
91
92         uint32_t tmp = chunk[index];
93         if (!IS_ALLOC(tmp))
94                 uart_puts("SYSERROR: ALREADY FREED!\n");
95
96         else if(index < CHUNKS) {
97                 chunk[index] = SET_FLAGS(FREE) | SET_SIZE(0);
98         }
99                 
100 }
101