blob: 8b34900ea6fffd5c9f1f6cb11a083e96c3aab786 [file] [log] [blame]
Brendan Greggee74c372016-02-15 22:22:19 -08001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# btrfsslower Trace slow btrfs operations.
5# For Linux, uses BCC, eBPF.
6#
7# USAGE: btrfsslower [-h] [-j] [-p PID] [min_ms]
8#
9# This script traces common btrfs 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 btrfs 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# 15-Feb-2016 Brendan Gregg Created this.
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +030025# 16-Oct-2016 Dina Goldshtein -p to filter by process ID.
Brendan Greggee74c372016-02-15 22:22: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 ./btrfsslower # trace operations slower than 10 ms (default)
39 ./btrfsslower 1 # trace operations slower than 1 ms
40 ./btrfsslower -j 1 # ... 1 ms, parsable output (csv)
41 ./btrfsslower 0 # trace all operations (warning: verbose)
42 ./btrfsslower -p 185 # trace PID 185 only
43"""
44parser = argparse.ArgumentParser(
45 description="Trace common btrfs 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 Greggee74c372016-02-15 22:22:19 -080092BPF_PERF_OUTPUT(events);
93
94//
95// Store timestamp and size on entry
96//
97
98// The current btrfs (Linux 4.5) uses generic_file_read_iter() instead of it's
99// own read function. So we need to trace that and then filter on btrfs, which
100// 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 Greggee74c372016-02-15 22:22:19 -0800106 if (FILTER_PID)
107 return 0;
108
109 // btrfs filter on file->f_op == btrfs_file_operations
110 struct file *fp = iocb->ki_filp;
111 if ((u64)fp->f_op != BTRFS_FILE_OPERATIONS)
112 return 0;
113
114 // store filep and timestamp by pid
115 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 Greggee74c372016-02-15 22:22:19 -0800121
122 return 0;
123}
124
125// btrfs_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 Greggee74c372016-02-15 22:22:19 -0800131 if (FILTER_PID)
132 return 0;
133
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300134 // store filep and timestamp by id
Brendan Greggee74c372016-02-15 22:22: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 Greggee74c372016-02-15 22:22:19 -0800141
142 return 0;
143}
144
145// The current btrfs (Linux 4.5) uses generic_file_open(), instead of it's own
146// function. Same as with reads. Trace the generic path and filter:
147int trace_open_entry(struct pt_regs *ctx, struct inode *inode,
148 struct file *file)
149{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300150 u64 id = bpf_get_current_pid_tgid();
151 u32 pid = id >> 32; // PID is higher part
152
Brendan Greggee74c372016-02-15 22:22:19 -0800153 if (FILTER_PID)
154 return 0;
155
156 // btrfs filter on file->f_op == btrfs_file_operations
157 if ((u64)file->f_op != BTRFS_FILE_OPERATIONS)
158 return 0;
159
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300160 // store filep and timestamp by id
Brendan Greggee74c372016-02-15 22:22:19 -0800161 struct val_t val = {};
162 val.ts = bpf_ktime_get_ns();
163 val.fp = file;
164 val.offset = 0;
165 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300166 entryinfo.update(&id, &val);
Brendan Greggee74c372016-02-15 22:22:19 -0800167
168 return 0;
169}
170
171// btrfs_sync_file():
172int trace_fsync_entry(struct pt_regs *ctx, struct file *file)
173{
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300174 u64 id = bpf_get_current_pid_tgid();
175 u32 pid = id >> 32; // PID is higher part
176
Brendan Greggee74c372016-02-15 22:22:19 -0800177 if (FILTER_PID)
178 return 0;
179
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300180 // store filep and timestamp by id
Brendan Greggee74c372016-02-15 22:22:19 -0800181 struct val_t val = {};
182 val.ts = bpf_ktime_get_ns();
183 val.fp = file;
184 val.offset = 0;
185 if (val.fp)
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300186 entryinfo.update(&id, &val);
Brendan Greggee74c372016-02-15 22:22:19 -0800187
188 return 0;
189}
190
191//
192// Output
193//
194
195static int trace_return(struct pt_regs *ctx, int type)
196{
197 struct val_t *valp;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300198 u64 id = bpf_get_current_pid_tgid();
199 u32 pid = id >> 32; // PID is higher part
Brendan Greggee74c372016-02-15 22:22:19 -0800200
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300201 valp = entryinfo.lookup(&id);
Brendan Greggee74c372016-02-15 22:22:19 -0800202 if (valp == 0) {
203 // missed tracing issue or filtered
204 return 0;
205 }
206
207 // calculate delta
208 u64 ts = bpf_ktime_get_ns();
209 u64 delta_us = (ts - valp->ts) / 1000;
Dina Goldshteinc8b9ae32016-10-18 03:01:05 +0300210 entryinfo.delete(&id);
Brendan Greggee74c372016-02-15 22:22:19 -0800211 if (FILTER_US)
212 return 0;
213
Brendan Greggee74c372016-02-15 22:22:19 -0800214 // populate output struct
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530215 u32 size = PT_REGS_RC(ctx);
Brendan Greggee74c372016-02-15 22:22:19 -0800216 struct data_t data = {.type = type, .size = size, .delta_us = delta_us,
217 .pid = pid};
218 data.ts_us = ts / 1000;
219 data.offset = valp->offset;
Brendan Greggee74c372016-02-15 22:22:19 -0800220 bpf_get_current_comm(&data.task, sizeof(data.task));
221
Brendan Greggbe294db2016-10-20 21:46:09 -0700222 // workaround (rewriter should handle file to d_name in one step):
223 struct dentry *de = NULL;
224 struct qstr qs = {};
225 bpf_probe_read(&de, sizeof(de), &valp->fp->f_path.dentry);
226 bpf_probe_read(&qs, sizeof(qs), (void *)&de->d_name);
227 if (qs.len == 0)
228 return 0;
229 bpf_probe_read(&data.file, sizeof(data.file), (void *)qs.name);
230
231 // output
Brendan Greggee74c372016-02-15 22:22:19 -0800232 events.perf_submit(ctx, &data, sizeof(data));
233
234 return 0;
235}
236
237int trace_read_return(struct pt_regs *ctx)
238{
239 return trace_return(ctx, TRACE_READ);
240}
241
242int trace_write_return(struct pt_regs *ctx)
243{
244 return trace_return(ctx, TRACE_WRITE);
245}
246
247int trace_open_return(struct pt_regs *ctx)
248{
249 return trace_return(ctx, TRACE_OPEN);
250}
251
252int trace_fsync_return(struct pt_regs *ctx)
253{
254 return trace_return(ctx, TRACE_FSYNC);
255}
256
257"""
258
259# code replacements
260with open(kallsyms) as syms:
261 ops = ''
262 for line in syms:
263 a = line.rstrip().split()
264 (addr, name) = (a[0], a[2])
ygreka5e2ce52016-06-27 12:54:55 -0700265 name = name.split("\t")[0]
Brendan Greggee74c372016-02-15 22:22:19 -0800266 if name == "btrfs_file_operations":
267 ops = "0x" + addr
268 break
269 if ops == '':
270 print("ERROR: no btrfs_file_operations in /proc/kallsyms. Exiting.")
271 exit()
272 bpf_text = bpf_text.replace('BTRFS_FILE_OPERATIONS', ops)
273if min_ms == 0:
274 bpf_text = bpf_text.replace('FILTER_US', '0')
275else:
276 bpf_text = bpf_text.replace('FILTER_US',
277 'delta_us <= %s' % str(min_ms * 1000))
278if args.pid:
279 bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid)
280else:
281 bpf_text = bpf_text.replace('FILTER_PID', '0')
282if debug:
283 print(bpf_text)
284
285# kernel->user event data: struct data_t
286DNAME_INLINE_LEN = 32 # linux/dcache.h
287TASK_COMM_LEN = 16 # linux/sched.h
288class Data(ct.Structure):
289 _fields_ = [
290 ("ts_us", ct.c_ulonglong),
291 ("type", ct.c_ulonglong),
292 ("size", ct.c_ulonglong),
293 ("offset", ct.c_ulonglong),
294 ("delta_us", ct.c_ulonglong),
295 ("pid", ct.c_ulonglong),
296 ("task", ct.c_char * TASK_COMM_LEN),
297 ("file", ct.c_char * DNAME_INLINE_LEN)
298 ]
299
300# process event
301def print_event(cpu, data, size):
302 event = ct.cast(data, ct.POINTER(Data)).contents
303
304 type = 'R'
305 if event.type == 1:
306 type = 'W'
307 elif event.type == 2:
308 type = 'O'
309 elif event.type == 3:
310 type = 'S'
311
312 if (csv):
313 print("%d,%s,%d,%s,%d,%d,%d,%s" % (
314 event.ts_us, event.task, event.pid, type, event.size,
315 event.offset, event.delta_us, event.file))
316 return
317 print("%-8s %-14.14s %-6s %1s %-7s %-8d %7.2f %s" % (strftime("%H:%M:%S"),
318 event.task, event.pid, type, event.size, event.offset / 1024,
319 float(event.delta_us) / 1000, event.file))
320
321# initialize BPF
322b = BPF(text=bpf_text)
323
324# Common file functions. See earlier comment about generic_*().
325b.attach_kprobe(event="generic_file_read_iter", fn_name="trace_read_entry")
326b.attach_kprobe(event="btrfs_file_write_iter", fn_name="trace_write_entry")
327b.attach_kprobe(event="generic_file_open", fn_name="trace_open_entry")
328b.attach_kprobe(event="btrfs_sync_file", fn_name="trace_fsync_entry")
329b.attach_kretprobe(event="generic_file_read_iter", fn_name="trace_read_return")
330b.attach_kretprobe(event="btrfs_file_write_iter", fn_name="trace_write_return")
331b.attach_kretprobe(event="generic_file_open", fn_name="trace_open_return")
332b.attach_kretprobe(event="btrfs_sync_file", fn_name="trace_fsync_return")
333
334# header
335if (csv):
336 print("ENDTIME_us,TASK,PID,TYPE,BYTES,OFFSET_b,LATENCY_us,FILE")
337else:
338 if min_ms == 0:
339 print("Tracing btrfs operations")
340 else:
341 print("Tracing btrfs operations slower than %d ms" % min_ms)
342 print("%-8s %-14s %-6s %1s %-7s %-8s %7s %s" % ("TIME", "COMM", "PID", "T",
343 "BYTES", "OFF_KB", "LAT(ms)", "FILENAME"))
344
345# read events
Mark Drayton5f5687e2017-02-20 18:13:03 +0000346b["events"].open_perf_buffer(print_event, page_cnt=64)
Brendan Greggee74c372016-02-15 22:22:19 -0800347while 1:
348 b.kprobe_poll()