blob: 09e85725c02bcd091a9e288c42f64eca185264b8 [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)")
54args = parser.parse_args()
55min_ms = int(args.min_ms)
56pid = args.pid
57csv = args.csv
58debug = 0
59
60# define BPF program
61bpf_text = """
62#include <uapi/linux/ptrace.h>
63#include <linux/fs.h>
64#include <linux/sched.h>
65#include <linux/dcache.h>
66
67// XXX: switch these to char's when supported
68#define TRACE_READ 0
69#define TRACE_WRITE 1
70#define TRACE_OPEN 2
71#define TRACE_FSYNC 3
72
73struct val_t {
74 u64 ts;
75 u64 offset;
76 struct file *fp;
77};
78
79struct data_t {
80 // XXX: switch some to u32's when supported
81 u64 ts_us;
82 u64 type;
83 u64 size;
84 u64 offset;
85 u64 delta_us;
86 u64 pid;
87 char task[TASK_COMM_LEN];
88 char file[DNAME_INLINE_LEN];
89};
90
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +030091BPF_HASH(entryinfo, u64, struct val_t);
Brendan Greggcd1cad12016-02-12 02:27:19 -080092BPF_PERF_OUTPUT(events);
93
94//
95// Store timestamp and size on entry
96//
97
98// The current ext4 (Linux 4.5) uses generic_file_read_iter(), instead of it's
99// own function, for reads. So we need to trace that and then filter on ext4,
100// which I do by checking file->f_op.
101int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb)
102{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300103 u64 id = bpf_get_current_pid_tgid();
104 u32 pid = id >> 32; // PID is higher part
105
Brendan Greggcd1cad12016-02-12 02:27:19 -0800106 if (FILTER_PID)
107 return 0;
108
109 // ext4 filter on file->f_op == ext4_file_operations
110 struct file *fp = iocb->ki_filp;
111 if ((u64)fp->f_op != EXT4_FILE_OPERATIONS)
112 return 0;
113
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300114 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800115 struct val_t val = {};
116 val.ts = bpf_ktime_get_ns();
117 val.fp = fp;
118 val.offset = iocb->ki_pos;
119 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300120 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800121
122 return 0;
123}
124
125// ext4_file_write_iter():
126int trace_write_entry(struct pt_regs *ctx, struct kiocb *iocb)
127{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300128 u64 id = bpf_get_current_pid_tgid();
129 u32 pid = id >> 32; // PID is higher part
130
Brendan Greggcd1cad12016-02-12 02:27:19 -0800131 if (FILTER_PID)
132 return 0;
133
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300134 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800135 struct val_t val = {};
136 val.ts = bpf_ktime_get_ns();
137 val.fp = iocb->ki_filp;
138 val.offset = iocb->ki_pos;
139 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300140 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800141
142 return 0;
143}
144
145// ext4_file_open():
146int trace_open_entry(struct pt_regs *ctx, struct inode *inode,
147 struct file *file)
148{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300149 u64 id = bpf_get_current_pid_tgid();
150 u32 pid = id >> 32; // PID is higher part
151
Brendan Greggcd1cad12016-02-12 02:27:19 -0800152 if (FILTER_PID)
153 return 0;
154
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300155 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800156 struct val_t val = {};
157 val.ts = bpf_ktime_get_ns();
158 val.fp = file;
159 val.offset = 0;
160 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300161 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800162
163 return 0;
164}
165
166// ext4_sync_file():
167int trace_fsync_entry(struct pt_regs *ctx, struct file *file)
168{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300169 u64 id = bpf_get_current_pid_tgid();
170 u32 pid = id >> 32; // PID is higher part
171
Brendan Greggcd1cad12016-02-12 02:27:19 -0800172 if (FILTER_PID)
173 return 0;
174
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300175 // store filep and timestamp by id
Brendan Greggcd1cad12016-02-12 02:27:19 -0800176 struct val_t val = {};
177 val.ts = bpf_ktime_get_ns();
178 val.fp = file;
179 val.offset = 0;
180 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300181 entryinfo.update(&id, &val);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800182
183 return 0;
184}
185
186//
187// Output
188//
189
190static int trace_return(struct pt_regs *ctx, int type)
191{
192 struct val_t *valp;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300193 u64 id = bpf_get_current_pid_tgid();
194 u32 pid = id >> 32; // PID is higher part
Brendan Greggcd1cad12016-02-12 02:27:19 -0800195
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300196 valp = entryinfo.lookup(&id);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800197 if (valp == 0) {
198 // missed tracing issue or filtered
199 return 0;
200 }
201
202 // calculate delta
203 u64 ts = bpf_ktime_get_ns();
204 u64 delta_us = (ts - valp->ts) / 1000;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300205 entryinfo.delete(&id);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800206 if (FILTER_US)
207 return 0;
208
Brendan Greggcd1cad12016-02-12 02:27:19 -0800209 // populate output struct
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530210 u32 size = PT_REGS_RC(ctx);
Brendan Greggcd1cad12016-02-12 02:27:19 -0800211 struct data_t data = {.type = type, .size = size, .delta_us = delta_us,
212 .pid = pid};
213 data.ts_us = ts / 1000;
214 data.offset = valp->offset;
Brendan Greggcd1cad12016-02-12 02:27:19 -0800215 bpf_get_current_comm(&data.task, sizeof(data.task));
216
Brendan Greggbe294db2016-10-20 21:46:09 -0700217 // workaround (rewriter should handle file to d_name in one step):
218 struct dentry *de = NULL;
219 struct qstr qs = {};
220 bpf_probe_read(&de, sizeof(de), &valp->fp->f_path.dentry);
221 bpf_probe_read(&qs, sizeof(qs), (void *)&de->d_name);
222 if (qs.len == 0)
223 return 0;
224 bpf_probe_read(&data.file, sizeof(data.file), (void *)qs.name);
225
226 // output
Brendan Greggcd1cad12016-02-12 02:27:19 -0800227 events.perf_submit(ctx, &data, sizeof(data));
228
229 return 0;
230}
231
232int trace_read_return(struct pt_regs *ctx)
233{
234 return trace_return(ctx, TRACE_READ);
235}
236
237int trace_write_return(struct pt_regs *ctx)
238{
239 return trace_return(ctx, TRACE_WRITE);
240}
241
242int trace_open_return(struct pt_regs *ctx)
243{
244 return trace_return(ctx, TRACE_OPEN);
245}
246
247int trace_fsync_return(struct pt_regs *ctx)
248{
249 return trace_return(ctx, TRACE_FSYNC);
250}
251
252"""
253
254# code replacements
255with open(kallsyms) as syms:
256 ops = ''
257 for line in syms:
258 (addr, size, name) = line.rstrip().split(" ", 2)
ygrek189f87f2016-06-27 11:07:47 -0700259 name = name.split("\t")[0]
Brendan Greggcd1cad12016-02-12 02:27:19 -0800260 if name == "ext4_file_operations":
261 ops = "0x" + addr
262 break
263 if ops == '':
264 print("ERROR: no ext4_file_operations in /proc/kallsyms. Exiting.")
Aleksander Alekseev4a950bf2017-10-23 21:22:36 +0300265 print("HINT: the kernel should be built with CONFIG_KALLSYMS_ALL.")
Brendan Greggcd1cad12016-02-12 02:27:19 -0800266 exit()
267 bpf_text = bpf_text.replace('EXT4_FILE_OPERATIONS', ops)
268if min_ms == 0:
269 bpf_text = bpf_text.replace('FILTER_US', '0')
270else:
271 bpf_text = bpf_text.replace('FILTER_US',
272 'delta_us <= %s' % str(min_ms * 1000))
273if args.pid:
274 bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid)
275else:
276 bpf_text = bpf_text.replace('FILTER_PID', '0')
277if debug:
278 print(bpf_text)
279
280# kernel->user event data: struct data_t
281DNAME_INLINE_LEN = 32 # linux/dcache.h
282TASK_COMM_LEN = 16 # linux/sched.h
283class Data(ct.Structure):
284 _fields_ = [
285 ("ts_us", ct.c_ulonglong),
286 ("type", ct.c_ulonglong),
287 ("size", ct.c_ulonglong),
288 ("offset", ct.c_ulonglong),
289 ("delta_us", ct.c_ulonglong),
290 ("pid", ct.c_ulonglong),
291 ("task", ct.c_char * TASK_COMM_LEN),
292 ("file", ct.c_char * DNAME_INLINE_LEN)
293 ]
294
295# process event
296def print_event(cpu, data, size):
297 event = ct.cast(data, ct.POINTER(Data)).contents
298
299 type = 'R'
300 if event.type == 1:
301 type = 'W'
302 elif event.type == 2:
303 type = 'O'
304 elif event.type == 3:
305 type = 'S'
306
307 if (csv):
308 print("%d,%s,%d,%s,%d,%d,%d,%s" % (
Rafael F78948e42017-03-26 14:54:25 +0200309 event.ts_us, event.task.decode(), event.pid, type, event.size,
310 event.offset, event.delta_us, event.file.decode()))
Brendan Greggcd1cad12016-02-12 02:27:19 -0800311 return
312 print("%-8s %-14.14s %-6s %1s %-7s %-8d %7.2f %s" % (strftime("%H:%M:%S"),
Rafael F78948e42017-03-26 14:54:25 +0200313 event.task.decode(), event.pid, type, event.size, event.offset / 1024,
314 float(event.delta_us) / 1000, event.file.decode()))
Brendan Greggcd1cad12016-02-12 02:27:19 -0800315
316# initialize BPF
317b = BPF(text=bpf_text)
318
319# Common file functions. See earlier comment about generic_file_read_iter().
320b.attach_kprobe(event="generic_file_read_iter", fn_name="trace_read_entry")
321b.attach_kprobe(event="ext4_file_write_iter", fn_name="trace_write_entry")
322b.attach_kprobe(event="ext4_file_open", fn_name="trace_open_entry")
323b.attach_kprobe(event="ext4_sync_file", fn_name="trace_fsync_entry")
324b.attach_kretprobe(event="generic_file_read_iter", fn_name="trace_read_return")
325b.attach_kretprobe(event="ext4_file_write_iter", fn_name="trace_write_return")
326b.attach_kretprobe(event="ext4_file_open", fn_name="trace_open_return")
327b.attach_kretprobe(event="ext4_sync_file", fn_name="trace_fsync_return")
328
329# header
330if (csv):
331 print("ENDTIME_us,TASK,PID,TYPE,BYTES,OFFSET_b,LATENCY_us,FILE")
332else:
333 if min_ms == 0:
334 print("Tracing ext4 operations")
335 else:
336 print("Tracing ext4 operations slower than %d ms" % min_ms)
337 print("%-8s %-14s %-6s %1s %-7s %-8s %7s %s" % ("TIME", "COMM", "PID", "T",
338 "BYTES", "OFF_KB", "LAT(ms)", "FILENAME"))
339
340# read events
Mark Drayton5f5687e2017-02-20 18:13:03 +0000341b["events"].open_perf_buffer(print_event, page_cnt=64)
Brendan Greggcd1cad12016-02-12 02:27:19 -0800342while 1:
343 b.kprobe_poll()