Skip to content
masdzub.com
~/articles/linux — one from the notebook

Tracing High CPU Usage on Linux with perf, top, and eBPF

A practical workflow for finding what burns CPU on Linux: read top correctly, sample stacks with perf, and use eBPF to catch runqueue and off-CPU delays.

masdzub@website:~$ cat ~/articles/tracing-high-cpu-usage-on-linux-with-perf-top-and-ebpf.aspx.md
# 1 file · 16 min read · topic: linux · status: published

Introduction

The fastest path from “CPU is at 100%” to “this function is burning the cycles” is a three-stage triage, and each stage answers a narrower question than the one before it. top and pidstat tell you whether the load is user time, system time, I/O wait, or steal, and which process and thread own it. perf samples stacks and attributes cycles to symbols inside a process or across the host. eBPF tools pick up the cases that perf cannot see: threads that are not running because they are waiting on the scheduler, a lock, or a disk, yet still keep the CPU busy in aggregate. Do them in that order. Running perf record -F 99 -g -p PID first on a box that is actually idle and simply waiting on disk produces a flat profile and wasted time.

This article is a working manual for that sequence. It assumes a modern systemd host, a kernel between 5.10 and 6.x, and root or sudo access. Commands are shown for Debian and Ubuntu naming, with Fedora and RHEL differences called out where the package or binary name changes.

Reading top without guessing

top prints a CPU summary line with eight fields: us, sy, ni, id, wa, hi, si, st. Each one means something different and the fix depends on which one is high. If us is close to 100, the workload is in user space and you should reach for perf. If sy is high, the time is inside the kernel, and the likely suspects are a syscall-heavy workload, a network softirq storm, or a misbehaving driver. If wa is high, the CPU is not the problem at all; the box is waiting on I/O and the real tool is iostat or biolatency, not a profiler. If st is high, the hypervisor is stealing time and no amount of application tuning helps. You need a bigger instance or a quieter neighbor.

A few defaults will mislead you. Press 1 inside top to expand the per-core view. A single-core spike on a 64-core machine can push the aggregate us to a harmless-looking 5 percent while one NUMA node saturates. Press H to switch from process view to thread view, because the process that owns the CPU almost never is the one at the top; one of its worker threads is. Also remember that %CPU in top is per core. A JVM showing 740% is not a bug. It is using roughly seven and a half cores.

For scripted triage, pidstat from the sysstat package gives cleaner output than scraping top:

Terminal window
pidstat -u 1 5
pidstat -t -u 1 5 -p 1234

The first shows per-process CPU over five one-second samples. The second breaks it down by thread ID, which is the number you need to hand to perf or bpftrace. The TID shown in the TID column is what you want, not the PID.

For a fast sort, ps is enough:

Terminal window
ps -eo pid,tid,pcpu,pmem,comm --sort=-pcpu | head -20

Get the TID of the hottest thread, then move to the next stage.

First triage with top and pidstat

Once you know the hot thread, decide whether the default perf view will help. There are two cases that look identical in top and diverge the moment you sample.

The first case is a hot us thread. A request handler, a JSON serialiser, a regex engine, or a busy loop is executing instructions. perf top -p TID will show you the function at the top within seconds.

The second case is a high-thread-count service that is doing very little work per thread. top shows aggregate load, but pidstat -t shows that no single thread exceeds 15 percent. The box is oversubscribed, not bottlenecked on one function. Sampling will show a lot of context switches and short stacks. The real instrument is runqlat and offcputime from the eBPF section, not perf top.

This distinction saves the most time in practice. A thread at 95 percent CPU and IPC near 1 is arithmetic-bound. A thread at 20 percent CPU with an IPC of 0.1 is stalled on memory, and a flame graph will show a wide bar against __memcpy_avx_unaligned or a mutex_lock that is not really the point. perf stat will confirm which it is:

Terminal window
sudo perf stat -p 1234 -e cycles,instructions,cache-misses,branch-misses,context-switches -- sleep 5

Read IPC as instructions per cycle (instructions / cycles). A value above 1.0 means the core is retiring work steadily. A value around 0.2 with a flat profile means the core stalls, and the next question is where. On cloud VMs without a passed-through PMU, hardware counters like cycles report <not supported>; fall back to software events (task-clock, context-switches, page-faults) in that case.

Sampling with perf: from perf top to a flame graph

perf ships as linux-tools-$(uname -r) on Ubuntu, linux-perf on Debian, and perf on Fedora. Verify it matches the running kernel before trusting any symbol:

Terminal window
perf --version
uname -r

