eBPF-based security platform
coccinelle: refuse the BPF concurrency hazards upatches meet
Daniel Borkmanncce83427bb88
diff --git a/AGENTS.md b/AGENTS.mdindex 8544244a..01a829de 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -350,13 +350,13 @@ one usually still compiles and passes tests.- **upatch state lives in BPF arenas where possible.** A upatch thataccumulates records keeps them in its one `BPF_MAP_TYPE_ARENA` map andships a `shirudo_serialize__<map>` program that walks them; hash and- array maps are for what cannot live in an arena: task, socket and- per-CPU scratch state, lookup keys the kernel owns, and the serializer- output. An arena gives one consistent snapshot, memory the serializer- can reset between exports, and an overflow count the record carries,- where an element-by-element read of a plain map gives a torn view and- a table that silently fills up. `upatches/kernel-obs/obs_table.h` is- the template to instantiate.+ array maps are for what cannot live in an arena: task and socket+ state, per-CPU counters and scratch, lookup keys the kernel owns, and+ the serializer output. An arena gives one consistent snapshot, memory+ the serializer can reset between exports, and an overflow count the+ record carries, where an element-by-element read of a plain map gives+ a torn view and a table that silently fills up.+ `upatches/kernel-obs/obs_table.h` is the template to instantiate.- **Test the locking of complex upatch BPF code with blitmus.** Whereprograms on several CPUs share state through atomics, acquire andrelease, or a lock or lock-free structure built from them, write the@@ -366,6 +366,55 @@ one usually still compiles and passes tests.`READ_ONCE()`, `WRITE_ONCE()`, acquire, release and the BPF atomics,not `bpf_spin_lock()` or RCU.`Documentation/upatches/write/memory-consistency/blitmus.rst` shows how.+- **Write upatch BPF code for runs that interleave, and apply each fix+ only under the preemption model and program types its hazard needs**,+ never to every program by reflex. Runs on different CPUs at once exist+ on every kernel: update a value other CPUs share, of a map that is not+ per-CPU or in inode, socket or cgroup storage, with+ `__sync_fetch_and_add()` and its kin; insert a missing key with+ `BPF_NOEXIST` and look it up again on `-EEXIST`; check every+ compare-and-swap result, as a failed one changes and orders nothing;+ publish a filled record with+ `__atomic_store_n(&p, v, __ATOMIC_RELEASE)` or a value-returning+ atomic, never `WRITE_ONCE()`, and read it through `READ_ONCE()` and an+ address dependency, or a load-acquire where the code compares the index+ with a constant first; expect writes that land in the half of a double+ buffer being drained, as BPF has no grace period; and read user memory+ once.++ A second run on one CPU before the first one ends depends on the+ kernel. `PREEMPT`, `PREEMPT_RT` and `PREEMPT_DYNAMIC`, the default and+ what distribution kernels use, bring preemptible RCU, and+ `PREEMPT_LAZY` on its own does not. Since 7.0 `PREEMPT_DYNAMIC` boots+ only `full` or `lazy`, not the `voluntary` distribution kernels used to+ boot, in which no task preempted a running program: do not carry that+ assumption over. With preemptible RCU another task can preempt most+ programs, and on every kernel `syscall` and sleepable ones. On every+ kernel a softirq can run on top of a run in a process, and `lsm`,+ `syscall`, `cgroup_skb`, `netfilter` and `uprobe.multi` programs have+ no guard against a second run of themselves, while `kprobe` and+ `kretprobe` programs never interleave with each other on a CPU and+ `fentry`, `fexit`, `fmod_ret` and `tp_btf` programs never with+ themselves. Only where such a second run can come is a per-CPU map+ value, or a slot picked by `bpf_get_smp_processor_id()`, shared between+ runs: keep scratch there in task storage where no program a softirq+ runs uses it (as the seal does), on the stack, or behind a busy flag+ taken with `__atomic_exchange_n()` and given back with a release store,+ and update a per-CPU counter there with an atomic. Elsewhere, such as a+ counter only one `kprobe` program updates, the plain form is right. A+ upatch whose correctness depends on the model says in its `README.md`+ which one it is written for, and its code is checked against that one.+ The test kernel is built with `PREEMPT_LAZY` alone, so the VM suite+ shows the preemption cases only for `syscall` and sleepable programs.++ The `bpf_` rules in `testing/coccinelle/` refuse these patterns within+ one function. No rule refuses per-CPU scratch, as whether it is a+ hazard depends on the kernel and the programs that share a map, which a+ rule cannot tell: review decides. A hazard spread over functions, or a+ file with its own token-pasting macros such as `obs_table.h`, needs+ review and blitmus.+ `Documentation/upatches/write/memory-consistency/hazards.rst` says+ where each hazard applies.## Memory, JSON and loggingdiff --git a/Documentation/contribute/code/developer-guide.rst b/Documentation/contribute/code/developer-guide.rstindex 08c6171e..e3051fd8 100644--- a/Documentation/contribute/code/developer-guide.rst+++ b/Documentation/contribute/code/developer-guide.rst@@ -640,6 +640,21 @@ can rewrite what it finds does so with ``-D patch``:* - ``fclose_unchecked``- ``fclose()`` of a stream opened for writing with its resultignored, after CERT C ERR33-C.+ * - ``bpf_map_rmw``+ - ``++``, ``+=`` or ``|=`` through the value of a map that is not+ per-CPU, or through inode, socket or cgroup storage, which other+ CPUs update meanwhile.+ * - ``bpf_cas_unchecked``+ - A compare-and-swap whose result is dropped.+ * - ``bpf_check_then_insert``+ - A ``BPF_ANY`` update of a key after a lookup found it missing,+ which races with another CPU doing the same.+ * - ``bpf_publish``+ - ``WRITE_ONCE()`` of a pointer, which publishes what it points to+ without ordering the stores that filled it.+ * - ``bpf_user_double_fetch``+ - Two reads of the same user address, between which the memory can+ change.A new pattern worth refusing gets a rule: write it from scratch underthe BSD-2-Clause, with a header that says why the pattern is refused,@@ -652,6 +667,19 @@ includes, which keeps it fast but leaves the types they declareunknown. A rule that needs them, as ``sizeof_ptr`` needs the type of astruct member, names its include options on a ``#spatch`` line.+The ``bpf_`` rules read the BPF sources through+:src:`testing/coccinelle/bpf.macros`, which tells Coccinelle what+``SEC()``, ``BPF_PROG()`` and the map definition macros mean, and each+declares ``SEC`` an attribute. Without that, Coccinelle takes a map+defined as ``} name SEC(".maps");`` for a type and skips every function+that takes its address, without an error. A file that defines its own+token-pasting macros, as :src:`upatches/kernel-obs/obs_table.h` does,+stays out of their reach. Each matches a hazard that exists on every+kernel. Per-CPU memory used as scratch is a hazard only under some+preemption models and program types, which a rule cannot tell, so no+rule refuses it. :doc:`/upatches/write/memory-consistency/hazards`+explains each hazard and where it applies.+Next steps----------diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex ed278f7e..a8c99507 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -52,7 +52,8 @@ signed config image.- ``check-coccinelle.sh``: a match that fails the check with itsfile, line and rule, the vendored sources left out, a rule namedalone, the rewrite of ``-D patch``, a case for each rule taken- from CERT C, and the tree itself+ from CERT C, a case for each BPF hazard rule beside the safe+ form it leaves alone, and the tree itself* - ``t0007-check-operator-linkage``- ``check-operator-linkage.sh``: the libraries an operator binarymay link and its own interpreter, another loader, a librarydiff --git a/Documentation/upatches/write/memory-consistency/hazards.rst b/Documentation/upatches/write/memory-consistency/hazards.rstnew file mode 100644index 00000000..5f2c2fc5--- /dev/null+++ b/Documentation/upatches/write/memory-consistency/hazards.rst@@ -0,0 +1,249 @@+..+ SPDX-License-Identifier: BSD-2-Clause+ Copyright (c) 2026 Authors of shirudo++:page-type: Explanation+:audience: upatch authors++Concurrency hazards+===================++An upatch's programs run on every CPU at once, and on one CPU a run can+stop halfway while another one runs. Code that looks right for one run+at a time loses updates, mixes up records or decides on data that+changed under it. This page lists the hazards that recur in BPF code,+what to write instead, and the Coccinelle rule in+:src:`testing/coccinelle/` that refuses it in the tree where a rule can.++When a run can stop halfway+---------------------------++A BPF program never moves to another CPU while it runs. Whether another+run can start on its CPU before it ends depends on the program type and+on the kernel's preemption model. On x86-64, arm64 and riscv64 the+kernel preempts tasks in every model it offers: ``PREEMPT``,+``PREEMPT_LAZY``, ``PREEMPT_RT`` and ``PREEMPT_DYNAMIC``, the default+and the one distribution kernels use, which picks ``full`` or ``lazy``+at boot. Kernels before 7.0 also offered ``none`` and ``voluntary``, in+which no task preempts a running program and which most distribution+kernels built with ``PREEMPT_DYNAMIC`` booted in; the kernels shirudo+needs have neither. All but ``PREEMPT_LAZY`` on its own come with+preemptible RCU, ``CONFIG_PREEMPT_RCU``. A kernel with it runs most+programs with only migration disabled, so another task can preempt them.+A kernel without it runs them with preemption disabled, except+``syscall`` programs, which run with only migration disabled on any+kernel. On either kernel an interrupt can run a softirq on top of a run+in a process, and a sleepable program can sleep. The kernel guards some+program types against a second run and not others:++.. list-table::+ :header-rows: 1+ :widths: 34 66++ * - Programs+ - On one CPU+ * - ``kprobe``, ``kretprobe``+ - Run with preemption disabled. The kernel skips a run while+ another ``kprobe`` or ``kretprobe`` program runs on the CPU.+ * - ``fentry``, ``fexit``, ``fmod_ret``, ``tp_btf``+ - Can be preempted with preemptible RCU. The kernel skips a run of a+ program that is already running on the CPU, so a program does not+ nest in itself, but other programs can run in between.+ * - ``lsm``, ``uprobe.multi``+ - Can be preempted with preemptible RCU and are not guarded: a+ second run of the same program can start on the CPU before the+ first one ends, and an ``lsm`` hook a softirq calls can run on top+ of one a process called.+ * - ``syscall``+ - Run with only migration disabled on any kernel and are not+ guarded: another task can preempt a run.+ * - ``lsm.s``, ``fentry.s``, ``fexit.s``, ``fmod_ret.s``+ - Can be preempted and sleep on any kernel. Another run can take the+ CPU at any sleeping call.+ * - ``cgroup_skb``, ``netfilter``+ - Can be preempted with preemptible RCU and are not guarded. An+ egress run from a process can be preempted by another task's+ egress run on the same CPU, and an ingress run in a softirq can+ run on top of it. ``netfilter`` programs run at IPv6+ pre-routing, mostly in a softirq.++The table covers the attach kinds ``shirudo build`` accepts, which+:doc:`/upatches/write/attach-kinds` lists.++The test kernel is built with ``PREEMPT_LAZY`` alone, without+preemptible RCU, so a run in the test VM shows the preemption cases only+for ``syscall`` and sleepable programs. Do not build a program on a+guarantee that only its current attach type gives: an ``fentry`` program+moved to ``lsm`` loses it.++Where each hazard applies+-------------------------++The hazards below are of two kinds. Those of runs that interleave on one+CPU, per-CPU memory used as scratch and a per-CPU counter updated+without an atomic, depend on the preemption model and on the program+types that share the memory, as the table above says. Those of runs on+different CPUs at once depend on neither and apply on every kernel. Fix+a hazard where it applies and not elsewhere: a busy flag or an atomic+that no interleaving needs costs time on every run and hides the+reasoning behind the code that does need one. An upatch whose+correctness depends on the preemption model says in its ``README.md``+which model it is written for.++.. list-table::+ :header-rows: 1+ :widths: 30 70++ * - Hazard+ - Applies+ * - Per-CPU memory used as scratch, a slot picked by CPU number, a+ per-CPU counter updated without an atomic+ - With preemptible RCU, wherever a program type the kernel does not+ guard against the others uses the memory. On every kernel, in+ ``syscall`` and sleepable programs, and where a program that an+ interrupt, a softirq or an NMI runs shares the memory with one+ that a process runs. Not where only ``kprobe`` and ``kretprobe``+ programs use it, nor where one guarded program uses it alone.+ * - Updates of shared values, inserting a missing key,+ compare-and-swap, reading user memory twice+ - On every kernel: other CPUs, or another thread, run at the same+ time.+ * - Publishing a record+ - On every kernel. arm64 and riscv64 reorder the stores, and the+ compiler may on any architecture.+ * - Switching buffers+ - On every kernel. With preemptible RCU a preempted run keeps the+ old buffer for longer.++Per-CPU memory used as scratch+------------------------------++A per-CPU map value is shared by every run on its CPU, not private to+one. A run that stores into it and uses the stored data later can find+it overwritten by a run that came in between. A slot of a plain array+picked with ``bpf_get_smp_processor_id()`` is the same thing built by+hand.++Use memory that belongs to the run instead:++- Task storage, for a program that runs in the context of the task it+ serves. Only that task's runs reach it, and a preempting task has its+ own. A program a softirq runs finds the task it interrupted as the+ current one, so keep such programs off that storage. The seal keeps+ its label buffer there.+- The stack, for what fits in it.+- A busy flag in the per-CPU value, taken with an atomic exchange and+ given back with a release store. A run that finds the flag taken+ skips its work and counts the skip.++Where no second run can come in between, as the table above lists, the+per-CPU value is the run's own and needs none of this. No rule refuses+the pattern: whether it is a hazard depends on the kernel a upatch is+written for and on the programs that share the memory, which a rule+cannot tell, so review decides.++Updates of shared values+------------------------++``count++`` is a load, an add and a store. Two CPUs that run it on the+same value at once lose one of the increments. That holds for the value+of a map that is not per-CPU, and for inode, socket and cgroup storage,+which hooks on different CPUs reach for the same inode, socket or+cgroup. Update such a value with ``__sync_fetch_and_add()``,+``__sync_fetch_and_or()`` and their kin, which do it in one instruction.+``bpf_map_rmw`` refuses the plain forms.++A per-CPU counter needs an atomic only where a run can come in between+on the same CPU: in a program the kernel does not guard, as listed+above, or when several programs update the same map. Task storage needs+none while only its own task's runs write it; a program that writes+another task's storage, a child's in ``task_alloc`` for instance, or+that a softirq runs needs the atomic.++Inserting a missing key+-----------------------++A lookup that finds nothing followed by an update with ``BPF_ANY``+races with another CPU doing the same: both find the key missing, both+insert, and the later insert overwrites what the first one stored, and+any update made to it in between. Insert with ``BPF_NOEXIST``, and when+it returns ``-EEXIST``, look the key up again and use the entry the+other CPU made. ``bpf_check_then_insert`` refuses the ``BPF_ANY`` form.++Compare-and-swap+----------------++A compare-and-swap can fail: another CPU changed the value first. Code+that drops the result goes on as if it had won. Check it, and retry or+give up, as the insert path of :src:`upatches/kernel-obs/obs_table.h`+does after four attempts. A failed compare-and-swap also orders no other+access. ``bpf_cas_unchecked`` refuses a dropped result.++Publishing a record+-------------------++A program that fills a record and then stores a pointer or an index to+it publishes the record. A reader on another CPU that loads the pointer+must see the filled record, but arm64 and riscv64 let it see the+pointer first unless the store orders the filling stores before it.+``WRITE_ONCE()`` does not. Publish with a release store,+``__atomic_store_n(&p, record, __ATOMIC_RELEASE)``, or with an atomic+that returns a value, as a successful compare-and-swap does. The reader+loads the pointer with ``READ_ONCE()`` and reads through it, an address+dependency, or with a load-acquire,+``__atomic_load_n(&p, __ATOMIC_ACQUIRE)``. Use the load-acquire when the+code compares the loaded index with a constant before it uses it: the+compiler can then replace the index with the constant and lose the+dependency.++The arena table template publishes its active buffer with a release+store. ``bpf_publish`` refuses ``WRITE_ONCE()`` of a pointer.++Which accesses order what:++- ``__sync_fetch_and_add()`` and its kin, ``__sync_lock_test_and_set()``,+ ``__atomic_exchange_n()`` and a successful compare-and-swap are full+ barriers. clang emits the value-returning instruction for+ ``__sync_fetch_and_add()`` even when the result is unused.+- ``__atomic_fetch_add(p, v, __ATOMIC_RELAXED)`` with its result unused+ orders nothing, nor does a failed compare-and-swap.+- A release store orders the accesses before it, and a load-acquire the+ accesses after it.++Switching buffers+-----------------++A double buffer that a reader drains while programs fill the other half+has no grace period in BPF: a program that loaded the active pointer+just before the switch still writes into the half being drained. The+reader must expect those late writes. The arena table template counts+the entries it finds in the spare half at the next switch as lost and+clears it, so a late write costs a record, not the table. No rule finds+this; design for it.++Reading user memory twice+-------------------------++User memory can change between two reads of the same address: another+thread of the process writes it meanwhile. A program that checks the+first copy and acts on the second checks different data. Read it once+into memory of the program's own and use that copy, and in an LSM hook,+prefer the kernel's copy in the hook's arguments.+``bpf_user_double_fetch`` refuses two reads of one address.++What the rules cannot see+-------------------------++The ``bpf_`` rules match code within one function, so a hazard spread+over several functions passes them, and they cannot parse a file that+defines its own token-pasting macros, such as+:src:`upatches/kernel-obs/obs_table.h`. Write the ordering such code+relies on as a litmus test and run it, as :doc:`blitmus` shows.++Related+-------++- :doc:`blitmus` to test an ordering on each architecture+- :doc:`/upatches/write/maps-arenas-serializers` for the arena table and+ its serializer+- :doc:`/contribute/code/developer-guide` for the Coccinelle rulesdiff --git a/Documentation/upatches/write/memory-consistency/index.rst b/Documentation/upatches/write/memory-consistency/index.rstindex 7fb0ff69..9c75572a 100644--- a/Documentation/upatches/write/memory-consistency/index.rst+++ b/Documentation/upatches/write/memory-consistency/index.rst@@ -27,7 +27,12 @@ The JIT turns each into the CPU's own instructions. Whether a givenchoice of them is enough for a pattern is the question a litmus testanswers.+:doc:`hazards` lists the patterns that go wrong in BPF code, what to+write instead and the Coccinelle rules that refuse them, and+:doc:`blitmus` tests an ordering on real hardware.+.. toctree:::titlesonly:+ hazardsblitmusdiff --git a/testing/ci-checks/t0006-check-coccinelle.sh b/testing/ci-checks/t0006-check-coccinelle.shindex 8e6a853a..69e2e537 100755--- a/testing/ci-checks/t0006-check-coccinelle.sh+++ b/testing/ci-checks/t0006-check-coccinelle.sh@@ -6,7 +6,8 @@# check with file, line, rule and message, one that does not passes it,# a rule that can rewrite does with -D patch, a rule reads the headers# its #spatch line asks for, on a throwaway repository, each rule taken-# from CERT C reports a sample of what it refuses, and the tree itself.+# from CERT C and each BPF hazard rule reports a sample of what it+# refuses, and the tree itself.cd "$(dirname "$0")/..". ./test-lib.sh@@ -145,6 +146,167 @@ test_expect_success 'each rule taken from CERT C reports its sample' 'grep -q "6 of 6 rules matched" "$W/err"'+# One case of each BPF hazard, and beside it the safe form, which no rule+# reports: the count of reports shows the safe forms stay quiet.+BPF_RULES="bpf_map_rmw bpf_cas_unchecked bpf_check_then_insert \+bpf_publish bpf_user_double_fetch"+write_bpf_samples() {+ cat >"$1" <<'EOF'+struct {+ __uint(type, BPF_MAP_TYPE_ARRAY);+ __uint(max_entries, 1);+ __type(key, __u32);+ __type(value, __u64);+} hits SEC(".maps");++struct {+ __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);+ __uint(max_entries, 1);+ __type(key, __u32);+ __type(value, __u64);+} cpu_hits SEC(".maps");++struct node {+ int filled;+};++static struct node *head;++void count_plain(void)+{+ __u32 zero = 0;+ __u64 *count;++ count = bpf_map_lookup_elem(&hits, &zero);+ if (count)+ (*count)++;+}++void count_percpu(void)+{+ __u32 zero = 0;+ __u64 *count;++ count = bpf_map_lookup_elem(&cpu_hits, &zero);+ if (count)+ (*count)++;+}++void count_atomic(void)+{+ __u32 zero = 0;+ __u64 *count;++ count = bpf_map_lookup_elem(&hits, &zero);+ if (count)+ __sync_fetch_and_add(count, 1);+}++void cas_ignored(__u32 *slot, __u32 old, __u32 new)+{+ __sync_val_compare_and_swap(slot, old, new);+}++int cas_checked(__u32 *slot, __u32 old, __u32 new)+{+ return __sync_val_compare_and_swap(slot, old, new) == old;+}++void insert_racy(__u32 *k, struct val *v)+{+ if (!bpf_map_lookup_elem(&vals, k)) {+ bpf_map_update_elem(&vals, k, v, BPF_ANY);+ }+}++void insert_exclusive(__u32 *k, struct val *v)+{+ if (!bpf_map_lookup_elem(&vals, k)) {+ bpf_map_update_elem(&vals, k, v, BPF_NOEXIST);+ }+}++void publish_once(struct node *n)+{+ n->filled = 1;+ WRITE_ONCE(head, n);+}++void publish_release(struct node *n)+{+ n->filled = 1;+ __atomic_store_n(&head, n, __ATOMIC_RELEASE);+ WRITE_ONCE(head, NULL);+}++int fetch_twice(const char *uptr)+{+ char a[16], b[16];++ bpf_copy_from_user_str(a, sizeof(a), uptr, 0);+ if (a[0] != 'x')+ return 0;+ bpf_probe_read_user(b, sizeof(b), uptr);+ return b[1];+}++int fetch_once(const char *uptr)+{+ char a[16];++ bpf_probe_read_user(a, sizeof(a), uptr);+ return a[0];+}++void count_decl(void)+{+ __u32 zero = 0;+ __u64 *count = bpf_map_lookup_elem(&hits, &zero);++ if (count)+ (*count)++;+}++void flags_task(struct task_struct *task)+{+ struct meta *m = bpf_task_storage_get(&tasks, task, 0, 0);++ if (m)+ m->flags |= 1;+}++struct meta *flags_reassigned(struct sock *sk)+{+ struct meta *m = bpf_sk_storage_get(&socks, sk, 0, 0);++ if (m)+ return m;+ m = meta_create(sk);+ if (m)+ m->flags |= 1;+ return m;+}+EOF+}++test_expect_success 'each BPF rule reports its sample and spares the safe form' '+ R3=$W/bpf &&+ mkdir -p "$R3/testing/coccinelle" &&+ git init -q "$R3" &&+ cp "$ROOT/testing/coccinelle/bpf.macros" "$R3/testing/coccinelle/" &&+ for r in $BPF_RULES; do+ cp "$ROOT/testing/coccinelle/$r.cocci" "$R3/testing/coccinelle/" ||+ exit 1+ done &&+ write_bpf_samples "$R3/samples.bpf.c" &&+ ! (cd "$R3" && git add -A && sh "$S") >"$W/out" 2>"$W/err" &&+ for r in $BPF_RULES; do+ grep -q "^$r: samples.bpf.c:" "$W/err" || exit 1+ done &&+ grep -q "5 of 5 rules matched" "$W/err" &&+ [ "$(grep -c "^bpf_[a-z_]*: samples.bpf.c:" "$W/err")" = 6 ]+'+test_expect_success 'the tree passes' '(cd "$ROOT" && sh "$S") >"$W/out" 2>"$W/err" &&grep -q "rules, no match" "$W/out"diff --git a/testing/coccinelle/bpf.macros b/testing/coccinelle/bpf.macrosnew file mode 100644index 00000000..09b8e7bb--- /dev/null+++ b/testing/coccinelle/bpf.macros@@ -0,0 +1,23 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// What the BPF sources' macros mean, for Coccinelle to parse them.++#define SEC(name)+#define __ksym+#define __kptr+#define __arena+#define __always_inline+#define __noinline+#define __weak+#define __hidden+#define __uint(name, val) int name+#define __type(name, val) val *name+#define __array(name, val) val *name+#define BPF_PROG(name, args...) name(args)+#define BPF_KPROBE(name, args...) name(args)+#define BPF_KRETPROBE(name, args...) name(args)+#define OBS_FN(name) name+#define OBS_CAT(a, b) a##b+#define BUILD_BUG_ON(cond) extern int build_bug_on+#define BUILD_BUG_ON_MSG(cond, msg) extern int build_bug_ondiff --git a/testing/coccinelle/bpf_cas_unchecked.cocci b/testing/coccinelle/bpf_cas_unchecked.coccinew file mode 100644index 00000000..d75871ec--- /dev/null+++ b/testing/coccinelle/bpf_cas_unchecked.cocci@@ -0,0 +1,24 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A compare-and-swap whose result nobody reads may have failed, on every+// kernel: another CPU changed the value first, and the code goes on as if+// it had won. A failed one also orders nothing.+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros++virtual report++@r depends on report@+attribute name SEC;+identifier cas = {__sync_val_compare_and_swap,+ __sync_bool_compare_and_swap,+ __atomic_compare_exchange_n, __atomic_compare_exchange};+position pos;+@@+cas@pos(...);++@script:python depends on report@+pos << r.pos;+@@+coccilib.report.print_report(pos[0],+ "compare-and-swap result ignored: check whether it won")diff --git a/testing/coccinelle/bpf_check_then_insert.cocci b/testing/coccinelle/bpf_check_then_insert.coccinew file mode 100644index 00000000..8bdd1419--- /dev/null+++ b/testing/coccinelle/bpf_check_then_insert.cocci@@ -0,0 +1,47 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Looking a key up and inserting it when it is missing races with another+// CPU doing the same, on every kernel: both find nothing, and the later+// BPF_ANY update overwrites what the first stored. BPF_NOEXIST inserts only+// when the key is still missing and returns -EEXIST otherwise.+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros++virtual report++@r depends on report@+attribute name SEC;+identifier m, p;+expression k, v, e2;+type T;+position pos;+@@+(+if (!bpf_map_lookup_elem(&m, k)) {+ ...+ bpf_map_update_elem@pos(&m, k, v, \(BPF_ANY\|0\));+ ...+}+|+p = bpf_map_lookup_elem(&m, k);+... when != p = e2+if (!p) {+ ...+ bpf_map_update_elem@pos(&m, k, v, \(BPF_ANY\|0\));+ ...+}+|+T *p = bpf_map_lookup_elem(&m, k);+... when != p = e2+if (!p) {+ ...+ bpf_map_update_elem@pos(&m, k, v, \(BPF_ANY\|0\));+ ...+}+)++@script:python depends on report@+pos << r.pos;+@@+coccilib.report.print_report(pos[0],+ "insert after a failed lookup races with other CPUs: update with BPF_NOEXIST")diff --git a/testing/coccinelle/bpf_map_rmw.cocci b/testing/coccinelle/bpf_map_rmw.coccinew file mode 100644index 00000000..d462aa1a--- /dev/null+++ b/testing/coccinelle/bpf_map_rmw.cocci@@ -0,0 +1,118 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A load, an add and a store through a value that other CPUs share lose+// updates on every kernel: the value of a map that is not per-CPU, and+// inode, socket and cgroup storage. __sync_fetch_and_add() and its kin+// update it in one instruction. A per-CPU value is left out: it needs the+// atomic only where a second run can start on its CPU before the first one+// ends, which depends on the preemption model and the programs that update+// it, and a counter that one kprobe or tracing program alone updates needs+// none on any kernel. Task storage is left out too, as only its task+// writes it, unless a program writes another task's or runs in a softirq.+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros++virtual report++@initialize:python@+@@+import re++shared = {}+map_def = re.compile(r'struct\s*\{([^}]*)\}\s*(\w+)\s+SEC\(\s*"\.maps"\s*\)')+++def shared_maps(path):+ if path not in shared:+ names = set()+ try:+ with open(path) as f:+ for body, name in map_def.findall(f.read()):+ if 'PERCPU' not in body:+ names.add(name)+ except OSError:+ pass+ shared[path] = names+ return shared[path]++@r depends on report@+attribute name SEC;+identifier m, p, f;+expression k, e, e2;+type T;+position pos;+@@+(+p = bpf_map_lookup_elem(&m, k);+|+T *p = bpf_map_lookup_elem(&m, k);+)+... when != p = e2+(+p->f@pos+++|+p->f@pos--+|+p->f@pos += e+|+p->f@pos -= e+|+p->f@pos |= e+|+p->f@pos &= e+|+ (*p@pos)+++|+ (*p@pos)--+|+*p@pos += e+|+*p@pos -= e+|+*p@pos |= e+)++@s depends on report@+identifier get = {bpf_inode_storage_get, bpf_sk_storage_get,+ bpf_cgrp_storage_get};+expression list args;+identifier p, f;+expression e, e2;+type T;+position pos;+@@+(+p = get(args);+|+T *p = get(args);+)+... when != p = e2+(+p->f@pos+++|+p->f@pos--+|+p->f@pos += e+|+p->f@pos -= e+|+p->f@pos |= e+|+p->f@pos &= e+)++@script:python depends on report@+m << r.m;+pos << r.pos;+@@+if m not in shared_maps(pos[0].file):+ cocci.include_match(False)+else:+ coccilib.report.print_report(pos[0],+ "read-modify-write of a shared map value is not atomic: use __sync_fetch_and_add() or its kin")++@script:python depends on report@+pos << s.pos;+@@+coccilib.report.print_report(pos[0],+ "read-modify-write of storage other CPUs share is not atomic: use __sync_fetch_and_add() or its kin")diff --git a/testing/coccinelle/bpf_publish.cocci b/testing/coccinelle/bpf_publish.coccinew file mode 100644index 00000000..bd4ffefd--- /dev/null+++ b/testing/coccinelle/bpf_publish.cocci@@ -0,0 +1,30 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// WRITE_ONCE() of a pointer publishes what it points to without ordering+// the stores that filled it, on every kernel: arm64 and riscv64 let a+// reader that follows the pointer see the old contents, and the compiler+// may move the stores after it on any architecture. A release store orders+// them.+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros++virtual report++@r depends on report@+attribute name SEC;+type T;+T *e;+expression x;+position pos;+@@+WRITE_ONCE@pos(x, e)++@script:python depends on report@+e << r.e;+pos << r.pos;+@@+if e.strip() in ("NULL", "0", "(void *)0"):+ cocci.include_match(False)+else:+ coccilib.report.print_report(pos[0],+ "WRITE_ONCE() publishes a pointer unordered: use __atomic_store_n(&x, p, __ATOMIC_RELEASE)")diff --git a/testing/coccinelle/bpf_user_double_fetch.cocci b/testing/coccinelle/bpf_user_double_fetch.coccinew file mode 100644index 00000000..8cb60980--- /dev/null+++ b/testing/coccinelle/bpf_user_double_fetch.cocci@@ -0,0 +1,31 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// User memory can change between two reads of the same address, on every+// kernel, as another thread writes it meanwhile: a decision taken on the+// first copy and an action on the second check different data. Read it+// once, into memory of the program's own.+#spatch --no-includes --macro-file testing/coccinelle/bpf.macros++virtual report++@r depends on report@+attribute name SEC;+identifier rd1 = {bpf_probe_read_user, bpf_probe_read_user_str,+ bpf_copy_from_user, bpf_copy_from_user_str,+ bpf_copy_from_user_task, bpf_copy_from_user_task_str};+identifier rd2 = {bpf_probe_read_user, bpf_probe_read_user_str,+ bpf_copy_from_user, bpf_copy_from_user_str,+ bpf_copy_from_user_task, bpf_copy_from_user_task_str};+expression d1, d2, n1, n2, src, e;+position pos;+@@+rd1(d1, n1, src, ...)+... when != src = e+rd2@pos(d2, n2, src, ...)++@script:python depends on report@+pos << r.pos;+@@+coccilib.report.print_report(pos[0],+ "user memory read twice: it can change in between; read it once")