summaryrefslogtreecommitdiffstats
path: root/arch/x86_64/boot/limine/framebuffer.c
blob: 637a7fcca9e1a1ea9e4164ee708ae5e527236e51 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "arch/x86_64/hal/paging.h"
#include "jove.h"
#include "config.h"
#include "hal/framebuffer.h"
#include "lib/string.h"
#include "lib/printf.h"

/*We don't know the size of the framebuffer until runtime, but at the same
 * time we don't want to dynamically allocate from physical memory. In this
 * case we allocate memory for the maximum supported framebuffer at compile
 * time and only use what we need at runtime.*/
#define FRAMEBUFFER_MAX_BYTES (FRAMEBUFFER_MAX_WIDTH * FRAMEBUFFER_MAX_WIDTH * 4)
#define FRAMEBUFFER_MAX_PAGES ((FRAMEBUFFER_MAX_BYTES + 4095) / 0x1000)
#define FRAMEBUFFER_MAX_HUGEPAGES ((FRAMEBUFFER_MAX_PAGES + 511) / 512)
#define FRAMEBUFFER_MAX_GIANTPAGES ((FRAMEBUFFER_MAX_HUGEPAGES + 511) / 512)

PAGEALIGN static page_t fb_pages[FRAMEBUFFER_MAX_GIANTPAGES + FRAMEBUFFER_MAX_HUGEPAGES][512];

extern page_t _kernel_pml4[512];

void*
fb_remap(uintptr_t fb_address,
         size_t fb_bytes)
{
    fb_address &= ~IDENT_VIRT_BASE;
    size_t fb_numpages = (fb_bytes + 4095) >> 12;

    if(fb_numpages > FRAMEBUFFER_MAX_PAGES) {
        kprintf("Framebuffer is too big! Please recompile the kernel with a bigger framebuffer allowance!");
        return NULL;
    }

    uintptr_t vptr = IDENT_VIRT_BASE | (511ULL << PMLI_SHL(3));
    size_t last_table = 0;
    for(size_t page = 0; page < fb_numpages; page++) {
        uintptr_t frame = fb_address + (page << 12);
        uintptr_t frame_virt = vptr + (page << 12);

        int tblres = 0;
        do {
            uintptr_t tbl_frame = KPTR_TOPHYS(&fb_pages[last_table++]);
            tblres = pagedir_map_table(_kernel_pml4, tbl_frame, frame_virt);
            if(tblres == EHASMAP) last_table--;
        } while(tblres == 0);

        pagedir_map_frame(_kernel_pml4, frame, frame_virt,
            PAGE_GLOBAL | PAGE_WRITEABLE | PAGE_XD);
    }

    return (void*)vptr;
}