bpf, x86: Restrict BPF JIT IBPB flush to CPUs that ran BPF
Subsystems (5)
cover bpf, x86: Restrict BPF JIT IBPB flush to CPUs that ran BPF
Hi,
we have recently started observing latency spikes on systems with isolated CPUs when classic BPF programs were running in the background (e.g. executed by NetworkManager or seccomp). The latencies are caused by the BPF JIT-spraying mitigation introduced by commit 96cce16e26dd ("bpf: Support for hardening against JIT spraying") and its follow-ups. The reason is that the IBPB flush is currently broadcast to every online CPU, including the isolated ones that never run BPF programs.
While recent changes [1] have significantly decreased the frequency of the IBPB flushes, they haven't eliminated them completely, which still poses a serious problem for latency-sensitive workloads.
This patch series implement one of the ideas from a9b1f19a6a67 ("bpf:
Prefer packs that won't trigger an IBPB flush on allocation") and introduce a mechanism to completely avoid the IBPB flushes on CPUs that have not run any BPF program since the last flush. This is sound because the original Spectre-v2 vulnerability is only exploitable if a cBPF program runs on a CPU that previously ran any BPF program (and therefore can reuse the branch predictors trained on the previous program).
Patch #1 introduces a new per-cpu flag bpf_prog_ran, which records that a CPU executed any BPF program, and patch #2 restricts the IBPB flushes on x86 to CPUs that have the flag set. This way, the isolated CPUs that never run any BPF programs do not receive the unnecessary flushes.
[1] https://lore.kernel.org/bpf/[email protected]/
Viktor Malik (2):
bpf: Track CPUs that have executed a BPF program x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
arch/x86/kernel/cpu/bugs.c | 8 +++++++- include/linux/filter.h | 27 ++++++++++++++++++++++++++- kernel/bpf/core.c | 8 ++++++++ kernel/bpf/trampoline.c | 5 +++++ 4 files changed, 46 insertions(+), 2 deletions(-)
Signature · 1 line
2.56.1
PATCH 1/2 bpf: Track CPUs that have executed a BPF program
The BPF JIT-spraying mitigation introduced by commit 96cce16e26dd ("bpf:
Support for hardening against JIT spraying") and follow-ups flushes the indirect branch predictors (IBPB on x86, via bpf_arch_pred_flush()) when cBPF JIT memory is reused, to drop stale predictions trained by code that previously occupied that memory. The flush is currently broadcast to every online CPU with on_each_cpu(). On systems with isolated CPUs running latency-sensitive workloads this is a serious regression: an unprivileged cBPF load/free forces an IPI and an IBPB onto CPUs that never run BPF, stealing time and wiping their branch predictors.
A flush is only ever needed on a CPU that has actually executed JITed BPF code since the last flush - that is the only way a stale prediction for a reused JIT chunk can exist there. Introduce a per-CPU flag, bpf_prog_ran, recording that the CPU has executed a BPF program, so that arch code can later target the flush at exactly those CPUs instead of all of them.
The flag is set for any BPF program, not just cBPF: the flush is triggered by a cBPF allocation, but the stale prediction being dropped may have been trained by whatever previously occupied the reused chunk, including an eBPF program.
The flag is set after the program executes (in __bpf_prog_run() and in the trampoline exit helpers), so that a flush racing with the program cannot clear the flag while predictions trained by that program are still live. The mechanism is gated behind the bpf_pred_flush_enabled static key, so there is no cost unless the mitigation is active.
This commit only introduces the flag; the x86 flush starts consuming it in a follow-up change.
--- include/linux/filter.h | 27 ++++++++++++++++++++++++++- kernel/bpf/core.c | 8 ++++++++ kernel/bpf/trampoline.c | 5 +++++ 3 files changed, 39 insertions(+), 1 deletion(-)
include/linux/filter.h +26 -1
@@ -873,6 +873,31 @@ typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx,unsigned int (*bpf_func)(const void *, const struct bpf_insn *)); +DECLARE_STATIC_KEY_FALSE (bpf_pred_flush_enabled); +DECLARE_PER_CPU (bool, bpf_prog_ran); + +/* +* When BPF JIT-spraying mitigation is in place, record, on the current CPU, +* that a JITed BPF program has just executed. +* +* The mitigation flushes the indirect branch predictors (IBPB on x86) when cBPF +* JIT memory is reused, to drop stale predictions from the code that previously +* occupied that memory. That flush is only ever needed on CPUs that have +* actually executed BPF since the last flush, so arch code consults this flag +* to target those CPUs. +*/ +static __always_inline void bpf_prog_mark_ran(void) +{ +bool *ran; + +if (!static_branch_unlikely (&bpf_pred_flush_enabled)) +return ; + + ran =raw_cpu_ptr (&bpf_prog_ran); +if (!READ_ONCE (*ran)) +WRITE_ONCE (*ran, true); +} + static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog,const void *ctx,bpf_dispatcher_fn dfunc)
@@ -898,6 +923,7 @@ static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, }else { ret =dfunc (ctx, prog->insnsi, prog->bpf_func); } +bpf_prog_mark_ran ();return ret; }
@@ -1598,7 +1624,6 @@ typedef void (*bpf_jit_fill_hole_t)(void *area, unsigned int size);*/ void bpf_arch_pred_flush (void );DECLARE_STATIC_CALL (bpf_arch_pred_flush, bpf_arch_pred_flush); -DECLARE_STATIC_KEY_FALSE (bpf_pred_flush_enabled);void bpf_jit_fill_hole_with_zero (void *area,unsigned int size);
kernel/bpf/core.c +8 -0
@@ -1204,6 +1204,14 @@ DEFINE_STATIC_CALL_NULL(bpf_arch_pred_flush, bpf_arch_pred_flush);* static branch instead of repeatedly querying the static call target. */ DEFINE_STATIC_KEY_FALSE (bpf_pred_flush_enabled); +EXPORT_SYMBOL (bpf_pred_flush_enabled); + +/* +* Set on a CPU once it has executed a JITed BPF program since the last +* predictor flush; see bpf_prog_mark_ran() and bpf_arch_pred_flush(). +*/ +DEFINE_PER_CPU (bool, bpf_prog_ran); +EXPORT_PER_CPU_SYMBOL (bpf_prog_ran);#define BPF_PROG_SIZE_TO_NBITS (size) (round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE)
kernel/bpf/trampoline.c +5 -0
@@ -1382,6 +1382,7 @@ static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)__releases (RCU ) { +bpf_prog_mark_ran ();/* Before the exit, which can enable preemption: time off the CPU is not run time */ update_prog_stats (prog, start);bpf_prog_exit_run_ctx (prog, &run_ctx->run_ctx);
@@ -1406,6 +1407,7 @@ static void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)__releases (RCU ) { +bpf_prog_mark_ran ();bpf_reset_run_ctx (run_ctx->run_ctx.saved_run_ctx);rcu_read_unlock_migrate ();
@@ -1430,6 +1432,7 @@ u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog, void notrace __bpf_prog_exit_sleepable_recur(struct bpf_prog *prog, u64 start,struct bpf_tramp_run_ctx *run_ctx) { +bpf_prog_mark_ran ();update_prog_stats (prog, start);bpf_prog_exit_run_ctx (prog, &run_ctx->run_ctx);migrate_enable ();
@@ -1451,6 +1454,7 @@ static u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog, static void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,struct bpf_tramp_run_ctx *run_ctx) { +bpf_prog_mark_ran ();bpf_reset_run_ctx (run_ctx->run_ctx.saved_run_ctx);update_prog_stats (prog, start);
@@ -1473,6 +1477,7 @@ static void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)__releases (RCU ) { +bpf_prog_mark_ran ();bpf_reset_run_ctx (run_ctx->run_ctx.saved_run_ctx);update_prog_stats (prog, start);
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH bpf-next 1/2] bpf: Track CPUs that have executed a BPF program
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] bpf: link failure under CONFIG_BPF_JIT=n in bpf_prog_mark_ran() - [Medium] bpf: missing…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] bpf: link failure under CONFIG_BPF_JIT=n in bpf_prog_mark_ran()
- [Medium] bpf: missing bpf_prog_mark_ran() in bpf_run_async_cb()
- [Low] bpf: untracked bpf_prog_pack trampoline execution bypassing __bpf_prog_exit*()
--
commit a794f32a47f5dda2a5c528bf869f1bd4c8182a6e
Author: Viktor Malik <[email protected]>
bpf: Track CPUs that have executed a BPF program
This commit introduces a per-CPU bpf_prog_ran flag, gated behind the bpf_pred_flush_enabled static key, and sets it in __bpf_prog_run() and the trampoline exit helpers so arch code can restrict indirect branch predictor flushes to CPUs that have executed BPF code.
Quoted 22 lines
include/linux/filter.h +14
-0@@ -873,6 +873,31 @@ typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx,unsigned int (*bpf_func)(const void *, const struct bpf_insn *)); +DECLARE_STATIC_KEY_FALSE (bpf_pred_flush_enabled); +DECLARE_PER_CPU (bool, bpf_prog_ran); + +/* +* When BPF JIT-spraying mitigation is in place, record, on the current CPU, +* that a JITed BPF program has just executed. +* +* The mitigation flushes the indirect branch predictors (IBPB on x86) when cBPF +* JIT memory is reused, to drop stale predictions from the code that previously +* occupied that memory. That flush is only ever needed on CPUs that have +* actually executed BPF since the last flush, so arch code consults this flag +* to target those CPUs. +*/ +static __always_inline void bpf_prog_mark_ran(void)
include/linux/filter.h typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx, · line 899
Quoted 10 lines
include/linux/filter.h +10
-0+{ +bool *ran; + +if (!static_branch_unlikely (&bpf_pred_flush_enabled)) +return ; + + ran =raw_cpu_ptr (&bpf_prog_ran); +if (!READ_ONCE (*ran)) +WRITE_ONCE (*ran, true); +}
[Severity: High]
Does this break linking when CONFIG_BPF=y and CONFIG_BPF_JIT=n?
bpf_pred_flush_enabled and bpf_prog_ran are declared and referenced unconditionally here, but both definitions and exports in kernel/bpf/core.c sit inside #ifdef CONFIG_BPF_JIT. Any interpreter-only build with callers of __bpf_prog_run(), such as seccomp_run_filters(), will fail vmlinux link and module modpost with undefined references to both symbols.
Guarding the declarations and bpf_prog_mark_ran() with #ifdef CONFIG_BPF_JIT and providing an empty stub otherwise fixes the build and avoids emitting a dead static branch when JIT is disabled.
[ ... ]
include/linux/filter.h static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, · line 928
Quoted 7 lines
include/linux/filter.h +1
-0@@ -898,6 +923,7 @@ static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, }else { ret =dfunc (ctx, prog->insnsi, prog->bpf_func); } +bpf_prog_mark_ran ();return ret; }
[Severity: Medium]
Should bpf_run_async_cb() in kernel/bpf/helpers.c also call bpf_prog_mark_ran()?
Async BPF callbacks (such as bpf_timer_cb() and bpf_wq_work()) invoke JITed subprograms allocated from bpf_prog_pack directly via callback_fn(), bypassing __bpf_prog_run() and the trampoline exit helpers.
A CPU that runs one while bpf_prog_ran is false is skipped by a later targeted flush when those bpf_prog_pack chunks are reused by cBPF, leaving stale indirect branch predictions live.
All callers of bpf_run_async_cb() already run with migration disabled, so calling bpf_prog_mark_ran() after callback_fn() there closes this gap.
[ ... ]
kernel/bpf/trampoline.c static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start, · line 1388
Quoted 12 lines
kernel/bpf/trampoline.c +1
-0@@ -1382,6 +1382,7 @@ static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)__releases (RCU ) { +bpf_prog_mark_ran ();/* Before the exit, which can enable preemption: time off the CPU is not run time */ update_prog_stats (prog, start);bpf_prog_exit_run_ctx (prog, &run_ctx->run_ctx);
[Severity: Low]
Can a CPU execute JITed trampoline code from bpf_prog_pack without setting bpf_prog_ran?
On x86-64, arch_alloc_bpf_trampoline() allocates trampolines from bpf_prog_pack, and under BPF_TRAMP_F_ORIG_STACK the trampoline runs an indirect call *rbx there with migration enabled.
In an fexit-only trampoline, a task can run call *rbx on CPU0, sleep in the original function, and migrate to CPU1 where __bpf_prog_exit*() runs, leaving bpf_prog_ran false on CPU0. The same happens through __bpf_tramp_exit() or during skip patching in __bpf_trampoline_unlink_prog().
If the trampoline image is later freed and reused by a cBPF allocation, a targeted predictor flush would skip that CPU.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Re: [PATCH bpf-next 1/2] bpf: Track CPUs that have executed a BPF program
Quoted 60 lines · On 12/4/26 15:03, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] bpf: link failure underCONFIG_BPF_JIT=ninbpf_prog_mark_ran()
- [Medium] bpf: missingbpf_prog_mark_ran()inbpf_run_async_cb()
- [Low] bpf: untrackedbpf_prog_packtrampoline execution bypassing __bpf_prog_exit*()
--commit
a794f32a47f5dda2a5c528bf869f1bd4c8182a6e
Author: Viktor Malik <[email protected]>bpf: Track CPUs that have executed a BPF program
This commit introduces a per-CPU
bpf_prog_ranflag, gated behind thebpf_pred_flush_enabledstatic key, and sets it in__bpf_prog_run()and the trampoline exit helpers so arch code can restrict indirect branch predictor flushes to CPUs that have executed BPF code.Quoted 22 lines
include/linux/filter.h +14
-0@@ -873,6 +873,31 @@ typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx,unsigned int (*bpf_func)(const void *, const struct bpf_insn *)); +DECLARE_STATIC_KEY_FALSE (bpf_pred_flush_enabled); +DECLARE_PER_CPU (bool, bpf_prog_ran); + +/* +* When BPF JIT-spraying mitigation is in place, record, on the current CPU, +* that a JITed BPF program has just executed. +* +* The mitigation flushes the indirect branch predictors (IBPB on x86) when cBPF +* JIT memory is reused, to drop stale predictions from the code that previously +* occupied that memory. That flush is only ever needed on CPUs that have +* actually executed BPF since the last flush, so arch code consults this flag +* to target those CPUs. +*/ +static __always_inline void bpf_prog_mark_ran(void)include/linux/filter.h typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx, · line 899
Quoted 10 lines
include/linux/filter.h +10
-0+{ +bool *ran; + +if (!static_branch_unlikely (&bpf_pred_flush_enabled)) +return ; + + ran =raw_cpu_ptr (&bpf_prog_ran); +if (!READ_ONCE (*ran)) +WRITE_ONCE (*ran, true); +}[Severity: High]
Does this break linking whenCONFIG_BPF=yandCONFIG_BPF_JIT=n?
bpf_pred_flush_enabledandbpf_prog_ranare declared and referenced unconditionally here, but both definitions and exports inkernel/bpf/core.csit inside #ifdefCONFIG_BPF_JIT. Any interpreter-only build with callers of__bpf_prog_run(), such asseccomp_run_filters(), will fail vmlinux link and module modpost with undefined references to both symbols.
Quoted 3 lines
Guarding the declarations and
bpf_prog_mark_ran()with #ifdefCONFIG_BPF_JITand providing an empty stub otherwise fixes the build and avoids emitting a dead static branch when JIT is disabled.
Good catch, will add guards and an empty stub for the !CONFIG_BPF_JIT case.
Quoted 19 lines
[ ... ]
include/linux/filter.h static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, · line 928
Quoted 7 lines
include/linux/filter.h +1
-0@@ -898,6 +923,7 @@ static __always_inline u32 __bpf_prog_run(const struct bpf_prog *prog, }else { ret =dfunc (ctx, prog->insnsi, prog->bpf_func); } +bpf_prog_mark_ran ();return ret; }[Severity: Medium]
Shouldbpf_run_async_cb()inkernel/bpf/helpers.calso callbpf_prog_mark_ran()?Async BPF callbacks (such as
bpf_timer_cb()andbpf_wq_work()) invoke JITed subprograms allocated frombpf_prog_packdirectly viacallback_fn(), bypassing__bpf_prog_run()and the trampoline exit helpers.
Quoted 6 lines
A CPU that runs one while
bpf_prog_ranis false is skipped by a later targeted flush when thosebpf_prog_packchunks are reused by cBPF, leaving stale indirect branch predictions live.All callers of
bpf_run_async_cb()already run with migration disabled, so callingbpf_prog_mark_ran()aftercallback_fn()there closes this gap.
Good suggestion, will apply.
Quoted 24 lines
[ ... ]
kernel/bpf/trampoline.c static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start, · line 1388
Quoted 12 lines
kernel/bpf/trampoline.c +1
-0@@ -1382,6 +1382,7 @@ static void notrace __bpf_prog_exit_recur(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)__releases (RCU ) { +bpf_prog_mark_ran ();/* Before the exit, which can enable preemption: time off the CPU is not run time */ update_prog_stats (prog, start);bpf_prog_exit_run_ctx (prog, &run_ctx->run_ctx);[Severity: Low]
Can a CPU execute JITed trampoline code frombpf_prog_packwithout settingbpf_prog_ran?On x86-64,
arch_alloc_bpf_trampoline()allocates trampolines frombpf_prog_pack, and underBPF_TRAMP_F_ORIG_STACKthe trampoline runs an indirect call *rbx there with migration enabled.
Quoted 7 lines
In an fexit-only trampoline, a task can run call *rbx on CPU0, sleep in the original function, and migrate to CPU1 where __bpf_prog_exit*() runs, leaving
bpf_prog_ranfalse on CPU0. The same happens through__bpf_tramp_exit()or during skip patching in__bpf_trampoline_unlink_prog().If the trampoline image is later freed and reused by a cBPF allocation, a targeted predictor flush would skip that CPU.
IIUC, this should be resolvable by adding bpf_prog_mark_ran() to both __bpf_tramp_enter() (to cover CPU0) and __bpf_tramp_exit() (to cover CPU1).
Re: [PATCH bpf-next 1/2] bpf: Track CPUs that have executed a BPF program
In reply to Viktor MalikQuoted 28 lines · Viktor Malik
The BPF JIT-spraying mitigation introduced by commit
96cce16e26dd("bpf:
Support for hardening against JIT spraying") and follow-ups flushes the indirect branch predictors (IBPB on x86, viabpf_arch_pred_flush()) when cBPF JIT memory is reused, to drop stale predictions trained by code that previously occupied that memory. The flush is currently broadcast to every online CPU withon_each_cpu(). On systems with isolated CPUs running latency-sensitive workloads this is a serious regression: an unprivileged cBPF load/free forces an IPI and an IBPB onto CPUs that never run BPF, stealing time and wiping their branch predictors.A flush is only ever needed on a CPU that has actually executed JITed BPF code since the last flush - that is the only way a stale prediction for a reused JIT chunk can exist there. Introduce a per-CPU flag,
bpf_prog_ran, recording that the CPU has executed a BPF program, so that arch code can later target the flush at exactly those CPUs instead of all of them.The flag is set for any BPF program, not just cBPF: the flush is triggered by a cBPF allocation, but the stale prediction being dropped may have been trained by whatever previously occupied the reused chunk, including an eBPF program.
The flag is set after the program executes (in
__bpf_prog_run()and in the trampoline exit helpers), so that a flush racing with the program cannot clear the flag while predictions trained by that program are still live. The mechanism is gated behind thebpf_pred_flush_enabledstatic key, so there is no cost unless the mitigation is active.
Quoted 4 lines
This commit only introduces the flag; the x86 flush starts consuming it in a follow-up change.
Signed-off-by Viktor Malik <[email protected]>
Re: [PATCH bpf-next 1/2] bpf: Track CPUs that have executed a BPF program
In reply to Viktor Malikinclude/linux/filter.h typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx, · line 899
Quoted 11 lines · Viktor Malik
include/linux/filter.h +11
-0+static __always_inline void bpf_prog_mark_ran(void) +{ +bool *ran; + +if (!static_branch_unlikely (&bpf_pred_flush_enabled)) +return ; + + ran =raw_cpu_ptr (&bpf_prog_ran); +if (!READ_ONCE (*ran)) +WRITE_ONCE (*ran, true); +}
This is bizarrely complex.
I obviously know why code might want to avoid dirtying a cacheline, especially when it might be shared. But this is per-cpu data. It's fundamentally not in other CPU caches.
What's wrong with?
if (static_branch_unlikely(&bpf_pred_flush_enabled)) this_cpu_write(bpf_prog_ran, true);
kernel/bpf/core.c DEFINE_STATIC_CALL_NULL(bpf_arch_pred_flush, bpf_arch_pred_flush); · line 1214
Quoted 9 lines
DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled);kernel/bpf/core.c +8
-0+EXPORT_SYMBOL (bpf_pred_flush_enabled); + +/* +* Set on a CPU once it has executed a JITed BPF program since the last +* predictor flush; see bpf_prog_mark_ran() and bpf_arch_pred_flush(). +*/ +DEFINE_PER_CPU (bool, bpf_prog_ran); +EXPORT_PER_CPU_SYMBOL (bpf_prog_ran);
What are the exports for? Any reason they're generic exports and not GPL-only?
Re: [PATCH bpf-next 1/2] bpf: Track CPUs that have executed a BPF program
Quoted 19 lines · Dave Hansen
include/linux/filter.h typedef unsigned int (*bpf_dispatcher_fn)(const void *ctx, · line 899
Quoted 11 lines · Viktor Malik
include/linux/filter.h +11
-0+static __always_inline void bpf_prog_mark_ran(void) +{ +bool *ran; + +if (!static_branch_unlikely (&bpf_pred_flush_enabled)) +return ; + + ran =raw_cpu_ptr (&bpf_prog_ran); +if (!READ_ONCE (*ran)) +WRITE_ONCE (*ran, true); +}This is bizarrely complex.
I obviously know why code might want to avoid dirtying a cacheline, especially when it might be shared. But this is per-cpu data. It's fundamentally not in other CPU caches.
Quoted 5 lines
What's wrong with?
if (static_branch_unlikely(&bpf_pred_flush_enabled)) this_cpu_write(bpf_prog_ran, true);
This CPU's bpf_prog_ran is read from another CPU in bpf_ibpb_needed() so I was probably overcautiously protecting the cacheline here. But that's likely not worth the complexity so I'll update to your suggestion.
Quoted 4 lines
Quoted 4 lines
DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled);kernel/bpf/core.c +3
-0+EXPORT_SYMBOL (bpf_pred_flush_enabled); + +/*
Quoted 8 lines
kernel/bpf/core.c DEFINE_STATIC_CALL_NULL(bpf_arch_pred_flush, bpf_arch_pred_flush); · line 1214
Quoted 5 lines
+ * Set on a CPU once it has executed a JITed BPF program since the last
+ * predictor flush; seebpf_prog_mark_ran()andbpf_arch_pred_flush().
+ */kernel/bpf/core.c +2
-0+DEFINE_PER_CPU (bool, bpf_prog_ran); +EXPORT_PER_CPU_SYMBOL (bpf_prog_ran);What are the exports for? Any reason they're generic exports and not GPL-only?
The exports are needed for builds when __bpf_prog_run() gets inlined into modules (XDP drivers, test_bpf.ko), otherwise the build failed on modpost errors.
No reason not to make them GPL-only, I'll change that in v2.
Thanks for the review!
Viktor
PATCH 2/2 x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
In reply to Viktor Malikbpf_arch_ibpb() issues the BPF JIT-spraying predictor flush on every online CPU via on_each_cpu(). On systems with isolated/nohz_full CPUs, an (unprivileged) cBPF load/free therefore delivers IPIs and IBPBs to CPUs that never run BPF, causing latency spikes on cores dedicated to latency-sensitive workloads (the IPI steal plus a branch-predictor wipe that slows the victim afterwards).
Use the per-CPU bpf_prog_ran flag introduced in the previous patch to flush only the CPUs that have executed a BPF program since the last flush. This is sound since a stale prediction for a reused JIT chunk can only exist on a CPU that executed the code previously placed in that chunk.
--- arch/x86/kernel/cpu/bugs.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
arch/x86/kernel/cpu/bugs.c +7 -1
@@ -2253,12 +2253,18 @@ static void __init spectre_v2_update_mitigation(void)#ifdef CONFIG_BPF_JIT static void __bpf_arch_ibpb (void *unused) { +WRITE_ONCE (*raw_cpu_ptr (&bpf_prog_ran), false);write_ibpb (); } +static bool bpf_ibpb_needed (int cpu,void *unused) +{ +return READ_ONCE (per_cpu (bpf_prog_ran, cpu)); +} +void bpf_arch_ibpb (void ) { -on_each_cpu (__bpf_arch_ibpb,NULL ,1 ); +on_each_cpu_cond (bpf_ibpb_needed, __bpf_arch_ibpb,NULL ,1 ); }static bool __init cpu_wants_ibpb_bpf (void )
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH bpf-next 2/2] x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] bpf: link failure on CONFIG_BPF_JIT=n from bpf_prog_mark_ran() - [Medium] x86/bugs: bpf_arch_ibpb()…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] bpf: link failure on CONFIG_BPF_JIT=n from bpf_prog_mark_ran()
- [Medium] x86/bugs: bpf_arch_ibpb() skips CPUs that ran bpf_run_async_cb()
- [Medium] x86/bugs: bpf_arch_ibpb() skips CPUs that ran BPF trampolines
- [Medium] x86/bugs: bpf_arch_ibpb() skips CPUs for reused non-BPF execmem VAs
--
commit 781f81166f8975129aeee336798a4632f98a3a71
Author: Viktor Malik <[email protected]>
x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
This commit changes bpf_arch_ibpb() to use on_each_cpu_cond() with the per-CPU bpf_prog_ran flag so that only CPUs that have executed a BPF program since the last flush receive an IPI and IBPB, clearing the flag before issuing write_ibpb().
arch/x86/kernel/cpu/bugs.c static void __init spectre_v2_update_mitigation(void) · line 2258
Quoted 11 lines
arch/x86/kernel/cpu/bugs.c +1
-0@@ -2253,12 +2253,18 @@ static void __init spectre_v2_update_mitigation(void)#ifdef CONFIG_BPF_JIT static void __bpf_arch_ibpb (void *unused) { +WRITE_ONCE (*raw_cpu_ptr (&bpf_prog_ran), false);write_ibpb (); }
[Severity: High]
Does commit "bpf: Track CPUs that have executed a BPF program" break linking when CONFIG_BPF_JIT=n?
kernel/bpf/core.c defines bpf_pred_flush_enabled and bpf_prog_ran inside #ifdef CONFIG_BPF_JIT, while include/linux/filter.h defines bpf_prog_mark_ran() outside that guard and calls it unconditionally from __bpf_prog_run().
Any build with CONFIG_BPF_JIT=n that compiles a caller such as __seccomp_filter() in kernel/seccomp.c fails to link with undefined references to both symbols. Guarding bpf_prog_mark_ran() with #ifdef CONFIG_BPF_JIT and providing an empty stub otherwise would avoid this.
arch/x86/kernel/cpu/bugs.c static void __init spectre_v2_update_mitigation(void) · line 2268
Quoted 11 lines
arch/x86/kernel/cpu/bugs.c +6
-1+static bool bpf_ibpb_needed (int cpu,void *unused) +{ +return READ_ONCE (per_cpu (bpf_prog_ran, cpu)); +} +void bpf_arch_ibpb (void ) { -on_each_cpu (__bpf_arch_ibpb,NULL ,1 ); +on_each_cpu_cond (bpf_ibpb_needed, __bpf_arch_ibpb,NULL ,1 ); }
[Severity: Medium]
Can bpf_arch_ibpb() skip a CPU that executed a JITed async BPF callback?
Async callbacks (such as bpf_timer_cb() and bpf_wq_work()) are JITed as subprograms into bpf_prog_pack chunks and invoked directly through bpf_run_async_cb() in kernel/bpf/helpers.c, bypassing __bpf_prog_run() and the trampoline exit helpers.
Because bpf_run_async_cb() does not call bpf_prog_mark_ran(), bpf_prog_ran remains false on that CPU. When a freed chunk is later reused for an unprivileged cBPF program, bpf_arch_ibpb() skips flushing that CPU and leaves stale branch predictions intact.
Calling bpf_prog_mark_ran() after callback_fn() returns in bpf_run_async_cb() would close this gap.
[Severity: Medium]
Will bpf_arch_ibpb() also skip CPUs that executed a JITed BPF trampoline image?
On x86_64, arch_alloc_bpf_trampoline() allocates trampoline images from bpf_prog_pack, while bpf_prog_mark_ran() is only called in the per-program __bpf_prog_exit*() helpers and not in __bpf_tramp_exit().
During __bpf_trampoline_unlink_prog(), bpf_trampoline_skip_prog() patches the skip target past bpf_trampoline_exit(), so a CPU running the trampoline before detach executes JITed trampoline branches (including call *rbx under BPF_TRAMP_F_ORIG_STACK) with bpf_prog_ran left false.
A task running a BPF_TRAMP_F_CALL_ORIG trampoline without fexit can also migrate or take a clearing IPI during orig_call before executing the trampoline epilogue. When the trampoline chunk is later reused for cBPF, bpf_arch_ibpb() skips flushing that CPU and leaves stale predictions.
[Severity: Medium]
Does restricting bpf_arch_ibpb() to CPUs with bpf_prog_ran set miss stale predictions from non-BPF code when a new pack reuses virtual addresses?
On x86, execmem_arch_setup() places EXECMEM_BPF in the same virtual address range and shared EXECMEM_ROX_CACHE pool as EXECMEM_MODULE_TEXT, EXECMEM_KPROBES, and EXECMEM_FTRACE, and execmem_free() does not issue an IBPB.
When alloc_new_pack() reuses addresses freed by an unloaded module or module .init.text, the first cBPF allocation calls bpf_arch_ibpb() and clears pack->dirty_map. CPUs that executed that unloaded code without running BPF have bpf_prog_ran false and are skipped without being flushed.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH bpf-next 2/2] x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
Quoted 6 lines · On 12/4/26 15:17, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] bpf: link failure onCONFIG_BPF_JIT=nfrombpf_prog_mark_ran()
- [Medium] x86/bugs:bpf_arch_ibpb()skips CPUs that ranbpf_run_async_cb()
- [Medium] x86/bugs:bpf_arch_ibpb()skips CPUs that ran BPF trampolines
These 3 were already flagged in the review of the first patch, I'll update my patches accordingly.
Quoted 95 lines
- [Medium] x86/bugs:
bpf_arch_ibpb()skips CPUs for reused non-BPF execmem VAs
--commit
781f81166f8975129aeee336798a4632f98a3a71
Author: Viktor Malik <[email protected]>x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
This commit changes
bpf_arch_ibpb()to useon_each_cpu_cond()with the per-CPUbpf_prog_ranflag so that only CPUs that have executed a BPF program since the last flush receive an IPI and IBPB, clearing the flag before issuingwrite_ibpb().arch/x86/kernel/cpu/bugs.c static void __init spectre_v2_update_mitigation(void) · line 2258
Quoted 11 lines
arch/x86/kernel/cpu/bugs.c +1
-0@@ -2253,12 +2253,18 @@ static void __init spectre_v2_update_mitigation(void)#ifdef CONFIG_BPF_JIT static void __bpf_arch_ibpb (void *unused) { +WRITE_ONCE (*raw_cpu_ptr (&bpf_prog_ran), false);write_ibpb (); }[Severity: High]
Does commit "bpf: Track CPUs that have executed a BPF program" break linking whenCONFIG_BPF_JIT=n?
kernel/bpf/core.cdefinesbpf_pred_flush_enabledandbpf_prog_raninside #ifdefCONFIG_BPF_JIT, whileinclude/linux/filter.hdefinesbpf_prog_mark_ran()outside that guard and calls it unconditionally from__bpf_prog_run().Any build with
CONFIG_BPF_JIT=nthat compiles a caller such as__seccomp_filter()inkernel/seccomp.cfails to link with undefined references to both symbols. Guardingbpf_prog_mark_ran()with #ifdefCONFIG_BPF_JITand providing an empty stub otherwise would avoid this.arch/x86/kernel/cpu/bugs.c static void __init spectre_v2_update_mitigation(void) · line 2268
Quoted 11 lines
arch/x86/kernel/cpu/bugs.c +6
-1+static bool bpf_ibpb_needed (int cpu,void *unused) +{ +return READ_ONCE (per_cpu (bpf_prog_ran, cpu)); +} +void bpf_arch_ibpb (void ) { -on_each_cpu (__bpf_arch_ibpb,NULL ,1 ); +on_each_cpu_cond (bpf_ibpb_needed, __bpf_arch_ibpb,NULL ,1 ); }[Severity: Medium]
Canbpf_arch_ibpb()skip a CPU that executed a JITed async BPF callback?Async callbacks (such as
bpf_timer_cb()andbpf_wq_work()) are JITed as subprograms intobpf_prog_packchunks and invoked directly throughbpf_run_async_cb()inkernel/bpf/helpers.c, bypassing__bpf_prog_run()and the trampoline exit helpers.Because
bpf_run_async_cb()does not callbpf_prog_mark_ran(),bpf_prog_ranremains false on that CPU. When a freed chunk is later reused for an unprivileged cBPF program,bpf_arch_ibpb()skips flushing that CPU and leaves stale branch predictions intact.Calling
bpf_prog_mark_ran()aftercallback_fn()returns inbpf_run_async_cb()would close this gap.[Severity: Medium]
Willbpf_arch_ibpb()also skip CPUs that executed a JITed BPF trampoline image?On
x86_64,arch_alloc_bpf_trampoline()allocates trampoline images frombpf_prog_pack, whilebpf_prog_mark_ran()is only called in the per-program __bpf_prog_exit*() helpers and not in__bpf_tramp_exit().During
__bpf_trampoline_unlink_prog(),bpf_trampoline_skip_prog()patches the skip target pastbpf_trampoline_exit(), so a CPU running the trampoline before detach executes JITed trampoline branches (including call *rbx underBPF_TRAMP_F_ORIG_STACK) withbpf_prog_ranleft false.A task running a
BPF_TRAMP_F_CALL_ORIGtrampoline without fexit can also migrate or take a clearing IPI duringorig_callbefore executing the trampoline epilogue. When the trampoline chunk is later reused for cBPF,bpf_arch_ibpb()skips flushing that CPU and leaves stale predictions.[Severity: Medium]
Does restrictingbpf_arch_ibpb()to CPUs withbpf_prog_ranset miss stale predictions from non-BPF code when a new pack reuses virtual addresses?On x86,
execmem_arch_setup()placesEXECMEM_BPFin the same virtual address range and sharedEXECMEM_ROX_CACHEpool asEXECMEM_MODULE_TEXT,EXECMEM_KPROBES, andEXECMEM_FTRACE, andexecmem_free()does not issue an IBPB.
Quoted 4 lines
When
alloc_new_pack()reuses addresses freed by an unloaded module or module .init.text, the first cBPF allocation callsbpf_arch_ibpb()and clearspack->dirty_map. CPUs that executed that unloaded code without running BPF havebpf_prog_ranfalse and are skipped without being flushed.
This one is a bit unfortunate. I'm not aware of any way to detect that a module or .init.text code was allocated at a given VA range at the time alloc_new_pack() runs and just conservatively flushing IBPB on all CPUs is not a viable option for NOHZ_FULL / isolcpus.
Re: [PATCH bpf-next 2/2] x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPF
In reply to Viktor MalikQuoted 7 lines · Viktor Malik
bpf_arch_ibpb()issues the BPF JIT-spraying predictor flush on every online CPU viaon_each_cpu(). On systems with isolated/nohz_full CPUs, an (unprivileged) cBPF load/free therefore delivers IPIs and IBPBs to CPUs that never run BPF, causing latency spikes on cores dedicated to latency-sensitive workloads (the IPI steal plus a branch-predictor wipe that slows the victim afterwards).
Quoted 8 lines
Use the per-CPU
bpf_prog_ranflag introduced in the previous patch to flush only the CPUs that have executed a BPF program since the last flush. This is sound since a stale prediction for a reused JIT chunk can only exist on a CPU that executed the code previously placed in that chunk.Fixes a3af84b0fa00 ("x86/bugs: Enable IBPB flush on BPF JIT allocation")Signed-off-by Viktor Malik <[email protected]>
+ Greg
Quoted 22 lines · Viktor Malik
Hi,
we have recently started observing latency spikes on systems with isolated CPUs when classic BPF programs were running in the background (e.g. executed by NetworkManager or seccomp). The latencies are caused by the BPF JIT-spraying mitigation introduced by commit
96cce16e26dd("bpf: Support for hardening against JIT spraying") and its follow-ups. The reason is that the IBPB flush is currently broadcast to every online CPU, including the isolated ones that never run BPF programs.While recent changes [1] have significantly decreased the frequency of the IBPB flushes, they haven't eliminated them completely, which still poses a serious problem for latency-sensitive workloads.
This patch series implement one of the ideas from
a9b1f19a6a67("bpf:
Prefer packs that won't trigger an IBPB flush on allocation") and introduce a mechanism to completely avoid the IBPB flushes on CPUs that have not run any BPF program since the last flush. This is sound because the original Spectre-v2 vulnerability is only exploitable if a cBPF program runs on a CPU that previously ran any BPF program (and therefore can reuse the branch predictors trained on the previous program).
Quoted 7 lines
Patch #1 introduces a new per-cpu flag
bpf_prog_ran, which records that a CPU executed any BPF program, and patch #2 restricts the IBPB flushes on x86 to CPUs that have the flag set. This way, the isolated CPUs that never run any BPF programs do not receive the unnecessary flushes.
So AFAICT the original mitigation made it through via the CVE/embargo process, and the addition of an on_each_cpu() flew under the radar.
This is quite unfortunate for NOHZ_FULL / isolcpus, it's the equivalent of allowing a priority inversion under PREEMPT_RT, or slapping on a huge preempt_disable() section. Luckily for us at Red Hat this got caught before it ended in production, but that's still not ideal.
The sashiko run on the 7.1 backports [1] did pick up on the on_each_cpu(), but only warned about a potential DoS, not about the isolation implications.
I'm trying to think of how to improve the tooling so that even in the case of an embargo'd release, at least one alarm would be raised. Is there some private sashiko instance that is used for embargo'd patch review ? If so we could teach it to be picky about on_each_cpu() additions. Otherwise the only other thing I can think of is to teach checkpatch about it too.
[1]: https://lore.kernel.org/all/[email protected]/
Quoted 12 lines
Viktor Malik (2):
bpf: Track CPUs that have executed a BPF program x86/bugs: Restrict BPF JIT IBPB flush to CPUs that ran BPFarch/x86/kernel/cpu/bugs.c | 8 +++++++- include/linux/filter.h | 27 ++++++++++++++++++++++++++- kernel/bpf/core.c | 8 ++++++++ kernel/bpf/trampoline.c | 5 +++++ 4 files changed, 46 insertions(+), 2 deletions(-)--
2.56.1
Quoted 4 lines · Valentin Schneider
This is quite unfortunate for
NOHZ_FULL/ isolcpus, it's the equivalent of allowing a priority inversion underPREEMPT_RT, or slapping on a hugepreempt_disable()section. Luckily for us at Red Hat this got caught before it ended in production, but that's still not ideal.
I think everything worked fine. Red Hat's entire business model is to take upstream and fashion it into something that can be put into production. If your customers ran stable directly, we wouldn't need Red Hat.
I do *NOT* want to add more things to the pre-embargo-release process. Even a private Sashiko. The best we can do is to get *A* mitigation out. Not a perfect one, but *A* mitigation. The kinks get worked out in public after the embargo.
The NOHZ_FULL people aren't running untrusted code anyway. So I'm not sure why they care in the first place other than being confused.
Shouldn't you be getting them all running mitigations=off in the first place?
Quoted 15 lines · Dave Hansen
Quoted 4 lines · Valentin Schneider
This is quite unfortunate for
NOHZ_FULL/ isolcpus, it's the equivalent of allowing a priority inversion underPREEMPT_RT, or slapping on a hugepreempt_disable()section. Luckily for us at Red Hat this got caught before it ended in production, but that's still not ideal.I think everything worked fine. Red Hat's entire business model is to take upstream and fashion it into something that can be put into production. If your customers ran stable directly, we wouldn't need Red Hat.
I do *NOT* want to add more things to the pre-embargo-release process. Even a private Sashiko. The best we can do is to get *A* mitigation out. Not a perfect one, but *A* mitigation. The kinks get worked out in public after the embargo.
Quoted 5 lines
The
NOHZ_FULLpeople aren't running untrusted code anyway. So I'm not sure why they care in the first place other than being confused.Shouldn't you be getting them all running mitigations=off in the first place?
That would make our lives so much easier :-) Unfortunately, no... AIUI with Openshift we can have all sorts of things running on the HK CPUs, it's all containerized but that doesn't really count anymore.
Quoted 10 lines · Valentin Schneider
Quoted 5 lines · Dave Hansen
The
NOHZ_FULLpeople aren't running untrusted code anyway. So I'm not sure why they care in the first place other than being confused.Shouldn't you be getting them all running mitigations=off in the first place?
That would make our lives so much easier :-) Unfortunately, no... AIUI with Openshift we can have all sorts of things running on the HK CPUs, it's all containerized but that doesn't really count anymore.
if untrusted tasks stay on HK CPUs there is no need to track every prog. Lets flush HK CPUs as today and track nohz_full CPUs only.
So JIT marks the CPU in the epilogue of unprivileged cBPF only.
I'm strongly against penalizing eBPF.
Instead of patches 1 and 2:
arch/x86/include/asm/nospec-branch.h +1 -0
@@ -444,6 +444,7 @@ extern void write_ibpb(void);#ifdef CONFIG_BPF_JIT extern void bpf_arch_ibpb (void ); +DECLARE_PER_CPU (bool, x86_cbpf_ran);#endif #ifdef CONFIG_X86_64
arch/x86/kernel/cpu/bugs.c +12 -1
@@ -13,6 +13,7 @@#include <linux/module.h> #include <linux/nospec.h> #include <linux/prctl.h> +#include <linux/sched/isolation.h> #include <linux/sched/smt.h> #include <linux/pgtable.h> #include <linux/bpf.h>
@@ -2251,14 +2252,24 @@ static void __init spectre_v2_update_mitigation(void) }#ifdef CONFIG_BPF_JIT +/* Set by JITed unprivileged cBPF on exit, with nohz_full= only */ +DEFINE_PER_CPU (bool, x86_cbpf_ran); +static void __bpf_arch_ibpb (void *unused) { +this_cpu_write (x86_cbpf_ran, false);write_ibpb (); } +static bool bpf_cpu_needs_ibpb (int cpu,void *unused) +{ +return housekeeping_cpu (cpu,HK_TYPE_KERNEL_NOISE ) || +READ_ONCE (per_cpu (x86_cbpf_ran, cpu)); +} +void bpf_arch_ibpb (void ) { -on_each_cpu (__bpf_arch_ibpb,NULL ,1 ); +on_each_cpu_cond (bpf_cpu_needs_ibpb, __bpf_arch_ibpb,NULL ,1 ); }static bool __init cpu_wants_ibpb_bpf (void )
arch/x86/net/bpf_jit_comp.c +8 -0
@@ -13,6 +13,7 @@#include <linux/bpf_unwind.h> #include <linux/bpf_verifier.h> #include <linux/memory.h> +#include <linux/sched/isolation.h> #include <linux/sort.h> #include <linux/extable.h> #include <asm/extable.h>
@@ -3913,6 +3914,13 @@ emit_jmp: !ns_capable_noaudit(&init_user_ns, CAP_SYS_ADMIN)) {if (emit_spectre_bhb_barrier (&prog, ip, bpf_prog))return -EINVAL ; +if (static_branch_unlikely (&bpf_pred_flush_enabled) && +housekeeping_enabled (HK_TYPE_KERNEL_NOISE )) { +/* mov byte ptr gs:[x86_cbpf_ran], 1 */ +EMIT4_off32 (0x65 ,0xC6 ,0x04 ,0x25 , + (u32 )(unsigned long )&x86_cbpf_ran); +EMIT1 (1 ); + } }/* Deallocate outgoing args 7+ area and the slot of BPF_REG_ARENA_SP. */ emit_add_rsp (&prog, outgoing_rsp + (arena_sp_save ?8 :0 ));
pw-bot: cr