AlgoViz

How the Linux kernel works

medium 40 min

The kernel is the one program that runs with full privilege.

Theory

Read or listen first. About 4 min.

What it is

A kernel is the program that starts first, stays in memory and runs with full privilege. It is the only code allowed to talk to the hardware directly: CPU cores, RAM, disks and network cards. Every other program, from your shell to a database, runs in user space with fewer rights and asks the kernel for service.

Linux is a monolithic kernel: the scheduler, memory manager, file systems, network stack and device drivers all run together in one privileged address space. Parts can still be added while it runs as loadable modules, for example a driver for a new disk. A microkernel takes the other road: it keeps only a small core privileged and runs drivers and file systems as separate user programs, which isolates them better but costs extra messages between them.

The kernel is not a process that sits and waits. It runs on behalf of something: a process that made a system call, a device that raised an interrupt, or an instruction that caused an exception. It also starts a few helper threads of its own, called kernel threads, which you can see in ps with their names in brackets.

Why it exists

Without a kernel every program would need its own disk driver, and one buggy program could overwrite another's memory or take the CPU forever. The kernel solves three problems at once: sharing (many programs, few CPUs and one disk), protection (a program cannot read another's memory or the kernel's) and abstraction (a file looks the same on any disk, a socket the same on any network card).

For production engineers the kernel is where many mysteries end. A command that is fast on a laptop and slow on a busy host, a process that ignores kill -9, a load average of 40 on an idle CPU, a container that dies without a log line: each one is explained by one part of the map on this page, and each part has a command that shows it.

A short history

  1. 1991

    Linus Torvalds writes the release notes for Linux 0.01. The notes on kernel.org carry the line "(C) 1991 Linus Torvalds".

  2. 9 Oct 2007

    Linux 2.6.23 is released with CFS, the Completely Fair Scheduler, which replaces the earlier O(1) scheduler.

  3. 24 Jan 2008

    Linux 2.6.24 is released. It contains the first control groups, the framework the kernel docs call cgroups.

  4. 18 Feb 2013

    Linux 3.8 completes user namespaces, so unprivileged users can create namespaces safely.

  5. 13 Mar 2016

    Linux 4.5 declares the unified cgroup hierarchy, cgroup v2, stable.

  6. 23 Dec 2018

    Linux 4.20 adds pressure stall information (PSI), files under /proc/pressure that measure time lost waiting for CPU, memory and I/O.

  7. 5 May 2019

    Linux 5.1 merges io_uring, a new interface for asynchronous I/O.

  8. 29 Oct 2023

    Linux 6.6 starts the move from CFS to a new scheduler called EEVDF.

  9. Nov 2026

    kernel.org lists 7.3.6 as the latest stable kernel and 7.4-rc4 as mainline. A new mainline kernel comes out every 9 to 10 weeks.

Inside this chapter

Kernel space and user space
Kernel space is memory and code that only the kernel may touch. User space is where ordinary programs run with limited rights.
Privilege level
A mode of the CPU. x86 calls them rings: the kernel runs in ring 0, programs in ring 3. Arm calls them exception levels.
System call
The fixed door from a program into the kernel: open, read, write, fork and a few hundred more.
Interrupt
A signal from a device, such as a disk or a network card, that makes the CPU stop and run a kernel handler.
Exception
Raised by the CPU itself while running an instruction, for example a page fault or a division by zero.
Context switch
Saving one task's registers and loading another's, so a different task runs on that CPU.
Task
The kernel's unit of scheduling. A process with four threads is four tasks that share memory. The kernel's structure for one is called task_struct.
Page and page fault
Memory is handled in fixed blocks called pages, 4,096 bytes on most machines. A fault happens when a program touches a page that is not mapped yet.
Page cache
File data that the kernel keeps in RAM after reading or writing it, so the next read needs no disk.
Kernel thread
A thread that lives only in the kernel and has no user program, such as kswapd or ksoftirqd.

How it works

Step through the idea, or press Play.

Step 1 of 4

Ask through the door. A system call enters kernel mode

Understand it

Start here

A tool library with one keeper

Picture a tool library. Members work at a long workbench in the hall. Behind a wall is a back room with the stock, and only one person, the keeper, has the keys. The story below follows one ordinary request and then asks why the same request was once slow.

