blob: 1f47459f8fc9cde1ffddc3cc7e79c197e6780ea0 [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")
Brendan Gregg38cef482016-01-15 17:26:30 -080094args = parser.parse_args()
Mark Drayton66bf2e82016-07-31 22:47:07 +010095if args.pid and args.tgid:
96 parser.error("specify only one of -p and -t")
Brendan Gregg38cef482016-01-15 17:26:30 -080097folded = args.folded
98duration = int(args.duration)
Brendan Gregg843340d2017-07-31 18:39:30 -070099debug = 0
Brendan Gregg38cef482016-01-15 17:26:30 -0800100
101# signal handler
102def signal_ignore(signal, frame):
103 print()
104
Brendan Greggd364d042016-01-19 17:12:52 -0800105# define BPF program
Brendan Gregg38cef482016-01-15 17:26:30 -0800106bpf_text = """
107#include <uapi/linux/ptrace.h>
108#include <linux/sched.h>
109
Glauber Costa52464582016-09-26 12:59:32 -0700110#define MINBLOCK_US MINBLOCK_US_VALUEULL
111#define MAXBLOCK_US MAXBLOCK_US_VALUEULL
Brendan Gregg38cef482016-01-15 17:26:30 -0800112
113struct key_t {
Andrew Birchall1f202e72016-05-05 10:56:40 -0700114 u32 pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100115 u32 tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700116 int user_stack_id;
117 int kernel_stack_id;
Brendan Gregg38cef482016-01-15 17:26:30 -0800118 char name[TASK_COMM_LEN];
Brendan Gregg38cef482016-01-15 17:26:30 -0800119};
120BPF_HASH(counts, struct key_t);
121BPF_HASH(start, u32);
Andrew Birchall47d871f2016-05-11 18:31:49 -0700122BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE)
Brendan Gregg38cef482016-01-15 17:26:30 -0800123
Brendan Greggd364d042016-01-19 17:12:52 -0800124int oncpu(struct pt_regs *ctx, struct task_struct *prev) {
Evgeny Vereshchagin9858ca52016-05-27 06:13:52 +0000125 u32 pid = prev->pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100126 u32 tgid = prev->tgid;
Brendan Greggd364d042016-01-19 17:12:52 -0800127 u64 ts, *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800128
Brendan Greggd364d042016-01-19 17:12:52 -0800129 // record previous thread sleep time
Brendan Gregg843340d2017-07-31 18:39:30 -0700130 if ((THREAD_FILTER) && (STATE_FILTER)) {
Brendan Greggd364d042016-01-19 17:12:52 -0800131 ts = bpf_ktime_get_ns();
132 start.update(&pid, &ts);
133 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800134
Andrew Birchall1f202e72016-05-05 10:56:40 -0700135 // get the current thread's start time
Brendan Greggd364d042016-01-19 17:12:52 -0800136 pid = bpf_get_current_pid_tgid();
Mark Drayton66bf2e82016-07-31 22:47:07 +0100137 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg38cef482016-01-15 17:26:30 -0800138 tsp = start.lookup(&pid);
Andrew Birchall1f202e72016-05-05 10:56:40 -0700139 if (tsp == 0) {
Brendan Greggf7471142016-01-19 14:40:41 -0800140 return 0; // missed start or filtered
Andrew Birchall1f202e72016-05-05 10:56:40 -0700141 }
142
143 // calculate current thread's delta time
Brendan Greggf7471142016-01-19 14:40:41 -0800144 u64 delta = bpf_ktime_get_ns() - *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800145 start.delete(&pid);
146 delta = delta / 1000;
Glauber Costa52464582016-09-26 12:59:32 -0700147 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Gregg38cef482016-01-15 17:26:30 -0800148 return 0;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700149 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800150
Brendan Greggf7471142016-01-19 14:40:41 -0800151 // create map key
Vicent Martie82fb1b2016-03-25 17:21:44 +0100152 u64 zero = 0, *val;
Brendan Greggf7471142016-01-19 14:40:41 -0800153 struct key_t key = {};
Vicent Martie82fb1b2016-03-25 17:21:44 +0100154
Andrew Birchall1f202e72016-05-05 10:56:40 -0700155 key.pid = pid;
Mark Drayton66bf2e82016-07-31 22:47:07 +0100156 key.tgid = tgid;
Andrew Birchall1f202e72016-05-05 10:56:40 -0700157 key.user_stack_id = USER_STACK_GET;
158 key.kernel_stack_id = KERNEL_STACK_GET;
Brendan Gregg38cef482016-01-15 17:26:30 -0800159 bpf_get_current_comm(&key.name, sizeof(key.name));
Brendan Gregg38cef482016-01-15 17:26:30 -0800160
Brendan Gregg38cef482016-01-15 17:26:30 -0800161 val = counts.lookup_or_init(&key, &zero);
162 (*val) += delta;
163 return 0;
164}
165"""
Andrew Birchall47d871f2016-05-11 18:31:49 -0700166
167# set thread filter
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700168thread_context = ""
Mark Drayton66bf2e82016-07-31 22:47:07 +0100169if args.tgid is not None:
170 thread_context = "PID %d" % args.tgid
171 thread_filter = 'tgid == %d' % args.tgid
172elif args.pid is not None:
173 thread_context = "TID %d" % args.pid
174 thread_filter = 'pid == %d' % args.pid
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700175elif args.user_threads_only:
176 thread_context = "user threads"
177 thread_filter = '!(prev->flags & PF_KTHREAD)'
178elif args.kernel_threads_only:
179 thread_context = "kernel threads"
180 thread_filter = 'prev->flags & PF_KTHREAD'
Brendan Gregg38cef482016-01-15 17:26:30 -0800181else:
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700182 thread_context = "all threads"
183 thread_filter = '1'
Brendan Gregg843340d2017-07-31 18:39:30 -0700184if args.state == 0:
185 state_filter = 'prev->state == 0'
Brendan Gregg48708192017-08-03 11:49:27 -0700186elif args.state:
Brendan Gregg843340d2017-07-31 18:39:30 -0700187 # these states are sometimes bitmask checked
188 state_filter = 'prev->state & %d' % args.state
189else:
190 state_filter = '1'
Andrew Birchall582b5dd2016-05-04 16:03:34 -0700191bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
Brendan Gregg843340d2017-07-31 18:39:30 -0700192bpf_text = bpf_text.replace('STATE_FILTER', state_filter)
Andrew Birchall47d871f2016-05-11 18:31:49 -0700193
194# set stack storage size
195bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
Glauber Costa52464582016-09-26 12:59:32 -0700196bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
197bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
Brendan Greggd364d042016-01-19 17:12:52 -0800198
Andrew Birchall1f202e72016-05-05 10:56:40 -0700199# handle stack args
200kernel_stack_get = "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID)"
201user_stack_get = \
202 "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK)"
203stack_context = ""
204if args.user_stacks_only:
205 stack_context = "user"
206 kernel_stack_get = "-1"
207elif args.kernel_stacks_only:
208 stack_context = "kernel"
209 user_stack_get = "-1"
210else:
211 stack_context = "user + kernel"
212bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
213bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
214
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300215need_delimiter = args.delimited and not (args.kernel_stacks_only or
216 args.user_stacks_only)
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000217
Andrew Birchall1f202e72016-05-05 10:56:40 -0700218# check for an edge case; the code below will handle this case correctly
219# but ultimately nothing will be displayed
220if args.kernel_threads_only and args.user_stacks_only:
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300221 print("ERROR: Displaying user stacks for kernel threads " +
222 "doesn't make sense.", file=stderr)
Andrew Birchall1f202e72016-05-05 10:56:40 -0700223 exit(1)
224
Brendan Gregg843340d2017-07-31 18:39:30 -0700225if (debug):
226 print(bpf_text)
227
Brendan Greggd364d042016-01-19 17:12:52 -0800228# initialize BPF
Brendan Gregg38cef482016-01-15 17:26:30 -0800229b = BPF(text=bpf_text)
Brendan Gregg38cef482016-01-15 17:26:30 -0800230b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
231matched = b.num_open_kprobes()
232if matched == 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700233 print("error: 0 functions traced. Exiting.", file=stderr)
234 exit(1)
Brendan Gregg38cef482016-01-15 17:26:30 -0800235
236# header
237if not folded:
Andrew Birchall1f202e72016-05-05 10:56:40 -0700238 print("Tracing off-CPU time (us) of %s by %s stack" %
239 (thread_context, stack_context), end="")
Brendan Gregg38cef482016-01-15 17:26:30 -0800240 if duration < 99999999:
241 print(" for %d secs." % duration)
242 else:
243 print("... Hit Ctrl-C to end.")
244
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700245try:
246 sleep(duration)
247except KeyboardInterrupt:
248 # as cleanup can take many seconds, trap Ctrl-C:
249 signal.signal(signal.SIGINT, signal_ignore)
Brendan Gregg38cef482016-01-15 17:26:30 -0800250
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700251if not folded:
252 print()
Brendan Gregg38cef482016-01-15 17:26:30 -0800253
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700254missing_stacks = 0
Andrew Birchall47d871f2016-05-11 18:31:49 -0700255has_enomem = False
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700256counts = b.get_table("counts")
257stack_traces = b.get_table("stack_traces")
258for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
Andrew Birchall47d871f2016-05-11 18:31:49 -0700259 # handle get_stackid erorrs
Andrew Birchall1f202e72016-05-05 10:56:40 -0700260 if (not args.user_stacks_only and k.kernel_stack_id < 0) or \
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300261 (not args.kernel_stacks_only and k.user_stack_id < 0 and
262 k.user_stack_id != -errno.EFAULT):
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700263 missing_stacks += 1
Andrew Birchall47d871f2016-05-11 18:31:49 -0700264 # check for an ENOMEM error
Teng Qin0b11d222016-07-18 13:21:10 -0700265 if k.kernel_stack_id == -errno.ENOMEM or \
266 k.user_stack_id == -errno.ENOMEM:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700267 has_enomem = True
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700268 continue
269
Mark Drayton66bf2e82016-07-31 22:47:07 +0100270 # user stacks will be symbolized by tgid, not pid, to avoid the overhead
271 # of one symbol resolver per thread
Andrew Birchall1f202e72016-05-05 10:56:40 -0700272 user_stack = [] if k.user_stack_id < 0 else \
273 stack_traces.walk(k.user_stack_id)
274 kernel_stack = [] if k.kernel_stack_id < 0 else \
275 stack_traces.walk(k.kernel_stack_id)
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700276
277 if folded:
278 # print folded stack output
Evgeny Vereshchaginff39d0c2016-06-07 18:00:01 +1000279 user_stack = list(user_stack)
280 kernel_stack = list(kernel_stack)
Andrew Birchall1f202e72016-05-05 10:56:40 -0700281 line = [k.name.decode()] + \
Mark Drayton66bf2e82016-07-31 22:47:07 +0100282 [b.sym(addr, k.tgid) for addr in reversed(user_stack)] + \
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000283 (need_delimiter and ["-"] or []) + \
Evgeny Vereshchaginf9886442016-06-08 06:06:33 +1000284 [b.ksym(addr) for addr in reversed(kernel_stack)]
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700285 print("%s %d" % (";".join(line), v.value))
286 else:
287 # print default multi-line stack output
Andrew Birchall1f202e72016-05-05 10:56:40 -0700288 for addr in kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500289 print(" %s" % b.ksym(addr))
Evgeny Vereshchagin4509f092016-06-08 06:33:54 +1000290 if need_delimiter:
291 print(" --")
Evgeny Vereshchaginf9886442016-06-08 06:06:33 +1000292 for addr in user_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500293 print(" %s" % b.sym(addr, k.tgid))
Rafael F78948e42017-03-26 14:54:25 +0200294 print(" %-16s %s (%d)" % ("-", k.name.decode(), k.pid))
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700295 print(" %d\n" % v.value)
296
297if missing_stacks > 0:
Andrew Birchall47d871f2016-05-11 18:31:49 -0700298 enomem_str = "" if not has_enomem else \
299 " Consider increasing --stack-storage-size."
300 print("WARNING: %d stack traces could not be displayed.%s" %
301 (missing_stacks, enomem_str),
Andrew Birchallee7e5b42016-05-03 16:54:00 -0700302 file=stderr)