-#define M_ALLOCATED 0x1
-#define M_PREV_FREE 0x2
-
-#define M_NOT_ALLOCATED 0x0
-#define M_PREV_ALLOCATED 0x0
-
-#define CHUNK_S(header) ((header) & ~0x3)
-#define CHUNK_PF(header) ((header)&M_PREV_FREE)
-#define CHUNK_A(header) ((header)&M_ALLOCATED)
-
-#define PACK(size, flags) (((size) & ~0x3) | (flags))
-
-#define SW(p, w) (*((uint32_t*)(p)) = w)
-#define LW(p) (*((uint32_t*)(p)))
-
-#define HPTR(bp) ((uint32_t*)(bp)-1)
-#define BPTR(bp) ((uint8_t*)(bp) + WSIZE)
-#define FPTR(hp, size) ((uint32_t*)(hp + size - WSIZE))
-#define NEXT_CHK(hp) ((uint8_t*)(hp) + CHUNK_S(LW(hp)))
-
-#define BOUNDARY 4
-#define WSIZE 4
-
-extern uint8_t __kernel_heap_start;
-
-void* current_heap_top = NULL;
-
-void*
-coalesce(uint8_t* chunk_ptr);
-
-void*
-lx_grow_heap(size_t sz);
-
-void place_chunk(uint8_t* ptr, size_t size);
-
-int
-dmm_init()
-{
- assert((uintptr_t)&__kernel_heap_start % BOUNDARY == 0);
-
- current_heap_top = &__kernel_heap_start;
- uint8_t* heap_start = &__kernel_heap_start;
-
- vmm_alloc_page(current_heap_top, PG_PREM_RW);
-
- SW(heap_start, PACK(4, M_ALLOCATED));
- SW(heap_start + WSIZE, PACK(0, M_ALLOCATED));
- current_heap_top += WSIZE;
-
- return lx_grow_heap(HEAP_INIT_SIZE) != NULL;
-}
-
-int
-lxsbrk(void* addr)
-{
- return lxbrk(addr - current_heap_top) != NULL;
-}
-
-void*
-lxbrk(size_t size)
-{
- if (size == 0) {
- return current_heap_top;
- }
-
- // plus WSIZE is the overhead for epilogue marker
- size += WSIZE;
- void* next = current_heap_top + ROUNDUP((uintptr_t)size, WSIZE);
-
- if ((uintptr_t)next >= K_STACK_START) {
- return NULL;
- }
-
- // Check the invariant
- assert(size % BOUNDARY == 0)
-
- uintptr_t heap_top_pg = PG_ALIGN(current_heap_top);
- if (heap_top_pg != PG_ALIGN(next))
- {
- // if next do require new pages to be allocated
- if (!vmm_alloc_pages((void*)(heap_top_pg + PG_SIZE), ROUNDUP(size, PG_SIZE), PG_PREM_RW)) {
- return NULL;
- }
-
- }
-
- void* old = current_heap_top;
- current_heap_top = next - WSIZE;
- return old;
-}
-
-void*
-lx_grow_heap(size_t sz) {
- void* start;
-
- sz = ROUNDUP(sz, BOUNDARY);
- if (!(start = lxbrk(sz))) {
- return NULL;
- }
-
- uint32_t old_marker = *((uint32_t*)start);
- uint32_t free_hdr = PACK(sz, CHUNK_PF(old_marker));
- SW(start, free_hdr);
- SW(FPTR(start, sz), free_hdr);
- SW(NEXT_CHK(start), PACK(0, M_ALLOCATED | M_PREV_FREE));
-
- return coalesce(start);
-}
-
-void*
-lx_malloc(size_t size)