The keeper of the tool library
the hatchfront shelfbasementstaff onlyOnly the keeper has keys

Members never touch the stock. They ask, they get interrupted, or they find an empty drawer.

The map

Hardware, kernel and user space

Think of a building with three floors. The ground floor is the hardware. The middle floor is the kernel, and only it has stairs to the ground floor. The top floor is user space, where your programs live. The only way down from the top floor is one staircase: the system call interface.

The kernel map

One Linux machine in three layers. In user space, bash calls fork, cat calls read and nginx calls recv, and all three arrows go into the system call interface in kernel space. From there arrows go to five subsystems: processes and scheduler, memory manager, VFS and file systems, network stack, and device drivers with IRQs. The VFS sends page cache work to the memory manager, and the network stack sends packets to the drivers. The scheduler runs tasks on the CPU cores, the memory manager sets up page tables in RAM, the drivers do block I/O to the disk, and the network card sends a dashed interrupt arrow up to the drivers.
Arrows go down only through the system call interface. The one arrow that comes up from the hardware is an interrupt.

Each subsystem, what it keeps, and how you look at it

SubsystemOwnsKey objectsLook with
Processes and schedulerWho runs, where, for how longTasks, run queuesps, top, pidstat, /proc/PID/status
Memory managerVirtual memory, pages, reclaimPage tables, page cache, anonymous pagesfree, vmstat, /proc/meminfo, /proc/PID/maps
VFS and file systemsPaths, files, open file stateDentries, inodes, file objects, superblocksls -l /proc/PID/fd, df, stat
Block layer and driversDisk requests and devicesRequests to the diskiostat -x, /proc/interrupts
Network stackSockets, TCP, IP, packetsSockets, sk_buff packetsss, ip, nstat
Namespaces and cgroupsWhat a group sees and usesNamespace and cgroup filesls -l /proc/PID/ns, /sys/fs/cgroup
sk_buff is the kernel's main structure for one packet. Each topic linked below goes one level deeper.

The CPU itself enforces the floors. It has privilege levels: on x86 the kernel runs in ring 0 and programs run in ring 3; on Arm the levels are called EL1 and EL0. Code in user mode that tries a privileged instruction, or touches kernel memory, causes an exception, and the kernel decides what happens. Usually the program is stopped with a signal. More on the boundary and why crossing it costs time: the kernel boundary.

Monolithic or microkernel?

  • Monolithic: Linux

    All core parts share one privileged address space. A call from the VFS into a driver is a plain function call. A bug in a driver can crash the whole kernel.

  • Loadable modules

    Drivers and file systems can be loaded while the kernel runs, with modprobe. lsmod lists them. Once loaded they run with full privilege like the rest.

  • Microkernel

    Only a small core is privileged. Drivers and file systems are separate programs that talk by messages. A crashed driver can restart, at the price of more crossings.

  • Why it matters at work

    On Linux a kernel bug in any driver shows up as a panic or a soft lockup for the whole machine, so kernel and driver versions are part of every incident report.

Entry points

Three ways into the kernel

A shop assistant can be interrupted in three ways: a customer asks a question, the phone rings, or they drop a box and the alarm goes off. The kernel's three entries work the same way.

System call, interrupt, exception

System callInterruptException
Who starts itThe program, on purposeA device: disk, network card, timerThe CPU, while running an instruction
In step with the program?YesNo: can arrive at any momentYes: caused by this instruction
Examplesread, write, openat, cloneA packet arrived, a disk read finished, a timer tickPage fault, divide by zero, invalid instruction
Runs in the context ofThe calling processWhatever was running, borrowed brieflyThe faulting process
May the handler sleep?Yes, for example waiting for the diskNoYes for a page fault that reads from disk
Where you see itstrace, perf trace/proc/interrupts, the in column of vmstatPage-fault counters in perf stat, /proc/vmstat

One read() system call

The C library wrapper puts the call number in a register and runs the syscall instruction. On an error the wrapper returns -1 and sets errno.

Some calls are asked so often that crossing the boundary would dominate their cost. For those the kernel maps a small piece of its own code into every process, called the vDSO. On x86-64 it provides clock_gettime, gettimeofday, time and getcpu, so asking for the time usually does not enter the kernel at all. You can see it as [vdso] in /proc/self/maps.

