Linux, Hour 7: Troubleshooting and Performance
- Systematically inspect every resource using the USE Method (Utilization / Saturation / Errors), complete Brendan Gregg’s 10-command checklist within 60 seconds, and state which column to examine for each command.
- Correctly interpret load average (Linux load includes uninterruptible sleep tasks in the D state), and use
vmstat,mpstat, andpidstatto distinguish between “insufficient CPU,” “I/O blocked,” and “lock contention.” - Understand the available column in
free, the page cache, and swap; interpret kernel OOM logs,oom_score_adj, cgroup v2’smemory.max/memory.high, and PSI pressure metrics. - Use
iostat -xto determine disk saturation (including the limitations ofr_await/w_await,aqu-sz, and%util), and distinguish between block exhaustion, inode exhaustion, and files that have been deleted but remain open. - Use
ss,tcpdump,nstat,conntrack,resolvectl, andtracepathto locate retransmissions, a full connection-tracking table, DNS timeouts, and MTU black holes. - Recover systems that cannot boot in GRUB, initramfs (dracut by default in 26.04), and emergency/rescue targets, and fix an incorrectly written
/etc/fstab. - Use
strace,ltrace,perf+ flame graphs,bpftrace, and bcc tools (named*-bpfccon Ubuntu) for in-depth analysis, and understand the overhead of each. - Build a reproducible fault-injection toolkit in
~/linuxlab/faults/, and independently complete diagnosis from symptoms to root cause in the “fault unknown-fault challenge.”
1-Hour Time Allocation
| # | Time | Module | Core Content | Animation / Interaction | Lab (linuxlab VM) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: Fault-Injection Environment | Install observability tools, genobservability tools, generate ~/linuxlab/faults/ injection/reset/mystery-box scripts, and take a snapshot | Environment self-checkinject.sh / reset.sh smoke test |
|
| 1 | 00–06 | Troubleshooting Methodology: USE and 60-Second Analysis | USE meethod, RED Method, 10-command checklist, mitigate the impact before finding the root cause, and record the timeline | Core animation: Walk through a real incident using the 60-second checklist (6 optional fault types) | Run the 10 commands after injecting a CPU fault |
| 2 | 06–13 | CPU and Load | loadaverage calculation and the D state, us/sy/wa/st/si, run queue, context switches, top/htop, vmstat, mpstat, pidstat, and PSI cpu | Load-average simulator (R and D tasks) | CPU hog + I/O hog, comparing load and CPU% |
| 3 | 13–21 | Memory: OOM, Swap, and Page Cache | free/available, page-cache reclaim, swap, overcommit, the OOM killer and oom_score_adj, cgroup memory.max/high, PSI memory, and systemd-oomd | Memory pressure: reclaim → swap → OOM victim selection | A memory leak is OOM-killed within a cgroup; read the kernel logs |
| 4 | 21–28 | Disk I/O and File Systems | iostat -x, iotop-c, await/aqu-sz/%util, full blocks vs. full inodes, deleted-but-still-open files, and PSI io | df / df -i / du three-view simulator | Disk full, inode exhaustion, and deleted-open—the three-part sequence |
| 5 | 28–35 | Network Troubleshooting: tcpdump, ss, and DNS | ss Statusatus and Recv-Q/Send-Q, tcpdump filters, retransmissions, conntrack, DNS timeouts, MTU/PMTUD, tc netem | Single-request failure-point locator | Slow DNS + 20% packet-loss injection and diagnosis |
| 6 | 35–42 | Boot Failures: GRUB, initramfs, and Rescue | Boot chain, Gchain, GRUB menu and kernel parameters, dracut/initramfs, rescue/emergency targets, root lockout and sulogin, fstab nofail | Boot-chain failure-point simulator | Write an incorrect fstab and recover under snapshot protection |
| 7 | 42–50 | Advanced Tools: strace, perf, and eBPF | strace -c/-f/-T, ltrace, perf top/record/report, flame graphs, bpftrace one-liners, the bcc toolkit, overhead comparison | Flame graph builder (sampling → folding → rendering) | Create a CPU flame graph for myapp and use bpftrace to capture OOM and slow I/O |
| 8 | 50–60 | Comprehensive Troubleshooting Mystery Box | Random injection,m injection, time-limited diagnosis, incident postmortem writing | Mystery-box diagnosis simulator + interactive troubleshooting tree | Three rounds of hands-on practice with blindbox.sh |
| — | After the course | Cheat Sheet · Comprehensive Lab | “mylows down on Monday morning” multi-fault exercise | Final assessment (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target Skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key Commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Systematic troubleshooting methods (USE / 60-second checklist) | ✓ | · | · | · | · | · | · | ✓ | uptime, dmesg, vmstat, sar | M1, M8 |
| CPU saturation and load interpretation | ✓ | ✓ | · | ✓ | · | · | ✓ | ✓ | mpstat -P ALL, pidstat, /proc/pressure/cpu | CPU hog |
| Memory pressure, OOM, cgroup limits | ✓ | · | ✓ | · | · | · | ✓ | ✓ | free -m, journalctl -k, systemctl show -p MemoryMax | memleak |
| Disk I/O and space/inodes | ✓ | ✓ | · | ✓ | · | · | ✓ | ✓ | iostat -xz, df -i, lsof +L1 | disk / inode / deleted |
| Networking, DNS, retransmissions, MTU | ✓ | · | · | · | ✓ | · | ✓ | ✓ | ss -tinp, tcpdump, resolvectl, tracepath | dns / netloss |
| Boot failures and rescue | · | · | · | ✓ | · | ✓ | · | ✓ | findmnt --verify, systemctl emergency, update-initramfs | fstab exercise |
| Service-level failures (systemd) | ✓ | · | ✓ | · | ✓ | ✓ | ✓ | ✓ | systemctl status, journalctl -u | myapp failures |
| System calls / profiling / eBPF tracing | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | strace -fc, perf record -g, bpftrace -e | Flame graphs |
| Fault injection and postmortems | ✓ | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | inject.sh, reset.sh, blindbox.sh | All |
Content Excluded from This Course (and Where to Learn It)
| Topic | Why It Is Not in This Course | Where to Learn It |
|---|---|---|
| Long-term monitoring, alerting, and dashboards (node_exporter, PSI metric collection) | This course focuses on “on-site diagnosis” and does not set up a monitoring system | Prometheus & Grafana in 8 + 1 Hours |
| cgroup / namespace details inside containers, | The principles are briefly covered in M3 of this course; the application layer is covered in the container course | Docker in 8 Hours |
| systemd unit writing, journal, journald, LVM, fstab basics | Assumed to be known for this course | Lesson 2 |
| Batch remediation, configuration drift management | Part of automated operations | Lesson 5, Ansible in 8 Hours |
| Kernel crash dumps (kdump / crash)dump / crash), kernel debuggers, driver issues | Requires a separate environment and a substantial amount of time | Ubuntu Server documentation: Kernel crash dump |
| Application-internal tuning for databases / JVMs and the like | Specific to the application | The official documentation for the corresponding application; this course only teaches “how to prove that the problem is with the applicationn for the corresponding application; this course only teaches “how to prove that the problem is with the application” |
How to Use This Courseware
Principles · Diagrams · Animations · Commands · Labs · Production Cases · Troubleshooting · Quizzes · Audio · Video. Recommended order: Principles → Animations → Use the troubleshooting toolbox to perform labs → Troubleshooting.
A quiz score of ≥ 70% or clicking “Mark This Module Complete” counts toward progress, which is saved in this browser (if local storage is disabled, it is cleared after a refresh).
The “Audio” tab uses the browser’s built-in Web Speech API (zh-CN) to read the lecture script aloud; when no Chinese voice package is available, the lecture script can be read directly or passed to a TTS tool.
linux-generic 7.0.0-42.42), systemd 259, sysstat 12.7.7, procps-ng 4.0.4, strace 6.19, bpftrace 0.25.0, bcc 0.35.0, iotop-c 1.31, htop 3.4.1, stress-ng 0.20.01 (all verified on 2026-11-17 at packages.ubuntu.com). Differences from 24.04 LTS are identified separately. The three most important points are: ① 26.04 uses dracut by default to generate the initramfs (24.04 uses initramfs-tools), but both provide the update-initramfs command; ② perf is provided by the new linux-perf package (24.04 uses linux-tools-$(uname -r)); ③ 26.04 uses sudo-rs and the Rust version of coreutils by default. The error messages of some commands may differ slightly from those of the GNU versions. Wherever coreutils error messages appear in this course, the GNU version is used as an example and marked “actual output may vary.” Any output not executed on a real machine is marked “Example.”Module 0 · Preparation: Set Up the Fault-Injection Lab
- Use the Lesson 1 VM named
linuxlab, thelabadminaccount with sudo access, and~/linuxlabas your working directory. We recommend 2 vCPUs, 4 GiB of memory, and a 20 GiB disk. With Multipass, create it usingmultipass launch --name linuxlab --cpus 2 --memory 4G --disk 20G. - Complete Lesson 2 first. It sets up
myapp.servicewith themyappsystem account, application files in/opt/myapp, a virtual environment in/opt/myapp/venv, configuration in/etc/myapp/myapp.env, port 5000, and a/healthzhealth check. Redis should be running asredis-server. - You can keep the security settings from Lesson 6, including UFW, AppArmor, and auditd. The exercises do not require opening additional ports, even if UFW is enabled.
- Note for WSL2 users: WSL2 shares the Windows host kernel, so experiments involving
tc netem,perfhardware events, and boot failures (M6) are unavailable or produce different results; use a Multipass / Hyper-V / VirtualBox virtual machine to complete this lesson.
Step 1: Check the lab machine and myapp
hostnamectl --static # Should be linuxlab lsb_release -ds; uname -r nproc; free -h; df -h / systemctl is-active myapp redis-server curl -fsS http://127.0.0.1:5000/healthz; echo
linuxlab
Ubuntu 26.04.1 LTS
7.0.0-42-generic
2
total used free shared buff/cache available
Mem: 3.8Gi 610Mi 2.6Gi 1.1Mi 850Mi 3.2Gi
Swap: 0B 0B 0B
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 19G 3.1G 16G 17% /
active
active
{"status": "ok"}
Multipass's Ubuntu cloud images do not have swap space by default (Swap is 0), which affects the behavior observed in M3; if a swap file was already created in the second lesson, the output will be different. The content returned by /healthz depends on the actual implementation from the second lesson.
Step 2: Install monitoring and troubleshooting tools
sudo apt update sudo apt install -y sysstat htop iotop-c lsof strace ltrace tcpdump conntrack \ bind9-dnsutils iproute2 stress-ng bpftrace bpfcc-tools psmisc # perf: On 26.04, use the version-independent linux-perf package sudo apt install -y linux-perf # On 24.04 LTS, use instead: sudo apt install -y linux-tools-common linux-tools-$(uname -r) perf --version; bpftrace --version; iostat -V | head -1
perf version 7.0.x bpftrace v0.25.0 sysstat version 12.7.7
| Packages (Ubuntu 26.04) | Commands provided | Purpose in this lesson |
|---|---|---|
sysstat | iostat mpstat pidstat sar | Primary tool for the 60-second checklist (background collection is not required in real-time mode) |
procps (preinstalled) | vmstat free top uptime ps | Load, memory, and processes |
iotop-c | iotop-c | View I/O by process (C rewrite; the old Python version is packaged as iotop, which is still in universe) |
bpftrace | bpftrace and /usr/sbin/*.bt tools (such as oomkill.bt and biolatency.bt) | eBPF one-liners|
bpfcc-tools | /usr/sbin/*-bpfcc (such as execsnoop-bpfcc, runqlat-bpfcc, and tcpretrans-bpfcc) | Ready-made bcc tools; Ubuntu/Debian add the |
linux-perf | perf | CPU profiling and flame graphs |
stress-ng | stress-ng | Generate CPU / I/O load |
Step 3: Generate the fault-injection toolkit ~/linuxlab/faults/
All faults follow three safety principles: ① they can run only on a machine whose hostname is linuxlab; ② they are kept in a “cage” as much as possible—process-related faults use systemd-run to create temporary units named fault-* (with their own cgroups, which can all be removed with a single systemctl stop), while disk-related faults occur on a 100 MiB loopback filesystem at /mnt/faultdisk, so the root partition will not be filled; ③ network packet loss includes a 15-minute automatic rollback timer, so it can self-heal even if the SSH connection is lost.
mkdir -p ~/linuxlab/faults && cd ~/linuxlab/faults
cat > inject.sh <<'EOF'
#!/usr/bin/env bash
# Linux Lesson 7 fault injection tool: Run only on the lab machine linuxlab!
set -euo pipefail
IMG=/var/tmp/faultdisk.img
MNT=/mnt/faultdisk
STATE=/run/faultbox/active
IFACE="$(ip route show default | awk '{print $5; exit}')"
[ "$(hostname)" = "linuxlab" ] || { echo "Execution denied: only allowed to run on linuxlab" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || { echo "Please run with sudo: sudo $0 $*" >&2; exit 1; }
mkdir -p /run/faultbox
ensure_disk() { # ensure_disk() { # 100 MiB loopback ext4, with only 2048 inodes; -m 0 reserves no space for root
if ! mountpoint -q "$MNT"; then
[ -f "$IMG" ] || { truncate -s 100M "$IMG"; mkfs.ext4 -q -N 2048 -m 0 "$IMG"; }
mkdir -p "$MNT"; mount -o loop "$IMG" "$MNT"; chmod 1777 "$MNT"
fi
}
writer() { # writer() { # Simulate a business process that continuously writes logs; log write failures to journald
systemctl is-active -q fault-writer 2>/dev/null && return 0
systemd-run --quiet --unit=fault-writer --collect --expand-environment=no bash -c \
'while :; do if ! date >> /mnt/faultdisk/app.log 2>/tmp/fault-writer.err; then logger -t fault-writer "write failed: $(cat /tmp/fault-writer.err)"; fi; sleep 2; done'
}
f="${1:-}"
case "$f" in
cpu) # cpu) # One fully loaded worker per CPU; automatically exits after 30 minutes
systemd-run --quiet --unit=fault-cpu --collect stress-ng --cpu "$(nproc)" --cpu-method matrixprod --timeout 30m ;;
iohog) # iohog) # Random reads and writes to cause disk saturation and D state
systemd-run --quiet --unit=fault-io --collect stress-ng --hdd 2 --hdd-bytes 512M --temp-path /var/tmp --timeout 30m ;;
memleak) # memleak) # Leak 10 MiB every 0.5 seconds; cgroup limit of 300M, swap disabled; restart 5 seconds after triggering cgroup OOM
systemd-run --quiet --unit=fault-memleak -p MemoryMax=300M -p MemorySwapMax=0 \
-p Restart=on-failure -p RestartSec=5 python3 -c '
import time
leak = []
while True:
leak.append(b"x" * 10485760)
time.sleep(0.5)' ;;
disk-full) # disk-full) # Fill the loopback filesystem's data blocks
ensure_disk; writer
dd if=/dev/zero of="$MNT/bigfile" bs=1M status=none 2>/dev/null || true ;;
inode) # inode) # Exhaust inodes with many empty files while block space remains plentiful
ensure_disk; writer; mkdir -p "$MNT/sessions"
for i in $(seq 1 4000); do : > "$MNT/sessions/sess_$i" 2>/dev/null || break; done ;;
deleted-open) # deleted-open) # Open and then delete an 80 MiB file in a process: df full, du empty
ensure_disk
systemd-run --quiet --unit=fault-holder --collect bash -c \
'exec 3>/mnt/faultdisk/huge.log; dd if=/dev/zero bs=1M count=80 status=none >&3; rm -f /mnt/faultdisk/huge.log; exec sleep infinity' ;;
dns) # dns) # Point the default network interface's DNS to the unreachable documentation address 192.0.2.53 (RFC 5737)
resolvectl dns "$IFACE" 192.0.2.53; resolvectl flush-caches ;;
netloss) # netloss) # 20% packet loss + 80ms latency; automatically revert after 15 minutes
tc qdisc replace dev "$IFACE" root netem loss 20% delay 80ms
systemd-run --quiet --unit=fault-netem-revert --on-active=15min /usr/sbin/tc qdisc del dev "$IFACE" root ;;
myapp) # myapp) # Reference a nonexistent environment file through a drop-in, preventing myapp from starting
mkdir -p /etc/systemd/system/myapp.service.d
printf '[Service]\nEnvironmentFile=/etc/myapp/myapp-prod.env\n' > /etc/systemd/system/myapp.service.d/zz-fault.conf
systemctl daemon-reload; systemctl restart myapp || true ;;
myapp-port) # myapp-port) # Another process grabs port 5000
systemctl stop myapp
systemd-run --quiet --unit=fault-port5000 --collect python3 -m http.server 5000 --bind 0.0.0.0
sleep 1; systemctl start myapp || true ;;
*)
echo "Usage: sudo $0 {cpu|iohog|memleak|disk-full|inode|deleted-open|dns|netloss|myapp|myapp-port}"; exit 2 ;;
esac
echo "$f" >> "$STATE"
[ "${QUIET:-0}" = 1 ] || echo "Fault injected: $f (reset: sudo ~/linuxlab/faults/reset.sh)"
EOF
cat > reset.sh <<'EOF'
#!/usr/bin/env bash
# Reset all faults (can be run repeatedly)
set -uo pipefail
[ "$(id -u)" -eq 0 ] || { echo "Please run with sudo" >&2; exit 1; }
IFACE="$(ip route show default | awk '{print $5; exit}')"
systemctl stop 'fault-*.service' 'fault-*.timer' 2>/dev/null
systemctl reset-failed 'fault-*' 2>/dev/null
resolvectl revert "$IFACE" 2>/dev/null; resolvectl flush-caches 2>/dev/null
tc qdisc del dev "$IFACE" root 2>/dev/null
if [ -f /etc/systemd/system/myapp.service.d/zz-fault.conf ]; then
rm -f /etc/systemd/system/myapp.service.d/zz-fault.conf; systemctl daemon-reload
fi
systemctl reset-failed myapp 2>/dev/null; systemctl start myapp 2>/dev/null
if mountpoint -q /mnt/faultdisk; then umount /mnt/faultdisk || umount -l /mnt/faultdisk; fi
rm -f /var/tmp/faultdisk.img /tmp/fault-writer.err /run/faultbox/active /root/.faultbox-answer
echo "Reset. myapp: $(systemctl is-active myapp) netem: $(tc qdisc show dev"$IFACE"| grep -c netem) entries"
EOF
cat > status.sh <<'EOF'
#!/usr/bin/env bash
# Don’t spoil the unknown-fault challenge answer; only show “whether anything remains”
systemctl list-units --all --no-legend 'fault-*' | awk '{print "unit:", $1, $3, $4}'
mountpoint -q /mnt/faultdisk && echo "faultdisk: mounted"
tc qdisc show | grep -q netem && echo "netem: active"
[ -f /etc/systemd/system/myapp.service.d/zz-fault.conf ] && echo "myapp drop-in: present"
true
EOF
cat > blindbox.sh <<'EOF'
#!/usr/bin/env bash
# Unknown-fault challenge: randomly inject 1 fault; the answer is stored only in a file readable by root
set -euo pipefail
[ "$(id -u)" -eq 0 ] || { echo "Please run with sudo" >&2; exit 1; }
DIR="$(cd "$(dirname "$0")" && pwd)"
ANS=/root/.faultbox-answer
if [ "${1:-}" = "--reveal" ]; then cat "$ANS" 2>/dev/null || echo "There is currently no unknown-fault challenge"; exit 0; fi
"$DIR/reset.sh" >/dev/null
FAULTS=(cpu iohog memleak disk-full inode deleted-open dns netloss myapp myapp-port)
pick="${FAULTS[RANDOM % ${#FAULTS[@]}]}"
QUIET=1 "$DIR/inject.sh" "$pick"
echo "$pick $(date -Is)" > "$ANS"; chmod 600 "$ANS"
echo "Mystery box opened ($(date +%T)). User report: “myapp on linuxlab seems to be acting up.”"
echo "Start the timer and diagnose using the 60-second checklist. View the answer: sudo $0 --reveal"
EOF
chmod +x *.sh && ls -l
-rwxrwxr-x 1 labadmin labadmin 1187 Nov 17 10:02 blindbox.sh -rwxrwxr-x 1 labadmin labadmin 3975 Nov 17 10:02 inject.sh -rwxrwxr-x 1 labadmin labadmin 868 Nov 17 10:02 reset.sh -rwxrwxr-x 1 labadmin labadmin 402 Nov 17 10:02 status.sh
myapp fault is overridden using the drop-in file zz-fault.conf; do not modify the unit file written in Lesson 2. To reset, simply delete the drop-in. ② The dns fault only modifies the “link-level” DNS for the default network interface. If you have configured a global DNS= in /etc/systemd/resolved.conf, the global servers will still be used, weakening the fault symptoms. ③ netloss will affect your SSH session (making it sluggish, but usually not disconnecting it); after 15 minutes, fault-netem-revert.timer automatically runs tc qdisc del. ④ The blind-box myapp-port fault requires myapp to bind to 0.0.0.0:5000 or 127.0.0.1:5000, as configured in Lesson 2.Step 4: Smoke test (inject → observe → reset)
cd ~/linuxlab/faults sudo ./inject.sh cpu uptime; systemctl status fault-cpu --no-pager | head -5 sudo ./reset.sh ./status.sh
Fault injected: cpu (reset: sudo ~/linuxlab/faults/reset.sh)
10:05:12 up 2:11, 1 user, load average: 1.62, 0.55, 0.20
● fault-cpu.service - /usr/bin/stress-ng --cpu 2 --cpu-method matrixprod --timeout 30m
Loaded: loaded (/run/systemd/transient/fault-cpu.service; transient)
Transient: yes
Active: active (running) since Tue 2026-11-17 10:04:58 UTC; 14s ago
Reset. myapp: active netem: 0 entries
Step 5: Take a snapshot of the lab machine (required before starting the M6 fault lab)
# Execute on the host machine (Multipass 1.13+ supports snapshots; the instance must be stopped first) multipass stop linuxlab multipass snapshot linuxlab --name before-hour7 multipass start linuxlab multipass list --snapshots # When a rollback is needed: multipass stop linuxlab && multipass restore linuxlab.before-hour7
In Hyper-V, use “Checkpoint”; in VirtualBox, use “Snapshot.” For snapshot command parameters, refer to multipass help snapshot.
Module 1 · Troubleshooting Methodology: The USE Method and 60-Second Analysis
- State the three dimensions of the USE Method and write one utilization, saturation, and error metric, along with the corresponding command, for each of CPU, memory, disk, and network.
- Recite the 10 commands in the 60-second checklist in order, and know which column to look at first for each command.
- Master the incident response sequence: confirm symptoms → mitigate → identify the root cause → fix → review; understand that “what changed recently” is often the fastest clue.
/proc from Lesson 1; systemd and journald from Lesson 2. Importance: ★★★★★ (all subsequent modules use this framework)What: What Is the USE Method?
The USE Method, proposed by Brendan Gregg, checks every type of resource for Utilization (the proportion of time a resource is busy or the proportion of capacity occupied), Saturation (the amount of work that cannot be serviced immediately and is waiting in a queue), and Errors (the count of error events). Its value lies in its completeness: list the resources first, then check each box to avoid “looking only at the CPU” and missing dropped packets on a network interface or a disk queue.
| Resource | Utilization | Saturation | Errors |
|---|---|---|---|
| CPU | mpstat -P ALL 1 100−%idle; top | vmstat 1 r column > CPU count; load average; /proc/pressure/cpu | Rare (MCE hardware error; see dmesg) |
| Memory | used / available from free -m | si/so from vmstat (swap-in/swap-out); /proc/pressure/memory; OOM events | OOMs and page allocation failures in the kernel log |
| Disk I/O | %util from iostat -xz 1 | aqu-sz (average queue length), r_await/w_await; /proc/pressure/io | I/O errors in dmesg, smartctl |
| Disk capacity | df -h, df -i | (A full disk is itself the endpoint of saturation.) | ENOSPC: No space left on device |
| Network | rxkB/s, txkB/s from sar -n DEV 1 and their ratio to bandwidth | Send-Q/Recv-Q from ss, retransmissions, overflow counters from nstat | errors/dropped from ip -s link, sar -n EDEV 1 |
| Software resources | Utilization of thread pools / connection pools / file descriptors | Number of requests waiting for a connection, accept queue overflows | EMFILE (Too many open files), timeouts |
Why: Why a methodology is needed
The most common failures during production incidents are not “not knowing how to use the tools,” but rather: ① the streetlight effect—using only the tools you know to look for problems; ② randomly changing parameters—tuning sysctl without a hypothesis; ③ mistaking symptoms for root causes—“high CPU” is just an observed symptom; the root cause may be a cache invalidation caused by a configuration change. USE is a resource-oriented checklist; its complement, the RED method (Rate / Errors / Duration), is service-oriented and tells you “what users are experiencing.” In practice, use RED first to confirm symptoms, then use USE to find resource bottlenecks.
How: 60-second checklist (Netflix Performance Team, 2015)
These 10 commands come from “Linux Performance Analysis in 60,000 Milliseconds,” published on the Netflix tech blog by Brendan Gregg and others. They are all standard tools; within 60 seconds of logging in, they can give you an overall assessment of the system:
| # | Command | What to check first | Corresponding USE |
|---|---|---|---|
| 1 | uptime | Trend in 1/5/15-minute load: a 1-minute value far above the 15-minute value indicates the problem has just started | CPU/disk saturation (roughly) |
| 2 | dmesg -T | tail | Kernel messages such as OOM, I/O errors, TCP packet loss, and hung tasks | Various E |
| 3 | vmstat 1 | r (runnable tasks), b (D-state), si/so, us/sy/id/wa/st | CPU S, memory S |
| 4 | mpstat -P ALL 1 | Whether one CPU is fully utilized (single-thread bottleneck), %iowait, %steal, %soft | CPU U |
| 5 | pidstat 1 | Which process is consuming CPU (rolling output makes changes easy to spot) | CPU U (by process) |
| 6 | iostat -xz 1 | r/s, w/s, r_await/w_await, aqu-sz, %util | Disk U/S |
| 7 | free -m | available column (not the free column), swap used | Memory U |
| 8 | sar -n DEV 1 | rxkB/s, txkB/s, %ifutil for each network interface | Network U |
| 9 | sar -n TCP,ETCP 1 | active/s (active connections), passive/s (passive connections), retrans/s | Network S/E |
| 10 | top | Comprehensive check: sort processes and check the S status column (R/D/Z) | Cross-check |
On systems in 2026, it is recommended to add two more “modern” commands: cat /proc/pressure/{cpu,memory,io} (PSI, which directly shows “how much time is spent stalled due to insufficient resources”) and systemctl --failed + journalctl -p err -b (service-level errors).
When: The pace of incident response
- Confirm and quantify the symptoms: Who reported it? Which interface? What time did it start? (
curl -w '%{time_total}', latency in the logs) - Ask “what changed recently?”:
journalctl --since "-2h" -p warning,/var/log/apt/history.log,last -n 10, and the commit history of the configuration repository. - Stop the bleeding first: Roll back, scale out, apply rate limiting, or restart a single instance—but preserve the scene before restarting (
ps auxf > ps.txt,journalctl -b > j.txt,ss -tanp > ss.txt). - 60-second checklist → hypothesis → verify with specialized tools (the tools in M2–M7).
- Fix and verify, then write a blameless postmortem: timeline, impact, root cause, why it was not detected earlier, and improvement items.
Comparison with Similar Methods
| USE | RED | Golden Signals(Google SRE) | “Tool-driven” troubleshooting | |
|---|---|---|---|---|
| Perspective | Resources (machines) | Requests (services) | Services: latency, traffic, errors, saturation | Look at whatever tools happen to be at hand |
| Applicable to | Host/kernel-level bottlenecks | Microservices, APIs | Alert design | Not recommended |
| Position in this course | Main line for M1–M5 | M1 symptom confirmation, M8 unknown-fault challenge | Monitoring course | Negative example |
Figure 1-1: USE Method Inspection Matrix
Figure 1-2: Workflow from Symptoms to Root Cause
Core Animation: Walk Through a Real Incident with the 60-Second Checklist
First select an injected fault, then click “Play” or “Next”: each step executes one command from the checklist, and the terminal below displays the output you would see on linuxlab (the values are examples); the USE matrix on the right highlights the clue discovered at this step. The final step provides the root cause and verification command. All faults can be reproduced in reality with ~/linuxlab/faults/inject.sh.
Core Commands and Parameters
| Command | Function | Key Parameters / Description |
|---|---|---|
uptime | Uptime and 1/5/15-minute load averages | You can also read /proc/loadavg (the fourth field is the “runnable/total task count”) |
dmesg -T | tail -n 30 | Kernel ring buffer | -T human-readable timestamps; -l err,warn; on Ubuntu, ordinary users cannot read it by default (kernel.dmesg_restrict=1); use sudo or journalctl -k |
vmstat 1 5 | System-wide CPU, memory, swap, and I/O overview | The first line is the average since boot; ignore it; -w wide format; -S M |
mpstat -P ALL 1 | Time distribution for each CPU | -P ALL all CPUs; look for a single core at 100% |
pidstat 1 | Per-process CPU usage | -u CPU, -r memory, -d disk, -w context switches, -t threads, -p PID |
iostat -xz 1 | Extended block device statistics | -x extended columns, -z hide inactive devices, -m MB units |
free -m | Memory overview | -h, -w (separate buffers and cache) |
sar -n DEV 1 / sar -n TCP,ETCP 1 | Network interface throughput / TCP connections and retransmissions | -n EDEV network interface errors; -n SOCK socket count |
top / htop | Interactive process view | In top, 1 expands CPUs, M sorts by memory, and P sorts by CPU |
cat /proc/pressure/* | PSI pressure stall information | some/full avg10/avg60/avg300 |
One-shot checklist (suitable for pasting into the incident channel)
cat > ~/linuxlab/sixty.sh <<'EOF'
#!/usr/bin/env bash
# 60-second Linux analysis checklist: each command samples a limited number of times and finishes in approximately 60 seconds
run(){ printf '\n===== %s =====\n' "$*"; "$@" 2>&1; }
run uptime
run sudo dmesg -T --level=err,warn,crit,alert,emerg | tail -n 15
run vmstat 1 5
run mpstat -P ALL 1 3
run pidstat 1 3
run iostat -xz 1 3
run free -m
run sar -n DEV 1 3
run sar -n TCP,ETCP 1 3
run top -b -n 1 -o %CPU | head -n 20
run grep -H . /proc/pressure/cpu /proc/pressure/memory /proc/pressure/io
run systemctl --failed --no-legend
EOF
chmod +x ~/linuxlab/sixty.sh
~/linuxlab/sixty.sh | tee ~/linuxlab/sixty-$(date +%F-%H%M).txt
===== uptime ===== 10:12:40 up 2:18, 1 user, load average: 0.08, 0.10, 0.09 ===== vmstat 1 5 ===== procs -----------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 2690112 61240 812300 0 0 12 20 110 190 1 1 98 0 0 0 1 0 0 2690040 61240 812300 0 0 0 0 105 170 0 0 100 0 0 0 ... ===== grep -H . /proc/pressure/cpu ... ===== /proc/pressure/cpu:some avg10=0.00 avg60=0.00 avg300=0.00 total=1834511 /proc/pressure/cpu:full avg10=0.00 avg60=0.00 avg300=0.00 total=0 /proc/pressure/memory:some avg10=0.00 avg60=0.00 avg300=0.00 total=21043
How to verify: On an idle system, r should be close to 0, id close to 100, and all PSI values should be 0—first save a “healthy baseline”; comparisons during an incident are meaningful only then. Common mistakes: treating the first line of vmstat as the current value; forgetting -z and letting iostat flood the screen. Production use: add sixty.sh to the on-call runbook and post the results within 1 minute of the incident starting. Starting with procps-ng 4.0.4, vmstat has an additional gu column at the end (26.04 includes 4.0.4); earlier versions do not have this column.
Find “what changed recently”
journalctl --since "-2h" -p warning --no-pager | tail -n 30 grep -E "^(Start-Date|Commandline)" /var/log/apt/history.log | tail -n 6 last -n 5; systemctl list-units --type=service --state=failed ls -lt /etc | head # ls -lt /etc | head # Configuration modified most recently
Lab 1: Establish a healthy baseline, then run the checklist again during a CPU failure (about 5 minutes)
cd ~/linuxlab
./sixty.sh > baseline.txt 2>&1
for i in $(seq 5); do curl -s -o /dev/null -w '%{time_total}\n' http://127.0.0.1:5000/healthz; done
0.003121 0.002874 0.002950 0.002811 0.002903
sudo ~/linuxlab/faults/inject.sh cpu
sleep 20
for i in $(seq 5); do curl -s -o /dev/null -w '%{time_total}\n' http://127.0.0.1:5000/healthz; done
Latency will usually increase only slightly: Linux’s CFS/EEVDF scheduler will allocate time slices to the interactive gunicorn process. This is precisely the common phenomenon of “100% CPU but the service is not down.”
./sixty.sh > incident.txt 2>&1 diff <(grep -A3 "===== uptime" baseline.txt) <(grep -A3 "===== uptime" incident.txt) grep -A6 "===== vmstat" incident.txt grep -A8 "===== pidstat" incident.txt
r b swpd free buff cache si so bi bo in cs us sy id wa st gu 2 0 0 2655300 61300 812600 0 0 0 4 2050 410 100 0 0 0 0 0 Average: UID PID %usr %system %guest %wait %CPU CPU Command Average: 0 4211 99.67 0.00 0.00 0.33 99.67 - stress-ng-cpu Average: 0 4212 99.33 0.00 0.00 0.67 99.33 - stress-ng-cpu
cat >> ~/linuxlab/incident-log.md <<EOF
## $(date -Is) Exercise: CPU saturation
- Symptom: /healthz latency $(curl -s -o /dev/null -w '%{time_total}' http://127.0.0.1:5000/healthz)s
- Finding: vmstat r=2 us=100; pidstat showed stress-ng-cpu consuming two full CPUs
- Root cause: fault-cpu.service (stress-ng)
- Action: systemctl stop fault-cpu
EOFsudo systemctl stop fault-cpu sleep 5; vmstat 1 3 sudo ~/linuxlab/faults/reset.sh
Case 1: “The database is slow” is actually packet loss on the network interface
Problem: The application team reported that query P99 had increased from 20ms to 1.2s, while the DBA found CPU and memory to be normal. Approach: The on-call engineer followed the checklist through item 9, sar -n TCP,ETCP 1, and found dozens of retransmissions per second; ip -s link showed RX dropped continuously increasing; the issue was ultimately traced to an undersized NIC ring buffer (ethtool -g). Configuration: Run ethtool -G eth0 rx 4096 and write it to the network configuration. Limitation: For virtual network interfaces in the cloud, the adjustable range is determined by the platform. Lesson: Looking only at CPU and memory can cause you to miss the entire network row of the USE matrix.
Case 2: Stop the bleeding before finding the root cause
Problem: Five minutes after the release, API instance memory continued rising, and two instances were OOM-killed. Approach: Roll back immediately (mitigate the impact), but before rolling back, save /proc/PID/smaps_rollup, journalctl -k, and a heap dump from one instance; afterward, reproduce the issue in the staging environment and find that the cache in the new version had no upper limit configured. Limitation: If you restart before rolling back, you will lose the only evidence from the incident scene.
Case 3: Put the checklist into the runbook
Problem: New engineers on overnight duty did not know where to start. Approach: Place sixty.sh in /usr/local/bin on all hosts (using the automated distribution from Lesson 5), and attach “Step 1: Run sixty.sh and paste the result” to the alert notification. Result: Average diagnosis time decreased significantly, and standardized raw data was also available during post-incident reviews.
Common Errors and Solutions
dmesg: read kernel buffer failed: Operation not permitted
Cause: Ubuntu defaults to kernel.dmesg_restrict = 1, so ordinary users cannot read kernel logs.
sysctl kernel.dmesg_restrict sudo dmesg -T | tail journalctl -k -b --no-pager | tail # journalctl -k -b --no-pager | tail # Readable by members of the adm/systemd-journal groups
Fix: Use sudo or journalctl -k; do not change dmesg_restrict to 0 for convenience.
Command 'iostat' not found, but can be installed with: sudo apt install sysstat
Cause: iostat/mpstat/pidstat/sar are all included in the sysstat package, which is not installed by default on minimally installed servers.
sudo apt install -y sysstat
Note: The real-time mode of sar (with an interval argument) does not depend on background collection; to view historical data from “3 a.m. last night,” you must enable sysstat collection in advance (sudo systemctl enable --now sysstat; on Ubuntu, you must also set ENABLED="true" in /etc/default/sysstat, subject to the actual file).
Cannot open /var/log/sysstat/sa17: No such file or directory
Cause: When sar is run without an interval, it reads historical data files, but collection has not been enabled.
Fix: At the incident scene, use real-time mode such as sar -n DEV 1; afterward, enable historical collection to avoid having no data next time.
Symptom: Everything on the checklist is normal, but users still say it is “slow”
Cause: The bottleneck is not on this machine (downstream database, DNS, load balancer), or it is in software resources (thread pool, connection pool, lock).
ss -tnp state established '( dport = :6379 )' | wc -l # ss -tnp state established '( dport = :6379 )' | wc -l # Number of connections to Redis
curl -s -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' http://127.0.0.1:5000/healthz
sudo strace -f -T -e trace=network,poll,epoll_wait -p "$(pgrep -f gunicorn | head -1)" -o /tmp/gunicorn.trace
Remediation direction: Use RED metrics to break latency down into DNS / connection / time to first byte; for “waiting” issues, use off-CPU analysis (offcputime-bpfcc from M7).
1. Write the command used in the 60-second checklist to observe TCP retransmissions, and specify which columns to look at.
sar -n TCP,ETCP 1 # Look at retrans/s in the ETCP section; you can also look at active/s and passive/s in the TCP section
2. Give one command to view the 10-second averages for all three types of PSI pressure simultaneously.
grep -H . /proc/pressure/{cpu,memory,io} | grep some3:00 a.m. alert: myapp's 5xx ratio is 30%. After logging in, uptime shows load 18.2, 6.1, 2.0 (2 vCPUs), and vmstat shows r=1, b=16, wa=85. What should you do next?
The 1-minute load value is much higher than the 15-minute value, indicating that the problem has just started; r is only 1, but b=16 and wa is high, indicating that many tasks are in D state waiting for I/O, rather than insufficient CPU. Next: run iostat -xz 1 to see which device's await/aqu-sz is spiking, run ps -eo pid,stat,wchan:32,cmd | awk '$2 ~ /D/' to identify processes in D state and the kernel functions on which they are blocked, and run dmesg -T | tail to check for I/O errors or hung tasks; at the same time, mitigate the impact by shifting traffic to healthy instances.
Verified Instructional Videos
Official and First-Handial and First-Hand Materials
- The USE Method(Brendan Gregg)
- USE Method: Linux Performance Checklist
- Linux Performance Analysis in 60,000 Milliseconds(Netflix TechBlog)
- PSI - Pressure Stall Information(kernel.org)
Video Storyboard (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script have been providedrectly generate video/MP3 files; a storyboard and narration script have been provided and can be handed over to a video tool for generation.
Visual: An alert pop-up reading “myapp latency increased”; an engineer opens a terminal, and a 60-second countdown appears in the upper-right corner of the screen.
Voice-over: During an incident, the worst thing is having no direction. We will first use sixty seconds to look over the entire machine.
Visual: Ten commands scroll by in sequence, with the columns each command is intended to inspect highlighted alongside it: load trends, kernel logs, r and b, 100% utilization on a single core, await, available memory, and retransmissions.
Voice-over: uptime shows trends, dmesg shows kernel errors, vmstat shows queues, mpstat shows individual cores, iostat shows disks, free shows available memory, and sar shows the network and retransmissions.
Visual: The USE matrix lights up cell by cell; the disk saturation cell turns red.
Voice-over: Check utilization, saturation, and errors for each resource. Whichever cell turns red is the hypothesis to verify next.
Visual: The timeline document automatically appends entries: time, observation, action, result.
Voice-over: Stop the bleeding first, then find the root cause; record every step so there is a basis for the retrospective.
Module 2 · CPU and Load: top, vmstat, mpstat, pidstat
- Explain how Linux load average is calculated (sampling the number of tasks in R + D states once every 5 seconds and calculating an exponentially decaying average), and why a blocked disk can also increase load.
- Understand the categories of CPU time: us / sy / ni / id / wa / hi / si / st, and know that %iowait is “a type of idle time.”
- Use
mpstatto identify single-core bottlenecks, usepidstat -u/-w/-tto locate processes, threads, and context switches, and usecpu.statto identify cgroup throttling.
What: What exactly is load average?
Approximately every 5 seconds (LOAD_FREQ = 5*HZ+1), the kernel counts the number of tasks that are “running or waiting to run (R state) + in uninterruptible sleep (D state),” and calculates separate exponentially decaying moving averages with 1-, 5-, and 15-minute time constants: load = load × e + n × (1 − e), where the 1-minute e = exp(−5/60) ≈ 0.92. Therefore:
- It measures “demand,” not “utilization”: on a 2-core machine, a load of 4 means that, on average, 2 tasks are queued (or stuck in the D state).
- It “lags”: a sudden load spike takes approximately 1 minute to make the 1-minute value approach the actual value.
- Linux-specific: Since 1993, tasks in the D state (usually waiting for disk I/O, NFS, or certain kernel locks) have been counted toward load, so Linux load is “system load” rather than “CPU load.” Brendan Gregg documented this history in his 2017 article “Linux Load Averages: Solving the Mystery”.
CPU Time Categories (shared by top / vmstat / mpstat)
| Field | Meaning | Typical causes when elevated |
|---|---|---|
| us / %usr | User mode | Application computation, serialization, regular expressions, encryption |
| sy / %sys | Kernel mode | Large numbers of system calls, small I/O operations, locks, memory allocation; network packet processing |
| ni / %nice | Lower-priority user-mode processes | Batch processing, backups (nice 19) |
| id / %idle | Idle | — |
| wa / %iowait | CPU is idle while tasks are waiting for I/O | Slow disk; note: it is a subset of idle, and its value can be misleading on multicore systems |
| hi / si(%irq / %soft) | Hard interrupts / soft interrupts | High network packet rate (NET_RX), timers; high %soft on a single core indicates that NIC queues are not distributed |
| st / %steal | Virtual machine wants to run, but the host does not provide CPU | “Noisy neighbors” in the cloud, burstable instance credits exhausted |
| gu / %guest | Time spent running virtual machine vCPUs | The local machine is a KVM host |
Why: Why break it down?
Different CPU issues require completely different handling: high us requires profiling (M7’s perf flame graph); high sy requires examining system calls (strace -c); high wa requires investigating the disk (M4); high st requires changing the instance type or contacting the cloud provider; high si requires NIC multi-queue/RPS; cgroup throttling requires tuning CPUQuota=/cpu.max.
How: How processes “queue”
Starting with Linux 6.6, the default scheduler changed from CFS to EEVDF (Earliest Eligible Virtual Deadline First), and Linux 7.0 inherited this design; each CPU has a run queue. The r column in vmstat is the global number of runnable tasks (including those currently running). A sustained value greater than the number of CPUs indicates saturation. More precise saturation metrics are:
- PSI: In
/proc/pressure/cpu,some avg10=35.2means that over the past 10 seconds, at least one task was stalled waiting for CPU for 35.2% of the time. Under cgroup v2, each service also has its owncpu.pressure. - Scheduling latency:
runqlat-bpfcc(M7) provides a histogram of the time tasks wait in the run queue. - cgroup throttling: For a service with
CPUQuota=configured,nr_throttledincpu.statincreases—even when the system’s CPUs are largely idle, the service becomes slower.
When: Decision process
uptime: Is load / nproc > 1? Is the trend rising or falling?vmstat 1: High r → CPU saturation; high b and high wa → I/O (go to M4); high st → virtualization.mpstat -P ALL 1: Overall usage is not high, but one CPU is at 100% → single-thread bottleneck or concentrated interrupts.pidstat 1/top: Identify the process;pidstat -t -p PID 1identifies the thread;pidstat -wshows context switches.- Is the service in a cgroup? Compare
systemctl show myapp -p CPUQuotaPerSecUSecwithcpu.stat.
Tool comparison
| top | htop | vmstat | mpstat | pidstat | |
|---|---|---|---|---|---|
| Granularity | System + process | System + process/thread (tree view) | System | Per CPU | Process/thread |
| Advantages | Available everywhere; supports batch processing with -b | Interactive and user-friendly; can display cgroup, I/O, and PSI columns | CPU, memory, and I/O on one screen | Finds per-core bottlenecks | Scrolling output, suitable for recording; can also collect statistics for short-lived processes |
| Limitations | Interactive refreshes can miss short-lived processes | Requires installation | Not per-process | Not per-process | Requires sysstat |
Figure 2-1: Which tasks does load average measure?
Figure 2-2: CPU problem decision process
Load average simulator: R tasks and D tasks
This simulates a 2-vCPU linuxlab. Each time the “clock” advances by 5 seconds, the kernel executes calc_global_load() once: it counts the number n of R + D tasks and updates the 1/5/15-minute loads using load = load·e + n·(1−e) (where e is exp(−5/60), exp(−5/300), and exp(−5/900), respectively). Observe: adding tasks in D state increases the load, but CPU utilization remains unchanged.
Core Commands and Parameters
| Command | Function | Key Parameters / Description |
|---|---|---|
cat /proc/loadavg | Raw load value | Column 4 2/183 = current runnable count / total number of schedulable entities; column 5 = most recent PID |
top -b -n1 -o %CPU | Batch snapshot | -H threads, -p PID, -c full command line; press 1 during interaction to view per-CPU data |
htop | Interactive | F2 Setup can add PSI, IO, and CGROUP columns; F5 tree view; H show/hide user threads |
vmstat 1 | r, b, cs, in, us/sy/id/wa/st | -w wide format, -t add timestamps |
mpstat -P ALL 1 | Per-CPU time distribution | -I SUM/-I SCPU interrupt statistics |
pidstat -u 1 / -t -p PID 1 / -w 1 | Process CPU / threads / context switches | cswch/s voluntary switches (waiting for resources), nvcswch/s involuntary switches (preempted, a signal of CPU contention) |
ps -eo pid,stat,pcpu,wchan:32,comm --sort=-pcpu | State + kernel wait point | R, D, S in STAT; wchan shows which kernel function the process is sleeping in |
systemd-cgtop | View CPU/memory/I/O by cgroup (service) | -m sort by memory; quickly identify “which service” |
vmstat -w 1 5 mpstat -P ALL 1 1 pidstat -u 1 3 pidstat -w 1 3 | sort -k5 -nr | head
--procs-- -----------------------memory---------------------- ---swap-- -----io---- -system-- ----------cpu---------- r b swpd free buff cache si so bi bo in cs us sy id wa st gu 3 0 0 2652880 61312 813004 0 0 0 8 2071 398 99 1 0 0 0 0 10:21:04 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 10:21:05 all 99.50 0.00 0.50 0.00 0.00 0.00 0.00 0.00 0.00 0.00 10:21:05 0 99.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 10:21:05 1 100.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
How to verify: r(3)> nproc(2), us≈100, id=0 → CPU saturation; some avg10 in /proc/pressure/cpu also rises synchronously. Common mistake: looking only at the first screen of top without pressing 1 to expand each CPU, thereby missing a single-CPU bottleneck.
Find D tasks in D state and where they are stuck
ps -eo pid,stat,wchan:32,comm | awk 'NR==1 || $2 ~ /^D/' sudo cat /proc/$(pgrep -f 'stress-ng-hdd' | head -1)/stack 2>/dev/null | head # sudo cat /proc/$(pgrep -f 'stress-ng-hdd' | head -1)/stack 2>/dev/null | head # Kernel call stack (requires root)
PID STAT WCHAN COMMAND 5120 D io_schedule stress-ng-hdd 5121 D folio_wait_bit_common stress-ng-hdd
cgroup CPU throttling
# Limit a test service to 20% CPU (equivalent to cpu.max = 20000 100000) sudo systemd-run --unit=quota-demo -p CPUQuota=20% stress-ng --cpu 1 --timeout 120s sleep 10 systemctl show quota-demo -p CPUQuotaPerSecUSec cat /sys/fs/cgroup/system.slice/quota-demo.service/cpu.max grep -E 'nr_periods|nr_throttled|throttled_usec' /sys/fs/cgroup/system.slice/quota-demo.service/cpu.stat cat /sys/fs/cgroup/system.slice/quota-demo.service/cpu.pressure
CPUQuotaPerSecUSec=200ms 20000 100000 nr_periods 98 nr_throttled 97 throttled_usec 7802114 some avg10=79.85 avg60=40.11 avg300=9.02 total=7811020 full avg10=79.85 avg60=40.11 avg300=9.02 total=7808800
Production use: When a service is slow but overall machine CPU usage is not high, check the service cgroup’s cpu.stat first. Cleanup: sudo systemctl stop quota-demo.
Lab 2: CPU Saturation vs. I/O Stalls—Same High Load, Completely Different Causes (Approximately 6 Minutes)
sudo ~/linuxlab/faults/inject.sh cpu sleep 60; uptime; vmstat 1 3; cat /proc/pressure/cpu
10:31:10 up 2:37, 1 user, load average: 1.95, 0.88, 0.40 r b ... us sy id wa st gu 2 0 ... 100 0 0 0 0 0 some avg10=48.92 avg60=37.10 avg300=11.44 total=41022314 full avg10=0.00 avg60=0.00 avg300=0.00 total=0
pidstat -u 1 3 | tail -n 5 top -b -n1 -o %CPU | sed -n '7,12p' systemd-cgtop -n 1 -b | head
sudo ~/linuxlab/faults/reset.sh sudo ~/linuxlab/faults/inject.sh iohog sleep 60; uptime; vmstat 1 3 ps -eo pid,stat,wchan:32,comm | awk 'NR==1 || $2 ~ /^D/' cat /proc/pressure/io
10:34:20 up 2:40, 1 user, load average: 2.41, 1.30, 0.71 r b ... us sy id wa st gu 0 2 ... 2 6 31 61 0 0 some avg10=88.20 avg60=70.13 avg300=22.40 total=50112230 full avg10=72.11 avg60=58.20 avg300=18.33 total=40122100
The load is likewise above 2, but r=0, b=2, wa is high, and the CPU has a large amount of idle time—this is what “high load ≠ insufficient CPU” means. The values are heavily affected by the disk type (they may not be obvious on an NVMe host; you can change --hdd to 4).
pidstat -w 1 3 | grep -E 'stress|Command'
During a CPU fault, nvcswch/s (being preempted) for stress-ng-cpu is high; during an I/O fault, cswch/s (voluntarily yielding while waiting for I/O) for stress-ng-hdd is high.
sudo ~/linuxlab/faults/reset.sh; uptime
Case 1: Load 120, but the CPU is 90% idle
Problem: An application server with an NFS mount has sustained load above 100, and even SSH logins are very slow. Approach: vmstat shows b=118; ps ... wchan shows many processes stuck in rpc_wait_bit_killable/nfs_*; the NFS server's network connection is interrupted. Configuration: After restoring the network, evaluate changing the mount options from hard to reasonable settings with timeo/retrans, and move critical paths off NFS. Limitation: Processes in the D state cannot be killed; you can only wait for I/O to return or reboot.
Case 2: Cloud host periodically slows down—%steal
Problem: API latency rises every afternoon on a burstable instance. Approach: mpstat shows %steal at 30–50%, and cloud monitoring shows that CPU credits have been exhausted. Configuration: Switch to a non-burstable instance type, or enable unlimited mode and evaluate the cost. Limitation: st can only be observed in a virtual machine; physical machines do not have this column.
Case 3: A single core saturated by soft interrupts
Problem: Throughput cannot increase on a high-concurrency gateway, while total machine CPU usage is only 25%. Approach: mpstat -P ALL 1 shows CPU0 %soft at 100%, with the others idle; cat /proc/interrupts shows that the network card has only one queue. Configuration: Enable network-card multiqueue (ethtool -L) or RPS (/sys/class/net/eth0/queues/rx-0/rps_cpus), and confirm that irqbalance is running. Limitation: The number of available queues is determined by the network card/virtual network card.
Common errors and solutions
INFO: task kworker/u4:2:812 blocked for more than 120 seconds.
Cause: The kernel hung task detector found that a task had remained in the D state for longer than kernel.hung_task_timeout_secs (120 seconds by default). This is usually caused by unresponsive storage or NFS, but may also be a kernel lock deadlock. It is usually followed by "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. and a call stack.
sudo dmesg -T | grep -A20 "blocked for more than" iostat -xz 1 3 ps -eo pid,stat,wchan:32,comm | awk '$2 ~ /^D/'
Fix: Locate the subsystem based on the call stack (block device, filesystem, NFS); check the storage path; do not merely turn off the warning.
Symptom: top shows %CPU 380%, but the machine has only 2 vCPUs?
Cause: I (the Irix mode switch) was pressed in top, or the screenshot was taken on a machine with more cores; in Irix mode, a process's %CPU is 100% per core, and a multithreaded process can reach nproc×100%.
Fix: Press I to switch to Solaris mode (normalized by total CPU); use the pidstat output as the reference.
myapp is responding slowly; overall system CPU usage is only 30%, but nr_throttled in cpu.stat continues to increase
Cause: The service unit has CPUQuota= configured (or the container uses --cpus), and is suspended after exhausting its quota within each 100 ms period. A multi-worker gunicorn can easily exhaust its quota within the first few milliseconds of a period.
systemctl show myapp -p CPUQuotaPerSecUSec -p CPUWeight cat /sys/fs/cgroup/system.slice/myapp.service/cpu.stat
Fix: Increase or remove CPUQuota. For latency-sensitive services, prioritize using CPUWeight= for relative guarantees; apply the change with sudo systemctl set-property myapp CPUQuota=150% (takes effect immediately and is persisted as a drop-in).
Occasional errors such as pidstat: command not found / Cannot open /proc/PID/stat
Cause: sysstat is not installed; or the process exited during sampling (short-lived process).
Fix: sudo apt install sysstat; use execsnoop-bpfcc (M7) to discover CPU consumption by short-lived processes—these “invisible CPU killers” often do not appear in top.
1. List all processes in D state and the functions they are waiting for in the kernel.
ps -eo pid,stat,wchan:32,comm | awk 'NR==1 || $2 ~ /^D/'
2. Display the CPU usage of each thread of the myapp main process every second, 5 times.
pidstat -t -u -p "$(systemctl show -p MainPID --value myapp)" 1 5
4-vCPU cloud host: load 3.9, mpstat shows all %usr at 25, CPU2 %usr at 100, and the others near 0; the business team says, “Why is it slow when CPU usage is only 25%?” How should this be explained? How should it be handled?
The application has a single-thread bottleneck (or one hot thread) and can use only one core; 25% overall is exactly 1/4. A load close to 4 indicates that other tasks are also queued or in D state; check vmstat's r/b values to distinguish between them. To handle it: use pidstat -t -p PID 1 to find hot threads and perf top -p PID to inspect hot functions; the long-term solution is to increase concurrency (more workers/processes) or optimize the algorithm; adding cores cannot resolve a single-thread bottleneck.
Verified Instructional Videos
Official and First-Partyial and First-Party Materials
- Linux Load Averages: Solving the Mystery(Brendan Gregg)
- proc_loadavg(5)
- vmstat(8) · top(1)
- EEVDF Scheduler(kernel.org)
- Control Group v2 (cpu.max / cpu.stat / cpu.pressure)
Video Storyboard Script (approximately 80 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
generate video/MP3; a storyboard and narration script have been provided.Visual: Two CPU blocks, a queued task queue, and a waiting area labeled “Disk.”
Narration: Linux load counts tasks that are running, waiting in the queue, and stuck on disk.
Visual: One sampling point every 5 seconds, with the curve rising smoothly; the 1-, 5-, and 15-minute curves catch up at different speeds.
Narration: The kernel samples once every five seconds and calculates an exponentially decaying average, so load is always half a beat behind.
Visual: A comparison of two vmstat views: high r and high us; high b and high wa.
Narration: High r means the CPU is insufficient; high b means I/O is blocked. The load may be equally high, but the remedies are completely different.
Module 3 · Memory: OOM, Swap, and Page Cache
- Understand the columns in
free, explain why the page cache “uses” memory without being a problem, and understand the meaning ofavailable. - Describe the kernel’s sequence of actions when memory is tight: reclaim page cache → reclaim anonymous pages to swap → trigger the OOM killer; understand how the overcommit policy affects
malloc. - Understand kernel OOM logs and use
oom_score/oom_score_adj(systemd’sOOMScoreAdjust=) to protect critical processes. - Distinguish system-wide OOM from cgroup OOM (
MemoryMax=/memory.max), and usememory.events,memory.pressure, and PSI for diagnosis.
What: The Several “Ledgers” of Linux Memory
| Category | What it is | Can it be reclaimed | Where to view it |
|---|---|---|---|
| Anonymous pages (anon) | Process heaps, stacks, and memory obtained through malloc | Can only be swapped out to swap; cannot be reclaimed without swap | AnonPages in /proc/meminfo; RssAnon in the process RSS |
| Page cache | Cache of file contents (read files, executable files, logs) | Clean pages can be discarded directly; dirty pages (Dirty) must first be written back to disk | buff/cache in free; Cached, Dirty |
| Shared memory / tmpfs (Shmem) | /dev/shm, /run, and tmpfs files | Can only be swapped out to swap | shared in free; df -h -t tmpfs |
| Kernel slab | dentry/inode caches, network buffers, and more | The SReclaimable portion can be reclaimed | slabtop, /proc/meminfo |
available (MemAvailable since kernel 3.14) is the kernel’s estimate of “how much more can be used by new programs without triggering swapping,” approximately equal to free + reclaimable page cache and slab − watermark reserves. To determine whether memory is under pressure, look at available, not free.
Why: Why Memory Problems Are Dangerous
Insufficient CPU merely makes things “slow”; insufficient memory can make things “die”: to protect itself, the kernel selects a process and sends it SIGKILL. More insidiously, there is memory pressure: after the page cache is squeezed out, every file read must access the disk (including the executable files themselves), and the system undergoes severe thrashing, manifested as a sharp load spike and a frozen SSH session, but without OOM yet.
How: What the Kernel Does When Memory Is Under Pressure
- Background reclamation: when free pages fall below the low watermark,
kswapdwakes up and reclaims page cache and anonymous pages (according tovm.swappiness, 60 by default). - Direct reclamation: below the min watermark, the process requesting memory reclaims memory itself—which directly slows the application and increases PSI memory.
- OOM killer: when reclamation is ineffective, the kernel calculates each process’s
oom_score(roughly, the proportion of RSS + swap + page tables to available memory, in the range 0–1000), then addsoom_score_adj(−1000 to 1000) and kills the process with the highest score.oom_score_adj = -1000means it will never be selected. - cgroup OOM: when a service has
MemoryMax=set (memory.maxin cgroup v2), once the limit is exceeded, reclamation and process killing occur only within that cgroup. The log recordsMemory cgroup out of memory, theoom_killcount inmemory.eventsincreases by one, and systemd records the service result asoom-kill.MemoryHigh=(memory.high) is a “soft limit”: after it is exceeded, forced reclamation and throttling occur, but processes are not killed.
overcommit: Why malloc Rarely Fails
vm.overcommit_memory | Behavior | Applicable To |
|---|---|---|
| 0 (default) | Heuristic: only allocations that are clearly impossible to satisfy are rejected; insufficient memory during actual use → OOM | General-purpose |
| 1 | Always allow | Some scientific computing applications; officially recommended for Redis (to avoid fork snapshot failures) |
| 2 | Strict: committed memory must not exceed swap + RAM × overcommit_ratio% | Systems that would rather have malloc fail than encounter OOM; check CommitLimit / Committed_AS in /proc/meminfo |
PSI and systemd-oomd
some in /proc/pressure/memory indicates the proportion of time during which at least one task is stalled due to memory (reclamation, swapping in, or refaults); full indicates the proportion of time during which all non-idle tasks are stalled simultaneously. systemd-oomd uses PSI and swap utilization to kill, by cgroup, the unit under the greatest pressure before a kernel OOM occurs (configure ManagedOOMMemoryPressure=kill, ManagedOOMSwap=kill). It is enabled by default on Ubuntu Desktop; on the Server edition, whether the systemd-oomd package is installed depends on the actual system (systemctl status systemd-oomd).
When: Diagnostic Procedure
free -m: What proportion is available? Is swap used increasing?vmstat 1: si/so continuously nonzero → swapping is in progress (a true pressure signal).cat /proc/pressure/memory: some avg10 > 10 warrants attention.journalctl -k | grep -i -E "out of memory|oom": Has anyone already been killed?- Who is using it:
ps -eo pid,rss,comm --sort=-rss | head,systemd-cgtop -m,pidstat -r 1(look at RSS growth = a leak).
Comparison: Several Types of “Insufficient Memory”
| System-wide OOM | cgroup OOM(MemoryMax) | MemoryHigh Throttling | systemd-oomd | |
|---|---|---|---|---|
| Trigger | Global memory exhausted and reclaim failed | cgroup usage reached memory.max | Exceeded memory.high | PSI pressure / swap exceeded threshold |
| Action | Kill the process with the highest global oom_score | Select a process to kill only within this cgroup | Force reclaim + slow down processes | Kill the entire cgroup (unit) |
| Logs | Out of memory: Killed process | Memory cgroup out of memory: Killed process | No kill; the high count in memory.events | systemd-oomd journal messages
drop_caches regularly”—this discards useful cache, causing all subsequent reads to hit the disk; it is only suitable for clearing the cache before benchmarking. ② “Performance is better with swap disabled”—without swap, anonymous pages cannot be reclaimed, so the kernel can only discard page cache more aggressively, eventually causing OOM sooner; a small amount of swap is often recommended as a buffer (except in special scenarios such as container nodes). ③ “Adding up process RSS gives the total usage”—shared libraries and shared memory are counted repeatedly; use PSS (/proc/PID/smaps_rollup) for greater accuracy. ④ “OOM always kills the process using the most memory”—oom_score_adj changes the ordering, and cgroup OOM selects a process only within that cgroup.Figure 3-1: Escalation path from memory pressure to OOM
Figure 3-2: cgroup v2 memory control files (using myapp.service as an example)
Memory pressure simulator: reclaim → swap → OOM victim selection
A linuxlab simulating 4 GiB of memory (with options to enable/disable swap and to set the leaking process's cgroup MemoryMax=300M). At each step, the leaking process requests another 200 MiB (50 MiB in cgroup mode). Observe the kernel first reclaim page cache, then swap out anonymous pages, and finally have the OOM killer select a victim based on oom_score (RSS proportion × 1000 + oom_score_adj).
Core commands and parameters
| Command | Function | Description |
|---|---|---|
free -m / free -h -w | Memory overview | Check available; -w separates buffers and cache |
grep -E 'MemAvailable|Dirty|Writeback|AnonPages|Shmem|SReclaimable|Commit' /proc/meminfo | Detailed accounting | Persistently high Dirty indicates that writeback cannot keep up |
vmstat 1 | si/so swapping in/out | Only persistent nonzero values are a problem; occasional small values are normal |
ps -eo pid,user,rss,vsz,comm --sort=-rss | head | Sort by RSS | RSS is in KiB; a large VSZ does not mean it is actually being used |
pidstat -r 1 | View RSS and page faults by process | High majflt/s (page faults requiring disk reads) = thrashing |
sudo cat /proc/PID/smaps_rollup | RSS/PSS/Swap summary | PSS apportions usage according to the sharing ratio |
cat /proc/PID/oom_score /proc/PID/oom_score_adj | OOM score | -1000 is never selected; 1000 is selected first |
systemctl show myapp -p MemoryCurrent -p MemoryMax -p MemoryHigh -p OOMScoreAdjust | Service memory properties | A value of infinity indicates no limit |
journalctl -k -g 'Out of memory|oom-kill' | OOM records | -g performs a regular expression match (journalctl must support PCRE2; Ubuntu supports it by default) |
swapon --show, cat /proc/sys/vm/swappiness | Swap configuration | Multipass cloud images have no swap by default |
free -h -w grep -E 'MemTotal|MemAvailable|Cached|Dirty|AnonPages|Shmem:|CommitLimit|Committed_AS' /proc/meminfo cat /proc/pressure/memory
total used free shared buffers cache available Mem: 3.8Gi 702Mi 1.9Gi 1.1Mi 64Mi 1.2Gi 3.1Gi Swap: 0B 0B 0B MemTotal: 3995664 kB MemAvailable: 3231200 kB Cached: 1190220 kB Dirty: 120 kB AnonPages: 560312 kB Shmem: 1132 kB CommitLimit: 1997832 kB Committed_AS: 1532040 kB some avg10=0.00 avg60=0.00 avg300=0.00 total=21043 full avg10=0.00 avg60=0.00 avg300=0.00 total=8812
Understanding Kernel OOM Logs (cgroup OOM, Example)
python3 invoked oom-killer: gfp_mask=0xcc0(GFP_KERNEL), order=0, oom_score_adj=0 CPU: 1 UID: 0 PID: 6120 Comm: python3 Not tainted 7.0.0-42-generic #42-Ubuntu ... memory: usage 307200kB, limit 307200kB, failcnt 41 swap: usage 0kB, limit 0kB, failcnt 0 ... oom-kill:constraint=CONSTRAINT_MEMCG,nodemask=(null),cpuset=/,mems_allowed=0,oom_memcg=/system.slice/fault-memleak.service,task_memcg=/system.slice/fault-memleak.service,task=python3,pid=6120,uid=0 Memory cgroup out of memory: Killed process 6120 (python3) total-vm:322340kB, anon-rss:300120kB, file-rss:5632kB, shmem-rss:0kB, UID:0 pgtables:668kB oom_score_adj:0
How to read it: The first line shows “who triggered it” (not necessarily the process that was killed); constraint=CONSTRAINT_MEMCG and oom_memcg= indicate a cgroup OOM and identify the service involved; the last line shows the killed process and its anon-rss. For a system-wide OOM, constraint is CONSTRAINT_NONE, and the last line is Out of memory: Killed process ....
The systemd Perspective
systemctl status fault-memleak --no-pager | head -12 journalctl -u fault-memleak --no-pager | grep -E "OOM|oom-kill|Failed with result"
fault-memleak.service: A process of this unit has been killed by the OOM killer. fault-memleak.service: Main process exited, code=killed, status=9/KILL fault-memleak.service: Failed with result 'oom-kill'. fault-memleak.service: Scheduled restart job, restart counter is at 1.
Protecting Critical Services
# Reduce the probability of myapp being selected for system-wide OOM, and give it a soft limit and a hard limit (drop-in, reversible) sudo systemctl edit myapp --drop-in=50-memory --stdin <<'EOF' [Service] OOMScoreAdjust=-500 MemoryHigh=600M MemoryMax=800M EOF sudo systemctl restart myapp systemctl show myapp -p OOMScoreAdjust -p MemoryHigh -p MemoryMax cat /proc/$(systemctl show -p MainPID --value myapp)/oom_score_adj
systemctl edit --stdin requires a newer systemd (256+; 259 in 26.04 supports it); on 24.04 (systemd 255), use the interactive sudo systemctl edit myapp and paste the same content. Note: Do not set Redis or databases to −1000—when they leak, the kernel can only kill other processes, potentially causing the entire system to hang.
Lab 3: OOM from a Memory Leak in a cgroup, and Reading All the Evidence (approximately 7 minutes)
sudo ~/linuxlab/faults/inject.sh memleak CG=/sys/fs/cgroup/system.slice/fault-memleak.service for i in $(seq 8); do printf '%s current=%sM ' "$(date +%T)" $(( $(cat $CG/memory.current) / 1048576 )); grep -E '^(max|oom_kill) ' $CG/memory.events | tr '\n' ' '; echo; sleep 2; done
10:42:01 current=52M max 0 oom_kill 0 10:42:03 current=132M max 0 oom_kill 0 10:42:05 current=213M max 0 oom_kill 0 10:42:07 current=294M max 12 oom_kill 0 10:42:09 current=0M max 31 oom_kill 1 10:42:11 current=0M max 31 oom_kill 1 10:42:13 current=0M max 0 oom_kill 0 10:42:15 current=71M max 0 oom_kill 0
Restart=on-failure + RestartSec=5 causes the service to restart after being killed, and the counters reset to zero with the new cgroup—in production, “restart self-healing” can mask leaks, so you must check the restart count and logs.
journalctl -k --since "-5min" -g 'oom-kill|Killed process' --no-pager journalctl -u fault-memleak --since "-5min" --no-pager | grep -E 'OOM|result' systemctl show fault-memleak -p NRestarts -p MemoryMax -p MemorySwapMax cat /sys/fs/cgroup/system.slice/fault-memleak.service/memory.pressure
PID=$(systemctl show -p MainPID --value fault-memleak) pidstat -r -p "$PID" 1 5
10:43:20 UID PID minflt/s majflt/s VSZ RSS %MEM Command 10:43:21 0 6402 5120.00 0.00 133912 112640 2.82 python3 10:43:22 0 6402 5121.00 0.00 154396 133120 3.33 python3
RSS grows steadily by about 20 MiB per second, and minflt/s is high—a typical “only goes up” leak pattern.
for p in $(pgrep -f gunicorn | head -2) $(pgrep redis-server) $PID; do printf '%-7s %-16s score=%-4s adj=%s\n' $p "$(cat /proc/$p/comm)" "$(cat /proc/$p/oom_score)" "$(cat /proc/$p/oom_score_adj)"; done
2101 gunicorn score=668 adj=0 2102 gunicorn score=671 adj=0 1890 redis-server score=667 adj=0 6402 python3 score=696 adj=0
On newer kernels (since 5.9), /proc/PID/oom_score displays (1000 + badness×1000/available pages) × 2/3. badness already includes oom_score_adj, so a process with adj=0 and low memory usage will have a score of about 667. Actual values may vary; the key is to compare relative values. After adding OOMScoreAdjust=-500 to myapp on the “Commands” tab, run this again; gunicorn’s score will drop noticeably.
sudo ~/linuxlab/faults/reset.sh # If you added a memory drop-in for myapp and want to undo it: # sudo rm /etc/systemd/system/myapp.service.d/50-memory.conf && sudo systemctl daemon-reload && sudo systemctl restart myapp
Case 1: “Memory leak” is actually page cache
Problem: Monitoring shows a log server at 95% memory usage, and the on-call staff run echo 3 > /proc/sys/vm/drop_caches from cron every night. Action: Check that available memory stays at 60% and PSI is 0; the “usage” calculation incorrectly counts cache as used. Configuration: Change monitoring to use MemAvailable (node_memory_MemAvailable_bytes in node_exporter) and remove the cron job. Result: Disk reads for log queries decrease, and latency drops.
Case 2: Redis is OOM-killed, but the culprit is the batch job next door
Problem: A batch job’s memory usage surges at night, and system-wide OOM selects redis-server, which has the largest RSS. Action: Set MemoryMax= for the batch service so it OOMs within its own cgroup; set OOMScoreAdjust=-900 for Redis and configure maxmemory. Limitation: Using oom_score_adj alone cannot solve insufficient total memory; it only changes who dies first.
Case 3: The service stays up, but P99 doubles—MemoryHigh throttling
Problem: To prevent leaks, the team sets MemoryHigh= for the service, after which latency spikes periodically. Action: The high count in memory.events rises rapidly, and some avg10 in memory.pressure reaches 30%—the service is repeatedly forced to reclaim memory near the high threshold. Configuration: Reset the threshold based on peak load-test usage plus headroom, and alert on memory.events high. Limitation: MemoryHigh is a soft limit; sudden allocations may still exceed it briefly.
Common mistakes and solutions
Out of memory: Killed process 2101 (gunicorn) total-vm:..., anon-rss:..., oom_score_adj:0
Cause: The system's total memory was exhausted, and the kernel selected the process with the highest score (which is not necessarily the “culprit”).
journalctl -k -b -g 'invoked oom-killer|Killed process' --no-pager journalctl -k -b --no-pager | grep -A40 'invoked oom-killer' | grep -E '^\s*\[|rss' | head -40 # journalctl -k -b --no-pager | grep -A40 'invoked oom-killer' | grep -E '^\s*\[|rss' | head -40 # Process table at the time (fields depend on the actual output)
Fix: The OOM log prints the RSS table for all processes at that time; identify the process that was actually growing; set MemoryMax= for it; set a negative OOMScoreAdjust= for critical services; consider adding swap as a buffer.
myapp.service: Failed with result 'oom-kill'.
Cause: The cgroup containing myapp reached MemoryMax=, or the process was selected by the global OOM killer (systemd records both cases as oom-kill). OOMPolicy= defaults to stop: if any process in the unit is killed by OOM, systemd stops the entire service (whether it restarts is then determined by Restart=).
systemctl show myapp -p MemoryMax -p MemoryPeak -p OOMPolicy -p NRestarts cat /sys/fs/cgroup/system.slice/myapp.service/memory.events
Fix: Distinguish between “the limit is too low” (the peak is close to MemoryMax but stable) and a “leak” (continuous growth); gunicorn can set --max-requests to periodically recycle workers as a mitigation.
fork: Cannot allocate memory / bash: fork: retry: Resource temporarily unavailable
Cause: The former may occur when the committed amount reaches CommitLimit with vm.overcommit_memory=2, or when memory is genuinely exhausted; the latter is more commonly caused by the number of processes/threads reaching a limit (TasksMax=, ulimit -u, kernel.pid_max), not by memory.
grep -E 'CommitLimit|Committed_AS' /proc/meminfo; sysctl vm.overcommit_memory systemctl show myapp -p TasksMax -p TasksCurrent; ulimit -u
Fix: Identify the thread leak (ps -eLf | wc -l), or adjust the TasksMax / overcommit settings as needed.
Symptom: SSH hangs for several minutes, then eventually recovers, with no OOM in the logs
Cause: Thrashing: the page cache (including program code pages) is repeatedly evicted and read back in, so the system makes almost no progress without reaching the conditions for OOM.
vmstat 1 5 # vmstat 1 5 # si/so and bi are very high cat /proc/pressure/memory # cat /proc/pressure/memory # full avg10 is very high sar -B 1 5 # sar -B 1 5 # majflt/s (requires sysstat)
Fix: Set MemoryHigh/MemoryMax for the offending service; enable systemd-oomd to take action early during pressure conditions; add more memory.
1. List the 5 processes with the highest memory usage (RSS).
ps -eo pid,user,rss,comm --sort=-rss | head -n 6
2. View all OOM events since this boot and display the processes that were killed.
journalctl -k -b --no-pager | grep -E 'Killed process|oom-kill:'
free -m shows total 3800, free 120, buff/cache 2900, and available 3000; however, monitoring reports “97% memory utilization” and triggers an alert. How should this be assessed?
Memory is not under pressure: available memory is 3000 MiB (approximately 79%), and most of the “used” memory is reclaimable page cache. Then use vmstat 1 to confirm that si/so are 0 and /proc/pressure/memory is 0. The problem lies in the monitoring metric: it should be changed to (MemTotal − MemAvailable) / MemTotal, together with PSI-based alerting. Do not use drop_caches to “solve” it.
Verified Instructional Videos
Video specifically explaining the OOM killer / cgroup v2 memory control: No verified video found (most search results were articles or uploads from channels that could not be confirmed); please refer to the official documentation and storyboard below.
Official Documentation
- Control Group v2 — Memory(kernel.org)
- proc_pid_oom_score_adj(5)
- systemd.resource-control(5) · systemd-oomd.service(8)
- Overcommit Accounting(kernel.org)
- PSI (kernel.org)
Video Storyboard (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script have been providedrectly generate video/MP3 files; a storyboard and narration script have been provided.
Visual: A memory module, with green page cache occupying most of it and only a small segment left for free; the available figure beside it is large.
Narration: Linux uses free memory for page cache. A small free value is not alarming; look at available.
Visual: A red leaking process continuously grows longer, squeezing the green page cache shorter; then swap arrows appear, and the PSI gauge rises.
Narration: When memory is under pressure, the kernel first drops page cache, then swaps out anonymous pages. At this point, PSI tells you how long programs have stalled waiting for memory.
Visual: Several processes display oom_score values above them; the one with the highest score is struck by a red lightning bolt, and the log line Killed process appears.
Narration: If reclamation fails, the OOM killer selects a victim by score. oom_score_adj can adjust the ordering.
Visual: The leaking process is locked in a cage labeled MemoryMax, where it is killed, while the other services remain unharmed.
Narration: Set MemoryMax for a suspicious service so that OOM occurs only within its own cgroup.
Module 4 · Disk I/O: iostat, iotop, and File System Issues
- Understand the key columns of
iostat -x:r/s w/s,rkB/s wkB/s,r_await w_await,aqu-sz, and%util, and know the limitations of %util on SSDs/NVMe. - Use
iotop-candpidstat -dto find processes generating I/O; use PSI io to determine whether I/O is actually causing tasks to stall. - Distinguish between block exhaustion (
df -hat 100%), inode exhaustion (df -iat 100%), and deleted but still-open files (a mismatch betweendfanddu), and repair them safely.
What: The Path Taken by an I/O Operation
An application calls read()/write() → VFS → file system (ext4/XFS) → page cache (most writes go only to the page cache and are marked as dirty pages, which are later flushed to disk by the kernel writeback thread) → block layer (merging, scheduler mq-deadline/none) → device driver (virtio-blk, NVMe) → disk. iostat counts requests at the block layer, so reads served from the page cache do not appear in iostat.
Key Columns of iostat -x
| Column | Meaning | How to Interpret It |
|---|---|---|
r/s w/s | Read/write requests completed per second (IOPS) | Compare with the disk specifications (cloud disk IOPS limit) |
rkB/s wkB/s | Throughput | Compare with the bandwidth limit |
rareq-sz wareq-sz | Average request size (KB) | More small I/O operations (4K) → IOPS reaches its limit first |
r_await w_await | Average request latency (ms), including queueing time | Normally < 1–2ms for SSDs; a few ms for cloud disks; tens or hundreds of ms indicates saturation or a fault |
aqu-sz | Average queue length (number of in-flight requests) | Saturation indicator: if it continuously exceeds the number of operations the device can process in parallel, requests are queued |
%util | Proportion of time the device has “at least one request in flight” | Meaningful for single-queue HDDs; for SSDs/NVMe/RAID/cloud disks, 100% does not mean the device has reached its maximum capability |
Starting with sysstat 12, the old svctm column was removed (because it was unreliable); columns related to discard (d/s) and flush (f/s) were also added.
Why: Why capacity-related failures are particularly common
Logs growing without limit, temporary files not being cleaned up, a program creating a small session file for every request, a process failing to reopen files after log rotation… None of these are “performance” problems; they are “configuration/operations” problems. But the consequences are serious: write failures (ENOSPC), databases refusing writes, journald stopping recording, and even the system becoming unable to log in (because it cannot write state files under /var/lib).
How: Three types of “disk full”
| Blocks exhausted | Inodes exhausted | Deleted but still open | |
|---|---|---|---|
| Symptom | Writes report No space left on device | Also reports No space left on device, but df -h still shows available space | df shows full, while the total from du is far less than the used space |
| Root cause | Large files, logs, backups | Huge numbers of small files (sessions, caches, mail queues) | The file was removed with rm, but a process still holds its file descriptor, so the inode and data blocks have not been released |
| Diagnosis | df -h, du -xh -d1, ncdu | df -i; count files by directory | lsof +L1, ls -l /proc/*/fd | grep deleted |
| Fix | Delete/compress/expand capacity | Delete small files and fix the program; ext4’s inode count is determined at mkfs time and cannot be increased online (XFS allocates dynamically) | Restart or have the process reopen the file; in an emergency, truncate it with : > /proc/PID/fd/N |
Also: ext4 reserves 5% of blocks for root by default (Reserved block count in tune2fs -l), so when ordinary users see “full,” root can still write; the Avail column in df has already excluded the reserved portion.
When: Diagnostic workflow
- Error
No space left on device→ check bothdf -handdf -i; if neither is full → it may be a quota or tmpfs size issue. - Large discrepancy between
dfanddu→lsof +L1; if the discrepancy still cannot be explained → files may be “covered” by a mount point (data written before the mount). - “Slow” →
iostat -xz 1: high await + high aqu-sz → saturation; high await but very low IOPS → device/cloud-disk failure or throttling; then useiotop-c -o/pidstat -d 1to find the process, and usebiolatency-bpfcc(M7) to view the latency distribution. - I/O error / filesystem read-only appears in the kernel log → a hardware or underlying storage problem; prioritize protecting the data.
Tool comparison
| iostat -x | iotop-c | pidstat -d | PSI io | biolatency-bpfcc | |
|---|---|---|---|---|---|
| Granularity | Device | Process/thread (real-time sorting) | Process (rolling) | System / cgroup | Device latency histogram |
| Dependencies | sysstat | iotop-c; some columns require kernel.task_delayacct=1 | sysstat | Built into the kernel | bpfcc-tools, root |
sync can make I/O faster” — it only forces dirty pages to be flushed and often makes the problem worse.Figure 4-1: The I/O stack and observation points
Figure 4-2: Why df and du do not match
df / df -i / du Three-View Simulator
Simulate the 100 MiB loopback filesystem /mnt/faultdisk (ext4, 2,048 inodes, -m 0) created by inject.sh. Click the buttons to perform the operations, observe how the three views change, and see when the process fault-writer, which continuously writes logs, begins reporting errors.
Core Commands and Options
| Command | Function | Description |
|---|---|---|
iostat -xz 1 | Device-level extended statistics | -m MB; -p sda includes partitions; -d shows devices only |
sudo iotop-c -o -P | Show only processes with I/O | -b -n 3 batch mode; the SWAPIN/IO% columns require sudo sysctl kernel.task_delayacct=1 |
pidstat -d 1 | Process read/write rates and iodelay | iodelay is the number of clock ticks spent waiting for block I/O |
df -hT / df -i | Block / inode usage | -x tmpfs -x squashfs filters out noise |
sudo du -xh -d1 / | sort -h | Calculate size by directory | -x does not cross file systems |
sudo du -x --inodes -d1 /var | sort -n | Calculate inode counts by directory (GNU du) | Rust coreutils by default in 26.04; if this option is unsupported, use the find syntax below instead |
sudo lsof +L1 | Deleted but still-open files | The NLINK column is 0; you can also use lsof -nP | grep '(deleted)' |
sudo tune2fs -l /dev/sda1 | grep -i -E 'inode count|free inodes|reserved block' | ext4 metadata | For XFS, use xfs_info |
journalctl --disk-usage / --vacuum-size=200M | Log usage and cleanup | For persistent settings, write SystemMaxUse= in journald.conf |
cat /proc/pressure/io | I/O pressure | A high full value means all tasks are waiting for I/O |
iostat -xz 1 3
Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz w/s wkB/s wrqm/s %wrqm w_await wareq-sz aqu-sz %util sda 1520.0 97280.0 0.00 0.00 3.10 64.00 1650.0 105600.0 12.0 0.72 18.40 64.00 35.10 99.80
How to read it: w_await 18ms and aqu-sz 35 indicate that requests are queued; %util 99.8 on a virtual disk is only corroborating evidence that it is “busy all the time.” Production use: Compare against the cloud disk’s IOPS/throughput limits to determine whether it is “being throttled” or the disk itself is slow.
Find inode-heavy directories (general method)
sudo find /var -xdev -type f 2>/dev/null | awk -F/ '{print "/"$2"/"$3"/"$4}' | sort | uniq -c | sort -nr | head
Handle deleted but still-open files
sudo lsof -nP +L1 # Preferred: have the process reopen the files (restart the service or send it a log-reopen signal, such as nginx's USR1) # Emergency: truncate the file pointed to by this file descriptor to release space immediately (data will be lost!) PID=$(systemctl show -p MainPID --value fault-holder) ls -l /proc/$PID/fd | grep deleted sudo truncate -s 0 /proc/$PID/fd/3
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NLINK NODE NAME sleep 7310 root 3w REG 7,0 83886080 0 13 /mnt/faultdisk/huge.log (deleted) l-wx------ 1 root root 64 Nov 17 10:55 3 -> /mnt/faultdisk/huge.log (deleted)
Note that COMMAND shows sleep: the script replaced bash with exec sleep infinity, but inherited fd 3—this is exactly what an “innocent-looking process holding a large file” looks like in the real world.
Experiment 4: Disk full, inode exhaustion, and deleted-open—the three-in-one (approximately 7 minutes)
sudo ~/linuxlab/faults/inject.sh disk-full df -h /mnt/faultdisk; df -i /mnt/faultdisk sleep 4; journalctl -t fault-writer --since "-1min" --no-pager | tail -n 2 sudo du -xh -d1 /mnt/faultdisk | sort -h
Filesystem Size Used Avail Use% Mounted on /dev/loop0 90M 90M 0 100% /mnt/faultdisk Filesystem Inodes IUsed IFree IUse% Mounted on /dev/loop0 2048 14 2034 1% /mnt/faultdisk Nov 17 11:01:12 linuxlab fault-writer[7120]: write failed: date: write error: No space left on device 90M /mnt/faultdisk/bigfile
A 100 MiB image has approximately 90 MiB available after formatting (the remainder is used by the journal area and metadata). To fix: sudo rm /mnt/faultdisk/bigfile; the writer will recover after a few seconds.
sudo ~/linuxlab/faults/reset.sh >/dev/null
sudo ~/linuxlab/faults/inject.sh inode
df -h /mnt/faultdisk; df -i /mnt/faultdisk
touch /mnt/faultdisk/test.txt
sudo find /mnt/faultdisk -xdev -type f | awk -F/ '{print "/"$2"/"$3"/"$4}' | sort | uniq -c | sort -nr | head -3
Filesystem Size Used Avail Use% Mounted on /dev/loop0 90M 124K 90M 1% /mnt/faultdisk Filesystem Inodes IUsed IFree IUse% Mounted on /dev/loop0 2048 2048 0 100% /mnt/faultdisk touch: cannot touch '/mnt/faultdisk/test.txt': No space left on device 2035 /mnt/faultdisk/sessions
Only 1% of the space is used, yet “No space left on device” is reported—this is inode exhaustion. To fix: sudo find /mnt/faultdisk/sessions -type f -delete; prevention: cleanup jobs (D/e rules in systemd-tmpfiles) and application changes.
sudo ~/linuxlab/faults/reset.sh >/dev/null sudo ~/linuxlab/faults/inject.sh deleted-open sleep 2 df -h /mnt/faultdisk; sudo du -sh /mnt/faultdisk sudo lsof -nP +L1 /mnt/faultdisk
Filesystem Size Used Avail Use% Mounted on /dev/loop0 90M 81M 9.6M 90% /mnt/faultdisk 16K /mnt/faultdisk COMMAND PID USER FD TYPE DEVICE SIZE/OFF NLINK NODE NAME sleep 7310 root 3w REG 7,0 83886080 0 13 /mnt/faultdisk/huge.log (deleted)
PID=$(systemctl show -p MainPID --value fault-holder) sudo truncate -s 0 /proc/$PID/fd/3; df -h /mnt/faultdisk | tail -1 sudo systemctl stop fault-holder; sudo lsof -nP +L1 /mnt/faultdisk; echo "lsof exit=$?"
sudo ~/linuxlab/faults/inject.sh iohog, then iostat -xz 1 5, sudo iotop-c -o -b -n 3, pidstat -d 1 3, and cat /proc/pressure/io.sudo ~/linuxlab/faults/reset.sh
Case 1: Disk is still full after log rotation
Problem: logrotate rotates application logs every night, but disk usage keeps increasing, while du reports that /var/log is not large. Approach: lsof +L1 shows that the application is holding a dozen or so old logs marked (deleted)—the logrotate configuration uses create mode but has no postrotate notification telling the application to reopen the files. Configuration: Add postrotate systemctl kill -s HUP app.service endscript (the application must support this), or change the setup to write logs to stdout and let journald handle them. Limitation: copytruncate can work around this, but logs written at the moment of truncation will be lost.
Case 2: PHP sessions exhaust inodes
Problem: The website suddenly cannot log users in and reports that the disk is full, while df -h shows only 40% usage. Approach: df -i shows 100% usage; there are 3 million files in the session directory, and the cleanup task stopped working long ago. Configuration: Restore the cleanup task (a systemd-tmpfiles rule) and store sessions in Redis. Limitation: Deleting millions of small files is itself slow. Use find -delete during off-peak hours to avoid rm * exceeding the argument-length limit.
Case 3: “Slow disk” caused by cloud disk throttling
Problem: Database latency spikes whenever the batch job runs on the hour. Approach: iostat -x shows w/s holding steady at around 3000, “pegged,” w_await rising from 2ms to 80ms, and aqu-sz at 60; the cloud disk’s IOPS limit is exactly 3000. Configuration: Upgrade the cloud disk performance tier or stagger the batch job. Limitation: %util stays at 100% here, so it cannot distinguish “throttling” from a “slow device”; you must compare against the specifications.
Common errors and solutions
write error: No space left on device (df -h shows space still available)
Cause: Inodes are exhausted; or the target is tmpfs (/tmp, /run) and its size limit has been reached; or the user’s disk quota has been exceeded.
df -i "$(dirname /path/to/file)"; df -h -t tmpfs; quota -s 2>/dev/null
Fix: Delete small files / increase the tmpfs size (mount -o remount,size=…) / adjust the quota.
EXT4-fs error (device sda1): ... Remounting filesystem read-only
Cause: ext4 detected a metadata error (often caused by an underlying I/O error) and switched to read-only mode to protect data, as specified by the errors=remount-ro mount option. Subsequent writes return Read-only file system.
sudo dmesg -T | grep -E 'I/O error|EXT4-fs' | tail findmnt -no OPTIONS / sudo smartctl -a /dev/sda 2>/dev/null | head -30 # sudo smartctl -a /dev/sda 2>/dev/null | head -30 # Physical disk; for cloud disks, check the platform monitoring
Fix: Back up readable data first; during a maintenance window (rescue mode, M6), unmount the filesystem and run fsck; investigate storage hardware or cloud disk events. Do not simply run mount -o remount,rw and continue writing.
I/O error, dev sda, sector 2048 op 0x1:(WRITE) flags 0x800 phys_seg 1 prio class 2
Cause: The block layer reported that the device returned an error (the field format depends on the actual kernel version). Possible causes include bad disk sectors, cables, the controller, or a cloud disk backend failure.
Fix: Record the time, confirm whether it is recurring, and prepare to migrate data or replace the disk; in the cloud, check service health events.
CONFIG_TASK_DELAY_ACCT and kernel.task_delayacct sysctl not enabled in kernel, cannot determine SWAPIN and IO %
Cause: iotop depends on task delay accounting, which is disabled by default in newer kernels (the exact wording of the message depends on the actual iotop version).
sudo sysctl kernel.task_delayacct=1 # sudo sysctl kernel.task_delayacct=1 # Enable temporarily, with minor overhead sudo iotop-c -o
Fix: Enable it temporarily while troubleshooting, then set it back to 0; or use pidstat -d instead.
umount: /mnt/data: target is busy.
Cause: A process has its current directory or an open file on this filesystem.
sudo fuser -vm /mnt/data; sudo lsof +f -- /mnt/data
Fix: Stop the relevant process; only as a last resort use umount -l (lazy unmount; processes can still access files that are already open).
1. Find all deleted files that are still open by processes and are larger than 100 MiB.
sudo lsof -nP +L1 | awk 'NR==1 || $7 > 104857600'
2. Find the 10 directories occupying the most space on the root file system (without crossing file systems).
sudo du -xh / 2>/dev/null | sort -h | tail -n 10
df -h / shows 100%, while sudo du -xsh / shows only 9 GiB (20 GiB disk), and lsof +L1 produces no output. What else could be the cause?
The data may be “hidden” by a mount point: a large amount of data was written to a directory (such as /var/lib/docker or /data) before a new file system was mounted there, so after the mount, du cannot see the files underneath. Verify with: sudo mount --bind / /mnt/rootonly && sudo du -xh -d2 /mnt/rootonly | sort -h | tail (a bind mount does not include submounts). Other possibilities: ext4 reserved blocks, snapshots (LVM thin/btrfs), and differences in sparse-file accounting.
Verified Educational Videos
Video specifically covering inode exhaustion / deleted-open files: No verified video found; please use the storyboard script below.
Official Documentation
- iostat(1) · pidstat(1)
- lsof(8)
- I/O statistics fields(kernel.org)
- ext4 Documentation (kernel.org)
- tmpfiles.d(5)
Video Storyboard Script (approximately 80 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
Visual: Three gauges: df blocks, df inodes, and du. The first gauge is full, with the error No space left on device.
Narration: The same error may mean that the blocks are full, or that the inodes have been exhausted. First, check df and df hyphen i at the same time.
Visual: rm deletes a file; the file disappears from the directory tree, but on the right, the inode is still held by a process's file descriptor, and df remains unchanged.
Narration: rm only deletes the directory entry. As long as a process still has the file open, the space will not be released. Use lsof plus L1 to find it.
Visual: iostat output, with await and aqu-sz highlighted and %util marked with a question mark.
Narration: To determine whether a disk is saturated, look at the wait time and queue length. One hundred percent util on an SSD does not necessarily mean it has reached its limit.
Module 5 · Network Troubleshooting: tcpdump, ss, and DNS
- Use
curl -wto break down the duration of a request into DNS / TCP connection establishment / TLS / time to first byte, and quickly determine which stage is slow. - Understand the states and Recv-Q/Send-Q of
ss(including the accept queue for LISTEN sockets), and usess -tiandnstatto observe RTT, retransmissions, and queue overflows. - Write commonly used
tcpdumpfilters and save pcap files; know where tcpdump captures packets in the protocol stack. - Diagnose DNS timeouts (systemd-resolved), a full conntrack table, and MTU black holes, and use
tc netemto reproduce packet loss and latency.
ip and ss commands, routing, and DNS fundamentals from Lesson 2. Importance:★★★★★What: The Four Stages of a Request
- Name resolution: The application reads
/etc/hoststhrough glibc (NSS), then queries the servers in/etc/resolv.conf. On Ubuntu,/etc/resolv.confis a symbolic link to/run/systemd/resolve/stub-resolv.conf; the server is the local stub127.0.0.53, which is forwarded by systemd-resolved to the upstream DNS configured for each network interface (link). - Connection establishment: The TCP three-way handshake (SYN → SYN-ACK → ACK). Connections that complete the handshake on the server enter the accept queue and wait for the application to call
accept(); the maximum queue length is the smaller of thelisten()backlog andnet.core.somaxconn. - Transmission: Lost data segments are recovered through retransmission; the retransmission timeout (RTO) uses exponential backoff starting at approximately 200 ms, and even when the packet loss rate is low, it can multiply tail latency. When the path MTU is mismatched and ICMP is filtered, an MTU black hole occurs, in which “small packets get through while large packets stall indefinitely.”
- Middleboxes and kernel tables: netfilter (nftables/iptables) rules and the conntrack connection-tracking table (NAT and stateful firewalls depend on it; when the table is full, new connections are dropped).
Why: Why Network Problems Are Difficult to Troubleshoot
The symptom is often just the word “timeout,” but a timeout can originate at any stage. The key is to distinguish between two types of errors: Connection refused—the other party explicitly refused the connection (an RST was received: no process is listening on the port, or the firewall issued a REJECT), indicating that the network is reachable; timeout—there was no response (DROP, packet loss, an unreachable route, or an unresponsive DNS server), requiring stage-by-stage troubleshooting.
How: Tools and Evidence
| Stage | Evidence | Command |
|---|---|---|
| DNS | Resolution time, which server, whether it timed out | resolvectl status, resolvectl query, dig, curl -w '%{time_namelookup}', gethostlatency-bpfcc |
| Connection establishment | Whether the SYN received a response, RSTs, accept queue overflows | ss -ltn(Recv-Q / Send-Q), nstat -az TcpExtListenOverflows, tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-rst) != 0' |
| Transmission | RTT, retransmissions, congestion window | ss -tin(rtt, retrans, cwnd), sar -n ETCP 1, nstat TcpRetransSegs, tcpretrans-bpfcc |
| Link | NIC errors, drops, qdisc | ip -s link, tc -s qdisc, ethtool -S |
| Path | Routing, MTU | ip route get, tracepath, ping -M do -s 1472 |
| Kernel tables | Conntrack usage and drops | sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max, conntrack -S |
Where tcpdump Captures Packets
tcpdump uses an AF_PACKET socket to “bypass-copy” packets between the NIC driver and the protocol stack: in the receive direction, it is before netfilter (so tcpdump can still see inbound packets dropped by the firewall with DROP); in the transmit direction, it is after qdisc (traffic control) and before handing packets to the driver (so tcpdump cannot see outbound packets discarded locally by tc netem; you will only see the subsequent retransmissions).
When: Decision Process
curl -sS -o /dev/null -w 'dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' URL- DNS stage is slow → use
resolvectl statusto check the upstream server, then test directly withdig @upstream-IP. - TCP stage is slow or fails → use
ssandtcpdumpto check whether the SYN receives a response; on the server side, check the accept queue. - Slow transfer → use
ss -tito check retrans and rtt; usesar -n ETCP 1to check the global retransmission rate. - Small requests work normally, but large responses stall → MTU. New connections fail randomly while existing connections work normally → conntrack table full or port exhaustion.
Tool Comparison
| ss | tcpdump | nstat / sar -n | tcpretrans-bpfcc | |
|---|---|---|---|---|
| What it shows | Current socket state (including kernel TCP information) | Every packet on the wire | Protocol counters | Every retransmission event (including the four-tuple) |
| Overhead | Very low | Moderate; add filters and -s truncation for high traffic | Very low | Low |
| Alternative | Older netstat (net-tools, no longer installed by default) | Analyze pcap with Wireshark/tshark | netstat -s | — |
resolved.conf instead. ③ “Send-Q on a LISTEN socket is data waiting to be sent” — for a listening socket, Recv-Q is the current accept queue length, and Send-Q is the queue limit (backlog). ④ “1% packet loss doesn’t matter” — TCP retransmissions can turn that 1% into significant tail latency.Figure 5-1: Request Path and Observability Tools for Each Segment
Figure 5-2: How Packet Loss Becomes Latency (RTO Exponential Backoff)
Request Failure Point Locator
Select a network fault and click “Send Request.” The animation moves along the request path, stops where the fault occurs, and displays the actual error at that point, the tools that can reveal the problem, and their output (example). DNS and packet loss among these faults can be reproduced in practice with inject.sh dns / inject.sh netloss.
Core Commands and Parameters
| Command | Purpose | Description |
|---|---|---|
ss -ltnp | Listening TCP ports and processes | -u for UDP; -p requires root to see processes owned by other users |
ss -tin state established '( sport = :5000 )' | Kernel TCP information for connections | rtt, rto, cwnd, retrans, bytes_retrans |
ss -s | Socket summary | TIME-WAIT count, orphaned |
nstat -az | grep -E 'Retrans|ListenOverflows|ListenDrops' | Protocol counters | Without -a, displays the delta since the last invocation |
sudo tcpdump -i any -nn -s 128 port 5000 | Packet capture | -w f.pcap to save; -c 100 to limit the count; -nn to skip name and port resolution |
resolvectl status / query / statistics | resolved status, resolution, and cache statistics | resolvectl flush-caches; revert IFACE |
dig +tries=1 +time=2 @1.1.1.1 example.com | Test by connecting directly to a DNS server | Bypass local resolved |
tracepath -n 1.1.1.1 | Path and PMTU | Does not require root |
ping -M do -s 1472 -c 3 HOST | Test whether an MTU of 1500 works (1472 + 28-byte header) | -M do prevents fragmentation |
sudo conntrack -S / -C | Connection tracking statistics / entry count | Requires the conntrack package; watch for drop, insert_failed |
tc -s qdisc show dev IFACE | Queue rules and drop statistics | netem dropped count |
IF=$(ip route show default | awk '{print $5; exit}')
ss -ltn 'sport = :5000'
curl -sS -o /dev/null -w 'dns=%{time_namelookup} tcp=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' http://127.0.0.1:5000/healthz
resolvectl status "$IF" | sed -n '1,12p'
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 2048 0.0.0.0:5000 0.0.0.0:*
dns=0.000021 tcp=0.000180 ttfb=0.002410 total=0.002470
Link 2 (ens3)
Current Scopes: DNS
Protocols: +DefaultRoute -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 192.168.64.1
DNS Servers: 192.168.64.1
The Send-Q 2048 on the LISTEN line is the backlog limit (gunicorn default --backlog 2048, restricted by net.core.somaxconn; the 26.04 kernel default is 4096), while Recv-Q is the current queue length. The network interface name (ens3, enp0s1, eth0) varies by virtualization platform.
Common tcpdump Filters
sudo tcpdump -i any -nn -c 20 'tcp port 5000 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)' # sudo tcpdump -i any -nn -c 20 'tcp port 5000 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)' # Show only handshakes and resets sudo tcpdump -i any -nn -c 20 udp port 53 # sudo tcpdump -i any -nn -c 20 udp port 53 # DNS queries and responses sudo tcpdump -i "$IF" -nn -s 0 -w /tmp/cap.pcap port 443 & # sudo tcpdump -i "$IF" -nn -s 0 -w /tmp/cap.pcap port 443 & # Save for Wireshark sudo tcpdump -i any -nn 'icmp[icmptype] == icmp-unreach' # sudo tcpdump -i any -nn 'icmp[icmptype] == icmp-unreach' # Includes fragmentation needed (MTU)
DNS Diagnostics
resolvectl query example.com
dig +tries=1 +time=2 example.com # dig +tries=1 +time=2 example.com # Via the local stub 127.0.0.53
dig +tries=1 +time=2 @"$(resolvectl dns "$IF" | awk '{print $NF}')" example.com # dig +tries=1 +time=2 @"$(resolvectl dns "$IF" | awk '{print $NF}')" example.com # Connect directly to the upstream
resolvectl statistics | sed -n '1,20p'
Lab 5: Slow DNS and 20% Packet Loss (approximately 7 minutes)
multipass shell). Automatically reverted after 15 minutes.IF=$(ip route show default | awk '{print $5; exit}')
time getent hosts ubuntu.com
curl -sS -o /dev/null -w 'dns=%{time_namelookup} total=%{time_total}\n' https://ubuntu.com
nstat -n # Reset nstat's incremental baselinesudo ~/linuxlab/faults/inject.sh dns time getent hosts example.org resolvectl query example.org resolvectl status "$IF" | grep -E 'DNS Server' sudo tcpdump -i any -nn -c 6 udp port 53
real 0m10.0xx s
example.org: resolve call failed: All attempts to contact name servers or networks failed
Current DNS Server: 192.0.2.53
DNS Servers: 192.0.2.53
11:20:01.101 ens3 Out IP 192.168.64.5.41532 > 192.0.2.53.53: 4512+ [1au] A? example.org. (40)
11:20:03.105 ens3 Out IP 192.168.64.5.41532 > 192.0.2.53.53: 4512+ [1au] A? example.org. (40)
tcpdump sees only the outgoing queries, with no responses—the upstream server is not responding. Cached names may still resolve (resolvectl flush-caches first). The total duration of getent depends on resolved retries and glibc timeouts; use the actual result.
sudo ~/linuxlab/faults/reset.sh >/dev/null
sudo ~/linuxlab/faults/inject.sh netloss
tc -s qdisc show dev "$IF"
for i in $(seq 10); do curl -sS -o /dev/null -w '%{time_total}\n' https://ubuntu.com; done
nstat | grep -E 'TcpRetransSegs|TcpExtTCPTimeouts'
ss -tin state established | grep -E -o 'rtt:[0-9./]+|retrans:[0-9/]+' | sort | uniq -c | head
qdisc netem 8001: root refcnt 2 limit 1000 delay 80ms loss 20% Sent 210340 bytes 1890 pkt (dropped 377, overlimits 0 requeues 0) 0.71 0.69 2.03 0.70 1.48 ... TcpRetransSegs 96 0.0 TcpExtTCPTimeouts 21 0.0
The total duration appears in “steps”—this is RTO backoff. Note that dropped 377 appears only in the tc statistics; tcpdump cannot capture these packets.
sar -n ETCP 1 3 sudo timeout 15 tcpretrans-bpfcc
11:25:02 atmptf/s estres/s retrans/s isegerr/s orsts/s 11:25:03 0.00 0.00 14.00 0.00 0.00 TIME PID IP LADDR:LPORT T> RADDR:RPORT STATE 11:25:05 0 4 192.168.64.5:52144 R> 185.125.190.20:443 ESTABLISHED
ping -M do -s 1472 -c 2 1.1.1.1 # A 1500 MTU path should succeed ping -M do -s 9000 -c 2 1.1.1.1 # Exceeds the local MTU: reports an error locally tracepath -n 1.1.1.1 | tail -n 3
ping: local error: message too long, mtu=1500
Resume: pmtu 1500 hops 9 back 9sudo ~/linuxlab/faults/reset.sh; tc qdisc show dev "$IF"
Case 1: Every request is consistently 5 seconds slow
Problem: Calls to a downstream API are consistently about 5 seconds slow, while the downstream service's own monitoring is normal. Approach: curl -w shows time_namelookup ≈ 5.0s; in resolvectl status, the first DNS server is down, so resolution waits for a timeout before switching to the second. Configuration: Correct the DNS list in netplan; on the application side, reuse connections with a connection pool and cache resolution results. Limitation: A fixed delay of an “integer number of seconds” is almost always a timeout-related issue (DNS, SYN retransmissions at 1s/3s, etc.).
Case 2: New connections fail randomly during peak periods
Problem: Some new connections to a NAT gateway host time out during traffic peaks, while established connections work normally. Approach: dmesg shows nf_conntrack: table full, dropping packet; the drop counter in conntrack -S is increasing. Configuration: Increase net.netfilter.nf_conntrack_max (and adjust the hash table size accordingly), shorten timeouts such as nf_conntrack_tcp_timeout_time_wait; use notrack for traffic that does not need tracking. Limitation: Each entry consumes kernel memory, so capacity must be planned based on available memory.
Case 3: Large file downloads stall after connecting through a VPN
Problem: A service accessed through a tunnel has a functioning login page, but downloading a large report stalls at 0%. Approach: ping -M do -s 1472 fails while -s 1372 succeeds; an intermediate firewall dropped ICMP “fragmentation needed”, causing PMTUD to fail. Configuration: Enable TCP MSS clamping on the tunnel interface (nftables: tcp flags syn tcp option maxseg size set rt mtu) or reduce the interface MTU. Limitation: MSS clamping cannot resolve this for UDP applications.
Common Errors and Solutions
curl: (6) Could not resolve host: api.example.internal
Cause: Name resolution failed (NXDOMAIN, upstream timeout, or an incorrectly configured search domain).
resolvectl query api.example.internal resolvectl status getent hosts api.example.internal; grep -v '^#' /etc/hosts
Fix: Use the error reported by resolvectl to distinguish between “does not exist” (check the name/search domain) and “cannot contact the server” (check the upstream DNS and network).
curl: (7) Failed to connect to 127.0.0.1 port 5000 after 0 ms: Couldn't connect to server
Cause: An RST was received: no process is listening on that port (the service is down or bound to another address), or the local firewall issued a REJECT. A duration of “0 ms” indicates immediate rejection rather than a timeout.
ss -ltnp 'sport = :5000'; systemctl status myapp --no-pager | head sudo nft list ruleset | grep -n 5000
Fix: Start the service or correct the bind address; for timeout-related errors (Connection timed out), troubleshoot DROP / routing / packet loss.
nf_conntrack: nf_conntrack: table full, dropping packet
Cause: The connection tracking table has reached nf_conntrack_max (the message prefix varies slightly across kernel versions; use the actual message as the reference).
sysctl net.netfilter.nf_conntrack_count net.netfilter.nf_conntrack_max
sudo conntrack -S | head
sudo conntrack -L 2>/dev/null | awk '{print $4}' | sort | uniq -c | sort -nr | head # sudo conntrack -L 2>/dev/null | awk '{print $4}' | sort | uniq -c | sort -nr | head # Statistics by state
Fix: Temporarily run sudo sysctl -w net.netfilter.nf_conntrack_max=262144, persistently write it to /etc/sysctl.d/; identify the source generating a large number of short-lived connections.
TCP: request_sock_TCP: Possible SYN flooding on port 0.0.0.0:5000. Sending cookies.
Cause: The SYN queue is full (a genuine attack, or a backlog caused by the application accepting connections too slowly). At the same time, an increase in TcpExtListenOverflows in nstat indicates that the accept queue is overflowing.
ss -ltn 'sport = :5000' # ss -ltn 'sport = :5000' # Recv-Q close to Send-Q? nstat -az TcpExtListenOverflows TcpExtListenDrops
Fix: If the application is slow, increase the number of workers / optimize processing; if necessary, increase the backlog and net.core.somaxconn; if it is an attack, apply rate limiting at the edge.
Error: Specified qdisc kind is unknown.
Cause: The sch_netem kernel module cannot be found when using tc ... netem. Ubuntu 26.04 generic kernels provide this module in linux-modules-*; some minimal/cloud kernels (or WSL2) may not have it.
sudo modprobe sch_netem && lsmod | grep netem uname -r; dpkg -S sch_netem.ko 2>/dev/null | head -2
Fix: Install the module package for the corresponding kernel (some cloud kernels on 24.04 require linux-modules-extra-$(uname -r)), or use a virtual machine instead.
1. Capture SYN and RST packets sent to or from port 5000, up to 20 packets, without resolving names.
sudo tcpdump -i any -nn -c 20 'tcp port 5000 and (tcp[tcpflags] & (tcp-syn|tcp-rst) != 0)'
2. Display the RTT and retransmission information for all established connections to Redis (6379).
ss -tin state established '( dport = :6379 )'
myapp calls an external API: small requests (1 KB) work normally, but the report endpoint returning 200 KB always times out; ping works normally, and DNS works normally. What do you suspect? How would you verify it?
A typical MTU black hole: full-length packets in the large response need to be fragmented along the path, but ICMP fragmentation-needed messages are being filtered, so the sender does not know to reduce the packet size. Verify: ping -M do -s 1472 target fails while a smaller size succeeds; use tracepath to check the PMTU; use tcpdump to observe the peer repeatedly retransmitting large packets. Fix: MSS clamping, adjusting the tunnel MTU, or allowing ICMP type 3 code 4.
Verified Educational Videos
Special-topic videos on troubleshooting systemd-resolved / conntrack / MTU: no verified videos found; refer to the official documentation and the storyboard below.
Official Documentation
- ss(8) · tcpdump(1) · pcap-filter(7)
- resolvectl(1) · systemd-resolved.service(8)
- tc-netem(8)
- nf_conntrack sysctl (kernel.org) · ip-sysctl (kernel.org)
Video Storyboard Script (approximately 90 seconds)
This course material cannot directly generate video/MP3 files; a storyboard and narration script are provided.
ectly generate video/MP3 files; a storyboard and narration script are provided.Visual: The output of curl -w is split into four colored timing bars: DNS, connection, TLS, and time to first byte, with the DNS segment particularly long.
Voiceover: Don’t rush to capture packets. curl -w can tell you which segment the time was spent in.
Visual: Packets move along the path and are crossed out at qdisc; the tcpdump shot is positioned in front of the network interface and captures only the later retransmitted packets.
Voiceover: Packets dropped by netem on the local host cannot be seen by tcpdump; what you see are retransmissions and increasingly long waits.
Visual: The retrans field in the output of ss -ti flashes, while sar’s retrans-per-second curve rises.
Voiceover: Retransmissions are the fingerprint of a network problem. Use ss, nstat, and sar to turn “the network is bad” into quantifiable evidence.
Module 6 · Boot Failures: GRUB, initramfs, and Rescue Mode
- Draw the boot chain: firmware → shim/GRUB → kernel + initramfs → switch_root → systemd →
local-fs.target→multi-user.target, and determine the failed stage based on the last message displayed on the screen. - Temporarily modify kernel parameters in the GRUB menu to enter
rescue.target,emergency.target, or dracut’srd.break; understand the impact of Ubuntu’s root account being locked by default on rescue mode. - Fix an incorrectly written
/etc/fstab(nofail,x-systemd.device-timeout=,findmnt --verify), and rebuild initramfs and GRUB in a chroot.
What: Every Stage of the Boot Chain
| Stage | What it does | Typical failure message (subject to actual output) |
|---|---|---|
| Firmware (UEFI/BIOS) | Performs self-tests and locates the bootloader in the EFI System Partition (loads shim first when Secure Boot is enabled) | “No bootable device”; Secure Boot verification failure |
| GRUB | Reads /boot/grub/grub.cfg, loads the kernel vmlinuz and initrd.img, and passes the kernel command line | After error: unknown filesystem., enters grub rescue>; error: file '/boot/vmlinuz-…' not found. |
| Kernel | Initializes hardware, decompresses initramfs into memory, and runs its init | Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) (usually because there is no initramfs) |
| initramfs | Loads storage drivers, assembles LVM/RAID/encrypted volumes, locates and mounts the root filesystem according to root=UUID=…, then performs switch_rootdracut: Warning: /dev/disk/by-uuid/… does not exist → enters the dracut emergency shell; initramfs-tools: ALERT! UUID=… does not exist. Dropping to a shell! → the (initramfs) prompt | |
| systemd(PID 1) | systemd-fstab-generator converts each line of fstab into a .mount unit; starts sysinit.target, local-fs.target, basic.target, and multi-user.target according to dependencies | Timed out waiting for device … → Dependency failed for Local File Systems. → emergency mode |
| Services | Starts sshd, myapp, etc. | The machine is up but services have failed: systemctl --failed |
Changes in Ubuntu 26.04: dracut is used by default to generate the initramfs (24.04 uses initramfs-tools); both provide the update-initramfs command, and their contents are viewed with lsinitrd (dracut) and lsinitramfs (initramfs-tools), respectively. dracut's debugging parameters are rd.break, rd.shell, and rd.debug; initramfs-tools' is break=.
Why: Why you need to know how to recover
When boot fails, there is no SSH and no monitoring agent—only the console. The most common causes are precisely human actions: writing fstab incorrectly, deleting the wrong kernel, UUIDs changing after partition adjustments, initramfs generation failing after an update, or installing a kernel when the disk is nearly full.
How: Several “entry points”
| Entry point | How to enter | What you get | Suitable for |
|---|---|---|---|
rescue.target | Press e in GRUB, add systemd.unit=rescue.target to the end of the linux line, and press Ctrl+X to boot | Single-user root-user root shell; local file systems are mounted, while services such as networking have not started | Service-caused hangs; repairs that require the complete file system |
emergency.target | Add systemd.unit=emergency.target; entered automatically when fstab fails | Only the root file system (read-only); almost nothing has started | fstab errors; other file systems cannot be mounted |
dracut rd.break | Add rd.break | An initramfs shell before switch_root; the actual root is at /sysroot | Problems with the root file system itself |
init=/bin/bash | Add init=/bin/bash | The kernel runs bash directly instead of systemd, with the root file system read-only | The last resort when root is locked and sulogin cannot be entered |
| Live ISO / rescue VM + chroot | Boot from installation media, or attach the system disk to another VM in the cloud | A complete tool environment | GRUB/initramfs corruption; situations requiring grub-install |
sulogin to require the root password; when root is locked, a prompt similar to Cannot open access to console, the root account is locked. is displayed and access is denied (the exact wording depends on the actual version). Mitigations: ① Set a strong password for root in advance and store it in a password vault (sudo passwd root), which is standard practice in many enterprises; ② Temporarily add systemd.setenv=SYSTEMD_SULOGIN_FORCE=1 to the kernel parameters to force a shell (depending on the actual version); ③ Use init=/bin/bash. This is also a security issue: anyone with console access can enter the system this way—on production systems, set a password for GRUB and protect console access.When: Determine the stage by looking at the last screen
>- Stops at
grub rescue>orgrub>→ GRUB cannot find its configuration/modules (partition changes,/bootcorruption). - Kernel panic … unable to mount root fs → initramfs is missing or corrupted.
- dracut emergency shell /
(initramfs)→ the root device cannot be found (UUID changed, missing driver, LVM not activated). You are in emergency mode.→ systemd stage, usually an fstab issue.- Login prompt is visible but SSH is unreachable → network/sshd/firewall (Lessons 2 and 6).
Comparison: Local VMs and Cloud
| Multipass / Hyper-V / VirtualBox | Azure VM | AWS EC2 | |
|---|---|---|---|
| View boot output | Hyper-V/VirtualBox console; Multipass itself does not provide an interactive console (use the console of its underlying virtualization platform) | Boot diagnostics screenshot + serial console (Lesson 3) | Get system log / instance screenshot + EC2 serial console (Lesson 4) |
| Offline repair | Revert to a snapshot, mount the virtual disk | Repair the VM (az vm repair) by attaching the system disk to a rescue VM | Stop the instance and attach the root volume to a rescue instance |
mount -o remount,rw /. ② “nofail makes the system ignore all errors” — it only prevents a failure to mount that filesystem from blocking boot; services that depend on that mount point will still fail, and the dependency must be expressed with RequiresMountsFor=. ③ “Reinstalling GRUB can fix everything” — if the issue is with initramfs or fstab, reinstalling GRUB will not help. ④ “It is fine to write /dev/sdb1 in fstab” — device names may change after a reboot; use UUID or LABEL instead.Figure 6-1: Boot Chain and Rescue Entry Points
Figure 6-2: How One Incorrect fstab Line Sends the System into Emergency Mode
nofailandx-systemd.device-timeout=Boot Chain Failure-Point Simulator
Choose a boot failure and “power on.” The animation progresses along the boot chain and stops at the stage where the error occurs. The terminal displays what you would see on the console (wording varies by actual version), then demonstrates step by step how to enter the rescue entry point and run the commands to repair it.
Core Commands and Parameters
| Command | Function | Description |
|---|---|---|
sudo findmnt --verify --verbose | Check fstab syntax, whether devices exist, and filesystem types | Required after modifying fstab and before rebooting |
sudo systemctl daemon-reload && sudo mount -a | Regenerate mount units and attempt to mount everything | Reboot only if no errors are reported |
systemd-analyze blame / critical-chain | Boot time analysis | Identify units that slow down boot |
journalctl -b -1 -p err | Errors from the previous boot | Persistent logs are required (Ubuntu provides /var/log/journal by default) |
journalctl --list-boots | Boot history | Determine whether the system is repeatedly rebooting |
cat /proc/cmdline | Current kernel parameters | Confirm root= and console= |
sudo update-initramfs -u -k all | Rebuild initramfs | In 26.04, this command is provided by dracut; in 24.04, it is provided by initramfs-tools |
sudo lsinitrd | head(dracut)/ lsinitramfs | View initramfs contents | Confirm that the driver, LVM, and crypt modules are included |
sudo update-grub / grub-install | Regenerate grub.cfg / reinstall the bootloader | Configuration is in /etc/default/grub and /etc/default/grub.d/ |
sudo grub-reboot 'Advanced options for Ubuntu>…' | Use the specified menu entry only on the next boot | Safe approach when testing a new kernel (menu entry name is determined by grub.cfg) |
Three Steps for Safely Modifying fstab
>sudo cp -a /etc/fstab /etc/fstab.bak.$(date +%F) sudo blkid -s UUID -o value /dev/vdb1 # sudo blkid -s UUID -o value /dev/vdb1 # Use the UUID rather than the device name echo 'UUID=xxxx-xxxx /data ext4 defaults,nofail,x-systemd.device-timeout=10s 0 2' | sudo tee -a /etc/fstab sudo findmnt --verify --verbose && sudo systemctl daemon-reload && sudo mount -a
/data [E] unreachable source: UUID=0000dead-beef-4bad-8bad-00000000feed: No such file or directory [W] ... 0 parse errors, 1 error, 0 warnings
Repairing fstab in emergency mode
# Console displays: You are in emergency mode. After logging in, type "journalctl -xb" to view # system logs, "systemctl reboot" to reboot, "systemctl default" or "exit" to boot into default mode. journalctl -xb -p err | tail -n 20 # journalctl -xb -p err | tail -n 20 # Find the failed .mount unit mount -o remount,rw / nano /etc/fstab # nano /etc/fstab # Comment out or correct the erroneous line, or add nofail systemctl daemon-reload mount -a && systemctl default # mount -a && systemctl default # Continue booting to the default target
Entering chroot from a Live ISO / rescue VM
sudo mount /dev/vda1 /mnt # sudo mount /dev/vda1 /mnt # Root partition (run vgchange -ay first for LVM) sudo mount /dev/vda16 /mnt/boot 2>/dev/null # sudo mount /dev/vda16 /mnt/boot 2>/dev/null # If there is a separate /boot (partition number determined by lsblk) sudo mount /dev/vda15 /mnt/boot/efi # sudo mount /dev/vda15 /mnt/boot/efi # EFI partition for d in dev proc sys run; do sudo mount --rbind /$d /mnt/$d; done sudo chroot /mnt /bin/bash update-initramfs -u -k all update-grub grub-install --target=x86_64-efi --efi-directory=/boot/efi # grub-install --target=x86_64-efi --efi-directory=/boot/efi # Only when the bootloader is damaged exit; sudo umount -R /mnt
Use lsblk -f as the authority for the partition layout: Ubuntu cloud images usually have a root partition + separate /boot + EFI partition; the installer's default layout may differ.
Lab 6: Write an incorrect fstab entry and recover under snapshot protection (about 7 minutes)
sudo cp -a /etc/fstab /etc/fstab.bak.hour7 truncate -s 64M ~/linuxlab/data.img && mkfs.ext4 -q ~/linuxlab/data.img sudo mkdir -p /data /data2 echo "$HOME/linuxlab/data.img /data ext4 loop,nofail 0 2" | sudo tee -a /etc/fstab echo "UUID=0000dead-beef-4bad-8bad-00000000feed /data2 ext4 defaults 0 2" | sudo tee -a /etc/fstab sudo findmnt --verify; echo "exit=$?"
sudo systemctl daemon-reload systemctl list-units --all 'data*.mount' sudo timeout 20 systemctl start data2.mount; echo "exit=$?" systemctl show data2.mount -p Requires -p After | tr ' ' '\n' | grep -i dev-disk systemctl list-dependencies --reverse data2.mount | head
You will see that data2.mount depends on dev-disk-by\x2duuid-….device and is required by local-fs.target—during reboot, it will wait about 90 seconds (DefaultDeviceTimeoutSec) for the device, then fail and send the system into emergency mode.
sudo systemctl reboot
On the console, you should expect to see (example): A start job is running for /dev/disk/by-uuid/0000dead-…, followed by Dependency failed for /data2., Dependency failed for Local File Systems., and finally You are in emergency mode…. If a message appears saying that root is locked, after reboot press e in the GRUB menu, append systemd.setenv=SYSTEMD_SULOGIN_FORCE=1 (or init=/bin/bash) to the end of the linux line, then press Ctrl+X to boot.
mount -o remount,rw / sed -i '/0000dead-beef/s/^/# /' /etc/fstab systemctl daemon-reload mount -a && systemctl default
journalctl --list-boots | tail -n 3 journalctl -b -1 -p err --no-pager | head -n 20 systemd-analyze critical-chain | head
sudo umount /data 2>/dev/null sudo cp -a /etc/fstab.bak.hour7 /etc/fstab sudo systemctl daemon-reload && sudo findmnt --verify rm -f ~/linuxlab/data.img; sudo rmdir /data /data2 # If the system cannot boot: on the host, run multipass stop linuxlab && multipass restore linuxlab.before-hour7
Case 1: The system fails to boot after expanding the data disk on a cloud VM
Problem: Operations migrated the data disk from one VM to another. After the original VM was rebooted, it became stuck and SSH was unreachable. Procedure: The cloud platform's serial console showed Dependency failed for Local File Systems; the data disk in fstab did not have nofail. Enter emergency mode through the serial console to repair it (the root password is required—it was set in advance). Configuration: Add nofail,x-systemd.device-timeout=10s uniformly to all non-system disks, and make this a standard in the configuration management covered in Lesson 5. Limitation: Services that depend on the data disk must declare RequiresMountsFor=/data; otherwise, they will write to an empty directory on the root partition.
Case 2: Kernel panic after a kernel update
Problem: When an automatic update installed a new kernel, there was insufficient space in /boot. initramfs generation failed, but GRUB was already pointing to the new kernel. Procedure: From the console, select the old kernel under Advanced options in the GRUB menu to boot; remove old kernels (sudo apt autoremove --purge), run update-initramfs -u -k new version, and then run update-grub. Prevention: Monitor /boot utilization; Ubuntu retains the current and previous kernels by default.
Case 3: Root partition UUID changed
Problem: On a new machine cloned from a disk image, the cloning tool regenerated the filesystem UUID, causing boot to become stuck in initramfs. Procedure: In the dracut shell, use blkid to see the new UUID; temporarily change root=UUID=… to the new value in GRUB to boot, then correct /etc/fstab and run update-grub and update-initramfs -u. Limitation: For encrypted volumes and LVM, also check /etc/crypttab and conflicts in VG names.
Common Errors and Solutions
error: unknown filesystem. Entering rescue mode... grub rescue>
Cause: GRUB cannot find the partition containing /boot/grub (the partition was deleted or moved, the disk was repartitioned, or the disk order changed).
grub rescue> ls # grub rescue> ls # List (hd0) (hd0,gpt1) ... grub rescue> ls (hd0,gpt1)/ # grub rescue> ls (hd0,gpt1)/ # Find the partition containing /boot/grub grub rescue> set prefix=(hd0,gpt1)/boot/grub grub rescue> set root=(hd0,gpt1) grub rescue> insmod normal grub rescue> normal
Fix: After entering the system, run sudo grub-install (for UEFI, specify the EFI directory) and sudo update-grub; use the actual partition number.
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)
Cause: The kernel does not have a corresponding initramfs (generation failed or it was deleted), or the GRUB configuration lacks an initrd line.
Fix: Select the old kernel in GRUB to boot; then use ls -l /boot to confirm whether initrd.img-version exists, run sudo update-initramfs -c -k version (create) or -u (update), and then run sudo update-grub.
Warning: /dev/disk/by-uuid/… does not exist → Entering emergency mode. Exit the shell to continue.(dracut)
Cause: The root device cannot be found in initramfs: the UUID changed, storage drivers are missing, or LVM/encrypted volumes were not activated. dracut generates /run/initramfs/rdsosreport.txt (the wording depends on the actual dracut version).
blkid; lsblk -f # blkid; lsblk -f # In the dracut shell cat /proc/cmdline lvm vgscan; lvm vgchange -ay # lvm vgscan; lvm vgchange -ay # If using LVM
Fix: Correct root= in the kernel parameters; after entering the system, rebuild initramfs and ensure that the drivers are included (dracut configuration is in /etc/dracut.conf.d/).
Dependency failed for Local File Systems. You are in emergency mode.
Cause: An fstab entry failed to mount (the device does not exist, the filesystem type is incorrect, an option is misspelled, or fsck is required).
journalctl -xb -p err | grep -E 'mount|Dependency' systemctl --failed
Fix: See the emergency repair procedure on the “Commands” tab; prevention: findmnt --verify + nofail.
Cannot open access to console, the root account is locked. See sulogin(8) man page for more details.
Cause: Ubuntu locks the root account by default; rescue/emergency mode requires the root password (the original text depends on the actual version).
Fix: Reboot, then add systemd.setenv=SYSTEMD_SULOGIN_FORCE=1 or init=/bin/bash in GRUB (the latter requires manually running mount -o remount,rw /; after fixing the issue, use exec /sbin/init or force a reboot). Long term: set a controlled password for root and set a password for GRUB.
1. After modifying fstab, verify that it is correct and attempt to mount it without rebooting.
sudo findmnt --verify --verbose && sudo systemctl daemon-reload && sudo mount -a
2. View all error-level logs from the previous boot.
journalctl -b -1 -p err --no-pager
An Ubuntu 26.04 server reboots and stops at dracut's emergency shell, reporting that a UUID does not exist. A colleague renamed the volume group containing the root partition just yesterday. How can it be recovered?
The root device path (or the root=/rd.lvm.lv= parameter) still points to the old VG name. In the dracut shell, use lvm vgs and lvm lvs to confirm the new name; reboot and temporarily change the kernel parameter in GRUB to the new path to boot; after entering the system, correct /etc/fstab and /etc/default/grub (if it contains rd.lvm.lv), then run update-grub and update-initramfs -u -k all. The same operations can also be completed from a rescue environment using chroot.
Verified Instructional Videos
No verified videos found. When searching for videos related to GRUB rescue, emergency mode, and fstab repair, no videos were found whose titles and channels could be confirmed through YouTube oEmbed and whose content was applicable to Ubuntu 26.04 (dracut). Please use the official documentation and storyboard below.
Official Documentation
- systemd.special(7): rescue.target / emergency.target
- systemd.mount(5): nofail, x-systemd.device-timeout
- kernel-command-line(7)
- dracut.cmdline(7): rd.break, rd.shell
- GNU GRUB Manual
- findmnt(8)
Video Storyboard (approximately 100 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
enerate video/MP3 files; a storyboard and narration script are provided.Visual: Six blocks in the boot chain light up in sequence: firmware, GRUB, kernel, initramfs, systemd, and services.
Voice-over: When the machine fails to boot, first determine which stage it has stopped at. The text on the final screen is the clue.
Visual: GRUB menu; press e, enter systemd.unit=rescue.target at the end of the linux line, and press Ctrl X.
Voice-over: GRUB is the master switch for all rescue entry points. Temporarily modifying the kernel parameters lets you enter rescue mode, emergency mode, or the initramfs debug shell.
Visual: Emergency prompt; run remount rw, edit fstab, run mount -a, and run systemctl default.
Voice-over: An incorrectly written fstab is the most common cause. First remount the root filesystem as writable, correct that line, and then continue booting.
Visual: nofail and x-systemd.device-timeout appear at the end of an fstab line; findmnt --verify runs in the terminal and displays zero errors.
Voice-over: Prevention is better than rescue. Add nofail to non-critical disks, and use findmnt to verify the changes first.
Module 7 · Advanced Tools: strace, perf, and eBPF (bpftrace)
- Use
strace -fc/-T/-e trace=to identify “which system call is it stuck on,” and understand its high overhead; know the purpose and limitations ofltrace. - Use
perf top,perf record -g, andperf reportfor CPU profiling, generate and interpret flame graphs (including perf support for Python 3.12+). - Understand how eBPF works (attaching to kprobe/tracepoint/uprobe/sampling events and aggregating in the kernel), write bpftrace one-liners, and use bcc tools with the
-bpfccsuffix on Ubuntu.
What: Four types of in-depth tools
| Tool | Principle | Questions answered | Overhead |
|---|---|---|---|
| strace | ptrace(2): The target process is paused on entry to and exit from each system call; strace reads the arguments and return value | Which system calls is the process making? Which ones failed (ENOENT, EACCES)? Which ones are slow? | High: System-call-intensive programs may run several to dozens of times slower; --seccomp-bpf can reduce overhead (tracing only selected calls) |
| ltrace | Set breakpoints at the PLT entries of dynamic library functions | Which library functions were called (e.g., getaddrinfo, malloc) | High; calls often cannot be observed in statically linked binaries or modern binaries built with -z now (BIND_NOW); results are for reference only |
| perf | Kernel perf_events: Record call stacks by sampling at a given frequency (e.g., 99 Hz); can also count hardware/software events and trace tracepoints | Which functions consume CPU time (on-CPU profiling)? IPC, cache misses? | Low to moderate (depending on sampling frequency) |
| eBPF(bpftrace / bcc) | Attach small programs validated by the kernel verifier to kprobe/kretprobe, tracepoint, uprobe, USDT, and perf events; aggregate in the kernel (histograms, counts) before passing results to user space | Almost any question: latency distributions, off-CPU waits, who opened a file, who was OOM-killed, every retransmission | Low (depending on event frequency); requires root and BTF |
Why: Why these tools are needed beyond the 60-second checklist
The checklist tells you “CPU user space is at 100%”—but not which function; it tells you “disk await is 50 ms”—but not which file of which process; it tells you “the service is slow”—but if it is waiting (on a lock, the network, or sleep), CPU profiling will show nothing, and off-CPU analysis is needed. These tools connect “resource-level symptoms” to “code-level causes.”
How: How to read a flame graph
- Each box is a function stack frame; width = the proportion of samples in which the function appears (wider means more CPU usage); vertical position = call relationships (lower frames call upper frames).
- The X axis is not time; it shows samples merged and sorted alphabetically. Colors are usually only for distinction and have no meaning.
- Look for a “wide, flat top” (plateau): that is the function directly consuming CPU.
- Complete stacks require frame pointers or DWARF unwinding: starting with Ubuntu 24.04, amd64/arm64 packages are compiled with frame pointers by default (
-fno-omit-frame-pointer), greatly improving perf stack completeness; Python 3.12+ can use-X perforPYTHONPERFSUPPORT=1to let perf see Python function names.
eBPF program lifecycle
- bpftrace compiles scripts into BPF bytecode (bcc uses Clang/LLVM to compile C snippets; libbpf-tools uses precompiled CO-RE programs).
bpf(BPF_PROG_LOAD)loads the program, and the kernel verifier checks it for bounded loops, safe memory access, and assurance that it cannot crash the kernel.- JIT-compiled into native machine code and attached to a specified event (such as
tracepoint:syscalls:sys_enter_openat). - When the event is triggered, the program runs in the kernel and writes the results to a BPF map (hash table, histogram, ring buffer).
- User space periodically reads the map and prints the results; after Ctrl+C, the program is unloaded. It relies on kernel BTF (
/sys/kernel/btf/vmlinux, provided by default by the Ubuntu kernel) to obtain structure information.
When: Which One to Choose
| Symptom | Preferred | Alternative |
|---|---|---|
| The program reports an error, but the logs are unclear (file not found, permissions) | strace -f -e trace=%file | opensnoop-bpfcc |
| High CPU usage in user space | perf record -g + flame graph | profile-bpfcc |
| The service is slow but CPU usage is not high (waiting) | offcputime-bpfcc | strace -T to see which call is taking time |
| Disk latency distribution | biolatency-bpfcc / biolatency.bt | iostat -x |
| Scheduling latency | runqlat-bpfcc | PSI cpu |
| Short-lived processes consuming CPU | execsnoop-bpfcc | pidstat |
| Which process was killed by OOM | oomkill-bpfcc / oomkill.bt | journalctl -k |
| TCP retransmissions | tcpretrans-bpfcc | ss -ti, nstat |
| Slow DNS resolution | gethostlatency-bpfcc | curl -w |
-e scope and duration, and prefer eBPF tools. ② “The horizontal axis of a flame graph represents time”—it does not. ③ “perf not showing function names is a perf problem”—usually, symbols or stack-unwinding information is missing (interpreted languages, missing frame pointers, stripped symbols). ④ “eBPF will crash the kernel”—the verifier guarantees safety, but complex programs on high-frequency events can still incur considerable overhead.Figure 7-1: Attachment Points of Various Tools in the System
Figure 7-2: From Sampling to a Flame Graph
Flame Graph Builder: Sampling → Folding → Rendering
Simulate sampling myapp (gunicorn + Flask) at 99 Hz: each click on “Sample for 1 second” randomly extracts 99 call stacks (according to the configured hotspot ratios). The folded count lines are shown below (the output format of stackcollapse), and the flame graph is rendered in real time above. Switch “Workload” to observe changes in the shape of the flame graph; click a block to view its proportion.
strace / ltrace
sudo strace -f -c -p "$(systemctl show -p MainPID --value myapp)" -o /tmp/myapp.sum & # sudo strace -f -c -p "$(systemctl show -p MainPID --value myapp)" -o /tmp/myapp.sum & # Summarize; press Ctrl+C or use kill to end for i in $(seq 50); do curl -s http://127.0.0.1:5000/healthz >/dev/null; done sudo pkill -INT -f 'strace -f -c'; sleep 1; head -n 15 /tmp/myapp.sum
% time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 41.20 0.004120 20 200 epoll_wait 18.03 0.001803 9 200 sendto 12.51 0.001251 6 200 50 recvfrom ... 100.00 0.010002 8 1210 55 total
# Show only file-related calls and failures: find “which configuration file was actually read” sudo strace -f -tt -T -e trace=%file -e status=failed -s 200 -o /tmp/start.trace systemctl restart myapp # For newly started programs: strace -f -e trace=openat,connect -s 120 curl -s http://127.0.0.1:5000/healthz -o /dev/null # Reduce overhead (trace only the selected system calls): sudo strace -f --seccomp-bpf -e trace=connect -p PID # ltrace: see the resolver library functions called by curl (may not be visible on modern binaries) ltrace -e getaddrinfo curl -s https://ubuntu.com -o /dev/null
-T displays the duration of each call, -tt timestamps in microseconds, -e status=failed displays only failed calls (strace 5.2+), and %file/%network/%process are system call categories. Note: strace can only trace the systemctl process itself; service processes are started by systemd (PID 1), so use -p to attach to them or temporarily wrap ExecStart with strace in the unit.
perf and Flame Graphs
cat /proc/sys/kernel/perf_event_paranoid # cat /proc/sys/kernel/perf_event_paranoid # Ubuntu is stricter by default; regular users are restricted, so use sudo sudo perf top -g # sudo perf top -g # Real-time hot functions (q to quit) sudo perf stat -a -- sleep 5 # sudo perf stat -a -- sleep 5 # Global counts: context switches, IPC, etc. (hardware counters may be unavailable in virtual machines) # Sample myapp for 20 seconds (to make Python function names visible: perf support in Python 3.12+) sudo systemctl edit myapp --drop-in=60-perf --stdin <<'EOF' [Service] Environment=PYTHONPERFSUPPORT=1 EOF sudo systemctl restart myapp sudo perf record -F 99 -g -p "$(pgrep -d, -f 'gunicorn')" -o /tmp/perf.data -- sleep 20 & for i in $(seq 2000); do curl -s http://127.0.0.1:5000/healthz >/dev/null; done; wait sudo perf report -i /tmp/perf.data --stdio --no-children | head -n 40 # Generate a flame graph git clone --depth 1 https://github.com/brendangregg/FlameGraph ~/linuxlab/FlameGraph sudo perf script -i /tmp/perf.data | ~/linuxlab/FlameGraph/stackcollapse-perf.pl | ~/linuxlab/FlameGraph/flamegraph.pl --title "myapp on-CPU" > ~/linuxlab/myapp-flame.svg ls -lh ~/linuxlab/myapp-flame.svg
Copy the SVG back to the host (multipass transfer linuxlab:/home/labadmin/linuxlab/myapp-flame.svg .) and open it in a browser; you can click to zoom in. After finishing, remove the drop-in: sudo rm /etc/systemd/system/myapp.service.d/60-perf.conf && sudo systemctl daemon-reload && sudo systemctl restart myapp. pgrep -d, joins multiple PIDs with commas for use with -p.
bpftrace One-Liners
sudo bpftrace -l 'tracepoint:syscalls:sys_enter_open*' # sudo bpftrace -l 'tracepoint:syscalls:sys_enter_open*' # List available probes
# Who is opening the file
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%-16s %s\n", comm, str(args.filename)); }'
# Count system calls by process (10 seconds)
sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); } interval:s:10 { exit(); }'
# Block I/O size distribution
sudo bpftrace -e 'tracepoint:block:block_rq_issue { @bytes = hist(args.bytes); }'
# 99 Hz sampled kernel stack (basic profiling)
sudo bpftrace -e 'profile:hz:99 /pid/ { @[comm, kstack(5)] = count(); } interval:s:10 { exit(); }'
# Utility scripts included with the package
ls /usr/sbin/*.bt | head; sudo /usr/sbin/oomkill.bt
In bpftrace 0.25, access tracepoint arguments using args.field (the old syntax args->field is no longer recommended).
bcc Tools (Ubuntu package name bpfcc-tools, commands have the -bpfcc suffix)
| Command | Purpose | Example |
|---|---|---|
execsnoop-bpfcc | Trace every exec (new process) | Find scripts being repeatedly launched by cron |
opensnoop-bpfcc | Trace open calls and failures | -x show failures only; -p PID |
biolatency-bpfcc | Block I/O latency histogram | -D 10 1 by device, 10 seconds |
runqlat-bpfcc | Run-queue (scheduler) latency histogram | 10 1 |
offcputime-bpfcc | Off-CPU time and stacks | -p PID -f 10 outputs folded format for drawing an off-CPU flame graph |
profile-bpfcc | CPU sampling profiling | -F 99 -f 10 |
tcpretrans-bpfcc | Every TCP retransmission | Used with the M5 packet-loss experiment |
oomkill-bpfcc | OOM kill events | Used with the M3 leak experiment |
gethostlatency-bpfcc | Latency of getaddrinfo and other resolution calls | Used with the M5 slow-DNS experiment |
sudo biolatency-bpfcc -D 5 1
disk = sda
usecs : count distribution
256 -> 511 : 120 |**** |
512 -> 1023 : 860 |**************************** |
1024 -> 2047 : 1210 |****************************************|
2048 -> 4095 : 640 |********************* |
4096 -> 8191 : 210 |****** |
16384 -> 32767 : 44 |* |
Experiment 7: Use in-depth tools to review the preceding faults (approximately 8 minutes)
sudo ~/linuxlab/faults/inject.sh myapp systemctl status myapp --no-pager | head -n 8 journalctl -u myapp -n 5 --no-pager
× myapp.service - myapp (Flask + gunicorn)
Active: failed (Result: resources) since ...
myapp.service: Failed to load environment files: No such file or directory
myapp.service: Failed to spawn 'start' task: No such file or directory
myapp.service: Failed with result 'resources'.
systemctl cat myapp | grep -n EnvironmentFile # Find the drop-in zz-fault.conf sudo ~/linuxlab/faults/reset.sh
The journal already states the issue very clearly in this example, so strace is not needed; but if the program itself fails to read the configuration and only prints “config error”, use strace -f -e trace=%file -e status=failed to find the path it is trying to open.
( for i in $(seq 30); do /bin/date >/dev/null; sleep 0.2; done ) & sudo timeout 8 execsnoop-bpfcc
PCOMM PID PPID RET ARGS date 8120 8101 0 /bin/date sleep 8121 8101 0 /usr/bin/sleep 0.2
sudo oomkill-bpfcc in one terminal and sudo ~/linuxlab/faults/inject.sh memleak in another:
Tracing OOM kills... Ctrl-C to stop.
11:52:30 Triggered by PID 9310 ("python3"), OOM kill of PID 9310 ("python3"), 76800 pages, loadavg: 0.31 0.22 0.18 2/190 9330myapp-flame.svg for myapp, paginated by “command”; then run sudo perf record -F 99 -a -g -- sleep 10 once on the stress-ng from inject.sh cpu, and compare the two flame graphs: stress-ng is one wide flat top (the matrix multiplication function), while myapp is a scattered Python/kernel network stack.sudo runqlat-bpfcc 5 1 # when healthy sudo ~/linuxlab/faults/inject.sh cpu sudo runqlat-bpfcc 5 1 # when saturated: millisecond-scale waits increase noticeably
sudo ~/linuxlab/faults/reset.sh sudo rm -f /etc/systemd/system/myapp.service.d/60-perf.conf /tmp/perf.data* /tmp/*.trace /tmp/myapp.sum sudo systemctl daemon-reload && sudo systemctl restart myapp
Case 1: 40 ms more per request—regular expressions in the flame graph
Problem: After the new version was deployed, CPU user time rose from 30% to 70%. Approach: Generate a flame graph with perf record -F 99 -g (with perf support enabled in Python), and discover that 40% of the samples fall in a regular-expression match in a log-redaction function. Configuration: Precompile the regular expression and narrow the matching scope. Limitation: Without frame pointers or perf support, the flame graph only shows interpreter frames such as _PyEval_EvalFrameDefault, so the application functions cannot be identified.
Case 2: The service is slow but CPU is mostly idle—off-CPU analysis
Problem: API P99 is 2 seconds, while CPU utilization is 20%. Approach: Generate an off-CPU flame graph with offcputime-bpfcc -p PID -f 30; the widest stack stops at futex—the connection pool has only 5 connections, and the remaining threads are queued on the lock. Configuration: Increase the connection pool size and add timeouts and metrics. Limitation: Off-CPU analysis is sensitive to event frequency; limit the PID and duration in production.
Case 3: strace brought down the production database
Problem: An engineer ran strace -f -p on a high-QPS database process, and throughput immediately dropped by an order of magnitude. Approach: Press Ctrl+C to recover immediately; use an eBPF tool such as syscount instead (for example, use bpftrace to count raw_syscalls) to obtain the same information. Lesson: Before using strace in production, assess the system call frequency; when it is necessary, use -e filtering and --seccomp-bpf, and set a duration.
Common errors and solutions
WARNING: perf not found for kernel 7.0.0-42 (You may need to install the following packages for this specific kernel …)
Cause: Ubuntu's /usr/bin/perf was once a wrapper script that looked up linux-tools-version according to the kernel version; after a kernel upgrade, if the corresponding package was not installed, it would display a message (the original text depends on the actual situation). 26.04 provides the version-independent linux-perf package.
dpkg -S "$(readlink -f "$(command -v perf)")" sudo apt install linux-perf # 26.04 sudo apt install linux-tools-$(uname -r) linux-tools-common # 24.04
Error: Access to performance monitoring and observability operations is limited. ... perf_event_paranoid setting is 4
Cause: Ubuntu's default kernel.perf_event_paranoid setting is relatively strict (the value depends on the actual situation), so non-root users cannot perform sampling.
Fix: Use sudo; do not lower this value globally for convenience (it will expand the information-exposure surface).
strace: attach: ptrace(PTRACE_SEIZE, 1234): Operation not permitted
Cause: Yama's kernel.yama.ptrace_scope=1 (the Ubuntu default) only permits tracing one's own child processes; or the target process is already attached to by another debugger.
sysctl kernel.yama.ptrace_scope sudo strace -p 1234 # sudo strace -p 1234 # root can attach grep TracerPid /proc/1234/status # grep TracerPid /proc/1234/status # Non-zero indicates that a tracer already exists
perf report contains only hexadecimal addresses / [unknown]
Cause: Symbols are missing (stripped binaries or JIT code), or stack unwinding failed (no frame pointers).
Fix: Install debug symbols (Ubuntu's debuginfod is available by default, and perf downloads them on demand, which may be slow); set PYTHONPERFSUPPORT=1 for Python; use perf-map-agent / -XX:+PreserveFramePointer for Java; when necessary, use perf record --call-graph dwarf (with higher overhead).
ERROR: Could not resolve symbol / Attaching 1 probe... followed by "Error loading BPF program" (bpftrace)
Cause: The probe name does not exist in the current kernel (the kernel function was renamed or inlined), BTF is missing, or Secure Boot lockdown mode restricts some functionality (the exact error text depends on the actual situation).
sudo bpftrace -l 'kprobe:vfs_*' | head ls -l /sys/kernel/btf/vmlinux cat /sys/kernel/security/lockdown
Fix: Prefer stable tracepoints; switch to a function name that exists in the current kernel; confirm that it is being run as root.
1. Sample the entire system at 99 Hz for 30 seconds (including call stacks), then view the first 30 lines of the report in text format.
sudo perf record -F 99 -a -g -- sleep 30 sudo perf report --stdio --no-children | head -n 30
2. Use bpftrace to count the number of times each process calls openat within 10 seconds.
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { @[comm] = count(); } interval:s:10 { exit(); }'myapp has high P99 latency, and the perf flame graph shows little and scattered CPU time; vmstat is normal. What tool would you use? What would you expect to discover?
CPU profiling only shows time “on the CPU,” while this service spends most of its time waiting. Use offcputime-bpfcc -p PID -f 30 to generate an off-CPU flame graph (or use strace -f -T -e trace=network,futex,poll,epoll_wait to see which blocking calls are taking time). Common findings include waiting for Redis/database responses (recvfrom over the network), connection-pool locks (futex), DNS resolution (gethostlatency-bpfcc), and synchronous log writes (fsync).
Verified Instructional Videos
Official Documentation
- strace(1) · ltrace(1)
- perf wiki · perf-record(1)
- Flame Graphs (Brendan Gregg) · FlameGraph Repository
- bpftrace · bcc
- Python support for the Linux perf profiler
- BPF Documentation (kernel.org)
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; it has provided a segot directly generate video/MP3; a storyboard and narration script are provided.
Shot 1 · 0–20s
Visual: strace output scrolls rapidly, and the “speedometer” next to the process drops very low.
Narration: strace can show every system call, but the cost is that the process must be stopped each time. Use it with caution in production.
Shot 2 · 20–55s
Visual: Sampling points fall like raindrops onto the call stack; the stacks are folded and layered into a flame graph, with the widest flat top highlighted.
Narration: perf samples the call stack 99 times per second, then folds the samples into a flame graph. The wider it is, the more CPU it consumes; the horizontal axis is not time.
Shot 3 · 55–90s
Visual: A small program passes through the “verifier” gate, attaches to a tracepoint in the kernel, and accumulates a histogram in the kernel.
Narration: After an eBPF program is checked by the verifier, it runs in the kernel and aggregates data directly in the kernel. It has low overhead and can answer almost any question.
- strace(1) · ltrace(1)
- perf wiki · perf-record(1)
- Flame Graphs (Brendan Gregg) · FlameGraph Repository
- bpftrace · bcc
- Python support for the Linux perf profiler
- BPF Documentation (kernel.org)
Video Storyboard Script (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; it has provided a segot directly generate video/MP3; a storyboard and narration script are provided.
Visual: strace output scrolls rapidly, and the “speedometer” next to the process drops very low.
Narration: strace can show every system call, but the cost is that the process must be stopped each time. Use it with caution in production.
Visual: Sampling points fall like raindrops onto the call stack; the stacks are folded and layered into a flame graph, with the widest flat top highlighted.
Narration: perf samples the call stack 99 times per second, then folds the samples into a flame graph. The wider it is, the more CPU it consumes; the horizontal axis is not time.
Visual: A small program passes through the “verifier” gate, attaches to a tracepoint in the kernel, and accumulates a histogram in the kernel.
Narration: After an eBPF program is checked by the verifier, it runs in the kernel and aggregates data directly in the kernel. It has low overhead and can answer almost any question.
Module 8 · Integrated Troubleshooting Challenge
- Without knowing the failure type, complete the diagnosis according to “quantify symptoms → 60-second checklist → hypotheses → verify with specialized tools → mitigate the impact → review.”
- Build a mapping of “symptoms → most likely resource → decisive evidence” to reduce guesswork.
- Write a structured incident review (timeline, impact, root cause, evidence, and improvement items).
What: Unknown-Fault Challenge Rules
sudo ~/linuxlab/faults/blindbox.shrandomly injects one of 10 failure types (cpu, iohog, memleak, disk-full, inode, deleted-open, dns, netloss, myapp, myapp-port). The answer is written to/root/.faultbox-answer, which is readable only by root.- Rules: You are not allowed to view the answer file,
systemctl list-units 'fault-*', orstatus.sh(which would amount to peeking); you may only proceed from “symptoms from the user’s perspective” and system metrics. - Scoring: Provide ① the root cause ② two pieces of decisive evidence ③ a stop-the-bleeding action within 5 minutes to receive full marks; points will be deducted proportionally for exceeding the time limit or providing insufficient evidence.
Why: Why Run an Unknown-Fault Challenge
Real incidents never tell you “this is a memory problem.” The unknown-fault challenge trains you to observe without preconceptions: let the data speak first, then propose a hypothesis and confirm it with another independent piece of evidence. It also exposes your “blind spots”—for example, always forgetting to check df -i or DNS.
How: Quick Reference from Symptoms → Evidence
| User Symptoms / First Impression | Most Likely | Decisive Evidence | Stop the Bleeding |
|---|---|---|---|
| System-wide slowdown, load ≈ above nproc, high us | CPU saturation (cpu) | vmstat r > nproc; pidstat points to a process | Stop or limit the process (systemctl set-property … CPUQuota=) |
| Slowdown, high load but substantial CPU idle time, high wa | I/O saturation (iohog) | vmstat b high; iostat await/aqu-sz high; iotop-c; PSI io | Limit I/O (IOWeight=/IOWriteBandwidthMax=) or stop it |
| A service repeatedly restarts, with intermittent logs | Memory leak / cgroup OOM (memleak) | Memory cgroup out of memory in journalctl -k; Failed with result 'oom-kill'; NRestarts | Roll back/restart and set MemoryMax; preserve the evidence |
Write failure, No space left on device | Block space full (disk-full) or inode space full (inode) | Either df -h or df -i shows 100% | Delete/move large files, or clean up small files |
| df says full, du says there isn't much | Deleted but still open (deleted-open) | lsof +L1 | Restart the process holding it or truncate its fd |
| External calls are consistently slow by several seconds or fail to resolve; local /healthz is normal | DNS(dns) | namelookup is slow in curl -w; upstream is abnormal in resolvectl status | Restore the DNS configuration (resolvectl revert) |
| External access is intermittently fast and slow; SSH is sluggish | Packet loss (netloss) | sar -n ETCP retrans/s; tc -s qdisc; ss -ti retrans | Remove the incorrect qdisc / repair the link |
myapp is completely unavailable, Couldn't connect | Service cannot start (myapp) or port is occupied (myapp-port) | systemctl status myapp; journalctl -u myapp; ss -ltnp 'sport = :5000' | Fix the configuration / stop the process occupying the port |
When: Retrospective Template (Blameless)
# Incident review: <one-sentence title> - - Timeline: discovered hh:mm → mitigated hh:mm → recovered hh:mm (for each step: observation / action / result) - - Impact: affected users / interfaces, duration, error rate, and latency - - Root cause: technical root cause + why it occurred (process, configuration, monitoring gaps) - - Evidence: command output (attach the original text), at least two independent pieces - - What went well / what could be improved - - Improvement items: owner + deadline (monitoring, automation, documentation, testing)
Figure 8-1: Symptoms → Resources → Evidence Map
Figure 8-2: 5-Minute Diagnostic Rhythm
Unknown-Fault Challenge Diagnostic Simulator
Click “Open the box” to randomly draw a fault (the same 10 types as blindbox.sh). You’ll see the symptom reported by the user; click “Run” on a command button below, and the terminal will show the output (example) for that fault. Each command executed uses 20 seconds of “diagnostic time.” When you’ve made a decision, select the root cause from the dropdown and submit. Scores are saved in this browser.
Unknown-Fault Challenge Tools and Evidence Collection
| Command | Purpose |
|---|---|
sudo ~/linuxlab/faults/blindbox.sh | After resetting, randomly inject one fault |
sudo ~/linuxlab/faults/blindbox.sh --reveal | View the answer after submitting a diagnosis |
~/linuxlab/sixty.sh | tee evidence.txt | 60-second checklist (Module 1) |
sudo ~/linuxlab/faults/reset.sh | Reset all faults |
Additional “First Minute” Commands (Easiest to Miss Outside the Checklist)
cat > ~/linuxlab/first-minute.sh <<'EOF'
#!/usr/bin/env bash
# Blind-box supplemental checks: services, logs, disk space, inodes, DNS, network
echo "== user view"; curl -sS -o /dev/null -m 15 -w 'local: code=%{http_code} total=%{time_total}\n' http://127.0.0.1:5000/healthz
curl -sS -o /dev/null -m 15 -w 'external: dns=%{time_namelookup} total=%{time_total}\n' https://ubuntu.com
echo "== services"; systemctl --failed --no-legend; systemctl is-active myapp
echo "== recent errors"; journalctl -p err --since "-10min" --no-pager | tail -n 8
echo "== kernel"; sudo dmesg -T --level=err,warn | tail -n 5
echo "== space"; df -h -x tmpfs -x squashfs -x efivarfs | awk 'NR==1 || $5+0 >= 85'
echo "== inodes"; df -i -x tmpfs -x squashfs -x efivarfs | awk 'NR==1 || $5+0 >= 85'
echo "== deleted"; sudo lsof -nP +L1 2>/dev/null | head -n 5
echo "== dns"; resolvectl status | grep -E 'Current DNS|DNS Servers' | head -n 4
echo "== net"; tc qdisc show | grep -v -E 'noqueue|fq_codel|mq ' ; nstat -az TcpRetransSegs | tail -n 1
echo "== psi"; grep -H some /proc/pressure/*
echo "== port5000"; sudo ss -ltnp 'sport = :5000'
EOF
chmod +x ~/linuxlab/first-minute.sh
This script uses only generic commands and does not read fault-* unit information, in accordance with the unknown-fault challenge rules. tc qdisc show will normally display rules for queues such as fq_codel / mq / noqueue; only what remains after filtering is worth noting (the default qdisc depends on the actual system).
Quick Reference: Mitigation Actions
sudo systemctl set-property --runtime SERVICE CPUQuota=50% # sudo systemctl set-property --runtime SERVICE CPUQuota=50% # Limit CPU (does not persist after restart) sudo systemctl set-property --runtime SERVICE IOWeight=10 # sudo systemctl set-property --runtime SERVICE IOWeight=10 # Lower I/O weight sudo systemctl set-property --runtime SERVICE MemoryMax=300M # sudo systemctl set-property --runtime SERVICE MemoryMax=300M # Limit memory sudo systemctl kill -s TERM SERVICE # sudo systemctl kill -s TERM SERVICE # Start politely, then escalate: TERM followed by KILL sudo resolvectl revert IFACE # sudo resolvectl revert IFACE # Restore the network interface’s DNS settings sudo tc qdisc del dev IFACE root # sudo tc qdisc del dev IFACE root # Delete the incorrect qdisc
Lab 8: Three Unknown-Fault Challenge Rounds (About 10 Minutes; More Rounds Can Be Done After Class)
~/linuxlab/incident-log.md open.sudo ~/linuxlab/faults/blindbox.sh ~/linuxlab/first-minute.sh ~/linuxlab/sixty.sh | tee ~/linuxlab/round1.txt
Write down: the root cause, two pieces of evidence, and the mitigation action. Then:
sudo ~/linuxlab/faults/blindbox.sh --reveal
inode 2026-11-17T12:05:31+00:00
reset.sh), then run first-minute.sh again to confirm recovery, and finally run sudo ~/linuxlab/faults/reset.sh.blindbox.sh resets everything first each time. You may draw the same fault again—that is also how the real world works.sudo env QUIET=1 ~/linuxlab/faults/inject.sh dns; sudo env QUIET=1 ~/linuxlab/faults/inject.sh deleted-open
Practice “run the checklist again after fixing one issue”—after the first root cause is fixed, if the symptoms do not disappear completely, that indicates there is a second problem.
~/linuxlab/postmortem-round1.md.sudo ~/linuxlab/faults/reset.sh; ~/linuxlab/faults/status.sh
Case 1: Compounding faults—disk full causing OOM?
Problem: In the early hours of the morning, services experienced widespread timeouts. The on-call engineer saw OOM logs and immediately added memory, but the problem persisted. Approach: Run the checklist again: df -h /var showed 100%—the full disk caused the application's write-retry queue to accumulate indefinitely in memory, eventually resulting in OOM. Root cause: The log level had been mistakenly set to DEBUG, and log rotation had failed. Lesson: OOM is the “result,” not the “cause”; after fixing one problem, run the checklist again.
Case 2: All services are “a little slower”
Problem: Multiple teams simultaneously reported that P99 had increased by around 300 ms, while each service's own metrics were normal. Approach: On a shared egress gateway, sar -n ETCP showed an increased retransmission rate, and tc -s qdisc revealed a forgotten netem test rule (someone had failed to clean it up after conducting a chaos experiment). Improvement: Chaos experiments must include automatic reversion (as with this lesson's fault-netem-revert.timer) and be registered.
Case 3: “The service won't start” is actually a port conflict
Problem: After deployment, the service repeatedly failed, with the logs showing only Connection in use retries. Approach: ss -ltnp 'sport = :5000' revealed that a process from the old version had not been stopped (the old unit was still running after the unit had been renamed). Improvement: Check the port and old unit in the deployment process; use Conflicts= to declare mutual exclusion.
Interactive troubleshooting tree: Something is “wrong” with a Linux host
Start with the symptom visible to the user and answer the questions step by step; the troubleshooting tree will provide a diagnosis and commands. Suitable for use when you get stuck in the unknown-fault challenge.
Common “sticking points” in the unknown-fault challenge
[ERROR] Connection in use: ('0.0.0.0', 5000)
Cause: gunicorn failed to bind to the port (another process was already listening); it retries several times per second before exiting (Retrying in 1 second. → Can't connect to ('0.0.0.0', 5000)).
sudo ss -ltnp 'sport = :5000'
journalctl -u myapp -n 20 --no-pager
Fix: Stop the process occupying the port (confirm that it is not an old version that is still serving), then run systemctl restart myapp.
myapp.service: Failed to load environment files: No such file or directory
Cause: EnvironmentFile= in the unit (or its drop-in) points to a nonexistent file; without the - prefix, a missing file causes startup to fail (wording depends on the actual systemd version).
systemctl cat myapp | grep -n -E '^# /|EnvironmentFile'
Fix: Correct the path or remove the erroneous drop-in, then restart after systemctl daemon-reload; write optional files as EnvironmentFile=-/path.
Symptom: Everything in the 60-second checklist is normal, but users still report that access to the external API fails
Cause: The checklist does not include DNS; the local /healthz also does not require DNS.
curl -sS -o /dev/null -w 'dns=%{time_namelookup}\n' https://ubuntu.com
resolvectl status | grep -E 'DNS Server'
Fix: Add first-minute.sh to your standard procedure.
[ERROR] Connection in use: ('0.0.0.0', 5000)
Cause: gunicorn failed to bind to the port (another process was already listening); it retries several times per second before exiting (Retrying in 1 second. → Can't connect to ('0.0.0.0', 5000)).
sudo ss -ltnp 'sport = :5000' journalctl -u myapp -n 20 --no-pager
Fix: Stop the process occupying the port (confirm that it is not an old version that is still serving), then run systemctl restart myapp.
myapp.service: Failed to load environment files: No such file or directory
Cause: EnvironmentFile= in the unit (or its drop-in) points to a nonexistent file; without the - prefix, a missing file causes startup to fail (wording depends on the actual systemd version).
systemctl cat myapp | grep -n -E '^# /|EnvironmentFile'
Fix: Correct the path or remove the erroneous drop-in, then restart after systemctl daemon-reload; write optional files as EnvironmentFile=-/path.
Symptom: Everything in the 60-second checklist is normal, but users still report that access to the external API fails
Cause: The checklist does not include DNS; the local /healthz also does not require DNS.
curl -sS -o /dev/null -w 'dns=%{time_namelookup}\n' https://ubuntu.com
resolvectl status | grep -E 'DNS Server'
Fix: Add first-minute.sh to your standard procedure.
1. In a single command, list filesystems with both block usage and inode usage ≥ 85% (excluding tmpfs).
paste <(df -h -x tmpfs --output=target,pcent) <(df -i -x tmpfs --output=ipcent) | awk 'NR==1 || $2+0 >= 85 || $3+0 >= 85'
2. Display the failed results (Failed with result) for all services in the past 15 minutes.
journalctl --since "-15min" --no-pager | grep "Failed with result"
Blind-box symptom: “myapp sometimes responds very slowly, and SSH also occasionally hangs.” vmstat, free, and iostat are all normal, and PSI is 0. What are your next steps and the expected evidence?
With resources all normal while SSH is also affected, this points to the network layer. Next steps: sar -n TCP,ETCP 1 (retrans/s is clearly > 0), nstat -az TcpRetransSegs increasing, connections with retransmissions in ss -tin, and tc -s qdisc show revealing a netem rule and its dropped count. Mitigation: delete the qdisc; follow-up: determine who added it and why.
Verified Instructional Videos
Themed video “Practicing fault injection / chaos experiments on a single Linux machine”: No verified video found.
References
- Google SRE Book: Postmortem Culture
- Performance Analysis Methodology(Brendan Gregg)
- tc-netem(8) · systemd-run(1)
Video Storyboard (approximately 90 seconds)
This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.
Visual: A gift box opens, and a user complaint floats out: “myapp doesn’t seem quite right.” The timer starts.
Voice-over: Unknown-fault challenge: you do not know what was injected; you only have a single sentence from the user.
Visual: The terminal sequentially runs curl dash w, the 60-second checklist, and df dash i; one cell in the USE matrix turns red.
Voice-over: Quantify the symptoms first, then run the checklist. Once you find an anomaly, confirm it with a second independent piece of evidence; do not let the first red light lead you astray.
Scene: Execute the mitigation command and watch the curve fall; the postmortem document automatically fills in the timeline, root cause, and improvement items.
Voice-over: Mitigate, verify recovery, then write the postmortem. Next time, the same problem will be detected within one minute.
Command Cheat Sheet
60-Second Checklist
uptime sudo dmesg -T | tail vmstat 1 mpstat -P ALL 1 pidstat 1 iostat -xz 1 free -m sar -n DEV 1 sar -n TCP,ETCP 1 top grep -H . /proc/pressure/*
CPU and Load
cat /proc/loadavg ps -eo pid,stat,wchan:32,comm | awk '$2 ~ /^D/' pidstat -t -u -p PID 1 pidstat -w 1 # cswch / nvcswch systemd-cgtop cat /sys/fs/cgroup/system.slice/SVC.service/cpu.stat sudo runqlat-bpfcc 10 1
Memory
free -h -w grep -E 'MemAvailable|Dirty|AnonPages|Commit' /proc/meminfo ps -eo pid,rss,comm --sort=-rss | head pidstat -r 1 journalctl -k -b | grep -E 'Killed process|oom-kill:' cat /proc/PID/oom_score /proc/PID/oom_score_adj systemctl show SVC -p MemoryCurrent -p MemoryMax -p NRestarts cat /sys/fs/cgroup/system.slice/SVC.service/memory.events
Disk and File Systems
iostat -xz 1 sudo iotop-c -o -P pidstat -d 1 df -hT; df -i sudo du -xh -d1 / | sort -h sudo lsof -nP +L1 sudo truncate -s 0 /proc/PID/fd/N # sudo truncate -s 0 /proc/PID/fd/N # Emergency release (data loss) journalctl --disk-usage sudo biolatency-bpfcc -D 10 1
Network and DNS
curl -sS -o /dev/null -w 'dns=%{time_namelookup} tcp=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' URL
ss -ltnp; ss -tin state established
nstat -az | grep -E 'Retrans|ListenOverflows'
sudo tcpdump -i any -nn -c 50 port 5000
resolvectl status; resolvectl query NAME
dig +tries=1 +time=2 @SERVER NAME
tracepath -n HOST; ping -M do -s 1472 HOST
sudo conntrack -S; tc -s qdisc showBoot and Rescue
sudo findmnt --verify --verbose sudo systemctl daemon-reload && sudo mount -a journalctl --list-boots; journalctl -b -1 -p err systemd-analyze critical-chain # GRUB kernel parameters: # systemd.unit=rescue.target | emergency.target # rd.break init=/bin/bash mount -o remount,rw / sudo update-initramfs -u -k all; sudo update-grub
strace / perf
sudo strace -f -c -p PID sudo strace -f -tt -T -e trace=%file -e status=failed -p PID sudo perf top -g sudo perf record -F 99 -a -g -- sleep 30 sudo perf report --stdio --no-children sudo perf script | stackcollapse-perf.pl | flamegraph.pl > f.svg
eBPF
sudo bpftrace -l 'tracepoint:syscalls:*open*'
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args.filename)); }'
sudo bpftrace -e 'profile:hz:99 { @[kstack] = count(); }'
sudo execsnoop-bpfcc
sudo opensnoop-bpfcc -x
sudo offcputime-bpfcc -p PID -f 10
sudo tcpretrans-bpfcc; sudo oomkill-bpfcc
sudo gethostlatency-bpfccQuick Troubleshooting Table
| Symptom / Error | First Command | Common Root Cause | Module |
|---|---|---|---|
| High load, high r, high us | pidstat 1 | CPU-intensive process, infinite loop | M2 |
| High load, high b, high wa | iostat -xz 1 | Disk saturation, NFS stuck | M2 / M4 |
| Service is slow even though the overall machine CPU is not high | cat …/cpu.stat | CPUQuota throttling, waiting for locks/network | M2 / M7 |
Killed process / oom-kill | journalctl -k -b | Leak, MemoryMax too small | M3 |
| SSH hangs and then recovers, no OOM | cat /proc/pressure/memory | Thrashing | M3 |
No space left on device | df -h; df -i | Blocks full / inodes full / tmpfs full | M4 |
| df full, du low | lsof +L1 | Deleted but still open, mount point shadowing | M4 |
Could not resolve host / consistently slow for 5 seconds | resolvectl status | Upstream DNS unreachable | M5 |
| Alternating between fast and slow, retransmissions | sar -n ETCP 1 | Packet loss, qdisc, link | M5 |
table full, dropping packet | conntrack -S | conntrack_max too small | M5 |
You are in emergency mode | journalctl -xb -p err | fstab error | M6 |
grub rescue> | ls, set prefix | Partition changes, /boot corrupted | M6 |
Service Failed with result 'resources' | systemctl cat SVC | Missing EnvironmentFile, etc. | M8 |
Connection in use: ('0.0.0.0', 5000) | ss -ltnp 'sport = :5000' | Port already in use | M8 |
Recommended Configuration Snippets
[Service] # Resource protection: keep myapp’s problems within its own cgroup MemoryHigh=600M MemoryMax=800M OOMScoreAdjust=-500 CPUWeight=200 TasksMax=512 LimitNOFILE=65536 Restart=on-failure RestartSec=3
UUID=<uuid> /data ext4 defaults,nofail,x-systemd.device-timeout=10s 0 2
# For easier troubleshooting (enable as needed) kernel.hung_task_timeout_secs = 120 # Temporarily enable iotop’s IO% column when troubleshooting I/O: # kernel.task_delayacct = 1
[Journal] SystemMaxUse=500M
Comprehensive Lab + Final Assessment
sudo ~/linuxlab/faults/reset.sh >/dev/null sudo env QUIET=1 ~/linuxlab/faults/inject.sh deleted-open sudo env QUIET=1 ~/linuxlab/faults/inject.sh iohog history -c # Teammate cleared the history to avoid spoilers
for i in $(seq 10); do curl -sS -o /dev/null -w '%{time_total}\n' http://127.0.0.1:5000/healthz; done | sort -n | tail -3
~/linuxlab/first-minute.sh 2>&1 | tee ~/linuxlab/final-first.txt~/linuxlab/sixty.sh 2>&1 | tee ~/linuxlab/final-sixty.txt grep -A4 -E '===== (vmstat|iostat)' ~/linuxlab/final-sixty.txt
Expected: vmstat’s b and wa are elevated, iostat’s await/aqu-sz are elevated, PSI io is non-zero; /mnt/faultdisk utilization is high.
sudo iotop-c -o -b -n 3 | head -n 15 pidstat -d 1 3 sudo biolatency-bpfcc 5 1
df -h /mnt/faultdisk; sudo du -sh /mnt/faultdisk sudo lsof -nP +L1
sudo systemctl set-property --runtime <I/O process unit> IOWeight=10 # Lower priority first sudo systemctl stop <I/O process unit> # Then stop it sudo truncate -s 0 /proc/<PID>/fd/<N> # Release the deleted file ~/linuxlab/first-minute.sh | head -n 12 # Verify recovery
The unit name can be obtained from ps -o unit= -p PID or systemctl status PID—this is the standard method for tracing a service back from a process.
50-resources.conf from the quick reference table to myapp, run sudo systemctl daemon-reload && sudo systemctl restart myapp, and confirm systemctl show myapp -p MemoryMax -p OOMScoreAdjust.~/linuxlab/postmortem-final.md using the M8 template, then run sudo ~/linuxlab/faults/reset.sh.Open-ended self-test (6 questions)
>1. Why is Linux's load average called “system load” rather than “CPU load”? Give an example where the load is high but adding CPUs is ineffective.
Linux counts D state (uninterruptible sleep, usually waiting for disk I/O or NFS) toward the load. For example, when an NFS server is unresponsive, hundreds of processes may be stuck in D state, resulting in a load in the hundreds while the CPU is idle; adding CPUs is completely ineffective—you need to fix the storage or network.
2. When should you use USE, and when should you use RED?
RED (rate, errors, and duration/latency) confirms “whether there is a problem and how severe it is” from the service/user perspective; USE (utilization, saturation, and errors) identifies “which resource is the bottleneck” from the resource perspective. Typically, first use RED to confirm and quantify the symptoms, then USE to locate the resource, and finally profiling/tracing tools to reach the code level.
3. What are the differences between system-wide OOM and cgroup OOM in terms of logs and scope of impact? How can the impact of a leak be limited to a single service?
System-wide OOM: constraint=CONSTRAINT_NONE, Out of memory: Killed process; it may kill any process. cgroup OOM: CONSTRAINT_MEMCG, Memory cgroup out of memory; it selects processes only within the over-limit cgroup. Set MemoryMax= for the service (optionally together with MemoryHigh= to throttle it in advance), and set a negative OOMScoreAdjust= for critical services.
4. Explain the three possible causes of “No space left on device” and give one diagnostic command for each.
Blocks exhausted (df -h), inodes exhausted (df -i), or tmpfs or the quota is full (df -h -t tmpfs / quota); additionally, when df and du do not match, use lsof +L1 to find files that have been deleted but remain open.
5. Why can’t tcpdump see outbound packets discarded by local netem? What does this imply for troubleshooting?
For outbound traffic, the capture point is after the qdisc; netem drops packets within the qdisc, so the packets never reach the capture point. Therefore, you can only see subsequent retransmissions; use the dropped counter from tc -s qdisc and retransmissions from nstat/ss -ti to prove packet loss. During troubleshooting, you must be clear about the observation point of each tool.
6. How should strace and eBPF tools be weighed in production environments?
strace is based on ptrace; it pauses the process for every system call, resulting in extremely high overhead for processes making frequent system calls. It is suitable for low-traffic, short-duration scenarios that require complete parameters, and -e/--seccomp-bpf can be used to reduce overhead. eBPF filters and aggregates within the kernel with low overhead, making it suitable for production; however, it requires root, BTF, and an understanding of the probes.
Sources and Version Notes
Sources and Verification Conclusions
| Topic | Verification conclusion | Sources (accessed 2026-11-17) |
|---|---|---|
| Current Ubuntu LTS | Ubuntu 26.04 LTS (Resolute Raccoon), released in 2026-04; Linux kernel 7.0 (linux-generic 7.0.0-42.42); dracut, sudo-rs, and Rust coreutils by default | Ubuntu 26.04 release notes; packages.ubuntu.com |
| Package versions (resolute) | systemd 259.5, sysstat 12.7.7, procps 4.0.4, strace 6.19, ltrace 0.7.91, bpftrace 0.25.0, bpfcc-tools 0.35.0, iotop-c 1.31, iotop 0.6(universe), htop 3.4.1, stress-ng 0.20.01, tcpdump 4.99.6, iproute2 6.19.0, conntrack 1.4.9, dracut 110, initramfs-tools 0.151, bind9-dnsutils 9.20 | packages.ubuntu.com/resolute |
| perf package | In 26.04, /usr/bin/perf is provided by linux-tools-common + linux-tools-$(uname -r) | packages.ubuntu.com file contents search |
| bcc / bpftrace tool filenames | /usr/sbin/execsnoop-bpfcc, oomkill-bpfcc, biolatency-bpfcc, tcpretrans-bpfcc, runqlat-bpfcc, opensnoop-bpfcc, gethostlatency-bpfcc, offcputime-bpfcc, profile-bpfcc(bpfcc-tools); /usr/sbin/oomkill.bt, biolatency.bt, execsnoop.bt(bpftrace) | packages.ubuntu.com file contents search |
| initramfs | In 26.04, update-initramfs is provided by both dracut and initramfs-tools; lsinitrd is in dracut-core, and lsinitramfs is in initramfs-tools-core | packages.ubuntu.com file contents search |
| tc netem module | sch_netem.ko is located in linux-modules-7.0.0-*-generic for the 26.04 generic kernel (not in an extra package) | packages.ubuntu.com file contents search |
| vmstat gu columns | procps-ng 4.0.4 NEWS: “vmstat: Print guest time in non-wide mode” | procps NEWS |
| 60-second checklist | 10 commands and their order | Netflix TechBlog (2015) |
| USE method, load average | USE definitions and Linux checklist; Linux load includes D state | USE Method; Linux Load Averages |
| PSI, cgroup v2, overcommit | some/full semantics; memory.max/high/events; overcommit modes | PSI; cgroup v2; overcommit |
| systemd resource control and rescue target | MemoryMax/High, OOMScoreAdjust, OOMPolicy; rescue/emergency; nofail, device-timeout | systemd.resource-control; systemd.special; systemd.mount |
| Python perf support | -X perf / PYTHONPERFSUPPORT for Python 3.12+ | Python HOWTO |
Video Verification Notes
All videos were verified via YouTube oEmbed (https://www.youtubode>https://www.youtube.com/oembed?url=…&format=json) on 2026-11-17 for their titles and channels:
| Video ID | Title | Channel | Used for |
|---|---|---|---|
| fhBHvsi0Ql0 | LISA19 - Linux Systems Performance | USENIX | M1, M2, M3, M5, M8 |
| FJW8nGV4jxY | Linux Performance Tools, Brendan Gregg, part 1 of 2 | Brendan Gregg | M1, M4 |
| zrr2nUln9Kk | Linux Performance Tools, Brendan Gregg, part 2 of 2 | Brendan Gregg | M1, M8 |
| 0LWgrHYsVhs | Demystifying Linux CPU Load Averages | BeginLinux Guru | M2 |
| XE2hdDspyPA | Linux Load Average Explained: Troubleshooting a Slow Server with uptime and top | OpsAccel Consulting | M2 |
| DQvvEPLToQc | Tcpdump in Linux | Linux R | M5 |
| D53T1Ejig1Q | USENIX ATC '17: Visualizing Performance with Flame Graphs | USENIX | M7 |
| nZfNehCzGdw | LISA13 - Blazing Performance with Flame Graphs | USENIX | M7 |
| bGAVrtb_tFs | Getting Started with BPF observability – Brendan Gregg, Netflix | eBPF & Cilium Community | M7 |
| _5Z2AU7QTH4 | LISA21 - BPF Internals | USENIX | M7 |
No verified dedicated videos were found for M3 (OOM / cgroup memory), M4 (inode / deleted-open), M6 (boot recovery), or the fault injection topic. Storyboard scripts have been provided in the corresponding “Videos” tabs. Videos from small third-party channels are for supplementary purposes only; this course and the official documentation take precedence.
Voice-Over Explanation Notes-Over Explanation Notes
The “Voice” tab uses the browser's built-in Web Speech API (speechSynthesis, zh-CN voice) to read the explanatory script aloud in real time; English terms are read using an en-US voice. This courseware cannot embed or generate MP3 files; when audio is needed, the explanatory script can be provided to any TTS tool.
Known Limitations
- All command output in this course is illustrative and was not executed line by line on a physical Ubuntu 26.04 machine; values, column widths, network interface names (ens3/enp0s1/eth0), PIDs, and so on should be determined by the actual environment.
- The error messages marked “subject to actual results” (such as systemd’s EnvironmentFile failure message, the error text from resolvectl, sulogin’s root-lock message, dracut warnings, the conntrack table-full message prefix, iotop’s delayacct prompt, and perf wrapper-script prompts) are based on upstream source code or recollections from common versions and were not verified verbatim on 26.04.
- Ubuntu 26.04 defaults to the Rust version of coreutils (uutils) and sudo-rs: the error messages or option support of
touch,dd,du --inodes, and similar commands may differ from the GNU versions; general alternative methods, such as using find to count inodes, are provided in the text. - The display formula for
/proc/PID/oom_scorevaries with the kernel version; the example values are provided only for comparing relative magnitudes. - The specific default value of Ubuntu’s
kernel.perf_event_paranoidand whether systemd-oomd is installed by default on the Server edition were not verified on a physical 26.04 machine. The course uses sudo throughout and prompts users to check for themselves. - The use of
SYSTEMD_SULOGIN_FORCEis based on the environment-variable description in the systemd documentation; behavior may vary between versions. Be sure to practice with snapshot protection. - The parameters for Multipass snapshot commands (1.13+) and
multipass transfershould be determined usingmultipass help. WSL2 cannot complete the M5 netem, M6 boot, or some perf experiments. - The fault injection script assumes that myapp is deployed according to the conventions in Lesson 2 (
myapp.service, port 5000). If the implementation in Lesson 2 differs—for example, if it listens only on 127.0.0.1—the symptoms of themyapp-portfault will differ.