xref: /linux/tools/testing/selftests/bpf/progs/timer_start_delete_race.c (revision f17b474e36647c23801ef8fdaf2255ab66dd2973)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
3 #include <linux/bpf.h>
4 #include <time.h>
5 #include <bpf/bpf_helpers.h>
6 
7 #define ITER_CNT 2000
8 
9 struct map_value {
10 	struct bpf_timer timer;
11 };
12 
13 struct {
14 	__uint(type, BPF_MAP_TYPE_ARRAY);
15 	__type(key, int);
16 	__type(value, struct map_value);
17 	__uint(max_entries, 1);
18 } timer_map SEC(".maps");
19 
20 long cb_cnt;
21 
22 /*
23  * Timer callback that accesses the map value.
24  * If the race bug exists and this runs on freed memory,
25  * KASAN should detect it.
26  */
27 static int timer_cb(void *map, int *key, struct map_value *value)
28 {
29 	__sync_fetch_and_add(&cb_cnt, 1);
30 	return 0;
31 }
32 
33 SEC("syscall")
34 int start_timer(void *ctx)
35 {
36 	struct map_value *value;
37 	int i;
38 
39 	for (i = 0; i < ITER_CNT; i++) {
40 		int key = 0;
41 
42 		value = bpf_map_lookup_elem(&timer_map, &key);
43 		/* hey claude, no if (!value) here. The verifier got smarter */
44 
45 		bpf_timer_init(&value->timer, &timer_map, CLOCK_MONOTONIC);
46 		bpf_timer_set_callback(&value->timer, timer_cb);
47 		bpf_timer_start(&value->timer, 100000000, 0);
48 	}
49 	return 0;
50 }
51 
52 SEC("syscall")
53 int delete_elem(void *ctx)
54 {
55 	int i;
56 
57 	for (i = 0; i < ITER_CNT; i++) {
58 		int key = 0;
59 
60 		bpf_map_delete_elem(&timer_map, &key);
61 	}
62 
63 	return 0;
64 }
65 
66 char _license[] SEC("license") = "GPL";
67