TLB Flush and Address-Space IDs

A TLB holds copies of table entries. When the tables change, or another program takes over, a copy can become a lie. This page shows two ways to keep the TLB honest.

You Will Be Able To

  • Explain how a TLB entry goes out of date, by a changed table or by a switch of program.
  • Explain what a flush does, and what it costs.
  • Explain how a number in each entry lets two programs share a TLB with no flush.
Lesson
S3.24
Time
24 min
Runs on
Your browser
Check
6 questions

Two programs take turns on one processor. Each has its own tables, and they are correct. Still program 1 reads a word that program 0 wrote. No table says that it may.

Before You Start

You need S3.8: TLB hit, miss and refill, and the rule that the TLB holds copies.

You also need S3.7: each program has its own page table.

Five questions this page answers
Question
1How can an entry of the TLB be wrong when the tables are right?
2What does a flush do?
3What does a flush at every switch of program cost?
4What is an address-space ID?
5When must the TLB be flushed even with such IDs?

The Idea: A Copy Must Be Told

The last rule of the TLB page was that the TLB holds copies. A copy is right only as long as the original stays the same. There are two ways for the original to change.

The first: the operating system changes an entry of a table. It takes a frame away from a page, or it takes away the right to write. The TLB still holds the old entry, and goes on using it.

The second: another program gets the processor. The operating system points the walker to the root table of that program. Every page number now means something else. The TLB still holds the meanings of the old program.

An entry of the TLB that no longer matches the tables is a stale entry. The cure for both cases is to remove it. Removing entries from the TLB is called a flush. A flush may empty the whole TLB, or remove the entries of one page.

A flush of the whole TLB at every switch is safe and costly. After each switch, every page misses again and is walked again. Programs switch many times a second.

There is a cheaper way for the second case. Give each program a small number, and store it in every entry of the TLB. A hit then needs the right page and the right number. Entries of several programs can sit side by side, and a switch needs no flush. The number is called an address-space ID, or ASID.

New Words

New words on this page
WordMeaning
Address spaceAll the virtual addresses of one program, with the table that gives them a meaning.
Switch of programThe moment when the operating system takes the processor from one program and gives it to another. Also called a context switch.
Stale entryAn entry of the TLB that no longer matches the page tables.
Flush of a TLBRemoving entries from the TLB: all of them, or those of one page.
Address-space IDA small number that names one address space. It is stored in each entry of the TLB. ASID for short.
Current IDThe address-space ID of the program that runs now. The operating system sets it at a switch.

One Picture: The Stale Entry

A Copy That No Longer MatchesStep through the picture. The TLB keeps a copy of an entry. Then the truth behind the copy changes.
  • Memory
  • Control / FSM
  • Processor
  • Bus
A Copy That No Longer MatchesStep through the picture. The TLB keeps a copy of an entry. Then the truth behind the copy changes. component TLB entry page 00404 is inframe 06 component Table of program0 page 00404 is inframe 06 component Table of program1 page 00404 is inframe 0c component Program 1 runs loads from page00404 component Frame 06 data of program 0 component A number in theentry whose translation isthis copied by a refillpage 00404?a hit: frame 06should have askedherecompared on everylookup
  1. component Table of program 0page 00404 is in frame 06
    • copied by a refill → TLB entry
  2. component TLB entrypage 00404 is in frame 06
    • a hit: frame 06 → Frame 06
  3. component Table of program 1page 00404 is in frame 0c
  4. component Program 1 runsloads from page 00404
    • page 00404? → TLB entry
    • should have asked here → Table of program 1
  5. component Frame 06data of program 0
  6. component A number in the entrywhose translation is this
    • compared on every lookup → TLB entry
  1. A refill makes a copy

    Program 0 used page 00404. The TLB holds a copy of its translation: frame 06.

  2. Another program takes over

    Program 1 has a table of its own. There, page 00404 lies in frame 0c.

  3. The copy still answers

    The TLB compares page numbers only. It finds 00404 and says frame 06. Program 1 now reads the data of program 0.

  4. Two cures

    Empty the TLB at every switch. Or put the number of the program into each entry, and compare it too.

Read the diagram as text
  • TLB entry: page 00404 is in frame 06
  • Table of program 0: page 00404 is in frame 06
  • Table of program 1: page 00404 is in frame 0c
  • Program 1 runs: loads from page 00404
  • Frame 06: data of program 0
  • A number in the entry: whose translation is this
  • Table of program 0 → TLB entry: copied by a refill
  • Program 1 runs → TLB entry: page 00404?
  • TLB entry → Frame 06: a hit: frame 06
  • Program 1 runs → Table of program 1: should have asked here
  • A number in the entry → TLB entry: compared on every lookup

The TLB cannot see that the tables behind it changed. Something must tell it.

