Skip to content

Instantly share code, notes, and snippets.

@soez
Created August 1, 2024 06:54
Show Gist options
  • Save soez/011cac41aee9d06a58b5095c1d288e1c to your computer and use it in GitHub Desktop.
Save soez/011cac41aee9d06a58b5095c1d288e1c to your computer and use it in GitHub Desktop.

Revisions

  1. soez created this gist Aug 1, 2024.
    38 changes: 38 additions & 0 deletions address_functions.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    #define MEMSTART 0x80000000UL
    #define VIRTUAL_KERNEL_START 0xffffffc008000000UL
    #define LINEAR_MAP_START 0xffffff8000000000UL

    bool is_lm_addr(uint64_t kaddr)
    {
    return (kaddr & (VIRTUAL_KERNEL_START - (0x8 << (6 * 4)))) == LINEAR_MAP_START;
    }

    uint64_t virt_to_phys(uint64_t kaddr)
    {
    if (is_lm_addr(kaddr)) {
    return kaddr - LINEAR_MAP_START + MEMSTART;
    } else {
    return kaddr - VIRTUAL_KERNEL_START + MEMSTART;
    }
    }

    uint64_t phys_to_virt(uint64_t paddr, bool is_lm_addr)
    {
    if (is_lm_addr) {
    return paddr + LINEAR_MAP_START - MEMSTART;
    } else {
    return paddr + VIRTUAL_KERNEL_START - MEMSTART;
    }
    }

    uint64_t vmemmap = 0xffffffff00000000UL;

    uint64_t virt_to_page(uint64_t kaddr)
    {
    return vmemmap + (((virt_to_phys(kaddr) - MEMSTART) >> 12) << 6);
    }

    uint64_t page_to_virt(uint64_t page, bool is_lm_addr)
    {
    return phys_to_virt((((page - vmemmap) >> 6) << 12) + MEMSTART, is_lm_addr);
    }