1 // SPDX-License-Identifier: GPL-2.0
2 // Copyright (c) 2019 Facebook
4 #include <linux/version.h>
5 #include <bpf/bpf_helpers.h>
10 struct bpf_spin_lock lock;
15 __uint(type, BPF_MAP_TYPE_HASH);
16 __uint(max_entries, 1);
18 __type(value, struct hmap_elem);
22 struct bpf_spin_lock lock;
27 __uint(type, BPF_MAP_TYPE_CGROUP_STORAGE);
28 __type(key, struct bpf_cgroup_storage_key);
29 __type(value, struct cls_elem);
30 } cls_map SEC(".maps");
33 struct bpf_spin_lock lock;
35 unsigned long long lasttime;
41 __uint(type, BPF_MAP_TYPE_ARRAY);
42 __uint(max_entries, 1);
44 __type(value, struct bpf_vqueue);
45 } vqueue SEC(".maps");
47 #define CREDIT_PER_NS(delta, rate) (((delta) * rate) >> 20)
49 SEC("cgroup_skb/ingress")
50 int bpf_spin_lock_test(struct __sk_buff *skb)
52 volatile int credit = 0, max_credit = 100, pkt_len = 64;
53 struct hmap_elem zero = {}, *val;
54 unsigned long long curtime;
60 val = bpf_map_lookup_elem(&hmap, &key);
62 bpf_map_update_elem(&hmap, &key, &zero, 0);
63 val = bpf_map_lookup_elem(&hmap, &key);
69 /* spin_lock in hash map run time test */
70 bpf_spin_lock(&val->lock);
75 if (val->cnt != 0 && val->cnt != 1)
77 bpf_spin_unlock(&val->lock);
79 /* spin_lock in array. virtual queue demo */
80 q = bpf_map_lookup_elem(&vqueue, &key);
83 curtime = bpf_ktime_get_ns();
84 bpf_spin_lock(&q->lock);
85 q->credit += CREDIT_PER_NS(curtime - q->lasttime, q->rate);
86 q->lasttime = curtime;
87 if (q->credit > max_credit)
88 q->credit = max_credit;
91 bpf_spin_unlock(&q->lock);
95 /* spin_lock in cgroup local storage */
96 cls = bpf_get_local_storage(&cls_map, 0);
97 bpf_spin_lock(&cls->lock);
99 bpf_spin_unlock(&cls->lock);
104 char _license[] SEC("license") = "GPL";