blob: 2067933af374b2d77d31796cfb44ce3cf697122d [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.
Brendan Gregg81baae42019-01-26 21:53:11 -080027# 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
Brendan Greggf4bf2752016-07-21 18:13:24 -070031from sys import stderr
32from time import sleep
33import argparse
34import signal
35import os
36import errno
Brendan Greggf4bf2752016-07-21 18:13:24 -070037
38#
39# Process Arguments
40#
41
42# arg validation
43def positive_int(val):
44 try:
45 ival = int(val)
46 except ValueError:
47 raise argparse.ArgumentTypeError("must be an integer")
48
49 if ival < 0:
50 raise argparse.ArgumentTypeError("must be positive")
51 return ival
52
53def positive_nonzero_int(val):
54 ival = positive_int(val)
55 if ival == 0:
56 raise argparse.ArgumentTypeError("must be nonzero")
57 return ival
58
Teng Qine4db7682018-04-24 16:24:20 -070059def stack_id_err(stack_id):
Michael Prokopc14d02a2020-01-09 02:29:18 +010060 # -EFAULT in get_stackid normally means the stack-trace is not available,
Teng Qine4db7682018-04-24 16:24:20 -070061 # Such as getting kernel stack trace in userspace code
62 return (stack_id < 0) and (stack_id != -errno.EFAULT)
63
Brendan Greggf4bf2752016-07-21 18:13:24 -070064# arguments
65examples = """examples:
66 ./profile # profile stack traces at 49 Hertz until Ctrl-C
67 ./profile -F 99 # profile stack traces at 99 Hertz
Teng Qin86df2b82018-04-23 12:36:51 -070068 ./profile -c 1000000 # profile stack traces every 1 in a million events
Brendan Greggf4bf2752016-07-21 18:13:24 -070069 ./profile 5 # profile at 49 Hertz for 5 seconds only
70 ./profile -f 5 # output in folded format for flame graphs
Xiaozhou Liu6b197902019-04-16 05:41:18 +080071 ./profile -p 185 # only profile process with PID 185
72 ./profile -L 185 # only profile thread with TID 185
Brendan Greggf4bf2752016-07-21 18:13:24 -070073 ./profile -U # only show user space stacks (no kernel)
74 ./profile -K # only show kernel space stacks (no user)
Alban Crequyf82ea452020-03-18 16:15:02 +010075 ./profile --cgroupmap ./mappath # only trace cgroups in this BPF map
Brendan Greggf4bf2752016-07-21 18:13:24 -070076"""
77parser = argparse.ArgumentParser(
78 description="Profile CPU stack traces at a timed interval",
79 formatter_class=argparse.RawDescriptionHelpFormatter,
80 epilog=examples)
81thread_group = parser.add_mutually_exclusive_group()
82thread_group.add_argument("-p", "--pid", type=positive_int,
Xiaozhou Liu6b197902019-04-16 05:41:18 +080083 help="profile process with this PID only")
84thread_group.add_argument("-L", "--tid", type=positive_int,
85 help="profile thread with this TID only")
Brendan Greggf4bf2752016-07-21 18:13:24 -070086# TODO: add options for user/kernel threads only
87stack_group = parser.add_mutually_exclusive_group()
88stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
89 help="show stacks from user space only (no kernel space stacks)")
90stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
91 help="show stacks from kernel space only (no user space stacks)")
Teng Qin86df2b82018-04-23 12:36:51 -070092sample_group = parser.add_mutually_exclusive_group()
93sample_group.add_argument("-F", "--frequency", type=positive_int,
94 help="sample frequency, Hertz")
95sample_group.add_argument("-c", "--count", type=positive_int,
96 help="sample period, number of events")
Brendan Greggf4bf2752016-07-21 18:13:24 -070097parser.add_argument("-d", "--delimited", action="store_true",
98 help="insert delimiter between kernel/user stacks")
99parser.add_argument("-a", "--annotations", action="store_true",
100 help="add _[k] annotations to kernel frames")
Brendan Gregg81baae42019-01-26 21:53:11 -0800101parser.add_argument("-I", "--include-idle", action="store_true",
102 help="include CPU idle stacks")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700103parser.add_argument("-f", "--folded", action="store_true",
104 help="output folded format, one line per stack (for flame graphs)")
Tommaso Sardelliaa4aa522018-04-30 22:35:29 +0200105parser.add_argument("--stack-storage-size", default=16384,
Brendan Greggf4bf2752016-07-21 18:13:24 -0700106 type=positive_nonzero_int,
107 help="the number of unique stack traces that can be stored and "
Tommaso Sardelli718c9282018-04-30 15:36:40 +0200108 "displayed (default %(default)s)")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700109parser.add_argument("duration", nargs="?", default=99999999,
110 type=positive_nonzero_int,
111 help="duration of trace, in seconds")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700112parser.add_argument("-C", "--cpu", type=int, default=-1,
113 help="cpu number to run profile on")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100114parser.add_argument("--ebpf", action="store_true",
115 help=argparse.SUPPRESS)
Alban Crequyf82ea452020-03-18 16:15:02 +0100116parser.add_argument("--cgroupmap",
117 help="trace cgroups in this BPF map only")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700118
119# option logic
120args = parser.parse_args()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700121pid = int(args.pid) if args.pid is not None else -1
122duration = int(args.duration)
123debug = 0
124need_delimiter = args.delimited and not (args.kernel_stacks_only or
125 args.user_stacks_only)
126# TODO: add stack depth, and interval
127
128#
129# Setup BPF
130#
131
132# define BPF program
133bpf_text = """
134#include <uapi/linux/ptrace.h>
Brendan Gregg715f7e62016-10-20 22:50:08 -0700135#include <uapi/linux/bpf_perf_event.h>
Brendan Greggf4bf2752016-07-21 18:13:24 -0700136#include <linux/sched.h>
137
138struct key_t {
139 u32 pid;
140 u64 kernel_ip;
141 u64 kernel_ret_ip;
142 int user_stack_id;
143 int kernel_stack_id;
144 char name[TASK_COMM_LEN];
145};
146BPF_HASH(counts, struct key_t);
Song Liu67ae6052018-02-01 14:59:24 -0800147BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700148
Alban Crequyf82ea452020-03-18 16:15:02 +0100149#if CGROUPSET
150BPF_TABLE_PINNED("hash", u64, u64, cgroupset, 1024, "CGROUPPATH");
151#endif
152
Brendan Greggf4bf2752016-07-21 18:13:24 -0700153// 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 Crequyf82ea452020-03-18 16:15:02 +0100166#if CGROUPSET
167 u64 cgroupid = bpf_get_current_cgroup_id();
168 if (cgroupset.lookup(&cgroupid) == NULL) {
169 return 0;
170 }
171#endif
172
Brendan Greggf4bf2752016-07-21 18:13:24 -0700173 // create map key
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800174 struct key_t key = {.pid = tgid};
Brendan Greggf4bf2752016-07-21 18:13:24 -0700175 bpf_get_current_comm(&key.name, sizeof(key.name));
176
177 // get stacks
178 key.user_stack_id = USER_STACK_GET;
179 key.kernel_stack_id = KERNEL_STACK_GET;
180
181 if (key.kernel_stack_id >= 0) {
182 // populate extras to fix the kernel stack
Paul Chaignon37f7fef2018-06-14 02:14:59 +0200183 u64 ip = PT_REGS_IP(&ctx->regs);
Yonghong Songb5fcb512018-04-14 22:55:11 -0700184 u64 page_offset;
Brendan Greggac297c12016-10-18 20:17:04 -0700185
Brendan Greggf4bf2752016-07-21 18:13:24 -0700186 // if ip isn't sane, leave key ips as zero for later checking
Yonghong Songb5fcb512018-04-14 22:55:11 -0700187#if defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE)
188 // x64, 4.16, ..., 4.11, etc., but some earlier kernel didn't have it
189 page_offset = __PAGE_OFFSET_BASE;
190#elif defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE_L4)
191 // x64, 4.17, and later
192#if defined(CONFIG_DYNAMIC_MEMORY_LAYOUT) && defined(CONFIG_X86_5LEVEL)
193 page_offset = __PAGE_OFFSET_BASE_L5;
Brendan Greggac297c12016-10-18 20:17:04 -0700194#else
Yonghong Songb5fcb512018-04-14 22:55:11 -0700195 page_offset = __PAGE_OFFSET_BASE_L4;
Brendan Greggac297c12016-10-18 20:17:04 -0700196#endif
Yonghong Songb5fcb512018-04-14 22:55:11 -0700197#else
198 // earlier x86_64 kernels, e.g., 4.6, comes here
199 // arm64, s390, powerpc, x86_32
200 page_offset = PAGE_OFFSET;
201#endif
202
203 if (ip > page_offset) {
Brendan Greggf4bf2752016-07-21 18:13:24 -0700204 key.kernel_ip = ip;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700205 }
206 }
207
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200208 counts.increment(key);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700209 return 0;
210}
211"""
212
Brendan Gregg81baae42019-01-26 21:53:11 -0800213# set idle filter
214idle_filter = "pid == 0"
215if args.include_idle:
216 idle_filter = "0"
217bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
218
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800219# set process/thread filter
Brendan Greggf4bf2752016-07-21 18:13:24 -0700220thread_context = ""
Brendan Greggf4bf2752016-07-21 18:13:24 -0700221if args.pid is not None:
222 thread_context = "PID %s" % args.pid
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800223 thread_filter = 'tgid == %s' % args.pid
224elif args.tid is not None:
225 thread_context = "TID %s" % args.tid
226 thread_filter = 'pid == %s' % args.tid
Brendan Greggf4bf2752016-07-21 18:13:24 -0700227else:
228 thread_context = "all threads"
229 thread_filter = '1'
230bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
231
232# set stack storage size
233bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
234
235# handle stack args
Teng Qine4db7682018-04-24 16:24:20 -0700236kernel_stack_get = "stack_traces.get_stackid(&ctx->regs, 0)"
237user_stack_get = "stack_traces.get_stackid(&ctx->regs, BPF_F_USER_STACK)"
Brendan Greggf4bf2752016-07-21 18:13:24 -0700238stack_context = ""
239if args.user_stacks_only:
240 stack_context = "user"
241 kernel_stack_get = "-1"
242elif args.kernel_stacks_only:
243 stack_context = "kernel"
244 user_stack_get = "-1"
245else:
246 stack_context = "user + kernel"
247bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
248bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Alban Crequyf82ea452020-03-18 16:15:02 +0100249if args.cgroupmap:
250 bpf_text = bpf_text.replace('CGROUPSET', '1')
251 bpf_text = bpf_text.replace('CGROUPPATH', args.cgroupmap)
252else:
253 bpf_text = bpf_text.replace('CGROUPSET', '0')
Brendan Greggf4bf2752016-07-21 18:13:24 -0700254
Teng Qin86df2b82018-04-23 12:36:51 -0700255sample_freq = 0
256sample_period = 0
257if args.frequency:
258 sample_freq = args.frequency
259elif args.count:
260 sample_period = args.count
261else:
262 # If user didn't specify anything, use default 49Hz sampling
263 sample_freq = 49
264sample_context = "%s%d %s" % (("", sample_freq, "Hertz") if sample_freq
265 else ("every ", sample_period, "events"))
266
Brendan Greggf4bf2752016-07-21 18:13:24 -0700267# header
268if not args.folded:
Teng Qin86df2b82018-04-23 12:36:51 -0700269 print("Sampling at %s of %s by %s stack" %
270 (sample_context, thread_context, stack_context), end="")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700271 if args.cpu >= 0:
272 print(" on CPU#{}".format(args.cpu), end="")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700273 if duration < 99999999:
274 print(" for %d secs." % duration)
275 else:
276 print("... Hit Ctrl-C to end.")
277
Nathan Scottcf0792f2018-02-02 16:56:50 +1100278if debug or args.ebpf:
Brendan Greggf4bf2752016-07-21 18:13:24 -0700279 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100280 if args.ebpf:
281 exit()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700282
Brendan Gregg715f7e62016-10-20 22:50:08 -0700283# initialize BPF & perf_events
284b = BPF(text=bpf_text)
285b.attach_perf_event(ev_type=PerfType.SOFTWARE,
286 ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event",
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700287 sample_period=sample_period, sample_freq=sample_freq, cpu=args.cpu)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700288
289# signal handler
290def signal_ignore(signal, frame):
291 print()
292
293#
Brendan Greggf4bf2752016-07-21 18:13:24 -0700294# Output Report
295#
296
297# collect samples
298try:
299 sleep(duration)
300except KeyboardInterrupt:
301 # as cleanup can take some time, trap Ctrl-C:
302 signal.signal(signal.SIGINT, signal_ignore)
303
304if not args.folded:
305 print()
306
307def aksym(addr):
308 if args.annotations:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200309 return b.ksym(addr) + "_[k]".encode()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700310 else:
311 return b.ksym(addr)
312
313# output stacks
314missing_stacks = 0
315has_enomem = False
316counts = b.get_table("counts")
317stack_traces = b.get_table("stack_traces")
318for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qine4db7682018-04-24 16:24:20 -0700319 # handle get_stackid errors
320 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Brendan Greggf4bf2752016-07-21 18:13:24 -0700321 missing_stacks += 1
Teng Qine4db7682018-04-24 16:24:20 -0700322 has_enomem = has_enomem or k.kernel_stack_id == -errno.ENOMEM
323 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
324 missing_stacks += 1
325 has_enomem = has_enomem or k.user_stack_id == -errno.ENOMEM
Brendan Greggf4bf2752016-07-21 18:13:24 -0700326
327 user_stack = [] if k.user_stack_id < 0 else \
328 stack_traces.walk(k.user_stack_id)
329 kernel_tmp = [] if k.kernel_stack_id < 0 else \
330 stack_traces.walk(k.kernel_stack_id)
331
332 # fix kernel stack
333 kernel_stack = []
334 if k.kernel_stack_id >= 0:
Brendan Gregg715f7e62016-10-20 22:50:08 -0700335 for addr in kernel_tmp:
336 kernel_stack.append(addr)
337 # the later IP checking
Brendan Greggf4bf2752016-07-21 18:13:24 -0700338 if k.kernel_ip:
339 kernel_stack.insert(0, k.kernel_ip)
340
Brendan Greggf4bf2752016-07-21 18:13:24 -0700341 if args.folded:
342 # print folded stack output
343 user_stack = list(user_stack)
344 kernel_stack = list(kernel_stack)
Jürgen Hötzeleba14832018-06-25 18:35:46 +0200345 line = [k.name]
Teng Qine4db7682018-04-24 16:24:20 -0700346 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
347 # hash collision (-EEXIST), we still print a placeholder for consistency
348 if not args.kernel_stacks_only:
349 if stack_id_err(k.user_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800350 line.append(b"[Missed User Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700351 else:
352 line.extend([b.sym(addr, k.pid) for addr in reversed(user_stack)])
353 if not args.user_stacks_only:
Gil Raphaelli29aa6192020-02-19 11:09:52 -0500354 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 -0700355 if stack_id_err(k.kernel_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800356 line.append(b"[Missed Kernel Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700357 else:
Brendan Gregg7324ba52019-01-22 15:47:08 -0800358 line.extend([aksym(addr) for addr in reversed(kernel_stack)])
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200359 print("%s %d" % (b";".join(line).decode('utf-8', 'replace'), v.value))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700360 else:
Teng Qine4db7682018-04-24 16:24:20 -0700361 # print default multi-line stack output
362 if not args.user_stacks_only:
363 if stack_id_err(k.kernel_stack_id):
364 print(" [Missed Kernel Stack]")
365 else:
366 for addr in kernel_stack:
367 print(" %s" % aksym(addr))
368 if not args.kernel_stacks_only:
369 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
370 print(" --")
371 if stack_id_err(k.user_stack_id):
372 print(" [Missed User Stack]")
373 else:
374 for addr in user_stack:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200375 print(" %s" % b.sym(addr, k.pid).decode('utf-8', 'replace'))
376 print(" %-16s %s (%d)" % ("-", k.name.decode('utf-8', 'replace'), k.pid))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700377 print(" %d\n" % v.value)
378
379# check missing
380if missing_stacks > 0:
381 enomem_str = "" if not has_enomem else \
382 " Consider increasing --stack-storage-size."
383 print("WARNING: %d stack traces could not be displayed.%s" %
384 (missing_stacks, enomem_str),
385 file=stderr)