Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

selftests/bpf: Make bpf get_preempt_count() work for v6.14+ kernels

Recent x86 kernels export __preempt_count as a ksym, while some old kernels
between v6.1 and v6.14 expose the preemption counter via
pcpu_hot.preempt_count. The existing selftest helper unconditionally
dereferenced __preempt_count, which breaks BPF program loading on such old
kernels.

Make the x86 preemption count lookup version-agnostic by:
- Marking __preempt_count and pcpu_hot as weak ksyms.
- Introducing a BTF-described pcpu_hot___local layout with
preserve_access_index.
- Selecting the appropriate access path at runtime using ksym availability
and bpf_ksym_exists() and bpf_core_field_exists().

This allows a single BPF binary to run correctly across kernel versions
(e.g., v6.18 vs. v6.13) without relying on compile-time version checks.

Signed-off-by: Changwoo Min <changwoo@igalia.com>
Link: https://lore.kernel.org/r/20260130021843.154885-1-changwoo@igalia.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Changwoo Min and committed by
Alexei Starovoitov
cd77618c b18a761c

+20 -2
+20 -2
tools/testing/selftests/bpf/bpf_experimental.h
··· 614 614 615 615 extern bool CONFIG_PREEMPT_RT __kconfig __weak; 616 616 #ifdef bpf_target_x86 617 - extern const int __preempt_count __ksym; 617 + extern const int __preempt_count __ksym __weak; 618 + 619 + struct pcpu_hot___local { 620 + int preempt_count; 621 + } __attribute__((preserve_access_index)); 622 + 623 + extern struct pcpu_hot___local pcpu_hot __ksym __weak; 618 624 #endif 619 625 620 626 struct task_struct___preempt_rt { ··· 630 624 static inline int get_preempt_count(void) 631 625 { 632 626 #if defined(bpf_target_x86) 633 - return *(int *) bpf_this_cpu_ptr(&__preempt_count); 627 + /* By default, read the per-CPU __preempt_count. */ 628 + if (bpf_ksym_exists(&__preempt_count)) 629 + return *(int *) bpf_this_cpu_ptr(&__preempt_count); 630 + 631 + /* 632 + * If __preempt_count does not exist, try to read preempt_count under 633 + * struct pcpu_hot. Between v6.1 and v6.14 -- more specifically, 634 + * [64701838bf057, 46e8fff6d45fe), preempt_count had been managed 635 + * under struct pcpu_hot. 636 + */ 637 + if (bpf_core_field_exists(pcpu_hot.preempt_count)) 638 + return ((struct pcpu_hot___local *) 639 + bpf_this_cpu_ptr(&pcpu_hot))->preempt_count; 634 640 #elif defined(bpf_target_arm64) 635 641 return bpf_get_current_task_btf()->thread_info.preempt.count; 636 642 #endif