Kernel Architecture & OS Internals Questions
How an operating system kernel is structured and what it is responsible for: kernel subsystems (scheduler, memory manager, drivers, interrupt handling), kernel vs. user space and the cost of crossing between them, and the boot and initialization path. Includes the core mechanisms the kernel provides: process and thread lifecycle (creation, zombies and orphans, uninterruptible sleep) and context switching, processes vs. threads as an architectural choice, CPU scheduling (CFS, priorities, preemption models, real-time policies on a general-purpose kernel), virtual memory (address translation, multi-level page tables and entry formats, TLB misses and shootdowns, page faults, copy-on-write, memory-mapped files, userfaultfd, swapping, page replacement, kernel allocators, process address-space layout, page-level protection such as NX and ASLR as mechanisms, hugepages, page coloring, overcommit and the OOM killer as kernel mechanisms), interrupts and softirqs, and how loadable modules and device drivers extend the kernel. Includes worked exercises such as page-replacement traces, address-translation arithmetic and small page-table, TLB or scheduler simulations. Covers the concepts and internals, not microcontroller interrupt and ISR design, RTOS and real-time scheduling theory, day-to-day host administration, system-call and POSIX API semantics, OS-level performance tuning, or forensic and security analysis of a host.
Compare paging and segmentation as memory-management schemes: how an address is formed in each, what hardware support they need, and why modern general-purpose kernels such as Linux rely on paging for isolation.
Sample Answer
The two schemes in one line each. Segmentation divides a program's memory into variable-length logical pieces (code, stack, heap...), and an address names a segment plus an offset inside it. Paging divides both virtual and physical memory into equal fixed-size blocks (pages and frames, 4 KiB on x86-64 and common ARM Linux) and an address names a page plus an offset inside it.
How an address is formed.
- Segmentation. The logical address is (segment selector, offset). The selector is a small number held in a segment register; the hardware uses it to find a segment descriptor in a table (on x86 the GDT, the global descriptor table, or the LDT, a per-task local one) holding a base (where the segment starts in memory), a limit (its size) and permissions. It checks
offset <= limit, then computeslinear = base + offset. Example: base 0x10000, limit 0x4000, offset 0x0ABC gives 0x10ABC; offset 0x5000 exceeds the limit and faults. - Paging. A 32-bit virtual address with 4 KiB pages splits into a 20-bit virtual page number (VPN) and a 12-bit offset (4 KiB is 2^12). Example: 0x00403ABC has VPN 0x403 and offset 0xABC. The page table maps VPN 0x403 to a physical frame number, say 0x12345, so the physical address is (0x12345 << 12) | 0xABC = 0x12345ABC. The offset passes through unchanged.
- Both stages on x86 (32-bit protected mode). Take the segmentation example above: the segment stage gives the linear address 0x10ABC. The paging stage then treats 0x10ABC as a virtual address: VPN = 0x10ABC >> 12 = 0x10, offset = 0xABC. If the page table maps VPN 0x10 to frame 0x345, the physical address is (0x345 << 12) | 0xABC = 0x345ABC. This two-stage pipeline is what the classic textbook picture shows.
Hardware support.
- Segmentation needs segment registers and descriptor tables, plus a base-plus-limit adder and comparator on every access.
- Paging needs a page-table base register (CR3 on x86, a control register holding the physical address of the top-level table; TTBR0/TTBR1 on ARM, the two translation table base registers, which hold the tables for the lower and upper halves of the address space) that points at the current process's table, a hardware page-table walker (circuitry that reads the table entries in memory to translate an address on a TLB miss), and a TLB (translation lookaside buffer, a small cache of recent translations, without which every load would cost extra memory reads). Each page-table entry carries present, read/write, user/supervisor and no-execute bits.
Trade-offs.
| Segmentation | Paging | |
|---|---|---|
| Unit size | Variable, matches program structure | Fixed |
| Fragmentation | External: free memory splits into holes too small to place a new segment, so you compact or fail | Internal only: on average half of the last page of a region is wasted, and any free frame fits any page |
| Physical layout | Each segment must be contiguous in RAM | Pages can be scattered anywhere |
| Swapping and sharing | Whole segments move, which is slow and awkward | Per-page demand loading (a page is read in only when first touched), swapping, copy-on-write (share a page until someone writes, then copy it) and sharing |
| Protection | Per segment (coarse) | Per page, enforced uniformly |
Why Linux relies on paging. Fixed-size pages remove external fragmentation, so the kernel can place any page in any free frame, swap or reclaim single pages, load program files lazily, share one frame between processes and duplicate it only when written (copy-on-write), and set permissions at page granularity (read-only code, no-execute data, kernel-only pages). Isolation comes from giving each process its own page table. Segmentation cannot be switched off on x86: in 32-bit protected mode every memory access goes through a segment register, and the architecture has no mode that skips it. So Linux sets it up as flat: all segments have base 0 and cover everything, and in 64-bit mode the CPU ignores base and limit for the code, data and stack segment registers. The FS and GS segment bases are still used (the kernel documentation says they remain functional in 64-bit mode), so the one surviving use of segmentation is as a cheap base register. Example: each thread's FS base points at that thread's own block of thread-local storage, so the same instruction mov %fs:0x10, %rax (read the 8 bytes at FS base + 0x10) reads a different thread's memory in each thread, with no register spent on a pointer. The Linux kernel does the same with GS for per-CPU data (variables that exist once per CPU), so code can reach "this CPU's copy" without first asking which CPU it is on.
Recommendation and caveat. For a general-purpose multitasking OS with demand paging and many processes, choose paging: the cost is page-table memory and TLB pressure. Multi-level tables fix the memory: instead of one flat array with an entry for every virtual page (a 32-bit space with 4 KiB pages needs 2^20 entries, 4 MiB at 4 bytes each), the address is split into several indices and a lower-level table exists only for ranges the process actually uses. Huge pages ease the TLB pressure: a 2 MiB page is mapped by a single entry, so one TLB slot covers what 512 ordinary 4 KiB pages would need. Segmentation-style base and limit checks still make sense on small embedded parts with no MMU, where one contiguous region per task is acceptable. Pure segmentation also appears historically in early x86 and 16-bit systems, and x86 combined both (segment to linear address, then paging to physical), which is why the classic textbook picture shows two translation stages.
A network card raises a hardware interrupt while a process is running. Describe what the kernel does from the interrupt to returning to the process. Why is work split between a fast handler and deferred work, and what are the options for that deferred work?
Sample Answer
Direct answer
The CPU stops the running process, switches to a kernel stack (the separate memory area the kernel uses for its own function calls), and jumps to the NIC driver's interrupt handler (the "top half"), which does the minimum: acknowledge the device, silence further interrupts from it and schedule the real work. The rest (the "bottom half") runs moments later, with interrupts enabled again, as a softirq (a software interrupt, kernel code that runs just after the hardware interrupt handler finishes and before the CPU returns to the interrupted task), where the driver pulls packets off the ring and the network stack processes them. Then the kernel checks whether a different task should run (for example the one just woken because data arrived) and returns to user mode. The work is split because the top half runs with its interrupt line masked or interrupts disabled, so every microsecond there delays other devices and the interrupted process. The deferral options are softirq, tasklet, BH workqueue, ordinary workqueue, threaded IRQ handler and, for networking, threaded NAPI.
The path, step by step (x86-64; details differ on other architectures)
- Delivery. The NIC raises an interrupt (usually an MSI-X message: the device performs a special memory write, and the interrupt controller turns it into a vector, a small number that says which kind of interrupt this is). The controller delivers it to one CPU, chosen by interrupt affinity (an administrator-settable mapping from each interrupt to the CPUs allowed to handle it).
- Hardware entry. The CPU finishes its current instruction, indexes the IDT (interrupt descriptor table) with the vector to find the handler's entry point, and, because the process was in user mode, switches to that CPU's kernel stack and pushes the user's SS, RSP, RFLAGS, CS and RIP onto it. These are the stack segment, stack pointer, flags register, code segment and instruction pointer of the interrupted program: together the return state, everything the CPU needs to resume it exactly where it stopped. An interrupt gate (the IDT entry type used for hardware interrupts) also clears the interrupt flag (the bit in RFLAGS that lets the CPU accept new maskable interrupts), so ordinary interrupts are held off for now.
- Software entry. Assembly code saves the remaining registers, switches to a per-CPU interrupt stack and calls the generic IRQ code, which looks up the descriptor for that interrupt number and calls the handler the driver registered with
request_irq. - Top half. The handler acknowledges the device, reads minimal state, and calls
napi_schedule(): the NAPI (New API, the kernel's network polling framework) instance is put on a per-CPU poll list and the network-receive softirq is marked pending. The kernel's NAPI documentation advises keeping the device's interrupts masked until polling finishes, since more interrupts are unnecessary while polling. The interrupt controller is acknowledged by the kernel's generic IRQ flow code, and the order depends on the interrupt type: for edge-style interrupts such as MSI-X the acknowledgement is sent before the driver's handler is called (the kernel'shandle_edge_irqcalls the chip's ack first), while for level-style interrupts the end-of-interrupt signal is sent after the handler returns (handle_fasteoi_irq). Either way the CPU's interrupt flag stays cleared until the handler path returns, so the order does not let a second interrupt in early. - Softirq. On the way out of the interrupt (
irq_exit), if softirqs are pending and this was not a nested interrupt, the kernel runs them right there on the same CPU with interrupts enabled. The receive softirq calls the driver's poll function with a budget (the driver may take at most that many received packets per call), the driver builds packet buffers from the DMA ring (a circular array of buffer descriptors that the NIC fills directly in memory with packet data, using DMA, direct memory access, without the CPU copying), and the packets climb through IP and TCP. Delivering data to a socket wakes the process blocked inrecv, which only marks it runnable. If softirq work keeps recurring or runs too long, the kernel hands it to the per-CPUksoftirqdthread so user tasks are not starved (ksoftirqdis an ordinary schedulable thread, so the scheduler can then share the CPU fairly). When the poll finishes, the driver callsnapi_complete_done()and device interrupts are re-enabled; under heavy load the system stays in polling mode and interrupts rarely fire, which prevents an interrupt storm. - Return. Before going back to user mode the kernel checks the "need reschedule" flag and pending signals. If the woken task should run,
schedule()switches to it; otherwise the interrupted process resumes at the saved RIP, never having noticed.
A worked trace for one packet (illustrative values; x86-64, one CPU, a process app in user mode):
| Moment | Stack in use | Interrupts | What changed |
|---|---|---|---|
app running | app's user stack | enabled | |
| NIC interrupt arrives, hardware entry | app's kernel stack | disabled (interrupt gate) | 5 return-state words pushed |
Top half runs napi_schedule() | per-CPU interrupt stack | disabled | NIC interrupts masked, NET_RX marked pending |
irq_exit, softirq NET_RX polls | interrupt stack | enabled | driver takes 1 packet (budget, say 64, not reached) and queues it to the socket |
recv's sleeper marked runnable, return path | kernel stack | enabled | need-reschedule set, schedule() picks the woken task |
If 200 packets had been waiting and the budget were 64, the poll would be called again and again until the ring is empty, or ksoftirqd takes over if that goes on too long.
Steps 2 to 5 run in interrupt context, with one exception: if the kernel hands softirq work to ksoftirqd (step 5), that work runs in the context of that kernel thread instead, but under the same bottom-half rules. In interrupt context there is no process to charge, current is just whichever task happened to be interrupted, and the code must not sleep, take a mutex or touch user memory. Process context (the options below that use threads) may do all of those.
The options for deferred work
The question that separates them is whether the deferred code is allowed to sleep (block waiting for something). Softirq, tasklet and BH workqueue work cannot; workqueue and threaded handlers can. In the table, RCU (read-copy-update) is the kernel's lock-free scheme for read-mostly data, whose cleanup callbacks normally run as a softirq (with offloaded callbacks or on a real-time kernel they run in kernel threads).
| Mechanism | Runs in | Can sleep? | Concurrency | Typical use |
|---|---|---|---|---|
| Softirq | Interrupt context at irq_exit or in ksoftirqd | No | The same softirq can run on several CPUs at once, so handlers need per-CPU data or locks | Network RX/TX, block I/O completion, timers, RCU |
| Tasklet | Softirq context | No | A given tasklet runs on one CPU at a time | Older driver code needing simple serialization (the legacy interface; new code uses the rows around it) |
| BH workqueue | Softirq context, per-CPU, queued order | No | Per CPU | Newer interface over softirq with queueing, flushing and cancelling |
| Workqueue | Kernel worker thread (process context) | Yes | Tunable | Work that allocates memory with sleeping, takes mutexes, does slow I/O |
Threaded IRQ handler (request_threaded_irq) | A dedicated kernel thread per interrupt | Yes | One thread per handler | Slow devices (I2C, SPI) and real-time kernels |
| Threaded NAPI | A dedicated NAPI kernel thread instead of softirq | Not in poll | One thread per instance | CPU-isolated, schedulable packet processing |
The kernel documentation describes BH workqueues as a convenience interface to softirq whose items run in the queueing CPU's softirq context and cannot sleep. Tasklets are the older softirq-based interface; BH workqueues and ordinary workqueues cover the same needs with more features.
Choosing, and the latency trade-off
- Need to sleep (allocate with waiting, take a mutex, talk over a slow bus): workqueue or threaded IRQ.
- Highest packet rate per core with no scheduling hop: NAPI and softirq.
- Wake-up latency that must be bounded for other, higher-priority work: threaded handlers or threaded NAPI, because a thread can be given a priority and preempted. Softirqs and hard interrupt code are not scheduled by priority, so a long softirq adds jitter (unpredictable variation in how long a task waits to run) to unrelated tasks on that CPU.
The cost of threads is a context switch and a scheduling delay per piece of work; the cost of softirq is non-preemptible time. A real-time kernel moves most of this into threads for exactly that reason.
Observing it
/proc/interrupts shows per-CPU counts for each device interrupt (for example a row such as 35: 120394 0 0 0 PCI-MSIX eth0-rx-0, meaning vector 35 fired 120,394 times on CPU 0 and never on CPUs 1 to 3; illustrative), /proc/softirqs per-CPU counts per softirq type (NET_RX), and top shows time in the hi and si columns. A CPU with high si and a busy ksoftirqd thread is saturated by bottom-half work, which suggests spreading queues across CPUs (receive-side scaling, where the NIC hashes each flow to one of several receive queues, each with its own interrupt and CPU; and interrupt affinity) rather than tuning a single handler.
After a process forks, parent and child appear to have separate memory but no copying has happened yet. How does copy-on-write make that work at the page-table level, and what goes wrong for a workload that writes heavily to memory right after the fork?
Sample Answer
Direct answer
At fork, the kernel does not copy the parent's memory. It gives the child its own page tables (the per-process maps from virtual pages to physical frames) that point at the same physical frames, and it marks every writable private page read-only in both processes. Reads cost nothing extra. The first write by either side hits a read-only entry, which raises a page fault (a CPU trap into the kernel); the fault handler sees the page is shared copy-on-write, allocates a new frame, copies the 4 KiB, points the writer's entry at the copy with write permission, and resumes the instruction. A workload that writes heavily right after the fork therefore takes one fault plus one page copy per page it touches, so latency spikes and memory use climbs toward double the parent's size. Resident size (RSS) means the physical memory a process currently has mapped.
At the page-table level
forkduplicates the memory-region list (VMAs, the kernel's records of each mapping) and copies page-table entries (PTEs) for private anonymous memory. For each writable private page, the PTE is made read-only in the parent and the child, and the physical page's reference count (how many holders keep the frame alive) and map count (how many page tables map it) are increased because two address spaces now map it.- Neither process sees a difference on reads. A write to a read-only PTE inside a region the VMA says is writable is recognised as a copy-on-write fault.
- The fault handler checks who else maps the page. If another process still maps it, it allocates a new frame, copies the 4 KiB, installs the copy in the writer's PTE as writable, and drops one reference on the old frame. If the writer is the only remaining mapper (the other process already copied or exited), it just makes the PTE writable again without copying.
- The stale read-only translation must be removed from the TLB (the CPU's cache of translations), at least for that address, or the CPU would keep faulting.
Cost per first-touched page: a trap, a frame allocation, a 4 KiB copy, a PTE update and a TLB invalidation. The parent also pays this on its first write to each page after the fork, even if the child never writes, because the parent's entries were made read-only too.
What goes wrong for a write-heavy workload
- Memory blow-up. Worst case is about 2 times the parent's resident memory. A database that forks a 10 GiB process to write a snapshot while the parent keeps taking updates: if the parent dirties 30 percent of pages while the child runs, the extra is 10 GiB times 0.3 = 3 GiB, so the machine needs 13 GiB for the pair. The page tables themselves are small by comparison: 10 GiB is 2,621,440 pages, and at 8 bytes per entry that is 20 MiB.
- Latency spikes. Each first write to a shared page stalls the writer for a fault and copy, and a burst of writes right after
forkturns into a burst of faults, often visible as p99 latency jumps (the 99th-percentile response time: the delay that only 1 request in 100 exceeds) just after a snapshot starts. - Allocation failures. Under strict overcommit (
vm.overcommit_memory=2, "never overcommit") the child's private writable mappings must be accounted for atforktime, so a fork can fail withENOMEMeven though copy-on-write would rarely copy everything. Default mode 0 uses a heuristic that rejects only obvious overcommits. - Huge pages change the grain. (Huge pages are page sizes larger than 4 KiB, commonly 2 MiB on x86-64; transparent huge pages is the kernel feature that uses them automatically.) Whether a write copies 4 KiB or something larger depends on the kernel version and on transparent huge page settings (
/sys/kernel/mm/transparent_hugepage/enabled), so check your host when fork pauses look too large.
Worked example (executed)
The program maps 16,384 anonymous pages (64 MiB) and writes to all of them, forks, then in the child reads its proportional share (Pss_Anon from /proc/self/smaps_rollup; Pss is the process's share of each page divided among the processes mapping it), writes one byte into every page, and counts its own minor page faults (faults that need no disk read) via getrusage.
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/wait.h>
static long minflt(void) { struct rusage r; getrusage(RUSAGE_SELF, &r); return r.ru_minflt; }
/* Read one field (in KiB) from /proc/self/smaps_rollup */
static long rollup(const char *key) {
FILE *f = fopen("/proc/self/smaps_rollup", "r");
char line[256]; long v = -1;
while (fgets(line, sizeof line, f))
if (!strncmp(line, key, strlen(key))) { sscanf(line + strlen(key), " %ld", &v); break; }
fclose(f);
return v;
}
int main(void) {
long page = sysconf(_SC_PAGESIZE);
size_t pages = 16384, len = pages * page;
char *buf = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memset(buf, 1, len); /* parent touches every page */
printf("page size %ld, buffer %zu pages = %zu KiB\n", page, pages, len / 1024);
fflush(stdout);
pid_t pid = fork();
if (pid == 0) {
long f0 = minflt(), p0 = rollup("Pss_Anon:");
printf("child, right after fork: Pss_Anon %ld KiB\n", p0);
for (size_t i = 0; i < len; i += page) buf[i] = 2; /* one byte per page */
long f1 = minflt(), p1 = rollup("Pss_Anon:");
printf("child, after writing every page: new minor faults %ld, Pss_Anon %ld KiB\n", f1 - f0, p1);
fflush(stdout);
_exit(0);
}
waitpid(pid, NULL, 0);
return 0;
}
Compiled with gcc -O2 -Wall -Wextra cow.c -o cow && ./cow (GCC 14, Linux, 4 KiB pages). Output from one run (the exact counts drift by a few between runs, for example 16,402 or 16,403 faults and Pss_Anon values a few KiB apart, because the program's own startup and printf allocate a little; the proportions do not change):
page size 4096, buffer 16384 pages = 65536 KiB
child, right after fork: Pss_Anon 32838 KiB
child, after writing every page: new minor faults 16403, Pss_Anon 65610 KiB
Right after the fork each page is mapped by two processes, so the child's proportional share is about half of 65,536 KiB (32,838 KiB; the extra 70 KiB or so is the program's other anonymous memory, and a few KiB of that varies from run to run). After writing one byte per page, the child took 16,403 faults (16,384 for the buffer plus about 19 other faults from the child's own stack, libc and output buffers) and its share doubled to the full 64 MiB: every page was copied.
Telling copy-on-write growth from a leak
| Signal | Copy-on-write growth | Leak |
|---|---|---|
| Time shape | rises after a fork, then saturates (cannot exceed the parent's resident size at fork time) | rises without bound over hours or days in one process |
| After the child exits | system memory falls back | stays high |
smaps_rollup / smaps | Shared_Dirty moves into Private_Dirty as pages are copied; Rss (resident set size) for both processes counts the same shared frames, so compare Pss | Private_Dirty and Anonymous grow steadily in one process |
| Faults | minflt (field 10 of /proc/PID/stat) jumps in step with writes, or perf stat -e minor-faults | no particular fault burst |
Sample Pss over time with grep -E 'Rss|Pss|Private_Dirty|Shared_Dirty' /proc/PID/smaps_rollup; the sum of Pss across all processes is the real memory, while the sum of Rss counts shared frames more than once.
Mitigations and interactions for fork-heavy services
- Skip the copy when you only want a new program:
vforkorposix_spawninstead offorkplusexec, so no page tables are duplicated just to be discarded. madvise(MADV_DONTNEED)(a hint telling the kernel a range's contents are no longer needed) on a private anonymous range drops the pages; later accesses see zero-filled pages. In a child that is a quick way to release memory it will never need. In the process that owns the data it destroys the data, so apply it only where discarding is correct.mlockall(a call that locks all of a process's pages in RAM so they are never swapped out) pins pages in RAM, but the man page says locks are not inherited by a forked child and warns that forking aftermlockormlockallis dangerous for real-time work: the copy-on-write faults that follow can cause high latencies. Lock memory in a process that does not fork, or pre-fault and avoid forking late.- OOM killer. The kernel scores each process by the memory it uses (adjusted by
oom_score_adj, a per-process setting that raises or lowers its score; the OOM killer is the kernel routine that kills a process when memory runs out). Pages shared copy-on-write count against each process that maps them, so a large parent can be picked even when much of its memory is shared with a child, and a growing child can push the machine into an OOM kill. WatchPss, not justRss, and size the host for the 2x worst case.
Trade-offs and pitfalls
- Copy-on-write makes
forkfast to return, not free: the cost moves to the first write of each page. - Forking a very large, write-heavy process is a poor idea; prefer a design that snapshots by copying selected data, or fork when the write rate is low.
Pick apart an x86-64 page-table entry: which low-order flag bits does it hold (present, writable, user, accessed, dirty, page size, global) and the no-execute bit at the top, where does the physical frame number sit, and how does the kernel use the accessed and dirty bits?
Sample Answer
Layout of a 64-bit x86-64 page-table entry (PTE). The entry is 64 bits, and the hardware reads these fields (bit numbers confirmed against Linux's arch/x86/include/asm/pgtable_types.h):
| Bit | Name | Meaning |
|---|---|---|
| 0 | Present (P) | 1 means the entry is valid and maps something; 0 means any access page-faults and the other bits are ignored by the hardware |
| 1 | Read/write (R/W) | 0 forbids writes |
| 2 | User/supervisor (U/S) | 0 means kernel-only; user-mode access faults |
| 3, 4 | Write-through, cache-disable | Caching policy for the page: write-through writes to memory on every store, cache-disable bypasses the CPU caches (used for device memory) |
| 5 | Accessed (A) | Set by the CPU on any read, write or instruction fetch through this entry |
| 6 | Dirty (D) | Set by the CPU on the first write |
| 7 | Page size (PS) | In a higher-level entry (a page directory or page-directory-pointer entry) 1 means this entry maps a 2 MiB or 1 GiB huge page directly instead of pointing at a lower table. (x86-64 translates an address through four levels of tables, each indexed by 9 bits of the address; a page directory is a middle-level table and a page-directory-pointer table is the one above it. An entry at those levels normally points at the next table down, and PS=1 stops the walk there.) In a last-level 4 KiB entry bit 7 is a different field, PAT (page attribute table index, one more bit used to choose the page's caching type from a small table the OS programs) |
| 8 | Global (G) | The TLB entry survives an address-space switch (used for kernel pages; needs CR4.PGE, and Linux with kernel page-table isolation, KPTI, keeps most kernel mappings out of the user page tables and marks far fewer pages global) |
| 9 to 11 | Software | Ignored by hardware, available to the OS |
| 12 up to the CPU's physical-address width (at most bit 51) | Frame number | Physical address of the frame, with the low 12 bits implied zero |
| 63 | No-execute (NX, XD on Intel) | 1 forbids instruction fetches |
The remaining high bits (52 to 62) are not part of the frame number: bits from the CPU's physical-address width up to 51 must be zero (reserved), bits 52 to 58 are ignored by the hardware and free for the OS (Linux uses 57 and 58 for software flags such as saved-dirty), and bits 59 to 62 are, when protection keys are enabled, a 4-bit protection key (Linux's pgtable_types.h names them _PAGE_BIT_PKEY_BIT0 to _PAGE_BIT_PKEY_BIT3), a tag that lets user code cheaply change access rights for all pages with that tag. The question's flags need none of these.
Where the frame number sits. In bits 12 to (MAXPHYADDR minus 1), where MAXPHYADDR is the number of physical-address bits the CPU actually implements (at most 52), so the physical address of the frame is the entry with the flag bits masked off. Because frames are 4 KiB aligned, the low 12 bits of a physical frame address are always zero and double as the flag bits.
Decode a real value. Take 0x8000000012345067. The fields fall into two groups by who writes them: the OS writes present, writable, user, no-execute, global and the frame number, while the CPU itself writes accessed and dirty. Here is a short decoder you can run (python pte.py, Python 3.12):
FLAGS = [(0, "present"), (1, "writable"), (2, "user"), (3, "write-through"),
(4, "cache-disable"), (5, "accessed"), (6, "dirty"), (7, "page-size"), (8, "global")]
def decode(pte, maxphys=52):
frame_mask = ((1 << maxphys) - 1) & ~0xFFF # bits 12..maxphys-1
out = [name for bit, name in FLAGS if pte >> bit & 1]
out.append("NX" if pte >> 63 & 1 else "executable")
frame = (pte & frame_mask) >> 12
return out, frame, frame << 12
pte = 0x8000000012345067
flags, frame, phys = decode(pte)
print(hex(pte), flags)
print("frame number", hex(frame), "-> physical base", hex(phys))
print("low 12 bits", hex(pte & 0xFFF), "bit 63", pte >> 63)
0x8000000012345067 ['present', 'writable', 'user', 'accessed', 'dirty', 'NX']
frame number 0x12345 -> physical base 0x12345000
low 12 bits 0x67 bit 63 1
Reading the two non-obvious lines. ((1 << maxphys) - 1) builds a number with maxphys one-bits (52 ones, bits 0 to 51); & ~0xFFF clears the lowest 12 of them, leaving ones only in bits 12 to 51: the constant works out to 0x000FFFFFFFFFF000 (the program does not print it). pte & frame_mask keeps just the frame-number bits and >> 12 moves them down to give the frame number. In pte >> bit & 1, >> binds tighter than & in Python, so it shifts the entry right by bit places (bringing that bit to position 0) and then & 1 keeps only that bit: 1 if it is set, 0 if not.
By hand: the low 12 bits are 0x067 = binary 0110 0111, so bits 0, 1, 2, 5 and 6 are set (present, writable, user, accessed, dirty), bit 63 is 1 (no-execute), and bits 12 and up give frame 0x12345, physical address 0x12345000. So this is a user-accessible, writable, non-executable data page in RAM that has been both read and written (since the OS last cleared the bits). A virtual address that uses this entry adds its 12-bit offset: virtual offset 0xABC lands at physical 0x12345ABC.
How the kernel uses accessed and dirty.
- Accessed tells the kernel what is in use. Page reclaim (the code that frees RAM under pressure) clears A on pages and checks later whether the CPU set it again: pages that stayed at 0 are cold and are evicted first (the basis of Linux's LRU-style lists, least-recently-used lists that order pages by how recently they were used). After A is cleared, a core whose TLB (the CPU's cache of recent translations) still holds the old translation does not walk the page table again, so it does not set A again even if the page is used: reclaim can then see a falsely cold page. A TLB flush would close that gap, but Linux on x86 deliberately does not flush when it clears A (
ptep_clear_flush_younginarch/x86/mm/pgtable.c: clearing the accessed bit without a flush "doesn't cause data corruption" but "could cause incorrect page aging"; the stale entry is flushed eventually by a context switch or another VM operation), trading slightly imprecise aging for avoiding the flush cost. Clearing or write-protecting for dirty tracking is different: there a stale writable TLB entry would let writes slip past unnoticed, so the flush is required. Reclaim is the work of freeing RAM when it runs short, and swap is disk space where anonymous pages can be parked. - Dirty tells the kernel what must be saved. A dirty file-backed page has to be written back to its file before the frame can be reused (and
msync/writeback find them this way), an anonymous page has to be written to swap, and a clean page can simply be dropped because the disk already holds the same content. - When Present is 0 the hardware ignores the rest of the entry, so Linux stores a swap location there (swap device and offset), plus markers for other states; this is why a not-present PTE is not necessarily "unused".
- Some CPUs do not set A and D in hardware; there the kernel emulates them with faults. For dirty: it maps a writable page read-only, the first write faults, and the fault handler records "dirty" in a software bit and makes the entry writable (the arm64 code in the Linux source does this when hardware dirty management is absent: it updates a software
PTE_DIRTYbit). For accessed: it leaves the entry unusable until first use, so the fault handler can record the access and make it usable.
What does the kernel track for a process versus a thread, and what do threads of one process share? When would you choose several processes over several threads for a server, and why?
Sample Answer
Direct answer
A process is a running program with its own address space, file-descriptor table, credentials and PID. A thread is a schedulable flow of execution inside a process. Threads of one process share the address space (code, globals, heap), the open files and the signal handlers, but each has its own registers, stack, thread ID and signal mask (the set of signals that thread currently blocks from being delivered). Choose threads when tasks need to share memory cheaply and a crash is acceptable to take down all of them. Choose several processes when you want fault or security isolation, or when sharing is minimal.
What the kernel tracks
On Linux the kernel schedules one task (task_struct) per thread. A "process" is a group of tasks that share resources. The clone system call creates a task, and flags decide what is shared. Each flag switches on one kind of sharing; a thread is a task created with all of them, and a separate process with none: CLONE_VM (same address space), CLONE_FILES (same descriptor table), CLONE_FS (same working directory), CLONE_SIGHAND (same signal handlers) and CLONE_THREAD (same process, so same PID as seen by getpid()). fork() is a clone that shares nothing: the child gets a copy-on-write copy of the address space (the kernel does not copy memory pages up front; parent and child share them read-only, and a page is copied only when one side writes to it), which is why it is cheap in proportion to the size of the page tables rather than the size of memory used.
| Resource | Per process | Shared by all its threads | Per thread |
|---|---|---|---|
| Address space (code, heap, globals) | Yes | Yes | No |
| File-descriptor table | Yes | Yes | No |
| Credentials (user and group IDs) | Yes | Normally the same | Kernel stores them per task |
| Signal dispositions (what to do when each signal arrives: ignore, run a handler, or terminate) | Yes | Yes | No |
| Registers, program counter, stack | No | No | Yes |
Signal mask, thread-local storage (variables declared so that each thread gets its own copy, abbreviated TLS in this table only), errno | No | No | Yes |
| Scheduling unit | No | No | Yes |
On Windows the same split exists differently: a process object owns the address space and handle table, a thread is the unit of scheduling, and there is no fork; creating a process (CreateProcess) is heavier and starts a fresh image.
A tiny experiment shows the difference. A global counter starts at 0. A thread sets it to 100 and finishes; a forked child sets it to 200 and exits. The parent then prints it each time.
#include <pthread.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int counter = 0; /* a global: lives in the address space */
void *bump(void *arg) { counter = 100; return NULL; }
int main(void) {
pthread_t t;
pthread_create(&t, NULL, bump, NULL); /* thread: same address space */
pthread_join(t, NULL);
printf("after thread: counter = %d\n", counter);
counter = 0;
pid_t pid = fork(); /* process: child gets its own copy */
if (pid == 0) { counter = 200; _exit(0); }
waitpid(pid, NULL, 0);
printf("after fork child: counter = %d\n", counter);
return 0;
}
Compiled with gcc and run in a Linux container, it printed:
after thread: counter = 100
after fork child: counter = 0
The thread wrote into the one shared address space, so the parent sees 100. The child wrote into its own copy, so the parent still sees 0.
Process versus threads for a server
| Concern | Threads in one process | Several processes |
|---|---|---|
| Crash isolation | A segmentation fault or abort in one thread kills them all | A crashing worker leaves siblings running |
| Creation cost | Lower (no new address space) | Higher (page tables, fork or exec) |
| Sharing data | Direct memory access, which requires locks | Needs inter-process communication (IPC) |
| IPC overhead | None for shared memory | Pipes and sockets copy through the kernel; shared-memory mappings avoid the copy but need their own synchronization |
| Security | A memory bug lets one thread read secrets of any other; the whole process has one set of permissions | Each process can have its own user ID, sandbox and filesystem view, so a compromised parser reaches little |
| Race hazards | Data races are possible on every shared variable | Races only on explicitly shared regions |
Recommendation. For a latency-sensitive service whose workers share a large in-memory cache, use threads (or an event loop on a few threads). For a component that handles untrusted input, such as a file parser, an image decoder, or a browser tab, run it in a separate low-privilege process (one given only the few permissions its job needs): if an attacker exploits a memory bug the damage stays in that process, and a crash restarts one worker. Real systems mix both: a browser uses a process per site and threads inside each, and Postgres uses a process per connection partly for isolation.
Worked example
A server decodes uploaded images. With thread-per-request, a malformed file that triggers a heap overflow (writing past the end of a heap buffer into neighbouring memory) runs the attacker's code with access to the process's encryption keys for HTTPS connections (the TLS protocol, unrelated to thread-local storage above), session cache and database credentials, all in the same address space, and a plain crash drops every in-flight request. With a pool of decoder processes running under a restricted user ID with a system-call filter (a kernel-enforced list of system calls the process may make, such as seccomp on Linux; anything else is refused or kills it), the same overflow reaches only that decoder's memory; the parent sees a child exit and starts a replacement. The price is copying each upload to the decoder through a pipe or a shared mapping.
Pitfalls and notes
- "Threads are always faster" ignores the locking they require; "processes are always safer" ignores IPC bugs and cost.
- Memory-forensics note: a memory image lists each thread as its own task entry, and because threads share one address space a dump of the process contains every thread's stack.
- Fork in a multithreaded program only copies the calling thread, which leaves locks held by other threads stuck in the child; call
execsoon after.
Unlock Full Question Bank
Get access to all 49 Kernel Architecture & OS Internals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.