1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2020 Facebook
3 
4 #include <linux/bpf.h>
5 #include <bpf/bpf_helpers.h>
6 
7 char _license[] SEC("license") = "GPL";
8 
9 struct sample {
10 	int pid;
11 	int seq;
12 	long value;
13 	char comm[16];
14 };
15 
16 struct ringbuf_map {
17 	__uint(type, BPF_MAP_TYPE_RINGBUF);
18 	/* libbpf will adjust to valid page size */
19 	__uint(max_entries, 1000);
20 } ringbuf1 SEC(".maps"),
21   ringbuf2 SEC(".maps");
22 
23 struct {
24 	__uint(type, BPF_MAP_TYPE_ARRAY_OF_MAPS);
25 	__uint(max_entries, 4);
26 	__type(key, int);
27 	__array(values, struct ringbuf_map);
28 } ringbuf_arr SEC(".maps") = {
29 	.values = {
30 		[0] = &ringbuf1,
31 		[2] = &ringbuf2,
32 	},
33 };
34 
35 struct {
36 	__uint(type, BPF_MAP_TYPE_HASH_OF_MAPS);
37 	__uint(max_entries, 1);
38 	__type(key, int);
39 	__array(values, struct ringbuf_map);
40 } ringbuf_hash SEC(".maps") = {
41 	.values = {
42 		[0] = &ringbuf1,
43 	},
44 };
45 
46 /* inputs */
47 int pid = 0;
48 int target_ring = 0;
49 long value = 0;
50 
51 /* outputs */
52 long total = 0;
53 long dropped = 0;
54 long skipped = 0;
55 
56 SEC("tp/syscalls/sys_enter_getpgid")
57 int test_ringbuf(void *ctx)
58 {
59 	int cur_pid = bpf_get_current_pid_tgid() >> 32;
60 	struct sample *sample;
61 	void *rb;
62 	int zero = 0;
63 
64 	if (cur_pid != pid)
65 		return 0;
66 
67 	rb = bpf_map_lookup_elem(&ringbuf_arr, &target_ring);
68 	if (!rb) {
69 		skipped += 1;
70 		return 1;
71 	}
72 
73 	sample = bpf_ringbuf_reserve(rb, sizeof(*sample), 0);
74 	if (!sample) {
75 		dropped += 1;
76 		return 1;
77 	}
78 
79 	sample->pid = pid;
80 	bpf_get_current_comm(sample->comm, sizeof(sample->comm));
81 	sample->value = value;
82 
83 	sample->seq = total;
84 	total += 1;
85 
86 	bpf_ringbuf_submit(sample, 0);
87 
88 	return 0;
89 }
90