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.
9 * This is designed to be portable, so it can serve as syscalls to malloc/free
15 * @copyright Copyright (c) Lunaixsky 2022
19 #include <lunaix/mm/dmm.h>
20 #include <lunaix/mm/page.h>
21 #include <lunaix/mm/vmm.h>
22 #include <lunaix/status.h>
24 #include <lunaix/spike.h>
25 #include <lunaix/syscall.h>
27 extern void __kernel_heap_start;
29 __DEFINE_LXSYSCALL1(int, sbrk, size_t, size)
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);
38 __DEFINE_LXSYSCALL1(void*, brk, void*, addr)
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);
48 dmm_init(heap_context_t* heap)
50 assert((uintptr_t)heap->start % BOUNDARY == 0);
52 heap->brk = heap->start;
53 mutex_init(&heap->lock);
55 int perm = PG_ALLOW_USER;
56 if (heap->brk >= &__kernel_heap_start) {
60 return vmm_set_mapping(
61 PD_REFERENCED, heap->brk, 0, PG_WRITE | perm, VMAP_NULL) != NULL;
65 lxbrk(heap_context_t* heap, void* addr, int user)
67 return -(lxsbrk(heap, addr - heap->brk, user) == (void*)-1);
71 lxsbrk(heap_context_t* heap, size_t size, int user)
77 void* current_brk = heap->brk;
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);
83 // any invalid situations
84 if (next >= heap->max_addr || next < current_brk) {
85 __current->k_status = LXINVLDPTR;
89 uintptr_t diff = PG_ALIGN(next) - PG_ALIGN(current_brk);
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,