blob: 1eb5d9ac9b44aadd1c2d58c0b4669c2228496ca9 [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")
61args = parser.parse_args()
62countdown = int(args.count)
63debug = 0
64
65# define BPF program
66bpf_text = """
67#include <uapi/linux/ptrace.h>
Brenden Blanco11a21c82016-02-10 15:42:16 -080068#include <linux/sched.h>
Brendan Gregg82769382017-04-18 14:23:14 -050069#include <linux/nsproxy.h>
70#include <linux/pid_namespace.h>
Brendan Gregg3a391c22016-02-08 01:20:31 -080071
72typedef struct pid_key {
Brenden Blancoa6875602016-05-02 23:32:44 -070073 u64 id; // work around
Brendan Gregg3a391c22016-02-08 01:20:31 -080074 u64 slot;
75} pid_key_t;
Brendan Gregg82769382017-04-18 14:23:14 -050076
77typedef struct pidns_key {
78 u64 id; // work around
79 u64 slot;
80} pidns_key_t;
81
Brendan Gregg3a391c22016-02-08 01:20:31 -080082BPF_HASH(start, u32);
83STORAGE
84
Brenden Blanco11a21c82016-02-10 15:42:16 -080085struct rq;
86
Brendan Gregg3a391c22016-02-08 01:20:31 -080087// record enqueue timestamp
88int trace_enqueue(struct pt_regs *ctx, struct rq *rq, struct task_struct *p,
89 int flags)
90{
Brenden Blancoa6875602016-05-02 23:32:44 -070091 u32 tgid = p->tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -080092 u32 pid = p->pid;
93 if (FILTER)
94 return 0;
95 u64 ts = bpf_ktime_get_ns();
96 start.update(&pid, &ts);
97 return 0;
98}
99
100// calculate latency
101int trace_run(struct pt_regs *ctx, struct task_struct *prev)
102{
Brenden Blancoa6875602016-05-02 23:32:44 -0700103 u32 pid, tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800104
105 // ivcsw: treat like an enqueue event and store timestamp
106 if (prev->state == TASK_RUNNING) {
Brenden Blancoa6875602016-05-02 23:32:44 -0700107 tgid = prev->tgid;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800108 pid = prev->pid;
109 if (!(FILTER)) {
110 u64 ts = bpf_ktime_get_ns();
111 start.update(&pid, &ts);
112 }
113 }
114
Brenden Blancoa6875602016-05-02 23:32:44 -0700115 tgid = bpf_get_current_pid_tgid() >> 32;
Brendan Gregg3a391c22016-02-08 01:20:31 -0800116 pid = bpf_get_current_pid_tgid();
117 if (FILTER)
118 return 0;
119 u64 *tsp, delta;
120
121 // fetch timestamp and calculate delta
122 tsp = start.lookup(&pid);
123 if (tsp == 0) {
124 return 0; // missed enqueue
125 }
126 delta = bpf_ktime_get_ns() - *tsp;
127 FACTOR
128
129 // store as histogram
130 STORE
131
132 start.delete(&pid);
133 return 0;
134}
135"""
136
137# code substitutions
138if args.pid:
Brenden Blancoa6875602016-05-02 23:32:44 -0700139 # pid from userspace point of view is thread group from kernel pov
140 bpf_text = bpf_text.replace('FILTER', 'tgid != %s' % args.pid)
Brendan Gregg3a391c22016-02-08 01:20:31 -0800141else:
142 bpf_text = bpf_text.replace('FILTER', '0')
143if args.milliseconds:
144 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
145 label = "msecs"
146else:
147 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
148 label = "usecs"
Brenden Blancoa6875602016-05-02 23:32:44 -0700149if args.pids or args.tids:
150 section = "pid"
151 pid = "tgid"
152 if args.tids:
153 pid = "pid"
154 section = "tid"
Brendan Gregg3a391c22016-02-08 01:20:31 -0800155 bpf_text = bpf_text.replace('STORAGE',
156 'BPF_HISTOGRAM(dist, pid_key_t);')
157 bpf_text = bpf_text.replace('STORE',
Brenden Blancoa6875602016-05-02 23:32:44 -0700158 'pid_key_t key = {.id = ' + pid + ', .slot = bpf_log2l(delta)}; ' +
Brendan Gregg3a391c22016-02-08 01:20:31 -0800159 'dist.increment(key);')
Brendan Gregg82769382017-04-18 14:23:14 -0500160elif args.pidnss:
161 section = "pidns"
162 bpf_text = bpf_text.replace('STORAGE',
163 'BPF_HISTOGRAM(dist, pidns_key_t);')
164 bpf_text = bpf_text.replace('STORE', 'pidns_key_t key = ' +
165 '{.id = prev->nsproxy->pid_ns_for_children->ns.inum, ' +
166 '.slot = bpf_log2l(delta)}; dist.increment(key);')
Brendan Gregg3a391c22016-02-08 01:20:31 -0800167else:
Brenden Blancoa6875602016-05-02 23:32:44 -0700168 section = ""
Brendan Gregg3a391c22016-02-08 01:20:31 -0800169 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
175# load BPF program
176b = BPF(text=bpf_text)
177b.attach_kprobe(event_re="enqueue_task_*", fn_name="trace_enqueue")
178b.attach_kprobe(event="finish_task_switch", fn_name="trace_run")
179
180print("Tracing run queue latency... Hit Ctrl-C to end.")
181
182# output
183exiting = 0 if args.interval else 1
184dist = b.get_table("dist")
185while (1):
186 try:
187 sleep(int(args.interval))
188 except KeyboardInterrupt:
189 exiting = 1
190
191 print()
192 if args.timestamp:
193 print("%-8s\n" % strftime("%H:%M:%S"), end="")
194
Brenden Blancoa6875602016-05-02 23:32:44 -0700195 dist.print_log2_hist(label, section, section_print_fn=int)
Brendan Gregg3a391c22016-02-08 01:20:31 -0800196 dist.clear()
197
198 countdown -= 1
199 if exiting or countdown == 0:
200 exit()