2024-09-19 11:04:35 -04:00
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stddef.h>
|
|
|
|
#include <stdint.h>
|
|
|
|
|
|
|
|
#include "kprintf.h"
|
|
|
|
#include "memory.h"
|
|
|
|
|
|
|
|
#define MAX_FRAMES 1048319
|
|
|
|
#define CEIL(x, y) (((x) + (y) - 1) / (y))
|
|
|
|
#define GET_FRAME(i) (frame_table[i / 8] & (1 << (i % 8)))
|
|
|
|
#define SET_FRAME(i, used) \
|
|
|
|
do { \
|
|
|
|
if (used) \
|
|
|
|
frame_table[i / 8] |= (1 << (i % 8)); \
|
|
|
|
else \
|
|
|
|
frame_table[i / 8] &= ~(1 << (i % 8)); \
|
|
|
|
} while (0)
|
|
|
|
|
|
|
|
extern uint32_t end_kernel;
|
|
|
|
|
|
|
|
static uint8_t frame_table[CEIL(MAX_FRAMES, 8)];
|
2024-09-19 11:39:14 -04:00
|
|
|
static uint32_t remaining_frames = MAX_FRAMES;
|
2024-09-19 11:04:35 -04:00
|
|
|
|
2024-09-19 11:39:14 -04:00
|
|
|
void *kalloc_frame(uint32_t nb_frames)
|
2024-09-19 11:04:35 -04:00
|
|
|
{
|
2024-09-19 11:39:14 -04:00
|
|
|
if (nb_frames > remaining_frames) {
|
2024-09-20 06:40:36 -04:00
|
|
|
kprintf(KERN_CRIT "Not enough frames (max: %d)\n", MAX_FRAMES);
|
2024-09-19 11:39:14 -04:00
|
|
|
return NULL;
|
|
|
|
}
|
2024-09-19 11:04:35 -04:00
|
|
|
size_t i = 0;
|
|
|
|
while (i < MAX_FRAMES) {
|
|
|
|
size_t free_frames = 1;
|
2024-09-19 11:16:45 -04:00
|
|
|
while (!GET_FRAME(i + free_frames) && free_frames < nb_frames &&
|
|
|
|
i + free_frames < remaining_frames)
|
2024-09-19 11:04:35 -04:00
|
|
|
free_frames++;
|
|
|
|
if (free_frames == nb_frames)
|
|
|
|
goto end;
|
|
|
|
i += free_frames;
|
|
|
|
}
|
|
|
|
end:
|
|
|
|
if (i != MAX_FRAMES) {
|
|
|
|
for (size_t j = 0; j < nb_frames; j++)
|
|
|
|
SET_FRAME(j + i, 1);
|
2024-09-19 11:16:45 -04:00
|
|
|
remaining_frames -= nb_frames;
|
2024-09-19 11:39:14 -04:00
|
|
|
return &end_kernel + i * PAGE_SIZE;
|
2024-09-19 11:04:35 -04:00
|
|
|
}
|
2024-09-20 06:40:36 -04:00
|
|
|
kprintf(KERN_WARNING "Not enough frames available\n", MAX_FRAMES);
|
2024-09-19 11:39:14 -04:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
void kfree_frame(void *frame, uint32_t nb_frames)
|
|
|
|
{
|
|
|
|
const uint32_t start = (frame - (void *)&end_kernel) / PAGE_SIZE;
|
|
|
|
|
|
|
|
if (start > MAX_FRAMES || frame < (void *)&end_kernel) {
|
2024-09-20 06:40:36 -04:00
|
|
|
kprintf(KERN_WARNING "Address out of range\n");
|
2024-09-19 11:39:14 -04:00
|
|
|
return;
|
|
|
|
} else if ((uint32_t)frame % PAGE_SIZE) {
|
2024-09-20 06:40:36 -04:00
|
|
|
kprintf(KERN_WARNING "Invalid address\n");
|
2024-09-19 11:39:14 -04:00
|
|
|
return;
|
|
|
|
} else if (start + nb_frames > MAX_FRAMES) {
|
2024-09-20 06:40:36 -04:00
|
|
|
kprintf(KERN_WARNING "Invalid number of frames\n");
|
2024-09-19 11:39:14 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
for (size_t i = start; i < start + nb_frames; i++)
|
|
|
|
SET_FRAME(i, 0);
|
|
|
|
remaining_frames += nb_frames;
|
2024-09-19 11:04:35 -04:00
|
|
|
}
|