Linux, Hour 7: Troubleshooting and Performance

Start with a simple symptom—“the machine is slow” or “the service is down”—then use the USE method and a 60-second checklist to isolate the cause across CPU, memory, storage, networking, and boot. Use strace, perf, and eBPF to inspect what is happening inside the kernel.
Ubuntu Server 26.04 LTS · Linux 7.0systemd 259sysstat 12.7.7 · procps 4.0.4bpftrace 0.25 · bcc 0.35Verified against official materials · 2026-11
Overall Learning Objectives
  • 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, and pidstat to 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’s memory.max/memory.high, and PSI pressure metrics.
  • Use iostat -x to determine disk saturation (including the limitations of r_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, and tracepath to 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 *-bpfcc on 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

#TimeModuleCore ContentAnimation / InteractionLab (linuxlab VM)
0Before classPreparation: Fault-Injection EnvironmentInstall observability tools, genobservability tools, generate ~/linuxlab/faults/ injection/reset/mystery-box scripts, and take a snapshotEnvironment self-checkinject.sh / reset.sh smoke test
100–06Troubleshooting Methodology: USE and 60-Second AnalysisUSE meethod, RED Method, 10-command checklist, mitigate the impact before finding the root cause, and record the timelineCore animation: Walk through a real incident using the 60-second checklist (6 optional fault types)Run the 10 commands after injecting a CPU fault
206–13CPU and Loadloadaverage calculation and the D state, us/sy/wa/st/si, run queue, context switches, top/htop, vmstat, mpstat, pidstat, and PSI cpuLoad-average simulator (R and D tasks)CPU hog + I/O hog, comparing load and CPU%
313–21Memory: OOM, Swap, and Page Cachefree/available, page-cache reclaim, swap, overcommit, the OOM killer and oom_score_adj, cgroup memory.max/high, PSI memory, and systemd-oomdMemory pressure: reclaim → swap → OOM victim selectionA memory leak is OOM-killed within a cgroup; read the kernel logs
421–28Disk I/O and File Systemsiostat -x, iotop-c, await/aqu-sz/%util, full blocks vs. full inodes, deleted-but-still-open files, and PSI iodf / df -i / du three-view simulatorDisk full, inode exhaustion, and deleted-open—the three-part sequence
528–35Network Troubleshooting: tcpdump, ss, and DNSss Statusatus and Recv-Q/Send-Q, tcpdump filters, retransmissions, conntrack, DNS timeouts, MTU/PMTUD, tc netemSingle-request failure-point locatorSlow DNS + 20% packet-loss injection and diagnosis
635–42Boot Failures: GRUB, initramfs, and RescueBoot chain, Gchain, GRUB menu and kernel parameters, dracut/initramfs, rescue/emergency targets, root lockout and sulogin, fstab nofailBoot-chain failure-point simulatorWrite an incorrect fstab and recover under snapshot protection
742–50Advanced Tools: strace, perf, and eBPFstrace -c/-f/-T, ltrace, perf top/record/report, flame graphs, bpftrace one-liners, the bcc toolkit, overhead comparisonFlame graph builder (sampling → folding → rendering)Create a CPU flame graph for myapp and use bpftrace to capture OOM and slow I/O
850–60Comprehensive Troubleshooting Mystery BoxRandom injection,m injection, time-limited diagnosis, incident postmortem writingMystery-box diagnosis simulator + interactive troubleshooting treeThree rounds of hands-on practice with blindbox.sh
—After the courseCheat Sheet · Comprehensive Lab“mylows down on Monday morning” multi-fault exerciseFinal assessment (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target SkillsM1M2M3M4M5M6M7M8Key CommandsLab
Systematic troubleshooting methods (USE / 60-second checklist)✓······✓uptime, dmesg, vmstat, sarM1, M8
CPU saturation and load interpretation✓✓·✓··✓✓mpstat -P ALL, pidstat, /proc/pressure/cpuCPU hog
Memory pressure, OOM, cgroup limits✓·✓···✓✓free -m, journalctl -k, systemctl show -p MemoryMaxmemleak
Disk I/O and space/inodes✓✓·✓··✓✓iostat -xz, df -i, lsof +L1disk / inode / deleted
Networking, DNS, retransmissions, MTU✓···✓·✓✓ss -tinp, tcpdump, resolvectl, tracepathdns / netloss
Boot failures and rescue···✓·✓·✓findmnt --verify, systemctl emergency, update-initramfsfstab exercise
Service-level failures (systemd)✓·✓·✓✓✓✓systemctl status, journalctl -umyapp failures
System calls / profiling / eBPF tracing·✓✓✓✓·✓✓strace -fc, perf record -g, bpftrace -eFlame graphs
Fault injection and postmortems✓✓✓✓✓··✓inject.sh, reset.sh, blindbox.shAll

Content Excluded from This Course (and Where to Learn It)

TopicWhy It Is Not in This CourseWhere 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 systemPrometheus & Grafana in 8 + 1 Hours
cgroup / namespace details inside containers, docker statsThe principles are briefly covered in M3 of this course; the application layer is covered in the container courseDocker in 8 Hours
systemd unit writing, journal, journald, LVM, fstab basicsAssumed to be known for this courseLesson 2
Batch remediation, configuration drift managementPart of automated operationsLesson 5, Ansible in 8 Hours
Kernel crash dumps (kdump / crash)dump / crash), kernel debuggers, driver issuesRequires a separate environment and a substantial amount of timeUbuntu Server documentation: Kernel crash dump
Application-internal tuning for databases / JVMs and the likeSpecific to the applicationThe 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

10 Tabs for Each Module
Principles · Diagrams · Animations · Commands · Labs · Production Cases · Troubleshooting · Quizzes · Audio · Video. Recommended order: Principles → Animations → Use the troubleshooting toolbox to perform labs → Troubleshooting.
Learning Progress
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).
Chinese Audio
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.
Version NotesThis course uses Ubuntu Server 26.04 LTS (Resolute Raccoon, released in 2026-04) as its baseline: Linux kernel 7.0 (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

Install the diagnostic tools, set up a repeatable fault-injection toolkit with a simple reset procedure, and snapshot the lab machine.
Before class ≈ 10 minuteslinuxlab · Ubuntu 26.04 LTSLab Machine Only
Prerequisites
  • Use the Lesson 1 VM named linuxlab, the labadmin account with sudo access, and ~/linuxlab as your working directory. We recommend 2 vCPUs, 4 GiB of memory, and a 20 GiB disk. With Multipass, create it using multipass launch --name linuxlab --cpus 2 --memory 4G --disk 20G.
  • Complete Lesson 2 first. It sets up myapp.service with the myapp system account, application files in /opt/myapp, a virtual environment in /opt/myapp/venv, configuration in /etc/myapp/myapp.env, port 5000, and a /healthz health check. Redis should be running as redis-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, perf hardware 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 providedPurpose in this lesson
sysstatiostat mpstat pidstat sarPrimary tool for the 60-second checklist (background collection is not required in real-time mode)
procps (preinstalled)vmstat free top uptime psLoad, memory, and processes
iotop-ciotop-cView I/O by process (C rewrite; the old Python version is packaged as iotop, which is still in universe)
bpftracebpftrace 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 -bpfcc suffix
linux-perfperfCPU profiling and flame graphs
stress-ngstress-ngGenerate 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
Script notes① The 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.

Environment self-checklist

Module 1 · Troubleshooting Methodology: The USE Method and 60-Second Analysis

00:00–06:00 · Don’t guess or reach for a reboot. Use a repeatable checklist to assess utilization, saturation, and errors across every resource.
6 minutessysstat 12.7.7 · procps 4.0.4★★★★★
Learning objectives
  • 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.
Prerequisites: Processes and /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.

ResourceUtilizationSaturationErrors
CPUmpstat -P ALL 1 100−%idle; topvmstat 1 r column > CPU count; load average; /proc/pressure/cpuRare (MCE hardware error; see dmesg)
Memoryused / available from free -msi/so from vmstat (swap-in/swap-out); /proc/pressure/memory; OOM eventsOOMs and page allocation failures in the kernel log
Disk I/O%util from iostat -xz 1aqu-sz (average queue length), r_await/w_await; /proc/pressure/ioI/O errors in dmesg, smartctl
Disk capacitydf -h, df -i(A full disk is itself the endpoint of saturation.)ENOSPC: No space left on device
NetworkrxkB/s, txkB/s from sar -n DEV 1 and their ratio to bandwidthSend-Q/Recv-Q from ss, retransmissions, overflow counters from nstaterrors/dropped from ip -s link, sar -n EDEV 1
Software resourcesUtilization of thread pools / connection pools / file descriptorsNumber of requests waiting for a connection, accept queue overflowsEMFILE (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:

#CommandWhat to check firstCorresponding USE
1uptimeTrend in 1/5/15-minute load: a 1-minute value far above the 15-minute value indicates the problem has just startedCPU/disk saturation (roughly)
2dmesg -T | tailKernel messages such as OOM, I/O errors, TCP packet loss, and hung tasksVarious E
3vmstat 1r (runnable tasks), b (D-state), si/so, us/sy/id/wa/stCPU S, memory S
4mpstat -P ALL 1Whether one CPU is fully utilized (single-thread bottleneck), %iowait, %steal, %softCPU U
5pidstat 1Which process is consuming CPU (rolling output makes changes easy to spot)CPU U (by process)
6iostat -xz 1r/s, w/s, r_await/w_await, aqu-sz, %utilDisk U/S
7free -mavailable column (not the free column), swap usedMemory U
8sar -n DEV 1rxkB/s, txkB/s, %ifutil for each network interfaceNetwork U
9sar -n TCP,ETCP 1active/s (active connections), passive/s (passive connections), retrans/sNetwork S/E
10topComprehensive 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

  1. Confirm and quantify the symptoms: Who reported it? Which interface? What time did it start? (curl -w '%{time_total}', latency in the logs)
  2. 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.
  3. 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).
  4. 60-second checklist → hypothesis → verify with specialized tools (the tools in M2–M7).
  5. 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

USEREDGolden Signals(Google SRE)“Tool-driven” troubleshooting
PerspectiveResources (machines)Requests (services)Services: latency, traffic, errors, saturationLook at whatever tools happen to be at hand
Applicable toHost/kernel-level bottlenecksMicroservices, APIsAlert designNot recommended
Position in this courseMain line for M1–M5M1 symptom confirmation, M8 unknown-fault challengeMonitoring courseNegative example
Common misconceptions① “%util at 100% means the disk is fully loaded”—for SSDs/NVMe and RAID, the device can process multiple requests in parallel; %util at 100% only means that “there are always requests in flight.” You need to look at await and aqu-sz (M4). ② “A high load average means there is not enough CPU”—Linux load includes tasks in the D state, and blocked disks or NFS can also increase the load (M2). ③ “A very small value in the free column means there is not enough memory”—Linux uses free memory as page cache; you need to look at available (M3). ④ “Restart first and ask questions later”—a restart will erase the scene, and the same problem will recur next week.

Figure 1-1: USE Method Inspection Matrix

Resource \ Dimension Utilization Saturation Errors CPU mpstat: 100 − %idle vmstat r > nproc · PSI cpu dmesg: MCE (rare) Memory free: total − available vmstat si/so · PSI memory OOM kill · Allocation failure Disk iostat %util · df / df -i aqu-sz · await · PSI io I/O error · ENOSPC Network sar -n DEV: %ifutil retrans/s · Send-Q · Overflow ip -s link: errors/dropped Check cell by cell: any abnormal cell is a “hypothesis to be verified,” not a conclusion
Figure 1-1 USE method: each resource × three dimensions, with a specific command corresponding to each cell

Figure 1-2: Workflow from Symptoms to Root Cause

SymptomRED: slow / error / down Recent change?journal · apt · git StabilizeSave the scene first 60-Second ChecklistFull USE Coverage Deep-Dive Verificationperf/strace/bpf Root Cause + RetrospectiveBlameless · Action Items Hypothesis disproved → Return to checklist Record every step in the incident timeline (time · observation · action · result); this is the raw material for the retrospective
Figure 1-2 Stabilize first, then find the root cause; if a hypothesis is disproved, return to the checklist instead of switching to another random tool

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.

USE Clue Matrix
Current hypothesis: (none yet)
Select a fault to begin.
labadmin@linuxlab:~$

Core Commands and Parameters

CommandFunctionKey Parameters / Description
uptimeUptime and 1/5/15-minute load averagesYou can also read /proc/loadavg (the fourth field is the “runnable/total task count”)
dmesg -T | tail -n 30Kernel 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 5System-wide CPU, memory, swap, and I/O overviewThe first line is the average since boot; ignore it; -w wide format; -S M
mpstat -P ALL 1Time distribution for each CPU-P ALL all CPUs; look for a single core at 100%
pidstat 1Per-process CPU usage-u CPU, -r memory, -d disk, -w context switches, -t threads, -p PID
iostat -xz 1Extended block device statistics-x extended columns, -z hide inactive devices, -m MB units
free -mMemory overview-h, -w (separate buffers and cache)
sar -n DEV 1 / sar -n TCP,ETCP 1Network interface throughput / TCP connections and retransmissions-n EDEV network interface errors; -n SOCK socket count
top / htopInteractive process viewIn top, 1 expands CPUs, M sorts by memory, and P sorts by CPU
cat /proc/pressure/*PSI pressure stall informationsome/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)

Record the healthy baseline (while myapp is running normally):
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
Inject a CPU failure and quantify the symptoms:
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.”

Run the checklist and compare it with the baseline:
./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
Write an incident timeline (practice the habit of recording incidents):
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
EOF
Stop the bleeding, verify, and clean up:
sudo 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).

Command-Line Operations Questions
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 some
Scenario Analysis Questions
3: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

▶
LISA19 - Linux Systems Performance — USENIX
Brendan Gregg · USENIX LISA 2019 · English · A systematic explanation of methodologies (including USE), the tools in the 60-second checklist, profiling, and BPF; the preferred video for this module
▶
Linux Performance Tools, Brendan Gregg, part 1 of 2 — Brendan Gregg
Velocity 2015 tutorial · English · An overview of observability tools and anti-methods, corresponding one-to-one with this course's checklist
▶
Linux Performance Tools, Brendan Gregg, part 2 of 2 — Brendan Gregg
English · Benchmarking, tuning, and static performance analysis; recorded earlier, so use the tool versions specified in this course

Official and First-Handial and First-Hand Materials

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.

Shot 1 · 0–15s
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.
Shot 2 · 15–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% in “Quiz”in “Quiz”

Module 2 · CPU and Load: top, vmstat, mpstat, pidstat

06:00 – 13:00 · Load is not the same as CPU utilization: distinguish between “waiting in the queue for CPU,” “stuck on I/O,” “throttled by cgroup,” and “stolen by virtualization”
7 minutesLinux 7.0 · EEVDF Scheduler★★★★★
Learning Objectives
  • 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 mpstat to identify single-core bottlenecks, use pidstat -u/-w/-t to locate processes, threads, and context switches, and use cpu.stat to identify cgroup throttling.
Prerequisite Knowledge: Process states (R/S/D/Z) and signals from Lesson 1. Importance:★★★★★

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)

FieldMeaningTypical causes when elevated
us / %usrUser modeApplication computation, serialization, regular expressions, encryption
sy / %sysKernel modeLarge numbers of system calls, small I/O operations, locks, memory allocation; network packet processing
ni / %niceLower-priority user-mode processesBatch processing, backups (nice 19)
id / %idleIdle—
wa / %iowaitCPU is idle while tasks are waiting for I/OSlow disk; note: it is a subset of idle, and its value can be misleading on multicore systems
hi / si(%irq / %soft)Hard interrupts / soft interruptsHigh network packet rate (NET_RX), timers; high %soft on a single core indicates that NIC queues are not distributed
st / %stealVirtual machine wants to run, but the host does not provide CPU“Noisy neighbors” in the cloud, burstable instance credits exhausted
gu / %guestTime spent running virtual machine vCPUsThe 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.2 means 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 own cpu.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_throttled in cpu.stat increases—even when the system’s CPUs are largely idle, the service becomes slower.

When: Decision process

  1. uptime: Is load / nproc > 1? Is the trend rising or falling?
  2. vmstat 1: High r → CPU saturation; high b and high wa → I/O (go to M4); high st → virtualization.
  3. mpstat -P ALL 1: Overall usage is not high, but one CPU is at 100% → single-thread bottleneck or concentrated interrupts.
  4. pidstat 1 / top: Identify the process; pidstat -t -p PID 1 identifies the thread; pidstat -w shows context switches.
  5. Is the service in a cgroup? Compare systemctl show myapp -p CPUQuotaPerSecUSec with cpu.stat.

Tool comparison

tophtopvmstatmpstatpidstat
GranularitySystem + processSystem + process/thread (tree view)SystemPer CPUProcess/thread
AdvantagesAvailable everywhere; supports batch processing with -bInteractive and user-friendly; can display cgroup, I/O, and PSI columnsCPU, memory, and I/O on one screenFinds per-core bottlenecksScrolling output, suitable for recording; can also collect statistics for short-lived processes
LimitationsInteractive refreshes can miss short-lived processesRequires installationNot per-processNot per-processRequires sysstat
Common misconceptions① “A load of 8 on an 8-core machine means it is fully loaded”—if six of them are tasks in D state, the CPU may actually be idle. ② “High %iowait means the disk is slow”—iowait only means that “the CPU is idle while someone is waiting for I/O”; when the CPU is busy, iowait decreases, but the disk has not become faster. ③ “CPU 300% in top is a bug”—the top process column calculates by single core by default (Irix mode), so multithreaded processes can exceed 100%. ④ “nice can limit a process’s CPU usage”—nice only affects weighting during contention; when the CPU is idle, a nice 19 process can still use it fully.

Figure 2-1: Which tasks does load average measure?

R: Running / Runnable CPU0 Running CPU1 Running Waiting in the run queue ×3 (vmstat r) Counted in load ✓PSI cpu measures precisely the “waiting” portion D: Uninterruptible Sleep Waiting for disk read/write completion (vmstat b) NFS server unresponsive, certain kernel locks Counted in Linux load ✓ (not counted in other Unix systems)Even kill -9 cannot kill it until I/O returns S: Interruptible Sleep / Other A gunicorn worker waiting on the network, a timer, or epoll I: Idle Kernel Thread (not counted) Z: Zombie (exited, waiting for the parent process to wait) Not counted in load ✗ load(1min) ← Every 5 seconds: load × 0.920 + (R + D) × 0.080
Figure 2-1 Linux load = exponential moving average of the number of R + D tasks (2-core machine: 2 running + 3 queued + 2 in D state ≈ load 7)

Figure 2-2: CPU problem decision process

load / nproc > 1 ? vmstat r highCPU saturation b high / wa highD state: go to M4 Disk st highHost contention / Credit exhaustion us highperf flame graph sy / si highstrace -c · Interrupt distribution Single core at 100%mpstat · pidstat -t The entire machine is idle, but the service is slowcgroup cpu.stat nr_throttled
Figure 2-2 First use vmstat to classify the problem into CPU / I/O / virtualization, then select specialized tools

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.

CPU0 / CPU1 Run queue (waiting) D state (waiting for I/O)
load average: 0.00, 0.00, 0.00
CPU utilization:0% · vmstat r=0 b=0 · Simulated time0s
nproc = 2
Click the button to add tasks, then run the clock.
$ cat /proc/loadavg 0.00 0.00 0.00 1/180 4200

Core Commands and Parameters

CommandFunctionKey Parameters / Description
cat /proc/loadavgRaw load valueColumn 4 2/183 = current runnable count / total number of schedulable entities; column 5 = most recent PID
top -b -n1 -o %CPUBatch snapshot-H threads, -p PID, -c full command line; press 1 during interaction to view per-CPU data
htopInteractiveF2 Setup can add PSI, IO, and CGROUP columns; F5 tree view; H show/hide user threads
vmstat 1r, b, cs, in, us/sy/id/wa/st-w wide format, -t add timestamps
mpstat -P ALL 1Per-CPU time distribution-I SUM/-I SCPU interrupt statistics
pidstat -u 1 / -t -p PID 1 / -w 1Process CPU / threads / context switchescswch/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=-pcpuState + kernel wait pointR, D, S in STAT; wchan shows which kernel function the process is sleeping in
systemd-cgtopView 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)

Inject a CPU fault and observe for 1 minute:
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
Locate processes and threads:
pidstat -u 1 3 | tail -n 5
top -b -n1 -o %CPU | sed -n '7,12p'
systemd-cgtop -n 1 -b | head
Switch to an I/O fault:
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).

Compare context switches:
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.

Cleanup:
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.

Command-Line Exercise
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
Scenario Analysis Exercise
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

▶
Demystifying Linux CPU Load Averages — BeginLinux Guru
English · Explains the difference between load averages and CPU utilization (third-party channel; the content of this lesson and the original text by Brendan Gregg should be taken as authoritative)
▶
Linux Load Average Explained: Troubleshooting a Slow Server with uptime and top — OpsAccel Consulting
English · Live demonstration of troubleshooting a slow server with uptime/top
▶
LISA19 - Linux Systems Performance — USENIX
Brendan Gregg · English · The CPU analysis and load sections can be used as in-depth reference material

Official and First-Partyial and First-Party Materials

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–80s
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.
or score ≥ 70% in the “Quiz”in the “Quiz”

Module 3 · Memory: OOM, Swap, and Page Cache

13:00 – 21:00 · “free is very small” does not mean insufficient memory; the real signals are available, paging, PSI, and OOM logs
8 minutescgroup v2 · PSIsystemd-oomd depends on the installation★★★★★
Learning Objectives
  • Understand the columns in free, explain why the page cache “uses” memory without being a problem, and understand the meaning of available.
  • 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’s OOMScoreAdjust=) to protect critical processes.
  • Distinguish system-wide OOM from cgroup OOM (MemoryMax=/memory.max), and use memory.events, memory.pressure, and PSI for diagnosis.
Prerequisites: The concepts of processes and virtual memory from Lesson 1, and systemd units from Lesson 2. Importance:★★★★★

What: The Several “Ledgers” of Linux Memory

CategoryWhat it isCan it be reclaimedWhere to view it
Anonymous pages (anon)Process heaps, stacks, and memory obtained through mallocCan only be swapped out to swap; cannot be reclaimed without swapAnonPages in /proc/meminfo; RssAnon in the process RSS
Page cacheCache of file contents (read files, executable files, logs)Clean pages can be discarded directly; dirty pages (Dirty) must first be written back to diskbuff/cache in free; Cached, Dirty
Shared memory / tmpfs (Shmem)/dev/shm, /run, and tmpfs filesCan only be swapped out to swapshared in free; df -h -t tmpfs
Kernel slabdentry/inode caches, network buffers, and moreThe SReclaimable portion can be reclaimedslabtop, /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

  1. Background reclamation: when free pages fall below the low watermark, kswapd wakes up and reclaims page cache and anonymous pages (according to vm.swappiness, 60 by default).
  2. Direct reclamation: below the min watermark, the process requesting memory reclaims memory itself—which directly slows the application and increases PSI memory.
  3. 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 adds oom_score_adj (−1000 to 1000) and kills the process with the highest score. oom_score_adj = -1000 means it will never be selected.
  4. cgroup OOM: when a service has MemoryMax= set (memory.max in cgroup v2), once the limit is exceeded, reclamation and process killing occur only within that cgroup. The log records Memory cgroup out of memory, the oom_kill count in memory.events increases by one, and systemd records the service result as oom-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_memoryBehaviorApplicable To
0 (default)Heuristic: only allocations that are clearly impossible to satisfy are rejected; insufficient memory during actual use → OOMGeneral-purpose
1Always allowSome scientific computing applications; officially recommended for Redis (to avoid fork snapshot failures)
2Strict: 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

  1. free -m: What proportion is available? Is swap used increasing?
  2. vmstat 1: si/so continuously nonzero → swapping is in progress (a true pressure signal).
  3. cat /proc/pressure/memory: some avg10 > 10 warrants attention.
  4. journalctl -k | grep -i -E "out of memory|oom": Has anyone already been killed?
  5. 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 OOMcgroup OOM(MemoryMax)MemoryHigh Throttlingsystemd-oomd
TriggerGlobal memory exhausted and reclaim failedcgroup usage reached memory.maxExceeded memory.highPSI pressure / swap exceeded threshold
ActionKill the process with the highest global oom_scoreSelect a process to kill only within this cgroupForce reclaim + slow down processesKill the entire cgroup (unit)
LogsOut of memory: Killed processMemory cgroup out of memory: Killed processNo kill; the high count in memory.eventssystemd-oomd journal messages
Common misconceptions① “buff/cache is too large, so run 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

Sufficient free memoryUse the surplus for the page cachePSI = 0 Below the low watermarkBackground reclamation by kswapdDiscard clean page cache first Below the min watermarkDirect reclamation · swap out anonymous pagesvmstat so>0 · PSI↑ ThrashingHigh refault · si/soLoad spikes and the system stalls OOM killerSelect the process with the highest oom_scoreSIGKILL systemd-oomd (if enabled) kills the entire cgroup early at this stage based on PSI / swap usageGoal: make decisions before kernel OOM and before the system freezes
Figure 3-1 Reclamation → paging → thrashing → OOM; PSI provides a signal before OOM

Figure 3-2: cgroup v2 memory control files (using myapp.service as an example)

/sys/fs/cgroup/system.slice/myapp.service/ memory.min / lowMemoryMin= / MemoryLow=Protection: disturb as little as possible during reclamation memory.highMemoryHigh=Soft limit: reclamation + throttlingDo not kill processes memory.maxMemoryMax=Hard limit: cgroup OOMmemory.swap.max ← MemorySwapMax= Observationmemory.current (current)memory.peak (peak)memory.events: high/max/oom_killmemory.pressure(PSI)memory.stat(anon/file…)
Figure 3-2 systemd resource properties correspond one-to-one with cgroup v2 files (systemd.resource-control(5))

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).

myapp(gunicorn)redis-serverLeaking process python3Page cacheFree
Start after selecting the configuration.
$ free -m

Core commands and parameters

CommandFunctionDescription
free -m / free -h -wMemory overviewCheck available; -w separates buffers and cache
grep -E 'MemAvailable|Dirty|Writeback|AnonPages|Shmem|SReclaimable|Commit' /proc/meminfoDetailed accountingPersistently high Dirty indicates that writeback cannot keep up
vmstat 1si/so swapping in/outOnly persistent nonzero values are a problem; occasional small values are normal
ps -eo pid,user,rss,vsz,comm --sort=-rss | headSort by RSSRSS is in KiB; a large VSZ does not mean it is actually being used
pidstat -r 1View RSS and page faults by processHigh majflt/s (page faults requiring disk reads) = thrashing
sudo cat /proc/PID/smaps_rollupRSS/PSS/Swap summaryPSS apportions usage according to the sharing ratio
cat /proc/PID/oom_score /proc/PID/oom_score_adjOOM score-1000 is never selected; 1000 is selected first
systemctl show myapp -p MemoryCurrent -p MemoryMax -p MemoryHigh -p OOMScoreAdjustService memory propertiesA 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/swappinessSwap configurationMultipass 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)

Inject the leak and observe RSS and cgroup usage in real time:
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.

Collect evidence from three sources: the kernel, systemd, and PSI.
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
Use PID to observe the leak rate:
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.

Observe the effect of oom_score_adj:
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.

Cleanup:
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.

Command-Line Operations
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:'
Scenario Analysis
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

▶
LISA19 - Linux Systems Performance — USENIX
Brendan Gregg · English · The memory section explains page cache, paging, and observation tools

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

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% in the “Quiz”in the “Quiz”

Module 4 · Disk I/O: iostat, iotop, and File System Issues

21:00 – 28:00 · A slow disk, a full disk, a disk that has run out of inodes, and a disk where space does not return even though files have clearly been deleted are four completely different failures
7 minutessysstat 12.7.7 · iotop-c 1.31★★★★★
Learning Objectives
  • 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-c and pidstat -d to find processes generating I/O; use PSI io to determine whether I/O is actually causing tasks to stall.
  • Distinguish between block exhaustion (df -h at 100%), inode exhaustion (df -i at 100%), and deleted but still-open files (a mismatch between df and du), and repair them safely.
Prerequisites: Lesson 2’s disks, partitions, LVM, mounts, and fstab. Importance:★★★★★ (a full disk is one of the most common production incidents)

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

ColumnMeaningHow to Interpret It
r/s w/sRead/write requests completed per second (IOPS)Compare with the disk specifications (cloud disk IOPS limit)
rkB/s wkB/sThroughputCompare with the bandwidth limit
rareq-sz wareq-szAverage request size (KB)More small I/O operations (4K) → IOPS reaches its limit first
r_await w_awaitAverage request latency (ms), including queueing timeNormally < 1–2ms for SSDs; a few ms for cloud disks; tens or hundreds of ms indicates saturation or a fault
aqu-szAverage 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
%utilProportion 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 exhaustedInodes exhaustedDeleted but still open
SymptomWrites report No space left on deviceAlso reports No space left on device, but df -h still shows available spacedf shows full, while the total from du is far less than the used space
Root causeLarge files, logs, backupsHuge 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
Diagnosisdf -h, du -xh -d1, ncdudf -i; count files by directorylsof +L1, ls -l /proc/*/fd | grep deleted
FixDelete/compress/expand capacityDelete 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

  1. Error No space left on device → check both df -h and df -i; if neither is full → it may be a quota or tmpfs size issue.
  2. Large discrepancy between df and du → lsof +L1; if the discrepancy still cannot be explained → files may be “covered” by a mount point (data written before the mount).
  3. “Slow” → iostat -xz 1: high await + high aqu-sz → saturation; high await but very low IOPS → device/cloud-disk failure or throttling; then use iotop-c -o / pidstat -d 1 to find the process, and use biolatency-bpfcc (M7) to view the latency distribution.
  4. I/O error / filesystem read-only appears in the kernel log → a hardware or underlying storage problem; prioritize protecting the data.

Tool comparison

iostat -xiotop-cpidstat -dPSI iobiolatency-bpfcc
GranularityDeviceProcess/thread (real-time sorting)Process (rolling)System / cgroupDevice latency histogram
Dependenciessysstatiotop-c; some columns require kernel.task_delayacct=1sysstatBuilt into the kernelbpfcc-tools, root
Common misconceptions① “%util at 100% means the disk is saturated” — see the table above. ② “Deleting a large file will free the space” — not as long as a process still has it open. ③ “A full inode table can be expanded with tune2fs” — not on ext4; you can only clean up or rebuild the filesystem. ④ “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

Application: write() / read() / fsync() VFS → ext4 / XFS (inodes, directory entries, journal) Page cache (dirty pages → kernel writeback threads) Block layer blk-mq: merging, scheduling (mq-deadline / none) Driver (virtio-blk / nvme) → disk / cloud disk strace -T (system call latency) · pidstat -d · iotop-c df -h / df -i · lsof +L1 · opensnoop-bpfcc free cache · /proc/meminfo Dirty/Writeback iostat -x(await, aqu-sz, %util)· biolatency dmesg: I/O error · smartctl · cloud disk monitoring Reads that hit the page cache do not reach the block layer: iostat cannot see them, but strace can see the system calls
Figure 4-1 Each layer has corresponding observation tools; troubleshoot from top to bottom

Figure 4-2: Why df and du do not match

Directory tree (du traverses here) /mnt/faultdisk/app.log 12Khuge.log ← already rm'd, directory entry gone du total: 12K inode 1234 (80 MiB data blocks) link count nlink = 0Open count>0 → not released df used: 80 MiB + 12K Process fault-holder /proc/PID/fd/3 →/mnt/faultdisk/huge.log (deleted) lsof +L1 lists files with NLINK=0
Figure 4-2 rm only removes the directory entry; the kernel reclaims the inode and data blocks only after the last file descriptor is closed

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.

df -h (blocks)
df -i(inode)
du -sh (directory tree)
Empty filesystem. Click the button above to operate.
$ df -h /mnt/faultdisk

Core Commands and Options

CommandFunctionDescription
iostat -xz 1Device-level extended statistics-m MB; -p sda includes partitions; -d shows devices only
sudo iotop-c -o -PShow only processes with I/O-b -n 3 batch mode; the SWAPIN/IO% columns require sudo sysctl kernel.task_delayacct=1
pidstat -d 1Process read/write rates and iodelayiodelay is the number of clock ticks spent waiting for block I/O
df -hT / df -iBlock / inode usage-x tmpfs -x squashfs filters out noise
sudo du -xh -d1 / | sort -hCalculate size by directory-x does not cross file systems
sudo du -x --inodes -d1 /var | sort -nCalculate 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 +L1Deleted but still-open filesThe 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 metadataFor XFS, use xfs_info
journalctl --disk-usage / --vacuum-size=200MLog usage and cleanupFor persistent settings, write SystemMaxUse= in journald.conf
cat /proc/pressure/ioI/O pressureA 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)

