refactor: vmm_set_map has option to ignore existed mapping.
[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 extern void __kernel_heap_start;
28
29 __DEFINE_LXSYSCALL1(int, sbrk, size_t, size)
30 {
31     heap_context_t* uheap = &__current->mm.u_heap;
32     mutex_lock(&uheap->lock);
33     void* r = lxsbrk(uheap, size, PG_ALLOW_USER);
34     mutex_unlock(&uheap->lock);
35     return r;
36 }
37
38 __DEFINE_LXSYSCALL1(void*, brk, void*, addr)
39 {
40     heap_context_t* uheap = &__current->mm.u_heap;
41     mutex_lock(&uheap->lock);
42     int r = lxbrk(uheap, addr, PG_ALLOW_USER);
43     mutex_unlock(&uheap->lock);
44     return r;
45 }
46
47 int
48 dmm_init(heap_context_t* heap)
49 {
50     assert((uintptr_t)heap->start % BOUNDARY == 0);
51
52     heap->brk = heap->start;
53     mutex_init(&heap->lock);
54
55     int perm = PG_ALLOW_USER;
56     if (heap->brk >= &__kernel_heap_start) {
57         perm = 0;
58     }
59
60     return vmm_set_mapping(
61              PD_REFERENCED, heap->brk, 0, PG_WRITE | perm, VMAP_NULL) != NULL;
62 }
63
64 int
65 lxbrk(heap_context_t* heap, void* addr, int user)
66 {
67     return -(lxsbrk(heap, addr - heap->brk, user) == (void*)-1);
68 }
69
70 void*
71 lxsbrk(heap_context_t* heap, size_t size, int user)
72 {
73     if (size == 0) {
74         return heap->brk;
75     }
76
77     void* current_brk = heap->brk;
78
79     // The upper bound of our next brk of heap given the size.
80     // This will be used to calculate the page we need to allocate.
81     void* next = current_brk + ROUNDUP(size, BOUNDARY);
82
83     // any invalid situations
84     if (next >= heap->max_addr || next < current_brk) {
85         __current->k_status = LXINVLDPTR;
86         return (void*)-1;
87     }
88
89     uintptr_t diff = PG_ALIGN(next) - PG_ALIGN(current_brk);
90     if (diff) {
91         // if next do require new pages to be mapped
92         for (size_t i = 0; i < diff; i += PG_SIZE) {
93             vmm_set_mapping(PD_REFERENCED,
94                             PG_ALIGN(current_brk) + PG_SIZE + i,
95                             0,
96                             PG_WRITE | user,
97                             VMAP_NULL);
98         }
99     }
100
101     heap->brk += size;
102     return current_brk;
103 }