Lesson 24 · Memory management

Translation Lookaside Buffer (TLB)

Every memory reference needs a translation, and the page table lives in memory. Without a cache of recent translations, each access would cost two.

Translation Lookaside Buffer (TLB) concept diagramA virtual address is looked up in a four-entry TLB holding pages 5, 9, 12 and 40. Page 5 hits and goes straight to frame 2, costing one memory access. Page 41 misses, walks the two-level page table for two extra reads, and the translation is loaded back into the TLB.virtual addresspage 5offTLB · 4 entriespageframe5F29F712F340F1physical addressF2offmemorythe data itselfpage table walkL1 → L2: 2 readslookuphit · 5 → F21 accessmiss · page 41refill TLB,evict LRU, retryhit 100 ns · miss 300 ns · at 98% hits EAT = 104 ns, at 50% = 200 ns
1

A Cache for Translations

  1. Virtual page number – the lookup key: the address without its offset.
  2. Frame number – what the translation resolves to.
  3. Valid bit – whether the entry can be used right now.
  4. ASID – which address space the entry belongs to, on hardware that tags entries.
  5. Protection bits – read, write, execute, checked on every hit.

The translation lookaside buffer (TLB) is a small cache inside the MMU that holds recent virtual-page-to-frame translations. It is hardware, not a kernel data structure, and typically holds 64 to 1,024 entries, searched all at once.

The problem it solves is plain. The page table lives in memory, so translating an address costs a memory read before the real access. With a two-level table that is three accesses for one; with the four-level table of x86-64 it is five.

For the operating system, the key fact about the TLB is that it is a pure speed-up: it changes no results. Remove it and every program still runs correctly, just several times slower. What the OS must do is keep it correct when mappings change.

  • Caches translations, never data
  • Checked before any page table
  • Edge case: a TLB entry can outlive its mapping, so the OS must invalidate it
2

TLB Hit and Miss

Every translation starts the same way: the MMU presents the virtual page number to the TLB and all entries are compared at once.

On a TLB hit the frame number comes straight back and the physical address is formed immediately. One memory access total — the data itself.

On a TLB miss the hardware walks the page table, one read per level (see multilevel paging). The translation it finds is loaded into the TLB, evicting an entry if it is full, on the bet that an address just used will be used again. Some CPUs (older MIPS, SPARC) leave the walk to the OS instead: the miss traps and a short kernel routine fills the entry.

A TLB miss is not a page fault. A miss means the translation was not cached; the page itself is usually in RAM, and the walk costs one or two extra memory reads. A fault means the page is not in memory at all and costs a disk read, tens of thousands of times longer.

  • Hit: 1 access. Miss on two levels: 3 accesses
  • A miss is not a fault — the page is usually resident
  • Misses populate the TLB, so the next reference hits
3

Effective Access Time

  1. h — hit ratio, the fraction of translations the TLB answers.
  2. c — TLB access time, often negligible and dropped.
  3. m — one main-memory access.
  4. L — page-table levels, so a miss costs (L+1)·m.

The value of the TLB is measured by the TLB hit ratio h, the share of translations it answers, and by the effective access time (EAT), the average cost of an access weighted by how often each path is taken.

Write h for the hit ratio, c for the TLB lookup itself, m for one memory access, and L for the number of page-table levels. A hit costs c + m. A miss costs c + (L+1)·m — the failed lookup, then one read per level, then the data.

That gives EAT = h(c + m) + (1−h)(c + (L+1)·m). Many textbooks drop c because the TLB is checked in parallel with the cache, leaving the simpler h·m + (1−h)·(L+1)·m. Use the full form when an exam question supplies a TLB access time.

Put real numbers in it. With c = 2 ns, m = 100 ns, two levels and a 98% hit ratio: 0.98 × 102 + 0.02 × 302 = 106 ns, against a raw 100 ns. At a 50% hit ratio it becomes 202 ns, half speed. The tracer's short run, with c dropped, hits only 40%: 220 ns.

