Lesson 7 · Memory management

Inverted Page Table in OS

One table for the whole machine with one row per physical frame. Its size depends only on RAM, but finding a page means searching, so real systems add a hash.

Inverted Page Table in OS concept diagramA visual explanation of the layout and operations shown in this lesson.one table for the whole machine — indexed by frame, so a lookup must search itlooking for<P1, page 7>pid + virtual pageis the search keyinverted page tableone row per physical frame0P3, page 2no1P1, page 4no2P1, page 7match3P7, page 94P3, page 15freeframewho lives therescanrow byrowframe 2the row index is the answerthe tradefixed size, but a search — real systems add a hash
1

One Entry per Frame

  1. Take the pair (process id, virtual page number) from the address.
  2. Find the entry holding that pair.
  3. The entry's position i is the frame number.
  4. Physical address = i × page size + offset.

An inverted page table has one entry for each frame of physical memory instead of one entry for each virtual page. There is a single table for the whole system, and entry i describes frame i: which process owns it and which of that process's virtual pages it holds.

The name comes from reading the mapping backwards. A normal page table is indexed by page number and stores a frame number. An inverted table is indexed by frame number and stores the page, so translating a page means finding the entry that holds it.

The process id is part of every entry because all processes share the table. P1's page 7 and P3's page 7 are different pages, and only the pid tells their entries apart.

  • Entry: process id, virtual page number, protection bits, chain pointer
  • 4 GB of RAM with 4 KB frames = 1,048,576 entries in total
  • With 8-byte entries that is 8 MB, however many processes run
2

Inverted Page Table vs Page Table

Choosing an inverted page table over an ordinary page table is a trade between total size and lookup speed. A normal table answers "where is page 7?" by reading entry 7. An inverted table cannot, because entry 7 describes frame 7, so it has to search.

In return its size is fixed. A flat 32-bit page table costs 4 MB per process, so 100 processes need 400 MB of tables; one inverted table for a 4 GB machine costs 8 MB in total.

Normal and inverted page tables compared
Normal page tableInverted page table
Indexed byVirtual page numberPhysical frame number
Entry storesFrame number and bitsProcess id, page number and bits
Number of tablesOne per processOne for the whole machine
Size grows withVirtual address space, per processPhysical memory only
LookupDirect indexSearch, made fast with a hash
Shared pagesTwo entries point to one frameHard: one entry per frame
  • Normal: fast index, many tables
  • Inverted: one small table, slower search
  • Non-resident pages still need a per-process record on disk
3

The Hash Anchor Table

Scanning a million entries on every TLB miss is not workable, so inverted tables always come with a hash anchor table. The pair (pid, page) is hashed to a slot, and the slot holds the index of the first inverted-table entry with that hash. Entries with the same hash are linked through a next field stored in each entry.

Take an 8-frame machine and h = (pid + page) mod 4. (P2, 0), (P3, 7) and (P4, 2) all hash to 2, so slot 2 points to frame 3 and the chain runs 3 → 4 → 7. To find (P3, 7): hash to slot 2, compare frame 3's (P2, 0), follow next to frame 4, match. Two comparisons, where a scan from the top needed five.

If the chain ends without a match, the page is not in memory and the hardware raises a page fault. The inverted table only describes resident pages, so the OS keeps a separate per-process record of where the others are on disk.

  • Slot = hash(pid, page); slot → first entry; next fields link the rest
  • A good hash keeps chains to one or two entries
  • The same idea as a hashed page table, but the chain lives inside the frame table
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Inverted page tableOne system-wide table with an entry per physical frame.
  • Hash anchor tableArray of slots; each points to the first frame entry with that hash.
  • Chain (next) fieldLinks entries whose (pid, page) pairs have the same hash.
  • Resident pageA page currently in a frame; only these appear in the table.

Formulas and rules

  • EntriesRAM size ÷ frame size (4 GB ÷ 4 KB = 1,048,576)
  • Table sizeentries × entry size (8 MB with 8-byte entries)
  • Frame numberthe matching entry's index
  • Lookup key(process id, virtual page number), never the page alone
Implementation

Searching an inverted page table

