Skip to content
Visual explainer 4h to learn 4 steps

Virtual memory, paging & address space

Explain how virtual addresses map to physical pages and read a process memory map.

By Invicly Tech, , in Linux System Programming. About 13 minutes to read.

Topic 29 of 42

In short

Every process sees its own private virtual address space, which the kernel maps to physical RAM in fixed-size pages, usually 4 KiB. The CPU's MMU translates addresses using page tables and caches recent translations in the TLB. Pages are populated lazily on first access, which is why programs can reserve far more memory than they use.

Explained simply

When your program uses an address like 0x7ffd1234, that is not a real spot in the RAM chips. It is a virtual address: a number in your program's own private map. The kernel and the CPU translate it to a real (physical) location behind the scenes.

Each process gets its own map, so two programs can both use address 0x400000 without ever touching each other's data. One buggy program cannot scribble on another. This is the main reason a crash in your browser does not take down your editor.

Memory is handed out in pages, small blocks of usually 4 KiB. The kernel is lazy on purpose: when you ask for 1 GiB, it only writes down a promise. A real page of RAM is given only when you first touch that part of memory. That first touch causes a page fault, which is a normal event, not an error.

Because promises are cheap, Linux lets programs promise more memory than the machine has. Usually that works, since most programs never touch all of it. If they do, and RAM and swap run out, the kernel's OOM (out of memory) killer stops one process to save the rest.

Press Play on a diagram to walk through it one step at a time.

FlowTranslating a virtual address
  1. 1
    CPU issues an address

    For example a load from 0x7ffd1234.

  2. 2
    TLB lookup

    Hit: physical frame found in a few cycles.

  3. 3
    Page table walk

    Miss: the MMU walks the multi-level page table.

  4. 4
    Page fault if not present

    Kernel maps or reads in the page, or sends SIGSEGV.

  5. 5
    Access physical RAM

    The translation is cached in the TLB.

LayersTypical layout of a 64-bit process, high to low addresses
  1. 1
    Kernel space

    Mapped in every process, not accessible from user mode

  2. 2
    Main thread stack

    [stack], grows down toward lower addresses

  3. 3
    mmap region

    Shared libraries, thread stacks, big malloc blocks

  4. 4
    Heap

    [heap], grows up with brk

  5. 5
    Data and BSS

    Global variables, rw-p

  6. 6
    Program code

    r-xp mapping of the executable

In depth

Pages, page tables and the TLB

On x86-64 a page is 4 KiB, so the low 12 bits of an address are the offset inside the page. The rest of the address is split into four 9-bit pieces, one per level of the page table. Each level is a 4 KiB table of 512 entries that points to the next table, and the last one gives the physical frame. With 4 levels the usable virtual space is 48 bits (256 TiB), and user programs get the lower half, up to 0x00007fffffffffff. Newer CPUs support 5 levels for 57-bit addresses.

Walking four tables for every memory access would be slow, so the CPU caches recent translations in the TLB (translation lookaside buffer). A hit costs almost nothing; a miss costs a page walk. Huge pages (2 MiB or 1 GiB) cover much more memory per TLB entry, which is why databases and VMs like them.

LayersHow a 48-bit x86-64 address is split
  1. 1
    Bits 47-39: level 4 index

    Picks 1 of 512 entries in the top table

  2. 2
    Bits 38-30: level 3 index

    Next table; can map a 1 GiB huge page

  3. 3
    Bits 29-21: level 2 index

    Next table; can map a 2 MiB huge page

  4. 4
    Bits 20-12: level 1 index

    Gives the 4 KiB physical frame

  5. 5
    Bits 11-0: offset

    Byte position inside the page

Reading /proc/PID/maps line by line

Each line in /proc/PID/maps is one mapping (the kernel calls it a VMA, virtual memory area). A line like 55d0c4a00000-55d0c4a21000 r-xp 00002000 08:01 1312 /usr/bin/cat has six fields: start and end address, permissions, offset into the file, device, inode, and the file name.

The permissions are r, w, x, and then p for private (copy-on-write) or s for shared. Code is r-xp, constants are r--p, writable globals are rw-p. Lines without a file are anonymous memory: [heap] is the brk heap, [stack] is the main thread stack, and big unnamed rw-p regions are usually malloc arenas or thread stacks. [vdso] is a small library the kernel maps in so calls like clock_gettime need no system call.

