1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 /* Copyright (c) 2021 Hengqi Chen */
3 #include <vmlinux.h>
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_core_read.h>
6 #include <bpf/bpf_tracing.h>
7 #include "filetop.h"
8 #include "stat.h"
9
10 #define MAX_ENTRIES 10240
11
12 const volatile pid_t target_pid = 0;
13 const volatile bool regular_file_only = true;
14 static struct file_stat zero_value = {};
15
16 struct {
17 __uint(type, BPF_MAP_TYPE_HASH);
18 __uint(max_entries, MAX_ENTRIES);
19 __type(key, struct file_id);
20 __type(value, struct file_stat);
21 } entries SEC(".maps");
22
get_file_path(struct file * file,char * buf,size_t size)23 static void get_file_path(struct file *file, char *buf, size_t size)
24 {
25 struct qstr dname;
26
27 dname = BPF_CORE_READ(file, f_path.dentry, d_name);
28 bpf_probe_read_kernel(buf, size, dname.name);
29 }
30
probe_entry(struct pt_regs * ctx,struct file * file,size_t count,enum op op)31 static int probe_entry(struct pt_regs *ctx, struct file *file, size_t count, enum op op)
32 {
33 __u64 pid_tgid = bpf_get_current_pid_tgid();
34 __u32 pid = pid_tgid >> 32;
35 __u32 tid = (__u32)pid_tgid;
36 int mode;
37 struct file_id key = {};
38 struct file_stat *valuep;
39
40 if (target_pid && target_pid != pid)
41 return 0;
42
43 mode = BPF_CORE_READ(file, f_inode, i_mode);
44 if (regular_file_only && !S_ISREG(mode))
45 return 0;
46
47 key.dev = BPF_CORE_READ(file, f_inode, i_sb, s_dev);
48 key.rdev = BPF_CORE_READ(file, f_inode, i_rdev);
49 key.inode = BPF_CORE_READ(file, f_inode, i_ino);
50 key.pid = pid;
51 key.tid = tid;
52 valuep = bpf_map_lookup_elem(&entries, &key);
53 if (!valuep) {
54 bpf_map_update_elem(&entries, &key, &zero_value, BPF_ANY);
55 valuep = bpf_map_lookup_elem(&entries, &key);
56 if (!valuep)
57 return 0;
58 valuep->pid = pid;
59 valuep->tid = tid;
60 bpf_get_current_comm(&valuep->comm, sizeof(valuep->comm));
61 get_file_path(file, valuep->filename, sizeof(valuep->filename));
62 if (S_ISREG(mode)) {
63 valuep->type = 'R';
64 } else if (S_ISSOCK(mode)) {
65 valuep->type = 'S';
66 } else {
67 valuep->type = 'O';
68 }
69 }
70 if (op == READ) {
71 valuep->reads++;
72 valuep->read_bytes += count;
73 } else { /* op == WRITE */
74 valuep->writes++;
75 valuep->write_bytes += count;
76 }
77 return 0;
78 };
79
80 SEC("kprobe/vfs_read")
BPF_KPROBE(vfs_read_entry,struct file * file,char * buf,size_t count,loff_t * pos)81 int BPF_KPROBE(vfs_read_entry, struct file *file, char *buf, size_t count, loff_t *pos)
82 {
83 return probe_entry(ctx, file, count, READ);
84 }
85
86 SEC("kprobe/vfs_write")
BPF_KPROBE(vfs_write_entry,struct file * file,const char * buf,size_t count,loff_t * pos)87 int BPF_KPROBE(vfs_write_entry, struct file *file, const char *buf, size_t count, loff_t *pos)
88 {
89 return probe_entry(ctx, file, count, WRITE);
90 }
91
92 char LICENSE[] SEC("license") = "Dual BSD/GPL";
93