That non-linearity is the point. The TLB does not need to be large, it needs to be right most of the time, and locality of reference ensures it is.

The same two-level table at four hit ratios, with c = 2 ns and m = 100 ns
Hit ratioEATOverhead vs raw memory
99%104 ns4%
98%106 ns6%
90%122 ns22%
50%202 ns102%
  • Drop c only when the question does not give a TLB access time
  • 98% on a two-level table costs about 6%; 50% doubles every access
  • Small TLBs work because references cluster, not because they are large
Key reference

Terms, operations, and practical uses

Terms to know

  • TLB reachEntries × page size: the memory a full TLB covers. 64 entries × 4 KB = 256 KB; huge pages raise it.
  • ASIDA tag on each entry naming its address space, so a switch need not flush.
  • invlpgThe x86 instruction that drops one TLB entry after a mapping changes.
  • Page walkReading the page table level by level after a miss.
Implementation

Ten references through a four-entry TLB

TLB_SIZE = 4
ACCESS_NS = 100.0
LEVELS = 2  # a miss reads one page-table entry per level, then the data


def effective_access_time(hit_ratio):
    miss_cost = (LEVELS + 1) * ACCESS_NS
    return hit_ratio * ACCESS_NS + (1 - hit_ratio) * miss_cost


def run(references):
    tlb = []  # least recently used first
    hits = 0
    for page in references:
        if page in tlb:
            hits += 1
            tlb.remove(page)
            print(f"page {page:>2}  hit   1 access")
        else:
            note = ""
            if len(tlb) == TLB_SIZE:
                note = f", evict {tlb.pop(0)}"
            print(f"page {page:>2}  miss  {LEVELS + 1} accesses{note}")
        tlb.append(page)
    return hits


references = [2, 7, 2, 9, 2, 4, 7, 11, 2, 9]
hits = run(references)
ratio = hits / len(references)
print(f"\nhits {hits} of {len(references)} = {ratio:.0%}")
print(f"EAT at {ratio:.0%}: {effective_access_time(ratio):.1f} ns")
print(f"EAT at 98%: {effective_access_time(0.98):.1f} ns")
#include <algorithm>
#include <cstdio>
#include <vector>

const int TLB_SIZE = 4;
const double ACCESS_NS = 100.0;
const int LEVELS = 2;  // a miss reads one page-table entry per level, then the data

double effectiveAccessTime(double hitRatio) {
    double missCost = (LEVELS + 1) * ACCESS_NS;
    return hitRatio * ACCESS_NS + (1 - hitRatio) * missCost;
}

int run(const std::vector<int>& references) {
    std::vector<int> tlb;  // least recently used first
    int hits = 0;
    for (int page : references) {
        auto it = std::find(tlb.begin(), tlb.end(), page);
        if (it != tlb.end()) {
            hits++;
            tlb.erase(it);
            std::printf("page %2d  hit   1 access\n", page);
        } else if ((int)tlb.size() == TLB_SIZE) {
            int evicted = tlb.front();
            tlb.erase(tlb.begin());
            std::printf("page %2d  miss  %d accesses, evict %d\n", page, LEVELS + 1, evicted);
        } else {
            std::printf("page %2d  miss  %d accesses\n", page, LEVELS + 1);
        }
        tlb.push_back(page);
    }
    return hits;
}

