The TLB: A Cache of Translations

Two reads of memory before every access would make virtual memory useless. A tiny cache remembers the last few translations, and almost every access finds its answer there.

You Will Be Able To

  • Explain what a TLB stores, and why it is small and fully associative.
  • Follow a hit, a miss and a refill, and count the table reads that the TLB saves.
  • Explain why the bits of the entry are checked on a hit as well.
Lesson
S3.8
Time
25 min
Runs on
Your browser
Check
6 questions

A loop adds up an array. Each step fetches an instruction and loads a word. With the tables of the last pages, each of those two accesses needs two more reads first. The processor reads memory six times, where it wanted to read twice.

Before You Start

You need S3.21: a walk of two tables costs two reads of memory. You need S3.22: the bits R, W and X of an entry.

You also need the fully associative cache from S3.4.

Five questions this page answers
Question
1What does a TLB store?
2What happens on a TLB hit, and on a TLB miss?
3Why is a TLB fully associative?
4Why does a TLB entry hold the bits of the page?
5What does a TLB cost when a program uses more pages than it has entries?

The Idea: Remember the Answer of the Walk

A walk takes two reads of memory, and it gives the same answer every time: page 00403 lies in frame 09. Programs use the same few pages again and again. That is locality once more. So remember the answer.

The memory for these answers is called the TLB. The letters stand for translation lookaside buffer. It is a small cache. Each entry holds a page number, the frame number that the walk found, and the bits of the page.

Every access asks the TLB first. If an entry holds the page, that is a TLB hit. The frame number comes out at once, and no table is read. If no entry holds it, that is a TLB miss. The tables are walked, and the result is stored in an entry. Storing it is called a refill.

A TLB is tiny: this page uses four entries. So it can afford to be fully associative. Any entry may hold any page, and all entries are compared at once. That matters, because a miss here is dear. It costs a whole walk.

The bits of the page must come along into the entry. On a hit, the table is not read. If the TLB did not know that a page has W at 0, nothing would stop a store into it.

New Words

New words on this page
WordMeaning
TLBTranslation lookaside buffer. A small cache of translations: page numbers and their frame numbers.
Entry of a TLBOne remembered translation: a valid bit, a page number, a frame number and the bits of the page.
TLB hitAn access whose page number is found in the TLB. No table is read.
TLB missAn access whose page number is not in the TLB. The tables must be walked.
Refill of a TLBStoring the result of a walk in an entry of the TLB.
Reach of a TLBThe memory that its entries cover together: the number of entries times the size of a page.

One Picture: Short Path, Long Path

A Short Path and a Long Path to the Frame NumberStep through the picture. A page number first asks the TLB. Only when that fails are the tables read.
  • Processor
  • Memory
  • Control / FSM
  • Bus
A Short Path and a Long Path to the Frame NumberStep through the picture. A page number first asks the TLB. Only when that fails are the tables read. component Page number the top 20 bits ofthe address component TLB four entries, allcompared at once component Check the bits R, W, X from theentry component Frame number joined with theoffset component Table walk two reads of memory comparehit: frame and bitsallowedmissrefill
  1. component Page numberthe top 20 bits of the address
    • compare → TLB
  2. component TLBfour entries, all compared at once
    • hit: frame and bits → Check the bits
    • miss → Table walk
  3. component Check the bitsR, W, X from the entry
    • allowed → Frame number
  4. component Frame numberjoined with the offset
  5. component Table walktwo reads of memory
    • refill → TLB
  1. Ask the TLB first

    The page number is compared with all four entries at the same time, as in a fully associative cache.

  2. A hit: the short path

    One entry holds this page. It gives the frame number and the bits of the page. No table is read.

  3. The bits are checked on every access

    The entry carries R, W and X. A store into a page without W is refused here, on a hit too.

  4. A miss: the long path

    No entry holds the page. The tables are walked, which costs two reads of memory.

  5. Refill

    The result of the walk is stored in an entry of the TLB. The next access to this page takes the short path.

Read the diagram as text
  • Page number: the top 20 bits of the address
  • TLB: four entries, all compared at once
  • Check the bits: R, W, X from the entry
  • Frame number: joined with the offset
  • Table walk: two reads of memory
  • Page number → TLB: compare
  • TLB → Check the bits: hit: frame and bits
  • Check the bits → Frame number: allowed
  • TLB → Table walk: miss
  • Table walk → TLB: refill