Block exhaustion:
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.

Inode exhaustion:
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.

Deleted but still open:
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)
Comparison of the two release methods: truncate first (the process keeps running), then stop the process:
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=$?"
(Optional) I/O saturation: 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.
Cleanup:
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).

Command-Line Operations
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
Scenario Analysis
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

▶
Linux Performance Tools, Brendan Gregg, part 1 of 2 — Brendan Gregg
English · Includes explanations of iostat, iotop, and disk observation tools (recorded in 2015; iostat column names are based on sysstat 12)

Video specifically covering inode exhaustion / deleted-open files: No verified video found; please use the storyboard script below.

Official Documentation

Video Storyboard Script (approximately 80 seconds)

This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–80s
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.
or achieve ≥ 70% in the “Quiz”ore of ≥ 70% in the “Quiz”

Module 5 · Network Troubleshooting: tcpdump, ss, and DNS

28:00 – 35:00 · Break “network unreachable/very slow” down into: name resolution → connection establishment → transfer → application, with evidence for each stage
7 minutesiproute2 6.19 · tcpdump 4.99.6 · systemd-resolved★★★★★
Learning Objectives
  • Use curl -w to 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 use ss -ti and nstat to observe RTT, retransmissions, and queue overflows.
  • Write commonly used tcpdump filters 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 netem to reproduce packet loss and latency.
