blob: 18072589268b43a29884ee7870db3d1ed8a7c492 [file] [log] [blame]
Sasha Goldshtein40975ab2016-06-29 03:57:01 +03001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
Sasha Goldshtein9972f272016-06-29 01:48:08 -07004# cpudist Summarize on- and off-CPU time per task as a histogram.
Sasha Goldshtein40975ab2016-06-29 03:57:01 +03005#
Sasha Goldshtein9972f272016-06-29 01:48:08 -07006# USAGE: cpudist [-h] [-O] [-T] [-m] [-P] [-L] [-p PID] [interval] [count]
Sasha Goldshtein40975ab2016-06-29 03:57:01 +03007#
Sasha Goldshtein9972f272016-06-29 01:48:08 -07008# This measures the time a task spends on or off the CPU, and shows this time
9# as a histogram, optionally per-process.
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030010#
11# Copyright 2016 Sasha Goldshtein
12# Licensed under the Apache License, Version 2.0 (the "License")
13
14from __future__ import print_function
15from bcc import BPF, Tracepoint
16from time import sleep, strftime
17import argparse
18
19examples = """examples:
20 cpudist # summarize on-CPU time as a histogram
Sasha Goldshtein9972f272016-06-29 01:48:08 -070021 cpudist -O # summarize off-CPU time as a histogram
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030022 cpudist 1 10 # print 1 second summaries, 10 times
23 cpudist -mT 1 # 1s summaries, milliseconds, and timestamps
24 cpudist -P # show each PID separately
25 cpudist -p 185 # trace PID 185 only
26"""
27parser = argparse.ArgumentParser(
28 description="Summarize on-CPU time per task as a histogram.",
29 formatter_class=argparse.RawDescriptionHelpFormatter,
30 epilog=examples)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070031parser.add_argument("-O", "--offcpu", action="store_true",
32 help="measure off-CPU time")
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030033parser.add_argument("-T", "--timestamp", action="store_true",
34 help="include timestamp on output")
35parser.add_argument("-m", "--milliseconds", action="store_true",
36 help="millisecond histogram")
37parser.add_argument("-P", "--pids", action="store_true",
38 help="print a histogram per process ID")
39parser.add_argument("-L", "--tids", action="store_true",
40 help="print a histogram per thread ID")
41parser.add_argument("-p", "--pid",
42 help="trace this PID only")
43parser.add_argument("interval", nargs="?", default=99999999,
44 help="output interval, in seconds")
45parser.add_argument("count", nargs="?", default=99999999,
46 help="number of outputs")
47args = parser.parse_args()
48countdown = int(args.count)
49debug = 0
50
51tp = Tracepoint.enable_tracepoint("sched", "sched_switch")
52bpf_text = "#include <uapi/linux/ptrace.h>\n"
53bpf_text += "#include <linux/sched.h>\n"
54bpf_text += tp.generate_decl()
55bpf_text += tp.generate_entry_probe()
56bpf_text += tp.generate_struct()
57
Sasha Goldshtein9972f272016-06-29 01:48:08 -070058if not args.offcpu:
59 bpf_text += "#define ONCPU\n"
60
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030061bpf_text += """
62typedef struct pid_key {
63 u64 id;
64 u64 slot;
65} pid_key_t;
66
Sasha Goldshtein9972f272016-06-29 01:48:08 -070067
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030068BPF_HASH(start, u32, u64);
69BPF_HASH(tgid_for_pid, u32, u32);
70STORAGE
71
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -070072static inline u32 get_tgid(u32 pid)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070073{
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -070074 u32 *stored_tgid = tgid_for_pid.lookup(&pid);
75 if (stored_tgid != 0)
76 return *stored_tgid;
77 return 0xffffffff;
Sasha Goldshtein9972f272016-06-29 01:48:08 -070078}
79
80static inline void store_start(u32 tgid, u32 pid, u64 ts)
81{
Sasha Goldshtein9972f272016-06-29 01:48:08 -070082 if (FILTER)
83 return;
84
85 start.update(&pid, &ts);
86}
87
88static inline void update_hist(u32 tgid, u32 pid, u64 ts)
89{
Sasha Goldshtein9972f272016-06-29 01:48:08 -070090 if (FILTER)
91 return;
92
93 u64 *tsp = start.lookup(&pid);
94 if (tsp == 0)
95 return;
96
97 u64 delta = ts - *tsp;
98 FACTOR
99 STORE
100}
101
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300102int sched_switch(struct pt_regs *ctx)
103{
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700104 u64 ts = bpf_ktime_get_ns();
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300105 u64 pid_tgid = bpf_get_current_pid_tgid();
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700106 u32 tgid = pid_tgid >> 32, pid = pid_tgid;
107 // Keep a mapping of tgid for pid because when sched_switch hits,
108 // we only have the tgid information for the *current* pid, but not
109 // for the previous one.
110 tgid_for_pid.update(&pid, &tgid);
111
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300112 u64 *di = __trace_di.lookup(&pid_tgid);
113 if (di == 0)
114 return 0;
115
116 struct sched_switch_trace_entry args = {};
117 bpf_probe_read(&args, sizeof(args), (void *)*di);
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300118
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700119#ifdef ONCPU
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -0700120 if (args.prev_state == TASK_RUNNING) {
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700121#else
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -0700122 if (1) {
123#endif
124 u32 prev_pid = args.prev_pid;
125 u32 prev_tgid = get_tgid(prev_pid);
126 if (prev_tgid == 0xffffffff)
127 goto BAIL;
128#ifdef ONCPU
129 update_hist(prev_tgid, prev_pid, ts);
130#else
131 store_start(prev_tgid, prev_pid, ts);
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700132#endif
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300133 }
134
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -0700135BAIL:
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700136#ifdef ONCPU
137 store_start(tgid, pid, ts);
138#else
139 update_hist(tgid, pid, ts);
140#endif
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300141
142 return 0;
143}
144"""
145
146if args.pid:
147 bpf_text = bpf_text.replace('FILTER', 'tgid != %s' % args.pid)
148else:
149 bpf_text = bpf_text.replace('FILTER', '0')
150if args.milliseconds:
151 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
152 label = "msecs"
153else:
154 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
155 label = "usecs"
156if args.pids or args.tids:
157 section = "pid"
158 pid = "tgid"
159 if args.tids:
160 pid = "pid"
161 section = "tid"
162 bpf_text = bpf_text.replace('STORAGE',
163 'BPF_HISTOGRAM(dist, pid_key_t);')
164 bpf_text = bpf_text.replace('STORE',
165 'pid_key_t key = {.id = ' + pid + ', .slot = bpf_log2l(delta)}; ' +
166 'dist.increment(key);')
167else:
168 section = ""
169 bpf_text = bpf_text.replace('STORAGE', 'BPF_HISTOGRAM(dist);')
170 bpf_text = bpf_text.replace('STORE',
171 'dist.increment(bpf_log2l(delta));')
172if debug:
173 print(bpf_text)
174
175b = BPF(text=bpf_text)
176Tracepoint.attach(b)
177b.attach_kprobe(event="perf_trace_sched_switch", fn_name="sched_switch")
178
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700179print("Tracing %s-CPU time... Hit Ctrl-C to end." %
180 ("off" if args.offcpu else "on"))
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300181
182exiting = 0 if args.interval else 1
183dist = b.get_table("dist")
184while (1):
185 try:
186 sleep(int(args.interval))
187 except KeyboardInterrupt:
188 exiting = 1
189
190 print()
191 if args.timestamp:
192 print("%-8s\n" % strftime("%H:%M:%S"), end="")
193
Sasha Goldshtein4b72f052016-06-29 02:18:06 -0700194 def pid_to_comm(pid):
195 try:
196 comm = open("/proc/%d/comm" % pid, "r").read()
197 return "%d %s" % (pid, comm)
198 except IOError:
199 return str(pid)
200
201 dist.print_log2_hist(label, section, section_print_fn=pid_to_comm)
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300202 dist.clear()
203
204 countdown -= 1
205 if exiting or countdown == 0:
206 exit()
207