* [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack
[not found] <20261125-nospec-result-reply-d60fdc6da8ef@fau.de>
@ 2026-11-25 17:12 ` Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn Luis Gerhorst
` (3 more replies)
0 siblings, 4 replies; 7+ messages in thread
From: Luis Gerhorst @ 2026-11-25 17:12 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Cc: Luis Gerhorst, Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
John Fastabend, Shuah Khan, Henriette Herzog, linux-kselftest
This is an alternative to patches 4 and 5 of [1]. It applies on top of
patches 1-3 of that series.
check_stack_write_fixed_off() sets nospec_result for every insn that
stores to the stack and must not be bypassed speculatively: a BPF_MEM
store, a BPF_ATOMIC insn, or a call of a helper or kfunc that
initializes a dynptr, an iterator or the flags of bpf_local_irq_save()
there. bpf_convert_ctx_accesses() emits the nospec only after BPF_MEM
stores.
[1] handles the other two cases per insn: patch 4 also emits the nospec
after BPF_ATOMIC insns, patch 5 makes do_check() continue a speculative
path behind a call because no nospec follows it. This series emits the
nospec after every insn with nospec_result instead, whatever the insn
is. do_check() is not changed: it can end a speculative path at each of
these insns, and the store of a call is covered for Spectre v4 like
every other store to the stack.
The nospec behind a call has to be inserted without taking the aux data
from the call, because the passes that follow still rewrite the call.
bpf_patch_insn_data() can not do that: it moves the aux data to the last
insn of the patch.
patch content
----- ------------------------------------------------------------------
1 bpf_insert_insns(), which inserts insns in front of or behind an
insn that keeps its aux data, and its use where a patch only
inserts. No functional change.
2 tests for the converted callers that no test reached
3 the fix: a pass that emits the nospec in front of an insn with
nospec, and behind an insn with nospec_result
4 tests for the nospec behind calls and atomics
The main downside is that bpf_insert_insns() needs a buffer of its own
to build the patch, because the callers pass env->insn_buf. This adds
insert_buf with INSN_BUF_SIZE insns (256 bytes) to bpf_verifier_env.
[1] https://lore.kernel.org/bpf/20261125040820.947816-1-alexei.starovoitov@gmail.com/
Luis Gerhorst (4):
bpf: Add bpf_insert_insns() to insert insns next to an insn
selftests/bpf: Test the insns that bpf_insert_insns() inserts
bpf: Emit nospec after every insn with nospec_result
selftests/bpf: Test nospec after stack writes of calls and atomics
include/linux/bpf_verifier.h | 2 +
kernel/bpf/fixups.c | 351 +++++++++---------
kernel/bpf/verifier.c | 3 +
.../bpf/progs/verifier_percpu_addr.c | 31 ++
.../selftests/bpf/progs/verifier_unpriv.c | 201 ++++++++++
.../selftests/bpf/progs/verifier_zext.c | 57 +++
6 files changed, 477 insertions(+), 168 deletions(-)
base-commit: 81c6c8c608b6075846d3bd5b6f57958300a56eda
prerequisite-patch-id: 6079fc600b6711222dba245601eab9d1b76f0ecc
prerequisite-patch-id: 1f8ba1a2f5b8b7bf73dea4349ccd7b2679f4ffaf
prerequisite-patch-id: 2a97f28aef89f4281e7205a16f2210d3a95581b2
--
2.56.1
^ permalink raw reply [flat|nested] 7+ messages in thread
* [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn
2026-11-25 17:12 ` [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack Luis Gerhorst
@ 2026-11-25 17:12 ` Luis Gerhorst
2026-11-25 18:17 ` bot+bpf-ci
2026-11-25 17:12 ` [PATCH bpf 2/4] selftests/bpf: Test the insns that bpf_insert_insns() inserts Luis Gerhorst
` (2 subsequent siblings)
3 siblings, 1 reply; 7+ messages in thread
From: Luis Gerhorst @ 2026-11-25 17:12 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Cc: Luis Gerhorst, Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
John Fastabend, Shuah Khan, Henriette Herzog, linux-kselftest
bpf_patch_insn_data() replaces an insn with a patch and moves the aux
data of the insn to the last insn of the patch. To insert insns in front
of or behind an insn, the callers put a copy of the insn into the patch.
This has a number of consequences:
- The copy is not the last insn of the patch if the insns are inserted
behind it. adjust_insn_aux_data() finds it by comparing all insns of
the patch with a copy of the original insn, and moves non_stack_access
back to it. The other fields stay at the last insn, so the insn is
left with zeroed aux data for the passes that follow.
- The copy moves down inside the patch if insns are inserted in front of
it. The callers have to adjust it with bpf_adj_moved_insn().
- The callers that insert in front of the insn have to say if the
targets of the insn follow it, with BPF_PATCH_MOVE_TARGET. This only
covers the indirect targets, they have to move the jumps to the insn
with adjust_jmp_off() themselves.
Add bpf_insert_insns() which takes only the new insns and where they
go: in front of the insn, with a jump to the insn running them or
skipping them, or behind the insn. It builds the patch, adjusts the
copy, moves the jumps to the insn if they are to skip the new insns, and
tells adjust_insn_aux_data() where the copy is. The insn keeps
all of its aux data. Every other insn of a patch is new and is marked
for non-stack access if it accesses memory, which no longer needs the
comparison.
Use it where a patch only inserts:
- the zero extension and the randomization of the upper 32 bits in
bpf_opt_subreg_zext_lo32_rnd_hi32()
- the prologue, the save of the ctx for the epilogue and the
initialization of the may_goto counter, which used
BPF_PATCH_MOVE_TARGET
- the per-CPU address of a ld_imm64 in bpf_do_misc_fixups()
- the nospec in front of and behind an insn in
bpf_convert_ctx_accesses()
bpf_insert_insns() returns an ERR_PTR(), so that the callers still
return -ERANGE if the insn can not be adjusted.
bpf_patch_insn_data() is left for the patches that replace the insn.
Where such a patch still contains the insn, the insn now counts as new
and is marked for non-stack access if it accesses memory. This makes no
difference, because none of these patches contains a stack access.
No functional change.
Assisted-by: Claude:claude-mythos-5-2
Signed-off-by: Luis Gerhorst <luis.gerhorst@fau.de>
---
include/linux/bpf_verifier.h | 1 +
kernel/bpf/fixups.c | 284 +++++++++++++++++------------------
2 files changed, 141 insertions(+), 144 deletions(-)
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index b43eb97bcd44..2f9fa9d889a4 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1217,6 +1217,7 @@ struct bpf_verifier_env {
char tmp_str_buf[TMP_STR_BUF_LEN];
char tmp_arg_name[32];
struct bpf_insn insn_buf[INSN_BUF_SIZE];
+ struct bpf_insn insert_buf[INSN_BUF_SIZE];
struct bpf_insn epilogue_buf[INSN_BUF_SIZE];
struct bpf_scc_callchain callchain_buf;
struct bpf_liveness *liveness;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index a656634fa9e4..485feffe0536 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -170,82 +170,60 @@ enum bpf_patch_mode {
BPF_PATCH_MOVE_TARGET, /* targets of 'off' follow the original insn to 'off + len - 1' */
};
+/* The patch does not contain the insn that it replaces. */
+#define BPF_PATCH_NO_ORIG -1
+
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
+ *
+ * The aux data of the original insn stays with the insn if the range still
+ * contains it, at index 'orig'. Otherwise 'orig' is BPF_PATCH_NO_ORIG and the
+ * aux data moves to the last insn of the range.
*/
static void adjust_insn_aux_data(struct bpf_verifier_env *env,
struct bpf_prog *new_prog, u32 off, u32 cnt,
- struct bpf_insn *original_insn,
- enum bpf_patch_mode mode)
+ int orig, enum bpf_patch_mode mode)
{
struct bpf_insn_aux_data *data = env->insn_aux_data;
struct bpf_insn *insn = new_prog->insnsi;
+ u32 last = off + cnt - 1;
+ u32 keep = orig == BPF_PATCH_NO_ORIG ? last : off + orig;
+ u32 target = mode == BPF_PATCH_MOVE_TARGET ? keep : off;
+ bool indirect_target = data[off].indirect_target;
u32 old_seen = data[off].seen;
- u32 prog_len;
+ u32 prog_len = new_prog->len;
int i;
- /* aux info at OFF always needs adjustment, no matter fast path
- * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
- * original insn at old prog.
- */
- data[off].zext_dst = bpf_insn_def32(new_prog, insn + off + cnt - 1) >= 0;
-
- if (cnt == 1) {
- /*
- * A non-memory accessing insn could have been replaced by a
- * memory accessing insn, systematically mark it for non-stack
- * access
- */
- data[off].non_stack_access = bpf_is_mem_insn(insn + off);
- return;
+ if (cnt > 1) {
+ env->insn_aux_data_len = prog_len;
+ memmove(data + last, data + off,
+ sizeof(struct bpf_insn_aux_data) * (prog_len - last));
+ /* The aux data of the original insn is at 'off' and 'last' now. */
+ data[keep] = data[last];
+ for (i = off; i <= last; i++)
+ if (i != keep)
+ memset(data + i, 0, sizeof(struct bpf_insn_aux_data));
}
- prog_len = new_prog->len;
- env->insn_aux_data_len = prog_len;
- memmove(data + off + cnt - 1, data + off,
- sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
- memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
- for (i = off; i < off + cnt - 1; i++) {
+ for (i = off; i <= last; i++) {
/* Expand insni[off]'s seen count to the patched range. */
data[i].seen = old_seen;
data[i].zext_dst = bpf_insn_def32(new_prog, insn + i) >= 0;
/*
- * In BPF_PATCH_MOVE_TARGET mode the original insn is the last
- * slot by construction.
+ * A new insn can access memory. Systematically mark it for
+ * non-stack access, only the original insn keeps its marking.
*/
- if (mode == BPF_PATCH_KEEP_TARGET &&
- !memcmp(insn + i, original_insn, sizeof(struct bpf_insn))) {
- data[i].non_stack_access =
- data[off + cnt - 1].non_stack_access;
- data[off + cnt - 1].non_stack_access = false;
- } else if (bpf_is_mem_insn(insn + i)) {
- data[i].non_stack_access = true;
- }
+ if (orig == BPF_PATCH_NO_ORIG || i != keep)
+ data[i].non_stack_access = bpf_is_mem_insn(insn + i);
}
/*
- * Last slot instruction could be a newly generated
- * BPF_ST/BPF_LDX/BPF_STX, systematically mark it for non-stack access
- * if it is not the original instruction, otherwise keep the
- * original marking
+ * An indirect jump to 'off' goes where the other targets of 'off' go.
+ * This matches bpf_insn_array_adjust().
*/
- if (bpf_is_mem_insn(insn + off + cnt - 1) &&
- memcmp(insn + off + cnt - 1, original_insn, sizeof(struct bpf_insn)))
- data[off + cnt - 1].non_stack_access = true;
-
- /*
- * The indirect_target flag of the original instruction was moved to the last of the
- * new instructions by the above memmove and memset, but the indirect jump target is
- * actually the first instruction, so move it back. This also matches with the behavior
- * of bpf_insn_array_adjust(), which preserves xlated_off to point to the first new
- * instruction. For BPF_PATCH_MOVE_TARGET the original instruction is the last one,
- * so the flag already sits where needed.
- */
- if (mode == BPF_PATCH_KEEP_TARGET && data[off + cnt - 1].indirect_target) {
- data[off].indirect_target = 1;
- data[off + cnt - 1].indirect_target = 0;
- }
+ data[keep].indirect_target = 0;
+ data[target].indirect_target = indirect_target;
}
static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
@@ -310,13 +288,12 @@ static bool bpf_rewrite_must_abort(void)
static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len,
- enum bpf_patch_mode mode)
+ int orig, enum bpf_patch_mode mode)
{
struct bpf_prog *new_prog;
struct bpf_insn_aux_data *new_data = NULL;
/* The first slot whose targets move. */
u32 first = mode == BPF_PATCH_MOVE_TARGET ? off : off + 1;
- struct bpf_insn original_insn;
if (bpf_rewrite_must_abort())
return NULL;
@@ -332,7 +309,6 @@ static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32
env->insn_aux_data = new_data;
}
- memcpy(&original_insn, env->prog->insnsi + off, sizeof(struct bpf_insn));
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (IS_ERR(new_prog)) {
if (PTR_ERR(new_prog) == -ERANGE)
@@ -341,7 +317,7 @@ static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32
env->insn_aux_data[off].orig_idx);
return NULL;
}
- adjust_insn_aux_data(env, new_prog, off, len, &original_insn, mode);
+ adjust_insn_aux_data(env, new_prog, off, len, orig, mode);
adjust_subprog_starts(env, off, len);
adjust_insn_arrays(env, first, len);
bpf_adjust_func_ptrs(env, off, len);
@@ -352,7 +328,8 @@ static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32
struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
- return __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_KEEP_TARGET);
+ return __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_NO_ORIG,
+ BPF_PATCH_KEEP_TARGET);
}
/*
@@ -431,6 +408,62 @@ static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
return 0;
}
+/* Where bpf_insert_insns() puts the new insns relative to the insn at 'off'. */
+enum bpf_insert_pos {
+ BPF_INSERT_BEFORE, /* in front of the insn, a jump to the insn runs them too */
+ BPF_INSERT_ENTRY, /* in front of the insn, a jump to the insn skips them */
+ BPF_INSERT_AFTER, /* behind the insn */
+};
+
+/*
+ * Insert 'cnt' insns next to env->prog->insnsi[off]. Unlike with
+ * bpf_patch_insn_data(), the insn is not replaced: it keeps its aux data,
+ * wherever it ends up. Returns the new prog or an ERR_PTR().
+ */
+static struct bpf_prog *bpf_insert_insns(struct bpf_verifier_env *env, u32 off,
+ const struct bpf_insn *insns, u32 cnt,
+ enum bpf_insert_pos pos)
+{
+ enum bpf_patch_mode mode = pos == BPF_INSERT_ENTRY ? BPF_PATCH_MOVE_TARGET :
+ BPF_PATCH_KEEP_TARGET;
+ struct bpf_insn *patch = env->insert_buf;
+ struct bpf_prog *new_prog;
+ /* The index of the insn in the patch. */
+ u32 orig;
+
+ if (verifier_bug_if(cnt >= INSN_BUF_SIZE, env, "%u insns inserted", cnt))
+ return ERR_PTR(-EFAULT);
+
+ if (pos == BPF_INSERT_AFTER) {
+ orig = 0;
+ memcpy(patch + 1, insns, cnt * sizeof(*insns));
+ } else {
+ orig = cnt;
+ memcpy(patch, insns, cnt * sizeof(*insns));
+ }
+ patch[orig] = env->prog->insnsi[off];
+
+ /* The insn moved down by 'orig' insns. */
+ if (bpf_adj_moved_insn(&patch[orig], orig)) {
+ verbose(env, "insn %d cannot be patched due to 16-bit range\n",
+ env->insn_aux_data[off].orig_idx);
+ return ERR_PTR(-ERANGE);
+ }
+
+ new_prog = __bpf_patch_insn_data(env, off, patch, cnt + 1, orig, mode);
+ if (!new_prog)
+ return ERR_PTR(-ENOMEM);
+
+ /*
+ * The jumps to the insn still name 'off'. Adjustment will succeed
+ * because __bpf_patch_insn_data() didn't fail.
+ */
+ if (pos == BPF_INSERT_ENTRY)
+ WARN_ON(adjust_jmp_off(new_prog, off, cnt));
+
+ return new_prog;
+}
+
static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
u32 off, u32 cnt)
{
@@ -757,7 +790,7 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
struct bpf_insn *patch;
/* use env->insn_buf as two independent buffers */
struct bpf_insn *zext_patch = env->insn_buf;
- struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
+ struct bpf_insn *rnd_hi32_patch = &env->insn_buf[1];
struct bpf_insn_aux_data *aux = env->insn_aux_data;
int i, patch_len, delta = 0, len = env->prog->len;
struct bpf_insn *insns = env->prog->insnsi;
@@ -765,10 +798,10 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
bool rnd_hi32;
rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
- zext_patch[1] = BPF_ZEXT_REG(0);
- rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
- rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
- rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
+ zext_patch[0] = BPF_ZEXT_REG(0);
+ rnd_hi32_patch[0] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
+ rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
+ rnd_hi32_patch[2] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
for (i = 0; i < len; i++) {
int adj_idx = i + delta;
struct bpf_insn insn;
@@ -801,11 +834,10 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
continue;
imm_rnd = get_random_u32();
- rnd_hi32_patch[0] = insn;
- rnd_hi32_patch[1].imm = imm_rnd;
- rnd_hi32_patch[3].dst_reg = load_reg;
+ rnd_hi32_patch[0].imm = imm_rnd;
+ rnd_hi32_patch[2].dst_reg = load_reg;
patch = rnd_hi32_patch;
- patch_len = 4;
+ patch_len = 3;
goto apply_patch_buffer;
}
@@ -830,19 +862,18 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
"zext_dst is set, but no reg is defined"))
return -EFAULT;
- zext_patch[0] = insn;
- zext_patch[1].dst_reg = load_reg;
- zext_patch[1].src_reg = load_reg;
+ zext_patch[0].dst_reg = load_reg;
+ zext_patch[0].src_reg = load_reg;
patch = zext_patch;
- patch_len = 2;
+ patch_len = 1;
apply_patch_buffer:
- new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, adj_idx, patch, patch_len, BPF_INSERT_AFTER);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
env->prog = new_prog;
insns = new_prog->insnsi;
aux = env->insn_aux_data;
- delta += patch_len - 1;
+ delta += patch_len;
}
return 0;
@@ -909,6 +940,7 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
const int insn_cnt = env->prog->len;
+ const struct bpf_insn nospec = BPF_ST_NOSPEC();
struct bpf_insn *epilogue_buf = env->epilogue_buf;
struct bpf_insn *insn_buf = env->insn_buf;
struct bpf_insn *insn;
@@ -930,13 +962,11 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
subprogs[0].stack_depth += 8;
insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
-subprogs[0].stack_depth);
- insn_buf[cnt++] = env->prog->insnsi[0];
- new_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,
- BPF_PATCH_MOVE_TARGET);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, 0, insn_buf, cnt, BPF_INSERT_ENTRY);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
env->prog = new_prog;
- delta += cnt - 1;
+ delta += cnt;
ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
if (ret < 0)
@@ -967,10 +997,11 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
env->prog->aux->attach_btf_id))
return -EINVAL;
env->prog->aux->has_prologue = true;
- new_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,
- BPF_PATCH_MOVE_TARGET);
- if (!new_prog)
- return -ENOMEM;
+ /* the prologue ends with a copy of the first insn */
+ new_prog = bpf_insert_insns(env, 0, insn_buf, cnt - 1,
+ BPF_INSERT_ENTRY);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
env->prog = new_prog;
delta += cnt - 1;
@@ -981,9 +1012,6 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
}
}
- if (delta)
- WARN_ON(adjust_jmp_off(env->prog, 0, delta));
-
if (bpf_prog_is_offloaded(env->prog->aux))
return 0;
@@ -996,29 +1024,20 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
if (env->insn_aux_data[i + delta].nospec) {
WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
- struct bpf_insn *patch = insn_buf;
- *patch++ = BPF_ST_NOSPEC();
- *patch = *insn;
- ret = bpf_adj_moved_insn(patch++, 1);
- if (ret) {
- verbose(env, "insn %d cannot be patched due to 16-bit range\n",
- env->insn_aux_data[i + delta].orig_idx);
- return ret;
- }
- cnt = patch - insn_buf;
- new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, i + delta, &nospec, 1,
+ BPF_INSERT_BEFORE);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
- delta += cnt - 1;
+ delta += 1;
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
/* This can not be easily merged with the
* nospec_result-case, because an insn may require a
* nospec before and after itself. Therefore also do not
* 'continue' here but potentially apply further
- * patching to insn. *insn should equal patch[1] now.
+ * patching to insn.
*/
}
@@ -1090,16 +1109,12 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
/* nospec_result is only used to mitigate Spectre v4 and
* to limit verification-time for Spectre v1.
*/
- struct bpf_insn *patch = insn_buf;
-
- *patch++ = *insn;
- *patch++ = BPF_ST_NOSPEC();
- cnt = patch - insn_buf;
- new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, i + delta, &nospec, 1,
+ BPF_INSERT_AFTER);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
- delta += cnt - 1;
+ delta += 1;
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
@@ -2192,23 +2207,20 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
/*
* We are *skipping* first half of ld_imm64 insn
- * with 'i++;', patching over second half of it
- * with that same half + mov64_percpu_reg insn.
- * All because bpf_patch_insn_data() can only
- * replace one 8-byte insn, which does not work
- * well for ld_imm64 insn.
+ * with 'i++;', to insert the mov64_percpu_reg insn
+ * behind the second half of it.
*/
- insn_buf[0] = insn[1];
- insn_buf[1] = BPF_MOV64_PERCPU_REG(insn->dst_reg, insn->dst_reg);
- cnt = 2;
+ insn_buf[0] = BPF_MOV64_PERCPU_REG(insn->dst_reg, insn->dst_reg);
+ cnt = 1;
i++;
- new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, i + delta, insn_buf, cnt,
+ BPF_INSERT_AFTER);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
- delta += cnt - 1;
+ delta += cnt;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
goto next_insn;
@@ -2818,28 +2830,12 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
BPF_MAX_LOOPS);
}
- /* Copy first actual insn to preserve it */
- insn_buf[cnt] = env->prog->insnsi[subprog_start];
- ret = bpf_adj_moved_insn(&insn_buf[cnt], cnt);
- if (ret) {
- verbose(env, "insn %d cannot be patched due to 16-bit range\n",
- env->insn_aux_data[subprog_start].orig_idx);
- return ret;
- }
- cnt++;
- new_prog = __bpf_patch_insn_data(env, subprog_start, insn_buf, cnt,
- BPF_PATCH_MOVE_TARGET);
- if (!new_prog)
- return -ENOMEM;
+ new_prog = bpf_insert_insns(env, subprog_start, insn_buf, cnt,
+ BPF_INSERT_ENTRY);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
env->prog = prog = new_prog;
- /*
- * If may_goto is a first insn of a prog there could be a jmp
- * insn that points to it, hence adjust all such jmps to point
- * to insn after BPF_ST that inits may_goto count.
- * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
- */
- WARN_ON(adjust_jmp_off(env->prog, subprog_start, cnt - 1));
}
/* Since poke tab is now finalized, publish aux to tracker. */
--
2.56.1
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [PATCH bpf 2/4] selftests/bpf: Test the insns that bpf_insert_insns() inserts
2026-11-25 17:12 ` [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn Luis Gerhorst
@ 2026-11-25 17:12 ` Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 4/4] selftests/bpf: Test nospec after stack writes of calls and atomics Luis Gerhorst
3 siblings, 0 replies; 7+ messages in thread
From: Luis Gerhorst @ 2026-11-25 17:12 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Cc: Luis Gerhorst, Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
John Fastabend, Shuah Khan, Henriette Herzog, linux-kselftest
Cover the cases of the callers of bpf_insert_insns() that no test
reaches:
- The randomization of the upper 32 bits with BPF_F_TEST_RND_HI32. The
existing tests that set the flag check that it is not emitted.
- A zext and a per-CPU address that do not fit, because they are
inserted between a jump with the smallest offset and its target. The
programs are valid, they are only rejected because the verifier can
not widen a jump when it patches a program.
Assisted-by: Claude:claude-mythos-5-2
Signed-off-by: Luis Gerhorst <luis.gerhorst@fau.de>
---
.../bpf/progs/verifier_percpu_addr.c | 31 ++++++++++
.../selftests/bpf/progs/verifier_zext.c | 57 +++++++++++++++++++
2 files changed, 88 insertions(+)
diff --git a/tools/testing/selftests/bpf/progs/verifier_percpu_addr.c b/tools/testing/selftests/bpf/progs/verifier_percpu_addr.c
index fd418f27996f..d7fbaa21359f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_percpu_addr.c
+++ b/tools/testing/selftests/bpf/progs/verifier_percpu_addr.c
@@ -57,6 +57,37 @@ __naked void percpu_addr(void)
: __clobber_all);
}
+/*
+ * The mov_percpu_addr is inserted behind the ld_imm64, between a jump with the
+ * smallest offset and its target. The program is valid, it is only rejected
+ * because the verifier can not widen a jump when it patches a program.
+ */
+SEC("raw_tp")
+__description("per-CPU address does not fit behind a ld_imm64")
+__failure __msg("cannot be patched due to 16-bit range")
+__arch_x86_64
+__naked void percpu_addr_jump_out_of_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r7 = 0; \
+ goto l1_%=; \
+l0_%=: r0 = 0; \
+ exit; \
+l1_%=: r1 = %[percpu_data] ll; \
+ .rept 32763; \
+ r2 = 0; \
+ .endr; \
+ if r7 != r6 goto l0_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm_addr(percpu_data)
+ : __clobber_all);
+}
+
#else
SEC("raw_tp")
diff --git a/tools/testing/selftests/bpf/progs/verifier_zext.c b/tools/testing/selftests/bpf/progs/verifier_zext.c
index 572017fe28fb..d06a02242c55 100644
--- a/tools/testing/selftests/bpf/progs/verifier_zext.c
+++ b/tools/testing/selftests/bpf/progs/verifier_zext.c
@@ -415,4 +415,61 @@ __naked void probe_mem(void)
: __clobber_all);
}
+/* 32-bit def whose upper half is never read -> upper half is randomized */
+SEC("socket")
+__flag(BPF_F_TEST_RND_HI32)
+__success __retval(0)
+__xlated("w1 = w0")
+__xlated("r12 = {{.*}}")
+__xlated("r12 <<= 32")
+__xlated("r1 |= r12")
+__xlated("r0 = 0")
+__naked void rnd_hi32_alu32_hi_unused(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ w1 = w0; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * The zext is inserted behind the cmpxchg, between a jump with the smallest
+ * offset and its target. The program is valid, it is only rejected because the
+ * verifier can not widen a jump when it patches a program.
+ */
+SEC("tc")
+__description("zext does not fit behind a cmpxchg")
+__failure __msg("cannot be patched due to 16-bit range")
+__naked void zext_cmpxchg32_jump_out_of_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r7 = 0; \
+ goto l1_%=; \
+l0_%=: r0 = 0; \
+ exit; \
+l1_%=: r1 = 0; \
+ *(u64 *)(r10 - 8) = r1; \
+ w0 = 0; \
+ w1 = 1; \
+ .8byte %[cmpxchg32]; \
+ r2 = r0; \
+ .rept 32759; \
+ r1 = 0; \
+ .endr; \
+ if r7 != r6 goto l0_%=; \
+ r0 = r2; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm_insn(cmpxchg32,
+ BPF_ATOMIC_OP(BPF_W, BPF_CMPXCHG, BPF_REG_10, BPF_REG_1, -8))
+ : __clobber_all);
+}
+
char _license[] SEC("license") = "GPL";
--
2.56.1
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result
2026-11-25 17:12 ` [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 2/4] selftests/bpf: Test the insns that bpf_insert_insns() inserts Luis Gerhorst
@ 2026-11-25 17:12 ` Luis Gerhorst
2026-11-25 18:17 ` bot+bpf-ci
2026-11-25 17:12 ` [PATCH bpf 4/4] selftests/bpf: Test nospec after stack writes of calls and atomics Luis Gerhorst
3 siblings, 1 reply; 7+ messages in thread
From: Luis Gerhorst @ 2026-11-25 17:12 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Cc: Luis Gerhorst, Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
John Fastabend, Shuah Khan, Henriette Herzog, linux-kselftest
check_stack_write_fixed_off() sets nospec_result of the insn that writes
to the stack if the store must not be bypassed speculatively. Besides a
BPF_MEM store, the insn can be a BPF_ATOMIC insn or a call: a helper or
kfunc that initializes a dynptr, an iterator or the flags of
bpf_local_irq_save() on the stack. But bpf_convert_ctx_accesses() emits
the nospec only after BPF_MEM stores.
This has two consequences for the other insns:
- Spectre v4: If the store is bypassed, what reads the slot behind the
insn gets the old content of the slot: a load in the program, or a
helper that is passed the slot as a dynptr.
- Spectre v1: do_check() ends a speculative path at an insn with
nospec_result, because a nospec follows that insn. Without the
nospec, the insns behind it are not verified for that path.
Emit the nospec after every insn with nospec_result, whatever the insn
is. Do this in a pass of its own, bpf_emit_nospec(), which runs before
bpf_convert_ctx_accesses(), and move the nospec in front of an insn
there too. The conversion of an insn no longer depends on nospec_result:
bpf_convert_ctx_accesses() used to skip an insn after it emitted the
nospec for it.
Both are inserted with bpf_insert_insns(), so that the insn keeps its
aux data for bpf_convert_ctx_accesses() and bpf_do_misc_fixups().
The pass is skipped if both Spectre v1 and v4 mitigations are bypassed,
because neither nospec nor nospec_result is set then. It only runs for
programs that are loaded without CAP_PERFMON: there it took at most
8.4 ms in our measurements, for a program of the maximum size of 1M
insns without any nospec, which is 0.4% of the 2.1 s that the program
takes to verify.
An insn that is only reached speculatively is rewritten to 'goto -1' by
sanitize_dead_code() and keeps nospec_result. It gets a nospec behind
it now, like it already gets one in front of it for nospec.
Fixes: d6f1c85f2253 ("bpf: Fall back to nospec for Spectre v1")
Assisted-by: Claude:claude-mythos-5-2
Signed-off-by: Luis Gerhorst <luis.gerhorst@fau.de>
---
include/linux/bpf_verifier.h | 1 +
kernel/bpf/fixups.c | 91 ++++++++++++++++++++++--------------
kernel/bpf/verifier.c | 3 ++
3 files changed, 59 insertions(+), 36 deletions(-)
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 2f9fa9d889a4..7dd71cef3f3a 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -2029,6 +2029,7 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);
int bpf_opt_remove_dead_code(struct bpf_verifier_env *env);
int bpf_opt_remove_nops(struct bpf_verifier_env *env);
int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr);
+int bpf_emit_nospec(struct bpf_verifier_env *env);
int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
int bpf_jit_subprogs(struct bpf_verifier_env *env);
int bpf_fixup_call_args(struct bpf_verifier_env *env);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 485feffe0536..d5faaf3233c8 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -940,7 +940,6 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
const int insn_cnt = env->prog->len;
- const struct bpf_insn nospec = BPF_ST_NOSPEC();
struct bpf_insn *epilogue_buf = env->epilogue_buf;
struct bpf_insn *insn_buf = env->insn_buf;
struct bpf_insn *insn;
@@ -1022,25 +1021,6 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
enum bpf_reg_type ptr_type;
u8 mode;
- if (env->insn_aux_data[i + delta].nospec) {
- WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
-
- new_prog = bpf_insert_insns(env, i + delta, &nospec, 1,
- BPF_INSERT_BEFORE);
- if (IS_ERR(new_prog))
- return PTR_ERR(new_prog);
-
- delta += 1;
- env->prog = new_prog;
- insn = new_prog->insnsi + i + delta;
- /* This can not be easily merged with the
- * nospec_result-case, because an insn may require a
- * nospec before and after itself. Therefore also do not
- * 'continue' here but potentially apply further
- * patching to insn.
- */
- }
-
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
@@ -1104,22 +1084,6 @@ int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
continue;
}
- if (type == BPF_WRITE &&
- env->insn_aux_data[i + delta].nospec_result) {
- /* nospec_result is only used to mitigate Spectre v4 and
- * to limit verification-time for Spectre v1.
- */
- new_prog = bpf_insert_insns(env, i + delta, &nospec, 1,
- BPF_INSERT_AFTER);
- if (IS_ERR(new_prog))
- return PTR_ERR(new_prog);
-
- delta += 1;
- env->prog = new_prog;
- insn = new_prog->insnsi + i + delta;
- continue;
- }
-
ptr_type = env->insn_aux_data[i + delta].ptr_type;
switch ((int)ptr_type) {
case PTR_TO_CTX:
@@ -1862,6 +1826,61 @@ static int may_goto_expand_timed(struct bpf_insn *insn_buf, int off,
return cnt;
}
+/*
+ * Emit the speculation barriers that do_check() asked for:
+ *
+ * - nospec: a nospec in front of the insn. It is set if the insn failed a
+ * check on a speculative path.
+ *
+ * - nospec_result: a nospec behind the insn. It is only used to mitigate
+ * Spectre v4 and to limit verification-time for Spectre v1. It is set for a
+ * store to the stack, whatever the insn that stores is: BPF_ST, BPF_STX
+ * including BPF_ATOMIC, or a call of a helper or kfunc.
+ *
+ * An insn may require both. The insn keeps its aux data, so this has to run
+ * before the passes that rewrite the insn itself: what they emit for the insn
+ * stays between the two nospec.
+ */
+int bpf_emit_nospec(struct bpf_verifier_env *env)
+{
+ const struct bpf_insn nospec = BPF_ST_NOSPEC();
+ struct bpf_prog *new_prog;
+ int i;
+
+ /* Neither of the two is set without the mitigations. */
+ if (env->bypass_spec_v1 && env->bypass_spec_v4)
+ return 0;
+
+ if (bpf_prog_is_offloaded(env->prog->aux))
+ return 0;
+
+ for (i = 0; i < env->prog->len; i++) {
+ if (env->insn_aux_data[i].nospec) {
+ WARN_ON_ONCE(env->insn_aux_data[i].alu_state);
+
+ new_prog = bpf_insert_insns(env, i, &nospec, 1, BPF_INSERT_BEFORE);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
+
+ env->prog = new_prog;
+ /* the insn and its aux data are behind the nospec now */
+ i++;
+ }
+
+ if (env->insn_aux_data[i].nospec_result) {
+ new_prog = bpf_insert_insns(env, i, &nospec, 1, BPF_INSERT_AFTER);
+ if (IS_ERR(new_prog))
+ return PTR_ERR(new_prog);
+
+ env->prog = new_prog;
+ /* skip the nospec */
+ i++;
+ }
+ }
+
+ return 0;
+}
+
/* Do various post-verification rewrites in a single program pass.
* These rewrites simplify JIT and interpreter implementations.
*/
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 13c53df386bc..aa73c3326d39 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -24220,6 +24220,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
sanitize_dead_code(env);
}
+ if (ret == 0)
+ ret = bpf_emit_nospec(env);
+
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = bpf_convert_ctx_accesses(env);
--
2.56.1
^ permalink raw reply related [flat|nested] 7+ messages in thread
* [PATCH bpf 4/4] selftests/bpf: Test nospec after stack writes of calls and atomics
2026-11-25 17:12 ` [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack Luis Gerhorst
` (2 preceding siblings ...)
2026-11-25 17:12 ` [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result Luis Gerhorst
@ 2026-11-25 17:12 ` Luis Gerhorst
3 siblings, 0 replies; 7+ messages in thread
From: Luis Gerhorst @ 2026-11-25 17:12 UTC (permalink / raw)
To: Alexei Starovoitov, bpf
Cc: Luis Gerhorst, Daniel Borkmann, Andrii Nakryiko, Eduard Zingerman,
Kumar Kartikeya Dwivedi, Martin KaFai Lau, Song Liu,
Yonghong Song, Jiri Olsa, Emil Tsalapatis, Ihor Solodrai,
John Fastabend, Shuah Khan, Henriette Herzog, linux-kselftest
Check that a nospec follows an insn that writes to the stack if the insn
is not a BPF_MEM store:
- a call of bpf_ringbuf_reserve_dynptr(), which initializes a dynptr on
the stack
- a BPF_ATOMIC insn
Also check that a program is rejected if it requires a nospec that does
not fit: in front of a jump with the smallest offset, or behind a store
that is between such a jump and its target. The programs are valid. They
are rejected because of a limit of insn patching that exists for every
insn the verifier inserts there: the jump can not be widened. The tests
document that the programs are not loaded without the nospec in this
case, not that they should be rejected. No test covered these error
paths so far.
Two more cases reach code that no test runs so far:
- a store that is only reached speculatively: do_check() ends the
speculative path at it because a nospec follows, and the store is
replaced as dead code
- a backward jump with a nospec in front of it, whose 16-bit offset
bpf_adj_moved_insn() adjusts
The programs that need more than an unprivileged program may do are
loaded with CAP_BPF but without CAP_PERFMON, so that Spectre v1 and v4
are mitigated for them.
Assisted-by: Claude:claude-mythos-5-2
Signed-off-by: Luis Gerhorst <luis.gerhorst@fau.de>
---
.../selftests/bpf/progs/verifier_unpriv.c | 201 ++++++++++++++++++
1 file changed, 201 insertions(+)
diff --git a/tools/testing/selftests/bpf/progs/verifier_unpriv.c b/tools/testing/selftests/bpf/progs/verifier_unpriv.c
index a54b5a58b945..12d5e9e66890 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unpriv.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unpriv.c
@@ -1035,6 +1035,71 @@ __naked void stack_write_nospec_slot_index(void)
" ::: __clobber_all);
}
+struct {
+ __uint(type, BPF_MAP_TYPE_RINGBUF);
+ __uint(max_entries, 4096);
+} map_ringbuf SEC(".maps");
+
+/* The helper initializes the dynptr on the stack. */
+SEC("socket")
+__description("unpriv: Spectre v4 nospec after stack write in helper")
+__success __success_unpriv
+__caps_unpriv(CAP_BPF)
+__retval(0)
+#ifdef SPEC_V4
+__xlated_unpriv("r4 = r10")
+__xlated_unpriv("r4 += -16")
+__xlated_unpriv("call")
+__xlated_unpriv("nospec")
+__xlated_unpriv("r1 = r10")
+#endif
+__naked void helper_stack_write_nospec_result(void)
+{
+ asm volatile (" \
+ r1 = %[map_ringbuf] ll; \
+ r2 = 8; \
+ r3 = 0; \
+ r4 = r10; \
+ r4 += -16; \
+ call %[bpf_ringbuf_reserve_dynptr]; \
+ r1 = r10; \
+ r1 += -16; \
+ r2 = 0; \
+ call %[bpf_ringbuf_discard_dynptr]; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_ringbuf_reserve_dynptr),
+ __imm(bpf_ringbuf_discard_dynptr),
+ __imm_addr(map_ringbuf)
+ : __clobber_all);
+}
+
+SEC("socket")
+__description("unpriv: Spectre v4 nospec after atomic stack write")
+__success __success_unpriv
+__caps_unpriv(CAP_BPF)
+__retval(2)
+#ifdef SPEC_V4
+__xlated_unpriv("r1 = 1")
+__xlated_unpriv("*(u64 *)(r10 -8) = r1")
+__xlated_unpriv("nospec")
+__xlated_unpriv("lock *(u64 *)(r10 -8) += r1")
+__xlated_unpriv("nospec")
+__xlated_unpriv("r0 = *(u64 *)(r10 -8)")
+__xlated_unpriv("exit")
+#endif
+__naked void atomic_stack_write_nospec_result(void)
+{
+ asm volatile (" \
+ r1 = 1; \
+ *(u64 *)(r10 - 8) = r1; \
+ lock *(u64 *)(r10 - 8) += r1; \
+ r0 = *(u64 *)(r10 - 8); \
+ exit; \
+" ::: __clobber_all);
+}
+
__noinline int nospec_global_func(int x)
{
return x + 1;
@@ -1072,4 +1137,140 @@ __naked void nospec_backward_call(void)
" ::: __clobber_all);
}
+/*
+ * The jump is reached with a pointer in r6 on a speculative path only, so a
+ * nospec is required in front of it. Its offset is the smallest one that a
+ * jump can have, and the nospec is between the jump and its target: the offset
+ * can not be adjusted for the nospec.
+ *
+ * The program is valid, it is only rejected because the verifier can not widen
+ * a jump when it patches a program. Any insn that is inserted between such a
+ * jump and its target has the same effect. Without the nospec the program
+ * would not be safe, so it must not be loaded. If jumps can be widened one day,
+ * this program has to be accepted.
+ *
+ * The insns that are only executed speculatively are removed as dead code, so
+ * they must not be between the jump and its target.
+ */
+SEC("socket")
+__description("unpriv: nospec does not fit in front of a jump")
+__success __failure_unpriv
+__msg_unpriv("cannot be patched due to 16-bit range")
+__caps_unpriv(CAP_BPF)
+__retval(0)
+__naked void nospec_jump_out_of_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r6 = r0; \
+ r7 = 0; \
+ if r0 < 0x100 goto l1_%=; \
+ /* executed only speculatively */ \
+ r6 = r10; \
+ goto l1_%=; \
+l0_%=: r0 = 0; \
+ exit; \
+l1_%=: .rept 32765; \
+ r1 = 0; \
+ .endr; \
+ if r7 != r6 goto l0_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Like above, but for the nospec behind a store to the stack that is between
+ * the jump and its target.
+ */
+SEC("socket")
+__description("unpriv: nospec does not fit behind a store")
+__success __failure_unpriv
+__msg_unpriv("cannot be patched due to 16-bit range")
+__caps_unpriv(CAP_BPF)
+__retval(0)
+__naked void nospec_result_jump_out_of_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r7 = 0; \
+ goto l1_%=; \
+l0_%=: r0 = 0; \
+ exit; \
+l1_%=: *(u64 *)(r10 - 8) = r7; \
+ .rept 32764; \
+ r1 = 0; \
+ .endr; \
+ if r7 != r6 goto l0_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* The store is only reached speculatively and is replaced as dead code. */
+SEC("socket")
+__description("unpriv: Spectre v4 nospec after dead stack write")
+__success __success_unpriv
+__retval(0)
+#ifdef SPEC_V4
+__xlated_unpriv("if r0 == 0x0 goto pc+2")
+__xlated_unpriv("goto pc-1")
+__xlated_unpriv("nospec")
+__xlated_unpriv("exit")
+#endif
+__naked void dead_stack_write_nospec_result(void)
+{
+ asm volatile (" \
+ w7 = 0; \
+ w7 ^= w7; \
+ w0 = w7; \
+ if r0 == 0 goto l0_%=; \
+ *(u64 *)(r10 - 8) = r0; \
+l0_%=: exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * The jump is reached with a pointer in r6 on a speculative path only. Its
+ * offset is adjusted for the nospec in front of it.
+ */
+SEC("socket")
+__description("unpriv: nospec in front of a backward jump")
+__success __success_unpriv
+__retval(0)
+#ifdef SPEC_V1
+__xlated_unpriv("nospec")
+__xlated_unpriv("if r7 != r6 goto pc-6")
+__xlated_unpriv("r0 = 0")
+__xlated_unpriv("exit")
+#endif
+__naked void nospec_backward_jump(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r6 = r0; \
+ r7 = 0; \
+ if r0 < 0x100 goto l1_%=; \
+ /* executed only speculatively */ \
+ r6 = r10; \
+ goto l1_%=; \
+l0_%=: r0 = 0; \
+ exit; \
+l1_%=: r1 = 0; \
+ r1 = 0; \
+ if r7 != r6 goto l0_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
char _license[] SEC("license") = "GPL";
--
2.56.1
^ permalink raw reply related [flat|nested] 7+ messages in thread
* Re: [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn
2026-11-25 17:12 ` [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn Luis Gerhorst
@ 2026-11-25 18:17 ` bot+bpf-ci
0 siblings, 0 replies; 7+ messages in thread
From: bot+bpf-ci @ 2026-11-25 18:17 UTC (permalink / raw)
To: luis.gerhorst, ast, bpf
Cc: luis.gerhorst, daniel, andrii, eddyz87, memxor, martin.lau, song,
yonghong.song, jolsa, emil, ihor.solodrai, john.fastabend, shuah,
henriette.herzog, linux-kselftest, ast, andrii, daniel,
martin.lau, eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 4999 bytes --]
> bpf: Add bpf_insert_insns() to insert insns next to an insn
TL;DR:
- Comments and commit message misdescribe aux data handling:
BPF_PATCH_NO_ORIG, "keeps its aux data", and zext_dst still being recomputed
- arena_member_fixup() sites may still use bpf_patch_insn_data() despite the
commit message
> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c
> @@ -170,82 +170,60 @@ enum bpf_patch_mode {
> BPF_PATCH_MOVE_TARGET, /* targets of 'off' follow the original insn to 'off + len - 1' */
> };
>
> +/* The patch does not contain the insn that it replaces. */
> +#define BPF_PATCH_NO_ORIG -1
> +
> /* single env->prog->insni[off] instruction was replaced with the range
> * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
> * [0, off) and [off, end) to new locations, so the patched range stays zero
> + *
> + * The aux data of the original insn stays with the insn if the range still
> + * contains it, at index 'orig'. Otherwise 'orig' is BPF_PATCH_NO_ORIG and the
> + * aux data moves to the last insn of the range.
> */
This isn't a bug, but the comment on BPF_PATCH_NO_ORIG says the patch does not
contain the insn that it replaces. bpf_patch_insn_data() passes
BPF_PATCH_NO_ORIG for every patch:
return __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_NO_ORIG,
BPF_PATCH_KEEP_TARGET);
Many of those patches still contain the insn, for example arena_member_fixup()
(buf[cnt++] = *insn;), add_hidden_subprog() and the insn_buf[N] = *insn
patches for tail calls, kfuncs and percpu alloc. For these, keep is the last
insn, so the original insn's aux data (ptr_type, arena_member, ...) moves to
the trailing insn and the original is left with zeroed aux data.
The commit message describes this correctly ("Where such a patch still
contains the insn, the insn now counts as new"), but the two comments read the
opposite way. Would something like "no insn of the patch inherits the aux data
of the original insn in place" be more accurate?
Also, in adjust_insn_aux_data() zext_dst is still recomputed for every slot,
including i == keep:
data[i].zext_dst = bpf_insn_def32(new_prog, insn + i) >= 0;
[ ... ]
> @@ -431,6 +408,62 @@ static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
> return 0;
> }
>
> +/* Where bpf_insert_insns() puts the new insns relative to the insn at 'off'. */
> +enum bpf_insert_pos {
> + BPF_INSERT_BEFORE, /* in front of the insn, a jump to the insn runs them too */
> + BPF_INSERT_ENTRY, /* in front of the insn, a jump to the insn skips them */
> + BPF_INSERT_AFTER, /* behind the insn */
> +};
> +
> +/*
> + * Insert 'cnt' insns next to env->prog->insnsi[off]. Unlike with
> + * bpf_patch_insn_data(), the insn is not replaced: it keeps its aux data,
> + * wherever it ends up. Returns the new prog or an ERR_PTR().
> + */
Is "it keeps its aux data" accurate for zext_dst? adjust_insn_aux_data()
overwrites zext_dst for the kept insn with bpf_insn_def32() >= 0, which drops
what bpf_compute_live_registers() computed:
zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32))
and what the verifier sets for arena ALU64 insns together with needs_zext.
A 32-bit def whose upper half is dead goes from false to true, and an ALU64
arena insn with needs_zext goes from true to false if bpf_insert_insns() runs
on it before bpf_do_misc_fixups() converts it to ALU32 (the nospec
BPF_INSERT_BEFORE in bpf_convert_ctx_accesses()).
The old code also recomputed zext_dst for that slot, so behavior doesn't
change in this commit. Could zext_dst be kept for i == keep, or the comment
and the commit message ("The insn keeps all of its aux data.") say that it is
recomputed?
[ ... ]
In bpf_convert_ctx_accesses(), arena_member_fixup() builds a patch that only
inserts behind the unchanged insn:
buf[cnt++] = *insn;
if (aux->arena_member_nullable || BPF_MODE(insn->code) == BPF_PROBE_MEM)
buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, insn->dst_reg, 0, 1);
buf[cnt++] = BPF_ALU32_IMM(BPF_SUB, insn->dst_reg, (s32)base);
Both callers still use bpf_patch_insn_data():
cnt = arena_member_fixup(env, i + delta, insn, insn_buf);
if (cnt < 0)
return cnt;
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
The commit message says bpf_insert_insns() is used "where a patch only
inserts" and bpf_patch_insn_data() "is left for the patches that replace the
insn". For these loads the aux data still moves to the trailing BPF_SUB, and
non_stack_access is now recomputed.
Should these two sites use bpf_insert_insns(env, i + delta, insn_buf + 1,
cnt - 1, BPF_INSERT_AFTER), or should the commit message be narrowed?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45667123547
^ permalink raw reply [flat|nested] 7+ messages in thread
* Re: [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result
2026-11-25 17:12 ` [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result Luis Gerhorst
@ 2026-11-25 18:17 ` bot+bpf-ci
0 siblings, 0 replies; 7+ messages in thread
From: bot+bpf-ci @ 2026-11-25 18:17 UTC (permalink / raw)
To: luis.gerhorst, ast, bpf
Cc: luis.gerhorst, daniel, andrii, eddyz87, memxor, martin.lau, song,
yonghong.song, jolsa, emil, ihor.solodrai, john.fastabend, shuah,
henriette.herzog, linux-kselftest, ast, andrii, daniel,
martin.lau, eddyz87, yonghong.song, mason, ihor.solodrai
[-- Attachment #1: Type: text/plain, Size: 2621 bytes --]
> bpf: Emit nospec after every insn with nospec_result
TL;DR: bpf_emit_nospec() runs after bpf_optimize_bpf_loop(), contrary to its
comment, so the nospec may land after an inlined bpf_loop and let it run
speculatively. This predates the patch.
> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c
[ ... ]
> +/*
> + * Emit the speculation barriers that do_check() asked for:
> + *
> [ ... ]
> + * An insn may require both. The insn keeps its aux data, so this has to run
> + * before the passes that rewrite the insn itself: what they emit for the insn
> + * stays between the two nospec.
> + */
> +int bpf_emit_nospec(struct bpf_verifier_env *env)
This comment says the pass has to run before the passes that rewrite the
insn itself, but bpf_check() does not follow that ordering.
bpf_emit_nospec() is called after bpf_optimize_bpf_loop():
if (ret == 0)
ret = bpf_optimize_bpf_loop(env);
...
if (ret == 0)
ret = bpf_emit_nospec(env);
inline_bpf_loop() replaces the bpf_loop call with a sequence of insns via
bpf_patch_insn_data(), so adjust_insn_aux_data() moves the call's aux data,
including a set nospec, to the last insn of the patch (the restore of r8
from the stack). bpf_emit_nospec() then places the barrier in front of
that restore rather than in front of the inlined loop.
Can this be reached with CAP_BPF but without CAP_PERFMON? For example, if
a speculative path reaches 'call bpf_loop' with a scalar in R3,
check_func_arg() fails, error_recoverable_with_nospec() accepts it, and
do_check() sets nospec and ends that path. The call can still be inlined
because of the architectural visit, so the inlined loop would run
speculatively with the scalar R3 passed to the callback as r2, which was
verified as PTR_TO_STACK.
The code before this patch had the same ordering, since
bpf_convert_ctx_accesses() also ran after bpf_optimize_bpf_loop(), so this
predates the patch.
The bpf_capable passes that run earlier look related: a conditional jump
that got nospec on a speculative path and whose target is dead is
hard-wired to 'ja 0' and then removed by bpf_opt_remove_nops() together
with its aux data.
Should the pass move earlier, should nospec be carried through those
rewrites, or should the comment avoid promising an ordering that
bpf_check() does not provide?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45667123547
^ permalink raw reply [flat|nested] 7+ messages in thread
end of thread, other threads:[~2026-11-25 18:17 UTC | newest]
Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
[not found] <20261125-nospec-result-reply-d60fdc6da8ef@fau.de>
2026-11-25 17:12 ` [PATCH bpf 0/4] bpf: Emit nospec after every insn that stores to the stack Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 1/4] bpf: Add bpf_insert_insns() to insert insns next to an insn Luis Gerhorst
2026-11-25 18:17 ` bot+bpf-ci
2026-11-25 17:12 ` [PATCH bpf 2/4] selftests/bpf: Test the insns that bpf_insert_insns() inserts Luis Gerhorst
2026-11-25 17:12 ` [PATCH bpf 3/4] bpf: Emit nospec after every insn with nospec_result Luis Gerhorst
2026-11-25 18:17 ` bot+bpf-ci
2026-11-25 17:12 ` [PATCH bpf 4/4] selftests/bpf: Test nospec after stack writes of calls and atomics Luis Gerhorst
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox