A TLB keeps the most recent translations. A translation found there is quick; otherwise the page table is read and the TLB is updated, throwing out the least recently used entry if it is full.
What to build
A program that translates addresses through an LRU TLB and reports how each one went.
Requirements
- The TLB holds at most
tpages and starts empty. The page table has the pages that are in memory, each with a frame. - For each address print
A TLB hit Pif its page is in the TLB,A TLB miss Pif it is not in the TLB but is in the page table, andA page faultif the page is not in the table, where A is the address and P the physical address (frame × page size + offset). - A hit makes the page the most recently used. A miss adds the page as the most recently used, first removing the least recently used page if the TLB is full. A page fault leaves the TLB unchanged.
- Finish with
hits H of N.
Input
A line with the page size and t. A line with m, then m lines page frame. A line with n, then n addresses, one per line.
Output
n + 1 lines.
Constraints
1 ≤ page size ≤ 65536; 1 ≤ t ≤ 8; 0 ≤ m ≤ 50; 1 ≤ n ≤ 100.
Example
Input:
100 2
3
0 5
1 6
2 7
5
10
110
20
210
120
Output:
10 TLB miss 510
110 TLB miss 610
20 TLB hit 520
210 TLB miss 710
120 TLB miss 620
hits 1 of 5
Why it works
The TLB is a small LRU cache in front of the page table, so repeated use of the same pages hits, while a loop over more pages than the TLB holds misses on every access.
Examples
100 2 3 0 5 1 6 2 7 5 10 110 20 210 120
10 TLB miss 510 110 TLB miss 610 20 TLB hit 520 210 TLB miss 710 120 TLB miss 620 hits 1 of 5
10 1 1 0 3 3 1 2 50
1 TLB miss 31 2 TLB hit 32 50 page fault hits 1 of 3
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the TLB as a list of pages ordered from least recently used (front) to most recently used (back).
Hint 2
A page in the TLB is a hit: move it to the back. A page in the table but not in the TLB is a miss: remove the front if the TLB is full, then add the page at the back. A page not in the table is a page fault and does not change the TLB.
Solution
Show one correct solution (try it yourself first)
size, t = map(int, input().split())
m = int(input())
table = {}
for _ in range(m):
p, f = map(int, input().split())
table[p] = f
n = int(input())
tlb, hits = [], 0
for _ in range(n):
a = int(input())
p, o = divmod(a, size)
if p not in table:
print(a, "page fault")
continue
phys = table[p] * size + o
if p in tlb:
hits += 1
tlb.remove(p)
tlb.append(p)
print(a, "TLB hit", phys)
else:
if len(tlb) == t:
tlb.pop(0)
tlb.append(p)
print(a, "TLB miss", phys)
print("hits", hits, "of", n)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step