1 // SPDX-License-Identifier: GPL-2.0
2 #include <vmlinux.h>
3 #include <bpf/bpf_tracing.h>
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_core_read.h>
6 #include "bpf_experimental.h"
7 #include "bpf_misc.h"
8 
9 struct node_acquire {
10 	long key;
11 	long data;
12 	struct bpf_rb_node node;
13 	struct bpf_refcount refcount;
14 };
15 
16 extern void bpf_rcu_read_lock(void) __ksym;
17 extern void bpf_rcu_read_unlock(void) __ksym;
18 
19 #define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
20 private(A) struct bpf_spin_lock glock;
21 private(A) struct bpf_rb_root groot __contains(node_acquire, node);
22 
23 static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
24 {
25 	struct node_acquire *node_a;
26 	struct node_acquire *node_b;
27 
28 	node_a = container_of(a, struct node_acquire, node);
29 	node_b = container_of(b, struct node_acquire, node);
30 
31 	return node_a->key < node_b->key;
32 }
33 
34 SEC("?tc")
35 __failure __msg("Unreleased reference id=4 alloc_insn=21")
36 long rbtree_refcounted_node_ref_escapes(void *ctx)
37 {
38 	struct node_acquire *n, *m;
39 
40 	n = bpf_obj_new(typeof(*n));
41 	if (!n)
42 		return 1;
43 
44 	bpf_spin_lock(&glock);
45 	bpf_rbtree_add(&groot, &n->node, less);
46 	/* m becomes an owning ref but is never drop'd or added to a tree */
47 	m = bpf_refcount_acquire(n);
48 	bpf_spin_unlock(&glock);
49 	if (!m)
50 		return 2;
51 
52 	m->key = 2;
53 	return 0;
54 }
55 
56 SEC("?tc")
57 __failure __msg("Unreleased reference id=3 alloc_insn=9")
58 long rbtree_refcounted_node_ref_escapes_owning_input(void *ctx)
59 {
60 	struct node_acquire *n, *m;
61 
62 	n = bpf_obj_new(typeof(*n));
63 	if (!n)
64 		return 1;
65 
66 	/* m becomes an owning ref but is never drop'd or added to a tree */
67 	m = bpf_refcount_acquire(n);
68 	m->key = 2;
69 
70 	bpf_spin_lock(&glock);
71 	bpf_rbtree_add(&groot, &n->node, less);
72 	bpf_spin_unlock(&glock);
73 
74 	return 0;
75 }
76 
77 SEC("?fentry.s/bpf_testmod_test_read")
78 __failure __msg("function calls are not allowed while holding a lock")
79 int BPF_PROG(rbtree_fail_sleepable_lock_across_rcu,
80 	     struct file *file, struct kobject *kobj,
81 	     struct bin_attribute *bin_attr, char *buf, loff_t off, size_t len)
82 {
83 	struct node_acquire *n;
84 
85 	n = bpf_obj_new(typeof(*n));
86 	if (!n)
87 		return 0;
88 
89 	/* spin_{lock,unlock} are in different RCU CS */
90 	bpf_rcu_read_lock();
91 	bpf_spin_lock(&glock);
92 	bpf_rbtree_add(&groot, &n->node, less);
93 	bpf_rcu_read_unlock();
94 
95 	bpf_rcu_read_lock();
96 	bpf_spin_unlock(&glock);
97 	bpf_rcu_read_unlock();
98 
99 	return 0;
100 }
101 
102 char _license[] SEC("license") = "GPL";
103