1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2
3 /*
4 * filetop Trace file reads/writes by process.
5 * Copyright (c) 2021 Hengqi Chen
6 *
7 * Based on filetop(8) from BCC by Brendan Gregg.
8 * 17-Jul-2021 Hengqi Chen Created this.
9 */
10 #include <argp.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <time.h>
17 #include <unistd.h>
18
19 #include <bpf/libbpf.h>
20 #include <bpf/bpf.h>
21 #include "filetop.h"
22 #include "filetop.skel.h"
23 #include "btf_helpers.h"
24 #include "trace_helpers.h"
25
26 #define warn(...) fprintf(stderr, __VA_ARGS__)
27 #define OUTPUT_ROWS_LIMIT 10240
28
29 enum SORT {
30 ALL,
31 READS,
32 WRITES,
33 RBYTES,
34 WBYTES,
35 };
36
37 static volatile sig_atomic_t exiting = 0;
38
39 static pid_t target_pid = 0;
40 static bool clear_screen = true;
41 static bool regular_file_only = true;
42 static int output_rows = 20;
43 static int sort_by = ALL;
44 static int interval = 1;
45 static int count = 99999999;
46 static bool verbose = false;
47
48 const char *argp_program_version = "filetop 0.1";
49 const char *argp_program_bug_address =
50 "https://github.com/iovisor/bcc/tree/master/libbpf-tools";
51 const char argp_program_doc[] =
52 "Trace file reads/writes by process.\n"
53 "\n"
54 "USAGE: filetop [-h] [-p PID] [interval] [count]\n"
55 "\n"
56 "EXAMPLES:\n"
57 " filetop # file I/O top, refresh every 1s\n"
58 " filetop -p 1216 # only trace PID 1216\n"
59 " filetop 5 10 # 5s summaries, 10 times\n";
60
61 static const struct argp_option opts[] = {
62 { "pid", 'p', "PID", 0, "Process ID to trace" },
63 { "noclear", 'C', NULL, 0, "Don't clear the screen" },
64 { "all", 'a', NULL, 0, "Include special files" },
65 { "sort", 's', "SORT", 0, "Sort columns, default all [all, reads, writes, rbytes, wbytes]" },
66 { "rows", 'r', "ROWS", 0, "Maximum rows to print, default 20" },
67 { "verbose", 'v', NULL, 0, "Verbose debug output" },
68 { NULL, 'h', NULL, OPTION_HIDDEN, "Show the full help" },
69 {},
70 };
71
parse_arg(int key,char * arg,struct argp_state * state)72 static error_t parse_arg(int key, char *arg, struct argp_state *state)
73 {
74 long pid, rows;
75 static int pos_args;
76
77 switch (key) {
78 case 'p':
79 errno = 0;
80 pid = strtol(arg, NULL, 10);
81 if (errno || pid <= 0) {
82 warn("invalid PID: %s\n", arg);
83 argp_usage(state);
84 }
85 target_pid = pid;
86 break;
87 case 'C':
88 clear_screen = false;
89 break;
90 case 'a':
91 regular_file_only = false;
92 break;
93 case 's':
94 if (!strcmp(arg, "all")) {
95 sort_by = ALL;
96 } else if (!strcmp(arg, "reads")) {
97 sort_by = READS;
98 } else if (!strcmp(arg, "writes")) {
99 sort_by = WRITES;
100 } else if (!strcmp(arg, "rbytes")) {
101 sort_by = RBYTES;
102 } else if (!strcmp(arg, "wbytes")) {
103 sort_by = WBYTES;
104 } else {
105 warn("invalid sort method: %s\n", arg);
106 argp_usage(state);
107 }
108 break;
109 case 'r':
110 errno = 0;
111 rows = strtol(arg, NULL, 10);
112 if (errno || rows <= 0) {
113 warn("invalid rows: %s\n", arg);
114 argp_usage(state);
115 }
116 output_rows = rows;
117 if (output_rows > OUTPUT_ROWS_LIMIT)
118 output_rows = OUTPUT_ROWS_LIMIT;
119 break;
120 case 'v':
121 verbose = true;
122 break;
123 case 'h':
124 argp_state_help(state, stderr, ARGP_HELP_STD_HELP);
125 break;
126 case ARGP_KEY_ARG:
127 errno = 0;
128 if (pos_args == 0) {
129 interval = strtol(arg, NULL, 10);
130 if (errno || interval <= 0) {
131 warn("invalid interval\n");
132 argp_usage(state);
133 }
134 } else if (pos_args == 1) {
135 count = strtol(arg, NULL, 10);
136 if (errno || count <= 0) {
137 warn("invalid count\n");
138 argp_usage(state);
139 }
140 } else {
141 warn("unrecognized positional argument: %s\n", arg);
142 argp_usage(state);
143 }
144 pos_args++;
145 break;
146 default:
147 return ARGP_ERR_UNKNOWN;
148 }
149 return 0;
150 }
151
libbpf_print_fn(enum libbpf_print_level level,const char * format,va_list args)152 static int libbpf_print_fn(enum libbpf_print_level level, const char *format, va_list args)
153 {
154 if (level == LIBBPF_DEBUG && !verbose)
155 return 0;
156 return vfprintf(stderr, format, args);
157 }
158
sig_int(int signo)159 static void sig_int(int signo)
160 {
161 exiting = 1;
162 }
163
sort_column(const void * obj1,const void * obj2)164 static int sort_column(const void *obj1, const void *obj2)
165 {
166 struct file_stat *s1 = (struct file_stat *)obj1;
167 struct file_stat *s2 = (struct file_stat *)obj2;
168
169 if (sort_by == READS) {
170 return s2->reads - s1->reads;
171 } else if (sort_by == WRITES) {
172 return s2->writes - s1->writes;
173 } else if (sort_by == RBYTES) {
174 return s2->read_bytes - s1->read_bytes;
175 } else if (sort_by == WBYTES) {
176 return s2->write_bytes - s1->write_bytes;
177 } else {
178 return (s2->reads + s2->writes + s2->read_bytes + s2->write_bytes)
179 - (s1->reads + s1->writes + s1->read_bytes + s1->write_bytes);
180 }
181 }
182
print_stat(struct filetop_bpf * obj)183 static int print_stat(struct filetop_bpf *obj)
184 {
185 FILE *f;
186 time_t t;
187 struct tm *tm;
188 char ts[16], buf[256];
189 struct file_id key, *prev_key = NULL;
190 static struct file_stat values[OUTPUT_ROWS_LIMIT];
191 int n, i, err = 0, rows = 0;
192 int fd = bpf_map__fd(obj->maps.entries);
193
194 f = fopen("/proc/loadavg", "r");
195 if (f) {
196 time(&t);
197 tm = localtime(&t);
198 strftime(ts, sizeof(ts), "%H:%M:%S", tm);
199 memset(buf, 0, sizeof(buf));
200 n = fread(buf, 1, sizeof(buf), f);
201 if (n)
202 printf("%8s loadavg: %s\n", ts, buf);
203 fclose(f);
204 }
205
206 printf("%-7s %-16s %-6s %-6s %-7s %-7s %1s %s\n",
207 "TID", "COMM", "READS", "WRITES", "R_Kb", "W_Kb", "T", "FILE");
208
209 while (1) {
210 err = bpf_map_get_next_key(fd, prev_key, &key);
211 if (err) {
212 if (errno == ENOENT) {
213 err = 0;
214 break;
215 }
216 warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
217 return err;
218 }
219 err = bpf_map_lookup_elem(fd, &key, &values[rows++]);
220 if (err) {
221 warn("bpf_map_lookup_elem failed: %s\n", strerror(errno));
222 return err;
223 }
224 prev_key = &key;
225 }
226
227 qsort(values, rows, sizeof(struct file_stat), sort_column);
228 rows = rows < output_rows ? rows : output_rows;
229 for (i = 0; i < rows; i++)
230 printf("%-7d %-16s %-6lld %-6lld %-7lld %-7lld %c %s\n",
231 values[i].tid, values[i].comm, values[i].reads, values[i].writes,
232 values[i].read_bytes / 1024, values[i].write_bytes / 1024,
233 values[i].type, values[i].filename);
234
235 printf("\n");
236 prev_key = NULL;
237
238 while (1) {
239 err = bpf_map_get_next_key(fd, prev_key, &key);
240 if (err) {
241 if (errno == ENOENT) {
242 err = 0;
243 break;
244 }
245 warn("bpf_map_get_next_key failed: %s\n", strerror(errno));
246 return err;
247 }
248 err = bpf_map_delete_elem(fd, &key);
249 if (err) {
250 warn("bpf_map_delete_elem failed: %s\n", strerror(errno));
251 return err;
252 }
253 prev_key = &key;
254 }
255 return err;
256 }
257
main(int argc,char ** argv)258 int main(int argc, char **argv)
259 {
260 LIBBPF_OPTS(bpf_object_open_opts, open_opts);
261 static const struct argp argp = {
262 .options = opts,
263 .parser = parse_arg,
264 .doc = argp_program_doc,
265 };
266 struct filetop_bpf *obj;
267 int err;
268
269 err = argp_parse(&argp, argc, argv, 0, NULL, NULL);
270 if (err)
271 return err;
272
273 libbpf_set_print(libbpf_print_fn);
274
275 err = ensure_core_btf(&open_opts);
276 if (err) {
277 fprintf(stderr, "failed to fetch necessary BTF for CO-RE: %s\n", strerror(-err));
278 return 1;
279 }
280
281 obj = filetop_bpf__open_opts(&open_opts);
282 if (!obj) {
283 warn("failed to open BPF object\n");
284 return 1;
285 }
286
287 obj->rodata->target_pid = target_pid;
288 obj->rodata->regular_file_only = regular_file_only;
289
290 err = filetop_bpf__load(obj);
291 if (err) {
292 warn("failed to load BPF object: %d\n", err);
293 goto cleanup;
294 }
295
296 err = filetop_bpf__attach(obj);
297 if (err) {
298 warn("failed to attach BPF programs: %d\n", err);
299 goto cleanup;
300 }
301
302 if (signal(SIGINT, sig_int) == SIG_ERR) {
303 warn("can't set signal handler: %s\n", strerror(errno));
304 err = 1;
305 goto cleanup;
306 }
307
308 while (1) {
309 sleep(interval);
310
311 if (clear_screen) {
312 err = system("clear");
313 if (err)
314 goto cleanup;
315 }
316
317 err = print_stat(obj);
318 if (err)
319 goto cleanup;
320
321 count--;
322 if (exiting || !count)
323 goto cleanup;
324 }
325
326 cleanup:
327 filetop_bpf__destroy(obj);
328 cleanup_core_btf(&open_opts);
329
330 return err != 0;
331 }
332