Luna/kernel/src/sys/mem.cpp
apio 69a9f7f06a Kernel: Move VMM from a class to a namespace
Also, rename the ugly Paging::VirtualMemoryManager name to just 'VMM'. Which is now used instead of kernelVMM.
2022-10-12 20:02:25 +02:00

93 lines
2.8 KiB
C++

#define MODULE "mem"
#include "errno.h"
#include "interrupts/Context.h"
#include "log/Log.h"
#include "memory/MemoryManager.h"
#include "memory/VMM.h"
#include "misc/utils.h"
#include <stddef.h>
#define MAP_FAIL(errno) 0xffffffffffffff00 | (unsigned char)(errno)
void sys_mmap(Context* context, void* address, size_t size, int flags)
{
if (size < PAGE_SIZE)
{
kdbgln("sys_mmap: size too small");
context->rax = MAP_FAIL(EINVAL);
return;
}
int real_flags = MAP_USER;
if (flags & MAP_READ_WRITE) real_flags |= MAP_READ_WRITE;
if (address)
{
kdbgln("sys_mmap: %ld pages at address %p, %s", size / PAGE_SIZE, address,
real_flags & MAP_READ_WRITE ? "rw" : "ro");
if (VMM::getPhysical((uint64_t)address) != (uint64_t)-1) // Address is already used.
{
kdbgln("attempt to mmap an already mapped address");
context->rax = MAP_FAIL(ENOMEM);
return;
}
uint64_t offset = (uint64_t)address % PAGE_SIZE;
void* result = MemoryManager::get_pages_at((uint64_t)address - offset,
Utilities::get_blocks_from_size(PAGE_SIZE, size), real_flags);
if (result)
{
kdbgln("mmap succeeded: %p", result);
context->rax = (uint64_t)result;
return;
}
else
{
kdbgln("mmap failed");
context->rax = MAP_FAIL(ENOMEM);
return;
}
}
kdbgln("sys_mmap: %ld pages at any address, %s", Utilities::get_blocks_from_size(PAGE_SIZE, size),
real_flags & MAP_READ_WRITE ? "rw" : "ro");
void* result = MemoryManager::get_pages(Utilities::get_blocks_from_size(PAGE_SIZE, size), real_flags);
if (result)
{
kdbgln("mmap succeeded: %p", result);
context->rax = (uint64_t)result;
return;
}
else
{
kdbgln("mmap failed");
context->rax = MAP_FAIL(ENOMEM);
return;
}
}
void sys_munmap(Context* context, void* address, size_t size)
{
kdbgln("sys_munmap: attempting to unmap %p", address);
if (size < PAGE_SIZE)
{
kdbgln("munmap failed: size is too small");
context->rax = -EINVAL;
return;
}
if (!address)
{
kdbgln("munmap failed: attempted to unmap page 0");
context->rax = -EINVAL;
return;
}
uint64_t flags = VMM::getFlags((uint64_t)address);
if (!(flags & MAP_USER))
{
kdbgln("munmap failed: attempted to unmap a kernel page");
context->rax = -EINVAL;
return;
}
uint64_t offset = (uint64_t)address % PAGE_SIZE;
MemoryManager::release_pages((void*)((uint64_t)address - offset), Utilities::get_blocks_from_size(PAGE_SIZE, size));
kdbgln("munmap succeeded");
context->rax = 0;
return;
}