blob: dfc456af6ae7d14a17c0040558a42778c9985ca2 [file] [log] [blame]
Brendan Gregg1dcedc42016-02-12 02:29:08 -08001#!/usr/bin/python
2# @lint-avoid-python-3-compatibility-imports
3#
4# ext4dist Summarize ext4 operation latency.
5# For Linux, uses BCC, eBPF.
6#
7# USAGE: ext4dist [-h] [-T] [-m] [-p PID] [interval] [count]
8#
9# Copyright 2016 Netflix, Inc.
10# Licensed under the Apache License, Version 2.0 (the "License")
11#
12# 12-Feb-2016 Brendan Gregg Created this.
13
14from __future__ import print_function
15from bcc import BPF
16from time import sleep, strftime
17import argparse
18
19# symbols
20kallsyms = "/proc/kallsyms"
21
22# arguments
23examples = """examples:
24 ./ext4dist # show operation latency as a histogram
25 ./ext4dist -p 181 # trace PID 181 only
26 ./ext4dist 1 10 # print 1 second summaries, 10 times
27 ./ext4dist -m 5 # 5s summaries, milliseconds
28"""
29parser = argparse.ArgumentParser(
30 description="Summarize ext4 operation latency",
31 formatter_class=argparse.RawDescriptionHelpFormatter,
32 epilog=examples)
33parser.add_argument("-T", "--notimestamp", action="store_true",
34 help="don't include timestamp on interval output")
35parser.add_argument("-m", "--milliseconds", action="store_true",
36 help="output in milliseconds")
37parser.add_argument("-p", "--pid",
38 help="trace this PID only")
39parser.add_argument("interval", nargs="?",
40 help="output interval, in seconds")
41parser.add_argument("count", nargs="?", default=99999999,
42 help="number of outputs")
43args = parser.parse_args()
44pid = args.pid
45countdown = int(args.count)
46if args.milliseconds:
47 factor = 1000000
48 label = "msecs"
49else:
50 factor = 1000
51 label = "usecs"
52if args.interval and int(args.interval) == 0:
53 print("ERROR: interval 0. Exiting.")
54 exit()
55debug = 0
56
57# define BPF program
58bpf_text = """
59#include <uapi/linux/ptrace.h>
60#include <linux/fs.h>
61#include <linux/sched.h>
62
63#define OP_NAME_LEN 8
64typedef struct dist_key {
65 char op[OP_NAME_LEN];
66 u64 slot;
67} dist_key_t;
68BPF_HASH(start, u32);
69BPF_HISTOGRAM(dist, dist_key_t);
70
71// time operation
72int trace_entry(struct pt_regs *ctx)
73{
74 u32 pid = bpf_get_current_pid_tgid();
75 if (FILTER_PID)
76 return 0;
77 u64 ts = bpf_ktime_get_ns();
78 start.update(&pid, &ts);
79 return 0;
80}
81
82// The current ext4 (Linux 4.5) uses generic_file_read_iter(), instead of it's
83// own function, for reads. So we need to trace that and then filter on ext4,
84// which I do by checking file->f_op.
85int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb)
86{
87 u32 pid = bpf_get_current_pid_tgid();
88 if (FILTER_PID)
89 return 0;
90
91 // ext4 filter on file->f_op == ext4_file_operations
92 struct file *fp = iocb->ki_filp;
93 if ((u64)fp->f_op != EXT4_FILE_OPERATIONS)
94 return 0;
95
96 u64 ts = bpf_ktime_get_ns();
97 start.update(&pid, &ts);
98 return 0;
99}
100
101static int trace_return(struct pt_regs *ctx, const char *op)
102{
103 u64 *tsp;
104 u32 pid = bpf_get_current_pid_tgid();
105
106 // fetch timestamp and calculate delta
107 tsp = start.lookup(&pid);
108 if (tsp == 0) {
109 return 0; // missed start or filtered
110 }
111 u64 delta = (bpf_ktime_get_ns() - *tsp) / FACTOR;
112
113 // store as histogram
114 dist_key_t key = {.slot = bpf_log2l(delta)};
115 __builtin_memcpy(&key.op, op, sizeof(key.op));
116 dist.increment(key);
117
118 start.delete(&pid);
119 return 0;
120}
121
122int trace_read_return(struct pt_regs *ctx)
123{
124 char *op = "read";
125 return trace_return(ctx, op);
126}
127
128int trace_write_return(struct pt_regs *ctx)
129{
130 char *op = "write";
131 return trace_return(ctx, op);
132}
133
134int trace_open_return(struct pt_regs *ctx)
135{
136 char *op = "open";
137 return trace_return(ctx, op);
138}
139
140int trace_fsync_return(struct pt_regs *ctx)
141{
142 char *op = "fsync";
143 return trace_return(ctx, op);
144}
145"""
146
147# code replacements
148with open(kallsyms) as syms:
149 ops = ''
150 for line in syms:
151 (addr, size, name) = line.rstrip().split(" ", 2)
ygreka5e2ce52016-06-27 12:54:55 -0700152 name = name.split("\t")[0]
Brendan Gregg1dcedc42016-02-12 02:29:08 -0800153 if name == "ext4_file_operations":
154 ops = "0x" + addr
155 break
156 if ops == '':
157 print("ERROR: no ext4_file_operations in /proc/kallsyms. Exiting.")
158 exit()
159 bpf_text = bpf_text.replace('EXT4_FILE_OPERATIONS', ops)
160bpf_text = bpf_text.replace('FACTOR', str(factor))
161if args.pid:
162 bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid)
163else:
164 bpf_text = bpf_text.replace('FILTER_PID', '0')
165if debug:
166 print(bpf_text)
167
168# load BPF program
169b = BPF(text=bpf_text)
170
171# Common file functions. See earlier comment about generic_file_read_iter().
172b.attach_kprobe(event="generic_file_read_iter", fn_name="trace_read_entry")
173b.attach_kprobe(event="ext4_file_write_iter", fn_name="trace_entry")
174b.attach_kprobe(event="ext4_file_open", fn_name="trace_entry")
175b.attach_kprobe(event="ext4_sync_file", fn_name="trace_entry")
176b.attach_kretprobe(event="generic_file_read_iter", fn_name="trace_read_return")
177b.attach_kretprobe(event="ext4_file_write_iter", fn_name="trace_write_return")
178b.attach_kretprobe(event="ext4_file_open", fn_name="trace_open_return")
179b.attach_kretprobe(event="ext4_sync_file", fn_name="trace_fsync_return")
180
181print("Tracing ext4 operation latency... Hit Ctrl-C to end.")
182
183# output
184exiting = 0
185dist = b.get_table("dist")
186while (1):
187 try:
188 if args.interval:
189 sleep(int(args.interval))
190 else:
191 sleep(99999999)
192 except KeyboardInterrupt:
193 exiting = 1
194
195 print()
196 if args.interval and (not args.notimestamp):
197 print(strftime("%H:%M:%S:"))
198
Rafael F78948e42017-03-26 14:54:25 +0200199 dist.print_log2_hist(label, "operation", section_print_fn=bytes.decode)
Brendan Gregg1dcedc42016-02-12 02:29:08 -0800200 dist.clear()
201
202 countdown -= 1
203 if exiting or countdown == 0:
204 exit()