"""
01_worked_example.py -- the whole translation pipeline, end to end
===================================================================

[Questions this demo answers]
  - Put it all together: a virtual address goes through the TLB, (on a miss) the
    page table, becomes a physical address, which then goes through the data
    CACHE. What are all the field splits, and where does each hit or miss?
  - This reproduces the CS:APP "Simple Memory System" worked example the slides
    walk through by hand.

[How to run]
  python3 01_worked_example.py

[How to read the output]
  PART A states the geometry and every field split (VPN/VPO, TLBT/TLBI,
  PPN/PPO, CT/CI/CO). PART B translates a few virtual addresses, showing the
  TLB and page-table steps and then the cache lookup on the resulting physical
  address. All contents are fixed, so the output is reproducible.

[Systems link / CS:APP 9.6.3]
  The physical address produced by translation is itself a cache address
  (Lecture 10): it splits into cache tag / set index / block offset. So one
  memory reference can touch the TLB, the page table and the data cache -- three
  caches of three different things.
"""

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

# --- the CS:APP simple memory system geometry ---
VA_BITS, PA_BITS, PAGE = 14, 12, 64          # 6 offset bits
TLB_SETS, TLB_WAYS = 4, 4                     # 16 entries
CACHE_SETS, CACHE_WAYS, CACHE_B = 16, 1, 4    # 16 lines, direct-mapped, 4-byte blocks


def build():
    pt = vmsim.PageTable(VA_BITS, PA_BITS, PAGE)
    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),
                            (0x00, 0x28, 1), (0x01, 0x12, 1)]:
        pt.set(vpn, ppn, bool(valid))
    tlb = vmsim.TLB(TLB_SETS, TLB_WAYS)
    for vpn in (0x0D, 0x0E, 0x0F):           # warm a few translations into the TLB
        e = pt.lookup(vpn)
        tlb.insert(vpn, e.ppn)
    # A small physically-addressed cache: fill a few blocks with known bytes.
    cache = {}                                # set index -> (tag, [4 bytes])
    def put(pa, data):
        co = pa & (CACHE_B - 1)
        ci = (pa >> 2) & (CACHE_SETS - 1)
        ct = pa >> (2 + 4)
        block = cache.setdefault(ci, [ct, [0, 0, 0, 0]])
        block[0] = ct
        block[1][co] = data
    # Put the byte 0x15 at PA 0xB69 exactly (the slides' V[0x369] result); its
    # block is bytes 0xB68..0xB6B, so 0xB69 is offset 1.
    for addr, val in ((0xB68, 0x11), (0xB69, 0x15), (0xB6A, 0x13), (0xB6B, 0x17)):
        put(addr, val)
    return pt, tlb, cache


def fields(va, pt, tlb, cache):
    vpn, vpo = pt.split_va(va)
    tlbt, tlbi = tlb.split_vpn(vpn)
    return vpn, vpo, tlbt, tlbi


def cache_lookup(pa, cache):
    co = pa & (CACHE_B - 1)
    ci = (pa >> 2) & (CACHE_SETS - 1)
    ct = pa >> (2 + 4)
    block = cache.get(ci)
    if block and block[0] == ct:
        return "hit", co, ci, ct, block[1][co]
    return "miss", co, ci, ct, None


def part_a():
    print("PART A: geometry and field splits (the CS:APP simple memory system)")
    print("  14-bit virtual address, 12-bit physical address, 64-byte pages")
    print("  virtual:  [ VPN  (8 bits) | VPO (6 bits) ]")
    print("  TLB:      16 entries, 4-way -> VPN = [ TLBT (6) | TLBI (2) ]")
    print("  physical: [ PPN  (6 bits) | PPO (6 bits) ]")
    print("  cache:    16 lines, direct-mapped, 4-byte blocks ->")
    print("            PA = [ CT (6) | CI (4) | CO (2) ]\n")


def part_b():
    pt, tlb, cache = build()
    print("PART B: translating and accessing")
    for va in (0x369, 0x3D4, 0x020):
        vpn, vpo, tlbt, tlbi = fields(va, pt, tlb, cache)
        print("  --- VA 0x%03x ---" % va)
        print("    VPN 0x%02x  VPO 0x%02x   TLBT 0x%02x  TLBI %d" % (vpn, vpo, tlbt, tlbi))
        pa, steps = vmsim.translate(va, pt, tlb)
        for s in steps[1:]:
            print("    " + s)
        if pa is None:
            print("    -> page fault: OS loads the page, then the access retries.\n")
            continue
        kind, co, ci, ct, byte = cache_lookup(pa, cache)
        print("    cache: PA 0x%03x -> CT 0x%02x  CI 0x%x  CO %d -> %s%s"
              % (pa, ct, ci, co, kind, "" if byte is None else (", byte = 0x%02x" % byte)))
        if kind == "miss":
            print("    -> cache miss: fetch the 4-byte block from memory.")
        print()
    print("  VA 0x369 reproduces the slides: VPN 0x0D, PPN 0x2D, PA 0xB69, byte 0x15.")
    print("  VA 0x020 is in VPN 0x00; whether it hits the TLB/cache depends on prior")
    print("  use -- here it misses the TLB, walks the table, and misses the cache.\n")


def main():
    print("=== Demo 01: end-to-end address translation + cache ===\n")
    part_a()
    part_b()
    print("Observations:")
    print("  * One memory reference can consult THREE caches: the TLB (translations),")
    print("    the page table (which is itself cached in the data cache), and the data")
    print("    cache (the value).")
    print("  * The physical address from translation is a cache address: it splits into")
    print("    cache tag / set index / block offset (Lecture 10).")
    print("  * The field widths come straight from the geometry; the hit/miss outcomes")
    print("    come from what happens to be resident.")


if __name__ == "__main__":
    main()
