blob: d2e65f2dd4d4e934b3881d2d04a7dde5c22e7276 [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")
Brendan Gregg74016c32015-09-21 15:49:21 -070066args = parser.parse_args()
Sasha Goldshteina466c462016-10-06 21:17:59 +030067
68def bail(error):
69 print("Error: " + error)
70 exit(1)
71
72parts = args.pattern.split(':')
73if len(parts) == 1:
74 library = None
75 pattern = args.pattern
76elif len(parts) == 2:
77 library = parts[0]
78 libpath = BPF.find_library(library) or BPF.find_exe(library)
79 if not libpath:
80 bail("can't resolve library %s" % library)
81 library = libpath
82 pattern = parts[1]
83else:
84 bail("unrecognized pattern format '%s'" % pattern)
85
Brendan Gregg74016c32015-09-21 15:49:21 -070086if not args.regexp:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080087 pattern = pattern.replace('*', '.*')
88 pattern = '^' + pattern + '$'
Brendan Gregg74016c32015-09-21 15:49:21 -070089
90# define BPF program
91bpf_text = """
92#include <uapi/linux/ptrace.h>
Brendan Gregg74016c32015-09-21 15:49:21 -070093
Sasha Goldshteina466c462016-10-06 21:17:59 +030094typedef struct ip_pid {
Alexei Starovoitovbdf07732016-01-14 10:09:20 -080095 u64 ip;
Sasha Goldshteina466c462016-10-06 21:17:59 +030096 u64 pid;
97} ip_pid_t;
98
99typedef struct hist_key {
100 ip_pid_t key;
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800101 u64 slot;
Sasha Goldshteina466c462016-10-06 21:17:59 +0300102} hist_key_t;
Brendan Gregg50bbca42015-09-25 12:47:53 -0700103
Brendan Gregg74016c32015-09-21 15:49:21 -0700104BPF_HASH(start, u32);
Brendan Gregg50bbca42015-09-25 12:47:53 -0700105STORAGE
Brendan Gregg74016c32015-09-21 15:49:21 -0700106
107int trace_func_entry(struct pt_regs *ctx)
108{
Sasha Goldshteina466c462016-10-06 21:17:59 +0300109 u64 pid_tgid = bpf_get_current_pid_tgid();
110 u32 pid = pid_tgid;
111 u32 tgid = pid_tgid >> 32;
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800112 u64 ts = bpf_ktime_get_ns();
Brendan Gregg74016c32015-09-21 15:49:21 -0700113
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800114 FILTER
115 ENTRYSTORE
116 start.update(&pid, &ts);
Brendan Gregg74016c32015-09-21 15:49:21 -0700117
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800118 return 0;
Brendan Gregg74016c32015-09-21 15:49:21 -0700119}
120
121int trace_func_return(struct pt_regs *ctx)
122{
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800123 u64 *tsp, delta;
Sasha Goldshteina466c462016-10-06 21:17:59 +0300124 u64 pid_tgid = bpf_get_current_pid_tgid();
125 u32 pid = pid_tgid;
126 u32 tgid = pid_tgid >> 32;
Brendan Gregg74016c32015-09-21 15:49:21 -0700127
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800128 // calculate delta time
129 tsp = start.lookup(&pid);
130 if (tsp == 0) {
131 return 0; // missed start
132 }
133 delta = bpf_ktime_get_ns() - *tsp;
134 start.delete(&pid);
135 FACTOR
Brendan Gregg74016c32015-09-21 15:49:21 -0700136
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800137 // store as histogram
138 STORE
Brendan Gregg74016c32015-09-21 15:49:21 -0700139
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800140 return 0;
Brendan Gregg74016c32015-09-21 15:49:21 -0700141}
142"""
Brendan Gregg50bbca42015-09-25 12:47:53 -0700143
Sasha Goldshteina466c462016-10-06 21:17:59 +0300144# do we need to store the IP and pid for each invocation?
145need_key = args.function or (library and not args.pid)
146
Brendan Gregg50bbca42015-09-25 12:47:53 -0700147# code substitutions
Brendan Gregg74016c32015-09-21 15:49:21 -0700148if args.pid:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800149 bpf_text = bpf_text.replace('FILTER',
htbegin5ac5d6e2017-05-24 22:53:17 +0800150 'if (tgid != %d) { return 0; }' % args.pid)
Brendan Gregg74016c32015-09-21 15:49:21 -0700151else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800152 bpf_text = bpf_text.replace('FILTER', '')
Brendan Gregg74016c32015-09-21 15:49:21 -0700153if args.milliseconds:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800154 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000000;')
155 label = "msecs"
Brendan Gregg74016c32015-09-21 15:49:21 -0700156elif args.microseconds:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800157 bpf_text = bpf_text.replace('FACTOR', 'delta /= 1000;')
158 label = "usecs"
Brendan Gregg74016c32015-09-21 15:49:21 -0700159else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800160 bpf_text = bpf_text.replace('FACTOR', '')
161 label = "nsecs"
Sasha Goldshteina466c462016-10-06 21:17:59 +0300162if need_key:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800163 bpf_text = bpf_text.replace('STORAGE', 'BPF_HASH(ipaddr, u32);\n' +
Sasha Goldshteina466c462016-10-06 21:17:59 +0300164 'BPF_HISTOGRAM(dist, hist_key_t);')
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800165 # stash the IP on entry, as on return it's kretprobe_trampoline:
166 bpf_text = bpf_text.replace('ENTRYSTORE',
Naveen N. Rao4afa96a2016-05-03 14:54:21 +0530167 'u64 ip = PT_REGS_IP(ctx); ipaddr.update(&pid, &ip);')
Sasha Goldshteina466c462016-10-06 21:17:59 +0300168 pid = '-1' if not library else 'tgid'
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800169 bpf_text = bpf_text.replace('STORE',
Sasha Goldshteina466c462016-10-06 21:17:59 +0300170 """
171 u64 ip, *ipp = ipaddr.lookup(&pid);
172 if (ipp) {
173 ip = *ipp;
174 hist_key_t key;
175 key.key.ip = ip;
176 key.key.pid = %s;
177 key.slot = bpf_log2l(delta);
178 dist.increment(key);
179 ipaddr.delete(&pid);
180 }
181 """ % pid)
Brendan Gregg50bbca42015-09-25 12:47:53 -0700182else:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800183 bpf_text = bpf_text.replace('STORAGE', 'BPF_HISTOGRAM(dist);')
184 bpf_text = bpf_text.replace('ENTRYSTORE', '')
185 bpf_text = bpf_text.replace('STORE',
186 'dist.increment(bpf_log2l(delta));')
Sasha Goldshteina466c462016-10-06 21:17:59 +0300187if args.verbose:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800188 print(bpf_text)
Brendan Gregg74016c32015-09-21 15:49:21 -0700189
190# signal handler
191def signal_ignore(signal, frame):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800192 print()
Brendan Gregg74016c32015-09-21 15:49:21 -0700193
194# load BPF program
195b = BPF(text=bpf_text)
Sasha Goldshteina466c462016-10-06 21:17:59 +0300196
197# attach probes
198if not library:
199 b.attach_kprobe(event_re=pattern, fn_name="trace_func_entry")
200 b.attach_kretprobe(event_re=pattern, fn_name="trace_func_return")
201 matched = b.num_open_kprobes()
202else:
Paul Chaignond73c58f2017-01-21 14:25:41 +0100203 b.attach_uprobe(name=library, sym_re=pattern, fn_name="trace_func_entry",
204 pid=args.pid or -1)
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300205 b.attach_uretprobe(name=library, sym_re=pattern,
Paul Chaignond73c58f2017-01-21 14:25:41 +0100206 fn_name="trace_func_return", pid=args.pid or -1)
Sasha Goldshteina466c462016-10-06 21:17:59 +0300207 matched = b.num_open_uprobes()
208
Brendan Gregg6b8add02015-09-25 11:16:33 -0700209if matched == 0:
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800210 print("0 functions matched by \"%s\". Exiting." % args.pattern)
211 exit()
Brendan Gregg74016c32015-09-21 15:49:21 -0700212
213# header
Brendan Gregg6b8add02015-09-25 11:16:33 -0700214print("Tracing %d functions for \"%s\"... Hit Ctrl-C to end." %
215 (matched / 2, args.pattern))
Brendan Gregg74016c32015-09-21 15:49:21 -0700216
217# output
Sasha Goldshteina466c462016-10-06 21:17:59 +0300218def print_section(key):
219 if not library:
220 return BPF.sym(key[0], -1)
221 else:
222 return "%s [%d]" % (BPF.sym(key[0], key[1]), key[1])
223
Brendan Gregg74016c32015-09-21 15:49:21 -0700224exiting = 0 if args.interval else 1
225dist = b.get_table("dist")
226while (1):
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800227 try:
228 sleep(int(args.interval))
229 except KeyboardInterrupt:
230 exiting = 1
231 # as cleanup can take many seconds, trap Ctrl-C:
232 signal.signal(signal.SIGINT, signal_ignore)
Brendan Gregg74016c32015-09-21 15:49:21 -0700233
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800234 print()
235 if args.timestamp:
236 print("%-8s\n" % strftime("%H:%M:%S"), end="")
Brendan Gregg74016c32015-09-21 15:49:21 -0700237
Sasha Goldshteina466c462016-10-06 21:17:59 +0300238 if need_key:
239 dist.print_log2_hist(label, "Function", section_print_fn=print_section,
240 bucket_fn=lambda k: (k.ip, k.pid))
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800241 else:
242 dist.print_log2_hist(label)
243 dist.clear()
Brendan Gregg74016c32015-09-21 15:49:21 -0700244
Alexei Starovoitovbdf07732016-01-14 10:09:20 -0800245 if exiting:
246 print("Detaching...")
247 exit()