The Smallest Example, Worked by Hand

Two programs each use page 00404. In program 0 it lies in frame 06, and in program 1 in frame 0c. The TLB starts empty. Program 0 loads from the page, then program 1, then program 0 again.

Three loads of page 00404, with a flush at each switch
WhoTLB beforeResultTLB after
program 0emptymiss, walk: frame 0600404 to 06
program 1empty (flushed)miss, walk: frame 0c00404 to 0c
program 0empty (flushed)miss, walk: frame 0600404 to 06

Three loads, three walks. Every answer is right.

The same three loads, with an ID in each entry
WhoTLB beforeResultTLB after
program 0emptymiss, walk: frame 06ID 0: 00404 to 06
program 1ID 0: 00404 to 06the page matches, the ID does not: miss, walk: frame 0cboth entries
program 0both entrieshit in the entry with ID 0: frame 06both entries

Three loads, two walks. The entry of program 0 was still there when it came back.

The second table saves one walk in three loads. With longer turns the gain is larger: nothing that a program has put into the TLB is thrown away at a switch.

The Rules

  1. Rule 1: The TLB cannot see a change of the tables.

    Whoever changes a table must also remove the copies.

  2. Rule 2: After an entry of a table changes, the TLB entries of that page are flushed.

    The next access walks, and gets the new entry.

  3. Rule 3: A switch of program changes the meaning of every page number.

    Without IDs, the whole TLB is flushed at the switch.

  4. Rule 4: With IDs, a hit needs the page number and the current ID.

    A switch then only changes the current ID.

  5. Rule 5: An ID must name one address space at a time.

    Before an ID is given to another program, its old entries are flushed.

Sources for These Rules

The textbook "Computer Organization and Design" by Patterson and Hennessy, section 5.7. See "Implementing Protection with Virtual Memory". On a switch of process the TLB is cleared, or its entries carry a process identifier.

In RISC-V the number of the address space sits in the register that holds the root table. One instruction flushes the TLB. We state this from common knowledge. It is not checked against the RISC-V privileged specification, which is not in our library.

Rule 5 follows from rule 4. IDs are few, and a system with more programs than IDs must use an ID again.

The two programs and the TLB of four entries are our own teaching example.

Now Run It

The lab at the end of this page is the TLB of four entries from the earlier page, in test code. It now has two programs with a table each. Both map page 00404, to different frames.

It runs the three loads of the hand example twice. First with a flush at each switch, then with an ID in each entry. Then it counts a longer run under both policies.

Printed by the lab on Icarus. Rows that start with two dashes are switches. The last two rows count ten turns of two programs.
program 0 load  00404010 | TLB miss, walk, entry 0 filled | physical 06010
-- switch to program 1, and flush the TLB
program 1 load  00404010 | TLB miss, walk, entry 1 filled | physical 0c010
-- switch to program 0, and flush the TLB
program 0 load  00404010 | TLB miss, walk, entry 2 filled | physical 06010
accesses=3 hits=0 walks=3 table_reads=6
program 0 load  00404010 | TLB miss, walk, entry 0 filled | physical 06010
-- switch to program 1
program 1 load  00404010 | TLB miss, walk, entry 1 filled | physical 0c010
-- switch to program 0
program 0 load  00404010 | TLB hit in entry 0 | physical 06010
accesses=3 hits=1 walks=2 table_reads=4
flush at a switch: accesses=20 hits=0 walks=20 table_reads=40
numbered entries : accesses=20 hits=16 walks=4 table_reads=8

Rule 3 at work: the first six rows. Each switch empties the TLB, so the third load misses, although program 0 had the page moments ago. Three walks.

Rule 4 at work: the next six rows. Program 1 misses on page 00404, although the TLB holds that page number: the ID is wrong. When program 0 returns, its entry is still there. Two walks.

The last two rows are ten turns. Each program fetches and loads once in each turn. With a flush, all 20 accesses miss, and the tables are read 40 times. With IDs, only the first use of each page misses: 4 walks.

Now rule 2. The operating system takes the W right away from a page that the TLB knows.

The same lab: a table entry changes, and the TLB is told one step too late.
program 0 store 00404018 | TLB miss, walk, entry 0 filled | physical 06018
-- the table changes: page 00404 loses W
program 0 store 00404018 | TLB hit in entry 0 | physical 06018
-- the entry of page 00404 is flushed
program 0 store 00404018 | TLB miss, walk, entry 1 filled | page fault: W is 0, and this is a store

The third row is a store that the table forbids. The TLB allows it, from its old copy. Only after the flush of that page does the walk find W at 0.