What happens on any crossing

  1. 1

    Switch mode

    The CPU moves to the kernel's privilege level and jumps to a fixed entry point that the kernel set up at boot. A program cannot pick another address.

  2. 2

    Save the program's state

    Registers are saved, so the program can continue exactly where it stopped.

  3. 3

    Do the work

    Run the system call, the interrupt handler or the fault handler.

  4. 4

    Check before going back

    Is a signal pending? Should another task run first? On the way back to user mode the kernel checks both.

  5. 5

    Return

    Restore registers, drop to user mode and continue the program, or a different task if the scheduler chose one.

Deeper: the system call path walks the table, the handler and errno in detail.

Tasks

Processes and threads

A recipe on paper is a program. A cook following it in a kitchen is a process: the recipe plus a place in it, ingredients and tools. Two cooks sharing one kitchen and one fridge are two threads of the same process.

Linux creates a process in two steps. fork() makes a copy of the caller. The manual says Linux does this with copy-on-write pages: parent and child share every page until one of them writes, and only then is that page copied. The child gets copies of the parent's file descriptors. Then execve() replaces the child's code, data, heap and stack with a new program. Open descriptors stay open across execve() unless they are marked close-on-exec.

The life of a task

Preempted means its time slice ran out or a more urgent task arrived. R covers both running and waiting in the run queue. S can be woken by a signal. D cannot, until the I/O completes.

State letters you will see in ps

LetterMeaningWhat to think
RRunning or runnable, on a run queueUsing a CPU or waiting for one
SInterruptible sleep, waiting for an eventNormal for an idle server
DUninterruptible sleep, usually I/OCounts in the load average. Signals wait
T / tStopped by job control / by a debuggerSomeone sent SIGSTOP, or a tracer is attached
ZZombie: exited, not reaped by its parentFix or restart the parent so it calls wait
IIdle kernel threadNormal, ignore it
From the ps manual. /proc/PID/status spells the same letters out, for example D (disk sleep).

Process or thread?

Two processesTwo threads of one process
Created withfork()clone() with CLONE_VM, CLONE_FILES, CLONE_THREAD and more
MemorySeparate, shared copy-on-write at firstOne address space
File descriptor tableCopiedShared
A fatal crashEnds one process, the other keeps runningEnds the whole process
Talk byPipes, sockets, shared memoryOrdinary variables, with locks
In the kernelTwo tasksAlso two tasks, in one thread group

When a process exits it becomes a zombie: the manual defines it as a child that terminated but has not been waited for. The parent gets SIGCHLD and should call wait(). If the parent dies first, the children are adopted by init or by the nearest subreaper. Deeper: the process lifecycle.

Three kinds of kernel context

ContextRuns becauseHas a user program?May sleep?Examples
Process contextA process made a system call or faultedYes, the callerYesread waiting for the disk
Interrupt contextA device raised an interruptNo, it borrows the CPUNoThe network card's handler
Kernel threadThe kernel started it for its own workNoYeskswapd, ksoftirqd/0, kworker
Softirqs, the deferred half of interrupt work, also may not sleep. When there are too many, the ksoftirqd thread of that CPU runs them.

CPU

The scheduler

On a machine with 8 cores there may be 500 tasks, and most of them are asleep. Each CPU has its own run queue of runnable tasks. The scheduler decides which one runs next and for how long, and moves tasks between CPUs when the queues get uneven.

From version 2.6.23 the default was CFS. Its documentation says it models an ideal, precise multi-tasking CPU: each task tracks a virtual runtime, and the task with the smallest one runs next. The tasks are kept in a time-ordered red-black tree. Linux 6.6 began the move to EEVDF, which still uses virtual runtime but also gives each task a virtual deadline and picks the earliest eligible deadline. Nice values range from -20, the highest priority, to 19, the lowest. A higher priority makes a task's virtual clock run slower, so it gets more real time.

Virtual time in a simplified model

Δv=Δt×1024wwA=1024, wB=2048  ⇒  ΔvA=10 ms, ΔvB=5 ms per 10 ms run\Delta v = \Delta t \times \frac{1024}{w} \qquad w_A = 1024,\ w_B = 2048 \;\Rightarrow\; \Delta v_A = 10\ \text{ms},\ \Delta v_B = 5\ \text{ms}\ \text{per 10 ms run}
Our simplified model with our own example weights. B's virtual clock moves half as fast, so to stay level with A it gets two thirds of the CPU and A gets one third.