Prerequisites: The ip and ss commands, routing, and DNS fundamentals from Lesson 2. Importance:★★★★★

What: The Four Stages of a Request

  1. Name resolution: The application reads /etc/hosts through glibc (NSS), then queries the servers in /etc/resolv.conf. On Ubuntu, /etc/resolv.conf is a symbolic link to /run/systemd/resolve/stub-resolv.conf; the server is the local stub 127.0.0.53, which is forwarded by systemd-resolved to the upstream DNS configured for each network interface (link).
  2. 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 the listen() backlog and net.core.somaxconn.
  3. 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.”
  4. 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

StageEvidenceCommand
DNSResolution time, which server, whether it timed outresolvectl status, resolvectl query, dig, curl -w '%{time_namelookup}', gethostlatency-bpfcc
Connection establishmentWhether the SYN received a response, RSTs, accept queue overflowsss -ltn(Recv-Q / Send-Q), nstat -az TcpExtListenOverflows, tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-rst) != 0'
TransmissionRTT, retransmissions, congestion windowss -tin(rtt, retrans, cwnd), sar -n ETCP 1, nstat TcpRetransSegs, tcpretrans-bpfcc
LinkNIC errors, drops, qdiscip -s link, tc -s qdisc, ethtool -S
PathRouting, MTUip route get, tracepath, ping -M do -s 1472
Kernel tablesConntrack usage and dropssysctl 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

  1. curl -sS -o /dev/null -w 'dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' URL
  2. DNS stage is slow → use resolvectl status to check the upstream server, then test directly with dig @upstream-IP.
  3. TCP stage is slow or fails → use ss and tcpdump to check whether the SYN receives a response; on the server side, check the accept queue.
  4. Slow transfer → use ss -ti to check retrans and rtt; use sar -n ETCP 1 to check the global retransmission rate.
  5. 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