SLOTS = 4
# frame -> (pid, page) living there; None means the frame is free
FRAMES = [None, (2, 3), (1, 7), (2, 0), (3, 7), (1, 2), None, (4, 2)]


def h(pid, page):
    return (pid + page) % SLOTS


# Hash anchor table: slot -> first frame; nxt[frame] links frames with one hash.
anchor = [-1] * SLOTS
nxt = [-1] * len(FRAMES)
for frame in reversed(range(len(FRAMES))):
    if FRAMES[frame] is not None:
        slot = h(*FRAMES[frame])
        nxt[frame] = anchor[slot]
        anchor[slot] = frame


def scan(pid, page):
    """Search every row. Returns (frame or -1, rows checked)."""
    for frame, entry in enumerate(FRAMES):
        if entry == (pid, page):
            return frame, frame + 1
    return -1, len(FRAMES)


def hashed(pid, page):
    """Follow the anchor slot's chain. Returns (frame or -1, comparisons)."""
    frame, compared = anchor[h(pid, page)], 0
    while frame != -1:
        compared += 1
        if FRAMES[frame] == (pid, page):
            return frame, compared
        frame = nxt[frame]
    return -1, compared


def main():
    for pid, page in ((1, 7), (4, 2), (3, 7), (1, 5)):
        f1, rows = scan(pid, page)
        f2, comps = hashed(pid, page)
        assert f1 == f2
        where = "page fault" if f1 < 0 else f"frame {f1}"
        print(f"(P{pid}, page {page})  -> {where:<10}  scan {rows} rows, "
              f"hash slot {h(pid, page)}: {comps} comparisons")
    print(f"4 GB RAM, 4 KB frames, 8 B entries: {(4 << 30) // 4096 * 8:,} bytes in total")


if __name__ == "__main__":
    main()
#include <cstdio>
#include <utility>
#include <vector>

// frame -> (pid, page) living there; pid 0 means the frame is free
const std::vector<std::pair<int, int>> FRAMES = {
    {0, 0}, {2, 3}, {1, 7}, {2, 0}, {3, 7}, {1, 2}, {0, 0}, {4, 2}};
const int SLOTS = 4;

int h(int pid, int page) { return (pid + page) % SLOTS; }

// Hash anchor table: slot -> first frame; nxt[frame] links frames with one hash.
std::vector<int> anchor(SLOTS, -1), nxt(FRAMES.size(), -1);

// Search every row. Returns the frame or -1; rows counts rows checked.
int scan(int pid, int page, int& rows) {
    for (int f = 0; f < (int)FRAMES.size(); f++)
        if (FRAMES[f] == std::make_pair(pid, page)) { rows = f + 1; return f; }
    rows = FRAMES.size();
    return -1;
}

// Follow the anchor slot's chain. Returns the frame or -1.
int hashed(int pid, int page, int& compared) {
    compared = 0;
    for (int f = anchor[h(pid, page)]; f != -1; f = nxt[f]) {
        compared++;
        if (FRAMES[f] == std::make_pair(pid, page)) return f;
    }
    return -1;
}

int main() {
    for (int f = FRAMES.size() - 1; f >= 0; f--) {
        if (FRAMES[f].first == 0) continue;
        int slot = h(FRAMES[f].first, FRAMES[f].second);
        nxt[f] = anchor[slot];
        anchor[slot] = f;
    }
    int queries[4][2] = {{1, 7}, {4, 2}, {3, 7}, {1, 5}};
    for (auto& q : queries) {
        int rows, comps;
        int f = scan(q[0], q[1], rows);
        hashed(q[0], q[1], comps);
        char where[16];
        if (f < 0) std::snprintf(where, sizeof where, "page fault");
        else std::snprintf(where, sizeof where, "frame %d", f);
        std::printf("(P%d, page %d)  -> %-10s  scan %d rows, hash slot %d: %d comparisons\n",
                    q[0], q[1], where, rows, h(q[0], q[1]), comps);
    }
    std::printf("4 GB RAM, 4 KB frames, 8 B entries: 8,388,608 bytes in total\n");
}
import java.util.Arrays;