For sizes, use /proc/PID/smaps (per mapping) or smaps_rollup (totals), or pmap -x PID for a table with RSS per mapping.

  • r-xp with a .so name: library code, shared between processes
  • rw-p with no name: heap, arena or thread stack
  • ---p regions are guard pages: any access crashes

Page faults and demand paging

A page fault is the CPU saying: this address has no valid translation, kernel, please decide. The kernel looks up the VMA. If no mapping covers the address, or the access breaks its permissions, the process gets SIGSEGV. Otherwise the fault is legal and the kernel fixes it.

A minor fault needs no disk: the first touch of anonymous memory (the kernel hands out a zeroed page), a file page already in the page cache, or a copy-on-write after fork (the kernel copies the shared page so the writer gets its own). A major fault must read from disk: a file page that is not cached, or a page that was swapped out. Minor faults cost around a microsecond; major faults cost a disk read, from tens of microseconds on fast SSDs to milliseconds on spinning disks.

You can count them with ps -o min_flt,maj_flt -p PID or perf stat -e page-faults ./prog.

FlowWhat the kernel does on a page fault
  1. 1
    CPU traps

    No valid translation for the address

  2. 2
    Find the VMA

    None, or wrong permission: SIGSEGV

  3. 3
    Anonymous page?

    Give a zeroed page: minor fault

  4. 4
    File page?

    In page cache: minor; else read disk: major

  5. 5
    Update page table

    Retry the instruction, which now works

Overcommit and the OOM killer

The setting vm.overcommit_memory decides how many promises the kernel makes. 0, the default, uses a heuristic that refuses only obviously impossible requests. 1 always says yes. 2 is strict: total committed memory may not exceed swap plus overcommit_ratio percent of RAM (50 by default); /proc/meminfo shows this as CommitLimit and the current total as Committed_AS. In mode 2, malloc really returns NULL when the limit is hit.

In modes 0 and 1, malloc almost never fails. Instead, when memory truly runs out, the OOM killer picks the process with the highest oom_score (mostly based on how much memory it uses) and kills it with SIGKILL. The kernel log shows Out of memory: Killed process. You can bias the choice through /proc/PID/oom_score_adj, from -1000 (never kill) to 1000 (kill first), or OOMScoreAdjust= in a systemd unit. Containers usually hit their cgroup limit (memory.max) first, which triggers an OOM kill inside that cgroup only.

  • sysctl vm.overcommit_memory shows the mode
  • journalctl -k | grep -i 'out of memory' finds OOM kills
  • cat /proc/PID/oom_score shows the current badness

RSS, VSZ and shared pages

top and ps show two numbers. VSZ (VIRT in top) is the size of every mapping, touched or not. It is often huge and mostly harmless: thread stacks, reserved arenas and mapped files all count. RSS (RES) is how much is actually in RAM right now.

RSS still over-counts. Pages from libc or a shared file are in RAM once but appear in the RSS of every process that maps them. PSS (proportional set size) fixes this by splitting each shared page among its users: a 100 KiB page set shared by 4 processes adds 25 KiB to each. Read it from /proc/PID/smaps_rollup. To find out how much memory a set of processes really uses together, add up PSS, not RSS.

Swapped-out pages are in neither RSS nor PSS; smaps_rollup shows them as Swap.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Explain pages, page tables and the TLB~1h
  2. 2
    Read a memory map in /proc/PID/maps~1h
  3. 3
    Describe page faults and demand paging~1h
  4. 4
    Explain overcommit and the OOM killer~1h

Key points

  • Virtual memory isolates processes and lets the kernel share pages such as libraries.
  • /proc/PID/maps lists every mapping with its permissions and backing file.
  • Minor faults map a page already in RAM; major faults need disk I/O.
  • Linux overcommits memory by default, and when RAM runs out the OOM killer picks a victim.
  • RSS is resident memory; VSZ is the total mapped virtual size.

Key terms

Tap a card to flip it. 0/6 known

Examples

bash
cat /proc/self/maps
grep -E "VmSize|VmRSS" /proc/self/status
getconf PAGESIZE
cat /proc/sys/vm/overcommit_memory
/usr/bin/time -v ls 2>&1 | grep -i fault

Inspect mappings, sizes, page size and fault counts.

Watch demand paging happen

