blob: 47d2adf297fe9a7354ca5e1c73c83b2b44eeea8c [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;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700145 int user_stack_id;
146 int kernel_stack_id;
147 char name[TASK_COMM_LEN];
148};
149BPF_HASH(counts, struct key_t);
Song Liu67ae6052018-02-01 14:59:24 -0800150BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700151
152// This code gets a bit complex. Probably not suitable for casual hacking.
153
Brendan Gregg715f7e62016-10-20 22:50:08 -0700154int do_perf_event(struct bpf_perf_event_data *ctx) {
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800155 u64 id = bpf_get_current_pid_tgid();
156 u32 tgid = id >> 32;
157 u32 pid = id;
158
Brendan Gregg81baae42019-01-26 21:53:11 -0800159 if (IDLE_FILTER)
160 return 0;
161
Brendan Greggf4bf2752016-07-21 18:13:24 -0700162 if (!(THREAD_FILTER))
163 return 0;
164
Alban Crequy32ab8582020-03-22 16:06:44 +0100165 if (container_should_be_filtered()) {
Alban Crequyf82ea452020-03-18 16:15:02 +0100166 return 0;
167 }
Alban Crequyf82ea452020-03-18 16:15:02 +0100168
Brendan Greggf4bf2752016-07-21 18:13:24 -0700169 // create map key
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800170 struct key_t key = {.pid = tgid};
Brendan Greggf4bf2752016-07-21 18:13:24 -0700171 bpf_get_current_comm(&key.name, sizeof(key.name));
172
173 // get stacks
174 key.user_stack_id = USER_STACK_GET;
175 key.kernel_stack_id = KERNEL_STACK_GET;
176
177 if (key.kernel_stack_id >= 0) {
178 // populate extras to fix the kernel stack
Paul Chaignon37f7fef2018-06-14 02:14:59 +0200179 u64 ip = PT_REGS_IP(&ctx->regs);
Yonghong Songb5fcb512018-04-14 22:55:11 -0700180 u64 page_offset;
Brendan Greggac297c12016-10-18 20:17:04 -0700181
Brendan Greggf4bf2752016-07-21 18:13:24 -0700182 // if ip isn't sane, leave key ips as zero for later checking
Yonghong Songb5fcb512018-04-14 22:55:11 -0700183#if defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE)
184 // x64, 4.16, ..., 4.11, etc., but some earlier kernel didn't have it
185 page_offset = __PAGE_OFFSET_BASE;
186#elif defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE_L4)
187 // x64, 4.17, and later
188#if defined(CONFIG_DYNAMIC_MEMORY_LAYOUT) && defined(CONFIG_X86_5LEVEL)
189 page_offset = __PAGE_OFFSET_BASE_L5;
Brendan Greggac297c12016-10-18 20:17:04 -0700190#else
Yonghong Songb5fcb512018-04-14 22:55:11 -0700191 page_offset = __PAGE_OFFSET_BASE_L4;
Brendan Greggac297c12016-10-18 20:17:04 -0700192#endif
Yonghong Songb5fcb512018-04-14 22:55:11 -0700193#else
194 // earlier x86_64 kernels, e.g., 4.6, comes here
195 // arm64, s390, powerpc, x86_32
196 page_offset = PAGE_OFFSET;
197#endif
198
199 if (ip > page_offset) {
Brendan Greggf4bf2752016-07-21 18:13:24 -0700200 key.kernel_ip = ip;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700201 }
202 }
203
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200204 counts.increment(key);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700205 return 0;
206}
207"""
208
Brendan Gregg81baae42019-01-26 21:53:11 -0800209# set idle filter
210idle_filter = "pid == 0"
211if args.include_idle:
212 idle_filter = "0"
213bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
214
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800215# set process/thread filter
Brendan Greggf4bf2752016-07-21 18:13:24 -0700216thread_context = ""
Brendan Greggf4bf2752016-07-21 18:13:24 -0700217if args.pid is not None:
218 thread_context = "PID %s" % args.pid
Xiaozhou Liu6b197902019-04-16 05:41:18 +0800219 thread_filter = 'tgid == %s' % args.pid
220elif args.tid is not None:
221 thread_context = "TID %s" % args.tid
222 thread_filter = 'pid == %s' % args.tid
Brendan Greggf4bf2752016-07-21 18:13:24 -0700223else:
224 thread_context = "all threads"
225 thread_filter = '1'
226bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
227
228# set stack storage size
229bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
230
231# handle stack args
Teng Qine4db7682018-04-24 16:24:20 -0700232kernel_stack_get = "stack_traces.get_stackid(&ctx->regs, 0)"
233user_stack_get = "stack_traces.get_stackid(&ctx->regs, BPF_F_USER_STACK)"
Brendan Greggf4bf2752016-07-21 18:13:24 -0700234stack_context = ""
235if args.user_stacks_only:
236 stack_context = "user"
237 kernel_stack_get = "-1"
238elif args.kernel_stacks_only:
239 stack_context = "kernel"
240 user_stack_get = "-1"
241else:
242 stack_context = "user + kernel"
243bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
244bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Alban Crequy32ab8582020-03-22 16:06:44 +0100245bpf_text = filter_by_containers(args) + bpf_text
Brendan Greggf4bf2752016-07-21 18:13:24 -0700246
Teng Qin86df2b82018-04-23 12:36:51 -0700247sample_freq = 0
248sample_period = 0
249if args.frequency:
250 sample_freq = args.frequency
251elif args.count:
252 sample_period = args.count
253else:
254 # If user didn't specify anything, use default 49Hz sampling
255 sample_freq = 49
256sample_context = "%s%d %s" % (("", sample_freq, "Hertz") if sample_freq
257 else ("every ", sample_period, "events"))
258
Brendan Greggf4bf2752016-07-21 18:13:24 -0700259# header
260if not args.folded:
Teng Qin86df2b82018-04-23 12:36:51 -0700261 print("Sampling at %s of %s by %s stack" %
262 (sample_context, thread_context, stack_context), end="")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700263 if args.cpu >= 0:
264 print(" on CPU#{}".format(args.cpu), end="")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700265 if duration < 99999999:
266 print(" for %d secs." % duration)
267 else:
268 print("... Hit Ctrl-C to end.")
269
Nathan Scottcf0792f2018-02-02 16:56:50 +1100270if debug or args.ebpf:
Brendan Greggf4bf2752016-07-21 18:13:24 -0700271 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100272 if args.ebpf:
273 exit()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700274
Brendan Gregg715f7e62016-10-20 22:50:08 -0700275# initialize BPF & perf_events
276b = BPF(text=bpf_text)
277b.attach_perf_event(ev_type=PerfType.SOFTWARE,
278 ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event",
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700279 sample_period=sample_period, sample_freq=sample_freq, cpu=args.cpu)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700280
281# signal handler
282def signal_ignore(signal, frame):
283 print()
284
285#
Brendan Greggf4bf2752016-07-21 18:13:24 -0700286# Output Report
287#
288
289# collect samples
290try:
291 sleep(duration)
292except KeyboardInterrupt:
293 # as cleanup can take some time, trap Ctrl-C:
294 signal.signal(signal.SIGINT, signal_ignore)
295
296if not args.folded:
297 print()
298
299def aksym(addr):
300 if args.annotations:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200301 return b.ksym(addr) + "_[k]".encode()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700302 else:
303 return b.ksym(addr)
304
305# output stacks
306missing_stacks = 0
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000307has_collision = False
Brendan Greggf4bf2752016-07-21 18:13:24 -0700308counts = b.get_table("counts")
309stack_traces = b.get_table("stack_traces")
310for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qine4db7682018-04-24 16:24:20 -0700311 # handle get_stackid errors
312 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Brendan Greggf4bf2752016-07-21 18:13:24 -0700313 missing_stacks += 1
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000314 # hash collision (-EEXIST) suggests that the map size may be too small
315 has_collision = has_collision or k.kernel_stack_id == -errno.EEXIST
Teng Qine4db7682018-04-24 16:24:20 -0700316 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
317 missing_stacks += 1
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000318 has_collision = has_collision or k.user_stack_id == -errno.EEXIST
Brendan Greggf4bf2752016-07-21 18:13:24 -0700319
320 user_stack = [] if k.user_stack_id < 0 else \
321 stack_traces.walk(k.user_stack_id)
322 kernel_tmp = [] if k.kernel_stack_id < 0 else \
323 stack_traces.walk(k.kernel_stack_id)
324
325 # fix kernel stack
326 kernel_stack = []
327 if k.kernel_stack_id >= 0:
Brendan Gregg715f7e62016-10-20 22:50:08 -0700328 for addr in kernel_tmp:
329 kernel_stack.append(addr)
330 # the later IP checking
Brendan Greggf4bf2752016-07-21 18:13:24 -0700331 if k.kernel_ip:
332 kernel_stack.insert(0, k.kernel_ip)
333
Brendan Greggf4bf2752016-07-21 18:13:24 -0700334 if args.folded:
335 # print folded stack output
336 user_stack = list(user_stack)
337 kernel_stack = list(kernel_stack)
Jürgen Hötzeleba14832018-06-25 18:35:46 +0200338 line = [k.name]
Teng Qine4db7682018-04-24 16:24:20 -0700339 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
340 # hash collision (-EEXIST), we still print a placeholder for consistency
341 if not args.kernel_stacks_only:
342 if stack_id_err(k.user_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800343 line.append(b"[Missed User Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700344 else:
345 line.extend([b.sym(addr, k.pid) for addr in reversed(user_stack)])
346 if not args.user_stacks_only:
Gil Raphaelli29aa6192020-02-19 11:09:52 -0500347 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 -0700348 if stack_id_err(k.kernel_stack_id):
DavadDi0cafe552020-01-21 20:33:33 +0800349 line.append(b"[Missed Kernel Stack]")
Teng Qine4db7682018-04-24 16:24:20 -0700350 else:
Brendan Gregg7324ba52019-01-22 15:47:08 -0800351 line.extend([aksym(addr) for addr in reversed(kernel_stack)])
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200352 print("%s %d" % (b";".join(line).decode('utf-8', 'replace'), v.value))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700353 else:
Teng Qine4db7682018-04-24 16:24:20 -0700354 # print default multi-line stack output
355 if not args.user_stacks_only:
356 if stack_id_err(k.kernel_stack_id):
357 print(" [Missed Kernel Stack]")
358 else:
359 for addr in kernel_stack:
360 print(" %s" % aksym(addr))
361 if not args.kernel_stacks_only:
362 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
363 print(" --")
364 if stack_id_err(k.user_stack_id):
365 print(" [Missed User Stack]")
366 else:
367 for addr in user_stack:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200368 print(" %s" % b.sym(addr, k.pid).decode('utf-8', 'replace'))
369 print(" %-16s %s (%d)" % ("-", k.name.decode('utf-8', 'replace'), k.pid))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700370 print(" %d\n" % v.value)
371
372# check missing
373if missing_stacks > 0:
Xiaozhou Liu1bddba62020-06-23 19:07:07 +0000374 enomem_str = "" if not has_collision else \
Brendan Greggf4bf2752016-07-21 18:13:24 -0700375 " Consider increasing --stack-storage-size."
376 print("WARNING: %d stack traces could not be displayed.%s" %
377 (missing_stacks, enomem_str),
378 file=stderr)