blob: 78cfc5f1c60e7741496ab66f9f80124b685b426f [file] [log] [blame]
Brendan Gregg38cef482016-01-15 17:26:30 -08001#!/usr/bin/python
2#
3# offcputime Summarize off-CPU time by kernel stack trace
4# For Linux, uses BCC, eBPF.
5#
6# USAGE: offcputime [-h] [-p PID] [-i INTERVAL] [-T] [duration]
7#
8# The current implementation uses an unrolled loop for x86_64, and was written
9# as a proof of concept. This implementation should be replaced in the future
10# with an appropriate bpf_ call, when available.
11#
12# Currently limited to a stack trace depth of 21 (maxdepth + 1).
13#
14# Copyright 2016 Netflix, Inc.
15# Licensed under the Apache License, Version 2.0 (the "License")
16#
17# 13-Jan-2016 Brendan Gregg Created this.
18
19from __future__ import print_function
20from bcc import BPF
21from time import sleep, strftime
22import argparse
23import signal
24
25# arguments
26examples = """examples:
27 ./offcputime # trace off-CPU stack time until Ctrl-C
28 ./offcputime 5 # trace for 5 seconds only
29 ./offcputime -f 5 # 5 seconds, and output in folded format
Brendan Greggd364d042016-01-19 17:12:52 -080030 ./offcputime -u # don't include kernel threads (user only)
Brendan Gregg38cef482016-01-15 17:26:30 -080031 ./offcputime -p 185 # trace fo PID 185 only
32"""
33parser = argparse.ArgumentParser(
34 description="Summarize off-CPU time by kernel stack trace",
35 formatter_class=argparse.RawDescriptionHelpFormatter,
36 epilog=examples)
Brendan Greggd364d042016-01-19 17:12:52 -080037parser.add_argument("-u", "--useronly", action="store_true",
38 help="user threads only (no kernel threads)")
Brendan Gregg38cef482016-01-15 17:26:30 -080039parser.add_argument("-p", "--pid",
40 help="trace this PID only")
41parser.add_argument("-v", "--verbose", action="store_true",
42 help="show raw addresses")
43parser.add_argument("-f", "--folded", action="store_true",
44 help="output folded format")
45parser.add_argument("duration", nargs="?", default=99999999,
46 help="duration of trace, in seconds")
47args = parser.parse_args()
48folded = args.folded
49duration = int(args.duration)
50debug = 0
51maxdepth = 20 # and MAXDEPTH
Brendan Greggd364d042016-01-19 17:12:52 -080052if args.pid and args.useronly:
53 print("ERROR: use either -p or -u.")
54 exit()
Brendan Gregg38cef482016-01-15 17:26:30 -080055
56# signal handler
57def signal_ignore(signal, frame):
58 print()
59
Brendan Greggd364d042016-01-19 17:12:52 -080060# define BPF program
Brendan Gregg38cef482016-01-15 17:26:30 -080061bpf_text = """
62#include <uapi/linux/ptrace.h>
63#include <linux/sched.h>
64
65#define MAXDEPTH 20
66#define MINBLOCK_US 1
67
68struct key_t {
69 char name[TASK_COMM_LEN];
70 // Skip saving the ip
71 u64 ret[MAXDEPTH];
72};
73BPF_HASH(counts, struct key_t);
74BPF_HASH(start, u32);
75
76static u64 get_frame(u64 *bp) {
77 if (*bp) {
78 // The following stack walker is x86_64 specific
79 u64 ret = 0;
80 if (bpf_probe_read(&ret, sizeof(ret), (void *)(*bp+8)))
81 return 0;
82 if (bpf_probe_read(bp, sizeof(*bp), (void *)*bp))
Brendan Gregg4d57da12016-01-19 00:55:12 -080083 *bp = 0;
Brendan Gregg38cef482016-01-15 17:26:30 -080084 if (ret < __START_KERNEL_map)
85 return 0;
86 return ret;
87 }
88 return 0;
89}
90
Brendan Greggd364d042016-01-19 17:12:52 -080091int oncpu(struct pt_regs *ctx, struct task_struct *prev) {
92 u32 pid;
93 u64 ts, *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -080094
Brendan Greggd364d042016-01-19 17:12:52 -080095 // record previous thread sleep time
96 if (FILTER) {
97 pid = prev->pid;
98 ts = bpf_ktime_get_ns();
99 start.update(&pid, &ts);
100 }
Brendan Gregg38cef482016-01-15 17:26:30 -0800101
Brendan Greggd364d042016-01-19 17:12:52 -0800102 // calculate current thread's delta time
103 pid = bpf_get_current_pid_tgid();
Brendan Gregg38cef482016-01-15 17:26:30 -0800104 tsp = start.lookup(&pid);
105 if (tsp == 0)
Brendan Greggf7471142016-01-19 14:40:41 -0800106 return 0; // missed start or filtered
107 u64 delta = bpf_ktime_get_ns() - *tsp;
Brendan Gregg38cef482016-01-15 17:26:30 -0800108 start.delete(&pid);
109 delta = delta / 1000;
110 if (delta < MINBLOCK_US)
111 return 0;
112
Brendan Greggf7471142016-01-19 14:40:41 -0800113 // create map key
114 u64 zero = 0, *val, bp = 0;
115 int depth = 0;
116 struct key_t key = {};
Brendan Gregg38cef482016-01-15 17:26:30 -0800117 bpf_get_current_comm(&key.name, sizeof(key.name));
118 bp = ctx->bp;
119
120 // unrolled loop (MAXDEPTH):
121 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
122 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
123 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
124 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
125 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
126 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
127 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
128 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
129 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
130 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
131
132 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
133 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
134 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
135 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
136 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
137 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
138 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
139 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
140 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
141 if (!(key.ret[depth++] = get_frame(&bp))) goto out;
142
143out:
144 val = counts.lookup_or_init(&key, &zero);
145 (*val) += delta;
146 return 0;
147}
148"""
149if args.pid:
Brendan Greggd364d042016-01-19 17:12:52 -0800150 filter = 'pid == %s' % args.pid
151elif args.useronly:
152 filter = '!(prev->flags & PF_KTHREAD)'
Brendan Gregg38cef482016-01-15 17:26:30 -0800153else:
Brendan Greggd364d042016-01-19 17:12:52 -0800154 filter = '1'
155bpf_text = bpf_text.replace('FILTER', filter)
Brendan Gregg38cef482016-01-15 17:26:30 -0800156if debug:
157 print(bpf_text)
Brendan Greggd364d042016-01-19 17:12:52 -0800158
159# initialize BPF
Brendan Gregg38cef482016-01-15 17:26:30 -0800160b = BPF(text=bpf_text)
Brendan Gregg38cef482016-01-15 17:26:30 -0800161b.attach_kprobe(event="finish_task_switch", fn_name="oncpu")
162matched = b.num_open_kprobes()
163if matched == 0:
164 print("0 functions traced. Exiting.")
165 exit()
166
167# header
168if not folded:
169 print("Tracing off-CPU time (us) by kernel stack", end="")
170 if duration < 99999999:
171 print(" for %d secs." % duration)
172 else:
173 print("... Hit Ctrl-C to end.")
174
175# output
176while (1):
177 try:
178 sleep(duration)
179 except KeyboardInterrupt:
180 # as cleanup can take many seconds, trap Ctrl-C:
181 signal.signal(signal.SIGINT, signal_ignore)
182
183 if not folded:
184 print()
185 counts = b.get_table("counts")
186 for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
187 if folded:
188 # print folded stack output
189 line = k.name + ";"
190 for i in reversed(range(0, maxdepth)):
191 if k.ret[i] == 0:
192 continue
193 line = line + b.ksym(k.ret[i])
194 if i != 0:
195 line = line + ";"
196 print("%s %d" % (line, v.value))
197 else:
198 # print default multi-line stack output
199 for i in range(0, maxdepth):
200 if k.ret[i] == 0:
201 break
202 print(" %-16x %s" % (k.ret[i],
203 b.ksym(k.ret[i])))
204 print(" %-16s %s" % ("-", k.name))
205 print(" %d\n" % v.value)
206 counts.clear()
207
208 if not folded:
209 print("Detaching...")
210 exit()