"""
01_address_translation.py -- virtual to physical, page hits, page faults
=========================================================================

[Questions this demo answers]
  - Every address a program uses is VIRTUAL. How does the hardware turn it into
    a physical address, and what is a page table?
  - What is the difference between a page HIT (the page is in DRAM) and a page
    FAULT (it is not)?
  - Why can two processes use the same virtual address for different data?
  - Why do real systems use MULTI-LEVEL page tables?

[How to run]
  python3 01_address_translation.py

[How to read the output]
  PART A splits an address and walks a single-level page table, showing a hit
  and a fault. PART B shows two processes with private page tables mapping the
  same VA to different physical pages. PART C shows why a flat page table is too
  big, and how a two-level table stores only the parts in use.

[Systems link / CS:APP 9.3-9.6]
  Virtual memory gives each process a private address space, translated on every
  access by the MMU through a page table the OS maintains. It is what makes
  Lecture 6's ASLR, Lecture 7's uniform load addresses, and process isolation
  possible.
"""

import course_path
course_path.use("lecture11")
import vmsim                                          # noqa: E402


def part_a():
    print("PART A: one address, one page table (14-bit VA, 64-byte pages)")
    pt = vmsim.PageTable(va_bits=14, pa_bits=12, page_bytes=64)
    # The slides' first page-table entries (VPN -> PPN, valid).
    for vpn, ppn, valid in [(0x08, 0x13, 1), (0x09, 0x17, 1), (0x0A, 0x09, 1),
                            (0x0B, 0, 0), (0x0C, 0, 0), (0x0D, 0x2D, 1),
                            (0x0E, 0x11, 1), (0x0F, 0x0D, 1)]:
        pt.set(vpn, ppn, bool(valid))
    print("  page size 64 B -> 6 offset bits; VPN = top 8 bits, VPO = low 6 bits.\n")
    for va in (0x369, 0x2FF):
        pa, steps = vmsim.translate(va, pt)
        for s in steps:
            print("  " + s)
        if pa is not None:
            print("  -> physical address 0x%x\n" % pa)
        else:
            print("  -> the OS must fetch the page from disk, then retry.\n")
    print("  V[0x369] translated to P[0xB69], exactly as the slides' example shows.")
    print("  V[0x2FF] (VPN 0x0B) is marked invalid -> a page fault.\n")


def part_b():
    print("PART B: private address spaces -- same VA, different data")
    pa_bits, vb, pb = 12, 14, 64
    pt1 = vmsim.PageTable(vb, pa_bits, pb)
    pt2 = vmsim.PageTable(vb, pa_bits, pb)
    pt1.set(0x02, 0x11)        # process 1: VPN 2 -> physical page 0x11
    pt2.set(0x02, 0x2A)        # process 2: VPN 2 -> physical page 0x2A
    va = 0x0080                # VPN 2, offset 0
    for name, pt in (("process 1", pt1), ("process 2", pt2)):
        pa, _ = vmsim.translate(va, pt)
        print("  %s: VA 0x%03x -> PA 0x%03x" % (name, va, pa))
    print("  Both use VA 0x080, but their page tables send it to different physical")
    print("  pages, so neither can see or corrupt the other's memory. The OS gives")
    print("  each process its own page table and switches which one is active on a")
    print("  context switch. (This is why every program can be linked to load at the")
    print("  same addresses -- Lecture 7 -- and why ASLR can randomize them -- L6.)\n")


class TwoLevel:
    """A tiny two-level page table: the top directory points at second-level
    tables, each covering a chunk of the VPN space. Only the pieces in use exist."""
    def __init__(self, va_bits, pa_bits, page_bytes, vpn_hi_bits):
        self.inner = vmsim.PageTable(va_bits, pa_bits, page_bytes)
        self.hi = vpn_hi_bits
        self.dir = {}                                  # top index -> set of present inner tables

    def map(self, vpn, ppn):
        top = vpn >> (self._lo())
        self.dir.setdefault(top, True)
        self.inner.set(vpn, ppn)

    def _lo(self):
        return (self.inner.va_bits - self.inner.p) - self.hi

    def count_tables(self, total_vpn_bits):
        return 1 + len(self.dir)                        # 1 directory + present 2nd-level tables


def part_c():
    print("PART C: why multi-level page tables")
    # A realistic-ish size: 32-bit VA, 4 KiB pages -> 20-bit VPN -> 2^20 entries.
    vpn_bits = 20
    flat_entries = 1 << vpn_bits
    print("  A 32-bit address space with 4 KiB pages has 2^20 = %d pages, so a FLAT"
          % flat_entries)
    print("  page table needs %d entries -- several MiB -- for EVERY process, even one" % flat_entries)
    print("  that uses a few pages. Most of it would be empty.")
    # Two-level: top 10 bits index a directory of 1024 second-level tables of 1024.
    t = TwoLevel(va_bits=32, pa_bits=32, page_bytes=4096, vpn_hi_bits=10)
    # A typical process: a bit of code low, a bit of stack high.
    for vpn in (0x00000, 0x00001, 0x00002, 0xFFFFF, 0xFFFFE):
        t.map(vpn, vpn & 0xFFF)
    present = t.count_tables(vpn_bits)
    print("  A two-level table stores only the second-level tables that are USED. A")
    print("  process touching a few pages near the bottom and top of memory needs")
    print("  1 directory + %d second-level tables = %d tables, not one giant one." % (present - 1, present))
    print("  Each table is one page; unused regions cost nothing. Real x86-64 uses")
    print("  FOUR levels for its 48-bit address space, for the same reason.\n")


def main():
    print("=== Demo 01: address translation, page hits and faults ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * A virtual address splits into VPN | offset; the page table maps the VPN")
    print("    to a physical page number, and the offset is carried across unchanged.")
    print("  * A valid entry is a page hit; a missing/invalid one is a page fault, which")
    print("    the OS handles by fetching the page (or killing the process on a bad one).")
    print("  * Per-process page tables give private, isolated address spaces.")
    print("  * Multi-level page tables store only the mapped regions, so a sparse")
    print("    address space costs little.")


if __name__ == "__main__":
    main()