int main() {
    std::vector<int> references = {2, 7, 2, 9, 2, 4, 7, 11, 2, 9};
    int hits = run(references);
    double ratio = (double)hits / references.size();
    std::printf("\nhits %d of %zu = %.0f%%\n", hits, references.size(), ratio * 100);
    std::printf("EAT at %.0f%%: %.1f ns\n", ratio * 100, effectiveAccessTime(ratio));
    std::printf("EAT at 98%%: %.1f ns\n", effectiveAccessTime(0.98));
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static final int TLB_SIZE = 4;
    static final double ACCESS_NS = 100.0;
    static final int LEVELS = 2;  // a miss reads one page-table entry per level, then the data

    static double effectiveAccessTime(double hitRatio) {
        double missCost = (LEVELS + 1) * ACCESS_NS;
        return hitRatio * ACCESS_NS + (1 - hitRatio) * missCost;
    }

    static int run(int[] references) {
        List<Integer> tlb = new ArrayList<>();  // least recently used first
        int hits = 0;
        for (int page : references) {
            if (tlb.contains(page)) {
                hits++;
                tlb.remove(Integer.valueOf(page));
                System.out.printf("page %2d  hit   1 access%n", page);
            } else if (tlb.size() == TLB_SIZE) {
                int evicted = tlb.remove(0);
                System.out.printf("page %2d  miss  %d accesses, evict %d%n", page, LEVELS + 1, evicted);
            } else {
                System.out.printf("page %2d  miss  %d accesses%n", page, LEVELS + 1);
            }
            tlb.add(page);
        }
        return hits;
    }

    public static void main(String[] args) {
        int[] references = {2, 7, 2, 9, 2, 4, 7, 11, 2, 9};
        int hits = run(references);
        double ratio = (double) hits / references.length;
        System.out.printf("%nhits %d of %d = %.0f%%%n", hits, references.length, ratio * 100);
        System.out.printf("EAT at %.0f%%: %.1f ns%n", ratio * 100, effectiveAccessTime(ratio));
        System.out.printf("EAT at 98%%: %.1f ns%n", effectiveAccessTime(0.98));
    }
}
Watch it run

Step through it

Running on references 2 7 2 9 2 4 7 11 2 9; 4-entry LRU TLB; two-level page table; 100 ns per memory access

virtual addresspageoffsetTLB · LRU firstemptyemptyemptyemptyL1 page tableL2 page tabledata in RAMreferences27292471129L1 read + L2 read + data read = 300 ns
Step 1

No TLB: three reads for every access

The page table lives in memory. With two levels, every load or store first reads an L1 entry, then an L2 entry, and only then the data: 3 accesses where the program asked for 1.

Output
1 / 14
4

What a Context Switch Costs

TLB entries are only valid for one address space. Virtual page 5 means different things in two processes, so when the scheduler switches, stale entries would translate addresses to another process's memory.

The blunt fix is to flush the entire TLB on every context switch. Correct, and expensive: the new process starts with a cold TLB and misses on everything until it warms up again.

Modern hardware avoids most of this with an ASID (address space identifier), tagging each entry with the process it belongs to. Entries from several processes coexist and a switch flushes nothing.

The kernel still flushes selectively — a single entry when a mapping changes, via instructions like invlpg. Getting that wrong is a serious bug class: a stale TLB entry lets a process read memory it no longer owns.

  • Without ASIDs a switch flushes everything
  • ASID-tagged entries survive the switch
  • A stale entry is a security bug, not just a performance one
5

TLB Replacement and Shootdown

A TLB holds 64 to 1024 entries, so it fills quickly and something must be evicted. Because it is hardware, the policy is built into the silicon rather than chosen by the kernel — typically LRU or a cheap approximation of it, occasionally random on simpler cores.

The entry evicted is not lost data, only a lost shortcut: the next reference to that page walks the page table again and re-caches the result. A bad eviction costs time, never correctness.

A TLB shootdown is the harder problem, and it only appears on multi-core machines. Each core has its own TLB. When one core changes a mapping (unmapping a page, changing permissions, moving a frame), the other cores may still hold the old translation, and the hardware does not keep them in step.

The kernel fixes this in software: it sends an inter-processor interrupt to every core sharing the address space, each invalidates the affected entry, and the originating core waits for all of them to acknowledge. That handshake is expensive — microseconds, spent with every participating core stalled — which is why kernels batch unmappings rather than shooting down one page at a time.

  • Replacement is a hardware policy, usually LRU or an approximation
  • Each core has its own TLB, and hardware does not keep them in sync
  • A shootdown is an interrupt to every core sharing the space, plus a wait for all of them
  • Kernels batch unmappings because each shootdown stalls every core involved