blob: 636ff97f048301f4258c341fac421932566b513e [file] [log] [blame]
Brendan Gregg3a391c22016-02-08 01:20:31 -08001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# runqlat Run queue (scheduler) latency as a histogram.
5# For Linux, uses BCC, eBPF.
6#
Brenden Blancoa6875602016-05-02 23:32:44 -07007# USAGE: runqlat [-h] [-T] [-m] [-P] [-L] [-p PID] [interval] [count]
Brendan Gregg3a391c22016-02-08 01:20:31 -08008#
9# This measures the time a task spends waiting on a run queue for a turn
10# on-CPU, and shows this time as a histogram. This time should be small, but a
11# task may need to wait its turn due to CPU load.
12#
13# This measures two types of run queue latency:
14# 1. The time from a task being enqueued on a run queue to its context switch
15# and execution. This traces enqueue_task_*() -> finish_task_switch(),
16# and instruments the run queue latency after a voluntary context switch.
17# 2. The time from when a task was involuntary context switched and still
18# in the runnable state, to when it next executed. This is instrumented
19# from finish_task_switch() alone.
20#
21# Copyright 2016 Netflix, Inc.
22# Licensed under the Apache License, Version 2.0 (the "License")
23#
24# 07-Feb-2016 Brendan Gregg Created this.
25
26from __future__ import print_function
27from bcc import BPF
28from time import sleep, strftime
29import argparse
30
31# arguments
32examples = """examples:
33 ./runqlat # summarize run queue latency as a histogram
34 ./runqlat 1 10 # print 1 second summaries, 10 times
35 ./runqlat -mT 1 # 1s summaries, milliseconds, and timestamps
36 ./runqlat -P # show each PID separately
37 ./runqlat -p 185 # trace PID 185 only
38"""
39parser = argparse.ArgumentParser(
Brendan Gregg82769382017-04-18 14:23:14 -050040 description="Summarize run queue (scheduler) latency as a histogram",
Brendan Gregg3a391c22016-02-08 01:20:31 -080041 formatter_class=argparse.RawDescriptionHelpFormatter,
42 epilog=examples)
43parser.add_argument("-T", "--timestamp", action="store_true",
44 help="include timestamp on output")
45parser.add_argument("-m", "--milliseconds", action="store_true",
46 help="millisecond histogram")
47parser.add_argument("-P", "--pids", action="store_true",
48 help="print a histogram per process ID")
Brendan Gregg82769382017-04-18 14:23:14 -050049# PID options are --pid and --pids, so namespaces should be --pidns (not done
50# yet) and --pidnss:
51parser.add_argument("--pidnss", action="store_true",
52 help="print a histogram per PID namespace")
Brenden Blancoa6875602016-05-02 23:32:44 -070053parser.add_argument("-L", "--tids", action="store_true",
54 help="print a histogram per thread ID")
Brendan Gregg3a391c22016-02-08 01:20:31 -080055parser.add_argument("-p", "--pid",
56 help="trace this PID only")
57parser.add_argument("interval", nargs="?", default=99999999,
58 help="output interval, in seconds")
59parser.add_argument("count", nargs="?", default=99999999,
60 help="number of outputs")
Nathan Scottcf0792f2018-02-02 16:56:50 +110061parser.add_argument("--ebpf", action="store_true",
62 help=argparse.SUPPRESS)
Brendan Gregg3a391c22016-02-08 01:20:31 -080063args = parser.parse_args()
64countdown = int(args.count)
65debug = 0
66
67# define BPF program
68bpf_text = """
69#include <uapi/linux/ptrace.h>
Brenden Blanco11a21c82016-02-10 15:42:16 -080070#include <linux/sched.h>
Brendan Gregg82769382017-04-18 14:23:14 -050071#include <linux/nsproxy.h>
72#include <linux/pid_namespace.h>
Brendan Gregg3a391c22016-02-08 01:20:31 -080073
74typedef struct pid_key {
Brenden Blancoa6875602016-05-02 23:32:44 -070075 u64 id; // work around
Brendan Gregg3a391c22016-02-08 01:20:31 -080076 u64 slot;
77} pid_key_t;
Brendan Gregg82769382017-04-18 14:23:14 -050078
79typedef struct pidns_key {
80 u64 id; // work around
81 u64 slot;
82} pidns_key_t;
83
Brendan Gregg3a391c22016-02-08 01:20:31 -080084BPF_HASH(start, u32);
85STORAGE
86
Brenden Blanco11a21c82016-02-10 15:42:16 -080087struct rq;
88
Brendan Gregg3a391c22016-02-08 01:20:31 -080089// record enqueue timestamp
90int trace_enqueue(struct pt_regs *ctx, struct rq *rq, struct task_struct *p,
91 int flags)
92{
Brenden Blancoa6875602016-05-02 23:32:44 -070093 u32 tgid = p->tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -080094 u32 pid = p->pid;
95 if (FILTER)
96 return 0;
97 u64 ts = bpf_ktime_get_ns();
98 start.update(&pid, &ts);
99 return 0;
100}
101
102// calculate latency
103int trace_run(struct pt_regs *ctx, struct task_struct *prev)
104{
Brenden Blancoa6875602016-05-02 23:32:44 -0700105 u32 pid, tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800106
107 // ivcsw: treat like an enqueue event and store timestamp
108 if (prev->state == TASK_RUNNING) {
Brenden Blancoa6875602016-05-02 23:32:44 -0700109 tgid = prev->tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800110 pid = prev->pid;
111 if (!(FILTER)) {
112 u64 ts = bpf_ktime_get_ns();
113 start.update(&pid, &ts);
114 }
115 }
116
Brenden Blancoa6875602016-05-02 23:32:44 -0700117 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800118 pid = bpf_get_current_pid_tgid();
119 if (FILTER)
120 return 0;
121 u64 *tsp, delta;
122
123 // fetch timestamp and calculate delta
124 tsp = start.lookup(&pid);
125 if (tsp == 0) {
126 return 0; // missed enqueue
127 }
128 delta = bpf_ktime_get_ns() - *tsp;
129 FACTOR
130
131 // store as histogram
132 STORE
133
134 start.delete(&pid);
135 return 0;
136}
137"""
138
139# code substitutions
140if args.pid:
Brenden Blancoa6875602016-05-02 23:32:44 -0700141 # pid from userspace point of view is thread group from kernel pov
142 bpf_text = bpf_text.replace('FILTER', 'tgid != %s' % args.pid)
Brendan Gregg3a391c22016-02-08 01:20:31 -0800143else:
144 bpf_text = bpf_text.replace('FILTER', '0')
145if args.milliseconds:
146 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
147 label = "msecs"
148else:
149 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
150 label = "usecs"
Brenden Blancoa6875602016-05-02 23:32:44 -0700151if args.pids or args.tids:
152 section = "pid"
153 pid = "tgid"
154 if args.tids:
155 pid = "pid"
156 section = "tid"
Brendan Gregg3a391c22016-02-08 01:20:31 -0800157 bpf_text = bpf_text.replace('STORAGE',
158 'BPF_HISTOGRAM(dist, pid_key_t);')
159 bpf_text = bpf_text.replace('STORE',
Brenden Blancoa6875602016-05-02 23:32:44 -0700160 'pid_key_t key = {.id = ' + pid + ', .slot = bpf_log2l(delta)}; ' +
Brendan Gregg3a391c22016-02-08 01:20:31 -0800161 'dist.increment(key);')
Brendan Gregg82769382017-04-18 14:23:14 -0500162elif args.pidnss:
163 section = "pidns"
164 bpf_text = bpf_text.replace('STORAGE',
165 'BPF_HISTOGRAM(dist, pidns_key_t);')
166 bpf_text = bpf_text.replace('STORE', 'pidns_key_t key = ' +
167 '{.id = prev->nsproxy->pid_ns_for_children->ns.inum, ' +
168 '.slot = bpf_log2l(delta)}; dist.increment(key);')
Brendan Gregg3a391c22016-02-08 01:20:31 -0800169else:
Brenden Blancoa6875602016-05-02 23:32:44 -0700170 section = ""
Brendan Gregg3a391c22016-02-08 01:20:31 -0800171 bpf_text = bpf_text.replace('STORAGE', 'BPF_HISTOGRAM(dist);')
172 bpf_text = bpf_text.replace('STORE',
173 'dist.increment(bpf_log2l(delta));')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100174if debug or args.ebpf:
Brendan Gregg3a391c22016-02-08 01:20:31 -0800175 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100176 if args.ebpf:
177 exit()
Brendan Gregg3a391c22016-02-08 01:20:31 -0800178
179# load BPF program
180b = BPF(text=bpf_text)
181b.attach_kprobe(event_re="enqueue_task_*", fn_name="trace_enqueue")
182b.attach_kprobe(event="finish_task_switch", fn_name="trace_run")
183
184print("Tracing run queue latency... Hit Ctrl-C to end.")
185
186# output
187exiting = 0 if args.interval else 1
188dist = b.get_table("dist")
189while (1):
190 try:
191 sleep(int(args.interval))
192 except KeyboardInterrupt:
193 exiting = 1
194
195 print()
196 if args.timestamp:
197 print("%-8s\n" % strftime("%H:%M:%S"), end="")
198
Brenden Blancoa6875602016-05-02 23:32:44 -0700199 dist.print_log2_hist(label, section, section_print_fn=int)
Brendan Gregg3a391c22016-02-08 01:20:31 -0800200 dist.clear()
201
202 countdown -= 1
203 if exiting or countdown == 0:
204 exit()