</>EmbeddedInterview

Simulate a two-level page-table walk.

Hard"Coding: Systems, Bitmaps & Virtualization"
#include <stdint.h>
#include <stdbool.h>

/* 32-bit VA: [31:22] L1 index, [21:12] L2 index, [11:0] page offset; 4-byte entries */
#define PTE_VALID (1u << 0)
#define PTE_WRITE (1u << 1)
#define PTE_USER  (1u << 2)
#define PTE_ADDR(e) ((e) & 0xFFFFF000u)

typedef enum { XLATE_OK, FAULT_L1, FAULT_L2, FAULT_PERM } xlate_t;

/* phys_read32 simulates reading physical memory where the tables live */
uint32_t phys_read32(uint32_t pa);

xlate_t translate(uint32_t l1_base, uint32_t va, bool write, bool user, uint32_t *pa)
{
    uint32_t l1e = phys_read32(l1_base + ((va >> 22) & 0x3FFu) * 4u);
    if (!(l1e & PTE_VALID)) return FAULT_L1;

    uint32_t l2e = phys_read32(PTE_ADDR(l1e) + ((va >> 12) & 0x3FFu) * 4u);
    if (!(l2e & PTE_VALID)) return FAULT_L2;

    if ((write && !(l2e & PTE_WRITE)) || (user && !(l2e & PTE_USER))) return FAULT_PERM;

    *pa = PTE_ADDR(l2e) | (va & 0xFFFu);              /* frame + offset */
    return XLATE_OK;
}

Points: split the VA into indexes and offset; each level's entry gives the physical address of the next table; check valid and permission bits and return a precise fault type (the OS needs it to decide between demand paging, copy-on-write and SIGSEGV); combine the final frame with the unchanged offset. Follow-ups: add a small TLB cache in front (array indexed by VPN with tags), large pages (an L1 entry that maps 4 MB directly), accessed/dirty bit updates, and the 4-level 9-9-9-9-12 split of ARM64.