sstcpdumpnstat / sar -ntcpretrans-bpfcc
What it showsCurrent socket state (including kernel TCP information)Every packet on the wireProtocol countersEvery retransmission event (including the four-tuple)
OverheadVery lowModerate; add filters and -s truncation for high trafficVery lowLow
AlternativeOlder netstat (net-tools, no longer installed by default)Analyze pcap with Wireshark/tsharknetstat -s—
Common Misconceptions① “If ping works, the service is fine” — ICMP and TCP follow different rules, and ping does not test MTU or ports. ② “If DNS is slow, edit /etc/resolv.conf” — on Ubuntu, it is managed by systemd-resolved and will be overwritten; modify netplan or 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

Applicationgetaddrinfo() systemd-resolved127.0.0.53 stub TCP socketHandshake · retransmissions · queues netfilterRules · conntrack qdisctc(netem) NIC / linkMTU · errors curl -w · strace resolvectl · dig ss -ti · nstat nft list · conntrack -S tc -s qdisc ip -s link · tracepath tcpdump outbound capture pointAfter qdisc: cannot see packets dropped by netem tcpdump inbound capture pointBefore netfilter: can also see inbound packets that are DROPped
Figure 5-1 First use curl -w to determine which stage is slow, then use that stage’s tools to gather evidence