We allocate 1 GiB and read our own VmRSS after each step. Step 1: right after malloc, RSS barely moves, because the kernel only reserved address space (glibc used mmap for a block this big). Step 2: after writing to half of it, RSS rises by about 512 MiB, one page fault per 4 KiB page. Step 3: free returns the whole mmap block to the kernel. Build with gcc -O0, because an optimising compiler may delete a buffer that is never read.

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void rss(const char *when) {
  char line[256]; FILE *f = fopen("/proc/self/status", "r");
  if (!f) return;
  while (fgets(line, sizeof line, f))
    if (strncmp(line, "VmRSS:", 6) == 0) printf("%-8s %s", when, line);
  fclose(f);
}
int main(void) {
  size_t n = 1UL << 30;                         /* 1 GiB */
  char *p = malloc(n); if (!p) { perror("malloc"); return 1; }
  rss("malloc"); memset(p, 1, n / 2); rss("touched");
  free(p); return 0; }

Investigate an OOM kill

A worker process disappears without a log line. A SIGKILL leaves no chance to log, so check the kernel. Step 1: search the kernel log for the OOM report; it names the process, its RSS and the cgroup. Step 2: if a cgroup limit was hit (constraint=CONSTRAINT_MEMCG), raise MemoryMax for that service or fix its memory use. Step 3: protect a critical process, such as the database, by lowering its oom_score_adj so the killer chooses something else.

bash
journalctl -k --since "1 hour ago" | grep -iE "out of memory|oom-kill"
# Out of memory: Killed process 4242 (worker) total-vm:..., anon-rss:3912345kB, ...
grep -E "MemTotal|MemAvailable|Committed_AS|CommitLimit" /proc/meminfo
cat /proc/$(pidof postgres | cut -d' ' -f1)/oom_score
# in the service unit: OOMScoreAdjust=-500 and MemoryMax=4G
systemctl show worker.service -p MemoryMax -p OOMScoreAdjust

Quick reference

  • getconf PAGESIZE prints the page size (4096 on most x86-64 and many ARM systems)
  • cat /proc/PID/maps lists mappings; pmap -x PID adds RSS per mapping
  • /proc/PID/smaps_rollup gives Rss, Pss and Swap totals for one process
  • ps -o pid,min_flt,maj_flt,rss,vsz -p PID shows faults and sizes
  • vm.overcommit_memory: 0 heuristic (default), 1 always, 2 strict
  • oom_score_adj ranges from -1000 (never kill) to 1000 (kill first)
  • Major fault = disk read; minor fault = page already in RAM or zero page

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A program calls malloc(1 GiB) but never touches the memory. What happens to RSS?

Question 2

2A page fault reads a page of a file that was not in the page cache. What kind of fault is it?

Question 3

3What does the s in r--s mean in /proc/PID/maps?

Question 4

4Ten processes each map the same 20 MiB library. What is the fairest way to count its memory per process?

Question 5

5With vm.overcommit_memory = 2, what usually happens when the commit limit is reached?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run cat /proc/self/maps and label each region: program code, heap, libraries, stack, vdso. Then run it again and note which addresses changed.

  2. Exercise 2medium

    Show copy-on-write after fork: allocate and touch 200 MiB, fork, and print the child's minor faults before and after it writes to the whole buffer.

  3. Exercise 3hard

    In a throwaway VM, run a program that allocates and touches memory in a loop until it is killed. Find the OOM report in the kernel log, then run it again with oom_score_adj set to -1000 for your shell and note what gets killed instead. Do not do this on a shared machine.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why is the VIRT column in top so much bigger than RES?
VIRT counts every mapping, including reserved but untouched memory, thread stacks and mapped files. RES is what is actually in RAM, and it is the number to watch for memory use.
Does each process have its own copy of libc in RAM?
No. The library's code pages are shared through the page cache, so they exist in RAM once. Only pages a process writes to, like its own data, become private copies.
What are transparent huge pages?
A kernel feature that automatically backs large anonymous regions with 2 MiB pages to reduce TLB misses. Check the mode in /sys/kernel/mm/transparent_hugepage/enabled; some databases recommend madvise mode or turning it off because of latency spikes.
Should I disable overcommit?
Usually not. Many programs reserve far more than they use, and strict mode makes them fail early. Mode 2 is used on some database servers where predictable allocation failure is better than a surprise OOM kill.

Go deeper

ShareXLinkedInWhatsApp