Voluntary switch

  • The task blocks: waits for a disk, a lock, a socket
  • Shown as cswch/s in pidstat -w
  • Many of them: the task is waiting, not computing

Involuntary switch

  • The task used its time and was preempted
  • Shown as nvcswch/s in pidstat -w
  • Many of them: more runnable tasks than CPUs

A context switch saves one task's registers and loads another's. If the new task is in another process, the CPU also switches to its page tables, and cached address translations and data may be cold for a while. vmstat 1 shows switches per second in the cs column, and /proc/PID/status keeps voluntary and involuntary counts per task. Deeper: CPU scheduling.

Memory

Virtual memory and paging

Every apartment in a block has a flat number 3, but they are different rooms. Every process gets its own virtual address space in the same way: two processes can both use address 0x1000 and mean different bytes of RAM. The CPU translates each virtual address with page tables that the kernel fills in, and keeps recent translations in a cache called the TLB.

How many pages in a gigabyte?

1 GiB4 KiB=230212=218=262,144 pages1 GiB2 MiB=512 huge pages\frac{1\ \text{GiB}}{4\ \text{KiB}} = \frac{2^{30}}{2^{12}} = 2^{18} = 262{,}144\ \text{pages} \qquad \frac{1\ \text{GiB}}{2\ \text{MiB}} = 512\ \text{huge pages}
The kernel docs say the page size depends on the architecture, and that x86 can also map 2M and 1G pages. Bigger pages need fewer translations, so the TLB covers more memory.

Memory is given lazily. malloc or mmap only reserves a range of addresses. The first time the program touches a page, the CPU raises a page fault, the kernel finds a free page, maps it and lets the instruction run again. A minor fault needs no disk: a zeroed page, or file data already in the page cache. A major fault must read from the disk, and the task sleeps meanwhile.

What the kernel does on a page fault

Not allowed means, for example, a write to a read-only page. SIGSEGV stops the program. Anonymous memory is memory not backed by a file, such as the heap and the stack.

When free memory runs low the kernel reclaims pages. The kernel docs describe two ways: the background thread kswapd wakes up and frees pages, or, if that is not enough, the allocating task does direct reclaim itself and stalls. Clean file pages can simply be dropped; dirty ones must be written first; anonymous pages can only go to swap. If nothing can be freed, the kernel invokes the OOM killer, which picks a task to kill to save the rest of the system. Deeper: virtual addresses.

Files in RAM

The page cache

A café keeps the most popular cakes in the glass counter and the rest in the cellar. The page cache is the glass counter: the kernel docs say that whenever a file is read, the data is put into the page cache, so the next read is a memory copy instead of a disk read.

Two reads of the same file

Writes go the other way: a write() copies into the cache and marks the page dirty. Kernel flusher threads write dirty pages to disk later.

Why the hit ratio decides the speed

tˉ=p thit+(1−p) tmissp=0.99: 0.0599 msp=0.90: 0.509 ms\bar t = p\,t_{\text{hit}} + (1-p)\,t_{\text{miss}} \qquad p = 0.99:\ 0.0599\ \text{ms} \qquad p = 0.90:\ 0.509\ \text{ms}
Our own example numbers: a hit costs 0.01 ms and a miss 5 ms. Dropping from 99% to 90% hits makes the average read about 8.5 times slower.

Reading free -m without panic

ColumnMeansCommon mistake
usedMemory programs holdThinking it includes the cache
buff/cachePage cache and kernel buffersCalling it wasted: it is reclaimable and speeds up reads
availableEstimate of memory that can be given out without swappingWatching free instead. Low free is normal on a busy machine

The settings vm.dirty_background_ratio and vm.dirty_ratio set how much dirty data may build up before flusher threads start writing, and before a writing process is made to write itself. echo 3 > /proc/sys/vm/drop_caches frees clean cache pages; the docs call it non-destructive and suggest running sync first, because dirty pages are not freed. Use it only in tests, never to "fix" a production box. Deeper: page cache and writeback.

Files

VFS and file systems

