Advanced Linux and Operating
Systems
CPU and memory virtualization
One intensive study day, from course abstractions to Fedora internals
User program: C, libc, pthreads
System-call ABI and controlled CPU entry
Linux kernel: tasks, scheduler, virtual memory
x86-64 hardware: privilege, MMU, TLB, interrupts
Grounded in the supplied Maastricht University course material, OSTEP, Linux kernel documentation, Linux man-pages, and the current
x86-64 Linux entry path.
Architecture focus: Fedora on x86-64. AArch64 differences for the course Raspberry Pi are called out explicitly.
CPU and Memory Virtualization
Linux / Fedora study day
Contents
1 How to use this guide
1.1
What mastery means at the end of the day . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
The intensive schedule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3
Corrections to keep beside the course sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
5
5
6
2 The organising ideas: abstraction, indirection, and control
2.1
Linux is the kernel; Fedora is the operating environment . . . . . . . . . . . . . . . . . . . . . .
2.2
The OS offers three things at once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3
Virtualisation is not necessarily emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4
How the kernel regains control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7
7
7
7
7
3 Minimum machine and C foundation
8
3.1
What exists on one running hardware thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2
Instruction execution, memory, and devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3
From C source to a running process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4
The user-space address layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.5
C calls, libc calls, and syscalls are different . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.6
Five terms you must keep separate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4 Processes, tasks, and threads on Linux
4.1
A process is a web of state, not one box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2
PID, TID, TGID, and pthread_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.3
Each thread needs two execution contexts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.4
Abstract states and Linux states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.5
fork(): one return point, two tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.6
wait(): sleeping plus reaping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7
execve(): replace the program, preserve the process identity . . . . . . . . . . . . . . . . . . . .
4.8
Why a shell uses fork -> redirection -> exec -> wait . . . . . . . . . . . . . . . . . . . . . .
4.9
Pthreads are kernel-scheduled tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.10 What NPTL must build for one pthread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.11 The representative NPTL clone contract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.12 Five exits that sound alike but are not alike . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.13 A stack and TLS observation program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
11
11
12
12
12
13
13
14
14
14
15
17
17
5 Limited direct execution: fast execution with retained control
5.1
The apparent contradiction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2
CPU privilege is an execution mode, not a human role . . . . . . . . . . . . . . . . . . . . . . .
5.3
Controlled entries: syscall, exception, interrupt . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.4
Why timer interrupts matter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.5
Interrupts and exceptions: the other controlled doors . . . . . . . . . . . . . . . . . . . . . . . .
19
19
19
19
20
20
6 One x86-64 syscall, instruction by instruction
6.1
Layer 1: the application and libc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2
Layer 2: what syscall hardware does . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.3
Layer 3: Linux establishes a safe kernel context . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.4
Layer 4: common entry work and dispatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.5
A syscall can block and cause a context switch . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.6
Layer 5: return to user mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.7
Signals: kernel-arranged control transfer within user mode . . . . . . . . . . . . . . . . . . . . .
6.8
AArch64 Raspberry Pi comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.9
Who saves what, when? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.10 Function call, mode switch, and context switch: final comparison . . . . . . . . . . . . . . . . .
22
23
23
23
24
25
25
26
27
28
29
7 Privilege, credentials, and secure authorisation
7.1
Protection layers that are often called “privilege” . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2
Linux credentials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.3
Credentials are versioned kernel objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
30
30
30
31
Advanced introduction - 4 September 2026
2
CPU and Memory Virtualization
7.4
7.5
7.6
7.7
7.8
7.9
7.10
7.11
Linux / Fedora study day
IDs and capabilities answer different questions . . . . . . . . . . . . . . . . . . . . . . . . . . .
Where legitimate privilege gain comes from . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
A secure privilege-transition procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Saved IDs: temporary drop versus permanent drop . . . . . . . . . . . . . . . . . . . . . . . . .
Exec is both a loader and a security transaction . . . . . . . . . . . . . . . . . . . . . . . . . .
Fedora privilege observation lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What sudo actually changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defence in depth around the kernel boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32
32
33
34
34
34
35
35
8 Scheduling and context switching
8.1
Scheduling is a queueing policy over runnable tasks . . . . . . . . . . . . . . . . . . . . . . . . .
8.2
Metrics and assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.3
Work one schedule by events, not intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.4
How Linux gets from an interrupt to schedule() . . . . . . . . . . . . . . . . . . . . . . . . . .
8.5
A context switch is layered state management . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.6
One runqueue per logical CPU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.7
Linux scheduling-class order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.8
Affinity, migrations, and NUMA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8.9
The supplied cpu.c is an illustration, not a benchmark . . . . . . . . . . . . . . . . . . . . . . .
37
37
37
38
38
38
39
39
40
40
9 Memory virtualization: the contract and the machinery
9.1
Start with the simplest translation: base and bounds . . . . . . . . . . . . . . . . . . . . . . . .
9.2
Paging: fixed-size indirection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.3
The common x86-64 four-level walk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.4
TLBs: caching the result of translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
41
41
41
42
45
10 Linux virtual memory in operation
10.1 A VMA is mutable shared metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.2 Where a C program’s mappings come from . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.3 malloc reserves an address; touching commits work . . . . . . . . . . . . . . . . . . . . . . . . .
10.4 The page-fault path: exception, decision, retry . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.5 Anonymous, file-backed, shared and private . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.6 fork: copy the map, share the frames, fault on write . . . . . . . . . . . . . . . . . . . . . . . .
10.7 execve: replace mappings, retain process identity . . . . . . . . . . . . . . . . . . . . . . . . . .
10.8 Working sets, reclaim and swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.9 Physical allocation: from nodes to objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.10 Huge pages and TLB reach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.11 NUMA: coherent does not mean equally near . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.12 Memory protections as security mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
46
46
47
48
48
48
49
49
50
52
53
54
55
11 Parallelism: from the C abstract machine to cache lines
11.1 Why volatile counter++ is broken . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.2 What the mutex adds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.3 Atomics, invariants and scalable reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.4 Acquire/release intuition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.5 Linux kernel synchronisation toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.6 Scheduler and memory interact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
56
56
56
57
58
58
59
12 Fedora laboratory: predict, observe, explain, alter
12.1 Preparation and compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 Lab 1 - program image, process, and address space . . . . . . . . . . . . . . . . . . . . . . . . .
12.3 Lab 2 - fork, wait, exec, and a zombie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.4 Lab 3 - a syscall entry without mythology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.5 Lab 4 - threads are independently scheduled tasks . . . . . . . . . . . . . . . . . . . . . . . . .
12.6 Lab 5 - scheduling and migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.7 Lab 6 - demand paging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.8 Lab 7 - construct and measure copy-on-write . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.9 Lab 8 - race, mutex, atomic, reduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.10 Lab 9 - steady-state translation locality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
59
60
61
61
62
63
63
64
64
65
Advanced introduction - 4 September 2026
3
CPU and Memory Virtualization
Linux / Fedora study day
12.11 Advanced Fedora memory laboratories - stretch track . . . . . . . . . . . . . . . . . . . . . . . 65
13 Capstone trace: one command through the whole system
13.1 Shell and process creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.2 Executable image and lazy mappings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.3 Thread creation and scheduling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.4 Memory access and faults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.5 Synchronisation and coherence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.6 Output syscall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.7 Preemption and context switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13.8 Exit and collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
68
68
68
68
68
68
69
69
69
14 Closed-notes mastery test
14.1 Part A - compact explanations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.2 Part B - scheduling and concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.3 Part C - address translation and virtual memory . . . . . . . . . . . . . . . . . . . . . . . . . .
14.4 Part D - synthesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.5 Part E - the deeper mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.6 Scoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
70
70
70
71
71
72
72
15 Answer key and worked derivations
15.1 Answers 1-15: execution and privilege . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.2 Answers 16-24: scheduling and concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.3 Answers 25-38: virtual memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.4 Answers 39-42: synthesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.5 Answers 43-48: deeper mechanisms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
73
73
74
74
75
76
16 Continue beyond this week
77
16.1 A disciplined kernel-source method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
17 Course-material alignment and source audit
17.1 How the supplied files are used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.2 Version boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.3 Primary and course-aligned reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Advanced introduction - 4 September 2026
78
78
78
78
4
CPU and Memory Virtualization
Linux / Fedora study day
1 How to use this guide
This is not a list of definitions. It is a mechanism-first route through one question:
How can ordinary instructions run directly on a real CPU at nearly full speed, while the operating
system still retains control, isolates programs, shares CPUs and memory, and securely performs
operations that applications are forbidden to perform themselves?
The answer is a collaboration between hardware and the kernel. CPU virtualization uses protected execution
modes, controlled entries, interrupts, saved execution contexts, and scheduling. Memory virtualization uses
address translation, page tables, TLBs, faults, and kernel policy. Linux connects both through its central
schedulable object, the task.
The document uses three depth markers:
Marker
Meaning
What you should do today
COURSE
Directly supports the supplied
lectures, Lab 1, and the style of
the past exams.
Maps the abstraction to a modern
Linux system.
Architecture or kernel-entry detail
beyond the formal course.
Know it well enough to derive or
trace it on paper.
LINUX
DEEP
Understand the structures and
observe them on Fedora.
Follow the causal chain; do not
memorise every symbol.
The supplied syllabus forbids generative AI during assessed labs, checkpoint quizzes, and the final exam. This
guide is for independent preparation. Do the assessed work yourself and be able to reconstruct every answer
without the guide.
The target mental model
A process is not a little virtual computer stored somewhere inside Linux. A Linux task is a saved execution
context plus references to resources. When scheduled, its user instructions run directly on a hardware
thread. The MMU interprets their addresses through that task’s page tables. A syscall, fault, or interrupt
transfers that hardware thread to a kernel-controlled entry point; Linux saves enough state, does trusted
work, may schedule a different task, and eventually restores a valid user context.
1.1 What mastery means at the end of the day
You should be able to:
1. distinguish a program, process, thread, Linux task, CPU hardware thread, and kernel thread;
2. explain fork(), execve(), wait(), zombies, pthread creation, and the resources shared in each case;
3. trace one x86-64 syscall from a C wrapper through syscall, the kernel stack and pt_regs, dispatch, blocking
or scheduling, and sysretq/iretq;
4. explain why this CPU mode change is not the same as becoming root, and how UIDs, capabilities,
namespaces, seccomp, and SELinux instead govern authorisation;
5. distinguish a function call, syscall, exception, interrupt, signal, mode switch, and context switch;
6. derive base-and-bounds, segmentation, paging, and multi-level page-table translations;
7. explain TLB hits and misses, page faults, demand allocation, copy-on-write, file-backed mappings, reclaim,
and swap;
8. relate cache coherence to atomics, the C memory model, mutexes/futexes, and Linux SMP scheduling;
9. use ps, /proc, strace, readelf, objdump, gdb, taskset, and perf to test those explanations on Fedora.
1.2 The intensive schedule
This is about 8 hours 20 minutes of focused work inside a 10-hour day. Stop each block when its output criterion
is satisfied; merely reading to the end does not count.
Advanced introduction - 4 September 2026
5
CPU and Memory Virtualization
Linux / Fedora study day
Time
Block
Output criterion
09:00-09:35
Machine and C/ABI refresh
09:35-10:35
Processes, tasks, pthread
construction
10:35-10:50
10:50-12:20
12:20-13:00
Break
Syscalls, interrupts, exceptions,
signals
Privilege and protection lifecycle
13:00-13:45
13:45-14:55
Lunch
Scheduling and context switching
14:55-15:10
15:10-16:35
16:35-17:35
Break
Address translation and page
tables
Linux virtual memory
17:35-17:50
17:50-18:50
Break
SMP, races, mutexes, coherence
18:50-19:40
Fedora experiments and synthesis
19:40-20:00
Closed-notes self-test
Draw the five layers from C source
to hardware.
Explain the course programs, then
draw NPTL stack/TLS/clone/join
state.
Leave the screen.
Reconstruct each entry frame and
return path without notes.
Trace where authority originates,
how exec changes it, and how it is
dropped.
No passive video substitute.
Trace ready/running/blocked
transitions and one task switch.
Short walk.
Complete 4 KiB, 2 MiB and 1 GiB
walks and decode four fault cases.
Trace VMA/PTE locking,
allocation, COW, reclaim and
shootdown.
Reset.
Diagnose threads.v0.c at C, ISA,
cache, and kernel levels.
Produce your own trace of a
process from shell to exit.
Score at least 80%; schedule repair
topics otherwise.
1.3 Corrections to keep beside the course sheets
Two material-level architecture errors
First, the annotation on Lecture01-notes.pdf, p. 15 reverses x86 privilege rings. On x86/Linux, ring 0 is kernel
mode and ring 3 is user mode; rings 1 and 2 are normally unused. Second, Linux_Syscall_quickref.pdf is an
old 32-bit i386 reference. Its int 0x80 path, numbers such as getpid = 20, and old source paths are not the
native x86-64 ABI used by Fedora. Treat it as historical evidence that syscall ABIs are architecture- and
version-specific, not as a current table.
There are also deliberate teaching simplifications. A process is not kept in one contiguous physical block. A
printed C pointer is a virtual address. A context switch does not copy a process’s entire memory to disk. And
volatile does not repair the data race in threads.v0.c.
Advanced introduction - 4 September 2026
6
CPU and Memory Virtualization
Linux / Fedora study day
2 The organising ideas: abstraction, indirection, and control
2.1 Linux is the kernel; Fedora is the operating environment
The word Linux strictly names the kernel: the privileged code that handles hardware, scheduling, memory,
filesystems, networking, and protection. Fedora combines that kernel with glibc, the dynamic linker, systemd,
command-line tools, desktop services, SELinux policy, package management, and applications. In an OS course,
“the OS” often means the kernel because that is where the core mechanisms live. In daily administration, it
often means the whole Fedora system.
Linux is a monolithic kernel in the architectural sense: core services run in one privileged address domain and
call each other directly. It is modular because drivers and subsystems can be loadable modules. This differs
from a microkernel, which moves more services into separately protected user processes and communicates
through messages. The trade-off is not “modern versus old”; it is primarily fault isolation and modularity
versus communication and transition cost, with many hybrid designs in practice.
2.2 The OS offers three things at once
1. Abstractions. A process sees virtual CPUs, an address space, files, sockets, clocks, and other high-level
objects rather than raw controllers and DRAM rows.
2. Resource management. The kernel multiplexes finite CPUs, memory, devices, and bandwidth and chooses
policies for who runs, what stays resident, and what I/O proceeds.
3. Protection. The kernel is a reference monitor: it must mediate sensitive operations, check authority, isolate
principals, and retain control even when applications are malicious or broken.
The most reusable design distinction is mechanism versus policy. A timer interrupt and context-switch
routine are mechanisms; deciding which runnable task wins is policy. Page-table permissions and page-fault entry
are mechanisms; choosing what to evict is policy. Keeping these apart lets policies evolve without redesigning
the hardware boundary.
2.3 Virtualisation is not necessarily emulation
CPU virtualisation in this course means that each process behaves as if it owns a CPU. Most of the time, there
is no instruction-by-instruction interpreter. Its ordinary instructions execute natively. The illusion comes from
time multiplexing plus saved state.
Memory virtualisation means each process behaves as if it owns a private, contiguous address space. Its pages
may be scattered across physical frames, shared, absent, file-backed, or swapped. The illusion comes from
translation plus fault handling.
Both use the same pattern:
Requirement
CPU
Memory
Name the virtual object
Indirection
Fast path in hardware
Slow path into kernel
Protection
Policy
Task’s register context
Scheduler selects a task
Direct instruction execution
Syscall/interrupt/schedule
CPL and privileged instructions
Scheduling class and placement
Virtual address
Page table maps a page
TLB hit and cache access
Page fault
U/S, R/W, NX permissions
Allocation, reclaim, replacement
The one-sentence theory
An operating system safely virtualises a resource by naming an abstraction, placing a protected level
of indirection between that name and the hardware resource, executing the common case directly, and
retaining a controlled slow path where policy can intervene.
2.4 How the kernel regains control
If user code could disable all interrupts, rewrite page-table roots, access devices directly, or jump to arbitrary
kernel instructions, isolation would be impossible. Hardware therefore supplies:
• a less privileged user mode and a privileged kernel mode;
Advanced introduction - 4 September 2026
7
CPU and Memory Virtualization
Linux / Fedora study day
• instructions and registers available only in privileged mode;
• controlled entry mechanisms with kernel-chosen destinations;
• a programmable timer and external interrupts;
• address translation and permissions checked on every instruction fetch and data access.
The kernel can regain control because the user program cannot mask the relevant timer interrupt or alter its
handler. A blocking syscall also returns control voluntarily, but correctness cannot depend on every program
volunteering.
3 Minimum machine and C foundation
3.1 What exists on one running hardware thread
At an architectural level, a logical CPU has:
• general registers such as RAX, RDI, and RSP;
• an instruction pointer RIP and flags in RFLAGS;
• vector/SIMD and floating-point state;
• control registers such as CR3, which selects the page-table root;
• a current privilege level and segment-selector state;
• model-specific registers used for facilities such as syscall entry;
• local interrupt-controller and timer state.
The core also has caches, TLBs, branch predictors, and other microarchitectural state that software does not
save as part of the logical thread. A context switch restores the architectural contract, not a snapshot of every
cache line and predictor entry. This distinction explains why switching can be functionally correct yet still harm
performance through cold caches and TLBs.
On a multicore machine, each logical CPU can execute one architectural instruction stream at a time.
Simultaneous multithreading exposes two or more logical CPUs on one physical core; they share some execution
and cache resources. lscpu -e shows Linux’s CPU, core, socket, and NUMA-node view.
3.2 Instruction execution, memory, and devices
The simple lecture diagram is still useful: a CPU fetches instructions and data from memory and communicates
with device controllers. Modern details refine the path:
• loads and stores usually hit caches; coherence keeps copies of a cache line compatible across cores;
• the MMU translates virtual addresses before protected memory access;
• many devices are reached through memory-mapped I/O over PCIe rather than old port I/O;
• drivers place descriptors in memory and notify a controller, often by a “doorbell” register;
• a controller can use DMA to transfer data without the CPU copying every byte;
• an IOMMU can constrain device-visible DMA addresses, just as the MMU constrains CPU addresses;
• completion normally raises an interrupt, after which kernel code wakes waiting work.
DMA means “the device can move data”, not “the OS is uninvolved”. The kernel driver sets up buffers,
mappings, ownership, and completion handling. Without an IOMMU or trustworthy devices, unrestricted
DMA could bypass CPU page protection.
3.3 From C source to a running process
For a command such as:
gcc -std=c17 -Wall -Wextra -Wpedantic -O0 -g -o p1 p1.c
./p1
the relevant stages are:
1. Preprocessing: headers and macros form a translation unit.
2. Compilation: C’s abstract-machine operations become target assembly, subject to the C language’s rules
and undefined behaviour.
3. Assembly: instructions and data become a relocatable ELF object.
4. Linking: the linker resolves symbols and produces an ELF executable, often a position-independent
executable on Fedora.
Advanced introduction - 4 September 2026
8
CPU and Memory Virtualization
Linux / Fedora study day
5. Execution: the shell creates a child and calls an exec function. The kernel’s ELF loader maps loadable
segments and starts the requested interpreter for a dynamically linked binary.
6. Dynamic linking: ld-linux maps libraries, performs relocations, prepares thread-local storage, and transfers
control to the executable’s entry point _start.
7. C runtime: startup code obtains argc, argv, the environment and auxiliary vector, initialises libc, calls main,
and converts a return from main into process termination.
Observe the layers before continuing
Run these against a compiled course program:
file ./p1
readelf -hW ./p1
readelf -lW ./p1
readelf -dW ./p1
ldd ./p1
objdump -d -Mintel ./p1 | less
In readelf -lW, distinguish ELF program headers such as PT_LOAD from source-level ideas such as “the code
section”. The kernel loader primarily consumes program headers. In objdump, find main, then notice that
calls such as getpid@plt initially go through the Procedure Linkage Table rather than directly naming kernel
code.
3.4 The user-space address layout
A typical dynamically linked process contains multiple virtual mappings:
Region
Typical content
Important fact
Executable mappings
Shared libraries
machine code and read-only
constants
initialised and zero-initialised
globals
allocator arenas and large
allocations
libc, loader, other DSOs
Per-thread stack
frames, locals, return addresses
Thread-local storage
variables with thread storage
duration, libc thread state
kernel-exported user-space helpers
and data
permissions usually separate
writable data from executable code
BSS need not occupy equivalent
bytes in the file
malloc is a library API, not itself a
syscall
independently mapped and
commonly position-independent
each pthread needs its own user
stack
x86-64 Linux commonly addresses
it through the FS base
some clock calls avoid a kernel
entry
Data and BSS
Heap-related mappings
vDSO/vvar
This is a virtual layout, not a promise of physically contiguous RAM. Mappings can lack resident pages until
first use.
3.5 C calls, libc calls, and syscalls are different
Under the System V AMD64 C ABI, the first six ordinary integer/pointer function arguments use RDI, RSI, RDX
, RCX, R8, R9. A call instruction saves a return address on the current user stack and jumps within the current
privilege domain.
A libc function may:
• do all work in user space (strlen);
• buffer or transform work before a syscall (printf);
• invoke a syscall wrapper (write);
• use a vDSO helper and usually avoid entry (clock_gettime on supported systems);
• invoke a different underlying syscall than its name suggests (fork, open, or wait wrappers can map to
clone/openat/wait variants).
Advanced introduction - 4 September 2026
9
CPU and Memory Virtualization
Linux / Fedora study day
The x86-64 Linux syscall ABI is separate: number in RAX; arguments in RDI, RSI, RDX, R10, R8, R9; result in RAX.
The fourth register differs because the syscall instruction overwrites RCX and R11.
3.6 Five terms you must keep separate
Term
Meaning
Program
Passive code and data representation, commonly an
executable file.
POSIX/user-facing resource and protection context,
conventionally a Linux thread group plus its shared
resources.
One sequential execution stream with its own
registers and stack.
One kernel-schedulable task_struct; this may be a user
thread or a kernel thread.
One CPU execution context on which Linux can
schedule a task.
Process
Thread
Linux task
Hardware thread / logical CPU
Retrieval checkpoint 1
Without looking back, answer: Why can two programs print the same pointer value without sharing
memory? Why can printf execute many ordinary function calls but only occasionally enter the kernel?
Which register differs between the C ABI’s fourth argument and the syscall ABI’s fourth argument, and
why?
Advanced introduction - 4 September 2026
10
CPU and Memory Virtualization
Linux / Fedora study day
4 Processes, tasks, and threads on Linux
4.1 A process is a web of state, not one box
Introductory diagrams use a process control block (PCB) containing a PID, state, saved registers, and memory
information. This is the right abstraction: the kernel needs durable state from which it can stop and later resume
an execution. Linux distributes that state among linked, reference-counted structures rather than putting every
resource directly in one record.
At the centre is one struct task_struct per schedulable task. Important references include:
Linux object
task_struct
kernel stack + architecture thread
state
mm_struct
files_struct
fs_struct
sighand_struct
signal_struct
cred
nsproxy and namespace
memberships
What it represents
Commonly shared by pthreads?
identity, task state, scheduling
entity, relationships, pending work
suspended kernel call chain and
low-level saved state
virtual-memory areas and
page-table root
file-descriptor table
current/root directory and umask
installed signal actions
thread-group-wide
signal/accounting state
UIDs, GIDs, capabilities and
related security state
No; one per thread
views of PIDs, mounts, network
and other global resources
No; one per thread
Yes (CLONE_VM)
Yes (CLONE_FILES)
Yes (CLONE_FS)
Yes (CLONE_SIGHAND)
Yes (CLONE_THREAD)
Logically process-wide under
POSIX; represented per task with
coordinated updates
Usually shared until explicitly
unshared
The clone()/clone3() flags decide which objects a new task shares. This is the unifying Linux idea behind both
process creation and threads:
• a fork-like child gets a new task and distinct process-level containers such as an mm_struct and descriptor table,
while COW frames, open-file descriptions, immutable credentials and namespace objects can still be shared
by reference;
• a pthread-like child gets a new task but shares the address space, descriptor table, signal dispositions and
thread-group identity;
• containers add namespaces and cgroups; they do not create a separate kernel.
A better definition
A Linux task is an independently schedulable execution stream. A conventional Linux “process” is a thread
group whose tasks share an address space and other process-level resources. The distinction is made by
sharing relationships, not by two unrelated species of kernel object.
4.2 PID, TID, TGID, and pthread_t
Linux internally assigns a PID-like identifier to every task. For the first task in a thread group, its task ID
equals the thread-group ID (TGID); this is the process ID shown by getpid(). Other threads have distinct task
IDs returned by Linux gettid() but share the TGID.
pthread_t is a user-space, opaque POSIX thread handle.
Do not assume it numerically equals a kernel TID.
Observe the distinction:
ps -eLo pid,tid,tgid,ppid,psr,stat,comm | less
ls /proc/$$/task
grep -E '^(Name|Pid|Tgid|PPid|Threads|Cpus_allowed_list):' /proc/$$/status
exposes each thread. PID namespaces can give the same task different visible IDs at
different namespace levels, so an identifier is always relative to a view.
/proc/<TGID>/task/<TID>/
Advanced introduction - 4 September 2026
11
CPU and Memory Virtualization
Linux / Fedora study day
4.3 Each thread needs two execution contexts
A user thread has:
1. a user context: user registers, instruction pointer, user stack, TLS, and access to the process’s user
mappings;
2. a kernel continuation: a per-task kernel stack and saved low-level state used while the task is inside a
syscall, exception, or other kernel path.
The kernel stack is not where ordinary C local variables from user code live. It is a protected stack used by
kernel functions executing on behalf of that task. This makes blocking natural: if a read() sleeps, its kernel
call frames remain on that task’s kernel stack. Another task uses another kernel stack. When the first task is
scheduled again, it resumes the suspended kernel path and can later return to user mode.
Kernel threads are tasks that execute kernel functions without a normal user address space; they typically have
no mm_struct of their own.
4.4 Abstract states and Linux states
The course state machine separates ready, running, blocked, and dead. Linux’s visible letters refine it:
ps state
Interpretation
Typical cause
S
running on a CPU or runnable
on a run queue
interruptible sleep
D
uninterruptible sleep
computing or waiting to be
selected
timer, pipe, terminal, socket, wait
queue
usually a kernel wait that ordinary
signals must not interrupt
SIGSTOP or Ctrl+Z/SIGTSTP
debugger/ptrace
parent has not collected status
internal kernel work
R
stopped by job control
stopped while traced
zombie: exited but not reaped
idle kernel thread
T
t
Z
I
Linux’s internal TASK_RUNNING covers both the abstract ready and currently running cases. A global observation
cannot reliably distinguish them at every instant because state is changing while tools read it.
The ordinary transition story is:
Runnable
schedule
Running
block
Sleeping
preempt
exit
wake
Zombie
A zombie is not running and no longer owns its old user address space. Linux retains enough identity, exit
status and accounting information for the parent. It may remain indefinitely if the parent remains alive and
never waits. An orphan is different: it is a live child whose parent exited; it is reparented to an init process or
configured subreaper.
4.5 fork(): one return point, two tasks
Conceptually, fork() duplicates the calling process. On success:
• the parent receives the child’s PID;
• the child receives zero;
• both resume after the same call;
• their scheduling order is unspecified;
• the child has a logically separate address space with initially identical contents;
• descriptor-table entries in each process refer to the same underlying open-file descriptions, so offsets and file
status flags can be shared;
Advanced introduction - 4 September 2026
12
CPU and Memory Virtualization
Linux / Fedora study day
• only the calling thread is reproduced if the parent was multithreaded.
Linux does not eagerly copy every user page. It copies page-table structure as needed, marks writable private
mappings copy-on-write, and initially lets parent and child PTEs refer to the same physical frames. A later
write faults and creates a private copy. This is why fork() can be much cheaper than the size of the process
suggests, although copying and later modifying large page tables still has costs.
Modern glibc implements its fork() wrapper using a clone-family kernel mechanism and runs registered
pthread_atfork handlers. The POSIX abstraction remains fork; do not replace portable semantics with one current
implementation detail.
4.5.1 Reading p1.c precisely
The first printf is executed once before the fork. After fork, two schedulable tasks reach different branches. The
child and parent messages can appear in either order because there is no ordering relationship between them.
There is a libc subtlety. When stdout is a terminal, the newline usually flushes the first line before fork. When
output is redirected, the first line may remain in a block-buffered user-space FILE buffer. That buffer is copied
by fork; if both processes later flush it, the apparent pre-fork line can be printed twice. The syscall did not
duplicate; user-space buffered state did.
Try:
for i in {1..5}; do ./p1; done
./p1 > redirected.txt
cat redirected.txt
strace -f -e trace=clone,fork,vfork,write,exit_group ./p1
Exact wrapper syscalls may differ by libc and architecture. Trust the trace for your machine.
4.6 wait(): sleeping plus reaping
wait()/waitpid() combines two ideas:
1. if no selected child has exited, the parent can sleep on a kernel wait queue rather than consume CPU;
2. once a child has exited, the parent collects status and releases the zombie record.
In p2.c, the parent’s final printf must happen after the child terminates because it follows successful wait(NULL).
wait does not force alternation and does not determine every earlier output order.
Production code should check failure and decode status. The fragment below assumes the parent saved a
successful fork() result in pid_t child and included <errno.h>, <sys/types.h>, and <sys/wait.h>:
int status;
pid_t got;
do {
got = waitpid(child, &status, 0);
} while (got == -1 && errno == EINTR);
if (got == -1)
perror("waitpid");
else if (WIFEXITED(status))
printf("exit status = %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("terminated by signal = %d\n", WTERMSIG(status));
A terminating child records status, notifies the parent (normally with SIGCHLD semantics), and wakes eligible
waiters. The awakened parent becomes runnable; that does not guarantee immediate execution.
4.7 execve(): replace the program, preserve the process identity
execve() is often described carelessly as creating a new process. It does not. On success, the calling process keeps
its PID but acquires a new program image:
• old user mappings are replaced by mappings for the main ELF image, its requested interpreter, a fresh stack,
vDSO and related state; the userspace dynamic linker maps shared libraries afterward;
• registers are initialised for the new entry point and stack;
• the calling thread becomes the sole surviving thread in the process;
Advanced introduction - 4 September 2026
13
CPU and Memory Virtualization
Linux / Fedora study day
• file descriptors remain open unless marked close-on-exec (FD_CLOEXEC);
• current directory, root directory and many identity attributes remain;
• caught signal dispositions are reset, while other attributes follow documented exec rules;
• set-user-ID, set-group-ID and file capabilities may transform credentials, subject to security constraints.
The change must be close to transactional: the kernel constructs and validates the new image before committing
away the old one, although rare late failures make the full implementation more subtle than a perfect transaction.
In the single-threaded p3.c, execvp("wc", ...) searches PATH in libc and ultimately requests an exec. Success never
returns to the old C code. The line after it is only an error path. This program can report that path with:
execvp(myargs[0], myargs);
perror("execvp");
_exit(127);
_exit avoids flushing copied stdio state. After a fork() from a multithreaded program, only async-signal-safe
operations are generally safe in the child before an exec, because locks held by vanished threads may remain
locked; perror is not on that safe list. Such a child should perform only a predesigned minimal fd/exec path and
report failure with safe primitives or to the parent.
4.8 Why a shell uses fork -> redirection -> exec -> wait
For a simple external command, a shell needs to preserve itself while creating a process that can alter file
descriptors and then replace its program. A typical path is:
1. shell calls fork or an optimised spawn mechanism;
2. child uses open, pipe, dup2, close, process-group calls, and then execve;
3. parent records the job and waits for a foreground command or returns immediately for a background job;
4. kernel schedules both according to policy.
An exec preserves open descriptors intentionally: this is how a pipe endpoint or redirected file becomes the new
program’s stdin/stdout. FD_CLOEXEC prevents accidental leakage of unrelated descriptors.
4.9 Pthreads are kernel-scheduled tasks
On current Linux, glibc’s Native POSIX Thread Library uses a one-to-one model: each pthread corresponds to
a Linux task visible to the scheduler. Thread creation uses clone-family functionality with sharing flags, a new
user stack, TLS setup, and kernel/user bookkeeping for joining and cancellation.
Threads in one process share mappings, so a pointer can name the same object in each thread. They do not
share register values or user stacks. A process with four runnable pthreads can run on four logical CPUs
simultaneously if affinity and scheduling permit.
pthread_join(t, ...) waits for thread t and creates an ordering relationship between the completed thread’s effects
and the successful joiner’s later execution. It does not make two worker threads mutually ordered while both
run.
4.10 What NPTL must build for one pthread
pthread_create() is not a thin spelling of one kernel syscall. On Fedora, glibc’s Native POSIX Thread Library first
constructs user-space state, then uses a clone-family operation to create a Linux task that shares the process
resources required by POSIX.
A new pthread needs at least:
State
Where it lives
General registers, instruction
pointer and stack pointer
CPU while running;
task/kernel save areas while
stopped
The process’s shared mm_struct
User stack mapping and guard
region
Advanced introduction - 4 September 2026
Shared with sibling pthreads?
No
The mapping is addressable by all
threads, but one thread owns its stack
discipline
14
CPU and Memory Virtualization
Linux / Fedora study day
State
Where it lives
Thread-local storage (TLS)
and thread control block
The process’s shared mappings,
selected by a per-thread TLS
base
Kernel memory attached to the
task
Per-task kernel state
Kernel stack and architecture
thread state
TID, scheduler entity, signal
mask, affinity, alternate signal
stack
Address space, descriptor table,
current directory and signal
dispositions
Shared kernel objects
Shared with sibling pthreads?
One instance per thread
No
No
Yes
The distinction in the second row is subtle and important. A pthread’s stack is private by convention, not by
page-table protection. Because all pthreads share the same page tables, a wild pointer in one thread can corrupt
another thread’s stack or TLS. Process isolation is a protection boundary; a thread boundary normally is not.
The initial thread’s user stack is created as part of execve() image setup. For later pthreads, glibc normally obtains
a stack mapping, reserves a guard region, creates a thread descriptor and TLS block, and chooses an initial
stack pointer. The default stack size is influenced by process limits and glibc policy. pthread_attr_setstacksize()
and pthread_attr_setguardsize() let a program request different values. On x86-64 the stack normally grows toward
lower addresses; a guard mapping with no access permission turns some overflows into a page fault, but it
cannot detect every out-of-bounds access.
glibc may cache a terminated worker’s stack mapping for reuse, so a successful pthread_join() does not imply an
immediate munmap(). The lifetime of automatic objects on that stack still ended when their block/thread ended;
a stale pointer is invalid even if the virtual mapping happens to remain. RSS and virtual-size observations must
therefore be interpreted as allocator/runtime policy, not as a direct count of live pthreads.
4.10.1 TLS is an address-selection mechanism
Each pthread sees a distinct object for a declaration such as:
static _Thread_local unsigned long requests;
The compiler does not need a separate instruction set for every TLS variable. It emits an access relative to the
thread’s TLS base, directly or through a dynamic-loader helper depending on the ELF TLS model. On x86-64
Linux, ordinary user TLS is conventionally anchored by the FS base. The thread control block points to runtime
metadata such as the dynamic thread vector used for TLS in loaded shared objects. glibc also implements
per-thread state such as errno through TLS.
The numeric address of a TLS object therefore differs between pthreads even though the source-level name is
identical. The scheduler or low-level switch machinery must make the correct TLS base effective whenever a
different task is resumed. For a new task, CLONE_SETTLS supplies its initial architecture-specific TLS value.
Stack and TLS do not create isolation
Different stack pointers and TLS bases make ordinary code select different storage. They do not prevent
another pthread from manufacturing a pointer to that storage. All of these pages remain in one shared
virtual address space.
4.11 The representative NPTL clone contract
Exact glibc code and whether it uses clone or clone3 vary by architecture and release. A representative pthread
creation requests a combination resembling:
CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |
CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS |
CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID
Interpret the flags as a sharing graph, not a magic constant:
Advanced introduction - 4 September 2026
15
CPU and Memory Virtualization
Flag
CLONE_VM
CLONE_FS
CLONE_FILES
CLONE_SIGHAND
CLONE_THREAD
CLONE_SYSVSEM
CLONE_SETTLS
CLONE_PARENT_SETTID
CLONE_CHILD_CLEARTID
Linux / Fedora study day
Contract relevant to pthreads
Share one address space and page tables.
Share current/root directories and umask state.
Share one file-descriptor table.
Share installed signal dispositions. It requires CLONE_VM.
Join the parent’s thread group and share
thread-group signal/accounting state. It requires
CLONE_SIGHAND.
Share System V semaphore adjustment state.
Install the new task’s TLS base from an
architecture-specific argument.
Store the new TID at a supplied parent-visible
address before creation returns.
At task exit, clear a supplied user-space TID word
and perform a futex wake on it.
There may be additional flags and setup for a particular glibc version. clone3() also packages arguments differently.
What matters is the contract: the kernel creates a separately schedulable task, while glibc has already prepared
the user stack, start trampoline, TLS, cancellation state and thread descriptor that make it a POSIX pthread.
The new task begins at a runtime trampoline rather than by magically returning through the caller’s C stack.
The trampoline establishes runtime invariants and calls the requested start routine. Since parent and child can
run immediately on different CPUs, every field consumed by the child must be fully published before creation
makes the child visible.
4.11.1 How pthread_join() reaches a sleeping kernel task
A joinable thread needs both a result handoff and a reliable death notification. A simplified NPTL lifecycle is:
1. glibc allocates and initialises the stack, TLS and thread descriptor, including a TID/liveness word.
2. The clone operation creates the task and asks the kernel to clear that word on exit.
3. If pthread_join() finds the target still alive, it waits using a futex-based loop on the word.
4. The exiting task enters the kernel for final task exit. The kernel stores zero to the clear-child-TID address
and futex-wakes waiters.
5. The joiner rechecks the predicate, obtains the thread’s result, and lets glibc reclaim or cache resources.
The check must be a loop. A futex wake is not a stored permit; it merely makes some current waiter runnable.
Values can change before a waiter runs, and futex waits can return for other reasons. Correctness lives in the
user-space state machine and its atomic/memory-ordering protocol; the futex supplies an atomic compare-andsleep operation plus wakeup queues.
This also explains why the kernel cannot simply treat the user stack as all of the thread. The kernel task can
be gone while glibc still retains a join result and a stack/TLS allocation. Kernel-task lifetime, POSIX-thread
lifetime and mapping lifetime meet at exit/join, but they are not identical.
Advanced introduction - 4 September 2026
16
CPU and Memory Virtualization
Operation in a multithreaded process
Linux / Fedora study day
Normal effect on Linux/glibc
4.12 Five exits that sound alike but are not alike
Operation in a multithreaded process
Normal effect on Linux/glibc
Worker start routine returns
Terminates that pthread and publishes the return
value as though passed to pthread_exit;
thread-specific-data destructors run. Outstanding
cleanup handlers are not invoked merely by returning.
Terminates only the caller; other pthreads continue.
Registered cleanup handlers are popped/executed
and thread-specific-data destructors run. If the initial
thread calls it, the process can remain alive.
Performs process-level libc termination, including
registered handlers and stdio flushing, then
terminates the thread group.
Skips user-space cleanup and terminates the process;
on Linux the wrapper uses a group-exit operation.
Terminates only the calling Linux task. It is neither
POSIX _exit() nor a substitute for pthread_exit: it
bypasses NPTL cleanup/accounting and can violate
libc invariants.
pthread_exit(value)
return from main or exit(status)
glibc _exit(status) / _Exit(status)
raw syscall(SYS_exit, status)
A joinable pthread that terminates retains enough user-space runtime state for another pthread to join it once
and collect its return value. A detached pthread cannot be joined; the runtime arranges automatic reclamation
after termination. Detaching is a lifetime decision, not a request to schedule the thread independently.
Fatal signals and explicit exit_group paths can terminate the whole thread group. By contrast, ordinary threaddirected signals and cancellation requests need not. POSIX cancellation is normally deferred to cancellation
points; it is not a general-purpose forced destruction of a task at an arbitrary instruction.
Three different ownership questions
Ask separately: Is the Linux task still schedulable? Is the POSIX thread still joinable? Does its stack/TLS
mapping still exist? A single word such as “dead” hides these different lifetimes.
4.13 A stack and TLS observation program
Compile this Fedora/glibc-oriented experiment with gcc -O2 -g -Wall -Wextra -pthread tls-stack.c -o tls-stack:
#define _GNU_SOURCE
#include <asm/prctl.h>
#include <errno.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <unistd.h>
static int shared_global;
static _Thread_local unsigned long tls_value;
static void *worker(void *arg)
{
long index = *(long *)arg;
int automatic_local = 0;
unsigned long fs_base = 0;
pthread_attr_t attr;
void *stack_low = NULL;
size_t stack_size = 0;
Advanced introduction - 4 September 2026
17
CPU and Memory Virtualization
Linux / Fedora study day
size_t guard_size = 0;
int e = pthread_getattr_np(pthread_self(), &attr);
if (e != 0) {
errno = e;
perror("pthread_getattr_np");
return NULL;
}
e = pthread_attr_getstack(&attr, &stack_low, &stack_size);
if (e == 0)
e = pthread_attr_getguardsize(&attr, &guard_size);
if (e != 0) {
errno = e;
perror("pthread_attr_getstack/guardsize");
pthread_attr_destroy(&attr);
return NULL;
}
pthread_attr_destroy(&attr);
if (syscall(SYS_arch_prctl, ARCH_GET_FS, &fs_base) == -1)
perror("ARCH_GET_FS");
tls_value = (unsigned long)index;
printf("pid=%jd tid=%jd local=%p tls=%p errno=%p global=%p "
"FS=%#lx stack=[%p,+%zu] guard=%zu\n",
(intmax_t)getpid(), (intmax_t)syscall(SYS_gettid),
(void *)&automatic_local, (void *)&tls_value, (void *)&errno,
(void *)&shared_global, fs_base, stack_low, stack_size, guard_size);
return (void *)(uintptr_t)(index + 100);
}
int main(void)
{
pthread_t threads[2];
long index[2] = {0, 1};
for (size_t i = 0; i < 2; i++) {
int e = pthread_create(&threads[i], NULL, worker, &index[i]);
if (e != 0) {
errno = e;
/* pthread functions return error codes */
perror("pthread_create");
exit(EXIT_FAILURE);
}
}
for (size_t i = 0; i < 2; i++) {
void *result;
int e = pthread_join(threads[i], &result);
if (e != 0) {
errno = e;
perror("pthread_join");
exit(EXIT_FAILURE);
}
printf("joined %zu: result=%lu\n", i,
(unsigned long)(uintptr_t)result);
}
}
Do not predict exact addresses. Predict equalities: same PID and global address; different TIDs, stack-local
addresses, TLS addresses, errno addresses and usually FS bases. Then trace clone/clone3, futex, exit and exit_group.
A trace may omit a futex wait if a worker has already terminated when its joiner checks the liveness word.
Thread construction checkpoint
Why can one pthread corrupt another’s stack even though each has its own stack pointer? What does
CLONE_SETTLS establish? Why does joining require a predicate loop rather than one unconditional futex wait?
Distinguish a worker returning, the initial thread calling pthread_exit, and main returning.
Advanced introduction - 4 September 2026
18
CPU and Memory Virtualization
Linux / Fedora study day
Course-to-Linux bridge
The course PCB is a sound abstraction for “everything required to resume and manage a process”. In Linux,
ask which part is per task and which object is shared. The course process state is also sound, but Linux
attaches scheduling state to individual tasks and merges ready/running into R for common observations.
Retrieval checkpoint 2
Explain four claims aloud: (1) fork() returns twice without returning twice in one execution stream; (2)
successful execve() changes the program but not the PID; (3) a zombie is dead yet still has a PID; (4)
two pthreads are part of one process but are independently schedulable. Then draw which of task_struct,
mm_struct, kernel stack and file table are shared by two pthreads.
5 Limited direct execution: fast execution with retained control
5.1 The apparent contradiction
To make a process fast, run its instructions directly on the CPU. To make a process safe, do not let it control
the machine. Limited direct execution resolves this with three rules:
1. ordinary user instructions execute natively in a restricted mode;
2. sensitive events enter only kernel-chosen code through hardware-defined gates;
3. timer and device interrupts let the kernel regain control independently of the program.
If the OS were merely a library, a program could decline to call it and run forever. If every instruction were
interpreted by the OS, control would be easy but the common case would be slow. Hardware protection makes
direct execution conditional.
5.2 CPU privilege is an execution mode, not a human role
x86 defines current privilege levels CPL 0 through 3. Linux uses:
• CPL 3: ordinary user code;
• CPL 0: kernel code;
• rings 1 and 2: normally unused by Linux.
The selector state in CS encodes CPL. In long mode, segmentation is largely flattened for normal addressing, but
its privilege machinery and descriptors still participate in transitions.
Instructions such as writing CR3, configuring interrupt tables, changing control registers, halting the CPU, and
direct port I/O under ordinary settings are privileged. An attempt from CPL 3 raises an exception; it does not
“try and maybe corrupt the machine”.
SYSCALL must not be a privileged instruction.
It is the permitted door from user code. Security comes from the
door’s fixed destination and the kernel’s validation, not from preventing users from knocking.
The crucial language correction
A syscall does not elevate the thread’s user identity. The CPU begins executing a trusted kernel
continuation at CPL 0 on behalf of the same task. The task’s UID and capabilities do not become
root. Every ordinary unprivileged process enters CPL 0 when it makes a syscall; kernel code then checks
what that task is authorised to request.
5.3 Controlled entries: syscall, exception, interrupt
Event
Synchronous with
current instruction?
Example
System call
Yes, deliberate
syscall, AArch64 svc #0
Exception/fault
Yes
page fault, divide error,
invalid opcode
Advanced introduction - 4 September 2026
How control target is
chosen
privileged entry
configuration
exception vector in
kernel-owned table
19
CPU and Memory Virtualization
Linux / Fedora study day
Event
Synchronous with
current instruction?
Trap in narrow CPU
terminology
Maskable interrupt
Yes, reported after
instruction
No
NMI-like event
No or exceptional
Example
How control target is
chosen
breakpoint
exception vector
timer, network/NVMe
completion
NMI, machine check
interrupt controller and
IDT
special vector/entry rules
OSTEP and many courses use “trap” generically for a deliberate system-call entry. x86 manuals use
fault/trap/abort more narrowly for exception classes. Always infer the intended level of terminology.
A signal is different again. It is a kernel abstraction delivered to a task. A hardware exception or another
process’s kill request can cause Linux to mark a signal pending. Before returning to user mode, the kernel may
rewrite the saved user context so execution first enters a user-space signal handler. sigreturn later asks the kernel
to restore a validated saved context.
5.4 Why timer interrupts matter
Suppose a user loop never syscalls:
for (;;) { /* pure computation */ }
When scheduling or timer policy requires a future deadline, Linux programs a local timer event. Its expiry
interrupts the loop, lets Linux account time, and may set a rescheduling request; at a valid exit point the
scheduler can run a different task. This is how compute-bound competitors can be time-sliced without voluntary
calls.
Modern Linux can stop the periodic scheduling tick while CPUs are idle and, with full-dynticks configuration,
while one suitable task runs. If new competition appears, another CPU can send a reschedule IPI; device
interrupts and synchronous exceptions are additional controlled entries. The durable requirement is that user
mode cannot block kernel-chosen entry events, not that every return to user mode arms a fixed-frequency tick.
5.5 Interrupts and exceptions: the other controlled doors
SYSCALL is only one way to enter the kernel. Regular faults and traps are synchronous with the current instruction
stream, while an interrupt reports an event that is logically independent of it. Machine checks and NMI-like
exceptional paths can be asynchronous or imprecise and need their own rules. IDT-based entries use the x86
Interrupt Descriptor Table, not the LSTAR target used by SYSCALL.
5.5.1 The IDT is a kernel-owned dispatch table
Each logical CPU has an IDTR register naming an IDT. An x86-64 IDT gate contains, among other fields:
• a 64-bit handler offset and a kernel code-segment selector;
• a gate type, present bit, and descriptor privilege level (DPL);
• an Interrupt Stack Table (IST) index.
The vector number selects one of 256 gates. Architecturally assigned exceptions occupy the low vectors. Linux
and the interrupt controllers allocate other vectors to local timers, inter-processor interrupts, and external
devices. For a device interrupt, an I/O APIC or MSI/MSI-X message routes the event to a target local APIC,
which presents a vector to that CPU. The vector is therefore the CPU entry key; the device IRQ number and
the eventual Linux handler are related by kernel-maintained routing state, not by identity.
Gate DPL is often misunderstood. It controls whether less-privileged code may deliberately invoke that gate
with an instruction such as int n. It does not let user code redirect a hardware interrupt, and it is not the
permission check for an exception generated by the CPU. Linux keeps ordinary interrupt gates inaccessible to
CPL 3 and exposes only carefully chosen software-entry gates where required.
The privilege rules have several independent inputs:
• CPL is the privilege of the code currently executing;
• the selected code descriptor determines the privilege of the destination;
• an explicit selector also contains a requested privilege level (RPL);
Advanced introduction - 4 September 2026
20
CPU and Memory Virtualization
Linux / Fedora study day
• the U/S bit in each page-table leaf independently controls user-mode memory access;
• IOPL plus the TSS I/O bitmap controls direct port-I/O instructions.
Linux normally uses CPL 3 for applications and CPL 0 for the kernel. A supervisor-only page remains
inaccessible at CPL 3 even if it is mapped, and an IDT gate cannot grant arbitrary access to it. The transition
selects a fixed kernel entry point that must still treat all user-derived state as untrusted.
5.5.2 What hardware pushes, and which stack receives it
For a normal user-to-kernel IDT entry, the processor obtains the ring-0 stack pointer from TSS.RSP0, changes to
that stack, and records the interrupted user context. The 64-bit architectural frame contains user RIP, CS, RFLAGS,
RSP, and SS. Some exceptions also push an error code. On an event that remains at the same CPL, x86 ordinarily
continues on the current stack unless IST is requested; 64-bit IDT entry still records the stack state, giving the
return path a regular frame shape.
An IDT gate can instead name one of the TSS’s IST entries. IST selects a dedicated known-good stack regardless
of the interrupted stack. Linux uses this facility for entry classes that must remain viable when the ordinary
kernel stack may be corrupted, exhausted, or already involved in a nested exceptional path. IST is not a new
privilege level; it is an emergency stack-selection mechanism.
Hardware does not push all general-purpose registers. Linux’s assembly entry stubs save the remaining registers
and normalise differences among entry frames so later code can use a consistent pt_regs view. This is one
reason that a diagram showing “the CPU saves the process state” is too vague: hardware creates a minimum
architectural frame, entry assembly completes the kernel’s software frame, and the scheduler preserves a different
continuation when switching tasks.
Exception error codes are event-specific. A page fault pushes a bit field describing facts such as present-versusnot-present, read-versus-write, user-versus-supervisor, reserved-bit violation, instruction fetch, or protection-key
involvement. The faulting linear address is written to CR2; it is not pushed as part of the exception frame. A
general-protection fault pushes a different kind of error code, and invalid opcode (#UD) pushes none. Entry stubs
must account for these shape differences before calling common code.
A useful stack invariant
Before ordinary C code runs, entry assembly must be on a trusted kernel stack with a frame whose layout
the kernel controls. The interrupted user can influence register values and may have arranged a malicious
user stack, but cannot choose the IDT target, TSS.RSP0, an IST pointer, or the kernel’s interpretation of the
entry class.
5.5.3 Fault, trap, and abort are restart semantics
Intel’s narrow terminology classifies exceptions by where the saved instruction pointer refers and whether restart
is meaningful:
• a fault is normally reported before architectural completion, so the saved RIP identifies the instruction to
retry; a demand page fault is the central example;
• a trap is normally reported after the triggering instruction; a breakpoint or single-step event is the usual
example;
• an abort reports a severe condition for which a precise restart point may not be available, such as some
machine-check conditions.
These words do not say whether Linux will recover. A user-mode #UD normally becomes SIGILL; a kernel-mode
fault may be repaired by an exception-table fixup, handled by the VM subsystem, or become an oops. A user
page fault may allocate a page, establish a COW mapping, wait for file I/O, raise SIGSEGV/SIGBUS, or invoke the
OOM machinery depending on the mapping and failure.
5.5.4 Linux entry bookkeeping is part of correctness
The low-level stub first reaches a state in which normal kernel rules are safe: trusted stack, saved registers,
appropriate GS and page-table state, and mitigated speculation where required. Common exception/interrupt
entry then updates bookkeeping in a deliberately constrained order. Depending on the entry class and kernel
configuration, this includes:
• context tracking and RCU transitions from user or idle state into kernel state;
• lock-dependency and tracing state;
Advanced introduction - 4 September 2026
21
CPU and Memory Virtualization
Linux / Fedora study day
• interrupt nesting and preemption accounting;
• time accounting and architecture-specific entry state.
This is not decorative instrumentation. RCU must know whether a CPU can still hold a read-side reference;
the scheduler must know whether preemption is legal; lock debugging must not infer an impossible lock context.
Linux marks the most fragile entry regions noinstr so compiler instrumentation cannot insert calls before those
invariants exist.
For a conventional hard interrupt, the top-half handler runs in atomic interrupt context: it cannot sleep, because
there is no task-owned blocked continuation for the scheduler to resume as a sleeping hardirq. It acknowledges
or services the urgent device state, records data, and arranges deferred work. Controller acknowledgement and
end-of-interrupt ordering are device- and controller-specific; for an APIC-delivered interrupt, Linux eventually
signals EOI so another interrupt of the relevant priority can be accepted.
Longer work can be deferred in several ways:
• a softirq runs deferred kernel work, either on interrupt return or in a ksoftirqd thread under load;
• a threaded IRQ moves most of a device handler into a schedulable kernel thread;
• a workqueue runs work in process context, where sleeping may be permitted.
An NMI is more restrictive still. It can arrive despite ordinary interrupt masking and can interrupt code that
already holds normal locks. NMI handlers therefore use only NMI-safe operations and carefully designed perCPU state. “Kernel mode” alone does not imply one uniform set of legal operations; hardirq, NMI, softirq,
process context, and preempt-disabled regions have different constraints.
5.5.5 Four concrete entry traces
Event
Minimum causal trace
Typical outcome
User demand page fault
load/store -> #PF vector ->
hardware frame and error code, CR2
set -> Linux VMA/PTE checks
instruction -> #UD or #GP -> vector
entry -> exception decoding
APIC timer expires -> vector
entry -> account time, run timer
callbacks, perhaps set
TIF_NEED_RESCHED -> EOI
NMI source -> dedicated entry
rules, often IST -> minimal
NMI-safe diagnosis/accounting
install mapping and retry the same
instruction, or deliver a signal
User invalid opcode / protection
violation
Local timer interrupt
NMI
usually arrange SIGILL or SIGSEGV
before user return
return to interrupted work or
schedule at a legal boundary
return, panic, or platform-specific
recovery
A timer interrupt does not necessarily call the scheduler immediately inside the device handler. It may only
make rescheduling necessary. Exit code observes that request at a point where interrupt nesting, preemption
state, locks, and RCU state permit a task switch.
Retrieval checkpoint: interrupt entry
Without notes, draw two frames: a CPL-3 page fault using TSS.RSP0, and a same-CPL kernel interrupt with
no ordinary privilege stack switch. Mark what hardware saves, what Linux entry assembly adds, where a
page-fault error code appears, and where the fault address actually lives. Then explain why an IST stack
and a hardirq thread are different mechanisms.
6 One x86-64 syscall, instruction by instruction
This section follows the conventional x86-64 SYSCALL path used on current Linux systems. Exact internal symbol
names and mitigation sequences change between kernels; the architectural invariants do not. New x86 FRED
entry mechanisms may eventually alter low-level entry details on supported hardware, so use this as a causal
model and inspect the source matching uname -r when doing kernel work.
Advanced introduction - 4 September 2026
22
CPU and Memory Virtualization
Linux / Fedora study day
6.1 Layer 1: the application and libc
Consider:
ssize_t n = write(STDOUT_FILENO, "hello\n", 6);
This is initially an ordinary C call into libc. The wrapper arranges the Linux syscall ABI:
Purpose
syscall number
argument 1
argument 2
argument 3
arguments 4-6 if present
return
Register for write
RAX = SYS_write
RDI = 1 (stdout file descriptor)
RSI = pointer to bytes
RDX = 6
R10, R8, R9
raw result in RAX
The symbolic constant comes from headers for the selected ABI. On x86-64, getpid is conventionally number 39;
on old i386 it is 20; on AArch64 it is different again. Hard-coding an internet table is the wrong habit.
Kernel syscalls conventionally return nonnegative results or a negative error number in a small range. Libc
recognises a raw value such as -EFAULT, returns -1, and stores the positive code in thread-local errno.
You can bypass a named wrapper but still use libc’s generic helper:
#include <sys/syscall.h>
#include <unistd.h>
long tid = syscall(SYS_gettid);
Do this to study the ABI, not as a default programming style; wrappers provide types, portability, cancellation
semantics and error conversion.
6.2 Layer 2: what syscall hardware does
At boot, privileged Linux setup configures model-specific registers including:
• IA32_EFER.SCE to enable SYSCALL/SYSRET;
• IA32_LSTAR with the kernel entry instruction address;
• IA32_STAR with selector information for kernel entry and user return;
• IA32_FMASK with user flags to clear on entry;
• GS-base state used to reach trusted per-CPU data.
When CPL-3 code executes syscall, the CPU performs a small, fixed transition:
1. save the following user instruction address in RCX;
2. save the pre-entry user RFLAGS in R11, with RF cleared as specified by the instruction, then clear IA32_FMASKselected bits in the live kernel RFLAGS;
3. load kernel selector state and the RIP configured in LSTAR, entering CPL 0;
4. begin the kernel entry stub with interrupts masked under Linux’s flag configuration.
The instruction deliberately does not switch RSP, push a full frame, save all registers, switch CR3, or switch GS.
Early assembly therefore runs at CPL 0 while RSP and most registers still contain untrusted user values. It must
use no ordinary kernel C assumptions until it establishes trusted state.
An interrupt gate is different: on a privilege transition, x86 interrupt/exception machinery can obtain a kernel
stack pointer through the TSS/IST machinery and pushes an architectural frame. Do not mentally use one
mechanism’s stack rules for the other.
6.3 Layer 3: Linux establishes a safe kernel context
The classic entry_SYSCALL_64 sequence conceptually does this:
1. swapgs exchanges the user GS base with the kernel’s per-CPU GS base;
2. save the user stack pointer in trusted per-CPU entry storage;
Advanced introduction - 4 September 2026
23
CPU and Memory Virtualization
Linux / Fedora study day
3. if Kernel Page Table Isolation (KPTI/PTI) is active, switch from the restricted user page-table root to the
full kernel page-table root;
4. load the top of the current task’s kernel stack;
5. construct a struct pt_regs frame containing general registers plus a synthetic user return frame;
6. clear or sanitise live register state as required and run speculation mitigations configured for the CPU;
7. call the architecture’s C syscall dispatcher with the frame and syscall number.
The canonical saved frame contains, conceptually:
r15 ... r12, rbp, rbx
r11, r10, r9, r8
rax, rcx, rdx, rsi, rdi
orig_rax
rip, cs, rflags, rsp, ss
The exact order is defined by the matching kernel’s struct pt_regs and assembly macros. It is not just a backup.
Ptrace, audit, seccomp, signal delivery, syscall restart logic and return code can inspect or modify this canonical
user context.
On the conventional entry path, Linux preserves the incoming syscall number in the orig_ax/orig_rax slot and seeds
the live return-value slot with -ENOSYS before dispatch. That makes skipped, rejected and restarted calls explicit.
This frame is a user-entry record, not the entire schedulable context: a kernel thread or a task preempted wholly
inside the kernel can context-switch without first creating a fresh user pt_regs frame.
6.3.1 KPTI explains the apparently awkward stacks
Without KPTI, kernel mappings historically remained in each process’s page tables but were protected by
supervisor permissions. KPTI uses a user page-table view that omits most kernel mappings and retains only a
minimal supervisor-only entry area. Entry must begin in that mapped trampoline, switch to the kernel page
tables, and only then freely use kernel text/data and the task stack. Return reverses the constraint: minimal
state moves through per-CPU entry/trampoline storage before the page-table view hides the ordinary kernel
stack.
This reduces the exposure behind attacks such as Meltdown. It can add translation overhead, mitigated on
capable x86 hardware by PCIDs and careful TLB handling.
6.4 Layer 4: common entry work and dispatch
Once safe low-level state exists, common entry code establishes bookkeeping in a strict order: lock dependency
tracking, RCU/context tracking, tracing and time accounting. It also processes entry hooks such as ptrace,
audit, seccomp filters and syscall tracing.
The entry path has already selected the ABI. The dispatcher normalises and checks the syscall number,
constrains speculative indexing, lets hooks such as seccomp or ptrace inspect, rewrite or reject the request,
and invokes a generated __x64_sys_* wrapper leading to subsystem code. Current upstream implementation
details may use a generated C dispatch switch while older descriptions emphasise an indexed syscall table; both
implement the same protected mapping from number to a finite kernel entry function.
For write, the kernel then roughly:
1. looks up file descriptor 1 in the calling process’s file table;
2. checks descriptor and object state;
3. treats the byte pointer as an untrusted user address;
4. enters the VFS/file operation path and copies or pins data through user-access primitives;
5. applies security, filesystem/device and blocking rules;
6. returns a byte count or negative error through the saved RAX slot.
The kernel must never dereference a user pointer as if it were a trusted kernel pointer. Architecture user-copy
primitives perform range checks, cooperate with SMAP, and have exception-table recovery paths for faults.
Such a copy can fault, sleep, or copy only a prefix. A successful access_ok-style range check is not a durable
promise: another thread can change mappings or data before a later access. Kernel code therefore copies once
into trusted storage when it needs a stable value, validates lengths and nested pointers carefully, and avoids
double-fetch/TOCTOU assumptions. A malicious pointer should produce -EFAULT or a partial-result rule, not a
kernel crash.
Advanced introduction - 4 September 2026
24
CPU and Memory Virtualization
Linux / Fedora study day
6.5 A syscall can block and cause a context switch
Suppose read() waits for an empty pipe:
1. the task is executing kernel code on its own kernel stack;
2. the pipe code enqueues a waiter and marks the task sleeping;
3. schedule() selects another runnable task on that CPU;
4. the original kernel stack remains suspended in memory;
5. a writer or interrupt-driven event makes the reader runnable;
6. it is eventually scheduled, possibly on another permitted CPU;
7. it resumes after the schedule point inside the syscall, completes, and returns to user mode.
This yields three different events:
• the initial syscall is a mode switch in the same task;
• sleeping invokes the scheduler and creates a context switch to another task;
• a later wakeup is a state/queue change, not necessarily immediate execution.
6.6 Layer 5: return to user mode
Before return, Linux handles pending work such as tracing, audit, signals, task work, syscall restart and
rescheduling. Raw x86-64 syscall results in the range -1 through -4095 conventionally denote errors, but a
syscall may instead return a successful partial byte count after doing some work. Libc converts only the raw
error convention to -1 plus thread-local errno. Linux then chooses between:
• sysretq fast path: usable only when saved RIP, flags and selectors meet strict safety conditions;
• iretq general path: restores the architectural return frame for cases ineligible for the fast path. Generalpurpose registers are restored by entry assembly before iretq; in 64-bit mode the instruction pops RIP, CS,
RFLAGS, RSP, and SS. Do not import the legacy-mode rule that makes stack fields conditional on a privilege
change.
On the fast path, Linux restores registers, transitions through the entry/trampoline stack when KPTI requires
it, switches to the user page-table root, restores the user GS side, arranges user RSP, and executes sysretq. SYSRETQ
uses RCX for the return RIP and R11 for flags; Linux validates state because historical/noncanonical-address corner
cases can otherwise be dangerous.
Interrupts must remain controlled during the tiny interval in which CPL is still 0 but the live stack pointer is
a user value. The entry/exit code is deliberately non-instrumentable in its most fragile regions.
C call: libc loads RAX and argument registers
CPU SYSCALL: CPL3 -> CPL0, RCX=return RIP, R11=flags, fixed LSTAR target
Entry assembly: GS, page tables, trusted kernel stack, pt_regs
Common entry checks -> syscall dispatch -> subsystem work
Optional block: sleep -> schedule another task -> wake -> resume
Exit work: signals / tracing / reschedule; validate return context
SYSRETQ fast path or IRETQ general path -> CPL3
Advanced introduction - 4 September 2026
25
CPU and Memory Virtualization
Linux / Fedora study day
6.7 Signals: kernel-arranged control transfer within user mode
A signal is not a hardware privilege transition. It is a Linux/POSIX notification abstraction. Delivery may be
prompted by a CPU exception, a terminal, a timer, another process, or kernel subsystem state, but a caught
handler executes at CPL 3 in the recipient’s own address space. The kernel temporarily redirects the next
user-mode continuation; it does not execute the handler as privileged code.
6.7.1 Generation, pending state, selection, and delivery
Keep four stages separate:
1. A signal is generated for a particular thread or for the process as a whole.
2. Linux records it as pending if it cannot be acted on immediately.
3. At a return-to-user boundary, Linux selects an eligible pending signal for the current thread.
4. Linux performs the default action, ignores it, or constructs a user context for a handler and delivers it.
Each thread has its own blocked-signal mask. Signal dispositions installed by sigaction are normally shared
process-wide among threads. A thread-directed signal, such as one sent with pthread_kill or caused synchronously
by that thread’s fault, is pending for that thread. A process-directed signal can be delivered to an eligible
thread whose mask permits it; “the process received a signal” does not imply a permanently predetermined
target thread.
Ordinary standard signals generally coalesce: if one instance is already pending, generating the same standard
signal again need not create a second queued instance. Real-time signals are queued with ordering and
accompanying values, subject to resource limits. SIGKILL and SIGSTOP cannot be caught, blocked, or ignored,
because allowing a target to redefine those operations would defeat their system-management semantics.
Signals are checked during exit work whenever the kernel is about to resume user mode. If a task was running
in user space, an interrupt, exception, or inter-processor notification first brings it into the kernel. If it was
blocked in a syscall, the wakeup and syscall exit path provide the delivery point. Linux never asynchronously
starts a POSIX handler in the middle of arbitrary kernel C code.
6.7.2 Building the user signal frame
For a caught signal, Linux conceptually performs these steps:
1. choose the normal user stack or an enabled alternate signal stack from sigaltstack;
2. copy an rt_sigframe to that user stack, including siginfo_t, a ucontext_t, the old mask, saved user registers, and
the relevant floating-point/(F)XSAVE extended-state payload plus its format/alignment metadata;
3. adjust the saved user register frame so the next return enters the handler with ABI-defined arguments;
4. arrange a return address to a signal-restorer trampoline;
5. return from the kernel to CPL 3.
The handler is then an unusual user-space function call whose caller was synthesized by the kernel. SA_ONSTACK is
valuable for stack-overflow and fault handlers because the ordinary stack may be the damaged resource. It is
not magic protection: the alternate stack must be allocated, registered, large enough, and not itself corrupted.
When the handler returns, a libc-provided or vDSO-associated restorer trampoline invokes rt_sigreturn. That
syscall tells Linux to read the saved frame, restore the blocked mask and user register state, restore relevant
floating-point/extended state, and resume the interrupted user continuation. No ordinary C function can
restore every register and the signal mask while also returning to an arbitrary saved instruction; rt_sigreturn is
the privileged, validated completion operation.
The signal frame is untrusted input
The frame lives in writable user memory. rt_sigreturn must therefore validate and sanitise the state it
consumes: user addresses must be valid for the architecture, selectors and flags must not request kernel
privilege, and extended-state formats must be acceptable. A corrupted process can rewrite its own frame,
but the kernel must prevent that rewrite from manufacturing CPL 0 or invalid kernel state. Crafted frames
are a building block in sigreturn-oriented programming after an attacker already gains user-space control;
they are not permission for an ordinary process to cross the kernel boundary unchecked.
Advanced introduction - 4 September 2026
26
CPU and Memory Virtualization
Linux / Fedora study day
6.7.3 Interrupted and restarted syscalls
A signal can meet a syscall in several states. If an operation has already transferred bytes, Linux commonly
returns that partial count; callers must not discard it merely because a signal also occurred. If no useful progress
occurred, libc may expose -1 with errno == EINTR, or Linux may restart the syscall.
Inside the kernel, restartable paths use internal results such as -ERESTARTSYS, -ERESTARTNOHAND, or -ERESTART_RESTARTBLOCK
. These are not ordinary user-visible errno values. During exit work Linux decides, based on the operation,
handler disposition, and flags such as SA_RESTART, whether to expose EINTR or rewrite the saved user context so
the syscall is attempted again. SA_RESTART applies only to specified interfaces, not every blocking call. A small
wrapper can retry only the no-progress EINTR result while preserving any positive partial count:
ssize_t write_retry(int fd, const void *buf, size_t len)
{
ssize_t n;
do {
n = write(fd, buf, len);
} while (n < 0 && errno == EINTR);
return n;
}
A write_all policy would loop over the remaining suffix, reject lengths it cannot represent, handle a surprising
zero return, and define what its caller receives if a later error occurs after earlier bytes have already been written.
Restart is not “jump back into libc from nowhere”. Linux edits its canonical saved user context: on x86-64 that
may restore the original syscall number and position the instruction pointer so the user-side syscall instruction
executes again.
6.7.4 Handler code runs under severe library constraints
A signal handler can interrupt the same thread while libc or an allocator holds internal locks. Calling a
non-async-signal-safe function such as printf, malloc, or most pthread operations can deadlock or corrupt state.
The POSIX async-signal-safe list is intentionally small. A common design is for the handler to set a volatile
sig_atomic_t flag or write a byte to a pre-created self-pipe/event notification path, then let normal control flow
perform complex work.
Blocking a signal around one data structure is also not general thread synchronisation. Signal masks govern
delivery to the current thread; another pthread may still access shared memory concurrently. Use C atomics or
pthread synchronisation for cross-thread memory ordering.
Retrieval checkpoint: signal delivery
Explain why a signal handler runs at CPL 3 even though the kernel caused the call. Draw generation ->
pending -> selection -> rt_sigframe -> handler -> restorer -> rt_sigreturn. Identify which state is processwide, which is per thread, why standard signals can coalesce, and where a maliciously edited frame is
checked.
6.8 AArch64 Raspberry Pi comparison
The Linux-level logic is the same but the architectural entry is not:
Feature
Fedora x86-64
64-bit Raspberry Pi / AArch64
user/kernel level
syscall instruction
number
arguments
result
exception vectors
CPL3 / CPL0
EL0 / EL1
syscall
svc #0
RAX
x8/w8 ABI view
RDI,RSI,RDX,R10,R8,R9
x0 through x5
RAX
x0
x86 entry/IDT mechanisms
table based at VBAR_EL1
This is why the supplied i386 quick reference applies to neither machine literally. POSIX source APIs can
remain similar while libc implements different Linux syscall ABIs.
Advanced introduction - 4 September 2026
27
CPU and Memory Virtualization
Linux / Fedora study day
6.9 Who saves what, when?
“Saving the process” hides several independent mechanisms. The right question is: which execution boundary
occurred, which later continuation must be reconstructed, and who owns the storage?
Boundary or state
Saver and storage
What is preserved
What it is not
Ordinary C call
compiler-generated user
code on the user stack
and in ABI-designated
registers
CPU in RCX and R11;
Linux entry assembly on
trusted entry/task stacks
return address and the
caller/callee state
required by the calling
convention
next user RIP and saved
user flags in hardware,
then GPRs and a
synthetic return frame in
a privilege transition or
full thread snapshot
x86-64 SYSCALL instruction
pt_regs
IDT interrupt/exception
CPU on the current,
TSS.RSP0, or IST-selected
stack; then Linux
assembly
User entry frame
Linux entry code in
struct pt_regs on the task’s
kernel stack
Context switch A -> B
scheduler plus
architecture switch_to
code, chiefly on each
task’s kernel stack and
task metadata
Floating point and
extended state
architecture/FPU code
in per-task state,
commonly using
XSAVE-format storage
clone setup and
architecture
context-switch/return
code in per-task
metadata and
registers/MSRs
memory-management
context switch using mm,
active_mm, CR3 roots,
PCID tags, and TLB
rules
TLS and thread-specific
CPU state
Address-space context
Advanced introduction - 4 September 2026
architectural RIP, CS,
RFLAGS, stack-switch state,
optional error code; then
remaining registers in a
normalised frame
canonical user
GPR/return state used
by syscall, ptrace, audit,
restart, and signal logic;
original syscall number is
retained separately (for
example orig_ax)
suspended kernel
continuation, kernel stack
pointer, ABI-preserved
registers, and
architecture state needed
to resume B
SIMD, x87, and enabled
extended components
when ownership/use
requires preservation
FS/GS base as
applicable, TLS pointer,
debug state, PKRU/CET
or other enabled
per-thread features
which translation context
B may use; threads can
retain the same mm; kernel
threads may borrow an
an automatic stack
switch or complete
hardware save; apart
from the instruction’s
architectural RF clearing,
IA32_FMASK clears selected
bits in live RFLAGS, not in
the saved R11 copy
a task switch; CR2 is
separate from a
page-fault frame
the only state needed for
every context switch
necessarily a new user
pt_regs; kernel preemption
and kernel threads can
switch without a fresh
user entry frame
necessarily copied on
every mode switch
shared process state
simply because the
threads share an mm
a mandatory CR3 value
change and full TLB
flush on every switch
active_mm
28
CPU and Memory Virtualization
Caught signal
Linux / Fedora study day
Linux copies an
rt_sigframe to a normal or
alternate user stack
saved user registers,
mask, signal metadata,
and floatingpoint/(F)XSAVE
extended-state payload
for later rt_sigreturn
trusted kernel storage;
the returning syscall
must validate it
also deserves precise language. In the 64-bit interrupt-return form discussed here, it restores the
architectural return fields - RIP, CS, RFLAGS, RSP, and SS. Linux restores general-purpose registers in software before
executing it. Conversely, SYSRETQ uses RCX and R11 and is allowed only after Linux proves the saved state meets
the fast path’s constraints.
IRETQ
The table explains a subtle blocked-syscall case. Task A enters through SYSCALL, so A’s user state is captured
in pt_regs. A later blocks; switch_to preserves A’s kernel continuation and swaps to B’s kernel stack. When A
wakes, the context switch resumes after schedule() inside the syscall. Only much later does exit code consume
A’s older pt_regs and reconstruct user mode. The mode switch and context switch save different continuations
at different times.
A compact reconstruction rule
For each boundary, name the continuation that must run next. A syscall/exception frame reconstructs user
execution; switch_to reconstructs a suspended kernel execution; a signal frame lets user mode reconstruct
the pre-handler state. If your explanation uses one undifferentiated “PCB register save” for all three, it is
hiding the mechanism you most need to understand.
6.10 Function call, mode switch, and context switch: final comparison
Task changes?
CPL changes?
Address space
changes?
normal C
function call
nonblocking
syscall
No
No
No
No
Yes, then back
KPTI view may
switch, logical mm same
page fault
handled for
same task
context switch
A -> B
No
Yes, then back
page tables may be
updated
Yes
occurs inside kernel
process PID/TGID
retained; a nonleader
caller can be
de-threaded
syscall path
maybe; no full mm
change for shared
address space
old mm replaced
Event
execve()
Stack changes?
new frame on
same user stack
user stack ->
task kernel stack
-> user
user -> kernel
-> user
A kernel stack
-> B kernel
stack
new initial user
stack
Retrieval checkpoint 3
Reconstruct the syscall path using only these anchors: RAX; RCX/R11; LSTAR; swapgs; KPTI; kernel stack; pt_regs;
dispatch; possible sleep; exit work; sysretq versus iretq. Then answer: Which steps are done by hardware,
and which must Linux do in assembly/software?
Advanced introduction - 4 September 2026
29
CPU and Memory Virtualization
Linux / Fedora study day
7 Privilege, credentials, and secure authorisation
7.1 Protection layers that are often called “privilege”
Layer
Question answered
Examples
CPU execution privilege
Which instructions and mappings
may the current code use?
Kernel credentials
What authority does this task
carry?
May that authority perform this
operation on this object?
Which kernel objects and ID
meanings are visible/governing?
May this task invoke this syscall
under these arguments?
May a later exec gain or relax
authority?
May this subject perform this
permission on this object?
CPL 3 versus CPL 0; effective U/S
permission accumulated down a
page-table walk
real/effective/saved UID, groups,
capabilities
file mode/ACL, signal permission,
socket rules
user, PID, mount, network
namespaces
seccomp filters
Object/discretionary policy
Namespace scope
Syscall-surface confinement
Privilege-transition constraint
LSM/object policy
inherited, irreversible no_new_privs
SELinux source domain/target
type/class/permission; Landlock
restrictions where used
Entering the kernel changes only the first row. Kernel code reads the other rows before acting.
7.2 Linux credentials
Important identity fields include:
• real, effective and saved-set user and group IDs;
• filesystem UID/GID used in some filesystem checks;
• supplementary groups;
• capability sets: permitted, effective, inheritable, bounding and ambient;
• securebits;
• the governing user namespace;
• an LSM security context, notably SELinux labels on Fedora.
Related task attributes live outside struct cred: notably the irreversible no_new_privs bit and seccomp state. They
constrain what the task may gain or invoke, but they are not identity fields in the credential object.
Traditional Unix treated effective UID 0 as all-powerful. Linux capabilities divide many root checks into named
powers such as CAP_NET_BIND_SERVICE, CAP_CHOWN, and CAP_SYS_ADMIN (the latter remains unfortunately broad). Capability
checks are relative to a user namespace; “root inside a container” is not automatically host root.
Inspect your shell:
id
grep -E '^(Uid|Gid|Groups|Cap(Inh|Prm|Eff|Bnd|Amb)|NoNewPrivs|Seccomp):' /proc/$$/status
command -v capsh >/dev/null && capsh --print
command -v getenforce >/dev/null && getenforce
command -v id >/dev/null && id -Z
Advanced introduction - 4 September 2026
30
CPU and Memory Virtualization
Linux / Fedora study day
7.3 Credentials are versioned kernel objects
Linux does not safely edit a credential record in place while other CPUs may be reading it. A task normally
points at an immutable, reference-counted struct cred. To change identity, kernel code prepares a new credential
object, validates the requested transformation, and commits a pointer replacement. Read-copy-update
techniques allow concurrent readers to keep seeing a stable old object until it is safe to reclaim.
task_struct contains two credential references that are normally equal:
• the objective or real credentials describe the task as an object when another actor examines or acts upon
it;
• the subjective credentials describe the authority used while the task acts on another object.
Kernel code can temporarily override subjective credentials for a tightly scoped operation, but it must not
mutate the shared object. This pattern matters for in-kernel services that perform work on behalf of another
principal.
At the Linux kernel interface, credentials are attached to tasks. POSIX, however, requires process-wide behavior
for calls such as setuid(). NPTL bridges the mismatch: glibc’s set-ID wrappers coordinate with every pthread
using an internal signal protocol so that each Linux task performs the credential syscall. Bypassing the wrapper
with a raw syscall can change only the calling task and violate the program’s POSIX-level invariant. Linux
capability sets are also technically per-thread; do not assume every identity-related library operation performs
the same group-wide protocol.
Fork and exec illustrate the credential lifecycle:
Event
Credential behavior
fork()/task creation
Child initially references or copies the parent’s
credential state; later changes use replacement rather
than unsafe shared mutation.
Kernel checks the caller’s current subjective
credentials plus object policy; entry to CPL 0 does
not alter them.
The resulting file object records an opening credential
(f_cred) used by some later operations; dropping UID
does not revoke an already-open descriptor.
Kernel permits only transitions allowed by current
IDs and capabilities, then commits new task
credentials. NPTL coordinates POSIX process-wide
changes.
Kernel recomputes credentials from the old
credentials, file ownership/mode, file capabilities,
namespaces and suppression rules, then installs the
new image and credentials together.
ordinary syscall
open()
setresuid() and related calls
execve()
The f_cred row is a reminder that authority can be converted into an object reference. A privileged process can
open a protected file, drop privilege, and still use the descriptor if the operation’s checks allow it. This is often
deliberate delegation. It is also why descriptor inheritance must be designed explicitly.
Advanced introduction - 4 September 2026
31
CPU and Memory Virtualization
Capability set
Linux / Fedora study day
Intuition
7.4 IDs and capabilities answer different questions
Real, effective and saved-set IDs support login identity, active identity and controlled temporary transitions. The
filesystem IDs participate in some VFS checks, while supplementary groups add group memberships. The details
of setuid() vary with privilege and history, so security-sensitive code should prefer explicit getresuid()/setresuid()
and group equivalents over guessing what one overloaded call changed.
Linux capabilities divide many checks that historically asked only whether effective UID was zero:
Capability set
Intuition
Permitted (P)
Effective (E)
Capabilities the thread may make effective.
Capabilities currently consulted by most capability
checks.
Capabilities selected by the thread to participate in
exec inheritance rules.
A ceiling that can prevent capabilities from being
gained through file-capability exec. Dropping from it
is one-way.
Capabilities preserved across an exec of a
nonprivileged program; each ambient capability must
also be permitted and inheritable.
Inheritable (I)
Bounding (B)
Ambient (A)
The exact exec equations include root-specific and namespace rules, but four invariants are more useful at first:
1. the effective set is what an ordinary capability check normally tests;
2. an effective capability must be backed by the permitted set;
3. the bounding set constrains file-derived privilege;
4. executing a privileged file clears the ambient set, while a nonprivileged exec can preserve valid ambient
capabilities.
Capability checks are interpreted relative to a governing user namespace. UID 0 plus a full-looking capability
mask inside a newly created user namespace does not imply equivalent power over objects governed by the
initial user namespace. “Container root” is therefore a scoped authority claim, not a synonym for host root.
A capability is not a CPU mode
CAP_NET_BIND_SERVICE does not let user instructions run at CPL 0.
It makes a particular kernel authorisation
check succeed when the task enters normally through a syscall. Conversely, every unprivileged task executes
kernel code at CPL 0 during a syscall without gaining that capability.
7.5 Where legitimate privilege gain comes from
An ordinary task cannot manufacture more authority with setuid(0) or capset(). A successful increase must follow
a kernel-recognised delegation path:
Mechanism
Where authority comes from
Security boundary
set-user-ID/set-group-ID
executable
file capabilities
Trusted file owner and mode bits
affect credentials during exec
Trusted extended attribute grants
selected capabilities during exec
Already privileged,
policy-controlled helper
authenticates/authorises and execs
a command
exec loader plus filesystem/mount
and policy checks
exec capability rules and capability
bounding state
helper policy, PAM/session setup,
controlled environment and exec
sudo
Advanced introduction - 4 September 2026
32
CPU and Memory Virtualization
Linux / Fedora study day
Mechanism
Where authority comes from
Security boundary
polkit-style service
A privileged long-running service
receives an IPC request and
authorises the action
The process previously possessed
that authority and deliberately
retained a route back
Namespace creator receives
capabilities scoped to the new
namespace
IPC peer identity, action policy
and narrow service API
saved IDs or retained permitted
capabilities
user namespace
set-ID/capability transition rules
namespace ownership and each
target object’s governing
namespace
Set-user-ID interpreter scripts are ignored as a general Linux privilege mechanism because interpreter selection
and script-file handling historically create dangerous races. A small compiled helper or, better, a narrow
privileged service avoids that ambiguity.
no_new_privs is an irreversible per-task promise, inherited across fork and exec, that exec will not grant privilege
that was absent before. It suppresses set-user-ID, set-group-ID and file-capability gains for that exec path. It
does not itself remove authority already held. It is a powerful foundation for sandboxes because an unprivileged
process can install restrictions without later escaping them by executing a privileged file.
On an exec that is considered secure, the kernel communicates secure-execution state through the auxiliary
vector (AT_SECURE). glibc’s dynamic loader then ignores or removes dangerous environment controls such as
library-preload/search variables. The kernel also applies rules around dumpability and ptrace, and a security
module such as SELinux can impose an additional transition or denial. The new program still needs careful
argv, environment, current-directory and descriptor handling; the kernel cannot infer application intent.
7.6 A secure privilege-transition procedure
The safe design is usually not “be root, do everything, then hope to drop root.” Make the privileged surface
small and make authority flow explicit:
1. Choose the narrowest delegation. Prefer one file descriptor, one capability, or one service method over
a general root shell. Separate the privileged helper from the large parser/UI where practical.
2. Establish a trusted execution environment. Use paths beneath trusted, non-writable directory
ancestry and resolve them without symlink, rename or mount-namespace races—for example, begin from a
trusted directory descriptor and use openat2() resolution constraints where appropriate. Also use a controlled
argv and environment, safe working directories, restrictive creation masks, and descriptors opened with
O_CLOEXEC. A fixed-looking string or one earlier stat() is not by itself trusted. Opening with O_CLOEXEC is atomic;
open() followed later by fcntl(FD_CLOEXEC) races with another thread doing fork/exec.
3. Authenticate and authorise the requested operation. Identity alone is not authorisation. Validate
lengths, object ownership, symlink/path traversal, namespaces, current object state, SELinux policy and
any time-of-check/time-of-use window.
4. Acquire only the protected resources that must be acquired while privileged. A pre-opened
descriptor is often a cleaner delegated capability than retaining a powerful UID.
5. Complete any policy-required exec/domain transition. An SELinux domain transition is driven by
labels, entrypoint and installed policy, not an arbitrary self-selected setting. If the design relies on such an
exec transition, perform and verify it at the policy-prescribed point before no_new_privs; NNP can cause an
LSM to decline even a transition intended to tighten confinement.
6. Remove routes that require current privilege. Clear ambient capabilities, drop unnecessary entries
from the bounding set, and configure/lock securebits before losing CAP_SETPCAP. Retain only the temporary
authority needed to finish the transition.
7. Drop supplementary groups, then GID authority, then UID authority. The order matters because
discarding UID capabilities too early may prevent the later group changes. Use explicit setgroups, setresgid
and setresuid calls and check every return value.
8. Clear retained authority and constrain future transitions. If the program used keep-capabilities
semantics across the UID change, remove remaining permitted, effective and inheritable capabilities. Set
no_new_privs when no later privilege-gaining exec or required LSM exec transition remains.
9. Reduce the remaining syscall surface. Apply an allowlist-oriented seccomp policy and resource limits
only after retaining the syscalls needed for setup. An unprivileged filter installation requires no_new_privs = 1
Advanced introduction - 4 September 2026
33
CPU and Memory Virtualization
Linux / Fedora study day
(otherwise the caller needs CAP_SYS_ADMIN in its user namespace); if capabilities were already cleared, verify
NNP first or filter installation fails. In a thread group, install before creating siblings or deliberately use
seccomp’s thread-synchronisation facility and handle failure. SELinux/Landlock decisions remain separate
layers; a chroot alone is not a complete sandbox.
10. Verify the postcondition. Read back real/effective/saved IDs, groups, capability sets, security domain
and NoNewPrivs. A temporary drop that leaves a privileged saved ID or permitted capability is not a permanent
drop.
Every step can fail. Ignoring one error can leave a process more privileged than its control flow assumes. In
a multithreaded program, privilege transition is especially hazardous because sibling threads share writable
memory and descriptors while Linux stores credentials per task. Prefer doing setup before creating threads, or
delegate privileged work to a separate, narrowly designed process.
Privilege is a lifecycle, not a bit
Model where authority originated, which task currently holds it, which objects were opened with it, whether
exec can recreate it, and exactly when it becomes unreachable. A UID snapshot alone cannot answer those
questions.
7.7 Saved IDs: temporary drop versus permanent drop
A set-user-ID program can begin with a real UID naming the invoker, an effective UID naming the file owner,
and a saved UID that permits a controlled switch back. Changing only the effective UID can be an intentional
temporary drop. It is not proof that privilege is gone.
For a permanent drop, security-sensitive code normally sets all real/effective/saved IDs to the unprivileged
target after handling supplementary groups, and removes capabilities and ambient/bounding routes as required.
Whether root semantics alter a particular transition depends on capability and namespace context, so check
documented return values and verify the final state. Never use “the next open failed” as the only proof: an
inherited descriptor may still confer access, and a different path may still regain authority.
7.8 Exec is both a loader and a security transaction
For a privileged exec, reason about this sequence:
1. resolve and open the executable under VFS and namespace rules;
2. validate format, permissions, mount flags and tracing/no_new_privs constraints;
3. compute prospective IDs, capability sets and LSM transition;
4. construct the new address space, main ELF image, interpreter, stack, auxiliary vector and vDSO;
5. close FD_CLOEXEC descriptors and apply exec attribute resets;
6. commit the new credentials and program image so execution begins at the new entry point.
The kernel maps the main ELF and its PT_INTERP interpreter if present. The dynamic linker then maps ordinary
shared libraries in user space. AT_SECURE changes how that linker treats the environment. This separation explains
why secure exec needs cooperation between kernel metadata rules and a trusted runtime loader.
There is no promise that every property changes at once in one abstract instruction. Linux carefully orders an
implementation with failure paths, point-of-no-return behavior, thread-group teardown and LSM hooks. The
stable interface claim is that successful exec never returns to the old program and begins the new image with
the computed security state.
7.9 Fedora privilege observation lab
Run these as observations, not as requests to weaken machine policy:
id
grep -E '^(Uid|Gid|Groups|Cap(Inh|Prm|Eff|Bnd|Amb)|NoNewPrivs|Seccomp):' \
/proc/$$/status
getcap -r /usr/bin /usr/sbin 2>/dev/null | head -30
for p in / /home /tmp; do
findmnt -no TARGET,OPTIONS --target "$p"
done
getenforce 2>/dev/null || true
id -Z 2>/dev/null || true
Advanced introduction - 4 September 2026
34
CPU and Memory Virtualization
Linux / Fedora study day
For one executable with file capabilities, inspect rather than modify it:
file=/path/reported/by/getcap
getcap -v "$file"
namei -l "$file"
readelf -l "$file" | sed -n '/INTERP/,+1p'
Then compare the process view before and inside a restricted shell if your installed tools support it:
setpriv --no-new-privs \
sh -c "grep -E '^(Uid|Gid|Cap(Inh|Prm|Eff|Bnd|Amb)|NoNewPrivs):' /proc/self/status"
Do not set capabilities or set-user-ID bits on arbitrary binaries. A copied interpreter, shell, editor or generalpurpose utility is a broad privilege grant, not a harmless experiment. If you later build a dedicated lab helper,
do it inside a disposable VM and make the operation narrower than “execute user-controlled input as root.”
Credential lifecycle checkpoint
Why can a raw set-ID syscall in one pthread violate the POSIX process model? Why might a process
still read a protected file after permanently dropping UID? Contrast effective, permitted, bounding and
ambient capabilities. Finally, give three independent reasons a set-user-ID bit might not produce elevated
credentials at exec.
7.10 What sudo actually changes
sudo is a user-space policy and authentication program installed with a trusted privilege transition (traditionally
a set-user-ID root executable plus system policy). Roughly, it:
1. begins as a process whose exec rules gave it authorised effective credentials;
2. identifies the invoking user and parses trusted policy;
3. authenticates if required;
4. constructs groups, UID, capabilities, environment, terminal/session and security context for the command;
5. forks/spawns and execves the requested program.
It does not expose an instruction that lets your old thread arbitrarily stay in ring 0. The command still runs
user instructions at CPL 3. When it syscalls, kernel checks see the credentials selected by policy; relative to the
invoker they may be more powerful, equally powerful, or deliberately less powerful along different dimensions.
Similarly, setuid() is a syscall that any task can invoke, but the kernel permits only specific identity transitions
unless the caller has CAP_SETUID. “Able to enter the syscall” and “authorised to obtain the result” are separate.
Set-user-ID and file capabilities are applied by exec credential rules, and can be suppressed by conditions such
as no_new_privs, a nosuid mount, tracing restrictions, or security policy. This makes exec a security boundary, not
merely a loader.
7.11 Defence in depth around the kernel boundary
No single mechanism is sufficient:
• U/S page permissions prevent CPL-3 code from reading supervisor pages.
• R/W and NX prevent disallowed writes and instruction fetches.
• SMEP prevents kernel mode from executing user-mapped code.
• SMAP blocks accidental kernel data access to user pages except around explicit access primitives.
• KPTI removes most kernel mappings from the user page-table view.
• ASLR and PIE randomise mapping locations; these complicate exploitation but do not enforce access by
themselves.
• seccomp can reduce the syscall interface available to a task.
• SELinux performs mandatory policy checks in addition to normal discretionary access control.
• IOMMU constrains device DMA.
• entry validation, exception tables, speculation mitigations and stack isolation harden the most
exposed transition code.
The kernel remains a large trusted computing base: once executing at CPL 0, a memory-safety or logic bug
can defeat the policy it is meant to enforce. Hardware supplies isolation primitives; kernel correctness is still
Advanced introduction - 4 September 2026
35
CPU and Memory Virtualization
Linux / Fedora study day
essential.
The secure syscall invariant
User mode may choose a syscall number, untrusted scalar values, and untrusted pointers. It may not
choose the kernel entry address or page tables. Entry establishes a trusted stack and kernel mapping
before general code runs. The kernel validates number, ranges, copied data, object state, credentials and
policy. Exit restores only a validated user context and drops back to user translation and privilege.
Retrieval checkpoint 4
Explain why TRAP/SYSCALL must be invocable in user mode while MOV CR3 must not. Then explain why an
unprivileged task nevertheless executes ring-0 instructions during read(), and why that does not let it open
/etc/shadow.
Advanced introduction - 4 September 2026
36
CPU and Memory Virtualization
Linux / Fedora study day
8 Scheduling and context switching
8.1 Scheduling is a queueing policy over runnable tasks
CPU virtualisation requires two separate capabilities:
• dispatch/context-switch mechanism: stop representing task A on a hardware CPU and resume task B;
• scheduling policy: decide which eligible task should be B.
A task that blocks is not losing a contest; it is declaring that running it now would make no progress. The kernel
removes it from the runnable set and connects it to an event source such as a wait queue, timer, completion or
futex. A wakeup makes it eligible again.
8.2 Metrics and assumptions
For task/job (i):
𝑇response,𝑖 = 𝑇first run,𝑖 − 𝑇arrival,𝑖
𝑇turnaround,𝑖 = 𝑇completion,𝑖 − 𝑇arrival,𝑖
For a CPU-only job with one CPU burst, the classroom identity is:
𝑇waiting,𝑖 = 𝑇turnaround,𝑖 − 𝑇CPU service,𝑖 .
If the job also performs I/O or sleeps, that subtraction includes blocked time as well as time ready but not
running. Then distinguish ready-queue waiting time from total non-CPU time instead of calling the entire
remainder scheduler waiting.
Other objectives include throughput, utilisation, fairness, deadline satisfaction, tail latency, bounded starvation,
energy, and locality. A policy cannot optimise all simultaneously. Always state assumptions about arrivals,
known burst lengths, preemption, I/O, priorities and context-switch cost.
8.2.1 Classroom policies
Policy
Rule
Strength
Main failure
FIFO/FCFS
finish in arrival order
simple, low switching
SJF
shortest known job first,
nonpreemptive
STCF/SRTF
smallest remaining time
first
Round robin
rotate after quantum
minimises average
completion-related
metrics for a known
batch
adapts to arrivals and is
optimal under strong
ideal assumptions
good interactive response
and bounded sharing
convoy effect behind long
jobs
service time is rarely
known; late short jobs
cannot preempt
MLFQ
adapt priority from
observed behaviour
approximates
responsiveness without
knowing lengths
estimation, starvation,
switching
tiny quantum wastes
overhead; large quantum
approaches FIFO
complex rules, gaming
and starvation controls
SCHED_FIFO and SCHED_RR in Linux are real-time policy names with precise priority semantics.
They are not simply
the course’s general-purpose FIFO and round-robin thought experiments.
Advanced introduction - 4 September 2026
37
CPU and Memory Virtualization
Linux / Fedora study day
8.3 Work one schedule by events, not intuition
Use this independent practice workload:
Task
A
B
C
Arrival
CPU burst
0
1
3
6
2
1
For each policy, maintain a timeline and update the ready queue only at meaningful events: arrival, completion,
block/wakeup, or quantum expiry. Response time uses first dispatch, not completion. Turnaround uses
completion. Under preemption, remaining service rather than original length controls STCF.
Do the following on paper before checking the answer appendix:
1. FIFO;
2. SJF with nonpreemptive A already running at time 0;
3. STCF with an interrupt at each arrival;
4. round robin with quantum 2 and zero switch cost.
This event-table method is exactly what the lecture checkpoint and past exam style require.
8.4 How Linux gets from an interrupt to schedule()
A timer interrupt does not blindly switch tasks in its first instruction. A simplified path is:
1. interrupt entry saves an architectural frame and establishes kernel state;
2. timer/scheduler accounting updates elapsed service and timing events;
3. policy code may mark that rescheduling is needed;
4. the interrupt handler finishes and the common exit path reaches a safe preemption point;
5. if the current task should no longer continue and preemption is allowed, Linux calls the scheduler;
6. scheduler chooses a next task and invokes context-switch machinery;
7. the eventual return-to-user path belongs to whichever task is now current.
Other triggers include a task blocking in a syscall, an explicit yield, exit/stop, a wakeup that makes a stronger
candidate eligible, kernel preemption at a safe point, and an interprocessor reschedule request. A timer event
is the standard mechanism for preempting compute-bound competitors after a policy deadline, but it is not
required for every return of control or every scheduling route.
8.5 A context switch is layered state management
Suppose task A entered the kernel from user mode and Linux decides to run B. Much of A’s volatile user
state already exists in a pt_regs frame on A’s kernel stack. The low-level switch does not redundantly copy the
entire process or every register into one PCB. It preserves the architecture-defined kernel continuation needed
to resume schedule() later.
A conceptual Linux switch performs:
1. account A and update/dequeue/requeue it according to why it stopped - preemption, blocking, migration
or exit are not the same transition;
2. choose B through the scheduler-class hierarchy;
3. select the active memory context: user tasks contribute an mm_struct, while kernel threads have mm == NULL and
can temporarily borrow an active_mm; switch page-table context when the effective memory context requires
it;
4. switch kernel stack pointers and save/restore callee-saved kernel context;
5. update per-CPU current and architecture/TLS/security state;
6. manage FPU/vector, debug and other extended state as required;
7. finish in B’s previously suspended kernel call chain, or for a never-run task enter the architecture’s firstrun/ret_from_fork path and runtime trampoline;
8. eventually return B’s saved user frame if B is leaving the kernel.
The surprising ordinary-resume case is step 7: after the assembly stack switch, the CPU is executing on B’s
kernel stack, so a ret continues wherever B last stopped. A later switch back to A makes A’s old schedule() call
Advanced introduction - 4 September 2026
38
CPU and Memory Virtualization
Linux / Fedora study day
appear to return. A brand-new task has no old call chain, so kernel setup gives it a deliberate first continuation
instead.
No process memory is copied to disk merely because of a context switch. Open files remain open. Pages remain
mapped. These resources are referenced by the task and survive while it is not running.
8.5.1 Switching threads can be cheaper, not free
If A and B are pthreads sharing one mm_struct, Linux need not select a different process page-table root. That can
avoid address-space/TLB work. Registers, stacks, scheduler bookkeeping and CPU microarchitectural effects
still change. If B is another process, Linux activates its mm; with x86 PCIDs, translations from multiple address
spaces can remain tagged in the TLB rather than always being globally flushed.
“Context switch cost” therefore includes:
• direct kernel instructions and locking;
• cache and branch-predictor disruption;
• TLB effects and possible page-table-root changes;
• migration to a core with colder private caches;
• NUMA effects if the task moves away from its memory.
8.6 One runqueue per logical CPU
Scalable Linux does not place every runnable task behind one global lock. Each logical CPU owns a runqueue
containing its current/idle tasks and class-specific queues. A task is normally running on one CPU or queued
on one CPU, never on two at once.
Wakeup placement and periodic/idle load balancing trade off:
• using idle capacity;
• preserving cache warmth;
• respecting affinity and cgroup/cpuset constraints;
• SMT, core, package and NUMA topology;
• heterogeneous CPU capacity and energy;
• avoiding excessive migration.
If CPU 0 wakes a task that should preempt work on CPU 5, it cannot directly change CPU 5’s stack. It
enqueues/communicates under scheduler synchronisation and normally requests remote rescheduling, typically
with an IPI; an idle CPU polling the right state can sometimes observe the request without a delivered interrupt.
CPU 5 enters or observes its own scheduling path and switches itself.
8.7 Linux scheduling-class order
A simplified priority among built-in classes is:
1. internal stop machinery;
2. SCHED_DEADLINE reservations (EDF/CBS ideas);
3. fixed-priority real-time SCHED_FIFO and SCHED_RR;
4. the fair class for ordinary tasks, with the configured sched_ext mode determining whether BPF policy replaces
fair handling or handles selected work below fair-class precedence;
5. the per-CPU idle task.
Optional sched_ext allows BPF-defined scheduling when explicitly loaded. In full-switch mode it can replace
fair-class handling for ordinary tasks; in partial mode the fair class remains above the ext class, which is still
above idle. Ordinary Fedora desktop tasks are normally in the fair class, not SJF.
8.7.1 EEVDF is the current fair-picker model
Older explanations of Linux’s Completely Fair Scheduler say to run the entity with smallest virtual runtime.
That remains useful background, but Linux began moving the fair class to Earliest Eligible Virtual Deadline
First (EEVDF) in kernel 6.6. Check your installed kernel rather than assuming a textbook vintage.
If task 𝑖 runs for real time Δ𝑡𝑖 with weight 𝑤𝑖 , its virtual service grows roughly as:
Δ𝑣𝑖 ≈ Δ𝑡𝑖
Advanced introduction - 4 September 2026
𝑤0
.
𝑤𝑖
39
CPU and Memory Virtualization
Linux / Fedora study day
A higher weight therefore consumes virtual time more slowly and earns a larger real-CPU share. EEVDF reasons
about lag (whether an entity is owed service) and a virtual deadline. In simplified form:
lag𝑖 ∝ 𝑤𝑖 (𝑉 − 𝑣𝑖 ),
𝑉 𝐷 𝑖 = 𝑣 𝑖 + 𝑞𝑖
𝑤0
,
𝑤𝑖
where 𝑉 is an aggregate virtual-time reference and 𝑞𝑖 is a requested slice measured in real-time units under
this normalisation. Eligible entities have nonnegative lag; among them, the earliest virtual deadline wins. This
combines long-term weighted fairness with better control of latency. Current implementation uses augmented
trees and additional rules for sleepers/deferred dequeue; these proportional formulas are intuition, not a complete
reimplementation.
Cgroup v2 adds hierarchical scheduling: cpu.weight divides shares among groups before tasks, while cpu.max can
impose bandwidth quotas. Thus nice values alone do not describe all CPU entitlement.
8.8 Affinity, migrations, and NUMA
Affinity is per task/thread. A pthread inherits its creator’s mask. The effective CPUs are the intersection of
the requested mask, cgroup/cpuset restrictions, and online/permitted CPUs.
taskset -pc $$
ps -o pid,tid,psr,stat,cls,rtprio,pri,ni,comm -L -p $$
Pinning can make experiments reproducible but is not automatically faster. Linux normally allocates anonymous
pages on first touch under the active NUMA policy. Pinning a compute thread far from the node that owns its
pages can increase latency and fabric traffic. On a single-node laptop this distinction is smaller, but core/cache
topology still matters.
8.9 The supplied cpu.c is an illustration, not a benchmark
The program repeatedly calls printf and Spin. It demonstrates interleaved progress, but:
• terminal output performs buffered I/O and syscalls and can block;
• common.h line 15 accidentally uses tv_sec twice rather than tv_usec, giving step-like time;
• gettimeofday is wall time, not the correct monotonic clock for elapsed measurement;
• the loop’s I/O can dominate the scheduling phenomenon.
A real measurement should use clock_gettime(CLOCK_MONOTONIC) or CLOCK_MONOTONIC_RAW as appropriate, minimise
observation effects, report affinity/topology, warm up, repeat, and use perf stat rather than inferring scheduling
from terminal order.
Observe scheduling without changing real-time policy
uname -r
lscpu -e=CPU,NODE,SOCKET,CORE,ONLINE
ps -eLo pid,tid,tgid,ppid,psr,stat,cls,rtprio,pri,ni,pcpu,comm --sort=pid,tid | less
# For one longer-running program:
pid=12345
# replace with the numeric PID you just launched
grep -E '^(State|Tgid|Pid|Threads|Cpus_allowed_list|voluntary_ctxt_switches|nonvoluntary_ctxt_switches):' /proc/$pid/
status
cat /proc/$pid/sched
# If perf is installed and permitted:
perf stat -e task-clock,context-switches,cpu-migrations,cycles,instructions ./your_program
Do not launch unbounded SCHED_FIFO, SCHED_RR or SCHED_DEADLINE work on your daily driver merely to experiment;
misconfigured real-time work can starve the desktop and administration.
Retrieval checkpoint 5
Why can a timer interrupt occur without a context switch? What state is already on A’s kernel stack
when schedule() switches to B? Why can switching between two pthreads avoid an mm switch? Why does
Advanced introduction - 4 September 2026
40
CPU and Memory Virtualization
Linux / Fedora study day
one runqueue per CPU require load balancing and reschedule IPIs?
9 Memory virtualization: the contract and the machinery
CPU virtualization answers, “Which execution stream runs now?” Memory virtualization answers, “What does
this load or store mean for this execution context?” The two mechanisms meet on page faults, fork, execve, TLB
shootdowns and context switches that select or maintain an effective address-space context; a same-mm thread
switch need not change the page-table root.
The useful mental model is not “each process owns a contiguous chunk of RAM.” It is:
Each address-space context defines a sparse, protected mapping from virtual pages to backing objects.
Some mappings currently have physical frames; some can obtain one on demand; some intentionally
share frames; and some accesses are forbidden.
The OS wants four properties at once:
1. Transparency: a program can use ordinary pointers as if it had a private, simple memory.
2. Protection: one context cannot read or overwrite another merely by fabricating a number.
3. Efficiency: common loads and stores must run in hardware without a syscall.
4. Controlled sharing: processes may deliberately share libraries, files, anonymous memory, or kernelprovided pages.
The implementation again follows limited direct execution. Userspace issues loads and stores directly. The
MMU checks translation and permission state installed by the kernel. Only exceptional cases trap into the
kernel.
9.1 Start with the simplest translation: base and bounds
Suppose a process emits virtual address 𝑉 𝐴. With one relocation register and one limit register, hardware can
compute:
𝑃𝐴 = 𝐵 + 𝑉 𝐴
if 0 ≤ 𝑉 𝐴 < 𝐿.
The kernel alone may load base 𝐵 and limit 𝐿. On a context switch it changes them, so the same virtual address
can name a different physical byte for the next process. This already gives relocation and isolation.
It also exposes the design pressure:
• the address space must occupy one contiguous physical extent;
• heap and stack growth are awkward;
• unused holes waste memory (internal fragmentation);
• finding differently sized physical holes causes external fragmentation.
Segmentation generalises this with separate base, bound and protection for logical regions such as code, heap
and stack. An address contains a segment selector plus an offset. It supports sparse logical regions and different
permissions, but variable-sized physical placement still fragments. In x86-64 long mode Linux normally uses a
flat segmentation model; paging supplies ordinary userspace isolation. FS and GS bases remain important for
thread-local and per-CPU state.
These old mechanisms matter because they make the essential invariant visible: translation metadata is
privileged, but translated accesses are fast and unprivileged.
9.2 Paging: fixed-size indirection
Choose a page size 𝑃 = 2𝑝 . Split a virtual address into:
𝑉 𝐴 = 𝑉 𝑃 𝑁 ⋅ 𝑃 + offset,
0 ≤ offset < 𝑃 .
A page-table entry maps the virtual page number (VPN) to a physical page frame number (PFN):
𝑃 𝐴 = 𝑃 𝐹 𝑁 ⋅ 𝑃 + offset.
Advanced introduction - 4 September 2026
41
CPU and Memory Virtualization
Linux / Fedora study day
The offset is not translated; it selects the same byte within the chosen page/frame. Fixed-size frames remove
external fragmentation for page placement. They introduce internal fragmentation in partially used final pages
and require translation metadata.
For a flat page table with 𝑉 virtual-address bits, 𝑝 offset bits and 𝐸 bytes per entry:
table bytes = 2𝑉 −𝑝 𝐸.
With a 48-bit virtual address, 4 KiB pages and 8-byte entries, a flat table would require 236 × 8 = 512 GiB per
address space. A multi-level radix tree allocates lower levels only for populated regions. Sparse address spaces
then need far less metadata.
Translation is not allocation
An address range can exist as a virtual-memory area without any private physical frames yet. A present
page-table entry can map a shared frame. A non-present entry can represent a valid demand-zero, filebacked or swapped page whose next access should fault. “Mapped,” “resident,” “unique,” and “writable”
are four different properties.
9.3 The common x86-64 four-level walk
On a typical current x86-64 Fedora machine with 4 KiB base pages and four hardware levels, a canonical 48-bit
virtual address is divided as follows:
Virtual-address bits
47-39
38-30
29-21
20-12
11-0
9-bit field
Hardware name
Linux generic name
top-level index
second index
third index
fourth index
byte offset
PML4
PDPT
PD
PT
offset
PGD
PUD
PMD
PTE
offset
Each index chooses one of 512 eight-byte entries, so every page-table page is itself 4 KiB. Linux source keeps
a generic five-level vocabulary - PGD, P4D, PUD, PMD, PTE. When a configured architecture level is absent,
its accessor layer is folded so it consumes no hardware table page; on ordinary four-level x86-64 the P4D level
is folded. Hardware and kernel support can instead enable five-level paging (LA57), giving a 57-bit canonical
address and one more 9-bit index. Do not infer the active mode only from the CPU’s advertised capability.
For four-level canonical addresses, bits 63-48 must be copies of bit 47. This creates a lower canonical half
and an upper canonical half; addresses in the hole between them are not ordinary linear addresses. The exact
user/kernel layout is a Linux configuration and architecture choice, not a law implied by paging alone.
9.3.1 One walk by hand
Take the lower-half canonical address:
VA = 0x00007f1234567abc
Its fields are:
Field
Bits
Value
PML4 / PGD index
PDPT / PUD index
PD / PMD index
PT / PTE index
page offset
47-39
38-30
29-21
20-12
11-0
0x0fe = 254
0x048 = 72
0x1a2 = 418
0x167 = 359
0xabc = 2748
Assume CR3 identifies a PML4 at physical 0x0000000123400000, and the entries point in sequence to tables at 0
x0000000456700000, 0x0000000678900000, and 0x000000089ab00000. An entry address is the table base plus 8 × index:
Advanced introduction - 4 September 2026
42
CPU and Memory Virtualization
Linux / Fedora study day
Read
Entry offset
Physical address read
0x7f0
0x00000001234007f0
0x240
0x0000000456700240
0xd10
0x0000000678900d10
0xb38
0x000000089ab00b38
PML4 entry 254
PDPT entry 72
PD entry 418
PT entry 359
If the leaf entry names frame base 0x00000000abcdf000, the translated physical address is:
0𝑥00000000𝑎𝑏𝑐𝑑𝑓000 | 0𝑥𝑎𝑏𝑐 = 0𝑥00000000𝑎𝑏𝑐𝑑𝑓𝑎𝑏𝑐.
In real hardware, a table base is extracted from each entry by masking flags and reserved bits according to the
CPU’s physical-address width. The concrete addresses above teach the arithmetic; they are not a claim about
your machine’s page tables.
9.3.2 Huge leaves terminate the walk early
The same virtual address can be resolved at a higher level when the entry’s page-size bit marks a leaf. This
changes both the alignment rule and which virtual bits form the offset.
Mapping size
Leaf level in a
four-level walk
Virtual offset bits
Alignment required of leaf
base
4 KiB
2 MiB
1 GiB
PT / PTE
PD / PMD
PDPT / PUD
11-0
20-0
29-0
4 KiB
2 MiB
1 GiB
Use the guide’s example address again:
VA = 0x00007f1234567abc
Suppose the PD entry selected by index 0x1a2 is a present 2 MiB leaf whose physical base is 0x0000000089a00000.
The hardware does not read a PT page. Bits 20-0 of the virtual address are now the offset:
offset2MiB = 𝑉 𝐴 & (221 − 1) = 0𝑥167𝑎𝑏𝑐,
𝑃 𝐴 = 0𝑥0000000089𝑎00000 | 0𝑥167𝑎𝑏𝑐
= 0𝑥0000000089𝑏67𝑎𝑏𝑐.
The physical base is valid because its low 21 bits are zero. The old 9-bit PTE index has not vanished; it has
become part of the 21-bit offset within the 2 MiB frame.
Now suppose instead that the PDPT entry selected by index 0x048 is a present 1 GiB leaf with physical base
0x0000000400000000. The hardware stops before both the PD and PT reads:
offset1GiB = 𝑉 𝐴 & (230 − 1) = 0𝑥34567𝑎𝑏𝑐,
𝑃 𝐴 = 0𝑥0000000400000000 | 0𝑥34567𝑎𝑏𝑐
= 0𝑥0000000434567𝑎𝑏𝑐.
Here both lower 9-bit indices become part of the 30-bit offset. Reserved physical-address bits, reserved flag
combinations, or a misaligned huge-leaf encoding cause a page fault with the reserved-bit condition rather than
a usable translation.
The precise huge-page performance claim
A 2 MiB or 1 GiB hardware leaf can reduce the number of dependent table reads needed after a TLB
miss, and one TLB entry covers more bytes. A TLB hit reads no page-table levels. A PTE-mapped
multi-size THP does not terminate the hardware walk early; its benefit comes from fewer faults and, on
some architectures, compression of suitably contiguous translations.
Advanced introduction - 4 September 2026
43
CPU and Memory Virtualization
Linux / Fedora study day
9.3.3 Decode the x86 page-fault error code
When x86 raises #PF, it writes the faulting linear address to CR2 and pushes a page-fault error code as part of
exception entry. It does not push CR2; Linux reads it. The commonly relevant error-code bits are:
Bit
Name
If clear
If set
0
P
non-present translation
1
2
3
W/R
U/S
RSVD
4
5
I/D
PK
6
SS
read-like access
supervisor access
no reserved-bit
violation
data access
no protection-key
violation
ordinary access
15
SGX
outside this condition
protection violation on
a present translation
write-like access
user-mode access
reserved paging bit was
set illegally
instruction fetch
protection-key check
failed
shadow-stack access,
where supported
SGX-specific violation,
where supported
Bits beyond the basic set depend on enabled CPU features. Always consult the active architecture manual
before decoding an unfamiliar value.
Typical low-bit patterns make useful predictions:
Access
user read from an
unmapped address
first user write to
untouched anonymous
memory
user write through a
present read-only PTE
user instruction fetch
from a present NX
page
Low error-code value
Hardware fact
0x4
non-present, read, user
0x6
non-present, write, user
0x7
protection, write, user
0x15
protection, user,
instruction fetch
Possible Linux
interpretation
invalid VMA, demand
fault, or
swapped/file-backed
state
valid writable VMA;
allocate or map
backing
illegal write, or
deliberate
COW/write-protect
trap
reject and usually
deliver SIGSEGV
The error code reports what the MMU observed, not whether the program’s abstract mapping should ultimately
permit the operation. A COW write and an illegal write can reach Linux with the same basic hardware pattern.
Linux must combine the code with the VMA, PTE/folio state, and backing semantics.
A noncanonical linear address normally faults before paging with #GP (or a stack-specific exception in relevant
cases), not #PF. Userspace may still receive SIGSEGV, so the signal name alone does not identify the hardware
exception. Likewise, a valid TLB miss raises no exception at all.
Translation drill: leaf or fault?
For one virtual address, classify five outcomes: TLB hit, valid 4 KiB walk, valid 2 MiB leaf, non-present #PF,
and noncanonical #GP. For each, state how many page-table entries hardware must read in the dependency
model, whether kernel code runs, which offset bits survive unchanged, and whether CR2 is architecturally
relevant.
Advanced introduction - 4 September 2026
44
CPU and Memory Virtualization
Linux / Fedora study day
9.3.4 Permissions accumulate down the walk
Important architectural information includes:
• Present: whether this entry participates in a valid translation.
• User/supervisor: whether CPL3 may use the path.
• Read/write: whether writes are permitted. With CR0.WP=1, supervisor writes also honour read-only
mappings.
• Execute disable (NX/XD): whether instruction fetch is forbidden when NX is enabled.
• Accessed: set by hardware as a translation is used.
• Dirty: set on writes at a leaf mapping.
• Page size: at a PDPT or PD leaf, terminates the walk early for a 1 GiB or 2 MiB mapping.
• Global: with page-global enable, can allow selected kernel translations to survive ordinary address-space
changes.
The effective permission is the restrictive combination of every traversed entry. A userspace write needs present,
user and writable permission all the way down. Execution additionally needs NX clear throughout. There is
no ordinary page-table “read-enable” bit and no dedicated W^X bit; W^X is a kernel policy built from writable and
executable permissions. Protection keys and features such as SMAP add further constraints.
If an entry is non-present, Linux may use its otherwise software-available contents to encode swap, migration
or other state. That encoding is Linux implementation, not the hardware’s general meaning for non-present
entries.
9.4 TLBs: caching the result of translation
Walking four tables for every load would be disastrous. Each logical CPU therefore has translation lookaside
buffers (TLBs) that cache recent translations and permissions. A memory access conceptually does:
1. split virtual page and offset;
2. look for a matching translation under the current address-space context;
3. on a TLB hit, check cached permission and access the cache/memory hierarchy;
4. on a TLB miss, perform a hardware page-table walk;
5. cache the successful translation, then retry the data access.
A TLB miss is not a page fault. A miss with present, permitted page tables is resolved by hardware. A
page fault is the architectural exception raised when the walk finds a non-present translation or a permission
violation (and for certain other paging conditions).
Under a deliberately crude model with 1 ns TLB lookup, 80 ns memory access, 99% TLB hits and a cold
four-level miss needing four page-table reads plus the final data read:
𝐸𝐴𝑇 = 0.99(1 + 80) + 0.01(1 + 5 × 80) = 84.2 ns.
Real CPUs overlap work and cache page-table entries in ordinary caches and paging-structure caches, so this is
a dependency model, not a prediction. It shows why TLB reach, huge pages and locality matter.
9.4.1 CR3, PCIDs and shootdowns
CR3 identifies the top-level translation context.
With process-context identifiers (PCIDs), its low 12 bits can
carry a 12-bit tag and a supported no-flush use can preserve translations belonging to other tags. Linux must
manage tag reuse correctly; KPTI may also use distinct user and kernel translation contexts for one logical mm.
PCIDs reduce, but do not eliminate, invalidation work.
When Linux unmaps a page, changes a permission, or reuses a physical frame, stale TLB entries on CPUs that
might retain that mm/PCID can be dangerous. Linux publishes the page-table change, invalidates locally with
architecture operations such as INVLPG or INVPCID, and sends TLB-shootdown IPIs to relevant remote CPUs. Each
target invalidates and acknowledges before the old mapping’s frame or permission can be safely reused. That
update-invalidate-acknowledge-before-reuse order is the security invariant.
Cache coherence does not solve this. Coherence can make the page-table memory writes visible, but a TLB
is a separate translation cache and may continue using an old result until explicitly invalidated under the
architecture’s rules.
Advanced introduction - 4 September 2026
45
CPU and Memory Virtualization
Linux / Fedora study day
Retrieval checkpoint 6
Why does multi-level paging save memory but not necessarily walk time? For the example address, derive
all five fields without looking. Explain why a TLB miss can complete without kernel execution, why a
page fault must enter the kernel, and why coherent caches do not remove the need for shootdown IPIs.
10 Linux virtual memory in operation
Hardware walks page tables; Linux decides what they should mean. The main abstractions are:
• an mm_struct for one userspace address space, including its top-level page-table pointer and accounting;
• vm_area_struct objects (VMAs) describing contiguous virtual ranges with uniform permissions and backing
rules;
• page tables describing currently materialised translations at page granularity;
• physical-page metadata, page-cache state, reverse mappings, reclaim state and allocator state.
Current Linux organises an mm_struct’s VMAs in a maple tree. This is version-sensitive implementation detail;
the stable idea is that a VMA answers, “Is this address range valid, with what permissions and backing?” A
page-table entry answers, “What is the current per-page translation/state?”
/proc/$pid/maps reports VMAs, not a list of resident physical pages. /proc/$pid/smaps and smaps_rollup add resident-set
and proportional accounting. Even those are sampled accounting views, not a promise that every page remains
resident after the read.
10.1 A VMA is mutable shared metadata
A VMA is not a permanent label attached to an address. System calls continuously reshape the interval map
in an mm_struct:
Operation
mmap
munmap
mprotect
brk
madvise
mremap
Typical VMA effect
Typical page-table effect
insert a range, possibly after
selecting a hole
remove a whole range or split
VMAs at its boundaries
split at boundaries, change
permissions, later merge
compatible neighbors
extend or shrink the process
data/heap interval
change policy or treatment of a
range; sometimes discard or
populate content
resize or move an interval
initially none for a lazy mapping;
later faults install leaves
clear translations, invalidate TLB
state, release references
rewrite permissions or split a huge
mapping, then invalidate
lazy on growth; unmap and release
on shrink
depends on the advice and backing
move, rebuild, or invalidate
relevant translation structure
VMAs with compatible neighbors can merge; an operation on the middle of one VMA can create as many as
three intervals. This is why /proc/$pid/maps is a current interval view, not an immutable history.
All pthreads created with CLONE_VM share the same mm_struct. If thread A calls munmap or mprotect, the addressspace change is therefore a change for thread B as well. Kernel locking makes the metadata update internally
consistent; it does not make the application protocol correct. B must not keep dereferencing a region while A
removes it merely because both calls are individually valid C.
10.1.1 The locks protect different objects
The broad concurrency structure on current Linux is:
1. The per-mm mmap_lock protects the VMA map as a whole. Read mode permits concurrent stable lookup; write
mode serializes structural changes such as insertion, removal, split, and merge.
2. Modern fault paths can use an optimistic RCU lookup plus a per-VMA read lock to avoid taking the
contended mmap_lock for every fault. If validation or lock acquisition fails, the path falls back or retries.
Advanced introduction - 4 September 2026
46
CPU and Memory Virtualization
Linux / Fedora study day
3. A writer takes the mmap_lock for write and the required per-VMA write locks before changing protected VMA
fields.
4. Page-table locks protect concrete page-table entries. Holding a VMA stable does not by itself serialize two
CPUs updating the same PTE page.
5. Reverse-mapping locks, folio locks, filesystem mapping locks, and invalidation mechanisms protect different
relationships. They are not interchangeable with the VMA and PTE locks.
A fault can need allocation, filesystem I/O, migration completion, or userfaultfd handling, all of which may
sleep. Linux therefore has retry paths: it can abandon an optimistic lookup or drop a lock, wait, revalidate the
address-space state, and try again. Never reason that a pointer remains valid across a sleep merely because it
belonged to a VMA before sleeping.
10.1.2 Changing a PTE is a distributed operation
Suppose one thread makes a page read-only while another logical CPU is using the same mm:
1. Linux stabilizes the VMA and serializes the page-table update.
2. It publishes the new PTE state under the architecture’s ordering rules.
3. It invalidates the local cached translation and targets CPUs that may retain a translation for this mm and
PCID.
4. Remote CPUs handle a TLB-shootdown IPI or an equivalent invalidation protocol.
5. Before Linux reuses a freed frame/page-table page, or relies on a stricter permission for safety, it ensures
that no target can continue using the stale translation. Work may be batched, but the safety invariant
cannot be skipped.
Cache coherence makes the modified PTE bytes visible. It does not force a hardware thread to stop using an
already cached translation. This is the exact boundary between the cache-coherence mechanism you already
know and OS-managed translation coherence.
Mapping concurrency is an application problem too
mmap_lock, VMA locks, PTE locks, and TLB shootdowns protect kernel invariants.
They do not create a
C happens-before edge for arbitrary data stored in the mapping. Use a mutex, atomics, a stop-the-world
protocol, or another application-level lifetime scheme before one thread revokes memory that another may
access.
10.2 Where a C program’s mappings come from
Running a dynamically linked ELF program typically creates mappings for:
• loadable ELF segments for the main executable;
• the ELF interpreter/dynamic linker;
• shared libraries;
• a growable user stack with a guard boundary;
• anonymous heap and allocator arenas;
• per-thread stacks and thread-local storage;
• the vDSO/vvar pages supplied by the kernel;
• explicit file or anonymous mmap regions.
The familiar source-level text / data / heap / stack drawing is a useful start, but it omits holes, shared objects,
multiple stacks, the dynamic loader and many anonymous mappings. ELF program headers, not source sections
alone, tell the loader what to map.
file ./your_program
readelf -hW ./your_program
readelf -lW ./your_program
objdump -d -M intel ./your_program | less
Fedora normally builds position-independent executables (PIE) so address-space layout randomisation can
relocate the main image. ASLR is defence-in-depth, not isolation by itself; page permissions and kernelcontrolled translations enforce isolation.
Advanced introduction - 4 September 2026
47
CPU and Memory Virtualization
Linux / Fedora study day
10.3 malloc reserves an address; touching commits work
malloc is a userspace allocator API, not a syscall.
An allocator manages chunks inside larger arenas obtained
from the kernel, commonly with brk and mmap. Exact thresholds and arena policies are libc/version/workload
details.
A successful allocation often means that a virtual range and accounting commitment exist. It does not guarantee
that a unique physical frame has already been installed for every page. Linux can satisfy anonymous memory
lazily:
1. allocator returns an address within a valid writable VMA;
2. the first read may map a shared read-only zero page in some cases;
3. the first write faults and obtains a private zero-filled frame;
4. Linux installs a writable PTE and restarts the instruction.
Zeroing is a security requirement: a new userspace page must not reveal bytes from its previous owner.
What ‘prog1.c‘ and ‘prog2.c‘ really show
malloc returns a virtual address. Different processes may legally use the same virtual number while mapping
different frames, but ASLR and allocator state mean the supplied programs may print different numbers.
Equality would illustrate independent translation; inequality does not refute it. %p expects (void *)p
. Ordinary users also cannot rely on /proc/pagemap exposing physical frame numbers because the kernel
restricts that information.
10.4 The page-fault path: exception, decision, retry
For an x86 page fault, hardware records the faulting linear address (traditionally in CR2) and an error code
describing present/protection, read/write, user/supervisor, instruction fetch and related conditions. It vectors
to Linux at CPL0. The broad kernel path is:
1. save an exception frame and enter common exception bookkeeping;
2. determine whether the fault came from user or kernel context;
3. locate the VMA covering the address;
4. reject an absent VMA or disallowed access;
5. resolve the page’s backing state - anonymous, file, copy-on-write, swap, migration, userfault handling, and
so on;
6. allocate, read, copy or wait as necessary;
7. update page tables and translation invalidation state;
8. return and retry the faulting instruction.
The same instruction can therefore appear to execute normally even though its first attempt caused a schedulervisible sleep and disk I/O. If Linux cannot make the access valid, userspace normally receives SIGSEGV; certain
object/backing errors can produce SIGBUS. A kernel-mode fault may instead be recovered by an exception table
(for a safe user-copy helper) or become a kernel bug.
10.4.1 Minor and major faults
• A minor fault can be resolved without reading the needed page from storage: demand-zero allocation, an
already-cached file page, or many COW faults.
• A major fault requires storage I/O for the needed content.
Neither term means TLB miss. A TLB miss does not normally increment userspace page-fault counts.
10.5 Anonymous, file-backed, shared and private
Two independent questions matter:
1. What backs the mapping - anonymous memory or a file/object?
2. Are modifications shared or private?
Mapping
Initial content
Write meaning
anonymous private
zero
private dirty anonymous page
Advanced introduction - 4 September 2026
48
CPU and Memory Virtualization
Linux / Fedora study day
Mapping
Initial content
Write meaning
file MAP_SHARED
file/page cache
file MAP_PRIVATE
file/page cache
explicit shared anonymous
zero
visible through the shared
mapping and eligible for writeback
copy-on-write private divergence;
does not update the file through
that mapping
modifications visible to mapping
participants
Linux’s page cache unifies cached file data used by read/write and file-backed mmap. Dirty shared/file pages
eventually require writeback. Clean file-cache pages can usually be discarded and read again. Dirty anonymous
pages need swap backing before they can be reclaimed without losing data.
10.6 fork: copy the map, share the frames, fault on write
fork() creates a logically separate address space. Linux copies relevant VMA and page-table structure, increments
references to underlying pages, and marks ordinary private writable mappings read-only in parent and child.
The VMA/private-mapping semantics say that a future write is allowed by making a private copy; the hardware
PTE is deliberately read-only. x86 has no dedicated “COW” PTE bit. Linux does not eagerly copy every byte.
When either side writes:
1. the CPU raises a protection page fault;
2. Linux recognises a valid private COW mapping;
3. if the page is still shared, Linux allocates a frame and copies the content;
4. it changes the faulting process’s PTE to the private writable frame;
5. it updates reference/reverse-mapping state and invalidates stale translation state;
6. the store is retried.
If kernel accounting proves that the old page is already exclusive, it may be made writable without copying.
The stable semantic promise is isolation after a write, not a mandatory copy operation on every COW fault.
This explains three observations at once:
• fork() can be much faster than copying the parent’s resident bytes;
• the first writes after fork() can be measurably slower;
• parent and child can initially report shared/proportional resident memory even though their virtual address
spaces are distinct.
10.7 execve: replace mappings, retain process identity
Successful execve keeps the process identity and many kernel relationships, but replaces the userspace image.
Linux validates the executable, builds a new memory context, maps loadable ELF regions and the interpreter,
creates an initial stack containing arguments, environment and auxiliary vector, installs vDSO state, applies
executable credential rules, terminates sibling threads, and commits the new image.
The old user instruction pointer and stack no longer exist, so success cannot return. The loader then performs
userspace relocation and library initialisation before main. Demand paging means much of the executable may
still be untouched when main begins.
Retrieval checkpoint 7
Draw three layers for one address: VMA rule, PTE state, physical/backing object. Explain a demand-zero
fault and a COW write fault at those three layers. Why can malloc succeed before all pages are resident?
Why does successful execve keep a PID but not return to its caller?
Advanced introduction - 4 September 2026
49
CPU and Memory Virtualization
Linux / Fedora study day
10.8 Working sets, reclaim and swap
Virtual memory is not synonymous with swap. Isolation, sparse address spaces, relocation, sharing and COW
all work without swap. Swap is one possible backing store for reclaiming anonymous pages.
A useful theoretical quantity is the working set over a recent window Δ:
𝑊 (𝑡, Δ) = {pages referenced during (𝑡 − Δ, 𝑡]}.
When active working sets fit, faults are mostly startup or phase changes. When the machine repeatedly evicts
pages that are soon demanded again, useful work collapses into faulting and I/O: thrashing.
Textbook replacement policies isolate important ideas:
• OPT evicts the page whose next use lies farthest in the future; it is an unattainable lower bound.
• FIFO ignores use and can exhibit Belady’s anomaly: more frames can cause more misses.
• exact LRU has a stack property but is expensive to maintain at kernel scale.
• clock/second-chance approximates recency using accessed information.
Linux uses scalable approximations, generations/lists and feedback, not textbook exact LRU. Multi-Gen LRU
may be configured on a particular kernel; treat its presence as inspectable policy, not a timeless API.
Linux reclaim is not one global LRU. A useful unit is the lruvec, conceptually the intersection of a NUMA
node and a memory cgroup. This lets pressure and protection be applied to the pages charged to one workload
on one node. The root memory cgroup also has per-node reclaim state.
Within that scope Linux distinguishes anonymous from file-backed memory and tracks recency with scalable
approximations. Depending on kernel configuration this can be active/inactive lists, Multi-Gen LRU generations,
or related evolving machinery. The stable principles are:
• recently useful pages should normally survive over cold pages;
• a page that is evicted and quickly faulted again is a refault, evidence that the eviction choice or available
capacity was poor;
• anonymous and file-backed memory have different costs, so reclaim balances them rather than pretending
all pages are equal;
• reclaim policy operates on folios as well as base pages, so one decision can cover more than 4 KiB;
• cgroup protection and limits alter which workload bears the pressure.
10.8.1 What can actually be reclaimed?
Memory state
What reclaim must do
clean file-cache folio
remove mappings if needed, then discard; file storage
can supply it again
arrange writeback before it can be discarded safely
ensure current contents have valid swap backing,
writing them when needed; an unchanged clean
swap-backed copy may already be discardable
normally cannot be discarded while preserving
contents
may be discarded because the application accepted
loss until it writes again
kept off ordinary eviction candidates until its state
changes
cannot freely be reclaimed or migrated while the
external user retains the pin
dirty file-cache folio
ordinary anonymous data with swap
ordinary anonymous data without usable swap
MADV_FREE-style lazy-free anonymous data
mlocked/unevictable memory
DMA or long-term pinned memory
Pinned and unevictable memory reduce the pool over which reclaim and compaction can succeed. A system
can therefore be under practical allocation pressure even while a naive total suggests that enough RAM exists.
When a zone falls below watermarks, per-node kswapd performs background reclaim. If that does not create
suitable free memory quickly enough, an allocating task can enter direct reclaim and spend its own latency
Advanced introduction - 4 September 2026
50
CPU and Memory Virtualization
Linux / Fedora study day
budget scanning, writing, or waiting. Under a cgroup memory.high boundary, tasks in that cgroup can likewise be
throttled and routed through direct reclaim even if the host as a whole has free memory.
Reclaim and compaction answer different questions:
• reclaim asks, “Can I make more pages free?”
• compaction asks, “Can I move allocated pages so the free pages form a sufficiently large contiguous block?”
Neither guarantees success. Unmovable or pinned pages can prevent compaction; dirty pages and unavailable
swap can make reclaim expensive or ineffective.
10.8.2 Memory-cgroup observations are part of the explanation
On cgroup v2, useful files include:
File
memory.current
memory.stat
memory.events
memory.events.local
memory.pressure
memory.numa_stat
memory.swap.current
What it answers
how many bytes this cgroup and its descendants are
currently charged
how the charge is divided among anonymous, file,
kernel/slab, workingset, fault, and reclaim categories
whether low/high/max/OOM conditions occurred in
this hierarchy
the same class of events generated locally rather than
by descendants
how much execution time is stalled by memory
pressure, via PSI
how charged memory is distributed across NUMA
nodes
current swap charge, if the controller exposes it
Usage is not pressure. A file-copy workload may use a large page cache but be easy to reclaim; a smaller
anonymous workload with no swap may experience serious stalls. PSI reports lost execution time, while memory.
current reports charged bytes. Read both.
Why refaults matter
A page being old is only a prediction that eviction will be cheap. If it returns almost immediately, the
refault provides evidence that the working set did not fit or that reclaim chose badly. Modern reclaim uses
such feedback; it is not textbook exact LRU with a timestamp on every access.
Low MemFree is often healthy because unused RAM caches data. MemAvailable is a better rough estimate of memory
that can be supplied without severe reclaim. It is still an estimate, not a reservation.
10.8.3 Overcommit and out-of-memory decisions
Because virtual allocation is lazy, Linux can promise more virtual/anonymous memory than it can make resident
simultaneously. Overcommit policy can be heuristic, optimistic or commit-accounted. Thus a very large mmap
may succeed while a later first write encounters memcg or global OOM handling, or a mapping-dependent fault
signal. Do not expect a delayed malloc-style ENOMEM return from the already executing store.
Allocation failure can also be local rather than global: a cgroup limit, NUMA policy, cpuset, DMA/Normal
zone constraint, high-order contiguity or writeback deadlock avoidance can matter even when some free RAM
exists elsewhere.
If recovery fails, kernel OOM logic chooses among eligible victims using a badness heuristic affected by cgroups
and oom_score_adj; it is not simply “kill the largest process.” Fedora systems may additionally run systemd-oomd,
which uses pressure and cgroup policy in userspace and can act before the kernel OOM killer. Do not induce
host-wide OOM as a learning experiment.
If swapon --show reports /dev/zram0, your Fedora installation uses a compressed RAM block device as swap. That
trades CPU time and some physical memory for greater effective capacity. It is distinct from zswap, which is a
compressed cache in front of some other swap backing.
Advanced introduction - 4 September 2026
51
CPU and Memory Virtualization
Linux / Fedora study day
10.9 Physical allocation: from nodes to objects
Linux does not have one undifferentiated free-page list. Nodes contain zones with watermarks and buddy free
areas. Per-CPU page caches provide a fast branch for common low-order traffic and refill from those zones;
higher-order and constrained requests can enter the zone/buddy paths directly. Separately, SLUB obtains page
blocks from the page allocator and subdivides them into kernel objects.
An allocation request carries more than a size. Its context constrains where Linux may look and what work it
may perform:
• NUMA policy and cpusets restrict eligible nodes;
• a zonelist expresses which memory zones may satisfy the request;
• GFP flags encode whether the caller may sleep, enter reclaim, start filesystem or storage I/O, and use
particular reserves;
• order 𝑘 requests 2𝑘 physically contiguous base pages;
• migration type helps keep movable and unmovable allocations from fragmenting every large extent;
• memory-cgroup charging may reject an allocation even when the host has free pages.
For common low-order traffic, a per-CPU-pageset cache can satisfy an allocation without taking the main zone
lock. On a miss, it refills from the buddy allocator. Higher-order or specially constrained requests can go to the
buddy allocator through other paths; the per-CPU cache is an optimization, not a mandatory layer traversed
by every allocation.
Early boot uses memblock before the ordinary allocators are ready. Zones encode reachability and policy constraints
such as DMA32, Normal and Movable. Details vary by architecture and configuration.
For base page size 𝑃 , a buddy block of order 𝑘 has:
size(𝑘) = 2𝑘 𝑃 ,
buddy(𝑝, 𝑘) = 𝑝 ⊕ 2𝑘
for a suitably aligned starting page-frame number 𝑝. Splitting provides a smaller block; two simultaneously free
buddies merge. With 4 KiB pages, order 9 is 2 MiB.
SLUB builds caches of kernel objects on top of page allocations and uses per-CPU freelists to reduce shared
locking. kmalloc provides kernel virtual addresses backed by suitably physically contiguous direct-mapped memory
within its practical limits. vmalloc creates a contiguous kernel virtual interval backed by noncontiguous frames,
at extra mapping/TLB cost. User malloc is a libc allocator and should not be confused with either.
10.9.1 Keep the three allocators separate
Layer
Allocates
page allocator
physical pages/folios, possibly
contiguous by order
SLUB
kernel objects such as task or
inode-related structures
chunks in one process’s virtual
mappings
userspace allocator such as glibc
malloc
Important fast path and source of
fragmentation
per-CPU pagesets and buddy free
areas; physical fragmentation
matters
per-CPU freelists/slabs; partially
occupied slabs retain pages
per-thread tcache, arenas, bins, brk,
and mmap; heap fragmentation and
retention matter
SLUB obtains pages from the page allocator and subdivides them into typed or size-class kernel objects. Its
per-CPU paths reduce shared locking, but an object allocation is not guaranteed never to fall back, reclaim, or
fail.
On a typical Fedora glibc system, malloc can serve a request from a thread cache or arena without a syscall.
When it needs more virtual address space it may grow a brk arena or create an mmap. free usually returns the
chunk to the allocator first; it does not promise an immediate munmap, RSS decrease, or memory return to the
kernel. Per-thread caches, multiple arenas, unusable holes between live chunks, and partially occupied pages
can keep RSS above live application data. Other allocators have different policies, so name the allocator before
treating these details as universal.
Advanced introduction - 4 September 2026
52
CPU and Memory Virtualization
Linux / Fedora study day
Allocator-path drill
Trace two requests. First, a userspace malloc(64) that hits glibc’s thread cache. Second, assume a particular
SLUB cache uses order-0 slabs, then trace a kmalloc that misses its per-CPU freelist and needs a new slab
page. At each step state whether a syscall, page fault, page-table update, physical-page allocation, cgroup
charge, reclaim, or TLB invalidation is necessarily required, merely possible, or impossible.
The x86-64 kernel address space includes conceptually distinct regions:
• a direct/linear mapping of ordinary RAM;
• vmemmap metadata describing physical pages/folios;
• vmalloc and module regions;
• ioremap mappings for device MMIO with appropriate cache attributes;
• separately protected kernel image text, read-only data and writable data.
This is why “kernel virtual address” does not always imply one contiguous physical object, and why a device
DMA address is yet another namespace. An IOMMU can translate and restrict device-visible DMA addresses
much as the CPU MMU translates process addresses.
10.10 Huge pages and TLB reach
Ordinary x86-64 Linux can use 4 KiB pages, 2 MiB PMD leaves and 1 GiB PUD leaves. “Transparent huge
page” now covers more than one size, while explicit HugeTLB pages use a reserved pool and different semantics.
Mechanism
Typical mapping
form
PMD-sized THP
one 2 MiB PMD
leaf
multi-size THP
(mTHP)
power-of-two group
larger than base
page but smaller
than PMD size,
usually still
PTE-mapped
hugetlbfs or
MAP_HUGETLB, with
configured
huge-page size
explicit HugeTLB
Allocation policy
transparent fault
allocation or later
collapse when
policy allows
per-size policy;
fault allocation and
supported collapse
behavior
explicit
pool/reservation
and distinct
accounting
Swap/reclaim
behavior
participates in
ordinary VM
features and can
split
ordinary
transparent-VM
behavior; exact
sizes depend on
architecture and
kernel
non-swappable and
governed by
HugeTLB rules
Best observation
AnonHugePages for
anonymous PMD
THP, plus THP
counters
per-size sysfs
statistics; do not
rely on AnonHugePages
/proc/meminfo
HugePages fields
and HugeTLB
cgroup/sysfs data
PMD THP has two durable translation advantages: a single TLB entry covers 2 MiB, and a TLB miss terminates
at the PMD rather than reading a PTE table. It may also turn hundreds of first touches into one larger fault.
mTHP trades some of that granularity for lower allocation/zeroing latency. A 64 KiB anonymous mTHP on
a 4 KiB base-page system still uses PTE mappings, so the page walk is not one level shorter. It can need one
fault for 16 base pages, and some architectures can compress suitably aligned contiguous PTE translations in
the TLB. Available sizes and defaults are visible in per-size sysfs directories; do not assume that every Fedora
kernel enables the same set.
Explicit HugeTLB is a different resource contract. Its pages come from configured pools or reservation
mechanisms, are accounted separately, and are normally not interchangeable with ordinary reclaimable
anonymous THP. Failure to obtain a HugeTLB page is visible to the application rather than silently becoming
an ordinary base-page mapping under the same request.
Potential advantages:
• far more bytes covered by each TLB entry;
• fewer page-table-walk dependencies on a TLB miss when the mapping is a PMD/PUD leaf, and fewer
page-table pages;
• fewer first-touch faults over a large range;
Advanced introduction - 4 September 2026
53
CPU and Memory Virtualization
Linux / Fedora study day
• improved streaming throughput in some workloads.
Potential costs:
• internal fragmentation;
• large zero, copy or COW work;
• compaction and collapse latency;
• coarse NUMA placement;
• split work for partial mprotect or munmap;
• less predictable tail latency.
/proc/$pid/smaps needs careful interpretation. Historically, AnonHugePages reports PMD-mapped anonymous THP,
not every mTHP allocation. A PTE-mapped mTHP may still show base MMUPageSize, so absence from AnonHugePages
is not proof that only base-page allocation occurred. Use the per-size files under /sys/kernel/mm/transparent_hugepage
/hugepages-*kB/stats/ and relevant /proc/vmstat counters, while remembering that system counters include other
workloads.
Do not change a global policy for a one-process experiment
Use madvise(MADV_HUGEPAGE) or madvise(MADV_NOHUGEPAGE) on the test mapping. Read sysfs to learn the machine
policy. Do not write machine-wide THP or HugeTLB settings on a daily-driver Fedora installation merely
to make one lab’s counts cleaner.
THP can therefore change an experiment’s page-fault count and COW granularity. For a clean 4 KiB teaching
experiment, request MADV_NOHUGEPAGE on the test mapping rather than changing a machine-wide policy.
10.11 NUMA: coherent does not mean equally near
A NUMA node groups CPUs and memory into a locality domain. Hardware maintains coherence across nodes,
but a remote access usually costs more latency and interconnect bandwidth.
Default anonymous placement commonly follows first touch under the current memory policy: the CPU/thread
that first faults and writes a page influences which node supplies it. Therefore:
• malloc alone does not place all frames;
• one master thread zeroing a whole array can place pages near the master;
• having each worker first-touch its own range often aligns placement with later use;
• CPU affinity without matching memory locality can make performance worse.
Linux supports local/default, preferred, bind and interleave policies and may perform automatic NUMA
balancing with hinting faults and task/page migration. A one-node laptop cannot demonstrate remote-node
latency, but the first-touch reasoning is still important for servers.
10.11.1 Policy scope and placement time
“First touch” is shorthand, not the whole policy. Linux memory policy has scopes:
Scope
Representative interface
Lifetime intuition
system default
kernel default
per-task
set_mempolicy, often via numactl
per-VMA/range
mbind
shared-object policy
shared-memory policy machinery
fallback for allocations with no
more specific policy
inherited across fork; task policy
can persist across exec and govern
new mappings
follows that mapping/range;
copied mapping metadata can be
inherited at fork
associated with eligible shared
backing rather than one thread’s
private range
The most specific applicable policy controls a future allocation, subject to nodes allowed by cpusets and other
constraints. Policy does not itself run a task on a CPU; CPU affinity and scheduler placement are separate.
Advanced introduction - 4 September 2026
54
CPU and Memory Virtualization
Linux / Fedora study day
Conversely, CPU pinning does not retroactively move pages that were already faulted on another node.
For default anonymous allocation, the CPU that handles the first materializing fault strongly influences the
local node selected. A policy can instead prefer, bind, or interleave. Existing pages remain where they are unless
explicit migration, reclaim/refault, or automatic NUMA balancing moves them. Automatic NUMA balancing
uses protected hinting faults and samples access locality before migrating tasks or pages, so a sufficiently long
experiment can change its own placement while being measured.
The causal chain to remember is:
thread placement at materializing fault
-> applicable memory policy and allowed-node mask
-> physical node selected for the new folio
-> later local or remote accesses
-> possible automatic task/page migration
Do not conflate four costs:
Cost
Granularity
Root cause
false sharing
NUMA remoteness
cache line
physical page/node
COW copying
page or huge page
TLB shootdown
translation entry/context
writers bounce one coherent line
frame is attached to another
locality domain
private write diverges from a
shared backing
mapping changed while CPUs may
cache it
10.12 Memory protections as security mechanisms
Typical userspace mappings aim for:
Region
program code
read-only data
writable data/BSS
heap and stacks
RELRO region after relocation
Typical permission
r-x
r-rw-, non-executable
rw-, non-executable
read-only
NX forbids instruction fetch. W^X is the policy that a page should not be writable and executable simultaneously;
x86 can encode RWX, so W^X is not one magic hardware bit. A JIT can change a mapping from writable to
executable or use carefully controlled dual mappings, subject to kernel and SELinux policy.
ASLR randomises locations such as PIE text, libraries/mmap base, stack, heap and vDSO. It is probabilistic
hardening, not access control. Kernel address-space layout randomisation is separate. Guard pages detect some
stack overflows. SMEP prevents supervisor execution from user pages; SMAP restricts supervisor data access
to user pages except through deliberate access sequences. KPTI can keep most kernel mappings out of the
userspace page-table context.
Read-only Fedora VM survey
uname -r
getconf PAGE_SIZE
lscpu | grep -E 'Architecture|Address sizes|NUMA node'
grep -m1 '^flags' /proc/cpuinfo | tr ' ' '\n' | \
grep -E '^(la57|pcid|invpcid|nx|smep|smap)$' | sort -u
cat /sys/kernel/mm/transparent_hugepage/enabled
cat /proc/sys/kernel/randomize_va_space
swapon --show
zramctl 2>/dev/null || true
Advanced introduction - 4 September 2026
55
CPU and Memory Virtualization
Linux / Fedora study day
cat /proc/pressure/memory
grep -E 'Mem(Total|Free|Available)|Cached|AnonPages|Swap|Committed_AS|CommitLimit|PageTables|Slab' /proc/meminfo
grep -E 'pgfault|pgmajfault|pgscan|pgsteal|oom' /proc/vmstat
cat /proc/buddyinfo
The la57 CPU flag advertises capability, not proof that this boot uses five levels. Exact PMU/TLB counters
and sysfs files vary by CPU and kernel configuration.
Retrieval checkpoint 8
Why can clean file cache be reclaimed more cheaply than dirty anonymous memory? Distinguish reclaim
from compaction. Explain why many free base pages do not guarantee a 2 MiB buddy block. Give one
benefit and two costs of THP. Explain first touch without using the phrase “malloc allocates on the local
node.”
11 Parallelism: from the C abstract machine to cache lines
Concurrency means multiple executions are in progress with interleavings to reason about. Parallelism
means work is physically executing at the same time on different cores or hardware threads. One Linux task
runs on at most one logical CPU at an instant; many tasks can run simultaneously across CPUs.
The key lesson for someone who already knows coherence is that a correct concurrent program crosses three
contracts:
1. Language memory model: which executions the compiler and language define.
2. ISA memory model: which orders the hardware may expose and what atomic/barrier instructions
guarantee.
3. Coherence protocol: how caches establish ownership and a per-location modification order.
Coherence is necessary, but it does not make a compound source operation atomic and does not rescue a C
program with a data race.
11.1 Why volatile counter++ is broken
The source operation:
counter++;
is conceptually load, add, store. Two threads can both load 41, both compute 42, and both store 42. One
increment is lost. More fundamentally, conflicting non-atomic accesses from different C threads without a
happens-before relationship form a data race, so the C execution has undefined behavior. The compiler need
not preserve the intuitive interleaving.
volatile is for observable accesses such as certain device registers or signal interactions under specific rules.
It
does not make access atomic, insert a lock, create acquire/release ordering, or establish happens-before.
Two useful POSIX ordering edges are: actions sequenced before a successful pthread_create are visible to the new
thread when it starts, and a worker’s actions happen before a successful pthread_join returns. These explain why
initialising each worker argument before creation and reducing private results after joins is well-defined. Neither
edge orders two workers with each other while both run.
11.2 What the mutex adds
For a normal POSIX mutex, a successful unlock synchronises with a later lock that obtains the mutex. This
provides mutual exclusion plus the release/acquire ordering needed to publish protected memory.
On Linux, an uncontended pthread mutex normally uses atomic userspace state only:
try atomic transition unlocked -> locked
success: enter critical section; no syscall
failure/contention: futex wait/wake slow path
Advanced introduction - 4 September 2026
56
CPU and Memory Virtualization
Linux / Fedora study day
A futex is not a mutex. It is a kernel primitive that can compare a userspace word and block or wake tasks
associated with its address. The compare-and-sleep protocol prevents a lost wake between noticing contention
and joining the wait queue.
The slow path is a predicate loop, not a stored notification:
1. attempt the userspace atomic state transition;
2. if it fails, call FUTEX_WAIT with the value that justified sleeping;
3. Linux checks that the word still has that value while arranging the wait; if it changed, return instead of
sleeping;
4. a releaser changes the userspace state and may call FUTEX_WAKE;
5. after any return or wake, test the predicate again.
FUTEX_WAKE does not save a permit for a future waiter and does not transfer mutex ownership.
Returns can be
spurious, several waiters can race, signals can interrupt a wait, and the primitive alone promises neither fairness
nor the C language’s happens-before relation. The mutex’s atomic acquire/release protocol supplies ownership
and memory ordering; the futex supplies efficient parking when progress is unavailable.
This predicts an observation: strace -e futex may show no futex call for an uncontended lock and many calls
once contention forces sleeping/waking.
The mutex in threads.v1.c fixes correctness but puts every increment in one serial critical section. It also transfers
ownership of the same cache line among cores. A mutex can therefore be correct and still scale poorly.
11.3 Atomics, invariants and scalable reduction
An atomic fetch-add gives an exact counter without a source-level mutex-protected critical section:
#include <stdint.h>
#include <stdatomic.h>
_Atomic uint64_t counter;
atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
Relaxed ordering is sufficient only if the atomicity of this counter is the entire invariant and later thread
completion supplies any needed observation order. Relaxed does not publish unrelated data.
The C implementation need not make every atomic type lock-free. Check atomic_is_lock_free when that property
matters. On ordinary aligned x86-64, a uint64_t fetch-add is normally compiled to a lock-prefixed read-modifywrite instruction, but the portable guarantee is atomic semantics, not a particular instruction or absence of an
internal lock.
Even a relaxed atomic increment makes one cache line a serial ownership point. A more scalable design gives
each thread a private or padded counter and reduces them after join:
worker 0 -> local[0] ----\
worker 1 -> local[1] -----+-> sum after joins
worker 2 -> local[2] -----+
worker 3 -> local[3] ----/
If different counters occupy the same cache line, writes can still bounce the line: false sharing. Align/pad
deliberately only after measurement; excessive padding wastes cache capacity.
11.3.1 One cache-line ownership trace
Assume cores 0 and 1 cache the counter line in a shared state. A store needs exclusive ownership, so the core
issues a read-for-ownership transaction and invalidates other copies. The mechanisms differ:
Design
Line-level story
Correctness and scaling
plain counter++
both cores may load the same
value; later ownership transfers
allow both to store the same
incremented value
lost update at machine level, and
undefined behavior at C level
Advanced introduction - 4 September 2026
57
CPU and Memory Virtualization
Linux / Fedora study day
Design
Line-level story
Correctness and scaling
relaxed atomic fetch-add
each read-modify-write obtains
exclusive ownership and becomes
one indivisible modification
lock ownership serializes entry; the
lock line and often the counter line
remain contested
each core repeatedly modifies a
different line; final reads occur
after joins
exact count, but the line
repeatedly migrates and operations
serialize at that coherence point
correct ordering and exclusion,
with possible spinning/parking
overhead
hot loop has no shared write line;
only startup and reduction
communicate
mutex per increment
padded private counters
MESI-family state names vary by processor, and a locked instruction need not lock the external bus. The
durable intuition is ownership: coherence can serialize modifications to one line, but only the language-level
atomic or lock protocol makes that serialization a defined program operation.
11.4 Acquire/release intuition
Suppose a producer initialises object fields, then publishes a pointer with a release store. A consumer that
observes that pointer with an acquire load can then see the preceding initialisation. The synchronisation edge
constrains compiler and CPU behavior.
Without an appropriate edge, “CPU A eventually made every line coherent” does not specify when CPU B
may use the pointer relative to the object fields. Store buffers, invalidation queues, speculation and compiler
transformations all sit above the simplistic picture.
On x86’s relatively strong TSO model, some source patterns happen to require fewer explicit hardware
fences than on AArch64. Correct portable C must still use C atomics/locks; the compiler maps the semantic
requirement to the target ISA.
11.5 Linux kernel synchronisation toolbox
Kernel context adds constraints absent from ordinary pthread code:
Mechanism
Typical use
spinlock
short non-sleeping
critical section
no
mutex
task-context owned
critical section
one atomic state or
lifetime
frequent local updates
yes
atomic/refcount
per-CPU data
RCU
read-mostly
publication/lifetime
May waiter sleep?
no
no shared update
ordinary RCU readers must not
voluntarily sleep; SRCU differs
Important limitation
contention burns CPU;
IRQ context may
require IRQ-safe
variant
not for hard-interrupt
context
does not protect a
multi-object invariant
access must account for
task migration
update serialisation
and reclamation
protocol still required
Disabling preemption keeps the current task on this CPU; it does not exclude another CPU. Disabling local
interrupts prevents local interrupt handlers; it does not exclude remote CPUs. A lock is still needed for SMP
mutual exclusion when shared state can be reached elsewhere.
spin_lock_irqsave is appropriate when the same lock can be taken by task context and a local hard interrupt:
it prevents the task from being interrupted locally while holding the lock, and the lock excludes other CPUs.
PREEMPT_RT changes some lock implementation properties, so always reason from the relevant kernel’s
documented API, not only the literal word “spin.”
Advanced introduction - 4 September 2026
58
CPU and Memory Virtualization
Linux / Fedora study day
11.5.1 RCU in one paragraph
An RCU reader enters a read-side region, dereferences an RCU-published pointer and reads stable fields without
taking the updater’s ordinary lock. An updater prepares a replacement, publishes it with the required ordering,
removes the old object from reachability, then waits for a grace period or queues a callback before freeing the old
object. A grace period means readers that were already active have finished; readers may legitimately observe
the old or new version. RCU solves publication and lifetime, not every compound invariant.
11.6 Scheduler and memory interact
Parallel performance depends on placement at several layers:
• wakeup placement decides which CPU first sees a task;
• migration can lose warm private caches and require a different TLB context;
• affinity can improve repeatability but reduce load-balancing freedom;
• thread first-touch influences NUMA placement under the applicable memory policy and allowed-node mask;
• shared locks and atomics bounce cache lines;
• page-table changes cause cross-CPU shootdowns for a shared mm;
• cgroup CPU and memory policies constrain both scheduling and placement.
POSIX threads sharing an mm_struct avoid changing to a different address space when the CPU switches among
them. Different logical CPUs have CPU-local translation state, but the exact TLB and cache topology is
microarchitecture-dependent: SMT siblings and cores may share some structures and have private others.
Sharing an address space saves mapping structure; it does not create one global hardware execution context.
Audit of ‘threads.v0.c‘ and ‘threads.v1.c‘
threads.v0.c has a C data race despite volatile; any observed final count is not a defined probabilistic result.
threads.v1.c establishes correctness with a mutex, and volatile is then unnecessary.
Compile the first with
ThreadSanitizer to find the race, compare a mutex, a relaxed atomic fetch-add and per-thread reduction,
then explain both correctness and scaling separately.
Retrieval checkpoint 9
Give a language-level reason and a machine-level interleaving for why counter++ fails. Why can a correct
atomic counter still scale badly? What does a futex add that atomic compare-and-exchange alone cannot?
Why do preempt_disable() and local interrupt masking not protect shared data from another CPU?
12 Fedora laboratory: predict, observe, explain, alter
The laboratory is not a command checklist. Use this loop for every experiment:
1. Predict exact observable events before running anything.
2. Run while recording commands, kernel version and relevant output.
3. Explain every important line using the mechanism in this guide.
4. Alter one variable and predict the difference.
Keep a plain-text notebook. For each surprising observation, write whether the cause is at the C/libc, Linux,
ABI, or hardware layer.
12.1 Preparation and compilation
Work on copies of the course files in a separate study directory. If packages are missing:
sudo dnf install gcc gdb strace binutils procps-ng util-linux \
perf sysstat time valgrind libcap numactl
Package names and availability can differ across Fedora releases. Skip a missing optional observer; do not
disable SELinux, Yama, perf_event_paranoid, kernel lockdown or BPF restrictions to make an exercise work.
Start with warnings and debug information:
mkdir -p build
Advanced introduction - 4 September 2026
59
CPU and Memory Virtualization
Linux / Fedora study day
for src in p1.c p2.c p3.c zombie.c prog1.c prog2.c; do
gcc -std=gnu17 -Og -g3 -fno-omit-frame-pointer \
-Wall -Wextra -Wpedantic "$src" -o "build/${src%.c}"
done
gcc -std=gnu17 -Og -g3 -fno-omit-frame-pointer \
-Wall -Wextra -Wpedantic -pthread threads.v0.c -o build/threads-v0
gcc -std=gnu17 -Og -g3 -fno-omit-frame-pointer \
-Wall -Wextra -Wpedantic -pthread threads.v1.c -o build/threads-v1
gcc -std=gnu17 -Og -g3 -fno-omit-frame-pointer \
-Wall -Wextra -Wpedantic cpu.c -o build/cpu
gnu17 makes POSIX/GNU declarations such as strdup visible under glibc’s normal feature profile.
If practising
strict -std=c17, use an appropriate feature-test macro for POSIX interfaces. Warnings about unused arguments
and %p are teaching signals, not reasons to remove warning flags.
Known defects in the supplied examples
• common.h computes tv_sec + tv_sec/1e6; the fractional term should use tv_usec. Prefer clock_gettime(
CLOCK_MONOTONIC) for elapsed time.
• Its __common_h__ name is reserved to the implementation, function definitions in a header need careful
linkage, and pthread functions return error numbers directly rather than setting errno in the usual way.
assert also vanishes under NDEBUG.
• p1.c-p3.c use int where POSIX specifies pid_t, and wait() returns the reaped PID, not the child’s status.
Production code should retain the child PID, call waitpid, retry EINTR, and decode the separate status
word.
• p3.c should report execvp failure with perror and use _exit(127) in the child. Its string duplication is
unnecessary, and wc p3.c succeeds only when the current directory contains that file.
• p1.c and p2.c can duplicate a pre-fork stdio buffer when stdout is redirected; a newline is not guaranteed
to flush a block-buffered file stream. In p3.c, a successful exec discards the child’s copied libc buffer, so
duplication occurs only if exec fails and the child later performs normal libc termination.
• zombie.c does not handle fork failure. Its zombie may also be suppressed if inherited SIGCHLD handling
requests automatic reaping, and sleep is only an observation window, not synchronisation.
• prog1.c and prog2.c should pass (void *)x/(void *)y to %p.
• Both thread examples parse with atoi and use signed counters, so malformed, negative or overflowing
inputs are not handled. Prefer strtoull/strtol with end-pointer and range checks, use a sufficiently wide
unsigned counter, and destroy the mutex after all joins.
• cpu.c performs terminal I/O and uses the flawed timer, so it is a demonstration rather than a scheduler
benchmark.
12.2 Lab 1 - program image, process, and address space
Predict: list the mappings you expect before looking: main executable, dynamic linker, libc, heap, stack,
vDSO/vvar. Which should be executable? Which are private?
readelf -hW build/prog1
readelf -lW build/prog1
build/prog1 & p1=$!
build/prog2 & p2=$!
ps -o pid,ppid,stat,vsz,rss,comm -p "$p1,$p2"
cat /proc/$p1/maps
grep -E '^(Rss|Pss|Private|Shared|Anonymous|AnonHugePages)' \
/proc/$p1/smaps_rollup
pmap -x "$p1"
kill "$p1" "$p2"
wait "$p1" "$p2" 2>/dev/null || true
Explain why the printed pointers are virtual addresses, why the programs can use the same numeric pointer
without sharing the integer, why ASLR may make them different, and why VSZ is not RAM consumption.
Now observe the loader and allocator-facing syscalls:
Advanced introduction - 4 September 2026
60
CPU and Memory Virtualization
Linux / Fedora study day
timeout 2s strace -f -ttT \
-e trace=execve,brk,mmap,mprotect,munmap \
build/prog1
The timeout signal ends the program blocked in pause. Relate each mapping permission to an ELF PT_LOAD, loader
hardening, stack, heap or shared object. Notice that many allocations can occur within existing arenas without
one syscall per malloc.
12.3 Lab 2 - fork, wait, exec, and a zombie
Before each command, write the allowed output orders. Then trace the process tree:
strace -ff -ttT -o /tmp/p1.trace \
-e trace=clone,clone3,fork,vfork,wait4,waitid,execve,exit,exit_group \
build/p1
strace -ff -ttT -o /tmp/p2.trace \
-e trace=clone,clone3,fork,vfork,wait4,waitid,execve,exit,exit_group \
build/p2
strace -ff -ttT -o /tmp/p3.trace \
-e trace=clone,clone3,fork,vfork,wait4,waitid,execve,exit,exit_group \
build/p3
less /tmp/p3.trace.*
Your explanation must include:
• why the raw syscall name may be clone/clone3 rather than the C wrapper name;
• why parent and child return different fork values;
• why wait changes termination order but does not make all execution deterministic;
• why the PID survives the child’s successful execve;
• why code after successful execvp is unreachable.
Test the stdio-buffer prediction:
build/p1
build/p1 > /tmp/p1.out
cat /tmp/p1.out
If the pre-fork line appears twice after redirection, explain it as a duplicated userspace buffer, not two executions
before fork. Compare fflush(NULL) before fork, unbuffered output, and child _exit behavior.
Observe a zombie without leaving one around:
build/zombie & parent=$!
sleep 0.2
ps -o pid,ppid,stat,wchan:24,cmd --ppid "$parent"
wait "$parent"
A Z task has no executing program/address space. The kernel retains exit identity and accounting until a
parent/subreaper collects it.
12.4 Lab 3 - a syscall entry without mythology
First build a probe that definitely requests all three operations:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void)
{
struct timespec ts;
pid_t pid = getpid();
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
return 1;
Advanced introduction - 4 September 2026
61
CPU and Memory Virtualization
Linux / Fedora study day
printf("pid=%ld time=%ld.%09ld\n", (long)pid,
(long)ts.tv_sec, ts.tv_nsec);
}
gcc -std=gnu17 -Og -g3 -Wall -Wextra -Wpedantic entry-probe.c -o build/entry-probe
strace -ttT -e trace=getpid,write,clock_gettime build/entry-probe
Many time calls use the vDSO, a kernel-supplied userspace helper that reads safely maintained data without
syscall. The probe must call clock_gettime before its absence from the trace is evidence of a vDSO path. getpid
and the eventual stdio flush should still expose controlled kernel entries on an ordinary run.
Use GDB on the probe or build/p1:
gdb -q build/entry-probe
At the GDB prompt:
set disassembly-flavor intel
catch syscall getpid
run
info registers rax rdi rsi rdx r10 r8 r9 rcx r11 rsp rip
x/8i $rip-12
continue
Depending on where GDB stops and how libc/vDSO is used, the register snapshot may be before entry or
after return. Interpret it using the x86-64 syscall ABI rather than assuming every visible register contains an
argument.
Then answer from memory:
What changes in hardware at SYSCALL?
What does Linux still have to save/switch?
Where are user RIP, flags and RSP represented?
What makes the kernel stack safe to use?
What checks can delay return?
Why might IRETQ be required instead of SYSRETQ?
12.5 Lab 4 - threads are independently scheduled tasks
Run a long enough thread program and inspect its task directory in another terminal:
build/threads-v1 100000000 & pid=$!
ls /proc/$pid/task
ps -T -p "$pid" -o pid,spid,psr,stat,class,pri,ni,wchan:24,comm
top -H -p "$pid"
for tid in /proc/$pid/task/*; do
grep -E '^(Name|State|Tgid|Pid|Threads|Cpus_allowed_list|voluntary_ctxt_switches|nonvoluntary_ctxt_switches):' \
"$tid/status"
done
wait "$pid"
Every directory under /proc/$pid/task corresponds to one kernel TID. All pthreads report the same TGID/getpid.
psr is current or most recent CPU, not permanent affinity.
Observe creation, joining and mutex contention without printing a million-event trace to the terminal. Start
with a bounded summary; use a much smaller detailed run only if needed:
summary="/tmp/os-thread-summary.$$.txt"
strace -f -c -o "$summary" \
-e trace=clone,clone3,futex,exit,exit_group \
build/threads-v1 100000
cat "$summary"
Advanced introduction - 4 September 2026
62
CPU and Memory Virtualization
Linux / Fedora study day
trace_dir=$(mktemp -d /tmp/os-thread-trace.XXXXXX)
strace -ff -ttT -o "$trace_dir/trace" \
-e trace=clone,clone3,futex,exit,exit_group \
build/threads-v1 1000
Explain the sharing flags conceptually: address space, file table, filesystem state, signal dispositions and threadgroup relationship are shared, while each task keeps registers, stacks, TLS, TID, signal mask and scheduling
state.
12.6 Lab 5 - scheduling and migration
First inspect rather than changing policy:
uname -r
lscpu -e=CPU,NODE,SOCKET,CORE,ONLINE
ps -eLo pid,tid,tgid,ppid,psr,stat,cls,rtprio,pri,ni,pcpu,comm \
--sort=pid,tid | less
perf stat \
-e task-clock,context-switches,cpu-migrations,page-faults,cycles,instructions \
build/threads-v1 5000000
Repeat with an allowed CPU mask:
taskset -c 0 build/threads-v1 5000000
taskset -c 0,1 build/threads-v1 5000000
Use CPU numbers that exist and are permitted by your cgroup. Predict how one CPU versus two changes
possible parallelism, mutex contention, migrations and elapsed time. Results can be counterintuitive because
the globally contended lock may dominate.
If permitted, perf sched record -- COMMAND followed by perf sched timehist shows wakeups and switches. A safe fallback
is:
pidstat -t -u -w -p ALL 1
cat /proc/interrupts
cat /proc/softirqs
For a concrete per-TID snapshot, launch a fresh run and inspect it before waiting:
build/threads-v1 100000000 & pid=$!
for status in /proc/$pid/task/*/status; do
grep -E '^(Pid|Tgid|voluntary_ctxt_switches|nonvoluntary_ctxt_switches):' "$status"
done
wait "$pid"
Names for reschedule and TLB IPIs vary by architecture. Do not use real-time scheduling policies for an
unbounded loop on a daily-driver machine.
Read switch counters per TID under /proc/$pid/task/$tid/status: the leader’s process-looking file is not a sum of
every pthread. A voluntary switch normally follows an operation that blocks or yields; a nonvoluntary switch
records preemption. Neither counter alone identifies why the next task won, so correlate with sched_switch/perf
sched when available. Also keep Linux’s SCHED_IDLE userspace policy separate from the special per-CPU idle task
that runs only when nothing else is runnable.
12.7 Lab 6 - demand paging
Write a small C program that maps at most 256 MiB of private anonymous memory, requests MADV_NOHUGEPAGE,
then writes one byte per base page. On a small VM/container, reduce this to a safe fraction of both MemAvailable
and current cgroup headroom. Measure ru_minflt/ru_majflt before and after the write loop with getrusage.
Core operations:
size_t n = 256UL * 1024 * 1024;
unsigned char *p = mmap(NULL, n, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
Advanced introduction - 4 September 2026
63
CPU and Memory Virtualization
Linux / Fedora study day
if (p == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); }
if (madvise(p, n, MADV_NOHUGEPAGE) == -1) {
perror("madvise");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < n; i += 4096)
p[i] = 1;
Do not hard-code 4096 in a reusable version; obtain the runtime page size with sysconf(_SC_PAGESIZE). The constant
is explicit here so you predict roughly 65,536 first-write faults. Noise from startup, allocator and kernel policy
means the count need not match exactly.
Run:
/usr/bin/time -v build/demand-fault
perf stat -e page-faults,minor-faults,major-faults build/demand-fault
Compare time to create the mapping with time to touch it. Then parameterise the advice so the same binary
can select no advice, MADV_NOHUGEPAGE, or MADV_HUGEPAGE, checking each return. Lab M2 performs the careful THP
comparison; AnonHugePages alone reports PMD-sized anonymous THP, not every possible mTHP allocation.
12.8 Lab 7 - construct and measure copy-on-write
Build this probe yourself as a C refresher:
1. map at most 128 MiB private anonymous memory, scaled down if host/cgroup headroom is limited, and
check the request for base pages;
2. parent writes one byte per page;
3. print parent PID and pause for inspection;
4. call fork and keep both tasks alive;
5. inspect smaps_rollup for parent and child;
6. child writes one byte per page, parent does not;
7. inspect PSS, Private_Dirty, RSS and minor faults again;
8. use waitpid and decode the child’s status.
Predictions:
• RSS does not need to double immediately at fork;
• shared COW pages contribute fractionally to PSS;
• child writes create minor protection faults and private pages;
• parent bytes remain unchanged;
• a MAP_SHARED mapping would have different write semantics.
Use pipes or signals to coordinate inspection points rather than arbitrary sleeps once the first version works. Do
not attempt to read physical frame numbers as an unprivileged proof: /proc/pagemap deliberately restricts PFN
exposure.
12.9 Lab 8 - race, mutex, atomic, reduction
First let a dynamic analyser establish the language-level defect:
gcc -std=gnu17 -O1 -g -fno-omit-frame-pointer -fsanitize=thread \
-pthread threads.v0.c -o build/threads-v0-tsan
build/threads-v0-tsan 1000000
If the Fedora toolchain/runtime cannot run ThreadSanitizer in your environment, use Valgrind Helgrind as a
slower fallback. Do not treat a run that happened to print the expected total as evidence of correctness.
Implement four variants with the same number of threads/iterations:
1. supplied racy volatile counter;
2. supplied mutex counter;
3. _Atomic uint64_t relaxed fetch-add;
4. one counter per thread plus reduction after joins.
Advanced introduction - 4 September 2026
64
CPU and Memory Virtualization
Linux / Fedora study day
For each, record correctness, wall time, CPU time, context switches, migrations and cache misses:
perf stat -r 5 \
-e task-clock,context-switches,cpu-migrations,cycles,instructions,cache-misses \
build/VARIANT ITERATIONS
The supplied programs hard-code two pthreads. First generalise each variant to accept a checked thread count,
then scale from one to the number of physical cores and later logical CPUs. The conclusion should distinguish:
• undefined behavior versus defined behavior;
• atomicity versus ordering;
• sleeping contention versus spinning/locked operations;
• cache-line ownership bottleneck versus parallel local accumulation;
• false sharing versus true sharing.
12.10 Lab 9 - steady-state translation locality
Build a benchmark that allocates and first-touches a large array, constructs a random permutation of page
indices, then reads one word from each selected page repeatedly. Keep the first-touch faults outside the timed
region. Sweep the number of pages across increasingly large working sets.
perf list | grep -i tlb | head -40
perf stat -r 5 \
-e cycles,instructions,page-faults,dTLB-loads,dTLB-load-misses \
build/tlb-walk PAGES
PMU event names and access vary by CPU. If they are unavailable, report elapsed cycles/time while keeping
method and affinity fixed. Compare sequential byte access, one word per page, random page order, and THP
advice. These cases are comparative rather than perfectly isolated: the random index stream and touched data
still affect caches. Keep first-touch faults outside the timed interval and correlate dTLB/page-walk events with
cache events before attributing a difference to TLB reach.
12.11 Advanced Fedora memory laboratories - stretch track
These exercises are a menu for a second session or for replacing a familiar basic lab; implementing all five does
not fit the final 50-minute laboratory block of the one-day schedule. Keep every allocation and loop bounded
on your daily-driver system.
12.11.1 Lab M1 - observe page-fault causes, not only counts
Extend the demand-paging probe so each dangerous case runs in a separate child process and the parent decodes
waitpid status:
1. first write to untouched private anonymous RW memory;
2. write after the page is present and mprotect(..., PROT_READ) has removed write permission;
3. read after munmap;
4. optional instruction fetch from a present NX page, using a deliberately controlled test function/mapping;
5. on x86-64 only, access a deliberately noncanonical value in a disposable child.
Before running, predict #PF low bits for cases 1-4 and predict #GP, not #PF, for case 5. The simplest design installs
no handler: let each child terminate and have the parent use WIFSIGNALED/WTERMSIG. If you add SA_SIGINFO, the handler
may copy minimal si_code/si_addr data to a pre-created pipe using only async-signal-safe operations, then restore
the default disposition and re-raise the signal. Merely returning would retry the same faulting instruction and
loop; calling _exit would instead make waitpid report normal exit, not WIFSIGNALED. Do not assume siginfo_t exposes
the raw x86 error code.
If your kernel exposes the tracepoint, inspect its fields before using it:
sudo cat /sys/kernel/tracing/events/exceptions/page_fault_user/format
perf list 'exceptions:*page_fault*'
Use trace-cmd, perf, or bpftrace only after adapting field names to that format file. A safe fallback is perf stat
-e page-faults,minor-faults,major-faults plus the child’s signal result. Explain why the aggregate counters cannot
distinguish COW from an invalid write by themselves.
Advanced introduction - 4 September 2026
65
CPU and Memory Virtualization
Linux / Fedora study day
12.11.2 Lab M2 - distinguish PMD THP, mTHP, and base pages
First inventory what this boot supports:
getconf PAGE_SIZE
cat /sys/kernel/mm/transparent_hugepage/enabled
cat /sys/kernel/mm/transparent_hugepage/hpage_pmd_size
for d in /sys/kernel/mm/transparent_hugepage/hugepages-*kB; do
[ -d "$d" ] || continue
printf '%s: ' "${d##*/}"
cat "$d/enabled" 2>/dev/null || true
done
grep -E '^thp_' /proc/vmstat
Parameterise the demand-fault program so one argument selects no advice, MADV_NOHUGEPAGE, or MADV_HUGEPAGE; do
not leave the Lab 6 hard-coded advice in place, and fail clearly if a requested madvise fails. Keep the process alive
briefly after first touch. Have it print the mapping start and length and, where supported, name the anonymous
VMA with prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ...) so you can select that one block from /proc/$pid/smaps rather
than grepping every VMA.
awk '/\[anon:os-thp-lab\]/{show=1; print; next}
show && /^(Size|Rss|Pss|AnonHugePages|KernelPageSize|MMUPageSize|THPeligible|VmFlags):/{print}
show && /^VmFlags:/{exit}' /proc/$pid/smaps
If anonymous VMA naming is unsupported, use the printed start/end address to select the corresponding smaps
block manually. Do not substitute an unscoped grep over the entire process.
Snapshot /proc/vmstat and each available per-size stats/ directory before and after. System-wide counters contain
noise, so repeat under similar idle conditions and treat small differences cautiously. Your report must answer:
• Did AnonHugePages prove a PMD mapping existed?
• Could mTHP have been used without appearing there?
• Did fewer minor faults come from fault granularity, TLB behavior, or both?
• Would a TLB hit care how many table levels exist?
12.11.3 Lab M3 - make a TLB shootdown observable
Write a two-thread program sharing one page-aligned mapping. Materialise a private page with an initial write,
change it to PROT_READ, then start the measured phase. Pin the reader to one allowed CPU and the controller to a
different physical core. Make the reader perform a bounded number of loads through a volatile unsigned char * and
accumulate/print a checksum so the compiler cannot hoist or remove the accesses; inspect the loop’s disassembly.
Make the controller perform a fixed, moderate number of alternations between PROT_READ and PROT_READ | PROT_WRITE
. Both states permit the reader’s load, so the experiment should not intentionally crash. Use atomics or a
mutex for startup/shutdown coordination so the benchmark itself has no C data race, and reject any failed
mprotect/affinity call.
Discover available events rather than hard-coding one kernel’s names:
perf list 'tlb:*'
sudo find /sys/kernel/tracing/events -maxdepth 2 -type d -iname '*tlb*' -print
Compare four cases: no mprotect, protection changes with both threads on one CPU, changes across two physical
cores, and changes across SMT siblings if the topology allows it. Record syscall count, elapsed time, and
any available TLB flush/IPI trace data. This does not measure a pure IPI latency; it measures VMA/PTE
locking, permission update, invalidation batching, syscall entry, and scheduling together. That is the point of
the explanation.
12.11.4 Lab M4 - bounded cgroup-v2 pressure
Reuse the parameterised demand-fault program from Lab 6. A cgroup limit is not a RAM reservation: an
ancestor limit, low host headroom, or systemd-oomd can still terminate work. First require comfortable MemAvailable,
inspect the effective ancestor limits below, and scale the allocation well below both host and cgroup headroom.
Skip the lab on an already pressured machine. Then start a transient user scope with a soft boundary and a
hard ceiling above the bounded plan:
Advanced introduction - 4 September 2026
66
CPU and Memory Virtualization
Linux / Fedora study day
systemd-run --user --scope --unit=os-memlab.scope \
-p MemoryHigh=128M -p MemoryMax=512M bash
Inside that shell, locate its own cgroup and take a baseline:
rel=$(awk -F: '$1 == "0" {print $3}' /proc/self/cgroup)
cg="/sys/fs/cgroup${rel}"
cat "$cg/memory.current"
cat "$cg/memory.events"
cat "$cg/memory.pressure"
grep -E '^(anon|file|slab|pgfault|pgmajfault|workingset_refault)' \
"$cg/memory.stat"
probe=$cg
while :; do
printf '%s current=' "$probe"; cat "$probe/memory.current"
printf '%s max=' "$probe"; cat "$probe/memory.max"
[ "$probe" = /sys/fs/cgroup ] && break
probe=${probe%/*}; [ -n "$probe" ] || probe=/sys/fs/cgroup
done
Parameterise a bounded pause, run the probe in the background, inspect it from the same shell, then wait for
it and read the files again:
build/demand-fault --bytes 256M --pause 10 & work=$!
cat "$cg/memory.current"
cat "$cg/memory.events"
cat "$cg/memory.pressure"
wait "$work"
Use a smaller --bytes value if the preflight requires it. Interpret rather than merely list changes:
• memory.current should rise during the resident phase and fall after exit;
• memory.events high can increase when tasks are throttled into reclaim above memory.high;
• memory.pressure measures stall time, not allocation size;
• memory.stat separates anonymous charge, faults, reclaim, and refault signals;
• the workload may use swap/zram or may be unable to reclaim much anonymous memory, depending on the
host.
Do not lower MemoryMax below the known bounded workload to provoke an OOM, and remember that the ceiling
cannot guarantee host safety. If the user manager rejects memory-controller properties, record the limitation
and use an instructor-provided delegated cgroup rather than changing the host-wide configuration.
12.11.5 Lab M5 - NUMA first touch, policy, and remoteness
This lab needs at least two memory nodes that your effective cpuset permits:
lscpu -e=CPU,CORE,SOCKET,NODE,ONLINE
numactl --hardware
numactl --show
Make an inspection build of the demand-fault probe that pauses for 15 seconds after touching its array. Run it
on one allowed CPU node and inspect placement while it sleeps:
numactl --cpunodebind=NODE_A \
build/demand-fault-inspect &
pid=$!
numastat -p "$pid"
grep -E 'anon|heap' "/proc/$pid/numa_maps"
wait "$pid"
This first run leaves memory policy at its default so the first-touch prediction is testable. Repeat once with
--membind=NODE_B to show that an explicit VMA/task policy can override local first touch.
Then use the steady-state build/tlb-walk array scanner from Lab 9. First hold the CPU node fixed and change
only the memory node; then run the reciprocal pair to reveal topology asymmetry:
Advanced introduction - 4 September 2026
67
CPU and Memory Virtualization
Linux / Fedora study day
numactl --cpunodebind=NODE_A --membind=NODE_A build/tlb-walk ARGS
numactl --cpunodebind=NODE_A --membind=NODE_B build/tlb-walk ARGS
numactl --cpunodebind=NODE_B --membind=NODE_B build/tlb-walk ARGS
numactl --cpunodebind=NODE_B --membind=NODE_A build/tlb-walk ARGS
Choose real node numbers from numactl --hardware; do not paste the placeholders. Keep page size, array size,
traversal, compiler options, and iteration count identical. First-touch before the timed loop, inspect numastat
-p, and repeat. Compare A/A with A/B to isolate locality while holding the executing node fixed; B/B and
B/A form the reciprocal check. In these explicitly bound cases, the CPU and memory masks are intended to
prevent automatic balancing from moving the workload to the other node. Verify masks and placement rather
than assuming the command succeeded. To observe automatic NUMA balancing itself, run a separate longer
default-policy case without strict binding and inspect placement before and after.
Finally compare serial master-thread initialization with parallel initialization in which each worker first-touches
the range it later scans. The prediction is about physical placement, not about the virtual addresses: every
thread shares the same mapping either way.
If the machine has one NUMA node, do not fabricate a performance conclusion. Complete the policy/placement
derivation, inspect /proc/self/numa_maps, and reserve the latency comparison for a multi-node server.
Retrieval checkpoint: the complete memory path
A worker on CPU 9 writes to a never-touched anonymous address while its cgroup is above memory.high.
Trace the possible path from TLB miss through page fault, VMA lookup, memcg charge, NUMA policy,
per-CPU or buddy allocation, PTE installation, invalidation, direct-reclaim stall, and retry. Which steps
are mandatory, which depend on existing state, and which can make the task sleep or migrate?
13 Capstone trace: one command through the whole system
Use this capstone after the individual labs. In a shell, run a dynamically linked program that creates two
pthreads, touches anonymous memory, writes a line, then exits. Tell the story below without skipping layers.
13.1 Shell and process creation
The shell parses the command. For an external foreground command it creates a child (often via fork/clone
-related machinery or a spawn path), prepares redirections and process-group state, then executes the new
image. The parent shell waits without consuming a CPU while blocked.
13.2 Executable image and lazy mappings
execve validates the ELF, replaces the child’s mm_struct, maps program segments/interpreter, creates an initial
stack and vDSO mapping, then returns to userspace at the loader. The loader maps libraries and applies
relocations. Most pages arrive on demand through minor or major faults.
13.3 Thread creation and scheduling
glibc allocates each pthread’s stack/TLS metadata and creates a Linux task sharing the mm, file table and thread
group. The new task becomes runnable on a selected per-CPU runqueue. It may execute simultaneously with
its creator on another logical CPU.
13.4 Memory access and faults
Each load/store generates a virtual address. A TLB hit supplies the translation directly. A valid TLB miss
triggers a hardware walk. First writes to untouched anonymous pages fault; Linux validates the VMA, obtains
zeroed physical memory, installs PTEs, returns, and the instruction retries.
13.5 Synchronisation and coherence
If workers update one mutex-protected queue, the uncontended path is userspace atomic state; contention can
sleep via futex. Mutex acquire/release gives the language happens-before relation. Hardware coherence transfers
ownership of modified lines, while Linux schedules blocked/woken tasks.
Advanced introduction - 4 September 2026
68
CPU and Memory Virtualization
Linux / Fedora study day
13.6 Output syscall
libc may buffer output. Eventually write places the syscall number/arguments in ABI registers and executes
syscall. Hardware enters CPL0 at the fixed entry point; Linux establishes GS, page-table and kernel-stack state,
builds pt_regs, performs tracing/security/file-descriptor checks, and calls the filesystem/terminal path. The call
may block.
13.7 Preemption and context switch
An interrupt, wakeup, blocking point or kernel preemption check can make another task run. Linux saves the
outgoing execution context on/through its kernel stack and task_struct, chooses from the local runqueue, switches
architecture and possibly memory context, then restores the next task. No userspace address space is copied
merely to switch.
13.8 Exit and collection
Each pthread eventually exits. Linux’s clear child TID and futex mechanisms support joins. Group exit releases
resources, tears down the address space after its users vanish, and leaves process exit status for the parent. The
shell’s wait returns, reaps the zombie record and displays the next prompt.
Capstone teach-back
Now replace the program with p3.c. Identify exactly which parts occur in the parent shell, original p3, child
before execvp, wc, and waiting parent. For every transition, name the current task, current address space,
current CPU privilege level, and whether a context switch is required, merely possible, or impossible.
Advanced introduction - 4 September 2026
69
CPU and Memory Virtualization
Linux / Fedora study day
14 Closed-notes mastery test
Allow 75 minutes, then 30 minutes to mark and repair. Do not use the preceding pages while answering. A
strong answer gives the causal chain and separates architecture, kernel implementation and userspace API.
14.1 Part A - compact explanations
1. Define program, process, thread, Linux task, hardware thread and kernel thread. Which entity does Linux
schedule?
2. A process has three pthreads. State at least five resources they normally share and five states each thread
keeps independently. Relate getpid, gettid, TGID and TID.
3. Why is the statement “a syscall elevates the process to root” false twice over?
4. Contrast a function call, syscall, CPU exception, hardware interrupt, signal, privilege-level transition and
context switch. Which pairs can occur without one another?
5. Trace native x86-64 write(fd, buf, n) from a libc wrapper to the first kernel C dispatcher. Name the key
registers and state that hardware does and does not save.
6. Why must the early syscall path treat user RSP, register arguments and pointers as hostile even though
execution is already at CPL0?
7. Give three reasons a syscall exit may use iretq rather than the fastest sysretq path.
8. Explain how a timer interrupt helps retain control but does not imply an immediate task switch.
9. What must conceptually change on a context switch between processes? Which parts can be avoided or
reduced when switching between pthreads that share an mm_struct?
10. Why does fork() return twice with different values? Why can the child see the same initial bytes without
eager copying?
11. What does a zombie retain, and what has already disappeared? Contrast waitpid with pthread_join.
12. Why can execve preserve a PID yet destroy every old userspace return address? Name four other effects of
execve.
13. Explain effective UID, capabilities, a user namespace and an SELinux decision as separate layers. What
does sudo arrange before execve?
14. Why are MOV CR3, arbitrary port I/O and changing interrupt-control state privileged, while syscall is
intentionally executable in user mode?
15. Why is the course’s 32-bit int 0x80 quick reference not a native syscall table for Fedora x86-64 or a Raspberry
Pi running AArch64?
14.2 Part B - scheduling and concurrency
16. For A=(arrival 0, burst 6), B=(1,2), C=(3,1), draw FIFO, nonpreemptive SJF, STCF and round-robin
(quantum 2) timelines. Compute each task’s response and turnaround time.
17. Explain why a per-CPU runqueue improves scaling but creates load-balancing, migration and remote-wakeup
problems. What does a reschedule IPI accomplish?
18. State the ordinary Linux scheduling-class order. Why is modern fair scheduling not simply SJF or fixedquantum round robin? What are lag and virtual deadline trying to represent in EEVDF?
19. Give both the formal C reason and a concrete load/add/store interleaving for the failure of volatile counter++.
20. Compare mutex, relaxed atomic fetch-add and per-thread reduction for the counter. Discuss correctness,
ordering, syscalls and cache-line movement.
21. What race does the futex compare-and-sleep operation prevent? Why might an uncontended pthread mutex
produce no syscall?
22. Distinguish cache coherence, hardware memory consistency and the C memory model. Why does MESI-like
coherence not create a C happens-before relation?
Advanced introduction - 4 September 2026
70
CPU and Memory Virtualization
Linux / Fedora study day
23. A kernel developer disables local interrupts and updates a shared list without a lock. Why is this unsafe on
SMP? When would an IRQ-safe spinlock be relevant?
24. Explain the RCU update sequence and the meaning of a grace period. What does RCU not automatically
serialise?
14.3 Part C - address translation and virtual memory
25. Derive the size of a flat page table for a 48-bit virtual address, 4 KiB pages and 8-byte entries. Why do
multiple levels reduce allocated metadata for sparse spaces?
26. Split 0x00007f1234567abc into the four 9-bit indices and 12-bit offset. If the leaf frame base is 0x00000000abcdf000,
give the final physical address.
27. Describe how present, user/supervisor, read/write and NX permissions combine during a multi-level x86-64
walk. Why can a VMA display rw-p while its current PTE is read-only?
28. Distinguish a TLB hit, a valid TLB miss, a minor page fault and a major page fault. Which normally
execute kernel code?
29. Under the toy assumptions 1 ns TLB lookup, 80 ns memory, 99% TLB hit rate and a cold four-level walk,
calculate effective access time. State why the number is not a real CPU prediction.
30. What is a PCID? Why can PCIDs reduce flushing but not eliminate TLB shootdowns? Construct the
security failure possible if a stale writable TLB entry survives page reuse.
31. Explain the three-layer state for an untouched anonymous mapping: VMA, PTE and physical backing. Now
trace its first write.
32. Parent and child share a private page after fork. Trace the child’s first write. What changes if the mapping
was MAP_SHARED?
33. Compare anonymous-private, file-private and file-shared mappings. Explain the page cache and why visibility
is not identical to durability.
34. Distinguish reclaim, writeback, swap and compaction. Why is a clean file page normally easier to reclaim
than dirty anonymous data?
35. Give two benefits and three costs of transparent huge pages. How could THP confuse a simple page-fault
or COW experiment?
36. Explain first-touch NUMA placement. Why can pinning worker threads make performance worse if the
pages were initialised elsewhere?
37. Describe the path from user malloc to a resident frame and separately the path from kernel kmalloc to storage.
Where do buddy and SLUB fit?
38. Explain ASLR, NX, W^X, SMEP, SMAP and KPTI without claiming that any one of them is a complete
security boundary.
14.4 Part D - synthesis
39. A thread calls read on an empty pipe, another process writes later, and the reader resumes on a different
CPU. Trace privilege transitions, task states, wait queues, scheduling, migration, cache/TLB effects and
syscall return.
40. A multithreaded process calls fork, and the child calls printf then malloc before execve. Identify the correctness
hazards and give a safer design.
41. strace shows clone3, futex, mmap, mprotect, write, and exit_group. For each, give one plausible higher-level action
and one reason the mapping is not necessarily one-to-one.
42. You observe high CPU time, few context switches, many dTLB misses and almost no page faults. What class
of bottleneck is plausible? What experiment separates TLB reach from cache locality and fault startup?
Advanced introduction - 4 September 2026
71
CPU and Memory Virtualization
Linux / Fedora study day
14.5 Part E - the deeper mechanisms
43. Contrast x86-64 SYSCALL entry with a CPL-3 page fault. Name the initial stack, hardware-saved fields, source
of the handler address, location of the fault address, and the role of TSS.RSP0 and IST.
44. Trace a caught process-directed signal in a multithreaded program from generation to rt_sigreturn. Why does
the handler remain at CPL 3, what lives in rt_sigframe, and what must the kernel validate? Include syscall
restart versus EINTR and partial success.
45. Explain how glibc/NPTL turns pthread_create into a new Linux task. Include the stack mapping, guard,
TLS/FS base, representative clone flags, clear-child-TID/futex join, detached lifetime, and the difference
among worker return, raw SYS_exit, and exit_group.
46. Explain why Linux credentials are immutable/versioned objects and why NPTL coordinates set-ID changes.
Then trace a privileged exec and a permanent privilege drop, including saved IDs, capability sets, no_new_privs,
AT_SECURE, open descriptors and SELinux.
47. For 0x00007f1234567abc, compute the offsets used by a 2 MiB PMD leaf and a 1 GiB PUD leaf. Decode low
page-fault error values 0x4, 0x6, 0x7, and 0x15. Why can COW and an illegal write have the same hardware
pattern, and why does a noncanonical address normally not cause #PF?
48. Thread A calls mprotect on a mapping while thread B uses the shared mm on another CPU. Trace VMA
splitting/locking, PTE update, translation invalidation and application-level lifetime synchronisation. Then
explain how node-by-memcg reclaim, direct reclaim, PMD THP, PTE-mapped mTHP and HugeTLB alter
the surrounding memory behavior.
14.6 Scoring
Give each question 0, 1 or 2:
• 0: absent, contradicted, or only a memorised name;
• 1: correct core idea but missing a necessary layer or causal step;
• 2: technically correct chain with layer distinctions and a relevant consequence.
Total: 96. Aim for 77 (80%) or higher. Any zero is a repair topic even if the total passes.
Advanced introduction - 4 September 2026
72
CPU and Memory Virtualization
Linux / Fedora study day
15 Answer key and worked derivations
Use this after attempting the test. These are marking anchors, not the only acceptable wording.
15.1 Answers 1-15: execution and privilege
1. A program is executable code/data representation; a process is an executing resource context/thread group;
a thread is one execution stream; a Linux task is one task_struct schedulable entity; a hardware thread is
one logical CPU execution context; a kernel thread is a task with no ordinary userspace mm. Linux schedules
tasks.
2. Pthreads normally share the mm, file-descriptor table, cwd/root/umask state, signal dispositions and
thread-group/process-wide signal state. Each has registers/IP, user stack, kernel stack, TLS, TID, signal
mask/pending thread signals, affinity and scheduling state. All normally share TGID/getpid; each has a
TID/gettid; leader TID equals TGID. pthread_t is opaque.
3. A syscall changes CPU execution privilege to CPL0 only for controlled kernel code; it does not change
credentials. Root/effective UID is itself only one authorisation input alongside capabilities, namespaces and
LSM policy.
4. A function call is same-address-space control transfer. A syscall is synchronous requested kernel entry. An
exception is synchronous to an instruction; an interrupt is asynchronous external/local event. A signal is a
kernel-delivered userspace event. A privilege transition changes CPU mode. A context switch changes the
scheduled task. A syscall or interrupt can return to the same task; a context switch can happen after either;
a function call needs neither.
5. Native x86-64: number in RAX; args in RDI,RSI,RDX,R10,R8,R9; result in RAX. syscall puts return RIP in RCX, flags
in R11, loads entry RIP/selectors from privileged state and masks flags. It does not switch RSP, CR3, GS, save
all GPRs or push a full frame. Linux assembly performs swapgs, preserves user RSP, handles KPTI, switches
to the task kernel stack, builds pt_regs, then dispatches.
6. CPL0 grants instruction authority, not data trust. User-controlled stack/register values can point anywhere,
be noncanonical, race with another thread, cross unmapped pages or violate permissions. Early code
must establish kernel-owned stack/per-CPU/page-table context before C code and use safe user-copy/access
checking.
7. Examples: signal or tracing work leaves a modified state that fails fast-path checks; ptrace changed state;
unusual flags (TF/RF); unexpected segment selectors; return RIP/state fails sysretq safety constraints;
compatibility/virtualisation conditions. The mere fact that a signal/tracing hook ran is not the architectural
rule - eligibility depends on the resulting saved frame. iretq restores the return frame more generally.
8. Periodic or deadline timer events force kernel entry so a CPU-bound task cannot retain control forever. The
handler accounts time/sets reschedule intent; if the current task remains best or preemption is unsafe, it
returns without switching.
9. Save/restore architectural registers and stack context, scheduler accounting/state, kernel stack/current task,
TLS/architecture state; a different process may require changing the active mm/CR3 context and associated
translation state. Threads sharing mm can retain the address-space root/context, but still pay register, stack,
scheduler, cache and predictor effects.
10. Linux creates a child task whose copied register frame is adjusted so it sees zero; parent sees child PID.
Separate page tables/VMAs initially reference the same physical pages read-only under COW; a private
write faults and diverges.
11. A zombie retains PID relationships, exit status and resource accounting needed by the parent. Its runnable
code, ordinary address space and open runtime resources are gone. waitpid collects a child process-level
exit record; pthread_join coordinates a thread in the same process using the library/kernel clear-TID/futex
protocol.
12. PID is kernel identity, not an address-space ID. execve replaces mappings and begins at a new ELF/interpreter
entry, so the old stack/return address disappears. It also terminates sibling threads, resets caught signal
dispositions, closes FD_CLOEXEC descriptors, constructs new argv/env/auxv, applies executable credential
transitions and remaps vDSO.
Advanced introduction - 4 September 2026
73
CPU and Memory Virtualization
Linux / Fedora study day
13. Effective UID participates in discretionary checks; capabilities split privileged operations into bits; a user
namespace scopes identity/capability meaning; SELinux applies mandatory labels/policy even after DAC.
sudo authenticates/authorises according to policy, sets credentials/groups/environment/limits as configured,
then executes the target. The later target syscalls still undergo checks.
14. Those instructions can subvert isolation or kernel control, so hardware rejects them at CPL3. syscall is
safe to expose because userspace can choose only a number/arguments while hardware enters a fixed kernelcontrolled address and Linux validates the request.
15. Syscall numbers, register ABI and entry instruction are architecture/ABI-specific. Native Fedora x86-64
uses syscall and the x86-64 table; AArch64 uses registers defined by its ABI and svc. Compatibility processes
may use a historical path, which does not make it the native ABI.
15.2 Answers 16-24: scheduling and concurrency
16. With zero switch cost and new arrivals joining the tail for round robin:
Policy
Timeline
FIFO
SJF (nonpreemptive)
STCF
RR, 𝑞 = 2
A 0-6; B 6-8; C 8-9
A 0-6; C 6-7; B 7-9
A 0-1; B 1-3; C 3-4; A 4-9
A 0-2; B 2-4; A 4-6; C 6-7; A 7-9
Response A/B/C
Turnaround A/B/C
0, 5, 5
0, 6, 3
0, 0, 0
0, 1, 3
6, 7, 6
6, 8, 4
9, 2, 1
9, 3, 4
17. Local queues avoid one global lock and preserve locality. They require topology-aware balancing, choosing
a wakeup CPU and occasionally migrating work. A remote reschedule IPI causes the target CPU to enter
the kernel/check scheduling; one CPU cannot directly replace another CPU’s current stack.
18. Simplified order: stop, deadline, RT FIFO/RR, fair, idle (with optional configured classes such as sched-ext).
Fair scheduling uses weights, history, eligibility, latency goals and hierarchy rather than known future service
times or one global quantum. Lag estimates service owed relative to fair virtual time; virtual deadline orders
eligible requests for latency while preserving long-run share.
19. Formally, conflicting non-atomic accesses without a synchronising happens-before edge form a C data race,
so behavior is undefined. Concretely, both threads load 𝑛, compute 𝑛 + 1, and store 𝑛 + 1, losing one update.
volatile changes neither fact.
20. Mutex gives exclusion and release/acquire, with a userspace fast path and possible futex sleep; one lock per
increment serialises. Relaxed fetch-add atomically fixes this one counter without ordering unrelated data or
normally sleeping, but bounces a hot line. Per-thread counters plus joins/reduction avoid shared writes and
usually scale best; padding may be needed to avoid false sharing.
21. Between a waiter observing a contended word and sleeping, an unlock could occur. Futex compare-andwait atomically rechecks/enqueues so it will not sleep after the condition already changed without a wake.
Uncontended state transitions complete with userspace atomic instructions, so no kernel wait/wake is needed.
22. Coherence gives per-location ownership/order; consistency constrains cross-location observations at ISA
level; C defines compiler-visible atomicity/happens-before and declares data races undefined. Coherent
delivery of writes does not establish a language synchronisation edge or make a multi-instruction update
indivisible.
23. Local interrupt masking affects only that CPU; another CPU can still reach the list. If a lock is used by
both task context and a local hard interrupt, the task-side acquisition may need to mask/save local IRQ
state while the spinlock excludes remote CPUs and the interrupt context.
24. Initialise replacement, publish with RCU ordering, remove old reachability, wait/queue until a grace period,
then reclaim. The grace period waits for pre-existing read-side critical sections, not all future readers. RCU
does not automatically serialise concurrent updaters or arbitrary multi-object invariants.
15.3 Answers 25-38: virtual memory
25. 248−12 entries times 8 bytes is 239 bytes = 512 GiB. A missing upper entry represents a large unused interval,
so lower table pages need not exist for sparse holes.
26. Indices are 0x0fe, 0x048, 0x1a2, 0x167; offset 0xabc. Final address is 0x00000000abcdfabc.
Advanced introduction - 4 September 2026
74
CPU and Memory Virtualization
Linux / Fedora study day
27. Every traversed entry must be present; CPL3 needs user permission throughout; a write needs writable
permission throughout; execution needs NX clear throughout. A VMA records logical writability while
Linux can temporarily use a read-only PTE to trap COW, dirty tracking, NUMA sampling or similar work.
28. A hit uses cached translation. A valid miss invokes the hardware walker and normally no kernel code. A
minor page fault enters Linux but needs no storage read; a major fault enters Linux and waits for needed
I/O.
29. Hit cost 1+80 = 81 ns. Miss cost 1+4×80+80 = 401 ns. 0.99(81)+0.01(401) = 84.2 ns. Real walkers/cache
hierarchies overlap and cache paging structures, and the assumed latencies/hit rate are artificial.
30. A PCID tags translations by address-space context so CR3 changes can retain entries. It cannot validate a
translation after its PTE/permission changes, and IDs are finite/reused. If a writable entry remains after the
frame is unmapped/reallocated, the old process could overwrite another owner through its stale translation;
shootdown must complete before unsafe reuse.
31. VMA says the anonymous range is valid and writable; no private present PTE/frame is required yet; backing
semantics promise zero. First write raises a non-present fault, Linux validates the VMA, obtains and zeroes
a frame, installs a user-writable PTE, invalidates as necessary and retries.
32. The VMA/private-mapping semantics are writable, while the hardware PTE is deliberately read-only; x86
has no COW bit. The protection fault finds a private COW mapping, allocates/copies if shared (or reuses if
exclusive), installs a private writable translation and retries. MAP_SHARED writes the shared backing/page-cache
object rather than privately diverging.
33. Anonymous private begins as zero and dirty data needs anonymous/swap backing.
File private
initially shares page-cache data, then COWs dirty private pages. File shared writes dirty the page
cache and are visible to other mappings. Visibility in cache can precede writeback/durability; explicit
sync/filesystem/device semantics govern persistence.
34. Reclaim frees capacity, writeback persists dirty file cache, swap backs evicted anonymous data, and
compaction creates contiguous blocks by migration. A clean file page can be dropped and reread; dirty
anonymous bytes need backing or would be lost.
35. Benefits include greater TLB reach, fewer dependent table reads on a TLB miss for PMD/PUD leaves,
fewer table pages and fewer faults. Costs include fragmentation, compaction/collapse latency, coarse NUMA
placement, large COW/zero work and split costs. A single huge-page fault can cover many base pages, and
one write can trigger huge-page split/copy behavior, invalidating simple 4 KiB counts.
36. Frames are commonly allocated on first fault/touch under policy. If one thread initialises pages on node 0
and workers later run on node 1, pinning them can guarantee remote memory rather than locality; balance
CPU and memory placement together.
37. User path: allocator reuses/obtains virtual range through brk/mmap; VMA exists; first touch faults; page
allocator supplies a frame and PTE is installed. Kernel small object: kmalloc commonly uses a SLUB cache;
SLUB obtains pages from the buddy/per-CPU page allocator. Larger/high-order physical contiguity and
reclaim/compaction constraints apply.
38. ASLR randomises locations; NX blocks fetch; W^X is a permission policy; SMEP blocks supervisor execution
of user pages; SMAP restricts supervisor data access to them; KPTI separates most kernel mappings from
user page tables. Each reduces one attack avenue but depends on correct kernel policy/code and does not
replace authorisation/isolation.
15.4 Answers 39-42: synthesis
39. read enters CPL0 on the same task, validates fd/buffer and finds no data, enqueues the task on a pipe wait
queue, sets a sleeping state and calls the scheduler. Another task runs. A writer enters the kernel, appends
data and wakes the reader, making it runnable and choosing a CPU. When scheduled, its preserved kernel
continuation resumes, copies data safely to user memory (which can fault), completes return work, restores
user context and returns CPL3. Migration can cold-start caches; the shared or retained mm/PCID determines
TLB effects. Multiple privilege transitions occur; the context switch happens because of blocking/wakeup,
not because every syscall mandates one.
40. Only the caller survives in the child, while copied memory can contain libc allocator/stdio locks owned by
vanished threads. POSIX permits only async-signal-safe operations before exec; printf and malloc are unsafe.
Advanced introduction - 4 September 2026
75
CPU and Memory Virtualization
Linux / Fedora study day
Pre-fork stdio buffers can duplicate too. Prefer posix_spawn or fork then perform only minimal async-signal-safe
fd operations and execve; on failure use write/_exit as appropriate.
41. clone3: pthread creation or process/spawn machinery; wrappers may fall back to clone. futex: contended
mutex, condition variable or join/clear-TID; uncontended operations are invisible. mmap: loader, allocator,
thread stack or explicit mapping. mprotect: loader RELRO, JIT or app permission change. write: stdio flush
or direct I/O; buffering combines calls. exit_group: libc process exit after return main; one task can instead use
other exit paths.
42. Steady-state address-translation/locality pressure is plausible, not demand paging. First-touch outside
measurement, sweep pages/stride/order, compare base versus huge-page advice, pin consistently, record
dTLB events if available and cache misses separately. Few page faults only says pages are resident/valid,
not that translations or data fit in TLB/caches.
15.5 Answers 43-48: deeper mechanisms
43. SYSCALL obtains its entry RIP/selectors from privileged MSRs, saves return RIP in RCX and flags in R11, but
does not switch stacks or push a frame; Linux assembly establishes GS, page tables, the task stack and
pt_regs. A CPL-3 page fault selects an IDT gate, switches to the kernel stack selected through the TSS, and
pushes the architectural interrupt frame plus a page-fault error code; Linux then saves remaining registers.
CR2, not the stack frame, holds the faulting linear address. TSS.RSP0 supplies the ordinary privilege-transition
stack; an IST gate deliberately selects a dedicated stack for exceptional/nesting robustness.
44. Generation creates thread- or process-pending state; an eligible thread is selected according to masks and
dispositions during return-to-user work. Linux writes signal metadata, saved register/mask state and the
floating-point/(F)XSAVE payload into an rt_sigframe on the normal or alternate user stack, changes pt_regs
to enter the handler, then returns to CPL 3. The restorer invokes rt_sigreturn; because the frame is writable
user input, Linux validates addresses, selectors, flags and extended state before restoration. A syscall that
made progress usually returns its partial result; otherwise exit logic can expose EINTR or rewrite the context
for a documented restart, influenced by the handler and SA_RESTART.
45. glibc prepares a stack mapping/guard, thread descriptor and TLS block, then creates a task with
sharing flags such as CLONE_VM, CLONE_FILES, CLONE_FS, CLONE_SIGHAND, CLONE_THREAD, CLONE_SETTLS, CLONE_PARENT_SETTID and
CLONE_CHILD_CLEARTID. The per-task x86-64 FS base selects that pthread’s TLS even though all mappings are
shared. On exit the kernel clears the child-TID word and futex-wakes a joiner, which rechecks a predicate
before collecting the result and releasing/caching runtime resources. Detached resources are reclaimed
without join. Worker return is pthread_exit-like; raw SYS_exit ends one Linux task; libc process exit/_exit
ultimately uses group termination.
46. A task points to reference-counted credentials that readers can treat as stable; a change prepares and
commits a replacement. Linux stores them per task, so glibc coordinates POSIX set-ID changes across
pthreads. Exec computes new IDs/capability sets/LSM state from the old credentials, executable metadata,
namespace and suppression rules; AT_SECURE tells the trusted loader to scrub dangerous environment behavior.
A permanent drop must remove supplementary groups, set all real/effective/saved IDs as intended, clear
permitted/effective/inheritable/ambient and bounding routes as required, establish no_new_privs, check every
error and verify the postcondition. Already-open descriptors can retain delegated access, O_CLOEXEC prevents
accidental exec inheritance, and SELinux remains an independent decision layer.
47. The 2 MiB offset is 0x167abc; the 1 GiB offset is 0x34567abc. 0x4 is non-present user read, 0x6 non-present user
write, 0x7 present-protection user write, and 0x15 present-protection user instruction fetch. The error code
reports the MMU observation, so Linux needs VMA/PTE/backing state to distinguish deliberate read-only
COW from an illegal write. A noncanonical linear address is rejected before the paging walk and normally
raises #GP, even though Linux may translate several different exceptions into SIGSEGV for user space.
48. Linux stabilises and possibly splits the shared VMA under address-space locks, serialises page-table changes,
publishes the stricter PTE, and invalidates local plus relevant remote cached translations before relying on
the permission or reusing storage. The kernel locks protect metadata, not application pointer lifetime; the
threads still need a mutex/atomic epoch or stop-the-world protocol. Reclaim works within node-by-memorycgroup scopes and may stall the allocating task in direct reclaim. A PMD THP gives a hardware huge leaf;
mTHP may group several base pages while remaining PTE-mapped; HugeTLB uses an explicit, separately
accounted, non-swappable pool. Each changes fault, allocation, reclaim and shootdown granularity.
Advanced introduction - 4 September 2026
76
CPU and Memory Virtualization
Linux / Fedora study day
16 Continue beyond this week
One intense day can build a coherent model, but retention and source fluency require repeated contact. Use
one weekly day with the same rhythm: theory derivation, Linux mapping, experiments, closed-notes synthesis.
Study day
Central question
Theory
2 - synchronisation
How do we make
interleavings correct and
scalable?
3 - I/O and persistence
How does an operation
survive devices and
crashes?
How do names become
durable blocks?
locks, semaphores,
condition variables,
deadlock, atomics,
memory models
interrupts/DMA,
batching, disks/SSDs,
crash consistency
inodes, directories, free
space, journaling, COW
filesystems
4 - filesystems
5 - networking
How does a packet cross
process/kernel/device
boundaries?
How are resources and
authority composed?
layering, queues,
flow/congestion
7 - virtualisation
How does one kernel
become a guest?
traps, shadowing, nested
translation
8 - kernel source
How do abstractions
survive real concurrency?
invariants and
lock/lifetime design
6 - isolation
reference monitors and
confinement
Fedora/Linux
implementation project
implement bounded
queue; trace futexes;
compare contention and
false sharing
trace read/write/fsync; page
cache, block layer,
io_uring overview
inspect mounts;
ext4/Btrfs concepts;
loopback test filesystem,
never the live root
sockets, ss, namespaces,
packet path and softirqs
namespaces, cgroup v2,
capabilities, seccomp,
SELinux labels/audit
KVM concepts, VM
exits, EPT/NPT, virtio;
compare containers
follow one syscall, one
fault and one wakeup in
your exact Fedora source
build
16.1 A disciplined kernel-source method
Do not begin by reading a large subsystem top to bottom. Start from an observed boundary:
1. identify the userspace API and native ABI (strace, man page, disassembly);
2. find the architecture entry or generated wrapper;
3. follow only the success path first;
4. write each invariant and lock/lifetime rule you depend on;
5. return for error, blocking and concurrency paths;
6. verify names against the exact Fedora kernel source matching uname -r.
Useful initial tours:
• x86 syscall entry: arch/x86/entry/entry_64.S and arch/x86/entry/syscall_64.c;
• task creation: kernel/fork.c;
• scheduler core and fair class: kernel/sched/core.c, kernel/sched/fair.c;
• fault handling: arch/x86/mm/fault.c, mm/memory.c;
• address-space maps: mm/mmap.c and documented VMA/Maple Tree interfaces;
• futexes: kernel/futex/;
• page allocation: mm/page_alloc.c;
• RCU: documentation first, then kernel/rcu/.
Symbol names and call structure change. The invariant and causal chain are the durable learning target.
Advanced introduction - 4 September 2026
77
CPU and Memory Virtualization
Linux / Fedora study day
17 Course-material alignment and source audit
17.1 How the supplied files are used
Supplied item
Role in this guide
Important extension/correction
Lecture1-intro.pdf, pp. 2-12
machine, apparent CPU sharing,
addresses, thread counter
Lecture01-notes.pdf, pp. 13-16
OS roles, process, limited direct
execution
Lecture02-notes.pdf, pp. 1-8
states, context switching,
FIFO/SJF/STCF/RR
ps states, fork/wait/exec/zombie
add multicore, MMU, TLB, DMA
and IOMMU details plus C
memory-model precision
correct ring numbering; decompose
mode switch, entry frame and
context switch
map abstract states to Linux tasks
and current SMP scheduling
add COW, stdio buffers, robust
wait/exec behavior and pthread
distinction
audit failures, buffering, exit
status and exec semantics
timer bug and I/O measurement
effects
ASLR, %p, VMA versus
PTE/frame distinction
volatile is not synchronisation;
futex and scalable alternatives
not a native Fedora x86-64 or
AArch64 reference
independent derivations; do not
reuse this guide during assessed
work
UM_OS_Lab1_P1_2026_Processes.pdf,
pp. 3-6
p1.c, p2.c, p3.c, zombie.c
process experiments
cpu.c, common.h
CPU-sharing demonstration
prog1.c, prog2.c
virtual-address observation
threads.v0.c, threads.v1.c
race and mutex
Linux_Syscall_quickref.pdf
historical ABI comparison
syllabus and 2025 exams
scope and question style
17.2 Version boundary
This revised guide was prepared on 4 September 2026 and focuses on a conventional Fedora x86-64 system.
Stable user APIs and architectural rules are separated from version-sensitive implementation details. Your
installed Fedora kernel can differ from current upstream through backports, configuration and architecture.
Inspect uname -r, Fedora’s matching source/debug packages and runtime interfaces before asserting a particular
internal helper or policy.
17.3 Primary and course-aligned reading
Theory:
• Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces - especially
CPU virtualisation, scheduling, address spaces, translation, paging, TLBs, replacement, concurrency and
persistence chapters.
• Intel, Intel 64 and IA-32 Architectures Software Developer’s Manual - system programming volumes for
protection, paging, SYSCALL, exceptions, interrupts and TLB invalidation.
• Arm, A-profile Architecture Reference Manual - use when reproducing mechanisms on the course’s AArch64
Raspberry Pi environment.
Linux architecture and entry:
• Linux kernel documentation, x86-64 entry and exit and generic entry/exit handling.
• Linux kernel documentation, Page Table Isolation.
• Current upstream source, entry_SYSCALL_64 and x86 syscall dispatch.
Tasks, credentials and scheduling:
• Linux man-pages, clone(2), fork(2), execve(2), wait(2), credentials(7), and capabilities(7).
Advanced introduction - 4 September 2026
78
CPU and Memory Virtualization
Linux / Fedora study day
• Linux man-pages, signal(7), sigreturn(2), and signal-safety(7).
• Linux kernel documentation, Credentials in Linux and Userspace I/O.
• Linux kernel documentation, EEVDF scheduler, scheduler domains, and cgroup v2 CPU controller.
• Linux man-pages, futex(2) and pthreads(7).
Memory management:
• Linux kernel documentation, Page Tables, Process Addresses, and x86-64 memory map.
• Linux kernel documentation, Physical Memory, Transparent Huge Pages, NUMA memory policy, and VM
sysctls.
• Linux man-pages, mmap(2), mprotect(2), proc_pid_maps(5), and proc_pid_smaps(5).
Concurrency and security:
• Linux kernel documentation, Memory Barriers, Lock types, Mutex design, and What is RCU?.
• Linux kernel documentation, Kernel Self-Protection.
The one-sentence synthesis
Linux lets user instructions run directly, but hardware interprets them inside kernel-installed privilege and
translation contexts; controlled entry paths let Linux validate exceptional requests, and per-task saved
state plus synchronised per-CPU scheduling, memory and cache/TLB mechanisms let the machine safely
resume any authorised execution stream.
Advanced introduction - 4 September 2026
79
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )