blob: 01961ee7fa9733c00c9479870285fb8d4fa6a99e [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
Teng Qine778db02018-04-24 16:11:49 -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 Greggaf2b46a2016-01-30 11:02:29 -080043# arguments
44examples = """examples:
45 ./offwaketime # trace off-CPU + waker stack time until Ctrl-C
46 ./offwaketime 5 # trace for 5 seconds only
47 ./offwaketime -f 5 # 5 seconds, and output in folded format
ceeaspb47cecb62016-11-26 22:36:10 +000048 ./offwaketime -m 1000 # trace only events that last more than 1000 usec
49 ./offwaketime -M 9000 # trace only events that last less than 9000 usec
50 ./offwaketime -p 185 # only trace threads for PID 185
51 ./offwaketime -t 188 # only trace thread 188
52 ./offwaketime -u # only trace user threads (no kernel)
53 ./offwaketime -k # only trace kernel threads (no user)
54 ./offwaketime -U # only show user space stacks (no kernel)
55 ./offwaketime -K # only show kernel space stacks (no user)
Brendan Greggaf2b46a2016-01-30 11:02:29 -080056"""
57parser = argparse.ArgumentParser(
58 description="Summarize blocked time by kernel stack trace + waker stack",
59 formatter_class=argparse.RawDescriptionHelpFormatter,
60 epilog=examples)
ceeaspb47cecb62016-11-26 22:36:10 +000061thread_group = parser.add_mutually_exclusive_group()
62# 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)
68thread_group.add_argument("-u", "--user-threads-only", action="store_true",
Brendan Greggaf2b46a2016-01-30 11:02:29 -080069 help="user threads only (no kernel threads)")
ceeaspb47cecb62016-11-26 22:36:10 +000070thread_group.add_argument("-k", "--kernel-threads-only", action="store_true",
71 help="kernel threads only (no user threads)")
72stack_group = parser.add_mutually_exclusive_group()
73stack_group.add_argument("-U", "--user-stacks-only", action="store_true",
74 help="show stacks from user space only (no kernel space stacks)")
75stack_group.add_argument("-K", "--kernel-stacks-only", action="store_true",
76 help="show stacks from kernel space only (no user space stacks)")
77parser.add_argument("-d", "--delimited", action="store_true",
78 help="insert delimiter between kernel/user stacks")
Brendan Greggaf2b46a2016-01-30 11:02:29 -080079parser.add_argument("-f", "--folded", action="store_true",
80 help="output folded format")
ceeaspb47cecb62016-11-26 22:36:10 +000081parser.add_argument("--stack-storage-size", default=1024,
82 type=positive_nonzero_int,
83 help="the number of unique stack traces that can be stored and "
84 "displayed (default 1024)")
Brendan Greggaf2b46a2016-01-30 11:02:29 -080085parser.add_argument("duration", nargs="?", default=99999999,
ceeaspb47cecb62016-11-26 22:36:10 +000086 type=positive_nonzero_int,
Brendan Greggaf2b46a2016-01-30 11:02:29 -080087 help="duration of trace, in seconds")
ceeaspb47cecb62016-11-26 22:36:10 +000088parser.add_argument("-m", "--min-block-time", default=1,
89 type=positive_nonzero_int,
90 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,
93 type=positive_nonzero_int,
94 help="the amount of time in microseconds under which we " +
95 "store traces (default U64_MAX)")
Nathan Scottcf0792f2018-02-02 16:56:50 +110096parser.add_argument("--ebpf", action="store_true",
97 help=argparse.SUPPRESS)
Brendan Greggaf2b46a2016-01-30 11:02:29 -080098args = parser.parse_args()
99folded = args.folded
100duration = int(args.duration)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800101
102# signal handler
103def signal_ignore(signal, frame):
104 print()
105
106# define BPF program
107bpf_text = """
108#include <uapi/linux/ptrace.h>
109#include <linux/sched.h>
110
ceeaspb47cecb62016-11-26 22:36:10 +0000111#define MINBLOCK_US MINBLOCK_US_VALUEULL
112#define MAXBLOCK_US MAXBLOCK_US_VALUEULL
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800113
114struct key_t {
115 char waker[TASK_COMM_LEN];
116 char target[TASK_COMM_LEN];
ceeaspb47cecb62016-11-26 22:36:10 +0000117 int w_k_stack_id;
118 int w_u_stack_id;
119 int t_k_stack_id;
120 int t_u_stack_id;
121 u32 t_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700122 u32 t_tgid;
ceeaspb47cecb62016-11-26 22:36:10 +0000123 u32 w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700124 u32 w_tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800125};
126BPF_HASH(counts, struct key_t);
Teng Qine7432d42018-04-19 14:45:18 -0700127
128// Key of this hash is PID of waiting Process,
129// value is timestamp when it went into waiting
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800130BPF_HASH(start, u32);
Teng Qine7432d42018-04-19 14:45:18 -0700131
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800132struct wokeby_t {
133 char name[TASK_COMM_LEN];
ceeaspb47cecb62016-11-26 22:36:10 +0000134 int k_stack_id;
135 int u_stack_id;
136 int w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700137 int w_tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800138};
Teng Qine7432d42018-04-19 14:45:18 -0700139// Key of the hash is PID of the Process to be waken, value is information
140// of the Process who wakes it
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800141BPF_HASH(wokeby, u32, struct wokeby_t);
142
Song Liu67ae6052018-02-01 14:59:24 -0800143BPF_STACK_TRACE(stack_traces, STACK_STORAGE_SIZE);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800144
145int waker(struct pt_regs *ctx, struct task_struct *p) {
Teng Qine7432d42018-04-19 14:45:18 -0700146 // PID and TGID of the target Process to be waken
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800147 u32 pid = p->pid;
ceeaspb47cecb62016-11-26 22:36:10 +0000148 u32 tgid = p->tgid;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800149
ceeaspb47cecb62016-11-26 22:36:10 +0000150 if (!(THREAD_FILTER)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800151 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000152 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800153
Teng Qine7432d42018-04-19 14:45:18 -0700154 // Construct information about current (the waker) Process
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800155 struct wokeby_t woke = {};
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800156 bpf_get_current_comm(&woke.name, sizeof(woke.name));
ceeaspb47cecb62016-11-26 22:36:10 +0000157 woke.k_stack_id = KERNEL_STACK_GET;
158 woke.u_stack_id = USER_STACK_GET;
Teng Qine7432d42018-04-19 14:45:18 -0700159 woke.w_pid = bpf_get_current_pid_tgid();
160 woke.w_tgid = bpf_get_current_pid_tgid() >> 32;
161
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800162 wokeby.update(&pid, &woke);
163 return 0;
164}
165
166int oncpu(struct pt_regs *ctx, struct task_struct *p) {
Teng Qine7432d42018-04-19 14:45:18 -0700167 // PID and TGID of the previous Process (Process going into waiting)
168 u32 pid = p->pid;
ceeaspb47cecb62016-11-26 22:36:10 +0000169 u32 tgid = p->tgid;
Teng Qine7432d42018-04-19 14:45:18 -0700170 u64 *tsp;
171 u64 ts = bpf_ktime_get_ns();
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800172
Teng Qine7432d42018-04-19 14:45:18 -0700173 // Record timestamp for the previous Process (Process going into waiting)
ceeaspb47cecb62016-11-26 22:36:10 +0000174 if (THREAD_FILTER) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800175 start.update(&pid, &ts);
176 }
177
Teng Qine7432d42018-04-19 14:45:18 -0700178 // Calculate current Process's wait time by finding the timestamp of when
179 // it went into waiting.
180 // pid and tgid are now the PID and TGID of the current (waking) Process.
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800181 pid = bpf_get_current_pid_tgid();
ceeaspb47cecb62016-11-26 22:36:10 +0000182 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800183 tsp = start.lookup(&pid);
ceeaspb47cecb62016-11-26 22:36:10 +0000184 if (tsp == 0) {
Teng Qine7432d42018-04-19 14:45:18 -0700185 // Missed or filtered when the Process went into waiting
186 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000187 }
Teng Qine7432d42018-04-19 14:45:18 -0700188 u64 delta = ts - *tsp;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800189 start.delete(&pid);
190 delta = delta / 1000;
ceeaspb47cecb62016-11-26 22:36:10 +0000191 if ((delta < MINBLOCK_US) || (delta > MAXBLOCK_US)) {
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800192 return 0;
ceeaspb47cecb62016-11-26 22:36:10 +0000193 }
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800194
195 // create map key
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800196 struct key_t key = {};
197 struct wokeby_t *woke;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800198
Teng Qine7432d42018-04-19 14:45:18 -0700199 bpf_get_current_comm(&key.target, sizeof(key.target));
200 key.t_pid = pid;
201 key.t_tgid = tgid;
ceeaspb47cecb62016-11-26 22:36:10 +0000202 key.t_k_stack_id = KERNEL_STACK_GET;
203 key.t_u_stack_id = USER_STACK_GET;
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800204
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800205 woke = wokeby.lookup(&pid);
206 if (woke) {
ceeaspb47cecb62016-11-26 22:36:10 +0000207 key.w_k_stack_id = woke->k_stack_id;
208 key.w_u_stack_id = woke->u_stack_id;
209 key.w_pid = woke->w_pid;
Teng Qine7432d42018-04-19 14:45:18 -0700210 key.w_tgid = woke->w_tgid;
Alexei Starovoitov7583a4e2016-02-03 21:25:43 -0800211 __builtin_memcpy(&key.waker, woke->name, TASK_COMM_LEN);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800212 wokeby.delete(&pid);
213 }
214
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200215 counts.increment(key, delta);
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800216 return 0;
217}
218"""
ceeaspb47cecb62016-11-26 22:36:10 +0000219
220# set thread filter
221thread_context = ""
222if args.tgid is not None:
223 thread_context = "PID %d" % args.tgid
224 thread_filter = 'tgid == %d' % args.tgid
225elif args.pid is not None:
226 thread_context = "TID %d" % args.pid
227 thread_filter = 'pid == %d' % args.pid
228elif args.user_threads_only:
229 thread_context = "user threads"
230 thread_filter = '!(p->flags & PF_KTHREAD)'
231elif args.kernel_threads_only:
232 thread_context = "kernel threads"
233 thread_filter = 'p->flags & PF_KTHREAD'
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800234else:
ceeaspb47cecb62016-11-26 22:36:10 +0000235 thread_context = "all threads"
236 thread_filter = '1'
237bpf_text = bpf_text.replace('THREAD_FILTER', thread_filter)
238
239# set stack storage size
240bpf_text = bpf_text.replace('STACK_STORAGE_SIZE', str(args.stack_storage_size))
241bpf_text = bpf_text.replace('MINBLOCK_US_VALUE', str(args.min_block_time))
242bpf_text = bpf_text.replace('MAXBLOCK_US_VALUE', str(args.max_block_time))
243
244# handle stack args
Teng Qine778db02018-04-24 16:11:49 -0700245kernel_stack_get = "stack_traces.get_stackid(ctx, 0)"
246user_stack_get = "stack_traces.get_stackid(ctx, BPF_F_USER_STACK)"
ceeaspb47cecb62016-11-26 22:36:10 +0000247stack_context = ""
248if args.user_stacks_only:
249 stack_context = "user"
250 kernel_stack_get = "-1"
251elif args.kernel_stacks_only:
252 stack_context = "kernel"
253 user_stack_get = "-1"
254else:
255 stack_context = "user + kernel"
256bpf_text = bpf_text.replace('USER_STACK_GET', user_stack_get)
257bpf_text = bpf_text.replace('KERNEL_STACK_GET', kernel_stack_get)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100258if args.ebpf:
259 print(bpf_text)
260 exit()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800261
262# initialize BPF
263b = BPF(text=bpf_text)
264b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
265b.attach_kprobe(event="try_to_wake_up", fn_name="waker")
266matched = b.num_open_kprobes()
267if matched == 0:
268 print("0 functions traced. Exiting.")
269 exit()
270
271# header
272if not folded:
ceeaspb47cecb62016-11-26 22:36:10 +0000273 print("Tracing blocked time (us) by %s off-CPU and waker stack" %
274 stack_context, end="")
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800275 if duration < 99999999:
276 print(" for %d secs." % duration)
277 else:
278 print("... Hit Ctrl-C to end.")
279
ceeaspb47cecb62016-11-26 22:36:10 +0000280# as cleanup can take many seconds, trap Ctrl-C:
281# print a newline for folded output on Ctrl-C
282signal.signal(signal.SIGINT, signal_ignore)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800283
ceeaspb47cecb62016-11-26 22:36:10 +0000284sleep(duration)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800285
ceeaspb47cecb62016-11-26 22:36:10 +0000286if not folded:
287 print()
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800288
ceeaspb47cecb62016-11-26 22:36:10 +0000289missing_stacks = 0
290has_enomem = False
291counts = b.get_table("counts")
292stack_traces = b.get_table("stack_traces")
Teng Qine778db02018-04-24 16:11:49 -0700293need_delimiter = args.delimited and not (args.kernel_stacks_only or
294 args.user_stacks_only)
ceeaspb47cecb62016-11-26 22:36:10 +0000295for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
296 # handle get_stackid errors
Teng Qine778db02018-04-24 16:11:49 -0700297 if not args.user_stacks_only:
298 missing_stacks += int(stack_id_err(k.w_k_stack_id))
299 missing_stacks += int(stack_id_err(k.t_k_stack_id))
300 has_enomem = has_enomem or (k.w_k_stack_id == -errno.ENOMEM) or \
301 (k.t_k_stack_id == -errno.ENOMEM)
302 if not args.kernel_stacks_only:
303 missing_stacks += int(stack_id_err(k.w_u_stack_id))
304 missing_stacks += int(stack_id_err(k.t_u_stack_id))
305 has_enomem = has_enomem or (k.w_u_stack_id == -errno.ENOMEM) or \
306 (k.t_u_stack_id == -errno.ENOMEM)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800307
ceeaspb47cecb62016-11-26 22:36:10 +0000308 waker_user_stack = [] if k.w_u_stack_id < 1 else \
309 reversed(list(stack_traces.walk(k.w_u_stack_id))[1:])
310 waker_kernel_stack = [] if k.w_k_stack_id < 1 else \
311 reversed(list(stack_traces.walk(k.w_k_stack_id))[1:])
312 target_user_stack = [] if k.t_u_stack_id < 1 else \
313 stack_traces.walk(k.t_u_stack_id)
314 target_kernel_stack = [] if k.t_k_stack_id < 1 else \
315 stack_traces.walk(k.t_k_stack_id)
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800316
ceeaspb47cecb62016-11-26 22:36:10 +0000317 if folded:
318 # print folded stack output
Teng Qine778db02018-04-24 16:11:49 -0700319 line = [k.target.decode()]
320 if not args.kernel_stacks_only:
321 if stack_id_err(k.t_u_stack_id):
322 line.append("[Missed User Stack]")
323 else:
324 line.extend([b.sym(addr, k.t_tgid)
325 for addr in reversed(list(target_user_stack)[1:])])
326 if not args.user_stacks_only:
327 line.extend(["-"] if (need_delimiter and k.t_k_stack_id > 0 and k.t_u_stack_id > 0) else [])
328 if stack_id_err(k.t_k_stack_id):
329 line.append("[Missed Kernel Stack]")
330 else:
331 line.extend([b.ksym(addr)
332 for addr in reversed(list(target_kernel_stack)[1:])])
333 line.append("--")
334 if not args.user_stacks_only:
335 if stack_id_err(k.w_k_stack_id):
336 line.append("[Missed Kernel Stack]")
337 else:
338 line.extend([b.ksym(addr)
339 for addr in reversed(list(waker_kernel_stack))])
340 if not args.kernel_stacks_only:
341 line.extend(["-"] if (need_delimiter and k.w_u_stack_id > 0 and k.w_k_stack_id > 0) else [])
342 if stack_id_err(k.w_u_stack_id):
343 line.extend("[Missed User Stack]")
344 else:
345 line.extend([b.sym(addr, k.w_tgid)
346 for addr in reversed(list(waker_user_stack))])
347 line.append(k.waker.decode())
ceeaspb47cecb62016-11-26 22:36:10 +0000348 print("%s %d" % (";".join(line), v.value))
ceeaspb47cecb62016-11-26 22:36:10 +0000349 else:
350 # print wakeup name then stack in reverse order
Rafael F78948e42017-03-26 14:54:25 +0200351 print(" %-16s %s %s" % ("waker:", k.waker.decode(), k.t_pid))
Teng Qine778db02018-04-24 16:11:49 -0700352 if not args.kernel_stacks_only:
353 if stack_id_err(k.w_u_stack_id):
354 print(" [Missed User Stack]")
355 else:
356 for addr in waker_user_stack:
357 print(" %s" % b.sym(addr, k.w_tgid))
358 if not args.user_stacks_only:
359 if need_delimiter and k.w_u_stack_id > 0 and k.w_k_stack_id > 0:
360 print(" -")
361 if stack_id_err(k.w_k_stack_id):
362 print(" [Missed Kernel Stack]")
363 else:
364 for addr in waker_kernel_stack:
365 print(" %s" % b.ksym(addr))
Brendan Greggaf2b46a2016-01-30 11:02:29 -0800366
ceeaspb47cecb62016-11-26 22:36:10 +0000367 # print waker/wakee delimiter
368 print(" %-16s %s" % ("--", "--"))
Javier Honduvilla Coto64bf9652018-08-01 06:50:19 +0200369
Teng Qine778db02018-04-24 16:11:49 -0700370 if not args.user_stacks_only:
371 if stack_id_err(k.t_k_stack_id):
372 print(" [Missed Kernel Stack]")
373 else:
374 for addr in target_kernel_stack:
375 print(" %s" % b.ksym(addr))
376 if not args.kernel_stacks_only:
377 if need_delimiter and k.t_u_stack_id > 0 and k.t_k_stack_id > 0:
378 print(" -")
379 if stack_id_err(k.t_u_stack_id):
380 print(" [Missed User Stack]")
381 else:
382 for addr in target_user_stack:
383 print(" %s" % b.sym(addr, k.t_tgid))
Rafael F78948e42017-03-26 14:54:25 +0200384 print(" %-16s %s %s" % ("target:", k.target.decode(), k.w_pid))
ceeaspb47cecb62016-11-26 22:36:10 +0000385 print(" %d\n" % v.value)
386
387if missing_stacks > 0:
388 enomem_str = " Consider increasing --stack-storage-size."
Teng Qine778db02018-04-24 16:11:49 -0700389 print("WARNING: %d stack traces lost and could not be displayed.%s" %
390 (missing_stacks, (enomem_str if has_enomem else "")),
ceeaspb47cecb62016-11-26 22:36:10 +0000391 file=stderr)