From addf96aae736aacb8ff3a34344173f6362bb5531 Mon Sep 17 00:00:00 2001 From: Michael Shaw Date: Thu, 20 Apr 2023 21:43:43 -0400 Subject: [PATCH] mem: fix bug with slab_create before this would overwrite into the next region, which would cause an error at `buddy_alloc_helper` as the region overridden was the `len` field of a `struct buddy_free_list` --- Makefile | 2 +- mem/buddy.c | 2 +- mem/slab.c | 28 +++++++++++++++------------- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index a20392e..bc2bc64 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ define DEFAULT_VAR = endef # User controllable CFLAGS. -CFLAGS ?= -g -O2 -pipe -Wall -Wextra +CFLAGS ?= -g -O0 -pipe -Wall -Wextra # User controllable linker flags. We set none by default. LDFLAGS ?= diff --git a/mem/buddy.c b/mem/buddy.c index 5bbebef..6eac097 100644 --- a/mem/buddy.c +++ b/mem/buddy.c @@ -108,7 +108,7 @@ static paddr_t buddy_alloc_helper(struct buddy_region_header *head, size_t size) struct buddy_free_list *new = (struct buddy_free_list *)((uintptr_t)flist + flist->len / 2); new->next = flist->next; new->prev = flist; - new->len = flist->len >> 1; + new->len = MAX(flist->len >> 1, 0x1000ull); new->depth = flist->depth + 1; if (new->next != NULL) diff --git a/mem/slab.c b/mem/slab.c index c19fa67..76895f4 100644 --- a/mem/slab.c +++ b/mem/slab.c @@ -4,6 +4,7 @@ #include #define SLAB_MIN_COUNT 64 +#define SLAB_ALIGN 7 size_t slab_sizes[] = { 16, 32, 64, 128, 256, 512, 1024, 2048 }; struct slab *slab_cache[ARRAY_SIZE(slab_sizes)]; @@ -14,7 +15,7 @@ struct kmap_entry *kmem_map = NULL; static inline void slab_range(struct slab *slab, uintptr_t *o_start, uintptr_t *o_end) { uintptr_t sslab = (uintptr_t)slab; - sslab = (sslab | 7) + 1; + sslab = (sslab | SLAB_ALIGN) + 1; *o_start = sslab; *o_end = sslab + (slab->size * slab->num); @@ -34,24 +35,25 @@ struct slab *slab_create(size_t size) return NULL; /* slab area start position */ - size_t start = (sizeof(struct slab) | 7) + 1; - ret->nextfree = (uintptr_t *)((uintptr_t)ret + start); + uintptr_t aret = (uintptr_t)ret; + uintptr_t start = (uintptr_t)ret + sizeof(struct slab); + + start |= SLAB_ALIGN; + start += 1; + + ret->num = (((aret + asize) - start) / size); ret->size = size; - ret->num = (asize - start) / size; ret->next = NULL; ret->prev = NULL; + ret->nextfree = (uintptr_t *)start; + ret->free = ret->num; - uintptr_t *ptr = ret->nextfree; - while (ptr != NULL) { - if (ptr > (uintptr_t *)((uintptr_t)ret + asize - size)) { - *ptr = (uintptr_t)NULL; - ptr = NULL; - } else { - *ptr = (uintptr_t)ptr + size; - ptr = (uintptr_t *)*ptr; - } + for(size_t i = 0; i < ret->num - 1; i++) { + *(uintptr_t *)(start + (i * size)) = start + ((i + 1) * size); } + *(uintptr_t *)(start + ((ret->num - 1) * size)) = 0; + return ret; }