blob: 11f3e98dadbe74cd8fc7a480b3dccef02bc65a33 [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)
Brendan Greggf4bf2752016-07-21 18:13:24 -070075"""
76parser = argparse.ArgumentParser(
77 description="Profile CPU stack traces at a timed interval",
78 formatter_class=argparse.RawDescriptionHelpFormatter,
79 epilog=examples)
80thread_group = parser.add_mutually_exclusive_group()
81thread_group.add_argument("-p", "--pid", type=positive_int,
Xiaozhou Liu6b197902019-04-16 05:41:18 +080082 help="profile process with this PID only")
83thread_group.add_argument("-L", "--tid", type=positive_int,
84 help="profile thread with this TID only")
Brendan Greggf4bf2752016-07-21 18:13:24 -070085# TODO: add options for user/kernel threads only
86stack_group = parser.add_mutually_exclusive_group()
87stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
88 help="show stacks from user space only (no kernel space stacks)")
89stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
90 help="show stacks from kernel space only (no user space stacks)")
Teng Qin86df2b82018-04-23 12:36:51 -070091sample_group = parser.add_mutually_exclusive_group()
92sample_group.add_argument("-F", "--frequency", type=positive_int,
93 help="sample frequency, Hertz")
94sample_group.add_argument("-c", "--count", type=positive_int,
95 help="sample period, number of events")
Brendan Greggf4bf2752016-07-21 18:13:24 -070096parser.add_argument("-d", "--delimited", action="store_true",
97 help="insert delimiter between kernel/user stacks")
98parser.add_argument("-a", "--annotations", action="store_true",
99 help="add _[k] annotations to kernel frames")
Brendan Gregg81baae42019-01-26 21:53:11 -0800100parser.add_argument("-I", "--include-idle", action="store_true",
101 help="include CPU idle stacks")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700102parser.add_argument("-f", "--folded", action="store_true",
103 help="output folded format, one line per stack (for flame graphs)")
Tommaso Sardelliaa4aa522018-04-30 22:35:29 +0200104parser.add_argument("--stack-storage-size", default=16384,
Brendan Greggf4bf2752016-07-21 18:13:24 -0700105 type=positive_nonzero_int,
106 help="the number of unique stack traces that can be stored and "
Tommaso Sardelli718c9282018-04-30 15:36:40 +0200107 "displayed (default %(default)s)")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700108parser.add_argument("duration", nargs="?", default=99999999,
109 type=positive_nonzero_int,
110 help="duration of trace, in seconds")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700111parser.add_argument("-C", "--cpu", type=int, default=-1,
112 help="cpu number to run profile on")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100113parser.add_argument("--ebpf", action="store_true",
114 help=argparse.SUPPRESS)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700115
116# option logic
117args = parser.parse_args()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700118pid = int(args.pid) if args.pid is not None else -1
119duration = int(args.duration)
120debug = 0
121need_delimiter = args.delimited and not (args.kernel_stacks_only or
122 args.user_stacks_only)
123# TODO: add stack depth, and interval
124
125#
126# Setup BPF
127#
128
129# define BPF program
130bpf_text = """
131#include <uapi/linux/ptrace.h>
Brendan Gregg715f7e62016-10-20 22:50:08 -0700132#include <uapi/linux/bpf_perf_event.h>
Brendan Greggf4bf2752016-07-21 18:13:24 -0700133#include <linux/sched.h>
134
135struct key_t {
136 u32 pid;
137 u64 kernel_ip;
138 u64 kernel_ret_ip;
139 int user_stack_id;
140 int kernel_stack_id;
141 char name[TASK_COMM_LEN];
142};
143BPF_HASH(counts, struct key_t);
Song Liu67ae6052018-02-01 14:59:24 -0800144BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700145
146// This code gets a bit complex. Probably not suitable for casual hacking.
147
Brendan Gregg715f7e62016-10-20 22:50:08 -0700148int do_perf_event(struct bpf_perf_event_data *ctx) {
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800149 u64 id = bpf_get_current_pid_tgid();
150 u32 tgid = id >> 32;
151 u32 pid = id;
152
Brendan Gregg81baae42019-01-26 21:53:11 -0800153 if (IDLE_FILTER)
154 return 0;
155
Brendan Greggf4bf2752016-07-21 18:13:24 -0700156 if (!(THREAD_FILTER))
157 return 0;
158
159 // create map key
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800160 struct key_t key = {.pid = tgid};
Brendan Greggf4bf2752016-07-21 18:13:24 -0700161 bpf_get_current_comm(&key.name, sizeof(key.name));
162
163 // get stacks
164 key.user_stack_id = USER_STACK_GET;
165 key.kernel_stack_id = KERNEL_STACK_GET;
166
167 if (key.kernel_stack_id >= 0) {
168 // populate extras to fix the kernel stack
Paul Chaignon37f7fef2018-06-14 02:14:59 +0200169 u64 ip = PT_REGS_IP(&ctx->regs);
Yonghong Songb5fcb512018-04-14 22:55:11 -0700170 u64 page_offset;
Brendan Greggac297c12016-10-18 20:17:04 -0700171
Brendan Greggf4bf2752016-07-21 18:13:24 -0700172 // if ip isn't sane, leave key ips as zero for later checking
Yonghong Songb5fcb512018-04-14 22:55:11 -0700173#if defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE)
174 // x64, 4.16, ..., 4.11, etc., but some earlier kernel didn't have it
175 page_offset = __PAGE_OFFSET_BASE;
176#elif defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE_L4)
177 // x64, 4.17, and later
178#if defined(CONFIG_DYNAMIC_MEMORY_LAYOUT) && defined(CONFIG_X86_5LEVEL)
179 page_offset = __PAGE_OFFSET_BASE_L5;
Brendan Greggac297c12016-10-18 20:17:04 -0700180#else
Yonghong Songb5fcb512018-04-14 22:55:11 -0700181 page_offset = __PAGE_OFFSET_BASE_L4;
Brendan Greggac297c12016-10-18 20:17:04 -0700182#endif
Yonghong Songb5fcb512018-04-14 22:55:11 -0700183#else
184 // earlier x86_64 kernels, e.g., 4.6, comes here
185 // arm64, s390, powerpc, x86_32
186 page_offset = PAGE_OFFSET;
187#endif
188
189 if (ip > page_offset) {
Brendan Greggf4bf2752016-07-21 18:13:24 -0700190 key.kernel_ip = ip;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700191 }
192 }
193
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200194 counts.increment(key);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700195 return 0;
196}
197"""
198
Brendan Gregg81baae42019-01-26 21:53:11 -0800199# set idle filter
200idle_filter = "pid == 0"
201if args.include_idle:
202 idle_filter = "0"
203bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
204
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800205# set process/thread filter
Brendan Greggf4bf2752016-07-21 18:13:24 -0700206thread_context = ""
Brendan Greggf4bf2752016-07-21 18:13:24 -0700207if args.pid is not None:
208 thread_context = "PID %s" % args.pid
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800209 thread_filter = 'tgid == %s' % args.pid
210elif args.tid is not None:
211 thread_context = "TID %s" % args.tid
212 thread_filter = 'pid == %s' % args.tid
Brendan Greggf4bf2752016-07-21 18:13:24 -0700213else:
214 thread_context = "all threads"
215 thread_filter = '1'
216bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
217
218# set stack storage size
219bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
220
221# handle stack args
Teng Qine4db7682018-04-24 16:24:20 -0700222kernel_stack_get = "stack_traces.get_stackid(&ctx->regs, 0)"
223user_stack_get = "stack_traces.get_stackid(&ctx->regs, BPF_F_USER_STACK)"
Brendan Greggf4bf2752016-07-21 18:13:24 -0700224stack_context = ""
225if args.user_stacks_only:
226 stack_context = "user"
227 kernel_stack_get = "-1"
228elif args.kernel_stacks_only:
229 stack_context = "kernel"
230 user_stack_get = "-1"
231else:
232 stack_context = "user + kernel"
233bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
234bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700235
Teng Qin86df2b82018-04-23 12:36:51 -0700236sample_freq = 0
237sample_period = 0
238if args.frequency:
239 sample_freq = args.frequency
240elif args.count:
241 sample_period = args.count
242else:
243 # If user didn't specify anything, use default 49Hz sampling
244 sample_freq = 49
245sample_context = "%s%d %s" % (("", sample_freq, "Hertz") if sample_freq
246 else ("every ", sample_period, "events"))
247
Brendan Greggf4bf2752016-07-21 18:13:24 -0700248# header
249if not args.folded:
Teng Qin86df2b82018-04-23 12:36:51 -0700250 print("Sampling at %s of %s by %s stack" %
251 (sample_context, thread_context, stack_context), end="")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700252 if args.cpu >= 0:
253 print(" on CPU#{}".format(args.cpu), end="")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700254 if duration < 99999999:
255 print(" for %d secs." % duration)
256 else:
257 print("... Hit Ctrl-C to end.")
258
Nathan Scottcf0792f2018-02-02 16:56:50 +1100259if debug or args.ebpf:
Brendan Greggf4bf2752016-07-21 18:13:24 -0700260 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100261 if args.ebpf:
262 exit()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700263
Brendan Gregg715f7e62016-10-20 22:50:08 -0700264# initialize BPF & perf_events
265b = BPF(text=bpf_text)
266b.attach_perf_event(ev_type=PerfType.SOFTWARE,
267 ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event",
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700268 sample_period=sample_period, sample_freq=sample_freq, cpu=args.cpu)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700269
270# signal handler
271def signal_ignore(signal, frame):
272 print()
273
274#
Brendan Greggf4bf2752016-07-21 18:13:24 -0700275# Output Report
276#
277
278# collect samples
279try:
280 sleep(duration)
281except KeyboardInterrupt:
282 # as cleanup can take some time, trap Ctrl-C:
283 signal.signal(signal.SIGINT, signal_ignore)
284
285if not args.folded:
286 print()
287
288def aksym(addr):
289 if args.annotations:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200290 return b.ksym(addr) + "_[k]".encode()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700291 else:
292 return b.ksym(addr)
293
294# output stacks
295missing_stacks = 0
296has_enomem = False
297counts = b.get_table("counts")
298stack_traces = b.get_table("stack_traces")
299for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qine4db7682018-04-24 16:24:20 -0700300 # handle get_stackid errors
301 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Brendan Greggf4bf2752016-07-21 18:13:24 -0700302 missing_stacks += 1
Teng Qine4db7682018-04-24 16:24:20 -0700303 has_enomem = has_enomem or k.kernel_stack_id == -errno.ENOMEM
304 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
305 missing_stacks += 1
306 has_enomem = has_enomem or k.user_stack_id == -errno.ENOMEM
Brendan Greggf4bf2752016-07-21 18:13:24 -0700307
308 user_stack = [] if k.user_stack_id < 0 else \
309 stack_traces.walk(k.user_stack_id)
310 kernel_tmp = [] if k.kernel_stack_id < 0 else \
311 stack_traces.walk(k.kernel_stack_id)
312
313 # fix kernel stack
314 kernel_stack = []
315 if k.kernel_stack_id >= 0:
Brendan Gregg715f7e62016-10-20 22:50:08 -0700316 for addr in kernel_tmp:
317 kernel_stack.append(addr)
318 # the later IP checking
Brendan Greggf4bf2752016-07-21 18:13:24 -0700319 if k.kernel_ip:
320 kernel_stack.insert(0, k.kernel_ip)
321
Brendan Greggf4bf2752016-07-21 18:13:24 -0700322 if args.folded:
323 # print folded stack output
324 user_stack = list(user_stack)
325 kernel_stack = list(kernel_stack)
Jürgen Hötzeleba14832018-06-25 18:35:46 +0200326 line = [k.name]
Teng Qine4db7682018-04-24 16:24:20 -0700327 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
328 # hash collision (-EEXIST), we still print a placeholder for consistency
329 if not args.kernel_stacks_only:
330 if stack_id_err(k.user_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800331 line.append(b"[Missed User Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700332 else:
333 line.extend([b.sym(addr, k.pid) for addr in reversed(user_stack)])
334 if not args.user_stacks_only:
Gil Raphaelli29aa6192020-02-19 11:09:52 -0500335 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 -0700336 if stack_id_err(k.kernel_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800337 line.append(b"[Missed Kernel Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700338 else:
Brendan Gregg7324ba52019-01-22 15:47:08 -0800339 line.extend([aksym(addr) for addr in reversed(kernel_stack)])
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200340 print("%s %d" % (b";".join(line).decode('utf-8', 'replace'), v.value))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700341 else:
Teng Qine4db7682018-04-24 16:24:20 -0700342 # print default multi-line stack output
343 if not args.user_stacks_only:
344 if stack_id_err(k.kernel_stack_id):
345 print(" [Missed Kernel Stack]")
346 else:
347 for addr in kernel_stack:
348 print(" %s" % aksym(addr))
349 if not args.kernel_stacks_only:
350 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
351 print(" --")
352 if stack_id_err(k.user_stack_id):
353 print(" [Missed User Stack]")
354 else:
355 for addr in user_stack:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200356 print(" %s" % b.sym(addr, k.pid).decode('utf-8', 'replace'))
357 print(" %-16s %s (%d)" % ("-", k.name.decode('utf-8', 'replace'), k.pid))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700358 print(" %d\n" % v.value)
359
360# check missing
361if missing_stacks > 0:
362 enomem_str = "" if not has_enomem else \
363 " Consider increasing --stack-storage-size."
364 print("WARNING: %d stack traces could not be displayed.%s" %
365 (missing_stacks, enomem_str),
366 file=stderr)