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.
What is the difference between paging and swapping? When does a system start swapping, what does a machine under heavy memory pressure look like from the outside, and how does the page cache compete with application memory?
Sample Answer
Direct answer
Paging is how the kernel manages memory in fixed-size blocks called pages (4 KiB on x86-64 and on common arm64 configurations). Every process uses virtual addresses, and page tables (per-process maps maintained by the kernel and walked by the CPU's memory-management unit, the MMU) translate each virtual page to a physical frame of RAM. Swapping is one use of that machinery: the kernel writes pages that have no file behind them (anonymous memory such as the heap, the stack and malloc'd data) to a swap area (a partition or file on disk) so the RAM frame can be reused, and reads the page back through a page fault (the CPU trap taken when a page is not present) if the program touches it again. Older Unix systems swapped whole processes out; Linux swaps individual pages.
Swapping does not begin at some fullness percentage. It begins when the kernel has to reclaim memory and decides that evicting anonymous pages is a better trade than dropping page cache (the in-RAM copy of file contents).
What counts as paging and what counts as swapping
| Kind of page | Examples | When reclaimed | Where it goes |
|---|---|---|---|
| File-backed, clean | program code, shared libraries, read-only data, cached file reads | dropped instantly | nowhere; re-read from the file on the next fault |
| File-backed, dirty | file data written but not yet flushed | written back to its file first | the file |
| Anonymous | heap, stack, malloc, mmap(MAP_ANONYMOUS) | written to swap, only if swap exists | swap area |
Shared-memory and tmpfs pages are the exception to "has a file behind it": they live in memory with no disk file to write back to, so under pressure they are swapped like anonymous pages (and they count as swap use too).
So "paging in" from a file (a program loading its code, an mmapped file) is routine and is not swapping. Swapping is specifically anonymous pages going to, and coming back from, the swap area. With no swap configured, anonymous pages can never be evicted: reclaim can only shrink the page cache, and when that runs out the kernel invokes the OOM killer (the last-resort step that kills a process to free memory).
When the kernel starts reclaiming and swapping
- Free memory is only a buffer. The kernel keeps per-zone watermarks (zones are regions of physical memory, and a watermark is a free-page threshold for each zone: min, low and high). When free pages fall under the low watermark, the background kernel thread
kswapd(the reclaim daemon) wakes and reclaims until free memory reaches the high watermark. The kernel documentation says kswapd is woken when a zone's free pages fall below the low watermark and stops once they are back above the high one, and that below the min watermark an allocation may trigger direct reclaim: the process asking for memory is stalled and made to reclaim pages itself. - In each reclaim pass the kernel chooses between file pages and anonymous pages. The
vm.swappinesssetting (0 to 200, default 60) is documented as the rough relative I/O cost of swapping versus filesystem paging, and at 100 the kernel applies equal pressure to both. A low value does not disable swap; a higher value makes the kernel more willing to swap idle anonymous pages to keep file cache. - If neither pool yields enough, the OOM killer runs.
What a machine under heavy memory pressure looks like from outside
The tell is swap activity (a rate), not swap usage (a total).
vmstat 1(prints one line per second): thesiandsocolumns (KiB per second swapped in and out) stay nonzero for many seconds,wa(CPU time waiting on I/O) climbs whileusandsylook modest, andb(tasks blocked in uninterruptible sleep) rises.- Load average rises while CPU use is not saturated, because tasks are waiting on page-ins, not computing.
/proc/pressure/memory(pressure stall information, PSI; it needs a kernel built withCONFIG_PSI, and some distributions ship it switched off until thepsi=1boot parameter is given, so on such a host the pressure files are unavailable until then) has asomeline (share of time at least one task was stalled on memory) and afullline (share of time all non-idle tasks were stalled at once). Afull avg10that stays at several percent or more for a sustained period (not a brief blip near zero, which healthy hosts show too) is a machine doing little useful work./proc/vmstatcounterspswpin,pswpoutandpgmajfault(major faults, the ones that hit the disk) climb fast;kswapd0shows steady CPU use intop.- Latency tails blow up: ssh logins crawl, health checks time out, and
dmesgeventually showsOut of memory: Killed process ....
What the numbers look like (illustrative values, not from a run). Harmless case, swap holds 2 GiB of cold pages:
procs -----memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 2097152 412000 90000 9100000 0 0 4 12 300 600 5 2 92 1 0
and /proc/pressure/memory reads some avg10=0.00 ... full avg10=0.00. Harmful case, a working set larger than RAM:
3 14 6291456 35000 2000 120000 5200 6100 5300 6200 2500 4000 4 9 20 67 0
and some avg10=62.00, full avg10=48.00. In the second line si and so are thousands of KiB per second, b is 14 blocked tasks and wa is 67%, so the machine is spending most of its time waiting on I/O for memory.
When swap use is harmless: a long-running host has 2 GiB of swap used by idle daemons and a one-off job's cold data, si and so are zero, and PSI memory is near zero. The kernel parked pages nobody touches and gave the RAM to page cache, which is the intended outcome. A large "Swap used" figure is a stock; it is only a problem when the flow (si/so) is sustained or when a latency-critical process's own pages are in swap (Swap: in /proc/PID/smaps).
How the page cache competes with application memory
The page cache is not a fixed reservation. It grows into any RAM the applications are not using, which is why free shows almost no "free" memory on a healthy server. The figure to read is MemAvailable in /proc/meminfo, the kernel's estimate of memory obtainable without swapping, mostly reclaimable cache. In the classic design, cache and anonymous memory sit on separate least-recently-used (LRU) lists (one set for file pages, one for anonymous pages, each split into an active list of recently touched pages and an inactive list of candidates for eviction) and reclaim scans both in proportion set by swappiness. Kernels built with the multi-generational LRU (CONFIG_LRU_GEN, switchable at run time through /sys/kernel/mm/lru_gen/enabled) replace the active and inactive split with age generations, but the file-versus-anonymous balance is still steered by swappiness, so the competition described below happens either way.
Competition appears in two directions:
- Cache pushes out applications. A 20 GiB backup reading through a 16 GiB machine fills the cache with pages used once. Reclaim must free frames for it, and if swappiness is high and the application's anonymous pages look cold, some go to swap and the application stalls when it wakes.
- Applications push out cache. When anonymous memory grows to nearly all of RAM, the cache shrinks until the program's own code and libraries (file-backed pages) are evicted and re-read constantly. The machine is not "swapping" yet it thrashes on file I/O.
Directory and inode caches (dentries: cached directory-entry lookups; inodes: the kernel's per-file records) are tuned separately by vm.vfs_cache_pressure, where lower values keep them longer. For a hard guarantee, use a cgroup (control group) memory limit such as memory.high (a soft limit above which the kernel throttles the group with heavy reclaim) so a batch job's cache and anonymous memory are bounded and cannot evict a neighbour.
Worked example
A 16 GiB machine has 4,194,304 pages of 4 KiB (16 GiB divided by 4 KiB). A database holds 10 GiB of anonymous memory (2,621,440 pages), and 5 GiB of that is idle replicas of old query state. The rest of RAM is page cache.
- A nightly job reads 20 GiB of files once. Cache must grow; free memory dips under the low watermark;
kswapdwakes. - The idle 5 GiB of anonymous pages have not been touched for hours, so they sit on the inactive list and reclaim sends some to swap.
sois nonzero for a minute, then returns to zero. After the job, swap holds a few GiB andsistays at zero. That is harmless. - Now the database grows to 17 GiB of working data on a 16 GiB machine. Every pass over its data faults pages back from swap and evicts others.
siandsostay high together, PSIfullstays at tens of percent, and latency collapses. Adding RAM, shrinking the working set or limiting concurrency fixes this; more swap would only delay the OOM killer.
Trade-offs and pitfalls
- Setting
swappiness=0to "turn swap off" misreads the control: it changes how the balance is struck and does not remove swap, and an OOM kill can still occur. - Treating "free is low" as an alarm. Low free with high
MemAvailableis a healthy cache. - Swap can hold secrets: it stores raw copies of process memory, such as keys or passwords, and the contents can stay on disk after the process exits. Encrypted swap (for example a swap partition under dm-crypt, Linux's disk encryption layer) protects it when the machine is off, and
mlockasks the kernel never to swap given pages. Forensic memory-scanning tools search RAM and swap for such leftovers. - Swap on a latency-critical host can be a net win when it is small and quiet (cold pages leave RAM) and a loss when it is the thing absorbing a working set that does not fit.
During an incident many processes are stuck in the D state, a key service is unresponsive, and CPU usage is low. What does uninterruptible sleep mean in the kernel, why can such tasks not be killed, and what would you check next to find what they are waiting on?
Sample Answer
What the D state means. Every task (a process or thread) the kernel schedules has a state. R is running or runnable, S is an interruptible sleep (waiting for something, and a signal can wake it), and D is uninterruptible sleep (the kernel flag is TASK_UNINTERRUPTIBLE; ps documents it as "uninterruptible sleep (usually I/O)" and proc(5) as "uninterruptible disk sleep"). A task in D has told the scheduler "do not run me until the event I am waiting for happens". It is off the CPU, so it uses no CPU time. That is why your service is dead while CPU usage is low.
Why it cannot be killed. A signal, including SIGKILL, is only acted on when the task is woken and about to return to user space. An uninterruptible sleep is not woken by signals, so kill -9 just leaves SIGKILL pending. It is delivered the moment the awaited event arrives, and never if the event never arrives. The design exists because kernel code in the middle of an operation (holding a lock, with a disk or network request in flight that will write into a buffer when it completes, halfway through a filesystem update) often cannot safely abort. Applications also assume that file I/O is not interrupted by signals. Linux added a middle state, TASK_KILLABLE (merged in 2.6.25), where only a fatal signal ends the sleep. The NFS client was the first code converted, but any wait that still uses the plain uninterruptible sleep stays unkillable. Two consequences: the task is not a zombie (Z, already dead, waiting for its parent to collect it), and for a plain uninterruptible wait (a request to a hung disk or a stuck driver) you cannot fix this by killing it; you must make the wait end. The wait name can tell you which kind you have: a wchan ending in _killable (such as the NFS ones below) means kill -9 will work even though ps shows D (a killable wait need not carry that suffix; the kernel_clone wait in the demo below is killable too). That matters for NFS: since 2.6.25 a hard-mounted NFS task waiting on a dead server sleeps in the killable form (nfs_wait_bit_killable and rpc_wait_bit_killable return -ERESTARTSYS when a fatal signal is pending in kernel source), so kill -9 normally clears those, although the mount itself stays hung and new tasks that touch it will pile up again.
Why load is high with idle CPUs. Linux's load average counts tasks that are runnable (R) plus tasks in D (the kernel adds the running and uninterruptible task counts in kernel/sched/loadavg.c). Fifty tasks stuck in D push load to 50 while the CPU sits idle. A high load with low CPU utilisation is a strong hint that you have a D-state pile-up, not a compute problem.
What I would check, in order.
- Count and identify the stuck tasks, and whether they share a wait location:
ps -eo pid,stat,wchan:32,comm | awk 'NR==1 || $2 ~ /^D/'
wchan (wait channel) is the name of the kernel function where the task sleeps. If forty tasks all show the same NFS or block-layer function (the block layer is the kernel code between file systems and storage devices), you have one root cause. Illustrative output (not from a run) of a pile-up behind a dead NFS server; these waits are killable, so kill -9 would remove those processes, while the same pile-up behind a hung disk would show block-layer or driver wait functions that ignore it:
PID STAT WCHAN COMMAND
2210 D nfs_wait_bit_killable java
2214 D nfs_wait_bit_killable java
2301 D rpc_wait_bit_killable rsync
... 37 more lines, 36 of them nfs_wait_bit_killable ...
One function name repeated across nearly every line says the tasks are waiting on one thing, so the next step is that thing (the NFS mount), not each process.
- Get the full kernel stack of one or two of them (needs root, and a kernel built with CONFIG_STACKTRACE, the option that lets the kernel record call stacks, per proc_pid_stack(5)):
cat /proc/<pid>/wchan; echo
cat /proc/<pid>/stack
Read it bottom to top: the bottom is the system call the application made (read, write, fsync, open), the top is where it is parked. Frames like nfs_* or rpc_* mean an NFS server or network stall, io_schedule (the kernel function that puts a task to sleep until its I/O finishes) under a filesystem function means waiting for a block device, a driver function means a hung device. A stuck NFS read might look like this illustrative stack (top frame first):
[<0>] rpc_wait_bit_killable+0x1c/0x60
[<0>] nfs_wait_on_request+0x40/0x90
[<0>] nfs_file_read+0x88/0xd0
[<0>] vfs_read+0x9c/0x1a0
[<0>] __x64_sys_read+0x1a/0x30
The bottom line is the read system call, the middle shows the NFS client, and the top shows it parked waiting on the RPC (remote procedure call) reply from the server.
- Dump all blocked tasks at once, including stacks, to the kernel log:
echo w > /proc/sysrq-trigger # sysrq ('magic SysRq', a kernel debugging interface, needs CONFIG_MAGIC_SYSRQ) 'w' = dump tasks in uninterruptible state
dmesg | tail -200
Also search dmesg for "blocked for more than ... seconds". The hung-task detector (a kernel watchdog thread that periodically looks for tasks stuck in D; it exists only in kernels built with CONFIG_DETECT_HUNG_TASK, which most distribution kernels enable) prints that warning with a stack for a task stuck in D longer than kernel.hung_task_timeout_secs (check your value with sysctl; 0 disables it). It skips tasks in the killable form of D (a comment in kernel/hung_task.c reads "skip the TASK_KILLABLE tasks -- these can be killed"), so a pile-up behind a hard NFS mount, whose waits are killable, can raise the load average without any such warning, while a plain uninterruptible wait (a hung disk or driver) does produce one.
-
Follow the stack to the resource. For storage:
iostat -x 1(is one device at 100% utilisation with a growing queue,aqu-sz, or is it at zero throughput because requests are not completing? Illustrative bad sign:%util100 withr/sandw/snear 0 andaqu-szlarge),dmesgfor SCSI/NVMe resets, timeouts and multipath path failures (multipath means one disk reachable over several network or cable paths, and a failure of all paths stalls I/O), andlsblk/cat /proc/mountsfor the device. For NFS:grep nfs /proc/mountsto seehardorsoft, then check whether the server answers (ping;rpcinfo -p <server>, which lists the server's RPC services and hangs or errors if it is unreachable;nfsiostat, which shows per-mount operation counts and round-trip times, so a mount with requests outstanding and no replies is stalled). With the defaulthardmount (retry forever; the alternativesoftgives up and returns an error after a timeout), NFS requests are retried indefinitely (nfs(5)), so a dead server freezes every task that touches the mount, silently, until it returns. For a driver hang:dmesgaround the first error, and the stack's top function names the driver. -
Find the common trigger: what changed just before the first stuck task (a storage failover, a network switch change, a server reboot, a full RAID rebuild (RAID: several disks combined into one volume), a new kernel module)? Look at the timestamp of the oldest
blocked for more thanmessage, when the waits are of the kind that produces one.
Fix. Restore the thing being waited on (bring the NFS server or the network path back, fix or fail over the storage path, reset the device). As soon as the awaited event completes, the tasks wake and any pending SIGKILLs are acted on, so stuck tasks usually disappear on their own. For tasks stuck on a dead NFS server specifically, kill -9 on the killable waits frees the processes without waiting for the server, but the mount keeps hanging every new access until it is fixed or detached. If the server is gone for good, a forced or lazy unmount (umount -f forces it; umount -l detaches the mount point immediately and cleans up later) can detach the mount, but be careful: it can lose unwritten data, and a task already blocked in the kernel may stay stuck. A reboot is the last resort. A soft NFS mount avoids the freeze but, as nfs(5) warns, can cause silent data corruption, so I would choose it only where responsiveness matters more than data integrity. For the service itself, put timeouts and a health check that does not touch the suspect mount, so the load balancer drains the node while you repair it.
A reproducible D state. This program parks itself in a killable D wait with vfork() (a variant of fork where the parent is suspended until the child execs or exits, because the child borrows the parent's memory) and has a monitor process look at it from outside. It is the easiest D state to produce safely on a laptop; it is a stand-in for the mechanics, and real incidents look like the NFS examples above.
// dstate.c: park a process in a killable D-state wait and look at it from outside.
// Build: gcc -O2 -Wall -Wextra dstate.c -o dstate Run as root (needed for /proc/<pid>/stack)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void) {
char pid[32];
snprintf(pid, sizeof pid, "%d", (int)getpid());
if (fork() == 0) { // monitor: inspects the parent while it is stuck
sleep(1);
execl("/bin/sh", "sh", "-c",
"ps -o pid,stat,wchan:32,comm -p $0; grep State /proc/$0/status; "
"echo \"wchan: $(cat /proc/$0/wchan)\"; head -3 /proc/$0/stack; "
"kill -KILL $0; sleep 0.2; ps -p $0 >/dev/null && echo still-there || echo gone-after-SIGKILL",
pid, (char *)NULL);
_exit(127);
}
if (vfork() == 0) { // the parent is suspended until this child execs or exits
sleep(5);
_exit(0);
}
return 0;
}
Built and run as root in a --privileged gcc:14 container on arm64 (/proc/<pid>/stack needs root and CONFIG_STACKTRACE; without root the head line fails with Permission denied while the first three views still work), it prints the following, apart from the PID and a Killed notice from the shell:
PID STAT WCHAN COMMAND
15 D kernel_clone dstate
State: D (disk sleep)
wchan: kernel_clone
[<0>] kernel_clone+0x1a0/0x430
[<0>] __arm64_sys_clone+0x64/0x98
[<0>] do_el0_svc+0x70/0xd0
gone-after-SIGKILL
This shows what the three views look like (ps STAT D, /proc/<pid>/status "disk sleep", the stack with the system call at the bottom). Note that "disk sleep" is just the label for D and this wait involved no disk. This particular wait is killable, so kill -KILL removes the process at once (gone-after-SIGKILL). A true TASK_UNINTERRUPTIBLE wait, such as a request outstanding to a hung disk or a driver stuck in the kernel, would ignore it, and a dead NFS server is not reproduced here.
A kernel module fails to load with an 'invalid module format' error, and another causes an oops soon after loading. What does each symptom tell you about how modules bind to a running kernel, and how do you isolate the cause?
Sample Answer
Background: what a module is. A loadable kernel module is a compiled object file (.ko, an ELF file) that the running kernel links into itself at load time. It runs in kernel mode with full privilege and calls kernel functions directly, with no stable binary interface protecting it (the kernel's internal API and data layouts change between versions and even between build configurations). So loading has two jobs: check that this module was built for this kernel, and resolve its references to kernel symbols. The two symptoms in the question fail at different points in that process.
Symptom 1: 'invalid module format' at load time = the kernel refused the module before running any of its code.
The load fails with ENOEXEC, which insmod prints as 'Invalid module format' (modprobe prints the plain C-library text for the same error, 'Exec format error'). The init_module man page lists the image not being a valid ELF file, or being for a different architecture, as ENOEXEC causes, and adds that the flags described below, which ask the kernel to skip the version checks, also end in ENOEXEC unless the kernel was built with CONFIG_MODULE_FORCE_LOAD. The kernel source (kernel/module/main.c and version.c, checked at v6.12) also returns ENOEXEC when the version magic string does not match and when the check of the module_layout symbol's checksum (a checksum of the layout of the kernel's struct module) fails. A checksum mismatch on any other symbol the module imports fails differently: the kernel logs disagrees about version of symbol <name> and returns EINVAL, which insmod shows as 'Invalid parameters' (modprobe shows 'Invalid argument') rather than 'Invalid module format'.
- Version magic (
vermagic): a string compiled into the module with the kernel version and prominent build features (SMP, preemption model and similar). The kernel compares it with its own and refuses the module on a difference. How much of the string is compared depends onCONFIG_MODVERSIONS: when the module carries symbol checksums (next bullet), the kernel-release word at the start is skipped (same_magic()inkernel/module/version.ccomments that the first part is the kernel version, which is ignored if the module has checksums) and only the feature words (SMP, preempt, mod_unload, modversions, architecture and similar) must match; withoutCONFIG_MODVERSIONSthe release must match as well. So a module built for 6.1.x and loaded on 6.5.x with modversions on usually fails the next check instead. - Symbol versioning (
CONFIG_MODVERSIONS): each exported kernel symbol has a checksum of its prototype (recorded in theModule.symversfile produced by the kernel build). The module records the checksums it was built against; if a function's signature or a struct it uses changed, the checksum differs and the load is refused (withENOEXECformodule_layout,EINVALfor other symbols, as above). This catches an ABI (binary interface) change even when the version string matches, for example the same version with a different config, and it is what normally rejects a module left over from an older kernel release when modversions is on.
The man page also describes flags that ask the kernel to skip each check (MODULE_INIT_IGNORE_VERMAGIC,MODULE_INIT_IGNORE_MODVERSIONS). Forcing a load past a real mismatch is the trap that produces Symptom 2. It is only possible on a kernel built withCONFIG_MODULE_FORCE_LOAD(the kernel then taints itself withF); on other kernels the force flags simply fail withENOEXEC.
Illustrative artifacts (the exact wording varies by kernel version). The shell shows only insmod: ERROR: could not insert module mydrv.ko: Invalid module format. The detail is in the kernel log:
$ dmesg | tail -2
mydrv: version magic '6.1.0-13-amd64 SMP preempt mod_unload modversions ' should be '6.1.0-13-amd64 SMP mod_unload modversions '
Read it as: the module was built for a kernel with the preempt feature and the running kernel (same release) was built without it, so the version-magic check failed and none of the module's code ran. The kernel release is the same in both strings; with modversions in them it would not have been compared anyway. The typical failure after upgrading from 6.1 to 6.5 with an old .ko is the symbol-version one instead, which logs a line like mydrv: disagrees about version of symbol module_layout, meaning the feature words matched but a checksum did not. For module_layout insmod reports 'Invalid module format'; for a different symbol name the same log line appears but insmod reports 'Invalid parameters'.
$ modinfo mydrv.ko | grep -E 'vermagic|license'
vermagic: 6.1.0-13-amd64 SMP preempt mod_unload modversions
license: GPL
vermagic is the version-magic string stored in the file. Compare it with uname -r.
Isolating symptom 1 (ordered checks)
dmesg | tailright after the failed load. The kernel normally logs more detail than the one-line user-space message; read it for which check failed.- Compare the two strings:
uname -rversus the version magic string embedded in the module file (modinfo <file>.koprints the module's attributes; look for thevermagicline, and compare it with the kernel's own version). WithCONFIG_MODVERSIONSthe kernel does not compare the release word, so a matching release does not rule out a checksum failure, and the feature words (SMP, preempt and so on) must match as well. - Confirm the target architecture: a module built on one CPU architecture will not load on another.
- Check that the build used the right tree: the kernel documentation builds an external module against the running kernel with
make -C /lib/modules/$(uname -r)/build M=$PWD, which needs the matching headers and build files installed. A module built against headers of a different version or config is the typical cause. - If
CONFIG_MODVERSIONSis on, the build must have used theModule.symversof the full build of the running kernel; the documentation notes that a bare prepared tree does not produce it.
Remedy for symptom 1: build against the running kernel and keep it matching. After every kernel update the old .ko no longer matches. A framework such as DKMS (Dynamic Kernel Module Support) keeps the module source registered and automates building and installing it for each installed kernel; verify after a kernel update that the new kernel got a freshly built module before rebooting into it. Do not use the ignore-version flags as a production fix.
Symptom 2: the module loaded and an oops (the kernel's report of an illegal operation in kernel mode) appears shortly after = the checks passed, so the kernel ran your code and the code (or its assumptions) is wrong.
Two families of cause:
- The module's own bug: a NULL or dangling pointer, an out-of-bounds write, using a freed object, sleeping in a context where sleeping is not allowed (interrupt context), or bad error-path cleanup in the init function.
- A hidden mismatch the checks missed: the module was force-loaded, or built with a different config than the running kernel, so a struct has different field offsets than the module assumes. Code reading a field at the wrong offset crashes at a seemingly unrelated place.
An illustrative oops, annotated:
BUG: kernel NULL pointer dereference, address: 0000000000000010
#PF: supervisor read access in kernel mode
RIP: 0010:mydrv_read+0x1a/0x90 [mydrv]
CPU: 2 PID: 1234 Comm: cat Tainted: G O 6.1.0-13-amd64 #1
Call Trace:
vfs_read+0x9b/0x1a0
Line 1 says what happened: a read from address 0x10, which is a small offset from a NULL pointer (a field 16 bytes into a structure whose pointer was NULL). The RIP line (the instruction pointer, the address of the instruction that faulted) names the function mydrv_read, byte offset 0x1a into it, inside a function 0x90 bytes long, in module mydrv. The Tainted: G O field says no proprietary module has been loaded (G: every loaded module declares a GPL-compatible licence) and an out-of-tree module is loaded (O); a proprietary module would show P instead of G. A kernel built with CONFIG_MODULE_SIG (as Debian's is) also sets E for an unsigned module, so a real report from such a kernel would normally show E next to the O as well. The call trace shows mydrv_read was called from vfs_read, so a read() on a device file triggered it. A concrete scenario: after a forced load, a structure's field moved, so the module read a stale offset; the oops then points at a plausible-looking line in a function you never changed. If the taint letters include F, suspect that first.
Isolating symptom 2 (ordered checks)
- Read the first lines of the oops in
dmesg: the message type (the kernel documentation's example oops for a NULL pointer showsBUG: unable to handle kernel NULL pointer dereference at (null), and current x86 kernels printBUG: kernel NULL pointer dereference, address: <address>as in the example above; the address shows how far from zero the access was), the instruction pointer (RIPon x86-64) giving function name plus offset, the module name in brackets, and the call trace. - Check taint flags in the report (taint is the kernel's record of anything that makes a report less trustworthy):
P(proprietary module),O(out-of-tree module, built outside the kernel source tree),F(force-loaded),E(unsigned module).Fpoints straight at a forced mismatch. The kernel docs note that reports from tainted kernels are often ignored by kernel developers, so reproduce on a clean kernel where possible. - Translate the crash address into a source line: with a
.kobuilt with debug info,addr2line(turns an address in a binary into a source file and line) orobjdump -dl(disassembles the module and interleaves source lines) against the module, or the kernel'sdecode_stacktrace.shscript (which rewrites an oops so eachfunction+offsetshows its source line, and needsCONFIG_DEBUG_INFO, the build option that keeps debug information). For exampleaddr2line -e mydrv.ko -f mydrv_read+0x1aprints a file and line. Often the line is a dereference of a pointer you can then reason about. - Reduce: does it crash on load, on first open, or under load? Load with the init function's later steps disabled, bisect your own commits, and try the same
.koon a kernel it was built for. - Add instrumentation: a kernel built with KASAN (kernel address sanitiser, a debug mode that tracks which memory is valid and reports bad accesses at once) catches use-after-free and out-of-bounds in module code at the faulting access instead of later.
Putting the two together: symptom 1 says the binding check failed, so the module and kernel disagree on version or interface; symptom 2 says binding succeeded and the problem is in behaviour. If symptom 2 started after you forced a load or after a kernel update with a stale .ko, treat it as symptom 1's root cause in disguise: rebuild against the exact running kernel and retest before debugging the code.
A process shows a virtual size of 40 GB but a resident size of 600 MB. What is a virtual address space, how does it differ from physical memory, how does it isolate processes, and when is a huge virtual size nothing to worry about?
Sample Answer
What a virtual address space is. Every process gets its own private numbering of memory, starting near 0 and running up to a limit set by the CPU (48 bits on common x86-64 Linux, which is 256 TiB of addresses in total: the lower 128 TiB is user space and the upper 128 TiB is reserved for the kernel, so a process can use up to 128 TiB). These are virtual addresses. Physical memory (RAM) is the real chips, numbered by physical addresses. The kernel (the privileged core of the OS) plus the CPU's MMU (memory management unit, the hardware that translates addresses) connect the two with page tables: per-process maps from fixed-size chunks of virtual memory (pages, usually 4 KiB) to chunks of RAM (frames). A virtual page with no entry, or an entry marked not-present, is simply not backed by anything.
How it differs from physical memory. The address space is a promise of addresses, not a purchase of RAM. Pages are backed lazily: the first touch of an unbacked page raises a page fault (a CPU exception that hands control to the kernel), and the kernel then picks a free frame and fills in the page table. So the virtual size can far exceed RAM, and pages can live in RAM, in a file, in swap, or nowhere yet.
How it isolates processes. Process A's page table contains no entries pointing at process B's private frames, so A has no address that can name them. Each entry also carries permission bits (user/supervisor, read/write, no-execute), and kernel memory is marked supervisor-only, so a user-mode access to it faults. Sharing is deliberate: two page tables point at the same frame (shared libraries, shared memory).
Reading "VSZ 40 GB, RSS 600 MB". VSZ (the VmSize line in /proc/<pid>/status) is the total size of all mapped virtual ranges. RSS (resident set size, VmRSS) is how much of that is currently in RAM. The gap is address space that is mapped but not touched. In the program, PROT_NONE means no access of any kind is permitted, so nothing needs to be backed or charged, and MAP_NORESERVE asks the kernel not to count the mapping against its commit limit (explained below). Here is a program that makes the gap on purpose (it ran on a Linux aarch64 container built from gcc:14; gcc vsz.c -o vsz && ./vsz):
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
static void show(const char *label) {
FILE *f = fopen("/proc/self/status", "r");
char line[256];
printf("%s:", label);
while (fgets(line, sizeof line, f)) {
if (!strncmp(line, "VmSize:", 7) || !strncmp(line, "VmRSS:", 6)) {
line[strcspn(line, "\n")] = 0;
printf(" %s", line);
}
}
printf("\n");
fclose(f);
}
int main(void) {
const size_t GB = 1UL << 30, MB = 1UL << 20;
show("start");
/* 39 GB reserved address space, no access, no memory behind it */
char *arena = mmap(NULL, 39 * GB, PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (arena == MAP_FAILED) { perror("mmap arena"); return 1; }
show("after 39 GB PROT_NONE reserve");
/* 600 MB of real, touched memory */
char *hot = mmap(NULL, 600 * MB, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (hot == MAP_FAILED) { perror("mmap hot"); return 1; }
show("after 600 MB mapped, untouched");
memset(hot, 1, 600 * MB);
show("after touching all 600 MB");
return 0;
}
start: VmSize: 2280 kB VmRSS: 1284 kB
after 39 GB PROT_NONE reserve: VmSize: 40896744 kB VmRSS: 1284 kB
after 600 MB mapped, untouched: VmSize: 41511144 kB VmRSS: 1284 kB
after touching all 600 MB: VmSize: 41511144 kB VmRSS: 615684 kB
The 39 GiB reservation added 40,894,464 kB to VmSize and nothing to RSS. Mapping 600 MiB added 614,400 kB to VmSize and still nothing to RSS. Only writing to the pages moved RSS by the same 614,400 kB (1,284 to 615,684). That is the 40 GB versus 600 MB picture.
When a huge VSZ is nothing to worry about. Two common harmless sources:
- Reserved but untouched arenas and stacks. Runtimes reserve big virtual ranges up front and fill them slowly, so the address space can grow later without moving anything:
- a JVM reserves its maximum heap;
- Go reserves arena address space;
- glibc gives each thread a malloc arena (a private region its allocator carves memory from) that reserves 64 MiB of address space on 64-bit;
- every thread has a stack (8 MiB default limit) of which a few KiB are touched.
Fifty threads can add gigabytes of VSZ and almost no RSS.
- File mappings. A mapped 30 GB database file or a set of shared libraries counts toward VSZ, but only the pages actually read are resident, and those pages sit in the page cache (the kernel's in-RAM copy of file contents). They are "clean" (identical to the file on disk), so under memory pressure the kernel can simply drop them and re-read them from the file later.
When it does matter. Watch RSS growing steadily (a leak), RSS plus swap (disk space used as overflow for RAM) against the container's memory limit, and the commit charge (the total of address space the kernel has promised can be backed by RAM or swap). Terms: a cgroup is the Linux feature that caps and accounts a group of processes, which is how containers get memory limits; cgroups count resident memory and page cache, not VSZ. The OOM killer is the kernel's last resort when memory runs out: it kills a process.
The overcommit mode (/proc/sys/vm/overcommit_memory) decides how strictly the commit charge is enforced:
- Mode 0 (heuristic, the default). Per the kernel documentation, "obvious overcommits of address space are refused". In the kernel source a single request is refused when it is larger than total RAM plus total swap. So a 40 GB writable private mapping fails on a 16 GB host with no swap, while the demo's 39 GB reservation succeeds because a
PROT_NONEmapping cannot be written and so is not charged (the kernel docs list read-only private anonymous mappings as costing nothing). - Mode 1. Always allow.
- Mode 2 (strict accounting, per
proc_sys_vm(5)). The kernel enforces aCommitLimitof swap plus a percentage of RAM (50% by default, set byvm.overcommit_ratio), shown in/proc/meminfo. Example: 16 GiB RAM and 8 GiB swap give 8 + 0.5 x 16 = 16 GiB, so a 40 GiB writablemmapis refused withENOMEM. Mode 2 ignoresMAP_NORESERVE.
ulimit -vsetsRLIMIT_AS(a per-process cap on total address-space size), which makes VSZ a real limit and breaks runtimes that reserve generously. In this container/proc/sys/vm/overcommit_memorywas 1, so the demo does not show a refusal; the mode 0 and mode 2 behaviour comes from the kernel documentation and source, not from this run.
Triage order for an alert on this process: compare RSS trend over time, check the cgroup limit, then pmap -x <pid> or /proc/<pid>/smaps to see which mappings hold the resident pages.
A machine powers on, the bootloader menu appears, but the system never reaches a login prompt and the screen is nearly silent. Given what you know of the boot stages, how do you work out which stage failed and what do you check at each?
Sample Answer
Direct answer
Seeing the bootloader menu already tells you the early stages worked: the firmware (UEFI or BIOS, the code that starts the machine) found a disk, ran the bootloader, and the bootloader drew its menu. The failure is in a later stage, and the job is to find which one by making the machine talk, then reading where its output stops. The stages after the menu are: (1) the bootloader loads the kernel image and an initramfs (a small in-memory root filesystem with early tools and drivers) into RAM and starts the kernel; (2) the kernel decompresses and initialises itself; (3) the kernel runs /init from the initramfs, which loads storage drivers, assembles RAID (several disks combined into one device) or LVM (Linux's logical volume manager, which carves flexible volumes out of disks), unlocks encryption and finds the real root filesystem; (4) the kernel switches to the real root and starts PID 1 (the first process, usually systemd); (5) PID 1 starts services until a login prompt appears. A nearly silent screen usually means the quiet option hides the messages or the console points at the wrong device, so the first move is to turn the output on.
Step 1: make it loud (one-time edit, nothing persisted)
At the bootloader menu, edit the kernel line for this boot only (in GRUB, press e) and:
- Remove
quiet(documented as disabling most log messages) and any splash option; for systemd's own messages also addplymouth.enable=0(Plymouth is the graphical boot splash; this turns it off so text messages show). - Add
ignore_loglevel, which the kernel docs describe as printing all kernel messages to the console. - Point the console at where you are looking:
console=tty0for the screen, orconsole=ttyS0,115200for a serial or virtual-machine console. The kernel docs listearlycon=andearlyprintk=for output before the normal console exists; theearlyprintkentry says it is "useful when the kernel crashes before the normal console is initialized".earlyprintk=is only available on some architectures (x86, 32-bit Arm, s390 and others); on arm64 useearlycon(with no value it takes the console from the device tree or ACPI SPCR table). - If the kernel seems to die in early init, add
initcall_debug(an initcall is one of the kernel's start-up functions, run in a fixed order during boot), which traces each initialisation function as it runs and is "useful for working out where the kernel is dying during startup".
Reboot with this edit and note the last thing printed. Where output stops identifies the stage.
Step 2: map the last message to a stage
| Last output | Stage that failed | What to check |
|---|---|---|
Nothing after the bootloader says it is loading the kernel and initramfs, or after Booting the kernel | Kernel did not start or has no working console (stage 1 or early 2) | try earlycon/earlyprintk and a different console=; boot the previous kernel entry from the menu; look for an unsupported kernel/hardware combination, a corrupted or truncated image in /boot (a full /boot during an update is a common cause), Secure Boot rejecting an unsigned kernel or module |
| Kernel messages scroll, then stop at an initcall | Stage 2, a driver or hardware init hangs | the last line from initcall_debug names the function; skip the offending driver with initcall_blacklist=<function name> (for a driver built into the kernel) or module_blacklist=<module> (for a loadable module the kernel loads); both are kernel parameters, whereas modprobe.blacklist=<module> is read by user-space modprobe and so only helps for modules loaded later, for example from the initramfs, not for a hang inside a built-in initcall; or boot a different kernel |
Messages then a wait: waiting for device ... to appear, a timeout, or a dracut/initramfs emergency prompt (dracut is the tool Red Hat-family systems use to build the initramfs) | Stage 3: initramfs cannot find or open the root device | the root= UUID or label is wrong or stale; the disk driver (NVMe, virtio, RAID controller) is missing from the initramfs; an LVM volume or encrypted device is not activated. In the emergency shell, ls /dev/disk/by-uuid, lsmod, dmesg searched for nvme, sd or virtio lines. Slow devices may need rootwait, documented as waiting indefinitely for the root device |
Kernel panic - not syncing: VFS: Unable to mount root fs on ... (the kernel source also prints Cannot open root device with a list of available partitions) | Stage 3 to 4: the kernel could not mount root | root device missing, no driver for the disk or the filesystem type built in or in the initramfs, wrong root= or rootfstype= (the filesystem type to expect on the root device, such as ext4) |
Failed to execute /init or No working init found. Try passing init= option to kernel | Initramfs or root has no runnable init | the initramfs is empty or corrupt (rebuild it); rdinit= selects a different program to run from the initramfs (the ramdisk) in place of /init, init= overrides the real-root init; the kernel tries /sbin/init, /etc/init, /bin/init, /bin/sh in turn |
Root mounted, then A start job is running for ... or a drop to emergency mode | Stage 5: a systemd unit or an /etc/fstab mount failed | boot with systemd.unit=rescue.target (a systemd option that boots to a minimal single-user mode instead of the normal target) or emergency, systemd.log_level=debug systemd.log_target=console; check journalctl -xb and fstab entries for missing devices (nofail for non-critical mounts) |
| Login prompt never appears but the system is up | Display manager or getty failure | other virtual terminal (Ctrl+Alt+F2), ssh, systemctl status of the display manager |
The kernel's built-in panic strings and init search order come from its init/do_mounts.c and init/main.c sources; panic= (with a positive number of seconds) makes a crashed machine reboot after a delay, and panic=0 waits forever, so use it to capture the message rather than losing it to an instant reboot.
Step 3: separate "new" from "old"
- If it worked yesterday, boot the previous kernel from the menu. If that boots, the new kernel or its regenerated initramfs is the culprit (missing driver, wrong module set, interrupted update).
- If an old kernel fails too, suspect the disk, the filesystem,
/etc/fstabor the bootloader configuration, not the kernel. - Boot rescue media and check
dmesgfor I/O errors, runfsckon an unmounted root, and inspect the initramfs contents (lsinitrdon dracut-based systems,lsinitramfson Debian and Ubuntu). - If the machine got far enough to write logs,
journalctl -b -1shows the previous boot, provided the journal is persistent.
Worked example
A server updated its kernel yesterday and now stops after the GRUB menu with a blank screen. Edit the entry: remove quiet, add ignore_loglevel and console=ttyS0,115200 (this server's console is a serial line; on a physical screen use console=tty0 instead). Output now reaches the initramfs and then stalls with a message of the form Warning: /dev/disk/by-uuid/... does not exist followed by Entering emergency mode (on Debian and Ubuntu the equivalent is ALERT! /dev/disk/by-uuid/... does not exist. Dropping to a shell!). The previous kernel boots fine. In the emergency shell ls /dev/disk/by-uuid is empty and lsmod shows no nvme or virtio_blk. Diagnosis: stage 3, the new initramfs lacks the storage driver (the disk controller module), so /init ran but never saw the root disk. Fix: boot the old kernel, regenerate the initramfs, confirm the driver is listed inside it (lsinitrd | grep nvme), and test the new entry before deleting the old one.
Variant to tell apart: if the screen instead ends at Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) (block device number 0,0, meaning no real disk was identified as root), the kernel never got a working initramfs to run, typically because the new image is missing, zero-length or truncated after an interrupted update or a full /boot, or because the initrd line is absent from the bootloader entry. The fix path is the same (boot the old entry, rebuild the initramfs) but the check is different: compare the image's size in /boot and the entry's initrd line, not the driver list.
Trade-offs and pitfalls
- Debug options such as
ignore_loglevelandinitcall_debugare noisy and slow a boot; use them to find the stage, then remove them. - Do not start by reinstalling the bootloader. If the menu appears, the bootloader works.
- Recovery commands (rescue shells, repairing GRUB) matter only after the failing stage is known; naming the stage first prevents fixing the wrong layer.
Unlock Full Question Bank
Get access to all 12 Kernel Architecture & OS Internals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.