class Main {
    // frame -> {pid, page} living there; null means the frame is free
    static final int[][] FRAMES = {null, {2, 3}, {1, 7}, {2, 0}, {3, 7}, {1, 2}, null, {4, 2}};
    static final int SLOTS = 4;
    static final int[] anchor = new int[SLOTS];
    static final int[] nxt = new int[FRAMES.length];

    static int h(int pid, int page) { return (pid + page) % SLOTS; }

    static boolean holds(int f, int pid, int page) {
        return FRAMES[f] != null && FRAMES[f][0] == pid && FRAMES[f][1] == page;
    }

    // Search every row. Returns {frame or -1, rows checked}.
    static int[] scan(int pid, int page) {
        for (int f = 0; f < FRAMES.length; f++)
            if (holds(f, pid, page)) return new int[] {f, f + 1};
        return new int[] {-1, FRAMES.length};
    }

    // Follow the anchor slot's chain. Returns {frame or -1, comparisons}.
    static int[] hashed(int pid, int page) {
        int compared = 0;
        for (int f = anchor[h(pid, page)]; f != -1; f = nxt[f]) {
            compared++;
            if (holds(f, pid, page)) return new int[] {f, compared};
        }
        return new int[] {-1, compared};
    }

    public static void main(String[] args) {
        Arrays.fill(anchor, -1);
        Arrays.fill(nxt, -1);
        for (int f = FRAMES.length - 1; f >= 0; f--) {
            if (FRAMES[f] == null) continue;
            int slot = h(FRAMES[f][0], FRAMES[f][1]);
            nxt[f] = anchor[slot];
            anchor[slot] = f;
        }
        int[][] queries = {{1, 7}, {4, 2}, {3, 7}, {1, 5}};
        for (int[] q : queries) {
            int[] s = scan(q[0], q[1]);
            int[] c = hashed(q[0], q[1]);
            String where = s[0] < 0 ? "page fault" : "frame " + s[0];
            System.out.printf("(P%d, page %d)  -> %-10s  scan %d rows, hash slot %d: %d comparisons%n",
                    q[0], q[1], where, s[1], h(q[0], q[1]), c[1]);
        }
        System.out.printf("4 GB RAM, 4 KB frames, 8 B entries: %,d bytes in total%n", (4L << 30) / 4096 * 8);
    }
}
Watch it run

Step through it

Running on 8 frames shared by P1–P4; find (P1, 7), (P4, 2), (P3, 7), (P1, 5); hash anchor h = (pid + page) mod 4

frame | pid, pagef0freef1P2, page 3f2P1, page 7f3P2, page 0f4P3, page 7f5P1, page 2f6freef7P4, page 28 frames of RAM= 8 rows in totalfor all 4 processesframes 0 and 6 are freeThe frame number is the row number, so it is never stored
Step 1

Rows are frames, not pages

This machine has 8 physical frames, so the table has 8 rows, one per frame, and every process shares it. Row f2 says frame 2 currently holds page 7 of process P1. A normal page table is the other way round: one table per process, indexed by page, storing a frame.

Output
1 / 9
4

The Shared Memory Problem

Speed is fixed by hashing; sharing is not. Shared libraries, mapped files and copy-on-write pages after fork() all need two processes to map the same frame, often at different virtual pages. A frame has exactly one entry, and that entry holds one (pid, page) pair.

There are workarounds. All sharers can be made to use the same virtual address, or the table can hold extra entries chained to the same frame, as some designs do. Each one adds complexity, which is part of why x86 and ARM kept per-process multilevel tables.

  • One frame, one entry, one owner
  • Sharing needs a second mapping with nowhere to live
  • Used on IBM RT, PowerPC and UltraSPARC, not on x86 or ARM
5

Edge Cases

A free frame's entry holds no pair and never matches. Switching processes needs no table switch, since the pid is in every entry, but the pid has to be compared on every lookup. A TLB miss costs a hash plus a chain walk, which is why the TLB matters just as much here. Page table structures puts this design next to the others.

  • Free frames: empty entries, skipped
  • Context switch: no page-table base to reload
  • Long chains come from a poor hash, not from the table's size