xref: /linux/tools/testing/selftests/bpf/progs/test_tcpnotify_kern.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <stddef.h>
3 #include <string.h>
4 #include <netinet/in.h>
5 #include <linux/bpf.h>
6 #include <linux/if_ether.h>
7 #include <linux/if_packet.h>
8 #include <linux/ip.h>
9 #include <linux/ipv6.h>
10 #include <linux/types.h>
11 #include <linux/socket.h>
12 #include <linux/tcp.h>
13 #include <bpf/bpf_helpers.h>
14 #include <bpf/bpf_endian.h>
15 #include "test_tcpnotify.h"
16 
17 struct {
18 	__uint(type, BPF_MAP_TYPE_ARRAY);
19 	__uint(max_entries, 4);
20 	__type(key, __u32);
21 	__type(value, struct tcpnotify_globals);
22 } global_map SEC(".maps");
23 
24 struct {
25 	__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
26 	__type(key, int);
27 	__type(value, __u32);
28 } perf_event_map SEC(".maps");
29 
30 SEC("sockops")
31 int bpf_testcb(struct bpf_sock_ops *skops)
32 {
33 	int rv = -1;
34 	int op;
35 
36 	op = (int) skops->op;
37 
38 	if (bpf_ntohl(skops->remote_port) != TESTPORT) {
39 		skops->reply = -1;
40 		return 0;
41 	}
42 
43 	switch (op) {
44 	case BPF_SOCK_OPS_TIMEOUT_INIT:
45 	case BPF_SOCK_OPS_RWND_INIT:
46 	case BPF_SOCK_OPS_NEEDS_ECN:
47 	case BPF_SOCK_OPS_BASE_RTT:
48 	case BPF_SOCK_OPS_RTO_CB:
49 		rv = 1;
50 		break;
51 
52 	case BPF_SOCK_OPS_TCP_CONNECT_CB:
53 	case BPF_SOCK_OPS_TCP_LISTEN_CB:
54 	case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB:
55 	case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB:
56 		bpf_sock_ops_cb_flags_set(skops, (BPF_SOCK_OPS_RETRANS_CB_FLAG|
57 					  BPF_SOCK_OPS_RTO_CB_FLAG));
58 		rv = 1;
59 		break;
60 	case BPF_SOCK_OPS_RETRANS_CB: {
61 			__u32 key = 0;
62 			struct tcpnotify_globals g, *gp;
63 			struct tcp_notifier msg = {
64 				.type = 0xde,
65 				.subtype = 0xad,
66 				.source = 0xbe,
67 				.hash = 0xef,
68 			};
69 
70 			rv = 1;
71 
72 			/* Update results */
73 			gp = bpf_map_lookup_elem(&global_map, &key);
74 			if (!gp)
75 				break;
76 			g = *gp;
77 			g.total_retrans = skops->total_retrans;
78 			g.ncalls++;
79 			bpf_map_update_elem(&global_map, &key, &g,
80 					    BPF_ANY);
81 			bpf_perf_event_output(skops, &perf_event_map,
82 					      BPF_F_CURRENT_CPU,
83 					      &msg, sizeof(msg));
84 		}
85 		break;
86 	default:
87 		rv = -1;
88 	}
89 	skops->reply = rv;
90 	return 1;
91 }
92 char _license[] SEC("license") = "GPL";
93