On Ubuntu the userspace perf tool ships separately from the kernel and a version mismatch can produce perf: failed to parse event or missing symbols. Install the matching package:

Terminal window
sudo apt install linux-tools-$(uname -r) linux-tools-common

Two sysctls gate access. perf_event_paranoid controls sampling, and kptr_restrict controls whether kernel pointers and symbols appear:

Terminal window
cat /proc/sys/kernel/perf_event_paranoid
cat /proc/sys/kernel/kptr_restrict

As root you usually do not need to touch either: CAP_PERFMON (or CAP_SYS_ADMIN) passes the checks, and RHEL 9 ships perf_event_paranoid=2 with profiling working fine for root. The paranoid knob matters for non-root users: at 1 they lose CPU-event access without CAP_PERFMON, and at 2 they lose kernel profiling too.

If kernel symbols come back as addresses in perf report, lower kptr_restrict:

Terminal window
sudo sysctl -w kernel.kptr_restrict=0

Persist changes in /etc/sysctl.d/99-perf.conf if this is a dedicated diagnostic host, and do not loosen them on a shared box unless you control who logs in.

The interactive view is the first thing to run:

Terminal window
sudo perf top -g -p 1234

-g enables call graph collection. -p limits to one process. Within a couple of seconds you will see a column of symbols sorted by overhead. If the top symbol is _raw_spin_lock or native_queued_spin_lock_slowpath, you have lock contention and you should read offcputime next, because the interesting part is the stack of callers, not the spinlock itself. If the top symbol is do_syscall_64 with a wide bar under sendto, the problem is syscall pressure, and syscount or bpftrace will be more useful than more sampling.

For a shareable artefact, record to disk:

Terminal window
sudo timeout -s INT 30 perf record -F 99 -g -p 1234 -o /tmp/perf.data
sudo perf report -i /tmp/perf.data --stdio

-F 99 samples at 99 Hz, which is low enough to stay out of the way and high enough to catch most hot paths. Avoid -F 1000 on a production host; it perturbs the very thing you are trying to measure. -g uses frame pointers by default. Whether a binary keeps them depends on how it was compiled, and plenty of distro packages omit them, so if the call graph appears flat with perf: ... [unknown] entries, switch to DWARF:

Terminal window
sudo timeout -s INT 30 perf record -F 99 --call-graph dwarf -p 1234 -o /tmp/perf.data

DWARF unwinding is expensive. On a hot box it can consume several percent of CPU itself. If you cannot afford that, use --call-graph lbr on Intel platforms that expose Last Branch Record registers (Haswell and newer); it is cheap but captures only a shallow chain: LBR holds roughly 8 to 32 branches depending on the model, so deep stacks get truncated.

To turn perf.data into a flame graph, use Brendan Gregg’s scripts:

Terminal window
sudo perf script -i /tmp/perf.data > /tmp/out.perf
git clone --depth 1 https://github.com/brendangregg/FlameGraph /tmp/FlameGraph
/tmp/FlameGraph/stackcollapse-perf.pl /tmp/out.perf > /tmp/out.folded
/tmp/FlameGraph/flamegraph.pl /tmp/out.folded > /tmp/flame.svg

On RHEL and Fedora, flamegraph.pl fails with Can't locate open.pm in @INC until perl-open is installed (dnf install -y perl-open).

Read the flame graph from the bottom up. The width at any level is the share of samples in that frame. A single wide plateau in a leaf function is your candidate. A wide frame that splits into many thin children is likely a framework overhead, not a single hot function.

Going deeper with eBPF: off-CPU, runqueue, and syscalls

perf answers the on-CPU question. eBPF answers the off-CPU question, and on many real incidents the CPU load is a symptom of threads waking and sleeping faster than the scheduler likes.

BCC’s BTF/CO-RE mode needs a kernel built with CONFIG_DEBUG_INFO_BTF=y and the matching BTF at /sys/kernel/btf/vmlinux; tracepoint args access in bpftrace also depends on BTF. Most modern distro kernels (5.10+) ship it. Check:

Terminal window
uname -r
ls /sys/kernel/btf/vmlinux

If that file exists, modern bcc and bpftrace will work without per-kernel compilation. Install on Ubuntu:

Terminal window
sudo apt install bpfcc-tools linux-headers-$(uname -r)

On Fedora and RHEL 8+:

Terminal window
sudo dnf install bcc-tools bpftrace

On Debian the bcc binaries carry a -bpfcc suffix (runqlat-bpfcc). On Fedora they live under /usr/share/bcc/tools/. The upstream names are the same: runqlat, offcputime, profile, syscount, execsnoop.

