Notes
All notes

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:

  1. The guest runs in a less privileged mode than the hypervisor.
  2. A privileged instruction (disable interrupts, change page tables, do I/O) traps.
  3. 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.

QQuestionWhy is trap-and-emulate impossible for some instructions on old x86?
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}
QQuestionIs a KVM guest a process or a separate OS?
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:

#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}
QQuestionWhy can a container start in milliseconds while a VM takes seconds?
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:

$ 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
QQuestionDoes a kernel thread have a stack?
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 --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.

QQuestionWhy can adding a second socket make an application slower?
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:

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.

QQuestionWhy can a normal pointer read of a device register return a stale

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.

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.

QQuestionWhy does Linux report almost no “free” memory on a healthy server?
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:

  1. Firmware (UEFI/BIOS) initializes hardware and loads a bootloader.
  2. Bootloader (GRUB, systemd-boot) loads the kernel and initramfs.
  3. Kernel initializes memory, interrupts, drivers, and mounts the root filesystem (possibly from initramfs).
  4. init/systemd (PID 1) starts services, mounts filesystems, brings up networking.
  5. 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.

QQuestionAt which point does a container’s PID 1 start?
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

QQuestionA container is OOM-killed even though the host has free memory. Why?
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.