90 lines
2.1 KiB
C
90 lines
2.1 KiB
C
#include "base_core.h"
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <sys/mman.h>
|
|
|
|
|
|
U32 platform_page_size(void)
|
|
{
|
|
return getpagesize();
|
|
}
|
|
|
|
static INLINE size_t AlignToPageSize(size_t sz)
|
|
{
|
|
U32 page_size = platform_page_size();
|
|
size_t aligned_sz = AlignUpPow2(sz, page_size);
|
|
|
|
return aligned_sz;
|
|
}
|
|
|
|
static INLINE size_t AlignToPageStart(size_t sz)
|
|
{
|
|
U32 page_size = platform_page_size();
|
|
size_t aligned_sz = AlignDownPow2(sz, page_size);
|
|
|
|
return aligned_sz;
|
|
}
|
|
|
|
void *platform_malloc(size_t sz)
|
|
{
|
|
return malloc(sz);
|
|
}
|
|
|
|
void platform_free(void *mem)
|
|
{
|
|
free(mem);
|
|
}
|
|
|
|
|
|
void *memory_allocate(size_t sz)
|
|
{
|
|
if (sz == 0) {
|
|
sz = 1;
|
|
}
|
|
|
|
size_t aligned_sz = AlignToPageSize(sz);
|
|
void *mem = mmap(0, aligned_sz, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
|
|
TRACEF("memory_allocate size=%zu aligned_size=%zu mem=%p\n", sz, aligned_sz, mem);
|
|
if (mem == MAP_FAILED) {
|
|
mem = NULL;
|
|
}
|
|
return mem;
|
|
}
|
|
|
|
void memory_free(void *mem, size_t sz)
|
|
{
|
|
size_t aligned_sz = AlignToPageSize(sz);
|
|
TRACEF(" memory_free size=%zu aligned_size=%zu mem=%p\n", sz, aligned_sz, mem);
|
|
|
|
int rc = munmap(mem, aligned_sz);
|
|
|
|
Assert(rc == 0);
|
|
}
|
|
|
|
void memory_commit(void *mem, size_t sz)
|
|
{
|
|
size_t aligned_sz = AlignToPageSize(sz);
|
|
void *aligned_mem = (void *)AlignToPageStart((uintptr_t)mem);
|
|
TRACEF("memory_commit size=%zu aligned_size=%zu ptr=%p aligned_mem=%p\n", sz, aligned_sz, mem, aligned_mem);
|
|
|
|
int rc;
|
|
rc = mprotect(aligned_mem, aligned_sz, PROT_READ | PROT_WRITE);
|
|
Assert(rc == 0);
|
|
rc = madvise(aligned_mem, aligned_sz, MADV_WILLNEED);
|
|
Assert(rc == 0);
|
|
}
|
|
|
|
void memory_decommit(void *mem, size_t sz)
|
|
{
|
|
size_t aligned_sz = AlignToPageSize(sz);
|
|
void *aligned_mem = (void *)AlignToPageStart((uintptr_t)mem);
|
|
TRACEF("memory_commit size=%zu aligned_size=%zu ptr=%p aligned_mem=%p\n", sz, aligned_sz, mem, aligned_mem);
|
|
|
|
int rc;
|
|
rc = mprotect(aligned_mem, aligned_sz, PROT_NONE);
|
|
Assert(rc == 0);
|
|
rc = madvise(aligned_mem, aligned_sz, MADV_DONTNEED);
|
|
Assert(rc == 0);
|
|
}
|