"""
02_tlb.py -- the TLB: a cache of translations
==============================================

[Questions this demo answers]
  - Every memory access needs a translation, and a multi-level page-table walk
    is several memory accesses itself. How is that not ruinous?
  - The TLB caches recent VPN->PPN translations. How much does locality in the
    PAGE access pattern help its hit rate?
  - How does the VPN split into a TLB index and tag, like a cache address?

[How to run]
  python3 02_tlb.py

[How to read the output]
  PART A translates a few addresses with a TLB, showing the first access to a
  page miss the TLB (and walk the table) and the next hit. PART B runs a
  locality-friendly page access pattern and a scattered one through the TLB and
  compares hit rates and the resulting average translation cost.

[Systems link / CS:APP 9.6.2]
  The TLB is a small, fast, usually highly-associative cache that lives in the
  MMU. Because programs touch few pages at a time (locality again), the TLB hit
  rate is very high, so most translations cost nothing beyond the TLB probe and
  the page-table walk is rare.
"""

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

PAGE = 64


def make_pt():
    pt = vmsim.PageTable(va_bits=14, pa_bits=12, page_bytes=PAGE)
    for vpn in range(0, 0x100):                       # map every page to some frame
        pt.set(vpn, (vpn * 7 + 3) & 0x3F)
    return pt


def part_a():
    print("PART A: the TLB skips the page-table walk on a repeat")
    pt = make_pt()
    tlb = vmsim.TLB(sets=4, ways=4)                   # 16 entries, like the slides
    print("  TLB: 4 sets x 4 ways; VPN splits into TLB tag | TLB index (2 bits).\n")
    for va in (0x369, 0x370, 0x2A5):                  # 0x369 and 0x370 share VPN 0x0D
        _, steps = vmsim.translate(va, pt, tlb)
        for s in steps:
            print("  " + s)
        print()
    print("  0x369 and 0x370 are in the same page (VPN 0x0D): the first misses the")
    print("  TLB and walks the table; the second HITS the TLB and skips the walk.\n")


def access_cost(hit):
    """Rough cost: 1 for a TLB probe; +4 extra memory accesses for a 4-level walk."""
    return 1 if hit else 1 + 4


def run_pattern(name, vpns):
    pt = make_pt()
    tlb = vmsim.TLB(sets=4, ways=4)
    total = 0
    for vpn in vpns:
        va = (vpn << 6) | 0x10
        before = tlb.hits
        vmsim.translate(va, pt, tlb)
        total += access_cost(tlb.hits > before)
    n = len(vpns)
    rate = tlb.hits / n * 100
    print("  %-26s TLB hit rate %5.1f%%   avg translation cost %.2f units"
          % (name, rate, total / n))
    return rate


def part_b():
    print("PART B: locality in the PAGE pattern drives the TLB hit rate")
    # Good: walk 8 pages, many accesses each (like scanning arrays row by row).
    good = []
    for vpn in range(0x20, 0x28):
        good += [vpn] * 16
    # Bad: hop across 64 different pages with no reuse (like chasing scattered pointers).
    import itertools
    bad = list(itertools.islice((((i * 37) & 0x3F) for i in itertools.count()), 128))
    run_pattern("good page locality", good)
    run_pattern("scattered pages", bad)
    print("  With locality, each page's first access misses the TLB and the rest hit,")
    print("  so the hit rate is high and translation is nearly free. Scattered page")
    print("  access thrashes the small TLB and pays the walk again and again.\n")


def main():
    print("=== Demo 02: the translation lookaside buffer (TLB) ===\n")
    part_a()
    part_b()
    print("Observations:")
    print("  * The TLB is a cache of VPN->PPN translations; the VPN splits into a TLB")
    print("    index and tag exactly as a memory address splits for a cache (Lecture 10).")
    print("  * The first access to a page misses the TLB and walks the page table; later")
    print("    accesses to the same page hit the TLB and skip the walk entirely.")
    print("  * Page-level locality keeps the TLB hit rate high, so the multi-level walk")
    print("    (several memory accesses) happens rarely -- translation is usually free.")


if __name__ == "__main__":
    main()
