feature: both physical and virtual allocators should be done
This commit is contained in:
73
src/memory/page.c
Normal file
73
src/memory/page.c
Normal file
@ -0,0 +1,73 @@
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "kprintf.h"
|
||||
#include "memory.h"
|
||||
#include "utils.h"
|
||||
|
||||
#define PT_SIZE 1024
|
||||
#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 (size_t i = 0; i < PT_SIZE; i++) {
|
||||
if (page_table_entries[i] >> 12 == i) {
|
||||
size_t j = i + 1;
|
||||
for (; j - i < nb_pages && j < PT_SIZE; j++)
|
||||
if (page_table_entries[j] >> 12 != j)
|
||||
break;
|
||||
if (j - i == nb_pages)
|
||||
return i;
|
||||
i = j - 1;
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
Reference in New Issue
Block a user