A library catalogue looks the same whether the book is on the first floor or in the annex. The VFS, the virtual file system, is the layer that gives every file system the same interface. The kernel docs describe it as the software layer that provides the file system interface to user space programs. ext4, XFS, a network file system and /proc all plug in under it.

Four objects in the VFS

ObjectKernel docs sayIn plain words
SuperblockRepresents a mounted file systemOne per mount: ext4 on /, tmpfs on /run
InodeRepresents an object in the file systemThe file itself: size, owner, mode, where the data is. No name
DentryCached link from a name to an inodeOne path piece, like etc or hostname. Lookups become fast
FileThe kernel side of a file descriptorOne open: the position and the flags. Two opens give two of these

openat("/etc/hostname") walks the path

A descriptor is just a small number that indexes the process's table. The walk / then etc then hostname is fast when the dentry cache already has each piece.

Because sockets, pipes and terminals also have file objects, the same read() and write() work on all of them. That is the meaning of "everything is a file". It also explains two classic surprises: a deleted file that a process still holds open keeps its disk space until the last descriptor closes, and "Too many open files" is a per-process limit on the descriptor table. Deeper: files and inodes.

Devices

Interrupts and drivers

A driver is the kernel code that knows how to talk to one kind of device. A disk driver turns read requests into commands for the controller. When the device is done, it raises an interrupt, the CPU stops what it was running, and the driver's handler runs.

Handlers must be quick, because the CPU has dropped other work. So interrupt work is split. The top half, the hard IRQ handler, does the minimum: acknowledge the device and note what arrived. The bottom half, usually a softirq, does the rest soon after with interrupts enabled again. The kernel's hacking guide says code in these contexts may not call anything that sleeps. When softirqs pile up, the per-CPU kernel thread ksoftirqd runs them.

A disk read completes

The interrupt borrowed CPU 2 from a task that had nothing to do with the disk. That time shows up as %irq and %soft in mpstat.

/proc/interrupts has one row per interrupt source and one column per CPU, so a single hot column means one CPU is doing all the work. /proc/softirqs shows the deferred kinds: TIMER, NET_RX, NET_TX, BLOCK and others. vmstat 1 counts interrupts per second in the in column, including the timer.

Network

The network stack

A packet arriving at a server travels up the floors of the building, from the network card to the program that reads it. The network card copies the packet straight into memory, into a ring buffer, without the CPU. This is called DMA. Then it raises an interrupt.

One packet, from the wire to nginx

A client sends a packet to the network card of our server. The card writes it by DMA into a ring buffer in the kernel and raises an interrupt, drawn as a dashed orange arrow, to the NAPI poll that runs in a softirq. NAPI takes packets from the ring buffer and passes them to IP and TCP, which put the bytes into the socket queue. nginx in user space reads them with recv, which wakes it.
The dashed orange arrow is the interrupt. After it, NAPI polls the ring for more packets instead of taking one interrupt per packet.
  1. 1

    Interrupt, then polling

    The NAPI docs say the device signals new events with an interrupt, and the host then schedules NAPI to process them, usually in softirq context. NAPI handles up to a budget of packets per poll, so a flood of packets does not mean a flood of interrupts.

  2. 2

    Into the stack

    Each packet is wrapped in an sk_buff. IP checks the address, TCP checks the order and acknowledges, and the bytes join the socket's receive queue.

  3. 3

    Wake the reader

    A task asleep in recv() or in epoll_wait() is woken and copies the bytes out.

  4. 4

    Many queues

    Modern cards have several receive queues. RSS spreads packets across them, so several CPUs share the work. RPS does the same in software.

Sending is the same road downward: send() copies into the socket's send buffer, TCP cuts segments, IP adds headers, the driver hands them to the card, and a later interrupt says that the card has sent them. Deeper: the Linux network path.

Containers

Namespaces and cgroups

A container is not a small virtual machine. It is a group of ordinary processes on the same kernel, given a private view and a budget. Namespaces decide what the group can see. Cgroups decide how much it can use.

Two containers, one kernel

One Linux machine runs container A with web and container B with worker. Each thinks it is PID 1 in its own view. Both send system calls to one shared kernel, where namespaces decide what each sees and cgroups decide what each uses. The cgroups box sends cpu.max to the CPU cores and memory.max to the RAM.
There is no second kernel. Both containers make system calls into the same one.