The TLB is a cache. What it caches is not data: it is the last few answers of the table walk.

The Smallest Example, Worked by Hand

A program has its code in page 00403 and its data in page 00404. The TLB has four entries and starts empty. Follow six accesses, and count the reads of the tables.

Six accesses through an empty TLB
AccessPageIn the TLB?Table readsTLB after it
fetch 0040300000403no: miss200403
load 0040401000404no: miss200403, 00404
fetch 0040300400403yes: hit000403, 00404
load 0040401400404yes: hit000403, 00404
fetch 0040300800403yes: hit000403, 00404
store 0040401800404yes: hit000403, 00404

Four table reads in all. Without a TLB the six accesses would need twelve.

Each page costs one walk, at its first use. After that the program runs as if there were no tables. A loop of a million steps on these two pages still needs four table reads.

Now a seventh access: a store to 00403abc. It is a hit, in the entry of the code page. That entry says R and X, and not W. The store is refused with a page fault, and no table was read to find that out.

The Rules

  1. Rule 1: Every access asks the TLB first.

    All entries are compared with the page number at the same time.

  2. Rule 2: A hit gives the frame number with no read of the tables.

    The offset is joined on, as always.

  3. Rule 3: A miss starts a walk, and the result refills an entry.

    A walk that ends in a page fault refills nothing.

  4. Rule 4: An entry carries the bits of its page.

    They are checked on every access, hit or miss.

  5. Rule 5: A full TLB must give up an entry for a refill.

    This page replaces the entry that was filled longest ago.

  6. Rule 6: The TLB never knows more than the tables.

    It holds copies. The tables stay the one true record.

Sources for These Rules

The textbook "Computer Organization and Design" by Patterson and Hennessy, section 5.7. See "Making Address Translation Fast: the TLB": a cache of recent translations, with the protection bits kept in each entry.

The textbook "Digital Design and Computer Architecture" by Harris and Harris, section 8.4.3: the translation lookaside buffer as a small fully associative cache.

Four entries and the replacement of the oldest entry are choices of this page. Real TLBs have more entries and various policies.

The tables behind the TLB follow the Sv32 scheme of RISC-V as commonly described. That layout is not checked against the specification.

Now Run It

The lab at the end of this page is test code. It puts a TLB of four entries in front of the tables of the last two pages. Each row is one access, and the last row counts.

Printed by the lab on Icarus. The last row counts the accesses, the hits, the walks and the reads of the tables.
fetch 00403000 | TLB miss, walk, entry 0 filled | physical 09000
load  00404010 | TLB miss, walk, entry 1 filled | physical 06010
fetch 00403004 | TLB hit in entry 0 | physical 09004
load  00404014 | TLB hit in entry 1 | physical 06014
fetch 00403008 | TLB hit in entry 0 | physical 09008
store 00404018 | TLB hit in entry 1 | physical 06018
store 00403abc | TLB hit in entry 0 | page fault: W is 0, and this is a store
load  00409000 | TLB miss, walk | page fault: no valid entry
accesses=8 hits=5 walks=3 table_reads=6

Rules 1 to 3 at work: the first six rows are the hand table. Two misses fill entries 0 and 1. The next four accesses hit.

Rule 4 at work: row 7. The store to the code page is a hit, and it is still a page fault. The entry brought the bits along.

Rule 3 again: row 8. The page at 00409000 has no entry in the tables. The walk finds that out, and nothing is put into the TLB.

The count: 8 accesses and 6 table reads. Without the TLB there would be 16.

Now give the TLB more pages than it has entries. This run touches five pages in turn, and then the first one again:

The same lab: five pages through four entries.
fetch 00403000 | TLB miss, walk, entry 0 filled | physical 09000
load  00404000 | TLB miss, walk, entry 1 filled | physical 06000
load  00405000 | TLB miss, walk, entry 2 filled | physical 07000
load  00406000 | TLB miss, walk, entry 3 filled | physical 08000
load  00407000 | TLB miss, walk, entry 0 filled | physical 0a000
fetch 00403004 | TLB miss, walk, entry 1 filled | physical 09004
accesses=6 hits=0 walks=6 table_reads=12

