X-Git-Url: https://scm.lunaixsky.com/lunaix-os.git/blobdiff_plain/a0655e5d30f3cdc73b1aaaa4825d8fae9f92ce4a..509574b18a3373030cd0d7b979499499ff06dd9b:/lunaix-os/kernel/mm/kalloc.c?ds=sidebyside diff --git a/lunaix-os/kernel/mm/kalloc.c b/lunaix-os/kernel/mm/kalloc.c index 16c1d82..e970c1d 100644 --- a/lunaix-os/kernel/mm/kalloc.c +++ b/lunaix-os/kernel/mm/kalloc.c @@ -23,9 +23,6 @@ extern uint8_t __kernel_heap_start; -// FIXME: This should go to PCB once we're started to support multitasking -static heap_context_t __kalloc_kheap; - void* lx_malloc_internal(heap_context_t* heap, size_t size); @@ -60,26 +57,32 @@ lx_grow_heap(heap_context_t* heap, size_t sz); Note: the brk always point to the beginning of epilogue. */ +static heap_context_t kheap; + int kalloc_init() { - __kalloc_kheap.start = &__kernel_heap_start; - __kalloc_kheap.brk = NULL; - __kalloc_kheap.max_addr = (void*)K_STACK_START; + kheap.start = &__kernel_heap_start; + kheap.brk = NULL; + kheap.max_addr = (void*)KSTACK_START; - if (!dmm_init(&__kalloc_kheap)) { + if (!dmm_init(&kheap)) { return 0; } - SW(__kalloc_kheap.start, PACK(4, M_ALLOCATED)); - SW(__kalloc_kheap.start + WSIZE, PACK(0, M_ALLOCATED)); - __kalloc_kheap.brk += WSIZE; + SW(kheap.start, PACK(4, M_ALLOCATED)); + SW(kheap.start + WSIZE, PACK(0, M_ALLOCATED)); + kheap.brk += WSIZE; - return lx_grow_heap(&__kalloc_kheap, HEAP_INIT_SIZE) != NULL; + return lx_grow_heap(&kheap, HEAP_INIT_SIZE) != NULL; } void* lxmalloc(size_t size) { - return lx_malloc_internal(&__kalloc_kheap, size); + mutex_lock(&kheap.lock); + void* r = lx_malloc_internal(&kheap, size); + mutex_unlock(&kheap.lock); + + return r; } void* @@ -104,6 +107,7 @@ lxfree(void* ptr) { if (!ptr) { return; } + mutex_lock(&kheap.lock); uint8_t* chunk_ptr = (uint8_t*)ptr - WSIZE; uint32_t hdr = LW(chunk_ptr); @@ -124,6 +128,8 @@ lxfree(void* ptr) { SW(next_hdr, LW(next_hdr) | M_PREV_FREE); coalesce(chunk_ptr); + + mutex_unlock(&kheap.lock); } @@ -243,7 +249,7 @@ lx_grow_heap(heap_context_t* heap, size_t sz) void* start; // The "+ WSIZE" capture the overhead for epilogue marker - if (!(start = lxbrk(heap, sz + WSIZE))) { + if (!(start = lxsbrk(heap, sz + WSIZE))) { return NULL; } sz = ROUNDUP(sz, BOUNDARY);