blob: 89cd5230dfbceaf48cda075e9aa9abdacee88714 [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
37import multiprocessing
38import ctypes as ct
39
40#
41# Process Arguments
42#
43
44# arg validation
45def positive_int(val):
46 try:
47 ival = int(val)
48 except ValueError:
49 raise argparse.ArgumentTypeError("must be an integer")
50
51 if ival < 0:
52 raise argparse.ArgumentTypeError("must be positive")
53 return ival
54
55def positive_nonzero_int(val):
56 ival = positive_int(val)
57 if ival == 0:
58 raise argparse.ArgumentTypeError("must be nonzero")
59 return ival
60
Teng Qine4db7682018-04-24 16:24:20 -070061def stack_id_err(stack_id):
62 # -EFAULT in get_stackid normally means the stack-trace is not availible,
63 # Such as getting kernel stack trace in userspace code
64 return (stack_id < 0) and (stack_id != -errno.EFAULT)
65
Brendan Greggf4bf2752016-07-21 18:13:24 -070066# arguments
67examples = """examples:
68 ./profile # profile stack traces at 49 Hertz until Ctrl-C
69 ./profile -F 99 # profile stack traces at 99 Hertz
Teng Qin86df2b82018-04-23 12:36:51 -070070 ./profile -c 1000000 # profile stack traces every 1 in a million events
Brendan Greggf4bf2752016-07-21 18:13:24 -070071 ./profile 5 # profile at 49 Hertz for 5 seconds only
72 ./profile -f 5 # output in folded format for flame graphs
73 ./profile -p 185 # only profile threads for PID 185
74 ./profile -U # only show user space stacks (no kernel)
75 ./profile -K # only show kernel space stacks (no user)
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,
83 help="profile this PID only")
84# TODO: add options for user/kernel threads only
85stack_group = parser.add_mutually_exclusive_group()
86stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
87 help="show stacks from user space only (no kernel space stacks)")
88stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
89 help="show stacks from kernel space only (no user space stacks)")
Teng Qin86df2b82018-04-23 12:36:51 -070090sample_group = parser.add_mutually_exclusive_group()
91sample_group.add_argument("-F", "--frequency", type=positive_int,
92 help="sample frequency, Hertz")
93sample_group.add_argument("-c", "--count", type=positive_int,
94 help="sample period, number of events")
Brendan Greggf4bf2752016-07-21 18:13:24 -070095parser.add_argument("-d", "--delimited", action="store_true",
96 help="insert delimiter between kernel/user stacks")
97parser.add_argument("-a", "--annotations", action="store_true",
98 help="add _[k] annotations to kernel frames")
Brendan Gregg81baae42019-01-26 21:53:11 -080099parser.add_argument("-I", "--include-idle", action="store_true",
100 help="include CPU idle stacks")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700101parser.add_argument("-f", "--folded", action="store_true",
102 help="output folded format, one line per stack (for flame graphs)")
Tommaso Sardelliaa4aa522018-04-30 22:35:29 +0200103parser.add_argument("--stack-storage-size", default=16384,
Brendan Greggf4bf2752016-07-21 18:13:24 -0700104 type=positive_nonzero_int,
105 help="the number of unique stack traces that can be stored and "
Tommaso Sardelli718c9282018-04-30 15:36:40 +0200106 "displayed (default %(default)s)")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700107parser.add_argument("duration", nargs="?", default=99999999,
108 type=positive_nonzero_int,
109 help="duration of trace, in seconds")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700110parser.add_argument("-C", "--cpu", type=int, default=-1,
111 help="cpu number to run profile on")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100112parser.add_argument("--ebpf", action="store_true",
113 help=argparse.SUPPRESS)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700114
115# option logic
116args = parser.parse_args()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700117pid = int(args.pid) if args.pid is not None else -1
118duration = int(args.duration)
119debug = 0
120need_delimiter = args.delimited and not (args.kernel_stacks_only or
121 args.user_stacks_only)
122# TODO: add stack depth, and interval
123
124#
125# Setup BPF
126#
127
128# define BPF program
129bpf_text = """
130#include <uapi/linux/ptrace.h>
Brendan Gregg715f7e62016-10-20 22:50:08 -0700131#include <uapi/linux/bpf_perf_event.h>
Brendan Greggf4bf2752016-07-21 18:13:24 -0700132#include <linux/sched.h>
133
134struct key_t {
135 u32 pid;
136 u64 kernel_ip;
137 u64 kernel_ret_ip;
138 int user_stack_id;
139 int kernel_stack_id;
140 char name[TASK_COMM_LEN];
141};
142BPF_HASH(counts, struct key_t);
Song Liu67ae6052018-02-01 14:59:24 -0800143BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700144
145// This code gets a bit complex. Probably not suitable for casual hacking.
146
Brendan Gregg715f7e62016-10-20 22:50:08 -0700147int do_perf_event(struct bpf_perf_event_data *ctx) {
Brendan Gregg4c9f6602016-11-30 20:26:26 -0800148 u32 pid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg81baae42019-01-26 21:53:11 -0800149 if (IDLE_FILTER)
150 return 0;
151
Brendan Greggf4bf2752016-07-21 18:13:24 -0700152 if (!(THREAD_FILTER))
153 return 0;
154
155 // create map key
Brendan Greggf4bf2752016-07-21 18:13:24 -0700156 struct key_t key = {.pid = pid};
157 bpf_get_current_comm(&key.name, sizeof(key.name));
158
159 // get stacks
160 key.user_stack_id = USER_STACK_GET;
161 key.kernel_stack_id = KERNEL_STACK_GET;
162
163 if (key.kernel_stack_id >= 0) {
164 // populate extras to fix the kernel stack
Paul Chaignon37f7fef2018-06-14 02:14:59 +0200165 u64 ip = PT_REGS_IP(&ctx->regs);
Yonghong Songb5fcb512018-04-14 22:55:11 -0700166 u64 page_offset;
Brendan Greggac297c12016-10-18 20:17:04 -0700167
Brendan Greggf4bf2752016-07-21 18:13:24 -0700168 // if ip isn't sane, leave key ips as zero for later checking
Yonghong Songb5fcb512018-04-14 22:55:11 -0700169#if defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE)
170 // x64, 4.16, ..., 4.11, etc., but some earlier kernel didn't have it
171 page_offset = __PAGE_OFFSET_BASE;
172#elif defined(CONFIG_X86_64) && defined(__PAGE_OFFSET_BASE_L4)
173 // x64, 4.17, and later
174#if defined(CONFIG_DYNAMIC_MEMORY_LAYOUT) && defined(CONFIG_X86_5LEVEL)
175 page_offset = __PAGE_OFFSET_BASE_L5;
Brendan Greggac297c12016-10-18 20:17:04 -0700176#else
Yonghong Songb5fcb512018-04-14 22:55:11 -0700177 page_offset = __PAGE_OFFSET_BASE_L4;
Brendan Greggac297c12016-10-18 20:17:04 -0700178#endif
Yonghong Songb5fcb512018-04-14 22:55:11 -0700179#else
180 // earlier x86_64 kernels, e.g., 4.6, comes here
181 // arm64, s390, powerpc, x86_32
182 page_offset = PAGE_OFFSET;
183#endif
184
185 if (ip > page_offset) {
Brendan Greggf4bf2752016-07-21 18:13:24 -0700186 key.kernel_ip = ip;
Brendan Greggf4bf2752016-07-21 18:13:24 -0700187 }
188 }
189
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200190 counts.increment(key);
Brendan Greggf4bf2752016-07-21 18:13:24 -0700191 return 0;
192}
193"""
194
Brendan Gregg81baae42019-01-26 21:53:11 -0800195# set idle filter
196idle_filter = "pid == 0"
197if args.include_idle:
198 idle_filter = "0"
199bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
200
Brendan Greggf4bf2752016-07-21 18:13:24 -0700201# set thread filter
202thread_context = ""
203perf_filter = "-a"
204if args.pid is not None:
205 thread_context = "PID %s" % args.pid
206 thread_filter = 'pid == %s' % args.pid
207 perf_filter = '-p %s' % args.pid
208else:
209 thread_context = "all threads"
210 thread_filter = '1'
211bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
212
213# set stack storage size
214bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
215
216# handle stack args
Teng Qine4db7682018-04-24 16:24:20 -0700217kernel_stack_get = "stack_traces.get_stackid(&ctx->regs, 0)"
218user_stack_get = "stack_traces.get_stackid(&ctx->regs, BPF_F_USER_STACK)"
Brendan Greggf4bf2752016-07-21 18:13:24 -0700219stack_context = ""
220if args.user_stacks_only:
221 stack_context = "user"
222 kernel_stack_get = "-1"
223elif args.kernel_stacks_only:
224 stack_context = "kernel"
225 user_stack_get = "-1"
226else:
227 stack_context = "user + kernel"
228bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
229bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700230
Teng Qin86df2b82018-04-23 12:36:51 -0700231sample_freq = 0
232sample_period = 0
233if args.frequency:
234 sample_freq = args.frequency
235elif args.count:
236 sample_period = args.count
237else:
238 # If user didn't specify anything, use default 49Hz sampling
239 sample_freq = 49
240sample_context = "%s%d %s" % (("", sample_freq, "Hertz") if sample_freq
241 else ("every ", sample_period, "events"))
242
Brendan Greggf4bf2752016-07-21 18:13:24 -0700243# header
244if not args.folded:
Teng Qin86df2b82018-04-23 12:36:51 -0700245 print("Sampling at %s of %s by %s stack" %
246 (sample_context, thread_context, stack_context), end="")
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700247 if args.cpu >= 0:
248 print(" on CPU#{}".format(args.cpu), end="")
Brendan Greggf4bf2752016-07-21 18:13:24 -0700249 if duration < 99999999:
250 print(" for %d secs." % duration)
251 else:
252 print("... Hit Ctrl-C to end.")
253
Nathan Scottcf0792f2018-02-02 16:56:50 +1100254if debug or args.ebpf:
Brendan Greggf4bf2752016-07-21 18:13:24 -0700255 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100256 if args.ebpf:
257 exit()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700258
Brendan Gregg715f7e62016-10-20 22:50:08 -0700259# initialize BPF & perf_events
260b = BPF(text=bpf_text)
261b.attach_perf_event(ev_type=PerfType.SOFTWARE,
262 ev_config=PerfSWConfig.CPU_CLOCK, fn_name="do_perf_event",
Nikita V. Shirokove36f9e12018-07-19 11:49:54 -0700263 sample_period=sample_period, sample_freq=sample_freq, cpu=args.cpu)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700264
265# signal handler
266def signal_ignore(signal, frame):
267 print()
268
269#
Brendan Greggf4bf2752016-07-21 18:13:24 -0700270# Output Report
271#
272
273# collect samples
274try:
275 sleep(duration)
276except KeyboardInterrupt:
277 # as cleanup can take some time, trap Ctrl-C:
278 signal.signal(signal.SIGINT, signal_ignore)
279
280if not args.folded:
281 print()
282
283def aksym(addr):
284 if args.annotations:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200285 return b.ksym(addr) + "_[k]".encode()
Brendan Greggf4bf2752016-07-21 18:13:24 -0700286 else:
287 return b.ksym(addr)
288
289# output stacks
290missing_stacks = 0
291has_enomem = False
292counts = b.get_table("counts")
293stack_traces = b.get_table("stack_traces")
Teng Qine4db7682018-04-24 16:24:20 -0700294need_delimiter = args.delimited and not (args.kernel_stacks_only or
295 args.user_stacks_only)
Brendan Greggf4bf2752016-07-21 18:13:24 -0700296for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qine4db7682018-04-24 16:24:20 -0700297 # handle get_stackid errors
298 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Brendan Greggf4bf2752016-07-21 18:13:24 -0700299 missing_stacks += 1
Teng Qine4db7682018-04-24 16:24:20 -0700300 has_enomem = has_enomem or k.kernel_stack_id == -errno.ENOMEM
301 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
302 missing_stacks += 1
303 has_enomem = has_enomem or k.user_stack_id == -errno.ENOMEM
Brendan Greggf4bf2752016-07-21 18:13:24 -0700304
305 user_stack = [] if k.user_stack_id < 0 else \
306 stack_traces.walk(k.user_stack_id)
307 kernel_tmp = [] if k.kernel_stack_id < 0 else \
308 stack_traces.walk(k.kernel_stack_id)
309
310 # fix kernel stack
311 kernel_stack = []
312 if k.kernel_stack_id >= 0:
Brendan Gregg715f7e62016-10-20 22:50:08 -0700313 for addr in kernel_tmp:
314 kernel_stack.append(addr)
315 # the later IP checking
Brendan Greggf4bf2752016-07-21 18:13:24 -0700316 if k.kernel_ip:
317 kernel_stack.insert(0, k.kernel_ip)
318
Brendan Greggf4bf2752016-07-21 18:13:24 -0700319 if args.folded:
320 # print folded stack output
321 user_stack = list(user_stack)
322 kernel_stack = list(kernel_stack)
Jürgen Hötzeleba14832018-06-25 18:35:46 +0200323 line = [k.name]
Teng Qine4db7682018-04-24 16:24:20 -0700324 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
325 # hash collision (-EEXIST), we still print a placeholder for consistency
326 if not args.kernel_stacks_only:
327 if stack_id_err(k.user_stack_id):
328 line.append("[Missed User Stack]")
329 else:
330 line.extend([b.sym(addr, k.pid) for addr in reversed(user_stack)])
331 if not args.user_stacks_only:
332 line.extend(["-"] if (need_delimiter and k.kernel_stack_id >= 0 and k.user_stack_id >= 0) else [])
333 if stack_id_err(k.kernel_stack_id):
334 line.append("[Missed Kernel Stack]")
335 else:
Brendan Gregg7324ba52019-01-22 15:47:08 -0800336 line.extend([aksym(addr) for addr in reversed(kernel_stack)])
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200337 print("%s %d" % (b";".join(line).decode('utf-8', 'replace'), v.value))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700338 else:
Teng Qine4db7682018-04-24 16:24:20 -0700339 # print default multi-line stack output
340 if not args.user_stacks_only:
341 if stack_id_err(k.kernel_stack_id):
342 print(" [Missed Kernel Stack]")
343 else:
344 for addr in kernel_stack:
345 print(" %s" % aksym(addr))
346 if not args.kernel_stacks_only:
347 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
348 print(" --")
349 if stack_id_err(k.user_stack_id):
350 print(" [Missed User Stack]")
351 else:
352 for addr in user_stack:
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200353 print(" %s" % b.sym(addr, k.pid).decode('utf-8', 'replace'))
354 print(" %-16s %s (%d)" % ("-", k.name.decode('utf-8', 'replace'), k.pid))
Brendan Greggf4bf2752016-07-21 18:13:24 -0700355 print(" %d\n" % v.value)
356
357# check missing
358if missing_stacks > 0:
359 enomem_str = "" if not has_enomem else \
360 " Consider increasing --stack-storage-size."
361 print("WARNING: %d stack traces could not be displayed.%s" %
362 (missing_stacks, enomem_str),
363 file=stderr)