42_KFS/src/memory/page.c

73 lines
1.8 KiB
C

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "kprintf.h"
#include "memory.h"
#include "utils.h"
#define PT_SIZE 0x300
#define MAX_TLB_ENTRIES 32
extern uint32_t page_table_entries[PT_SIZE] __attribute__((aligned(4096)));
static int16_t find_next_block(size_t nb_pages)
{
for (uint16_t i = 0; i < PT_SIZE; i++) {
uint16_t j;
for (j = 0;
page_table_entries[i + j] >> 12 == i + j && j < nb_pages;
j++)
;
if (j == nb_pages)
return i;
i += j;
}
return -1;
}
void *alloc_pages(size_t size)
{
const uint32_t nb_pages = CEIL(size, PAGE_SIZE);
const int16_t index = find_next_block(nb_pages);
if (index < 0) {
kprintf(KERN_CRIT "Not enough pages (max: %d)\n", PT_SIZE);
return NULL;
}
for (size_t i = index; i - (size_t)index < nb_pages; i++) {
void *frame = alloc_frames(PAGE_SIZE);
if (!frame) {
for (size_t j = index; j < i; j++)
free_frames(
(void *)(page_table_entries[j] >> 12),
PAGE_SIZE);
return NULL;
}
page_table_entries[i] = (uint32_t)frame << 12 | INIT_FLAGS;
}
return (void *)(page_table_entries[index] >> 12);
}
int free_pages(void *page_ptr, size_t size)
{
const uint32_t nb_pages = CEIL(size, PAGE_SIZE);
const uint32_t page_index = (uint32_t)page_ptr / PAGE_SIZE;
if ((uint32_t)page_ptr > PT_SIZE * PAGE_SIZE) {
kprintf(KERN_WARNING "Address out of range\n");
return -1;
} else if ((uint32_t)page_ptr % PAGE_SIZE) {
kprintf(KERN_WARNING "Invalid address\n");
return -1;
} else if (page_index + nb_pages > PT_SIZE) {
kprintf(KERN_WARNING "Invalid number of frames\n");
return -1;
}
for (size_t i = page_index; i < page_index + nb_pages; i++) {
free_frames((void *)(page_table_entries[i] >> 12), PAGE_SIZE);
page_table_entries[i] = (i >> 12) | INIT_FLAGS;
}
return 0;
}