Figure 5-2: How Packet Loss Becomes Latency (RTO Exponential Backoff)

Clientmyapp :5000 ✗ Dropped by netem Wait for RTO ≈ 200ms+ (calculated based on RTT) ✗ Dropped again RTO doubles ≈ 400ms+ 3rd transmission succeeds → total latency ≈ 0.6s or more ss -ti will show retrans:0/2; nstat TcpRetransSegs increases
Figure 5-2 With 20% packet loss, about 1 in every 25 requests requires two consecutive retransmissions (0.2² = 4%)

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.

Select a failure.
$ curl -sS -o /dev/null -w '...' http://api.example.internal:5000/healthz

Core Commands and Parameters

CommandPurposeDescription
ss -ltnpListening 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 connectionsrtt, rto, cwnd, retrans, bytes_retrans
ss -sSocket summaryTIME-WAIT count, orphaned
nstat -az | grep -E 'Retrans|ListenOverflows|ListenDrops'Protocol countersWithout -a, displays the delta since the last invocation
sudo tcpdump -i any -nn -s 128 port 5000Packet capture-w f.pcap to save; -c 100 to limit the count; -nn to skip name and port resolution
resolvectl status / query / statisticsresolved status, resolution, and cache statisticsresolvectl flush-caches; revert IFACE
dig +tries=1 +time=2 @1.1.1.1 example.comTest by connecting directly to a DNS serverBypass local resolved
tracepath -n 1.1.1.1Path and PMTUDoes not require root
ping -M do -s 1472 -c 3 HOSTTest whether an MTU of 1500 works (1472 + 28-byte header)-M do prevents fragmentation
sudo conntrack -S / -CConnection tracking statistics / entry countRequires the conntrack package; watch for drop, insert_failed
tc -s qdisc show dev IFACEQueue rules and drop statisticsnetem 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)

Note A packet-loss fault will affect your SSH session; it is recommended that you work from the virtual machine console (or multipass shell). Automatically reverted after 15 minutes.
Record the baseline:
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 baseline
Inject slow DNS and observe:
sudo ~/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.

Reset DNS and inject 20% packet loss:
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.