Runqueue latency is the first stop when top shows high sy and a pile of threads:

Terminal window
sudo runqlat-bpfcc 5 1

The histogram shows how long threads waited to be scheduled after becoming runnable. Latency above a few hundred microseconds in the p99 is a sign the box is oversubscribed. If the p99 sits in the millisecond range and the machine has 8 cores, you are seeing the scheduler queue, and the fix is fewer threads, a higher CPU request, or a cgroup fix.

Off-CPU profiling is how you find lock contention and I/O:

Terminal window
sudo offcputime-bpfcc -p 1234 10

The output aggregates stacks by the time they spent sleeping. A wide frame under futex_wait_queue_me from application code points at a lock. A wide frame under io_schedule or blk_mq_* points at disk. A wide frame under epoll_wait is normal for an idle event loop and means the CPU sample you took earlier was noise.

For a userspace stack similar to perf record, profile from bcc works without frame pointers for many toolchains:

Terminal window
sudo profile-bpfcc -F 99 -p 1234 30

One-off queries are easier with bpftrace:

Terminal window
sudo bpftrace -e 'profile:hz:99 /pid == 1234/ { @[ustack] = count(); }'

This prints a userspace stack histogram for one process at 99 Hz, with no files to move around. To see where threads block, trace the scheduler:

Terminal window
sudo bpftrace -e 'tracepoint:sched:sched_switch /args.prev_pid == 1234/ { @[kstack] = count(); }'

The tracepoint arguments live under args. in bpftrace 0.12 and later; a bare prev_pid fails to parse. The output shows the kernel paths that were on the stack when that thread last left the CPU, which is what it was doing right before it blocked. If kstack is truncated, add -v to see the full stack. If the stack contains only __schedule because the kernel was built with stack depth limits, fall back to offcputime.

A useful composite during an incident is the state of every CPU over the sampling window:

Terminal window
mpstat -P ALL 1

High %sys on a single core with the rest idle points to a hardirq or a pinned ksoftirqd. That is a network or storage driver problem, and bpftrace with tracepoint:irq:softirq_entry will show which vector is firing.

Putting it together: a triage playbook

A concrete example makes the sequence easier to remember. Assume an alert fires on a 16-core VM running a Java order service. top shows us at 65 and sy at 30, with one process at 520 percent.

Open top, press 1, and confirm the load is spread across cores rather than pinned to one. If it is pinned to one, the process is single-threaded on a critical path; if it is spread, it is a pool. Press H and note the hottest TIDs.

Run pidstat -t -u 1 5 -p PID and group the threads by name. In a Java process, the GC threads, the HTTP worker pool, and the JIT compiler all show up. If GC Thread#0 is the hot one, the profiler question is about allocation and pause, and perf record will show G1ParScanThreadState or ParallelScanTask at the top. That is a heap-sizing conversation, not a code change.

If the hot threads are HTTP workers, take a perf sample for 30 seconds against the process. Look for a single wide leaf in perf report. Common outcomes on Java servers are String.split or Pattern.matcher in a hot serialiser, GZIPOutputStream.write in a compression path, and sun.nio.ch.EPollArrayWrapper doing the actual read loop. Each one points at a different owner of the fix.

If the sample is flat or [unknown], the JVM has stripped frame pointers and symbols. Install the -XX:+PreserveFramePointer flag or run perf record with --call-graph dwarf against a debug build. For long-lived production JVMs, async-profiler is the better instrument because it understands the JVM’s own safepoints; perf is the fallback for native calls and the kernel side.

If the sample is dominated by do_syscall_64 and tcp_sendmsg, stop profiling and look at the network path. ss -s and nstat will tell you whether the box is retransmitting, and syscount-bpfcc -p PID -d 10 will show which syscalls dominate over ten seconds. A service that spends 30 percent of user time in sys is usually doing small buffered writes, and switching to BufferedOutputStream or a batched write changes the profile shape.

Only after those two stages, when the box is still loaded but perf cannot attribute it, reach for runqlat and offcputime. At that point the machinery is right, and the answer will be something like a cgroup CPU quota that throttles at 100ms boundaries, visible with cpu.stat in the cgroup directory:

Terminal window
cat /sys/fs/cgroup/system.slice/orders.service/cpu.stat

A large nr_throttled count with a rising throttled_usec means the workload hits a quota ceiling every period. The thread pool is not broken; the cgroup is. This is one of the most common causes of “high CPU with low throughput” and perf never sees it, because the throttle happens above the process.

