Merge branch 'master' into signal-dev
[lunaix-os.git] / lunaix-os / kernel / mm / kalloc.c
index 91905b4139cb2ee4933c07ddb7f4f5b37e1c93ef..e970c1d5ac96ad399102a28b7deca8818cff939b 100644 (file)
@@ -57,27 +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() {
-    heap_context_t* kheap = &__current->mm.k_heap;
-    kheap->start = &__kernel_heap_start;
-    kheap->brk = NULL;
-    kheap->max_addr = (void*)KSTACK_START;
+    kheap.start = &__kernel_heap_start;
+    kheap.brk = NULL;
+    kheap.max_addr = (void*)KSTACK_START;
 
-    if (!dmm_init(kheap)) {
+    if (!dmm_init(&kheap)) {
         return 0;
     }
 
-    SW(kheap->start, PACK(4, M_ALLOCATED));
-    SW(kheap->start + WSIZE, PACK(0, M_ALLOCATED));
-    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(kheap, HEAP_INIT_SIZE) != NULL;
+    return lx_grow_heap(&kheap, HEAP_INIT_SIZE) != NULL;
 }
 
 void*
 lxmalloc(size_t size) {
-    return lx_malloc_internal(&__current->mm.k_heap, size);
+    mutex_lock(&kheap.lock);
+    void* r = lx_malloc_internal(&kheap, size);
+    mutex_unlock(&kheap.lock);
+
+    return r;
 }
 
 void*
@@ -102,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);
@@ -122,6 +128,8 @@ lxfree(void* ptr) {
     SW(next_hdr, LW(next_hdr) | M_PREV_FREE);
     
     coalesce(chunk_ptr);
+
+    mutex_unlock(&kheap.lock);
 }
 
 
@@ -241,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);