#define pr_fmt(fmt) "[alloc]: " fmt //#define DEBUG #include "alloc.h" #include "errno.h" #include "list.h" #include "math.h" #include "mem.h" #include "vga.h" // Slab will contains object from sizeof(void *) to PAGE_SIZE/2 by pow2 #define SLUB_SIZE (PAGE_SHIFT - 1) struct slabDesc *slub; int initSlabDesc(struct slabDesc **desc, size_t size); static int formatPage(struct slabDesc *desc, size_t size); int initSlab(void) { uint start = log2(sizeof(void *)); list_init(slub); for (uint i = start; i < SLUB_SIZE; i++) { struct slabDesc *slab; if (initSlabDesc(&slab, 1U << i)) return ENOMEM; list_add_tail(slub, slab); } return 0; } int initSlabDesc(struct slabDesc **desc, size_t size) { if (size > PAGE_SIZE) return ENOENT; paddr_t alloc = allocPhyPage(); if (alloc == (paddr_t)NULL) return ENOMEM; if (pageMap((vaddr_t)alloc, alloc, PAGING_MEM_WRITE)) { return ENOMEM; } *desc = (struct slabDesc *)alloc; list_singleton(*desc, *desc); (*desc)->page = (vaddr_t)alloc; (*desc)->full = 0; (*desc)->freeEl = (char *)(*desc) + sizeof(struct slabDesc); (*desc)->size = size; pr_devel("got page %d for size %d first %d", alloc, size, (*desc)->freeEl); return formatPage((*desc), size); } static int formatPage(struct slabDesc *desc, size_t size) { char *cur = (char *)desc + sizeof(struct slabDesc); ulong i; for (i = 0; i < ((PAGE_SIZE - sizeof(struct slabDesc)) / size - 1); i++) { *((vaddr_t *)cur) = (vaddr_t)cur + size; cur += size; } *((vaddr_t *)cur) = (vaddr_t)NULL; pr_devel("last at %d allocated %d\n", cur, i + 1); return 0; } static void *allocFromSlab(struct slabDesc *slab) { vaddr_t *next = slab->freeEl; if (*next == (vaddr_t)NULL) { pr_devel("Slab %d full\n", slab); slab->full = 1; } else { slab->freeEl = (void *)(*next); } return (void *)next; } void *malloc(size_t size) { if (size > (1U << SLUB_SIZE)) { printf("implement malloc for big size\n"); return NULL; } struct slabDesc *slubEntry; uint slubIdx = 0; list_foreach(slub, slubEntry, slubIdx) { if(size <= slubEntry->size) break; } struct slabDesc *slab; int slabIdx; list_foreach(slubEntry, slab, slabIdx) { if (!slab->full) { pr_devel("found place in slub %d at idx %d \n", slubIdx, slabIdx); return allocFromSlab(slab); } } if (!list_foreach_early_break(slubEntry, slab, slabIdx)) { struct slabDesc *newSlab; initSlabDesc(&newSlab, slab->size); list_add_head(slubEntry, newSlab); return allocFromSlab(newSlab); } return NULL; }