matos/core/alloc.c

99 lines
3.0 KiB
C
Raw Normal View History

2019-04-11 22:34:20 +02:00
#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 *slubArray[SLUB_SIZE];
int initSlabDesc(struct slabDesc **desc, size_t size);
static int formatPage(struct slabDesc *desc, size_t size);
2019-04-11 22:34:20 +02:00
int initSlab(void)
{
uint start = log2(sizeof(void *));
for (uint i = start; i < SLUB_SIZE; i++) {
if (initSlabDesc(&slubArray[i - start], 1U << i))
return ENOMEM;
}
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)
2019-04-11 22:34:20 +02:00
{
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;
}
uint slubIdx = 0;
while (size > slubArray[slubIdx]->size) {
slubIdx++;
}
struct slabDesc *slab;
int slabIdx;
list_foreach(slubArray[slubIdx], 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(slubArray[slubIdx], slab, slabIdx)) {
struct slabDesc *newSlab;
initSlabDesc(&newSlab, slab->size);
list_add_head(slubArray[slubIdx], newSlab);
return allocFromSlab(newSlab);
}
return NULL;
}