Cross-validate with sar and bcc:
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
(Optional) MTU experiment: Demonstrate this on another network interface or loopback that does not affect SSH:
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 9
Cleanup:
sudo ~/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.

Command-Line Operations
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 )'
Scenario Analysis
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

▶
Tcpdump in Linux — Linux R
English · Demonstration of basic tcpdump usage (third-party small channel; filter syntax is governed by pcap-filter(7))
▶
LISA19 - Linux Systems Performance — USENIX
Brendan Gregg · English · Network observability tools and BPF network tracing

Special-topic videos on troubleshooting systemd-resolved / conntrack / MTU: no verified videos found; refer to the official documentation and the storyboard below.

Official Documentation

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–55s
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.
Shot 3 · 55–90s
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.
or score ≥ 70% in the “Quiz”in the “Quiz”

Module 6 · Boot Failures: GRUB, initramfs, and Rescue Mode

35:00 – 42:00 · When the machine won’t boot, first determine which link in the boot chain it’s stuck at, then choose the corresponding “entry point” for repair
7 minutesGRUB 2 · dracut 110 (26.04 default) · systemd 259Console and snapshots required★★★★☆
Learning objectives
  • 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’s rd.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.
Prerequisites: The systemd targets, fstab, and LVM from Lesson 2; the cloud serial console from Lessons 3 and 4. Importance:★★★★☆ (low probability of occurrence, but the greatest impact when it occurs)

What: Every Stage of the Boot Chain

StageWhat it doesTypical 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
GRUBReads /boot/grub/grub.cfg, loads the kernel vmlinuz and initrd.img, and passes the kernel command lineAfter error: unknown filesystem., enters grub rescue>; error: file '/boot/vmlinuz-…' not found.
KernelInitializes hardware, decompresses initramfs into memory, and runs its initKernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) (usually because there is no initramfs)
initramfsLoads 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 dependenciesTimed out waiting for device … → Dependency failed for Local File Systems. → emergency mode
ServicesStarts 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 pointHow to enterWhat you getSuitable for
rescue.targetPress e in GRUB, add systemd.unit=rescue.target to the end of the linux line, and press Ctrl+X to bootSingle-user root-user root shell; local file systems are mounted, while services such as networking have not startedService-caused hangs; repairs that require the complete file system
emergency.targetAdd systemd.unit=emergency.target; entered automatically when fstab failsOnly the root file system (read-only); almost nothing has startedfstab errors; other file systems cannot be mounted
dracut rd.breakAdd rd.breakAn initramfs shell before switch_root; the actual root is at /sysrootProblems with the root file system itself
init=/bin/bashAdd init=/bin/bashThe kernel runs bash directly instead of systemd, with the root file system read-onlyThe last resort when root is locked and sulogin cannot be entered
Live ISO / rescue VM + chrootBoot from installation media, or attach the system disk to another VM in the cloudA complete tool environmentGRUB/initramfs corruption; situations requiring grub-install
Ubuntu's root account lock issueUbuntu locks the root password by default. The rescue/emergency targets use 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

>
  1. Stops at grub rescue> or grub> → GRUB cannot find its configuration/modules (partition changes, /boot corruption).
  2. Kernel panic … unable to mount root fs → initramfs is missing or corrupted.
  3. dracut emergency shell / (initramfs) → the root device cannot be found (UUID changed, missing driver, LVM not activated).
  4. You are in emergency mode. → systemd stage, usually an fstab issue.
  5. Login prompt is visible but SSH is unreachable → network/sshd/firewall (Lessons 2 and 6).

Comparison: Local VMs and Cloud

Multipass / Hyper-V / VirtualBoxAzure VMAWS EC2
View boot outputHyper-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 repairRevert to a snapshot, mount the virtual diskRepair the VM (az vm repair) by attaching the system disk to a rescue VMStop the instance and attach the root volume to a rescue instance
Common misconceptions① “Just edit fstab directly in emergency mode” — the root filesystem is read-only; first run 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

UEFIshim → GRUB GRUBgrub.cfg · kernel parameters KernelUnpack initramfs initramfsdracut · find root=UUID systemdfstab → .mount multi-usersshd · myapp grub rescue>Live ISO + chrootgrub-install Kernel panicSelect an older kernelRebuild initramfs dracut shellrd.break · /sysrootrdsosreport.txt emergencyremount,rw · edit fstabrescue.target The GRUB menu (invoked by Shift / Esc) is the “master switch” for entering the various downstream entry points: append rd.break / systemd.unit=… / init=/bin/bash to the linux line
Figure 6-1 Each stage has its own failure modes and recovery entry points

Figure 6-2: How One Incorrect fstab Line Sends the System into Emergency Mode

/etc/fstab: UUID=dead…/data ext4 defaults 0 2 fstab-generatordata.mount (Requires device) Wait for device for 90 secondsTimed out waiting… Without nofail: local-fs.target failsOnFailure=emergency.target With nofail: only data.mount failsSystem continues booting; repair via SSH
Figure 6-2 Always addnofailandx-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.

Select a failure.
[ 0.000000] Linux version 7.0.0-42-generic ...

Core Commands and Parameters

CommandFunctionDescription
sudo findmnt --verify --verboseCheck fstab syntax, whether devices exist, and filesystem typesRequired after modifying fstab and before rebooting
sudo systemctl daemon-reload && sudo mount -aRegenerate mount units and attempt to mount everythingReboot only if no errors are reported
systemd-analyze blame / critical-chainBoot time analysisIdentify units that slow down boot
journalctl -b -1 -p errErrors from the previous bootPersistent logs are required (Ubuntu provides /var/log/journal by default)
journalctl --list-bootsBoot historyDetermine whether the system is repeatedly rebooting
cat /proc/cmdlineCurrent kernel parametersConfirm root= and console=
sudo update-initramfs -u -k allRebuild initramfsIn 26.04, this command is provided by dracut; in 24.04, it is provided by initramfs-tools
sudo lsinitrd | head(dracut)/ lsinitramfsView initramfs contentsConfirm that the driver, LVM, and crypt modules are included
sudo update-grub / grub-installRegenerate grub.cfg / reinstall the bootloaderConfiguration 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 bootSafe 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)

PrerequisiteA snapshot must already exist (Module 0, Step 5); the full version requires access to the VM console (Hyper-V / VirtualBox, or the console of the underlying platform used by Multipass). If you only have SSH access, do Part A.
A. Safe exercise without rebooting: Create a “data disk” using a loop device, write one correct and one incorrect fstab entry, and use findmnt to detect the error:
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=$?"
Observe how systemd handles the bad entry (without rebooting; trigger it manually):
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.

B. (When a console is available) Actually reboot once:
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.

Repair it in the emergency shell:
mount -o remount,rw /
sed -i '/0000dead-beef/s/^/# /' /etc/fstab
systemctl daemon-reload
mount -a && systemctl default
Review: inspect errors from the previous boot:
journalctl --list-boots | tail -n 3
journalctl -b -1 -p err --no-pager | head -n 20
systemd-analyze critical-chain | head
Cleanup (regardless of whether Part B was completed):
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.

Command-Line Exercises
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
Scenario Analysis Exercise
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

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–50s
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.
Shot 3 · 50–80s
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.
Shot 4 · 80–100s
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.
or score ≥ 70% in the “Quiz”in the “Quiz”

Module 7 · Advanced Tools: strace, perf, and eBPF (bpftrace)

42:00 – 50:00 · After the 60-second checklist tells you “which resource,” use these tools to answer “which code path, which system call, and why”
8 minutesstrace 6.19 · linux-perf 7.0 · bpftrace 0.25.0 · bcc 0.35.0Root required★★★★☆
Learning objectives
  • 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 of ltrace.
  • Use perf top, perf record -g, and perf report for 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 -bpfcc suffix on Ubuntu.
Prerequisites: Resource analysis from M1–M5; the concept of system calls from Lesson 1. Importance: ★★★★☆

What: Four types of in-depth tools

