blob: fe06d1b08f941b3dfd3af7e3d95b173208aa05b7 [file] [log] [blame]
Brendan Gregg74016c32015-09-21 15:49:21 -07001#!/usr/bin/python
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08002# @lint-avoid-python-3-compatibility-imports
Brendan Gregg74016c32015-09-21 15:49:21 -07003#
Sasha Goldshteina466c462016-10-06 21:17:59 +03004# funclatency Time functions and print latency as a histogram.
Alexei Starovoitovbdf07732016-01-14 10:09:20 -08005# For Linux, uses BCC, eBPF.
Brendan Gregg74016c32015-09-21 15:49:21 -07006#
Sasha Goldshteina466c462016-10-06 21:17:59 +03007# USAGE: funclatency [-h] [-p PID] [-i INTERVAL] [-T] [-u] [-m] [-F] [-r] [-v]
8# pattern
Brendan Gregg74016c32015-09-21 15:49:21 -07009#
10# Run "funclatency -h" for full usage.
11#
Sasha Goldshteinf41ae862016-10-19 01:14:30 +030012# The pattern is a string with optional '*' wildcards, similar to file
13# globbing. If you'd prefer to use regular expressions, use the -r option.
Brendan Gregg74016c32015-09-21 15:49:21 -070014#
Brendan Gregg50bbca42015-09-25 12:47:53 -070015# Currently nested or recursive functions are not supported properly, and
16# timestamps will be overwritten, creating dubious output. Try to match single
17# functions, or groups of functions that run at the same stack layer, and
18# don't ultimately call each other.
19#
Brendan Gregg74016c32015-09-21 15:49:21 -070020# Copyright (c) 2015 Brendan Gregg.
21# Licensed under the Apache License, Version 2.0 (the "License")
22#
Sasha Goldshteina466c462016-10-06 21:17:59 +030023# 20-Sep-2015 Brendan Gregg Created this.
24# 06-Oct-2016 Sasha Goldshtein Added user function support.
Brendan Gregg74016c32015-09-21 15:49:21 -070025
26from __future__ import print_function
27from bcc import BPF
28from time import sleep, strftime
29import argparse
30import signal
31
32# arguments
33examples = """examples:
Sasha Goldshteina466c462016-10-06 21:17:59 +030034 ./funclatency do_sys_open # time the do_sys_open() kernel function
35 ./funclatency c:read # time the read() C library function
Brendan Gregg74016c32015-09-21 15:49:21 -070036 ./funclatency -u vfs_read # time vfs_read(), in microseconds
37 ./funclatency -m do_nanosleep # time do_nanosleep(), in milliseconds
38 ./funclatency -mTi 5 vfs_read # output every 5 seconds, with timestamps
39 ./funclatency -p 181 vfs_read # time process 181 only
40 ./funclatency 'vfs_fstat*' # time both vfs_fstat() and vfs_fstatat()
Sasha Goldshteina466c462016-10-06 21:17:59 +030041 ./funclatency 'c:*printf' # time the *printf family of functions
Brendan Gregg50bbca42015-09-25 12:47:53 -070042 ./funclatency -F 'vfs_r*' # show one histogram per matched function
Brendan Gregg74016c32015-09-21 15:49:21 -070043"""
44parser = argparse.ArgumentParser(
Sasha Goldshteina466c462016-10-06 21:17:59 +030045 description="Time functions and print latency as a histogram",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080046 formatter_class=argparse.RawDescriptionHelpFormatter,
47 epilog=examples)
htbegin5ac5d6e2017-05-24 22:53:17 +080048parser.add_argument("-p", "--pid", type=int,
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080049 help="trace this PID only")
Brendan Gregg74016c32015-09-21 15:49:21 -070050parser.add_argument("-i", "--interval", default=99999999,
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080051 help="summary interval, seconds")
Brendan Gregg74016c32015-09-21 15:49:21 -070052parser.add_argument("-T", "--timestamp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080053 help="include timestamp on output")
Brendan Gregg74016c32015-09-21 15:49:21 -070054parser.add_argument("-u", "--microseconds", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080055 help="microsecond histogram")
Brendan Gregg74016c32015-09-21 15:49:21 -070056parser.add_argument("-m", "--milliseconds", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080057 help="millisecond histogram")
Brendan Gregg50bbca42015-09-25 12:47:53 -070058parser.add_argument("-F", "--function", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080059 help="show a separate histogram per function")
Brendan Gregg74016c32015-09-21 15:49:21 -070060parser.add_argument("-r", "--regexp", action="store_true",
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080061 help="use regular expressions. Default is \"*\" wildcards only.")
Sasha Goldshteina466c462016-10-06 21:17:59 +030062parser.add_argument("-v", "--verbose", action="store_true",
63 help="print the BPF program (for debugging purposes)")
Brendan Gregg74016c32015-09-21 15:49:21 -070064parser.add_argument("pattern",
Sasha Goldshteina466c462016-10-06 21:17:59 +030065 help="search expression for functions")
Nathan Scottcf0792f2018-02-02 16:56:50 +110066parser.add_argument("--ebpf", action="store_true",
67 help=argparse.SUPPRESS)
Brendan Gregg74016c32015-09-21 15:49:21 -070068args = parser.parse_args()
Sasha Goldshteina466c462016-10-06 21:17:59 +030069
70def bail(error):
71 print("Error: " + error)
72 exit(1)
73
74parts = args.pattern.split(':')
75if len(parts) == 1:
76 library = None
77 pattern = args.pattern
78elif len(parts) == 2:
79 library = parts[0]
80 libpath = BPF.find_library(library) or BPF.find_exe(library)
81 if not libpath:
82 bail("can't resolve library %s" % library)
83 library = libpath
84 pattern = parts[1]
85else:
86 bail("unrecognized pattern format '%s'" % pattern)
87
Brendan Gregg74016c32015-09-21 15:49:21 -070088if not args.regexp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080089 pattern = pattern.replace('*', '.*')
90 pattern = '^' + pattern + '$'
Brendan Gregg74016c32015-09-21 15:49:21 -070091
92# define BPF program
93bpf_text = """
94#include <uapi/linux/ptrace.h>
Brendan Gregg74016c32015-09-21 15:49:21 -070095
Sasha Goldshteina466c462016-10-06 21:17:59 +030096typedef struct ip_pid {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080097 u64 ip;
Sasha Goldshteina466c462016-10-06 21:17:59 +030098 u64 pid;
99} ip_pid_t;
100
101typedef struct hist_key {
102 ip_pid_t key;
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800103 u64 slot;
Sasha Goldshteina466c462016-10-06 21:17:59 +0300104} hist_key_t;
Brendan Gregg50bbca42015-09-25 12:47:53 -0700105
Brendan Gregg74016c32015-09-21 15:49:21 -0700106BPF_HASH(start, u32);
Brendan Gregg50bbca42015-09-25 12:47:53 -0700107STORAGE
Brendan Gregg74016c32015-09-21 15:49:21 -0700108
109int trace_func_entry(struct pt_regs *ctx)
110{
Sasha Goldshteina466c462016-10-06 21:17:59 +0300111 u64 pid_tgid = bpf_get_current_pid_tgid();
112 u32 pid = pid_tgid;
113 u32 tgid = pid_tgid >> 32;
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800114 u64 ts = bpf_ktime_get_ns();
Brendan Gregg74016c32015-09-21 15:49:21 -0700115
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800116 FILTER
117 ENTRYSTORE
118 start.update(&pid, &ts);
Brendan Gregg74016c32015-09-21 15:49:21 -0700119
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800120 return 0;
Brendan Gregg74016c32015-09-21 15:49:21 -0700121}
122
123int trace_func_return(struct pt_regs *ctx)
124{
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800125 u64 *tsp, delta;
Sasha Goldshteina466c462016-10-06 21:17:59 +0300126 u64 pid_tgid = bpf_get_current_pid_tgid();
127 u32 pid = pid_tgid;
128 u32 tgid = pid_tgid >> 32;
Brendan Gregg74016c32015-09-21 15:49:21 -0700129
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800130 // calculate delta time
131 tsp = start.lookup(&pid);
132 if (tsp == 0) {
133 return 0; // missed start
134 }
135 delta = bpf_ktime_get_ns() - *tsp;
136 start.delete(&pid);
137 FACTOR
Brendan Gregg74016c32015-09-21 15:49:21 -0700138
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800139 // store as histogram
140 STORE
Brendan Gregg74016c32015-09-21 15:49:21 -0700141
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800142 return 0;
Brendan Gregg74016c32015-09-21 15:49:21 -0700143}
144"""
Brendan Gregg50bbca42015-09-25 12:47:53 -0700145
Sasha Goldshteina466c462016-10-06 21:17:59 +0300146# do we need to store the IP and pid for each invocation?
147need_key = args.function or (library and not args.pid)
148
Brendan Gregg50bbca42015-09-25 12:47:53 -0700149# code substitutions
Brendan Gregg74016c32015-09-21 15:49:21 -0700150if args.pid:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800151 bpf_text = bpf_text.replace('FILTER',
htbegin5ac5d6e2017-05-24 22:53:17 +0800152 'if (tgid != %d) { return 0; }' % args.pid)
Brendan Gregg74016c32015-09-21 15:49:21 -0700153else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800154 bpf_text = bpf_text.replace('FILTER', '')
Brendan Gregg74016c32015-09-21 15:49:21 -0700155if args.milliseconds:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800156 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
157 label = "msecs"
Brendan Gregg74016c32015-09-21 15:49:21 -0700158elif args.microseconds:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800159 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
160 label = "usecs"
Brendan Gregg74016c32015-09-21 15:49:21 -0700161else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800162 bpf_text = bpf_text.replace('FACTOR', '')
163 label = "nsecs"
Sasha Goldshteina466c462016-10-06 21:17:59 +0300164if need_key:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800165 bpf_text = bpf_text.replace('STORAGE', 'BPF_HASH(ipaddr, u32);\n' +
Sasha Goldshteina466c462016-10-06 21:17:59 +0300166 'BPF_HISTOGRAM(dist, hist_key_t);')
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800167 # stash the IP on entry, as on return it's kretprobe_trampoline:
168 bpf_text = bpf_text.replace('ENTRYSTORE',
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530169 'u64 ip = PT_REGS_IP(ctx); ipaddr.update(&pid, &ip);')
Sasha Goldshteina466c462016-10-06 21:17:59 +0300170 pid = '-1' if not library else 'tgid'
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800171 bpf_text = bpf_text.replace('STORE',
Sasha Goldshteina466c462016-10-06 21:17:59 +0300172 """
173 u64 ip, *ipp = ipaddr.lookup(&pid);
174 if (ipp) {
175 ip = *ipp;
176 hist_key_t key;
177 key.key.ip = ip;
178 key.key.pid = %s;
179 key.slot = bpf_log2l(delta);
180 dist.increment(key);
181 ipaddr.delete(&pid);
182 }
183 """ % pid)
Brendan Gregg50bbca42015-09-25 12:47:53 -0700184else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800185 bpf_text = bpf_text.replace('STORAGE', 'BPF_HISTOGRAM(dist);')
186 bpf_text = bpf_text.replace('ENTRYSTORE', '')
187 bpf_text = bpf_text.replace('STORE',
188 'dist.increment(bpf_log2l(delta));')
Nathan Scottcf0792f2018-02-02 16:56:50 +1100189if args.verbose or args.ebpf:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800190 print(bpf_text)
Nathan Scottcf0792f2018-02-02 16:56:50 +1100191 if args.ebpf:
192 exit()
Brendan Gregg74016c32015-09-21 15:49:21 -0700193
194# signal handler
195def signal_ignore(signal, frame):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800196 print()
Brendan Gregg74016c32015-09-21 15:49:21 -0700197
198# load BPF program
199b = BPF(text=bpf_text)
Sasha Goldshteina466c462016-10-06 21:17:59 +0300200
201# attach probes
202if not library:
203 b.attach_kprobe(event_re=pattern, fn_name="trace_func_entry")
204 b.attach_kretprobe(event_re=pattern, fn_name="trace_func_return")
205 matched = b.num_open_kprobes()
206else:
Paul Chaignond73c58f2017-01-21 14:25:41 +0100207 b.attach_uprobe(name=library, sym_re=pattern, fn_name="trace_func_entry",
208 pid=args.pid or -1)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300209 b.attach_uretprobe(name=library, sym_re=pattern,
Paul Chaignond73c58f2017-01-21 14:25:41 +0100210 fn_name="trace_func_return", pid=args.pid or -1)
Sasha Goldshteina466c462016-10-06 21:17:59 +0300211 matched = b.num_open_uprobes()
212
Brendan Gregg6b8add02015-09-25 11:16:33 -0700213if matched == 0:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800214 print("0 functions matched by \"%s\". Exiting." % args.pattern)
215 exit()
Brendan Gregg74016c32015-09-21 15:49:21 -0700216
217# header
Brendan Gregg6b8add02015-09-25 11:16:33 -0700218print("Tracing %d functions for \"%s\"... Hit Ctrl-C to end." %
219 (matched / 2, args.pattern))
Brendan Gregg74016c32015-09-21 15:49:21 -0700220
221# output
Sasha Goldshteina466c462016-10-06 21:17:59 +0300222def print_section(key):
223 if not library:
224 return BPF.sym(key[0], -1)
225 else:
226 return "%s [%d]" % (BPF.sym(key[0], key[1]), key[1])
227
Brendan Gregg74016c32015-09-21 15:49:21 -0700228exiting = 0 if args.interval else 1
229dist = b.get_table("dist")
230while (1):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800231 try:
232 sleep(int(args.interval))
233 except KeyboardInterrupt:
234 exiting = 1
235 # as cleanup can take many seconds, trap Ctrl-C:
236 signal.signal(signal.SIGINT, signal_ignore)
Brendan Gregg74016c32015-09-21 15:49:21 -0700237
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800238 print()
239 if args.timestamp:
240 print("%-8s\n" % strftime("%H:%M:%S"), end="")
Brendan Gregg74016c32015-09-21 15:49:21 -0700241
Sasha Goldshteina466c462016-10-06 21:17:59 +0300242 if need_key:
243 dist.print_log2_hist(label, "Function", section_print_fn=print_section,
244 bucket_fn=lambda k: (k.ip, k.pid))
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800245 else:
246 dist.print_log2_hist(label)
247 dist.clear()
Brendan Gregg74016c32015-09-21 15:49:21 -0700248
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800249 if exiting:
250 print("Detaching...")
251 exit()