1 #include "../../include/bpf_api.h"
2
3 #define ENTRY_INIT 3
4 #define ENTRY_0 0
5 #define ENTRY_1 1
6 #define MAX_JMP_SIZE 2
7
8 #define FOO 42
9 #define BAR 43
10
11 /* This example doesn't really do anything useful, but it's purpose is to
12 * demonstrate eBPF tail calls on a very simple example.
13 *
14 * cls_entry() is our classifier entry point, from there we jump based on
15 * skb->hash into cls_case1() or cls_case2(). They are both part of the
16 * program array jmp_tc. Indicated via __section_tail(), the tc loader
17 * populates the program arrays with the loaded file descriptors already.
18 *
19 * To demonstrate nested jumps, cls_case2() jumps within the same jmp_tc
20 * array to cls_case1(). And whenever we arrive at cls_case1(), we jump
21 * into cls_exit(), part of the jump array jmp_ex.
22 *
23 * Also, to show it's possible, all programs share map_sh and dump the value
24 * that the entry point incremented. The sections that are loaded into a
25 * program array can be atomically replaced during run-time, e.g. to change
26 * classifier behaviour.
27 */
28
29 BPF_PROG_ARRAY(jmp_tc, FOO, PIN_OBJECT_NS, MAX_JMP_SIZE);
30 BPF_PROG_ARRAY(jmp_ex, BAR, PIN_OBJECT_NS, 1);
31
32 BPF_ARRAY4(map_sh, 0, PIN_OBJECT_NS, 1);
33
__section_tail(FOO,ENTRY_0)34 __section_tail(FOO, ENTRY_0)
35 int cls_case1(struct __sk_buff *skb)
36 {
37 char fmt[] = "case1: map-val: %d from:%u\n";
38 int key = 0, *val;
39
40 val = map_lookup_elem(&map_sh, &key);
41 if (val)
42 trace_printk(fmt, sizeof(fmt), *val, skb->cb[0]);
43
44 skb->cb[0] = ENTRY_0;
45 tail_call(skb, &jmp_ex, ENTRY_0);
46
47 return BPF_H_DEFAULT;
48 }
49
__section_tail(FOO,ENTRY_1)50 __section_tail(FOO, ENTRY_1)
51 int cls_case2(struct __sk_buff *skb)
52 {
53 char fmt[] = "case2: map-val: %d from:%u\n";
54 int key = 0, *val;
55
56 val = map_lookup_elem(&map_sh, &key);
57 if (val)
58 trace_printk(fmt, sizeof(fmt), *val, skb->cb[0]);
59
60 skb->cb[0] = ENTRY_1;
61 tail_call(skb, &jmp_tc, ENTRY_0);
62
63 return BPF_H_DEFAULT;
64 }
65
__section_tail(BAR,ENTRY_0)66 __section_tail(BAR, ENTRY_0)
67 int cls_exit(struct __sk_buff *skb)
68 {
69 char fmt[] = "exit: map-val: %d from:%u\n";
70 int key = 0, *val;
71
72 val = map_lookup_elem(&map_sh, &key);
73 if (val)
74 trace_printk(fmt, sizeof(fmt), *val, skb->cb[0]);
75
76 /* Termination point. */
77 return BPF_H_DEFAULT;
78 }
79
80 __section_cls_entry
cls_entry(struct __sk_buff * skb)81 int cls_entry(struct __sk_buff *skb)
82 {
83 char fmt[] = "fallthrough\n";
84 int key = 0, *val;
85
86 /* For transferring state, we can use skb->cb[0] ... skb->cb[4]. */
87 val = map_lookup_elem(&map_sh, &key);
88 if (val) {
89 lock_xadd(val, 1);
90
91 skb->cb[0] = ENTRY_INIT;
92 tail_call(skb, &jmp_tc, skb->hash & (MAX_JMP_SIZE - 1));
93 }
94
95 trace_printk(fmt, sizeof(fmt));
96 return BPF_H_DEFAULT;
97 }
98
99 BPF_LICENSE("GPL");
100