blob: 756d82624143328ea61a163014b4ddbee31f02a4 [file] [log] [blame]
Brendan Greggcd1cad12016-02-12 02:27:19 -08001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# ext4slower Trace slow ext4 operations.
5# For Linux, uses BCC, eBPF.
6#
7# USAGE: ext4slower [-h] [-j] [-p PID] [min_ms]
8#
9# This script traces common ext4 file operations: reads, writes, opens, and
10# syncs. It measures the time spent in these operations, and prints details
11# for each that exceeded a threshold.
12#
13# WARNING: This adds low-overhead instrumentation to these ext4 operations,
14# including reads and writes from the file system cache. Such reads and writes
15# can be very frequent (depending on the workload; eg, 1M/sec), at which
16# point the overhead of this tool (even if it prints no "slower" events) can
17# begin to become significant.
18#
19# By default, a minimum millisecond threshold of 10 is used.
20#
21# Copyright 2016 Netflix, Inc.
22# Licensed under the Apache License, Version 2.0 (the "License")
23#
24# 11-Feb-2016 Brendan Gregg Created this.
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +030025# 15-Oct-2016 Dina Goldshtein -p to filter by process ID.
Brendan Greggcd1cad12016-02-12 02:27:19 -080026
27from __future__ import print_function
28from bcc import BPF
29import argparse
30from time import strftime
31import ctypes as ct
32
33# symbols
34kallsyms = "/proc/kallsyms"
35
36# arguments
37examples = """examples:
38 ./ext4slower # trace operations slower than 10 ms (default)
39 ./ext4slower 1 # trace operations slower than 1 ms
40 ./ext4slower -j 1 # ... 1 ms, parsable output (csv)
41 ./ext4slower 0 # trace all operations (warning: verbose)
42 ./ext4slower -p 185 # trace PID 185 only
43"""
44parser = argparse.ArgumentParser(
45 description="Trace common ext4 file operations slower than a threshold",
46 formatter_class=argparse.RawDescriptionHelpFormatter,
47 epilog=examples)
48parser.add_argument("-j", "--csv", action="store_true",
49 help="just print fields: comma-separated values")
50parser.add_argument("-p", "--pid",
51 help="trace this PID only")
52parser.add_argument("min_ms", nargs="?", default='10',
53 help="minimum I/O duration to trace, in ms (default 10)")
Nathan Scottcf0792f2018-02-02 16:56:50 +110054parser.add_argument("--ebpf", action="store_true",
55 help=argparse.SUPPRESS)
Brendan Greggcd1cad12016-02-12 02:27:19 -080056args = parser.parse_args()
57min_ms = int(args.min_ms)
58pid = args.pid
59csv = args.csv
60debug = 0
61
62# define BPF program
63bpf_text = """
64#include <uapi/linux/ptrace.h>
65#include <linux/fs.h>
66#include <linux/sched.h>
67#include <linux/dcache.h>
68
69// XXX: switch these to char's when supported
70#define TRACE_READ 0
71#define TRACE_WRITE 1
72#define TRACE_OPEN 2
73#define TRACE_FSYNC 3
74
75struct val_t {
76 u64 ts;
77 u64 offset;
78 struct file *fp;
79};
80
81struct data_t {
82 // XXX: switch some to u32's when supported
83 u64 ts_us;
84 u64 type;
85 u64 size;
86 u64 offset;
87 u64 delta_us;
88 u64 pid;
89 char task[TASK_COMM_LEN];
90 char file[DNAME_INLINE_LEN];
91};
92
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +030093BPF_HASH(entryinfo, u64, struct val_t);
Brendan Greggcd1cad12016-02-12 02:27:19 -080094BPF_PERF_OUTPUT(events);
95
96//
97// Store timestamp and size on entry
98//
99
100// The current ext4 (Linux 4.5) uses generic_file_read_iter(), instead of it's
101// own function, for reads. So we need to trace that and then filter on ext4,
102// which I do by checking file->f_op.
103int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb)
104{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300105 u64 id = bpf_get_current_pid_tgid();
106 u32 pid = id >> 32; // PID is higher part
107
Brendan Greggcd1cad12016-02-12 02:27:19 -0800108 if (FILTER_PID)
109 return 0;
110
111 // ext4 filter on file->f_op == ext4_file_operations
112 struct file *fp = iocb->ki_filp;
113 if ((u64)fp->f_op != EXT4_FILE_OPERATIONS)
114 return 0;
115
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300116 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800117 struct val_t val = {};
118 val.ts = bpf_ktime_get_ns();
119 val.fp = fp;
120 val.offset = iocb->ki_pos;
121 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300122 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800123
124 return 0;
125}
126
127// ext4_file_write_iter():
128int trace_write_entry(struct pt_regs *ctx, struct kiocb *iocb)
129{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300130 u64 id = bpf_get_current_pid_tgid();
131 u32 pid = id >> 32; // PID is higher part
132
Brendan Greggcd1cad12016-02-12 02:27:19 -0800133 if (FILTER_PID)
134 return 0;
135
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300136 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800137 struct val_t val = {};
138 val.ts = bpf_ktime_get_ns();
139 val.fp = iocb->ki_filp;
140 val.offset = iocb->ki_pos;
141 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300142 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800143
144 return 0;
145}
146
147// ext4_file_open():
148int trace_open_entry(struct pt_regs *ctx, struct inode *inode,
149 struct file *file)
150{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300151 u64 id = bpf_get_current_pid_tgid();
152 u32 pid = id >> 32; // PID is higher part
153
Brendan Greggcd1cad12016-02-12 02:27:19 -0800154 if (FILTER_PID)
155 return 0;
156
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300157 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800158 struct val_t val = {};
159 val.ts = bpf_ktime_get_ns();
160 val.fp = file;
161 val.offset = 0;
162 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300163 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800164
165 return 0;
166}
167
168// ext4_sync_file():
169int trace_fsync_entry(struct pt_regs *ctx, struct file *file)
170{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300171 u64 id = bpf_get_current_pid_tgid();
172 u32 pid = id >> 32; // PID is higher part
173
Brendan Greggcd1cad12016-02-12 02:27:19 -0800174 if (FILTER_PID)
175 return 0;
176
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300177 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800178 struct val_t val = {};
179 val.ts = bpf_ktime_get_ns();
180 val.fp = file;
181 val.offset = 0;
182 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300183 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800184
185 return 0;
186}
187
188//
189// Output
190//
191
192static int trace_return(struct pt_regs *ctx, int type)
193{
194 struct val_t *valp;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300195 u64 id = bpf_get_current_pid_tgid();
196 u32 pid = id >> 32; // PID is higher part
Brendan Greggcd1cad12016-02-12 02:27:19 -0800197
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300198 valp = entryinfo.lookup(&id);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800199 if (valp == 0) {
200 // missed tracing issue or filtered
201 return 0;
202 }
203
204 // calculate delta
205 u64 ts = bpf_ktime_get_ns();
206 u64 delta_us = (ts - valp->ts) / 1000;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300207 entryinfo.delete(&id);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800208 if (FILTER_US)
209 return 0;
210
Brendan Greggcd1cad12016-02-12 02:27:19 -0800211 // populate output struct
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530212 u32 size = PT_REGS_RC(ctx);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800213 struct data_t data = {.type = type, .size = size, .delta_us = delta_us,
214 .pid = pid};
215 data.ts_us = ts / 1000;
216 data.offset = valp->offset;
Brendan Greggcd1cad12016-02-12 02:27:19 -0800217 bpf_get_current_comm(&data.task, sizeof(data.task));
218
Brendan Greggbe294db2016-10-20 21:46:09 -0700219 // workaround (rewriter should handle file to d_name in one step):
220 struct dentry *de = NULL;
221 struct qstr qs = {};
Paul Chaignon0cdf2962018-05-05 10:47:44 +0200222 de = valp->fp->f_path.dentry;
223 qs = de->d_name;
Brendan Greggbe294db2016-10-20 21:46:09 -0700224 if (qs.len == 0)
225 return 0;
226 bpf_probe_read(&data.file, sizeof(data.file), (void *)qs.name);
227
228 // output
Brendan Greggcd1cad12016-02-12 02:27:19 -0800229 events.perf_submit(ctx, &data, sizeof(data));
230
231 return 0;
232}
233
234int trace_read_return(struct pt_regs *ctx)
235{
236 return trace_return(ctx, TRACE_READ);
237}
238
239int trace_write_return(struct pt_regs *ctx)
240{
241 return trace_return(ctx, TRACE_WRITE);
242}
243
244int trace_open_return(struct pt_regs *ctx)
245{
246 return trace_return(ctx, TRACE_OPEN);
247}
248
249int trace_fsync_return(struct pt_regs *ctx)
250{
251 return trace_return(ctx, TRACE_FSYNC);
252}
253
254"""
255
256# code replacements
257with open(kallsyms) as syms:
258 ops = ''
259 for line in syms:
260 (addr, size, name) = line.rstrip().split(" ", 2)
ygrek189f87f2016-06-27 11:07:47 -0700261 name = name.split("\t")[0]
Brendan Greggcd1cad12016-02-12 02:27:19 -0800262 if name == "ext4_file_operations":
263 ops = "0x" + addr
264 break
265 if ops == '':
266 print("ERROR: no ext4_file_operations in /proc/kallsyms. Exiting.")
Aleksander Alekseev4a950bf2017-10-23 21:22:36 +0300267 print("HINT: the kernel should be built with CONFIG_KALLSYMS_ALL.")
Brendan Greggcd1cad12016-02-12 02:27:19 -0800268 exit()
269 bpf_text = bpf_text.replace('EXT4_FILE_OPERATIONS', ops)
270if min_ms == 0:
271 bpf_text = bpf_text.replace('FILTER_US', '0')
272else:
273 bpf_text = bpf_text.replace('FILTER_US',
274 'delta_us <= %s' % str(min_ms * 1000))
275if args.pid:
276 bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid)
277else:
278 bpf_text = bpf_text.replace('FILTER_PID', '0')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100279if debug or args.ebpf:
Brendan Greggcd1cad12016-02-12 02:27:19 -0800280 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100281 if args.ebpf:
282 exit()
Brendan Greggcd1cad12016-02-12 02:27:19 -0800283
284# kernel->user event data: struct data_t
285DNAME_INLINE_LEN = 32 # linux/dcache.h
286TASK_COMM_LEN = 16 # linux/sched.h
287class Data(ct.Structure):
288 _fields_ = [
289 ("ts_us", ct.c_ulonglong),
290 ("type", ct.c_ulonglong),
291 ("size", ct.c_ulonglong),
292 ("offset", ct.c_ulonglong),
293 ("delta_us", ct.c_ulonglong),
294 ("pid", ct.c_ulonglong),
295 ("task", ct.c_char * TASK_COMM_LEN),
296 ("file", ct.c_char * DNAME_INLINE_LEN)
297 ]
298
299# process event
300def print_event(cpu, data, size):
301 event = ct.cast(data, ct.POINTER(Data)).contents
302
303 type = 'R'
304 if event.type == 1:
305 type = 'W'
306 elif event.type == 2:
307 type = 'O'
308 elif event.type == 3:
309 type = 'S'
310
311 if (csv):
312 print("%d,%s,%d,%s,%d,%d,%d,%s" % (
Rafael F78948e42017-03-26 14:54:25 +0200313 event.ts_us, event.task.decode(), event.pid, type, event.size,
314 event.offset, event.delta_us, event.file.decode()))
Brendan Greggcd1cad12016-02-12 02:27:19 -0800315 return
316 print("%-8s %-14.14s %-6s %1s %-7s %-8d %7.2f %s" % (strftime("%H:%M:%S"),
Rafael F78948e42017-03-26 14:54:25 +0200317 event.task.decode(), event.pid, type, event.size, event.offset / 1024,
318 float(event.delta_us) / 1000, event.file.decode()))
Brendan Greggcd1cad12016-02-12 02:27:19 -0800319
320# initialize BPF
321b = BPF(text=bpf_text)
322
323# Common file functions. See earlier comment about generic_file_read_iter().
324b.attach_kprobe(event="generic_file_read_iter", fn_name="trace_read_entry")
325b.attach_kprobe(event="ext4_file_write_iter", fn_name="trace_write_entry")
326b.attach_kprobe(event="ext4_file_open", fn_name="trace_open_entry")
327b.attach_kprobe(event="ext4_sync_file", fn_name="trace_fsync_entry")
328b.attach_kretprobe(event="generic_file_read_iter", fn_name="trace_read_return")
329b.attach_kretprobe(event="ext4_file_write_iter", fn_name="trace_write_return")
330b.attach_kretprobe(event="ext4_file_open", fn_name="trace_open_return")
331b.attach_kretprobe(event="ext4_sync_file", fn_name="trace_fsync_return")
332
333# header
334if (csv):
335 print("ENDTIME_us,TASK,PID,TYPE,BYTES,OFFSET_b,LATENCY_us,FILE")
336else:
337 if min_ms == 0:
338 print("Tracing ext4 operations")
339 else:
340 print("Tracing ext4 operations slower than %d ms" % min_ms)
341 print("%-8s %-14s %-6s %1s %-7s %-8s %7s %s" % ("TIME", "COMM", "PID", "T",
342 "BYTES", "OFF_KB", "LAT(ms)", "FILENAME"))
343
344# read events
Mark Drayton5f5687e2017-02-20 18:13:03 +0000345b["events"].open_perf_buffer(print_event, page_cnt=64)
Brendan Greggcd1cad12016-02-12 02:27:19 -0800346while 1:
Teng Qindbf00292018-02-28 21:47:50 -0800347 b.perf_buffer_poll()