blob: ad540ee70e94b66caa3aa5f6f16f6e848898ce73 [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
Brendan Gregg38cef482016-01-15 17:26:30 -080038# arguments
39examples = """examples:
40 ./offcputime # trace off-CPU stack time until Ctrl-C
41 ./offcputime 5 # trace for 5 seconds only
42 ./offcputime -f 5 # 5 seconds, and output in folded format
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030043 ./offcputime -m 1000 # trace only events that last more than 1000 usec
44 ./offcputime -M 10000 # trace only events that last less than 10000 usec
Andrew Birchall582b5dd2016-05-04 16:03:34 -070045 ./offcputime -p 185 # only trace threads for PID 185
Mark Drayton66bf2e82016-07-31 22:47:07 +010046 ./offcputime -t 188 # only trace thread 188
Andrew Birchall582b5dd2016-05-04 16:03:34 -070047 ./offcputime -u # only trace user threads (no kernel)
48 ./offcputime -k # only trace kernel threads (no user)
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070049 ./offcputime -U # only show user space stacks (no kernel)
50 ./offcputime -K # only show kernel space stacks (no user)
Brendan Gregg38cef482016-01-15 17:26:30 -080051"""
52parser = argparse.ArgumentParser(
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070053 description="Summarize off-CPU time by stack trace",
Brendan Gregg38cef482016-01-15 17:26:30 -080054 formatter_class=argparse.RawDescriptionHelpFormatter,
55 epilog=examples)
Andrew Birchall47d871f2016-05-11 18:31:49 -070056thread_group = parser.add_mutually_exclusive_group()
Mark Drayton66bf2e82016-07-31 22:47:07 +010057# Note: this script provides --pid and --tid flags but their arguments are
58# referred to internally using kernel nomenclature: TGID and PID.
59thread_group.add_argument("-p", "--pid", metavar="PID", dest="tgid",
60 help="trace this PID only", type=positive_int)
61thread_group.add_argument("-t", "--tid", metavar="TID", dest="pid",
62 help="trace this TID only", type=positive_int)
Andrew Birchall582b5dd2016-05-04 16:03:34 -070063thread_group.add_argument("-u", "--user-threads-only", action="store_true",
64 help="user threads only (no kernel threads)")
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070065thread_group.add_argument("-k", "--kernel-threads-only", action="store_true",
66 help="kernel threads only (no user threads)")
Andrew Birchall1f202e72016-05-05 10:56:40 -070067stack_group = parser.add_mutually_exclusive_group()
68stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070069 help="show stacks from user space only (no kernel space stacks)")
Andrew Birchall1f202e72016-05-05 10:56:40 -070070stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
Andrew Birchall7f0a6f82016-05-24 01:44:41 -070071 help="show stacks from kernel space only (no user space stacks)")
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +100072parser.add_argument("-d", "--delimited", action="store_true",
73 help="insert delimiter between kernel/user stacks")
Brendan Gregg38cef482016-01-15 17:26:30 -080074parser.add_argument("-f", "--folded", action="store_true",
75 help="output folded format")
Andrew Birchall47d871f2016-05-11 18:31:49 -070076parser.add_argument("--stack-storage-size", default=1024,
77 type=positive_nonzero_int,
Mark Drayton66bf2e82016-07-31 22:47:07 +010078 help="the number of unique stack traces that can be stored and "
79 "displayed (default 1024)")
Brendan Gregg38cef482016-01-15 17:26:30 -080080parser.add_argument("duration", nargs="?", default=99999999,
Andrew Birchall47d871f2016-05-11 18:31:49 -070081 type=positive_nonzero_int,
Brendan Gregg38cef482016-01-15 17:26:30 -080082 help="duration of trace, in seconds")
Glauber Costa52464582016-09-26 12:59:32 -070083parser.add_argument("-m", "--min-block-time", default=1,
84 type=positive_nonzero_int,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030085 help="the amount of time in microseconds over which we " +
86 "store traces (default 1)")
87parser.add_argument("-M", "--max-block-time", default=(1 << 64) - 1,
Glauber Costa52464582016-09-26 12:59:32 -070088 type=positive_nonzero_int,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030089 help="the amount of time in microseconds under which we " +
90 "store traces (default U64_MAX)")
Brendan Gregg48708192017-08-03 11:49:27 -070091parser.add_argument("--state", type=positive_int,
Brendan Gregg843340d2017-07-31 18:39:30 -070092 help="filter on this thread state bitmask (eg, 2 == TASK_UNINTERRUPTIBLE" +
93 ") see include/linux/sched.h")
Nathan Scottcf0792f2018-02-02 16:56:50 +110094parser.add_argument("--ebpf", action="store_true",
95 help=argparse.SUPPRESS)
Brendan Gregg38cef482016-01-15 17:26:30 -080096args = parser.parse_args()
Mark Drayton66bf2e82016-07-31 22:47:07 +010097if args.pid and args.tgid:
98 parser.error("specify only one of -p and -t")
Brendan Gregg38cef482016-01-15 17:26:30 -080099folded = args.folded
100duration = int(args.duration)
Brendan Gregg843340d2017-07-31 18:39:30 -0700101debug = 0
Brendan Gregg38cef482016-01-15 17:26:30 -0800102
103# signal handler
104def signal_ignore(signal, frame):
105 print()
106
Brendan Greggd364d042016-01-19 17:12:52 -0800107# define BPF program
Brendan Gregg38cef482016-01-15 17:26:30 -0800108bpf_text = """
109#include <uapi/linux/ptrace.h>
110#include <linux/sched.h>
111
Glauber Costa52464582016-09-26 12:59:32 -0700112#define MINBLOCK_US MINBLOCK_US_VALUEULL
113#define MAXBLOCK_US MAXBLOCK_US_VALUEULL
Brendan Gregg38cef482016-01-15 17:26:30 -0800114
115struct key_t {
Andrew Birchall1f202e72016-05-05 10:56:40 -0700116 u32 pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100117 u32 tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700118 int user_stack_id;
119 int kernel_stack_id;
Brendan Gregg38cef482016-01-15 17:26:30 -0800120 char name[TASK_COMM_LEN];
Brendan Gregg38cef482016-01-15 17:26:30 -0800121};
122BPF_HASH(counts, struct key_t);
123BPF_HASH(start, u32);
Song Liu67ae6052018-02-01 14:59:24 -0800124BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Gregg38cef482016-01-15 17:26:30 -0800125
Brendan Greggd364d042016-01-19 17:12:52 -0800126int oncpu(struct pt_regs *ctx, struct task_struct *prev) {
Evgeny Vereshchagin9858ca52016-05-27 06:13:52 +0000127 u32 pid = prev->pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100128 u32 tgid = prev->tgid;
Brendan Greggd364d042016-01-19 17:12:52 -0800129 u64 ts, *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800130
Brendan Greggd364d042016-01-19 17:12:52 -0800131 // record previous thread sleep time
Brendan Gregg843340d2017-07-31 18:39:30 -0700132 if ((THREAD_FILTER) && (STATE_FILTER)) {
Brendan Greggd364d042016-01-19 17:12:52 -0800133 ts = bpf_ktime_get_ns();
134 start.update(&pid, &ts);
135 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800136
Andrew Birchall1f202e72016-05-05 10:56:40 -0700137 // get the current thread's start time
Brendan Greggd364d042016-01-19 17:12:52 -0800138 pid = bpf_get_current_pid_tgid();
Mark Drayton66bf2e82016-07-31 22:47:07 +0100139 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg38cef482016-01-15 17:26:30 -0800140 tsp = start.lookup(&pid);
Andrew Birchall1f202e72016-05-05 10:56:40 -0700141 if (tsp == 0) {
Brendan Greggf7471142016-01-19 14:40:41 -0800142 return 0; // missed start or filtered
Andrew Birchall1f202e72016-05-05 10:56:40 -0700143 }
144
145 // calculate current thread's delta time
Brendan Greggf7471142016-01-19 14:40:41 -0800146 u64 delta = bpf_ktime_get_ns() - *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800147 start.delete(&pid);
148 delta = delta / 1000;
Glauber Costa52464582016-09-26 12:59:32 -0700149 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Gregg38cef482016-01-15 17:26:30 -0800150 return 0;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700151 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800152
Brendan Greggf7471142016-01-19 14:40:41 -0800153 // create map key
Vicent Martie82fb1b2016-03-25 17:21:44 +0100154 u64 zero = 0, *val;
Brendan Greggf7471142016-01-19 14:40:41 -0800155 struct key_t key = {};
Vicent Martie82fb1b2016-03-25 17:21:44 +0100156
Andrew Birchall1f202e72016-05-05 10:56:40 -0700157 key.pid = pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100158 key.tgid = tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700159 key.user_stack_id = USER_STACK_GET;
160 key.kernel_stack_id = KERNEL_STACK_GET;
Brendan Gregg38cef482016-01-15 17:26:30 -0800161 bpf_get_current_comm(&key.name, sizeof(key.name));
Brendan Gregg38cef482016-01-15 17:26:30 -0800162
Brendan Gregg38cef482016-01-15 17:26:30 -0800163 val = counts.lookup_or_init(&key, &zero);
164 (*val) += delta;
165 return 0;
166}
167"""
Andrew Birchall47d871f2016-05-11 18:31:49 -0700168
169# set thread filter
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700170thread_context = ""
Mark Drayton66bf2e82016-07-31 22:47:07 +0100171if args.tgid is not None:
172 thread_context = "PID %d" % args.tgid
173 thread_filter = 'tgid == %d' % args.tgid
174elif args.pid is not None:
175 thread_context = "TID %d" % args.pid
176 thread_filter = 'pid == %d' % args.pid
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700177elif args.user_threads_only:
178 thread_context = "user threads"
179 thread_filter = '!(prev->flags & PF_KTHREAD)'
180elif args.kernel_threads_only:
181 thread_context = "kernel threads"
182 thread_filter = 'prev->flags & PF_KTHREAD'
Brendan Gregg38cef482016-01-15 17:26:30 -0800183else:
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700184 thread_context = "all threads"
185 thread_filter = '1'
Brendan Gregg843340d2017-07-31 18:39:30 -0700186if args.state == 0:
187 state_filter = 'prev->state == 0'
Brendan Gregg48708192017-08-03 11:49:27 -0700188elif args.state:
Brendan Gregg843340d2017-07-31 18:39:30 -0700189 # these states are sometimes bitmask checked
190 state_filter = 'prev->state & %d' % args.state
191else:
192 state_filter = '1'
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700193bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
Brendan Gregg843340d2017-07-31 18:39:30 -0700194bpf_text = bpf_text.replace('STATE_FILTER', state_filter)
Andrew Birchall47d871f2016-05-11 18:31:49 -0700195
196# set stack storage size
197bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
Glauber Costa52464582016-09-26 12:59:32 -0700198bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
199bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
Brendan Greggd364d042016-01-19 17:12:52 -0800200
Andrew Birchall1f202e72016-05-05 10:56:40 -0700201# handle stack args
202kernel_stack_get = "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID)"
203user_stack_get = \
204 "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK)"
205stack_context = ""
206if args.user_stacks_only:
207 stack_context = "user"
208 kernel_stack_get = "-1"
209elif args.kernel_stacks_only:
210 stack_context = "kernel"
211 user_stack_get = "-1"
212else:
213 stack_context = "user + kernel"
214bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
215bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
216
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300217need_delimiter = args.delimited and not (args.kernel_stacks_only or
218 args.user_stacks_only)
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000219
Andrew Birchall1f202e72016-05-05 10:56:40 -0700220# check for an edge case; the code below will handle this case correctly
221# but ultimately nothing will be displayed
222if args.kernel_threads_only and args.user_stacks_only:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300223 print("ERROR: Displaying user stacks for kernel threads " +
224 "doesn't make sense.", file=stderr)
Andrew Birchall1f202e72016-05-05 10:56:40 -0700225 exit(1)
226
Nathan Scottcf0792f2018-02-02 16:56:50 +1100227if debug or args.ebpf:
Brendan Gregg843340d2017-07-31 18:39:30 -0700228 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100229 if args.ebpf:
230 exit()
Brendan Gregg843340d2017-07-31 18:39:30 -0700231
Brendan Greggd364d042016-01-19 17:12:52 -0800232# initialize BPF
Brendan Gregg38cef482016-01-15 17:26:30 -0800233b = BPF(text=bpf_text)
Brendan Gregg38cef482016-01-15 17:26:30 -0800234b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
235matched = b.num_open_kprobes()
236if matched == 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700237 print("error: 0 functions traced. Exiting.", file=stderr)
238 exit(1)
Brendan Gregg38cef482016-01-15 17:26:30 -0800239
240# header
241if not folded:
Andrew Birchall1f202e72016-05-05 10:56:40 -0700242 print("Tracing off-CPU time (us) of %s by %s stack" %
243 (thread_context, stack_context), end="")
Brendan Gregg38cef482016-01-15 17:26:30 -0800244 if duration < 99999999:
245 print(" for %d secs." % duration)
246 else:
247 print("... Hit Ctrl-C to end.")
248
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700249try:
250 sleep(duration)
251except KeyboardInterrupt:
252 # as cleanup can take many seconds, trap Ctrl-C:
253 signal.signal(signal.SIGINT, signal_ignore)
Brendan Gregg38cef482016-01-15 17:26:30 -0800254
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700255if not folded:
256 print()
Brendan Gregg38cef482016-01-15 17:26:30 -0800257
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700258missing_stacks = 0
Andrew Birchall47d871f2016-05-11 18:31:49 -0700259has_enomem = False
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700260counts = b.get_table("counts")
261stack_traces = b.get_table("stack_traces")
262for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Andrew Birchall47d871f2016-05-11 18:31:49 -0700263 # handle get_stackid erorrs
Andrew Birchall1f202e72016-05-05 10:56:40 -0700264 if (not args.user_stacks_only and k.kernel_stack_id < 0) or \
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300265 (not args.kernel_stacks_only and k.user_stack_id < 0 and
266 k.user_stack_id != -errno.EFAULT):
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700267 missing_stacks += 1
Andrew Birchall47d871f2016-05-11 18:31:49 -0700268 # check for an ENOMEM error
Teng Qin0b11d222016-07-18 13:21:10 -0700269 if k.kernel_stack_id == -errno.ENOMEM or \
270 k.user_stack_id == -errno.ENOMEM:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700271 has_enomem = True
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700272 continue
273
Mark Drayton66bf2e82016-07-31 22:47:07 +0100274 # user stacks will be symbolized by tgid, not pid, to avoid the overhead
275 # of one symbol resolver per thread
Andrew Birchall1f202e72016-05-05 10:56:40 -0700276 user_stack = [] if k.user_stack_id < 0 else \
277 stack_traces.walk(k.user_stack_id)
278 kernel_stack = [] if k.kernel_stack_id < 0 else \
279 stack_traces.walk(k.kernel_stack_id)
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700280
281 if folded:
282 # print folded stack output
Evgeny Vereshchaginff39d0c2016-06-07 18:00:01 +1000283 user_stack = list(user_stack)
284 kernel_stack = list(kernel_stack)
Andrew Birchall1f202e72016-05-05 10:56:40 -0700285 line = [k.name.decode()] + \
Mark Drayton66bf2e82016-07-31 22:47:07 +0100286 [b.sym(addr, k.tgid) for addr in reversed(user_stack)] + \
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000287 (need_delimiter and ["-"] or []) + \
Evgeny Vereshchaginf9886442016-06-08 06:06:33 +1000288 [b.ksym(addr) for addr in reversed(kernel_stack)]
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700289 print("%s %d" % (";".join(line), v.value))
290 else:
291 # print default multi-line stack output
Andrew Birchall1f202e72016-05-05 10:56:40 -0700292 for addr in kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500293 print(" %s" % b.ksym(addr))
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000294 if need_delimiter:
295 print(" --")
Evgeny Vereshchaginf9886442016-06-08 06:06:33 +1000296 for addr in user_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500297 print(" %s" % b.sym(addr, k.tgid))
Rafael F78948e42017-03-26 14:54:25 +0200298 print(" %-16s %s (%d)" % ("-", k.name.decode(), k.pid))
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700299 print(" %d\n" % v.value)
300
301if missing_stacks > 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700302 enomem_str = "" if not has_enomem else \
303 " Consider increasing --stack-storage-size."
304 print("WARNING: %d stack traces could not be displayed.%s" %
305 (missing_stacks, enomem_str),
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700306 file=stderr)