ToolPrincipleQuestions answeredOverhead
straceptrace(2): The target process is paused on entry to and exit from each system call; strace reads the arguments and return valueWhich 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)
ltraceSet breakpoints at the PLT entries of dynamic library functionsWhich 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
perfKernel perf_events: Record call stacks by sampling at a given frequency (e.g., 99 Hz); can also count hardware/software events and trace tracepointsWhich 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 spaceAlmost any question: latency distributions, off-CPU waits, who opened a file, who was OOM-killed, every retransmissionLow (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 perf or PYTHONPERFSUPPORT=1 to let perf see Python function names.

eBPF program lifecycle

  1. bpftrace compiles scripts into BPF bytecode (bcc uses Clang/LLVM to compile C snippets; libbpf-tools uses precompiled CO-RE programs).
  2. 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.
  3. JIT-compiled into native machine code and attached to a specified event (such as tracepoint:syscalls:sys_enter_openat).
  4. When the event is triggered, the program runs in the kernel and writes the results to a BPF map (hash table, histogram, ring buffer).
  5. 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

SymptomPreferredAlternative
The program reports an error, but the logs are unclear (file not found, permissions)strace -f -e trace=%fileopensnoop-bpfcc
High CPU usage in user spaceperf record -g + flame graphprofile-bpfcc
The service is slow but CPU usage is not high (waiting)offcputime-bpfccstrace -T to see which call is taking time
Disk latency distributionbiolatency-bpfcc / biolatency.btiostat -x
Scheduling latencyrunqlat-bpfccPSI cpu
Short-lived processes consuming CPUexecsnoop-bpfccpidstat
Which process was killed by OOMoomkill-bpfcc / oomkill.btjournalctl -k
TCP retransmissionstcpretrans-bpfccss -ti, nstat
Slow DNS resolutiongethostlatency-bpfcccurl -w
Common Misconceptions① “strace can be attached freely in production”—it significantly slows down the target process; in production, limit the -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

Userspace: myapp (gunicorn / Python) · libc · libpython uprobe / USDT PLT breakpoint (ltrace) perf sampling (user stack) System call boundary ← strace (ptrace stops the process each time) · tracepoint:syscalls:* Kernel kprobeAny kernel function tracepointStable static points perf_eventsTimed sampling / PMU Scheduler / Block / TCPEvents eBPF runtime bpftrace / bcc compilation↓ bpf(BPF_PROG_LOAD)Verifier → JITAttach to any event on the leftWrite to a BPF map in the kernel(counts / histograms / ringbuf)Read and print in user spaceRequires BTF · requires root
Figure 7-1 strace operates at the system call boundary and has high overhead; eBPF can attach to nearly any event and aggregate data within the kernel

Figure 7-2: From Sampling to a Flame Graph

perf record -F 99 -gRecord call stacks 99 times per second→ perf.data perf scriptExport samples and stacks individually(symbolization) stackcollapse-perf.pla;b;c 123 (folded count) flamegraph.pl→ Interactive SVGWidth = sample proportion 99 Hz rather than 100 Hz: avoids bias caused by synchronizing with periodic timer tasks (lockstep sampling)
Figure 7-2 FlameGraph toolchain (Brendan Gregg’s FlameGraph repository)

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.

Samples 0
Select the workload, then start sampling.
$ sudo perf record -F 99 -g -p $(pgrep -d, -f gunicorn) -- sleep 5

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)

CommandPurposeExample
execsnoop-bpfccTrace every exec (new process)Find scripts being repeatedly launched by cron
opensnoop-bpfccTrace open calls and failures-x show failures only; -p PID
biolatency-bpfccBlock I/O latency histogram-D 10 1 by device, 10 seconds
runqlat-bpfccRun-queue (scheduler) latency histogram10 1
offcputime-bpfccOff-CPU time and stacks-p PID -f 10 outputs folded format for drawing an off-CPU flame graph
profile-bpfccCPU sampling profiling-F 99 -f 10
tcpretrans-bpfccEvery TCP retransmissionUsed with the M5 packet-loss experiment
oomkill-bpfccOOM kill eventsUsed with the M3 leak experiment
gethostlatency-bpfccLatency of getaddrinfo and other resolution callsUsed 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)

Use strace to find the real cause of myapp startup failure:
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.

Short-lived processes: execsnoop (run the loop in another terminal):
( 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
Real-time OOM capture: run 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 9330
CPU flame graph: generate myapp-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.
Scheduling latency: Compare under CPU failure:
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
Cleanup:
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.

Command-Line Operations
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(); }'
Scenario Analysis
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

▶
USENIX ATC '17: Visualizing Performance with Flame Graphs — USENIX
Brendan Gregg · English · Principles, generation, and interpretation of flame graphs (updated version)
▶
LISA13 - Blazing Performance with Flame Graphs — USENIX
Brendan Gregg · English · The first flame graph presentation (longer and earlier; optional)
▶
Getting Started with BPF observability – Brendan Gregg, Netflix — eBPF & Cilium Community
English · Introduction to bpftrace and bcc tools
▶
LISA21 - BPF Internals — USENIX
Brendan Gregg · English · Internal mechanisms of the BPF verifier, JIT, maps, and more (advanced)

Official Documentation

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.

or score ≥ 70% in the “Quiz”in the “Quiz”

Module 8 · Integrated Troubleshooting Challenge

50:00 – 60:00 · You won’t know which fault was injected. Use the symptoms and the 60-second checklist to identify the cause, choose a mitigation, and present the supporting evidence within five minutes.
10 minutesblindbox.sh · 10 failure types★★★★★
Learning Objectives
  • 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).
Prerequisites: Modules 1–7. Importance:★★★★★ (ties together all the preceding knowledge)

What: Unknown-Fault Challenge Rules

  • sudo ~/linuxlab/faults/blindbox.sh randomly 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-*', or status.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 ImpressionMost LikelyDecisive EvidenceStop the Bleeding
System-wide slowdown, load ≈ above nproc, high usCPU saturation (cpu)vmstat r > nproc; pidstat points to a processStop or limit the process (systemctl set-property … CPUQuota=)
Slowdown, high load but substantial CPU idle time, high waI/O saturation (iohog)vmstat b high; iostat await/aqu-sz high; iotop-c; PSI ioLimit I/O (IOWeight=/IOWriteBandwidthMax=) or stop it
A service repeatedly restarts, with intermittent logsMemory leak / cgroup OOM (memleak)Memory cgroup out of memory in journalctl -k; Failed with result 'oom-kill'; NRestartsRoll back/restart and set MemoryMax; preserve the evidence
Write failure, No space left on deviceBlock 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 muchDeleted but still open (deleted-open)lsof +L1Restart the process holding it or truncate its fd
External calls are consistently slow by several seconds or fail to resolve; local /healthz is normalDNS(dns)namelookup is slow in curl -w; upstream is abnormal in resolvectl statusRestore the DNS configuration (resolvectl revert)
External access is intermittently fast and slow; SSH is sluggishPacket loss (netloss)sar -n ETCP retrans/s; tc -s qdisc; ss -ti retransRemove the incorrect qdisc / repair the link
myapp is completely unavailable, Couldn't connectService 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)
Common misconceptions① “Finding an anomaly means you’ve found the root cause” — in the unknown-fault challenge, a CPU fault can also make myapp a little slower, but with a DNS fault the CPU is normal; use a second, independent piece of evidence to confirm. ② “Mitigation = fix” — stopping the fault unit is mitigation; the root cause is “why was someone running stress-ng in production?” in the retrospective. ③ “Diagnosis complete means you’re done” — you must verify recovery (run the checklist again and confirm that user-side metrics have recovered).

Figure 8-1: Symptoms → Resources → Evidence Map

SymptomResource / layerDecisive evidence Everything slows down The service repeatedly restarts Write failure ENOSPC External calls are slow / fail The service is completely unavailable CPU · disk I/O Memory (cgroup) Blocks · inodes · deleted-open DNS · packet loss systemd unit · port vmstat r/b · iostat await journalctl -k OOM · NRestarts df -h · df -i · lsof +L1 curl -w · resolvectl · retrans systemctl status · ss -ltnp Memory pressure can also cause “everything to slow down”
Figure 8-1 The same symptom may point to multiple resources (dashed lines), so a second independent piece of evidence is required

