How the Linux kernel works
medium 40 minThe 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
1991
Linus Torvalds writes the release notes for Linux 0.01. The notes on kernel.org carry the line "(C) 1991 Linus Torvalds".
9 Oct 2007
Linux 2.6.23 is released with CFS, the Completely Fair Scheduler, which replaces the earlier O(1) scheduler.
24 Jan 2008
Linux 2.6.24 is released. It contains the first control groups, the framework the kernel docs call cgroups.
18 Feb 2013
Linux 3.8 completes user namespaces, so unprivileged users can create namespaces safely.
13 Mar 2016
Linux 4.5 declares the unified cgroup hierarchy, cgroup v2, stable.
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.
5 May 2019
Linux 5.1 merges io_uring, a new interface for asynchronous I/O.
29 Oct 2023
Linux 6.6 starts the move from CFS to a new scheduler called EEVDF.
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.
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.
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
Each subsystem, what it keeps, and how you look at it
| Subsystem | Owns | Key objects | Look with |
|---|---|---|---|
| Processes and scheduler | Who runs, where, for how long | Tasks, run queues | ps, top, pidstat, /proc/PID/status |
| Memory manager | Virtual memory, pages, reclaim | Page tables, page cache, anonymous pages | free, vmstat, /proc/meminfo, /proc/PID/maps |
| VFS and file systems | Paths, files, open file state | Dentries, inodes, file objects, superblocks | ls -l /proc/PID/fd, df, stat |
| Block layer and drivers | Disk requests and devices | Requests to the disk | iostat -x, /proc/interrupts |
| Network stack | Sockets, TCP, IP, packets | Sockets, sk_buff packets | ss, ip, nstat |
| Namespaces and cgroups | What a group sees and uses | Namespace and cgroup files | ls -l /proc/PID/ns, /sys/fs/cgroup |
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.lsmodlists 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 call | Interrupt | Exception | |
|---|---|---|---|
| Who starts it | The program, on purpose | A device: disk, network card, timer | The CPU, while running an instruction |
| In step with the program? | Yes | No: can arrive at any moment | Yes: caused by this instruction |
| Examples | read, write, openat, clone | A packet arrived, a disk read finished, a timer tick | Page fault, divide by zero, invalid instruction |
| Runs in the context of | The calling process | Whatever was running, borrowed briefly | The faulting process |
| May the handler sleep? | Yes, for example waiting for the disk | No | Yes for a page fault that reads from disk |
| Where you see it | strace, perf trace | /proc/interrupts, the in column of vmstat | Page-fault counters in perf stat, /proc/vmstat |
One read() system call
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
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
Save the program's state
Registers are saved, so the program can continue exactly where it stopped.
- 3
Do the work
Run the system call, the interrupt handler or the fault handler.
- 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
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
State letters you will see in ps
| Letter | Meaning | What to think |
|---|---|---|
| R | Running or runnable, on a run queue | Using a CPU or waiting for one |
| S | Interruptible sleep, waiting for an event | Normal for an idle server |
| D | Uninterruptible sleep, usually I/O | Counts in the load average. Signals wait |
| T / t | Stopped by job control / by a debugger | Someone sent SIGSTOP, or a tracer is attached |
| Z | Zombie: exited, not reaped by its parent | Fix or restart the parent so it calls wait |
| I | Idle kernel thread | Normal, ignore it |
Process or thread?
| Two processes | Two threads of one process | |
|---|---|---|
| Created with | fork() | clone() with CLONE_VM, CLONE_FILES, CLONE_THREAD and more |
| Memory | Separate, shared copy-on-write at first | One address space |
| File descriptor table | Copied | Shared |
| A fatal crash | Ends one process, the other keeps running | Ends the whole process |
| Talk by | Pipes, sockets, shared memory | Ordinary variables, with locks |
| In the kernel | Two tasks | Also 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
| Context | Runs because | Has a user program? | May sleep? | Examples |
|---|---|---|---|---|
| Process context | A process made a system call or faulted | Yes, the caller | Yes | read waiting for the disk |
| Interrupt context | A device raised an interrupt | No, it borrows the CPU | No | The network card's handler |
| Kernel thread | The kernel started it for its own work | No | Yes | kswapd, ksoftirqd/0, kworker |
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
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?
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
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
Why the hit ratio decides the speed
Reading free -m without panic
| Column | Means | Common mistake |
|---|---|---|
| used | Memory programs hold | Thinking it includes the cache |
| buff/cache | Page cache and kernel buffers | Calling it wasted: it is reclaimable and speeds up reads |
| available | Estimate of memory that can be given out without swapping | Watching 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
| Object | Kernel docs say | In plain words |
|---|---|---|
| Superblock | Represents a mounted file system | One per mount: ext4 on /, tmpfs on /run |
| Inode | Represents an object in the file system | The file itself: size, owner, mode, where the data is. No name |
| Dentry | Cached link from a name to an inode | One path piece, like etc or hostname. Lookups become fast |
| File | The kernel side of a file descriptor | One open: the position and the flags. Two opens give two of these |
openat("/etc/hostname") walks the path
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
/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
- 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
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
Wake the reader
A task asleep in
recv()or inepoll_wait()is woken and copies the bytes out. - 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
The namespace types
| Namespace | Gives the group its own | /proc/PID/ns entry |
|---|---|---|
| Mount | Set of mounts: its own root file system | mnt |
| PID | Process numbers: its first process is PID 1 | pid |
| Network | Interfaces, routes, ports, firewall rules | net |
| UTS | Host name | uts |
| IPC | Shared memory and message queues | ipc |
| User | User and group ID mapping: root inside, not outside | user |
| Cgroup | View of the cgroup tree | cgroup |
| Time | Offsets for some clocks, added in Linux 5.6 | time |
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
Deeper: namespace views and resource limits.
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
Four ways to wait for I/O
| Way | How it waits | Good for | Price |
|---|---|---|---|
| Blocking calls | read() sleeps until data is there | Simple programs, one thing at a time | One thread per connection |
| Non-blocking | read() returns at once with EAGAIN if nothing is ready | Programs that do other work meanwhile | Busy loops if used alone |
| epoll | One call waits for any of many descriptors to become ready | Servers with thousands of sockets | Still one read per ready socket |
| io_uring | Requests go into a ring shared with the kernel; results come back in another | Many small I/Os with few crossings | Newer interface, since 5.1; more to learn |
One thread, many sockets, with epoll
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
| File | Answers |
|---|---|
/proc/PID/status | State, threads, memory, context switches of one process |
/proc/PID/fd/ | Every open descriptor, as a link to the file, pipe or socket |
/proc/PID/maps | Every memory mapping with its permissions, including [heap], [stack] and [vdso] |
/proc/PID/wchan and stack | Where 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/softirqs | Interrupt counts per source and per CPU |
/sys/fs/cgroup/ | Groups, their processes and limits |
dmesg or journalctl -k | The 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
$ 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 +++Each line, mapped to the kernel
| Line | Subsystem | What happened |
|---|---|---|
| execve | Processes, memory | The old program image is replaced; the binary is mapped, not read |
| openat ld.so.cache, libc | VFS | The dynamic loader finds and opens the C library |
| mmap libc | Memory | The library is mapped; its pages come in by page faults |
| openat /etc/hostname | VFS | Path walk through the dentry cache, new file object, fd 3 |
| read = 6 | VFS, page cache | Copy from the cache, or sleep in D for the disk |
| write(1, ...) | VFS, terminal driver | fd 1 is the terminal, a pipe or a socket: same call |
| read = 0 | VFS | End of file |
| exit_group | Processes | Memory 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.
$ 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$ 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 0Which command answers which question
| Question | Command | Look at |
|---|---|---|
| Which kernel is this? | uname -r, cat /proc/version | Version and build |
| Which system calls, and how slow? | strace -c ls, strace -f -T -p PID | Calls, errors, time per call. It slows the target |
| What state is this process in? | cat /proc/PID/status, ps -o stat,wchan | State, threads, switches, where it sleeps |
| Is it faulting or switching a lot? | perf stat -e page-faults,context-switches CMD | Counts for one command |
| Where does kernel CPU go? | perf top, mpstat -P ALL 1 | Hot kernel functions, %sys, %irq, %soft |
| Who handles interrupts? | cat /proc/interrupts, cat /proc/softirqs | One 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/*.max | Namespace 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
| Failure | Looks like | Check that tells it apart | Fix |
|---|---|---|---|
| Waiting for a CPU | Slow, but the program does nothing odd | vmstat 1: r above the CPU count; pidstat -w: many nvcswch/s; PSI cpu some | Fewer busy tasks, more CPUs, or nice the batch work |
| Waiting for the disk | Slow, load high, CPU idle | ps shows D; vmstat b and wa; iostat -x await | Find the busy device or the slow network file system |
| kill -9 does nothing | The process is "hung" | STAT is D; read /proc/PID/wchan and /proc/PID/stack | Fix the I/O it waits for; the signal acts when the wait ends |
| High system CPU | %sys high, little useful work | perf top on kernel symbols; strace -c -p PID for the call rate | Fewer, larger system calls; batching; a kernel fix |
| Interrupt storm on one CPU | One core at 100%, the rest idle | One hot column in /proc/interrupts; %irq or %soft in mpstat -P ALL | Spread queues with RSS or RPS; check irqbalance |
| Soft lockup | Machine stalls, then recovers or panics | dmesg shows a soft lockup: the kernel looped for more than 20 seconds | Capture the trace; update the kernel or the driver |
| OOM kill | Process vanished without a log line | dmesg OOM report; oom_kill in memory.events | Raise the limit or fix the leak; set memory.high to slow down first |
Load per 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
- Linux manual: syscalls(2)
- Linux manual: syscall(2), calling conventions
- Linux manual: vdso(7)
- Linux manual: signal(7)
- Linux manual: fork(2)
- Linux manual: clone(2)
- Linux manual: execve(2)
- Linux manual: wait(2)
- Linux manual: sched(7)
- Linux manual: /proc/pid/status
- Linux manual: /proc/loadavg
- Linux manual: /proc/pid/stack
- Linux manual: /proc/interrupts
- Linux manual: namespaces(7)
- Linux manual: cgroups(7)
- Linux manual: ps(1)
- Linux manual: vmstat(8)
- Linux manual: strace(1)
- Linux manual: perf-stat(1)
- Linux manual: mpstat(1)
- Linux manual: pidstat(1)
- Kernel docs: memory management concepts
- Kernel docs: the virtual file system
- Kernel docs: CFS scheduler
- Kernel docs: EEVDF scheduler
- Kernel docs: control group v2
- Kernel docs: pressure stall information
- Kernel docs: NAPI
- Kernel docs: network scaling (RSS, RPS)
- Kernel docs: sk_buff
- Kernel docs: unreliable guide to hacking the kernel (contexts)
- Kernel docs: per-CPU kernel threads
- Kernel docs: lockup watchdogs
- Kernel docs: sysctl vm (drop_caches, dirty ratios)
- Kernel docs: x86-64 memory map
- Linux 0.01 release notes
- Kernel Newbies: Linux 2.6.23 (CFS)
- Kernel Newbies: Linux 2.6.24 (cgroups)
- Kernel Newbies: Linux 3.8 (user namespaces)
- Kernel Newbies: Linux 4.5 (cgroup v2 stable)
- Kernel Newbies: Linux 4.20 (PSI)
- Kernel Newbies: Linux 5.1 (io_uring)
- Kernel Newbies: Linux 5.6 (time namespaces)
- Kernel Newbies: Linux 6.6 (EEVDF)
- kernel.org: releases
- GNU Bash manual: shell operation and expansions