blob: 57e81f44f68663b3dc25e4e3bbaa864f1a7628a7 [file] [log] [blame]
Brendan Greggaf2b46a2016-01-30 11:02:29 -08001#!/usr/bin/python
2#
3# offwaketime Summarize blocked time by kernel off-CPU stack + waker stack
4# For Linux, uses BCC, eBPF.
5#
ceeaspb47cecb62016-11-26 22:36:10 +00006# USAGE: offwaketime [-h] [-p PID | -u | -k] [-U | -K] [-f] [duration]
Brendan Greggaf2b46a2016-01-30 11:02:29 -08007#
8# Copyright 2016 Netflix, Inc.
9# Licensed under the Apache License, Version 2.0 (the "License")
10#
Alexei Starovoitov7583a4e2016-02-03 21:25:43 -080011# 20-Jan-2016 Brendan Gregg Created this.
Brendan Greggaf2b46a2016-01-30 11:02:29 -080012
13from __future__ import print_function
14from bcc import BPF
Alexei Starovoitov7583a4e2016-02-03 21:25:43 -080015from time import sleep
Brendan Greggaf2b46a2016-01-30 11:02:29 -080016import argparse
17import signal
ceeaspb47cecb62016-11-26 22:36:10 +000018import errno
19from sys import stderr
20
21# 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
Brendan Greggaf2b46a2016-01-30 11:02:29 -080037
38# arguments
39examples = """examples:
40 ./offwaketime # trace off-CPU + waker stack time until Ctrl-C
41 ./offwaketime 5 # trace for 5 seconds only
42 ./offwaketime -f 5 # 5 seconds, and output in folded format
ceeaspb47cecb62016-11-26 22:36:10 +000043 ./offwaketime -m 1000 # trace only events that last more than 1000 usec
44 ./offwaketime -M 9000 # trace only events that last less than 9000 usec
45 ./offwaketime -p 185 # only trace threads for PID 185
46 ./offwaketime -t 188 # only trace thread 188
47 ./offwaketime -u # only trace user threads (no kernel)
48 ./offwaketime -k # only trace kernel threads (no user)
49 ./offwaketime -U # only show user space stacks (no kernel)
50 ./offwaketime -K # only show kernel space stacks (no user)
Brendan Greggaf2b46a2016-01-30 11:02:29 -080051"""
52parser = argparse.ArgumentParser(
53 description="Summarize blocked time by kernel stack trace + waker stack",
54 formatter_class=argparse.RawDescriptionHelpFormatter,
55 epilog=examples)
ceeaspb47cecb62016-11-26 22:36:10 +000056thread_group = parser.add_mutually_exclusive_group()
57# 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)
63thread_group.add_argument("-u", "--user-threads-only", action="store_true",
Brendan Greggaf2b46a2016-01-30 11:02:29 -080064 help="user threads only (no kernel threads)")
ceeaspb47cecb62016-11-26 22:36:10 +000065thread_group.add_argument("-k", "--kernel-threads-only", action="store_true",
66 help="kernel threads only (no user threads)")
67stack_group = parser.add_mutually_exclusive_group()
68stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
69 help="show stacks from user space only (no kernel space stacks)")
70stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
71 help="show stacks from kernel space only (no user space stacks)")
72parser.add_argument("-d", "--delimited", action="store_true",
73 help="insert delimiter between kernel/user stacks")
Brendan Greggaf2b46a2016-01-30 11:02:29 -080074parser.add_argument("-f", "--folded", action="store_true",
75 help="output folded format")
ceeaspb47cecb62016-11-26 22:36:10 +000076parser.add_argument("--stack-storage-size", default=1024,
77 type=positive_nonzero_int,
78 help="the number of unique stack traces that can be stored and "
79 "displayed (default 1024)")
Brendan Greggaf2b46a2016-01-30 11:02:29 -080080parser.add_argument("duration", nargs="?", default=99999999,
ceeaspb47cecb62016-11-26 22:36:10 +000081 type=positive_nonzero_int,
Brendan Greggaf2b46a2016-01-30 11:02:29 -080082 help="duration of trace, in seconds")
ceeaspb47cecb62016-11-26 22:36:10 +000083parser.add_argument("-m", "--min-block-time", default=1,
84 type=positive_nonzero_int,
85 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,
88 type=positive_nonzero_int,
89 help="the amount of time in microseconds under which we " +
90 "store traces (default U64_MAX)")
Nathan Scottcf0792f2018-02-02 16:56:50 +110091parser.add_argument("--ebpf", action="store_true",
92 help=argparse.SUPPRESS)
Brendan Greggaf2b46a2016-01-30 11:02:29 -080093args = parser.parse_args()
94folded = args.folded
95duration = int(args.duration)
Brendan Greggaf2b46a2016-01-30 11:02:29 -080096
97# signal handler
98def signal_ignore(signal, frame):
99 print()
100
101# define BPF program
102bpf_text = """
103#include <uapi/linux/ptrace.h>
104#include <linux/sched.h>
105
ceeaspb47cecb62016-11-26 22:36:10 +0000106#define MINBLOCK_US MINBLOCK_US_VALUEULL
107#define MAXBLOCK_US MAXBLOCK_US_VALUEULL
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800108
109struct key_t {
110 char waker[TASK_COMM_LEN];
111 char target[TASK_COMM_LEN];
ceeaspb47cecb62016-11-26 22:36:10 +0000112 int w_k_stack_id;
113 int w_u_stack_id;
114 int t_k_stack_id;
115 int t_u_stack_id;
116 u32 t_pid;
117 u32 w_pid;
118 u32 tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800119};
120BPF_HASH(counts, struct key_t);
121BPF_HASH(start, u32);
122struct wokeby_t {
123 char name[TASK_COMM_LEN];
ceeaspb47cecb62016-11-26 22:36:10 +0000124 int k_stack_id;
125 int u_stack_id;
126 int w_pid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800127};
128BPF_HASH(wokeby, u32, struct wokeby_t);
129
Song Liu67ae6052018-02-01 14:59:24 -0800130BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800131
132int waker(struct pt_regs *ctx, struct task_struct *p) {
133 u32 pid = p->pid;
ceeaspb47cecb62016-11-26 22:36:10 +0000134 u32 tgid = p->tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800135
ceeaspb47cecb62016-11-26 22:36:10 +0000136 if (!(THREAD_FILTER)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800137 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000138 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800139
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800140 struct wokeby_t woke = {};
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800141 bpf_get_current_comm(&woke.name, sizeof(woke.name));
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800142
ceeaspb47cecb62016-11-26 22:36:10 +0000143 woke.k_stack_id = KERNEL_STACK_GET;
144 woke.u_stack_id = USER_STACK_GET;
145 woke.w_pid = pid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800146 wokeby.update(&pid, &woke);
147 return 0;
148}
149
150int oncpu(struct pt_regs *ctx, struct task_struct *p) {
ceeaspb47cecb62016-11-26 22:36:10 +0000151 u32 pid = p->pid, t_pid=pid;
152 u32 tgid = p->tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800153 u64 ts, *tsp;
154
155 // record previous thread sleep time
ceeaspb47cecb62016-11-26 22:36:10 +0000156 if (THREAD_FILTER) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800157 ts = bpf_ktime_get_ns();
158 start.update(&pid, &ts);
159 }
160
161 // calculate current thread's delta time
162 pid = bpf_get_current_pid_tgid();
ceeaspb47cecb62016-11-26 22:36:10 +0000163 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800164 tsp = start.lookup(&pid);
ceeaspb47cecb62016-11-26 22:36:10 +0000165 if (tsp == 0) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800166 return 0; // missed start or filtered
ceeaspb47cecb62016-11-26 22:36:10 +0000167 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800168 u64 delta = bpf_ktime_get_ns() - *tsp;
169 start.delete(&pid);
170 delta = delta / 1000;
ceeaspb47cecb62016-11-26 22:36:10 +0000171 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800172 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000173 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800174
175 // create map key
ceeaspb47cecb62016-11-26 22:36:10 +0000176 u64 zero = 0, *val;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800177 struct key_t key = {};
178 struct wokeby_t *woke;
179 bpf_get_current_comm(&key.target, sizeof(key.target));
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800180
ceeaspb47cecb62016-11-26 22:36:10 +0000181 key.t_k_stack_id = KERNEL_STACK_GET;
182 key.t_u_stack_id = USER_STACK_GET;
183 key.t_pid = t_pid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800184
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800185 woke = wokeby.lookup(&pid);
186 if (woke) {
ceeaspb47cecb62016-11-26 22:36:10 +0000187 key.w_k_stack_id = woke->k_stack_id;
188 key.w_u_stack_id = woke->u_stack_id;
189 key.w_pid = woke->w_pid;
190 key.tgid = tgid;
Alexei Starovoitov7583a4e2016-02-03 21:25:43 -0800191 __builtin_memcpy(&key.waker, woke->name, TASK_COMM_LEN);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800192 wokeby.delete(&pid);
193 }
194
195 val = counts.lookup_or_init(&key, &zero);
196 (*val) += delta;
197 return 0;
198}
199"""
ceeaspb47cecb62016-11-26 22:36:10 +0000200
201# set thread filter
202thread_context = ""
203if args.tgid is not None:
204 thread_context = "PID %d" % args.tgid
205 thread_filter = 'tgid == %d' % args.tgid
206elif args.pid is not None:
207 thread_context = "TID %d" % args.pid
208 thread_filter = 'pid == %d' % args.pid
209elif args.user_threads_only:
210 thread_context = "user threads"
211 thread_filter = '!(p->flags & PF_KTHREAD)'
212elif args.kernel_threads_only:
213 thread_context = "kernel threads"
214 thread_filter = 'p->flags & PF_KTHREAD'
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800215else:
ceeaspb47cecb62016-11-26 22:36:10 +0000216 thread_context = "all threads"
217 thread_filter = '1'
218bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
219
220# set stack storage size
221bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
222bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
223bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
224
225# handle stack args
226kernel_stack_get = "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID)"
227user_stack_get = \
228 "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK)"
229stack_context = ""
230if args.user_stacks_only:
231 stack_context = "user"
232 kernel_stack_get = "-1"
233elif args.kernel_stacks_only:
234 stack_context = "kernel"
235 user_stack_get = "-1"
236else:
237 stack_context = "user + kernel"
238bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
239bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100240if args.ebpf:
241 print(bpf_text)
242 exit()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800243
244# initialize BPF
245b = BPF(text=bpf_text)
246b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
247b.attach_kprobe(event="try_to_wake_up", fn_name="waker")
248matched = b.num_open_kprobes()
249if matched == 0:
250 print("0 functions traced. Exiting.")
251 exit()
252
253# header
254if not folded:
ceeaspb47cecb62016-11-26 22:36:10 +0000255 print("Tracing blocked time (us) by %s off-CPU and waker stack" %
256 stack_context, end="")
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800257 if duration < 99999999:
258 print(" for %d secs." % duration)
259 else:
260 print("... Hit Ctrl-C to end.")
261
ceeaspb47cecb62016-11-26 22:36:10 +0000262# as cleanup can take many seconds, trap Ctrl-C:
263# print a newline for folded output on Ctrl-C
264signal.signal(signal.SIGINT, signal_ignore)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800265
ceeaspb47cecb62016-11-26 22:36:10 +0000266sleep(duration)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800267
ceeaspb47cecb62016-11-26 22:36:10 +0000268if not folded:
269 print()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800270
ceeaspb47cecb62016-11-26 22:36:10 +0000271missing_stacks = 0
272has_enomem = False
273counts = b.get_table("counts")
274stack_traces = b.get_table("stack_traces")
275for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
276 # handle get_stackid errors
277 # check for an ENOMEM error
278 if k.w_k_stack_id == -errno.ENOMEM or \
279 k.t_k_stack_id == -errno.ENOMEM or \
280 k.w_u_stack_id == -errno.ENOMEM or \
281 k.t_u_stack_id == -errno.ENOMEM:
282 missing_stacks += 1
283 continue
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800284
ceeaspb47cecb62016-11-26 22:36:10 +0000285 waker_user_stack = [] if k.w_u_stack_id < 1 else \
286 reversed(list(stack_traces.walk(k.w_u_stack_id))[1:])
287 waker_kernel_stack = [] if k.w_k_stack_id < 1 else \
288 reversed(list(stack_traces.walk(k.w_k_stack_id))[1:])
289 target_user_stack = [] if k.t_u_stack_id < 1 else \
290 stack_traces.walk(k.t_u_stack_id)
291 target_kernel_stack = [] if k.t_k_stack_id < 1 else \
292 stack_traces.walk(k.t_k_stack_id)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800293
ceeaspb47cecb62016-11-26 22:36:10 +0000294 if folded:
295 # print folded stack output
296 line = \
Linuxraptorfabd9a12018-01-19 00:21:17 -0800297 [k.target.decode()] + \
ceeaspb47cecb62016-11-26 22:36:10 +0000298 [b.sym(addr, k.tgid)
299 for addr in reversed(list(target_user_stack)[1:])] + \
300 (["-"] if args.delimited else [""]) + \
301 [b.ksym(addr)
302 for addr in reversed(list(target_kernel_stack)[1:])] + \
303 ["--"] + \
304 [b.ksym(addr)
305 for addr in reversed(list(waker_kernel_stack))] + \
306 (["-"] if args.delimited else [""]) + \
307 [b.sym(addr, k.tgid)
308 for addr in reversed(list(waker_user_stack))] + \
Linuxraptorfabd9a12018-01-19 00:21:17 -0800309 [k.waker.decode()]
ceeaspb47cecb62016-11-26 22:36:10 +0000310 print("%s %d" % (";".join(line), v.value))
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800311
ceeaspb47cecb62016-11-26 22:36:10 +0000312 else:
313 # print wakeup name then stack in reverse order
Rafael F78948e42017-03-26 14:54:25 +0200314 print(" %-16s %s %s" % ("waker:", k.waker.decode(), k.t_pid))
ceeaspb47cecb62016-11-26 22:36:10 +0000315 for addr in waker_user_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500316 print(" %s" % b.sym(addr, k.tgid))
ceeaspb47cecb62016-11-26 22:36:10 +0000317 if args.delimited:
318 print(" -")
319 for addr in waker_kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500320 print(" %s" % b.ksym(addr))
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800321
ceeaspb47cecb62016-11-26 22:36:10 +0000322 # print waker/wakee delimiter
323 print(" %-16s %s" % ("--", "--"))
324
325 # print default multi-line stack output
326 for addr in target_kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500327 print(" %s" % b.ksym(addr))
ceeaspb47cecb62016-11-26 22:36:10 +0000328 if args.delimited:
329 print(" -")
330 for addr in target_user_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500331 print(" %s" % b.sym(addr, k.tgid))
Rafael F78948e42017-03-26 14:54:25 +0200332 print(" %-16s %s %s" % ("target:", k.target.decode(), k.w_pid))
ceeaspb47cecb62016-11-26 22:36:10 +0000333 print(" %d\n" % v.value)
334
335if missing_stacks > 0:
336 enomem_str = " Consider increasing --stack-storage-size."
337 print("WARNING: %d stack traces could not be displayed.%s" %
338 (missing_stacks, enomem_str),
339 file=stderr)