Advanced OS Concepts (OS Core #9)
The last layer is about sharing a machine at a coarser grain: whole operating systems on one hypervisor, isolated process trees in containers, memory attached to specific sockets, and device registers mapped into the address space. The thread running through all of it is the same: virtualize a resource, then enforce the boundary.
Virtualization
Virtualization runs one or more guest operating systems on a host, each believing it owns the hardware. The hypervisor (virtual machine monitor) owns the real hardware and presents fake devices to the guests.
The classical mechanism is trap and emulate:
- The guest runs in a less privileged mode than the hypervisor.
- A privileged instruction (disable interrupts, change page tables, do I/O) traps.
- The hypervisor emulates the effect and resumes the guest.
That works only if every sensitive instruction is privileged. On older x86 it was
not: popf, sgdt, and some segment operations behaved differently without
trapping, which is why x86 virtualization was hard until hardware support arrived.
Modern CPUs add virtualization extensions: Intel VT-x and AMD-V provide a new privilege level for the hypervisor, and extended page tables (EPT/NPT) let the CPU translate guest-physical to host-physical addresses directly. Without EPT, the hypervisor had to shadow guest page tables, which was expensive.
ASolution
Some sensitive instructions are not privileged: they behave differently in user mode but do not fault. The hypervisor never gets control, so it cannot emulate them. Hardware virtualization fixes this by adding an explicit guest mode.
Hypervisors: type 1 and type 2
| Type 1 (bare metal) | Type 2 (hosted) | |
|---|---|---|
| Runs on | hardware directly | an existing OS |
| Guests | full VMs | full VMs |
| Overhead | lower | higher (host OS in the path) |
| Examples | Xen, ESXi, Hyper-V, KVM | VirtualBox, VMware Workstation |
| Use | data centres, cloud | desktops, development |
KVM is a special case: it is a Linux kernel module that turns the host kernel into
a hypervisor. The host is the type-1 layer, and each guest is a normal process
managed by the Linux scheduler. That is why KVM guests show up in ps as qemu-kvm
processes.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=3.2cm, minimum height=0.5cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=gray!10] (hw1) at (0,0) {hardware};
\node[b, fill=orange!18] (hv1) at (0,0.7) {hypervisor};
\node[b, fill=blue!12] (g1) at (-1.0,1.6) {guest A};
\node[b, fill=blue!12] (g2) at (1.0,1.6) {guest B};
\draw[a] (hv1) -- (g1); \draw[a] (hv1) -- (g2);
\node[font=\scriptsize, anchor=north] at (0,-0.35) {type 1};
\node[b, fill=gray!10] (hw2) at (6.2,0) {hardware};
\node[b, fill=green!15] (host) at (6.2,0.7) {host OS};
\node[b, fill=orange!18] (hv2) at (6.2,1.4) {hypervisor app};
\node[b, fill=blue!12] (g3) at (6.2,2.2) {guest};
\draw[a] (hw2) -- (host); \draw[a] (host) -- (hv2); \draw[a] (hv2) -- (g3);
\node[font=\scriptsize, anchor=north] at (6.2,-0.35) {type 2};
\end{tikzpicture}
ASolution
Both. It is a separate OS from the guest’s point of view, and it is a host
process (usually qemu-kvm) from the host’s point of view. The host scheduler
decides when its virtual CPUs run.
Containers
A container is not a small VM. It is a normal process (or process tree) on the host kernel, isolated by kernel features:
- Namespaces control what the process can see: mount (
mnt), process IDs (pid), network (net), hostname (uts), IPC, users (user), cgroups, and time. A process in a new PID namespace sees itself as PID 1. - cgroups control how much it can use: CPU shares and quotas, memory limits, I/O weights, process counts.
- Filesystem tricks give it a root:
chroot/pivot_rootplus an overlay filesystem assembled from image layers. - Capabilities and seccomp restrict what root inside the container can actually do, and which syscalls are allowed.
#define _GNU_SOURCE
#include <sched.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstdio>
int main() {
// new PID, mount, and network namespaces
if (unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET) < 0) {
std::perror("unshare");
return 1;
}
// CLONE_NEWPID affects children, so fork and exec the shell
pid_t pid = fork();
if (pid == 0) {
execlp("bash", "bash", (char*)nullptr);
_exit(1);
}
waitpid(pid, nullptr, 0);
}
Inside that shell, ps shows a tiny process tree and ip link shows only a
loopback interface. The host still sees the processes; they are just in different
namespaces.
| Virtual machine | Container | |
|---|---|---|
| Kernel | its own | shared with host |
| Boot time | seconds | milliseconds |
| Memory overhead | full OS | process only |
| Isolation | hardware-enforced | kernel-enforced |
| Density | tens per host | hundreds per host |
| Live migration | mature | harder |
| Security boundary | strong | weaker (shared kernel) |
A container escape is a kernel exploit; a VM escape is a hypervisor exploit. That difference drives most of the security advice.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=2.4cm, minimum height=0.5cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=gray!10] (hw) at (0,0) {hardware};
\node[b, fill=green!15] (k) at (0,0.7) {host kernel};
\node[b, fill=blue!12] (c1) at (-1.3,1.5) {container A};
\node[b, fill=blue!12] (c2) at (1.3,1.5) {container B};
\draw[a] (k) -- (c1); \draw[a] (k) -- (c2);
\node[font=\scriptsize, anchor=north] at (0,-0.35) {shared kernel: namespaces + cgroups};
\end{tikzpicture}
ASolution
The container starts a process on the existing kernel. The VM must boot a full operating system, initialize devices, and start services.
Kernel threads
A kernel thread runs only kernel code, has no user address space, and is scheduled like any other task. It is how the kernel does background work.
Common examples on Linux:
kworker/*: deferred work (workqueues).ksoftirqd/*: soft interrupt processing.kswapd0: reclaims memory under pressure.migration/*: per-CPU threads for moving tasks between CPUs.kthreadd: the parent of all kernel threads (PID 2).
$ ps -eLo pid,tid,comm | grep -E 'kworker|kswapd|migration' | head
Kernel threads are visible in ps with names in brackets. They cannot be killed
from user space; the kernel manages their lifetime. A driver creates one with
kthread_run() and stops it with kthread_stop().
The distinction from a user thread:
| Kernel thread | User thread | |
|---|---|---|
| Address space | none | process address space |
| Runs | kernel code only | user code, enters kernel via syscalls |
| Created by | kernel/driver | pthread_create, std::thread |
Visible in ps |
yes, bracketed | yes |
| Can be killed | no | yes |
ASolution
Yes, a kernel stack only. It has no user stack because it never returns to user mode.
NUMA basics
On a multi-socket machine, memory is attached to specific CPU sockets. A NUMA node is a CPU group plus its local memory. Accessing local memory is fast; going across the interconnect is slower.
Typical latency on a modern server: 80–120 ns local, 140–250 ns remote. Bandwidth also drops across the link, especially when several sockets saturate it.
The default Linux policy is first touch: the first CPU to touch a page gets it allocated on its local node. A single-threaded initialization phase therefore places all memory on one node, and the other sockets pay remote latency forever.
Fixes:
numactl --interleave=all ./appspreads pages across nodes.mbind/set_mempolicyset policy per mapping.- Initialize memory in parallel so each thread first-touches local pages.
- Use NUMA-aware allocators (jemalloc, tcmalloc with NUMA support).
$ numactl --hardware
available: 2 nodes (0-1)
node 0 cpus: 0 1 2 3 ...
node 1 cpus: 8 9 10 11 ...
A thread’s CPU affinity matters as much as its memory placement: a thread pinned to node 1 but allocating on node 0 gets the worst of both.
ASolution
If the working set is allocated on one node and the threads run on the other, every memory access crosses the interconnect. Adding sockets adds remote traffic, not just capacity.
Memory-mapped devices
Device registers are exposed as physical addresses. The driver maps them into kernel virtual memory and reads or writes them with special accessors:
void __iomem* base = ioremap(phys_addr, size);
u32 status = readl(base + STATUS_REG);
writel(value, base + CONTROL_REG);
iounmap(base);
Three rules:
- Never use ordinary pointer dereferences. The compiler may cache, reorder, or
combine accesses.
readl/writelinclude the barriers the device requires. - The memory is uncached. Reads go to the device, not to a cache line.
- Ordering matters. Some devices require a read-back or a full barrier before the next write; the driver’s documentation says which.
User space can map device memory with /dev/mem (root only, dangerous) or through
UIO/VFIO, which are the supported ways to write a user-space driver. VFIO also
gives the device an IOMMU mapping, so DMA cannot scribble over arbitrary memory.
Port I/O (in/out instructions) is the older x86 mechanism, with a separate
64 KB address space. MMIO is the norm for PCIe devices.
value?
ASolution
The compiler or CPU may have cached it, or reordered it with another access.
MMIO needs volatile accessors plus barriers, which readl/writel provide.
Filesystem caching and the page cache
Linux keeps file data in the page cache, a single cache shared by read,
write, and mmap. Every file page that is in memory is there.
- A read hits the page cache or triggers readahead and a disk read.
- A write copies into the cache and marks the page dirty.
- Background threads write dirty pages back (
vm.dirty_writeback_centisecs, 5 s default). - Under memory pressure, clean pages are dropped first; dirty pages are written back before eviction.
Tunables that matter in production:
vm.dirty_ratio = 20 # max % of RAM dirty before writers block
vm.dirty_background_ratio = 10 # start background writeback
vm.vfs_cache_pressure = 100 # reclaim aggressiveness for inode/dentry caches
echo 3 > /proc/sys/vm/drop_caches clears clean caches (a debugging tool, not a
production fix). posix_fadvise hints that a range will or will not be used soon.
The page cache explains a common measurement: the first read of a file is slow, the second is fast, and adding RAM improves throughput without changing the disk. It also explains why “free memory” on Linux is usually small: unused RAM is cache.
ASolution
Unused RAM is used for the page cache. It is reclaimable instantly, so free
shows it as available, not free.
Putting it together: boot to containers
The layers in order:
- Firmware (UEFI/BIOS) initializes hardware and loads a bootloader.
- Bootloader (GRUB, systemd-boot) loads the kernel and initramfs.
- Kernel initializes memory, interrupts, drivers, and mounts the root filesystem (possibly from initramfs).
- init/systemd (PID 1) starts services, mounts filesystems, brings up networking.
- Services run; a container runtime creates namespaces and cgroups and starts the container’s PID 1.
Every abstraction in this series appears in that list: page tables and MMU at step 3, scheduling and signals at step 4, filesystems and descriptors when services open their configuration, and namespaces/cgroups at step 5.
ASolution
After the host is fully booted and the container runtime has created the namespaces and cgroups. The container’s PID 1 is a normal host process in a different PID namespace.
Bugs and edge cases
- Treating containers as security boundaries equal to VMs. They share the kernel; a kernel bug can cross the boundary.
- No memory limit in a container. One container can consume the host’s RAM and trigger the OOM killer for everyone.
- Ignoring cgroup v1 versus v2. Controllers, hierarchy, and file names differ; tooling may read the wrong one.
- CPU pinning without NUMA awareness. Pinning a thread to a CPU whose node holds none of its memory makes latency worse.
- Assuming first-touch is optimal. A serial initialization phase places all pages on one node.
- Using
/dev/memin production. It bypasses the IOMMU and can corrupt memory; use UIO/VFIO. - Dropping caches as a fix. It slows the next workload and hides the real problem.
- Huge pages without planning. They reduce TLB pressure but increase fragmentation and COW cost.
- Overcommitting memory. The OOM killer chooses a victim later; set limits and test under pressure.
ASolution
The container hit its cgroup memory limit. The host may have free pages, but the cgroup controller enforces the container’s own ceiling, and the kernel kills inside the cgroup rather than reclaiming from elsewhere.
That is the end of the OS series. The next step is practice: trace a syscall with
strace, read /proc/self/maps, and reproduce a race with two threads and
-fsanitize=thread.