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 __DEFINE_LXSYSCALL1(int, sbrk, size_t, size)
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);
36 __DEFINE_LXSYSCALL1(void*, brk, void*, addr)
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);
46 dmm_init(heap_context_t* heap)
48 assert((uintptr_t)heap->start % BOUNDARY == 0);
50 heap->brk = heap->start;
51 mutex_init(&heap->lock);
53 int perm = PG_ALLOW_USER;
54 if (heap->brk >= KHEAP_START) {
58 return vmm_set_mapping(
59 PD_REFERENCED, heap->brk, 0, PG_WRITE | perm, VMAP_NULL) != NULL;
63 lxbrk(heap_context_t* heap, void* addr, int user)
65 return -(lxsbrk(heap, addr - heap->brk, user) == (void*)-1);
69 lxsbrk(heap_context_t* heap, size_t size, int user)
75 void* current_brk = heap->brk;
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);
81 // any invalid situations
82 if (next >= heap->max_addr || next < current_brk) {
83 __current->k_status = LXINVLDPTR;
87 uintptr_t diff = PG_ALIGN(next) - PG_ALIGN(current_brk);
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,