#include "System.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdint.h>

unsigned long System::page_size;
unsigned int System::page_size_log;
unsigned long System::page_base_mask;
unsigned long System::page_offset_mask;

bool System::init()
{
    long sc_page_size = sysconf(_SC_PAGESIZE);
    if (sc_page_size < 0)
    {
        fprintf(stderr, "Unable to determine operating system page size.\n");
        return false;
    }

    System::page_size = (unsigned long)sc_page_size;
    System::page_size_log = 0u;
    System::page_offset_mask = System::page_size - 1u;
    System::page_base_mask = ~System::page_offset_mask;

    for (uint_fast8_t i = 0u; i < 32u; i++)
    {
        unsigned long v = 1u << i;
        if (v == System::page_size)
        {
            System::page_size_log = i;
            break;
        }
    }

    if ((System::page_size < 256u) ||
            (System::page_size > (4u * 1024u * 1024u)) ||
            (System::page_size_log == 0u))
    {
        fprintf(stderr, "Unsupported page size detected: 0x%lx\n", System::page_size);
        return false;
    }

    return true;
}

void * System::alloc_pages(int num)
{
    return mmap(
            NULL,
            num * System::page_size,
            PROT_READ | PROT_WRITE,
            MAP_PRIVATE | MAP_ANONYMOUS,
            -1,
            0);
}

void System::free_pages(void * addr, int num)
{
    (void)munmap(addr, num << System::page_size_log);
}
