blob: 093d07c5f245a38e8b639b5e5fb4d1efe892db4f [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Brendan Greggf4bf2752016-07-21 18:13:24 -07002# @lint-avoid-python-3-compatibility-imports
3#
4# profile Profile CPU usage by sampling stack traces at a timed interval.
5# For Linux, uses BCC, BPF, perf_events. Embedded C.
6#
7# This is an efficient profiler, as stack traces are frequency counted in
8# kernel context, rather than passing every stack to user space for frequency
9# counting there. Only the unique stacks and counts are passed to user space
10# at the end of the profile, greatly reducing the kernel<->user transfer.
11#
Brendan Gregg81baae42019-01-26 21:53:11 -080012# By default CPU idle stacks are excluded by simply excluding PID 0.
13#
Brendan Gregg715f7e62016-10-20 22:50:08 -070014# REQUIRES: Linux 4.9+ (BPF_PROG_TYPE_PERF_EVENT support). Under tools/old is
15# a version of this tool that may work on Linux 4.6 - 4.8.
Brendan Greggf4bf2752016-07-21 18:13:24 -070016#
17# Copyright 2016 Netflix, Inc.
18# Licensed under the Apache License, Version 2.0 (the "License")
19#
Brendan Gregg715f7e62016-10-20 22:50:08 -070020# THANKS: Alexei Starovoitov, who added proper BPF profiling support to Linux;
21# Sasha Goldshtein, Andrew Birchall, and Evgeny Vereshchagin, who wrote much
22# of the code here, borrowed from tracepoint.py and offcputime.py; and
23# Teng Qin, who added perf support in bcc.
Brendan Greggf4bf2752016-07-21 18:13:24 -070024#
25# 15-Jul-2016 Brendan Gregg Created this.
Brendan Gregg715f7e62016-10-20 22:50:08 -070026# 20-Oct-2016 " " Switched to use the new 4.9 support.
Alban Crequy32ab8582020-03-22 16:06:44 +010027# 26-Jan-2019 " " Changed to exclude CPU idle by default.
Brendan Greggf4bf2752016-07-21 18:13:24 -070028
29from __future__ import print_function
Brendan Gregg715f7e62016-10-20 22:50:08 -070030from bcc import BPF, PerfType, PerfSWConfig
Alban Crequy32ab8582020-03-22 16:06:44 +010031from bcc.containers import filter_by_containers
Brendan Greggf4bf2752016-07-21 18:13:24 -070032from sys import stderr
33from time import sleep
34import argparse
35import signal
36import os
37import errno
Brendan Greggf4bf2752016-07-21 18:13:24 -070038
39#
40# Process Arguments
41#
42
43# arg validation
44def positive_int(val):
45 try:
46 ival = int(val)
47 except ValueError:
48 raise argparse.ArgumentTypeError("must be an integer")
49
50 if ival < 0:
51 raise argparse.ArgumentTypeError("must be positive")
52 return ival
53
54def positive_nonzero_int(val):
55 ival = positive_int(val)
56 if ival == 0:
57 raise argparse.ArgumentTypeError("must be nonzero")
58 return ival
59
Teng Qine4db7682018-04-24 16:24:20 -070060def stack_id_err(stack_id):
Michael Prokopc14d02a2020-01-09 02:29:18 +010061 # -EFAULT in get_stackid normally means the stack-trace is not available,
Teng Qine4db7682018-04-24 16:24:20 -070062 # Such as getting kernel stack trace in userspace code
63 return (stack_id < 0) and (stack_id != -errno.EFAULT)
64
Brendan Greggf4bf2752016-07-21 18:13:24 -070065# arguments
66examples = """examples:
67 ./profile # profile stack traces at 49 Hertz until Ctrl-C
68 ./profile -F 99 # profile stack traces at 99 Hertz
Teng Qin86df2b82018-04-23 12:36:51 -070069 ./profile -c 1000000 # profile stack traces every 1 in a million events
Brendan Greggf4bf2752016-07-21 18:13:24 -070070 ./profile 5 # profile at 49 Hertz for 5 seconds only
71 ./profile -f 5 # output in folded format for flame graphs
Xiaozhou Liu6b197902019-04-16 05:41:18 +080072 ./profile -p 185 # only profile process with PID 185
73 ./profile -L 185 # only profile thread with TID 185
Brendan Greggf4bf2752016-07-21 18:13:24 -070074 ./profile -U # only show user space stacks (no kernel)
75 ./profile -K # only show kernel space stacks (no user)
Alban Crequy32ab8582020-03-22 16:06:44 +010076 ./profile --cgroupmap mappath # only trace cgroups in this BPF map
77 ./profile --mntnsmap mappath # only trace mount namespaces in the map
Brendan Greggf4bf2752016-07-21 18:13:24 -070078"""
79parser = argparse.ArgumentParser(
80 description="Profile CPU stack traces at a timed interval",
81 formatter_class=argparse.RawDescriptionHelpFormatter,
82 epilog=examples)
83thread_group = parser.add_mutually_exclusive_group()
84thread_group.add_argument("-p", "--pid", type=positive_int,
Xiaozhou Liu6b197902019-04-16 05:41:18 +080085 help="profile process with this PID only")
86thread_group.add_argument("-L", "--tid", type=positive_int,
87 help="profile thread with this TID only")
Brendan Greggf4bf2752016-07-21 18:13:24 -070088# TODO: add options for user/kernel threads only
89stack_group = parser.add_mutually_exclusive_group()
90stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
91 help="show stacks from user space only (no kernel space stacks)")
92stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
93 help="show stacks from kernel space only (no user space stacks)")
Teng Qin86df2b82018-04-23 12:36:51 -070094sample_group = parser.add_mutually_exclusive_group()
95sample_group.add_argument("-F", "--frequency", type=positive_int,
96 help="sample frequency, Hertz")
97sample_group.add_argument("-c", "--count", type=positive_int,
98 help="sample period, number of events")
Brendan Greggf4bf2752016-07-21 18:13:24 -070099parser.add_argument("-d", "--delimited", action="store_true",
100 help="insert delimiter between kernel/user stacks")
101parser.add_argument("-a", "--annotations", action="store_true",
102 help="add _[k] annotations to kernel frames")
Brendan Gregg81baae42019-01-26 21:53:11 -0800103parser.add_argument("-I", "--include-idle", action="store_true",
104 help="include CPU idle stacks")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700105parser.add_argument("-f", "--folded", action="store_true",
106 help="output folded format, one line per stack (for flame graphs)")
Tommaso Sardelliaa4aa522018-04-30 22:35:29 +0200107parser.add_argument("--stack-storage-size", default=16384,
Brendan Greggf4bf2752016-07-21 18:13:24 -0700108 type=positive_nonzero_int,
109 help="the number of unique stack traces that can be stored and "
Tommaso Sardelli718c9282018-04-30 15:36:40 +0200110 "displayed (default %(default)s)")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700111parser.add_argument("duration", nargs="?", default=99999999,
112 type=positive_nonzero_int,
113 help="duration of trace, in seconds")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700114parser.add_argument("-C", "--cpu", type=int, default=-1,
115 help="cpu number to run profile on")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100116parser.add_argument("--ebpf", action="store_true",
117 help=argparse.SUPPRESS)
Alban Crequyf82ea452020-03-18 16:15:02 +0100118parser.add_argument("--cgroupmap",
119 help="trace cgroups in this BPF map only")
Alban Crequy32ab8582020-03-22 16:06:44 +0100120parser.add_argument("--mntnsmap",
121 help="trace mount namespaces in this BPF map only")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700122
123# option logic
124args = parser.parse_args()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700125pid = int(args.pid) if args.pid is not None else -1
126duration = int(args.duration)
127debug = 0
128need_delimiter = args.delimited and not (args.kernel_stacks_only or
129 args.user_stacks_only)
130# TODO: add stack depth, and interval
131
132#
133# Setup BPF
134#
135
136# define BPF program
137bpf_text = """
138#include <uapi/linux/ptrace.h>
Brendan Gregg715f7e62016-10-20 22:50:08 -0700139#include <uapi/linux/bpf_perf_event.h>
Brendan Greggf4bf2752016-07-21 18:13:24 -0700140#include <linux/sched.h>
141
142struct key_t {
143 u32 pid;
144 u64 kernel_ip;
145 u64 kernel_ret_ip;
146 int user_stack_id;
147 int kernel_stack_id;
148 char name[TASK_COMM_LEN];
149};
150BPF_HASH(counts, struct key_t);
Song Liu67ae6052018-02-01 14:59:24 -0800151BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700152
153// This code gets a bit complex. Probably not suitable for casual hacking.
154
Brendan Gregg715f7e62016-10-20 22:50:08 -0700155int do_perf_event(struct bpf_perf_event_data *ctx) {
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800156 u64 id = bpf_get_current_pid_tgid();
157 u32 tgid = id >> 32;
158 u32 pid = id;
159
Brendan Gregg81baae42019-01-26 21:53:11 -0800160 if (IDLE_FILTER)
161 return 0;
162
Brendan Greggf4bf2752016-07-21 18:13:24 -0700163 if (!(THREAD_FILTER))
164 return 0;
165
Alban Crequy32ab8582020-03-22 16:06:44 +0100166 if (container_should_be_filtered()) {
Alban Crequyf82ea452020-03-18 16:15:02 +0100167 return 0;
168 }
Alban Crequyf82ea452020-03-18 16:15:02 +0100169
Brendan Greggf4bf2752016-07-21 18:13:24 -0700170 // create map key
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800171 struct key_t key = {.pid = tgid};
Brendan Greggf4bf2752016-07-21 18:13:24 -0700172 bpf_get_current_comm(&key.name, sizeof(key.name));
173
174 // get stacks
175 key.user_stack_id = USER_STACK_GET;
176 key.kernel_stack_id = KERNEL_STACK_GET;
177
178 if (key.kernel_stack_id >= 0) {
179 // populate extras to fix the kernel stack
Paul Chaignon37f7fef2018-06-14 02:14:59 +0200180 u64 ip = PT_REGS_IP(&ctx->regs);
Yonghong Songb5fcb512018-04-14 22:55:11 -0700181 u64 page_offset;
Brendan Greggac297c12016-10-18 20:17:04 -0700182
Brendan Greggf4bf2752016-07-21 18:13:24 -0700183 // if ip isn't sane, leave key ips as zero for later checking
Yonghong Songb5fcb512018-04-14 22:55:11 -0700184#if defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE)
185 // x64, 4.16, ..., 4.11, etc., but some earlier kernel didn't have it
186 page_offset = __PAGE_OFFSET_BASE;
187#elif defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE_L4)
188 // x64, 4.17, and later
189#if defined(CONFIG_DYNAMIC_MEMORY_LAYOUT) && defined(CONFIG_X86_5LEVEL)
190 page_offset = __PAGE_OFFSET_BASE_L5;
Brendan Greggac297c12016-10-18 20:17:04 -0700191#else
Yonghong Songb5fcb512018-04-14 22:55:11 -0700192 page_offset = __PAGE_OFFSET_BASE_L4;
Brendan Greggac297c12016-10-18 20:17:04 -0700193#endif
Yonghong Songb5fcb512018-04-14 22:55:11 -0700194#else
195 // earlier x86_64 kernels, e.g., 4.6, comes here
196 // arm64, s390, powerpc, x86_32
197 page_offset = PAGE_OFFSET;
198#endif
199
200 if (ip > page_offset) {
Brendan Greggf4bf2752016-07-21 18:13:24 -0700201 key.kernel_ip = ip;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700202 }
203 }
204
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200205 counts.increment(key);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700206 return 0;
207}
208"""
209
Brendan Gregg81baae42019-01-26 21:53:11 -0800210# set idle filter
211idle_filter = "pid == 0"
212if args.include_idle:
213 idle_filter = "0"
214bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
215
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800216# set process/thread filter
Brendan Greggf4bf2752016-07-21 18:13:24 -0700217thread_context = ""
Brendan Greggf4bf2752016-07-21 18:13:24 -0700218if args.pid is not None:
219 thread_context = "PID %s" % args.pid
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800220 thread_filter = 'tgid == %s' % args.pid
221elif args.tid is not None:
222 thread_context = "TID %s" % args.tid
223 thread_filter = 'pid == %s' % args.tid
Brendan Greggf4bf2752016-07-21 18:13:24 -0700224else:
225 thread_context = "all threads"
226 thread_filter = '1'
227bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
228
229# set stack storage size
230bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
231
232# handle stack args
Teng Qine4db7682018-04-24 16:24:20 -0700233kernel_stack_get = "stack_traces.get_stackid(&ctx->regs, 0)"
234user_stack_get = "stack_traces.get_stackid(&ctx->regs, BPF_F_USER_STACK)"
Brendan Greggf4bf2752016-07-21 18:13:24 -0700235stack_context = ""
236if args.user_stacks_only:
237 stack_context = "user"
238 kernel_stack_get = "-1"
239elif args.kernel_stacks_only:
240 stack_context = "kernel"
241 user_stack_get = "-1"
242else:
243 stack_context = "user + kernel"
244bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
245bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Alban Crequy32ab8582020-03-22 16:06:44 +0100246bpf_text = filter_by_containers(args) + bpf_text
Brendan Greggf4bf2752016-07-21 18:13:24 -0700247
Teng Qin86df2b82018-04-23 12:36:51 -0700248sample_freq = 0
249sample_period = 0
250if args.frequency:
251 sample_freq = args.frequency
252elif args.count:
253 sample_period = args.count
254else:
255 # If user didn't specify anything, use default 49Hz sampling
256 sample_freq = 49
257sample_context = "%s%d %s" % (("", sample_freq, "Hertz") if sample_freq
258 else ("every ", sample_period, "events"))
259
Brendan Greggf4bf2752016-07-21 18:13:24 -0700260# header
261if not args.folded:
Teng Qin86df2b82018-04-23 12:36:51 -0700262 print("Sampling at %s of %s by %s stack" %
263 (sample_context, thread_context, stack_context), end="")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700264 if args.cpu >= 0:
265 print(" on CPU#{}".format(args.cpu), end="")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700266 if duration < 99999999:
267 print(" for %d secs." % duration)
268 else:
269 print("... Hit Ctrl-C to end.")
270
Nathan Scottcf0792f2018-02-02 16:56:50 +1100271if debug or args.ebpf:
Brendan Greggf4bf2752016-07-21 18:13:24 -0700272 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100273 if args.ebpf:
274 exit()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700275
Brendan Gregg715f7e62016-10-20 22:50:08 -0700276# initialize BPF & perf_events
277b = BPF(text=bpf_text)
278b.attach_perf_event(ev_type=PerfType.SOFTWARE,
279 ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event",
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700280 sample_period=sample_period, sample_freq=sample_freq, cpu=args.cpu)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700281
282# signal handler
283def signal_ignore(signal, frame):
284 print()
285
286#
Brendan Greggf4bf2752016-07-21 18:13:24 -0700287# Output Report
288#
289
290# collect samples
291try:
292 sleep(duration)
293except KeyboardInterrupt:
294 # as cleanup can take some time, trap Ctrl-C:
295 signal.signal(signal.SIGINT, signal_ignore)
296
297if not args.folded:
298 print()
299
300def aksym(addr):
301 if args.annotations:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200302 return b.ksym(addr) + "_[k]".encode()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700303 else:
304 return b.ksym(addr)
305
306# output stacks
307missing_stacks = 0
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000308has_collision = False
Brendan Greggf4bf2752016-07-21 18:13:24 -0700309counts = b.get_table("counts")
310stack_traces = b.get_table("stack_traces")
311for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qine4db7682018-04-24 16:24:20 -0700312 # handle get_stackid errors
313 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Brendan Greggf4bf2752016-07-21 18:13:24 -0700314 missing_stacks += 1
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000315 # hash collision (-EEXIST) suggests that the map size may be too small
316 has_collision = has_collision or k.kernel_stack_id == -errno.EEXIST
Teng Qine4db7682018-04-24 16:24:20 -0700317 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
318 missing_stacks += 1
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000319 has_collision = has_collision or k.user_stack_id == -errno.EEXIST
Brendan Greggf4bf2752016-07-21 18:13:24 -0700320
321 user_stack = [] if k.user_stack_id < 0 else \
322 stack_traces.walk(k.user_stack_id)
323 kernel_tmp = [] if k.kernel_stack_id < 0 else \
324 stack_traces.walk(k.kernel_stack_id)
325
326 # fix kernel stack
327 kernel_stack = []
328 if k.kernel_stack_id >= 0:
Brendan Gregg715f7e62016-10-20 22:50:08 -0700329 for addr in kernel_tmp:
330 kernel_stack.append(addr)
331 # the later IP checking
Brendan Greggf4bf2752016-07-21 18:13:24 -0700332 if k.kernel_ip:
333 kernel_stack.insert(0, k.kernel_ip)
334
Brendan Greggf4bf2752016-07-21 18:13:24 -0700335 if args.folded:
336 # print folded stack output
337 user_stack = list(user_stack)
338 kernel_stack = list(kernel_stack)
Jürgen Hötzeleba14832018-06-25 18:35:46 +0200339 line = [k.name]
Teng Qine4db7682018-04-24 16:24:20 -0700340 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
341 # hash collision (-EEXIST), we still print a placeholder for consistency
342 if not args.kernel_stacks_only:
343 if stack_id_err(k.user_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800344 line.append(b"[Missed User Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700345 else:
346 line.extend([b.sym(addr, k.pid) for addr in reversed(user_stack)])
347 if not args.user_stacks_only:
Gil Raphaelli29aa6192020-02-19 11:09:52 -0500348 line.extend([b"-"] if (need_delimiter and k.kernel_stack_id >= 0 and k.user_stack_id >= 0) else [])
Teng Qine4db7682018-04-24 16:24:20 -0700349 if stack_id_err(k.kernel_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800350 line.append(b"[Missed Kernel Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700351 else:
Brendan Gregg7324ba52019-01-22 15:47:08 -0800352 line.extend([aksym(addr) for addr in reversed(kernel_stack)])
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200353 print("%s %d" % (b";".join(line).decode('utf-8', 'replace'), v.value))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700354 else:
Teng Qine4db7682018-04-24 16:24:20 -0700355 # print default multi-line stack output
356 if not args.user_stacks_only:
357 if stack_id_err(k.kernel_stack_id):
358 print(" [Missed Kernel Stack]")
359 else:
360 for addr in kernel_stack:
361 print(" %s" % aksym(addr))
362 if not args.kernel_stacks_only:
363 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
364 print(" --")
365 if stack_id_err(k.user_stack_id):
366 print(" [Missed User Stack]")
367 else:
368 for addr in user_stack:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200369 print(" %s" % b.sym(addr, k.pid).decode('utf-8', 'replace'))
370 print(" %-16s %s (%d)" % ("-", k.name.decode('utf-8', 'replace'), k.pid))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700371 print(" %d\n" % v.value)
372
373# check missing
374if missing_stacks > 0:
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000375 enomem_str = "" if not has_collision else \
Brendan Greggf4bf2752016-07-21 18:13:24 -0700376 " Consider increasing --stack-storage-size."
377 print("WARNING: %d stack traces could not be displayed.%s" %
378 (missing_stacks, enomem_str),
379 file=stderr)