ae899086d79fcd00f91bb1eb6faca4b8aa04dc04
[lunaix-os.git] / lunaix-os / kernel / mm / dmm.c
1 /**
2  * @file dmm.c
3  * @author Lunaixsky
4  * @brief Dynamic memory manager for heap. This design do not incorporate any\
5  * specific implementation of malloc family. The main purpose of this routines is to
6  * provide handy method to initialize & grow the heap as needed by upstream implementation.
7  * 
8  * This is designed to be portable, so it can serve as syscalls to malloc/free in the c std lib. 
9  * 
10  * @version 0.2
11  * @date 2022-03-3
12  *
13  * @copyright Copyright (c) Lunaixsky 2022
14  *
15  */
16
17 #include <lunaix/mm/dmm.h>
18 #include <lunaix/mm/vmm.h>
19 #include <lunaix/mm/page.h>
20
21 #include <lunaix/spike.h>
22
23 int
24 dmm_init(heap_context_t* heap)
25 {
26     assert((uintptr_t)heap->start % BOUNDARY == 0);
27
28     heap->brk = heap->start;
29
30     return vmm_alloc_page(heap->brk, PG_PREM_RW) != NULL;
31 }
32
33 int
34 lxsbrk(heap_context_t* heap, void* addr)
35 {
36     return lxbrk(heap, addr - heap->brk) != NULL;
37 }
38
39 void*
40 lxbrk(heap_context_t* heap, size_t size)
41 {
42     if (size == 0) {
43         return heap->brk;
44     }
45
46     void* current_brk = heap->brk;
47
48     // The upper bound of our next brk of heap given the size.
49     // This will be used to calculate the page we need to allocate.
50     void* next = current_brk + ROUNDUP(size, BOUNDARY);
51
52     // any invalid situations
53     if (next >= heap->max_addr || next < current_brk) {
54         return NULL;
55     }
56
57     uintptr_t diff = PG_ALIGN(next) - PG_ALIGN(current_brk);
58     if (diff) {
59         // if next do require new pages to be allocated
60         if (!vmm_alloc_pages((void*)(PG_ALIGN(current_brk) + PG_SIZE),
61                              diff,
62                              PG_PREM_RW)) {
63             // for debugging
64             assert_msg(0, "unable to brk");
65             return NULL;
66         }
67     }
68
69     heap->brk += size;
70     return current_brk;
71 }