blob: c092e1cfaf973d1d7d67a84e25b264ed66447026 [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;
Teng Qine7432d42018-04-19 14:45:18 -0700117 u32 t_tgid;
ceeaspb47cecb62016-11-26 22:36:10 +0000118 u32 w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700119 u32 w_tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800120};
121BPF_HASH(counts, struct key_t);
Teng Qine7432d42018-04-19 14:45:18 -0700122
123// Key of this hash is PID of waiting Process,
124// value is timestamp when it went into waiting
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800125BPF_HASH(start, u32);
Teng Qine7432d42018-04-19 14:45:18 -0700126
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800127struct wokeby_t {
128 char name[TASK_COMM_LEN];
ceeaspb47cecb62016-11-26 22:36:10 +0000129 int k_stack_id;
130 int u_stack_id;
131 int w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700132 int w_tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800133};
Teng Qine7432d42018-04-19 14:45:18 -0700134// Key of the hash is PID of the Process to be waken, value is information
135// of the Process who wakes it
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800136BPF_HASH(wokeby, u32, struct wokeby_t);
137
Song Liu67ae6052018-02-01 14:59:24 -0800138BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800139
140int waker(struct pt_regs *ctx, struct task_struct *p) {
Teng Qine7432d42018-04-19 14:45:18 -0700141 // PID and TGID of the target Process to be waken
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800142 u32 pid = p->pid;
ceeaspb47cecb62016-11-26 22:36:10 +0000143 u32 tgid = p->tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800144
ceeaspb47cecb62016-11-26 22:36:10 +0000145 if (!(THREAD_FILTER)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800146 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000147 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800148
Teng Qine7432d42018-04-19 14:45:18 -0700149 // Construct information about current (the waker) Process
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800150 struct wokeby_t woke = {};
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800151 bpf_get_current_comm(&woke.name, sizeof(woke.name));
ceeaspb47cecb62016-11-26 22:36:10 +0000152 woke.k_stack_id = KERNEL_STACK_GET;
153 woke.u_stack_id = USER_STACK_GET;
Teng Qine7432d42018-04-19 14:45:18 -0700154 woke.w_pid = bpf_get_current_pid_tgid();
155 woke.w_tgid = bpf_get_current_pid_tgid() >> 32;
156
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800157 wokeby.update(&pid, &woke);
158 return 0;
159}
160
161int oncpu(struct pt_regs *ctx, struct task_struct *p) {
Teng Qine7432d42018-04-19 14:45:18 -0700162 // PID and TGID of the previous Process (Process going into waiting)
163 u32 pid = p->pid;
ceeaspb47cecb62016-11-26 22:36:10 +0000164 u32 tgid = p->tgid;
Teng Qine7432d42018-04-19 14:45:18 -0700165 u64 *tsp;
166 u64 ts = bpf_ktime_get_ns();
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800167
Teng Qine7432d42018-04-19 14:45:18 -0700168 // Record timestamp for the previous Process (Process going into waiting)
ceeaspb47cecb62016-11-26 22:36:10 +0000169 if (THREAD_FILTER) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800170 start.update(&pid, &ts);
171 }
172
Teng Qine7432d42018-04-19 14:45:18 -0700173 // Calculate current Process's wait time by finding the timestamp of when
174 // it went into waiting.
175 // pid and tgid are now the PID and TGID of the current (waking) Process.
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800176 pid = bpf_get_current_pid_tgid();
ceeaspb47cecb62016-11-26 22:36:10 +0000177 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800178 tsp = start.lookup(&pid);
ceeaspb47cecb62016-11-26 22:36:10 +0000179 if (tsp == 0) {
Teng Qine7432d42018-04-19 14:45:18 -0700180 // Missed or filtered when the Process went into waiting
181 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000182 }
Teng Qine7432d42018-04-19 14:45:18 -0700183 u64 delta = ts - *tsp;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800184 start.delete(&pid);
185 delta = delta / 1000;
ceeaspb47cecb62016-11-26 22:36:10 +0000186 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800187 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000188 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800189
190 // create map key
ceeaspb47cecb62016-11-26 22:36:10 +0000191 u64 zero = 0, *val;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800192 struct key_t key = {};
193 struct wokeby_t *woke;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800194
Teng Qine7432d42018-04-19 14:45:18 -0700195 bpf_get_current_comm(&key.target, sizeof(key.target));
196 key.t_pid = pid;
197 key.t_tgid = tgid;
ceeaspb47cecb62016-11-26 22:36:10 +0000198 key.t_k_stack_id = KERNEL_STACK_GET;
199 key.t_u_stack_id = USER_STACK_GET;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800200
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800201 woke = wokeby.lookup(&pid);
202 if (woke) {
ceeaspb47cecb62016-11-26 22:36:10 +0000203 key.w_k_stack_id = woke->k_stack_id;
204 key.w_u_stack_id = woke->u_stack_id;
205 key.w_pid = woke->w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700206 key.w_tgid = woke->w_tgid;
Alexei Starovoitov7583a4e2016-02-03 21:25:43 -0800207 __builtin_memcpy(&key.waker, woke->name, TASK_COMM_LEN);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800208 wokeby.delete(&pid);
209 }
210
211 val = counts.lookup_or_init(&key, &zero);
212 (*val) += delta;
213 return 0;
214}
215"""
ceeaspb47cecb62016-11-26 22:36:10 +0000216
217# set thread filter
218thread_context = ""
219if args.tgid is not None:
220 thread_context = "PID %d" % args.tgid
221 thread_filter = 'tgid == %d' % args.tgid
222elif args.pid is not None:
223 thread_context = "TID %d" % args.pid
224 thread_filter = 'pid == %d' % args.pid
225elif args.user_threads_only:
226 thread_context = "user threads"
227 thread_filter = '!(p->flags & PF_KTHREAD)'
228elif args.kernel_threads_only:
229 thread_context = "kernel threads"
230 thread_filter = 'p->flags & PF_KTHREAD'
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800231else:
ceeaspb47cecb62016-11-26 22:36:10 +0000232 thread_context = "all threads"
233 thread_filter = '1'
234bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
235
236# set stack storage size
237bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
238bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
239bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
240
241# handle stack args
242kernel_stack_get = "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID)"
243user_stack_get = \
244 "stack_traces.get_stackid(ctx, BPF_F_REUSE_STACKID | BPF_F_USER_STACK)"
245stack_context = ""
246if args.user_stacks_only:
247 stack_context = "user"
248 kernel_stack_get = "-1"
249elif args.kernel_stacks_only:
250 stack_context = "kernel"
251 user_stack_get = "-1"
252else:
253 stack_context = "user + kernel"
254bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
255bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100256if args.ebpf:
257 print(bpf_text)
258 exit()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800259
260# initialize BPF
261b = BPF(text=bpf_text)
262b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
263b.attach_kprobe(event="try_to_wake_up", fn_name="waker")
264matched = b.num_open_kprobes()
265if matched == 0:
266 print("0 functions traced. Exiting.")
267 exit()
268
269# header
270if not folded:
ceeaspb47cecb62016-11-26 22:36:10 +0000271 print("Tracing blocked time (us) by %s off-CPU and waker stack" %
272 stack_context, end="")
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800273 if duration < 99999999:
274 print(" for %d secs." % duration)
275 else:
276 print("... Hit Ctrl-C to end.")
277
ceeaspb47cecb62016-11-26 22:36:10 +0000278# as cleanup can take many seconds, trap Ctrl-C:
279# print a newline for folded output on Ctrl-C
280signal.signal(signal.SIGINT, signal_ignore)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800281
ceeaspb47cecb62016-11-26 22:36:10 +0000282sleep(duration)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800283
ceeaspb47cecb62016-11-26 22:36:10 +0000284if not folded:
285 print()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800286
ceeaspb47cecb62016-11-26 22:36:10 +0000287missing_stacks = 0
288has_enomem = False
289counts = b.get_table("counts")
290stack_traces = b.get_table("stack_traces")
291for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
292 # handle get_stackid errors
293 # check for an ENOMEM error
294 if k.w_k_stack_id == -errno.ENOMEM or \
295 k.t_k_stack_id == -errno.ENOMEM or \
296 k.w_u_stack_id == -errno.ENOMEM or \
297 k.t_u_stack_id == -errno.ENOMEM:
298 missing_stacks += 1
299 continue
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800300
ceeaspb47cecb62016-11-26 22:36:10 +0000301 waker_user_stack = [] if k.w_u_stack_id < 1 else \
302 reversed(list(stack_traces.walk(k.w_u_stack_id))[1:])
303 waker_kernel_stack = [] if k.w_k_stack_id < 1 else \
304 reversed(list(stack_traces.walk(k.w_k_stack_id))[1:])
305 target_user_stack = [] if k.t_u_stack_id < 1 else \
306 stack_traces.walk(k.t_u_stack_id)
307 target_kernel_stack = [] if k.t_k_stack_id < 1 else \
308 stack_traces.walk(k.t_k_stack_id)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800309
ceeaspb47cecb62016-11-26 22:36:10 +0000310 if folded:
311 # print folded stack output
312 line = \
Linuxraptorfabd9a12018-01-19 00:21:17 -0800313 [k.target.decode()] + \
Teng Qine7432d42018-04-19 14:45:18 -0700314 [b.sym(addr, k.t_tgid)
ceeaspb47cecb62016-11-26 22:36:10 +0000315 for addr in reversed(list(target_user_stack)[1:])] + \
316 (["-"] if args.delimited else [""]) + \
317 [b.ksym(addr)
318 for addr in reversed(list(target_kernel_stack)[1:])] + \
319 ["--"] + \
320 [b.ksym(addr)
321 for addr in reversed(list(waker_kernel_stack))] + \
322 (["-"] if args.delimited else [""]) + \
Teng Qine7432d42018-04-19 14:45:18 -0700323 [b.sym(addr, k.w_tgid)
ceeaspb47cecb62016-11-26 22:36:10 +0000324 for addr in reversed(list(waker_user_stack))] + \
Linuxraptorfabd9a12018-01-19 00:21:17 -0800325 [k.waker.decode()]
ceeaspb47cecb62016-11-26 22:36:10 +0000326 print("%s %d" % (";".join(line), v.value))
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800327
ceeaspb47cecb62016-11-26 22:36:10 +0000328 else:
329 # print wakeup name then stack in reverse order
Rafael F78948e42017-03-26 14:54:25 +0200330 print(" %-16s %s %s" % ("waker:", k.waker.decode(), k.t_pid))
ceeaspb47cecb62016-11-26 22:36:10 +0000331 for addr in waker_user_stack:
Teng Qine7432d42018-04-19 14:45:18 -0700332 print(" %s" % b.sym(addr, k.w_tgid))
ceeaspb47cecb62016-11-26 22:36:10 +0000333 if args.delimited:
334 print(" -")
335 for addr in waker_kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500336 print(" %s" % b.ksym(addr))
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800337
ceeaspb47cecb62016-11-26 22:36:10 +0000338 # print waker/wakee delimiter
339 print(" %-16s %s" % ("--", "--"))
340
341 # print default multi-line stack output
342 for addr in target_kernel_stack:
Sasha Goldshtein2f780682017-02-09 00:20:56 -0500343 print(" %s" % b.ksym(addr))
ceeaspb47cecb62016-11-26 22:36:10 +0000344 if args.delimited:
345 print(" -")
346 for addr in target_user_stack:
Teng Qine7432d42018-04-19 14:45:18 -0700347 print(" %s" % b.sym(addr, k.t_tgid))
Rafael F78948e42017-03-26 14:54:25 +0200348 print(" %-16s %s %s" % ("target:", k.target.decode(), k.w_pid))
ceeaspb47cecb62016-11-26 22:36:10 +0000349 print(" %d\n" % v.value)
350
351if missing_stacks > 0:
352 enomem_str = " Consider increasing --stack-storage-size."
353 print("WARNING: %d stack traces could not be displayed.%s" %
354 (missing_stacks, enomem_str),
355 file=stderr)