Figure 8-2: 5-Minute Diagnostic Rhythm

0:00–0:30Quantify the symptom with curl -w 0:30–1:3060-second checklist + df -i + PSI 1:30–3:00Hypothesis → second piece of evidence 3:00–4:00Containment + verify recovery 4:00–5:00Write the retrospective key points
Figure 8-2 Timeboxing prevents getting stuck with a single tool

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.

Diagnostic time 0:00 / 5:00
No box has been opened yet.
labadmin@linuxlab:~$

Unknown-Fault Challenge Tools and Evidence Collection

CommandPurpose
sudo ~/linuxlab/faults/blindbox.shAfter resetting, randomly inject one fault
sudo ~/linuxlab/faults/blindbox.sh --revealView the answer after submitting a diagnosis
~/linuxlab/sixty.sh | tee evidence.txt60-second checklist (Module 1)
sudo ~/linuxlab/faults/reset.shReset 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)

Preparation: Two terminals (one VM console and one SSH session, to avoid losing access during a network fault), a timer, and ~/linuxlab/incident-log.md open.
Round 1:
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
Mitigate and verify: Execute the mitigation action you selected (rather than reset.sh), then run first-minute.sh again to confirm recovery, and finally run sudo ~/linuxlab/faults/reset.sh.
Rounds 2 and 3: Repeat the process; blindbox.sh resets everything first each time. You may draw the same fault again—that is also how the real world works.
(Advanced) Dual faults: Have a partner manually execute two injections, for example:
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.

Write the postmortem: Using the template on the “Principles” page, write up one of the rounds as a postmortem and save it as ~/linuxlab/postmortem-round1.md.
Cleanup:
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.

Command-Line Operations
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"
Scenario Analysis
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

▶
LISA19 - Linux Systems Performance — USENIX
Brendan Gregg · English · Reviews the analysis methods for all the resources in this lesson from a comprehensive perspective; suitable for review before the unknown-fault challenge
▶
Linux Performance Tools, Brendan Gregg, part 2 of 2 — Brendan Gregg
English · Includes discussion of methodology and tool selection

Themed video “Practicing fault injection / chaos experiments on a single Linux machine”: No verified video found.

References

Video Storyboard (approximately 90 seconds)

This courseware cannot directly generate video/MP3 files; a storyboard and narration script are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–60s
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.
Shot 3 · 60–90s
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.
or score ≥ 70% in the “Quiz”in the “Quiz”

Command Cheat Sheet

Common commands for troubleshooting and performance analysis, a quick troubleshooting table, and recommended configuration snippets
Ubuntu 26.04 LTSPrintable

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 show

Boot 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-bpfcc

Quick Troubleshooting Table

Symptom / ErrorFirst CommandCommon Root CauseModule
High load, high r, high uspidstat 1CPU-intensive process, infinite loopM2
High load, high b, high waiostat -xz 1Disk saturation, NFS stuckM2 / M4
Service is slow even though the overall machine CPU is not highcat …/cpu.statCPUQuota throttling, waiting for locks/networkM2 / M7
Killed process / oom-killjournalctl -k -bLeak, MemoryMax too smallM3
SSH hangs and then recovers, no OOMcat /proc/pressure/memoryThrashingM3
No space left on devicedf -h; df -iBlocks full / inodes full / tmpfs fullM4
df full, du lowlsof +L1Deleted but still open, mount point shadowingM4
Could not resolve host / consistently slow for 5 secondsresolvectl statusUpstream DNS unreachableM5
Alternating between fast and slow, retransmissionssar -n ETCP 1Packet loss, qdisc, linkM5
table full, dropping packetconntrack -Sconntrack_max too smallM5
You are in emergency modejournalctl -xb -p errfstab errorM6
grub rescue>ls, set prefixPartition changes, /boot corruptedM6
Service Failed with result 'resources'systemctl cat SVCMissing EnvironmentFile, etc.M8
Connection in use: ('0.0.0.0', 5000)ss -ltnp 'sport = :5000'Port already in useM8

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

Scenario: “myapp slowed down Monday morning” — two overlapping failures, with complete diagnosis, containment, hardening, and retrospective
Approx. 30 minuteslinuxlab
Scenario: Monday, 09:00. Customer service reports that some requests to myapp are very slow, and another user says, “Upload failed.” You, the on-call engineer, log in to linuxlab. Your teammate has already (secretly) injected two faults. Goal: Find the two root causes, mitigate them, harden the system, and write a postmortem within 15 minutes.
Faults Injected by Your Teammate (do not look at the screen):
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
Quantify symptoms:
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
60-second checklist; record the abnormal fields:
~/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.

Verify hypothesis 1 (I/O saturation):
sudo iotop-c -o -b -n 3 | head -n 15
pidstat -d 1 3
sudo biolatency-bpfcc 5 1
Verify hypothesis 2 (space):
df -h /mnt/faultdisk; sudo du -sh /mnt/faultdisk
sudo lsof -nP +L1
Stop the bleeding (only for the processes found; do not use reset.sh):
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.

Hardening: add 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.
Review and cleanup: write ~/linuxlab/postmortem-final.md using the M8 template, then run sudo ~/linuxlab/faults/reset.sh.
Acceptance checklist

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.

Course catalog

Sources and Version Notes

Verify the date: 2026-11-17
Refer to official materials

Sources and Verification Conclusions

TopicVerification conclusionSources (accessed 2026-11-17)
Current Ubuntu LTSUbuntu 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 defaultUbuntu 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.20packages.ubuntu.com/resolute
perf packageIn 26.04, /usr/bin/perf is provided by linux-perf (7.0.0-42.42); 24.04 uses 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
initramfsIn 26.04, update-initramfs is provided by both dracut and initramfs-tools; lsinitrd is in dracut-core, and lsinitramfs is in initramfs-tools-corepackages.ubuntu.com file contents search
tc netem modulesch_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 columnsprocps-ng 4.0.4 NEWS: “vmstat: Print guest time in non-wide mode”procps NEWS
60-second checklist10 commands and their orderNetflix TechBlog (2015)
USE method, load averageUSE definitions and Linux checklist; Linux load includes D stateUSE Method; Linux Load Averages
PSI, cgroup v2, overcommitsome/full semantics; memory.max/high/events; overcommit modesPSI; cgroup v2; overcommit
systemd resource control and rescue targetMemoryMax/High, OOMScoreAdjust, OOMPolicy; rescue/emergency; nofail, device-timeoutsystemd.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 IDTitleChannelUsed for
fhBHvsi0Ql0LISA19 - Linux Systems PerformanceUSENIXM1, M2, M3, M5, M8
FJW8nGV4jxYLinux Performance Tools, Brendan Gregg, part 1 of 2Brendan GreggM1, M4
zrr2nUln9KkLinux Performance Tools, Brendan Gregg, part 2 of 2Brendan GreggM1, M8
0LWgrHYsVhsDemystifying Linux CPU Load AveragesBeginLinux GuruM2
XE2hdDspyPALinux Load Average Explained: Troubleshooting a Slow Server with uptime and topOpsAccel ConsultingM2
DQvvEPLToQcTcpdump in LinuxLinux RM5
D53T1Ejig1QUSENIX ATC '17: Visualizing Performance with Flame GraphsUSENIXM7
nZfNehCzGdwLISA13 - Blazing Performance with Flame GraphsUSENIXM7
bGAVrtb_tFsGetting Started with BPF observability – Brendan Gregg, NetflixeBPF & Cilium CommunityM7
_5Z2AU7QTH4LISA21 - BPF InternalsUSENIXM7

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_score varies with the kernel version; the example values are provided only for comparing relative magnitudes.
  • The specific default value of Ubuntu’s kernel.perf_event_paranoid and 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_FORCE is 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 transfer should be determined using multipass 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 the myapp-port fault will differ.

Course catalog