From: Alexei Starovoitov User space often sets the bound of a loop in .rodata before it loads the prog. The variable is volatile, thus the prog loads it in each iteration: const volatile int nr_cpus; for (i = 0; i < nr_cpus; i++) Scalar evolution calculates how many times a loop runs. Then the verifier does not have to verify the loop one iteration at a time. But scalar evolution does not examine maps. For it the result of the load is unknown, and it cannot calculate the number of iterations: loop header at 3, non-linear latch at 5 The map is read-only, thus the load always gives the same constant. bpf_compute_const_regs() runs before scalar evolution and already knows this constant. Use it. insn_aux_data of an insn describes the registers before this insn. Thus the result of the load is in insn_aux_data of the next insn. loop header at 3, header_count is 10 A loop with a large bound in .rodata reached the limit of 1M insns. Now it loads, as it does with the same bound in a register. A counted loop is verified with ranges, and there is no way back to one iteration at a time: a prog that needs the exact counter in each iteration (an offset into ctx, two counters with a constant sum) is rejected now, as it is with the same bound in the insn. 7 loops of scx_cake get a count. Each of them changes one more register that has no formula, thus the verifier still unrolls them. No prog of Cilium, scx, the selftests or the public progs of Meta changes. Signed-off-by: Alexei Starovoitov --- kernel/bpf/scev.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c index 0f46a85f7648..8521c34899b0 100644 --- a/kernel/bpf/scev.c +++ b/kernel/bpf/scev.c @@ -770,6 +770,15 @@ static int transfer(struct bpf_verifier_env *env, struct env *e, int idx) switch (mode) { case BPF_MEM: case BPF_MEMSX: + /* + * for (i = 0; i < nr_cpus; i++) with "const volatile int nr_cpus": + * bpf_compute_const_regs() knows what is loaded from a read-only map. + */ + if (insn->src_reg != BPF_REG_FP && idx + 1 < env->prog->len && + (env->insn_aux_data[idx + 1].const_reg_mask & BIT(dst))) { + imm = env->insn_aux_data[idx + 1].const_reg_vals[dst]; + return replace_reg(scev, e, dst, imm_expr(scev, imm)); + } return maybe_load_fp(scev, e, insn); default: goto mark_dst_unknown; -- 2.55.0