Rule 5 at work: the fifth row. A fifth page arrives, and entry 0 is filled again. That entry held the code page. So the last access is a miss, although the page was used moments ago.

This lab leaves out the time of each step and the hardware that walks. It also leaves out what happens when a table changes. The next two pages add those.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
A cache of translationsA walk for every accessMost accesses need no table read. A few dozen entries of hardware.
Fully associativeDirect-mappedNo two pages fight over an entry, so walks stay rare. A comparator for every entry.
The bits kept in the entryThe bits read from the table each timeProtection costs no read. The entry is wider.
Refill only after a good walkRefill after every walkA page fault leaves no trace in the TLB. A page that faults is walked again next time.

The Trap: A Hit That Skips the Check

A team builds the TLB to hold page and frame numbers only. The bits R, W and X are checked by the walk, they say. Here is a store into the code page, tried twice:

The same lab, with a TLB that does not check the bits on a hit.
store 00403abc | TLB miss, walk, entry 0 filled | page fault: W is 0, and this is a store
fetch 00403000 | TLB hit in entry 0 | physical 09000
store 00403abc | TLB hit in entry 0 | physical 09abc

The first row is right. The store misses the TLB, the walk reads the entry, and W at 0 refuses it.

The third row is the failure. It is the same store. By now a fetch has put the code page into the TLB. The store hits, no walk happens, and so nothing checks W. The word is written into the code.

The protection worked on the first try and failed on the second. Rule 4 is the check: test every refusal twice, once as a miss and once as a hit.

At Scale

This page4 entries: a reach of 16 KiB
A real processordozens of entries in level 1, more behind

This section looks ahead. Real TLBs are larger, and they still cover little of a large memory.

  1. Reach

    Four entries of pages of 4 KiB cover 16 KiB. A program that jumps around in more memory than that misses often.

  2. Large pages

    One entry for a large page covers far more memory. That is the main reason large pages exist. Common practice.

  3. Two levels, two TLBs

    Common practice is a small TLB for fetches, one for data, and a larger one behind both.

  4. Who does the walk

    In many processors a small state machine walks the tables: the next lesson. In others, software does it.

Try It

Run the lab. Check the first six rows against the hand table.

Add a second load of 00409000 before totals. Is it a hit? Explain the count of table reads.

Replace the body by five loads of five different data pages, twice round. Predict the hits before you run it.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: fetch 00403000 | TLB miss, walk, entry 0 filled | physical 09000 load 00404010 | TLB miss, walk, entry 1 filled | physical 06010 fetch 00403004 | TLB hit in entry 0 | physical 09004 load 00404014 | TLB hit in entry 1 | physical 06014 fetch 00403008 | TLB hit in entry 0 | physical 09008 store 00404018 | TLB hit in entry 1 | physical 06018 store 00403abc | TLB hit in entry 0 | page fault: W is 0, and this is a store load 00409000 | TLB miss, walk | page fault: no valid entry accesses=8 hits=5 walks=3 table_reads=6

Check Yourself

