blob: e1f3af939d64cfe79237ae34f3d11dc8dfa9ddd7 [file] [log] [blame]
Brendan Gregg38cef482016-01-15 17:26:30 -08001#!/usr/bin/python
2#
Andrew Birchall1f202e72016-05-05 10:56:40 -07003# offcputime Summarize off-CPU time by stack trace
Brendan Gregg38cef482016-01-15 17:26:30 -08004# For Linux, uses BCC, eBPF.
5#
Andrew Birchall1f202e72016-05-05 10:56:40 -07006# USAGE: offcputime [-h] [-p PID | -u | -k] [-U | -K] [-f] [duration]
Brendan Gregg38cef482016-01-15 17:26:30 -08007#
Brendan Gregg38cef482016-01-15 17:26:30 -08008# Copyright 2016 Netflix, Inc.
9# Licensed under the Apache License, Version 2.0 (the "License")
10#
11# 13-Jan-2016 Brendan Gregg Created this.
12
13from __future__ import print_function
14from bcc import BPF
Andrew Birchallee7e5b42016-05-03 16:54:00 -070015from sys import stderr
Brendan Gregg38cef482016-01-15 17:26:30 -080016from time import sleep, strftime
17import argparse
Teng Qin0b11d222016-07-18 13:21:10 -070018import errno
Brendan Gregg38cef482016-01-15 17:26:30 -080019import signal
20
Andrew Birchall47d871f2016-05-11 18:31:49 -070021# arg validation
22def positive_int(val):
23 try:
24 ival = int(val)
25 except ValueError:
26 raise argparse.ArgumentTypeError("must be an integer")
27
28 if ival < 0:
29 raise argparse.ArgumentTypeError("must be positive")
30 return ival
31
32def positive_nonzero_int(val):
33 ival = positive_int(val)
34 if ival == 0:
35 raise argparse.ArgumentTypeError("must be nonzero")
36 return ival
37
Teng Qinea728052018-04-13 16:48:09 -070038def stack_id_err(stack_id):
39 # -EFAULT in get_stackid normally means the stack-trace is not availible,
40 # Such as getting kernel stack trace in userspace code
41 return (stack_id < 0) and (stack_id != -errno.EFAULT)
42
Brendan Gregg38cef482016-01-15 17:26:30 -080043# arguments
44examples = """examples:
45 ./offcputime # trace off-CPU stack time until Ctrl-C
46 ./offcputime 5 # trace for 5 seconds only
47 ./offcputime -f 5 # 5 seconds, and output in folded format
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030048 ./offcputime -m 1000 # trace only events that last more than 1000 usec
49 ./offcputime -M 10000 # trace only events that last less than 10000 usec
Andrew Birchall582b5dd2016-05-04 16:03:34 -070050 ./offcputime -p 185 # only trace threads for PID 185
Mark Drayton66bf2e82016-07-31 22:47:07 +010051 ./offcputime -t 188 # only trace thread 188
Andrew Birchall582b5dd2016-05-04 16:03:34 -070052 ./offcputime -u # only trace user threads (no kernel)
53 ./offcputime -k # only trace kernel threads (no user)
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070054 ./offcputime -U # only show user space stacks (no kernel)
55 ./offcputime -K # only show kernel space stacks (no user)
Brendan Gregg38cef482016-01-15 17:26:30 -080056"""
57parser = argparse.ArgumentParser(
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070058 description="Summarize off-CPU time by stack trace",
Brendan Gregg38cef482016-01-15 17:26:30 -080059 formatter_class=argparse.RawDescriptionHelpFormatter,
60 epilog=examples)
Andrew Birchall47d871f2016-05-11 18:31:49 -070061thread_group = parser.add_mutually_exclusive_group()
Mark Drayton66bf2e82016-07-31 22:47:07 +010062# Note: this script provides --pid and --tid flags but their arguments are
63# referred to internally using kernel nomenclature: TGID and PID.
64thread_group.add_argument("-p", "--pid", metavar="PID", dest="tgid",
65 help="trace this PID only", type=positive_int)
66thread_group.add_argument("-t", "--tid", metavar="TID", dest="pid",
67 help="trace this TID only", type=positive_int)
Andrew Birchall582b5dd2016-05-04 16:03:34 -070068thread_group.add_argument("-u", "--user-threads-only", action="store_true",
69 help="user threads only (no kernel threads)")
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070070thread_group.add_argument("-k", "--kernel-threads-only", action="store_true",
71 help="kernel threads only (no user threads)")
Andrew Birchall1f202e72016-05-05 10:56:40 -070072stack_group = parser.add_mutually_exclusive_group()
73stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070074 help="show stacks from user space only (no kernel space stacks)")
Andrew Birchall1f202e72016-05-05 10:56:40 -070075stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070076 help="show stacks from kernel space only (no user space stacks)")
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +100077parser.add_argument("-d", "--delimited", action="store_true",
78 help="insert delimiter between kernel/user stacks")
Brendan Gregg38cef482016-01-15 17:26:30 -080079parser.add_argument("-f", "--folded", action="store_true",
80 help="output folded format")
Andrew Birchall47d871f2016-05-11 18:31:49 -070081parser.add_argument("--stack-storage-size", default=1024,
82 type=positive_nonzero_int,
Mark Drayton66bf2e82016-07-31 22:47:07 +010083 help="the number of unique stack traces that can be stored and "
84 "displayed (default 1024)")
Brendan Gregg38cef482016-01-15 17:26:30 -080085parser.add_argument("duration", nargs="?", default=99999999,
Andrew Birchall47d871f2016-05-11 18:31:49 -070086 type=positive_nonzero_int,
Brendan Gregg38cef482016-01-15 17:26:30 -080087 help="duration of trace, in seconds")
Glauber Costa52464582016-09-26 12:59:32 -070088parser.add_argument("-m", "--min-block-time", default=1,
89 type=positive_nonzero_int,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030090 help="the amount of time in microseconds over which we " +
91 "store traces (default 1)")
92parser.add_argument("-M", "--max-block-time", default=(1 << 64) - 1,
Glauber Costa52464582016-09-26 12:59:32 -070093 type=positive_nonzero_int,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030094 help="the amount of time in microseconds under which we " +
95 "store traces (default U64_MAX)")
Brendan Gregg48708192017-08-03 11:49:27 -070096parser.add_argument("--state", type=positive_int,
Brendan Gregg843340d2017-07-31 18:39:30 -070097 help="filter on this thread state bitmask (eg, 2 == TASK_UNINTERRUPTIBLE" +
98 ") see include/linux/sched.h")
Nathan Scottcf0792f2018-02-02 16:56:50 +110099parser.add_argument("--ebpf", action="store_true",
100 help=argparse.SUPPRESS)
Brendan Gregg38cef482016-01-15 17:26:30 -0800101args = parser.parse_args()
Mark Drayton66bf2e82016-07-31 22:47:07 +0100102if args.pid and args.tgid:
103 parser.error("specify only one of -p and -t")
Brendan Gregg38cef482016-01-15 17:26:30 -0800104folded = args.folded
105duration = int(args.duration)
Brendan Gregg843340d2017-07-31 18:39:30 -0700106debug = 0
Brendan Gregg38cef482016-01-15 17:26:30 -0800107
108# signal handler
109def signal_ignore(signal, frame):
110 print()
111
Brendan Greggd364d042016-01-19 17:12:52 -0800112# define BPF program
Brendan Gregg38cef482016-01-15 17:26:30 -0800113bpf_text = """
114#include <uapi/linux/ptrace.h>
115#include <linux/sched.h>
116
Glauber Costa52464582016-09-26 12:59:32 -0700117#define MINBLOCK_US MINBLOCK_US_VALUEULL
118#define MAXBLOCK_US MAXBLOCK_US_VALUEULL
Brendan Gregg38cef482016-01-15 17:26:30 -0800119
120struct key_t {
Andrew Birchall1f202e72016-05-05 10:56:40 -0700121 u32 pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100122 u32 tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700123 int user_stack_id;
124 int kernel_stack_id;
Brendan Gregg38cef482016-01-15 17:26:30 -0800125 char name[TASK_COMM_LEN];
Brendan Gregg38cef482016-01-15 17:26:30 -0800126};
127BPF_HASH(counts, struct key_t);
128BPF_HASH(start, u32);
Song Liu67ae6052018-02-01 14:59:24 -0800129BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Gregg38cef482016-01-15 17:26:30 -0800130
Brendan Greggd364d042016-01-19 17:12:52 -0800131int oncpu(struct pt_regs *ctx, struct task_struct *prev) {
Evgeny Vereshchagin9858ca52016-05-27 06:13:52 +0000132 u32 pid = prev->pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100133 u32 tgid = prev->tgid;
Brendan Greggd364d042016-01-19 17:12:52 -0800134 u64 ts, *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800135
Brendan Greggd364d042016-01-19 17:12:52 -0800136 // record previous thread sleep time
Brendan Gregg843340d2017-07-31 18:39:30 -0700137 if ((THREAD_FILTER) && (STATE_FILTER)) {
Brendan Greggd364d042016-01-19 17:12:52 -0800138 ts = bpf_ktime_get_ns();
139 start.update(&pid, &ts);
140 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800141
Andrew Birchall1f202e72016-05-05 10:56:40 -0700142 // get the current thread's start time
Brendan Greggd364d042016-01-19 17:12:52 -0800143 pid = bpf_get_current_pid_tgid();
Mark Drayton66bf2e82016-07-31 22:47:07 +0100144 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg38cef482016-01-15 17:26:30 -0800145 tsp = start.lookup(&pid);
Andrew Birchall1f202e72016-05-05 10:56:40 -0700146 if (tsp == 0) {
Brendan Greggf7471142016-01-19 14:40:41 -0800147 return 0; // missed start or filtered
Andrew Birchall1f202e72016-05-05 10:56:40 -0700148 }
149
150 // calculate current thread's delta time
Brendan Greggf7471142016-01-19 14:40:41 -0800151 u64 delta = bpf_ktime_get_ns() - *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800152 start.delete(&pid);
153 delta = delta / 1000;
Glauber Costa52464582016-09-26 12:59:32 -0700154 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Gregg38cef482016-01-15 17:26:30 -0800155 return 0;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700156 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800157
Brendan Greggf7471142016-01-19 14:40:41 -0800158 // create map key
Vicent Martie82fb1b2016-03-25 17:21:44 +0100159 u64 zero = 0, *val;
Brendan Greggf7471142016-01-19 14:40:41 -0800160 struct key_t key = {};
Vicent Martie82fb1b2016-03-25 17:21:44 +0100161
Andrew Birchall1f202e72016-05-05 10:56:40 -0700162 key.pid = pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100163 key.tgid = tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700164 key.user_stack_id = USER_STACK_GET;
165 key.kernel_stack_id = KERNEL_STACK_GET;
Brendan Gregg38cef482016-01-15 17:26:30 -0800166 bpf_get_current_comm(&key.name, sizeof(key.name));
Brendan Gregg38cef482016-01-15 17:26:30 -0800167
Brendan Gregg38cef482016-01-15 17:26:30 -0800168 val = counts.lookup_or_init(&key, &zero);
169 (*val) += delta;
170 return 0;
171}
172"""
Andrew Birchall47d871f2016-05-11 18:31:49 -0700173
174# set thread filter
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700175thread_context = ""
Mark Drayton66bf2e82016-07-31 22:47:07 +0100176if args.tgid is not None:
177 thread_context = "PID %d" % args.tgid
178 thread_filter = 'tgid == %d' % args.tgid
179elif args.pid is not None:
180 thread_context = "TID %d" % args.pid
181 thread_filter = 'pid == %d' % args.pid
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700182elif args.user_threads_only:
183 thread_context = "user threads"
184 thread_filter = '!(prev->flags & PF_KTHREAD)'
185elif args.kernel_threads_only:
186 thread_context = "kernel threads"
187 thread_filter = 'prev->flags & PF_KTHREAD'
Brendan Gregg38cef482016-01-15 17:26:30 -0800188else:
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700189 thread_context = "all threads"
190 thread_filter = '1'
Brendan Gregg843340d2017-07-31 18:39:30 -0700191if args.state == 0:
192 state_filter = 'prev->state == 0'
Brendan Gregg48708192017-08-03 11:49:27 -0700193elif args.state:
Brendan Gregg843340d2017-07-31 18:39:30 -0700194 # these states are sometimes bitmask checked
195 state_filter = 'prev->state & %d' % args.state
196else:
197 state_filter = '1'
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700198bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
Brendan Gregg843340d2017-07-31 18:39:30 -0700199bpf_text = bpf_text.replace('STATE_FILTER', state_filter)
Andrew Birchall47d871f2016-05-11 18:31:49 -0700200
201# set stack storage size
202bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
Glauber Costa52464582016-09-26 12:59:32 -0700203bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
204bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
Brendan Greggd364d042016-01-19 17:12:52 -0800205
Andrew Birchall1f202e72016-05-05 10:56:40 -0700206# handle stack args
Teng Qinea728052018-04-13 16:48:09 -0700207kernel_stack_get = "stack_traces.get_stackid(ctx, 0)"
208user_stack_get = "stack_traces.get_stackid(ctx, BPF_F_USER_STACK)"
Andrew Birchall1f202e72016-05-05 10:56:40 -0700209stack_context = ""
210if args.user_stacks_only:
211 stack_context = "user"
212 kernel_stack_get = "-1"
213elif args.kernel_stacks_only:
214 stack_context = "kernel"
215 user_stack_get = "-1"
216else:
217 stack_context = "user + kernel"
218bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
219bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
220
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300221need_delimiter = args.delimited and not (args.kernel_stacks_only or
222 args.user_stacks_only)
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000223
Andrew Birchall1f202e72016-05-05 10:56:40 -0700224# check for an edge case; the code below will handle this case correctly
225# but ultimately nothing will be displayed
226if args.kernel_threads_only and args.user_stacks_only:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300227 print("ERROR: Displaying user stacks for kernel threads " +
228 "doesn't make sense.", file=stderr)
Andrew Birchall1f202e72016-05-05 10:56:40 -0700229 exit(1)
230
Nathan Scottcf0792f2018-02-02 16:56:50 +1100231if debug or args.ebpf:
Brendan Gregg843340d2017-07-31 18:39:30 -0700232 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100233 if args.ebpf:
234 exit()
Brendan Gregg843340d2017-07-31 18:39:30 -0700235
Brendan Greggd364d042016-01-19 17:12:52 -0800236# initialize BPF
Brendan Gregg38cef482016-01-15 17:26:30 -0800237b = BPF(text=bpf_text)
Brendan Gregg38cef482016-01-15 17:26:30 -0800238b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
239matched = b.num_open_kprobes()
240if matched == 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700241 print("error: 0 functions traced. Exiting.", file=stderr)
242 exit(1)
Brendan Gregg38cef482016-01-15 17:26:30 -0800243
244# header
245if not folded:
Andrew Birchall1f202e72016-05-05 10:56:40 -0700246 print("Tracing off-CPU time (us) of %s by %s stack" %
247 (thread_context, stack_context), end="")
Brendan Gregg38cef482016-01-15 17:26:30 -0800248 if duration < 99999999:
249 print(" for %d secs." % duration)
250 else:
251 print("... Hit Ctrl-C to end.")
252
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700253try:
254 sleep(duration)
255except KeyboardInterrupt:
256 # as cleanup can take many seconds, trap Ctrl-C:
257 signal.signal(signal.SIGINT, signal_ignore)
Brendan Gregg38cef482016-01-15 17:26:30 -0800258
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700259if not folded:
260 print()
Brendan Gregg38cef482016-01-15 17:26:30 -0800261
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700262missing_stacks = 0
Andrew Birchall47d871f2016-05-11 18:31:49 -0700263has_enomem = False
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700264counts = b.get_table("counts")
265stack_traces = b.get_table("stack_traces")
266for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Teng Qinea728052018-04-13 16:48:09 -0700267 # handle get_stackid errors
268 if not args.user_stacks_only and stack_id_err(k.kernel_stack_id):
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700269 missing_stacks += 1
Teng Qinea728052018-04-13 16:48:09 -0700270 has_enomem = has_enomem or k.kernel_stack_id == -errno.ENOMEM
271 if not args.kernel_stacks_only and stack_id_err(k.user_stack_id):
272 missing_stacks += 1
273 has_enomem = has_enomem or k.user_stack_id == -errno.ENOMEM
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700274
Mark Drayton66bf2e82016-07-31 22:47:07 +0100275 # user stacks will be symbolized by tgid, not pid, to avoid the overhead
276 # of one symbol resolver per thread
Andrew Birchall1f202e72016-05-05 10:56:40 -0700277 user_stack = [] if k.user_stack_id < 0 else \
278 stack_traces.walk(k.user_stack_id)
279 kernel_stack = [] if k.kernel_stack_id < 0 else \
280 stack_traces.walk(k.kernel_stack_id)
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700281
282 if folded:
283 # print folded stack output
Evgeny Vereshchaginff39d0c2016-06-07 18:00:01 +1000284 user_stack = list(user_stack)
285 kernel_stack = list(kernel_stack)
Teng Qinea728052018-04-13 16:48:09 -0700286 line = [k.name.decode()]
287 # if we failed to get the stack is, such as due to no space (-ENOMEM) or
288 # hash collision (-EEXIST), we still print a placeholder for consistency
289 if not args.kernel_stacks_only:
290 if stack_id_err(k.user_stack_id):
291 line.append("[Missed User Stack]")
292 else:
293 line.extend([b.sym(addr, k.tgid) for addr in reversed(user_stack)])
294 if not args.user_stacks_only:
Teng Qine778db02018-04-24 16:11:49 -0700295 line.extend(["-"] if (need_delimiter and k.kernel_stack_id >= 0 and k.user_stack_id >= 0) else [])
Teng Qinea728052018-04-13 16:48:09 -0700296 if stack_id_err(k.kernel_stack_id):
297 line.append("[Missed Kernel Stack]")
298 else:
299 line.extend([b.ksym(addr) for addr in reversed(kernel_stack)])
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700300 print("%s %d" % (";".join(line), v.value))
301 else:
302 # print default multi-line stack output
Teng Qinea728052018-04-13 16:48:09 -0700303 if not args.user_stacks_only:
304 if stack_id_err(k.kernel_stack_id):
305 print(" [Missed Kernel Stack]")
306 else:
307 for addr in kernel_stack:
308 print(" %s" % b.ksym(addr))
309 if not args.kernel_stacks_only:
Teng Qine778db02018-04-24 16:11:49 -0700310 if need_delimiter and k.user_stack_id >= 0 and k.kernel_stack_id >= 0:
Teng Qinea728052018-04-13 16:48:09 -0700311 print(" --")
312 if stack_id_err(k.user_stack_id):
313 print(" [Missed User Stack]")
314 else:
315 for addr in user_stack:
316 print(" %s" % b.sym(addr, k.tgid))
Rafael F78948e42017-03-26 14:54:25 +0200317 print(" %-16s %s (%d)" % ("-", k.name.decode(), k.pid))
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700318 print(" %d\n" % v.value)
319
320if missing_stacks > 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700321 enomem_str = "" if not has_enomem else \
322 " Consider increasing --stack-storage-size."
Teng Qinea728052018-04-13 16:48:09 -0700323 print("WARNING: %d stack traces lost and could not be displayed.%s" %
Andrew Birchall47d871f2016-05-11 18:31:49 -0700324 (missing_stacks, enomem_str),
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700325 file=stderr)