fix: simplify code and start frame at 1 instead of 0 for the NULL

This commit is contained in:
starnakin 2024-10-15 01:31:53 +02:00
parent 9dc9002f00
commit 5f075a9090

View File

@ -6,13 +6,24 @@
#include "memory.h" #include "memory.h"
#include "utils.h" #include "utils.h"
#define MAX_FRAMES 1048319 #define MAX_FRAMES (0xC0000000 / PAGE_SIZE)
static uint32_t end_kernel; // WIP but it's useless now
static uint8_t frame_table[MAX_FRAMES]; static uint8_t frame_table[MAX_FRAMES];
static uint32_t remaining_frames = MAX_FRAMES; static uint32_t remaining_frames = MAX_FRAMES;
static int32_t find_next_block(size_t nb_frames)
{
for (uint32_t i = 1; i < MAX_FRAMES; i++) {
uint32_t j;
for (j = 0; frame_table[i + j] == 0 && j < nb_frames; j++)
;
if (j == nb_frames)
return i;
i += j;
}
return -1;
}
void *alloc_frames(size_t size) void *alloc_frames(size_t size)
{ {
const uint32_t nb_frames = CEIL(size, PAGE_SIZE); const uint32_t nb_frames = CEIL(size, PAGE_SIZE);
@ -20,35 +31,24 @@ void *alloc_frames(size_t size)
kprintf(KERN_CRIT "Not enough frames (max: %d)\n", MAX_FRAMES); kprintf(KERN_CRIT "Not enough frames (max: %d)\n", MAX_FRAMES);
return NULL; return NULL;
} }
size_t i = find_next_block(nb_frames);
size_t i = 0; if (i == -1) {
while (i < MAX_FRAMES) { kprintf(KERN_WARNING "Not enough frames available\n",
size_t free_frames = 1; MAX_FRAMES);
while (!frame_table[i + free_frames] && free_frames < nb_frames) return NULL;
free_frames++;
if (free_frames == nb_frames)
goto end;
if (!free_frames)
i++;
i += free_frames;
} }
end:
if (i != MAX_FRAMES) {
for (size_t j = 0; j < nb_frames; j++) for (size_t j = 0; j < nb_frames; j++)
frame_table[j + i] = 1; frame_table[j + i] = 1;
remaining_frames -= nb_frames; remaining_frames -= nb_frames;
return &end_kernel + i * PAGE_SIZE; return (void*)(i * PAGE_SIZE);
}
kprintf(KERN_WARNING "Not enough frames available\n", MAX_FRAMES);
return NULL;
} }
int free_frames(void *frame_ptr, size_t size) int free_frames(void *frame_ptr, size_t size)
{ {
const uint32_t nb_frames = CEIL(size, PAGE_SIZE); const uint32_t nb_frames = CEIL(size, PAGE_SIZE);
const uint32_t start = (frame_ptr - (void *)&end_kernel) / PAGE_SIZE; const uint32_t start = (uint32_t)frame_ptr / PAGE_SIZE;
if (start > MAX_FRAMES || frame_ptr < (void *)&end_kernel) { if (start > MAX_FRAMES) {
kprintf(KERN_WARNING "Address out of range\n"); kprintf(KERN_WARNING "Address out of range\n");
return -1; return -1;
} else if ((uint32_t)frame_ptr % PAGE_SIZE) { } else if ((uint32_t)frame_ptr % PAGE_SIZE) {