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