1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2021 Facebook */
3 
4 #include "vmlinux.h"
5 #include <bpf/bpf_helpers.h>
6 #include <bpf/bpf_tracing.h>
7 
8 #ifndef EBUSY
9 #define EBUSY 16
10 #endif
11 
12 char _license[] SEC("license") = "GPL";
13 int nr_del_errs = 0;
14 int test_pid = 0;
15 
16 struct {
17 	__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
18 	__uint(map_flags, BPF_F_NO_PREALLOC);
19 	__type(key, int);
20 	__type(value, long);
21 } map_a SEC(".maps");
22 
23 struct {
24 	__uint(type, BPF_MAP_TYPE_TASK_STORAGE);
25 	__uint(map_flags, BPF_F_NO_PREALLOC);
26 	__type(key, int);
27 	__type(value, long);
28 } map_b SEC(".maps");
29 
30 SEC("fentry/bpf_local_storage_lookup")
BPF_PROG(on_lookup)31 int BPF_PROG(on_lookup)
32 {
33 	struct task_struct *task = bpf_get_current_task_btf();
34 
35 	if (!test_pid || task->pid != test_pid)
36 		return 0;
37 
38 	/* The bpf_task_storage_delete will call
39 	 * bpf_local_storage_lookup.  The prog->active will
40 	 * stop the recursion.
41 	 */
42 	bpf_task_storage_delete(&map_a, task);
43 	bpf_task_storage_delete(&map_b, task);
44 	return 0;
45 }
46 
47 SEC("fentry/bpf_local_storage_update")
BPF_PROG(on_update)48 int BPF_PROG(on_update)
49 {
50 	struct task_struct *task = bpf_get_current_task_btf();
51 	long *ptr;
52 
53 	if (!test_pid || task->pid != test_pid)
54 		return 0;
55 
56 	ptr = bpf_task_storage_get(&map_a, task, 0,
57 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
58 	/* ptr will not be NULL when it is called from
59 	 * the bpf_task_storage_get(&map_b,...F_CREATE) in
60 	 * the BPF_PROG(on_enter) below.  It is because
61 	 * the value can be found in map_a and the kernel
62 	 * does not need to acquire any spin_lock.
63 	 */
64 	if (ptr) {
65 		int err;
66 
67 		*ptr += 1;
68 		err = bpf_task_storage_delete(&map_a, task);
69 		if (err == -EBUSY)
70 			nr_del_errs++;
71 	}
72 
73 	/* This will still fail because map_b is empty and
74 	 * this BPF_PROG(on_update) has failed to acquire
75 	 * the percpu busy lock => meaning potential
76 	 * deadlock is detected and it will fail to create
77 	 * new storage.
78 	 */
79 	ptr = bpf_task_storage_get(&map_b, task, 0,
80 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
81 	if (ptr)
82 		*ptr += 1;
83 
84 	return 0;
85 }
86 
87 SEC("tp_btf/sys_enter")
BPF_PROG(on_enter,struct pt_regs * regs,long id)88 int BPF_PROG(on_enter, struct pt_regs *regs, long id)
89 {
90 	struct task_struct *task;
91 	long *ptr;
92 
93 	task = bpf_get_current_task_btf();
94 	if (!test_pid || task->pid != test_pid)
95 		return 0;
96 
97 	ptr = bpf_task_storage_get(&map_a, task, 0,
98 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
99 	if (ptr && !*ptr)
100 		*ptr = 200;
101 
102 	ptr = bpf_task_storage_get(&map_b, task, 0,
103 				   BPF_LOCAL_STORAGE_GET_F_CREATE);
104 	if (ptr && !*ptr)
105 		*ptr = 100;
106 	return 0;
107 }
108