Predict the outputA loop runs five times. Each time it fetches from the code page and loads from one data page. The TLB starts empty. What does the last row say?
// A TLB of four entries in front of a two-level page table. A hit needs no read of the tables.
module tb;
  logic [31:0] mem [0:32767];          // physical memory in words: 32 frames of 4096 bytes
  logic [21:0] root;                   // the frame that holds the first table
  bit show = 0;                        // 1: print a row for each table read
  // The low bits of an entry. D A G U X W R V are bits 7 to 0.
  localparam logic [7:0] V = 8'h01, R = 8'h02, W = 8'h04, X = 8'h08, U = 8'h10, A = 8'h40, D = 8'h80;

  task automatic put(input logic [21:0] table_frame, input int index, input logic [21:0] frame, input logic [7:0] bits);
    mem[table_frame * 1024 + index] = {frame, 2'b00, bits};      // an entry has 4 bytes, so a table of 1024 entries fills one frame
  endtask

  // Walk the two levels for one virtual address. why: 0 found, 1 no valid entry at level 1, 2 no valid entry at level 0,
  // 3 the last level points on to another table.
  task automatic walk(input logic [31:0] virt, output int why, output logic [31:0] found, output logic [31:0] phys);
    logic [9:0]  index1, index0;
    logic [31:0] at, e;
    index1 = virt[31:22];  index0 = virt[21:12];
    why = 0;  found = 0;  phys = 0;
    at = {root, 12'h000} + 4 * index1;
    e  = mem[at >> 2];
    if (!(e & V)) begin
      if (show) $display("  level 1: entry %0d of the table in frame %02h, at %05h = %08h | not valid", index1, root[7:0], at[19:0], e);
      why = 1;
    end else if (e & (R | W | X)) begin                           // a leaf already: one entry for 4 MiB (1024 pages)
      if (show) $display("  level 1: entry %0d of the table in frame %02h, at %05h = %08h | valid, a large page that starts at frame %03h", index1, root[7:0], at[19:0], e, e[21:10]);
      found = e;  phys = {e[31:20], virt[21:0]};
    end else begin
      if (show) $display("  level 1: entry %0d of the table in frame %02h, at %05h = %08h | valid, points to the table in frame %02h", index1, root[7:0], at[19:0], e, e[17:10]);
      at = {e[31:10], 12'h000} + 4 * index0;
      e  = mem[at >> 2];
      if (!(e & V)) begin
        if (show) $display("  level 0: entry %0d of that table, at %05h = %08h | not valid", index0, at[19:0], e);
        why = 2;
      end else if (!(e & (R | W | X))) begin
        if (show) $display("  level 0: entry %0d of that table, at %05h = %08h | points on, but there is no third level", index0, at[19:0], e);
        why = 3;
      end else begin
        if (show) $display("  level 0: entry %0d of that table, at %05h = %08h | valid, the page is in frame %02h", index0, at[19:0], e, e[17:10]);
        found = e;  phys = {e[31:10], virt[11:0]};
      end
    end
  endtask

  // The TLB. Each entry remembers one translation: a page number, its frame number and the bits of its entry.
  logic        t_valid [0:3];
  logic [19:0] t_page  [0:3];
  logic [21:0] t_frame [0:3];
  logic [7:0]  t_bits  [0:3];
  logic [3:0]  t_id    [0:3];           // only used with USE_ID: the program that the entry belongs to
  int next_in = 0;                      // the entry that is filled next: round and round
  int accesses = 0, hits = 0, walks = 0, table_reads = 0;
  int who = 0;                          // the program that runs now
  bit FLUSH_ON_SWITCH = 0;              // 1: a switch of program clears the whole TLB
  bit USE_ID = 0;                       // 1: each entry carries the number of its program, and a hit needs the same number

  bit quiet = 0;                        // 1: count only, print no rows

  task automatic flush;                 // forget every translation
    for (int i = 0; i < 4; i++) t_valid[i] = 0;
  endtask
  task automatic flush_page(input logic [19:0] page);   // forget the translations of one page
    for (int i = 0; i < 4; i++) if (t_page[i] == page) t_valid[i] = 0;
  endtask

  task automatic switch_to(input int prog);
    who = prog;
    root = prog == 0 ? 22'h10 : 22'h14;   // the register with the root table changes
    if (FLUSH_ON_SWITCH) flush;
    if (!quiet) $display("-- switch to program %0d%s", prog, FLUSH_ON_SWITCH ? ", and flush the TLB" : "");
  endtask

  task automatic access(input string kind, input logic [31:0] virt);
    int at, why;
    logic [31:0] e, phys;
    logic [7:0]  b;
    string how, verdict;
    accesses++;
    at = -1;
    for (int i = 0; i < 4; i++)           // all four entries are compared at once in hardware
      if (t_valid[i] && t_page[i] == virt[31:12] && (!USE_ID || t_id[i] == who)) at = i;
    if (at >= 0) begin
      hits++;
      how = $sformatf("TLB hit in entry %0d", at);
      phys = {t_frame[at], virt[11:0]};  b = t_bits[at];
    end else begin
      walk(virt, why, e, phys);
      walks++;  table_reads += (why == 1) ? 1 : 2;
      b = e[7:0];
      if (why != 0) how = "TLB miss, walk";
      else begin                          // refill: the translation is remembered for the next time
        at = next_in;  next_in = (next_in + 1) % 4;
        t_valid[at] = 1;  t_page[at] = virt[31:12];  t_frame[at] = e[31:10];  t_bits[at] = b;  t_id[at] = who;
        how = $sformatf("TLB miss, walk, entry %0d filled", at);
      end
    end
    if (!(b & V))                                    verdict = "page fault: no valid entry";
    else if (kind == "fetch" && !(b & X))            verdict = "page fault: X is 0, and this is a fetch";
    else if (kind == "load"  && !(b & R))            verdict = "page fault: R is 0, and this is a load";
    else if (kind == "store" && !(b & W))            verdict = "page fault: W is 0, and this is a store";
    else                                             verdict = $sformatf("physical %05h", phys[19:0]);
    if (!quiet) $display("%-5s %08h | %s | %s", kind, virt, how, verdict);
  endtask

  task automatic totals;
    $display("accesses=%0d hits=%0d walks=%0d table_reads=%0d", accesses, hits, walks, table_reads);
    accesses = 0;  hits = 0;  walks = 0;  table_reads = 0;
  endtask
  task automatic restart(input bit flush_on_switch, input bit use_id);   // an empty TLB, program 0, and a policy
    flush;  next_in = 0;  who = 0;  root = 22'h10;
    FLUSH_ON_SWITCH = flush_on_switch;  USE_ID = use_id;
  endtask
  task automatic ten_slices;            // two programs take turns, five times each. Each turn: a fetch and a load
    for (int r = 0; r < 5; r++) begin
      switch_to(0);  access("fetch", 32'h0040_3000 + 4 * r);  access("load", 32'h0040_4000 + 4 * r);
      switch_to(1);  access("fetch", 32'h0040_3000 + 4 * r);  access("load", 32'h0040_4000 + 4 * r);
    end
  endtask

  initial begin
    for (int i = 0; i < 32768; i++) mem[i] = 32'h0;
    flush;
    // Program 0: root table in frame 10, second table in frame 11.
    put(22'h10, 1, 22'h11, V);
    put(22'h11, 3, 22'h09, V | R | X | U | A);           // 00403000: code
    put(22'h11, 4, 22'h06, V | R | W | U | A | D);       // 00404000 to 00407000: data
    put(22'h11, 5, 22'h07, V | R | W | U | A | D);
    put(22'h11, 6, 22'h08, V | R | W | U | A | D);
    put(22'h11, 7, 22'h0a, V | R | W | U | A | D);
    // Program 1: root table in frame 14, second table in frame 15. The same virtual pages, other frames.
    put(22'h14, 1, 22'h15, V);
    put(22'h15, 3, 22'h0b, V | R | X | U | A);
    put(22'h15, 4, 22'h0c, V | R | W | U | A | D);
    root = 22'h10;
    for (int i = 0; i < 5; i++) begin
      access("fetch", 32'h0040_3000 + 4 * i);
      access("load",  32'h0040_4000 + 4 * i);
    end
    totals;
  end
endmodule
ConceptWhat does an entry of a TLB hold?
ConceptWhy can a TLB be fully associative?
ConceptA store hits in the TLB. The entry has W at 0. What happens?
ConceptA walk ends because the page has no valid entry. What is put into the TLB?
ConceptA program uses five pages in turn, and its TLB has four entries that are replaced oldest first. What happens?

Common Mistakes

Wrong Keep only page and frame numbers in the TLB.

On a hit the table is not read, so nothing else can check the bits.

Fix Store R, W and X in the entry, and check them on every access.

Wrong Refill the TLB after a walk that faulted.

The entry would stand for a page that has no valid translation.

Fix Refill only with a valid entry of the last level.

Wrong Size the TLB by the number of programs.

What counts is how many pages a program uses at the same time.

Fix Compare the reach of the TLB with the memory that the inner loops touch.

Remember

  • The TLB is a small cache of translations: page number in, frame number out.
  • A hit needs no table read. A miss costs a walk, and the result refills an entry.
  • The bits of the page are kept in the entry and checked on every access.
  • The TLB holds copies. The tables stay the true record.

Practice

Report a problem with this page