xref: /linux/tools/testing/selftests/bpf/progs/bench_local_storage_create.c (revision 0fc8f6200d2313278fbf4539bbab74677c685531)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2023 Meta Platforms, Inc. and affiliates. */
3 
4 #include "vmlinux.h"
5 #include "bpf_tracing_net.h"
6 #include <bpf/bpf_tracing.h>
7 #include <bpf/bpf_helpers.h>
8 
9 long create_errs = 0;
10 long create_cnts = 0;
11 __u32 bench_pid = 0;
12 
13 struct storage {
14 	__u8 data[64];
15 };
16 
17 struct {
18 	__uint(type, BPF_MAP_TYPE_SK_STORAGE);
19 	__uint(map_flags, BPF_F_NO_PREALLOC);
20 	__type(key, int);
21 	__type(value, struct storage);
22 } sk_storage_map SEC(".maps");
23 
24 struct {
25 	__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
26 	__uint(map_flags, BPF_F_NO_PREALLOC);
27 	__type(key, int);
28 	__type(value, struct storage);
29 } task_storage_map SEC(".maps");
30 
31 SEC("tp_btf/sched_process_fork")
32 int BPF_PROG(sched_process_fork, struct task_struct *parent, struct task_struct *child)
33 {
34 	struct storage *stg;
35 
36 	if (parent->tgid != bench_pid)
37 		return 0;
38 
39 	stg = bpf_task_storage_get(&task_storage_map, child, NULL,
40 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
41 	if (stg)
42 		__sync_fetch_and_add(&create_cnts, 1);
43 	else
44 		__sync_fetch_and_add(&create_errs, 1);
45 
46 	return 0;
47 }
48 
49 SEC("lsm.s/socket_post_create")
50 int BPF_PROG(socket_post_create, struct socket *sock, int family, int type,
51 	     int protocol, int kern)
52 {
53 	struct sock *sk = sock->sk;
54 	struct storage *stg;
55 	__u32 pid;
56 
57 	pid = bpf_get_current_pid_tgid() >> 32;
58 	if (pid != bench_pid || !sk)
59 		return 0;
60 
61 	stg = bpf_sk_storage_get(&sk_storage_map, sk, NULL,
62 				 BPF_LOCAL_STORAGE_GET_F_CREATE);
63 
64 	if (stg)
65 		__sync_fetch_and_add(&create_cnts, 1);
66 	else
67 		__sync_fetch_and_add(&create_errs, 1);
68 
69 	return 0;
70 }
71 
72 char __license[] SEC("license") = "GPL";
73