The namespace types

NamespaceGives the group its own/proc/PID/ns entry
MountSet of mounts: its own root file systemmnt
PIDProcess numbers: its first process is PID 1pid
NetworkInterfaces, routes, ports, firewall rulesnet
UTSHost nameuts
IPCShared memory and message queuesipc
UserUser and group ID mapping: root inside, not outsideuser
CgroupView of the cgroup treecgroup
TimeOffsets for some clocks, added in Linux 5.6time
The eight types in the namespaces manual. Mount namespaces are the oldest: the manual dates them to Linux 2.4.19.

Cgroup v2 has a single hierarchy mounted as type cgroup2, usually at /sys/fs/cgroup. Each directory is a group; its cgroup.procs file lists the processes in it, and controller files set limits. memory.max is a hard limit: if usage reaches it and cannot be reduced, the OOM killer is invoked inside that cgroup. memory.high throttles the group and puts it under heavy reclaim instead. pids.max caps the number of tasks. cpu.max holds a quota and a period, max 100000 by default, which means no limit.

What cpu.max = 50000 100000 means

50,000 μs100,000 μs=0.5 CPU4 busy threads⇒50 ms4=12.5 ms each per 100 ms\frac{50{,}000\ \mu\text{s}}{100{,}000\ \mu\text{s}} = 0.5\ \text{CPU} \qquad 4\ \text{busy threads} \Rightarrow \frac{50\ \text{ms}}{4} = 12.5\ \text{ms each per 100 ms}
The group may run 50 ms per 100 ms period in total, across all CPUs. Four busy threads use the budget up early and then wait for the next period: they are throttled.

Fewer crossings

Blocking, epoll and io_uring

Every trip through the hatch costs a little. A program that reads a file 1 byte at a time makes a million system calls for one megabyte; one that reads 64 KiB at a time makes 16. Servers with thousands of connections face the same question for sockets: how do you wait for many things without one thread, or one system call, per thing?

System calls for one megabyte

1,048,5761=1,048,576 calls1,048,57665,536=16 calls\frac{1{,}048{,}576}{1} = 1{,}048{,}576\ \text{calls} \qquad \frac{1{,}048{,}576}{65{,}536} = 16\ \text{calls}
The data and the disk work are the same. Only the number of crossings changes, and with it the share of system CPU.

Four ways to wait for I/O

WayHow it waitsGood forPrice
Blocking callsread() sleeps until data is thereSimple programs, one thing at a timeOne thread per connection
Non-blockingread() returns at once with EAGAIN if nothing is readyPrograms that do other work meanwhileBusy loops if used alone
epollOne call waits for any of many descriptors to become readyServers with thousands of socketsStill one read per ready socket
io_uringRequests go into a ring shared with the kernel; results come back in anotherMany small I/Os with few crossingsNewer interface, since 5.1; more to learn
epoll's manual calls it an I/O event notification facility. In io_uring a failed request returns minus the error number in its result field.

One thread, many sockets, with epoll

The thread sleeps once for all its sockets and wakes only for the ones that have work.

Windows

/proc, /sys and the kernel log

The kernel publishes what it knows as files. /proc holds one directory per process, named by its PID, plus system-wide files such as loadavg, meminfo and interrupts. /sys describes devices, drivers and cgroups. /proc/sys holds tunables that sysctl reads and writes. None of these files live on a disk: the kernel makes up their content when you read them.

Which file answers which question

