1 // SPDX-License-Identifier: GPL-2.0
9 #include <sys/syscall.h>
12 #include <linux/bpf.h>
13 #include <sys/socket.h>
15 #include <bpf/libbpf.h>
16 #include <sys/ioctl.h>
17 #include <linux/rtnetlink.h>
19 #include <linux/perf_event.h>
20 #include <linux/err.h>
22 #include "bpf_rlimit.h"
24 #include "cgroup_helpers.h"
26 #include "test_tcpnotify.h"
27 #include "trace_helpers.h"
29 #define SOCKET_BUFFER_SIZE (getpagesize() < 8192L ? getpagesize() : 8192L)
34 static void dummyfn(void *ctx
, int cpu
, void *data
, __u32 size
)
36 struct tcp_notifier
*t
= data
;
38 if (t
->type
!= 0xde || t
->subtype
!= 0xad ||
39 t
->source
!= 0xbe || t
->hash
!= 0xef)
44 void tcp_notifier_poller(struct perf_buffer
*pb
)
49 err
= perf_buffer__poll(pb
, 100);
50 if (err
< 0 && err
!= -EINTR
) {
51 printf("failed perf_buffer__poll: %d\n", err
);
57 static void *poller_thread(void *arg
)
59 struct perf_buffer
*pb
= arg
;
61 tcp_notifier_poller(pb
);
65 int verify_result(const struct tcpnotify_globals
*result
)
67 return (result
->ncalls
> 0 && result
->ncalls
== rx_callbacks
? 0 : 1);
70 int main(int argc
, char **argv
)
72 const char *file
= "test_tcpnotify_kern.o";
73 struct bpf_map
*perf_map
, *global_map
;
74 struct perf_buffer_opts pb_opts
= {};
75 struct tcpnotify_globals g
= {0};
76 struct perf_buffer
*pb
= NULL
;
77 const char *cg_path
= "/foo";
78 int prog_fd
, rv
, cg_fd
= -1;
79 int error
= EXIT_FAILURE
;
80 struct bpf_object
*obj
;
87 pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t
), &cpuset
);
89 if (setup_cgroup_environment())
92 cg_fd
= create_and_get_cgroup(cg_path
);
96 if (join_cgroup(cg_path
))
99 if (bpf_prog_load(file
, BPF_PROG_TYPE_SOCK_OPS
, &obj
, &prog_fd
)) {
100 printf("FAILED: load_bpf_file failed for: %s\n", file
);
104 rv
= bpf_prog_attach(prog_fd
, cg_fd
, BPF_CGROUP_SOCK_OPS
, 0);
106 printf("FAILED: bpf_prog_attach: %d (%s)\n",
107 error
, strerror(errno
));
111 perf_map
= bpf_object__find_map_by_name(obj
, "perf_event_map");
113 printf("FAIL:map '%s' not found\n", "perf_event_map");
117 global_map
= bpf_object__find_map_by_name(obj
, "global_map");
119 printf("FAIL:map '%s' not found\n", "global_map");
123 pb_opts
.sample_cb
= dummyfn
;
124 pb
= perf_buffer__new(bpf_map__fd(perf_map
), 8, &pb_opts
);
128 pthread_create(&tid
, NULL
, poller_thread
, pb
);
131 "iptables -A INPUT -p tcp --dport %d -j DROP",
136 "nc 127.0.0.1 %d < /etc/passwd > /dev/null 2>&1 ",
141 "iptables -D INPUT -p tcp --dport %d -j DROP",
145 rv
= bpf_map_lookup_elem(bpf_map__fd(global_map
), &key
, &g
);
147 printf("FAILED: bpf_map_lookup_elem returns %d\n", rv
);
153 if (verify_result(&g
)) {
154 printf("FAILED: Wrong stats Expected %d calls, got %d\n",
155 g
.ncalls
, rx_callbacks
);
162 bpf_prog_detach(cg_fd
, BPF_CGROUP_SOCK_OPS
);
164 cleanup_cgroup_environment();
165 if (!IS_ERR_OR_NULL(pb
))
166 perf_buffer__free(pb
);