Luna/kernel/src/sys/mem.cpp

90 lines
2.6 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 <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 (kernelVMM.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, size / PAGE_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", size / PAGE_SIZE, real_flags & MAP_READ_WRITE ? "rw" : "ro");
void* result = MemoryManager::get_pages(size / PAGE_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 = kernelVMM.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), size / PAGE_SIZE);
kdbgln("munmap succeeded");
context->rax = 0;
return;
}