void mem_init(void) { struct free_arena_header *fp; int i; uint16_t *bios_free_mem = (uint16_t *)0x413; /* Initialize the head nodes */ fp = &__malloc_head[0]; for (i = 0 ; i < NHEAP ; i++) { fp->a.next = fp->a.prev = fp->next_free = fp->prev_free = fp; fp->a.attrs = ARENA_TYPE_HEAD | (i << ARENA_HEAP_POS); fp->a.tag = MALLOC_HEAD; fp++; } /* Initialize the main heap */ fp = (struct free_arena_header *)main_heap; fp->a.attrs = ARENA_TYPE_USED | (HEAP_MAIN << ARENA_HEAP_POS); ARENA_SIZE_SET(fp->a.attrs, sizeof main_heap); __inject_free_block(fp); /* Initialize the lowmem heap */ fp = (struct free_arena_header *)__lowmem_heap; fp->a.attrs = ARENA_TYPE_USED | (HEAP_LOWMEM << ARENA_HEAP_POS); ARENA_SIZE_SET(fp->a.attrs, (*bios_free_mem << 10) - (uintptr_t)fp); __inject_free_block(fp); }
static struct free_arena_header * __free_block(struct free_arena_header *ah) { struct free_arena_header *pah, *nah; struct free_arena_header *head = &__core_malloc_head[ARENA_HEAP_GET(ah->a.attrs)]; pah = ah->a.prev; nah = ah->a.next; if ( ARENA_TYPE_GET(pah->a.attrs) == ARENA_TYPE_FREE && (char *)pah+ARENA_SIZE_GET(pah->a.attrs) == (char *)ah ) { /* Coalesce into the previous block */ ARENA_SIZE_SET(pah->a.attrs, ARENA_SIZE_GET(pah->a.attrs) + ARENA_SIZE_GET(ah->a.attrs)); pah->a.next = nah; nah->a.prev = pah; #ifdef DEBUG_MALLOC ARENA_TYPE_SET(ah->a.attrs, ARENA_TYPE_DEAD); #endif ah = pah; pah = ah->a.prev; } else { /* Need to add this block to the free chain */ ARENA_TYPE_SET(ah->a.attrs, ARENA_TYPE_FREE); ah->a.tag = MALLOC_FREE; ah->next_free = head->next_free; ah->prev_free = head; head->next_free = ah; ah->next_free->prev_free = ah; } /* In either of the previous cases, we might be able to merge with the subsequent block... */ if ( ARENA_TYPE_GET(nah->a.attrs) == ARENA_TYPE_FREE && (char *)ah+ARENA_SIZE_GET(ah->a.attrs) == (char *)nah ) { ARENA_SIZE_SET(ah->a.attrs, ARENA_SIZE_GET(ah->a.attrs) + ARENA_SIZE_GET(nah->a.attrs)); /* Remove the old block from the chains */ nah->next_free->prev_free = nah->prev_free; nah->prev_free->next_free = nah->next_free; ah->a.next = nah->a.next; nah->a.next->a.prev = ah; #ifdef DEBUG_MALLOC ARENA_TYPE_SET(nah->a.attrs, ARENA_TYPE_DEAD); #endif } /* Return the block that contains the called block */ return ah; }