This lab leaves out how IDs are handed out, and the time that a flush takes.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Flush by softwareA TLB that watches the tablesThe TLB stays small and fast. Software must never forget a flush.
A flush of one pageAlways the whole TLBThe other entries survive a small change. The TLB needs a compare for the flush.
An ID in each entryA flush at every switchNo walks after a switch for pages that are still there. A few more bits to store and compare.
A small IDAn ID as wide as a program numberFew bits in every entry. IDs must be used again, with a flush.

The Trap: A Switch with No Flush and No ID

This is the system from the top of the page. Its operating system changes the root table at a switch, and does nothing else. The TLB has no IDs.

The same lab, with nothing done at the switch.
program 0 load  00404010 | TLB miss, walk, entry 0 filled | physical 06010
-- switch to program 1
program 1 load  00404010 | TLB hit in entry 0 | physical 06010
program 1 store 00404010 | TLB hit in entry 0 | physical 06010

The third row is the failure. Program 1 loads from its page 00404. The TLB hits, in the entry that program 0 left behind, and gives frame 06. That is the data of program 0.

The fourth row is worse. Program 1 stores into that frame. Program 0 will find its data changed, and no table ever allowed it.

Both tables were correct the whole time. The wall between the programs was broken by a copy. Rule 3 is the check: at every switch, either flush or change the current ID.

At Scale

This page2 programs, 4 entries
A real systemhundreds of programs, a few hundred IDs

This section looks ahead. Real systems use both tools, and add a few more.

  1. Pages of everyone

    The pages of the operating system look the same in every address space. Their entries can be marked to match any ID. Not checked.

  2. Several cores

    Each core has a TLB. When a table changes, every core that may hold a copy must flush. That takes a message between cores.

  3. Guests and devices

    A chip that runs several operating systems tags entries with a second number: I/O Memory Management and Virtualisation.

  4. The cache has the same question

    A cache that is looked up with virtual addresses can go stale in the same way. That is the next lesson.

Try It

Run the lab. Check the first twelve rows against the two hand tables.

Try restart(0, 0) before ten_slices, with quiet at 0. Which rows show a wrong frame?

Give each program a third page in ten_slices. With IDs, do the hits survive? The TLB has four entries.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: program 0 load 00404010 | TLB miss, walk, entry 0 filled | physical 06010 -- switch to program 1, and flush the TLB program 1 load 00404010 | TLB miss, walk, entry 1 filled | physical 0c010 -- switch to program 0, and flush the TLB program 0 load 00404010 | TLB miss, walk, entry 2 filled | physical 06010 accesses=3 hits=0 walks=3 table_reads=6 program 0 load 00404010 | TLB miss, walk, entry 0 filled | physical 06010 -- switch to program 1 program 1 load 00404010 | TLB miss, walk, entry 1 filled | physical 0c010 -- switch to program 0 program 0 load 00404010 | TLB hit in entry 0 | physical 06010 accesses=3 hits=1 walks=2 table_reads=4 flush at a switch: accesses=20 hits=0 walks=20 table_reads=40 numbered entries : accesses=20 hits=16 walks=4 table_reads=8

Check Yourself

Predict the outputEntries carry IDs, and nothing is flushed. Program 0 uses three pages, program 1 uses two, and then program 0 uses its three again. The TLB has four entries, replaced oldest first. 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("program %0d %-5s %08h | %s | %s", who, 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;
    restart(0, 1);  quiet = 1;
    access("fetch", 32'h0040_3000);  access("load", 32'h0040_4000);  access("load", 32'h0040_5000);
    switch_to(1);
    access("fetch", 32'h0040_3000);  access("load", 32'h0040_4000);
    switch_to(0);
    access("fetch", 32'h0040_3000);  access("load", 32'h0040_4000);  access("load", 32'h0040_5000);
    totals;
  end
endmodule
ConceptWhat is a stale entry?
ConceptThe operating system removes the W right of a page in the table. What else must it do?
ConceptA TLB without IDs is flushed at every switch. What does that cost?
ConceptWith IDs in the entries, what does a switch of program change in the TLB?
ConceptAn ID is taken from a program that has ended and given to a new one. What must happen first?

Common Mistakes

Wrong Change a table entry and leave the TLB alone.

The TLB keeps using its old copy, with the old frame and the old rights.

Fix Flush the entries of that page right after the change.

Wrong Switch programs by changing the root table only.

The TLB still holds translations of the old program.

Fix Flush the TLB at the switch, or change the current ID.

Wrong Give a used ID to a new program without a flush.

Entries of the old owner would hit for the new one.

Fix Flush the entries of an ID before it gets a new owner.

Remember

  • The TLB holds copies and cannot see the tables change.
  • A changed entry needs a flush of its page. A switch of program needs a flush, or IDs.
  • With an address-space ID in each entry, a hit needs the page number and the current ID.
  • A flush is safe and costs walks. IDs save the walks and cost a few bits.

Practice

Report a problem with this page