feat: a pseudo shell environment for basic interacting and testing purpose
[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
6  * is to provide handy method to initialize & grow the heap as needed by
7  * upstream implementation.
8  *
9  * This is designed to be portable, so it can serve as syscalls to malloc/free
10  * in the c std lib.
11  *
12  * @version 0.2
13  * @date 2022-03-3
14  *
15  * @copyright Copyright (c) Lunaixsky 2022
16  *
17  */
18
19 #include <lunaix/mm/dmm.h>
20 #include <lunaix/mm/page.h>
21 #include <lunaix/mm/vmm.h>
22 #include <lunaix/status.h>
23
24 #include <lunaix/spike.h>
25 #include <lunaix/syscall.h>
26
27 __DEFINE_LXSYSCALL1(int, sbrk, size_t, size)
28 {
29     heap_context_t* uheap = &__current->mm.u_heap;
30     mutex_lock(&uheap->lock);
31     void* r = lxsbrk(uheap, size, PG_ALLOW_USER);
32     mutex_unlock(&uheap->lock);
33     return r;
34 }
35
36 __DEFINE_LXSYSCALL1(void*, brk, void*, addr)
37 {
38     heap_context_t* uheap = &__current->mm.u_heap;
39     mutex_lock(&uheap->lock);
40     int r = lxbrk(uheap, addr, PG_ALLOW_USER);
41     mutex_unlock(&uheap->lock);
42     return r;
43 }
44
45 int
46 dmm_init(heap_context_t* heap)
47 {
48     assert((uintptr_t)heap->start % BOUNDARY == 0);
49
50     heap->brk = heap->start;
51     mutex_init(&heap->lock);
52
53     int perm = PG_ALLOW_USER;
54     if (heap->brk >= KHEAP_START) {
55         perm = 0;
56     }
57
58     return vmm_set_mapping(
59              PD_REFERENCED, heap->brk, 0, PG_WRITE | perm, VMAP_NULL) != NULL;
60 }
61
62 int
63 lxbrk(heap_context_t* heap, void* addr, int user)
64 {
65     return -(lxsbrk(heap, addr - heap->brk, user) == (void*)-1);
66 }
67
68 void*
69 lxsbrk(heap_context_t* heap, size_t size, int user)
70 {
71     if (size == 0) {
72         return heap->brk;
73     }
74
75     void* current_brk = heap->brk;
76
77     // The upper bound of our next brk of heap given the size.
78     // This will be used to calculate the page we need to allocate.
79     void* next = current_brk + ROUNDUP(size, BOUNDARY);
80
81     // any invalid situations
82     if (next >= heap->max_addr || next < current_brk) {
83         __current->k_status = LXINVLDPTR;
84         return (void*)-1;
85     }
86
87     uintptr_t diff = PG_ALIGN(next) - PG_ALIGN(current_brk);
88     if (diff) {
89         // if next do require new pages to be mapped
90         for (size_t i = 0; i < diff; i += PG_SIZE) {
91             vmm_set_mapping(PD_REFERENCED,
92                             PG_ALIGN(current_brk) + PG_SIZE + i,
93                             0,
94                             PG_WRITE | user,
95                             VMAP_NULL);
96         }
97     }
98
99     heap->brk += size;
100     return current_brk;
101 }