blob: 3f58aa182c9fa7bde25e21eea26eedc12c4e8e05 [file] [log] [blame]
Alexey Ivanovcc01a9c2019-01-16 09:50:46 -08001#!/usr/bin/python
Sasha Goldshtein40975ab2016-06-29 03:57:01 +03002# @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#
xingfeng2510c1a767b2022-03-27 11:52:17 +08006# USAGE: cpudist [-h] [-O] [-T] [-m] [-P] [-L] [-p PID] [-I] [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#
xingfeng2510c1a767b2022-03-27 11:52:17 +080011# By default CPU idle time are excluded by simply excluding PID 0.
12#
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030013# Copyright 2016 Sasha Goldshtein
14# Licensed under the Apache License, Version 2.0 (the "License")
xingfeng2510c1a767b2022-03-27 11:52:17 +080015#
16# 27-Mar-2022 Rocky Xing Changed to exclude CPU idle time by default.
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030017
18from __future__ import print_function
Rafael Fonsecaaf236e72017-02-15 17:28:26 +010019from bcc import BPF
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030020from time import sleep, strftime
21import argparse
22
23examples = """examples:
24 cpudist # summarize on-CPU time as a histogram
Sasha Goldshtein9972f272016-06-29 01:48:08 -070025 cpudist -O # summarize off-CPU time as a histogram
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030026 cpudist 1 10 # print 1 second summaries, 10 times
27 cpudist -mT 1 # 1s summaries, milliseconds, and timestamps
28 cpudist -P # show each PID separately
29 cpudist -p 185 # trace PID 185 only
xingfeng2510c1a767b2022-03-27 11:52:17 +080030 cpudist -I # include CPU idle time
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030031"""
32parser = argparse.ArgumentParser(
33 description="Summarize on-CPU time per task as a histogram.",
34 formatter_class=argparse.RawDescriptionHelpFormatter,
35 epilog=examples)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070036parser.add_argument("-O", "--offcpu", action="store_true",
37 help="measure off-CPU time")
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030038parser.add_argument("-T", "--timestamp", action="store_true",
39 help="include timestamp on output")
40parser.add_argument("-m", "--milliseconds", action="store_true",
41 help="millisecond histogram")
42parser.add_argument("-P", "--pids", action="store_true",
43 help="print a histogram per process ID")
44parser.add_argument("-L", "--tids", action="store_true",
45 help="print a histogram per thread ID")
46parser.add_argument("-p", "--pid",
47 help="trace this PID only")
xingfeng2510c1a767b2022-03-27 11:52:17 +080048parser.add_argument("-I", "--include-idle", action="store_true",
49 help="include CPU idle time")
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030050parser.add_argument("interval", nargs="?", default=99999999,
51 help="output interval, in seconds")
52parser.add_argument("count", nargs="?", default=99999999,
53 help="number of outputs")
Nathan Scottcf0792f2018-02-02 16:56:50 +110054parser.add_argument("--ebpf", action="store_true",
55 help=argparse.SUPPRESS)
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030056args = parser.parse_args()
57countdown = int(args.count)
58debug = 0
59
Sasha Goldshtein06d90d32016-06-30 07:39:27 -070060bpf_text = """#include <uapi/linux/ptrace.h>
61#include <linux/sched.h>
62"""
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030063
Sasha Goldshtein9972f272016-06-29 01:48:08 -070064if not args.offcpu:
65 bpf_text += "#define ONCPU\n"
66
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030067bpf_text += """
xingfeng2510e683daa2022-03-27 11:10:55 +080068typedef struct entry_key {
69 u32 pid;
70 u32 cpu;
71} entry_key_t;
72
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030073typedef struct pid_key {
74 u64 id;
75 u64 slot;
76} pid_key_t;
77
Sasha Goldshtein9972f272016-06-29 01:48:08 -070078
xingfeng2510e683daa2022-03-27 11:10:55 +080079BPF_HASH(start, entry_key_t, u64, MAX_PID);
Sasha Goldshtein40975ab2016-06-29 03:57:01 +030080STORAGE
81
xingfeng2510e683daa2022-03-27 11:10:55 +080082static inline void store_start(u32 tgid, u32 pid, u32 cpu, u64 ts)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070083{
xingfeng2510c1a767b2022-03-27 11:52:17 +080084 if (PID_FILTER)
85 return;
86
87 if (IDLE_FILTER)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070088 return;
89
xingfeng2510e683daa2022-03-27 11:10:55 +080090 entry_key_t entry_key = { .pid = pid, .cpu = cpu };
91 start.update(&entry_key, &ts);
Sasha Goldshtein9972f272016-06-29 01:48:08 -070092}
93
xingfeng2510e683daa2022-03-27 11:10:55 +080094static inline void update_hist(u32 tgid, u32 pid, u32 cpu, u64 ts)
Sasha Goldshtein9972f272016-06-29 01:48:08 -070095{
xingfeng2510c1a767b2022-03-27 11:52:17 +080096 if (PID_FILTER)
97 return;
98
99 if (IDLE_FILTER)
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700100 return;
101
xingfeng2510e683daa2022-03-27 11:10:55 +0800102 entry_key_t entry_key = { .pid = pid, .cpu = cpu };
103 u64 *tsp = start.lookup(&entry_key);
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700104 if (tsp == 0)
105 return;
106
Sasha Goldshteinbee8d362016-06-30 10:46:27 -0700107 if (ts < *tsp) {
108 // Probably a clock issue where the recorded on-CPU event had a
109 // timestamp later than the recorded off-CPU event, or vice versa.
110 return;
111 }
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700112 u64 delta = ts - *tsp;
113 FACTOR
114 STORE
115}
116
Sasha Goldshtein06d90d32016-06-30 07:39:27 -0700117int sched_switch(struct pt_regs *ctx, struct task_struct *prev)
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300118{
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700119 u64 ts = bpf_ktime_get_ns();
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300120 u64 pid_tgid = bpf_get_current_pid_tgid();
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700121 u32 tgid = pid_tgid >> 32, pid = pid_tgid;
xingfeng2510e683daa2022-03-27 11:10:55 +0800122 u32 cpu = bpf_get_smp_processor_id();
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300123
Nick-nizhenab14faf2021-05-27 13:21:59 +0800124 u32 prev_pid = prev->pid;
125 u32 prev_tgid = prev->tgid;
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700126#ifdef ONCPU
xingfeng2510e683daa2022-03-27 11:10:55 +0800127 update_hist(prev_tgid, prev_pid, cpu, ts);
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700128#else
xingfeng2510e683daa2022-03-27 11:10:55 +0800129 store_start(prev_tgid, prev_pid, cpu, ts);
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -0700130#endif
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300131
Sasha Goldshtein3c976bb2016-06-29 23:35:43 -0700132BAIL:
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700133#ifdef ONCPU
xingfeng2510e683daa2022-03-27 11:10:55 +0800134 store_start(tgid, pid, cpu, ts);
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700135#else
xingfeng2510e683daa2022-03-27 11:10:55 +0800136 update_hist(tgid, pid, cpu, ts);
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700137#endif
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300138
139 return 0;
140}
141"""
142
143if args.pid:
xingfeng2510c1a767b2022-03-27 11:52:17 +0800144 bpf_text = bpf_text.replace('PID_FILTER', 'tgid != %s' % args.pid)
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300145else:
xingfeng2510c1a767b2022-03-27 11:52:17 +0800146 bpf_text = bpf_text.replace('PID_FILTER', '0')
147
148# set idle filter
149idle_filter = 'pid == 0'
150if args.include_idle:
151 idle_filter = '0'
152bpf_text = bpf_text.replace('IDLE_FILTER', idle_filter)
153
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300154if args.milliseconds:
155 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
156 label = "msecs"
157else:
158 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
159 label = "usecs"
160if args.pids or args.tids:
161 section = "pid"
162 pid = "tgid"
163 if args.tids:
164 pid = "pid"
165 section = "tid"
166 bpf_text = bpf_text.replace('STORAGE',
Tristan Cacqueray9b433f22019-10-23 15:02:03 +0000167 'BPF_HISTOGRAM(dist, pid_key_t, MAX_PID);')
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300168 bpf_text = bpf_text.replace('STORE',
169 'pid_key_t key = {.id = ' + pid + ', .slot = bpf_log2l(delta)}; ' +
170 'dist.increment(key);')
171else:
172 section = ""
173 bpf_text = bpf_text.replace('STORAGE', 'BPF_HISTOGRAM(dist);')
174 bpf_text = bpf_text.replace('STORE',
zcy80242fb2021-07-02 00:12:32 +0800175 'dist.atomic_increment(bpf_log2l(delta));')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100176if debug or args.ebpf:
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300177 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100178 if args.ebpf:
179 exit()
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300180
Tristan Cacqueray9b433f22019-10-23 15:02:03 +0000181max_pid = int(open("/proc/sys/kernel/pid_max").read())
182
183b = BPF(text=bpf_text, cflags=["-DMAX_PID=%d" % max_pid])
Guodong Xu00b72fd2021-03-13 02:23:47 +0000184b.attach_kprobe(event_re="^finish_task_switch$|^finish_task_switch\.isra\.\d$",
185 fn_name="sched_switch")
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300186
Sasha Goldshtein9972f272016-06-29 01:48:08 -0700187print("Tracing %s-CPU time... Hit Ctrl-C to end." %
188 ("off" if args.offcpu else "on"))
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300189
190exiting = 0 if args.interval else 1
191dist = b.get_table("dist")
192while (1):
193 try:
194 sleep(int(args.interval))
195 except KeyboardInterrupt:
196 exiting = 1
197
198 print()
199 if args.timestamp:
200 print("%-8s\n" % strftime("%H:%M:%S"), end="")
201
Sasha Goldshtein4b72f052016-06-29 02:18:06 -0700202 def pid_to_comm(pid):
203 try:
204 comm = open("/proc/%d/comm" % pid, "r").read()
205 return "%d %s" % (pid, comm)
206 except IOError:
207 return str(pid)
208
209 dist.print_log2_hist(label, section, section_print_fn=pid_to_comm)
Sasha Goldshtein40975ab2016-06-29 03:57:01 +0300210 dist.clear()
211
212 countdown -= 1
213 if exiting or countdown == 0:
214 exit()