Troubleshooting common errors

These are messages that show up on real hosts and what they usually mean.

perf record: failed to mmap with 1 (Operation not permitted) usually means the caller lacks the needed perf capability or the paranoid level blocks it for that user. As root on a normal RHEL/Fedora host with the default perf_event_paranoid=2 it still works; the common real cases are a non-root user without CAP_PERFMON, a container missing the capability, or lockdown=confidentiality. Check:

Terminal window
cat /proc/sys/kernel/perf_event_paranoid
cat /sys/kernel/security/lockdown 2>/dev/null
capsh --print | grep -i perf

If you are inside a container, the runtime must pass CAP_PERFMON (docker run --cap-add PERFMON on runtimes that accept the name) or CAP_SYS_ADMIN on older kernels, and the profile is visible on the host. Kubernetes pods need securityContext.capabilities.add: ["PERFMON"] plus hostPID: true for system-wide sampling.

perf report showing [unknown] for userspace symbols means the binary was stripped or the mapping file was not captured. Do not pass -o to a directory outside the working tree unless you also copy /proc/PID/maps forward. The reliable fix is to install the distribution’s debug symbols (linux-image-$(uname -r)-dbgsym from the Ubuntu ddeb repository, dnf debuginfo-install kernel on Fedora/RHEL) and re-record.

perf: interrupt took too long on the console is not an error from perf itself. It is a kernel NMI watchdog message reporting that the sampling interrupt could not be serviced in time, usually because the box is heavily oversubscribed or a driver is holding a spinlock too long. Reducing the sample rate to -F 49 clears it.

Failed to attach BPF program from bcc usually means the kernel predates the required BTF or the tool was built for a different kernel. Verify with bpftool feature probe and check ls /sys/kernel/btf/vmlinux. On CentOS 7 and RHEL 7, eBPF tooling is essentially unusable; use perf and top there and plan a kernel upgrade.

cannot open BPF map or bpf: map_create failed points at the memlock limit. Raise it for the shell you launch the tool from:

Terminal window
sudo prlimit --pid $$ --memlock=unlimited:unlimited
sudo bpftrace -e 'tracepoint:sched:sched_switch { @[comm] = count(); }'

Or set it permanently in /etc/security/limits.conf. On kernels before 5.11 BPF memory was charged against the RLIMIT_MEMLOCK soft limit, commonly 64 KiB, which is too small for even execsnoop; from 5.11 the accounting moved to memcg and this limit rarely bites.

Operation not permitted when running bpftrace as root on a secured host is often the kernel lockdown mode, where lockdown=confidentiality blocks all BPF tracing. Switch the boot parameter to lockdown=integrity or remove it, and reboot.

kernel.unprivileged_bpf_disabled=1 is a different gate: it stops non-root users from loading BPF programs at all, while root and holders of CAP_BPF keep working.

Limitations and trade-offs

Every tool in this flow has a cost, and being honest about them prevents bad advice.

perf sampling is cheap at 99 Hz and expensive at 1 kHz or with DWARF call graphs. On a CPU-bound host the profiler itself can push the alert over the threshold. Always sample for a bounded window and use timeout -s INT.

Frame pointers are not free either. Distributions that enable them by default pay a small register cost on every function call in exchange for accurate call graphs. When they are missing, most production perf sessions need DWARF or --call-graph lbr, and both have limits: DWARF unwinding is expensive and can miss inlined frames, and LBR holds only a handful of branches.

eBPF is powerful but not universal. Current bpftrace releases name kernel 5.15 as their practical minimum, older distro packages stretch further back but lack newer features, and RHEL 7’s 3.10-era kernel is out. Hardened kernels can also refuse BPF tracing outright: lockdown=confidentiality blocks it, and kernel.unprivileged_bpf_disabled=1 restricts it to root and CAP_BPF holders.

top and pidstat are safe but coarse. They tell you who is hot, not why. On containers the %CPU shown inside a pod reflects the whole host core, not the cgroup limit, so a 4-core quota pod can show 400% and still be throttled. Cross-check with cpu.stat.

Continuous profilers (Pyroscope, Parca, Grafana Alloy with eBPF) fill the gap between perf runs by keeping a low-frequency profile always on. They cost disk and CPU, and they still benefit from the same triage: a continuous profile from a starved cgroup will show the same flat stacks you would get from a one-off perf record. Start with top and pidstat, confirm the bottleneck is on-CPU, and only then sample. The profiler is the last mile, not the first.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.