FileAnswers
/proc/PID/statusState, threads, memory, context switches of one process
/proc/PID/fd/Every open descriptor, as a link to the file, pipe or socket
/proc/PID/mapsEvery memory mapping with its permissions, including [heap], [stack] and [vdso]
/proc/PID/wchan and stackWhere in the kernel a task sleeps
/proc/PID/ns/Which namespaces the process is in
/proc/loadavg, /proc/pressure/*Load and time lost to waiting
/proc/interrupts, /proc/softirqsInterrupt counts per source and per CPU
/sys/fs/cgroup/Groups, their processes and limits
dmesg or journalctl -kThe kernel log: OOM kills, soft lockups, driver errors

All together

One cat through the whole kernel

Now follow cat /etc/hostname from the moment you press Enter. Each step lights up one box of the map.

cat /etc/hostname, step by step

Every line is a system call or a fault. On a cold cache, the fault and the read each add a disk wait in state D.
Text
$ strace -f -tt -T cat /etc/hostnameexecve("/usr/bin/cat", ["cat", "/etc/hostname"], 0x7ffc... /* 24 vars */) = 0openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3mmap(NULL, 2125824, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f...close(3)                                = 0openat(AT_FDCWD, "/etc/hostname", O_RDONLY) = 3fstat(3, {st_mode=S_IFREG|0644, st_size=6, ...}) = 0read(3, "web-1\n", 131072)             = 6write(1, "web-1\n", 6)                 = 6read(3, "", 131072)                     = 0close(3)                                = 0exit_group(0)                           = ?+++ exited with 0 +++
Written by us to show the shape of real output, trimmed and without the -tt and -T timestamps. Paths, sizes and the loader's calls differ by distribution and version. In strace, -f follows children, -tt adds wall-clock time with microseconds and -T shows the time spent in each call.

Each line, mapped to the kernel

LineSubsystemWhat happened
execveProcesses, memoryThe old program image is replaced; the binary is mapped, not read
openat ld.so.cache, libcVFSThe dynamic loader finds and opens the C library
mmap libcMemoryThe library is mapped; its pages come in by page faults
openat /etc/hostnameVFSPath walk through the dentry cache, new file object, fd 3
read = 6VFS, page cacheCopy from the cache, or sleep in D for the disk
write(1, ...)VFS, terminal driverfd 1 is the terminal, a pipe or a socket: same call
read = 0VFSEnd of file
exit_groupProcessesMemory freed; the parent gets SIGCHLD and reaps with wait

Try it

Commands to run

These are read-only and safe on any Linux machine or container. The outputs below were captured by us on 27 November 2026, on Linux 7.0.14 inside the virtual machine of Docker Desktop on an Arm Mac. Your numbers will differ.

Text
$ uname -r7.0.14-linuxkit$ grep -E '^(Name|State|Threads|VmRSS|voluntary|nonvol)' /proc/self/statusName:	catState:	R (running)VmRSS:	     888 kBThreads:	1voluntary_ctxt_switches:	0nonvoluntary_ctxt_switches:	0$ ls -l /proc/self/fdlrwx------ 1 root root 64 Nov 27 12:03 0 -> /dev/nulll-wx------ 1 root root 64 Nov 27 12:03 1 -> pipe:[1694441]l-wx------ 1 root root 64 Nov 27 12:03 2 -> pipe:[1694442]$ cat /proc/loadavg0.06 0.07 0.03 3/497 12$ cat /proc/pressure/iosome avg10=0.00 avg60=0.00 avg300=0.00 total=21026616full avg10=0.00 avg60=0.00 avg300=0.00 total=20624262$ cat /sys/fs/cgroup/cpu.max /sys/fs/cgroup/memory.maxmax 100000max
The status file describes the process reading it, here cat itself. In loadavg, 3/497 means 3 runnable tasks out of 497. The cgroup files show no CPU or memory limit for this container.
Text
$ ps -eo pid,stat,wchan:20,cmd | head -6  PID STAT WCHAN                CMD    1 Sl   -                    /initd    2 S    -                    [kthreadd]    3 S    -                    [pool_workqueue_release]    4 I<   -                    [kworker/R-rcu_gp]    5 I<   -                    [kworker/R-sync_wq]$ vmstat 1 3procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu------- r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu 0  0      0 826216 222436 5490916    0    0    33    75 1099    0  0  0 100  0  0  0 0  0      0 826632 222436 5490804    0    0     0     4 1160 1497  0  0 100  0  0  0 0  0      0 826632 222436 5490804    0    0     0     0  948 1199  0  0 100  0  0  0
Names in brackets are kernel threads: ps prints the name in brackets when a task has no command line. In vmstat, r is runnable tasks, b is tasks blocked on I/O, in is interrupts and cs is context switches per second. The first line is an average since boot.

Which command answers which question

QuestionCommandLook at
Which kernel is this?uname -r, cat /proc/versionVersion and build
Which system calls, and how slow?strace -c ls, strace -f -T -p PIDCalls, errors, time per call. It slows the target
What state is this process in?cat /proc/PID/status, ps -o stat,wchanState, threads, switches, where it sleeps
Is it faulting or switching a lot?perf stat -e page-faults,context-switches CMDCounts for one command
Where does kernel CPU go?perf top, mpstat -P ALL 1Hot kernel functions, %sys, %irq, %soft
Who handles interrupts?cat /proc/interrupts, cat /proc/softirqsOne hot CPU column
Is something waiting for resources?cat /proc/pressure/{cpu,memory,io}some and full percentages
What can this container see and use?ls -l /proc/self/ns, cat /sys/fs/cgroup/*.maxNamespace IDs, limits

When it breaks

Failure drills

Back to the slow afternoon in the story. A two-second cat could be waiting for a CPU, for a disk, or for a lock. From outside they look the same. The table below gives the check that tells each failure apart from its look-alikes.

Symptom, check, fix

FailureLooks likeCheck that tells it apartFix
Waiting for a CPUSlow, but the program does nothing oddvmstat 1: r above the CPU count; pidstat -w: many nvcswch/s; PSI cpu someFewer busy tasks, more CPUs, or nice the batch work
Waiting for the diskSlow, load high, CPU idleps shows D; vmstat b and wa; iostat -x awaitFind the busy device or the slow network file system
kill -9 does nothingThe process is "hung"STAT is D; read /proc/PID/wchan and /proc/PID/stackFix the I/O it waits for; the signal acts when the wait ends
High system CPU%sys high, little useful workperf top on kernel symbols; strace -c -p PID for the call rateFewer, larger system calls; batching; a kernel fix
Interrupt storm on one CPUOne core at 100%, the rest idleOne hot column in /proc/interrupts; %irq or %soft in mpstat -P ALLSpread queues with RSS or RPS; check irqbalance
Soft lockupMachine stalls, then recovers or panicsdmesg shows a soft lockup: the kernel looped for more than 20 secondsCapture the trace; update the kernel or the driver
OOM killProcess vanished without a log linedmesg OOM report; oom_kill in memory.eventsRaise the limit or fix the leak; set memory.high to slow down first
Load average counts tasks in state R and state D, so a high load with an idle CPU points at waiting, not computing.

Load per CPU

load=40, 8 CPUs, r≈2, b≈38  ⇒  about 38 of the 40 are waiting for I/O\text{load} = 40,\ 8\ \text{CPUs},\ r \approx 2,\ b \approx 38 \;\Rightarrow\; \text{about } 38 \text{ of the } 40 \text{ are waiting for I/O}
Our own example. Load alone said "5 per CPU", but vmstat splits it into 2 runnable and 38 blocked tasks. Look at the disk, not the CPU.

Summary

The whole topic in one minute.

The kernel is the only code that runs with full privilege and touches the hardware. Programs live in user space and enter the kernel in three ways: a system call when they ask, an interrupt when a device needs attention, and an exception when an instruction faults. A crossing has a cost, so programs batch their requests.

Inside, a few subsystems share the work: processes and the scheduler decide who runs on which CPU; the memory manager gives every process its own virtual address space and fills pages on demand; the VFS turns paths into inodes and keeps file data in the page cache; the network stack moves packets between sockets and network cards; drivers handle devices and their interrupts. Namespaces and cgroups turn groups of processes into containers.

Each part has a window: strace for system calls, /proc/PID/status and ps for tasks and states, vmstat and perf for switches and faults, free and /proc/meminfo for memory, /proc/interrupts for devices, ss for sockets, and the cgroup files for limits. When something is slow, find the subsystem first, then use its tool.

  • The kernel is the one privileged program. It owns the hardware and shares it.
  • Three ways in: a system call (asked), an interrupt (a device), an exception (an instruction faulted).
  • Signals are acted on when a task returns to user mode, so a task in D state ignores even SIGKILL until its I/O ends.
  • fork copies with copy-on-write, execve replaces the program, wait reaps the zombie.
  • Each CPU has a run queue. CFS and now EEVDF pick by virtual runtime, weighted by nice.
  • Memory is virtual and lazy: page faults fill pages, the page cache keeps file data, the OOM killer is the last resort.
  • The VFS turns paths into dentries, inodes and file objects. Sockets and pipes are files too.
  • Interrupts do the minimum, softirqs do the rest. Namespaces limit what a container sees, cgroups what it uses.

Sources