| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/09/28 01:35 | flow | patch-triage |
5mArgs:null Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_compute_loops",
"bpf_compute_idoms",
"bpf_compute_loop_iters",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_split_cur_state",
"bpf_set_reg_range",
"bpf_reg_union",
"cnum64_intersect_linear",
"btf_struct_access"
],
"KMSANReasoning": "The patch series introduces loop analysis and Scalar Evolution (SCEV) to the eBPF verifier. It adds CFG algorithms (immediate dominator calculation, loop and latch detection), a binary min-heap for worklist processing, symbolic SCEV expression tracking, loop iteration estimation, register range widening/clamping, and support for variable-offset BTF struct array accesses.\n\nKMSAN vs KASAN applicability:\n- Uninitialized memory / Info-leaks (KMSAN): No kernel memory or structs are copied to user space (the verifier produces formatted log text and returns integer return codes). All newly introduced data structures (e.g., struct bpf_loop, struct bpf_loop_exit, struct scev, struct env, idoms, postorder arrays, heap buffers) are allocated using kzalloc, kvcalloc, kvzalloc, or with __GFP_ZERO. Local stack variables (such as struct bpf_loop_iters, struct linear_latch, struct bounds, struct array_access) are either explicitly zeroed or fully populated before their fields are read. No uninitialized memory is read or exposed.\n- Memory safety and logic correctness (KASAN): The risks in this patch are typical of compiler/verifier analysis passes: out-of-bounds indexing in instruction/graph arrays, heap buffer bounds in the worklist binary heap, memory leaks, and verifier soundness bugs (such as incorrect bounds widening that could permit out-of-bounds accesses during BPF execution). These failure modes are detected by KASAN, UBSAN, and standard kernel debugging facilities, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false,
"Reasoning": "The patch series implements Scalar Evolution (SCEV) and loop induction variable analysis in the eBPF verifier. It adds CFG dominator tree computation (idoms), natural loop and backedge/exit detection, symbolic expression tracking, loop bound calculation, register widening, and clamping to verify bounded loops. It also introduces linear step/base tracking for scalar registers and variable-offset access validation for BTF struct arrays. These changes modify core verifier logic reachable from userspace via the bpf(BPF_PROG_LOAD, ...) syscall, making fuzzing essential to uncover soundness bugs, safety regressions, and unexpected verifier crashes.",
"WorthFuzzing": true
} |
| 1/1 | 2026/09/28 01:35 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit d7942ef1185d903ecca00472af297f633f20d95d\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Mon Sep 28 01:35:30 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h\nindex c775bd7577063..a5fa2b5cc0c0d 100644\n--- a/include/linux/bpf_verifier.h\n+++ b/include/linux/bpf_verifier.h\n@@ -9,6 +9,20 @@\n #include \u003clinux/filter.h\u003e /* for MAX_BPF_STACK */\n #include \u003clinux/tnum.h\u003e\n #include \u003clinux/cnum.h\u003e\n+#include \u003clinux/math64.h\u003e /* for div_s64_rem() */\n+\n+/*\n+ * Mathematical modulo, the residue of 'v' modulo 'step', normalized to [0, step).\n+ * This differs from C's '%' operator, which truncates the quotient toward zero\n+ * and so returns a remainder with the sign of the dividend (e.g. -1 % 3 == -1, not 2).\n+ */\n+static inline u16 imod(s64 v, u16 step)\n+{\n+\ts32 rem;\n+\n+\tdiv_s64_rem(v, step, \u0026rem);\n+\treturn rem \u003c 0 ? rem + step : rem;\n+}\n \n /* Maximum variable offset umax_value permitted when resolving memory accesses.\n * In practice this is far bigger than any realistic pointer offset; this limit\n@@ -164,6 +178,13 @@ struct bpf_reg_state {\n \t * during state comparisons.\n \t */\n \tu32 map_uid;\n+\t/*\n+\t * The value described by this register is some point lying on\n+\t * a line described by a linear equation base + step * k.\n+\t * Invariant: base \u003c step.\n+\t */\n+\tu16 base;\n+\tu16 step;\n \t/* if (!precise \u0026\u0026 SCALAR_VALUE) min/max/tnum don't affect safety */\n \tbool precise;\n };\n@@ -307,6 +328,21 @@ struct bpf_retval_range {\n \tbool return_32bit;\n };\n \n+struct bpf_loop_iters {\n+\tu32 min_header_count; /* min number of times header is executed */\n+\tu32 max_header_count; /* max number of times header is executed */\n+\tbool pre_cond;\n+};\n+\n+struct loop_stack_entry {\n+\tstruct bpf_verifier_state *entry_state;\n+\tstruct bpf_loop_iters iters;\n+\tu32 loop_id:31;\n+\tu32 terminates:1;\n+};\n+\n+#define LOOP_STACK_SIZE 16\n+\n /* state of the program:\n * type of all registers and stack info\n */\n@@ -352,6 +388,12 @@ struct bpf_func_state {\n \tu32 callback_depth;\n \t/* Instructions processed in this frame and callees on the current path. */\n \tu32 insns_subtotal;\n+\t/*\n+\t * Control-flow loop nesting at the current insn within this frame's\n+\t * subprogram (loops never cross subprogram boundaries).\n+\t */\n+\tu32 loop_stack_cnt;\n+\tstruct loop_stack_entry loop_stack[LOOP_STACK_SIZE];\n \n \t/* The following fields should be last. See copy_func_state() */\n \t/* The state of the stack. Each element of the array describes BPF_REG_SIZE\n@@ -415,6 +457,7 @@ static_assert(MAX_BPF_STACK_SLOTS \u003c= (1 \u003c\u003c 12));\n #define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS)\n #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \\\n \t\t\t MAX_CALL_FRAMES)\n+\n struct bpf_verifier_state {\n \t/* call stack tracking */\n \tstruct bpf_func_state *frame[MAX_CALL_FRAMES];\n@@ -481,7 +524,9 @@ struct bpf_verifier_state {\n \tbool speculative;\n \tbool in_sleepable;\n \n-\t/* first and last insn idx of this verifier state */\n+\t/* First and last insn idx of this verifier state.\n+\t * last_insn_idx is -1 if no instructions have been executed yet.\n+\t */\n \tu32 first_insn_idx;\n \tu32 last_insn_idx;\n \t/* if this state is a backedge state then equal_state\n@@ -629,6 +674,44 @@ struct bpf_iarray {\n \tu32 items[];\n };\n \n+#define iarray_for_each(item, arr)\t\t\t\t\t\t\\\n+\tfor (int ___idx = 0;\t\t\t\t\t\t\t\\\n+\t ___idx \u003c (arr)-\u003ecnt \u0026\u0026 ({ item = (arr)-\u003eitems[___idx]; 1; });\t\\\n+\t ___idx++)\n+\n+#define MAX_BACKEDGES 16\n+#define MAX_LOOP_EXITS 256\n+\n+struct bpf_backedge {\n+\tint from;\n+\tint latch; /* -1 if no latch can be found */\n+};\n+\n+struct bpf_loop_exit {\n+\tint from; /* instruction inside the loop */\n+\tint to; /* instruction outside the loop */\n+};\n+\n+/* SCEV/widening register space: r0..r10 plus every stack slot of a frame. */\n+#define BPF_SCEV_REGS_NUM (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)\n+\n+struct bpf_loop {\n+\tstruct bpf_backedge backedges[MAX_BACKEDGES];\n+\t/* edges exiting from this loop, includes edges from nested loops */\n+\tstruct bpf_loop_exit *exits;\n+\tint backedges_cnt;\n+\tint exits_cnt;\n+\tbool irreducible;\n+\tbool backedges_overflow;\n+\tbool exits_overflow;\n+\t/*\n+\t * Loop-entry registers used to compute stack addresses for loads,\n+\t * stores and calls requiring fixed stack offsets, in this and nested\n+\t * loops.\n+\t */\n+\tunsigned long store_base_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];\n+};\n+\n struct bpf_insn_aux_data {\n \tunion {\n \t\tenum bpf_reg_type ptr_type;\t/* pointer type for load/store insns */\n@@ -662,6 +745,13 @@ struct bpf_insn_aux_data {\n \t};\n \tstruct btf_struct_meta *kptr_struct_meta;\n \tu64 map_key_state; /* constant (32 bit) key tracking for maps */\n+\t/*\n+\t * Per-instruction summary of stack slots in the current frame\n+\t * that this instruction may write to.\n+\t */\n+\tDECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);\n+\tDECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);\n+\tu16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */\n \tint ctx_field_size; /* the ctx field size for load insn, maybe 0 */\n \tu32 seen; /* this insn was processed by the verifier at env-\u003epass_cnt */\n \tbool nospec; /* do not execute this instruction speculatively */\n@@ -672,6 +762,8 @@ struct bpf_insn_aux_data {\n \tbool non_sleepable; /* helper/kfunc may be called from non-sleepable context */\n \tbool is_iter_next; /* bpf_iter_\u003ctype\u003e_next() kfunc call */\n \tbool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */\n+\tbool bb_end;\n+\tbool need_scev;\n \tu8 alu_state; /* used in combination with alu_limit */\n \t/* true if STX or LDX instruction is a part of a spill/fill\n \t * pattern for a bpf_fastcall call.\n@@ -699,6 +791,13 @@ struct bpf_insn_aux_data {\n \tu32 non_stack_access:1; /* instruction can access non-stack memory */\n \t/* true if some jump or call instruction targets this instruction */\n \tu32 jump_target:1;\n+\t/*\n+\t * True if this instruction is a loop entry. For loops with a single entry\n+\t * this bit will coincide with 'loop' pointer being non-NULL.\n+\t * Irreducible loops have multiple entries, all of them will be marked as 'loop_entry',\n+\t * but only the one at 'loop_header' will have a non-NULL 'loop' pointer.\n+\t */\n+\tu32 loop_entry:1;\n \t/*\n \t * CFG strongly connected component this instruction belongs to,\n \t * zero if it is a singleton SCC.\n@@ -718,6 +817,10 @@ struct bpf_insn_aux_data {\n \tu16 const_reg_map_mask;\n \tu16 const_reg_subprog_mask;\n \tu32 const_reg_vals[10];\n+\t/* index of a loop header of the innermost loop containing this instruction, -1 if none */\n+\ts32 loop_header;\n+\t/* additional information about the loop if this instruction is a loop header */\n+\tstruct bpf_loop *loop;\n };\n \n #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */\n@@ -920,6 +1023,7 @@ struct bpf_scc_info {\n };\n \n struct bpf_liveness;\n+struct scev;\n \n struct bpf_fd_array {\n \tunion {\n@@ -1005,6 +1109,7 @@ struct bpf_verifier_env {\n \t\t * see bpf_subprog_info-\u003epostorder_start.\n \t\t */\n \t\tint *insn_postorder;\n+\t\tint *postorder_nums;\n \t\tint cur_stack;\n \t\t/* current position in the insn_postorder vector */\n \t\tint cur_postorder;\n@@ -1080,6 +1185,10 @@ struct bpf_verifier_env {\n \tu32 scc_cnt;\n \tstruct bpf_iarray *succ;\n \tstruct bpf_iarray *gotox_tmp_buf;\n+\tint *idoms;\n+\tstruct scev *scev;\n+\t/* SCEV representation of stack slots not allocated yet. */\n+\tstruct bpf_reg_state scev_not_init_reg;\n };\n \n static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)\n@@ -1258,6 +1367,7 @@ void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);\n int mark_chain_precision(struct bpf_verifier_env *env, int regno);\n \n int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx);\n+int bpf_split_cur_state(struct bpf_verifier_env *env);\n int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st);\n \n void bpf_clear_jmp_history(struct bpf_verifier_state *state);\n@@ -1272,6 +1382,7 @@ int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state\n void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist);\n void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,\n \t\t\t struct bpf_reg_state *reg);\n+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);\n void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg);\n void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,\n \t\t\t\t struct bpf_verifier_state *st);\n@@ -1724,10 +1835,16 @@ s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env,\n \t\t\t\t struct bpf_insn *insn, int arg,\n \t\t\t\t int insn_idx);\n int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);\n+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n+\t\t struct cnum64 range, u16 step);\n+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,\n+\t\t const struct bpf_reg_state *src);\n \n int bpf_stack_liveness_init(struct bpf_verifier_env *env);\n void bpf_stack_liveness_free(struct bpf_verifier_env *env);\n int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);\n+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);\n+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);\n bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);\n int bpf_compute_live_registers(struct bpf_verifier_env *env);\n \n@@ -1819,6 +1936,7 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt\n \t\t\t\t struct bpf_attach_target_info *tgt_info);\n \n /* Functions in fixups.c, called from bpf_check() */\n+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len);\n int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env);\n int bpf_optimize_bpf_loop(struct bpf_verifier_env *env);\n void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);\n@@ -1831,4 +1949,40 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env);\n int bpf_do_misc_fixups(struct bpf_verifier_env *env);\n int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);\n \n+int bpf_flip_opcode(u32 opcode);\n+u8 bpf_rev_opcode(u8 opcode);\n+\n+int bpf_compute_idoms(struct bpf_verifier_env *env);\n+int bpf_compute_loops(struct bpf_verifier_env *env);\n+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);\n+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);\n+\n+/*\n+ * Simple binary heap implementation as described by\n+ * https://en.wikipedia.org/wiki/Binary_heap\n+ */\n+struct bpf_min_heap {\n+\tint (*compare)(int, int, void *); /* ordering function for @elements */\n+\tint *elements; /* min-heap ordered by @compare */\n+\tvoid *arg; /* 3rd argument passed to @compare */\n+\tint capacity;\n+\tint count;\n+};\n+\n+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg);\n+void bpf_min_heap_free(struct bpf_min_heap *heap);\n+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt);\n+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt);\n+\n+int bpf_init_scev(struct bpf_verifier_env *env);\n+void bpf_free_scev(struct bpf_verifier_env *env);\n+int bpf_compute_scev(struct bpf_verifier_env *env);\n+\n+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\n+\t\t\t struct bpf_loop_iters *iters);\n+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\n+\t\t\tstruct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters);\n+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 insn_idx,\n+\t\t\tstruct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters);\n+\n #endif /* _LINUX_BPF_VERIFIER_H */\ndiff --git a/include/linux/cnum.h b/include/linux/cnum.h\nindex 49b7d0c7645de..49160318adf90 100644\n--- a/include/linux/cnum.h\n+++ b/include/linux/cnum.h\n@@ -39,6 +39,7 @@ u32 cnum32_umin(struct cnum32 cnum);\n u32 cnum32_umax(struct cnum32 cnum);\n s32 cnum32_smin(struct cnum32 cnum);\n s32 cnum32_smax(struct cnum32 cnum);\n+struct cnum32 cnum32_union(struct cnum32 a, struct cnum32 b);\n struct cnum32 cnum32_intersect(struct cnum32 a, struct cnum32 b);\n void cnum32_intersect_with(struct cnum32 *dst, struct cnum32 src);\n void cnum32_intersect_with_urange(struct cnum32 *dst, u32 min, u32 max);\n@@ -65,6 +66,7 @@ u64 cnum64_umin(struct cnum64 cnum);\n u64 cnum64_umax(struct cnum64 cnum);\n s64 cnum64_smin(struct cnum64 cnum);\n s64 cnum64_smax(struct cnum64 cnum);\n+struct cnum64 cnum64_union(struct cnum64 a, struct cnum64 b);\n struct cnum64 cnum64_intersect(struct cnum64 a, struct cnum64 b);\n void cnum64_intersect_with(struct cnum64 *dst, struct cnum64 src);\n void cnum64_intersect_with_urange(struct cnum64 *dst, u64 min, u64 max);\n@@ -78,5 +80,6 @@ bool cnum64_is_subset(struct cnum64 outer, struct cnum64 inner);\n \n struct cnum32 cnum32_from_cnum64(struct cnum64 cnum);\n struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b);\n+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step);\n \n #endif /* _LINUX_CNUM_H */\ndiff --git a/include/linux/tnum.h b/include/linux/tnum.h\nindex ca2cfec8de08a..16682248f963a 100644\n--- a/include/linux/tnum.h\n+++ b/include/linux/tnum.h\n@@ -134,4 +134,6 @@ static inline bool tnum_subreg_is_const(struct tnum a)\n /* Returns the smallest member of t larger than z */\n u64 tnum_step(struct tnum t, u64 z);\n \n+u32 tnum_alignment(struct tnum a);\n+\n #endif /* _LINUX_TNUM_H */\ndiff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile\nindex c1f9b0d3468d3..fdff31d962d6c 100644\n--- a/kernel/bpf/Makefile\n+++ b/kernel/bpf/Makefile\n@@ -6,7 +6,7 @@ cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse\n endif\n CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)\n \n-obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o\n+obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o loops.o heap.o scev.o\n obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o\n obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o\n obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o\ndiff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c\nindex 0e38b9575328c..43d5740034c0f 100644\n--- a/kernel/bpf/backtrack.c\n+++ b/kernel/bpf/backtrack.c\n@@ -888,6 +888,10 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,\n \t\t}\n \n \t\tif (last_idx \u003c 0) {\n+\t\t\t/* Consecutive checkpoints can have no instructions between them. */\n+\t\t\tif (st-\u003eparent)\n+\t\t\t\tgoto parent;\n+\n \t\t\t/* we are at the entry into subprog, which\n \t\t\t * is expected for global funcs, but only if\n \t\t\t * requested precise registers are R1-R5\n@@ -952,6 +956,7 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,\n \t\t\t\treturn -EFAULT;\n \t\t\t}\n \t\t}\n+parent:\n \t\tst = st-\u003eparent;\n \t\tif (!st)\n \t\t\tbreak;\ndiff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c\nindex 9bcfefdfb7346..37437b93471d2 100644\n--- a/kernel/bpf/btf.c\n+++ b/kernel/bpf/btf.c\n@@ -7496,6 +7496,14 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,\n }\n EXPORT_SYMBOL_GPL(btf_ctx_access);\n \n+#define MAX_ARRAYS_WALK 16\n+\n+/* Description of an array crossed while walking a BTF access chain */\n+struct array_access {\n+\tu32 id;\t\t/* BTF_KIND_ARRAY type id */\n+\tu32 off;\t/* offset of the access within the array */\n+};\n+\n enum bpf_struct_walk_result {\n \t/* \u003c 0 error */\n \tWALK_SCALAR = 0,\n@@ -7504,10 +7512,43 @@ enum bpf_struct_walk_result {\n \tWALK_STRUCT,\n };\n \n+static const struct btf_member *find_flex_member(const struct btf *btf, const struct btf_type *t)\n+{\n+\tconst struct btf_array *array;\n+\tconst struct btf_type *mtype;\n+\tconst struct btf_member *member;\n+\tu32 vlen = btf_type_vlen(t);\n+\n+\tif (vlen == 0)\n+\t\treturn NULL;\n+\n+\tmember = btf_type_member(t) + vlen - 1;\n+\tmtype = btf_type_skip_modifiers(btf, member-\u003etype, NULL);\n+\tif (!btf_type_is_array(mtype))\n+\t\treturn NULL;\n+\n+\tarray = (const struct btf_array *)(mtype + 1);\n+\tif (array-\u003enelems != 0)\n+\t\treturn NULL;\n+\n+\treturn member;\n+}\n+\n+static int push_array(struct array_access *arrays, u32 *arrays_cnt, struct array_access item)\n+{\n+\tif (arrays == NULL)\n+\t\treturn 0;\n+\tif (*arrays_cnt == MAX_ARRAYS_WALK)\n+\t\treturn -1;\n+\tarrays[(*arrays_cnt)++] = item;\n+\treturn 0;\n+}\n+\n static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,\n \t\t\t const struct btf_type *t, int off, int size,\n \t\t\t u32 *next_btf_id, enum bpf_type_flag *flag,\n-\t\t\t const char **field_name, bool walk_flex_arrays)\n+\t\t\t const char **field_name, bool walk_flex_arrays,\n+\t\t\t struct array_access *arrays, u32 *arrays_cnt)\n {\n \tu32 i, moff, mtrue_end, msize = 0, total_nelems = 0;\n \tconst struct btf_type *mtype, *elem_type = NULL;\n@@ -7542,22 +7583,19 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,\n \t\t/* If the last element is a variable size array, we may\n \t\t * need to relax the rule.\n \t\t */\n-\t\tif (vlen == 0)\n+\t\tmember = find_flex_member(btf, t);\n+\t\tif (!member)\n \t\t\tgoto error;\n \n-\t\tmember = btf_type_member(t) + vlen - 1;\n-\t\tmtype = btf_type_skip_modifiers(btf, member-\u003etype,\n-\t\t\t\t\t\tNULL);\n-\t\tif (!btf_type_is_array(mtype))\n+\t\tmoff = __btf_member_bit_offset(t, member) / 8;\n+\t\tif (off \u003c moff)\n \t\t\tgoto error;\n \n+\t\tmtype = btf_type_skip_modifiers(btf, member-\u003etype, \u0026mid);\n \t\tarray_elem = (struct btf_array *)(mtype + 1);\n-\t\tif (array_elem-\u003enelems != 0)\n-\t\t\tgoto error;\n \n-\t\tmoff = __btf_member_bit_offset(t, member) / 8;\n-\t\tif (off \u003c moff)\n-\t\t\tgoto error;\n+\t\tif (push_array(arrays, arrays_cnt, (struct array_access){ mid, off - moff }))\n+\t\t\treturn -E2BIG;\n \n \t\t/* allow structure and integer */\n \t\tt = btf_type_skip_modifiers(btf, array_elem-\u003etype,\n@@ -7680,6 +7718,9 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,\n \t\t\t * the array's element as long as it is\n \t\t\t * within the mtrue_end boundary.\n \t\t\t */\n+\t\t\tif (push_array(arrays, arrays_cnt,\n+\t\t\t\t (struct array_access){ mid, off - moff }))\n+\t\t\t\treturn -E2BIG;\n \n \t\t\t/* skip empty array */\n \t\t\tif (moff == mtrue_end)\n@@ -7772,15 +7813,29 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,\n \n int btf_struct_access(struct bpf_verifier_log *log,\n \t\t const struct bpf_reg_state *reg,\n-\t\t int off, int size, enum bpf_access_type atype __maybe_unused,\n+\t\t int _off, int size, enum bpf_access_type atype __maybe_unused,\n \t\t u32 *next_btf_id, enum bpf_type_flag *flag,\n \t\t const char **field_name)\n {\n \tconst struct btf *btf = reg-\u003ebtf;\n \tenum bpf_type_flag tmp_flag = 0;\n+\tstruct array_access arrays[MAX_ARRAYS_WALK];\n+\tconst struct btf_member *member;\n \tconst struct btf_type *t;\n+\tu32 i, arrays_cnt = 0;\n \tu32 id = reg-\u003ebtf_id;\n-\tint err;\n+\ts64 min_off, max_off, flex_off;\n+\tint err, off, ret;\n+\n+\tif (check_add_overflow(reg_smin(reg), (s64)_off, \u0026min_off) ||\n+\t check_add_overflow(reg_smax(reg), (s64)_off, \u0026max_off) ||\n+\t min_off != (int)min_off) {\n+\t\tbpf_log(log,\n+\t\t\t\"offset computation overflows: register offset range is [%lld, %lld], instruction offset is %d\\n\",\n+\t\t\treg_smin(reg), reg_smax(reg), _off);\n+\t\treturn -EINVAL;\n+\t}\n+\toff = min_off;\n \n \twhile (type_is_alloc(reg-\u003etype)) {\n \t\tstruct btf_struct_meta *meta;\n@@ -7807,26 +7862,30 @@ int btf_struct_access(struct bpf_verifier_log *log,\n \tt = btf_type_by_id(btf, id);\n \tdo {\n \t\terr = btf_struct_walk(log, btf, t, off, size, \u0026id, \u0026tmp_flag,\n-\t\t\t\t field_name, !type_is_alloc(reg-\u003etype));\n-\n+\t\t\t\t field_name, !type_is_alloc(reg-\u003etype), arrays, \u0026arrays_cnt);\n \t\tswitch (err) {\n \t\tcase WALK_PTR:\n \t\t\t/* For local types, the destination register cannot\n \t\t\t * become a pointer again.\n \t\t\t */\n-\t\t\tif (type_is_alloc(reg-\u003etype))\n-\t\t\t\treturn SCALAR_VALUE;\n+\t\t\tif (type_is_alloc(reg-\u003etype)) {\n+\t\t\t\tret = SCALAR_VALUE;\n+\t\t\t\tgoto check_variable_offset;\n+\t\t\t}\n \t\t\t/* If we found the pointer or scalar on t+off,\n \t\t\t * we're done.\n \t\t\t */\n \t\t\t*next_btf_id = id;\n \t\t\t*flag = tmp_flag;\n-\t\t\treturn PTR_TO_BTF_ID;\n+\t\t\tret = PTR_TO_BTF_ID;\n+\t\t\tgoto check_variable_offset;\n \t\tcase WALK_PTR_UNTRUSTED:\n \t\t\t*flag = MEM_RDONLY | PTR_UNTRUSTED;\n-\t\t\treturn PTR_TO_MEM;\n+\t\t\tret = PTR_TO_MEM;\n+\t\t\tgoto check_variable_offset;\n \t\tcase WALK_SCALAR:\n-\t\t\treturn SCALAR_VALUE;\n+\t\t\tret = SCALAR_VALUE;\n+\t\t\tgoto check_variable_offset;\n \t\tcase WALK_STRUCT:\n \t\t\t/* We found nested struct, so continue the search\n \t\t\t * by diving in it. At this point the offset is\n@@ -7846,6 +7905,54 @@ int btf_struct_access(struct bpf_verifier_log *log,\n \t} while (t);\n \n \treturn -EINVAL;\n+\n+check_variable_offset:\n+\tif (min_off == max_off)\n+\t\treturn ret;\n+\n+\t/* Find an offset at which access would go to a flexible array tail (if any). */\n+\tt = btf_type_skip_modifiers(btf, reg-\u003ebtf_id, NULL);\n+\tmember = find_flex_member(btf, t);\n+\tflex_off = member ? __btf_member_bit_offset(t, member) / 8 : S64_MAX;\n+\n+\t/*\n+\t * If this is a varying offset access, the step recorded within a register\n+\t * should correspond to one of the arrays visited while walking.\n+\t */\n+\tfor (i = 0; i \u003c arrays_cnt; i++) {\n+\t\ts64 array_start, array_end, access_end;\n+\t\tu32 asize, esize, elem_id;\n+\n+\t\t/*\n+\t\t * 'arrays' records top-level arrays only, use __btf_resolve_size()\n+\t\t * to get flattened representation.\n+\t\t */\n+\t\tt = btf_type_by_id(btf, arrays[i].id);\n+\t\tif (IS_ERR(__btf_resolve_size(btf, t, \u0026asize, NULL, \u0026elem_id, NULL, NULL)) ||\n+\t\t IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, elem_id), \u0026esize)))\n+\t\t\tcontinue;\n+\t\t/* Make sure every accessed offset lands on the same field of some element. */\n+\t\tif (esize == 0 || reg-\u003estep % esize != 0)\n+\t\t\tcontinue;\n+\n+\t\tarray_start = min_off - arrays[i].off;\n+\t\t/* An array within the flexible tail has no upper bound to exceed */\n+\t\tif (array_start \u003e= flex_off)\n+\t\t\treturn ret;\n+\n+\t\t/* the 'size' bytes read at max_off must stay within the array */\n+\t\tif (check_add_overflow(array_start, (s64)asize, \u0026array_end) ||\n+\t\t check_add_overflow(max_off, (s64)size, \u0026access_end) ||\n+\t\t access_end \u003e array_end)\n+\t\t\tcontinue;\n+\t\treturn ret;\n+\t}\n+\n+\tbpf_log(log,\n+\t\t\"invalid variable offset access into struct %s: offsets [%lld, %lld] size %d step %d do not match any array\\n\",\n+\t\tbtf_name_by_offset(btf, btf_type_by_id(btf, reg-\u003ebtf_id)-\u003ename_off),\n+\t\tmin_off, max_off, size, reg-\u003estep);\n+\treturn -EINVAL;\n }\n \n /* Check that two BTF types, each specified as an BTF object + id, are exactly\n@@ -7886,7 +7993,7 @@ bool btf_struct_ids_match(struct bpf_verifier_log *log,\n \tif (!type)\n \t\treturn false;\n \terr = btf_struct_walk(log, btf, type, off, 1, \u0026id, \u0026flag, NULL,\n-\t\t\t walk_flex_arrays);\n+\t\t\t walk_flex_arrays, NULL, NULL);\n \tif (err != WALK_STRUCT)\n \t\treturn false;\n \ndiff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c\nindex b0bd9ba951dfb..bd771efec66a3 100644\n--- a/kernel/bpf/cfg.c\n+++ b/kernel/bpf/cfg.c\n@@ -767,6 +767,11 @@ int bpf_check_cfg(struct bpf_verifier_env *env)\n \treturn ret;\n }\n \n+struct dfs_state {\n+\tu32 traversed:1;\n+\tu32 next_succ:31;\n+};\n+\n /*\n * For each subprogram 'i' fill array env-\u003ecfg.insn_subprogram sub-range\n * [env-\u003esubprog_info[i].postorder_start, env-\u003esubprog_info[i+1].postorder_start)\n@@ -774,43 +779,52 @@ int bpf_check_cfg(struct bpf_verifier_env *env)\n */\n int bpf_compute_postorder(struct bpf_verifier_env *env)\n {\n-\tu32 cur_postorder, i, top, stack_sz, s;\n-\tint *stack = NULL, *postorder = NULL, *state = NULL;\n-\tstruct bpf_iarray *succ;\n+\tint *stack = NULL, *postorder = NULL, *postorder_nums = NULL;\n+\tint subprog_idx, stack_sz, cur, s, cur_postorder, start;\n+\tstruct dfs_state *state = NULL;\n+\tstruct bpf_iarray *succ = NULL;\n \n+\tpostorder_nums = kvzalloc_objs(int, env-\u003eprog-\u003elen, GFP_KERNEL_ACCOUNT);\n \tpostorder = kvzalloc_objs(int, env-\u003eprog-\u003elen, GFP_KERNEL_ACCOUNT);\n-\tstate = kvzalloc_objs(int, env-\u003eprog-\u003elen, GFP_KERNEL_ACCOUNT);\n \tstack = kvzalloc_objs(int, env-\u003eprog-\u003elen, GFP_KERNEL_ACCOUNT);\n-\tif (!postorder || !state || !stack) {\n+\tstate = kvzalloc_objs(struct dfs_state, env-\u003eprog-\u003elen, GFP_KERNEL_ACCOUNT);\n+\tif (!postorder_nums || !postorder || !stack || !state) {\n+\t\tkvfree(postorder_nums);\n \t\tkvfree(postorder);\n-\t\tkvfree(state);\n \t\tkvfree(stack);\n+\t\tkvfree(state);\n \t\treturn -ENOMEM;\n \t}\n \tcur_postorder = 0;\n-\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n-\t\tenv-\u003esubprog_info[i].postorder_start = cur_postorder;\n-\t\tstack[0] = env-\u003esubprog_info[i].start;\n+\tfor (subprog_idx = 0; subprog_idx \u003c env-\u003esubprog_cnt; subprog_idx++) {\n+\t\tstart = env-\u003esubprog_info[subprog_idx].start;\n+\t\tenv-\u003esubprog_info[subprog_idx].postorder_start = cur_postorder;\n+\t\tstack[0] = start;\n \t\tstack_sz = 1;\n+\t\tstate[start].traversed = true;\n \t\tdo {\n-\t\t\ttop = stack[stack_sz - 1];\n-\t\t\tstate[top] |= DISCOVERED;\n-\t\t\tif (state[top] \u0026 EXPLORED) {\n-\t\t\t\tpostorder[cur_postorder++] = top;\n+\t\t\tcur = stack[stack_sz - 1];\n+\t\t\tsucc = bpf_insn_successors(env, cur);\n+\t\t\tif (state[cur].next_succ == succ-\u003ecnt) {\n+\t\t\t\tpostorder_nums[cur] = cur_postorder;\n+\t\t\t\tpostorder[cur_postorder] = cur;\n+\t\t\t\tcur_postorder++;\n \t\t\t\tstack_sz--;\n \t\t\t\tcontinue;\n \t\t\t}\n-\t\t\tsucc = bpf_insn_successors(env, top);\n-\t\t\tfor (s = 0; s \u003c succ-\u003ecnt; ++s) {\n-\t\t\t\tif (!state[succ-\u003eitems[s]]) {\n-\t\t\t\t\tstack[stack_sz++] = succ-\u003eitems[s];\n-\t\t\t\t\tstate[succ-\u003eitems[s]] |= DISCOVERED;\n-\t\t\t\t}\n+\t\t\ts = succ-\u003eitems[state[cur].next_succ];\n+\t\t\tif (!state[s].traversed) {\n+\t\t\t\tstate[s].traversed = true;\n+\t\t\t\tstate[s].next_succ = 0;\n+\t\t\t\tstack[stack_sz] = s;\n+\t\t\t\tstack_sz++;\n+\t\t\t\tcontinue;\n \t\t\t}\n-\t\t\tstate[top] |= EXPLORED;\n+\t\t\tstate[cur].next_succ++;\n \t\t} while (stack_sz);\n \t}\n-\tenv-\u003esubprog_info[i].postorder_start = cur_postorder;\n+\tenv-\u003esubprog_info[subprog_idx].postorder_start = cur_postorder;\n+\tenv-\u003ecfg.postorder_nums = postorder_nums;\n \tenv-\u003ecfg.insn_postorder = postorder;\n \tenv-\u003ecfg.cur_postorder = cur_postorder;\n \tkvfree(stack);\ndiff --git a/kernel/bpf/cnum.c b/kernel/bpf/cnum.c\nindex 86142cb2aee5f..2bff2c7e0cdf5 100644\n--- a/kernel/bpf/cnum.c\n+++ b/kernel/bpf/cnum.c\n@@ -2,6 +2,7 @@\n /* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n \n #include \u003clinux/bits.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e /* for imod() */\n \n #define T 32\n #include \"cnum_defs.h\"\n@@ -118,3 +119,38 @@ struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b)\n \t}\n \treturn t;\n }\n+\n+/* Intersect 'in' with the set of integers defined by equation 'base + step * k'. */\n+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step)\n+{\n+\ts64 smin = cnum64_smin(in);\n+\ts64 smax = cnum64_smax(in);\n+\ts64 lo, hi;\n+\tu16 d;\n+\n+\tif (step \u003c= 1 || cnum64_is_empty(in))\n+\t\treturn in;\n+\t/*\n+\t * Round smin up to the next value congruent to 'base' modulo 'step',\n+\t * i.e. increase smin by d = (base - smin) mod step:\n+\t *\n+\t * |\u003c---- d ----\u003e|\n+\t * |-----------|=============|...\n+\t * base+step*k smin base+step*(k+1)\n+\t */\n+\td = imod(base - imod(smin, step), step);\n+\tif ((u64)smax - (u64)smin \u003c d)\n+\t\treturn CNUM64_EMPTY;\n+\tlo = smin + d;\n+\t/*\n+\t * Round smax down to the previous value congruent to 'base' modulo 'step',\n+\t * i.e. decrease smax by d = (smax - base) mod step:\n+\t *\n+\t * |\u003c--- d ---\u003e|\n+\t * ...|===========|-------------|\n+\t * base+step*k smax base+step*(k+1)\n+\t */\n+\td = imod(imod(smax, step) - base, step);\n+\thi = smax - d;\n+\treturn cnum64_from_srange(lo, hi);\n+}\ndiff --git a/kernel/bpf/cnum_defs.h b/kernel/bpf/cnum_defs.h\nindex 30685e43de049..05b17a8b4814f 100644\n--- a/kernel/bpf/cnum_defs.h\n+++ b/kernel/bpf/cnum_defs.h\n@@ -198,6 +198,50 @@ static inline struct cnum_t FN(normalize)(struct cnum_t cnum)\n \treturn cnum;\n }\n \n+/*\n+ * Return a smallest arc containing both 'a' and 'b'.\n+ * Break equal-size ties by choosing the smaller base.\n+ */\n+struct cnum_t FN(union)(struct cnum_t a, struct cnum_t b)\n+{\n+\tstruct cnum_t b1, ab, ba;\n+\tut end;\n+\n+\tif (FN(is_empty)(a))\n+\t\treturn b;\n+\tif (FN(is_empty)(b))\n+\t\treturn a;\n+\n+\t/*\n+\t * Rotate so that a1.base == 0 and a1.end == a.size.\n+\t * Normalize b1 to preserve the full-circle representation.\n+\t */\n+\tb1 = FN(normalize)((struct cnum_t){ b.base - a.base, b.size });\n+\tend = max(a.size, (ut)(b1.base + b1.size));\n+\n+\tif (FN(urange_overflow)(b1)) {\n+\t\t/* a1 reaches b1's main arc: together they cover the circle. */\n+\t\tif (b1.base \u003c= a.size)\n+\t\t\treturn (struct cnum_t){ 0, UT_MAX };\n+\n+\t\t/* Extend b1's tail through a1's end, then rotate back. */\n+\t\treturn FN(normalize)((struct cnum_t){ b.base, end - b1.base });\n+\t}\n+\n+\t/* ab, rotated back, covers both nonwrapping arcs. */\n+\tab = (struct cnum_t){ a.base, end };\n+\tif (b1.base \u003c= a.size)\n+\t\treturn FN(normalize)(ab);\n+\n+\t/* The arcs are disjoint; ba is the other possible covering arc. */\n+\tba = (struct cnum_t){ b.base, a.size - b1.base };\n+\tif (ba.size \u003c ab.size ||\n+\t (ba.size == ab.size \u0026\u0026 ba.base \u003c ab.base))\n+\t\tab = ba;\n+\n+\treturn FN(normalize)(ab);\n+}\n+\n struct cnum_t FN(add)(struct cnum_t a, struct cnum_t b)\n {\n \tif (FN(is_empty)(a) || FN(is_empty)(b))\ndiff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c\nindex 37cf130ebb57b..ecea117f2848f 100644\n--- a/kernel/bpf/fixups.c\n+++ b/kernel/bpf/fixups.c\n@@ -614,6 +614,22 @@ static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,\n \treturn 0;\n }\n \n+/* Clean up dynamically allocated fields of aux data for instructions [start, ...] */\n+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)\n+{\n+\tstruct bpf_insn_aux_data *aux_data = env-\u003einsn_aux_data;\n+\tint end = start + len;\n+\tint i;\n+\n+\tfor (i = start; i \u003c end; i++) {\n+\t\tif (aux_data[i].loop) {\n+\t\t\tkvfree(aux_data[i].loop-\u003eexits);\n+\t\t\tkvfree(aux_data[i].loop);\n+\t\t\taux_data[i].loop = NULL;\n+\t\t}\n+\t}\n+}\n+\n static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)\n {\n \tstruct bpf_insn_aux_data *aux_data = env-\u003einsn_aux_data;\n@@ -626,6 +642,8 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)\n \tif (bpf_prog_is_offloaded(env-\u003eprog-\u003eaux))\n \t\tbpf_prog_offload_remove_insns(env, off, cnt);\n \n+\tbpf_clear_insn_aux_data(env, off, cnt);\n+\n \terr = bpf_remove_insns(env-\u003eprog, off, cnt);\n \tif (err)\n \t\treturn err;\ndiff --git a/kernel/bpf/heap.c b/kernel/bpf/heap.c\nnew file mode 100644\nindex 0000000000000..029f9217b8726\n--- /dev/null\n+++ b/kernel/bpf/heap.c\n@@ -0,0 +1,87 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/bpf_verifier.h\u003e\n+\n+/* Indexes for binary tree encoded as an array */\n+static inline int left_child(int i) { return 2 * i + 1; }\n+static inline int right_child(int i) { return 2 * i + 2; }\n+static inline int parent(int i) { return (i - 1) / 2; }\n+\n+static inline int greater(struct bpf_min_heap *heap, int a, int b)\n+{\n+\treturn heap-\u003ecompare(a, b, heap-\u003earg) \u003e 0;\n+}\n+\n+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg)\n+{\n+\tmemset(heap, 0, sizeof(*heap));\n+\theap-\u003ecompare = compare;\n+\theap-\u003earg = arg;\n+}\n+\n+void bpf_min_heap_free(struct bpf_min_heap *heap)\n+{\n+\tkfree(heap-\u003eelements);\n+\theap-\u003eelements = NULL;\n+\theap-\u003ecapacity = 0;\n+\theap-\u003ecount = 0;\n+}\n+\n+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt)\n+{\n+\tint new_capacity, i;\n+\tint *elements;\n+\tvoid *tmp;\n+\n+\tif (heap-\u003ecount == heap-\u003ecapacity) {\n+\t\tnew_capacity = heap-\u003ecapacity ? heap-\u003ecapacity * 2 : 16;\n+\t\ttmp = krealloc(heap-\u003eelements,\n+\t\t\t sizeof(*heap-\u003eelements) * new_capacity,\n+\t\t\t GFP_KERNEL_ACCOUNT);\n+\t\tif (!tmp)\n+\t\t\treturn -ENOMEM;\n+\t\theap-\u003eelements = tmp;\n+\t\theap-\u003ecapacity = new_capacity;\n+\t}\n+\n+\telements = heap-\u003eelements;\n+\ti = heap-\u003ecount;\n+\telements[i] = elt;\n+\theap-\u003ecount++;\n+\twhile (i != 0 \u0026\u0026 greater(heap, elements[parent(i)], elements[i])) {\n+\t\tswap(elements[i], elements[parent(i)]);\n+\t\ti = parent(i);\n+\t}\n+\treturn 0;\n+}\n+\n+static inline void sink_root(struct bpf_min_heap *heap)\n+{\n+\tint *elements = heap-\u003eelements;\n+\tint i = 0;\n+\n+\twhile ((left_child(i) \u003c heap-\u003ecount \u0026\u0026 greater(heap, elements[i], elements[left_child(i)])) ||\n+\t (right_child(i) \u003c heap-\u003ecount \u0026\u0026 greater(heap, elements[i], elements[right_child(i)]))) {\n+\t\tif (right_child(i) \u003e= heap-\u003ecount || greater(heap, elements[right_child(i)], elements[left_child(i)])) {\n+\t\t\tswap(elements[i], elements[left_child(i)]);\n+\t\t\ti = left_child(i);\n+\t\t} else {\n+\t\t\tswap(elements[i], elements[right_child(i)]);\n+\t\t\ti = right_child(i);\n+\t\t}\n+\t}\n+}\n+\n+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt)\n+{\n+\tif (heap-\u003ecount == 0)\n+\t\treturn false;\n+\n+\tint *elements = heap-\u003eelements;\n+\t*elt = elements[0];\n+\telements[0] = elements[heap-\u003ecount - 1];\n+\t--heap-\u003ecount;\n+\tsink_root(heap);\n+\treturn true;\n+}\ndiff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c\nindex cd9523f69298e..cba3a6c021b49 100644\n--- a/kernel/bpf/liveness.c\n+++ b/kernel/bpf/liveness.c\n@@ -23,6 +23,7 @@ enum {\n \tFM_MAY_READ,\t/* stack slots that may be read by this instruction */\n \tFM_MUST_WRITE,\t/* stack slots written by this instruction */\n \tFM_LIVE_BEFORE,\t/* stack slots that may be read by this insn and its successors */\n+\tFM_MAY_WRITE,\t/* stack slots that may be written by this instruction */\n \tFM_MASK_CNT,\n };\n \n@@ -262,6 +263,12 @@ static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_\n \treturn mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi);\n }\n \n+static int mark_stack_may_write(struct func_instance *instance, u32 frame, u32 insn_idx,\n+\t\t\t\ts32 lo, s32 hi)\n+{\n+\treturn mark_stack_range(instance, frame, insn_idx, FM_MAY_WRITE, lo, hi);\n+}\n+\n /*\n * Mark every half-slot of @frame as possibly read by @insn_idx. This widens\n * the masks to the program's stack budget: a full read recorded at a narrower\n@@ -277,9 +284,16 @@ static int mark_stack_read_all(struct bpf_verifier_env *env, struct func_instanc\n \t\t\t env-\u003estack_limit / BPF_HALF_REG_SIZE - 1);\n }\n \n-/* Accumulate @src, a mask @src_words wide, into may_read of @frame at @insn_idx */\n-static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,\n-\t\t\t\tconst unsigned long *src, u32 src_words)\n+static int mark_stack_may_write_all(struct bpf_verifier_env *env, struct func_instance *instance,\n+\t\t\t\t u32 frame, u32 insn_idx)\n+{\n+\treturn mark_stack_may_write(instance, frame, insn_idx, 0,\n+\t\t\t\t env-\u003estack_limit / BPF_HALF_REG_SIZE - 1);\n+}\n+\n+/* Accumulate @src, a mask @src_words wide, into @kind mask of @frame at @insn_idx */\n+static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_idx, u32 kind,\n+\t\t\t const unsigned long *src, u32 src_words)\n {\n \tu32 nbits = src_words * BITS_PER_LONG;\n \tstruct frame_masks *fm;\n@@ -292,7 +306,7 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i\n \tfm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1));\n \tif (!fm)\n \t\treturn -ENOMEM;\n-\tdst = rel_mask(fm, relative_idx(instance, insn_idx), FM_MAY_READ);\n+\tdst = rel_mask(fm, relative_idx(instance, insn_idx), kind);\n \t/* @src has no bits set past @last, hence none past @fm-\u003ewords either */\n \tsrc_words = min(src_words, fm-\u003ewords);\n \tfor (w = 0; w \u003c src_words; w++)\n@@ -300,6 +314,12 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i\n \treturn 0;\n }\n \n+static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,\n+\t\t\t\tconst unsigned long *src, u32 src_words)\n+{\n+\treturn mark_stack_mask(instance, frame, insn_idx, FM_MAY_READ, src, src_words);\n+}\n+\n int bpf_jmp_offset(struct bpf_insn *insn)\n {\n \tu8 code = insn-\u003ecode;\n@@ -624,16 +644,41 @@ static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first,\n \treturn env-\u003etmp_str_buf;\n }\n \n+/* Print mask @kind of the instruction at relative index @i for every frame, if any bit is set. */\n+static bool print_mask(struct bpf_verifier_env *env, struct func_instance *instance, int i,\n+\t\t const char *name, u32 kind)\n+{\n+\tstruct frame_masks *fm;\n+\tbool printed = false;\n+\tunsigned long *mask;\n+\tint frame;\n+\tu64 pos;\n+\n+\tpos = env-\u003elog.end_pos;\n+\tverbose(env, \"%s\", name);\n+\tfor (frame = instance-\u003edepth; frame \u003e= 0; --frame) {\n+\t\tfm = instance-\u003eframes[frame];\n+\t\tif (!fm)\n+\t\t\tcontinue;\n+\t\tmask = rel_mask(fm, i, kind);\n+\t\tif (bitmap_empty(mask, frame_mask_bits(fm)))\n+\t\t\tcontinue;\n+\t\tverbose(env, \"%s\", fmt_spis_mask(env, frame, !printed, mask, fm-\u003ewords));\n+\t\tprinted = true;\n+\t}\n+\tif (!printed)\n+\t\tbpf_vlog_reset(\u0026env-\u003elog, pos);\n+\treturn printed;\n+}\n+\n static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance)\n {\n \tint start = env-\u003esubprog_info[instance-\u003esubprog].start;\n \tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n-\tstruct frame_masks *fm;\n-\tunsigned long *mask;\n \tint len = instance-\u003einsn_cnt;\n-\tint insn_idx, frame, i;\n-\tbool has_use, has_def;\n \tu64 pos, insn_pos;\n+\tint insn_idx, i;\n+\tbool printed;\n \n \tif (!(env-\u003elog.level \u0026 BPF_LOG_LEVEL2))\n \t\treturn;\n@@ -642,41 +687,17 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i\n \tverbose(env, \"%s:\\n\", fmt_instance(env, instance));\n \tfor (i = 0; i \u003c len; i++) {\n \t\tinsn_idx = start + i;\n-\t\thas_use = false;\n-\t\thas_def = false;\n \t\tpos = env-\u003elog.end_pos;\n \t\tverbose(env, \"%3d: \", insn_idx);\n \t\tbpf_verbose_insn(env, \u0026insns[insn_idx]);\n \t\tinsn_pos = env-\u003elog.end_pos;\n \t\tverbose(env, \"%*c;\", bpf_vlog_alignment(insn_pos - pos), ' ');\n-\t\tpos = env-\u003elog.end_pos;\n-\t\tverbose(env, \" use: \");\n-\t\tfor (frame = instance-\u003edepth; frame \u003e= 0; --frame) {\n-\t\t\tfm = instance-\u003eframes[frame];\n-\t\t\tif (!fm)\n-\t\t\t\tcontinue;\n-\t\t\tmask = rel_mask(fm, i, FM_MAY_READ);\n-\t\t\tif (bitmap_empty(mask, frame_mask_bits(fm)))\n-\t\t\t\tcontinue;\n-\t\t\tverbose(env, \"%s\", fmt_spis_mask(env, frame, !has_use, mask, fm-\u003ewords));\n-\t\t\thas_use = true;\n-\t\t}\n-\t\tif (!has_use)\n-\t\t\tbpf_vlog_reset(\u0026env-\u003elog, pos);\n-\t\tpos = env-\u003elog.end_pos;\n-\t\tverbose(env, \" def: \");\n-\t\tfor (frame = instance-\u003edepth; frame \u003e= 0; --frame) {\n-\t\t\tfm = instance-\u003eframes[frame];\n-\t\t\tif (!fm)\n-\t\t\t\tcontinue;\n-\t\t\tmask = rel_mask(fm, i, FM_MUST_WRITE);\n-\t\t\tif (bitmap_empty(mask, frame_mask_bits(fm)))\n-\t\t\t\tcontinue;\n-\t\t\tverbose(env, \"%s\", fmt_spis_mask(env, frame, !has_def, mask, fm-\u003ewords));\n-\t\t\thas_def = true;\n-\t\t}\n-\t\tif (!has_def)\n-\t\t\tbpf_vlog_reset(\u0026env-\u003elog, has_use ? pos : insn_pos);\n+\t\tprinted = false;\n+\t\tprinted |= print_mask(env, instance, i, \" use: \", FM_MAY_READ);\n+\t\tprinted |= print_mask(env, instance, i, \" def: \", FM_MUST_WRITE);\n+\t\tprinted |= print_mask(env, instance, i, \" may_def: \", FM_MAY_WRITE);\n+\t\tif (!printed)\n+\t\t\tbpf_vlog_reset(\u0026env-\u003elog, insn_pos);\n \t\tverbose(env, \"\\n\");\n \t\tif (bpf_is_ldimm64(\u0026insns[insn_idx]))\n \t\t\ti++;\n@@ -697,6 +718,49 @@ static int cmp_instances(const void *pa, const void *pb)\n \treturn 0;\n }\n \n+/* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */\n+static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)\n+{\n+\tu32 slot;\n+\n+\tfor (slot = 0; slot \u003c MAX_BPF_STACK_SLOTS \u0026\u0026 slot * 2 + 1 \u003c nbits; slot++)\n+\t\tif (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask))\n+\t\t\t__set_bit(slot, slots);\n+}\n+\n+/*\n+ * Precompute, for each instruction, the OR of may_write and live_before masks\n+ * over its top frame across all func_instances reaching it, stash them in the\n+ * insn_aux_data.\n+ */\n+static void compute_may_write_masks(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_liveness *liveness = env-\u003eliveness;\n+\tstruct func_instance *instance;\n+\tstruct frame_masks *fm;\n+\tu32 nbits;\n+\tint bkt, i;\n+\n+\thash_for_each(liveness-\u003efunc_instances, bkt, instance, hl_node) {\n+\t\tfm = instance-\u003eframes[instance-\u003edepth];\n+\t\tif (!fm)\n+\t\t\tcontinue;\n+\t\tnbits = frame_mask_bits(fm);\n+\t\tfor (i = 0; i \u003c instance-\u003einsn_cnt; i++) {\n+\t\t\thalf_spis_to_slots(aux[instance-\u003esubprog_start + i].may_write_mask,\n+\t\t\t\t\t rel_mask(fm, i, FM_MAY_WRITE), nbits);\n+\t\t\thalf_spis_to_slots(aux[instance-\u003esubprog_start + i].live_stack_before,\n+\t\t\t\t\t rel_mask(fm, i, FM_LIVE_BEFORE), nbits);\n+\t\t}\n+\t}\n+}\n+\n+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)\n+{\n+\treturn env-\u003einsn_aux_data[insn_idx].may_write_mask;\n+}\n+\n /* print use/def slots for all instances ordered by callsite first, then by depth */\n static int print_instances(struct bpf_verifier_env *env)\n {\n@@ -1444,10 +1508,12 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn,\n * access_bytes == 0: no access\n *\n */\n-static int record_stack_access_off(struct func_instance *instance, s64 fp_off,\n-\t\t\t\t s64 access_bytes, u32 frame, u32 insn_idx)\n+static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg,\n+\t\t\t\t u32 off_idx, s64 access_bytes, u32 frame, u32 insn_idx)\n {\n+\ts64 fp_off = arg-\u003eoff[off_idx];\n \ts32 slot_hi, slot_lo;\n+\tint err;\n \n \tif (fp_off \u003e= 0)\n \t\t/*\n@@ -1459,7 +1525,8 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,\n \tif (access_bytes == S64_MIN) {\n \t\t/* helper/kfunc read unknown amount of bytes from fp_off until fp+0 */\n \t\tslot_hi = (-fp_off - 1) / STACK_SLOT_SZ;\n-\t\treturn mark_stack_read(instance, frame, insn_idx, 0, slot_hi);\n+\t\terr = mark_stack_read(instance, frame, insn_idx, 0, slot_hi);\n+\t\treturn err ?: mark_stack_may_write(instance, frame, insn_idx, 0, slot_hi);\n \t}\n \tif (access_bytes \u003e 0) {\n \t\t/* Mark any touched slot as use */\n@@ -1471,7 +1538,15 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,\n \t\taccess_bytes = -access_bytes;\n \t\tslot_hi = (-fp_off) / STACK_SLOT_SZ - 1;\n \t\tslot_lo = max_t(s32, (-fp_off - access_bytes + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0);\n-\t\treturn mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);\n+\t\tif (arg-\u003eoff_cnt == 1) {\n+\t\t\terr = mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t}\n+\t\t/* Mark partially covered slots as may_def */\n+\t\tslot_hi = (-fp_off - 1) / STACK_SLOT_SZ;\n+\t\tslot_lo = max_t(s32, (-fp_off - access_bytes) / STACK_SLOT_SZ, 0);\n+\t\treturn mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi);\n \t}\n \treturn 0;\n }\n@@ -1480,25 +1555,31 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,\n * 'arg' is FP-derived argument to helper/kfunc or load/store that\n * reads (positive) or writes (negative) 'access_bytes' into 'use' or 'def'.\n */\n-static int record_stack_access(struct bpf_verifier_env *env, struct func_instance *instance,\n-\t\t\t const struct arg_track *arg,\n-\t\t\t s64 access_bytes, u32 frame, u32 insn_idx)\n+static int record_precise(struct bpf_verifier_env *env,\n+\t\t\t struct func_instance *instance,\n+\t\t\t const struct arg_track *arg,\n+\t\t\t s64 access_bytes, u32 frame, u32 insn_idx)\n {\n \tint i, err;\n \n \tif (access_bytes == 0)\n \t\treturn 0;\n \tif (arg-\u003eoff_cnt == 0) {\n-\t\tif (access_bytes \u003e 0 || access_bytes == S64_MIN)\n-\t\t\treturn mark_stack_read_all(env, instance, frame, insn_idx);\n+\t\tif (access_bytes \u003e 0 || access_bytes == S64_MIN) {\n+\t\t\terr = mark_stack_read_all(env, instance, frame, insn_idx);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t}\n+\t\tif (access_bytes \u003c 0 || access_bytes == S64_MIN) {\n+\t\t\terr = mark_stack_may_write_all(env, instance, frame, insn_idx);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t}\n \t\treturn 0;\n \t}\n-\tif (access_bytes != S64_MIN \u0026\u0026 access_bytes \u003c 0 \u0026\u0026 arg-\u003eoff_cnt != 1)\n-\t\t/* multi-offset write cannot set stack_def */\n-\t\treturn 0;\n \n \tfor (i = 0; i \u003c arg-\u003eoff_cnt; i++) {\n-\t\terr = record_stack_access_off(instance, arg-\u003eoff[i], access_bytes, frame, insn_idx);\n+\t\terr = record_stack_access_off(instance, arg, i, access_bytes, frame, insn_idx);\n \t\tif (err)\n \t\t\treturn err;\n \t}\n@@ -1507,10 +1588,11 @@ static int record_stack_access(struct bpf_verifier_env *env, struct func_instanc\n \n /*\n * When a pointer is ARG_IMPRECISE, conservatively mark every frame in\n- * the bitmask as fully used.\n+ * the bitmask as fully used. Same as in record_stack_access(),\n+ * negative 'access_bytes' means stack write.\n */\n static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *instance,\n-\t\t\t u32 mask, u32 insn_idx)\n+\t\t\t s64 access_bytes, u32 mask, u32 insn_idx)\n {\n \tint depth = instance-\u003edepth;\n \tint f, err;\n@@ -1519,25 +1601,45 @@ static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *\n \t\tif (!(mask \u0026 1))\n \t\t\tcontinue;\n \t\tif (f \u003c= depth) {\n-\t\t\terr = mark_stack_read_all(env, instance, f, insn_idx);\n-\t\t\tif (err)\n-\t\t\t\treturn err;\n+\t\t\tif (access_bytes \u003e 0 || access_bytes == S64_MIN) {\n+\t\t\t\terr = mark_stack_read_all(env, instance, f, insn_idx);\n+\t\t\t\tif (err)\n+\t\t\t\t\treturn err;\n+\t\t\t}\n+\t\t\tif (access_bytes \u003c 0) {\n+\t\t\t\terr = mark_stack_may_write_all(env, instance, f, insn_idx);\n+\t\t\t\tif (err)\n+\t\t\t\t\treturn err;\n+\t\t\t}\n \t\t}\n \t}\n \treturn 0;\n }\n \n+static int record_stack_access(struct bpf_verifier_env *env,\n+\t\t\t struct func_instance *instance,\n+\t\t\t const struct arg_track *ptr,\n+\t\t\t s64 access_bytes, u32 insn_idx)\n+{\n+\tif (ptr-\u003eframe \u003e= 0 \u0026\u0026 ptr-\u003eframe \u003c= instance-\u003edepth)\n+\t\treturn record_precise(env, instance, ptr, access_bytes, ptr-\u003eframe, insn_idx);\n+\tif (ptr-\u003eframe == ARG_IMPRECISE)\n+\t\treturn record_imprecise(env, instance, access_bytes, ptr-\u003emask, insn_idx);\n+\t/* ARG_NONE: not derived from any frame pointer, skip */\n+\treturn 0;\n+}\n+\n /* Record load/store access for a given 'at' state of 'insn'. */\n static int record_load_store_access(struct bpf_verifier_env *env,\n \t\t\t\t struct func_instance *instance,\n \t\t\t\t struct arg_track *at, int insn_idx)\n {\n \tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[insn_idx];\n-\tint depth = instance-\u003edepth;\n \ts32 sz = bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode));\n \tu8 class = BPF_CLASS(insn-\u003ecode);\n \tstruct arg_track resolved, *ptr;\n-\tint oi;\n+\tbool rmw = false; /* atomic read-modify-write: both read and write */\n+\tint oi, err;\n \n \t/*\n \t * Stack arg insns use dst_reg/src_reg=BPF_REG_PARAMS(11). Since at[]\n@@ -1555,12 +1657,20 @@ static int record_load_store_access(struct bpf_verifier_env *env,\n \t\tbreak;\n \tcase BPF_STX:\n \t\tif (BPF_MODE(insn-\u003ecode) == BPF_ATOMIC) {\n-\t\t\tif (insn-\u003eimm == BPF_STORE_REL)\n-\t\t\t\tsz = -sz;\n-\t\t\tif (insn-\u003eimm == BPF_LOAD_ACQ)\n+\t\t\tswitch (insn-\u003eimm) {\n+\t\t\tcase BPF_LOAD_ACQ:\n \t\t\t\tptr = \u0026at[insn-\u003esrc_reg];\n-\t\t\telse\n+\t\t\t\tbreak;\n+\t\t\tcase BPF_STORE_REL:\n+\t\t\t\tptr = \u0026at[insn-\u003edst_reg];\n+\t\t\t\tsz = -sz;\n+\t\t\t\tbreak;\n+\t\t\tdefault:\n+\t\t\t\t/* ADD/AND/OR/XOR(+FETCH), XCHG, CMPXCHG */\n \t\t\t\tptr = \u0026at[insn-\u003edst_reg];\n+\t\t\t\trmw = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n \t\t} else {\n \t\t\tptr = \u0026at[insn-\u003edst_reg];\n \t\t\tsz = -sz;\n@@ -1587,12 +1697,10 @@ static int record_load_store_access(struct bpf_verifier_env *env,\n \t\tptr = \u0026resolved;\n \t}\n \n-\tif (ptr-\u003eframe \u003e= 0 \u0026\u0026 ptr-\u003eframe \u003c= depth)\n-\t\treturn record_stack_access(env, instance, ptr, sz, ptr-\u003eframe, insn_idx);\n-\tif (ptr-\u003eframe == ARG_IMPRECISE)\n-\t\treturn record_imprecise(env, instance, ptr-\u003emask, insn_idx);\n-\t/* ARG_NONE: not derived from any frame pointer, skip */\n-\treturn 0;\n+\terr = record_stack_access(env, instance, ptr, sz, insn_idx);\n+\tif (!err \u0026\u0026 rmw) /* also record the write half */\n+\t\terr = record_stack_access(env, instance, ptr, -sz, insn_idx);\n+\treturn err;\n }\n \n static int record_arg_access(struct bpf_verifier_env *env,\n@@ -1602,7 +1710,6 @@ static int record_arg_access(struct bpf_verifier_env *env,\n \t\t\t int insn_idx)\n {\n \tint depth = instance-\u003edepth;\n-\tint frame = at-\u003eframe;\n \tint err = 0;\n \ts64 bytes;\n \n@@ -1618,17 +1725,16 @@ static int record_arg_access(struct bpf_verifier_env *env,\n \t\t\terr = mark_stack_read_all(env, instance, f, insn_idx);\n \t\t\tif (err)\n \t\t\t\treturn err;\n+\t\t\terr = mark_stack_may_write_all(env, instance, f, insn_idx);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n \t\t}\n \t\treturn 0;\n \t}\n \tif (bytes == 0)\n \t\treturn 0;\n \n-\tif (frame \u003e= 0 \u0026\u0026 frame \u003c= depth)\n-\t\terr = record_stack_access(env, instance, at, bytes, frame, insn_idx);\n-\telse if (frame == ARG_IMPRECISE)\n-\t\terr = record_imprecise(env, instance, at-\u003emask, insn_idx);\n-\treturn err;\n+\treturn record_stack_access(env, instance, at, bytes, insn_idx);\n }\n \n /* Record stack access for a given 'at' state of helper/kfunc 'insn' */\n@@ -1808,6 +1914,17 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env,\n \t}\n }\n \n+static void record_stack_ptrs(struct bpf_verifier_env *env, int idx, struct arg_track *at_in)\n+{\n+\tu16 r, mask = 0;\n+\n+\tfor (r = 0; r \u003c MAX_BPF_REG; r++)\n+\t\tif (arg_is_fp(\u0026at_in[r]))\n+\t\t\tmask |= BIT(r);\n+\n+\tenv-\u003einsn_aux_data[idx].stack_ptrs |= mask;\n+}\n+\n /*\n * Compute arg tracking dataflow for a single subprog.\n * Runs forward fixed-point with arg_track_xfer(), then records\n@@ -1957,6 +2074,8 @@ static int compute_subprog_args(struct bpf_verifier_env *env,\n \t\t\tsnap-\u003eslots = nslots;\n \t\t\tmemcpy(snap-\u003eat, \u0026at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap-\u003eat));\n \t\t}\n+\n+\t\trecord_stack_ptrs(env, idx, at_in[i]);\n \t}\n \n \tinfo-\u003eat_in = at_in;\n@@ -1987,6 +2106,7 @@ static bool has_fp_args(struct arg_track *args)\n /*\n * Merge a freshly analyzed instance into the original.\n * may_read: union (any pass might read the slot).\n+ * may_write: union (slots written on ANY pass).\n * must_write: intersection (only slots written on ALL passes are guaranteed).\n * live_before is recomputed by a subsequent update_instance() on @dst.\n *\n@@ -2025,18 +2145,50 @@ static int merge_instances(struct func_instance *dst, struct func_instance *src)\n \t\tfor (i = 0; i \u003c dst-\u003einsn_cnt; i++) {\n \t\t\tunsigned long *dst_read = rel_mask(d, i, FM_MAY_READ);\n \t\t\tunsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE);\n+\t\t\tunsigned long *dst_may_write = rel_mask(d, i, FM_MAY_WRITE);\n \t\t\tunsigned long *src_read = rel_mask(s, i, FM_MAY_READ);\n \t\t\tunsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE);\n+\t\t\tunsigned long *src_may_write = rel_mask(s, i, FM_MAY_WRITE);\n \n \t\t\tfor (w = 0; w \u003c d-\u003ewords; w++) {\n \t\t\t\tdst_read[w] |= w \u003c s-\u003ewords ? src_read[w] : 0;\n \t\t\t\tdst_write[w] \u0026= w \u003c s-\u003ewords ? src_write[w] : 0;\n+\t\t\t\tdst_may_write[w] |= w \u003c s-\u003ewords ? src_may_write[w] : 0;\n \t\t\t}\n \t\t}\n \t}\n \treturn 0;\n }\n \n+/*\n+ * Fold a fully analyzed callee instance writes to upper frames as\n+ * may_write marks at callsite in caller's frames.\n+ */\n+static int merge_may_write(struct func_instance *caller, struct func_instance *callee)\n+{\n+\tDECLARE_BITMAP(acc, FRAME_HALF_SPIS);\n+\tu32 call_idx = callee-\u003ecallsite;\n+\tstruct frame_masks *fm;\n+\tu32 f, i, nbits;\n+\tint err;\n+\n+\tfor (f = 0; f \u003c callee-\u003edepth; f++) {\n+\t\tfm = callee-\u003eframes[f];\n+\t\tif (!fm)\n+\t\t\tcontinue;\n+\t\tnbits = frame_mask_bits(fm);\n+\t\tbitmap_zero(acc, nbits);\n+\t\tfor (i = 0; i \u003c callee-\u003einsn_cnt; i++)\n+\t\t\tbitmap_or(acc, acc, rel_mask(fm, i, FM_MAY_WRITE), nbits);\n+\t\tif (bitmap_empty(acc, nbits))\n+\t\t\tcontinue;\n+\t\terr = mark_stack_mask(caller, f, call_idx, FM_MAY_WRITE, acc, fm-\u003ewords);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn 0;\n+}\n+\n static struct func_instance *fresh_instance(struct func_instance *src)\n {\n \tstruct func_instance *f;\n@@ -2204,6 +2356,11 @@ static int analyze_subprog(struct bpf_verifier_env *env,\n \t\t\t\t\tgoto out_free;\n \t\t\t}\n \t\t}\n+\n+\t\t/* Summarize callee's writes to ancestor frames onto the callsite */\n+\t\terr = merge_may_write(instance, callee_instance);\n+\t\tif (err)\n+\t\t\tgoto out_free;\n \t}\n \n \tif (prev_instance) {\n@@ -2266,6 +2423,8 @@ int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)\n \t\t\tgoto out;\n \t}\n \n+\tcompute_may_write_masks(env);\n+\n \tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2)\n \t\terr = print_instances(env);\n \n@@ -2472,8 +2631,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)\n \tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n \tstruct insn_live_regs *state;\n \tint insn_cnt = env-\u003eprog-\u003elen;\n-\tu64 pos, insn_pos;\n-\tint err = 0, i, j, subprog, start, end;\n+\tint err = 0, i, subprog, start, end;\n \tbool changed, ret_reg_pair;\n \n \t/* Use the following algorithm:\n@@ -2552,31 +2710,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)\n \t\tinsn_aux[i].zext_dst = def32 \u003e= 0 \u0026\u0026 (mask_hi(out) \u0026 BIT(def32));\n \t}\n \n-\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2) {\n-\t\tverbose(env, \"Live regs before insn:\\n\");\n-\t\tfor (i = 0; i \u003c insn_cnt; ++i) {\n-\t\t\tif (env-\u003einsn_aux_data[i].scc)\n-\t\t\t\tverbose(env, \"%3d \", env-\u003einsn_aux_data[i].scc);\n-\t\t\telse\n-\t\t\t\tverbose(env, \" \");\n-\t\t\tverbose(env, \"%3d: \", i);\n-\t\t\tfor (j = BPF_REG_0; j \u003c BPF_REG_10; ++j)\n-\t\t\t\tif (insn_aux[i].live_regs_before \u0026 BIT(j))\n-\t\t\t\t\tverbose(env, \"%d\", j);\n-\t\t\t\telse\n-\t\t\t\t\tverbose(env, \".\");\n-\t\t\tverbose(env, \" \");\n-\t\t\tpos = env-\u003elog.end_pos;\n-\t\t\tbpf_verbose_insn(env, \u0026insns[i]);\n-\t\t\tinsn_pos = env-\u003elog.end_pos;\n-\t\t\tif (insn_aux[i].zext_dst)\n-\t\t\t\tverbose(env, \"%*c; zext\", bpf_vlog_alignment(insn_pos - pos), ' ');\n-\t\t\tverbose(env, \"\\n\");\n-\t\t\tif (bpf_is_ldimm64(\u0026insns[i]))\n-\t\t\t\ti++;\n-\t\t}\n-\t}\n-\n out:\n \tkvfree(state);\n \treturn err;\ndiff --git a/kernel/bpf/log.c b/kernel/bpf/log.c\nindex d850a7863d2ed..6a5564f626693 100644\n--- a/kernel/bpf/log.c\n+++ b/kernel/bpf/log.c\n@@ -692,6 +692,8 @@ static void print_reg_state(struct bpf_verifier_env *env,\n \n \t\t\ttnum_strn(tn_buf, sizeof(tn_buf), reg-\u003evar_off);\n \t\t\tverbose_a(\"var_off=%s\", tn_buf);\n+\t\t\tif (reg-\u003ebase != 0 || reg-\u003estep != 1)\n+\t\t\t\tverbose_a(\"step=%d+%d\", reg-\u003ebase, reg-\u003estep);\n \t\t}\n \t}\n \tverbose(env, \")\");\n@@ -790,6 +792,11 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie\n \t\tverbose(env, \" cb\");\n \tif (state-\u003ein_async_callback_fn)\n \t\tverbose(env, \" async_cb\");\n+\tif (state-\u003eloop_stack_cnt) {\n+\t\tverbose(env, \" loop_stack=\");\n+\t\tfor (i = 0; i \u003c state-\u003eloop_stack_cnt; i++)\n+\t\t\tverbose(env, \"%s%d\", i ? \",\" : \"\", state-\u003eloop_stack[i].loop_id);\n+\t}\n \tverbose(env, \"\\n\");\n \tif (!print_all)\n \t\tmark_verifier_state_clean(env);\ndiff --git a/kernel/bpf/loops.c b/kernel/bpf/loops.c\nnew file mode 100644\nindex 0000000000000..5f52a88d52837\n--- /dev/null\n+++ b/kernel/bpf/loops.c\n@@ -0,0 +1,576 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e\n+\n+static bool is_cfg_jump(struct bpf_insn *insn)\n+{\n+\tu8 class = BPF_CLASS(insn-\u003ecode);\n+\tu8 opcode = BPF_OP(insn-\u003ecode);\n+\n+\tswitch (class) {\n+\tcase BPF_JMP:\n+\tcase BPF_JMP32:\n+\t\treturn opcode != BPF_CALL;\n+\tdefault:\n+\t\treturn false;\n+\t}\n+}\n+\n+static struct bpf_iarray **compute_predecessors(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_iarray *succ, *preds, **result;\n+\tstruct bpf_prog *prog = env-\u003eprog;\n+\tu32 *num_preds, i, s, sz, len = prog-\u003elen;\n+\tstruct bpf_insn *insn;\n+\tvoid *tmp;\n+\n+\tnum_preds = kvcalloc(prog-\u003elen, sizeof(u32), GFP_KERNEL_ACCOUNT);\n+\tif (!num_preds)\n+\t\treturn NULL;\n+\n+\t/*\n+\t * 'result' layout:\n+\t * - array of pointers (struct bpf_iarray *)[len]\n+\t * - struct bpf_iarray one after another\n+\t */\n+\tsz = sizeof(struct bpf_iarray) * len;\n+\tsz += sizeof(struct bpf_iarray *) * len;\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tinsn = env-\u003eprog-\u003einsnsi + i;\n+\t\tsucc = bpf_insn_successors(env, i);\n+\t\tsz += sizeof(u32) * succ-\u003ecnt;\n+\t\tiarray_for_each(s, succ) {\n+\t\t\tnum_preds[s]++;\n+\t\t}\n+\t\tif (bpf_is_ldimm64(insn))\n+\t\t\ti++;\n+\t}\n+\n+\tresult = kvzalloc(sz, GFP_KERNEL_ACCOUNT);\n+\tif (!result) {\n+\t\tkvfree(num_preds);\n+\t\treturn NULL;\n+\t}\n+\n+\ttmp = (void *)\u0026result[len];\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tresult[i] = tmp;\n+\t\ttmp += sizeof(struct bpf_iarray);\n+\t\ttmp += sizeof(u32) * num_preds[i];\n+\t}\n+\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tinsn = env-\u003eprog-\u003einsnsi + i;\n+\t\tsucc = bpf_insn_successors(env, i);\n+\t\tiarray_for_each(s, succ) {\n+\t\t\tpreds = result[s];\n+\t\t\tpreds-\u003eitems[preds-\u003ecnt++] = i;\n+\t\t}\n+\t\tif (succ-\u003ecnt \u003e 1 ||\n+\t\t (succ-\u003ecnt == 1 \u0026\u0026 num_preds[succ-\u003eitems[0]] \u003e 1) ||\n+\t\t is_cfg_jump(insn))\n+\t\t\taux[i].bb_end = true;\n+\t\tif (bpf_is_ldimm64(insn))\n+\t\t\ti++;\n+\t}\n+\n+\tkvfree(num_preds);\n+\treturn result;\n+}\n+\n+static int idoms_intersect(struct bpf_verifier_env *env, int a, int b)\n+{\n+\tint *postorder_nums = env-\u003ecfg.postorder_nums;\n+\tint *idoms = env-\u003eidoms;\n+\n+\twhile (a != b) {\n+\t\twhile (postorder_nums[a] \u003c postorder_nums[b]) {\n+\t\t\ta = idoms[a];\n+\t\t}\n+\t\twhile (postorder_nums[b] \u003c postorder_nums[a]) {\n+\t\t\tb = idoms[b];\n+\t\t}\n+\t}\n+\treturn a;\n+}\n+\n+/* See \"A Simple, Fast Dominance Algorithm\" by Cooper et al. for details. */\n+static void compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarray **preds, int subprog_idx)\n+{\n+\tstruct bpf_subprog_info *subprog = \u0026env-\u003esubprog_info[subprog_idx];\n+\tint start = subprog-\u003estart;\n+\tint po_first = subprog-\u003epostorder_start;\n+\tint po_last = (subprog + 1)-\u003epostorder_start - 1;\n+\tint *idoms = env-\u003eidoms;\n+\tint po_num, pred;\n+\tbool changed;\n+\n+\tidoms[start] = 0;\n+\tchanged = true;\n+\tdo {\n+\t\tchanged = false;\n+\t\t/* iterate in reverse postorder */\n+\t\tfor (po_num = po_last; po_num \u003e= po_first; po_num--) {\n+\t\t\tint idx = env-\u003ecfg.insn_postorder[po_num];\n+\t\t\tint new_idom = -1;\n+\n+\t\t\tiarray_for_each(pred, preds[idx]) {\n+\t\t\t\tif (idoms[pred] == -1)\n+\t\t\t\t\tcontinue;\n+\t\t\t\tif (new_idom == -1)\n+\t\t\t\t\tnew_idom = pred;\n+\t\t\t\telse\n+\t\t\t\t\tnew_idom = idoms_intersect(env, pred, new_idom);\n+\t\t\t}\n+\t\t\tif (new_idom != -1 \u0026\u0026 idoms[idx] != new_idom) {\n+\t\t\t\tidoms[idx] = new_idom;\n+\t\t\t\tchanged = true;\n+\t\t\t}\n+\t\t}\n+\t} while (changed);\n+\tidoms[start] = -1;\n+}\n+\n+int bpf_compute_idoms(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_iarray **preds;\n+\tu32 len = env-\u003eprog-\u003elen;\n+\tint *idoms, i;\n+\n+\tpreds = compute_predecessors(env);\n+\tif (!preds)\n+\t\treturn -ENOMEM;\n+\n+\tidoms = kvcalloc(len, sizeof(*idoms), GFP_KERNEL_ACCOUNT);\n+\tif (!idoms) {\n+\t\tkvfree(preds);\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\tenv-\u003eidoms = idoms;\n+\tfor (i = 0; i \u003c len; i++)\n+\t\tidoms[i] = -1;\n+\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++)\n+\t\tcompute_subprog_idoms(env, preds, i);\n+\n+\tkvfree(preds);\n+\treturn 0;\n+}\n+\n+struct dfs_state {\n+\tu32 traversed:1;\n+\tu32 next_succ:31;\n+};\n+\n+struct loops_dfs {\n+\tstruct dfs_state *state;\n+\tint *dfs_pos;\n+\tint *stack;\n+};\n+\n+static void mark_irreducible(struct bpf_verifier_env *env, int h)\n+{\n+\tenv-\u003einsn_aux_data[h].loop-\u003eirreducible = true;\n+}\n+\n+static void mark_entry(struct bpf_verifier_env *env, int s)\n+{\n+\tenv-\u003einsn_aux_data[s].loop_entry = true;\n+}\n+\n+static void add_backedge(struct bpf_verifier_env *env, int from, int h)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_loop *loop = aux[h].loop;\n+\tint cnt = loop-\u003ebackedges_cnt;\n+\n+\tif (cnt == MAX_BACKEDGES) {\n+\t\tloop-\u003ebackedges_overflow = true;\n+\t\treturn;\n+\t}\n+\tloop-\u003ebackedges[cnt].from = from;\n+\tloop-\u003ebackedges[cnt].latch = -1;\n+\tloop-\u003ebackedges_cnt++;\n+}\n+\n+static int add_exit(struct bpf_loop *loop, int from, int to)\n+{\n+\tif (loop-\u003eexits_overflow)\n+\t\treturn 0;\n+\tif (loop-\u003eexits_cnt == MAX_LOOP_EXITS) {\n+\t\tloop-\u003eexits_overflow = true;\n+\t\treturn 0;\n+\t}\n+\tif (!loop-\u003eexits) {\n+\t\tloop-\u003eexits = kvcalloc(MAX_LOOP_EXITS, sizeof(*loop-\u003eexits), GFP_KERNEL_ACCOUNT);\n+\t\tif (!loop-\u003eexits)\n+\t\t\treturn -ENOMEM;\n+\t}\n+\tloop-\u003eexits[loop-\u003eexits_cnt] = (struct bpf_loop_exit) {\n+\t\t.from = from,\n+\t\t.to = to,\n+\t};\n+\tloop-\u003eexits_cnt++;\n+\treturn 0;\n+}\n+\n+static int mark_as_header(struct bpf_verifier_env *env, int h)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\n+\tif (!aux[h].loop) {\n+\t\tmark_entry(env, h);\n+\t\taux[h].loop = kvzalloc_obj(struct bpf_loop, GFP_KERNEL_ACCOUNT);\n+\t\tif (!aux[h].loop)\n+\t\t\treturn -ENOMEM;\n+\t}\n+\treturn 0;\n+}\n+\n+static int assign_header(struct bpf_verifier_env *env, struct loops_dfs *dfs, int n, int h)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint *dfs_pos = dfs-\u003edfs_pos;\n+\tint err, nh;\n+\n+\terr = mark_as_header(env, h);\n+\tif (err)\n+\t\treturn err;\n+\n+\t/* Don't encode self-loops, otherwise can't reflect loops nesting structure. */\n+\tif (n == h)\n+\t\treturn 0;\n+\n+\t/* Make sure that loop headers up the chain are sorted by dfs_pos. */\n+\twhile (aux[n].loop_header != -1) {\n+\t\tnh = aux[n].loop_header;\n+\t\tif (nh == h)\n+\t\t\treturn 0;\n+\t\tif (dfs_pos[nh] \u003c dfs_pos[h]) {\n+\t\t\taux[n].loop_header = h;\n+\t\t\tn = h;\n+\t\t\th = nh;\n+\t\t} else {\n+\t\t\tn = nh;\n+\t\t}\n+\t}\n+\taux[n].loop_header = h;\n+\treturn 0;\n+}\n+\n+static bool is_cond_jmp_insn(struct bpf_insn *insn)\n+{\n+\tu8 class = BPF_CLASS(insn-\u003ecode);\n+\tu8 opcode = BPF_OP(insn-\u003ecode);\n+\n+\tif (class != BPF_JMP \u0026\u0026 class != BPF_JMP32)\n+\t\treturn false;\n+\n+\tswitch (opcode) {\n+\tcase BPF_JEQ:\n+\tcase BPF_JGE:\n+\tcase BPF_JGT:\n+\tcase BPF_JLE:\n+\tcase BPF_JLT:\n+\tcase BPF_JNE:\n+\tcase BPF_JSET:\n+\tcase BPF_JSGE:\n+\tcase BPF_JSGT:\n+\tcase BPF_JSLE:\n+\tcase BPF_JSLT:\n+\t\treturn true;\n+\tdefault:\n+\t\treturn false;\n+\t}\n+}\n+\n+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\n+\treturn aux[idx].loop ? idx : aux[idx].loop_header;\n+}\n+\n+static int find_dominating_condition(struct bpf_verifier_env *env, int n, int top)\n+{\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n+\tint common_dom, n_loop, t_loop, f_loop;\n+\tint *idoms = env-\u003eidoms;\n+\n+\tn_loop = bpf_loop_at_index(env, n);\n+\tcommon_dom = idoms_intersect(env, n, top);\n+\tif (common_dom != top)\n+\t\treturn -1;\n+\twhile (n \u003e= 0) {\n+\t\tif (is_cond_jmp_insn(\u0026insns[n]) \u0026\u0026 bpf_loop_at_index(env, n) == n_loop) {\n+\t\t\tt_loop = bpf_loop_at_index(env, n + insns[n].off + 1);\n+\t\t\tf_loop = bpf_loop_at_index(env, n + 1);\n+\t\t\tif (f_loop != n_loop \u0026\u0026 !bpf_is_nested_loop(env, f_loop, n_loop))\n+\t\t\t\treturn n;\n+\t\t\tif (t_loop != n_loop \u0026\u0026 !bpf_is_nested_loop(env, t_loop, n_loop))\n+\t\t\t\treturn n;\n+\t\t}\n+\t\tif (n == top)\n+\t\t\tbreak;\n+\t\tn = idoms[n];\n+\t}\n+\treturn -1;\n+}\n+\n+/*\n+ * As described in \"A New Algorithm for Identifying Loops in Decompilation\" by Wei et al,\n+ * adapted to be non-recursive.\n+ */\n+static int compute_loops_in_subprog(struct bpf_verifier_env *env, struct loops_dfs *dfs,\n+\t\t\t\t int subprog_idx)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct dfs_state *state = dfs-\u003estate;\n+\tint start = env-\u003esubprog_info[subprog_idx].start;\n+\tint *dfs_pos = dfs-\u003edfs_pos;\n+\tint *stack = dfs-\u003estack;\n+\tint s, h, err, cur, stack_sz;\n+\tstruct bpf_iarray *succ;\n+\tu32 i;\n+\n+\tstack[0] = start;\n+\tstate[start].traversed = true;\n+\tstate[start].next_succ = 0;\n+\tdfs_pos[start] = 1;\n+\tstack_sz = 1;\n+\ti = 0;\n+\tdo {\n+\t\t/*\n+\t\t * The algorithm should be very fast in practice,\n+\t\t * guard against pathological inputs, just in case.\n+\t\t */\n+\t\tif ((++i % 1024) == 0) {\n+\t\t\tif (signal_pending(current))\n+\t\t\t\treturn -EAGAIN;\n+\t\t\tcond_resched();\n+\t\t}\n+\n+\t\tcur = stack[stack_sz - 1];\n+\t\tsucc = bpf_insn_successors(env, cur);\n+\t\tif (state[cur].next_succ == succ-\u003ecnt) {\n+\t\t\tdfs_pos[cur] = 0;\n+\t\t\tstack_sz--;\n+\t\t\tcontinue;\n+\t\t}\n+\t\ts = succ-\u003eitems[state[cur].next_succ];\n+\t\tif (!state[s].traversed) {\n+\t\t\t/* Case A: start -\u003e ... -\u003e cur -\u003e s [unexplored] */\n+\t\t\tstate[s].traversed = true;\n+\t\t\tstate[s].next_succ = 0;\n+\t\t\tstack[stack_sz] = s;\n+\t\t\tdfs_pos[s] = stack_sz + 1;\n+\t\t\tstack_sz++;\n+\t\t\tcontinue;\n+\t\t}\n+\t\t/* 's' is fully explored at this point */\n+\t\tif (dfs_pos[s]) {\n+\t\t\t/*\n+\t\t\t * start -\u003e ... -\u003e s -\u003e cur --.\n+\t\t\t * ^ |\n+\t\t\t * '----------'\n+\t\t\t * Case B: 's' is in the current DFS path.\n+\t\t\t */\n+\t\t\terr = assign_header(env, dfs, cur, s);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t\tadd_backedge(env, cur, s);\n+\t\t} else if (aux[s].loop_header == -1) {\n+\t\t\t/*\n+\t\t\t * start -\u003e ... -\u003e ... -\u003e s -\u003e ... -\u003e end\n+\t\t\t * | ^\n+\t\t\t * '---\u003e cur ---'\n+\t\t\t * Case C: 's' is explored, not in the current DFS path,\n+\t\t\t * and not a part of any loop.\n+\t\t\t */\n+\t\t} else if (dfs_pos[aux[s].loop_header]) {\n+\t\t\t/*\n+\t\t\t * .----------------------.\n+\t\t\t * v |\n+\t\t\t * start -\u003e ... -\u003e h -\u003e ... -\u003e ... -\u003e s --'\n+\t\t\t * | ^\n+\t\t\t *\t '---\u003e cur ---'\n+\t\t\t * Case D: 's' is explored, not in current DFS path,\n+\t\t\t * but its innermost loop header is.\n+\t\t\t */\n+\t\t\terr = assign_header(env, dfs, cur, aux[s].loop_header);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t} else {\n+\t\t\t/*\n+\t\t\t * case E: 's' is explored, not in current DFS path,\n+\t\t\t * its innermost loop header is not in current DFS path,\n+\t\t\t * hence 's' is another entry into the same loop.\n+\t\t\t */\n+\t\t\th = aux[s].loop_header;\n+\t\t\tmark_irreducible(env, h);\n+\t\t\tmark_entry(env, s);\n+\t\t\twhile (aux[h].loop_header != -1) {\n+\t\t\t\th = aux[h].loop_header;\n+\t\t\t\tif (dfs_pos[h]) {\n+\t\t\t\t\terr = assign_header(env, dfs, cur, h);\n+\t\t\t\t\tif (err)\n+\t\t\t\t\t\treturn err;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t\tmark_irreducible(env, h);\n+\t\t\t}\n+\t\t}\n+\t\tstate[cur].next_succ++;\n+\t} while (stack_sz);\n+\n+\treturn 0;\n+}\n+\n+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint idx;\n+\n+\tfor (idx = inner_header; idx \u003e= 0; idx = aux[idx].loop_header)\n+\t\tif (aux[idx].loop_header == outer_header)\n+\t\t\treturn true;\n+\n+\treturn false;\n+}\n+\n+int bpf_compute_loops(struct bpf_verifier_env *env)\n+{\n+\tint i, j, s, t, iloop, sloop, err = 0, len = env-\u003eprog-\u003elen;\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct bpf_backedge *backedge;\n+\tstruct loops_dfs dfs = {};\n+\tstruct bpf_iarray *succ;\n+\tstruct bpf_loop *loop;\n+\n+\tdfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);\n+\tdfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);\n+\tdfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);\n+\tif (!dfs.dfs_pos || !dfs.state || !dfs.stack) {\n+\t\terr = -ENOMEM;\n+\t\tgoto out;\n+\t}\n+\tfor (i = 0; i \u003c len; i++)\n+\t\taux[i].loop_header = -1;\n+\tfor (i = 0; i \u003c env-\u003esubprog_cnt; i++) {\n+\t\terr = compute_loops_in_subprog(env, \u0026dfs, i);\n+\t\tif (err)\n+\t\t\tgoto out;\n+\t}\n+\t/* find latches */\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tloop = aux[i].loop;\n+\t\tif (!loop)\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c loop-\u003ebackedges_cnt; j++) {\n+\t\t\tbackedge = \u0026loop-\u003ebackedges[j];\n+\t\t\tbackedge-\u003elatch = find_dominating_condition(env, backedge-\u003efrom, i);\n+\t\t}\n+\t}\n+\t/* find exits */\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tiloop = aux[i].loop ? i : aux[i].loop_header;\n+\t\tif (iloop \u003c 0)\n+\t\t\tcontinue;\n+\t\tsucc = bpf_insn_successors(env, i);\n+\t\tiarray_for_each(s, succ) {\n+\t\t\t/*\n+\t\t\t * Nothing left to record once the innermost loop of 'i'\n+\t\t\t * overflowed: the walk below would stop at it right away.\n+\t\t\t */\n+\t\t\tif (aux[iloop].loop-\u003eexits_overflow)\n+\t\t\t\tbreak;\n+\t\t\tsloop = aux[s].loop ? s : aux[s].loop_header;\n+\t\t\tif (iloop == sloop)\n+\t\t\t\tcontinue;\n+\t\t\tif (bpf_is_nested_loop(env, sloop, iloop))\n+\t\t\t\tcontinue;\n+\t\t\t/*\n+\t\t\t * At this point 'sloop' is either -1, an outer loop,\n+\t\t\t * or a loop in another branch of the loop hierarchy.\n+\t\t\t */\n+\t\t\tfor (t = iloop; t \u003e= 0 \u0026\u0026 t != sloop; t = aux[t].loop_header) {\n+\t\t\t\t/*\n+\t\t\t\t * Account for the following configuration:\n+\t\t\t\t *\n+\t\t\t\t * tloop {\n+\t\t\t\t * iloop {\n+\t\t\t\t * ... i: goto s;\n+\t\t\t\t * }\n+\t\t\t\t * sloop {\n+\t\t\t\t * s:\n+\t\t\t\t * ...\n+\t\t\t\t * }\n+\t\t\t\t * }\n+\t\t\t\t */\n+\t\t\t\tif (bpf_is_nested_loop(env, sloop, t))\n+\t\t\t\t\tbreak;\n+\t\t\t\t/*\n+\t\t\t\t * Record edges i -\u003e s as exits from tloop when:\n+\t\t\t\t *\n+\t\t\t\t * sloop {\n+\t\t\t\t * tloop {\n+\t\t\t\t * iloop {\n+\t\t\t\t * ... i: goto s;\n+\t\t\t\t * }\n+\t\t\t\t * }\n+\t\t\t\t * s: ...\n+\t\t\t\t * }\n+\t\t\t\t */\n+\t\t\t\t/* Enclosing loops inherit the overflow, see below */\n+\t\t\t\tif (aux[t].loop-\u003eexits_overflow)\n+\t\t\t\t\tbreak;\n+\t\t\t\terr = add_exit(aux[t].loop, i, s);\n+\t\t\t\tif (err)\n+\t\t\t\t\tgoto out;\n+\t\t\t}\n+\t\t}\n+\t\tif (bpf_is_ldimm64(env-\u003eprog-\u003einsnsi + i))\n+\t\t\ti++;\n+\t}\n+\t/* A nested loop with a truncated exit list can't be abstracted by SCEV */\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tloop = aux[i].loop;\n+\t\tif (!loop || !loop-\u003eexits_overflow)\n+\t\t\tcontinue;\n+\t\tfor (t = aux[i].loop_header; t \u003e= 0; t = aux[t].loop_header)\n+\t\t\taux[t].loop-\u003eexits_overflow = true;\n+\t}\n+\n+\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2) {\n+\t\tfor (i = 0; i \u003c len; i++) {\n+\t\t\tloop = aux[i].loop;\n+\t\t\tif (!loop)\n+\t\t\t\tcontinue;\n+\t\t\tbpf_log(log, \"loop at %d\", i);\n+\t\t\tif (aux[i].loop_header \u003e= 0)\n+\t\t\t\tbpf_log(log, \", nested in %d\", aux[i].loop_header);\n+\t\t\tif (loop-\u003eirreducible)\n+\t\t\t\tbpf_log(log, \", irreducible\");\n+\t\t\tif (loop-\u003eexits_overflow)\n+\t\t\t\tbpf_log(log, \", too many exits\");\n+\t\t\tbpf_log(log, \"\\n\");\n+\t\t\tfor (j = 0; j \u003c loop-\u003ebackedges_cnt; j++)\n+\t\t\t\tbpf_log(log, \" backedge from %d, latch at %d\\n\",\n+\t\t\t\t\tloop-\u003ebackedges[j].from, loop-\u003ebackedges[j].latch);\n+\t\t\tfor (j = 0; j \u003c loop-\u003eexits_cnt; j++)\n+\t\t\t\tbpf_log(log, \" exit from %d to %d\\n\",\n+\t\t\t\t\tloop-\u003eexits[j].from, loop-\u003eexits[j].to);\n+\t\t}\n+\t}\n+\n+out:\n+\tkvfree(dfs.dfs_pos);\n+\tkvfree(dfs.stack);\n+\tkvfree(dfs.state);\n+\treturn err;\n+}\ndiff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c\nnew file mode 100644\nindex 0000000000000..1fa6b25a4f291\n--- /dev/null\n+++ b/kernel/bpf/scev.c\n@@ -0,0 +1,2246 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */\n+\n+#include \"linux/cnum.h\"\n+#include \u003clinux/bpf_verifier.h\u003e\n+#include \u003clinux/jhash.h\u003e\n+#include \u003clinux/bug.h\u003e\n+#include \u003clinux/tnum.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+\n+#define REGS_NUM BPF_SCEV_REGS_NUM\n+#define UNKNOWN_EXPR_ID 0\n+#define OPAQUE_EXPR_ID 1\n+\n+/*\n+ * BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.\n+ * For scalar evolution purpose we want to reuse most of the opcode definitions,\n+ * but also add a few custom operations (REG and IMM).\n+ * Use the enum below to uniformly represent all operations relevant for SCEV.\n+ */\n+enum expr_op {\n+\t/* leave range 0..255 for standard bpf opcodes */\n+\tUNKNOWN = 256, /* start custom opcodes from the second byte */\n+\tREG,\n+\tIMM,\n+\tSDIV, SMOD,\n+\tSEXT8, SEXT16, SEXT32,\n+\tZEXT8, ZEXT16, ZEXT32,\n+\tBSWAP16, BSWAP32, BSWAP64,\n+\t/* during the loop body execution the value can be either of param[0] or param[1] */\n+\tANY,\n+\t/* some value that verifier is not going to track precisely */\n+\tOPAQUE,\n+\t/* '*(u8/16/32 *)(r10 + X) = Y' writes define slot contents only partially */\n+\tSPILL8, SPILL16, SPILL32,\n+\t/*\n+\t * SCEV expression corresponding to linear equation 'param[0] + param[1] * k',\n+\t * where k is a loop iteration number. Loop here refers to innermost loop\n+\t * containing instruction associated with this expression, as returned by\n+\t * bpf_loop_at_index().\n+\t */\n+\tLINEAR_SCEV,\n+};\n+\n+struct expr {\n+\tu32 op;\n+\tunion {\n+\t\tu32 params[2];\n+\t\ts64 imm;\n+\t};\n+};\n+\n+struct expr_bucket {\n+\tu32 cnt;\n+\tu32 cap;\n+\tu32 ids[];\n+};\n+\n+struct env {\n+\tbool empty;\n+\tu32 reg2expr[REGS_NUM];\n+\tu32 reg2scev[REGS_NUM];\n+};\n+\n+struct insn_envs {\n+\tu32 cnt;\n+\tstruct {\n+\t\tint loop_header;\n+\t\tstruct env *env;\n+\t} entries[];\n+};\n+\n+#define NUM_BUCKETS 256\n+#define EXPR_STACK_DEPTH 8\n+\n+struct expr_stack_elt {\n+\tu32 id:28;\n+\tu32 pre:1;\n+\tu32 next_param:2;\n+};\n+\n+struct scev {\n+\t/*\n+\t * Expressions are identified by id, exprs_ht ensures that\n+ * each expression exists as a unique instance.\n+\t * This allows for fast equivalence check: id1 === id2.\n+\t */\n+\tstruct expr_bucket *exprs_ht[NUM_BUCKETS]; // Don't want to add struct hlist_node to expr\n+\tstruct bpf_min_heap worklist;\n+\tstruct insn_envs **envs;\n+\tstruct expr *exprs;\n+\t/*\n+\t * Loops are analyzed one by one, this array keeps track if a particular\n+\t * instruction was visited on a current pass.\n+\t */\n+\tu32 *discovered;\n+\tint exprs_cnt;\n+\tint exprs_cap;\n+\tint envs_cnt;\n+\tint stack_sz;\n+\tstruct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];\n+\tu32 ids_buf[EXPR_STACK_DEPTH];\n+};\n+\n+static u32 expr_hash(struct expr *e)\n+{\n+\treturn jhash_3words(e-\u003eop, e-\u003eparams[0], e-\u003eparams[1], 0);\n+}\n+\n+static int expr_eq(struct expr *a, struct expr *b)\n+{\n+\treturn a-\u003eop == b-\u003eop \u0026\u0026 a-\u003eimm == b-\u003eimm;\n+}\n+\n+static int add_expr(struct scev *scev, struct expr e)\n+{\n+\tstruct expr_bucket *bucket;\n+\tu32 i, id, hash, new_cap;\n+\tvoid *tmp;\n+\n+\thash = expr_hash(\u0026e) % NUM_BUCKETS;\n+\tbucket = scev-\u003eexprs_ht[hash];\n+\n+\tif (bucket) {\n+\t\tfor (i = 0; i \u003c bucket-\u003ecnt; i++) {\n+\t\t\tid = bucket-\u003eids[i];\n+\t\t\tif (expr_eq(\u0026e, \u0026scev-\u003eexprs[id]))\n+\t\t\t\treturn id;\n+\t\t}\n+\t}\n+\n+\tif (!bucket || bucket-\u003ecap == bucket-\u003ecnt) {\n+\t\tnew_cap = bucket ? bucket-\u003ecap * 2 : 32;\n+\t\tbucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);\n+\t\tif (!bucket)\n+\t\t\treturn -ENOMEM;\n+\t\tscev-\u003eexprs_ht[hash] = bucket;\n+\t\tbucket-\u003ecap = new_cap;\n+\t}\n+\n+\tif (scev-\u003eexprs_cnt == scev-\u003eexprs_cap) {\n+\t\tnew_cap = scev-\u003eexprs_cap + 256;\n+\t\ttmp = kvrealloc(scev-\u003eexprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);\n+\t\tif (!tmp)\n+\t\t\treturn -ENOMEM;\n+\t\tscev-\u003eexprs = tmp;\n+\t\tscev-\u003eexprs_cap = new_cap;\n+\t}\n+\n+\tid = scev-\u003eexprs_cnt++;\n+\tscev-\u003eexprs[id] = e;\n+\tbucket-\u003eids[bucket-\u003ecnt++] = id;\n+\treturn id;\n+}\n+\n+static int expr2(struct scev *scev, u32 op, int a, int b)\n+{\n+\tif (a \u003c 0)\n+\t\treturn a;\n+\tif (b \u003c 0)\n+\t\treturn b;\n+\treturn add_expr(scev, (struct expr){ .op = op, .params = {a, b} });\n+}\n+\n+static int expr1(struct scev *scev, u32 op, int a)\n+{\n+\tif (a \u003c 0)\n+\t\treturn a;\n+\treturn expr2(scev, op, a, 0);\n+}\n+\n+static int expr0(struct scev *scev, u32 op)\n+{\n+\treturn expr2(scev, op, 0, 0);\n+}\n+\n+static bool is_expr1(struct expr *expr, u32 op, int a)\n+{\n+\treturn expr-\u003eop == op \u0026\u0026 expr-\u003eparams[0] == a;\n+}\n+\n+static int imm_expr(struct scev *scev, s64 value)\n+{\n+\treturn add_expr(scev, (struct expr){ .op = IMM, .imm = value });\n+}\n+\n+static bool same_exprs(struct scev *scev, int id_a, int id_b)\n+{\n+\treturn id_a == id_b;\n+}\n+\n+static bool is_imm(struct scev *scev, int id, s64 *imm)\n+{\n+\tif (scev-\u003eexprs[id].op != IMM)\n+\t\treturn false;\n+\t*imm = scev-\u003eexprs[id].imm;\n+\treturn true;\n+}\n+\n+static bool is_op(struct scev *scev, int id, u32 op)\n+{\n+\tif (scev-\u003eexprs[id].op != op)\n+\t\treturn false;\n+\treturn true;\n+}\n+\n+static bool is_unop(struct scev *scev, enum expr_op op, int id, u32 *p0)\n+{\n+\tif (scev-\u003eexprs[id].op != op)\n+\t\treturn false;\n+\t*p0 = scev-\u003eexprs[id].params[0];\n+\treturn true;\n+}\n+\n+static bool is_binop(struct scev *scev, enum expr_op op, int id, u32 *p0, u32 *p1)\n+{\n+\tif (scev-\u003eexprs[id].op != op)\n+\t\treturn false;\n+\t*p0 = scev-\u003eexprs[id].params[0];\n+\t*p1 = scev-\u003eexprs[id].params[1];\n+\treturn true;\n+}\n+\n+static bool is_reg(struct scev *scev, int id, u32 *reg)\n+{\n+\treturn is_unop(scev, REG, id, reg);\n+}\n+\n+static bool is_add(struct scev *scev, int id, u32 *left, u32 *right)\n+{\n+\treturn is_binop(scev, BPF_ADD, id, left, right);\n+}\n+\n+static bool is_zext32(struct scev *scev, int id, u32 *left)\n+{\n+\treturn is_unop(scev, ZEXT32, id, left);\n+}\n+\n+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)\n+{\n+\treturn is_binop(scev, ANY, id, left, right);\n+}\n+\n+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)\n+{\n+\treturn is_binop(scev, LINEAR_SCEV, id, base, slope);\n+}\n+\n+static bool is_opaque(struct scev *scev, int id)\n+{\n+\treturn is_op(scev, id, OPAQUE);\n+}\n+\n+static void log_reg(struct bpf_verifier_env *env, u32 reg)\n+{\n+\tif (reg \u003c MAX_BPF_REG)\n+\t\tbpf_log(\u0026env-\u003elog, \"r%d\", reg);\n+\telse\n+\t\tbpf_log(\u0026env-\u003elog, \"*fp%d\", (MAX_BPF_REG - reg - 1) * 8);\n+}\n+\n+static const char *op_str(u32 op)\n+{\n+\tswitch (op) {\n+\tcase BPF_ADD: return \"+\";\n+\tcase BPF_SUB: return \"-\";\n+\tcase BPF_MUL: return \"*\";\n+\tcase BPF_DIV: return \"/\";\n+\tcase SDIV: return \"s/\";\n+\tcase BPF_OR: return \"|\";\n+\tcase BPF_AND: return \"\u0026\";\n+\tcase BPF_LSH: return \"\u003c\u003c\";\n+\tcase BPF_RSH: return \"\u003e\u003e\";\n+\tcase BPF_NEG: return \"-\";\n+\tcase BPF_MOD: return \"%\";\n+\tcase SMOD: return \"s%\";\n+\tcase BPF_XOR: return \"^\";\n+\tcase BPF_ARSH: return \"s\u003e\u003e\";\n+\tcase SEXT8: return \"sext8\";\n+\tcase SEXT16: return \"sext16\";\n+\tcase SEXT32: return \"sext32\";\n+\tcase ZEXT8: return \"zext8\";\n+\tcase ZEXT16: return \"zext16\";\n+\tcase ZEXT32: return \"zext32\";\n+\tcase BSWAP16: return \"bswap16\";\n+\tcase BSWAP32: return \"bswap32\";\n+\tcase BSWAP64: return \"bswap64\";\n+\tcase SPILL8: return \"spill8\";\n+\tcase SPILL16: return \"spill16\";\n+\tcase SPILL32: return \"spill32\";\n+\tcase ANY: return \"any\";\n+\tcase LINEAR_SCEV: return \"linear\";\n+\t}\n+\treturn NULL;\n+}\n+\n+static u32 op_params_num(u32 op)\n+{\n+\tswitch (op) {\n+\tcase BPF_ADD:\n+\tcase BPF_SUB:\n+\tcase BPF_MUL:\n+\tcase BPF_DIV:\n+\tcase BPF_MOD:\n+\tcase BPF_OR:\n+\tcase BPF_XOR:\n+\tcase BPF_AND:\n+\tcase BPF_LSH:\n+\tcase BPF_RSH:\n+\tcase BPF_ARSH:\n+\tcase SDIV:\n+\tcase SMOD:\n+\tcase ANY:\n+\tcase LINEAR_SCEV:\n+\t\treturn 2;\n+\tcase BPF_NEG:\n+\tcase SEXT8:\n+\tcase SEXT16:\n+\tcase SEXT32:\n+\tcase ZEXT8:\n+\tcase ZEXT16:\n+\tcase ZEXT32:\n+\tcase BSWAP16:\n+\tcase BSWAP32:\n+\tcase BSWAP64:\n+\tcase SPILL8:\n+\tcase SPILL16:\n+\tcase SPILL32:\n+\t\treturn 1;\n+\tcase REG:\n+\tcase IMM:\n+\tcase OPAQUE:\n+\t\treturn 0;\n+\tdefault:\n+\t\treturn 0;\n+\t}\n+}\n+\n+static bool expr_stack_push(struct scev *scev, u32 id)\n+{\n+\tif (scev-\u003estack_sz \u003e= EXPR_STACK_DEPTH)\n+\t\treturn false;\n+\tscev-\u003eexpr_stack[scev-\u003estack_sz].id = id;\n+\tscev-\u003eexpr_stack[scev-\u003estack_sz].pre = true;\n+\tscev-\u003eexpr_stack[scev-\u003estack_sz].next_param = 0;\n+\tscev-\u003estack_sz++;\n+\treturn true;\n+}\n+\n+enum {\n+\tPRE = BIT(1), POST = BIT(2), DEPTH_LIMIT = BIT(3)\n+};\n+\n+static bool expr_next(struct scev *scev, u32 *id, u32 *order)\n+{\n+\tstruct expr_stack_elt *elt;\n+\tstruct expr *expr;\n+\tu32 num_params;\n+\n+\tif (scev-\u003estack_sz == 0)\n+\t\treturn false;\n+\n+\telt = \u0026scev-\u003eexpr_stack[scev-\u003estack_sz - 1];\n+\t*id = elt-\u003eid;\n+\t*order = 0;\n+\texpr = \u0026scev-\u003eexprs[elt-\u003eid];\n+\tnum_params = op_params_num(expr-\u003eop);\n+\tif (elt-\u003epre) {\n+\t\telt-\u003epre = false;\n+\t\t*order = PRE;\n+\t\treturn true;\n+\t}\n+\tif (elt-\u003enext_param == num_params) {\n+\t\t*order = POST;\n+\t\tscev-\u003estack_sz--;\n+\t\treturn true;\n+\t}\n+\tif (scev-\u003estack_sz == EXPR_STACK_DEPTH) {\n+\t\t*order = POST | DEPTH_LIMIT;\n+\t\tscev-\u003estack_sz--;\n+\t\treturn true;\n+\t}\n+\texpr_stack_push(scev, expr-\u003eparams[elt-\u003enext_param]);\n+\telt-\u003enext_param++;\n+\treturn expr_next(scev, id, order);\n+}\n+\n+static void log_expr(struct bpf_verifier_env *env, u32 id)\n+{\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct expr *expr;\n+\tconst char *str;\n+\tu32 order;\n+\n+\tscev-\u003estack_sz = 0;\n+\texpr_stack_push(scev, id);\n+\twhile (expr_next(scev, \u0026id, \u0026order)) {\n+\t\tif ((order \u0026 PRE) \u0026\u0026 scev-\u003estack_sz \u003e 1)\n+\t\t\tbpf_log(log, \" \");\n+\t\texpr = \u0026scev-\u003eexprs[id];\n+\t\tswitch (expr-\u003eop) {\n+\t\tcase UNKNOWN:\n+\t\t\tif (order \u0026 PRE)\n+\t\t\t\tbpf_log(log, \"?\");\n+\t\t\tbreak;\n+\t\tcase OPAQUE:\n+\t\t\tif (order \u0026 PRE)\n+\t\t\t\tbpf_log(log, \"_\");\n+\t\t\tbreak;\n+\t\tcase REG:\n+\t\t\tif (order \u0026 PRE)\n+\t\t\t\tlog_reg(env, expr-\u003eparams[0]);\n+\t\t\tbreak;\n+\t\tcase IMM:\n+\t\t\tif (order \u0026 PRE)\n+\t\t\t\tbpf_log(log, \"%lld\", expr-\u003eimm);\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\tif (order \u0026 PRE) {\n+\t\t\t\tstr = op_str(expr-\u003eop);\n+\t\t\t\tbpf_log(log, \"(\");\n+\t\t\t\tif (str)\n+\t\t\t\t\tbpf_log(log, \"%s\", str);\n+\t\t\t\telse\n+\t\t\t\t\tbpf_log(log, \"bad-expr-op %x\", expr-\u003eop);\n+\t\t\t}\n+\t\t\tif (order \u0026 DEPTH_LIMIT)\n+\t\t\t\tbpf_log(log, \"...\");\n+\t\t\tif (order \u0026 POST)\n+\t\t\t\tbpf_log(log, \")\");\n+\t\t}\n+\t}\n+}\n+\n+enum print_env_flags {\n+\tPRINT_SCEV = BIT(1)\n+};\n+\n+static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tu16 live_regs = aux[insn_idx].live_regs_before;\n+\n+\treturn reg \u003c MAX_BPF_REG\n+\t ? (BIT(reg) \u0026 live_regs)\n+\t : test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);\n+}\n+\n+static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx, u32 flags)\n+{\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tbool printed_some = false;\n+\tbool print_scev = flags \u0026 PRINT_SCEV;\n+\tbool is_self_scev;\n+\tbool is_self_reg;\n+\tint i, r;\n+\n+\tif (e-\u003eempty) {\n+\t\tbpf_log(log, \" \u003cempty\u003e\\n\");\n+\t\treturn;\n+\t}\n+\n+\tfor (i = 0; i \u003c REGS_NUM; i++) {\n+\t\tif (!reg_alive_at(env, i, insn_idx))\n+\t\t\tcontinue;\n+\t\tis_self_reg = is_reg(scev, e-\u003ereg2expr[i], \u0026r) \u0026\u0026 i == r;\n+\t\tis_self_scev = is_reg(scev, e-\u003ereg2scev[i], \u0026r) \u0026\u0026 i == r;\n+\t\tif (is_self_reg \u0026\u0026 (!print_scev || is_self_scev))\n+\t\t\tcontinue;\n+\t\tprinted_some = true;\n+\t\tbpf_log(log, \" \");\n+\t\tlog_reg(env, i);\n+\t\tbpf_log(log, \"=\");\n+\t\tlog_expr(env, e-\u003ereg2expr[i]);\n+\t\tif (print_scev \u0026\u0026 e-\u003ereg2expr[i] != UNKNOWN_EXPR_ID) {\n+\t\t\tbpf_log(log, \" / \");\n+\t\t\tlog_expr(env, e-\u003ereg2scev[i]);\n+\t\t}\n+\t\tbpf_log(log, \"\\n\");\n+\t}\n+\tif (!printed_some)\n+\t\tbpf_log(log, \" \u003call regs unchanged\u003e\\n\");\n+}\n+static struct env *find_loop_env(struct scev *scev, int loop_header, int insn_idx)\n+{\n+\tstruct insn_envs *envs = scev-\u003eenvs[insn_idx];\n+\tu32 i;\n+\n+\tif (!envs)\n+\t\treturn NULL;\n+\tfor (i = 0; i \u003c envs-\u003ecnt; i++)\n+\t\tif (envs-\u003eentries[i].loop_header == loop_header)\n+\t\t\treturn envs-\u003eentries[i].env;\n+\treturn NULL;\n+}\n+\n+static struct env *find_header_env(struct scev *scev, int header)\n+{\n+\treturn find_loop_env(scev, header, header);\n+}\n+\n+static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx)\n+{\n+\tstruct insn_envs *envs = scev-\u003eenvs[insn_idx];\n+\tu32 cnt = envs ? envs-\u003ecnt : 0;\n+\tstruct insn_envs *tmp;\n+\tstruct env *e;\n+\n+\te = find_loop_env(scev, loop_header, insn_idx);\n+\tif (e)\n+\t\treturn e;\n+\n+\te = kzalloc(sizeof(*e), GFP_KERNEL_ACCOUNT);\n+\tif (!e)\n+\t\treturn NULL;\n+\n+\ttmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);\n+\tif (!tmp) {\n+\t\tkfree(e);\n+\t\treturn NULL;\n+\t}\n+\n+\te-\u003eempty = true;\n+\ttmp-\u003eentries[cnt].loop_header = loop_header;\n+\ttmp-\u003eentries[cnt].env = e;\n+\ttmp-\u003ecnt = cnt + 1;\n+\tscev-\u003eenvs[insn_idx] = tmp;\n+\treturn e;\n+}\n+\n+static void setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tint i;\n+\n+\tfor (i = 0; i \u003c REGS_NUM; i++)\n+\t\te-\u003ereg2expr[i] = expr1(scev, REG, i);\n+}\n+\n+static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)\n+{\n+\tif (id \u003c 0)\n+\t\treturn id;\n+\te-\u003ereg2expr[reg] = id;\n+\treturn 0;\n+}\n+\n+static void forget_call_regs(struct env *e)\n+{\n+\tint i;\n+\n+\tfor (i = BPF_REG_0; i \u003c= BPF_REG_5; i++)\n+\t\te-\u003ereg2expr[i] = UNKNOWN_EXPR_ID;\n+}\n+\n+static u32 spill_spi(struct bpf_insn *insn)\n+{\n+\treturn -insn-\u003eoff / BPF_REG_SIZE - 1;\n+}\n+\n+static u32 off_to_reg(struct bpf_insn *insn)\n+{\n+\treturn spill_spi(insn) + MAX_BPF_REG;\n+}\n+\n+static bool is_spill_off(int off)\n+{\n+\treturn off % BPF_REG_SIZE == 0 \u0026\u0026\n+\t off \u003c= -BPF_REG_SIZE \u0026\u0026\n+\t off \u003e= -MAX_BPF_STACK_JIT;\n+}\n+\n+static void mark_opaque(struct env *e, int off, int size)\n+{\n+\tint b, spi;\n+\n+\tfor (b = off; b \u003c off + size; b++) {\n+\t\tif (b \u003e= 0 || b \u003c -MAX_BPF_STACK_JIT)\n+\t\t\tcontinue;\n+\t\tspi = (-b - 1) / BPF_REG_SIZE;\n+\t\te-\u003ereg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;\n+\t}\n+}\n+\n+static int mk_spill(struct scev *scev, u8 size, int id)\n+{\n+\tswitch (size) {\n+\tcase BPF_B: return expr1(scev, SPILL8, id);\n+\tcase BPF_H: return expr1(scev, SPILL16, id);\n+\tcase BPF_W: return expr1(scev, SPILL32, id);\n+\tcase BPF_DW: return id;\n+\t}\n+\treturn UNKNOWN_EXPR_ID;\n+}\n+\n+static int mk_fill(struct scev *scev, int id, u8 code)\n+{\n+\tbool sx = BPF_MODE(code) == BPF_MEMSX;\n+\n+\tswitch (BPF_SIZE(code)) {\n+\tcase BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);\n+\tcase BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);\n+\tcase BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);\n+\tcase BPF_DW: return sx ? UNKNOWN_EXPR_ID : id; /* DW sign-extended load is invalid */\n+\t}\n+\treturn UNKNOWN_EXPR_ID;\n+}\n+\n+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)\n+{\n+\tu8 size = BPF_SIZE(insn-\u003ecode);\n+\n+\tif (insn-\u003edst_reg != BPF_REG_FP)\n+\t\treturn 0;\n+\tif (is_spill_off(insn-\u003eoff))\n+\t\treturn replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));\n+\tmark_opaque(e, insn-\u003eoff, bpf_size_to_bytes(size));\n+\treturn 0;\n+}\n+\n+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)\n+{\n+\tint id;\n+\n+\tif (insn-\u003esrc_reg == BPF_REG_FP \u0026\u0026 is_spill_off(insn-\u003eoff))\n+\t\tid = mk_fill(scev, e-\u003ereg2expr[off_to_reg(insn)], insn-\u003ecode);\n+\telse\n+\t\tid = OPAQUE_EXPR_ID;\n+\treturn replace_reg(scev, e, insn-\u003edst_reg, id);\n+}\n+\n+static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)\n+{\n+\tconst bool little_endian = htons(0x3412) == 0x1234;\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 *reg2expr = e-\u003ereg2expr;\n+\tu8 class = BPF_CLASS(insn-\u003ecode);\n+\tu8 x_or_k = BPF_SRC(insn-\u003ecode);\n+\tu8 opcode = BPF_OP(insn-\u003ecode);\n+\tu8 mode = BPF_MODE(insn-\u003ecode);\n+\tu32 dst = insn-\u003edst_reg;\n+\tu32 src = insn-\u003esrc_reg;\n+\tu32 op, sext;\n+\tint i, id;\n+\ts64 imm;\n+\n+\tswitch (class) {\n+\tcase BPF_ALU:\n+\tcase BPF_ALU64:\n+\t\tswitch (opcode) {\n+\t\tcase BPF_MOV:\n+\t\t\tswitch (insn-\u003eoff) {\n+\t\t\tcase 0: sext = 0; break;\n+\t\t\tcase 8: sext = SEXT8; break;\n+\t\t\tcase 16: sext = SEXT16; break;\n+\t\t\tcase 32: sext = SEXT32; break;\n+\t\t\tdefault:\n+\t\t\t\tgoto mark_dst_unknown;\n+\t\t\t}\n+\n+\t\t\tif (x_or_k == BPF_X \u0026\u0026 insn-\u003eimm == 0)\n+\t\t\t\tid = reg2expr[src];\n+\t\t\telse if (x_or_k == BPF_K \u0026\u0026 src == 0 \u0026\u0026 insn-\u003eoff == 0)\n+\t\t\t\tid = imm_expr(scev, insn-\u003eimm);\n+\t\t\telse\n+\t\t\t\tgoto mark_dst_unknown;\n+\n+\t\t\tif (sext)\n+\t\t\t\tid = expr1(scev, sext, id);\n+\t\t\tif (class == BPF_ALU)\n+\t\t\t\tid = expr1(scev, ZEXT32, id);\n+\n+\t\t\treturn replace_reg(scev, e, dst, id);\n+\n+\t\tcase BPF_ADD:\n+\t\tcase BPF_SUB:\n+\t\tcase BPF_MUL:\n+\t\tcase BPF_DIV:\n+\t\tcase BPF_MOD:\n+\t\tcase BPF_OR:\n+\t\tcase BPF_XOR:\n+\t\tcase BPF_AND:\n+\t\tcase BPF_LSH:\n+\t\tcase BPF_RSH:\n+\t\tcase BPF_ARSH:\n+\t\t\tif (opcode == BPF_DIV \u0026\u0026 insn-\u003eoff == 1)\n+\t\t\t\top = SDIV;\n+\t\t\telse if (opcode == BPF_MOD \u0026\u0026 insn-\u003eoff == 1)\n+\t\t\t\top = SMOD;\n+\t\t\telse if (insn-\u003eoff == 0)\n+\t\t\t\top = opcode;\n+\t\t\telse\n+\t\t\t\tgoto mark_dst_unknown;\n+\n+\t\t\tif (x_or_k == BPF_X \u0026\u0026 insn-\u003eimm == 0)\n+\t\t\t\tid = reg2expr[src];\n+\t\t\telse if (x_or_k == BPF_K \u0026\u0026 src == 0)\n+\t\t\t\tid = imm_expr(scev, insn-\u003eimm);\n+\t\t\telse\n+\t\t\t\tgoto mark_dst_unknown;\n+\n+\t\t\tid = expr2(scev, op, reg2expr[dst], id);\n+\n+\t\t\tif (class == BPF_ALU)\n+\t\t\t\tid = expr1(scev, ZEXT32, id);\n+\n+\t\t\treturn replace_reg(scev, e, dst, id);\n+\n+\t\tcase BPF_NEG:\n+\t\t\tif (src == 0 \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026 insn-\u003eimm == 0)\n+\t\t\t\tid = expr1(scev, BPF_NEG, reg2expr[dst]);\n+\t\t\telse\n+\t\t\t\tgoto mark_dst_unknown;\n+\n+\t\t\tif (class == BPF_ALU)\n+\t\t\t\tid = expr1(scev, ZEXT32, id);\n+\n+\t\t\treturn replace_reg(scev, e, dst, id);\n+\n+\t\tcase BPF_END:\n+\t\t\tswitch (insn-\u003eimm) {\n+\t\t\tcase 16: op = BSWAP16; break;\n+\t\t\tcase 32: op = BSWAP32; break;\n+\t\t\tcase 64: op = BSWAP64; break;\n+\t\t\tdefault:\n+\t\t\t\tgoto mark_dst_unknown;\n+\t\t\t}\n+\n+\t\t\tif (class == BPF_ALU \u0026\u0026 x_or_k == BPF_TO_LE \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026 little_endian)\n+\t\t\t\top = 0; /* little-endian to little-endian is noop */\n+\t\t\telse if (class == BPF_ALU \u0026\u0026 x_or_k == BPF_TO_BE \u0026\u0026 insn-\u003eoff == 0 \u0026\u0026 !little_endian)\n+\t\t\t\top = 0; /* big-endian to big-endian is noop */\n+\t\t\telse if (class == BPF_ALU64 \u0026\u0026 x_or_k == 0 \u0026\u0026 insn-\u003eoff == 0)\n+\t\t\t\t/* always swap */;\n+\t\t\telse\n+\t\t\t\tgoto mark_dst_unknown;\n+\n+\t\t\tid = reg2expr[dst];\n+\t\t\tif (op)\n+\t\t\t\tid = expr1(scev, op, reg2expr[dst]);\n+\n+\t\t\tif (class == BPF_ALU)\n+\t\t\t\tid = expr1(scev, ZEXT32, id);\n+\n+\t\t\treturn replace_reg(scev, e, dst, id);\n+\t\tdefault:\n+\t\t\tgoto mark_dst_unknown;\n+\t\t}\n+\t\tbreak;\n+\tcase BPF_LDX:\n+\t\tswitch (mode) {\n+\t\tcase BPF_MEM:\n+\t\tcase BPF_MEMSX:\n+\t\t\treturn maybe_load_fp(scev, e, insn);\n+\t\tdefault:\n+\t\t\tgoto mark_dst_unknown;\n+\t\t}\n+\tcase BPF_STX:\n+\t\tswitch (mode) {\n+\t\tcase BPF_MEM:\n+\t\t\treturn maybe_store_fp(scev, e, insn, reg2expr[src]);\n+\t\tcase BPF_ATOMIC:\n+\t\t\tif (insn-\u003eimm == BPF_LOAD_ACQ)\n+\t\t\t\treturn maybe_load_fp(scev, e, insn);\n+\t\t\tif (insn-\u003eimm == BPF_STORE_REL) {\n+\t\t\t\treturn maybe_store_fp(scev, e, insn, reg2expr[src]);\n+\t\t\t}\n+\t\t\t/*\n+\t\t\t * verifier does not track other atomic ops precisely,\n+\t\t\t * hence mark the results as opaque.\n+\t\t\t */\n+\t\t\tif (insn-\u003edst_reg == BPF_REG_FP)\n+\t\t\t\tmark_opaque(e, insn-\u003eoff, bpf_size_to_bytes(BPF_SIZE(insn-\u003ecode)));\n+\t\t\tif (insn-\u003eimm == BPF_CMPXCHG)\n+\t\t\t\treturn replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);\n+\t\t\tif (insn-\u003eimm \u0026 BPF_FETCH)\n+\t\t\t\treturn replace_reg(scev, e, src, OPAQUE_EXPR_ID);\n+\t\t\tbreak;\n+\t\t}\n+\t\tbreak;\n+\tcase BPF_ST:\n+\t\tif (insn-\u003edst_reg == BPF_REG_FP) {\n+\t\t\tid = imm_expr(scev, insn-\u003eimm);\n+\t\t\tif (id \u003c 0)\n+\t\t\t\treturn id;\n+\t\t\treturn maybe_store_fp(scev, e, insn, id);\n+\t\t}\n+\t\tbreak;\n+\tcase BPF_JMP:\n+\tcase BPF_JMP32:\n+\t\tif (opcode == BPF_CALL)\n+\t\t\tforget_call_regs(e);\n+\t\t/* for non-CALL there are no changes in register states */\n+\t\tbreak;\n+\tcase BPF_LD:\n+\t\tswitch (mode) {\n+\t\tcase BPF_IMM:\n+\t\t\t/* rX = imm ll */\n+\t\t\tif (BPF_SIZE(insn-\u003ecode) == BPF_DW \u0026\u0026 insn-\u003esrc_reg == 0) {\n+\t\t\t\timm = ((u64)(insn + 1)-\u003eimm \u003c\u003c 32) | (u32)insn-\u003eimm;\n+\t\t\t\treturn replace_reg(scev, e, dst, imm_expr(scev, imm));\n+\t\t\t}\n+\t\t\t/* map, map value, BTF id, function */\n+\t\t\tif (BPF_SIZE(insn-\u003ecode) == BPF_DW)\n+\t\t\t\treturn replace_reg(scev, e, dst, OPAQUE_EXPR_ID);\n+\t\t\tgoto mark_dst_unknown;\n+\t\tcase BPF_ABS:\n+\t\tcase BPF_IND:\n+\t\t\tforget_call_regs(e);\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\tgoto mark_dst_unknown;\n+\t\t}\n+\t\tbreak;\n+\tdefault:\n+\t\t/* unknown instruction, nuke state */\n+\t\tfor (i = 0; i \u003c REGS_NUM; i++)\n+\t\t\treg2expr[i] = UNKNOWN_EXPR_ID;\n+\t\tbreak;\n+\t}\n+\treturn 0;\n+\n+mark_dst_unknown:\n+\treg2expr[dst] = UNKNOWN_EXPR_ID;\n+\treturn 0;\n+}\n+\n+/*\n+ * Construct minimal 'ANY' expression by traversing 'a' and 'b'\n+ * and accumulating non-duplicated non-ANY entries.\n+ */\n+static int mk_any(struct scev *scev, u32 a, u32 b)\n+{\n+\tstruct expr_stack_elt *elt;\n+\tstruct expr *expr;\n+\tu32 i, j, ids_buf_sz;\n+\tu32 roots[2] = {a, b};\n+\tint id;\n+\n+\tids_buf_sz = 0;\n+\tfor (i = 0; i \u003c ARRAY_SIZE(roots); i++) {\n+\t\tscev-\u003estack_sz = 0;\n+\t\texpr_stack_push(scev, roots[i]);\n+\t\twhile (scev-\u003estack_sz) {\n+\t\t\telt = \u0026scev-\u003eexpr_stack[--scev-\u003estack_sz];\n+\t\t\tid = elt-\u003eid;\n+\t\t\texpr = \u0026scev-\u003eexprs[elt-\u003eid];\n+\t\t\tif (expr-\u003eop == ANY) {\n+\t\t\t\tif (!expr_stack_push(scev, expr-\u003eparams[0]) ||\n+\t\t\t\t !expr_stack_push(scev, expr-\u003eparams[1]))\n+\t\t\t\t\treturn UNKNOWN_EXPR_ID;\n+\t\t\t} else {\n+\t\t\t\tfor (j = 0; j \u003c ids_buf_sz; j++) {\n+\t\t\t\t\tif (same_exprs(scev, scev-\u003eids_buf[j], id))\n+\t\t\t\t\t\tgoto next;\n+\t\t\t\t}\n+\t\t\t\tif (ids_buf_sz == ARRAY_SIZE(scev-\u003eids_buf))\n+\t\t\t\t\treturn UNKNOWN_EXPR_ID;\n+\t\t\t\tscev-\u003eids_buf[ids_buf_sz++] = id;\n+\t\t\t}\n+next:;\n+\t\t}\n+\t}\n+\tif (WARN_ON(ids_buf_sz == 0))\n+\t\treturn -EFAULT;\n+\tid = scev-\u003eids_buf[0];\n+\tfor (i = 1; i \u003c ids_buf_sz; i++) {\n+\t\tid = expr2(scev, ANY, id, scev-\u003eids_buf[i]);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t}\n+\treturn id;\n+}\n+\n+static int join(struct scev *scev, struct env *acc, struct env *cur)\n+{\n+\tint i, id;\n+\n+\tif (acc-\u003eempty) {\n+\t\tmemcpy(acc, cur, sizeof(*acc));\n+\t\tacc-\u003eempty = false;\n+\t\treturn 0;\n+\t}\n+\n+\tfor (i = 0; i \u003c REGS_NUM; i++) {\n+\t\tif (!same_exprs(scev, acc-\u003ereg2expr[i], cur-\u003ereg2expr[i])) {\n+\t\t\tid = mk_any(scev, acc-\u003ereg2expr[i], cur-\u003ereg2expr[i]);\n+\t\t\tif (id \u003c 0)\n+\t\t\t\treturn id;\n+\t\t\tacc-\u003ereg2expr[i] = id;\n+\t\t}\n+\t}\n+\treturn 0;\n+}\n+\n+/* Mark any register modified in 'header_env' as unknown in 'acc'. */\n+static void forget_non_invariants(struct scev *scev, struct env *acc, struct env *header_env)\n+{\n+\tstruct expr *header_expr;\n+\tint i;\n+\n+\tif (acc-\u003eempty)\n+\t\tacc-\u003eempty = false;\n+\n+\tfor (i = 0; i \u003c REGS_NUM; i++) {\n+\t\theader_expr = \u0026scev-\u003eexprs[header_env-\u003ereg2expr[i]];\n+\t\tif (is_expr1(header_expr, REG, i))\n+\t\t\tcontinue;\n+\t\tacc-\u003ereg2expr[i] = UNKNOWN_EXPR_ID;\n+\t}\n+}\n+\n+static int worklist_push(struct scev *scev, int loop_header, int idx)\n+{\n+\tu32 tag = (u32)loop_header + 1;\n+\tint err;\n+\n+\tif (scev-\u003ediscovered[idx] == tag)\n+\t\treturn 0;\n+\n+\terr = bpf_min_heap_push(\u0026scev-\u003eworklist, idx);\n+\tif (err)\n+\t\treturn err;\n+\n+\tscev-\u003ediscovered[idx] = tag;\n+\treturn 0;\n+}\n+\n+static bool reg_alive_at_succ(struct bpf_verifier_env *env, u32 r, u32 insn_idx)\n+{\n+\tstruct bpf_iarray *succ = bpf_insn_successors(env, insn_idx);\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c succ-\u003ecnt; i++)\n+\t\tif (reg_alive_at(env, r, succ-\u003eitems[i]))\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+enum changes_at {\n+\tLOG_AT_TRANSFER,\n+\tLOG_AT_JOIN,\n+};\n+\n+static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,\n+\t\t\t struct env *old, struct env *new, int insn_idx)\n+{\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tu64 null_pos = log-\u003eend_pos;\n+\tbool any_changes = false;\n+\tu32 old_id, new_id;\n+\tu64 len;\n+\tint r;\n+\n+\tbpf_log(log, \"%s %4d: \", at == LOG_AT_TRANSFER ? \"t\" : \"j\", insn_idx);\n+\tbpf_verbose_insn(env, \u0026env-\u003eprog-\u003einsnsi[insn_idx]);\n+\tlen = log-\u003eend_pos - null_pos;\n+\tbpf_log(log, \"%*s\", max(37 - (int)len, 1), \" \");\n+\tbpf_log(log, \" ; \");\n+\tfor (r = 0; r \u003c REGS_NUM; r++) {\n+\t\told_id = old-\u003ereg2expr[r];\n+\t\tnew_id = new-\u003ereg2expr[r];\n+\t\tif (at == LOG_AT_TRANSFER \u0026\u0026 !reg_alive_at_succ(env, r, insn_idx))\n+\t\t\tcontinue;\n+\t\tif (at == LOG_AT_JOIN \u0026\u0026 !reg_alive_at(env, r, insn_idx))\n+\t\t\tcontinue;\n+\t\tif (same_exprs(scev, old_id, new_id))\n+\t\t\tcontinue;\n+\t\tif (any_changes)\n+\t\t\tbpf_log(log, \", \");\n+\t\tlog_reg(env, r);\n+\t\tbpf_log(log, \" \");\n+\t\tlog_expr(env, old_id);\n+\t\tbpf_log(log, \" -\u003e \");\n+\t\tlog_expr(env, new_id);\n+\t\tany_changes = true;\n+\t}\n+\tbpf_log(log, \"\\n\");\n+\tif (!any_changes)\n+\t\tbpf_vlog_reset(log, null_pos);\n+}\n+\n+static bool is_probe_read_helper(u32 func_id)\n+{\n+\treturn func_id == BPF_FUNC_probe_read ||\n+\t func_id == BPF_FUNC_probe_read_kernel ||\n+\t func_id == BPF_FUNC_probe_read_user ||\n+\t func_id == BPF_FUNC_probe_read_str ||\n+\t func_id == BPF_FUNC_probe_read_kernel_str ||\n+\t func_id == BPF_FUNC_probe_read_user_str;\n+}\n+\n+/*\n+ * If instruction is an indirect write to stack, invalidate SCEVs for spi's\n+ * that this instruction can touch.\n+ */\n+static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)\n+{\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tstruct scev *scev = env-\u003escev;\n+\tu8 class = BPF_CLASS(insn-\u003ecode);\n+\tconst unsigned long *mask;\n+\tu32 spi, reg;\n+\tbool opaque;\n+\n+\t/* Direct fp stores are fine. */\n+\tif ((class == BPF_ST || class == BPF_STX) \u0026\u0026 insn-\u003edst_reg == BPF_REG_FP)\n+\t\treturn;\n+\n+\tmask = bpf_may_write_mask(env, idx);\n+\topaque = bpf_helper_call(insn) \u0026\u0026 is_probe_read_helper(insn-\u003eimm);\n+\tfor_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {\n+\t\treg = MAX_BPF_REG + spi;\n+\t\tif (cur_env-\u003ereg2expr[reg] == UNKNOWN_EXPR_ID)\n+\t\t\tcontinue;\n+\t\treplace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);\n+\t}\n+}\n+\n+/* OR the loop-entry registers referenced by expr 'id' into 'mask'. */\n+static void or_expr_regs(struct bpf_verifier_env *env, u32 id, unsigned long *mask)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 order;\n+\n+\tscev-\u003estack_sz = 0;\n+\texpr_stack_push(scev, id);\n+\twhile (expr_next(scev, \u0026id, \u0026order)) {\n+\t\tif ((order \u0026 PRE) \u0026\u0026 scev-\u003eexprs[id].op == REG)\n+\t\t\t__set_bit(scev-\u003eexprs[id].params[0], mask);\n+\t}\n+}\n+\n+/* Mask of argument registers (R1..R5) a call at 'idx' passes by register. */\n+static u16 call_params_mask(struct bpf_verifier_env *env, int idx)\n+{\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tstruct bpf_call_summary cs;\n+\tint n = bpf_get_call_summary(env, insn, \u0026cs) ? cs.arg_slot_cnt : MAX_BPF_FUNC_REG_ARGS;\n+\n+\treturn n ? GENMASK(BPF_REG_1 + n - 1, BPF_REG_1) : 0;\n+}\n+\n+/*\n+ * For instructions like:\n+ * - *(u64 *)(rBase + off) = rX\n+ * - rX = *(u64 *)(rBase + off)\n+ * - calls that construct objects on stack (e.g. dynptr_from_mem(rBase, ...))\n+ * When 'rBase' can be a stack pointer and is derived from some registers Rs\n+ * defined at loop entry, record Rs into 'mask'.\n+ */\n+static void collect_store_base_regs(struct bpf_verifier_env *env,\n+\t\t\t\t struct env *cur_env, int idx, unsigned long *mask)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[idx];\n+\tu8 class = BPF_CLASS(insn-\u003ecode);\n+\tu8 size = BPF_SIZE(insn-\u003ecode);\n+\tu16 base_regs = 0;\n+\tu32 r;\n+\n+\tif (size == BPF_W || size == BPF_DW) {\n+\t\tif ((class == BPF_STX || class == BPF_ST) \u0026\u0026 insn-\u003edst_reg != BPF_REG_FP)\n+\t\t\tbase_regs |= BIT(insn-\u003edst_reg);\n+\t\telse if (class == BPF_LDX \u0026\u0026 insn-\u003esrc_reg != BPF_REG_FP)\n+\t\t\tbase_regs |= BIT(insn-\u003esrc_reg);\n+\t}\n+\n+\tif (class == BPF_JMP \u0026\u0026 BPF_OP(insn-\u003ecode) == BPF_CALL \u0026\u0026\n+\t bpf_needs_fixed_stack_off(env, idx))\n+\t\tbase_regs |= call_params_mask(env, idx);\n+\n+\tbase_regs \u0026= aux[idx].stack_ptrs;\n+\tfor (r = 0; r \u003c MAX_BPF_REG; r++)\n+\t\tif (base_regs \u0026 BIT(r))\n+\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r], mask);\n+}\n+\n+/* Find the topmost loop header containing idx inside cur_header, or -1 if none. */\n+static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_header)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint header;\n+\n+\tfor (header = bpf_loop_at_index(env, idx); header \u003e= 0;\n+\t header = aux[header].loop_header)\n+\t\tif (aux[header].loop_header == cur_header)\n+\t\t\treturn header;\n+\n+\treturn -1;\n+}\n+\n+/*\n+ * Join cur_env into the successor's environment and schedule their traversal.\n+ * Map successors in nested loops to their topmost nested header.\n+ * Ignore successors outside the current loop and its nested loops.\n+ */\n+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,\n+\t\t\t struct env *old_env, struct env *cur_env)\n+{\n+\tbool log_level2 = env-\u003elog.level \u0026 BPF_LOG_LEVEL2;\n+\tstruct scev *scev = env-\u003escev;\n+\tint err, nested_header;\n+\tstruct env *succ_env;\n+\n+\t/*\n+\t * There are several possibilities for a successor:\n+\t * - succ_idx can be a part of a loop outside of the cur_header's loop,\n+\t * such edges are ignored.\n+\t * - succ_idx can be a part of the same loop as cur_header,\n+\t * for such edges succ_idx environment is updated:\n+\t * e[succ_idx] = join(e[succ_idx], cur_env)\n+\t * - succ_idx can be a part of some loop inner to cur_header,\n+\t * in such a case there exists some loop header H,\n+\t * such that H.loop_header == cur_header\n+\t * and H is the same as succ_idx's loop or contains it.\n+\t */\n+\tif (bpf_loop_at_index(env, succ_idx) != cur_header) {\n+\t\t/*\n+\t\t * topmost_nested_loop() either finds H or returns -1,\n+\t\t * in case if succ_idx is a part of a loop outer to cur_header.\n+\t\t */\n+\t\tnested_header = topmost_nested_loop(env, succ_idx, cur_header);\n+\t\tif (nested_header \u003c 0)\n+\t\t\treturn 0;\n+\t\tsucc_idx = nested_header;\n+\t}\n+\tsucc_env = get_loop_env(scev, cur_header, succ_idx);\n+\tif (!succ_env)\n+\t\treturn -ENOMEM;\n+\tif (log_level2)\n+\t\tmemcpy(old_env, succ_env, sizeof(*old_env));\n+\terr = join(scev, succ_env, cur_env);\n+\tif (err)\n+\t\treturn err;\n+\terr = worklist_push(scev, cur_header, succ_idx);\n+\tif (err)\n+\t\treturn err;\n+\tif (log_level2)\n+\t\tlog_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);\n+\treturn 0;\n+}\n+\n+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)\n+{\n+\tstruct bpf_min_heap *worklist = \u0026env-\u003escev-\u003eworklist;\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_loop *cur_loop = aux[cur_header].loop;\n+\tstruct env *header_env, *nested_header_env;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct bpf_loop *nested_loop;\n+\tstruct env *cur_env = NULL;\n+\tstruct env *old_env = NULL;\n+\tstruct bpf_iarray *succ;\n+\tbool log_level2 = env-\u003elog.level \u0026 BPF_LOG_LEVEL2;\n+\tint s, i, err, idx, succ_idx;\n+\tu32 r;\n+\n+\tif (log_level2)\n+\t\tbpf_log(\u0026env-\u003elog, \"Computing SCEV for loop at %d:\\n\", cur_header);\n+\n+\t/*\n+\t * For irreducible loops, and for loops nesting a loop with a truncated\n+\t * exit list, just assume that everything is clobbered for now.\n+\t */\n+\tif (cur_loop-\u003eirreducible || cur_loop-\u003eexits_overflow) {\n+\t\theader_env = get_loop_env(scev, cur_header, cur_header);\n+\t\tif (!header_env)\n+\t\t\treturn -ENOMEM;\n+\t\t/* The freshly allocated environment has all expressions unknown. */\n+\t\tbitmap_fill(cur_loop-\u003estore_base_regs, REGS_NUM);\n+\t\theader_env-\u003eempty = false;\n+\t\treturn 0;\n+\t}\n+\n+\tcur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);\n+\tif (!cur_env)\n+\t\tgoto nomem;\n+\tif (log_level2) {\n+\t\told_env = kzalloc(sizeof(*old_env), GFP_KERNEL_ACCOUNT);\n+\t\tif (!old_env)\n+\t\t\tgoto nomem;\n+\t}\n+\theader_env = get_loop_env(scev, cur_header, cur_header);\n+\tif (!header_env)\n+\t\tgoto nomem;\n+\tsetup_initial_loop_env(env, header_env, cur_header);\n+\terr = worklist_push(scev, cur_header, cur_header);\n+\tif (err)\n+\t\tgoto out;\n+\n+\tfor (;;) {\n+\t\tif (!bpf_min_heap_pop(worklist, \u0026idx))\n+\t\t\tbreak;\n+\n+\t\t/* join_successor() maps nested-loop entries to their representative header. */\n+\t\tnested_loop = idx != cur_header ? aux[idx].loop : NULL;\n+\t\tmemcpy(cur_env, find_loop_env(scev, cur_header, idx), sizeof(*cur_env));\n+\t\tif (nested_loop) {\n+\t\t\t/*\n+\t\t\t * Process nested loop as a single instruction by\n+\t\t\t * forgetting anything non-invariant in the nested loop\n+\t\t\t */\n+\t\t\tif (log_level2)\n+\t\t\t\tmemcpy(old_env, cur_env, sizeof(*old_env));\n+\t\t\t/* Pull the nested loop's stack-store base dependencies up. */\n+\t\t\tfor_each_set_bit(r, nested_loop-\u003estore_base_regs, BPF_SCEV_REGS_NUM)\n+\t\t\t\tor_expr_regs(env, cur_env-\u003ereg2expr[r], cur_loop-\u003estore_base_regs);\n+\t\t\tnested_header_env = find_header_env(scev, idx);\n+\t\t\tforget_non_invariants(scev, cur_env, nested_header_env);\n+\t\t\tif (log_level2)\n+\t\t\t\tlog_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);\n+\t\t\t/*\n+\t\t\t * Treat nested loop exits as successors,\n+\t\t\t * join cur_env into successor's envs.\n+\t\t\t */\n+\t\t\tfor (i = 0; i \u003c nested_loop-\u003eexits_cnt; i++) {\n+\t\t\t\ts = nested_loop-\u003eexits[i].to;\n+\t\t\t\terr = join_successor(env, cur_header, s, old_env, cur_env);\n+\t\t\t\tif (err)\n+\t\t\t\t\tgoto out;\n+\t\t\t}\n+\t\t} else {\n+\t\t\t/*\n+\t\t\t * Iterate instructions within a single basic block\n+\t\t\t * starting at 'idx' mutating 'cur_env'.\n+\t\t\t */\n+\t\t\tfor (;;) {\n+\t\t\t\tif (log_level2)\n+\t\t\t\t\tmemcpy(old_env, cur_env, sizeof(*old_env));\n+\t\t\t\tcollect_store_base_regs(env, cur_env, idx, cur_loop-\u003estore_base_regs);\n+\t\t\t\terr = transfer(env, cur_env, idx);\n+\t\t\t\tif (err)\n+\t\t\t\t\tgoto out;\n+\t\t\t\treset_scevs_at_indirect_writes(env, cur_env, idx);\n+\t\t\t\tif (log_level2)\n+\t\t\t\t\tlog_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);\n+\t\t\t\tsucc = bpf_insn_successors(env, idx);\n+\t\t\t\tif (succ-\u003ecnt != 1)\n+\t\t\t\t\tbreak;\n+\t\t\t\tsucc_idx = succ-\u003eitems[0];\n+\t\t\t\tif (aux[idx].bb_end || aux[succ_idx].need_scev ||\n+\t\t\t\t bpf_loop_at_index(env, succ_idx) != cur_header)\n+\t\t\t\t\tbreak;\n+\t\t\t\tidx = succ_idx;\n+\t\t\t}\n+\t\t\t/* Join cur_env into basic block successor's envs. */\n+\t\t\tiarray_for_each(s, succ) {\n+\t\t\t\terr = join_successor(env, cur_header, s, old_env, cur_env);\n+\t\t\t\tif (err)\n+\t\t\t\t\tgoto out;\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\terr = 0;\n+out:\n+\tkfree(cur_env);\n+\tkfree(old_env);\n+\treturn err;\n+nomem:\n+\terr = -ENOMEM;\n+\tgoto out;\n+}\n+\n+static void mark_latches(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_loop *loop;\n+\tint len = env-\u003eprog-\u003elen;\n+\tint i, j, latch;\n+\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tloop = aux[i].loop;\n+\t\tif (!loop)\n+\t\t\tcontinue;\n+\t\taux[i].need_scev = true;\n+\t\tif (loop-\u003eirreducible)\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c loop-\u003ebackedges_cnt; j++) {\n+\t\t\tlatch = loop-\u003ebackedges[j].latch;\n+\t\t\tif (latch \u003e= 0)\n+\t\t\t\taux[latch].need_scev = true;\n+\t\t}\n+\t}\n+}\n+\n+static bool is_any_imm_reg_opaque(struct scev *scev, u32 id)\n+{\n+\tu32 l, r, reg, order;\n+\ts64 imm;\n+\n+\tscev-\u003estack_sz = 0;\n+\texpr_stack_push(scev, id);\n+\twhile (expr_next(scev, \u0026id, \u0026order)) {\n+\t\tif (order \u0026 DEPTH_LIMIT)\n+\t\t\treturn false;\n+\t\tif (!(order \u0026 PRE) ||\n+\t\t is_imm(scev, id, \u0026imm) ||\n+\t\t is_reg(scev, id, \u0026reg) ||\n+\t\t is_opaque(scev, id) ||\n+\t\t is_any(scev, id, \u0026l, \u0026r))\n+\t\t\tcontinue;\n+\t\treturn false;\n+\t}\n+\treturn true;\n+}\n+\n+/*\n+ * Can implement explicit stack version, but it is harder to read.\n+ * Stick with recursive version for now.\n+ */\n+static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,\n+ int (*fn)(struct scev *scev, u32 id, void *priv))\n+{\n+\tstruct expr expr;\n+\tint p0, p1, id;\n+\n+\tif (lvl \u003e= EXPR_STACK_DEPTH)\n+\t\treturn UNKNOWN_EXPR_ID;\n+\n+ expr = scev-\u003eexprs[root]; /* snapshot the expr before potential realloc */\n+\tswitch (op_params_num(expr.op)) {\n+\tcase 0:\n+\t\tid = root;\n+\t\tbreak;\n+\tcase 1:\n+\t\tp0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);\n+\t\tid = expr1(scev, expr.op, p0);\n+\t\tbreak;\n+\tcase 2:\n+\t\tp0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);\n+\t\tp1 = transform_expr_once(scev, lvl + 1, expr.params[1], priv, fn);\n+\t\tid = expr2(scev, expr.op, p0, p1);\n+\t\tbreak;\n+\t}\n+\treturn id \u003c 0 ? id : fn(scev, id, priv);\n+}\n+\n+static int transform_expr(struct scev *scev, u32 root, void *priv,\n+ int (*fn)(struct scev *scev, u32 id, void *priv))\n+{\n+\tint id_old, id_new = root;\n+\n+\tdo {\n+\t\tid_old = id_new;\n+\t\tid_new = transform_expr_once(scev, 0, id_old, priv, fn);\n+\t\tif (id_new \u003c 0)\n+\t\t\treturn id_new;\n+\t} while (id_old != id_new);\n+\treturn id_new;\n+}\n+\n+static int simplify(struct scev *scev, u32 id, void *priv)\n+{\n+\tu32 l, r, base, slope;\n+\ts64 imm1, imm2;\n+\n+\t/* (+ (linear base slope) imm) -\u003e (linear (+ base imm) slope) */\n+\tif (is_add(scev, id, \u0026l, \u0026r) \u0026\u0026\n+\t is_linear(scev, l, \u0026base, \u0026slope) \u0026\u0026\n+\t is_imm(scev, r, \u0026imm1))\n+\t\treturn expr2(scev, LINEAR_SCEV, expr2(scev, BPF_ADD, base, r), slope);\n+\n+\t/* (+ imm imm) -\u003e imm */\n+\tif (is_add(scev, id, \u0026l, \u0026r) \u0026\u0026\n+\t is_imm(scev, l, \u0026imm1) \u0026\u0026\n+\t is_imm(scev, r, \u0026imm2))\n+\t\treturn imm_expr(scev, imm1 + imm2);\n+\n+\tif (is_zext32(scev, id, \u0026l) \u0026\u0026 is_imm(scev, l, \u0026imm1))\n+\t\treturn imm_expr(scev, (u64)(u32)imm1);\n+\n+\treturn id;\n+}\n+\n+static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 ra, rb, l, r, ra_expr;\n+\ts64 imm;\n+\tint id;\n+\n+\tfor (ra = 0; ra \u003c REGS_NUM; ra++) {\n+\t\tid = transform_expr(scev, header_env-\u003ereg2expr[ra], NULL, simplify);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\theader_env-\u003ereg2expr[ra] = id;\n+\t\tra_expr = header_env-\u003ereg2expr[ra];\n+\t\t/* rA = (+ rA IMM) */\n+\t\tif (is_add(scev, ra_expr, \u0026l, \u0026r) \u0026\u0026\n+\t\t is_reg(scev, l, \u0026rb) \u0026\u0026\n+\t\t is_imm(scev, r, \u0026imm) \u0026\u0026\n+\t\t ra == rb) {\n+\t\t\tid = expr2(scev, LINEAR_SCEV, l, r);\n+\t\t\tif (id \u003c 0)\n+\t\t\t\treturn id;\n+\t\t\theader_env-\u003ereg2scev[ra] = id;\n+\t\t\tcontinue;\n+\t\t}\n+\t\t/* rA = rA */\n+\t\tif (is_reg(scev, ra_expr, \u0026rb) \u0026\u0026 ra == rb) {\n+\t\t\theader_env-\u003ereg2scev[ra] = ra_expr;\n+\t\t\tcontinue;\n+\t\t}\n+\t\t/* rA = (any 1 2 3 4 ...) */\n+\t\tif (is_any_imm_reg_opaque(scev, ra_expr)) {\n+\t\t\theader_env-\u003ereg2scev[ra] = ra_expr;\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t}\n+\treturn 0;\n+}\n+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)\n+{\n+\tu32 reg, base, slope, *reg2scev = priv;\n+\n+\t/* (reg r) -\u003e (linear ...), where r is a LINEAR_SCEV in the header */\n+\tif (is_reg(scev, id, \u0026reg) \u0026\u0026\n+\t is_linear(scev, reg2scev[reg], \u0026base, \u0026slope))\n+\t\treturn reg2scev[reg];\n+\treturn id;\n+}\n+\n+static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tint id, reg;\n+\n+\tfor (reg = 0; reg \u003c REGS_NUM; reg++) {\n+\t\tid = einsn-\u003ereg2expr[reg];\n+\t\tid = transform_expr_once(scev, 0, id, eheader-\u003ereg2scev, instantiate_header_scevs);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\tid = transform_expr(scev, id, NULL, simplify);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\teinsn-\u003ereg2scev[reg] = id;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static void log_scevs(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct bpf_loop *loop;\n+\tint i, j, len, latch;\n+\n+\tlen = env-\u003eprog-\u003elen;\n+\tfor (i = 0; i \u003c len; i++) {\n+\t\tloop = aux[i].loop;\n+\t\tif (!loop)\n+\t\t\tcontinue;\n+\t\tbpf_log(log, \"scev at header %d:\\n\", i);\n+\t\tprint_env(env, find_header_env(scev, i), i, PRINT_SCEV);\n+\t\tif (loop-\u003eirreducible)\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c loop-\u003ebackedges_cnt; j++) {\n+\t\t\tlatch = loop-\u003ebackedges[j].latch;\n+\t\t\tif (latch \u003c 0)\n+\t\t\t\tcontinue;\n+\t\t\tbpf_log(log, \" scev at latch %d:\\n\", latch);\n+\t\t\tprint_env(env, find_loop_env(scev, bpf_loop_at_index(env, latch), latch),\n+\t\t\t\t latch, PRINT_SCEV);\n+\t\t}\n+\t}\n+}\n+\n+int bpf_compute_scev(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct scev *scev = env-\u003escev;\n+\tint *postorder = env-\u003ecfg.insn_postorder;\n+\tint cnt = env-\u003ecfg.cur_postorder;\n+\tint i, idx, err, header;\n+\n+\tmark_latches(env);\n+\t/*\n+\t * Visit loop headers in postorder, to guarantee that scevs\n+ * for innermost loops are computed first.\n+\t */\n+\tfor (i = 0; i \u003c cnt; i++) {\n+\t\tidx = postorder[i];\n+\t\tif (!aux[idx].loop)\n+\t\t\tcontinue;\n+\t\terr = compute_scev_for_loop(env, idx);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n+\t/*\n+\t * Compute scevs from exprs collected on a previous step. Iterate instructions in\n+\t * reverse post-order so that each loop header is processed before instructions\n+\t * reachable from it.\n+\t */\n+\tfor (i = cnt - 1; i \u003e= 0; i--) {\n+\t\tidx = postorder[i];\n+\t\tif (!aux[idx].need_scev)\n+\t\t\tcontinue;\n+\t\theader = bpf_loop_at_index(env, idx);\n+\t\terr = aux[idx].loop\n+\t\t ? compute_header_scevs(env, find_header_env(scev, header))\n+\t\t : compute_insn_scevs(env, find_header_env(scev, header),\n+\t\t\t\t find_loop_env(scev, header, idx));\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n+\tfor (i = 0; i \u003c env-\u003eprog-\u003elen; i++)\n+\t\tif (aux[i].loop)\n+\t\t\taux[i].prune_point = true;\n+\n+\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2)\n+\t\tlog_scevs(env);\n+\n+\treturn 0;\n+}\n+\n+static int reverse_ranked_compare(int a, int b, void *arg)\n+{\n+\tint *rank = arg;\n+\n+\treturn rank[b] - rank[a];\n+}\n+\n+void bpf_free_scev(struct bpf_verifier_env *env)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct insn_envs *envs;\n+\tint i;\n+\tu32 j;\n+\n+\tif (!scev)\n+\t\treturn;\n+\tfor (i = 0; i \u003c scev-\u003eenvs_cnt; i++) {\n+\t\tenvs = scev-\u003eenvs[i];\n+\t\tif (!envs)\n+\t\t\tcontinue;\n+\t\tfor (j = 0; j \u003c envs-\u003ecnt; j++)\n+\t\t\tkfree(envs-\u003eentries[j].env);\n+\t\tkfree(envs);\n+\t}\n+\tfor (i = 0; i \u003c ARRAY_SIZE(scev-\u003eexprs_ht); i++)\n+\t\tkvfree(scev-\u003eexprs_ht[i]);\n+\tbpf_min_heap_free(\u0026scev-\u003eworklist);\n+\tkvfree(scev-\u003eenvs);\n+\tkvfree(scev-\u003eexprs);\n+\tkvfree(scev-\u003ediscovered);\n+\tkfree(scev);\n+\tenv-\u003escev = NULL;\n+}\n+\n+int bpf_init_scev(struct bpf_verifier_env *env)\n+{\n+\tstruct scev *scev;\n+\n+\tscev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);\n+\tif (!scev)\n+\t\treturn -ENOMEM;\n+\tenv-\u003escev = scev;\n+\tbpf_mark_reg_not_init(env, \u0026env-\u003escev_not_init_reg);\n+\t/* Order worklist in reverse post-order. */\n+\tbpf_min_heap_init(\u0026scev-\u003eworklist, reverse_ranked_compare, env-\u003ecfg.postorder_nums);\n+\tif (expr0(scev, UNKNOWN) \u003c 0 || expr0(scev, OPAQUE) \u003c 0)\n+\t\tgoto nomem;\n+\tscev-\u003eenvs = kvcalloc(env-\u003eprog-\u003elen, sizeof(*scev-\u003eenvs), GFP_KERNEL_ACCOUNT);\n+\tscev-\u003ediscovered = kvcalloc(env-\u003eprog-\u003elen, sizeof(*scev-\u003ediscovered), GFP_KERNEL_ACCOUNT);\n+\tif (!scev-\u003eenvs || !scev-\u003ediscovered)\n+\t\tgoto nomem;\n+\t/*\n+\t * Remember original program length, in case bpf_free_scev()\n+ * is called after bpf program rewrites that increase program\n+ * length.\n+\t */\n+\tscev-\u003eenvs_cnt = env-\u003eprog-\u003elen;\n+\treturn 0;\n+nomem:\n+\tbpf_free_scev(env);\n+\treturn -ENOMEM;\n+}\n+\n+static struct bpf_reg_state *scev_regno_to_reg(struct bpf_verifier_env *env,\n+\t\t\t\t\t struct bpf_func_state *st, u32 r)\n+{\n+\tint spi, slots_available;\n+\n+\tif (r \u003c MAX_BPF_REG)\n+\t\treturn \u0026st-\u003eregs[r];\n+\n+\tslots_available = st-\u003eallocated_stack / BPF_REG_SIZE;\n+\tspi = r - MAX_BPF_REG;\n+\tif (spi \u003c slots_available)\n+\t\treturn \u0026st-\u003estack[spi].spilled_ptr;\n+\n+\treturn \u0026env-\u003escev_not_init_reg;\n+}\n+\n+static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 r)\n+{\n+\tint insn_idx = bpf_frame_insn_idx(st, st-\u003ecurframe);\n+\tu16 live_regs = env-\u003einsn_aux_data[insn_idx].live_regs_before;\n+\tint spi;\n+\n+\tif (r \u003c MAX_BPF_REG) {\n+\t\treturn BIT(r) \u0026 live_regs;\n+\t} else {\n+\t\tspi = r - MAX_BPF_REG;\n+\t\treturn bpf_stack_slot_alive(env, st-\u003ecurframe, spi * 2) ||\n+\t\t bpf_stack_slot_alive(env, st-\u003ecurframe, spi * 2 + 1);\n+\t}\n+}\n+\n+/*\n+ * Latch is a condition deciding if execution remains inside a loop.\n+ * Linear latch represents a condition 'if \u003creg\u003e \u003cop\u003e \u003cloop invariant\u003e goto \u003cloop-header\u003e',\n+ * where equation '\u003cbase\u003e + i * \u003cstep\u003e \u003cop\u003e \u003cbound\u003e' describes values taken by register \u003creg\u003e,\n+ * 'i' is the loop iteration number, starting from 0.\n+ */\n+struct linear_latch {\n+\tu32 insn_idx;\n+\tu32 base_expr;\n+\tu32 step_expr;\n+\tu32 bound_expr;\n+\tu32 reg_expr;\n+\tu32 reg;\n+\tu32 op;\n+};\n+\n+static bool loop_invariant(struct scev *scev, u32 id)\n+{\n+\ts64 imm;\n+\tu32 reg;\n+\n+\treturn is_reg(scev, id, \u0026reg) || is_imm(scev, id, \u0026imm);\n+}\n+\n+static int match_linear_latch(struct bpf_verifier_env *env,\n+\t\t\t u32 latch_idx,\n+\t\t\t struct linear_latch *latch)\n+{\n+\tstruct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[latch_idx];\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct env *latch_env = find_loop_env(scev, bpf_loop_at_index(env, latch_idx), latch_idx);\n+\tu32 true_branch_tgt;\n+\tu32 l, r, op, base;\n+\tu32 src_reg_scev;\n+\tu32 dst_reg_scev;\n+\tint id;\n+\n+\t/* 32-bit arithmetic is not handled yet */\n+\tif (BPF_CLASS(insn-\u003ecode) != BPF_JMP)\n+\t\treturn false;\n+\top = BPF_OP(insn-\u003ecode);\n+\t/* Flip the condition if true branch jumps out of the loop */\n+\ttrue_branch_tgt = latch_idx + bpf_jmp_offset(insn) + 1;\n+\tif (bpf_loop_at_index(env, true_branch_tgt) != bpf_loop_at_index(env, latch_idx))\n+\t\top = bpf_rev_opcode(op);\n+\tswitch (op) {\n+\tcase BPF_JSLT:\n+\tcase BPF_JSLE:\n+\tcase BPF_JSGT:\n+\tcase BPF_JSGE:\n+\tcase BPF_JLT:\n+\tcase BPF_JLE:\n+\tcase BPF_JGT:\n+\tcase BPF_JGE:\n+\tcase BPF_JNE:\n+\t\tbreak;\n+\tdefault:\n+\t\treturn false;\n+\t}\n+\n+\tlatch-\u003eop = op;\n+\tlatch-\u003einsn_idx = latch_idx;\n+\n+\tdst_reg_scev = latch_env-\u003ereg2scev[insn-\u003edst_reg];\n+\tsrc_reg_scev = latch_env-\u003ereg2scev[insn-\u003esrc_reg];\n+\tif (!is_linear(scev, dst_reg_scev, \u0026base, \u0026latch-\u003estep_expr))\n+\t\treturn false;\n+\n+\tif (BPF_SRC(insn-\u003ecode) == BPF_K) {\n+\t\tid = imm_expr(scev, insn-\u003eimm);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\tlatch-\u003ebound_expr = id;\n+\t} else {\n+\t\tlatch-\u003ebound_expr = src_reg_scev;\n+\t}\n+\n+\tif (is_reg(scev, base, \u0026latch-\u003ereg)) {\n+\t\tid = imm_expr(scev, 0);\n+\t\tif (id \u003c 0)\n+\t\t\treturn id;\n+\t\tlatch-\u003ebase_expr = id;\n+\t\tlatch-\u003ereg_expr = base;\n+\t} else if (is_add(scev, base, \u0026l, \u0026r) \u0026\u0026\n+\t\t is_reg(scev, l, \u0026latch-\u003ereg)) {\n+\t\tlatch-\u003ebase_expr = r;\n+\t\tlatch-\u003ereg_expr = l;\n+\t} else {\n+\t\treturn false;\n+\t}\n+\n+\tif (!loop_invariant(scev, latch-\u003ebase_expr) ||\n+\t !loop_invariant(scev, latch-\u003estep_expr) ||\n+\t !loop_invariant(scev, latch-\u003ebound_expr))\n+\t\treturn false;\n+\n+\treturn true;\n+}\n+\n+static bool eval_expr(struct bpf_verifier_env *env, struct scev *scev, struct bpf_func_state *st, u32 id, u64 *result)\n+{\n+\tstruct bpf_reg_state *reg;\n+\tu32 regno;\n+\ts64 imm;\n+\n+\tif (is_reg(scev, id, \u0026regno)) {\n+\t\treg = scev_regno_to_reg(env, st, regno);\n+\t\tif (reg-\u003etype == NOT_INIT)\n+\t\t\treturn false;\n+\t\tif (tnum_is_const(reg-\u003evar_off)) {\n+\t\t\t*result = reg-\u003evar_off.value;\n+\t\t\treturn true;\n+\t\t}\n+\t} else if (is_imm(scev, id, \u0026imm)) {\n+\t\t*result = imm;\n+\t\treturn true;\n+\t}\n+\treturn false;\n+}\n+\n+/* Like DIV_ROUND_UP() but overflow safe */\n+static u64 div_round_up(u64 a, u64 b)\n+{\n+\treturn a / b + (a % b != 0);\n+}\n+\n+/*\n+ * Loop with post-condition:\n+ *\n+ * r0 = 0\n+ * l: ... r0 ∈ [0,1,2] header executed 3 times\n+ * r0 += 1 r0 ∈ [0,1,2]\n+ * ... r0 ∈ [1,2,3]\n+ * if r0 != 3 goto l r0 ∈ [1,2,3] backedge taken 2 times\n+ * ... r0 ∈ [3]\n+ *\n+ * SCEV at header: r0 = k\n+ * SCEV at latch: r0 = 1 + k\n+ *\n+ * Loop with pre-condition:\n+ *\n+ * r0 = 0\n+ * l: ... r0 ∈ [0,1,2,3] header executed 4 times\n+ * if r0 == 3 goto e r0 ∈ [0,1,2,3] backedge taken 3 times\n+ * r0 += 1 r0 ∈ [0,1,2]\n+ * ... r0 ∈ [1,2,3]\n+ * goto l r0 ∈ [1,2,3]\n+ * e: ... r0 ∈ [3]\n+ *\n+ * SCEV at header: r0 = k\n+ * SCEV at latch: r0 = k\n+ */\n+static bool compute_max_iters(struct bpf_verifier_env *env,\n+\t\t\t struct bpf_func_state *st,\n+\t\t\t struct linear_latch *latch,\n+\t\t\t struct bpf_loop_iters *iters)\n+{\n+\tu64 base, step, diff, bound, initial, max_iters;\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_loop *loop = aux[bpf_loop_at_index(env, latch-\u003einsn_idx)].loop;\n+\tstruct scev *scev = env-\u003escev;\n+\tu8 op = latch-\u003eop;\n+\n+\tif (!eval_expr(env, scev, st, latch-\u003ebase_expr, \u0026base) ||\n+\t !eval_expr(env, scev, st, latch-\u003estep_expr, \u0026step) ||\n+\t !eval_expr(env, scev, st, latch-\u003ebound_expr, \u0026bound) ||\n+\t !eval_expr(env, scev, st, latch-\u003ereg_expr, \u0026initial))\n+\t\treturn false;\n+\n+\tif (step == 0)\n+\t\treturn false;\n+\tif ((s64)step == S64_MIN)\n+\t\treturn false;\n+\tif ((s64)step \u003c 0) {\n+\t\t/* Multiply both sides of the equation by -1, e.g. -2*i \u003e -3 becomes 2*i \u003c 3 */\n+\t\top = bpf_flip_opcode(op);\n+\t\tstep = -step;\n+\t\tswap(bound, initial);\n+\t}\n+\tdiff = bound - initial;\n+\tif (diff / step == U64_MAX)\n+\t\treturn false;\n+\tswitch (op) {\n+\tcase BPF_JLT:\n+\t\tmax_iters = (u64)initial \u003e= (u64)bound ? 0 : div_round_up(diff, step);\n+\t\tbreak;\n+\tcase BPF_JLE:\n+\t\tmax_iters = (u64)initial \u003e (u64)bound ? 0 : diff / step + 1;\n+\t\tbreak;\n+\tcase BPF_JSLT:\n+\t\tmax_iters = (s64)initial \u003e= (s64)bound ? 0 : div_round_up(diff, step);\n+\t\tbreak;\n+\tcase BPF_JSLE:\n+\t\tmax_iters = (s64)initial \u003e (s64)bound ? 0 : diff / step + 1;\n+\t\tbreak;\n+\tcase BPF_JNE:\n+\t\tmax_iters = diff % step ? U32_MAX : div_round_up(diff, step);\n+\t\tbreak;\n+\tdefault:\n+\t\treturn false;\n+\t}\n+\n+\tif (max_iters \u003e U32_MAX)\n+\t\treturn false;\n+\n+\t/*\n+\t * The latch is a conditional jump with one jump target exiting the loop.\n+\t * Linear latch is matched only if the loop has a single backedge.\n+\t * The loop still, however can have multiple exits.\n+\t * In such case, conservatively assume that non-latch exit can happen\n+\t * at any iteration, thus setting minimal number of iterations as 0.\n+\t */\n+\titers-\u003emax_header_count = max_iters + (base == 0 ? 1 : 0);\n+\titers-\u003emin_header_count = loop-\u003eexits_cnt == 1 ? iters-\u003emax_header_count : 0;\n+\titers-\u003epre_cond = base == 0;\n+\treturn true;\n+}\n+\n+static void mark_scev_reg_scratched(struct bpf_verifier_env *env, u32 r)\n+{\n+\tif (r \u003c MAX_BPF_REG)\n+\t\tmark_reg_scratched(env, r);\n+\telse\n+\t\tmark_stack_slot_scratched(env, r - __MAX_BPF_REG);\n+}\n+\n+/* Main logic in verifier.c forbids varying offsets for certain register types. */\n+static bool is_widenable_reg_type(const struct bpf_reg_state *reg)\n+{\n+\tswitch (base_type(reg-\u003etype)) {\n+\tcase SCALAR_VALUE:\n+\tcase PTR_TO_MAP_VALUE:\n+\tcase PTR_TO_MAP_KEY:\n+\tcase PTR_TO_STACK:\n+\tcase PTR_TO_PACKET:\n+\tcase PTR_TO_PACKET_META:\n+\tcase PTR_TO_MEM:\n+\tcase PTR_TO_BUF:\n+\tcase PTR_TO_BTF_ID:\n+\t\treturn true;\n+\tdefault:\n+\t\treturn false;\n+\t}\n+}\n+\n+/* Check that ANY leaves can be unioned with r's loop-entry value. */\n+static bool is_any_imm_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,\n+\t\t\t struct env *header_env, u32 r, u32 id)\n+{\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct bpf_reg_state *reg, *leaf_reg;\n+\tu32 l, rr, leaf, ra, order;\n+\ts64 imm;\n+\n+\tif (!is_any(scev, id, \u0026l, \u0026rr))\n+\t\treturn false;\n+\treg = scev_regno_to_reg(env, loop_entry, r);\n+\tif (!is_widenable_reg_type(reg))\n+\t\treturn false;\n+\n+\tscev-\u003estack_sz = 0;\n+\texpr_stack_push(scev, id);\n+\twhile (expr_next(scev, \u0026id, \u0026order)) {\n+\t\tif (order \u0026 DEPTH_LIMIT)\n+\t\t\treturn false;\n+\t\tif (!(order \u0026 PRE) || is_any(scev, id, \u0026l, \u0026rr))\n+\t\t\tcontinue;\n+\t\tif (is_imm(scev, id, \u0026imm)) {\n+\t\t\tif (reg-\u003etype != SCALAR_VALUE)\n+\t\t\t\treturn false;\n+\t\t} else if (is_reg(scev, id, \u0026leaf)) {\n+\t\t\t/* Other leaves must denote loop-invariant registers. */\n+\t\t\tif (leaf != r \u0026\u0026\n+\t\t\t !(is_reg(scev, header_env-\u003ereg2scev[leaf], \u0026ra) \u0026\u0026 ra == leaf))\n+\t\t\t\treturn false;\n+\t\t\tleaf_reg = scev_regno_to_reg(env, loop_entry, leaf);\n+\t\t\tif (leaf_reg-\u003etype != reg-\u003etype)\n+\t\t\t\treturn false;\n+\t\t} else {\n+\t\t\treturn false;\n+\t\t}\n+\t}\n+\treturn true;\n+}\n+\n+struct bounds {\n+\tstruct cnum64 range;\n+\tu16 step;\n+};\n+\n+static bool is_simple_linear(struct scev *scev, u32 id, u32 *base_reg, s64 *slope_imm)\n+{\n+\tu32 base, slope;\n+\n+\treturn is_linear(scev, id, \u0026base, \u0026slope) \u0026\u0026\n+\t is_reg(scev, base, base_reg) \u0026\u0026\n+\t is_imm(scev, slope, slope_imm) \u0026\u0026\n+\t *slope_imm \u003c= S16_MAX \u0026\u0026\n+\t *slope_imm \u003e= S16_MIN \u0026\u0026\n+\t *slope_imm != 0;\n+}\n+\n+/*\n+ * Compute the range an induction variable in `reg` spans over the loop.\n+ * Returns false if the computation overflows s64.\n+ */\n+static bool linear_bounds(struct bpf_reg_state *reg, struct bpf_loop_iters *iters, s64 slope,\n+\t\t\t struct bounds *out)\n+{\n+\ts64 slope_abs = slope \u003c 0 ? -slope : slope;\n+\ts64 min_val = reg_smin(reg);\n+\ts64 max_val = reg_smax(reg);\n+\ts64 total_change;\n+\tu16 step;\n+\n+\tif (check_mul_overflow(slope, (s64)iters-\u003emax_header_count - 1, \u0026total_change))\n+\t\treturn false;\n+\tif (slope \u003e 0) {\n+\t\tif (check_add_overflow(max_val, total_change, \u0026max_val))\n+\t\t\treturn false;\n+\t} else {\n+\t\tif (check_add_overflow(min_val, total_change, \u0026min_val))\n+\t\t\treturn false;\n+\t}\n+\t/*\n+\t * If the entry value is a single point the value set is 'v + slope * k',\n+\t * so the step is |slope|. Otherwise, only the power-of-two alignment\n+\t * shared by the entry value and the slope.\n+\t */\n+\tif (cnum64_is_const(reg-\u003er64))\n+\t\tstep = slope_abs;\n+\telse\n+\t\tstep = 1u \u003c\u003c min_t(u32, tnum_alignment(reg-\u003evar_off), __ffs(slope_abs));\n+\tout-\u003erange = cnum64_from_srange(min_val, max_val);\n+\tout-\u003estep = step;\n+\treturn true;\n+}\n+\n+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\n+\t\t\t struct bpf_loop_iters *iters)\n+{\n+\tstruct bpf_func_state *cur_func = st-\u003eframe[st-\u003ecurframe];\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct env *header_env;\n+\tstruct linear_latch latch;\n+\tstruct bpf_loop *loop;\n+\tstruct bounds bounds;\n+\tint insn_idx = st-\u003einsn_idx;\n+\tint linear_latch;\n+\tu32 r, base_reg;\n+\tint latch_idx;\n+\ts64 slope_imm;\n+\tint err;\n+\n+\t/*\n+\t * If insn_idx is a loop header for a reducible loop with a single backedge.\n+\t * loop is NULL for secondary entries to irreducible loops.\n+\t */\n+\tloop = aux[insn_idx].loop;\n+\tif (!loop || loop-\u003eirreducible || loop-\u003ebackedges_cnt != 1 || loop-\u003ebackedges_overflow ||\n+\t loop-\u003eexits_overflow) {\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2)\n+\t\t\tbpf_log(log, \"loop header at %d, unsupported loop:%s%s%s\\n\", insn_idx,\n+\t\t\t\t!loop || loop-\u003eirreducible ? \" irreducible\" : \"\",\n+\t\t\t\tloop \u0026\u0026 loop-\u003ebackedges_cnt \u003e 1 ? \" multiple backedges\" : \"\",\n+\t\t\t\tloop \u0026\u0026 loop-\u003eexits_overflow ? \" too many exits\" : \"\");\n+\t\treturn 0;\n+\t}\n+\n+\t/* If this backedge has a latch */\n+\tlatch_idx = loop-\u003ebackedges[0].latch;\n+\tif (latch_idx \u003c 0)\n+\t\treturn 0;\n+\n+\tlinear_latch = match_linear_latch(env, latch_idx, \u0026latch);\n+\tif (linear_latch \u003c 0)\n+\t\treturn linear_latch;\n+\n+\tif (!linear_latch) {\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2)\n+\t\t\tbpf_log(log, \"loop header at %d, non-linear latch at %d\\n\",\n+\t\t\t\tinsn_idx, latch_idx);\n+\t\treturn 0;\n+\t}\n+\n+\tif (!compute_max_iters(env, cur_func, \u0026latch, iters)) {\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2)\n+\t\t\tbpf_log(log, \"loop header at %d, can't compute iterations count\\n\", insn_idx);\n+\t\treturn 0;\n+\t}\n+\n+\tif (iters-\u003emax_header_count == 0) {\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2)\n+\t\t\tbpf_log(log, \"loop header at %d, 0 iterations count\\n\", insn_idx);\n+\t\treturn 0;\n+\t}\n+\n+\tif (iters-\u003emax_header_count == U32_MAX) {\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2)\n+\t\t\tbpf_log(log, \"loop header at %d, inf iterations count\\n\", insn_idx);\n+\t\treturn 0;\n+\t}\n+\n+\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n+\t\tbpf_log(log, \"loop header at %d, header_count is \", insn_idx);\n+\t\tif (iters-\u003emin_header_count == iters-\u003emax_header_count)\n+\t\t\tbpf_log(log, \"%u \", iters-\u003emax_header_count);\n+\t\telse\n+\t\t\tbpf_log(log, \"[%u..%u] \", iters-\u003emin_header_count, iters-\u003emax_header_count);\n+\t\tbpf_log(log, \"%s\\n\", iters-\u003epre_cond ? \"pre-cond\" : \"post-cond\");\n+\t}\n+\n+\terr = bpf_live_stack_query_init(env, st);\n+\tif (err)\n+\t\treturn err;\n+\n+\theader_env = find_header_env(scev, insn_idx);\n+\tfor (r = 0; r \u003c REGS_NUM; r++) {\n+\t\tstruct bpf_reg_state *reg;\n+\t\tu32 ra, r_scev, r_expr;\n+\t\tbool spill_base = false;\n+\n+\t\tif (!scev_reg_alive(env, st, r))\n+\t\t\tcontinue;\n+\n+\t\tr_scev = header_env-\u003ereg2scev[r];\n+\t\treg = scev_regno_to_reg(env, cur_func, r);\n+\t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e) */\n+\t\tif (is_simple_linear(scev, r_scev, \u0026base_reg, \u0026slope_imm) \u0026\u0026\n+\t\t is_widenable_reg_type(reg)) {\n+\t\t\tif (base_reg == r) {\n+\t\t\t\t/* Can't widen if the iteration range overflows */\n+\t\t\t\tif (!linear_bounds(reg, iters, slope_imm, \u0026bounds))\n+\t\t\t\t\tgoto cant_widen;\n+\t\t\t\t/* Spills at varying offsets lose precision */\n+\t\t\t\tif (test_bit(r, loop-\u003estore_base_regs)) {\n+\t\t\t\t\tspill_base = true;\n+\t\t\t\t\tgoto cant_widen;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\t/* rA = rA, loop does not change this reg */\n+\t\tif (is_reg(scev, r_scev, \u0026ra) \u0026\u0026 r == ra)\n+\t\t\tcontinue;\n+\n+\t\t/* (any 1 (any 2 (any 3 4))) */\n+\t\tif (is_any_imm_reg(env, cur_func, header_env, r, r_scev))\n+\t\t\tcontinue;\n+\n+cant_widen:\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n+\t\t\tr_expr = header_env-\u003ereg2expr[r];\n+\t\t\tbpf_log(log, \"loop header at %d, can't widen \", insn_idx);\n+\t\t\tlog_reg(env, r);\n+\t\t\tbpf_log(log, \", expr is \");\n+\t\t\tlog_expr(env, r_expr);\n+\t\t\tif (spill_base)\n+\t\t\t\tbpf_log(log, \", requires exact stack-offset tracking\");\n+\t\t\tbpf_log(log, \"\\n\");\n+\t\t}\n+\t\treturn 0;\n+\t}\n+\n+\treturn 1;\n+}\n+\n+static void scratch_scalar_id(struct bpf_reg_state *reg)\n+{\n+\tif (reg-\u003etype == SCALAR_VALUE)\n+\t\treg-\u003eid = 0;\n+}\n+\n+/* The filtering pass has checked that every leaf can be unioned into acc. */\n+static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,\n+\t\t\t struct bpf_reg_state *acc, u32 id)\n+{\n+\tstruct bpf_reg_state *tmp = \u0026env-\u003efake_reg[0], *leaf_reg;\n+\tstruct scev *scev = env-\u003escev;\n+\tu32 l, r, leaf, order;\n+\ts64 imm;\n+\tint err;\n+\n+\tscev-\u003estack_sz = 0;\n+\texpr_stack_push(scev, id);\n+\twhile (expr_next(scev, \u0026id, \u0026order)) {\n+\t\tif (order \u0026 DEPTH_LIMIT) {\n+\t\t\tverifier_bug(env, \"scev ANY union exceeds expression depth limit\");\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\t\tif (!(order \u0026 PRE) || is_any(scev, id, \u0026l, \u0026r))\n+\t\t\tcontinue;\n+\t\tif (is_imm(scev, id, \u0026imm)) {\n+\t\t\tbpf_mark_reg_known_scalar(tmp, imm);\n+\t\t\tleaf_reg = tmp;\n+\t\t} else if (is_reg(scev, id, \u0026leaf)) {\n+\t\t\tleaf_reg = scev_regno_to_reg(env, loop_entry, leaf);\n+\t\t} else {\n+\t\t\tverifier_bug(env, \"scev ANY union has an unsupported leaf\");\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\t\terr = bpf_reg_union(env, acc, leaf_reg);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn 0;\n+}\n+\n+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\n+\t\t\tstruct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)\n+{\n+\tstruct bpf_func_state *cur_func = st-\u003eframe[st-\u003ecurframe];\n+\tstruct bpf_func_state *entry_func = loop_entry-\u003eframe[loop_entry-\u003ecurframe];\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct bpf_reg_state *reg;\n+\tstruct env *header_env;\n+\tstruct bounds bounds;\n+\tu32 r, base_reg, r_expr, a, b;\n+\tint insn_idx = st-\u003einsn_idx;\n+\ts64 slope_imm;\n+\tint err;\n+\n+\theader_env = find_header_env(scev, insn_idx);\n+\tfor (r = 0; r \u003c REGS_NUM; r++) {\n+\t\tif (!scev_reg_alive(env, st, r))\n+\t\t\tcontinue;\n+\n+\t\tr_expr = header_env-\u003ereg2scev[r];\n+\t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e)*/\n+\t\tif (is_simple_linear(scev, r_expr, \u0026base_reg, \u0026slope_imm) \u0026\u0026\n+\t\t base_reg == r) {\n+\t\t\treg = scev_regno_to_reg(env, cur_func, r);\n+\t\t\t/* Feasibility was checked in the filtering pass above. */\n+\t\t\tif (!linear_bounds(reg, iters, slope_imm, \u0026bounds)) {\n+\t\t\t\tverifier_bug(env, \"scev widen bounds overflow for r%d\", r);\n+\t\t\t\treturn -EFAULT;\n+\t\t\t}\n+\t\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n+\t\t\t\tbpf_log(log, \"loop header at %d, widening \", insn_idx);\n+\t\t\t\tlog_reg(env, r);\n+\t\t\t\tbpf_log(log, \" to %lld..%lld step %u\\n\",\n+\t\t\t\t\tcnum64_smin(bounds.range), cnum64_smax(bounds.range),\n+\t\t\t\t\tbounds.step);\n+\t\t\t}\n+\t\t\tscratch_scalar_id(reg);\n+\t\t\terr = bpf_set_reg_range(env, reg, bounds.range, bounds.step);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t\tmark_scev_reg_scratched(env, r);\n+\t\t} else if (is_any(scev, r_expr, \u0026a, \u0026b)) {\n+\t\t\treg = scev_regno_to_reg(env, cur_func, r);\n+\t\t\terr = union_any_reg(env, entry_func, reg, r_expr);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n+\t\t\t\tbpf_log(log, \"loop header at %d, widening \", insn_idx);\n+\t\t\t\tlog_reg(env, r);\n+\t\t\t\tbpf_log(log, \" to %lld..%lld step %u\\n\",\n+\t\t\t\t\treg_smin(reg), reg_smax(reg), reg-\u003estep);\n+\t\t\t}\n+\t\t\tscratch_scalar_id(reg);\n+\t\t\tmark_scev_reg_scratched(env, r);\n+\t\t}\n+\t}\n+\treturn 1;\n+}\n+\n+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,\n+\t\t\tstruct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters)\n+{\n+\tstruct bpf_func_state *entry_st = entry_state-\u003eframe[entry_state-\u003ecurframe];\n+\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n+\tstruct bpf_reg_state *reg, *entry_reg;\n+\tstruct scev *scev = env-\u003escev;\n+\tstruct env *header_env;\n+\tstruct bounds bounds;\n+\tu32 r, base_reg;\n+\ts64 slope_imm;\n+\tint err;\n+\n+\tif (entry_state-\u003ecurframe != cur_func_state-\u003eframeno) {\n+\t\tverifier_bug(env, \"clamping registers for a wrong frame: %d vs %d\\n\",\n+\t\t\t entry_state-\u003ecurframe, cur_func_state-\u003eframeno);\n+\t\treturn -EFAULT;\n+\t}\n+\n+\theader_env = find_header_env(scev, insn_idx);\n+\tfor (r = 0; r \u003c REGS_NUM; r++) {\n+\t\t/* If SCEV for r is (linear \u003creg\u003e \u003cslope\u003e)*/\n+\t\tif (!is_simple_linear(scev, header_env-\u003ereg2scev[r], \u0026base_reg, \u0026slope_imm) ||\n+\t\t base_reg != r)\n+\t\t\tcontinue;\n+\n+\t\tentry_reg = scev_regno_to_reg(env, entry_st, r);\n+\t\treg = scev_regno_to_reg(env, cur_func_state, r);\n+\t\tif (entry_reg-\u003etype == NOT_INIT || reg-\u003etype == NOT_INIT)\n+\t\t\tcontinue;\n+\n+\t\tif (!linear_bounds(entry_reg, iters, slope_imm, \u0026bounds)) {\n+\t\t\tverifier_bug(env, \"scev clamp bounds overflow for r%d\", r);\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\t\tbounds.range = cnum64_intersect(reg-\u003er64, bounds.range);\n+\t\tif (cnum64_is_empty(bounds.range)) {\n+\t\t\tverifier_bug(env, \"scev clamp produced empty range for r%d\", r);\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\t\tif (log-\u003elevel \u0026 BPF_LOG_LEVEL2) {\n+\t\t\tbpf_log(log, \"loop header at %d, clamping \", insn_idx);\n+\t\t\tlog_reg(env, r);\n+\t\t\tbpf_log(log, \" to %lld..%lld step %u\\n\",\n+\t\t\t\tcnum64_smin(bounds.range), cnum64_smax(bounds.range),\n+\t\t\t\tbounds.step);\n+\t\t}\n+\t\tscratch_scalar_id(reg);\n+\t\terr = bpf_set_reg_range(env, reg, bounds.range, bounds.step);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t\tmark_scev_reg_scratched(env, r);\n+\t}\n+\treturn 0;\n+}\ndiff --git a/kernel/bpf/states.c b/kernel/bpf/states.c\nindex 18bf7b660c2f6..c1771a355e4e4 100644\n--- a/kernel/bpf/states.c\n+++ b/kernel/bpf/states.c\n@@ -302,8 +302,30 @@ int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_s\n static bool range_within(const struct bpf_reg_state *old,\n \t\t\t const struct bpf_reg_state *cur)\n {\n-\treturn cnum64_is_subset(old-\u003er64, cur-\u003er64) \u0026\u0026\n-\t cnum32_is_subset(old-\u003er32, cur-\u003er32);\n+\tif (!cnum64_is_subset(old-\u003er64, cur-\u003er64) ||\n+\t !cnum32_is_subset(old-\u003er32, cur-\u003er32))\n+\t\treturn false;\n+\n+\tif (old-\u003estep \u003c= 1)\n+\t\treturn true;\n+\n+\tif (cnum64_is_const(cur-\u003er64))\n+\t\treturn imod((s64)cnum64_smin(cur-\u003er64), old-\u003estep) == old-\u003ebase;\n+\n+\t/*\n+\t * Both `old` and `cur` define some sets of points.\n+\t * Return true, if points defined by `cur` are a subset of points defined by `old`:\n+\t * - bounds for `cur` should be within bounds for `old`;\n+\t * - cur-\u003estep should be dividable by old-\u003estep;\n+\t * - cur-\u003ebase should start at integer number of old-\u003estep\n+\t * steps from old-\u003ebase.\n+\t *\n+\t * E.g. the following ranges are compatible:\n+\t * - old [0, 10] step 2\n+\t * - new [2, 10] step 4\n+\t */\n+\treturn cur-\u003estep % old-\u003estep == 0 \u0026\u0026\n+\t (cur-\u003ebase - old-\u003ebase) % old-\u003estep == 0;\n }\n \n /* If in the old state two registers had the same id, then they need to have\n@@ -610,6 +632,7 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,\n \tcase PTR_TO_MEM:\n \tcase PTR_TO_BUF:\n \tcase PTR_TO_TP_BUFFER:\n+\tcase PTR_TO_BTF_ID:\n \t\t/* If the new min/max/var_off satisfy the old ones and\n \t\t * everything else matches, we are OK.\n \t\t */\n@@ -644,7 +667,12 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,\n \t\treturn range_within(rold, rcur) \u0026\u0026\n \t\t tnum_in(rold-\u003evar_off, rcur-\u003evar_off);\n \tcase PTR_TO_STACK:\n-\t\treturn regs_exact(rold, rcur, idmap);\n+\t\treturn memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 \u0026\u0026\n+\t\t range_within(rold, rcur) \u0026\u0026\n+\t\t tnum_in(rold-\u003evar_off, rcur-\u003evar_off) \u0026\u0026\n+\t\t check_ids(rold-\u003eid, rcur-\u003eid, idmap) \u0026\u0026\n+\t\t check_ids(rold-\u003eparent_id, rcur-\u003eparent_id, idmap) \u0026\u0026\n+\t\t rold-\u003eframeno == rcur-\u003eframeno;\n \tcase PTR_TO_ARENA:\n \t\treturn true;\n \tcase PTR_TO_INSN:\n@@ -914,6 +942,28 @@ static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *c\n \treturn true;\n }\n \n+static bool loop_stack_safe(struct bpf_verifier_env *env, struct bpf_func_state *old,\n+\t\t\t struct bpf_func_state *cur)\n+{\n+\tstruct loop_stack_entry *old_stack = old-\u003eloop_stack;\n+\tstruct loop_stack_entry *cur_stack = cur-\u003eloop_stack;\n+\tu32 i;\n+\n+\tif (old-\u003eloop_stack_cnt != cur-\u003eloop_stack_cnt)\n+\t\treturn false;\n+\n+\tfor (i = 0; i \u003c old-\u003eloop_stack_cnt; i++) {\n+\t\tif (old_stack[i].loop_id == cur_stack[i].loop_id \u0026\u0026\n+\t\t old_stack[i].iters.max_header_count == cur_stack[i].iters.max_header_count \u0026\u0026\n+\t\t old_stack[i].iters.pre_cond == cur_stack[i].iters.pre_cond \u0026\u0026\n+\t\t old_stack[i].terminates == cur_stack[i].terminates)\n+\t\t\tcontinue;\n+\t\treturn false;\n+\t}\n+\n+\treturn true;\n+}\n+\n /* compare two verifier states\n *\n * all states stored in state_list are known to be valid, since\n@@ -964,6 +1014,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat\n \tif (!stack_arg_safe(env, old, cur, \u0026env-\u003eidmap_scratch, exact))\n \t\treturn false;\n \n+\tif (!loop_stack_safe(env, old, cur))\n+\t\treturn false;\n+\n \treturn true;\n }\n \n@@ -1010,6 +1063,7 @@ static bool states_equal(struct bpf_verifier_env *env,\n \t\tif (!func_states_equal(env, old-\u003eframe[i], cur-\u003eframe[i], insn_idx, exact))\n \t\t\treturn false;\n \t}\n+\n \treturn true;\n }\n \n@@ -1240,16 +1294,82 @@ static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_\n \t}\n }\n \n-int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n+int bpf_split_cur_state(struct bpf_verifier_env *env)\n {\n+\tstruct bpf_verifier_state *cur = env-\u003ecur_state, *new;\n \tstruct bpf_verifier_state_list *new_sl;\n+\tstruct list_head *head;\n+\tint insn_idx = cur-\u003einsn_idx;\n+\tint err;\n+\n+\thead = bpf_explored_state(env, insn_idx);\n+\tnew_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);\n+\tif (!new_sl)\n+\t\treturn -ENOMEM;\n+\tenv-\u003etotal_states++;\n+\tenv-\u003eexplored_states_size++;\n+\tupdate_peak_states(env);\n+\tenv-\u003eprev_jmps_processed = env-\u003ejmps_processed;\n+\tenv-\u003eprev_insn_processed = env-\u003einsn_processed;\n+\n+\t/* forget precise markings we inherited, see __mark_chain_precision */\n+\tif (env-\u003ebpf_capable)\n+\t\tmark_all_scalars_imprecise(env, cur);\n+\n+\tbpf_clear_singular_ids(env, cur);\n+\n+\t/* add new state to the head of linked list */\n+\tnew = \u0026new_sl-\u003estate;\n+\terr = bpf_copy_verifier_state(new, cur);\n+\tif (err) {\n+\t\tbpf_free_verifier_state(new, false);\n+\t\tkfree(new_sl);\n+\t\treturn err;\n+\t}\n+\tnew-\u003einsn_idx = insn_idx;\n+\tverifier_bug_if(new-\u003ebranches != 1, env,\n+\t\t\t\"%s:branches_to_explore=%d insn %d\",\n+\t\t\t__func__, new-\u003ebranches, insn_idx);\n+\terr = maybe_enter_scc(env, new);\n+\tif (err) {\n+\t\tbpf_free_verifier_state(new, false);\n+\t\tkfree(new_sl);\n+\t\treturn err;\n+\t}\n+\n+\tcur-\u003eparent = new;\n+\tcur-\u003elast_insn_idx = -1;\n+\tcur-\u003efirst_insn_idx = insn_idx;\n+\tcur-\u003edfs_depth = new-\u003edfs_depth + 1;\n+\tbpf_clear_jmp_history(cur);\n+\tlist_add(\u0026new_sl-\u003enode, head);\n+\treturn 0;\n+}\n+\n+/* Force a checkpoint upon reaching a loop header for a terminating loop. */\n+static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)\n+{\n+\tstruct bpf_verifier_state *cur = env-\u003ecur_state;\n+\tstruct bpf_func_state *frame = cur-\u003eframe[cur-\u003ecurframe];\n+\tstruct loop_stack_entry *top;\n+\n+\tif (bpf_loop_at_index(env, insn_idx) != insn_idx || !frame-\u003eloop_stack_cnt)\n+\t\treturn false;\n+\ttop = \u0026frame-\u003eloop_stack[frame-\u003eloop_stack_cnt - 1];\n+\treturn top-\u003eloop_id == insn_idx \u0026\u0026 top-\u003eterminates;\n+}\n+\n+int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n+{\n \tstruct bpf_verifier_state_list *sl;\n-\tstruct bpf_verifier_state *cur = env-\u003ecur_state, *new;\n-\tbool force_new_state, add_new_state, loop;\n+\tstruct bpf_verifier_state *cur = env-\u003ecur_state;\n+\tbool force_new_state, add_new_state, loop, loop_checkpoint;\n \tint n, err, states_cnt = 0;\n \tstruct list_head *pos, *tmp, *head;\n \n+\tloop_checkpoint = need_loop_checkpoint(env, insn_idx);\n \tforce_new_state = env-\u003etest_state_freq || bpf_is_force_checkpoint(env, insn_idx) ||\n+\t\t\t loop_checkpoint ||\n \t\t\t /* Avoid accumulating infinitely long jmp history */\n \t\t\t cur-\u003ejmp_history_cnt \u003e 40;\n \n@@ -1280,10 +1400,11 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n \t\t\tcontinue;\n \n \t\tif (sl-\u003estate.branches) {\n-\t\t\tstruct bpf_func_state *frame = sl-\u003estate.frame[0];\n+\t\t\tstruct bpf_func_state *old_top_frame = sl-\u003estate.frame[0];\n+\t\t\tstruct bpf_func_state *old_cur_frame = sl-\u003estate.frame[sl-\u003estate.curframe];\n \n-\t\t\tif (frame-\u003ein_async_callback_fn \u0026\u0026\n-\t\t\t frame-\u003easync_entry_cnt != cur-\u003eframe[0]-\u003easync_entry_cnt) {\n+\t\t\tif (old_top_frame-\u003ein_async_callback_fn \u0026\u0026\n+\t\t\t old_top_frame-\u003easync_entry_cnt != cur-\u003eframe[0]-\u003easync_entry_cnt) {\n \t\t\t\t/* Different async_entry_cnt means that the verifier is\n \t\t\t\t * processing another entry into async callback.\n \t\t\t\t * Seeing the same state is not an indication of infinite\n@@ -1382,6 +1503,20 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n \t\t\t\t}\n \t\t\t\tgoto skip_inf_loop_check;\n \t\t\t}\n+\n+\t\t\t/*\n+\t\t\t * If old state belongs to a control flow loop that we know terminates,\n+\t\t\t * it should be safe to prune current state.\n+\t\t\t */\n+\t\t\tif (old_cur_frame-\u003eloop_stack_cnt \u0026\u0026\n+\t\t\t old_cur_frame-\u003eloop_stack[old_cur_frame-\u003eloop_stack_cnt - 1].terminates) {\n+\t\t\t\tif (states_equal(env, \u0026sl-\u003estate, cur, RANGE_WITHIN)) {\n+\t\t\t\t\tloop = true;\n+\t\t\t\t\tgoto hit;\n+\t\t\t\t}\n+\t\t\t\tgoto skip_inf_loop_check;\n+\t\t\t}\n+\n \t\t\t/* attempt to detect infinite loop to avoid unnecessary doomed work */\n \t\t\tif (states_maybe_looping(\u0026sl-\u003estate, cur) \u0026\u0026\n \t\t\t states_equal(env, \u0026sl-\u003estate, cur, EXACT) \u0026\u0026\n@@ -1540,7 +1675,8 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n \t\t * Use bigger 'n' for checkpoints because evicting checkpoint states\n \t\t * too early would hinder iterator convergence.\n \t\t */\n-\t\tn = bpf_is_force_checkpoint(env, insn_idx) \u0026\u0026 sl-\u003estate.branches \u003e 0 ? 64 : 3;\n+\t\tn = (bpf_is_force_checkpoint(env, insn_idx) || loop_checkpoint) \u0026\u0026\n+\t\t sl-\u003estate.branches \u003e 0 ? 64 : 3;\n \t\tif (sl-\u003emiss_cnt \u003e sl-\u003ehit_cnt * n + n) {\n \t\t\t/* the state is unlikely to be useful. Remove it to\n \t\t\t * speed up verification\n@@ -1572,44 +1708,5 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)\n \t * When looping the sl-\u003estate.branches will be \u003e 0 and this state\n \t * will not be considered for equivalence until branches == 0.\n \t */\n-\tnew_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);\n-\tif (!new_sl)\n-\t\treturn -ENOMEM;\n-\tenv-\u003etotal_states++;\n-\tenv-\u003eexplored_states_size++;\n-\tupdate_peak_states(env);\n-\tenv-\u003eprev_jmps_processed = env-\u003ejmps_processed;\n-\tenv-\u003eprev_insn_processed = env-\u003einsn_processed;\n-\n-\t/* forget precise markings we inherited, see __mark_chain_precision */\n-\tif (env-\u003ebpf_capable)\n-\t\tmark_all_scalars_imprecise(env, cur);\n-\n-\tbpf_clear_singular_ids(env, cur);\n-\n-\t/* add new state to the head of linked list */\n-\tnew = \u0026new_sl-\u003estate;\n-\terr = bpf_copy_verifier_state(new, cur);\n-\tif (err) {\n-\t\tbpf_free_verifier_state(new, false);\n-\t\tkfree(new_sl);\n-\t\treturn err;\n-\t}\n-\tnew-\u003einsn_idx = insn_idx;\n-\tverifier_bug_if(new-\u003ebranches != 1, env,\n-\t\t\t\"%s:branches_to_explore=%d insn %d\",\n-\t\t\t__func__, new-\u003ebranches, insn_idx);\n-\terr = maybe_enter_scc(env, new);\n-\tif (err) {\n-\t\tbpf_free_verifier_state(new, false);\n-\t\tkfree(new_sl);\n-\t\treturn err;\n-\t}\n-\n-\tcur-\u003eparent = new;\n-\tcur-\u003efirst_insn_idx = insn_idx;\n-\tcur-\u003edfs_depth = new-\u003edfs_depth + 1;\n-\tbpf_clear_jmp_history(cur);\n-\tlist_add(\u0026new_sl-\u003enode, head);\n-\treturn 0;\n+\treturn bpf_split_cur_state(env);\n }\ndiff --git a/kernel/bpf/tnum.c b/kernel/bpf/tnum.c\nindex ec9c310cf5d7f..1f620facd1b7e 100644\n--- a/kernel/bpf/tnum.c\n+++ b/kernel/bpf/tnum.c\n@@ -317,3 +317,14 @@ u64 tnum_step(struct tnum t, u64 z)\n \tinc = (filled + 1) \u0026 t.mask;\n \treturn t.value | inc;\n }\n+\n+/*\n+ * Return the number of trailing bits known to be zero in a tnum.\n+ * Return 64 for a tnum representing zero.\n+ */\n+u32 tnum_alignment(struct tnum a)\n+{\n+\tu64 v = a.value | a.mask;\n+\n+\treturn v ? __ffs64(v) : 64;\n+}\ndiff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c\nindex 03dbc0e003986..327bfc00da5f5 100644\n--- a/kernel/bpf/verifier.c\n+++ b/kernel/bpf/verifier.c\n@@ -5,6 +5,7 @@\n */\n #include \u003cuapi/linux/btf.h\u003e\n #include \u003clinux/bpf-cgroup.h\u003e\n+#include \u003clinux/count_zeros.h\u003e\n #include \u003clinux/kernel.h\u003e\n #include \u003clinux/types.h\u003e\n #include \u003clinux/slab.h\u003e\n@@ -30,6 +31,7 @@\n #include \u003clinux/module.h\u003e\n #include \u003clinux/cpumask.h\u003e\n #include \u003clinux/cnum.h\u003e\n+#include \u003clinux/gcd.h\u003e\n #include \u003clinux/bpf_mem_alloc.h\u003e\n #include \u003cnet/xdp.h\u003e\n #include \u003clinux/trace_events.h\u003e\n@@ -1910,12 +1912,19 @@ static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,\n \t}\n }\n \n+static void reg_step_reset(struct bpf_reg_state *reg)\n+{\n+\treg-\u003ebase = 0;\n+\treg-\u003estep = 1;\n+}\n+\n /* This helper doesn't clear reg-\u003eid */\n static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)\n {\n \treg-\u003evar_off = tnum_const(imm);\n \treg-\u003er64 = cnum64_from_urange(imm, imm);\n \treg-\u003er32 = cnum32_from_urange((u32)imm, (u32)imm);\n+\treg_step_reset(reg);\n }\n \n /* Mark the unknown part of a register (variable offset or scalar value) as\n@@ -1932,6 +1941,12 @@ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)\n \t___mark_reg_known(reg, imm);\n }\n \n+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)\n+{\n+\t__mark_reg_known(reg, imm);\n+\treg-\u003etype = SCALAR_VALUE;\n+}\n+\n static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)\n {\n \treg-\u003evar_off = tnum_const_subreg(reg-\u003evar_off, imm);\n@@ -2158,10 +2173,16 @@ static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)\n \treg-\u003er64 = cnum64_cnum32_intersect(reg-\u003er64, reg-\u003er32);\n }\n \n+static void deduce_bounds_64_from_step(struct bpf_reg_state *reg)\n+{\n+\treg-\u003er64 = cnum64_intersect_linear(reg-\u003er64, reg-\u003ebase, reg-\u003estep);\n+}\n+\n static void __reg_deduce_bounds(struct bpf_reg_state *reg)\n {\n \tdeduce_bounds_32_from_64(reg);\n \tdeduce_bounds_64_from_32(reg);\n+\tdeduce_bounds_64_from_step(reg);\n }\n \n /* Attempts to improve var_off based on unsigned min/max information */\n@@ -2173,8 +2194,18 @@ static void __reg_bound_offset(struct bpf_reg_state *reg)\n \tstruct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),\n \t\t\t\t\t tnum_range(reg_u32_min(reg),\n \t\t\t\t\t\t\t reg_u32_max(reg)));\n+\tu32 trailing_zero_bits;\n+\tu16 base = reg-\u003ebase;\n+\tu16 step = reg-\u003estep;\n \n \treg-\u003evar_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);\n+\n+\tif (base == 0)\n+\t\ttrailing_zero_bits = count_trailing_zeros(step);\n+\telse\n+\t\ttrailing_zero_bits = min(count_trailing_zeros(base),\n+\t\t\t\t\t count_trailing_zeros(step));\n+\treg-\u003evar_off = tnum_and(reg-\u003evar_off, tnum_const(~0ULL \u003c\u003c trailing_zero_bits));\n }\n \n static bool range_bounds_violation(struct bpf_reg_state *reg);\n@@ -2250,6 +2281,7 @@ static int reg_bounds_sanity_check(struct bpf_verifier_env *env,\n \tif (env-\u003etest_reg_invariants)\n \t\treturn -EFAULT;\n \t__mark_reg_unbounded(reg);\n+\treg_step_reset(reg);\n \treturn 0;\n }\n \n@@ -2260,6 +2292,7 @@ void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)\n \treg-\u003etype = SCALAR_VALUE;\n \treg-\u003evar_off = tnum_unknown;\n \t__mark_reg_unbounded(reg);\n+\treg_step_reset(reg);\n }\n \n /* Mark a register as having a completely unknown (scalar) value,\n@@ -6339,6 +6372,7 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,\n \tconst char *field_name = NULL;\n \tenum bpf_type_flag flag = 0;\n \tu32 btf_id = 0;\n+\ts64 min_off;\n \tint ret;\n \n \tif (!env-\u003eallow_ptr_leaks) {\n@@ -6354,36 +6388,31 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,\n \t\treturn -EINVAL;\n \t}\n \n-\tif (!tnum_is_const(reg-\u003evar_off)) {\n-\t\tchar tn_buf[48];\n-\n-\t\ttnum_strn(tn_buf, sizeof(tn_buf), reg-\u003evar_off);\n+\tif (check_add_overflow(reg_smin(reg), off, \u0026min_off)) {\n \t\tverbose(env,\n-\t\t\t\"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\\n\",\n-\t\t\treg_arg_name(env, argno), tname, off, tn_buf);\n+\t\t\t\"%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\\n\",\n+\t\t\treg_arg_name(env, argno), tname, reg_smin(reg), off);\n \t\treturn -EACCES;\n \t}\n \n-\toff += reg-\u003evar_off.value;\n-\n-\tif (off \u003c 0) {\n+\tif (min_off \u003c 0) {\n \t\tverbose(env,\n-\t\t\t\"%s is ptr_%s invalid negative access: off=%d\\n\",\n-\t\t\treg_arg_name(env, argno), tname, off);\n+\t\t\t\"%s is ptr_%s invalid negative access: off=%lld\\n\",\n+\t\t\treg_arg_name(env, argno), tname, min_off);\n \t\treturn -EACCES;\n \t}\n \n \tif (reg-\u003etype \u0026 MEM_USER) {\n \t\tverbose(env,\n-\t\t\t\"%s is ptr_%s access user memory: off=%d\\n\",\n-\t\t\treg_arg_name(env, argno), tname, off);\n+\t\t\t\"%s is ptr_%s access user memory\\n\",\n+\t\t\treg_arg_name(env, argno), tname);\n \t\treturn -EACCES;\n \t}\n \n \tif (reg-\u003etype \u0026 MEM_PERCPU) {\n \t\tverbose(env,\n-\t\t\t\"%s is ptr_%s access percpu memory: off=%d\\n\",\n-\t\t\treg_arg_name(env, argno), tname, off);\n+\t\t\t\"%s is ptr_%s access percpu memory\\n\",\n+\t\t\treg_arg_name(env, argno), tname);\n \t\treturn -EACCES;\n \t}\n \n@@ -6393,6 +6422,18 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,\n \t}\n \n \tif (env-\u003eops-\u003ebtf_struct_access \u0026\u0026 !type_is_alloc(reg-\u003etype) \u0026\u0026 atype == BPF_WRITE) {\n+\t\tif (!tnum_is_const(reg-\u003evar_off)) {\n+\t\t\tchar tn_buf[48];\n+\n+\t\t\ttnum_strn(tn_buf, sizeof(tn_buf), reg-\u003evar_off);\n+\t\t\tverbose(env,\n+\t\t\t\t\"%s is ptr_%s invalid variable offset: off=%d, var_off=%s\\n\",\n+\t\t\t\treg_arg_name(env, argno), tname, off, tn_buf);\n+\t\t\treturn -EACCES;\n+\t\t}\n+\n+\t\toff += reg-\u003evar_off.value;\n+\n \t\tif (!btf_is_kernel(reg-\u003ebtf)) {\n \t\t\tverifier_bug(env, \"reg-\u003ebtf must be kernel btf\");\n \t\t\treturn -EFAULT;\n@@ -14046,6 +14087,46 @@ static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 of\n \treturn *kfunc.flags \u0026 KF_SPINLOCK_SAFE;\n }\n \n+/*\n+ * True if insn calls a helper/kfunc that requires one of its arguments to\n+ * be a stack pointer with a constant offset.\n+ */\n+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)\n+{\n+\tconst struct bpf_insn *insn = \u0026env-\u003eprog-\u003einsnsi[insn_idx];\n+\tu32 *flags, btf_id;\n+\n+\tif (bpf_helper_call(insn)) {\n+\t\treturn insn-\u003eimm == BPF_FUNC_dynptr_from_mem ||\n+\t\t insn-\u003eimm == BPF_FUNC_ringbuf_reserve_dynptr;\n+\t}\n+\n+\t/* vmlinux kfuncs only */\n+\tif (!bpf_pseudo_kfunc_call(insn) || insn-\u003eoff != 0)\n+\t\treturn false;\n+\tbtf_id = insn-\u003eimm;\n+\n+\tflags = btf_kfunc_flags(btf_vmlinux, btf_id, env-\u003eprog);\n+\tif (flags \u0026\u0026 (*flags \u0026 (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))\n+\t\treturn true;\n+\n+\tif (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||\n+\t btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||\n+\t btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||\n+\t btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||\n+\t btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||\n+\t btf_id == special_kfunc_list[KF_bpf_local_irq_restore])\n+\t\treturn true;\n+\n+\tif (btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb] ||\n+\t btf_id == special_kfunc_list[KF_bpf_dynptr_from_xdp] ||\n+\t btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta] ||\n+\t btf_id == special_kfunc_list[KF_bpf_dynptr_from_file])\n+\t\treturn true;\n+\n+\treturn false;\n+}\n+\n static bool is_sync_callback_calling_kfunc(u32 btf_id)\n {\n \treturn is_bpf_rbtree_add_kfunc(btf_id);\n@@ -15582,6 +15663,50 @@ static int sanitize_check_bounds(struct bpf_verifier_env *env,\n \treturn 0;\n }\n \n+static void scalar_step_add(struct bpf_reg_state *dst_reg,\n+\t\t\t const struct bpf_reg_state *a,\n+\t\t\t const struct bpf_reg_state *b)\n+{\n+\tu16 base, step;\n+\n+\t/* If either 'a' or 'b' is a constant, update the base/step for the counterpart. */\n+\tif (tnum_is_const(b-\u003evar_off)) {\n+\t\tstep = a-\u003estep;\n+\t\tbase = imod((s64)a-\u003ebase + (s64)b-\u003evar_off.value, step);\n+\t} else if (tnum_is_const(a-\u003evar_off)) {\n+\t\tstep = b-\u003estep;\n+\t\tbase = imod((s64)b-\u003ebase + (s64)a-\u003evar_off.value, step);\n+\t} else {\n+\t\tstep = 1;\n+\t\tbase = 0;\n+\t}\n+\tdst_reg-\u003ebase = base;\n+\tdst_reg-\u003estep = step;\n+}\n+\n+static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)\n+{\n+\tu64 amount = src_reg-\u003evar_off.value;\n+\n+\tif (tnum_is_const(src_reg-\u003evar_off) \u0026\u0026 (s64)amount \u003e= 0 \u0026\u0026\n+\t !check_mul_overflow(dst_reg-\u003estep, amount, \u0026dst_reg-\u003estep) \u0026\u0026\n+\t dst_reg-\u003estep != 0)\n+\t\tdst_reg-\u003ebase = (dst_reg-\u003ebase * amount) % dst_reg-\u003estep;\n+\telse\n+\t\treg_step_reset(dst_reg);\n+}\n+\n+static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)\n+{\n+\tu64 amount = src_reg-\u003evar_off.value;\n+\n+\tif (tnum_is_const(src_reg-\u003evar_off) \u0026\u0026 amount \u003c 64 \u0026\u0026\n+\t !check_mul_overflow(dst_reg-\u003estep, 1ull \u003c\u003c amount, \u0026dst_reg-\u003estep))\n+\t\tdst_reg-\u003ebase = (dst_reg-\u003ebase * (1ull \u003c\u003c amount)) % dst_reg-\u003estep;\n+\telse\n+\t\treg_step_reset(dst_reg);\n+}\n+\n /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.\n * Caller should also handle BPF_MOV case separately.\n * If we return -EACCES, caller may want to try again treating pointer as a\n@@ -15739,6 +15864,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn\n \t\t * added into the variable offset, and we copy the fixed offset\n \t\t * from ptr_reg.\n \t\t */\n+\t\tscalar_step_add(dst_reg, ptr_reg, off_reg);\n \t\tdst_reg-\u003er64 = cnum64_add(ptr_reg-\u003er64, off_reg-\u003er64);\n \t\tdst_reg-\u003evar_off = tnum_add(ptr_reg-\u003evar_off, off_reg-\u003evar_off);\n \t\tdst_reg-\u003eraw = ptr_reg-\u003eraw;\n@@ -15800,6 +15926,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn\n \t\t\tif ((!known \u0026\u0026 smin_val \u003c 0) || dst_reg-\u003erange \u003c 0)\n \t\t\t\tmemset(\u0026dst_reg-\u003eraw, 0, sizeof(dst_reg-\u003eraw));\n \t\t}\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_AND:\n \tcase BPF_OR:\n@@ -16499,6 +16626,7 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins\n \t\t * Bounds will be re-derived from the new tnum later.\n \t\t */\n \t\t__mark_reg_unbounded(dst_reg);\n+\t\treg_step_reset(dst_reg);\n \t}\n \t/* For bswap16/32, truncate dst register to match the swapped size */\n \tif (insn-\u003eimm == 16 || insn-\u003eimm == 32)\n@@ -16625,6 +16753,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t */\n \tswitch (opcode) {\n \tcase BPF_ADD:\n+\t\tscalar_step_add(dst_reg, dst_reg, \u0026src_reg);\n \t\tscalar32_min_max_add(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_add(dst_reg, \u0026src_reg);\n \t\tdst_reg-\u003evar_off = tnum_add(dst_reg-\u003evar_off, src_reg.var_off);\n@@ -16633,6 +16762,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\tscalar32_min_max_sub(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_sub(dst_reg, \u0026src_reg);\n \t\tdst_reg-\u003evar_off = tnum_sub(dst_reg-\u003evar_off, src_reg.var_off);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_NEG:\n \t\tenv-\u003efake_reg[0] = *dst_reg;\n@@ -16640,11 +16770,13 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\tscalar32_min_max_sub(dst_reg, \u0026env-\u003efake_reg[0]);\n \t\tscalar_min_max_sub(dst_reg, \u0026env-\u003efake_reg[0]);\n \t\tdst_reg-\u003evar_off = tnum_neg(env-\u003efake_reg[0].var_off);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_MUL:\n \t\tdst_reg-\u003evar_off = tnum_mul(dst_reg-\u003evar_off, src_reg.var_off);\n \t\tscalar32_min_max_mul(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_mul(dst_reg, \u0026src_reg);\n+\t\tscalar_step_mul(dst_reg, \u0026src_reg);\n \t\tbreak;\n \tcase BPF_DIV:\n \t\t/* BPF div specification: x / 0 = 0 */\n@@ -16662,6 +16794,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\t\t\tscalar_min_max_sdiv(dst_reg, \u0026src_reg);\n \t\t\telse\n \t\t\t\tscalar_min_max_udiv(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_MOD:\n \t\t/* BPF mod specification: x % 0 = x */\n@@ -16677,6 +16810,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\t\t\tscalar_min_max_smod(dst_reg, \u0026src_reg);\n \t\t\telse\n \t\t\t\tscalar_min_max_umod(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_AND:\n \t\tif (tnum_is_const(src_reg.var_off)) {\n@@ -16687,6 +16821,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\tdst_reg-\u003evar_off = tnum_and(dst_reg-\u003evar_off, src_reg.var_off);\n \t\tscalar32_min_max_and(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_and(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_OR:\n \t\tif (tnum_is_const(src_reg.var_off)) {\n@@ -16697,32 +16832,38 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,\n \t\tdst_reg-\u003evar_off = tnum_or(dst_reg-\u003evar_off, src_reg.var_off);\n \t\tscalar32_min_max_or(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_or(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_XOR:\n \t\tdst_reg-\u003evar_off = tnum_xor(dst_reg-\u003evar_off, src_reg.var_off);\n \t\tscalar32_min_max_xor(dst_reg, \u0026src_reg);\n \t\tscalar_min_max_xor(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_LSH:\n \t\tif (alu32)\n \t\t\tscalar32_min_max_lsh(dst_reg, \u0026src_reg);\n \t\telse\n \t\t\tscalar_min_max_lsh(dst_reg, \u0026src_reg);\n+\t\tscalar_step_lsh(dst_reg, \u0026src_reg);\n \t\tbreak;\n \tcase BPF_RSH:\n \t\tif (alu32)\n \t\t\tscalar32_min_max_rsh(dst_reg, \u0026src_reg);\n \t\telse\n \t\t\tscalar_min_max_rsh(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_ARSH:\n \t\tif (alu32)\n \t\t\tscalar32_min_max_arsh(dst_reg, \u0026src_reg);\n \t\telse\n \t\t\tscalar_min_max_arsh(dst_reg, \u0026src_reg);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tcase BPF_END:\n \t\tscalar_byte_swap(dst_reg, insn);\n+\t\treg_step_reset(dst_reg);\n \t\tbreak;\n \tdefault:\n \t\tbreak;\n@@ -16934,6 +17075,45 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,\n \treturn 0;\n }\n \n+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n+\t\t struct cnum64 range, u16 step)\n+{\n+\treg-\u003er64 = range;\n+\treg-\u003er32 = CNUM32_UNBOUNDED;\n+\treg-\u003estep = step;\n+\treg-\u003ebase = imod(cnum64_smin(range), step);\n+\treg-\u003evar_off = tnum_unknown;\n+\treg_bounds_sync(reg); /* this should infer the tnum alignment */\n+\treturn reg_bounds_sanity_check(env, reg, \"bpf_set_reg_range\");\n+}\n+\n+/* acc := acc U src, matching types only. Caller must clear acc's scalar ID. */\n+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,\n+\t\t const struct bpf_reg_state *src)\n+{\n+\tu16 base, step;\n+\n+\tif (acc-\u003etype != src-\u003etype) {\n+\t\tverifier_bug(env, \"union of registers with different types\");\n+\t\treturn -EFAULT;\n+\t}\n+\tacc-\u003er64 = cnum64_union(acc-\u003er64, src-\u003er64);\n+\tacc-\u003er32 = cnum32_union(acc-\u003er32, src-\u003er32);\n+\tacc-\u003evar_off = tnum_union(acc-\u003evar_off, src-\u003evar_off);\n+\n+\t/* Retain a common congruence if the bases agree modulo the gcd. */\n+\tstep = gcd(acc-\u003estep, src-\u003estep);\n+\tbase = acc-\u003ebase % step;\n+\tif (base != src-\u003ebase % step) {\n+\t\treg_step_reset(acc);\n+\t} else {\n+\t\tacc-\u003ebase = base;\n+\t\tacc-\u003estep = step;\n+\t}\n+\treg_bounds_sync(acc);\n+\treturn reg_bounds_sanity_check(env, acc, \"bpf_reg_union\");\n+}\n+\n /* check validity of 32-bit and 64-bit arithmetic operations */\n static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)\n {\n@@ -17203,8 +17383,6 @@ static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,\n \n static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,\n \t\t\t\tu8 opcode, bool is_jmp32);\n-static u8 rev_opcode(u8 opcode);\n-\n /*\n * Learn more information about live branches by simulating refinement on both branches.\n * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means\n@@ -17213,7 +17391,7 @@ static u8 rev_opcode(u8 opcode);\n static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)\n {\n \t/* Fallthrough (FALSE) branch */\n-\tregs_refine_cond_op(\u0026env-\u003efalse_reg1, \u0026env-\u003efalse_reg2, rev_opcode(opcode), is_jmp32);\n+\tregs_refine_cond_op(\u0026env-\u003efalse_reg1, \u0026env-\u003efalse_reg2, bpf_rev_opcode(opcode), is_jmp32);\n \treg_bounds_sync(\u0026env-\u003efalse_reg1);\n \treg_bounds_sync(\u0026env-\u003efalse_reg2);\n \t/*\n@@ -17399,7 +17577,7 @@ static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_s\n \treturn simulate_both_branches_taken(env, opcode, is_jmp32);\n }\n \n-static int flip_opcode(u32 opcode)\n+int bpf_flip_opcode(u32 opcode)\n {\n \t/* How can we transform \"a \u003cop\u003e b\" into \"b \u003cop\u003e a\"? */\n \tstatic const u8 opcode_flip[16] = {\n@@ -17430,7 +17608,7 @@ static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,\n \t\tpkt = dst_reg;\n \t} else if (dst_reg-\u003etype == PTR_TO_PACKET_END) {\n \t\tpkt = src_reg;\n-\t\topcode = flip_opcode(opcode);\n+\t\topcode = bpf_flip_opcode(opcode);\n \t} else {\n \t\treturn -1;\n \t}\n@@ -17485,7 +17663,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r\n \n \t\t/* arrange that reg2 is a scalar, and reg1 is a pointer */\n \t\tif (!is_reg_const(reg2, is_jmp32)) {\n-\t\t\topcode = flip_opcode(opcode);\n+\t\t\topcode = bpf_flip_opcode(opcode);\n \t\t\tswap(reg1, reg2);\n \t\t}\n \t\t/* and ensure that reg2 is a constant */\n@@ -17519,7 +17697,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r\n /* Opcode that corresponds to a *false* branch condition.\n * E.g., if r1 \u003c r2, then reverse (false) condition is r1 \u003e= r2\n */\n-static u8 rev_opcode(u8 opcode)\n+u8 bpf_rev_opcode(u8 opcode)\n {\n \tswitch (opcode) {\n \tcase BPF_JEQ:\t\treturn BPF_JNE;\n@@ -17554,7 +17732,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state\n \tcase BPF_JGT:\n \tcase BPF_JSGE:\n \tcase BPF_JSGT:\n-\t\topcode = flip_opcode(opcode);\n+\t\topcode = bpf_flip_opcode(opcode);\n \t\tswap(reg1, reg2);\n \t\tbreak;\n \tdefault:\n@@ -17631,6 +17809,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state\n \t\t * violations if we're on a dead branch.\n \t\t */\n \t\t__mark_reg_unbounded(reg1);\n+\t\treg_step_reset(reg1);\n \t\tif (is_jmp32) {\n \t\t\tt = tnum_and(tnum_subreg(reg1-\u003evar_off), tnum_const(~val));\n \t\t\treg1-\u003evar_off = tnum_with_subreg(reg1-\u003evar_off, t);\n@@ -19465,6 +19644,204 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)\n \treturn -EFAULT;\n }\n \n+static bool has_entered_loop(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint prev_insn_idx = env-\u003eprev_insn_idx;\n+\tint insn_idx = env-\u003einsn_idx;\n+\n+\treturn aux[insn_idx].loop_entry \u0026\u0026\n+\t (prev_insn_idx == -1 ||\n+\t\tbpf_loop_at_index(env, prev_insn_idx) != bpf_loop_at_index(env, insn_idx));\n+}\n+\n+static bool is_next_loop_iteration(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint prev_insn_idx = env-\u003eprev_insn_idx;\n+\tint insn_idx = env-\u003einsn_idx;\n+\n+\treturn aux[insn_idx].loop_entry \u0026\u0026\n+\t (prev_insn_idx != -1 \u0026\u0026\n+\t\tbpf_loop_at_index(env, prev_insn_idx) == bpf_loop_at_index(env, insn_idx));\n+}\n+\n+static bool has_exited_loop(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tint prev_insn_idx = env-\u003eprev_insn_idx;\n+\tint insn_idx = env-\u003einsn_idx;\n+\tint prev_loop_idx, h;\n+\n+\tif (prev_insn_idx == -1)\n+\t\treturn false;\n+\n+\tprev_loop_idx = bpf_loop_at_index(env, prev_insn_idx);\n+\tif (prev_loop_idx \u003c 0)\n+\t\treturn false;\n+\n+\t/* Still inside the previous instruction's loop if that loop encloses insn_idx */\n+\tfor (h = bpf_loop_at_index(env, insn_idx); h \u003e= 0; h = aux[h].loop_header)\n+\t\tif (h == prev_loop_idx)\n+\t\t\treturn false;\n+\n+\treturn true;\n+}\n+\n+/*\n+ * Push the loop entered at insn_idx onto the stack. Usually this adds a single\n+ * entry on top of its enclosing loop. However, an edge may enter an inner loop\n+ * directly, bypassing the header(s) of its enclosing loop(s), e.g.:\n+ *\n+ * 1: for (...): // enclosing loop, header at 1\n+ * 2: for (...): // inner loop, header at 2\n+ * ...\n+ * 3: if ...:\n+ * goto 2b; // enters loop 2 without going through header 1\n+ *\n+ * Such a bypass makes the enclosing loop irreducible, so its header is missing\n+ * from the stack and both headers (1) and (2) need to be pushed onto stack.\n+ * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;\n+ * the bypassed ancestors are irreducible and pushed as non-terminating.\n+ *\n+ * Assumes loop_stack_pop() has already truncated the stack to the common ancestor\n+ * of the bpf_loop_at_index(env-\u003eprev_insn_idx) and bpf_loop_at_index(env-\u003einsn_idx).\n+ */\n+static int loop_stack_push(struct bpf_verifier_env *env,\n+\t\t\t struct bpf_verifier_state *entry_state,\n+\t\t\t bool terminates,\n+\t\t\t struct bpf_loop_iters *iters)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_func_state *frame = cur_func(env);\n+\tstruct loop_stack_entry *loop_stack = frame-\u003eloop_stack;\n+\tu32 missing_headers[LOOP_STACK_SIZE];\n+\tu32 cnt = frame-\u003eloop_stack_cnt;\n+\tu32 num_missing = 0;\n+\tint h;\n+\n+\tfor (h = bpf_loop_at_index(env, env-\u003einsn_idx); h \u003e= 0; h = aux[h].loop_header, num_missing++) {\n+\t\tif (cnt \u0026\u0026 loop_stack[cnt - 1].loop_id == h)\n+\t\t\tbreak;\n+\t\tif (num_missing == LOOP_STACK_SIZE)\n+\t\t\tgoto e2big;\n+\t\tmissing_headers[num_missing] = h;\n+\t}\n+\n+\tfor (; num_missing; num_missing--, cnt++) {\n+\t\tif (cnt == LOOP_STACK_SIZE)\n+\t\t\tgoto e2big;\n+\t\tloop_stack[cnt].loop_id = missing_headers[num_missing - 1];\n+\t\tif (num_missing == 1) {\n+\t\t\tloop_stack[cnt].iters = terminates ? *iters : (struct bpf_loop_iters){};\n+\t\t\tloop_stack[cnt].terminates = terminates;\n+\t\t\tloop_stack[cnt].entry_state = entry_state;\n+\t\t} else {\n+\t\t\tloop_stack[cnt].iters = (struct bpf_loop_iters){};\n+\t\t\tloop_stack[cnt].terminates = false;\n+\t\t\tloop_stack[cnt].entry_state = NULL;\n+\t\t}\n+\t}\n+\tframe-\u003eloop_stack_cnt = cnt;\n+\treturn 0;\n+\n+e2big:\n+\tverbose(env, \"Too many nested loops (%d/%d) at %d\\n\", cnt, num_missing, env-\u003einsn_idx);\n+\treturn -E2BIG;\n+}\n+\n+/*\n+ * An exit from a loop can cross several nested loops, e.g.:\n+ *\n+ * 1: for (...):\n+ * 2: for (...):\n+ * 3: for (...):\n+ * if ...: // before goto the loop stack is [1, 2, 3 \u003ctop\u003e]\n+ * goto 1b; // after goto it should become [1]\n+ */\n+static int loop_stack_pop(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\n+\tstruct bpf_func_state *frame = cur_func(env);\n+\tint h, i;\n+\n+\t/*\n+\t * Walk the loop nest of insn_idx outwards (innermost first) and stop at\n+\t * the first loop that is present on the stack - that loop is the common\n+\t * ancestor and becomes the new top. If no enclosing loop is on the\n+\t * stack, drop all loops.\n+\t */\n+\tfor (h = bpf_loop_at_index(env, env-\u003einsn_idx); h \u003e= 0; h = aux[h].loop_header) {\n+\t\tfor (i = frame-\u003eloop_stack_cnt - 1; i \u003e= 0; i--) {\n+\t\t\tif (frame-\u003eloop_stack[i].loop_id == h) {\n+\t\t\t\tframe-\u003eloop_stack_cnt = i + 1;\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tframe-\u003eloop_stack_cnt = 0;\n+\treturn 0;\n+}\n+\n+static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_func_state *frame = cur_func(env);\n+\tstruct loop_stack_entry *entry;\n+\n+\tif (frame-\u003eloop_stack_cnt == 0) {\n+\t\tverifier_bug(env, \"%s: loop stack empty at %d\", __FUNCTION__, env-\u003einsn_idx);\n+\t\treturn -EFAULT;\n+\t}\n+\n+\tentry = \u0026frame-\u003eloop_stack[frame-\u003eloop_stack_cnt - 1];\n+\tif (!entry-\u003eterminates)\n+\t\treturn 0;\n+\n+\treturn bpf_clamp_scev_regs(env, frame, env-\u003einsn_idx, entry-\u003eentry_state, \u0026entry-\u003eiters);\n+}\n+\n+static int handle_loop_entry_exit(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_verifier_state *cur = env-\u003ecur_state;\n+\tstruct bpf_loop_iters iters;\n+\tbool terminates;\n+\tint err;\n+\n+\tif (is_next_loop_iteration(env)) {\n+\t\terr = maybe_clamp_scev_regs(env);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\tif (has_exited_loop(env)) {\n+\t\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2)\n+\t\t\tverbose(env, \"exiting loop %d\\n\", bpf_loop_at_index(env, env-\u003eprev_insn_idx));\n+\t\terr = loop_stack_pop(env);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\tif (has_entered_loop(env)) {\n+\t\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2)\n+\t\t\tverbose(env, \"entering loop %d\\n\", bpf_loop_at_index(env, env-\u003einsn_idx));\n+\t\terr = bpf_compute_loop_iters(env, env-\u003ecur_state, \u0026iters);\n+\t\tif (err \u003c 0)\n+\t\t\treturn err;\n+\t\tterminates = err == 1;\n+\t\tif (terminates) {\n+\t\t\terr = bpf_split_cur_state(env);\n+\t\t\tif (err)\n+\t\t\t\treturn err;\n+\t\t\terr = bpf_widen_scev_regs(env, cur, cur-\u003eparent, \u0026iters);\n+\t\t\tif (err \u003c 0)\n+\t\t\t\treturn err;\n+\t\t}\n+\t\terr = loop_stack_push(env, env-\u003ecur_state-\u003eparent, terminates, \u0026iters);\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\treturn 0;\n+}\n+\n static int do_check(struct bpf_verifier_env *env)\n {\n \tbool pop_log = !(env-\u003elog.level \u0026 BPF_LOG_LEVEL2);\n@@ -19479,6 +19856,12 @@ static int do_check(struct bpf_verifier_env *env)\n \t\tstruct bpf_insn_aux_data *insn_aux;\n \t\tint err;\n \n+\t\tif (signal_pending(current))\n+\t\t\treturn -EAGAIN;\n+\n+\t\tif (need_resched())\n+\t\t\tcond_resched();\n+\n \t\t/* reset current history entry on each new instruction */\n \t\tenv-\u003ecur_hist_ent = NULL;\n \n@@ -19525,6 +19908,15 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\t}\n \t\t}\n \n+\t\t/*\n+\t\t * Possibly widen the registers before creating a checkpoint\n+\t\t * in bpf_is_state_visited(). The next loop iteration will\n+\t\t * have a chance to hit this checkpoint and converge.\n+\t\t */\n+\t\terr = handle_loop_entry_exit(env);\n+\t\tif (err)\n+\t\t\treturn err;\n+\n \t\tif (bpf_is_prune_point(env, env-\u003einsn_idx)) {\n \t\t\terr = bpf_is_state_visited(env, env-\u003einsn_idx);\n \t\t\tif (err \u003c 0)\n@@ -19550,12 +19942,6 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\t\treturn err;\n \t\t}\n \n-\t\tif (signal_pending(current))\n-\t\t\treturn -EAGAIN;\n-\n-\t\tif (need_resched())\n-\t\t\tcond_resched();\n-\n \t\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2 \u0026\u0026 do_print_state) {\n \t\t\tverbose(env, \"\\nfrom %d to %d%s:\",\n \t\t\t\tenv-\u003eprev_insn_idx, env-\u003einsn_idx,\n@@ -19565,6 +19951,13 @@ static int do_check(struct bpf_verifier_env *env)\n \t\t\tdo_print_state = false;\n \t\t}\n \n+\t\tif (bpf_loop_at_index(env, env-\u003einsn_idx) \u003e= 0 \u0026\u0026\n+\t\t cur_func(env)-\u003eloop_stack_cnt == 0) {\n+\t\t\tverifier_bug(env, \"loop stack empty at %d, while inside the loop %d\\n\",\n+\t\t\t\t env-\u003einsn_idx, bpf_loop_at_index(env, env-\u003einsn_idx));\n+\t\t\treturn -EFAULT;\n+\t\t}\n+\n \t\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL) {\n \t\t\tif (verifier_state_scratched(env))\n \t\t\t\tprint_insn_state(env, state, state-\u003ecurframe);\n@@ -22441,6 +22834,45 @@ static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)\n \treturn false;\n }\n \n+/* Various log level 2 information about the program */\n+static void log_program(struct bpf_verifier_env *env)\n+{\n+\tstruct bpf_insn_aux_data *insn_aux = env-\u003einsn_aux_data;\n+\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n+\tu32 insn_cnt = env-\u003eprog-\u003elen;\n+\tu64 pos, insn_pos;\n+\tu32 i, j;\n+\n+\tverbose(env, \"Program dump (scc? loop_header? idom insn#: live_regs_before):\\n\");\n+\tfor (i = 0; i \u003c insn_cnt; ++i) {\n+\t\tverbose_linfo(env, i, \" ; \");\n+\t\tif (env-\u003einsn_aux_data[i].scc)\n+\t\t\tverbose(env, \"%3d \", env-\u003einsn_aux_data[i].scc);\n+\t\telse\n+\t\t\tverbose(env, \" \");\n+\t\tif (env-\u003einsn_aux_data[i].loop_header \u003e= 0)\n+\t\t\tverbose(env, \"%3d \", env-\u003einsn_aux_data[i].loop_header);\n+\t\telse\n+\t\t\tverbose(env, \" \");\n+\t\tverbose(env, \"%3d \", env-\u003eidoms[i]);\n+\t\tverbose(env, \"%3d: \", i);\n+\t\tfor (j = BPF_REG_0; j \u003c BPF_REG_10; ++j)\n+\t\t\tif (insn_aux[i].live_regs_before \u0026 BIT(j))\n+\t\t\t\tverbose(env, \"%d\", j);\n+\t\t\telse\n+\t\t\t\tverbose(env, \".\");\n+\t\tverbose(env, \" \");\n+\t\tpos = env-\u003elog.end_pos;\n+\t\tbpf_verbose_insn(env, \u0026insns[i]);\n+\t\tinsn_pos = env-\u003elog.end_pos;\n+\t\tif (insn_aux[i].zext_dst)\n+\t\t\tverbose(env, \"%*c; zext\", bpf_vlog_alignment(insn_pos - pos), ' ');\n+\t\tverbose(env, \"\\n\");\n+\t\tif (bpf_is_ldimm64(\u0026insns[i]))\n+\t\t\ti++;\n+\t}\n+}\n+\n int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \t struct bpf_log_attr *attr_log)\n {\n@@ -22642,10 +23074,29 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n \n+\tret = bpf_compute_idoms(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n+\tret = bpf_compute_loops(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n \tret = bpf_compute_live_registers(env);\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n \n+\tif (env-\u003elog.level \u0026 BPF_LOG_LEVEL2)\n+\t\tlog_program(env);\n+\n+\tret = bpf_init_scev(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n+\tret = bpf_compute_scev(env);\n+\tif (ret \u003c 0)\n+\t\tgoto skip_full_check;\n+\n \tret = mark_fastcall_patterns(env);\n \tif (ret \u003c 0)\n \t\tgoto skip_full_check;\n@@ -22791,9 +23242,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \trelease_btfs(env);\n err_free_env:\n \tbpf_free_subprog_jts(env);\n+\tif (env-\u003einsn_aux_data)\n+\t\tbpf_clear_insn_aux_data(env, 0, env-\u003einsn_aux_data_len);\n \tvfree(env-\u003einsn_aux_data);\n \tkvfree(env-\u003efd_array);\n+\tbpf_free_scev(env);\n \tbpf_stack_liveness_free(env);\n+\tkvfree(env-\u003ecfg.postorder_nums);\n \tkvfree(env-\u003ecfg.insn_postorder);\n \tkvfree(env-\u003escc_info);\n \tkvfree(env-\u003esucc);\n@@ -22801,6 +23256,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n \tkvfree(env-\u003ecallx_edges);\n \tkvfree(env-\u003efunc_ptrs);\n \tbpf_diag_free(env);\n+\tkvfree(env-\u003eidoms);\n \tkvfree(env);\n \treturn ret;\n }\ndiff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c\nindex 8a6d341b754ac..2bc1ef910c16d 100644\n--- a/tools/testing/selftests/bpf/prog_tests/verifier.c\n+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c\n@@ -19,12 +19,14 @@\n #include \"verifier_basic_stack.skel.h\"\n #include \"verifier_bitfield_write.skel.h\"\n #include \"verifier_bounds.skel.h\"\n+#include \"verifier_bounds_step.skel.h\"\n #include \"verifier_bounds_deduction.skel.h\"\n #include \"verifier_bounds_deduction_non_const.skel.h\"\n #include \"verifier_bounds_mix_sign_unsign.skel.h\"\n #include \"verifier_bpf_get_stack.skel.h\"\n #include \"verifier_bpf_trap.skel.h\"\n #include \"verifier_bswap.skel.h\"\n+#include \"verifier_btf_array_access.skel.h\"\n #include \"verifier_btf_ctx_access.skel.h\"\n #include \"verifier_btf_flex_array.skel.h\"\n #include \"verifier_btf_unreliable_prog.skel.h\"\n@@ -55,6 +57,7 @@\n #include \"verifier_helper_packet_access.skel.h\"\n #include \"verifier_helper_restricted.skel.h\"\n #include \"verifier_helper_value_access.skel.h\"\n+#include \"verifier_idoms.skel.h\"\n #include \"verifier_int_ptr.skel.h\"\n #include \"verifier_iterating_callbacks.skel.h\"\n #include \"verifier_jeq_infer_not_null.skel.h\"\n@@ -71,6 +74,7 @@\n #include \"verifier_live_stack.skel.h\"\n #include \"verifier_liveness_exp.skel.h\"\n #include \"verifier_load_acquire.skel.h\"\n+#include \"verifier_loop_hierarchy.skel.h\"\n #include \"verifier_loops1.skel.h\"\n #include \"verifier_lwt.skel.h\"\n #include \"verifier_map_in_map.skel.h\"\n@@ -103,6 +107,7 @@\n #include \"verifier_ringbuf.skel.h\"\n #include \"verifier_runtime_jit.skel.h\"\n #include \"verifier_scalar_ids.skel.h\"\n+#include \"verifier_scev.skel.h\"\n #include \"verifier_sdiv.skel.h\"\n #include \"verifier_search_pruning.skel.h\"\n #include \"verifier_sock.skel.h\"\n@@ -203,12 +208,14 @@ void test_verifier_arena_globals2(void) { RUN(verifier_arena_globals2); }\n void test_verifier_basic_stack(void) { RUN(verifier_basic_stack); }\n void test_verifier_bitfield_write(void) { RUN(verifier_bitfield_write); }\n void test_verifier_bounds(void) { RUN(verifier_bounds); }\n+void test_verifier_bounds_step(void) { RUN(verifier_bounds_step); }\n void test_verifier_bounds_deduction(void) { RUN(verifier_bounds_deduction); }\n void test_verifier_bounds_deduction_non_const(void) { RUN(verifier_bounds_deduction_non_const); }\n void test_verifier_bounds_mix_sign_unsign(void) { RUN(verifier_bounds_mix_sign_unsign); }\n void test_verifier_bpf_get_stack(void) { RUN(verifier_bpf_get_stack); }\n void test_verifier_bpf_trap(void) { RUN(verifier_bpf_trap); }\n void test_verifier_bswap(void) { RUN(verifier_bswap); }\n+void test_verifier_btf_array_access(void) { RUN(verifier_btf_array_access); }\n void test_verifier_btf_ctx_access(void) { RUN(verifier_btf_ctx_access); }\n void test_verifier_btf_flex_array(void) { RUN(verifier_btf_flex_array); }\n void test_verifier_btf_unreliable_prog(void) { RUN(verifier_btf_unreliable_prog); }\n@@ -239,6 +246,7 @@ void test_verifier_helper_access_var_len(void) { RUN(verifier_helper_access_var_\n void test_verifier_helper_packet_access(void) { RUN(verifier_helper_packet_access); }\n void test_verifier_helper_restricted(void) { RUN(verifier_helper_restricted); }\n void test_verifier_helper_value_access(void) { RUN(verifier_helper_value_access); }\n+void test_verifier_idoms(void) { RUN(verifier_idoms); }\n void test_verifier_int_ptr(void) { RUN(verifier_int_ptr); }\n void test_verifier_iterating_callbacks(void) { RUN(verifier_iterating_callbacks); }\n void test_verifier_jeq_infer_not_null(void) { RUN(verifier_jeq_infer_not_null); }\n@@ -255,6 +263,7 @@ void test_verifier_leak_ptr(void) { RUN(verifier_leak_ptr); }\n void test_verifier_linked_scalars(void) { RUN(verifier_linked_scalars); }\n void test_verifier_live_stack(void) { RUN(verifier_live_stack); }\n void test_verifier_liveness_exp(void) { RUN(verifier_liveness_exp); }\n+void test_verifier_loop_hierarchy(void) { RUN(verifier_loop_hierarchy); }\n void test_verifier_loops1(void) { RUN(verifier_loops1); }\n void test_verifier_lwt(void) { RUN(verifier_lwt); }\n void test_verifier_map_in_map(void) { RUN(verifier_map_in_map); }\n@@ -286,6 +295,7 @@ void test_verifier_regalloc(void) { RUN(verifier_regalloc); }\n void test_verifier_ringbuf(void) { RUN(verifier_ringbuf); }\n void test_verifier_runtime_jit(void) { RUN(verifier_runtime_jit); }\n void test_verifier_scalar_ids(void) { RUN(verifier_scalar_ids); }\n+void test_verifier_scev(void) { RUN(verifier_scev); }\n void test_verifier_sdiv(void) { RUN(verifier_sdiv); }\n void test_verifier_search_pruning(void) { RUN(verifier_search_pruning); }\n void test_verifier_sock(void) { RUN(verifier_sock); }\ndiff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h\nindex f3dbc3b59bff2..d7f706c3bc4af 100644\n--- a/tools/testing/selftests/bpf/progs/bpf_misc.h\n+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h\n@@ -43,6 +43,10 @@\n * __msg_unpriv Same as __msg but for unprivileged mode.\n * __not_msg_unpriv Same as __not_msg but for unprivileged mode.\n *\n+ * __msg_next Same as __msg but expects the match to be on the next\n+ * __msg_next_unpriv log line compared to the last match, not just some line\n+ * after the last match.\n+ *\n * __stderr Message expected to be found in bpf stderr stream. The\n * same regex rules apply like __msg.\n * __stderr_unpriv Same as __stderr but for unpriveleged mode.\n@@ -145,6 +149,7 @@\n \n #define __msg(msg)\t\t__test_tag(\"test_expect_msg=\" msg)\n #define __not_msg(msg)\t\t__test_tag(\"test_expect_not_msg=\" msg)\n+#define __msg_next(msg)\t\t__test_tag(\"test_expect_msg_next=\" msg)\n #define __xlated(msg)\t\t__test_tag(\"test_expect_xlated=\" msg)\n #define __jited(msg)\t\t__test_tag(\"test_jited=\" msg)\n #define __failure\t\t__test_tag(\"test_expect_failure\")\n@@ -153,6 +158,7 @@\n #define __skip(reason)\t\t__test_tag(\"test_skip=\" reason)\n #define __msg_unpriv(msg)\t__test_tag(\"test_expect_msg_unpriv=\" msg)\n #define __not_msg_unpriv(msg)\t__test_tag(\"test_expect_not_msg_unpriv=\" msg)\n+#define __msg_next_unpriv(msg)\t__test_tag(\"test_expect_msg_next_unpriv=\" msg)\n #define __xlated_unpriv(msg)\t__test_tag(\"test_expect_xlated_unpriv=\" msg)\n #define __jited_unpriv(msg)\t__test_tag(\"test_jited_unpriv=\" msg)\n #define __failure_unpriv\t__test_tag(\"test_expect_failure_unpriv\")\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c\nnew file mode 100644\nindex 0000000000000..cb55fc216bc8a\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c\n@@ -0,0 +1,307 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/bpf.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+\n+/*\n+ * Tests for the linear \"base + step * k\" description tracked per scalar\n+ * register.\n+ *\n+ * The base/step computed by scalar arithmetic is observed directly in the\n+ * level-2 register dump, printed as \"step=\u003cbase\u003e+\u003cstep\u003e\" when the register is\n+ * not the trivial base=0, step=1. Range inference that depends on the line\n+ * (e.g. a sign-crossing range with a non-power-of-2 step) is checked via the\n+ * resulting smin/smax, which feed ordinary signed branch decisions.\n+ *\n+ * Note: eq/neq branch checks do not consult base/step, so impossible-value\n+ * pruning is intentionally not relied upon here; the register dump is the\n+ * reliable signal.\n+ */\n+\n+/* a \u0026= 0xff; a *= 3 =\u003e multiples of 3, step=0+3 (not representable as tnum) */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__msg(\"r0 *= 3 {{.*}}step=0+3)\")\n+__naked void step_mul_non_pow2(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 0xff;\t\t\t\t\t\\\n+\tr0 *= 3;\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/* a \u0026= 0xff; a \u003c\u003c= 2 =\u003e step=0+4 */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__msg(\"r0 \u003c\u003c= 2 {{.*}}step=0+4)\")\n+__naked void step_lsh(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 0xff;\t\t\t\t\t\\\n+\tr0 \u003c\u003c= 2;\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/* a \u0026= 0xff; a *= 4; a += 1 =\u003e base shifts to 1, step=1+4 */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__msg(\"r0 += 1 {{.*}}step=1+4)\")\n+__naked void step_add_const_base(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 0xff;\t\t\t\t\t\\\n+\tr0 *= 4;\t\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Sign-crossing range with a non-power-of-2 step. After \"*= 3; += -3\" the value\n+ * set is {-3, 0, 3, 6}. The line description is tracked in signed space, so the\n+ * intersection keeps smax=6. A u64-modular intersection would mis-place the\n+ * line for the negative values and wrongly narrow smax to 4.\n+ */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__msg(\"r0 += -3 {{.*}}smax=smax32=6)\")\n+__naked void step_neg_value_range(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 3;\t\t\t\t\t\\\n+\tr0 *= 3;\t\t\t\t\t\\\n+\tr0 += -3;\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Same {-3, 0, 3, 6} value set: 6 is reachable, so \"if r0 s\u003e 4\" can be taken\n+ * and the illegal scalar dereference behind it must be rejected. Guards against\n+ * the unsound narrowing (smax=4) that would prune the branch and accept the\n+ * program. This rides on the signed comparison, which uses smin/smax.\n+ */\n+SEC(\"socket\")\n+__failure __msg(\"invalid mem access 'scalar'\")\n+__naked void step_neg_value_sound(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 3;\t\t\t\t\t\\\n+\tr0 *= 3;\t\t\t\t\t\\\n+\tr0 += -3;\t\t\t\t\t\\\n+\tif r0 s\u003e 4 goto l_bad_%=;\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+l_bad_%=:\t\t\t\t\t\t\\\n+\tr1 = *(u8 *)(r0 + 0);\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+struct step_val {\n+\t__u8 data[1024];\n+};\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_ARRAY);\n+\t__uint(max_entries, 1);\n+\t__type(key, __u32);\n+\t__type(value, struct step_val);\n+} step_map SEC(\".maps\");\n+\n+/* Old register [4..130, step 2] should prune cur register [8..64, step 4]. */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__msg(\"7: (27) r6 *= 4 ; R6=scalar({{.*}}umin32=8,{{.*}}umax32=68,{{.*}},step=0+4)\")\n+__msg(\"10: (27) r7 *= 2 ; R7=scalar({{.*}}umin32=4,{{.*}}umax32=130,{{.*}},step=0+2)\")\n+__msg(\"11: (25) if r0 \u003e 0x2a goto pc+1\")\n+__msg(\"from 11 to 13: safe\")\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__naked void step_prune_hit_multiple(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 \u0026= 0x0f;\t\t\t\t\t\\\n+\tr6 += 2;\t\t\t\t\t\\\n+\tr6 *= 4;\t\t\t\t\t\\\n+\tr7 \u0026= 0x3f;\t\t\t\t\t\\\n+\tr7 += 2;\t\t\t\t\t\\\n+\tr7 *= 2;\t\t\t\t\t\\\n+\tif r0 \u003e 42 goto 1f;\t/* can't predict */\t\\\n+\tr6 = r7;\t\t/* step=2 explored first, step=4 explored next */ \\\n+1:\tr0 = r10;\t\t\t\t\t\\\n+\tr6 = -r6;\t\t\t\t\t\\\n+\tr0 += r6;\t\t\t\t\t\\\n+\t*(u8 *)(r0 + 0) = 7;\t/* force r6 precise */\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32),\n+\t __imm(bpf_map_lookup_elem),\n+\t __imm_addr(step_map)\n+\t: __clobber_all);\n+}\n+\n+/* Old register [0..126, step 2] should not prune cur register [0..45, step 3]. */\n+SEC(\"socket\")\n+__failure __log_level(2)\n+__msg(\"6: (27) r6 *= 3 ; R6=scalar({{.*}}smin32=0,{{.*}}umax32=45,{{.*}},step=0+3)\")\n+__msg(\"8: (27) r7 *= 2 ; R7=scalar({{.*}}smin32=0,{{.*}}umax32=126,{{.*}},step=0+2)\")\n+__msg(\"9: (25) if r0 \u003e 0x2a goto pc+1\")\n+__msg(\"11: (15) if r6 == 0x3 goto pc+2\")\n+__msg(\"11: R6=scalar({{.*}},step=0+2)\")\n+__msg(\"13: (95) exit\")\n+__msg(\"from 9 to 11: {{.*}} R6=scalar({{.*}},step=0+3)\")\n+__msg(\"from 11 to 14\")\n+__msg(\"div by zero\")\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__naked void step_prune_miss_non_multiple(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 \u0026= 0x0f;\t\t\t\t\t\\\n+\tr6 *= 3;\t\t\t\t\t\\\n+\tr7 \u0026= 0x3f;\t\t\t\t\t\\\n+\tr7 *= 2;\t\t\t\t\t\\\n+\tif r0 \u003e 42 goto 1f;\t/* can't predict */\t\\\n+\tr6 = r7;\t\t/* step=2 explored first, step=3 explored next */ \\\n+1:\t\t\t\t\t\t\t\\\n+\tif r6 == 3 goto 2f;\t/* false if step=2, should not prune step=3 */ \\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\tr0 /= 0;\t\t/* trap */\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Constant current register lying on the cached line: cached is {0,3,6,...}\n+ * (step 3, base 0), current is the constant 6. range_within() takes the\n+ * constant branch: imod(6, 3) == base 0, so cur is on the line and the\n+ * (precise) state is pruned -\u003e \"safe\".\n+ */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"14: (27) r1 *= 3\")\t\t/* cached path: step 3 line */\n+__msg(\"16: (b7) r1 = 6\")\t\t/* current path: const 6, on the line */\n+__msg(\"17: safe\")\t\t\t/* pruned at join: imod(6, 3) == 0 */\n+__naked void step_prune_hit_const_on_line(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\t*(u32*)(r10 - 4) = r1;\t\t\t\t\\\n+\tr2 = r10;\t\t\t\t\t\\\n+\tr2 += -4;\t\t\t\t\t\\\n+\tr1 = %[step_map] ll;\t\t\t\t\\\n+\tcall %[bpf_map_lookup_elem];\t\t\t\\\n+\tif r0 == 0 goto l_out_%=;\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tr1 = r6;\t\t\t\t\t\\\n+\tr1 \u0026= 0xff;\t\t\t\t\t\\\n+\tif r6 \u003e 0 goto l_cur_%=;\t\t\t\\\n+\tr1 *= 3;\t\t\t/* old: step 3 */\t\\\n+\tgoto l_join_%=;\t\t\t\t\t\\\n+l_cur_%=:\t\t\t\t\t\t\\\n+\tr1 = 6;\t\t\t\t/* cur: const on line */\t\\\n+l_join_%=:\t\t\t\t\t\t\\\n+\tr0 = r7;\t\t\t\t\t\\\n+\tr0 += r1;\t\t\t/* r1 forced precise */\t\\\n+\tr2 = *(u8 *)(r0 + 0);\t\t\t\t\\\n+l_out_%=:\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32),\n+\t __imm(bpf_map_lookup_elem),\n+\t __imm_addr(step_map)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Constant current register NOT on the cached line: cached is {0,3,6,...}\n+ * (step 3, base 0), current is the constant 7. imod(7, 3) == 1 != base 0,\n+ * so range_within() fails and the join is traversed again. A power-of-two\n+ * step is avoided on purpose: with step 3 the tnum is loose enough to admit\n+ * 7, so imod() is\n+ * the sole check that rejects it. No failure shape is possible here: 7 is\n+ * within the line's bounds and tnum, and the cached line path already\n+ * verifies the whole outro, so an eager prune could not miss an error.\n+ */\n+SEC(\"socket\")\n+__success __log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"14: (27) r1 *= 3\")\t\t/* cached path: step 3 line */\n+__msg(\"16: (b7) r1 = 7\")\t\t/* current path: const 7, off the line */\n+/* not pruned: current continues past the join with the constant offset 7 */\n+__msg(\"19: R0=map_value({{.*}}imm=7) R1=7\")\n+__naked void step_prune_miss_const_off_line(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\t*(u32*)(r10 - 4) = r1;\t\t\t\t\\\n+\tr2 = r10;\t\t\t\t\t\\\n+\tr2 += -4;\t\t\t\t\t\\\n+\tr1 = %[step_map] ll;\t\t\t\t\\\n+\tcall %[bpf_map_lookup_elem];\t\t\t\\\n+\tif r0 == 0 goto l_out_%=;\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tr1 = r6;\t\t\t\t\t\\\n+\tr1 \u0026= 0xff;\t\t\t\t\t\\\n+\tif r6 \u003e 0 goto l_cur_%=;\t\t\t\\\n+\tr1 *= 3;\t\t\t/* old: step 3 */\t\\\n+\tgoto l_join_%=;\t\t\t\t\t\\\n+l_cur_%=:\t\t\t\t\t\t\\\n+\tr1 = 7;\t\t\t\t/* cur: const off line */\t\\\n+l_join_%=:\t\t\t\t\t\t\\\n+\tr0 = r7;\t\t\t\t\t\\\n+\tr0 += r1;\t\t\t/* r1 forced precise */\t\\\n+\tr2 = *(u8 *)(r0 + 0);\t\t\t\t\\\n+l_out_%=:\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32),\n+\t __imm(bpf_map_lookup_elem),\n+\t __imm_addr(step_map)\n+\t: __clobber_all);\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c\nnew file mode 100644\nindex 0000000000000..ab6b744573657\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c\n@@ -0,0 +1,506 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003cvmlinux.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_core_read.h\u003e\n+#include \"bpf_experimental.h\"\n+#include \"bpf_misc.h\"\n+\n+/*\n+ * Variable-offset access into arrays within a BTF access chain, e.g. a[i].b,\n+ * where 'i' is a register with a varying offset. The register's step has to\n+ * match the stride of one of the arrays crossed while walking the access\n+ * chain, and the maximal possible offset has to stay within that array.\n+ *\n+ * A program-allocated object (bpf_obj_new) is used as the source of a\n+ * PTR_TO_BTF_ID with a shape we fully control.\n+ */\n+struct inner {\n+\tint a;\n+\tint b;\n+};\n+\n+struct outer {\n+\tstruct inner arr[8];\t/* off 0, stride 8, size 64 */\n+\tchar bytes[32];\t\t/* off 64, stride 1, size 32 */\n+\tlong longs[8];\t\t/* off 96, stride 8, size 64 */\n+\tint grid[4][4];\t\t/* off 160, 16 ints, size 64 */\n+};\n+\n+/* arr[i].b, i in [0, 7], 4-byte read: stays within arr. */\n+SEC(\"syscall\")\n+__success\n+int arr_field_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 4);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/* arr[i].b, i in [0, 15]: max offset runs past the end of arr. */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct outer\")\n+int arr_field_out_of_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 15;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 4);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/* longs[i], i in [0, 7], 8-byte read: scalar array with stride 8. */\n+SEC(\"syscall\")\n+__success\n+int long_array_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tlong val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u64 *)(r1 + 96);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * bytes[i], i in [0, 31], read as 4 bytes: min_off is valid within the array,\n+ * but the 4-byte read at max_off runs past the array end. Exercises the\n+ * size-aware bound in btf_struct_access().\n+ */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct outer\")\n+int byte_array_size_spanning(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 31;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 64);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/* bytes[i], i in [0, 31], 1-byte read: step 1 matches the char array stride. */\n+SEC(\"syscall\")\n+__success\n+int byte_array_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 31;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u8 *)(r1 + 64);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * arr[] accessed with step 4 (half of sizeof(struct inner)): the step is not\n+ * a whole number of elements, so no crossed array has a matching stride.\n+ */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct outer\")\n+int arr_unaligned_step(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 4;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 0);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * grid[i][0], i in [0, 3]: steps along the outer dimension of a 2D array\n+ * (stride 16). __btf_resolve_size() linearizes the array; the step is a\n+ * multiple of the innermost element size (4).\n+ */\n+SEC(\"syscall\")\n+__success\n+int grid_outer_dim(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 3;\t\t\t\t\t\t\\\n+\tr2 *= 16;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 160);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * grid[0][i], i in [0, 3]: steps along the inner dimension of a 2D array\n+ * (stride 4, the innermost element size).\n+ */\n+SEC(\"syscall\")\n+__success\n+int grid_inner_dim(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct outer *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 3;\t\t\t\t\t\t\\\n+\tr2 *= 4;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 160);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * An array of pointers within a program-allocated object. Reading a pointer\n+ * member of a local object yields a SCALAR_VALUE, but the varying offset still\n+ * has to be validated against the array bounds.\n+ */\n+struct with_ptrs {\n+\tstruct inner *parr[8];\t/* off 0, stride 8 (sizeof ptr), size 64 */\n+};\n+\n+/* parr[i], i in [0, 7], 8-byte read: stays within parr. */\n+SEC(\"syscall\")\n+__success\n+int ptr_array_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct with_ptrs *o;\n+\tlong val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u64 *)(r1 + 0);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * parr[i], i in [0, 15]: max offset runs past the end of parr. Without the\n+ * variable-offset check on the WALK_PTR path this would be wrongly accepted.\n+ */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct with_ptrs\")\n+int ptr_array_out_of_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct with_ptrs *o;\n+\tlong val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 15;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u64 *)(r1 + 0);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * The cases above all use bpf_obj_new() (PTR_TO_BTF_ID | MEM_ALLOC). Exercise\n+ * the trusted kernel-BTF path too, using a task_struct from\n+ * bpf_get_current_task_btf() and its embedded char comm[] array. The comm\n+ * offset is folded into the pointer as a constant before the varying index.\n+ */\n+\n+/* task-\u003ecomm[i], i in [0, 15], 1-byte read: stays within comm. */\n+SEC(\"syscall\")\n+__success\n+int kernel_btf_array_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct task_struct *task;\n+\tint val = 0;\n+\n+\ttask = bpf_get_current_task_btf();\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[task];\t\t\t\t\t\t\\\n+\tr1 += %[off];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 15;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u8 *)(r1 + 0);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [task] \"r\"(task), [i] \"r\"(i),\n+\t [off] \"i\"(offsetof(struct task_struct, comm))\n+\t: \"r1\", \"r2\");\n+\treturn val;\n+}\n+\n+/* task-\u003ecomm[i], i in [0, 31]: max offset runs past comm. */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct task_struct\")\n+int kernel_btf_array_out_of_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct task_struct *task;\n+\tint val = 0;\n+\n+\ttask = bpf_get_current_task_btf();\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[task];\t\t\t\t\t\t\\\n+\tr1 += %[off];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 31;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u8 *)(r1 + 0);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [task] \"r\"(task), [i] \"r\"(i),\n+\t [off] \"i\"(offsetof(struct task_struct, comm))\n+\t: \"r1\", \"r2\");\n+\treturn val;\n+}\n+\n+/*\n+ * Array nested below a struct member at a non-zero offset. The walk descends\n+ * through 'm' (resetting the running offset) before reaching 'arr', exercising\n+ * the array_start = min_off - arrays[i].off telescoping across a WALK_STRUCT\n+ * dive.\n+ */\n+struct mid {\n+\tstruct inner arr[8];\t/* stride 8, size 64 */\n+};\n+\n+struct nest {\n+\tlong pad;\t\t/* off 0 */\n+\tstruct mid m;\t\t/* off 8 */\n+};\n+\n+/* m.arr[i].b, i in [0, 7], 4-byte read: stays within m.arr. */\n+SEC(\"syscall\")\n+__success\n+int nested_struct_in_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct nest *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 12);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/* m.arr[i].b, i in [0, 15]: max offset runs past the end of m.arr. */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct nest\")\n+int nested_struct_out_of_bounds(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct nest *o;\n+\tint val = 0;\n+\n+\to = bpf_obj_new(typeof(*o));\n+\tif (!o)\n+\t\treturn 0;\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 15;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 12);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\tbpf_obj_drop(o);\n+\treturn val;\n+}\n+\n+/*\n+ * A trailing flexible array member makes the struct tail an unbounded region,\n+ * so a varying access into it has no upper bound to exceed (mirrors how\n+ * unix_address.name[] is accessed via sun_path[i]).\n+ *\n+ * A custom (program) BTF struct can only be reached as a PTR_TO_BTF_ID through\n+ * bpf_obj_new(), which does not allow flexible array members. So use a kernel\n+ * type via an untrusted PTR_TO_BTF_ID (bpf_core_cast()). struct vring_used ends\n+ * with a flexible array 'ring[]' of struct vring_used_elem { __virtio32 id, len; },\n+ * mirroring a 'struct foo { int a; int b; }' flexible array.\n+ */\n+\n+/* ring[i].len, i in [0, 63], 4-byte read: the flexible array has no upper bound. */\n+SEC(\"syscall\")\n+__success\n+int flex_array_field(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct vring_used *o;\n+\tint val = 0;\n+\n+\to = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 63;\t\t\t\t\t\t\\\n+\tr2 *= 8;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 8);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\treturn val;\n+}\n+\n+/*\n+ * ring[] accessed with step 4 (half of sizeof(struct vring_used_elem)): the\n+ * step is not a whole number of elements, so the flexible array stride does\n+ * not match.\n+ */\n+SEC(\"syscall\")\n+__failure\n+__msg(\"invalid variable offset access into struct vring_used\")\n+int flex_array_unaligned_step(void *ctx)\n+{\n+\tunsigned long i = bpf_get_prandom_u32();\n+\tstruct vring_used *o;\n+\tint val = 0;\n+\n+\to = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\tr1 = %[o];\t\t\t\t\t\t\\\n+\tr2 = %[i];\t\t\t\t\t\t\\\n+\tr2 \u0026= 7;\t\t\t\t\t\t\\\n+\tr2 *= 4;\t\t\t\t\t\t\\\n+\tr1 += r2;\t\t\t\t\t\t\\\n+\t%[val] = *(u32 *)(r1 + 4);\t\t\t\t\\\n+\"\t: [val] \"=r\"(val)\n+\t: [o] \"r\"(o), [i] \"r\"(i)\n+\t: \"r1\", \"r2\");\n+\treturn val;\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_gotox.c b/tools/testing/selftests/bpf/progs/verifier_gotox.c\nindex f5a9878c7b8d4..03a3bee212361 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_gotox.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_gotox.c\n@@ -509,7 +509,7 @@ __naked void too_many_gotox_edges(void)\n \n SEC(\"socket\")\n __description(\"gotox-edges-at-limit\")\n-__success __retval(0)\n+__failure __msg(\"Too many nested loops\")\n __naked void gotox_edges_at_limit(void)\n {\n \tasm volatile (\n@@ -517,6 +517,10 @@ __naked void gotox_edges_at_limit(void)\n \t\t * 1000 gotox * 1000 targets = 1,000,000 CFG edges. At run\n \t\t * time, each block loads the next table entry and jumps to\n \t\t * the following block, so the program terminates.\n+\t\t *\n+\t\t * Every block can jump to every later block, so the CFG is\n+\t\t * a nest of ~1000 irreducible loops, deeper than the\n+\t\t * verifier's loop stack; the program is rejected.\n \t\t */\n \t\tGOTOX_TABLE_BEGIN(1000)\n \t\t\".rept 1000;\"\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_idoms.c b/tools/testing/selftests/bpf/progs/verifier_idoms.c\nnew file mode 100644\nindex 0000000000000..a29d6332baa4f\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_idoms.c\n@@ -0,0 +1,390 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/bpf.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+#include \"../../../include/linux/filter.h\"\n+\n+/*\n+ * kernel/bpf/loops.c:bpf_compute_idoms() computes the immediate dominator\n+ * of every instruction (Cooper et al, \"A Simple, Fast Dominance Algorithm\").\n+ *\n+ * The immediate dominator is printed by log_program() as the numeric column\n+ * immediately before the \"\u003cinsn#\u003e:\" field of every \"Program dump\" line:\n+ *\n+ * Program dump (scc? loop_header? idom insn#: live_regs_before):\n+ * -1 0: ....... (b7) r0 = 0 \u003c- idom(0) = -1 (subprog entry)\n+ * 0 1: ....... (07) r0 += 1 \u003c- idom(1) = 0\n+ * ^^^^^^\n+ * idom insn#\n+ *\n+ * The __msg() patterns below wildcard the scc/loop_header/live_regs columns and\n+ * anchor on \"\u003cidom\u003e \u003cinsn#\u003e:\" followed by the disassembled instruction, so\n+ * they assert the idom value of each instruction.\n+ */\n+\n+/*\n+ * Straight-line code, with an ldimm64 in the middle. Instruction index 2 is\n+ * the second half of the ldimm64 at index 1 and is not a CFG node; the idom of\n+ * index 3 must be 1, not 2. Exercises the bpf_is_ldimm64() skip in both passes\n+ * of compute_predecessors().\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (18) r1 = 0x1122334455667788\")\n+__msg(\"{{.*}} 1 3: {{.*}} (07) r0 += 1\")\n+__msg(\"{{.*}} 3 4: {{.*}} (0f) r0 += r1\")\n+__msg(\"{{.*}} 4 5: {{.*}} (95) exit\")\n+__naked void straight_line_ldimm64(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\tr1 = 0x1122334455667788 ll;\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr0 += r1;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Asymmetric if-then-else diamond: the \"then\" arm is 5 instructions long, the\n+ * \"else\" arm is a single instruction. The merge point (insn 8) is dominated by\n+ * the branch (insn 1), not by either arm. This forces idoms_intersect() to walk\n+ * the two predecessors up unequal postorder depths before they meet.\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7\")\n+__msg(\"{{.*}} 0 1: {{.*}} (25) if r0 \u003e 0x0 goto pc+5\")\n+__msg(\"{{.*}} 1 2: {{.*}} (b7) r1 = 1\")\n+__msg(\"{{.*}} 2 3: {{.*}} (b7) r1 = 2\")\n+__msg(\"{{.*}} 3 4: {{.*}} (b7) r1 = 3\")\n+__msg(\"{{.*}} 4 5: {{.*}} (b7) r1 = 4\")\n+__msg(\"{{.*}} 5 6: {{.*}} (05) goto pc+1\")\n+__msg(\"{{.*}} 1 7: {{.*}} (b7) r1 = 9\")\n+__msg(\"{{.*}} 1 8: {{.*}} (95) exit\")\n+__naked void asymmetric_diamond(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 \u003e 0 goto 1f;\t\t\t\t\\\n+\tr1 = 1;\t\t\t\t\t\t\\\n+\tr1 = 2;\t\t\t\t\t\t\\\n+\tr1 = 3;\t\t\t\t\t\t\\\n+\tr1 = 4;\t\t\t\t\t\t\\\n+\tgoto 2f;\t\t\t\t\t\\\n+1:\tr1 = 9;\t\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Simple loop: the header (insn 1) is dominated by the pre-header (insn 0). The\n+ * back edge (insn 2 -\u003e insn 1) must not change idom(1); the back-edge\n+ * predecessor folds up via idoms_intersect().\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (a5) if r0 \u003c 0xa goto pc-2\")\n+__msg(\"{{.*}} 2 3: {{.*}} (95) exit\")\n+__naked void simple_loop(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Loop with an if-else in its body. The in-loop merge point (insn 5) is\n+ * dominated by the in-loop branch (insn 3), combining a back-edge intersect\n+ * with a forward-diamond intersect.\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (bf) r1 = r0\")\n+__msg(\"{{.*}} 2 3: {{.*}} (25) if r1 \u003e 0x5 goto pc+1\")\n+__msg(\"{{.*}} 3 4: {{.*}} (b7) r1 = 1\")\n+__msg(\"{{.*}} 3 5: {{.*}} (0f) r0 += r1\")\n+__msg(\"{{.*}} 5 6: {{.*}} (a5) if r0 \u003c 0x64 goto pc-6\")\n+__msg(\"{{.*}} 6 7: {{.*}} (95) exit\")\n+__naked void loop_with_if_else_body(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = r0;\t\t\t\t\t\\\n+\tif r1 \u003e 5 goto 2f;\t\t\t\t\\\n+\tr1 = 1;\t\t\t\t\t\t\\\n+2:\tr0 += r1;\t\t\t\t\t\\\n+\tif r0 \u003c 100 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Nested loops: the idom chain runs inner-header -\u003e outer-body -\u003e outer-header\n+ * -\u003e pre-header. Exercises intersect across back edges at two nesting depths.\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (b7) r1 = 0\")\n+__msg(\"{{.*}} 2 3: {{.*}} (07) r1 += 1\")\n+__msg(\"{{.*}} 3 4: {{.*}} (a5) if r1 \u003c 0x5 goto pc-2\")\n+__msg(\"{{.*}} 4 5: {{.*}} (a5) if r0 \u003c 0xa goto pc-5\")\n+__msg(\"{{.*}} 5 6: {{.*}} (95) exit\")\n+__naked void nested_loops(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 5 goto 2b;\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Loop header (insn 1) with two back edges (from insn 4 and insn 5), i.e. three\n+ * predecessors. Both back edges route through the incrementing header, so the\n+ * loop is bounded and verifies. Repeated idoms_intersect() at the header must\n+ * stay stable and keep idom(1) at the pre-header (insn 0).\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r6 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (07) r6 += 1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (25) if r6 \u003e 0xa goto pc+3\")\n+__msg(\"{{.*}} 2 3: {{.*}} (bf) r7 = r6\")\n+__msg(\"{{.*}} 3 4: {{.*}} (a5) if r7 \u003c 0x5 goto pc-4\")\n+__msg(\"{{.*}} 4 5: {{.*}} (05) goto pc-5\")\n+__msg(\"{{.*}} 2 6: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 6 7: {{.*}} (95) exit\")\n+__naked void multi_backedge_header(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tr6 += 1;\t\t\t\t\t\\\n+\tif r6 \u003e 10 goto 2f;\t\t\t\t\\\n+\tr7 = r6;\t\t\t\t\t\\\n+\tif r7 \u003c 5 goto 1b;\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Irreducible CFG (loop with two entries, insn 3 and insn 5, reached from the\n+ * insn 2 branch). Dominators remain well-defined; this is a convergence test\n+ * for the fixpoint under irreducibility. Note insn 6 is dominated by the branch\n+ * (insn 2), not by either arm.\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7\")\n+__msg(\"{{.*}} 0 1: {{.*}} (b7) r1 = 0\")\n+__msg(\"{{.*}} 1 2: {{.*}} (25) if r0 \u003e 0x5 goto pc+2\")\n+__msg(\"{{.*}} 2 3: {{.*}} (b7) r1 = 1\")\n+__msg(\"{{.*}} 3 4: {{.*}} (05) goto pc+1\")\n+__msg(\"{{.*}} 2 5: {{.*}} (b7) r1 = 2\")\n+__msg(\"{{.*}} 2 6: {{.*}} (0f) r0 += r1\")\n+__msg(\"{{.*}} 6 7: {{.*}} (a5) if r0 \u003c 0x10 goto pc-5\")\n+__msg(\"{{.*}} 7 8: {{.*}} (95) exit\")\n+__naked void irreducible(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\tif r0 \u003e 5 goto 2f;\t\t\t\t\\\n+1:\tr1 = 1;\t\t\t\t\t\t\\\n+\tgoto 3f;\t\t\t\t\t\\\n+2:\tr1 = 2;\t\t\t\t\t\t\\\n+3:\tr0 += r1;\t\t\t\t\t\\\n+\tif r0 \u003c 16 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Idoms are computed per subprog. Layout (libbpf preorder) is:\n+ * main: 0..1, sub: 2..7\n+ * The callee entry (insn 2) must have idom -1 (subprog reset), and idoms inside\n+ * the callee must reference only the callee's instructions, never main's. The\n+ * in-callee merge (insn 7) is dominated by the in-callee branch (insn 3). The\n+ * branch is on a prandom value so it is not constant-folded away.\n+ */\n+static __naked __noinline __used\n+unsigned long idoms_diamond_sub(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 \u003e 0 goto 1f;\t\t\t\t\\\n+\tr0 = 1;\t\t\t\t\t\t\\\n+\tgoto 2f;\t\t\t\t\t\\\n+1:\tr0 = 2;\t\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (85) call pc+1\")\n+__msg(\"{{.*}} 0 1: {{.*}} (95) exit\")\n+__msg(\"{{.*}} -1 2: {{.*}} (85) call bpf_get_prandom_u32#7\")\n+__msg(\"{{.*}} 2 3: {{.*}} (25) if r0 \u003e 0x0 goto pc+2\")\n+__msg(\"{{.*}} 3 4: {{.*}} (b7) r0 = 1\")\n+__msg(\"{{.*}} 4 5: {{.*}} (05) goto pc+1\")\n+__msg(\"{{.*}} 3 6: {{.*}} (b7) r0 = 2\")\n+__msg(\"{{.*}} 3 7: {{.*}} (95) exit\")\n+__naked void multi_subprog(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall idoms_diamond_sub;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * The first instruction of a subprog (insn 3) is itself a loop header, i.e. it\n+ * has an incoming back edge. Its idom must still be -1 (the subprog entry has no\n+ * dominator). Exercises the idoms[start]=0 ... idoms[start]=-1 handling in\n+ * compute_subprog_idoms().\n+ */\n+static __naked __noinline __used\n+unsigned long idoms_entry_header_sub(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+1:\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 10 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (b7) r1 = 0\")\n+__msg(\"{{.*}} 0 1: {{.*}} (85) call pc+1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (95) exit\")\n+__msg(\"{{.*}} -1 3: {{.*}} (07) r1 += 1\")\n+__msg(\"{{.*}} 3 4: {{.*}} (a5) if r1 \u003c 0xa goto pc-2\")\n+__msg(\"{{.*}} 4 5: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 5 6: {{.*}} (95) exit\")\n+__naked void entry_is_loop_header(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\tcall idoms_entry_header_sub;\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Self-loop: insn 1 is its own predecessor. idom(1) must be the pre-header\n+ * (insn 0); the self-edge is ignored (idoms[pred] == -1 on the first pass, then\n+ * idoms_intersect(a == b) short-circuits). Program is rejected later for an\n+ * infinite loop, but the dump (and idoms) are printed before that.\n+ */\n+SEC(\"socket\")\n+__failure\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7\")\n+__msg(\"{{.*}} 0 1: {{.*}} (a5) if r0 \u003c 0xa goto pc-1\")\n+__msg(\"{{.*}} 1 2: {{.*}} (95) exit\")\n+__msg(\"infinite loop detected\")\n+__naked void self_loop(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+1:\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+#if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) || defined(__TARGET_ARCH_powerpc)\n+/*\n+ * Indirect jump (gotox) with a two-entry jump table. The gotox (insn 4) has two\n+ * successors (insn 5 and insn 7), so both targets have the gotox as their only\n+ * predecessor and idom. Also re-exercises the ldimm64 skip: insn 2's idom is 0,\n+ * the ldimm64 at index 0 (index 1 is its second half).\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\"{{.*}} -1 0: {{.*}} (18) r0 = {{0x[0-9a-f]+}}\")\n+__msg(\"{{.*}} 0 2: {{.*}} (07) r0 += 8\")\n+__msg(\"{{.*}} 2 3: {{.*}} (79) r0 = *(u64 *)(r0 +0)\")\n+__msg(\"{{.*}} 3 4: {{.*}} (0d) gotox r0\")\n+__msg(\"{{.*}} 4 5: {{.*}} (b7) r0 = 0\")\n+__msg(\"{{.*}} 5 6: {{.*}} (95) exit\")\n+__msg(\"{{.*}} 4 7: {{.*}} (b7) r0 = 1\")\n+__msg(\"{{.*}} 7 8: {{.*}} (95) exit\")\n+__naked void gotox_jump_table(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\t\\\n+\t.pushsection .jumptables,\\\"\\\",@progbits;\t\t\\\n+jt0_%=:\t\t\t\t\t\t\t\t\\\n+\t.quad ret0_%= - socket;\t\t\t\t\t\\\n+\t.quad ret1_%= - socket;\t\t\t\t\t\\\n+\t.size jt0_%=, 16;\t\t\t\t\t\\\n+\t.global jt0_%=;\t\t\t\t\t\t\\\n+\t.popsection;\t\t\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tr0 = jt0_%= ll;\t\t\t\t\t\t\\\n+\tr0 += 8;\t\t\t\t\t\t\\\n+\tr0 = *(u64 *)(r0 + 0);\t\t\t\t\t\\\n+\t.8byte %[gotox_r0];\t\t\t\t\t\\\n+ret0_%=:\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+ret1_%=:\t\t\t\t\t\t\t\\\n+\tr0 = 1;\t\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm_insn(gotox_r0, BPF_RAW_INSN(BPF_JMP | BPF_JA | BPF_X, BPF_REG_0, 0, 0, 0))\n+\t: __clobber_all);\n+}\n+#endif\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c\nindex 16b2b1e575342..496229a9b284c 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c\n@@ -61,8 +61,12 @@ __naked void read_write_join(void)\n SEC(\"socket\")\n __log_level(2)\n __msg(\"stack use/def subprog#0 must_write_not_same_slot (d0,cs0):\")\n-__msg(\"6: (7b) *(u64 *)(r2 +0) = r0{{$}}\")\n-__msg(\"Live regs before insn:\")\n+/*\n+ * 'r2 += r1' adds a scalar, so the offset is lost (off_cnt == 0): no def,\n+ * but the write conservatively marks the whole frame as may_def.\n+ */\n+__msg(\"6: (7b) *(u64 *)(r2 +0) = r0 ; may_def: fp0-8..-{{(512|2048)}}\")\n+__msg(\"Program dump\")\n __naked void must_write_not_same_slot(void)\n {\n \tasm volatile (\n@@ -79,6 +83,31 @@ __naked void must_write_not_same_slot(void)\n \t: __clobber_all);\n }\n \n+SEC(\"socket\")\n+__log_level(2)\n+__msg(\"stack use/def subprog#0 may_write_two_precise_offsets (d0,cs0):\")\n+/*\n+ * r1 is fp-8 or fp-16, with both offsets tracked precisely (off_cnt == 2).\n+ * A write through it cannot set def, but marks both candidate slots as may_def.\n+ */\n+__msg(\"6: (7b) *(u64 *)(r1 +0) = r0 ; may_def: fp0-8 fp0-16\")\n+__naked void may_write_two_precise_offsets(void)\n+{\n+\tasm volatile (\n+\t\"call %[bpf_get_prandom_u32];\"\n+\t\"r1 = r10;\"\n+\t\"if r0 \u003e 42 goto 1f;\"\n+\t\"r1 += -8;\"\n+\t\"goto 2f;\"\n+\"1:\"\n+\t\"r1 += -16;\"\n+\"2:\"\n+\t\"*(u64 *)(r1 + 0) = r0;\"\n+\t\"exit;\"\n+\t:: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n SEC(\"socket\")\n __log_level(2)\n __msg(\"0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8\")\n@@ -106,11 +135,11 @@ __naked void must_write_not_same_type(void)\n \n SEC(\"socket\")\n __log_level(2)\n-/* Callee writes fp[0]-8: stack_use at call site has slots 0,1 live */\n+/* Callee writes fp[0]-8: the def is summarized as may_def at the call site */\n __msg(\"stack use/def subprog#0 caller_stack_write (d0,cs0):\")\n-__msg(\"2: (85) call pc+1{{$}}\")\n+__msg(\"2: (85) call pc+1 ; may_def: fp0-8\")\n __msg(\"stack use/def subprog#1 write_first_param (d1,cs2):\")\n-__msg(\"4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8\")\n+__msg(\"4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8 may_def: fp0-8\")\n __naked void caller_stack_write(void)\n {\n \tasm volatile (\n@@ -130,6 +159,49 @@ static __used __naked void write_first_param(void)\n \t::: __clobber_all);\n }\n \n+/*\n+ * Cross-frame imprecise write: imprecise_frame_writer() receives a pointer\n+ * into the caller's frame (frame 0) but conditionally replaces it with a\n+ * pointer into its own frame (frame 1). At the store the two are joined into\n+ * ARG_IMPRECISE (frame is unknown, mask = {0,1}), so the offset is dropped and\n+ * the whole of both candidate frames is conservatively marked as may_def.\n+ */\n+SEC(\"socket\")\n+__log_level(2)\n+/* The callee's write into the caller frame is summarized at the call site. */\n+__msg(\"stack use/def subprog#0 imprecise_frame_write (d0,cs0):\")\n+__msg(\"2: (85) call pc+2 ; may_def: fp0-8..-{{(512|2048)}}\")\n+__msg(\"stack use/def subprog#1 imprecise_frame_writer (d1,cs2):\")\n+__msg(\"12: (7b) *(u64 *)(r1 +0) = r2 ; may_def: fp1-8..-{{(512|2048)}} fp0-8..-{{(512|2048)}}\")\n+__naked void imprecise_frame_write(void)\n+{\n+\tasm volatile (\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\n+\t\"call imprecise_frame_writer;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked void imprecise_frame_writer(void)\n+{\n+\tasm volatile (\n+\t\"r6 = r1;\"\t\t\t/* save arg: pointer into frame 0 */\n+\t\"call %[bpf_get_prandom_u32];\"\n+\t\"r1 = r6;\"\t\t\t/* r1 = frame0-8 (arg) */\n+\t\"if r0 == 0 goto 1f;\"\n+\t\"r1 = r10;\"\n+\t\"r1 += -8;\"\t\t\t/* r1 = frame1-8 (own frame) */\n+\"1:\"\n+\t\"r2 = 0;\"\n+\t\"*(u64 *)(r1 + 0) = r2;\"\t/* join frame0-8 | frame1-8 -\u003e imprecise */\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t:: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n SEC(\"socket\")\n __log_level(2)\n __msg(\"stack use/def subprog#0 caller_stack_read (d0,cs0):\")\n@@ -804,7 +876,7 @@ void __kfunc_btf_root(void)\n */\n SEC(\"socket\")\n __success __log_level(2)\n-__msg(\" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24{{$}}\")\n+__msg(\" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24 may_def: fp0-24{{$}}\")\n __msg(\" 9: (85) call bpf_iter_num_next{{.*}} ; use: fp0-24{{$}}\")\n __msg(\"14: (85) call bpf_iter_num_destroy{{.*}} ; use: fp0-24{{$}}\")\n __naked void kfunc_iter_stack_liveness(void)\n@@ -1007,8 +1079,9 @@ __naked void four_byte_read_upper_half(void)\n */\n SEC(\"socket\")\n __log_level(2)\n-__msg(\"0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8\")\n-__msg(\"1: (6a) *(u16 *)(r10 -4) = 0{{$}}\")\n+__msg(\"0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8 may_def: fp0-8\")\n+/* 2-byte write only partially covers the upper half: may_def, but no def. */\n+__msg(\"1: (6a) *(u16 *)(r10 -4) = 0 ; may_def: fp0-4h\")\n __msg(\"2: (61) r0 = *(u32 *)(r10 -4) ; use: fp0-4h\")\n __naked void two_byte_write_no_kill(void)\n {\n@@ -1355,9 +1428,12 @@ __naked void fp_spill_loses_precision_kills_liveness(void)\n */\n SEC(\"socket\")\n __log_level(2)\n-/* fp-8 live at call (callee conditionally writes → slot not killed) */\n-__msg(\"1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8\")\n-__msg(\"4: (85) call pc+2{{$}}\")\n+/*\n+ * fp-8 live at call: callee conditionally writes it, so the slot is not killed\n+ * (no def), but the conditional write surfaces as may_def at the call site.\n+ */\n+__msg(\"1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8 may_def: fp0-8\")\n+__msg(\"4: (85) call pc+2 ; may_def: fp0-8\")\n __msg(\"5: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8\")\n __naked void conditional_stx_in_subprog(void)\n {\n@@ -2385,8 +2461,27 @@ __flag(BPF_F_TEST_STATE_FREQ)\n __msg(\"subprog#2 write_first_read_second:\")\n __msg(\"17: (7a) *(u64 *)(r1 +0) = 42{{$}}\")\n __msg(\"18: (79) r0 = *(u64 *)(r2 +0) // r1=fp0-8 r2=fp0-16{{$}}\")\n+/*\n+ * The callee's write into the caller frame is summarized as may_def at the\n+ * call sites, transitively across both frames (depth 2 -\u003e 1 -\u003e 0). The two\n+ * call sites differ because the shared write_first_read_second instance\n+ * accumulates the cross-pass union ({fp-8, fp-16}) at different points\n+ * relative to each forwarding_rw's summarization.\n+ */\n+__msg(\"stack use/def subprog#0 shared_instance_must_write_overwrite (d0,cs0):\")\n+__msg(\"7: (85) call pc+7 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16\")\n+__msg(\"12: (85) call pc+2 ; use: fp0-8 may_def: fp0-16\")\n+__msg(\"stack use/def subprog#1 forwarding_rw (d1,cs7):\")\n+__msg(\"15: (85) call pc+1 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16\")\n+__msg(\"stack use/def subprog#1 forwarding_rw (d1,cs12):\")\n+__msg(\"15: (85) call pc+1 ; use: fp0-8 may_def: fp0-16\")\n __msg(\"stack use/def subprog#2 write_first_read_second (d2,cs15):\")\n-__msg(\"17: (7a) *(u64 *)(r1 +0) = 42{{$}}\")\n+/*\n+ * Shared across two callsites with swapped args (r1 is fp-8 on one pass,\n+ * fp-16 on the other): must_write intersects to empty (no def), may_write\n+ * unions to both slots.\n+ */\n+__msg(\"17: (7a) *(u64 *)(r1 +0) = 42 ; may_def: fp0-8 fp0-16\")\n __msg(\"18: (79) r0 = *(u64 *)(r2 +0) ; use: fp0-8 fp0-16\")\n __naked void shared_instance_must_write_overwrite(void)\n {\n@@ -2428,6 +2523,65 @@ static __used __naked void write_first_read_second(void)\n \t::: __clobber_all);\n }\n \n+/*\n+ * merge_instances() must preserve may_write when one pass doesn't touch a frame.\n+ * mvs_leaf is reached through a single callsite (mvs_mid) from two outer chains,\n+ * so it is one shared (depth,callsite) instance analyzed twice and merged:\n+ * - chain A passes r2 = map value, mvs_leaf's doesn't touch stack;\n+ * - chain B passes r2 = caller stack slot fp-8.\n+ * The merge must keep the stack pass's may_write even though the map pass left\n+ * frame 0 untouched.\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"stack use/def subprog#2 mvs_leaf (d2,cs19):\")\n+__msg(\"21: (7a) *(u64 *)(r2 +0) = 42 ; may_def: fp0-8\")\n+__naked void merge_preserves_may_write(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"*(u64 *)(r10 - 24) = r1;\"\t\t/* map key */\n+\t\"r1 = %[map] ll;\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -24;\"\n+\t\"call %[bpf_map_lookup_elem];\"\n+\t\"if r0 == 0 goto 1f;\"\n+\t/* chain A: r2 = map value (ARG_NONE, not stack) */\n+\t\"r1 = r10;\"\n+\t\"r1 += -16;\"\t\t\t\t/* unused fp anchor */\n+\t\"r2 = r0;\"\n+\t\"call mvs_mid;\"\n+\t/* chain B: r2 = caller stack slot fp-8 */\n+\t\"r1 = r10;\"\n+\t\"r1 += -16;\"\n+\t\"r2 = r10;\"\n+\t\"r2 += -8;\"\n+\t\"call mvs_mid;\"\n+\"1:\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t: : __imm(bpf_map_lookup_elem), __imm_addr(map)\n+\t: __clobber_all);\n+}\n+\n+static __used __naked void mvs_mid(void)\n+{\n+\tasm volatile (\n+\t\"call mvs_leaf;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n+static __used __naked void mvs_leaf(void)\n+{\n+\tasm volatile (\n+\t\"*(u64 *)(r2 + 0) = 42;\"\n+\t\"r0 = 0;\"\n+\t\"exit;\"\n+\t::: __clobber_all);\n+}\n+\n /*\n * Shared must_write when (callsite, depth) instance is reused.\n * Main calls fwd_to_stale_wr at two sites. fwd_to_stale_wr calls\n@@ -2512,6 +2666,32 @@ __naked void load_acquire_dont_clear_dst(void)\n \n #endif /* CAN_USE_LOAD_ACQ_STORE_REL */\n \n+SEC(\"socket\")\n+__log_level(2)\n+__success\n+__msg(\"lock *(u64 *)(r10 -8) += r1{{.*}}use: fp0-8{{.*}}may_def: fp0-8\")\n+__msg(\"r1 = atomic64_fetch_add((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8\")\n+__msg(\"r1 = atomic64_xchg((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8\")\n+__msg(\"r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8\")\n+__naked void atomic_rmw(void)\n+{\n+\tasm volatile (\n+\t\"r1 = 0;\"\n+\t\"*(u64 *)(r10 - 8) = r1;\"\n+\t\".8byte %[atomic_add];\"\n+\t\".8byte %[atomic_fetch_add];\"\n+\t\".8byte %[atomic_xchg];\"\n+\t\"r0 = 0;\"\n+\t\".8byte %[atomic_cmpxchg];\"\n+\t\"exit;\"\n+\t:\n+\t: __imm_insn(atomic_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD, BPF_REG_10, BPF_REG_1, -8)),\n+\t __imm_insn(atomic_fetch_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD | BPF_FETCH, BPF_REG_10, BPF_REG_1, -8)),\n+\t __imm_insn(atomic_xchg, BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_10, BPF_REG_1, -8)),\n+\t __imm_insn(atomic_cmpxchg, BPF_ATOMIC_OP(BPF_DW, BPF_CMPXCHG, BPF_REG_10, BPF_REG_1, -8))\n+\t: __clobber_all);\n+}\n+\n SEC(\"socket\")\n __success\n __naked void imprecise_fill_loses_cross_frame(void)\n@@ -2848,8 +3028,9 @@ static __used __naked void imprecise_dst_spill_join_sub(void)\n SEC(\"socket\")\n __log_level(2)\n __msg(\"0: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8\")\n-__msg(\"1: (73) *(u8 *)(r10 -1) = r0{{$}}\")\n-__msg(\"2: (6b) *(u16 *)(r10 -4) = r0{{$}}\")\n+/* narrow stores define nothing, but they may write the half-slot they touch */\n+__msg(\"1: (73) *(u8 *)(r10 -1) = r0 ; may_def: fp0-4h\")\n+__msg(\"2: (6b) *(u16 *)(r10 -4) = r0 ; may_def: fp0-4h\")\n __msg(\"3: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8\")\n __naked void narrow_store_defines_nothing(void)\n {\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c\nnew file mode 100644\nindex 0000000000000..5c5bf5b445290\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c\n@@ -0,0 +1,317 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/bpf.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+\n+/*\n+ * kernel/bpf/loops.c:compute_loops() distinguish between\n+ * the following cases:\n+ * - B: backedge -\u003e simple loop\n+ * - C: cross edge to non-loop node -\u003e no-op\n+ * - D: edge to node whose header is in DFS path -\u003e nested loop\n+ * - E: edge to node whose header is NOT in DFS path -\u003e irreducible\n+ *\n+ * Below test cases cover the above branches in various combinations.\n+ */\n+\n+/* Case B: single bounded loop. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 1 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\" 1 1 1 2: {{.*}} (a5) if r0 \u003c 0xa goto pc-2\")\n+__msg(\" 2 3: {{.*}} (95) exit\")\n+__naked void loop_single(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Case B: two independent loops at the same nesting level. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"loop at 4{{$}}\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 2 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\" 2 1 1 2: {{.*}} (a5) if r0 \u003c 0xa goto pc-2\")\n+__msg(\" 2 3: {{.*}} (b7) r1 = 0\")\n+__msg(\" 1 3 4: {{.*}} (07) r1 += 1\")\n+__msg(\" 1 4 4 5: {{.*}} (a5) if r1 \u003c 0xa goto pc-2\")\n+__msg(\" 5 6: {{.*}} (95) exit\")\n+__naked void loop_two_independent(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 10 goto 2b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Case B + D: nested loops. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"loop at 3, nested in 1\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 1 0 1: {{.*}} (07) r0 += 1\")\t\t\t/* outer loop header */\n+__msg(\" 1 1 1 2: {{.*}} (b7) r1 = 0\")\t\t\t/* outer loop insn */\n+__msg(\" 1 1 2 3: {{.*}} (07) r1 += 1\")\t\t\t/* inner loop header */\n+__msg(\" 1 3 3 4: {{.*}} (a5) if r1 \u003c 0x5 goto pc-2\")\t/* inner loop insn */\n+__msg(\" 1 1 4 5: {{.*}} (a5) if r0 \u003c 0xa goto pc-5\")\t/* outer loop insn */\n+__msg(\" 5 6: {{.*}} (95) exit\")\n+__naked void loop_nested(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 5 goto 2b;\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Case C: forward edges, no loops. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (85) call bpf_get_prandom_u32\")\n+__msg(\" 0 1: {{.*}} (25) if r0 \u003e 0x0 goto pc+2\")\n+__msg(\" 1 2: {{.*}} (b7) r0 = 2\")\n+__msg(\" 2 3: {{.*}} (05) goto pc+1\")\n+__msg(\" 1 4: {{.*}} (b7) r0 = 3\")\n+__msg(\" 1 5: {{.*}} (95) exit\")\n+__naked void fwd_edges_no_loop(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 \u003e 0 goto 1f;\t\t\t\t\\\n+\tr0 = 2;\t\t\t\t\t\t\\\n+\tgoto 2f;\t\t\t\t\t\\\n+1:\tr0 = 3;\t\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/* Case B + D: two sibling inner loops within one outer loop. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"loop at 3, nested in 1\")\n+__msg(\"loop at 6, nested in 1\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 1 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\" 1 1 1 2: {{.*}} (b7) r1 = 0\")\n+__msg(\" 1 1 2 3: {{.*}} (07) r1 += 1\")\n+__msg(\" 1 3 3 4: {{.*}} (a5) if r1 \u003c 0x5 goto pc-2\")\n+__msg(\" 1 1 4 5: {{.*}} (b7) r2 = 0\")\n+__msg(\" 1 1 5 6: {{.*}} (07) r2 += 1\")\n+__msg(\" 1 6 6 7: {{.*}} (a5) if r2 \u003c 0x5 goto pc-2\")\n+__msg(\" 1 1 7 8: {{.*}} (a5) if r0 \u003c 0xa goto pc-8\")\n+__msg(\" 8 9: {{.*}} (95) exit\")\n+__naked void loop_nested_siblings(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 5 goto 2b;\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+3:\tr2 += 1;\t\t\t\t\t\\\n+\tif r2 \u003c 5 goto 3b;\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Three levels of nesting. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"loop at 3, nested in 1\")\n+__msg(\"loop at 5, nested in 3\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 1 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\" 1 1 1 2: {{.*}} (b7) r1 = 0\")\n+__msg(\" 1 1 2 3: {{.*}} (07) r1 += 1\")\n+__msg(\" 1 3 3 4: {{.*}} (b7) r2 = 0\")\n+__msg(\" 1 3 4 5: {{.*}} (07) r2 += 1\")\n+__msg(\" 1 5 5 6: {{.*}} (a5) if r2 \u003c 0x3 goto pc-2\")\n+__msg(\" 1 3 6 7: {{.*}} (a5) if r1 \u003c 0x5 goto pc-5\")\n+__msg(\" 1 1 7 8: {{.*}} (a5) if r0 \u003c 0xa goto pc-8\")\n+__msg(\" 8 9: {{.*}} (95) exit\")\n+__naked void loop_three_levels(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+3:\tr2 += 1;\t\t\t\t\t\\\n+\tif r2 \u003c 3 goto 3b;\t\t\t\t\\\n+\tif r1 \u003c 5 goto 2b;\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Loop with an if-else body (forward branch inside loop, Case C). */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (b7) r0 = 0\")\n+__msg(\" 1 0 1: {{.*}} (07) r0 += 1\")\n+__msg(\" 1 1 1 2: {{.*}} (bf) r1 = r0\")\n+__msg(\" 1 1 2 3: {{.*}} (25) if r1 \u003e 0x5 goto pc+1\")\n+__msg(\" 1 1 3 4: {{.*}} (b7) r1 = 1\")\n+__msg(\" 1 1 3 5: {{.*}} (0f) r0 += r1\")\n+__msg(\" 1 1 5 6: {{.*}} (a5) if r0 \u003c 0x64 goto pc-6\")\n+__msg(\" 6 7: {{.*}} (95) exit\")\n+__naked void loop_with_if_else(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = r0;\t\t\t\t\t\\\n+\tif r1 \u003e 5 goto 2f;\t\t\t\t\\\n+\tr1 = 1;\t\t\t\t\t\t\\\n+2:\tr0 += r1;\t\t\t\t\t\\\n+\tif r0 \u003c 100 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/* Case E: irreducible loop. */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 3, irreducible\")\n+__msg(\"Program dump\")\n+__msg(\" -1 0: {{.*}} (85) call bpf_get_prandom_u32#7\")\n+__msg(\" 0 1: {{.*}} (b7) r1 = 0\")\n+__msg(\" 1 2: {{.*}} (25) if r0 \u003e 0x5 goto pc+2\")\n+__msg(\" 1 2 3: {{.*}} (b7) r1 = 1\")\n+__msg(\" 1 3 3 4: {{.*}} (05) goto pc+1\")\n+__msg(\" 2 5: {{.*}} (b7) r1 = 2\")\n+__msg(\" 1 3 2 6: {{.*}} (0f) r0 += r1\")\n+__msg(\" 1 3 6 7: {{.*}} (a5) if r0 \u003c 0x10 goto pc-5\")\n+__msg(\" 7 8: {{.*}} (95) exit\")\n+__naked void loop_irreducible(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\tif r0 \u003e 5 goto 2f;\t\t\t\t\\\n+1:\tr1 = 1;\t\t\t\t\t\t\\\n+\tgoto 3f;\t\t\t\t\t\\\n+2:\tr1 = 2;\t\t\t\t\t\t\\\n+3:\tr0 += r1;\t\t\t\t\t\\\n+\tif r0 \u003c 16 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"socket\")\n+__failure\n+__log_level(2)\n+__msg(\"loop at 1\")\n+__msg(\"infinite loop detected at insn 1\")\n+__naked void loop_self(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+1:\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Loops at 5 and 7 are nested inside loops at 3 and 1.\n+ * The edge 6 -\u003e 7 exits loop at 5 and enters loop at 7.\n+ * Check that it is logged only as an exit from loop at 5.\n+ *\n+ * 0: r0 = 0;\n+ * do {\n+ * 1: r0++;\n+ * 2: r1 = 0;\n+ * do {\n+ * 3: r1++;\n+ * 4: r2 = 0;\n+ * do {\n+ * 5: r2++;\n+ * 6: } while (r2 \u003c 3);\n+ * do {\n+ * 7: r2--;\n+ * 8: } while (r2 != 0);\n+ * 9: } while (r1 \u003c 4);\n+ * 10: } while (r0 \u003c 5);\n+ * 11: return r0;\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg_next(\" backedge from 10, latch at 10\")\n+__msg_next(\" exit from 10 to 11\")\n+__msg_next(\"loop at 3, nested in 1\")\n+__msg_next(\" backedge from 9, latch at 9\")\n+__msg_next(\" exit from 9 to 10\")\n+__msg_next(\"loop at 5, nested in 3\")\n+__msg_next(\" backedge from 6, latch at 6\")\n+__msg_next(\" exit from 6 to 7\")\n+__msg_next(\"loop at 7, nested in 3\")\n+__msg_next(\" backedge from 8, latch at 8\")\n+__msg_next(\" exit from 8 to 9\")\n+__naked void loop_nested_siblings_common_ancestors(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr1 += 1;\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+3:\tr2 += 1;\t\t\t\t\t\\\n+\tif r2 \u003c 3 goto 3b;\t\t\t\t\\\n+4:\tr2 += -1;\t\t\t\t\t\\\n+\tif r2 != 0 goto 4b;\t\t\t\t\\\n+\tif r1 \u003c 4 goto 2b;\t\t\t\t\\\n+\tif r0 \u003c 5 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c\nnew file mode 100644\nindex 0000000000000..69e9062870acb\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c\n@@ -0,0 +1,1108 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */\n+\n+#include \u003clinux/bpf.h\u003e\n+#include \u003cstdbool.h\u003e\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \"bpf_misc.h\"\n+#include \"bpf_kfuncs.h\"\n+\n+struct map_val {\n+\tchar foo[1024];\n+};\n+\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_HASH);\n+\t__uint(max_entries, 1);\n+\t__type(key, int);\n+\t__type(value, struct map_val);\n+} map SEC(\".maps\");\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r0=(+ r0 1) / (linear r0 1)\")\n+__naked void simple_loop1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+loop_%=:\t\t\t\t\t\t\\\n+\tif r0 == 10 goto exit_%=;\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tgoto loop_%=;\t\t\t\t\t\\\n+exit_%=:\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg(\"8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -\u003e ?\")\n+__naked void indirect_write_invalidates_scev(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = r0;\t\t\t\t\\\n+loop_%=:\t\t\t\t\t\t\\\n+\tr0 = *(u64 *)(r10 - 8);\t\t\t\t\\\n+\tif r0 == 10 goto exit_%=;\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = r0;\t\t\t\t\\\n+\tr1 = r10;\t\t\t\t\t\\\n+\tr1 += -8;\t\t\t\t\t\\\n+\t*(u64 *)(r1 + 0) = r0;\t\t\t\t\\\n+\tgoto loop_%=;\t\t\t\t\t\\\n+exit_%=:\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg_next(\"scev at header 2:\")\n+__msg_next(\" *fp-8=(+ *fp-8 1) / (linear *fp-8 1)\")\n+__msg_next(\" scev at latch 3:\")\n+__msg_next(\" r0=*fp-8 / (linear *fp-8 1)\")\n+__msg_next(\" *fp-8=*fp-8 / (linear *fp-8 1)\")\n+__naked void simple_loop2(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = r0;\t\t\t\t\\\n+loop_%=:\t\t\t\t\t\t\\\n+\tr0 = *(u64 *)(r10 - 8);\t\t\t\t\\\n+\tif r0 == 10 goto exit_%=;\t\t\t\\\n+\tr0 = *(u64 *)(r10 - 8);\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = r0;\t\t\t\t\\\n+\tgoto loop_%=;\t\t\t\t\t\\\n+exit_%=:\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg_next(\"scev at header 2:\")\n+__msg_next(\" r1=(+ r1 1) / (linear r1 1)\")\n+__naked void meet_agrees(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r1 == 2 goto 3f;\t\t\t\t\\\n+\tif r0 == 7 goto 2f;\t\t\t\t\\\n+\tr1 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\tr1 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+3:\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__failure\n+__log_level(2)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r6=(any r6 (+ r6 1)) / ?\")\n+__naked void meet_disagrees(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r6 == 2 goto 3f;\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 == 7 goto 1b;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+3:\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__log_level(2)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r6=(bswap32 (bswap32 (zext32 (- (- (zext32 (+ (\u003e\u003e...) 1))))))) / ?\")\n+__naked void expr_chain(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r6 == 2 goto 2f;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tr6 \u003c\u003c= 32;\t\t\t\t\t\\\n+\tr6 \u003e\u003e= 32;\t\t\t\t\t\\\n+\tw6 += 1;\t\t\t\t\t\\\n+\tr6 = -r6;\t\t\t\t\t\\\n+\tw6 = -w6;\t\t\t\t\t\\\n+\tr6 = bswap32 r6;\t\t\t\t\\\n+\tr6 = bswap32 r6;\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n+__msg_next(\" r7=?\")\n+__msg_next(\" scev at latch 1:\")\n+__msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n+__msg_next(\" r7=?\")\n+__msg_next(\"scev at header 4:\")\n+__msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n+__msg_next(\" scev at latch 4:\")\n+__msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n+__naked void nested_loop1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r6 == 2 goto 2f;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tr7 = 0;\t\t\t\t\t\t\\\n+3:\t\t\t\t\t\t\t\\\n+\tif r7 == 2 goto 4f;\t\t\t\t\\\n+\tr7 += 1;\t\t\t\t\t\\\n+\tgoto 3b;\t\t\t\t\t\\\n+4:\t\t\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\tr0 = r7;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r6=(+ r6 1) / (linear r6 1)\")\n+__msg_next(\" r7=?\")\n+__msg_next(\" scev at latch 4:\")\n+__msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n+__msg_next(\"scev at header 4:\")\n+__msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n+__msg_next(\" scev at latch 4:\")\n+__msg_next(\" r7=(+ r7 1) / (linear r7 1)\")\n+__msg(\"loop header at 1, can't widen r7, expr is ?\")\n+__msg(\"loop header at 4, widening r7 to 0..2 step 1\")\n+__log_level(2)\n+__naked void nested_loop_hdr_backedge1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\t\t\t\t\t\t\t\\\n+\tif r6 == 2 goto 3f;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\t r7 = 0;\t\t\t\t\t\\\n+2:\t\t\t\t\t\t\t\\\n+\t if r7 == 2 goto 1b;\t\t\t\t\\\n+\t r7 += 1;\t\t\t\t\t\\\n+\t goto 2b;\t\t\t\t\t\\\n+3:\t\t\t\t\t\t\t\\\n+\tr0 = r7;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 10 post-cond\")\n+__msg(\"loop header at 1, widening r0 to 0..9 step 1\")\n+__msg(\"processed 5 insns\")\n+__naked void post_cond_jlt(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 3, header_count is 8\")\n+__msg(\"loop header at 3, widening r0 to 2..9 step 1\")\n+__msg(\"3: R0=scalar(smin=umin=smin32=umin32=2,smax=umax=smax32=umax32=9,{{.*}})\")\n+__msg(\"processed 6 insns\")\n+__naked void post_cond_jlt_with_base(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr7 = 10 ll;\t/* ldimm64 for a twist */\t\\\n+\tr0 = 2;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c r7 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 11\")\n+__msg(\"loop header at 1, widening r0 to 0..10 step 1\")\n+__msg(\"1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})\")\n+__msg(\"processed 5 insns\")\n+__naked void post_cond_jle(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003c= 10 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 10\")\n+__msg(\"loop header at 1, widening r0 to 0..9 step 1\")\n+__msg(\"1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=9,{{.*}})\")\n+__msg(\"processed 6 insns\")\n+__naked void post_cond_jge(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 \u003e= 10 goto 2f;\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 11\")\n+__msg(\"loop header at 1, widening r0 to 0..10 step 1\")\n+__msg(\"1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})\")\n+__msg(\"processed 6 insns\")\n+__naked void pre_cond_jge(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tif r0 \u003e= 10 goto 2f;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 2 post-cond\")\n+__naked void post_cond_jgt(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 2;\t\t\t\t\t\t\\\n+1:\tr0 += -1;\t\t\t\t\t\\\n+\tif r0 \u003e 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r0=(+ r0 1) / (linear r0 1)\")\n+__msg_next(\" scev at latch 2:\")\n+__msg_next(\" r0=(+ r0 1) / (linear (+ r0 1) 1)\")\n+__msg(\"loop header at 1, widening r0\")\n+__msg(\"1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})\")\n+__msg(\"1: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})\")\n+__msg(\"2: (55) if r0 != 0x3 goto pc-2\")\n+__msg(\"3: (95) exit\")\n+__msg(\"loop header at 1, clamping r0\")\n+__msg(\"from 2 to 1: safe\")\n+__msg(\"processed 5 insns\")\n+__naked void post_cond_jne(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 != 3 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r0=(+ r0 -1) / (linear r0 -1)\")\n+__msg_next(\" scev at latch 2:\")\n+__msg_next(\" r0=(+ r0 -1) / (linear (+ r0 -1) -1)\")\n+__msg(\"loop header at 1, header_count is 3 post-cond\")\n+__msg(\"loop header at 1, widening r0 to 1..3 step 1\")\n+__msg(\"1: R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,var_off=(0x0; 0x3)) loop_stack=1\")\n+__msg(\"loop header at 1, clamping r0 to 1..2 step 1\")\n+__msg(\"processed 5 insns\")\n+__naked void post_cond_jne_neg_step(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 3;\t\t\t\t\t\t\\\n+1:\tr0 += -1;\t\t\t\t\t\\\n+\tif r0 != 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg_next(\"scev at header 1:\")\n+__msg_next(\" r0=(+ r0 1) / (linear r0 1)\")\n+__msg_next(\" scev at latch 1:\")\n+__msg_next(\" r0=(+ r0 1) / (linear r0 1)\")\n+__msg(\"loop header at 1, widening r0\")\n+__msg(\"1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=3,{{.*}})\")\n+__msg(\"1: (15) if r0 == 0x3 goto pc+2 ; R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})\")\n+__msg(\"2: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})\")\n+__msg(\"3: (05) goto pc-3\")\n+__msg(\"loop header at 1, clamping r0\")\n+__msg(\"1: safe\")\n+__msg(\"from 1 to 4: R0=3\")\n+__msg(\"4: R0=3\")\n+__msg(\"4: (95) exit\")\n+__msg(\"processed 6 insns\")\n+__naked void pre_cond_je1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tif r0 == 3 goto 2f;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is [0..3] post-cond\")\n+__naked void one_backedge_two_exits(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 == 0 goto 2f;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tif r6 != 3 goto 1b;\t\t\t\t\\\n+2:\tr0 = r6;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg_next(\"scev at header 11:\")\n+__msg_next(\" r0=(+ r0 1) / (linear r0 1)\")\n+__msg_next(\" r1=(+ r1 2) / (linear r1 2)\")\n+__msg_next(\" scev at latch 16:\")\n+__msg_next(\" r0=(+ r0 1) / (linear (+ r0 1) 1)\")\n+__msg_next(\" r1=(+ r1 2) / (linear (+ r1 2) 2)\")\n+__msg(\"loop header at 11, widening r0\")\n+__msg(\"loop header at 11, widening r1\")\n+__msg(\"11: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=7,var_off=(0x0; 0x7)) R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=14,var_off=(0x0; 0xe),step=0+2)\")\n+/* loop exit */\n+__msg(\"16: (a5) if r0 \u003c 0x8 goto pc-6\")\n+__msg(\"exiting loop 11\")\n+__msg(\"17: (95) exit\")\n+/* second iteration */\n+__msg(\"loop header at 11, clamping r0\")\n+__msg(\"loop header at 11, clamping r1\")\n+/* iteration convergence */\n+__msg(\"from 16 to 11: safe\")\n+__not_msg(\"{{^}}11:\")\n+/* map lookup error path */\n+__msg(\"from 7 to 17: safe\")\n+__naked void correlated_regs(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\t*(u64*)(r10 - 8) = r1;\t\t\t\t\\\n+\tr2 = r10;\t\t\t\t\t\\\n+\tr2 += -8;\t\t\t\t\t\\\n+\tr1 = %[map] ll;\t\t\t\t\t\\\n+\tcall %[bpf_map_lookup_elem];\t\t\t\\\n+\tif r0 == 0 goto 2f;\t\t\t\t\\\n+\tr6 = r0;\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+1:\tr2 = r6;\t\t\t\t\t\\\n+\tr2 += r1;\t\t\t\t\t\\\n+\t*(u8 *)(r2 + 0) = 1;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr1 += 2;\t\t\t\t\t\\\n+\tif r0 \u003c 8 goto 1b;\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_map_lookup_elem),\n+\t __imm_addr(map)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * k = 0\n+ * for (i = 0; i \u003c 4; i++):\n+ * for (j = 0; j \u003c 4; j++):\n+ * k += 1\n+ * k \u003c\u003c= 1 // make SCEV construction not possible\n+ * k \u003e\u003e= 1\n+ * map[k] = 1 // make k precise\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"19: (72) *(u8 *)(r4 +0) = 1 ; R4=map_value(id={{.*}},map=map,ks=4,vs=1024,imm=16)\")\n+__not_msg(\"19: \")\n+__msg(\"processed 106 insns\")\n+__naked void nested_loops_precise_var1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\t*(u64*)(r10 - 8) = 0;\t\t\t\t\\\n+\tr1 = %[map] ll;\t\t\t\t\t\\\n+\tr2 = r10;\t\t\t\t\t\\\n+\tr2 += -8;\t\t\t\t\t\\\n+\tcall %[bpf_map_lookup_elem];\t\t\t\\\n+\tif r0 == 0 goto 3f;\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\tr3 = 0;\t\t\t\t\t\t\\\n+\t/* outer loop */\t\t\t\t\\\n+1:\tr2 = 0;\t\t\t\t\t\t\\\n+\t/* inner loop */\t\t\t\t\\\n+2:\tr2 += 1;\t\t\t\t\t\\\n+\tr3 += 1;\t\t\t\t\t\\\n+\tr3 \u003c\u003c= 1;\t\t\t\t\t\\\n+\tr3 \u003e\u003e= 1;\t\t\t\t\t\\\n+\tif r2 \u003c 4 goto 2b;\t\t\t\t\\\n+\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr4 = r0;\t\t\t\t\t\\\n+\tr4 += r3;\t\t\t\t\t\\\n+\t*(u8 *)(r4 + 0) = 1;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+3:\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_map_lookup_elem),\n+\t __imm_addr(map)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 1 pre-cond\")\n+__naked void pre_cond_jgt(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = -1;\t\t\t\t\t\\\n+1:\tif r0 \u003e 1 goto 2f;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+2:\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 2 post-cond\")\n+__naked void loop_jslt_latch_post(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = -2;\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 s\u003c 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 1 post-cond\")\n+__naked void loop_jslt_latch_post1(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = -1;\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 s\u003c 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, 0 iterations count\")\n+__naked void loop_jslt_latch_post2(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 s\u003c 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 1, header_count is 3 post-cond\")\n+__naked void loop_jsle_latch_post(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = -2;\t\t\t\t\t\\\n+1:\tr0 += 1;\t\t\t\t\t\\\n+\tif r0 s\u003c= 0 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg(\"loop header at 2, header_count is 100 post-cond\")\n+__msg(\"loop header at 4, header_count is [0..100] post-cond\")\n+__msg(\"loop header at 6, header_count is [0..100] post-cond\")\n+__msg(\"processed 20 insns\")\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__naked void nested_loop_with_two_exits(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tr6 += 1;\t\t\t\t\t\\\n+\tr7 = 0;\t\t\t\t\t\t\\\n+2:\tr7 += 1;\t\t\t\t\t\\\n+\tr8 = 0;\t\t\t\t\t\t\\\n+3:\tr8 += 1;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 == 42 goto +1;\t\t\t\t\\\n+\tgoto 4f;\t\t\t\t\t\\\n+\tif r8 \u003c 100 goto 3b;\t\t\t\t\\\n+\tif r7 \u003c 100 goto 2b;\t\t\t\t\\\n+4:\tif r6 \u003c 100 goto 1b;\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__naked void exit_loop_into_loop_header(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr1 = 0;\t\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+loop_a_%=:\t\t\t\t\t\t\\\n+\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 10 goto loop_a_%=;\t\t\t\\\n+loop_b_%=:\t\t\t\t\t\t\\\n+\tr2 += 1;\t\t\t\t\t\\\n+\tif r2 \u003c 10 goto loop_b_%=;\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * This exercises verifier.c:loop_stack_{pop,push}() implementation,\n+ * at 'goto d' loops 'b' and 'a' have to be popped from stack,\n+ * while loops 'c' and 'd' have to be pushed to stack.\n+ *\n+ * loop a: // header 5\n+ * loop b: // header 6\n+ * if (rand) goto d; // 8 -\u003e 12, side entry into inner loop d\n+ * ...\n+ * loop c: // header 11\n+ * loop d: // header 12\n+ * ...\n+ */\n+SEC(\"xdp\")\n+__log_level(2)\n+__msg(\"loop at 5\")\n+__msg(\"loop at 6, nested in 5\")\n+__msg(\"loop at 11, irreducible\")\n+__msg(\"loop at 12, nested in 11\")\n+/* entry via if r0 == 5 goto d_%= false branch */\n+__msg(\"loop header at 12, header_count is 3 post-cond\")\n+__msg(\"loop header at 12, widening r9 to 0..2 step 1\")\n+__msg(\"12: R8=1 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) loop_stack=11,12\")\n+/* entry via if r0 == 5 goto d_%= true branch */\n+__msg(\"loop header at 12, header_count is 3 post-cond\")\n+__msg(\"loop header at 12, widening r9 to 0..2 step 1\")\n+__msg(\"from 8 to 12: R8=0 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) R10=fp0 loop_stack=11,12\")\n+__naked void enter_nested_loop_from_side(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+\tr7 = 0;\t\t\t\t\t\t\\\n+\tr8 = 0;\t\t\t\t\t\t\\\n+\tr9 = 0;\t\t\t\t\t\t\\\n+a_%=:\tr6 += 1;\t\t\t\t\t\\\n+b_%=:\tr7 += 1;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tif r0 == 5 goto d_%=;\t\t\t\t\\\n+\tif r7 \u003c 3 goto b_%=;\t\t\t\t\\\n+\tif r6 \u003c 3 goto a_%=;\t\t\t\t\\\n+c_%=:\tr8 += 1;\t\t\t\t\t\\\n+d_%=:\tr9 += 1;\t\t\t\t\t\\\n+\tif r9 \u003c 3 goto d_%=;\t\t\t\t\\\n+\tif r8 \u003c 3 goto c_%=;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Loop A (counter in r6) contains irreducible loop B (header 5),\n+ * which contains C (counter in r9).\n+ * Entering B at 'body' saves and restores r6, making it appear invariant.\n+ * Entering B at 'alternate' skips the save and modifies r6 instead.\n+ * Hence A must not infer a SCEV expression for r6.\n+ * SCEV expression for r9 in C should still be computed.\n+ *\n+ * 0: r6 = 0;\n+ * do { // A\n+ * 1: r6++;\n+ * 2: r0 = bpf_get_prandom_u32();\n+ * 3: r7 = 0;\n+ * 4: if (r0 \u003e 5) goto alternate;\n+ * 5: B: r8 = r6; // B\n+ * 6: goto body;\n+ * 7: alternate:\n+ * r8 = r6;\n+ * 8: r8++;\n+ * 9: body:\n+ * r6 = r8;\n+ * 10: r9 = 0;\n+ * do { // C\n+ * 11: r9++;\n+ * 12: } while (r9 \u003c 3);\n+ * 13: r7++;\n+ * 14: if (r7 \u003c 4) goto B;\n+ * 15: } while (r6 \u003c 4);\n+ * 16: r0 = 0;\n+ * 17: return r0;\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg(\"loop at 1{{$}}\")\n+__msg(\"loop at 5, nested in 1, irreducible\")\n+__msg(\"loop at 11, nested in 5\")\n+__msg(\"scev at header 1:\")\n+__msg_next(\" r6=?\")\n+__msg(\"scev at header 11:\")\n+__msg_next(\" r9=(+ r9 1) / (linear r9 1)\")\n+__msg(\"loop header at 11, widening r9 to 0..2 step 1\")\n+__not_msg(\"loop header at 1, widening r6\")\n+__naked void nested_irreducible_loop(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+a_%=:\tr6 += 1;\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr7 = 0;\t\t\t\t\t\t\\\n+\tif r0 \u003e 5 goto alternate_%=;\t\t\t\\\n+b_%=:\tr8 = r6;\t\t\t\t\t\\\n+\tgoto body_%=;\t\t\t\t\t\\\n+alternate_%=:\t\t\t\t\t\t\\\n+\tr8 = r6;\t\t\t\t\t\\\n+\tr8 += 1;\t\t\t\t\t\\\n+body_%=:\t\t\t\t\t\t\\\n+\tr6 = r8;\t\t\t\t\t\\\n+\tr9 = 0;\t\t\t\t\t\t\\\n+c_%=:\tr9 += 1;\t\t\t\t\t\\\n+\tif r9 \u003c 3 goto c_%=;\t\t\t\t\\\n+\tr7 += 1;\t\t\t\t\t\\\n+\tif r7 \u003c 4 goto b_%=;\t\t\t\t\\\n+\tif r6 \u003c 4 goto a_%=;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Induction variable seeded from a non-constant value. r7 enters the loop as a\n+ * range aligned to 2 (prandom \u0026 0x6 -\u003e {0,2,4,6}) and is incremented by a\n+ * non-power-of-2 slope of 6. Since the entry value is not a single point, only\n+ * the power-of-two alignment shared by the entry value and the slope can be\n+ * guaranteed, so the widened step is 2 - not |slope|=6, which would be unsound\n+ * here (a constant entry value would have allowed step 6).\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 4, widening r7 to 0..18 step 2\")\n+__msg(\"R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=18,var_off=(0x0; 0x1e),step=0+2)\")\n+__naked void widen_nonconst_base(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tr7 \u0026= 0x6;\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tr7 += 6;\t\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tif r6 \u003c 3 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * Two nested loops with (1) exiting directly to (2):\n+ *\n+ * for (r6 = 0; r6 \u003c 4; r6++) {\n+ * r7 = 0;\n+ * for (; r7 \u003c 3; r7++) {} // (1)\n+ * for (; r7 != 0; r7--) {} // (2)\n+ * }\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__msg(\"loop header at 1, widening r6 to 0..3 step 1\")\n+__msg(\"loop header at 2, widening r7 to 0..2 step 1\")\n+__msg(\"loop header at 4, widening r7 to 1..3 step 1\")\n+__naked void sibling_inner_loops(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tr7 = 0;\t\t\t\t\t\t\\\n+2:\tr7 += 1;\t\t\t\t\t\\\n+\tif r7 \u003c 3 goto 2b;\t\t\t\t\\\n+3:\tr7 += -1;\t\t\t\t\t\\\n+\tif r7 != 0 goto 3b;\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tif r6 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__msg(\"loop header at 0, can't compute iterations count\")\n+__naked void uninit_slot_counter(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+1:\tr0 = *(u64 *)(r10 - 8);\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = r0;\t\t\t\t\\\n+\tif r0 \u003c 10 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * The assignment happens only on the second iteration:\n+ *\n+ * r7 = 5;\n+ * for (r6 = 0; r6 \u003c 3; r6++)\n+ * if (r6 == 1)\n+ * r7 = 10;\n+ * if (r7 != 10)\n+ * invalid_stack_read();\n+ *\n+ * R7 is always 10 at the real exit. Widening loses the correlation between\n+ * R6 and R7, leaving R7 in [5, 10] both at the loop header and after the loop.\n+ * The verifier therefore rejects the possible invalid stack read.\n+ */\n+SEC(\"xdp\")\n+__failure\n+__log_level(2)\n+__msg(\"2: {{.*}}R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))\")\n+__msg(\"7: R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))\")\n+__msg(\"invalid read from stack R10 off=0 size=8\")\n+__naked void conditional_assignment_on_second_iteration(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr7 = 5;\t\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tif r6 \u003e= 3 goto 3f;\t\t\t\t\\\n+\tif r6 != 1 goto 2f;\t\t\t\t\\\n+\tr7 = 10;\t\t\t\t\t\\\n+2:\tr6 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+3:\tif r7 == 10 goto 4f;\t\t\t\t\\\n+\tr0 = *(u64 *)(r10 + 0);\t\t\t\t\\\n+4:\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Join two stack pointer offsets via (any r7 r8), with r8 loop-invariant.\n+ * The joined range [-16, -8] still points to initialized stack memory,\n+ * so dereferencing r7 after the loop is safe.\n+ */\n+SEC(\"xdp\")\n+__success __retval(0)\n+__log_level(2)\n+__msg(\"loop header at 7, widening r7 to -16..-8 step 1\")\n+__msg(\"7: {{.*}}R7=fp(smin=smin32=-16,smax=smax32=-8,\")\n+__msg(\"12: R7=fp(smin=smin32=-16,smax=smax32=-8,\")\n+__naked void conditional_stack_pointer_assignment(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 16) = 0;\t\t\t\t\\\n+\t*(u64 *)(r10 - 8) = 0;\t\t\t\t\\\n+\tr7 = r10;\t\t\t\t\t\\\n+\tr7 += -16;\t\t\t\t\t\\\n+\tr8 = r10;\t\t\t\t\t\\\n+\tr8 += -8;\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tif r6 \u003e= 3 goto 3f;\t\t\t\t\\\n+\tif r6 != 1 goto 2f;\t\t\t\t\\\n+\tr7 = r8;\t\t\t\t\t\\\n+2:\tr6 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+3:\tr0 = *(u64 *)(r7 + 0);\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * r7 starts as 1 + 6*k and invariant r8 as 1 + 9*k (0 \u003c= k \u003c= 3).\n+ * The (any r7 r8) union must preserve base 1 and step gcd(6, 9) = 3.\n+ */\n+SEC(\"xdp\")\n+__success __retval(1)\n+__log_level(2)\n+__msg(\"r7 += 1 {{.*}}step=1+6)\")\n+__msg(\"r8 += 1 {{.*}}step=1+9)\")\n+__msg(\"loop header at 9, widening r7 to 1..28 step 3\")\n+__msg(\"9: {{.*}}R7=scalar({{.*}},step=1+3)\")\n+__msg(\"14: R7=scalar({{.*}},step=1+3)\")\n+__naked void conditional_scalar_assignment_gcd(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tcall %[bpf_get_prandom_u32];\t\t\t\\\n+\tr0 \u0026= 3;\t\t\t\t\t\\\n+\tr7 = r0;\t\t\t\t\t\\\n+\tr7 *= 6;\t\t\t\t\t\\\n+\tr7 += 1;\t\t\t\t\t\\\n+\tr8 = r0;\t\t\t\t\t\\\n+\tr8 *= 9;\t\t\t\t\t\\\n+\tr8 += 1;\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+1:\tif r6 \u003e= 3 goto 3f;\t\t\t\t\\\n+\tif r6 != 1 goto 2f;\t\t\t\t\\\n+\tr7 = r8;\t\t\t\t\t\\\n+2:\tr6 += 1;\t\t\t\t\t\\\n+\tgoto 1b;\t\t\t\t\t\\\n+3:\tr0 = r7;\t\t\t\t\t\\\n+\tr0 %%= 3;\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t:\n+\t: __imm(bpf_get_prandom_u32)\n+\t: __clobber_all);\n+}\n+\n+/*\n+ * A loop induction variable used to compute the base address of a store to the\n+ * stack must not be widened: the spill offset would become varying, which the\n+ * verifier does not track.\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking\")\n+__naked void no_widen_stack_spill(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+1:\tr3 = r10;\t\t\t\t\t\\\n+\tr3 += -64;\t\t\t\t\t\\\n+\tr3 += r2;\t\t\t\t\t\\\n+\t*(u64 *)(r3 + 0) = r0;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr2 += 8;\t\t\t\t\t\\\n+\tif r0 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+/*\n+ * Same hazard across a loop nest: the outer induction variable r2 addresses a\n+ * stack store performed inside the inner loop. The dependency is pulled up from\n+ * the inner loop, so the outer loop must not widen r2.\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking\")\n+__msg(\"loop header at 3, widening r1 to 0..1 step 1\")\n+__naked void no_widen_stack_spill_nested(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+1:\tr1 = 0;\t\t\t\t\t\t\\\n+2:\tr3 = r10;\t\t\t\t\t\\\n+\tr3 += -64;\t\t\t\t\t\\\n+\tr3 += r2;\t\t\t\t\t\\\n+\t*(u64 *)(r3 + 0) = r1;\t\t\t\t\\\n+\tr1 += 1;\t\t\t\t\t\\\n+\tif r1 \u003c 2 goto 2b;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr2 += 8;\t\t\t\t\t\\\n+\tif r0 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * Complement of no_widen_stack_spill: a sub-register (1-byte) store to the stack\n+ * lands as STACK_MISC and carries no tracked value, so the induction variable\n+ * addressing it (r2) is still widened.\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"widening r2 to 0..24 step 8\")\n+__naked void widen_byte_stack_store(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+1:\tr3 = r10;\t\t\t\t\t\\\n+\tr3 += -64;\t\t\t\t\t\\\n+\tr3 += r2;\t\t\t\t\t\\\n+\t*(u8 *)(r3 + 0) = r0;\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr2 += 8;\t\t\t\t\t\\\n+\tif r0 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * A fill (BPF_LDX) at a varying stack offset loses precision just like a spill,\n+ * so the induction variable computing the load base (r2) must not be widened.\n+ * The slots are initialized up front so the fill itself is a valid read.\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"loop header at 6, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking\")\n+__naked void no_widen_stack_fill(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\t*(u64 *)(r10 - 64) = r0;\t\t\t\\\n+\t*(u64 *)(r10 - 56) = r0;\t\t\t\\\n+\t*(u64 *)(r10 - 48) = r0;\t\t\t\\\n+\t*(u64 *)(r10 - 40) = r0;\t\t\t\\\n+\tr2 = 0;\t\t\t\t\t\t\\\n+1:\tr3 = r10;\t\t\t\t\t\\\n+\tr3 += -64;\t\t\t\t\t\\\n+\tr3 += r2;\t\t\t\t\t\\\n+\tr4 = *(u64 *)(r3 + 0);\t\t\t\t\\\n+\tr0 += 1;\t\t\t\t\t\\\n+\tr2 += 8;\t\t\t\t\t\\\n+\tif r0 \u003c 4 goto 1b;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n+/*\n+ * A dynptr/iter/irq/res_spin_lock call initializes a stack object through a\n+ * pointer argument, which acts like a spill base: the induction variable\n+ * computing that argument's varying stack offset must not be widened, otherwise\n+ * the slot can't be resolved. Here each iteration constructs an xdp dynptr at\n+ * \u0026dptrs[i].\n+ */\n+SEC(\"xdp\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+__msg(\"can't widen {{.*}}, requires exact stack-offset tracking\")\n+int no_widen_dynptr_kfunc_arg(struct xdp_md *ctx)\n+{\n+\tstruct bpf_dynptr dptrs[4];\n+\tint i;\n+\n+#pragma clang loop unroll(disable)\n+\tfor (i = 0; i \u003c 4; i++)\n+\t\tbpf_dynptr_from_xdp(ctx, 0, \u0026dptrs[i]);\n+\n+\treturn 0;\n+}\n+\n+char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c\nindex 3e0bea9819cab..5da8b9a6018cf 100644\n--- a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c\n+++ b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c\n@@ -586,4 +586,37 @@ __naked void stack_check_size_512_with_may_goto(void)\n }\n #endif\n \n+/* Verify that old PTR_TO_STACK state is considered a super-set of\n+ * new PTR_TO_STACK state when new variable range is a sub-range\n+ * of the old range, e.g. old [-72, -16] vs new [-64, -16].\n+ */\n+SEC(\"socket\")\n+__success\n+__log_level(2)\n+__flag(BPF_F_TEST_STATE_FREQ)\n+/* r7 is widened to [-72, -16] at the loop header (insn 3),\n+ * the loop body sees [-64, -8] after 'r7 += 8'\n+ */\n+__msg(\"loop header at 3, widening r7 to -72..-16 step 8\")\n+__msg(\"R7=fp(smin=smin32=-64,smax=smax32=-8\")\n+/* back-edge state is clamped to the remaining iterations and pruned\n+ * at the header, because [-64, -16] is within the widened [-72, -16]\n+ */\n+__msg(\"loop header at 3, clamping r7 to -64..-16 step 8\")\n+__msg(\"from 5 to 3: safe\")\n+__msg(\"processed 9 insns\")\n+__naked void stack_ptr_subrange_in_loop(void)\n+{\n+\tasm volatile (\"\t\t\t\t\t\\\n+\tr7 = r10;\t\t\t\t\t\\\n+\tr7 += -72;\t\t\t\t\t\\\n+\tr6 = 0;\t\t\t\t\t\t\\\n+\tr7 += 8;\t\t\t\t\t\\\n+\tr6 += 1;\t\t\t\t\t\\\n+\tif r6 \u003c 8 goto -3;\t\t\t\t\\\n+\tr0 = 0;\t\t\t\t\t\t\\\n+\texit;\t\t\t\t\t\t\\\n+\"\t::: __clobber_all);\n+}\n+\n char _license[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c\nindex 25eeb1c1248b3..edeeb244e693f 100644\n--- a/tools/testing/selftests/bpf/test_loader.c\n+++ b/tools/testing/selftests/bpf/test_loader.c\n@@ -508,6 +508,16 @@ static int parse_test_spec(struct test_loader *tester,\n \t\t\tif (err)\n \t\t\t\tgoto cleanup;\n \t\t\tspec-\u003emode_mask |= UNPRIV;\n+\t\t} else if ((msg = str_has_pfx(s, \"test_expect_msg_next=\"))) {\n+\t\t\terr = __push_msg(msg, true, false, \u0026spec-\u003epriv.expect_msgs);\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t\tspec-\u003emode_mask |= PRIV;\n+\t\t} else if ((msg = str_has_pfx(s, \"test_expect_msg_next_unpriv=\"))) {\n+\t\t\terr = __push_msg(msg, true, false, \u0026spec-\u003eunpriv.expect_msgs);\n+\t\t\tif (err)\n+\t\t\t\tgoto cleanup;\n+\t\t\tspec-\u003emode_mask |= UNPRIV;\n \t\t} else if ((msg = str_has_pfx(s, \"test_jited=\"))) {\n \t\t\tif (arch_mask == 0) {\n \t\t\t\tPRINT_FAIL(\"__jited used before __arch_*\");\n"
} |
| 2/1 | 2026/09/28 01:35 | agent | patch-evaluator |
0mModel:core Args: null Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_compute_loops",
"bpf_compute_idoms",
"bpf_compute_loop_iters",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_split_cur_state",
"bpf_set_reg_range",
"bpf_reg_union",
"cnum64_intersect_linear",
"btf_struct_access"
],
"Reasoning": "The patch series implements Scalar Evolution (SCEV) and loop induction variable analysis in the eBPF verifier. It adds CFG dominator tree computation (idoms), natural loop and backedge/exit detection, symbolic expression tracking, loop bound calculation, register widening, and clamping to verify bounded loops. It also introduces linear step/base tracking for scalar registers and variable-offset access validation for BTF struct arrays. These changes modify core verifier logic reachable from userspace via the bpf(BPF_PROG_LOAD, ...) syscall, making fuzzing essential to uncover soundness bugs, safety regressions, and unexpected verifier crashes.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d7942ef1185d903ecca00472af297f633f20d95d
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Sep 28 01:35:30 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c775bd7577063..a5fa2b5cc0c0d 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -9,6 +9,20 @@
#include <linux/filter.h> /* for MAX_BPF_STACK */
#include <linux/tnum.h>
#include <linux/cnum.h>
+#include <linux/math64.h> /* for div_s64_rem() */
+
+/*
+ * Mathematical modulo, the residue of 'v' modulo 'step', normalized to [0, step).
+ * This differs from C's '%' operator, which truncates the quotient toward zero
+ * and so returns a remainder with the sign of the dividend (e.g. -1 % 3 == -1, not 2).
+ */
+static inline u16 imod(s64 v, u16 step)
+{
+ s32 rem;
+
+ div_s64_rem(v, step, &rem);
+ return rem < 0 ? rem + step : rem;
+}
/* Maximum variable offset umax_value permitted when resolving memory accesses.
* In practice this is far bigger than any realistic pointer offset; this limit
@@ -164,6 +178,13 @@ struct bpf_reg_state {
* during state comparisons.
*/
u32 map_uid;
+ /*
+ * The value described by this register is some point lying on
+ * a line described by a linear equation base + step * k.
+ * Invariant: base < step.
+ */
+ u16 base;
+ u16 step;
/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
bool precise;
};
@@ -307,6 +328,21 @@ struct bpf_retval_range {
bool return_32bit;
};
+struct bpf_loop_iters {
+ u32 min_header_count; /* min number of times header is executed */
+ u32 max_header_count; /* max number of times header is executed */
+ bool pre_cond;
+};
+
+struct loop_stack_entry {
+ struct bpf_verifier_state *entry_state;
+ struct bpf_loop_iters iters;
+ u32 loop_id:31;
+ u32 terminates:1;
+};
+
+#define LOOP_STACK_SIZE 16
+
/* state of the program:
* type of all registers and stack info
*/
@@ -352,6 +388,12 @@ struct bpf_func_state {
u32 callback_depth;
/* Instructions processed in this frame and callees on the current path. */
u32 insns_subtotal;
+ /*
+ * Control-flow loop nesting at the current insn within this frame's
+ * subprogram (loops never cross subprogram boundaries).
+ */
+ u32 loop_stack_cnt;
+ struct loop_stack_entry loop_stack[LOOP_STACK_SIZE];
/* The following fields should be last. See copy_func_state() */
/* The state of the stack. Each element of the array describes BPF_REG_SIZE
@@ -415,6 +457,7 @@ static_assert(MAX_BPF_STACK_SLOTS <= (1 << 12));
#define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS)
#define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \
MAX_CALL_FRAMES)
+
struct bpf_verifier_state {
/* call stack tracking */
struct bpf_func_state *frame[MAX_CALL_FRAMES];
@@ -481,7 +524,9 @@ struct bpf_verifier_state {
bool speculative;
bool in_sleepable;
- /* first and last insn idx of this verifier state */
+ /* First and last insn idx of this verifier state.
+ * last_insn_idx is -1 if no instructions have been executed yet.
+ */
u32 first_insn_idx;
u32 last_insn_idx;
/* if this state is a backedge state then equal_state
@@ -629,6 +674,44 @@ struct bpf_iarray {
u32 items[];
};
+#define iarray_for_each(item, arr) \
+ for (int ___idx = 0; \
+ ___idx < (arr)->cnt && ({ item = (arr)->items[___idx]; 1; }); \
+ ___idx++)
+
+#define MAX_BACKEDGES 16
+#define MAX_LOOP_EXITS 256
+
+struct bpf_backedge {
+ int from;
+ int latch; /* -1 if no latch can be found */
+};
+
+struct bpf_loop_exit {
+ int from; /* instruction inside the loop */
+ int to; /* instruction outside the loop */
+};
+
+/* SCEV/widening register space: r0..r10 plus every stack slot of a frame. */
+#define BPF_SCEV_REGS_NUM (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)
+
+struct bpf_loop {
+ struct bpf_backedge backedges[MAX_BACKEDGES];
+ /* edges exiting from this loop, includes edges from nested loops */
+ struct bpf_loop_exit *exits;
+ int backedges_cnt;
+ int exits_cnt;
+ bool irreducible;
+ bool backedges_overflow;
+ bool exits_overflow;
+ /*
+ * Loop-entry registers used to compute stack addresses for loads,
+ * stores and calls requiring fixed stack offsets, in this and nested
+ * loops.
+ */
+ unsigned long store_base_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
+};
+
struct bpf_insn_aux_data {
union {
enum bpf_reg_type ptr_type; /* pointer type for load/store insns */
@@ -662,6 +745,13 @@ struct bpf_insn_aux_data {
};
struct btf_struct_meta *kptr_struct_meta;
u64 map_key_state; /* constant (32 bit) key tracking for maps */
+ /*
+ * Per-instruction summary of stack slots in the current frame
+ * that this instruction may write to.
+ */
+ DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
+ DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
+ u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
bool nospec; /* do not execute this instruction speculatively */
@@ -672,6 +762,8 @@ struct bpf_insn_aux_data {
bool non_sleepable; /* helper/kfunc may be called from non-sleepable context */
bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
+ bool bb_end;
+ bool need_scev;
u8 alu_state; /* used in combination with alu_limit */
/* true if STX or LDX instruction is a part of a spill/fill
* pattern for a bpf_fastcall call.
@@ -699,6 +791,13 @@ struct bpf_insn_aux_data {
u32 non_stack_access:1; /* instruction can access non-stack memory */
/* true if some jump or call instruction targets this instruction */
u32 jump_target:1;
+ /*
+ * True if this instruction is a loop entry. For loops with a single entry
+ * this bit will coincide with 'loop' pointer being non-NULL.
+ * Irreducible loops have multiple entries, all of them will be marked as 'loop_entry',
+ * but only the one at 'loop_header' will have a non-NULL 'loop' pointer.
+ */
+ u32 loop_entry:1;
/*
* CFG strongly connected component this instruction belongs to,
* zero if it is a singleton SCC.
@@ -718,6 +817,10 @@ struct bpf_insn_aux_data {
u16 const_reg_map_mask;
u16 const_reg_subprog_mask;
u32 const_reg_vals[10];
+ /* index of a loop header of the innermost loop containing this instruction, -1 if none */
+ s32 loop_header;
+ /* additional information about the loop if this instruction is a loop header */
+ struct bpf_loop *loop;
};
#define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
@@ -920,6 +1023,7 @@ struct bpf_scc_info {
};
struct bpf_liveness;
+struct scev;
struct bpf_fd_array {
union {
@@ -1005,6 +1109,7 @@ struct bpf_verifier_env {
* see bpf_subprog_info->postorder_start.
*/
int *insn_postorder;
+ int *postorder_nums;
int cur_stack;
/* current position in the insn_postorder vector */
int cur_postorder;
@@ -1080,6 +1185,10 @@ struct bpf_verifier_env {
u32 scc_cnt;
struct bpf_iarray *succ;
struct bpf_iarray *gotox_tmp_buf;
+ int *idoms;
+ struct scev *scev;
+ /* SCEV representation of stack slots not allocated yet. */
+ struct bpf_reg_state scev_not_init_reg;
};
static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1258,6 +1367,7 @@ void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
int mark_chain_precision(struct bpf_verifier_env *env, int regno);
int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx);
+int bpf_split_cur_state(struct bpf_verifier_env *env);
int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
void bpf_clear_jmp_history(struct bpf_verifier_state *state);
@@ -1272,6 +1382,7 @@ int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state
void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist);
void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
struct bpf_reg_state *reg);
+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg);
void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,
struct bpf_verifier_state *st);
@@ -1724,10 +1835,16 @@ s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env,
struct bpf_insn *insn, int arg,
int insn_idx);
int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);
+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
+ struct cnum64 range, u16 step);
+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
+ const struct bpf_reg_state *src);
int bpf_stack_liveness_init(struct bpf_verifier_env *env);
void bpf_stack_liveness_free(struct bpf_verifier_env *env);
int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
int bpf_compute_live_registers(struct bpf_verifier_env *env);
@@ -1819,6 +1936,7 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
struct bpf_attach_target_info *tgt_info);
/* Functions in fixups.c, called from bpf_check() */
+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len);
int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env);
int bpf_optimize_bpf_loop(struct bpf_verifier_env *env);
void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);
@@ -1831,4 +1949,40 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env);
int bpf_do_misc_fixups(struct bpf_verifier_env *env);
int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
+int bpf_flip_opcode(u32 opcode);
+u8 bpf_rev_opcode(u8 opcode);
+
+int bpf_compute_idoms(struct bpf_verifier_env *env);
+int bpf_compute_loops(struct bpf_verifier_env *env);
+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
+
+/*
+ * Simple binary heap implementation as described by
+ * https://en.wikipedia.org/wiki/Binary_heap
+ */
+struct bpf_min_heap {
+ int (*compare)(int, int, void *); /* ordering function for @elements */
+ int *elements; /* min-heap ordered by @compare */
+ void *arg; /* 3rd argument passed to @compare */
+ int capacity;
+ int count;
+};
+
+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg);
+void bpf_min_heap_free(struct bpf_min_heap *heap);
+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt);
+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt);
+
+int bpf_init_scev(struct bpf_verifier_env *env);
+void bpf_free_scev(struct bpf_verifier_env *env);
+int bpf_compute_scev(struct bpf_verifier_env *env);
+
+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_loop_iters *iters);
+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters);
+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 insn_idx,
+ struct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters);
+
#endif /* _LINUX_BPF_VERIFIER_H */
diff --git a/include/linux/cnum.h b/include/linux/cnum.h
index 49b7d0c7645de..49160318adf90 100644
--- a/include/linux/cnum.h
+++ b/include/linux/cnum.h
@@ -39,6 +39,7 @@ u32 cnum32_umin(struct cnum32 cnum);
u32 cnum32_umax(struct cnum32 cnum);
s32 cnum32_smin(struct cnum32 cnum);
s32 cnum32_smax(struct cnum32 cnum);
+struct cnum32 cnum32_union(struct cnum32 a, struct cnum32 b);
struct cnum32 cnum32_intersect(struct cnum32 a, struct cnum32 b);
void cnum32_intersect_with(struct cnum32 *dst, struct cnum32 src);
void cnum32_intersect_with_urange(struct cnum32 *dst, u32 min, u32 max);
@@ -65,6 +66,7 @@ u64 cnum64_umin(struct cnum64 cnum);
u64 cnum64_umax(struct cnum64 cnum);
s64 cnum64_smin(struct cnum64 cnum);
s64 cnum64_smax(struct cnum64 cnum);
+struct cnum64 cnum64_union(struct cnum64 a, struct cnum64 b);
struct cnum64 cnum64_intersect(struct cnum64 a, struct cnum64 b);
void cnum64_intersect_with(struct cnum64 *dst, struct cnum64 src);
void cnum64_intersect_with_urange(struct cnum64 *dst, u64 min, u64 max);
@@ -78,5 +80,6 @@ bool cnum64_is_subset(struct cnum64 outer, struct cnum64 inner);
struct cnum32 cnum32_from_cnum64(struct cnum64 cnum);
struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b);
+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step);
#endif /* _LINUX_CNUM_H */
diff --git a/include/linux/tnum.h b/include/linux/tnum.h
index ca2cfec8de08a..16682248f963a 100644
--- a/include/linux/tnum.h
+++ b/include/linux/tnum.h
@@ -134,4 +134,6 @@ static inline bool tnum_subreg_is_const(struct tnum a)
/* Returns the smallest member of t larger than z */
u64 tnum_step(struct tnum t, u64 z);
+u32 tnum_alignment(struct tnum a);
+
#endif /* _LINUX_TNUM_H */
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index c1f9b0d3468d3..fdff31d962d6c 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -6,7 +6,7 @@ cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
endif
CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
-obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o
+obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o loops.o heap.o scev.o
obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
diff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c
index 0e38b9575328c..43d5740034c0f 100644
--- a/kernel/bpf/backtrack.c
+++ b/kernel/bpf/backtrack.c
@@ -888,6 +888,10 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,
}
if (last_idx < 0) {
+ /* Consecutive checkpoints can have no instructions between them. */
+ if (st->parent)
+ goto parent;
+
/* we are at the entry into subprog, which
* is expected for global funcs, but only if
* requested precise registers are R1-R5
@@ -952,6 +956,7 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,
return -EFAULT;
}
}
+parent:
st = st->parent;
if (!st)
break;
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 9bcfefdfb7346..37437b93471d2 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -7496,6 +7496,14 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,
}
EXPORT_SYMBOL_GPL(btf_ctx_access);
+#define MAX_ARRAYS_WALK 16
+
+/* Description of an array crossed while walking a BTF access chain */
+struct array_access {
+ u32 id; /* BTF_KIND_ARRAY type id */
+ u32 off; /* offset of the access within the array */
+};
+
enum bpf_struct_walk_result {
/* < 0 error */
WALK_SCALAR = 0,
@@ -7504,10 +7512,43 @@ enum bpf_struct_walk_result {
WALK_STRUCT,
};
+static const struct btf_member *find_flex_member(const struct btf *btf, const struct btf_type *t)
+{
+ const struct btf_array *array;
+ const struct btf_type *mtype;
+ const struct btf_member *member;
+ u32 vlen = btf_type_vlen(t);
+
+ if (vlen == 0)
+ return NULL;
+
+ member = btf_type_member(t) + vlen - 1;
+ mtype = btf_type_skip_modifiers(btf, member->type, NULL);
+ if (!btf_type_is_array(mtype))
+ return NULL;
+
+ array = (const struct btf_array *)(mtype + 1);
+ if (array->nelems != 0)
+ return NULL;
+
+ return member;
+}
+
+static int push_array(struct array_access *arrays, u32 *arrays_cnt, struct array_access item)
+{
+ if (arrays == NULL)
+ return 0;
+ if (*arrays_cnt == MAX_ARRAYS_WALK)
+ return -1;
+ arrays[(*arrays_cnt)++] = item;
+ return 0;
+}
+
static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
const struct btf_type *t, int off, int size,
u32 *next_btf_id, enum bpf_type_flag *flag,
- const char **field_name, bool walk_flex_arrays)
+ const char **field_name, bool walk_flex_arrays,
+ struct array_access *arrays, u32 *arrays_cnt)
{
u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
const struct btf_type *mtype, *elem_type = NULL;
@@ -7542,22 +7583,19 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
/* If the last element is a variable size array, we may
* need to relax the rule.
*/
- if (vlen == 0)
+ member = find_flex_member(btf, t);
+ if (!member)
goto error;
- member = btf_type_member(t) + vlen - 1;
- mtype = btf_type_skip_modifiers(btf, member->type,
- NULL);
- if (!btf_type_is_array(mtype))
+ moff = __btf_member_bit_offset(t, member) / 8;
+ if (off < moff)
goto error;
+ mtype = btf_type_skip_modifiers(btf, member->type, &mid);
array_elem = (struct btf_array *)(mtype + 1);
- if (array_elem->nelems != 0)
- goto error;
- moff = __btf_member_bit_offset(t, member) / 8;
- if (off < moff)
- goto error;
+ if (push_array(arrays, arrays_cnt, (struct array_access){ mid, off - moff }))
+ return -E2BIG;
/* allow structure and integer */
t = btf_type_skip_modifiers(btf, array_elem->type,
@@ -7680,6 +7718,9 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
* the array's element as long as it is
* within the mtrue_end boundary.
*/
+ if (push_array(arrays, arrays_cnt,
+ (struct array_access){ mid, off - moff }))
+ return -E2BIG;
/* skip empty array */
if (moff == mtrue_end)
@@ -7772,15 +7813,29 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
int btf_struct_access(struct bpf_verifier_log *log,
const struct bpf_reg_state *reg,
- int off, int size, enum bpf_access_type atype __maybe_unused,
+ int _off, int size, enum bpf_access_type atype __maybe_unused,
u32 *next_btf_id, enum bpf_type_flag *flag,
const char **field_name)
{
const struct btf *btf = reg->btf;
enum bpf_type_flag tmp_flag = 0;
+ struct array_access arrays[MAX_ARRAYS_WALK];
+ const struct btf_member *member;
const struct btf_type *t;
+ u32 i, arrays_cnt = 0;
u32 id = reg->btf_id;
- int err;
+ s64 min_off, max_off, flex_off;
+ int err, off, ret;
+
+ if (check_add_overflow(reg_smin(reg), (s64)_off, &min_off) ||
+ check_add_overflow(reg_smax(reg), (s64)_off, &max_off) ||
+ min_off != (int)min_off) {
+ bpf_log(log,
+ "offset computation overflows: register offset range is [%lld, %lld], instruction offset is %d\n",
+ reg_smin(reg), reg_smax(reg), _off);
+ return -EINVAL;
+ }
+ off = min_off;
while (type_is_alloc(reg->type)) {
struct btf_struct_meta *meta;
@@ -7807,26 +7862,30 @@ int btf_struct_access(struct bpf_verifier_log *log,
t = btf_type_by_id(btf, id);
do {
err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag,
- field_name, !type_is_alloc(reg->type));
-
+ field_name, !type_is_alloc(reg->type), arrays, &arrays_cnt);
switch (err) {
case WALK_PTR:
/* For local types, the destination register cannot
* become a pointer again.
*/
- if (type_is_alloc(reg->type))
- return SCALAR_VALUE;
+ if (type_is_alloc(reg->type)) {
+ ret = SCALAR_VALUE;
+ goto check_variable_offset;
+ }
/* If we found the pointer or scalar on t+off,
* we're done.
*/
*next_btf_id = id;
*flag = tmp_flag;
- return PTR_TO_BTF_ID;
+ ret = PTR_TO_BTF_ID;
+ goto check_variable_offset;
case WALK_PTR_UNTRUSTED:
*flag = MEM_RDONLY | PTR_UNTRUSTED;
- return PTR_TO_MEM;
+ ret = PTR_TO_MEM;
+ goto check_variable_offset;
case WALK_SCALAR:
- return SCALAR_VALUE;
+ ret = SCALAR_VALUE;
+ goto check_variable_offset;
case WALK_STRUCT:
/* We found nested struct, so continue the search
* by diving in it. At this point the offset is
@@ -7846,6 +7905,54 @@ int btf_struct_access(struct bpf_verifier_log *log,
} while (t);
return -EINVAL;
+
+check_variable_offset:
+ if (min_off == max_off)
+ return ret;
+
+ /* Find an offset at which access would go to a flexible array tail (if any). */
+ t = btf_type_skip_modifiers(btf, reg->btf_id, NULL);
+ member = find_flex_member(btf, t);
+ flex_off = member ? __btf_member_bit_offset(t, member) / 8 : S64_MAX;
+
+ /*
+ * If this is a varying offset access, the step recorded within a register
+ * should correspond to one of the arrays visited while walking.
+ */
+ for (i = 0; i < arrays_cnt; i++) {
+ s64 array_start, array_end, access_end;
+ u32 asize, esize, elem_id;
+
+ /*
+ * 'arrays' records top-level arrays only, use __btf_resolve_size()
+ * to get flattened representation.
+ */
+ t = btf_type_by_id(btf, arrays[i].id);
+ if (IS_ERR(__btf_resolve_size(btf, t, &asize, NULL, &elem_id, NULL, NULL)) ||
+ IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, elem_id), &esize)))
+ continue;
+ /* Make sure every accessed offset lands on the same field of some element. */
+ if (esize == 0 || reg->step % esize != 0)
+ continue;
+
+ array_start = min_off - arrays[i].off;
+ /* An array within the flexible tail has no upper bound to exceed */
+ if (array_start >= flex_off)
+ return ret;
+
+ /* the 'size' bytes read at max_off must stay within the array */
+ if (check_add_overflow(array_start, (s64)asize, &array_end) ||
+ check_add_overflow(max_off, (s64)size, &access_end) ||
+ access_end > array_end)
+ continue;
+ return ret;
+ }
+
+ bpf_log(log,
+ "invalid variable offset access into struct %s: offsets [%lld, %lld] size %d step %d do not match any array\n",
+ btf_name_by_offset(btf, btf_type_by_id(btf, reg->btf_id)->name_off),
+ min_off, max_off, size, reg->step);
+ return -EINVAL;
}
/* Check that two BTF types, each specified as an BTF object + id, are exactly
@@ -7886,7 +7993,7 @@ bool btf_struct_ids_match(struct bpf_verifier_log *log,
if (!type)
return false;
err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL,
- walk_flex_arrays);
+ walk_flex_arrays, NULL, NULL);
if (err != WALK_STRUCT)
return false;
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index b0bd9ba951dfb..bd771efec66a3 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -767,6 +767,11 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
return ret;
}
+struct dfs_state {
+ u32 traversed:1;
+ u32 next_succ:31;
+};
+
/*
* For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
* [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
@@ -774,43 +779,52 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
*/
int bpf_compute_postorder(struct bpf_verifier_env *env)
{
- u32 cur_postorder, i, top, stack_sz, s;
- int *stack = NULL, *postorder = NULL, *state = NULL;
- struct bpf_iarray *succ;
+ int *stack = NULL, *postorder = NULL, *postorder_nums = NULL;
+ int subprog_idx, stack_sz, cur, s, cur_postorder, start;
+ struct dfs_state *state = NULL;
+ struct bpf_iarray *succ = NULL;
+ postorder_nums = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
postorder = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
- state = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
stack = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
- if (!postorder || !state || !stack) {
+ state = kvzalloc_objs(struct dfs_state, env->prog->len, GFP_KERNEL_ACCOUNT);
+ if (!postorder_nums || !postorder || !stack || !state) {
+ kvfree(postorder_nums);
kvfree(postorder);
- kvfree(state);
kvfree(stack);
+ kvfree(state);
return -ENOMEM;
}
cur_postorder = 0;
- for (i = 0; i < env->subprog_cnt; i++) {
- env->subprog_info[i].postorder_start = cur_postorder;
- stack[0] = env->subprog_info[i].start;
+ for (subprog_idx = 0; subprog_idx < env->subprog_cnt; subprog_idx++) {
+ start = env->subprog_info[subprog_idx].start;
+ env->subprog_info[subprog_idx].postorder_start = cur_postorder;
+ stack[0] = start;
stack_sz = 1;
+ state[start].traversed = true;
do {
- top = stack[stack_sz - 1];
- state[top] |= DISCOVERED;
- if (state[top] & EXPLORED) {
- postorder[cur_postorder++] = top;
+ cur = stack[stack_sz - 1];
+ succ = bpf_insn_successors(env, cur);
+ if (state[cur].next_succ == succ->cnt) {
+ postorder_nums[cur] = cur_postorder;
+ postorder[cur_postorder] = cur;
+ cur_postorder++;
stack_sz--;
continue;
}
- succ = bpf_insn_successors(env, top);
- for (s = 0; s < succ->cnt; ++s) {
- if (!state[succ->items[s]]) {
- stack[stack_sz++] = succ->items[s];
- state[succ->items[s]] |= DISCOVERED;
- }
+ s = succ->items[state[cur].next_succ];
+ if (!state[s].traversed) {
+ state[s].traversed = true;
+ state[s].next_succ = 0;
+ stack[stack_sz] = s;
+ stack_sz++;
+ continue;
}
- state[top] |= EXPLORED;
+ state[cur].next_succ++;
} while (stack_sz);
}
- env->subprog_info[i].postorder_start = cur_postorder;
+ env->subprog_info[subprog_idx].postorder_start = cur_postorder;
+ env->cfg.postorder_nums = postorder_nums;
env->cfg.insn_postorder = postorder;
env->cfg.cur_postorder = cur_postorder;
kvfree(stack);
diff --git a/kernel/bpf/cnum.c b/kernel/bpf/cnum.c
index 86142cb2aee5f..2bff2c7e0cdf5 100644
--- a/kernel/bpf/cnum.c
+++ b/kernel/bpf/cnum.c
@@ -2,6 +2,7 @@
/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
#include <linux/bits.h>
+#include <linux/bpf_verifier.h> /* for imod() */
#define T 32
#include "cnum_defs.h"
@@ -118,3 +119,38 @@ struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b)
}
return t;
}
+
+/* Intersect 'in' with the set of integers defined by equation 'base + step * k'. */
+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step)
+{
+ s64 smin = cnum64_smin(in);
+ s64 smax = cnum64_smax(in);
+ s64 lo, hi;
+ u16 d;
+
+ if (step <= 1 || cnum64_is_empty(in))
+ return in;
+ /*
+ * Round smin up to the next value congruent to 'base' modulo 'step',
+ * i.e. increase smin by d = (base - smin) mod step:
+ *
+ * |<---- d ---->|
+ * |-----------|=============|...
+ * base+step*k smin base+step*(k+1)
+ */
+ d = imod(base - imod(smin, step), step);
+ if ((u64)smax - (u64)smin < d)
+ return CNUM64_EMPTY;
+ lo = smin + d;
+ /*
+ * Round smax down to the previous value congruent to 'base' modulo 'step',
+ * i.e. decrease smax by d = (smax - base) mod step:
+ *
+ * |<--- d --->|
+ * ...|===========|-------------|
+ * base+step*k smax base+step*(k+1)
+ */
+ d = imod(imod(smax, step) - base, step);
+ hi = smax - d;
+ return cnum64_from_srange(lo, hi);
+}
diff --git a/kernel/bpf/cnum_defs.h b/kernel/bpf/cnum_defs.h
index 30685e43de049..05b17a8b4814f 100644
--- a/kernel/bpf/cnum_defs.h
+++ b/kernel/bpf/cnum_defs.h
@@ -198,6 +198,50 @@ static inline struct cnum_t FN(normalize)(struct cnum_t cnum)
return cnum;
}
+/*
+ * Return a smallest arc containing both 'a' and 'b'.
+ * Break equal-size ties by choosing the smaller base.
+ */
+struct cnum_t FN(union)(struct cnum_t a, struct cnum_t b)
+{
+ struct cnum_t b1, ab, ba;
+ ut end;
+
+ if (FN(is_empty)(a))
+ return b;
+ if (FN(is_empty)(b))
+ return a;
+
+ /*
+ * Rotate so that a1.base == 0 and a1.end == a.size.
+ * Normalize b1 to preserve the full-circle representation.
+ */
+ b1 = FN(normalize)((struct cnum_t){ b.base - a.base, b.size });
+ end = max(a.size, (ut)(b1.base + b1.size));
+
+ if (FN(urange_overflow)(b1)) {
+ /* a1 reaches b1's main arc: together they cover the circle. */
+ if (b1.base <= a.size)
+ return (struct cnum_t){ 0, UT_MAX };
+
+ /* Extend b1's tail through a1's end, then rotate back. */
+ return FN(normalize)((struct cnum_t){ b.base, end - b1.base });
+ }
+
+ /* ab, rotated back, covers both nonwrapping arcs. */
+ ab = (struct cnum_t){ a.base, end };
+ if (b1.base <= a.size)
+ return FN(normalize)(ab);
+
+ /* The arcs are disjoint; ba is the other possible covering arc. */
+ ba = (struct cnum_t){ b.base, a.size - b1.base };
+ if (ba.size < ab.size ||
+ (ba.size == ab.size && ba.base < ab.base))
+ ab = ba;
+
+ return FN(normalize)(ab);
+}
+
struct cnum_t FN(add)(struct cnum_t a, struct cnum_t b)
{
if (FN(is_empty)(a) || FN(is_empty)(b))
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 37cf130ebb57b..ecea117f2848f 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -614,6 +614,22 @@ static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
return 0;
}
+/* Clean up dynamically allocated fields of aux data for instructions [start, ...] */
+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
+{
+ struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
+ int end = start + len;
+ int i;
+
+ for (i = start; i < end; i++) {
+ if (aux_data[i].loop) {
+ kvfree(aux_data[i].loop->exits);
+ kvfree(aux_data[i].loop);
+ aux_data[i].loop = NULL;
+ }
+ }
+}
+
static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
@@ -626,6 +642,8 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
if (bpf_prog_is_offloaded(env->prog->aux))
bpf_prog_offload_remove_insns(env, off, cnt);
+ bpf_clear_insn_aux_data(env, off, cnt);
+
err = bpf_remove_insns(env->prog, off, cnt);
if (err)
return err;
diff --git a/kernel/bpf/heap.c b/kernel/bpf/heap.c
new file mode 100644
index 0000000000000..029f9217b8726
--- /dev/null
+++ b/kernel/bpf/heap.c
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf_verifier.h>
+
+/* Indexes for binary tree encoded as an array */
+static inline int left_child(int i) { return 2 * i + 1; }
+static inline int right_child(int i) { return 2 * i + 2; }
+static inline int parent(int i) { return (i - 1) / 2; }
+
+static inline int greater(struct bpf_min_heap *heap, int a, int b)
+{
+ return heap->compare(a, b, heap->arg) > 0;
+}
+
+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg)
+{
+ memset(heap, 0, sizeof(*heap));
+ heap->compare = compare;
+ heap->arg = arg;
+}
+
+void bpf_min_heap_free(struct bpf_min_heap *heap)
+{
+ kfree(heap->elements);
+ heap->elements = NULL;
+ heap->capacity = 0;
+ heap->count = 0;
+}
+
+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt)
+{
+ int new_capacity, i;
+ int *elements;
+ void *tmp;
+
+ if (heap->count == heap->capacity) {
+ new_capacity = heap->capacity ? heap->capacity * 2 : 16;
+ tmp = krealloc(heap->elements,
+ sizeof(*heap->elements) * new_capacity,
+ GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ heap->elements = tmp;
+ heap->capacity = new_capacity;
+ }
+
+ elements = heap->elements;
+ i = heap->count;
+ elements[i] = elt;
+ heap->count++;
+ while (i != 0 && greater(heap, elements[parent(i)], elements[i])) {
+ swap(elements[i], elements[parent(i)]);
+ i = parent(i);
+ }
+ return 0;
+}
+
+static inline void sink_root(struct bpf_min_heap *heap)
+{
+ int *elements = heap->elements;
+ int i = 0;
+
+ while ((left_child(i) < heap->count && greater(heap, elements[i], elements[left_child(i)])) ||
+ (right_child(i) < heap->count && greater(heap, elements[i], elements[right_child(i)]))) {
+ if (right_child(i) >= heap->count || greater(heap, elements[right_child(i)], elements[left_child(i)])) {
+ swap(elements[i], elements[left_child(i)]);
+ i = left_child(i);
+ } else {
+ swap(elements[i], elements[right_child(i)]);
+ i = right_child(i);
+ }
+ }
+}
+
+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt)
+{
+ if (heap->count == 0)
+ return false;
+
+ int *elements = heap->elements;
+ *elt = elements[0];
+ elements[0] = elements[heap->count - 1];
+ --heap->count;
+ sink_root(heap);
+ return true;
+}
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index cd9523f69298e..cba3a6c021b49 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -23,6 +23,7 @@ enum {
FM_MAY_READ, /* stack slots that may be read by this instruction */
FM_MUST_WRITE, /* stack slots written by this instruction */
FM_LIVE_BEFORE, /* stack slots that may be read by this insn and its successors */
+ FM_MAY_WRITE, /* stack slots that may be written by this instruction */
FM_MASK_CNT,
};
@@ -262,6 +263,12 @@ static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_
return mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi);
}
+static int mark_stack_may_write(struct func_instance *instance, u32 frame, u32 insn_idx,
+ s32 lo, s32 hi)
+{
+ return mark_stack_range(instance, frame, insn_idx, FM_MAY_WRITE, lo, hi);
+}
+
/*
* Mark every half-slot of @frame as possibly read by @insn_idx. This widens
* the masks to the program's stack budget: a full read recorded at a narrower
@@ -277,9 +284,16 @@ static int mark_stack_read_all(struct bpf_verifier_env *env, struct func_instanc
env->stack_limit / BPF_HALF_REG_SIZE - 1);
}
-/* Accumulate @src, a mask @src_words wide, into may_read of @frame at @insn_idx */
-static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,
- const unsigned long *src, u32 src_words)
+static int mark_stack_may_write_all(struct bpf_verifier_env *env, struct func_instance *instance,
+ u32 frame, u32 insn_idx)
+{
+ return mark_stack_may_write(instance, frame, insn_idx, 0,
+ env->stack_limit / BPF_HALF_REG_SIZE - 1);
+}
+
+/* Accumulate @src, a mask @src_words wide, into @kind mask of @frame at @insn_idx */
+static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_idx, u32 kind,
+ const unsigned long *src, u32 src_words)
{
u32 nbits = src_words * BITS_PER_LONG;
struct frame_masks *fm;
@@ -292,7 +306,7 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i
fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1));
if (!fm)
return -ENOMEM;
- dst = rel_mask(fm, relative_idx(instance, insn_idx), FM_MAY_READ);
+ dst = rel_mask(fm, relative_idx(instance, insn_idx), kind);
/* @src has no bits set past @last, hence none past @fm->words either */
src_words = min(src_words, fm->words);
for (w = 0; w < src_words; w++)
@@ -300,6 +314,12 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i
return 0;
}
+static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,
+ const unsigned long *src, u32 src_words)
+{
+ return mark_stack_mask(instance, frame, insn_idx, FM_MAY_READ, src, src_words);
+}
+
int bpf_jmp_offset(struct bpf_insn *insn)
{
u8 code = insn->code;
@@ -624,16 +644,41 @@ static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first,
return env->tmp_str_buf;
}
+/* Print mask @kind of the instruction at relative index @i for every frame, if any bit is set. */
+static bool print_mask(struct bpf_verifier_env *env, struct func_instance *instance, int i,
+ const char *name, u32 kind)
+{
+ struct frame_masks *fm;
+ bool printed = false;
+ unsigned long *mask;
+ int frame;
+ u64 pos;
+
+ pos = env->log.end_pos;
+ verbose(env, "%s", name);
+ for (frame = instance->depth; frame >= 0; --frame) {
+ fm = instance->frames[frame];
+ if (!fm)
+ continue;
+ mask = rel_mask(fm, i, kind);
+ if (bitmap_empty(mask, frame_mask_bits(fm)))
+ continue;
+ verbose(env, "%s", fmt_spis_mask(env, frame, !printed, mask, fm->words));
+ printed = true;
+ }
+ if (!printed)
+ bpf_vlog_reset(&env->log, pos);
+ return printed;
+}
+
static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance)
{
int start = env->subprog_info[instance->subprog].start;
struct bpf_insn *insns = env->prog->insnsi;
- struct frame_masks *fm;
- unsigned long *mask;
int len = instance->insn_cnt;
- int insn_idx, frame, i;
- bool has_use, has_def;
u64 pos, insn_pos;
+ int insn_idx, i;
+ bool printed;
if (!(env->log.level & BPF_LOG_LEVEL2))
return;
@@ -642,41 +687,17 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i
verbose(env, "%s:\n", fmt_instance(env, instance));
for (i = 0; i < len; i++) {
insn_idx = start + i;
- has_use = false;
- has_def = false;
pos = env->log.end_pos;
verbose(env, "%3d: ", insn_idx);
bpf_verbose_insn(env, &insns[insn_idx]);
insn_pos = env->log.end_pos;
verbose(env, "%*c;", bpf_vlog_alignment(insn_pos - pos), ' ');
- pos = env->log.end_pos;
- verbose(env, " use: ");
- for (frame = instance->depth; frame >= 0; --frame) {
- fm = instance->frames[frame];
- if (!fm)
- continue;
- mask = rel_mask(fm, i, FM_MAY_READ);
- if (bitmap_empty(mask, frame_mask_bits(fm)))
- continue;
- verbose(env, "%s", fmt_spis_mask(env, frame, !has_use, mask, fm->words));
- has_use = true;
- }
- if (!has_use)
- bpf_vlog_reset(&env->log, pos);
- pos = env->log.end_pos;
- verbose(env, " def: ");
- for (frame = instance->depth; frame >= 0; --frame) {
- fm = instance->frames[frame];
- if (!fm)
- continue;
- mask = rel_mask(fm, i, FM_MUST_WRITE);
- if (bitmap_empty(mask, frame_mask_bits(fm)))
- continue;
- verbose(env, "%s", fmt_spis_mask(env, frame, !has_def, mask, fm->words));
- has_def = true;
- }
- if (!has_def)
- bpf_vlog_reset(&env->log, has_use ? pos : insn_pos);
+ printed = false;
+ printed |= print_mask(env, instance, i, " use: ", FM_MAY_READ);
+ printed |= print_mask(env, instance, i, " def: ", FM_MUST_WRITE);
+ printed |= print_mask(env, instance, i, " may_def: ", FM_MAY_WRITE);
+ if (!printed)
+ bpf_vlog_reset(&env->log, insn_pos);
verbose(env, "\n");
if (bpf_is_ldimm64(&insns[insn_idx]))
i++;
@@ -697,6 +718,49 @@ static int cmp_instances(const void *pa, const void *pb)
return 0;
}
+/* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */
+static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)
+{
+ u32 slot;
+
+ for (slot = 0; slot < MAX_BPF_STACK_SLOTS && slot * 2 + 1 < nbits; slot++)
+ if (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask))
+ __set_bit(slot, slots);
+}
+
+/*
+ * Precompute, for each instruction, the OR of may_write and live_before masks
+ * over its top frame across all func_instances reaching it, stash them in the
+ * insn_aux_data.
+ */
+static void compute_may_write_masks(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_liveness *liveness = env->liveness;
+ struct func_instance *instance;
+ struct frame_masks *fm;
+ u32 nbits;
+ int bkt, i;
+
+ hash_for_each(liveness->func_instances, bkt, instance, hl_node) {
+ fm = instance->frames[instance->depth];
+ if (!fm)
+ continue;
+ nbits = frame_mask_bits(fm);
+ for (i = 0; i < instance->insn_cnt; i++) {
+ half_spis_to_slots(aux[instance->subprog_start + i].may_write_mask,
+ rel_mask(fm, i, FM_MAY_WRITE), nbits);
+ half_spis_to_slots(aux[instance->subprog_start + i].live_stack_before,
+ rel_mask(fm, i, FM_LIVE_BEFORE), nbits);
+ }
+ }
+}
+
+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
+{
+ return env->insn_aux_data[insn_idx].may_write_mask;
+}
+
/* print use/def slots for all instances ordered by callsite first, then by depth */
static int print_instances(struct bpf_verifier_env *env)
{
@@ -1444,10 +1508,12 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn,
* access_bytes == 0: no access
*
*/
-static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
- s64 access_bytes, u32 frame, u32 insn_idx)
+static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg,
+ u32 off_idx, s64 access_bytes, u32 frame, u32 insn_idx)
{
+ s64 fp_off = arg->off[off_idx];
s32 slot_hi, slot_lo;
+ int err;
if (fp_off >= 0)
/*
@@ -1459,7 +1525,8 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
if (access_bytes == S64_MIN) {
/* helper/kfunc read unknown amount of bytes from fp_off until fp+0 */
slot_hi = (-fp_off - 1) / STACK_SLOT_SZ;
- return mark_stack_read(instance, frame, insn_idx, 0, slot_hi);
+ err = mark_stack_read(instance, frame, insn_idx, 0, slot_hi);
+ return err ?: mark_stack_may_write(instance, frame, insn_idx, 0, slot_hi);
}
if (access_bytes > 0) {
/* Mark any touched slot as use */
@@ -1471,7 +1538,15 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
access_bytes = -access_bytes;
slot_hi = (-fp_off) / STACK_SLOT_SZ - 1;
slot_lo = max_t(s32, (-fp_off - access_bytes + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0);
- return mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);
+ if (arg->off_cnt == 1) {
+ err = mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);
+ if (err)
+ return err;
+ }
+ /* Mark partially covered slots as may_def */
+ slot_hi = (-fp_off - 1) / STACK_SLOT_SZ;
+ slot_lo = max_t(s32, (-fp_off - access_bytes) / STACK_SLOT_SZ, 0);
+ return mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi);
}
return 0;
}
@@ -1480,25 +1555,31 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
* 'arg' is FP-derived argument to helper/kfunc or load/store that
* reads (positive) or writes (negative) 'access_bytes' into 'use' or 'def'.
*/
-static int record_stack_access(struct bpf_verifier_env *env, struct func_instance *instance,
- const struct arg_track *arg,
- s64 access_bytes, u32 frame, u32 insn_idx)
+static int record_precise(struct bpf_verifier_env *env,
+ struct func_instance *instance,
+ const struct arg_track *arg,
+ s64 access_bytes, u32 frame, u32 insn_idx)
{
int i, err;
if (access_bytes == 0)
return 0;
if (arg->off_cnt == 0) {
- if (access_bytes > 0 || access_bytes == S64_MIN)
- return mark_stack_read_all(env, instance, frame, insn_idx);
+ if (access_bytes > 0 || access_bytes == S64_MIN) {
+ err = mark_stack_read_all(env, instance, frame, insn_idx);
+ if (err)
+ return err;
+ }
+ if (access_bytes < 0 || access_bytes == S64_MIN) {
+ err = mark_stack_may_write_all(env, instance, frame, insn_idx);
+ if (err)
+ return err;
+ }
return 0;
}
- if (access_bytes != S64_MIN && access_bytes < 0 && arg->off_cnt != 1)
- /* multi-offset write cannot set stack_def */
- return 0;
for (i = 0; i < arg->off_cnt; i++) {
- err = record_stack_access_off(instance, arg->off[i], access_bytes, frame, insn_idx);
+ err = record_stack_access_off(instance, arg, i, access_bytes, frame, insn_idx);
if (err)
return err;
}
@@ -1507,10 +1588,11 @@ static int record_stack_access(struct bpf_verifier_env *env, struct func_instanc
/*
* When a pointer is ARG_IMPRECISE, conservatively mark every frame in
- * the bitmask as fully used.
+ * the bitmask as fully used. Same as in record_stack_access(),
+ * negative 'access_bytes' means stack write.
*/
static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *instance,
- u32 mask, u32 insn_idx)
+ s64 access_bytes, u32 mask, u32 insn_idx)
{
int depth = instance->depth;
int f, err;
@@ -1519,25 +1601,45 @@ static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *
if (!(mask & 1))
continue;
if (f <= depth) {
- err = mark_stack_read_all(env, instance, f, insn_idx);
- if (err)
- return err;
+ if (access_bytes > 0 || access_bytes == S64_MIN) {
+ err = mark_stack_read_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
+ }
+ if (access_bytes < 0) {
+ err = mark_stack_may_write_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
+ }
}
}
return 0;
}
+static int record_stack_access(struct bpf_verifier_env *env,
+ struct func_instance *instance,
+ const struct arg_track *ptr,
+ s64 access_bytes, u32 insn_idx)
+{
+ if (ptr->frame >= 0 && ptr->frame <= instance->depth)
+ return record_precise(env, instance, ptr, access_bytes, ptr->frame, insn_idx);
+ if (ptr->frame == ARG_IMPRECISE)
+ return record_imprecise(env, instance, access_bytes, ptr->mask, insn_idx);
+ /* ARG_NONE: not derived from any frame pointer, skip */
+ return 0;
+}
+
/* Record load/store access for a given 'at' state of 'insn'. */
static int record_load_store_access(struct bpf_verifier_env *env,
struct func_instance *instance,
struct arg_track *at, int insn_idx)
{
struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
- int depth = instance->depth;
s32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code));
u8 class = BPF_CLASS(insn->code);
struct arg_track resolved, *ptr;
- int oi;
+ bool rmw = false; /* atomic read-modify-write: both read and write */
+ int oi, err;
/*
* Stack arg insns use dst_reg/src_reg=BPF_REG_PARAMS(11). Since at[]
@@ -1555,12 +1657,20 @@ static int record_load_store_access(struct bpf_verifier_env *env,
break;
case BPF_STX:
if (BPF_MODE(insn->code) == BPF_ATOMIC) {
- if (insn->imm == BPF_STORE_REL)
- sz = -sz;
- if (insn->imm == BPF_LOAD_ACQ)
+ switch (insn->imm) {
+ case BPF_LOAD_ACQ:
ptr = &at[insn->src_reg];
- else
+ break;
+ case BPF_STORE_REL:
+ ptr = &at[insn->dst_reg];
+ sz = -sz;
+ break;
+ default:
+ /* ADD/AND/OR/XOR(+FETCH), XCHG, CMPXCHG */
ptr = &at[insn->dst_reg];
+ rmw = true;
+ break;
+ }
} else {
ptr = &at[insn->dst_reg];
sz = -sz;
@@ -1587,12 +1697,10 @@ static int record_load_store_access(struct bpf_verifier_env *env,
ptr = &resolved;
}
- if (ptr->frame >= 0 && ptr->frame <= depth)
- return record_stack_access(env, instance, ptr, sz, ptr->frame, insn_idx);
- if (ptr->frame == ARG_IMPRECISE)
- return record_imprecise(env, instance, ptr->mask, insn_idx);
- /* ARG_NONE: not derived from any frame pointer, skip */
- return 0;
+ err = record_stack_access(env, instance, ptr, sz, insn_idx);
+ if (!err && rmw) /* also record the write half */
+ err = record_stack_access(env, instance, ptr, -sz, insn_idx);
+ return err;
}
static int record_arg_access(struct bpf_verifier_env *env,
@@ -1602,7 +1710,6 @@ static int record_arg_access(struct bpf_verifier_env *env,
int insn_idx)
{
int depth = instance->depth;
- int frame = at->frame;
int err = 0;
s64 bytes;
@@ -1618,17 +1725,16 @@ static int record_arg_access(struct bpf_verifier_env *env,
err = mark_stack_read_all(env, instance, f, insn_idx);
if (err)
return err;
+ err = mark_stack_may_write_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
}
return 0;
}
if (bytes == 0)
return 0;
- if (frame >= 0 && frame <= depth)
- err = record_stack_access(env, instance, at, bytes, frame, insn_idx);
- else if (frame == ARG_IMPRECISE)
- err = record_imprecise(env, instance, at->mask, insn_idx);
- return err;
+ return record_stack_access(env, instance, at, bytes, insn_idx);
}
/* Record stack access for a given 'at' state of helper/kfunc 'insn' */
@@ -1808,6 +1914,17 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env,
}
}
+static void record_stack_ptrs(struct bpf_verifier_env *env, int idx, struct arg_track *at_in)
+{
+ u16 r, mask = 0;
+
+ for (r = 0; r < MAX_BPF_REG; r++)
+ if (arg_is_fp(&at_in[r]))
+ mask |= BIT(r);
+
+ env->insn_aux_data[idx].stack_ptrs |= mask;
+}
+
/*
* Compute arg tracking dataflow for a single subprog.
* Runs forward fixed-point with arg_track_xfer(), then records
@@ -1957,6 +2074,8 @@ static int compute_subprog_args(struct bpf_verifier_env *env,
snap->slots = nslots;
memcpy(snap->at, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap->at));
}
+
+ record_stack_ptrs(env, idx, at_in[i]);
}
info->at_in = at_in;
@@ -1987,6 +2106,7 @@ static bool has_fp_args(struct arg_track *args)
/*
* Merge a freshly analyzed instance into the original.
* may_read: union (any pass might read the slot).
+ * may_write: union (slots written on ANY pass).
* must_write: intersection (only slots written on ALL passes are guaranteed).
* live_before is recomputed by a subsequent update_instance() on @dst.
*
@@ -2025,18 +2145,50 @@ static int merge_instances(struct func_instance *dst, struct func_instance *src)
for (i = 0; i < dst->insn_cnt; i++) {
unsigned long *dst_read = rel_mask(d, i, FM_MAY_READ);
unsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE);
+ unsigned long *dst_may_write = rel_mask(d, i, FM_MAY_WRITE);
unsigned long *src_read = rel_mask(s, i, FM_MAY_READ);
unsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE);
+ unsigned long *src_may_write = rel_mask(s, i, FM_MAY_WRITE);
for (w = 0; w < d->words; w++) {
dst_read[w] |= w < s->words ? src_read[w] : 0;
dst_write[w] &= w < s->words ? src_write[w] : 0;
+ dst_may_write[w] |= w < s->words ? src_may_write[w] : 0;
}
}
}
return 0;
}
+/*
+ * Fold a fully analyzed callee instance writes to upper frames as
+ * may_write marks at callsite in caller's frames.
+ */
+static int merge_may_write(struct func_instance *caller, struct func_instance *callee)
+{
+ DECLARE_BITMAP(acc, FRAME_HALF_SPIS);
+ u32 call_idx = callee->callsite;
+ struct frame_masks *fm;
+ u32 f, i, nbits;
+ int err;
+
+ for (f = 0; f < callee->depth; f++) {
+ fm = callee->frames[f];
+ if (!fm)
+ continue;
+ nbits = frame_mask_bits(fm);
+ bitmap_zero(acc, nbits);
+ for (i = 0; i < callee->insn_cnt; i++)
+ bitmap_or(acc, acc, rel_mask(fm, i, FM_MAY_WRITE), nbits);
+ if (bitmap_empty(acc, nbits))
+ continue;
+ err = mark_stack_mask(caller, f, call_idx, FM_MAY_WRITE, acc, fm->words);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
static struct func_instance *fresh_instance(struct func_instance *src)
{
struct func_instance *f;
@@ -2204,6 +2356,11 @@ static int analyze_subprog(struct bpf_verifier_env *env,
goto out_free;
}
}
+
+ /* Summarize callee's writes to ancestor frames onto the callsite */
+ err = merge_may_write(instance, callee_instance);
+ if (err)
+ goto out_free;
}
if (prev_instance) {
@@ -2266,6 +2423,8 @@ int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)
goto out;
}
+ compute_may_write_masks(env);
+
if (env->log.level & BPF_LOG_LEVEL2)
err = print_instances(env);
@@ -2472,8 +2631,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
struct bpf_insn *insns = env->prog->insnsi;
struct insn_live_regs *state;
int insn_cnt = env->prog->len;
- u64 pos, insn_pos;
- int err = 0, i, j, subprog, start, end;
+ int err = 0, i, subprog, start, end;
bool changed, ret_reg_pair;
/* Use the following algorithm:
@@ -2552,31 +2710,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32));
}
- if (env->log.level & BPF_LOG_LEVEL2) {
- verbose(env, "Live regs before insn:\n");
- for (i = 0; i < insn_cnt; ++i) {
- if (env->insn_aux_data[i].scc)
- verbose(env, "%3d ", env->insn_aux_data[i].scc);
- else
- verbose(env, " ");
- verbose(env, "%3d: ", i);
- for (j = BPF_REG_0; j < BPF_REG_10; ++j)
- if (insn_aux[i].live_regs_before & BIT(j))
- verbose(env, "%d", j);
- else
- verbose(env, ".");
- verbose(env, " ");
- pos = env->log.end_pos;
- bpf_verbose_insn(env, &insns[i]);
- insn_pos = env->log.end_pos;
- if (insn_aux[i].zext_dst)
- verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
- verbose(env, "\n");
- if (bpf_is_ldimm64(&insns[i]))
- i++;
- }
- }
-
out:
kvfree(state);
return err;
diff --git a/kernel/bpf/log.c b/kernel/bpf/log.c
index d850a7863d2ed..6a5564f626693 100644
--- a/kernel/bpf/log.c
+++ b/kernel/bpf/log.c
@@ -692,6 +692,8 @@ static void print_reg_state(struct bpf_verifier_env *env,
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose_a("var_off=%s", tn_buf);
+ if (reg->base != 0 || reg->step != 1)
+ verbose_a("step=%d+%d", reg->base, reg->step);
}
}
verbose(env, ")");
@@ -790,6 +792,11 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
verbose(env, " cb");
if (state->in_async_callback_fn)
verbose(env, " async_cb");
+ if (state->loop_stack_cnt) {
+ verbose(env, " loop_stack=");
+ for (i = 0; i < state->loop_stack_cnt; i++)
+ verbose(env, "%s%d", i ? "," : "", state->loop_stack[i].loop_id);
+ }
verbose(env, "\n");
if (!print_all)
mark_verifier_state_clean(env);
diff --git a/kernel/bpf/loops.c b/kernel/bpf/loops.c
new file mode 100644
index 0000000000000..5f52a88d52837
--- /dev/null
+++ b/kernel/bpf/loops.c
@@ -0,0 +1,576 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/slab.h>
+#include <linux/bpf_verifier.h>
+
+static bool is_cfg_jump(struct bpf_insn *insn)
+{
+ u8 class = BPF_CLASS(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+
+ switch (class) {
+ case BPF_JMP:
+ case BPF_JMP32:
+ return opcode != BPF_CALL;
+ default:
+ return false;
+ }
+}
+
+static struct bpf_iarray **compute_predecessors(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_iarray *succ, *preds, **result;
+ struct bpf_prog *prog = env->prog;
+ u32 *num_preds, i, s, sz, len = prog->len;
+ struct bpf_insn *insn;
+ void *tmp;
+
+ num_preds = kvcalloc(prog->len, sizeof(u32), GFP_KERNEL_ACCOUNT);
+ if (!num_preds)
+ return NULL;
+
+ /*
+ * 'result' layout:
+ * - array of pointers (struct bpf_iarray *)[len]
+ * - struct bpf_iarray one after another
+ */
+ sz = sizeof(struct bpf_iarray) * len;
+ sz += sizeof(struct bpf_iarray *) * len;
+ for (i = 0; i < len; i++) {
+ insn = env->prog->insnsi + i;
+ succ = bpf_insn_successors(env, i);
+ sz += sizeof(u32) * succ->cnt;
+ iarray_for_each(s, succ) {
+ num_preds[s]++;
+ }
+ if (bpf_is_ldimm64(insn))
+ i++;
+ }
+
+ result = kvzalloc(sz, GFP_KERNEL_ACCOUNT);
+ if (!result) {
+ kvfree(num_preds);
+ return NULL;
+ }
+
+ tmp = (void *)&result[len];
+ for (i = 0; i < len; i++) {
+ result[i] = tmp;
+ tmp += sizeof(struct bpf_iarray);
+ tmp += sizeof(u32) * num_preds[i];
+ }
+
+ for (i = 0; i < len; i++) {
+ insn = env->prog->insnsi + i;
+ succ = bpf_insn_successors(env, i);
+ iarray_for_each(s, succ) {
+ preds = result[s];
+ preds->items[preds->cnt++] = i;
+ }
+ if (succ->cnt > 1 ||
+ (succ->cnt == 1 && num_preds[succ->items[0]] > 1) ||
+ is_cfg_jump(insn))
+ aux[i].bb_end = true;
+ if (bpf_is_ldimm64(insn))
+ i++;
+ }
+
+ kvfree(num_preds);
+ return result;
+}
+
+static int idoms_intersect(struct bpf_verifier_env *env, int a, int b)
+{
+ int *postorder_nums = env->cfg.postorder_nums;
+ int *idoms = env->idoms;
+
+ while (a != b) {
+ while (postorder_nums[a] < postorder_nums[b]) {
+ a = idoms[a];
+ }
+ while (postorder_nums[b] < postorder_nums[a]) {
+ b = idoms[b];
+ }
+ }
+ return a;
+}
+
+/* See "A Simple, Fast Dominance Algorithm" by Cooper et al. for details. */
+static void compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarray **preds, int subprog_idx)
+{
+ struct bpf_subprog_info *subprog = &env->subprog_info[subprog_idx];
+ int start = subprog->start;
+ int po_first = subprog->postorder_start;
+ int po_last = (subprog + 1)->postorder_start - 1;
+ int *idoms = env->idoms;
+ int po_num, pred;
+ bool changed;
+
+ idoms[start] = 0;
+ changed = true;
+ do {
+ changed = false;
+ /* iterate in reverse postorder */
+ for (po_num = po_last; po_num >= po_first; po_num--) {
+ int idx = env->cfg.insn_postorder[po_num];
+ int new_idom = -1;
+
+ iarray_for_each(pred, preds[idx]) {
+ if (idoms[pred] == -1)
+ continue;
+ if (new_idom == -1)
+ new_idom = pred;
+ else
+ new_idom = idoms_intersect(env, pred, new_idom);
+ }
+ if (new_idom != -1 && idoms[idx] != new_idom) {
+ idoms[idx] = new_idom;
+ changed = true;
+ }
+ }
+ } while (changed);
+ idoms[start] = -1;
+}
+
+int bpf_compute_idoms(struct bpf_verifier_env *env)
+{
+ struct bpf_iarray **preds;
+ u32 len = env->prog->len;
+ int *idoms, i;
+
+ preds = compute_predecessors(env);
+ if (!preds)
+ return -ENOMEM;
+
+ idoms = kvcalloc(len, sizeof(*idoms), GFP_KERNEL_ACCOUNT);
+ if (!idoms) {
+ kvfree(preds);
+ return -ENOMEM;
+ }
+
+ env->idoms = idoms;
+ for (i = 0; i < len; i++)
+ idoms[i] = -1;
+
+ for (i = 0; i < env->subprog_cnt; i++)
+ compute_subprog_idoms(env, preds, i);
+
+ kvfree(preds);
+ return 0;
+}
+
+struct dfs_state {
+ u32 traversed:1;
+ u32 next_succ:31;
+};
+
+struct loops_dfs {
+ struct dfs_state *state;
+ int *dfs_pos;
+ int *stack;
+};
+
+static void mark_irreducible(struct bpf_verifier_env *env, int h)
+{
+ env->insn_aux_data[h].loop->irreducible = true;
+}
+
+static void mark_entry(struct bpf_verifier_env *env, int s)
+{
+ env->insn_aux_data[s].loop_entry = true;
+}
+
+static void add_backedge(struct bpf_verifier_env *env, int from, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop = aux[h].loop;
+ int cnt = loop->backedges_cnt;
+
+ if (cnt == MAX_BACKEDGES) {
+ loop->backedges_overflow = true;
+ return;
+ }
+ loop->backedges[cnt].from = from;
+ loop->backedges[cnt].latch = -1;
+ loop->backedges_cnt++;
+}
+
+static int add_exit(struct bpf_loop *loop, int from, int to)
+{
+ if (loop->exits_overflow)
+ return 0;
+ if (loop->exits_cnt == MAX_LOOP_EXITS) {
+ loop->exits_overflow = true;
+ return 0;
+ }
+ if (!loop->exits) {
+ loop->exits = kvcalloc(MAX_LOOP_EXITS, sizeof(*loop->exits), GFP_KERNEL_ACCOUNT);
+ if (!loop->exits)
+ return -ENOMEM;
+ }
+ loop->exits[loop->exits_cnt] = (struct bpf_loop_exit) {
+ .from = from,
+ .to = to,
+ };
+ loop->exits_cnt++;
+ return 0;
+}
+
+static int mark_as_header(struct bpf_verifier_env *env, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+
+ if (!aux[h].loop) {
+ mark_entry(env, h);
+ aux[h].loop = kvzalloc_obj(struct bpf_loop, GFP_KERNEL_ACCOUNT);
+ if (!aux[h].loop)
+ return -ENOMEM;
+ }
+ return 0;
+}
+
+static int assign_header(struct bpf_verifier_env *env, struct loops_dfs *dfs, int n, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int *dfs_pos = dfs->dfs_pos;
+ int err, nh;
+
+ err = mark_as_header(env, h);
+ if (err)
+ return err;
+
+ /* Don't encode self-loops, otherwise can't reflect loops nesting structure. */
+ if (n == h)
+ return 0;
+
+ /* Make sure that loop headers up the chain are sorted by dfs_pos. */
+ while (aux[n].loop_header != -1) {
+ nh = aux[n].loop_header;
+ if (nh == h)
+ return 0;
+ if (dfs_pos[nh] < dfs_pos[h]) {
+ aux[n].loop_header = h;
+ n = h;
+ h = nh;
+ } else {
+ n = nh;
+ }
+ }
+ aux[n].loop_header = h;
+ return 0;
+}
+
+static bool is_cond_jmp_insn(struct bpf_insn *insn)
+{
+ u8 class = BPF_CLASS(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+
+ if (class != BPF_JMP && class != BPF_JMP32)
+ return false;
+
+ switch (opcode) {
+ case BPF_JEQ:
+ case BPF_JGE:
+ case BPF_JGT:
+ case BPF_JLE:
+ case BPF_JLT:
+ case BPF_JNE:
+ case BPF_JSET:
+ case BPF_JSGE:
+ case BPF_JSGT:
+ case BPF_JSLE:
+ case BPF_JSLT:
+ return true;
+ default:
+ return false;
+ }
+}
+
+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+
+ return aux[idx].loop ? idx : aux[idx].loop_header;
+}
+
+static int find_dominating_condition(struct bpf_verifier_env *env, int n, int top)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ int common_dom, n_loop, t_loop, f_loop;
+ int *idoms = env->idoms;
+
+ n_loop = bpf_loop_at_index(env, n);
+ common_dom = idoms_intersect(env, n, top);
+ if (common_dom != top)
+ return -1;
+ while (n >= 0) {
+ if (is_cond_jmp_insn(&insns[n]) && bpf_loop_at_index(env, n) == n_loop) {
+ t_loop = bpf_loop_at_index(env, n + insns[n].off + 1);
+ f_loop = bpf_loop_at_index(env, n + 1);
+ if (f_loop != n_loop && !bpf_is_nested_loop(env, f_loop, n_loop))
+ return n;
+ if (t_loop != n_loop && !bpf_is_nested_loop(env, t_loop, n_loop))
+ return n;
+ }
+ if (n == top)
+ break;
+ n = idoms[n];
+ }
+ return -1;
+}
+
+/*
+ * As described in "A New Algorithm for Identifying Loops in Decompilation" by Wei et al,
+ * adapted to be non-recursive.
+ */
+static int compute_loops_in_subprog(struct bpf_verifier_env *env, struct loops_dfs *dfs,
+ int subprog_idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct dfs_state *state = dfs->state;
+ int start = env->subprog_info[subprog_idx].start;
+ int *dfs_pos = dfs->dfs_pos;
+ int *stack = dfs->stack;
+ int s, h, err, cur, stack_sz;
+ struct bpf_iarray *succ;
+ u32 i;
+
+ stack[0] = start;
+ state[start].traversed = true;
+ state[start].next_succ = 0;
+ dfs_pos[start] = 1;
+ stack_sz = 1;
+ i = 0;
+ do {
+ /*
+ * The algorithm should be very fast in practice,
+ * guard against pathological inputs, just in case.
+ */
+ if ((++i % 1024) == 0) {
+ if (signal_pending(current))
+ return -EAGAIN;
+ cond_resched();
+ }
+
+ cur = stack[stack_sz - 1];
+ succ = bpf_insn_successors(env, cur);
+ if (state[cur].next_succ == succ->cnt) {
+ dfs_pos[cur] = 0;
+ stack_sz--;
+ continue;
+ }
+ s = succ->items[state[cur].next_succ];
+ if (!state[s].traversed) {
+ /* Case A: start -> ... -> cur -> s [unexplored] */
+ state[s].traversed = true;
+ state[s].next_succ = 0;
+ stack[stack_sz] = s;
+ dfs_pos[s] = stack_sz + 1;
+ stack_sz++;
+ continue;
+ }
+ /* 's' is fully explored at this point */
+ if (dfs_pos[s]) {
+ /*
+ * start -> ... -> s -> cur --.
+ * ^ |
+ * '----------'
+ * Case B: 's' is in the current DFS path.
+ */
+ err = assign_header(env, dfs, cur, s);
+ if (err)
+ return err;
+ add_backedge(env, cur, s);
+ } else if (aux[s].loop_header == -1) {
+ /*
+ * start -> ... -> ... -> s -> ... -> end
+ * | ^
+ * '---> cur ---'
+ * Case C: 's' is explored, not in the current DFS path,
+ * and not a part of any loop.
+ */
+ } else if (dfs_pos[aux[s].loop_header]) {
+ /*
+ * .----------------------.
+ * v |
+ * start -> ... -> h -> ... -> ... -> s --'
+ * | ^
+ * '---> cur ---'
+ * Case D: 's' is explored, not in current DFS path,
+ * but its innermost loop header is.
+ */
+ err = assign_header(env, dfs, cur, aux[s].loop_header);
+ if (err)
+ return err;
+ } else {
+ /*
+ * case E: 's' is explored, not in current DFS path,
+ * its innermost loop header is not in current DFS path,
+ * hence 's' is another entry into the same loop.
+ */
+ h = aux[s].loop_header;
+ mark_irreducible(env, h);
+ mark_entry(env, s);
+ while (aux[h].loop_header != -1) {
+ h = aux[h].loop_header;
+ if (dfs_pos[h]) {
+ err = assign_header(env, dfs, cur, h);
+ if (err)
+ return err;
+ break;
+ }
+ mark_irreducible(env, h);
+ }
+ }
+ state[cur].next_succ++;
+ } while (stack_sz);
+
+ return 0;
+}
+
+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int idx;
+
+ for (idx = inner_header; idx >= 0; idx = aux[idx].loop_header)
+ if (aux[idx].loop_header == outer_header)
+ return true;
+
+ return false;
+}
+
+int bpf_compute_loops(struct bpf_verifier_env *env)
+{
+ int i, j, s, t, iloop, sloop, err = 0, len = env->prog->len;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct bpf_backedge *backedge;
+ struct loops_dfs dfs = {};
+ struct bpf_iarray *succ;
+ struct bpf_loop *loop;
+
+ dfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+ dfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);
+ dfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+ if (!dfs.dfs_pos || !dfs.state || !dfs.stack) {
+ err = -ENOMEM;
+ goto out;
+ }
+ for (i = 0; i < len; i++)
+ aux[i].loop_header = -1;
+ for (i = 0; i < env->subprog_cnt; i++) {
+ err = compute_loops_in_subprog(env, &dfs, i);
+ if (err)
+ goto out;
+ }
+ /* find latches */
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ backedge = &loop->backedges[j];
+ backedge->latch = find_dominating_condition(env, backedge->from, i);
+ }
+ }
+ /* find exits */
+ for (i = 0; i < len; i++) {
+ iloop = aux[i].loop ? i : aux[i].loop_header;
+ if (iloop < 0)
+ continue;
+ succ = bpf_insn_successors(env, i);
+ iarray_for_each(s, succ) {
+ /*
+ * Nothing left to record once the innermost loop of 'i'
+ * overflowed: the walk below would stop at it right away.
+ */
+ if (aux[iloop].loop->exits_overflow)
+ break;
+ sloop = aux[s].loop ? s : aux[s].loop_header;
+ if (iloop == sloop)
+ continue;
+ if (bpf_is_nested_loop(env, sloop, iloop))
+ continue;
+ /*
+ * At this point 'sloop' is either -1, an outer loop,
+ * or a loop in another branch of the loop hierarchy.
+ */
+ for (t = iloop; t >= 0 && t != sloop; t = aux[t].loop_header) {
+ /*
+ * Account for the following configuration:
+ *
+ * tloop {
+ * iloop {
+ * ... i: goto s;
+ * }
+ * sloop {
+ * s:
+ * ...
+ * }
+ * }
+ */
+ if (bpf_is_nested_loop(env, sloop, t))
+ break;
+ /*
+ * Record edges i -> s as exits from tloop when:
+ *
+ * sloop {
+ * tloop {
+ * iloop {
+ * ... i: goto s;
+ * }
+ * }
+ * s: ...
+ * }
+ */
+ /* Enclosing loops inherit the overflow, see below */
+ if (aux[t].loop->exits_overflow)
+ break;
+ err = add_exit(aux[t].loop, i, s);
+ if (err)
+ goto out;
+ }
+ }
+ if (bpf_is_ldimm64(env->prog->insnsi + i))
+ i++;
+ }
+ /* A nested loop with a truncated exit list can't be abstracted by SCEV */
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop || !loop->exits_overflow)
+ continue;
+ for (t = aux[i].loop_header; t >= 0; t = aux[t].loop_header)
+ aux[t].loop->exits_overflow = true;
+ }
+
+ if (env->log.level & BPF_LOG_LEVEL2) {
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ bpf_log(log, "loop at %d", i);
+ if (aux[i].loop_header >= 0)
+ bpf_log(log, ", nested in %d", aux[i].loop_header);
+ if (loop->irreducible)
+ bpf_log(log, ", irreducible");
+ if (loop->exits_overflow)
+ bpf_log(log, ", too many exits");
+ bpf_log(log, "\n");
+ for (j = 0; j < loop->backedges_cnt; j++)
+ bpf_log(log, " backedge from %d, latch at %d\n",
+ loop->backedges[j].from, loop->backedges[j].latch);
+ for (j = 0; j < loop->exits_cnt; j++)
+ bpf_log(log, " exit from %d to %d\n",
+ loop->exits[j].from, loop->exits[j].to);
+ }
+ }
+
+out:
+ kvfree(dfs.dfs_pos);
+ kvfree(dfs.stack);
+ kvfree(dfs.state);
+ return err;
+}
diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c
new file mode 100644
index 0000000000000..1fa6b25a4f291
--- /dev/null
+++ b/kernel/bpf/scev.c
@@ -0,0 +1,2246 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
+
+#include "linux/cnum.h"
+#include <linux/bpf_verifier.h>
+#include <linux/jhash.h>
+#include <linux/bug.h>
+#include <linux/tnum.h>
+#include <linux/overflow.h>
+
+#define REGS_NUM BPF_SCEV_REGS_NUM
+#define UNKNOWN_EXPR_ID 0
+#define OPAQUE_EXPR_ID 1
+
+/*
+ * BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.
+ * For scalar evolution purpose we want to reuse most of the opcode definitions,
+ * but also add a few custom operations (REG and IMM).
+ * Use the enum below to uniformly represent all operations relevant for SCEV.
+ */
+enum expr_op {
+ /* leave range 0..255 for standard bpf opcodes */
+ UNKNOWN = 256, /* start custom opcodes from the second byte */
+ REG,
+ IMM,
+ SDIV, SMOD,
+ SEXT8, SEXT16, SEXT32,
+ ZEXT8, ZEXT16, ZEXT32,
+ BSWAP16, BSWAP32, BSWAP64,
+ /* during the loop body execution the value can be either of param[0] or param[1] */
+ ANY,
+ /* some value that verifier is not going to track precisely */
+ OPAQUE,
+ /* '*(u8/16/32 *)(r10 + X) = Y' writes define slot contents only partially */
+ SPILL8, SPILL16, SPILL32,
+ /*
+ * SCEV expression corresponding to linear equation 'param[0] + param[1] * k',
+ * where k is a loop iteration number. Loop here refers to innermost loop
+ * containing instruction associated with this expression, as returned by
+ * bpf_loop_at_index().
+ */
+ LINEAR_SCEV,
+};
+
+struct expr {
+ u32 op;
+ union {
+ u32 params[2];
+ s64 imm;
+ };
+};
+
+struct expr_bucket {
+ u32 cnt;
+ u32 cap;
+ u32 ids[];
+};
+
+struct env {
+ bool empty;
+ u32 reg2expr[REGS_NUM];
+ u32 reg2scev[REGS_NUM];
+};
+
+struct insn_envs {
+ u32 cnt;
+ struct {
+ int loop_header;
+ struct env *env;
+ } entries[];
+};
+
+#define NUM_BUCKETS 256
+#define EXPR_STACK_DEPTH 8
+
+struct expr_stack_elt {
+ u32 id:28;
+ u32 pre:1;
+ u32 next_param:2;
+};
+
+struct scev {
+ /*
+ * Expressions are identified by id, exprs_ht ensures that
+ * each expression exists as a unique instance.
+ * This allows for fast equivalence check: id1 === id2.
+ */
+ struct expr_bucket *exprs_ht[NUM_BUCKETS]; // Don't want to add struct hlist_node to expr
+ struct bpf_min_heap worklist;
+ struct insn_envs **envs;
+ struct expr *exprs;
+ /*
+ * Loops are analyzed one by one, this array keeps track if a particular
+ * instruction was visited on a current pass.
+ */
+ u32 *discovered;
+ int exprs_cnt;
+ int exprs_cap;
+ int envs_cnt;
+ int stack_sz;
+ struct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];
+ u32 ids_buf[EXPR_STACK_DEPTH];
+};
+
+static u32 expr_hash(struct expr *e)
+{
+ return jhash_3words(e->op, e->params[0], e->params[1], 0);
+}
+
+static int expr_eq(struct expr *a, struct expr *b)
+{
+ return a->op == b->op && a->imm == b->imm;
+}
+
+static int add_expr(struct scev *scev, struct expr e)
+{
+ struct expr_bucket *bucket;
+ u32 i, id, hash, new_cap;
+ void *tmp;
+
+ hash = expr_hash(&e) % NUM_BUCKETS;
+ bucket = scev->exprs_ht[hash];
+
+ if (bucket) {
+ for (i = 0; i < bucket->cnt; i++) {
+ id = bucket->ids[i];
+ if (expr_eq(&e, &scev->exprs[id]))
+ return id;
+ }
+ }
+
+ if (!bucket || bucket->cap == bucket->cnt) {
+ new_cap = bucket ? bucket->cap * 2 : 32;
+ bucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+ if (!bucket)
+ return -ENOMEM;
+ scev->exprs_ht[hash] = bucket;
+ bucket->cap = new_cap;
+ }
+
+ if (scev->exprs_cnt == scev->exprs_cap) {
+ new_cap = scev->exprs_cap + 256;
+ tmp = kvrealloc(scev->exprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs = tmp;
+ scev->exprs_cap = new_cap;
+ }
+
+ id = scev->exprs_cnt++;
+ scev->exprs[id] = e;
+ bucket->ids[bucket->cnt++] = id;
+ return id;
+}
+
+static int expr2(struct scev *scev, u32 op, int a, int b)
+{
+ if (a < 0)
+ return a;
+ if (b < 0)
+ return b;
+ return add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+}
+
+static int expr1(struct scev *scev, u32 op, int a)
+{
+ if (a < 0)
+ return a;
+ return expr2(scev, op, a, 0);
+}
+
+static int expr0(struct scev *scev, u32 op)
+{
+ return expr2(scev, op, 0, 0);
+}
+
+static bool is_expr1(struct expr *expr, u32 op, int a)
+{
+ return expr->op == op && expr->params[0] == a;
+}
+
+static int imm_expr(struct scev *scev, s64 value)
+{
+ return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
+}
+
+static bool same_exprs(struct scev *scev, int id_a, int id_b)
+{
+ return id_a == id_b;
+}
+
+static bool is_imm(struct scev *scev, int id, s64 *imm)
+{
+ if (scev->exprs[id].op != IMM)
+ return false;
+ *imm = scev->exprs[id].imm;
+ return true;
+}
+
+static bool is_op(struct scev *scev, int id, u32 op)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ return true;
+}
+
+static bool is_unop(struct scev *scev, enum expr_op op, int id, u32 *p0)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ *p0 = scev->exprs[id].params[0];
+ return true;
+}
+
+static bool is_binop(struct scev *scev, enum expr_op op, int id, u32 *p0, u32 *p1)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ *p0 = scev->exprs[id].params[0];
+ *p1 = scev->exprs[id].params[1];
+ return true;
+}
+
+static bool is_reg(struct scev *scev, int id, u32 *reg)
+{
+ return is_unop(scev, REG, id, reg);
+}
+
+static bool is_add(struct scev *scev, int id, u32 *left, u32 *right)
+{
+ return is_binop(scev, BPF_ADD, id, left, right);
+}
+
+static bool is_zext32(struct scev *scev, int id, u32 *left)
+{
+ return is_unop(scev, ZEXT32, id, left);
+}
+
+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
+{
+ return is_binop(scev, ANY, id, left, right);
+}
+
+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+{
+ return is_binop(scev, LINEAR_SCEV, id, base, slope);
+}
+
+static bool is_opaque(struct scev *scev, int id)
+{
+ return is_op(scev, id, OPAQUE);
+}
+
+static void log_reg(struct bpf_verifier_env *env, u32 reg)
+{
+ if (reg < MAX_BPF_REG)
+ bpf_log(&env->log, "r%d", reg);
+ else
+ bpf_log(&env->log, "*fp%d", (MAX_BPF_REG - reg - 1) * 8);
+}
+
+static const char *op_str(u32 op)
+{
+ switch (op) {
+ case BPF_ADD: return "+";
+ case BPF_SUB: return "-";
+ case BPF_MUL: return "*";
+ case BPF_DIV: return "/";
+ case SDIV: return "s/";
+ case BPF_OR: return "|";
+ case BPF_AND: return "&";
+ case BPF_LSH: return "<<";
+ case BPF_RSH: return ">>";
+ case BPF_NEG: return "-";
+ case BPF_MOD: return "%";
+ case SMOD: return "s%";
+ case BPF_XOR: return "^";
+ case BPF_ARSH: return "s>>";
+ case SEXT8: return "sext8";
+ case SEXT16: return "sext16";
+ case SEXT32: return "sext32";
+ case ZEXT8: return "zext8";
+ case ZEXT16: return "zext16";
+ case ZEXT32: return "zext32";
+ case BSWAP16: return "bswap16";
+ case BSWAP32: return "bswap32";
+ case BSWAP64: return "bswap64";
+ case SPILL8: return "spill8";
+ case SPILL16: return "spill16";
+ case SPILL32: return "spill32";
+ case ANY: return "any";
+ case LINEAR_SCEV: return "linear";
+ }
+ return NULL;
+}
+
+static u32 op_params_num(u32 op)
+{
+ switch (op) {
+ case BPF_ADD:
+ case BPF_SUB:
+ case BPF_MUL:
+ case BPF_DIV:
+ case BPF_MOD:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_AND:
+ case BPF_LSH:
+ case BPF_RSH:
+ case BPF_ARSH:
+ case SDIV:
+ case SMOD:
+ case ANY:
+ case LINEAR_SCEV:
+ return 2;
+ case BPF_NEG:
+ case SEXT8:
+ case SEXT16:
+ case SEXT32:
+ case ZEXT8:
+ case ZEXT16:
+ case ZEXT32:
+ case BSWAP16:
+ case BSWAP32:
+ case BSWAP64:
+ case SPILL8:
+ case SPILL16:
+ case SPILL32:
+ return 1;
+ case REG:
+ case IMM:
+ case OPAQUE:
+ return 0;
+ default:
+ return 0;
+ }
+}
+
+static bool expr_stack_push(struct scev *scev, u32 id)
+{
+ if (scev->stack_sz >= EXPR_STACK_DEPTH)
+ return false;
+ scev->expr_stack[scev->stack_sz].id = id;
+ scev->expr_stack[scev->stack_sz].pre = true;
+ scev->expr_stack[scev->stack_sz].next_param = 0;
+ scev->stack_sz++;
+ return true;
+}
+
+enum {
+ PRE = BIT(1), POST = BIT(2), DEPTH_LIMIT = BIT(3)
+};
+
+static bool expr_next(struct scev *scev, u32 *id, u32 *order)
+{
+ struct expr_stack_elt *elt;
+ struct expr *expr;
+ u32 num_params;
+
+ if (scev->stack_sz == 0)
+ return false;
+
+ elt = &scev->expr_stack[scev->stack_sz - 1];
+ *id = elt->id;
+ *order = 0;
+ expr = &scev->exprs[elt->id];
+ num_params = op_params_num(expr->op);
+ if (elt->pre) {
+ elt->pre = false;
+ *order = PRE;
+ return true;
+ }
+ if (elt->next_param == num_params) {
+ *order = POST;
+ scev->stack_sz--;
+ return true;
+ }
+ if (scev->stack_sz == EXPR_STACK_DEPTH) {
+ *order = POST | DEPTH_LIMIT;
+ scev->stack_sz--;
+ return true;
+ }
+ expr_stack_push(scev, expr->params[elt->next_param]);
+ elt->next_param++;
+ return expr_next(scev, id, order);
+}
+
+static void log_expr(struct bpf_verifier_env *env, u32 id)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct expr *expr;
+ const char *str;
+ u32 order;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if ((order & PRE) && scev->stack_sz > 1)
+ bpf_log(log, " ");
+ expr = &scev->exprs[id];
+ switch (expr->op) {
+ case UNKNOWN:
+ if (order & PRE)
+ bpf_log(log, "?");
+ break;
+ case OPAQUE:
+ if (order & PRE)
+ bpf_log(log, "_");
+ break;
+ case REG:
+ if (order & PRE)
+ log_reg(env, expr->params[0]);
+ break;
+ case IMM:
+ if (order & PRE)
+ bpf_log(log, "%lld", expr->imm);
+ break;
+ default:
+ if (order & PRE) {
+ str = op_str(expr->op);
+ bpf_log(log, "(");
+ if (str)
+ bpf_log(log, "%s", str);
+ else
+ bpf_log(log, "bad-expr-op %x", expr->op);
+ }
+ if (order & DEPTH_LIMIT)
+ bpf_log(log, "...");
+ if (order & POST)
+ bpf_log(log, ")");
+ }
+ }
+}
+
+enum print_env_flags {
+ PRINT_SCEV = BIT(1)
+};
+
+static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ u16 live_regs = aux[insn_idx].live_regs_before;
+
+ return reg < MAX_BPF_REG
+ ? (BIT(reg) & live_regs)
+ : test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);
+}
+
+static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx, u32 flags)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ bool printed_some = false;
+ bool print_scev = flags & PRINT_SCEV;
+ bool is_self_scev;
+ bool is_self_reg;
+ int i, r;
+
+ if (e->empty) {
+ bpf_log(log, " <empty>\n");
+ return;
+ }
+
+ for (i = 0; i < REGS_NUM; i++) {
+ if (!reg_alive_at(env, i, insn_idx))
+ continue;
+ is_self_reg = is_reg(scev, e->reg2expr[i], &r) && i == r;
+ is_self_scev = is_reg(scev, e->reg2scev[i], &r) && i == r;
+ if (is_self_reg && (!print_scev || is_self_scev))
+ continue;
+ printed_some = true;
+ bpf_log(log, " ");
+ log_reg(env, i);
+ bpf_log(log, "=");
+ log_expr(env, e->reg2expr[i]);
+ if (print_scev && e->reg2expr[i] != UNKNOWN_EXPR_ID) {
+ bpf_log(log, " / ");
+ log_expr(env, e->reg2scev[i]);
+ }
+ bpf_log(log, "\n");
+ }
+ if (!printed_some)
+ bpf_log(log, " <all regs unchanged>\n");
+}
+static struct env *find_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 i;
+
+ if (!envs)
+ return NULL;
+ for (i = 0; i < envs->cnt; i++)
+ if (envs->entries[i].loop_header == loop_header)
+ return envs->entries[i].env;
+ return NULL;
+}
+
+static struct env *find_header_env(struct scev *scev, int header)
+{
+ return find_loop_env(scev, header, header);
+}
+
+static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 cnt = envs ? envs->cnt : 0;
+ struct insn_envs *tmp;
+ struct env *e;
+
+ e = find_loop_env(scev, loop_header, insn_idx);
+ if (e)
+ return e;
+
+ e = kzalloc(sizeof(*e), GFP_KERNEL_ACCOUNT);
+ if (!e)
+ return NULL;
+
+ tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);
+ if (!tmp) {
+ kfree(e);
+ return NULL;
+ }
+
+ e->empty = true;
+ tmp->entries[cnt].loop_header = loop_header;
+ tmp->entries[cnt].env = e;
+ tmp->cnt = cnt + 1;
+ scev->envs[insn_idx] = tmp;
+ return e;
+}
+
+static void setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)
+{
+ struct scev *scev = env->scev;
+ int i;
+
+ for (i = 0; i < REGS_NUM; i++)
+ e->reg2expr[i] = expr1(scev, REG, i);
+}
+
+static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
+{
+ if (id < 0)
+ return id;
+ e->reg2expr[reg] = id;
+ return 0;
+}
+
+static void forget_call_regs(struct env *e)
+{
+ int i;
+
+ for (i = BPF_REG_0; i <= BPF_REG_5; i++)
+ e->reg2expr[i] = UNKNOWN_EXPR_ID;
+}
+
+static u32 spill_spi(struct bpf_insn *insn)
+{
+ return -insn->off / BPF_REG_SIZE - 1;
+}
+
+static u32 off_to_reg(struct bpf_insn *insn)
+{
+ return spill_spi(insn) + MAX_BPF_REG;
+}
+
+static bool is_spill_off(int off)
+{
+ return off % BPF_REG_SIZE == 0 &&
+ off <= -BPF_REG_SIZE &&
+ off >= -MAX_BPF_STACK_JIT;
+}
+
+static void mark_opaque(struct env *e, int off, int size)
+{
+ int b, spi;
+
+ for (b = off; b < off + size; b++) {
+ if (b >= 0 || b < -MAX_BPF_STACK_JIT)
+ continue;
+ spi = (-b - 1) / BPF_REG_SIZE;
+ e->reg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;
+ }
+}
+
+static int mk_spill(struct scev *scev, u8 size, int id)
+{
+ switch (size) {
+ case BPF_B: return expr1(scev, SPILL8, id);
+ case BPF_H: return expr1(scev, SPILL16, id);
+ case BPF_W: return expr1(scev, SPILL32, id);
+ case BPF_DW: return id;
+ }
+ return UNKNOWN_EXPR_ID;
+}
+
+static int mk_fill(struct scev *scev, int id, u8 code)
+{
+ bool sx = BPF_MODE(code) == BPF_MEMSX;
+
+ switch (BPF_SIZE(code)) {
+ case BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);
+ case BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);
+ case BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);
+ case BPF_DW: return sx ? UNKNOWN_EXPR_ID : id; /* DW sign-extended load is invalid */
+ }
+ return UNKNOWN_EXPR_ID;
+}
+
+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)
+{
+ u8 size = BPF_SIZE(insn->code);
+
+ if (insn->dst_reg != BPF_REG_FP)
+ return 0;
+ if (is_spill_off(insn->off))
+ return replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));
+ mark_opaque(e, insn->off, bpf_size_to_bytes(size));
+ return 0;
+}
+
+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)
+{
+ int id;
+
+ if (insn->src_reg == BPF_REG_FP && is_spill_off(insn->off))
+ id = mk_fill(scev, e->reg2expr[off_to_reg(insn)], insn->code);
+ else
+ id = OPAQUE_EXPR_ID;
+ return replace_reg(scev, e, insn->dst_reg, id);
+}
+
+static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ const bool little_endian = htons(0x3412) == 0x1234;
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct scev *scev = env->scev;
+ u32 *reg2expr = e->reg2expr;
+ u8 class = BPF_CLASS(insn->code);
+ u8 x_or_k = BPF_SRC(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+ u8 mode = BPF_MODE(insn->code);
+ u32 dst = insn->dst_reg;
+ u32 src = insn->src_reg;
+ u32 op, sext;
+ int i, id;
+ s64 imm;
+
+ switch (class) {
+ case BPF_ALU:
+ case BPF_ALU64:
+ switch (opcode) {
+ case BPF_MOV:
+ switch (insn->off) {
+ case 0: sext = 0; break;
+ case 8: sext = SEXT8; break;
+ case 16: sext = SEXT16; break;
+ case 32: sext = SEXT32; break;
+ default:
+ goto mark_dst_unknown;
+ }
+
+ if (x_or_k == BPF_X && insn->imm == 0)
+ id = reg2expr[src];
+ else if (x_or_k == BPF_K && src == 0 && insn->off == 0)
+ id = imm_expr(scev, insn->imm);
+ else
+ goto mark_dst_unknown;
+
+ if (sext)
+ id = expr1(scev, sext, id);
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_ADD:
+ case BPF_SUB:
+ case BPF_MUL:
+ case BPF_DIV:
+ case BPF_MOD:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_AND:
+ case BPF_LSH:
+ case BPF_RSH:
+ case BPF_ARSH:
+ if (opcode == BPF_DIV && insn->off == 1)
+ op = SDIV;
+ else if (opcode == BPF_MOD && insn->off == 1)
+ op = SMOD;
+ else if (insn->off == 0)
+ op = opcode;
+ else
+ goto mark_dst_unknown;
+
+ if (x_or_k == BPF_X && insn->imm == 0)
+ id = reg2expr[src];
+ else if (x_or_k == BPF_K && src == 0)
+ id = imm_expr(scev, insn->imm);
+ else
+ goto mark_dst_unknown;
+
+ id = expr2(scev, op, reg2expr[dst], id);
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_NEG:
+ if (src == 0 && insn->off == 0 && insn->imm == 0)
+ id = expr1(scev, BPF_NEG, reg2expr[dst]);
+ else
+ goto mark_dst_unknown;
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_END:
+ switch (insn->imm) {
+ case 16: op = BSWAP16; break;
+ case 32: op = BSWAP32; break;
+ case 64: op = BSWAP64; break;
+ default:
+ goto mark_dst_unknown;
+ }
+
+ if (class == BPF_ALU && x_or_k == BPF_TO_LE && insn->off == 0 && little_endian)
+ op = 0; /* little-endian to little-endian is noop */
+ else if (class == BPF_ALU && x_or_k == BPF_TO_BE && insn->off == 0 && !little_endian)
+ op = 0; /* big-endian to big-endian is noop */
+ else if (class == BPF_ALU64 && x_or_k == 0 && insn->off == 0)
+ /* always swap */;
+ else
+ goto mark_dst_unknown;
+
+ id = reg2expr[dst];
+ if (op)
+ id = expr1(scev, op, reg2expr[dst]);
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+ default:
+ goto mark_dst_unknown;
+ }
+ break;
+ case BPF_LDX:
+ switch (mode) {
+ case BPF_MEM:
+ case BPF_MEMSX:
+ return maybe_load_fp(scev, e, insn);
+ default:
+ goto mark_dst_unknown;
+ }
+ case BPF_STX:
+ switch (mode) {
+ case BPF_MEM:
+ return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ case BPF_ATOMIC:
+ if (insn->imm == BPF_LOAD_ACQ)
+ return maybe_load_fp(scev, e, insn);
+ if (insn->imm == BPF_STORE_REL) {
+ return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ }
+ /*
+ * verifier does not track other atomic ops precisely,
+ * hence mark the results as opaque.
+ */
+ if (insn->dst_reg == BPF_REG_FP)
+ mark_opaque(e, insn->off, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (insn->imm == BPF_CMPXCHG)
+ return replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);
+ if (insn->imm & BPF_FETCH)
+ return replace_reg(scev, e, src, OPAQUE_EXPR_ID);
+ break;
+ }
+ break;
+ case BPF_ST:
+ if (insn->dst_reg == BPF_REG_FP) {
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ return maybe_store_fp(scev, e, insn, id);
+ }
+ break;
+ case BPF_JMP:
+ case BPF_JMP32:
+ if (opcode == BPF_CALL)
+ forget_call_regs(e);
+ /* for non-CALL there are no changes in register states */
+ break;
+ case BPF_LD:
+ switch (mode) {
+ case BPF_IMM:
+ /* rX = imm ll */
+ if (BPF_SIZE(insn->code) == BPF_DW && insn->src_reg == 0) {
+ imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
+ return replace_reg(scev, e, dst, imm_expr(scev, imm));
+ }
+ /* map, map value, BTF id, function */
+ if (BPF_SIZE(insn->code) == BPF_DW)
+ return replace_reg(scev, e, dst, OPAQUE_EXPR_ID);
+ goto mark_dst_unknown;
+ case BPF_ABS:
+ case BPF_IND:
+ forget_call_regs(e);
+ break;
+ default:
+ goto mark_dst_unknown;
+ }
+ break;
+ default:
+ /* unknown instruction, nuke state */
+ for (i = 0; i < REGS_NUM; i++)
+ reg2expr[i] = UNKNOWN_EXPR_ID;
+ break;
+ }
+ return 0;
+
+mark_dst_unknown:
+ reg2expr[dst] = UNKNOWN_EXPR_ID;
+ return 0;
+}
+
+/*
+ * Construct minimal 'ANY' expression by traversing 'a' and 'b'
+ * and accumulating non-duplicated non-ANY entries.
+ */
+static int mk_any(struct scev *scev, u32 a, u32 b)
+{
+ struct expr_stack_elt *elt;
+ struct expr *expr;
+ u32 i, j, ids_buf_sz;
+ u32 roots[2] = {a, b};
+ int id;
+
+ ids_buf_sz = 0;
+ for (i = 0; i < ARRAY_SIZE(roots); i++) {
+ scev->stack_sz = 0;
+ expr_stack_push(scev, roots[i]);
+ while (scev->stack_sz) {
+ elt = &scev->expr_stack[--scev->stack_sz];
+ id = elt->id;
+ expr = &scev->exprs[elt->id];
+ if (expr->op == ANY) {
+ if (!expr_stack_push(scev, expr->params[0]) ||
+ !expr_stack_push(scev, expr->params[1]))
+ return UNKNOWN_EXPR_ID;
+ } else {
+ for (j = 0; j < ids_buf_sz; j++) {
+ if (same_exprs(scev, scev->ids_buf[j], id))
+ goto next;
+ }
+ if (ids_buf_sz == ARRAY_SIZE(scev->ids_buf))
+ return UNKNOWN_EXPR_ID;
+ scev->ids_buf[ids_buf_sz++] = id;
+ }
+next:;
+ }
+ }
+ if (WARN_ON(ids_buf_sz == 0))
+ return -EFAULT;
+ id = scev->ids_buf[0];
+ for (i = 1; i < ids_buf_sz; i++) {
+ id = expr2(scev, ANY, id, scev->ids_buf[i]);
+ if (id < 0)
+ return id;
+ }
+ return id;
+}
+
+static int join(struct scev *scev, struct env *acc, struct env *cur)
+{
+ int i, id;
+
+ if (acc->empty) {
+ memcpy(acc, cur, sizeof(*acc));
+ acc->empty = false;
+ return 0;
+ }
+
+ for (i = 0; i < REGS_NUM; i++) {
+ if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[i])) {
+ id = mk_any(scev, acc->reg2expr[i], cur->reg2expr[i]);
+ if (id < 0)
+ return id;
+ acc->reg2expr[i] = id;
+ }
+ }
+ return 0;
+}
+
+/* Mark any register modified in 'header_env' as unknown in 'acc'. */
+static void forget_non_invariants(struct scev *scev, struct env *acc, struct env *header_env)
+{
+ struct expr *header_expr;
+ int i;
+
+ if (acc->empty)
+ acc->empty = false;
+
+ for (i = 0; i < REGS_NUM; i++) {
+ header_expr = &scev->exprs[header_env->reg2expr[i]];
+ if (is_expr1(header_expr, REG, i))
+ continue;
+ acc->reg2expr[i] = UNKNOWN_EXPR_ID;
+ }
+}
+
+static int worklist_push(struct scev *scev, int loop_header, int idx)
+{
+ u32 tag = (u32)loop_header + 1;
+ int err;
+
+ if (scev->discovered[idx] == tag)
+ return 0;
+
+ err = bpf_min_heap_push(&scev->worklist, idx);
+ if (err)
+ return err;
+
+ scev->discovered[idx] = tag;
+ return 0;
+}
+
+static bool reg_alive_at_succ(struct bpf_verifier_env *env, u32 r, u32 insn_idx)
+{
+ struct bpf_iarray *succ = bpf_insn_successors(env, insn_idx);
+ u32 i;
+
+ for (i = 0; i < succ->cnt; i++)
+ if (reg_alive_at(env, r, succ->items[i]))
+ return true;
+ return false;
+}
+
+enum changes_at {
+ LOG_AT_TRANSFER,
+ LOG_AT_JOIN,
+};
+
+static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
+ struct env *old, struct env *new, int insn_idx)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ u64 null_pos = log->end_pos;
+ bool any_changes = false;
+ u32 old_id, new_id;
+ u64 len;
+ int r;
+
+ bpf_log(log, "%s %4d: ", at == LOG_AT_TRANSFER ? "t" : "j", insn_idx);
+ bpf_verbose_insn(env, &env->prog->insnsi[insn_idx]);
+ len = log->end_pos - null_pos;
+ bpf_log(log, "%*s", max(37 - (int)len, 1), " ");
+ bpf_log(log, " ; ");
+ for (r = 0; r < REGS_NUM; r++) {
+ old_id = old->reg2expr[r];
+ new_id = new->reg2expr[r];
+ if (at == LOG_AT_TRANSFER && !reg_alive_at_succ(env, r, insn_idx))
+ continue;
+ if (at == LOG_AT_JOIN && !reg_alive_at(env, r, insn_idx))
+ continue;
+ if (same_exprs(scev, old_id, new_id))
+ continue;
+ if (any_changes)
+ bpf_log(log, ", ");
+ log_reg(env, r);
+ bpf_log(log, " ");
+ log_expr(env, old_id);
+ bpf_log(log, " -> ");
+ log_expr(env, new_id);
+ any_changes = true;
+ }
+ bpf_log(log, "\n");
+ if (!any_changes)
+ bpf_vlog_reset(log, null_pos);
+}
+
+static bool is_probe_read_helper(u32 func_id)
+{
+ return func_id == BPF_FUNC_probe_read ||
+ func_id == BPF_FUNC_probe_read_kernel ||
+ func_id == BPF_FUNC_probe_read_user ||
+ func_id == BPF_FUNC_probe_read_str ||
+ func_id == BPF_FUNC_probe_read_kernel_str ||
+ func_id == BPF_FUNC_probe_read_user_str;
+}
+
+/*
+ * If instruction is an indirect write to stack, invalidate SCEVs for spi's
+ * that this instruction can touch.
+ */
+static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct scev *scev = env->scev;
+ u8 class = BPF_CLASS(insn->code);
+ const unsigned long *mask;
+ u32 spi, reg;
+ bool opaque;
+
+ /* Direct fp stores are fine. */
+ if ((class == BPF_ST || class == BPF_STX) && insn->dst_reg == BPF_REG_FP)
+ return;
+
+ mask = bpf_may_write_mask(env, idx);
+ opaque = bpf_helper_call(insn) && is_probe_read_helper(insn->imm);
+ for_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {
+ reg = MAX_BPF_REG + spi;
+ if (cur_env->reg2expr[reg] == UNKNOWN_EXPR_ID)
+ continue;
+ replace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);
+ }
+}
+
+/* OR the loop-entry registers referenced by expr 'id' into 'mask'. */
+static void or_expr_regs(struct bpf_verifier_env *env, u32 id, unsigned long *mask)
+{
+ struct scev *scev = env->scev;
+ u32 order;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if ((order & PRE) && scev->exprs[id].op == REG)
+ __set_bit(scev->exprs[id].params[0], mask);
+ }
+}
+
+/* Mask of argument registers (R1..R5) a call at 'idx' passes by register. */
+static u16 call_params_mask(struct bpf_verifier_env *env, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct bpf_call_summary cs;
+ int n = bpf_get_call_summary(env, insn, &cs) ? cs.arg_slot_cnt : MAX_BPF_FUNC_REG_ARGS;
+
+ return n ? GENMASK(BPF_REG_1 + n - 1, BPF_REG_1) : 0;
+}
+
+/*
+ * For instructions like:
+ * - *(u64 *)(rBase + off) = rX
+ * - rX = *(u64 *)(rBase + off)
+ * - calls that construct objects on stack (e.g. dynptr_from_mem(rBase, ...))
+ * When 'rBase' can be a stack pointer and is derived from some registers Rs
+ * defined at loop entry, record Rs into 'mask'.
+ */
+static void collect_store_base_regs(struct bpf_verifier_env *env,
+ struct env *cur_env, int idx, unsigned long *mask)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ u8 class = BPF_CLASS(insn->code);
+ u8 size = BPF_SIZE(insn->code);
+ u16 base_regs = 0;
+ u32 r;
+
+ if (size == BPF_W || size == BPF_DW) {
+ if ((class == BPF_STX || class == BPF_ST) && insn->dst_reg != BPF_REG_FP)
+ base_regs |= BIT(insn->dst_reg);
+ else if (class == BPF_LDX && insn->src_reg != BPF_REG_FP)
+ base_regs |= BIT(insn->src_reg);
+ }
+
+ if (class == BPF_JMP && BPF_OP(insn->code) == BPF_CALL &&
+ bpf_needs_fixed_stack_off(env, idx))
+ base_regs |= call_params_mask(env, idx);
+
+ base_regs &= aux[idx].stack_ptrs;
+ for (r = 0; r < MAX_BPF_REG; r++)
+ if (base_regs & BIT(r))
+ or_expr_regs(env, cur_env->reg2expr[r], mask);
+}
+
+/* Find the topmost loop header containing idx inside cur_header, or -1 if none. */
+static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_header)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int header;
+
+ for (header = bpf_loop_at_index(env, idx); header >= 0;
+ header = aux[header].loop_header)
+ if (aux[header].loop_header == cur_header)
+ return header;
+
+ return -1;
+}
+
+/*
+ * Join cur_env into the successor's environment and schedule their traversal.
+ * Map successors in nested loops to their topmost nested header.
+ * Ignore successors outside the current loop and its nested loops.
+ */
+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
+ struct env *old_env, struct env *cur_env)
+{
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct scev *scev = env->scev;
+ int err, nested_header;
+ struct env *succ_env;
+
+ /*
+ * There are several possibilities for a successor:
+ * - succ_idx can be a part of a loop outside of the cur_header's loop,
+ * such edges are ignored.
+ * - succ_idx can be a part of the same loop as cur_header,
+ * for such edges succ_idx environment is updated:
+ * e[succ_idx] = join(e[succ_idx], cur_env)
+ * - succ_idx can be a part of some loop inner to cur_header,
+ * in such a case there exists some loop header H,
+ * such that H.loop_header == cur_header
+ * and H is the same as succ_idx's loop or contains it.
+ */
+ if (bpf_loop_at_index(env, succ_idx) != cur_header) {
+ /*
+ * topmost_nested_loop() either finds H or returns -1,
+ * in case if succ_idx is a part of a loop outer to cur_header.
+ */
+ nested_header = topmost_nested_loop(env, succ_idx, cur_header);
+ if (nested_header < 0)
+ return 0;
+ succ_idx = nested_header;
+ }
+ succ_env = get_loop_env(scev, cur_header, succ_idx);
+ if (!succ_env)
+ return -ENOMEM;
+ if (log_level2)
+ memcpy(old_env, succ_env, sizeof(*old_env));
+ err = join(scev, succ_env, cur_env);
+ if (err)
+ return err;
+ err = worklist_push(scev, cur_header, succ_idx);
+ if (err)
+ return err;
+ if (log_level2)
+ log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ return 0;
+}
+
+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
+{
+ struct bpf_min_heap *worklist = &env->scev->worklist;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *cur_loop = aux[cur_header].loop;
+ struct env *header_env, *nested_header_env;
+ struct scev *scev = env->scev;
+ struct bpf_loop *nested_loop;
+ struct env *cur_env = NULL;
+ struct env *old_env = NULL;
+ struct bpf_iarray *succ;
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ int s, i, err, idx, succ_idx;
+ u32 r;
+
+ if (log_level2)
+ bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
+
+ /*
+ * For irreducible loops, and for loops nesting a loop with a truncated
+ * exit list, just assume that everything is clobbered for now.
+ */
+ if (cur_loop->irreducible || cur_loop->exits_overflow) {
+ header_env = get_loop_env(scev, cur_header, cur_header);
+ if (!header_env)
+ return -ENOMEM;
+ /* The freshly allocated environment has all expressions unknown. */
+ bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
+ header_env->empty = false;
+ return 0;
+ }
+
+ cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
+ if (!cur_env)
+ goto nomem;
+ if (log_level2) {
+ old_env = kzalloc(sizeof(*old_env), GFP_KERNEL_ACCOUNT);
+ if (!old_env)
+ goto nomem;
+ }
+ header_env = get_loop_env(scev, cur_header, cur_header);
+ if (!header_env)
+ goto nomem;
+ setup_initial_loop_env(env, header_env, cur_header);
+ err = worklist_push(scev, cur_header, cur_header);
+ if (err)
+ goto out;
+
+ for (;;) {
+ if (!bpf_min_heap_pop(worklist, &idx))
+ break;
+
+ /* join_successor() maps nested-loop entries to their representative header. */
+ nested_loop = idx != cur_header ? aux[idx].loop : NULL;
+ memcpy(cur_env, find_loop_env(scev, cur_header, idx), sizeof(*cur_env));
+ if (nested_loop) {
+ /*
+ * Process nested loop as a single instruction by
+ * forgetting anything non-invariant in the nested loop
+ */
+ if (log_level2)
+ memcpy(old_env, cur_env, sizeof(*old_env));
+ /* Pull the nested loop's stack-store base dependencies up. */
+ for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r], cur_loop->store_base_regs);
+ nested_header_env = find_header_env(scev, idx);
+ forget_non_invariants(scev, cur_env, nested_header_env);
+ if (log_level2)
+ log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
+ /*
+ * Treat nested loop exits as successors,
+ * join cur_env into successor's envs.
+ */
+ for (i = 0; i < nested_loop->exits_cnt; i++) {
+ s = nested_loop->exits[i].to;
+ err = join_successor(env, cur_header, s, old_env, cur_env);
+ if (err)
+ goto out;
+ }
+ } else {
+ /*
+ * Iterate instructions within a single basic block
+ * starting at 'idx' mutating 'cur_env'.
+ */
+ for (;;) {
+ if (log_level2)
+ memcpy(old_env, cur_env, sizeof(*old_env));
+ collect_store_base_regs(env, cur_env, idx, cur_loop->store_base_regs);
+ err = transfer(env, cur_env, idx);
+ if (err)
+ goto out;
+ reset_scevs_at_indirect_writes(env, cur_env, idx);
+ if (log_level2)
+ log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
+ succ = bpf_insn_successors(env, idx);
+ if (succ->cnt != 1)
+ break;
+ succ_idx = succ->items[0];
+ if (aux[idx].bb_end || aux[succ_idx].need_scev ||
+ bpf_loop_at_index(env, succ_idx) != cur_header)
+ break;
+ idx = succ_idx;
+ }
+ /* Join cur_env into basic block successor's envs. */
+ iarray_for_each(s, succ) {
+ err = join_successor(env, cur_header, s, old_env, cur_env);
+ if (err)
+ goto out;
+ }
+ }
+ }
+
+ err = 0;
+out:
+ kfree(cur_env);
+ kfree(old_env);
+ return err;
+nomem:
+ err = -ENOMEM;
+ goto out;
+}
+
+static void mark_latches(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop;
+ int len = env->prog->len;
+ int i, j, latch;
+
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ aux[i].need_scev = true;
+ if (loop->irreducible)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ latch = loop->backedges[j].latch;
+ if (latch >= 0)
+ aux[latch].need_scev = true;
+ }
+ }
+}
+
+static bool is_any_imm_reg_opaque(struct scev *scev, u32 id)
+{
+ u32 l, r, reg, order;
+ s64 imm;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT)
+ return false;
+ if (!(order & PRE) ||
+ is_imm(scev, id, &imm) ||
+ is_reg(scev, id, ®) ||
+ is_opaque(scev, id) ||
+ is_any(scev, id, &l, &r))
+ continue;
+ return false;
+ }
+ return true;
+}
+
+/*
+ * Can implement explicit stack version, but it is harder to read.
+ * Stick with recursive version for now.
+ */
+static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
+ int (*fn)(struct scev *scev, u32 id, void *priv))
+{
+ struct expr expr;
+ int p0, p1, id;
+
+ if (lvl >= EXPR_STACK_DEPTH)
+ return UNKNOWN_EXPR_ID;
+
+ expr = scev->exprs[root]; /* snapshot the expr before potential realloc */
+ switch (op_params_num(expr.op)) {
+ case 0:
+ id = root;
+ break;
+ case 1:
+ p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
+ id = expr1(scev, expr.op, p0);
+ break;
+ case 2:
+ p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
+ p1 = transform_expr_once(scev, lvl + 1, expr.params[1], priv, fn);
+ id = expr2(scev, expr.op, p0, p1);
+ break;
+ }
+ return id < 0 ? id : fn(scev, id, priv);
+}
+
+static int transform_expr(struct scev *scev, u32 root, void *priv,
+ int (*fn)(struct scev *scev, u32 id, void *priv))
+{
+ int id_old, id_new = root;
+
+ do {
+ id_old = id_new;
+ id_new = transform_expr_once(scev, 0, id_old, priv, fn);
+ if (id_new < 0)
+ return id_new;
+ } while (id_old != id_new);
+ return id_new;
+}
+
+static int simplify(struct scev *scev, u32 id, void *priv)
+{
+ u32 l, r, base, slope;
+ s64 imm1, imm2;
+
+ /* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
+ if (is_add(scev, id, &l, &r) &&
+ is_linear(scev, l, &base, &slope) &&
+ is_imm(scev, r, &imm1))
+ return expr2(scev, LINEAR_SCEV, expr2(scev, BPF_ADD, base, r), slope);
+
+ /* (+ imm imm) -> imm */
+ if (is_add(scev, id, &l, &r) &&
+ is_imm(scev, l, &imm1) &&
+ is_imm(scev, r, &imm2))
+ return imm_expr(scev, imm1 + imm2);
+
+ if (is_zext32(scev, id, &l) && is_imm(scev, l, &imm1))
+ return imm_expr(scev, (u64)(u32)imm1);
+
+ return id;
+}
+
+static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
+{
+ struct scev *scev = env->scev;
+ u32 ra, rb, l, r, ra_expr;
+ s64 imm;
+ int id;
+
+ for (ra = 0; ra < REGS_NUM; ra++) {
+ id = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
+ if (id < 0)
+ return id;
+ header_env->reg2expr[ra] = id;
+ ra_expr = header_env->reg2expr[ra];
+ /* rA = (+ rA IMM) */
+ if (is_add(scev, ra_expr, &l, &r) &&
+ is_reg(scev, l, &rb) &&
+ is_imm(scev, r, &imm) &&
+ ra == rb) {
+ id = expr2(scev, LINEAR_SCEV, l, r);
+ if (id < 0)
+ return id;
+ header_env->reg2scev[ra] = id;
+ continue;
+ }
+ /* rA = rA */
+ if (is_reg(scev, ra_expr, &rb) && ra == rb) {
+ header_env->reg2scev[ra] = ra_expr;
+ continue;
+ }
+ /* rA = (any 1 2 3 4 ...) */
+ if (is_any_imm_reg_opaque(scev, ra_expr)) {
+ header_env->reg2scev[ra] = ra_expr;
+ continue;
+ }
+
+ }
+ return 0;
+}
+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
+{
+ u32 reg, base, slope, *reg2scev = priv;
+
+ /* (reg r) -> (linear ...), where r is a LINEAR_SCEV in the header */
+ if (is_reg(scev, id, ®) &&
+ is_linear(scev, reg2scev[reg], &base, &slope))
+ return reg2scev[reg];
+ return id;
+}
+
+static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
+{
+ struct scev *scev = env->scev;
+ int id, reg;
+
+ for (reg = 0; reg < REGS_NUM; reg++) {
+ id = einsn->reg2expr[reg];
+ id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
+ if (id < 0)
+ return id;
+ id = transform_expr(scev, id, NULL, simplify);
+ if (id < 0)
+ return id;
+ einsn->reg2scev[reg] = id;
+ }
+
+ return 0;
+}
+
+static void log_scevs(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct bpf_loop *loop;
+ int i, j, len, latch;
+
+ len = env->prog->len;
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ bpf_log(log, "scev at header %d:\n", i);
+ print_env(env, find_header_env(scev, i), i, PRINT_SCEV);
+ if (loop->irreducible)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ latch = loop->backedges[j].latch;
+ if (latch < 0)
+ continue;
+ bpf_log(log, " scev at latch %d:\n", latch);
+ print_env(env, find_loop_env(scev, bpf_loop_at_index(env, latch), latch),
+ latch, PRINT_SCEV);
+ }
+ }
+}
+
+int bpf_compute_scev(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct scev *scev = env->scev;
+ int *postorder = env->cfg.insn_postorder;
+ int cnt = env->cfg.cur_postorder;
+ int i, idx, err, header;
+
+ mark_latches(env);
+ /*
+ * Visit loop headers in postorder, to guarantee that scevs
+ * for innermost loops are computed first.
+ */
+ for (i = 0; i < cnt; i++) {
+ idx = postorder[i];
+ if (!aux[idx].loop)
+ continue;
+ err = compute_scev_for_loop(env, idx);
+ if (err)
+ return err;
+ }
+
+ /*
+ * Compute scevs from exprs collected on a previous step. Iterate instructions in
+ * reverse post-order so that each loop header is processed before instructions
+ * reachable from it.
+ */
+ for (i = cnt - 1; i >= 0; i--) {
+ idx = postorder[i];
+ if (!aux[idx].need_scev)
+ continue;
+ header = bpf_loop_at_index(env, idx);
+ err = aux[idx].loop
+ ? compute_header_scevs(env, find_header_env(scev, header))
+ : compute_insn_scevs(env, find_header_env(scev, header),
+ find_loop_env(scev, header, idx));
+ if (err)
+ return err;
+ }
+
+ for (i = 0; i < env->prog->len; i++)
+ if (aux[i].loop)
+ aux[i].prune_point = true;
+
+ if (env->log.level & BPF_LOG_LEVEL2)
+ log_scevs(env);
+
+ return 0;
+}
+
+static int reverse_ranked_compare(int a, int b, void *arg)
+{
+ int *rank = arg;
+
+ return rank[b] - rank[a];
+}
+
+void bpf_free_scev(struct bpf_verifier_env *env)
+{
+ struct scev *scev = env->scev;
+ struct insn_envs *envs;
+ int i;
+ u32 j;
+
+ if (!scev)
+ return;
+ for (i = 0; i < scev->envs_cnt; i++) {
+ envs = scev->envs[i];
+ if (!envs)
+ continue;
+ for (j = 0; j < envs->cnt; j++)
+ kfree(envs->entries[j].env);
+ kfree(envs);
+ }
+ for (i = 0; i < ARRAY_SIZE(scev->exprs_ht); i++)
+ kvfree(scev->exprs_ht[i]);
+ bpf_min_heap_free(&scev->worklist);
+ kvfree(scev->envs);
+ kvfree(scev->exprs);
+ kvfree(scev->discovered);
+ kfree(scev);
+ env->scev = NULL;
+}
+
+int bpf_init_scev(struct bpf_verifier_env *env)
+{
+ struct scev *scev;
+
+ scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
+ if (!scev)
+ return -ENOMEM;
+ env->scev = scev;
+ bpf_mark_reg_not_init(env, &env->scev_not_init_reg);
+ /* Order worklist in reverse post-order. */
+ bpf_min_heap_init(&scev->worklist, reverse_ranked_compare, env->cfg.postorder_nums);
+ if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE) < 0)
+ goto nomem;
+ scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
+ scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
+ if (!scev->envs || !scev->discovered)
+ goto nomem;
+ /*
+ * Remember original program length, in case bpf_free_scev()
+ * is called after bpf program rewrites that increase program
+ * length.
+ */
+ scev->envs_cnt = env->prog->len;
+ return 0;
+nomem:
+ bpf_free_scev(env);
+ return -ENOMEM;
+}
+
+static struct bpf_reg_state *scev_regno_to_reg(struct bpf_verifier_env *env,
+ struct bpf_func_state *st, u32 r)
+{
+ int spi, slots_available;
+
+ if (r < MAX_BPF_REG)
+ return &st->regs[r];
+
+ slots_available = st->allocated_stack / BPF_REG_SIZE;
+ spi = r - MAX_BPF_REG;
+ if (spi < slots_available)
+ return &st->stack[spi].spilled_ptr;
+
+ return &env->scev_not_init_reg;
+}
+
+static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 r)
+{
+ int insn_idx = bpf_frame_insn_idx(st, st->curframe);
+ u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
+ int spi;
+
+ if (r < MAX_BPF_REG) {
+ return BIT(r) & live_regs;
+ } else {
+ spi = r - MAX_BPF_REG;
+ return bpf_stack_slot_alive(env, st->curframe, spi * 2) ||
+ bpf_stack_slot_alive(env, st->curframe, spi * 2 + 1);
+ }
+}
+
+/*
+ * Latch is a condition deciding if execution remains inside a loop.
+ * Linear latch represents a condition 'if <reg> <op> <loop invariant> goto <loop-header>',
+ * where equation '<base> + i * <step> <op> <bound>' describes values taken by register <reg>,
+ * 'i' is the loop iteration number, starting from 0.
+ */
+struct linear_latch {
+ u32 insn_idx;
+ u32 base_expr;
+ u32 step_expr;
+ u32 bound_expr;
+ u32 reg_expr;
+ u32 reg;
+ u32 op;
+};
+
+static bool loop_invariant(struct scev *scev, u32 id)
+{
+ s64 imm;
+ u32 reg;
+
+ return is_reg(scev, id, ®) || is_imm(scev, id, &imm);
+}
+
+static int match_linear_latch(struct bpf_verifier_env *env,
+ u32 latch_idx,
+ struct linear_latch *latch)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[latch_idx];
+ struct scev *scev = env->scev;
+ struct env *latch_env = find_loop_env(scev, bpf_loop_at_index(env, latch_idx), latch_idx);
+ u32 true_branch_tgt;
+ u32 l, r, op, base;
+ u32 src_reg_scev;
+ u32 dst_reg_scev;
+ int id;
+
+ /* 32-bit arithmetic is not handled yet */
+ if (BPF_CLASS(insn->code) != BPF_JMP)
+ return false;
+ op = BPF_OP(insn->code);
+ /* Flip the condition if true branch jumps out of the loop */
+ true_branch_tgt = latch_idx + bpf_jmp_offset(insn) + 1;
+ if (bpf_loop_at_index(env, true_branch_tgt) != bpf_loop_at_index(env, latch_idx))
+ op = bpf_rev_opcode(op);
+ switch (op) {
+ case BPF_JSLT:
+ case BPF_JSLE:
+ case BPF_JSGT:
+ case BPF_JSGE:
+ case BPF_JLT:
+ case BPF_JLE:
+ case BPF_JGT:
+ case BPF_JGE:
+ case BPF_JNE:
+ break;
+ default:
+ return false;
+ }
+
+ latch->op = op;
+ latch->insn_idx = latch_idx;
+
+ dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
+ src_reg_scev = latch_env->reg2scev[insn->src_reg];
+ if (!is_linear(scev, dst_reg_scev, &base, &latch->step_expr))
+ return false;
+
+ if (BPF_SRC(insn->code) == BPF_K) {
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ latch->bound_expr = id;
+ } else {
+ latch->bound_expr = src_reg_scev;
+ }
+
+ if (is_reg(scev, base, &latch->reg)) {
+ id = imm_expr(scev, 0);
+ if (id < 0)
+ return id;
+ latch->base_expr = id;
+ latch->reg_expr = base;
+ } else if (is_add(scev, base, &l, &r) &&
+ is_reg(scev, l, &latch->reg)) {
+ latch->base_expr = r;
+ latch->reg_expr = l;
+ } else {
+ return false;
+ }
+
+ if (!loop_invariant(scev, latch->base_expr) ||
+ !loop_invariant(scev, latch->step_expr) ||
+ !loop_invariant(scev, latch->bound_expr))
+ return false;
+
+ return true;
+}
+
+static bool eval_expr(struct bpf_verifier_env *env, struct scev *scev, struct bpf_func_state *st, u32 id, u64 *result)
+{
+ struct bpf_reg_state *reg;
+ u32 regno;
+ s64 imm;
+
+ if (is_reg(scev, id, ®no)) {
+ reg = scev_regno_to_reg(env, st, regno);
+ if (reg->type == NOT_INIT)
+ return false;
+ if (tnum_is_const(reg->var_off)) {
+ *result = reg->var_off.value;
+ return true;
+ }
+ } else if (is_imm(scev, id, &imm)) {
+ *result = imm;
+ return true;
+ }
+ return false;
+}
+
+/* Like DIV_ROUND_UP() but overflow safe */
+static u64 div_round_up(u64 a, u64 b)
+{
+ return a / b + (a % b != 0);
+}
+
+/*
+ * Loop with post-condition:
+ *
+ * r0 = 0
+ * l: ... r0 ∈ [0,1,2] header executed 3 times
+ * r0 += 1 r0 ∈ [0,1,2]
+ * ... r0 ∈ [1,2,3]
+ * if r0 != 3 goto l r0 ∈ [1,2,3] backedge taken 2 times
+ * ... r0 ∈ [3]
+ *
+ * SCEV at header: r0 = k
+ * SCEV at latch: r0 = 1 + k
+ *
+ * Loop with pre-condition:
+ *
+ * r0 = 0
+ * l: ... r0 ∈ [0,1,2,3] header executed 4 times
+ * if r0 == 3 goto e r0 ∈ [0,1,2,3] backedge taken 3 times
+ * r0 += 1 r0 ∈ [0,1,2]
+ * ... r0 ∈ [1,2,3]
+ * goto l r0 ∈ [1,2,3]
+ * e: ... r0 ∈ [3]
+ *
+ * SCEV at header: r0 = k
+ * SCEV at latch: r0 = k
+ */
+static bool compute_max_iters(struct bpf_verifier_env *env,
+ struct bpf_func_state *st,
+ struct linear_latch *latch,
+ struct bpf_loop_iters *iters)
+{
+ u64 base, step, diff, bound, initial, max_iters;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop = aux[bpf_loop_at_index(env, latch->insn_idx)].loop;
+ struct scev *scev = env->scev;
+ u8 op = latch->op;
+
+ if (!eval_expr(env, scev, st, latch->base_expr, &base) ||
+ !eval_expr(env, scev, st, latch->step_expr, &step) ||
+ !eval_expr(env, scev, st, latch->bound_expr, &bound) ||
+ !eval_expr(env, scev, st, latch->reg_expr, &initial))
+ return false;
+
+ if (step == 0)
+ return false;
+ if ((s64)step == S64_MIN)
+ return false;
+ if ((s64)step < 0) {
+ /* Multiply both sides of the equation by -1, e.g. -2*i > -3 becomes 2*i < 3 */
+ op = bpf_flip_opcode(op);
+ step = -step;
+ swap(bound, initial);
+ }
+ diff = bound - initial;
+ if (diff / step == U64_MAX)
+ return false;
+ switch (op) {
+ case BPF_JLT:
+ max_iters = (u64)initial >= (u64)bound ? 0 : div_round_up(diff, step);
+ break;
+ case BPF_JLE:
+ max_iters = (u64)initial > (u64)bound ? 0 : diff / step + 1;
+ break;
+ case BPF_JSLT:
+ max_iters = (s64)initial >= (s64)bound ? 0 : div_round_up(diff, step);
+ break;
+ case BPF_JSLE:
+ max_iters = (s64)initial > (s64)bound ? 0 : diff / step + 1;
+ break;
+ case BPF_JNE:
+ max_iters = diff % step ? U32_MAX : div_round_up(diff, step);
+ break;
+ default:
+ return false;
+ }
+
+ if (max_iters > U32_MAX)
+ return false;
+
+ /*
+ * The latch is a conditional jump with one jump target exiting the loop.
+ * Linear latch is matched only if the loop has a single backedge.
+ * The loop still, however can have multiple exits.
+ * In such case, conservatively assume that non-latch exit can happen
+ * at any iteration, thus setting minimal number of iterations as 0.
+ */
+ iters->max_header_count = max_iters + (base == 0 ? 1 : 0);
+ iters->min_header_count = loop->exits_cnt == 1 ? iters->max_header_count : 0;
+ iters->pre_cond = base == 0;
+ return true;
+}
+
+static void mark_scev_reg_scratched(struct bpf_verifier_env *env, u32 r)
+{
+ if (r < MAX_BPF_REG)
+ mark_reg_scratched(env, r);
+ else
+ mark_stack_slot_scratched(env, r - __MAX_BPF_REG);
+}
+
+/* Main logic in verifier.c forbids varying offsets for certain register types. */
+static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
+{
+ switch (base_type(reg->type)) {
+ case SCALAR_VALUE:
+ case PTR_TO_MAP_VALUE:
+ case PTR_TO_MAP_KEY:
+ case PTR_TO_STACK:
+ case PTR_TO_PACKET:
+ case PTR_TO_PACKET_META:
+ case PTR_TO_MEM:
+ case PTR_TO_BUF:
+ case PTR_TO_BTF_ID:
+ return true;
+ default:
+ return false;
+ }
+}
+
+/* Check that ANY leaves can be unioned with r's loop-entry value. */
+static bool is_any_imm_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
+ struct env *header_env, u32 r, u32 id)
+{
+ struct scev *scev = env->scev;
+ struct bpf_reg_state *reg, *leaf_reg;
+ u32 l, rr, leaf, ra, order;
+ s64 imm;
+
+ if (!is_any(scev, id, &l, &rr))
+ return false;
+ reg = scev_regno_to_reg(env, loop_entry, r);
+ if (!is_widenable_reg_type(reg))
+ return false;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT)
+ return false;
+ if (!(order & PRE) || is_any(scev, id, &l, &rr))
+ continue;
+ if (is_imm(scev, id, &imm)) {
+ if (reg->type != SCALAR_VALUE)
+ return false;
+ } else if (is_reg(scev, id, &leaf)) {
+ /* Other leaves must denote loop-invariant registers. */
+ if (leaf != r &&
+ !(is_reg(scev, header_env->reg2scev[leaf], &ra) && ra == leaf))
+ return false;
+ leaf_reg = scev_regno_to_reg(env, loop_entry, leaf);
+ if (leaf_reg->type != reg->type)
+ return false;
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
+struct bounds {
+ struct cnum64 range;
+ u16 step;
+};
+
+static bool is_simple_linear(struct scev *scev, u32 id, u32 *base_reg, s64 *slope_imm)
+{
+ u32 base, slope;
+
+ return is_linear(scev, id, &base, &slope) &&
+ is_reg(scev, base, base_reg) &&
+ is_imm(scev, slope, slope_imm) &&
+ *slope_imm <= S16_MAX &&
+ *slope_imm >= S16_MIN &&
+ *slope_imm != 0;
+}
+
+/*
+ * Compute the range an induction variable in `reg` spans over the loop.
+ * Returns false if the computation overflows s64.
+ */
+static bool linear_bounds(struct bpf_reg_state *reg, struct bpf_loop_iters *iters, s64 slope,
+ struct bounds *out)
+{
+ s64 slope_abs = slope < 0 ? -slope : slope;
+ s64 min_val = reg_smin(reg);
+ s64 max_val = reg_smax(reg);
+ s64 total_change;
+ u16 step;
+
+ if (check_mul_overflow(slope, (s64)iters->max_header_count - 1, &total_change))
+ return false;
+ if (slope > 0) {
+ if (check_add_overflow(max_val, total_change, &max_val))
+ return false;
+ } else {
+ if (check_add_overflow(min_val, total_change, &min_val))
+ return false;
+ }
+ /*
+ * If the entry value is a single point the value set is 'v + slope * k',
+ * so the step is |slope|. Otherwise, only the power-of-two alignment
+ * shared by the entry value and the slope.
+ */
+ if (cnum64_is_const(reg->r64))
+ step = slope_abs;
+ else
+ step = 1u << min_t(u32, tnum_alignment(reg->var_off), __ffs(slope_abs));
+ out->range = cnum64_from_srange(min_val, max_val);
+ out->step = step;
+ return true;
+}
+
+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *cur_func = st->frame[st->curframe];
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct env *header_env;
+ struct linear_latch latch;
+ struct bpf_loop *loop;
+ struct bounds bounds;
+ int insn_idx = st->insn_idx;
+ int linear_latch;
+ u32 r, base_reg;
+ int latch_idx;
+ s64 slope_imm;
+ int err;
+
+ /*
+ * If insn_idx is a loop header for a reducible loop with a single backedge.
+ * loop is NULL for secondary entries to irreducible loops.
+ */
+ loop = aux[insn_idx].loop;
+ if (!loop || loop->irreducible || loop->backedges_cnt != 1 || loop->backedges_overflow ||
+ loop->exits_overflow) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, unsupported loop:%s%s%s\n", insn_idx,
+ !loop || loop->irreducible ? " irreducible" : "",
+ loop && loop->backedges_cnt > 1 ? " multiple backedges" : "",
+ loop && loop->exits_overflow ? " too many exits" : "");
+ return 0;
+ }
+
+ /* If this backedge has a latch */
+ latch_idx = loop->backedges[0].latch;
+ if (latch_idx < 0)
+ return 0;
+
+ linear_latch = match_linear_latch(env, latch_idx, &latch);
+ if (linear_latch < 0)
+ return linear_latch;
+
+ if (!linear_latch) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, non-linear latch at %d\n",
+ insn_idx, latch_idx);
+ return 0;
+ }
+
+ if (!compute_max_iters(env, cur_func, &latch, iters)) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, can't compute iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (iters->max_header_count == 0) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, 0 iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (iters->max_header_count == U32_MAX) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, inf iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, header_count is ", insn_idx);
+ if (iters->min_header_count == iters->max_header_count)
+ bpf_log(log, "%u ", iters->max_header_count);
+ else
+ bpf_log(log, "[%u..%u] ", iters->min_header_count, iters->max_header_count);
+ bpf_log(log, "%s\n", iters->pre_cond ? "pre-cond" : "post-cond");
+ }
+
+ err = bpf_live_stack_query_init(env, st);
+ if (err)
+ return err;
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ struct bpf_reg_state *reg;
+ u32 ra, r_scev, r_expr;
+ bool spill_base = false;
+
+ if (!scev_reg_alive(env, st, r))
+ continue;
+
+ r_scev = header_env->reg2scev[r];
+ reg = scev_regno_to_reg(env, cur_func, r);
+ /* If SCEV for r is (linear <reg> <slope>) */
+ if (is_simple_linear(scev, r_scev, &base_reg, &slope_imm) &&
+ is_widenable_reg_type(reg)) {
+ if (base_reg == r) {
+ /* Can't widen if the iteration range overflows */
+ if (!linear_bounds(reg, iters, slope_imm, &bounds))
+ goto cant_widen;
+ /* Spills at varying offsets lose precision */
+ if (test_bit(r, loop->store_base_regs)) {
+ spill_base = true;
+ goto cant_widen;
+ }
+ }
+ continue;
+ }
+
+ /* rA = rA, loop does not change this reg */
+ if (is_reg(scev, r_scev, &ra) && r == ra)
+ continue;
+
+ /* (any 1 (any 2 (any 3 4))) */
+ if (is_any_imm_reg(env, cur_func, header_env, r, r_scev))
+ continue;
+
+cant_widen:
+ if (log->level & BPF_LOG_LEVEL2) {
+ r_expr = header_env->reg2expr[r];
+ bpf_log(log, "loop header at %d, can't widen ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, ", expr is ");
+ log_expr(env, r_expr);
+ if (spill_base)
+ bpf_log(log, ", requires exact stack-offset tracking");
+ bpf_log(log, "\n");
+ }
+ return 0;
+ }
+
+ return 1;
+}
+
+static void scratch_scalar_id(struct bpf_reg_state *reg)
+{
+ if (reg->type == SCALAR_VALUE)
+ reg->id = 0;
+}
+
+/* The filtering pass has checked that every leaf can be unioned into acc. */
+static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
+ struct bpf_reg_state *acc, u32 id)
+{
+ struct bpf_reg_state *tmp = &env->fake_reg[0], *leaf_reg;
+ struct scev *scev = env->scev;
+ u32 l, r, leaf, order;
+ s64 imm;
+ int err;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT) {
+ verifier_bug(env, "scev ANY union exceeds expression depth limit");
+ return -EFAULT;
+ }
+ if (!(order & PRE) || is_any(scev, id, &l, &r))
+ continue;
+ if (is_imm(scev, id, &imm)) {
+ bpf_mark_reg_known_scalar(tmp, imm);
+ leaf_reg = tmp;
+ } else if (is_reg(scev, id, &leaf)) {
+ leaf_reg = scev_regno_to_reg(env, loop_entry, leaf);
+ } else {
+ verifier_bug(env, "scev ANY union has an unsupported leaf");
+ return -EFAULT;
+ }
+ err = bpf_reg_union(env, acc, leaf_reg);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *cur_func = st->frame[st->curframe];
+ struct bpf_func_state *entry_func = loop_entry->frame[loop_entry->curframe];
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct bpf_reg_state *reg;
+ struct env *header_env;
+ struct bounds bounds;
+ u32 r, base_reg, r_expr, a, b;
+ int insn_idx = st->insn_idx;
+ s64 slope_imm;
+ int err;
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ if (!scev_reg_alive(env, st, r))
+ continue;
+
+ r_expr = header_env->reg2scev[r];
+ /* If SCEV for r is (linear <reg> <slope>)*/
+ if (is_simple_linear(scev, r_expr, &base_reg, &slope_imm) &&
+ base_reg == r) {
+ reg = scev_regno_to_reg(env, cur_func, r);
+ /* Feasibility was checked in the filtering pass above. */
+ if (!linear_bounds(reg, iters, slope_imm, &bounds)) {
+ verifier_bug(env, "scev widen bounds overflow for r%d", r);
+ return -EFAULT;
+ }
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, widening ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ cnum64_smin(bounds.range), cnum64_smax(bounds.range),
+ bounds.step);
+ }
+ scratch_scalar_id(reg);
+ err = bpf_set_reg_range(env, reg, bounds.range, bounds.step);
+ if (err)
+ return err;
+ mark_scev_reg_scratched(env, r);
+ } else if (is_any(scev, r_expr, &a, &b)) {
+ reg = scev_regno_to_reg(env, cur_func, r);
+ err = union_any_reg(env, entry_func, reg, r_expr);
+ if (err)
+ return err;
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, widening ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ reg_smin(reg), reg_smax(reg), reg->step);
+ }
+ scratch_scalar_id(reg);
+ mark_scev_reg_scratched(env, r);
+ }
+ }
+ return 1;
+}
+
+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,
+ struct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *entry_st = entry_state->frame[entry_state->curframe];
+ struct bpf_verifier_log *log = &env->log;
+ struct bpf_reg_state *reg, *entry_reg;
+ struct scev *scev = env->scev;
+ struct env *header_env;
+ struct bounds bounds;
+ u32 r, base_reg;
+ s64 slope_imm;
+ int err;
+
+ if (entry_state->curframe != cur_func_state->frameno) {
+ verifier_bug(env, "clamping registers for a wrong frame: %d vs %d\n",
+ entry_state->curframe, cur_func_state->frameno);
+ return -EFAULT;
+ }
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ /* If SCEV for r is (linear <reg> <slope>)*/
+ if (!is_simple_linear(scev, header_env->reg2scev[r], &base_reg, &slope_imm) ||
+ base_reg != r)
+ continue;
+
+ entry_reg = scev_regno_to_reg(env, entry_st, r);
+ reg = scev_regno_to_reg(env, cur_func_state, r);
+ if (entry_reg->type == NOT_INIT || reg->type == NOT_INIT)
+ continue;
+
+ if (!linear_bounds(entry_reg, iters, slope_imm, &bounds)) {
+ verifier_bug(env, "scev clamp bounds overflow for r%d", r);
+ return -EFAULT;
+ }
+ bounds.range = cnum64_intersect(reg->r64, bounds.range);
+ if (cnum64_is_empty(bounds.range)) {
+ verifier_bug(env, "scev clamp produced empty range for r%d", r);
+ return -EFAULT;
+ }
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, clamping ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ cnum64_smin(bounds.range), cnum64_smax(bounds.range),
+ bounds.step);
+ }
+ scratch_scalar_id(reg);
+ err = bpf_set_reg_range(env, reg, bounds.range, bounds.step);
+ if (err)
+ return err;
+ mark_scev_reg_scratched(env, r);
+ }
+ return 0;
+}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 18bf7b660c2f6..c1771a355e4e4 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -302,8 +302,30 @@ int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_s
static bool range_within(const struct bpf_reg_state *old,
const struct bpf_reg_state *cur)
{
- return cnum64_is_subset(old->r64, cur->r64) &&
- cnum32_is_subset(old->r32, cur->r32);
+ if (!cnum64_is_subset(old->r64, cur->r64) ||
+ !cnum32_is_subset(old->r32, cur->r32))
+ return false;
+
+ if (old->step <= 1)
+ return true;
+
+ if (cnum64_is_const(cur->r64))
+ return imod((s64)cnum64_smin(cur->r64), old->step) == old->base;
+
+ /*
+ * Both `old` and `cur` define some sets of points.
+ * Return true, if points defined by `cur` are a subset of points defined by `old`:
+ * - bounds for `cur` should be within bounds for `old`;
+ * - cur->step should be dividable by old->step;
+ * - cur->base should start at integer number of old->step
+ * steps from old->base.
+ *
+ * E.g. the following ranges are compatible:
+ * - old [0, 10] step 2
+ * - new [2, 10] step 4
+ */
+ return cur->step % old->step == 0 &&
+ (cur->base - old->base) % old->step == 0;
}
/* If in the old state two registers had the same id, then they need to have
@@ -610,6 +632,7 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
case PTR_TO_MEM:
case PTR_TO_BUF:
case PTR_TO_TP_BUFFER:
+ case PTR_TO_BTF_ID:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
*/
@@ -644,7 +667,12 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_STACK:
- return regs_exact(rold, rcur, idmap);
+ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
+ range_within(rold, rcur) &&
+ tnum_in(rold->var_off, rcur->var_off) &&
+ check_ids(rold->id, rcur->id, idmap) &&
+ check_ids(rold->parent_id, rcur->parent_id, idmap) &&
+ rold->frameno == rcur->frameno;
case PTR_TO_ARENA:
return true;
case PTR_TO_INSN:
@@ -914,6 +942,28 @@ static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *c
return true;
}
+static bool loop_stack_safe(struct bpf_verifier_env *env, struct bpf_func_state *old,
+ struct bpf_func_state *cur)
+{
+ struct loop_stack_entry *old_stack = old->loop_stack;
+ struct loop_stack_entry *cur_stack = cur->loop_stack;
+ u32 i;
+
+ if (old->loop_stack_cnt != cur->loop_stack_cnt)
+ return false;
+
+ for (i = 0; i < old->loop_stack_cnt; i++) {
+ if (old_stack[i].loop_id == cur_stack[i].loop_id &&
+ old_stack[i].iters.max_header_count == cur_stack[i].iters.max_header_count &&
+ old_stack[i].iters.pre_cond == cur_stack[i].iters.pre_cond &&
+ old_stack[i].terminates == cur_stack[i].terminates)
+ continue;
+ return false;
+ }
+
+ return true;
+}
+
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
@@ -964,6 +1014,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat
if (!stack_arg_safe(env, old, cur, &env->idmap_scratch, exact))
return false;
+ if (!loop_stack_safe(env, old, cur))
+ return false;
+
return true;
}
@@ -1010,6 +1063,7 @@ static bool states_equal(struct bpf_verifier_env *env,
if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
return false;
}
+
return true;
}
@@ -1240,16 +1294,82 @@ static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_
}
}
-int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
+int bpf_split_cur_state(struct bpf_verifier_env *env)
{
+ struct bpf_verifier_state *cur = env->cur_state, *new;
struct bpf_verifier_state_list *new_sl;
+ struct list_head *head;
+ int insn_idx = cur->insn_idx;
+ int err;
+
+ head = bpf_explored_state(env, insn_idx);
+ new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
+ if (!new_sl)
+ return -ENOMEM;
+ env->total_states++;
+ env->explored_states_size++;
+ update_peak_states(env);
+ env->prev_jmps_processed = env->jmps_processed;
+ env->prev_insn_processed = env->insn_processed;
+
+ /* forget precise markings we inherited, see __mark_chain_precision */
+ if (env->bpf_capable)
+ mark_all_scalars_imprecise(env, cur);
+
+ bpf_clear_singular_ids(env, cur);
+
+ /* add new state to the head of linked list */
+ new = &new_sl->state;
+ err = bpf_copy_verifier_state(new, cur);
+ if (err) {
+ bpf_free_verifier_state(new, false);
+ kfree(new_sl);
+ return err;
+ }
+ new->insn_idx = insn_idx;
+ verifier_bug_if(new->branches != 1, env,
+ "%s:branches_to_explore=%d insn %d",
+ __func__, new->branches, insn_idx);
+ err = maybe_enter_scc(env, new);
+ if (err) {
+ bpf_free_verifier_state(new, false);
+ kfree(new_sl);
+ return err;
+ }
+
+ cur->parent = new;
+ cur->last_insn_idx = -1;
+ cur->first_insn_idx = insn_idx;
+ cur->dfs_depth = new->dfs_depth + 1;
+ bpf_clear_jmp_history(cur);
+ list_add(&new_sl->node, head);
+ return 0;
+}
+
+/* Force a checkpoint upon reaching a loop header for a terminating loop. */
+static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)
+{
+ struct bpf_verifier_state *cur = env->cur_state;
+ struct bpf_func_state *frame = cur->frame[cur->curframe];
+ struct loop_stack_entry *top;
+
+ if (bpf_loop_at_index(env, insn_idx) != insn_idx || !frame->loop_stack_cnt)
+ return false;
+ top = &frame->loop_stack[frame->loop_stack_cnt - 1];
+ return top->loop_id == insn_idx && top->terminates;
+}
+
+int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
+{
struct bpf_verifier_state_list *sl;
- struct bpf_verifier_state *cur = env->cur_state, *new;
- bool force_new_state, add_new_state, loop;
+ struct bpf_verifier_state *cur = env->cur_state;
+ bool force_new_state, add_new_state, loop, loop_checkpoint;
int n, err, states_cnt = 0;
struct list_head *pos, *tmp, *head;
+ loop_checkpoint = need_loop_checkpoint(env, insn_idx);
force_new_state = env->test_state_freq || bpf_is_force_checkpoint(env, insn_idx) ||
+ loop_checkpoint ||
/* Avoid accumulating infinitely long jmp history */
cur->jmp_history_cnt > 40;
@@ -1280,10 +1400,11 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
continue;
if (sl->state.branches) {
- struct bpf_func_state *frame = sl->state.frame[0];
+ struct bpf_func_state *old_top_frame = sl->state.frame[0];
+ struct bpf_func_state *old_cur_frame = sl->state.frame[sl->state.curframe];
- if (frame->in_async_callback_fn &&
- frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
+ if (old_top_frame->in_async_callback_fn &&
+ old_top_frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
/* Different async_entry_cnt means that the verifier is
* processing another entry into async callback.
* Seeing the same state is not an indication of infinite
@@ -1382,6 +1503,20 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
}
goto skip_inf_loop_check;
}
+
+ /*
+ * If old state belongs to a control flow loop that we know terminates,
+ * it should be safe to prune current state.
+ */
+ if (old_cur_frame->loop_stack_cnt &&
+ old_cur_frame->loop_stack[old_cur_frame->loop_stack_cnt - 1].terminates) {
+ if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
+ loop = true;
+ goto hit;
+ }
+ goto skip_inf_loop_check;
+ }
+
/* attempt to detect infinite loop to avoid unnecessary doomed work */
if (states_maybe_looping(&sl->state, cur) &&
states_equal(env, &sl->state, cur, EXACT) &&
@@ -1540,7 +1675,8 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
* Use bigger 'n' for checkpoints because evicting checkpoint states
* too early would hinder iterator convergence.
*/
- n = bpf_is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
+ n = (bpf_is_force_checkpoint(env, insn_idx) || loop_checkpoint) &&
+ sl->state.branches > 0 ? 64 : 3;
if (sl->miss_cnt > sl->hit_cnt * n + n) {
/* the state is unlikely to be useful. Remove it to
* speed up verification
@@ -1572,44 +1708,5 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
* When looping the sl->state.branches will be > 0 and this state
* will not be considered for equivalence until branches == 0.
*/
- new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
- if (!new_sl)
- return -ENOMEM;
- env->total_states++;
- env->explored_states_size++;
- update_peak_states(env);
- env->prev_jmps_processed = env->jmps_processed;
- env->prev_insn_processed = env->insn_processed;
-
- /* forget precise markings we inherited, see __mark_chain_precision */
- if (env->bpf_capable)
- mark_all_scalars_imprecise(env, cur);
-
- bpf_clear_singular_ids(env, cur);
-
- /* add new state to the head of linked list */
- new = &new_sl->state;
- err = bpf_copy_verifier_state(new, cur);
- if (err) {
- bpf_free_verifier_state(new, false);
- kfree(new_sl);
- return err;
- }
- new->insn_idx = insn_idx;
- verifier_bug_if(new->branches != 1, env,
- "%s:branches_to_explore=%d insn %d",
- __func__, new->branches, insn_idx);
- err = maybe_enter_scc(env, new);
- if (err) {
- bpf_free_verifier_state(new, false);
- kfree(new_sl);
- return err;
- }
-
- cur->parent = new;
- cur->first_insn_idx = insn_idx;
- cur->dfs_depth = new->dfs_depth + 1;
- bpf_clear_jmp_history(cur);
- list_add(&new_sl->node, head);
- return 0;
+ return bpf_split_cur_state(env);
}
diff --git a/kernel/bpf/tnum.c b/kernel/bpf/tnum.c
index ec9c310cf5d7f..1f620facd1b7e 100644
--- a/kernel/bpf/tnum.c
+++ b/kernel/bpf/tnum.c
@@ -317,3 +317,14 @@ u64 tnum_step(struct tnum t, u64 z)
inc = (filled + 1) & t.mask;
return t.value | inc;
}
+
+/*
+ * Return the number of trailing bits known to be zero in a tnum.
+ * Return 64 for a tnum representing zero.
+ */
+u32 tnum_alignment(struct tnum a)
+{
+ u64 v = a.value | a.mask;
+
+ return v ? __ffs64(v) : 64;
+}
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 03dbc0e003986..327bfc00da5f5 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -5,6 +5,7 @@
*/
#include <uapi/linux/btf.h>
#include <linux/bpf-cgroup.h>
+#include <linux/count_zeros.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
@@ -30,6 +31,7 @@
#include <linux/module.h>
#include <linux/cpumask.h>
#include <linux/cnum.h>
+#include <linux/gcd.h>
#include <linux/bpf_mem_alloc.h>
#include <net/xdp.h>
#include <linux/trace_events.h>
@@ -1910,12 +1912,19 @@ static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
}
}
+static void reg_step_reset(struct bpf_reg_state *reg)
+{
+ reg->base = 0;
+ reg->step = 1;
+}
+
/* This helper doesn't clear reg->id */
static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->var_off = tnum_const(imm);
reg->r64 = cnum64_from_urange(imm, imm);
reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
+ reg_step_reset(reg);
}
/* Mark the unknown part of a register (variable offset or scalar value) as
@@ -1932,6 +1941,12 @@ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
___mark_reg_known(reg, imm);
}
+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
+{
+ __mark_reg_known(reg, imm);
+ reg->type = SCALAR_VALUE;
+}
+
static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
{
reg->var_off = tnum_const_subreg(reg->var_off, imm);
@@ -2158,10 +2173,16 @@ static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
}
+static void deduce_bounds_64_from_step(struct bpf_reg_state *reg)
+{
+ reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
+}
+
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
deduce_bounds_32_from_64(reg);
deduce_bounds_64_from_32(reg);
+ deduce_bounds_64_from_step(reg);
}
/* Attempts to improve var_off based on unsigned min/max information */
@@ -2173,8 +2194,18 @@ static void __reg_bound_offset(struct bpf_reg_state *reg)
struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
tnum_range(reg_u32_min(reg),
reg_u32_max(reg)));
+ u32 trailing_zero_bits;
+ u16 base = reg->base;
+ u16 step = reg->step;
reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
+
+ if (base == 0)
+ trailing_zero_bits = count_trailing_zeros(step);
+ else
+ trailing_zero_bits = min(count_trailing_zeros(base),
+ count_trailing_zeros(step));
+ reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
}
static bool range_bounds_violation(struct bpf_reg_state *reg);
@@ -2250,6 +2281,7 @@ static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
if (env->test_reg_invariants)
return -EFAULT;
__mark_reg_unbounded(reg);
+ reg_step_reset(reg);
return 0;
}
@@ -2260,6 +2292,7 @@ void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
reg->type = SCALAR_VALUE;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
+ reg_step_reset(reg);
}
/* Mark a register as having a completely unknown (scalar) value,
@@ -6339,6 +6372,7 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
const char *field_name = NULL;
enum bpf_type_flag flag = 0;
u32 btf_id = 0;
+ s64 min_off;
int ret;
if (!env->allow_ptr_leaks) {
@@ -6354,36 +6388,31 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
return -EINVAL;
}
- if (!tnum_is_const(reg->var_off)) {
- char tn_buf[48];
-
- tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
+ if (check_add_overflow(reg_smin(reg), off, &min_off)) {
verbose(env,
- "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
- reg_arg_name(env, argno), tname, off, tn_buf);
+ "%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n",
+ reg_arg_name(env, argno), tname, reg_smin(reg), off);
return -EACCES;
}
- off += reg->var_off.value;
-
- if (off < 0) {
+ if (min_off < 0) {
verbose(env,
- "%s is ptr_%s invalid negative access: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s invalid negative access: off=%lld\n",
+ reg_arg_name(env, argno), tname, min_off);
return -EACCES;
}
if (reg->type & MEM_USER) {
verbose(env,
- "%s is ptr_%s access user memory: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s access user memory\n",
+ reg_arg_name(env, argno), tname);
return -EACCES;
}
if (reg->type & MEM_PERCPU) {
verbose(env,
- "%s is ptr_%s access percpu memory: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s access percpu memory\n",
+ reg_arg_name(env, argno), tname);
return -EACCES;
}
@@ -6393,6 +6422,18 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
}
if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
+ if (!tnum_is_const(reg->var_off)) {
+ char tn_buf[48];
+
+ tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
+ verbose(env,
+ "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
+ reg_arg_name(env, argno), tname, off, tn_buf);
+ return -EACCES;
+ }
+
+ off += reg->var_off.value;
+
if (!btf_is_kernel(reg->btf)) {
verifier_bug(env, "reg->btf must be kernel btf");
return -EFAULT;
@@ -14046,6 +14087,46 @@ static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 of
return *kfunc.flags & KF_SPINLOCK_SAFE;
}
+/*
+ * True if insn calls a helper/kfunc that requires one of its arguments to
+ * be a stack pointer with a constant offset.
+ */
+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
+{
+ const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
+ u32 *flags, btf_id;
+
+ if (bpf_helper_call(insn)) {
+ return insn->imm == BPF_FUNC_dynptr_from_mem ||
+ insn->imm == BPF_FUNC_ringbuf_reserve_dynptr;
+ }
+
+ /* vmlinux kfuncs only */
+ if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
+ return false;
+ btf_id = insn->imm;
+
+ flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
+ if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
+ return true;
+
+ if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
+ btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
+ btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
+ return true;
+
+ if (btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_xdp] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_file])
+ return true;
+
+ return false;
+}
+
static bool is_sync_callback_calling_kfunc(u32 btf_id)
{
return is_bpf_rbtree_add_kfunc(btf_id);
@@ -15582,6 +15663,50 @@ static int sanitize_check_bounds(struct bpf_verifier_env *env,
return 0;
}
+static void scalar_step_add(struct bpf_reg_state *dst_reg,
+ const struct bpf_reg_state *a,
+ const struct bpf_reg_state *b)
+{
+ u16 base, step;
+
+ /* If either 'a' or 'b' is a constant, update the base/step for the counterpart. */
+ if (tnum_is_const(b->var_off)) {
+ step = a->step;
+ base = imod((s64)a->base + (s64)b->var_off.value, step);
+ } else if (tnum_is_const(a->var_off)) {
+ step = b->step;
+ base = imod((s64)b->base + (s64)a->var_off.value, step);
+ } else {
+ step = 1;
+ base = 0;
+ }
+ dst_reg->base = base;
+ dst_reg->step = step;
+}
+
+static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+{
+ u64 amount = src_reg->var_off.value;
+
+ if (tnum_is_const(src_reg->var_off) && (s64)amount >= 0 &&
+ !check_mul_overflow(dst_reg->step, amount, &dst_reg->step) &&
+ dst_reg->step != 0)
+ dst_reg->base = (dst_reg->base * amount) % dst_reg->step;
+ else
+ reg_step_reset(dst_reg);
+}
+
+static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+{
+ u64 amount = src_reg->var_off.value;
+
+ if (tnum_is_const(src_reg->var_off) && amount < 64 &&
+ !check_mul_overflow(dst_reg->step, 1ull << amount, &dst_reg->step))
+ dst_reg->base = (dst_reg->base * (1ull << amount)) % dst_reg->step;
+ else
+ reg_step_reset(dst_reg);
+}
+
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
@@ -15739,6 +15864,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
+ scalar_step_add(dst_reg, ptr_reg, off_reg);
dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->raw = ptr_reg->raw;
@@ -15800,6 +15926,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
if ((!known && smin_val < 0) || dst_reg->range < 0)
memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
}
+ reg_step_reset(dst_reg);
break;
case BPF_AND:
case BPF_OR:
@@ -16499,6 +16626,7 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins
* Bounds will be re-derived from the new tnum later.
*/
__mark_reg_unbounded(dst_reg);
+ reg_step_reset(dst_reg);
}
/* For bswap16/32, truncate dst register to match the swapped size */
if (insn->imm == 16 || insn->imm == 32)
@@ -16625,6 +16753,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
*/
switch (opcode) {
case BPF_ADD:
+ scalar_step_add(dst_reg, dst_reg, &src_reg);
scalar32_min_max_add(dst_reg, &src_reg);
scalar_min_max_add(dst_reg, &src_reg);
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
@@ -16633,6 +16762,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar32_min_max_sub(dst_reg, &src_reg);
scalar_min_max_sub(dst_reg, &src_reg);
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
+ reg_step_reset(dst_reg);
break;
case BPF_NEG:
env->fake_reg[0] = *dst_reg;
@@ -16640,11 +16770,13 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
+ reg_step_reset(dst_reg);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_mul(dst_reg, &src_reg);
scalar_min_max_mul(dst_reg, &src_reg);
+ scalar_step_mul(dst_reg, &src_reg);
break;
case BPF_DIV:
/* BPF div specification: x / 0 = 0 */
@@ -16662,6 +16794,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar_min_max_sdiv(dst_reg, &src_reg);
else
scalar_min_max_udiv(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_MOD:
/* BPF mod specification: x % 0 = x */
@@ -16677,6 +16810,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar_min_max_smod(dst_reg, &src_reg);
else
scalar_min_max_umod(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_AND:
if (tnum_is_const(src_reg.var_off)) {
@@ -16687,6 +16821,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_and(dst_reg, &src_reg);
scalar_min_max_and(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_OR:
if (tnum_is_const(src_reg.var_off)) {
@@ -16697,32 +16832,38 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_or(dst_reg, &src_reg);
scalar_min_max_or(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_XOR:
dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_xor(dst_reg, &src_reg);
scalar_min_max_xor(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_LSH:
if (alu32)
scalar32_min_max_lsh(dst_reg, &src_reg);
else
scalar_min_max_lsh(dst_reg, &src_reg);
+ scalar_step_lsh(dst_reg, &src_reg);
break;
case BPF_RSH:
if (alu32)
scalar32_min_max_rsh(dst_reg, &src_reg);
else
scalar_min_max_rsh(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_ARSH:
if (alu32)
scalar32_min_max_arsh(dst_reg, &src_reg);
else
scalar_min_max_arsh(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_END:
scalar_byte_swap(dst_reg, insn);
+ reg_step_reset(dst_reg);
break;
default:
break;
@@ -16934,6 +17075,45 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
return 0;
}
+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
+ struct cnum64 range, u16 step)
+{
+ reg->r64 = range;
+ reg->r32 = CNUM32_UNBOUNDED;
+ reg->step = step;
+ reg->base = imod(cnum64_smin(range), step);
+ reg->var_off = tnum_unknown;
+ reg_bounds_sync(reg); /* this should infer the tnum alignment */
+ return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
+}
+
+/* acc := acc U src, matching types only. Caller must clear acc's scalar ID. */
+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
+ const struct bpf_reg_state *src)
+{
+ u16 base, step;
+
+ if (acc->type != src->type) {
+ verifier_bug(env, "union of registers with different types");
+ return -EFAULT;
+ }
+ acc->r64 = cnum64_union(acc->r64, src->r64);
+ acc->r32 = cnum32_union(acc->r32, src->r32);
+ acc->var_off = tnum_union(acc->var_off, src->var_off);
+
+ /* Retain a common congruence if the bases agree modulo the gcd. */
+ step = gcd(acc->step, src->step);
+ base = acc->base % step;
+ if (base != src->base % step) {
+ reg_step_reset(acc);
+ } else {
+ acc->base = base;
+ acc->step = step;
+ }
+ reg_bounds_sync(acc);
+ return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
+}
+
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
@@ -17203,8 +17383,6 @@ static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
u8 opcode, bool is_jmp32);
-static u8 rev_opcode(u8 opcode);
-
/*
* Learn more information about live branches by simulating refinement on both branches.
* regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
@@ -17213,7 +17391,7 @@ static u8 rev_opcode(u8 opcode);
static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
{
/* Fallthrough (FALSE) branch */
- regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32);
+ regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
reg_bounds_sync(&env->false_reg1);
reg_bounds_sync(&env->false_reg2);
/*
@@ -17399,7 +17577,7 @@ static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_s
return simulate_both_branches_taken(env, opcode, is_jmp32);
}
-static int flip_opcode(u32 opcode)
+int bpf_flip_opcode(u32 opcode)
{
/* How can we transform "a <op> b" into "b <op> a"? */
static const u8 opcode_flip[16] = {
@@ -17430,7 +17608,7 @@ static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
pkt = dst_reg;
} else if (dst_reg->type == PTR_TO_PACKET_END) {
pkt = src_reg;
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
} else {
return -1;
}
@@ -17485,7 +17663,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r
/* arrange that reg2 is a scalar, and reg1 is a pointer */
if (!is_reg_const(reg2, is_jmp32)) {
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
swap(reg1, reg2);
}
/* and ensure that reg2 is a constant */
@@ -17519,7 +17697,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r
/* Opcode that corresponds to a *false* branch condition.
* E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
*/
-static u8 rev_opcode(u8 opcode)
+u8 bpf_rev_opcode(u8 opcode)
{
switch (opcode) {
case BPF_JEQ: return BPF_JNE;
@@ -17554,7 +17732,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state
case BPF_JGT:
case BPF_JSGE:
case BPF_JSGT:
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
swap(reg1, reg2);
break;
default:
@@ -17631,6 +17809,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state
* violations if we're on a dead branch.
*/
__mark_reg_unbounded(reg1);
+ reg_step_reset(reg1);
if (is_jmp32) {
t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
reg1->var_off = tnum_with_subreg(reg1->var_off, t);
@@ -19465,6 +19644,204 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
return -EFAULT;
}
+static bool has_entered_loop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+
+ return aux[insn_idx].loop_entry &&
+ (prev_insn_idx == -1 ||
+ bpf_loop_at_index(env, prev_insn_idx) != bpf_loop_at_index(env, insn_idx));
+}
+
+static bool is_next_loop_iteration(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+
+ return aux[insn_idx].loop_entry &&
+ (prev_insn_idx != -1 &&
+ bpf_loop_at_index(env, prev_insn_idx) == bpf_loop_at_index(env, insn_idx));
+}
+
+static bool has_exited_loop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+ int prev_loop_idx, h;
+
+ if (prev_insn_idx == -1)
+ return false;
+
+ prev_loop_idx = bpf_loop_at_index(env, prev_insn_idx);
+ if (prev_loop_idx < 0)
+ return false;
+
+ /* Still inside the previous instruction's loop if that loop encloses insn_idx */
+ for (h = bpf_loop_at_index(env, insn_idx); h >= 0; h = aux[h].loop_header)
+ if (h == prev_loop_idx)
+ return false;
+
+ return true;
+}
+
+/*
+ * Push the loop entered at insn_idx onto the stack. Usually this adds a single
+ * entry on top of its enclosing loop. However, an edge may enter an inner loop
+ * directly, bypassing the header(s) of its enclosing loop(s), e.g.:
+ *
+ * 1: for (...): // enclosing loop, header at 1
+ * 2: for (...): // inner loop, header at 2
+ * ...
+ * 3: if ...:
+ * goto 2b; // enters loop 2 without going through header 1
+ *
+ * Such a bypass makes the enclosing loop irreducible, so its header is missing
+ * from the stack and both headers (1) and (2) need to be pushed onto stack.
+ * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
+ * the bypassed ancestors are irreducible and pushed as non-terminating.
+ *
+ * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
+ * of the bpf_loop_at_index(env->prev_insn_idx) and bpf_loop_at_index(env->insn_idx).
+ */
+static int loop_stack_push(struct bpf_verifier_env *env,
+ struct bpf_verifier_state *entry_state,
+ bool terminates,
+ struct bpf_loop_iters *iters)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_func_state *frame = cur_func(env);
+ struct loop_stack_entry *loop_stack = frame->loop_stack;
+ u32 missing_headers[LOOP_STACK_SIZE];
+ u32 cnt = frame->loop_stack_cnt;
+ u32 num_missing = 0;
+ int h;
+
+ for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
+ if (cnt && loop_stack[cnt - 1].loop_id == h)
+ break;
+ if (num_missing == LOOP_STACK_SIZE)
+ goto e2big;
+ missing_headers[num_missing] = h;
+ }
+
+ for (; num_missing; num_missing--, cnt++) {
+ if (cnt == LOOP_STACK_SIZE)
+ goto e2big;
+ loop_stack[cnt].loop_id = missing_headers[num_missing - 1];
+ if (num_missing == 1) {
+ loop_stack[cnt].iters = terminates ? *iters : (struct bpf_loop_iters){};
+ loop_stack[cnt].terminates = terminates;
+ loop_stack[cnt].entry_state = entry_state;
+ } else {
+ loop_stack[cnt].iters = (struct bpf_loop_iters){};
+ loop_stack[cnt].terminates = false;
+ loop_stack[cnt].entry_state = NULL;
+ }
+ }
+ frame->loop_stack_cnt = cnt;
+ return 0;
+
+e2big:
+ verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
+ return -E2BIG;
+}
+
+/*
+ * An exit from a loop can cross several nested loops, e.g.:
+ *
+ * 1: for (...):
+ * 2: for (...):
+ * 3: for (...):
+ * if ...: // before goto the loop stack is [1, 2, 3 <top>]
+ * goto 1b; // after goto it should become [1]
+ */
+static int loop_stack_pop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_func_state *frame = cur_func(env);
+ int h, i;
+
+ /*
+ * Walk the loop nest of insn_idx outwards (innermost first) and stop at
+ * the first loop that is present on the stack - that loop is the common
+ * ancestor and becomes the new top. If no enclosing loop is on the
+ * stack, drop all loops.
+ */
+ for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
+ for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
+ if (frame->loop_stack[i].loop_id == h) {
+ frame->loop_stack_cnt = i + 1;
+ return 0;
+ }
+ }
+ }
+
+ frame->loop_stack_cnt = 0;
+ return 0;
+}
+
+static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
+{
+ struct bpf_func_state *frame = cur_func(env);
+ struct loop_stack_entry *entry;
+
+ if (frame->loop_stack_cnt == 0) {
+ verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
+ return -EFAULT;
+ }
+
+ entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
+ if (!entry->terminates)
+ return 0;
+
+ return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state, &entry->iters);
+}
+
+static int handle_loop_entry_exit(struct bpf_verifier_env *env)
+{
+ struct bpf_verifier_state *cur = env->cur_state;
+ struct bpf_loop_iters iters;
+ bool terminates;
+ int err;
+
+ if (is_next_loop_iteration(env)) {
+ err = maybe_clamp_scev_regs(env);
+ if (err)
+ return err;
+ }
+ if (has_exited_loop(env)) {
+ if (env->log.level & BPF_LOG_LEVEL2)
+ verbose(env, "exiting loop %d\n", bpf_loop_at_index(env, env->prev_insn_idx));
+ err = loop_stack_pop(env);
+ if (err)
+ return err;
+ }
+ if (has_entered_loop(env)) {
+ if (env->log.level & BPF_LOG_LEVEL2)
+ verbose(env, "entering loop %d\n", bpf_loop_at_index(env, env->insn_idx));
+ err = bpf_compute_loop_iters(env, env->cur_state, &iters);
+ if (err < 0)
+ return err;
+ terminates = err == 1;
+ if (terminates) {
+ err = bpf_split_cur_state(env);
+ if (err)
+ return err;
+ err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
+ if (err < 0)
+ return err;
+ }
+ err = loop_stack_push(env, env->cur_state->parent, terminates, &iters);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
static int do_check(struct bpf_verifier_env *env)
{
bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
@@ -19479,6 +19856,12 @@ static int do_check(struct bpf_verifier_env *env)
struct bpf_insn_aux_data *insn_aux;
int err;
+ if (signal_pending(current))
+ return -EAGAIN;
+
+ if (need_resched())
+ cond_resched();
+
/* reset current history entry on each new instruction */
env->cur_hist_ent = NULL;
@@ -19525,6 +19908,15 @@ static int do_check(struct bpf_verifier_env *env)
}
}
+ /*
+ * Possibly widen the registers before creating a checkpoint
+ * in bpf_is_state_visited(). The next loop iteration will
+ * have a chance to hit this checkpoint and converge.
+ */
+ err = handle_loop_entry_exit(env);
+ if (err)
+ return err;
+
if (bpf_is_prune_point(env, env->insn_idx)) {
err = bpf_is_state_visited(env, env->insn_idx);
if (err < 0)
@@ -19550,12 +19942,6 @@ static int do_check(struct bpf_verifier_env *env)
return err;
}
- if (signal_pending(current))
- return -EAGAIN;
-
- if (need_resched())
- cond_resched();
-
if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
verbose(env, "\nfrom %d to %d%s:",
env->prev_insn_idx, env->insn_idx,
@@ -19565,6 +19951,13 @@ static int do_check(struct bpf_verifier_env *env)
do_print_state = false;
}
+ if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
+ cur_func(env)->loop_stack_cnt == 0) {
+ verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
+ env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
+ return -EFAULT;
+ }
+
if (env->log.level & BPF_LOG_LEVEL) {
if (verifier_state_scratched(env))
print_insn_state(env, state, state->curframe);
@@ -22441,6 +22834,45 @@ static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)
return false;
}
+/* Various log level 2 information about the program */
+static void log_program(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
+ struct bpf_insn *insns = env->prog->insnsi;
+ u32 insn_cnt = env->prog->len;
+ u64 pos, insn_pos;
+ u32 i, j;
+
+ verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
+ for (i = 0; i < insn_cnt; ++i) {
+ verbose_linfo(env, i, " ; ");
+ if (env->insn_aux_data[i].scc)
+ verbose(env, "%3d ", env->insn_aux_data[i].scc);
+ else
+ verbose(env, " ");
+ if (env->insn_aux_data[i].loop_header >= 0)
+ verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
+ else
+ verbose(env, " ");
+ verbose(env, "%3d ", env->idoms[i]);
+ verbose(env, "%3d: ", i);
+ for (j = BPF_REG_0; j < BPF_REG_10; ++j)
+ if (insn_aux[i].live_regs_before & BIT(j))
+ verbose(env, "%d", j);
+ else
+ verbose(env, ".");
+ verbose(env, " ");
+ pos = env->log.end_pos;
+ bpf_verbose_insn(env, &insns[i]);
+ insn_pos = env->log.end_pos;
+ if (insn_aux[i].zext_dst)
+ verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
+ verbose(env, "\n");
+ if (bpf_is_ldimm64(&insns[i]))
+ i++;
+ }
+}
+
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
struct bpf_log_attr *attr_log)
{
@@ -22642,10 +23074,29 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ ret = bpf_compute_idoms(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ ret = bpf_compute_loops(env);
+ if (ret < 0)
+ goto skip_full_check;
+
ret = bpf_compute_live_registers(env);
if (ret < 0)
goto skip_full_check;
+ if (env->log.level & BPF_LOG_LEVEL2)
+ log_program(env);
+
+ ret = bpf_init_scev(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ ret = bpf_compute_scev(env);
+ if (ret < 0)
+ goto skip_full_check;
+
ret = mark_fastcall_patterns(env);
if (ret < 0)
goto skip_full_check;
@@ -22791,9 +23242,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
release_btfs(env);
err_free_env:
bpf_free_subprog_jts(env);
+ if (env->insn_aux_data)
+ bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
vfree(env->insn_aux_data);
kvfree(env->fd_array);
+ bpf_free_scev(env);
bpf_stack_liveness_free(env);
+ kvfree(env->cfg.postorder_nums);
kvfree(env->cfg.insn_postorder);
kvfree(env->scc_info);
kvfree(env->succ);
@@ -22801,6 +23256,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
kvfree(env->callx_edges);
kvfree(env->func_ptrs);
bpf_diag_free(env);
+ kvfree(env->idoms);
kvfree(env);
return ret;
}
diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c
index 8a6d341b754ac..2bc1ef910c16d 100644
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@ -19,12 +19,14 @@
#include "verifier_basic_stack.skel.h"
#include "verifier_bitfield_write.skel.h"
#include "verifier_bounds.skel.h"
+#include "verifier_bounds_step.skel.h"
#include "verifier_bounds_deduction.skel.h"
#include "verifier_bounds_deduction_non_const.skel.h"
#include "verifier_bounds_mix_sign_unsign.skel.h"
#include "verifier_bpf_get_stack.skel.h"
#include "verifier_bpf_trap.skel.h"
#include "verifier_bswap.skel.h"
+#include "verifier_btf_array_access.skel.h"
#include "verifier_btf_ctx_access.skel.h"
#include "verifier_btf_flex_array.skel.h"
#include "verifier_btf_unreliable_prog.skel.h"
@@ -55,6 +57,7 @@
#include "verifier_helper_packet_access.skel.h"
#include "verifier_helper_restricted.skel.h"
#include "verifier_helper_value_access.skel.h"
+#include "verifier_idoms.skel.h"
#include "verifier_int_ptr.skel.h"
#include "verifier_iterating_callbacks.skel.h"
#include "verifier_jeq_infer_not_null.skel.h"
@@ -71,6 +74,7 @@
#include "verifier_live_stack.skel.h"
#include "verifier_liveness_exp.skel.h"
#include "verifier_load_acquire.skel.h"
+#include "verifier_loop_hierarchy.skel.h"
#include "verifier_loops1.skel.h"
#include "verifier_lwt.skel.h"
#include "verifier_map_in_map.skel.h"
@@ -103,6 +107,7 @@
#include "verifier_ringbuf.skel.h"
#include "verifier_runtime_jit.skel.h"
#include "verifier_scalar_ids.skel.h"
+#include "verifier_scev.skel.h"
#include "verifier_sdiv.skel.h"
#include "verifier_search_pruning.skel.h"
#include "verifier_sock.skel.h"
@@ -203,12 +208,14 @@ void test_verifier_arena_globals2(void) { RUN(verifier_arena_globals2); }
void test_verifier_basic_stack(void) { RUN(verifier_basic_stack); }
void test_verifier_bitfield_write(void) { RUN(verifier_bitfield_write); }
void test_verifier_bounds(void) { RUN(verifier_bounds); }
+void test_verifier_bounds_step(void) { RUN(verifier_bounds_step); }
void test_verifier_bounds_deduction(void) { RUN(verifier_bounds_deduction); }
void test_verifier_bounds_deduction_non_const(void) { RUN(verifier_bounds_deduction_non_const); }
void test_verifier_bounds_mix_sign_unsign(void) { RUN(verifier_bounds_mix_sign_unsign); }
void test_verifier_bpf_get_stack(void) { RUN(verifier_bpf_get_stack); }
void test_verifier_bpf_trap(void) { RUN(verifier_bpf_trap); }
void test_verifier_bswap(void) { RUN(verifier_bswap); }
+void test_verifier_btf_array_access(void) { RUN(verifier_btf_array_access); }
void test_verifier_btf_ctx_access(void) { RUN(verifier_btf_ctx_access); }
void test_verifier_btf_flex_array(void) { RUN(verifier_btf_flex_array); }
void test_verifier_btf_unreliable_prog(void) { RUN(verifier_btf_unreliable_prog); }
@@ -239,6 +246,7 @@ void test_verifier_helper_access_var_len(void) { RUN(verifier_helper_access_var_
void test_verifier_helper_packet_access(void) { RUN(verifier_helper_packet_access); }
void test_verifier_helper_restricted(void) { RUN(verifier_helper_restricted); }
void test_verifier_helper_value_access(void) { RUN(verifier_helper_value_access); }
+void test_verifier_idoms(void) { RUN(verifier_idoms); }
void test_verifier_int_ptr(void) { RUN(verifier_int_ptr); }
void test_verifier_iterating_callbacks(void) { RUN(verifier_iterating_callbacks); }
void test_verifier_jeq_infer_not_null(void) { RUN(verifier_jeq_infer_not_null); }
@@ -255,6 +263,7 @@ void test_verifier_leak_ptr(void) { RUN(verifier_leak_ptr); }
void test_verifier_linked_scalars(void) { RUN(verifier_linked_scalars); }
void test_verifier_live_stack(void) { RUN(verifier_live_stack); }
void test_verifier_liveness_exp(void) { RUN(verifier_liveness_exp); }
+void test_verifier_loop_hierarchy(void) { RUN(verifier_loop_hierarchy); }
void test_verifier_loops1(void) { RUN(verifier_loops1); }
void test_verifier_lwt(void) { RUN(verifier_lwt); }
void test_verifier_map_in_map(void) { RUN(verifier_map_in_map); }
@@ -286,6 +295,7 @@ void test_verifier_regalloc(void) { RUN(verifier_regalloc); }
void test_verifier_ringbuf(void) { RUN(verifier_ringbuf); }
void test_verifier_runtime_jit(void) { RUN(verifier_runtime_jit); }
void test_verifier_scalar_ids(void) { RUN(verifier_scalar_ids); }
+void test_verifier_scev(void) { RUN(verifier_scev); }
void test_verifier_sdiv(void) { RUN(verifier_sdiv); }
void test_verifier_search_pruning(void) { RUN(verifier_search_pruning); }
void test_verifier_sock(void) { RUN(verifier_sock); }
diff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h
index f3dbc3b59bff2..d7f706c3bc4af 100644
--- a/tools/testing/selftests/bpf/progs/bpf_misc.h
+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h
@@ -43,6 +43,10 @@
* __msg_unpriv Same as __msg but for unprivileged mode.
* __not_msg_unpriv Same as __not_msg but for unprivileged mode.
*
+ * __msg_next Same as __msg but expects the match to be on the next
+ * __msg_next_unpriv log line compared to the last match, not just some line
+ * after the last match.
+ *
* __stderr Message expected to be found in bpf stderr stream. The
* same regex rules apply like __msg.
* __stderr_unpriv Same as __stderr but for unpriveleged mode.
@@ -145,6 +149,7 @@
#define __msg(msg) __test_tag("test_expect_msg=" msg)
#define __not_msg(msg) __test_tag("test_expect_not_msg=" msg)
+#define __msg_next(msg) __test_tag("test_expect_msg_next=" msg)
#define __xlated(msg) __test_tag("test_expect_xlated=" msg)
#define __jited(msg) __test_tag("test_jited=" msg)
#define __failure __test_tag("test_expect_failure")
@@ -153,6 +158,7 @@
#define __skip(reason) __test_tag("test_skip=" reason)
#define __msg_unpriv(msg) __test_tag("test_expect_msg_unpriv=" msg)
#define __not_msg_unpriv(msg) __test_tag("test_expect_not_msg_unpriv=" msg)
+#define __msg_next_unpriv(msg) __test_tag("test_expect_msg_next_unpriv=" msg)
#define __xlated_unpriv(msg) __test_tag("test_expect_xlated_unpriv=" msg)
#define __jited_unpriv(msg) __test_tag("test_jited_unpriv=" msg)
#define __failure_unpriv __test_tag("test_expect_failure_unpriv")
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
new file mode 100644
index 0000000000000..cb55fc216bc8a
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+/*
+ * Tests for the linear "base + step * k" description tracked per scalar
+ * register.
+ *
+ * The base/step computed by scalar arithmetic is observed directly in the
+ * level-2 register dump, printed as "step=<base>+<step>" when the register is
+ * not the trivial base=0, step=1. Range inference that depends on the line
+ * (e.g. a sign-crossing range with a non-power-of-2 step) is checked via the
+ * resulting smin/smax, which feed ordinary signed branch decisions.
+ *
+ * Note: eq/neq branch checks do not consult base/step, so impossible-value
+ * pruning is intentionally not relied upon here; the register dump is the
+ * reliable signal.
+ */
+
+/* a &= 0xff; a *= 3 => multiples of 3, step=0+3 (not representable as tnum) */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 *= 3 {{.*}}step=0+3)")
+__naked void step_mul_non_pow2(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 *= 3; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* a &= 0xff; a <<= 2 => step=0+4 */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 <<= 2 {{.*}}step=0+4)")
+__naked void step_lsh(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 <<= 2; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* a &= 0xff; a *= 4; a += 1 => base shifts to 1, step=1+4 */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 += 1 {{.*}}step=1+4)")
+__naked void step_add_const_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 *= 4; \
+ r0 += 1; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Sign-crossing range with a non-power-of-2 step. After "*= 3; += -3" the value
+ * set is {-3, 0, 3, 6}. The line description is tracked in signed space, so the
+ * intersection keeps smax=6. A u64-modular intersection would mis-place the
+ * line for the negative values and wrongly narrow smax to 4.
+ */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 += -3 {{.*}}smax=smax32=6)")
+__naked void step_neg_value_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r0 *= 3; \
+ r0 += -3; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Same {-3, 0, 3, 6} value set: 6 is reachable, so "if r0 s> 4" can be taken
+ * and the illegal scalar dereference behind it must be rejected. Guards against
+ * the unsound narrowing (smax=4) that would prune the branch and accept the
+ * program. This rides on the signed comparison, which uses smin/smax.
+ */
+SEC("socket")
+__failure __msg("invalid mem access 'scalar'")
+__naked void step_neg_value_sound(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r0 *= 3; \
+ r0 += -3; \
+ if r0 s> 4 goto l_bad_%=; \
+ r0 = 0; \
+ exit; \
+l_bad_%=: \
+ r1 = *(u8 *)(r0 + 0); \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+struct step_val {
+ __u8 data[1024];
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct step_val);
+} step_map SEC(".maps");
+
+/* Old register [4..130, step 2] should prune cur register [8..64, step 4]. */
+SEC("socket")
+__success __log_level(2)
+__msg("7: (27) r6 *= 4 ; R6=scalar({{.*}}umin32=8,{{.*}}umax32=68,{{.*}},step=0+4)")
+__msg("10: (27) r7 *= 2 ; R7=scalar({{.*}}umin32=4,{{.*}}umax32=130,{{.*}},step=0+2)")
+__msg("11: (25) if r0 > 0x2a goto pc+1")
+__msg("from 11 to 13: safe")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void step_prune_hit_multiple(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r6 &= 0x0f; \
+ r6 += 2; \
+ r6 *= 4; \
+ r7 &= 0x3f; \
+ r7 += 2; \
+ r7 *= 2; \
+ if r0 > 42 goto 1f; /* can't predict */ \
+ r6 = r7; /* step=2 explored first, step=4 explored next */ \
+1: r0 = r10; \
+ r6 = -r6; \
+ r0 += r6; \
+ *(u8 *)(r0 + 0) = 7; /* force r6 precise */ \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+/* Old register [0..126, step 2] should not prune cur register [0..45, step 3]. */
+SEC("socket")
+__failure __log_level(2)
+__msg("6: (27) r6 *= 3 ; R6=scalar({{.*}}smin32=0,{{.*}}umax32=45,{{.*}},step=0+3)")
+__msg("8: (27) r7 *= 2 ; R7=scalar({{.*}}smin32=0,{{.*}}umax32=126,{{.*}},step=0+2)")
+__msg("9: (25) if r0 > 0x2a goto pc+1")
+__msg("11: (15) if r6 == 0x3 goto pc+2")
+__msg("11: R6=scalar({{.*}},step=0+2)")
+__msg("13: (95) exit")
+__msg("from 9 to 11: {{.*}} R6=scalar({{.*}},step=0+3)")
+__msg("from 11 to 14")
+__msg("div by zero")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void step_prune_miss_non_multiple(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r6 &= 0x0f; \
+ r6 *= 3; \
+ r7 &= 0x3f; \
+ r7 *= 2; \
+ if r0 > 42 goto 1f; /* can't predict */ \
+ r6 = r7; /* step=2 explored first, step=3 explored next */ \
+1: \
+ if r6 == 3 goto 2f; /* false if step=2, should not prune step=3 */ \
+ r0 = 0; \
+ exit; \
+2: \
+ r0 /= 0; /* trap */ \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Constant current register lying on the cached line: cached is {0,3,6,...}
+ * (step 3, base 0), current is the constant 6. range_within() takes the
+ * constant branch: imod(6, 3) == base 0, so cur is on the line and the
+ * (precise) state is pruned -> "safe".
+ */
+SEC("socket")
+__success __log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("14: (27) r1 *= 3") /* cached path: step 3 line */
+__msg("16: (b7) r1 = 6") /* current path: const 6, on the line */
+__msg("17: safe") /* pruned at join: imod(6, 3) == 0 */
+__naked void step_prune_hit_const_on_line(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r1 = 0; \
+ *(u32*)(r10 - 4) = r1; \
+ r2 = r10; \
+ r2 += -4; \
+ r1 = %[step_map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto l_out_%=; \
+ r7 = r0; \
+ r1 = r6; \
+ r1 &= 0xff; \
+ if r6 > 0 goto l_cur_%=; \
+ r1 *= 3; /* old: step 3 */ \
+ goto l_join_%=; \
+l_cur_%=: \
+ r1 = 6; /* cur: const on line */ \
+l_join_%=: \
+ r0 = r7; \
+ r0 += r1; /* r1 forced precise */ \
+ r2 = *(u8 *)(r0 + 0); \
+l_out_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+/*
+ * Constant current register NOT on the cached line: cached is {0,3,6,...}
+ * (step 3, base 0), current is the constant 7. imod(7, 3) == 1 != base 0,
+ * so range_within() fails and the join is traversed again. A power-of-two
+ * step is avoided on purpose: with step 3 the tnum is loose enough to admit
+ * 7, so imod() is
+ * the sole check that rejects it. No failure shape is possible here: 7 is
+ * within the line's bounds and tnum, and the cached line path already
+ * verifies the whole outro, so an eager prune could not miss an error.
+ */
+SEC("socket")
+__success __log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("14: (27) r1 *= 3") /* cached path: step 3 line */
+__msg("16: (b7) r1 = 7") /* current path: const 7, off the line */
+/* not pruned: current continues past the join with the constant offset 7 */
+__msg("19: R0=map_value({{.*}}imm=7) R1=7")
+__naked void step_prune_miss_const_off_line(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r1 = 0; \
+ *(u32*)(r10 - 4) = r1; \
+ r2 = r10; \
+ r2 += -4; \
+ r1 = %[step_map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto l_out_%=; \
+ r7 = r0; \
+ r1 = r6; \
+ r1 &= 0xff; \
+ if r6 > 0 goto l_cur_%=; \
+ r1 *= 3; /* old: step 3 */ \
+ goto l_join_%=; \
+l_cur_%=: \
+ r1 = 7; /* cur: const off line */ \
+l_join_%=: \
+ r0 = r7; \
+ r0 += r1; /* r1 forced precise */ \
+ r2 = *(u8 *)(r0 + 0); \
+l_out_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c
new file mode 100644
index 0000000000000..ab6b744573657
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c
@@ -0,0 +1,506 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_core_read.h>
+#include "bpf_experimental.h"
+#include "bpf_misc.h"
+
+/*
+ * Variable-offset access into arrays within a BTF access chain, e.g. a[i].b,
+ * where 'i' is a register with a varying offset. The register's step has to
+ * match the stride of one of the arrays crossed while walking the access
+ * chain, and the maximal possible offset has to stay within that array.
+ *
+ * A program-allocated object (bpf_obj_new) is used as the source of a
+ * PTR_TO_BTF_ID with a shape we fully control.
+ */
+struct inner {
+ int a;
+ int b;
+};
+
+struct outer {
+ struct inner arr[8]; /* off 0, stride 8, size 64 */
+ char bytes[32]; /* off 64, stride 1, size 32 */
+ long longs[8]; /* off 96, stride 8, size 64 */
+ int grid[4][4]; /* off 160, 16 ints, size 64 */
+};
+
+/* arr[i].b, i in [0, 7], 4-byte read: stays within arr. */
+SEC("syscall")
+__success
+int arr_field_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* arr[i].b, i in [0, 15]: max offset runs past the end of arr. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int arr_field_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* longs[i], i in [0, 7], 8-byte read: scalar array with stride 8. */
+SEC("syscall")
+__success
+int long_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 96); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * bytes[i], i in [0, 31], read as 4 bytes: min_off is valid within the array,
+ * but the 4-byte read at max_off runs past the array end. Exercises the
+ * size-aware bound in btf_struct_access().
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int byte_array_size_spanning(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 64); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* bytes[i], i in [0, 31], 1-byte read: step 1 matches the char array stride. */
+SEC("syscall")
+__success
+int byte_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 64); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * arr[] accessed with step 4 (half of sizeof(struct inner)): the step is not
+ * a whole number of elements, so no crossed array has a matching stride.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int arr_unaligned_step(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * grid[i][0], i in [0, 3]: steps along the outer dimension of a 2D array
+ * (stride 16). __btf_resolve_size() linearizes the array; the step is a
+ * multiple of the innermost element size (4).
+ */
+SEC("syscall")
+__success
+int grid_outer_dim(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 3; \
+ r2 *= 16; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 160); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * grid[0][i], i in [0, 3]: steps along the inner dimension of a 2D array
+ * (stride 4, the innermost element size).
+ */
+SEC("syscall")
+__success
+int grid_inner_dim(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 3; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 160); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * An array of pointers within a program-allocated object. Reading a pointer
+ * member of a local object yields a SCALAR_VALUE, but the varying offset still
+ * has to be validated against the array bounds.
+ */
+struct with_ptrs {
+ struct inner *parr[8]; /* off 0, stride 8 (sizeof ptr), size 64 */
+};
+
+/* parr[i], i in [0, 7], 8-byte read: stays within parr. */
+SEC("syscall")
+__success
+int ptr_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct with_ptrs *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * parr[i], i in [0, 15]: max offset runs past the end of parr. Without the
+ * variable-offset check on the WALK_PTR path this would be wrongly accepted.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct with_ptrs")
+int ptr_array_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct with_ptrs *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * The cases above all use bpf_obj_new() (PTR_TO_BTF_ID | MEM_ALLOC). Exercise
+ * the trusted kernel-BTF path too, using a task_struct from
+ * bpf_get_current_task_btf() and its embedded char comm[] array. The comm
+ * offset is folded into the pointer as a constant before the varying index.
+ */
+
+/* task->comm[i], i in [0, 15], 1-byte read: stays within comm. */
+SEC("syscall")
+__success
+int kernel_btf_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct task_struct *task;
+ int val = 0;
+
+ task = bpf_get_current_task_btf();
+ asm volatile (" \
+ r1 = %[task]; \
+ r1 += %[off]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [task] "r"(task), [i] "r"(i),
+ [off] "i"(offsetof(struct task_struct, comm))
+ : "r1", "r2");
+ return val;
+}
+
+/* task->comm[i], i in [0, 31]: max offset runs past comm. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct task_struct")
+int kernel_btf_array_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct task_struct *task;
+ int val = 0;
+
+ task = bpf_get_current_task_btf();
+ asm volatile (" \
+ r1 = %[task]; \
+ r1 += %[off]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [task] "r"(task), [i] "r"(i),
+ [off] "i"(offsetof(struct task_struct, comm))
+ : "r1", "r2");
+ return val;
+}
+
+/*
+ * Array nested below a struct member at a non-zero offset. The walk descends
+ * through 'm' (resetting the running offset) before reaching 'arr', exercising
+ * the array_start = min_off - arrays[i].off telescoping across a WALK_STRUCT
+ * dive.
+ */
+struct mid {
+ struct inner arr[8]; /* stride 8, size 64 */
+};
+
+struct nest {
+ long pad; /* off 0 */
+ struct mid m; /* off 8 */
+};
+
+/* m.arr[i].b, i in [0, 7], 4-byte read: stays within m.arr. */
+SEC("syscall")
+__success
+int nested_struct_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct nest *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 12); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* m.arr[i].b, i in [0, 15]: max offset runs past the end of m.arr. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct nest")
+int nested_struct_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct nest *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 12); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * A trailing flexible array member makes the struct tail an unbounded region,
+ * so a varying access into it has no upper bound to exceed (mirrors how
+ * unix_address.name[] is accessed via sun_path[i]).
+ *
+ * A custom (program) BTF struct can only be reached as a PTR_TO_BTF_ID through
+ * bpf_obj_new(), which does not allow flexible array members. So use a kernel
+ * type via an untrusted PTR_TO_BTF_ID (bpf_core_cast()). struct vring_used ends
+ * with a flexible array 'ring[]' of struct vring_used_elem { __virtio32 id, len; },
+ * mirroring a 'struct foo { int a; int b; }' flexible array.
+ */
+
+/* ring[i].len, i in [0, 63], 4-byte read: the flexible array has no upper bound. */
+SEC("syscall")
+__success
+int flex_array_field(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct vring_used *o;
+ int val = 0;
+
+ o = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 63; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 8); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ return val;
+}
+
+/*
+ * ring[] accessed with step 4 (half of sizeof(struct vring_used_elem)): the
+ * step is not a whole number of elements, so the flexible array stride does
+ * not match.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct vring_used")
+int flex_array_unaligned_step(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct vring_used *o;
+ int val = 0;
+
+ o = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ return val;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_gotox.c b/tools/testing/selftests/bpf/progs/verifier_gotox.c
index f5a9878c7b8d4..03a3bee212361 100644
--- a/tools/testing/selftests/bpf/progs/verifier_gotox.c
+++ b/tools/testing/selftests/bpf/progs/verifier_gotox.c
@@ -509,7 +509,7 @@ __naked void too_many_gotox_edges(void)
SEC("socket")
__description("gotox-edges-at-limit")
-__success __retval(0)
+__failure __msg("Too many nested loops")
__naked void gotox_edges_at_limit(void)
{
asm volatile (
@@ -517,6 +517,10 @@ __naked void gotox_edges_at_limit(void)
* 1000 gotox * 1000 targets = 1,000,000 CFG edges. At run
* time, each block loads the next table entry and jumps to
* the following block, so the program terminates.
+ *
+ * Every block can jump to every later block, so the CFG is
+ * a nest of ~1000 irreducible loops, deeper than the
+ * verifier's loop stack; the program is rejected.
*/
GOTOX_TABLE_BEGIN(1000)
".rept 1000;"
diff --git a/tools/testing/selftests/bpf/progs/verifier_idoms.c b/tools/testing/selftests/bpf/progs/verifier_idoms.c
new file mode 100644
index 0000000000000..a29d6332baa4f
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_idoms.c
@@ -0,0 +1,390 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "../../../include/linux/filter.h"
+
+/*
+ * kernel/bpf/loops.c:bpf_compute_idoms() computes the immediate dominator
+ * of every instruction (Cooper et al, "A Simple, Fast Dominance Algorithm").
+ *
+ * The immediate dominator is printed by log_program() as the numeric column
+ * immediately before the "<insn#>:" field of every "Program dump" line:
+ *
+ * Program dump (scc? loop_header? idom insn#: live_regs_before):
+ * -1 0: ....... (b7) r0 = 0 <- idom(0) = -1 (subprog entry)
+ * 0 1: ....... (07) r0 += 1 <- idom(1) = 0
+ * ^^^^^^
+ * idom insn#
+ *
+ * The __msg() patterns below wildcard the scc/loop_header/live_regs columns and
+ * anchor on "<idom> <insn#>:" followed by the disassembled instruction, so
+ * they assert the idom value of each instruction.
+ */
+
+/*
+ * Straight-line code, with an ldimm64 in the middle. Instruction index 2 is
+ * the second half of the ldimm64 at index 1 and is not a CFG node; the idom of
+ * index 3 must be 1, not 2. Exercises the bpf_is_ldimm64() skip in both passes
+ * of compute_predecessors().
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (18) r1 = 0x1122334455667788")
+__msg("{{.*}} 1 3: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 3 4: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 4 5: {{.*}} (95) exit")
+__naked void straight_line_ldimm64(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r1 = 0x1122334455667788 ll; \
+ r0 += 1; \
+ r0 += r1; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Asymmetric if-then-else diamond: the "then" arm is 5 instructions long, the
+ * "else" arm is a single instruction. The merge point (insn 8) is dominated by
+ * the branch (insn 1), not by either arm. This forces idoms_intersect() to walk
+ * the two predecessors up unequal postorder depths before they meet.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (25) if r0 > 0x0 goto pc+5")
+__msg("{{.*}} 1 2: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 2 3: {{.*}} (b7) r1 = 2")
+__msg("{{.*}} 3 4: {{.*}} (b7) r1 = 3")
+__msg("{{.*}} 4 5: {{.*}} (b7) r1 = 4")
+__msg("{{.*}} 5 6: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 1 7: {{.*}} (b7) r1 = 9")
+__msg("{{.*}} 1 8: {{.*}} (95) exit")
+__naked void asymmetric_diamond(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r1 = 1; \
+ r1 = 2; \
+ r1 = 3; \
+ r1 = 4; \
+ goto 2f; \
+1: r1 = 9; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Simple loop: the header (insn 1) is dominated by the pre-header (insn 0). The
+ * back edge (insn 2 -> insn 1) must not change idom(1); the back-edge
+ * predecessor folds up via idoms_intersect().
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg("{{.*}} 2 3: {{.*}} (95) exit")
+__naked void simple_loop(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Loop with an if-else in its body. The in-loop merge point (insn 5) is
+ * dominated by the in-loop branch (insn 3), combining a back-edge intersect
+ * with a forward-diamond intersect.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (bf) r1 = r0")
+__msg("{{.*}} 2 3: {{.*}} (25) if r1 > 0x5 goto pc+1")
+__msg("{{.*}} 3 4: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 3 5: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 5 6: {{.*}} (a5) if r0 < 0x64 goto pc-6")
+__msg("{{.*}} 6 7: {{.*}} (95) exit")
+__naked void loop_with_if_else_body(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = r0; \
+ if r1 > 5 goto 2f; \
+ r1 = 1; \
+2: r0 += r1; \
+ if r0 < 100 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Nested loops: the idom chain runs inner-header -> outer-body -> outer-header
+ * -> pre-header. Exercises intersect across back edges at two nesting depths.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 2 3: {{.*}} (07) r1 += 1")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2")
+__msg("{{.*}} 4 5: {{.*}} (a5) if r0 < 0xa goto pc-5")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__naked void nested_loops(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Loop header (insn 1) with two back edges (from insn 4 and insn 5), i.e. three
+ * predecessors. Both back edges route through the incrementing header, so the
+ * loop is bounded and verifies. Repeated idoms_intersect() at the header must
+ * stay stable and keep idom(1) at the pre-header (insn 0).
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r6 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r6 += 1")
+__msg("{{.*}} 1 2: {{.*}} (25) if r6 > 0xa goto pc+3")
+__msg("{{.*}} 2 3: {{.*}} (bf) r7 = r6")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r7 < 0x5 goto pc-4")
+__msg("{{.*}} 4 5: {{.*}} (05) goto pc-5")
+__msg("{{.*}} 2 6: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 6 7: {{.*}} (95) exit")
+__naked void multi_backedge_header(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: r6 += 1; \
+ if r6 > 10 goto 2f; \
+ r7 = r6; \
+ if r7 < 5 goto 1b; \
+ goto 1b; \
+2: r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Irreducible CFG (loop with two entries, insn 3 and insn 5, reached from the
+ * insn 2 branch). Dominators remain well-defined; this is a convergence test
+ * for the fixpoint under irreducibility. Note insn 6 is dominated by the branch
+ * (insn 2), not by either arm.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 1 2: {{.*}} (25) if r0 > 0x5 goto pc+2")
+__msg("{{.*}} 2 3: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 3 4: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 2 5: {{.*}} (b7) r1 = 2")
+__msg("{{.*}} 2 6: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 6 7: {{.*}} (a5) if r0 < 0x10 goto pc-5")
+__msg("{{.*}} 7 8: {{.*}} (95) exit")
+__naked void irreducible(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+ if r0 > 5 goto 2f; \
+1: r1 = 1; \
+ goto 3f; \
+2: r1 = 2; \
+3: r0 += r1; \
+ if r0 < 16 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Idoms are computed per subprog. Layout (libbpf preorder) is:
+ * main: 0..1, sub: 2..7
+ * The callee entry (insn 2) must have idom -1 (subprog reset), and idoms inside
+ * the callee must reference only the callee's instructions, never main's. The
+ * in-callee merge (insn 7) is dominated by the in-callee branch (insn 3). The
+ * branch is on a prandom value so it is not constant-folded away.
+ */
+static __naked __noinline __used
+unsigned long idoms_diamond_sub(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r0 = 1; \
+ goto 2f; \
+1: r0 = 2; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call pc+1")
+__msg("{{.*}} 0 1: {{.*}} (95) exit")
+__msg("{{.*}} -1 2: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 2 3: {{.*}} (25) if r0 > 0x0 goto pc+2")
+__msg("{{.*}} 3 4: {{.*}} (b7) r0 = 1")
+__msg("{{.*}} 4 5: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 3 6: {{.*}} (b7) r0 = 2")
+__msg("{{.*}} 3 7: {{.*}} (95) exit")
+__naked void multi_subprog(void)
+{
+ asm volatile (" \
+ call idoms_diamond_sub; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * The first instruction of a subprog (insn 3) is itself a loop header, i.e. it
+ * has an incoming back edge. Its idom must still be -1 (the subprog entry has no
+ * dominator). Exercises the idoms[start]=0 ... idoms[start]=-1 handling in
+ * compute_subprog_idoms().
+ */
+static __naked __noinline __used
+unsigned long idoms_entry_header_sub(void)
+{
+ asm volatile (" \
+1: r1 += 1; \
+ if r1 < 10 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 0 1: {{.*}} (85) call pc+1")
+__msg("{{.*}} 1 2: {{.*}} (95) exit")
+__msg("{{.*}} -1 3: {{.*}} (07) r1 += 1")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r1 < 0xa goto pc-2")
+__msg("{{.*}} 4 5: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__naked void entry_is_loop_header(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ call idoms_entry_header_sub; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Self-loop: insn 1 is its own predecessor. idom(1) must be the pre-header
+ * (insn 0); the self-edge is ignored (idoms[pred] == -1 on the first pass, then
+ * idoms_intersect(a == b) short-circuits). Program is rejected later for an
+ * infinite loop, but the dump (and idoms) are printed before that.
+ */
+SEC("socket")
+__failure
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (a5) if r0 < 0xa goto pc-1")
+__msg("{{.*}} 1 2: {{.*}} (95) exit")
+__msg("infinite loop detected")
+__naked void self_loop(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+1: if r0 < 10 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+#if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) || defined(__TARGET_ARCH_powerpc)
+/*
+ * Indirect jump (gotox) with a two-entry jump table. The gotox (insn 4) has two
+ * successors (insn 5 and insn 7), so both targets have the gotox as their only
+ * predecessor and idom. Also re-exercises the ldimm64 skip: insn 2's idom is 0,
+ * the ldimm64 at index 0 (index 1 is its second half).
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (18) r0 = {{0x[0-9a-f]+}}")
+__msg("{{.*}} 0 2: {{.*}} (07) r0 += 8")
+__msg("{{.*}} 2 3: {{.*}} (79) r0 = *(u64 *)(r0 +0)")
+__msg("{{.*}} 3 4: {{.*}} (0d) gotox r0")
+__msg("{{.*}} 4 5: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__msg("{{.*}} 4 7: {{.*}} (b7) r0 = 1")
+__msg("{{.*}} 7 8: {{.*}} (95) exit")
+__naked void gotox_jump_table(void)
+{
+ asm volatile (" \
+ .pushsection .jumptables,\"\",@progbits; \
+jt0_%=: \
+ .quad ret0_%= - socket; \
+ .quad ret1_%= - socket; \
+ .size jt0_%=, 16; \
+ .global jt0_%=; \
+ .popsection; \
+ \
+ r0 = jt0_%= ll; \
+ r0 += 8; \
+ r0 = *(u64 *)(r0 + 0); \
+ .8byte %[gotox_r0]; \
+ret0_%=: \
+ r0 = 0; \
+ exit; \
+ret1_%=: \
+ r0 = 1; \
+ exit; \
+" :
+ : __imm_insn(gotox_r0, BPF_RAW_INSN(BPF_JMP | BPF_JA | BPF_X, BPF_REG_0, 0, 0, 0))
+ : __clobber_all);
+}
+#endif
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
index 16b2b1e575342..496229a9b284c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
@@ -61,8 +61,12 @@ __naked void read_write_join(void)
SEC("socket")
__log_level(2)
__msg("stack use/def subprog#0 must_write_not_same_slot (d0,cs0):")
-__msg("6: (7b) *(u64 *)(r2 +0) = r0{{$}}")
-__msg("Live regs before insn:")
+/*
+ * 'r2 += r1' adds a scalar, so the offset is lost (off_cnt == 0): no def,
+ * but the write conservatively marks the whole frame as may_def.
+ */
+__msg("6: (7b) *(u64 *)(r2 +0) = r0 ; may_def: fp0-8..-{{(512|2048)}}")
+__msg("Program dump")
__naked void must_write_not_same_slot(void)
{
asm volatile (
@@ -79,6 +83,31 @@ __naked void must_write_not_same_slot(void)
: __clobber_all);
}
+SEC("socket")
+__log_level(2)
+__msg("stack use/def subprog#0 may_write_two_precise_offsets (d0,cs0):")
+/*
+ * r1 is fp-8 or fp-16, with both offsets tracked precisely (off_cnt == 2).
+ * A write through it cannot set def, but marks both candidate slots as may_def.
+ */
+__msg("6: (7b) *(u64 *)(r1 +0) = r0 ; may_def: fp0-8 fp0-16")
+__naked void may_write_two_precise_offsets(void)
+{
+ asm volatile (
+ "call %[bpf_get_prandom_u32];"
+ "r1 = r10;"
+ "if r0 > 42 goto 1f;"
+ "r1 += -8;"
+ "goto 2f;"
+"1:"
+ "r1 += -16;"
+"2:"
+ "*(u64 *)(r1 + 0) = r0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__log_level(2)
__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8")
@@ -106,11 +135,11 @@ __naked void must_write_not_same_type(void)
SEC("socket")
__log_level(2)
-/* Callee writes fp[0]-8: stack_use at call site has slots 0,1 live */
+/* Callee writes fp[0]-8: the def is summarized as may_def at the call site */
__msg("stack use/def subprog#0 caller_stack_write (d0,cs0):")
-__msg("2: (85) call pc+1{{$}}")
+__msg("2: (85) call pc+1 ; may_def: fp0-8")
__msg("stack use/def subprog#1 write_first_param (d1,cs2):")
-__msg("4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8")
+__msg("4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8 may_def: fp0-8")
__naked void caller_stack_write(void)
{
asm volatile (
@@ -130,6 +159,49 @@ static __used __naked void write_first_param(void)
::: __clobber_all);
}
+/*
+ * Cross-frame imprecise write: imprecise_frame_writer() receives a pointer
+ * into the caller's frame (frame 0) but conditionally replaces it with a
+ * pointer into its own frame (frame 1). At the store the two are joined into
+ * ARG_IMPRECISE (frame is unknown, mask = {0,1}), so the offset is dropped and
+ * the whole of both candidate frames is conservatively marked as may_def.
+ */
+SEC("socket")
+__log_level(2)
+/* The callee's write into the caller frame is summarized at the call site. */
+__msg("stack use/def subprog#0 imprecise_frame_write (d0,cs0):")
+__msg("2: (85) call pc+2 ; may_def: fp0-8..-{{(512|2048)}}")
+__msg("stack use/def subprog#1 imprecise_frame_writer (d1,cs2):")
+__msg("12: (7b) *(u64 *)(r1 +0) = r2 ; may_def: fp1-8..-{{(512|2048)}} fp0-8..-{{(512|2048)}}")
+__naked void imprecise_frame_write(void)
+{
+ asm volatile (
+ "r1 = r10;"
+ "r1 += -8;"
+ "call imprecise_frame_writer;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void imprecise_frame_writer(void)
+{
+ asm volatile (
+ "r6 = r1;" /* save arg: pointer into frame 0 */
+ "call %[bpf_get_prandom_u32];"
+ "r1 = r6;" /* r1 = frame0-8 (arg) */
+ "if r0 == 0 goto 1f;"
+ "r1 = r10;"
+ "r1 += -8;" /* r1 = frame1-8 (own frame) */
+"1:"
+ "r2 = 0;"
+ "*(u64 *)(r1 + 0) = r2;" /* join frame0-8 | frame1-8 -> imprecise */
+ "r0 = 0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__log_level(2)
__msg("stack use/def subprog#0 caller_stack_read (d0,cs0):")
@@ -804,7 +876,7 @@ void __kfunc_btf_root(void)
*/
SEC("socket")
__success __log_level(2)
-__msg(" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24{{$}}")
+__msg(" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24 may_def: fp0-24{{$}}")
__msg(" 9: (85) call bpf_iter_num_next{{.*}} ; use: fp0-24{{$}}")
__msg("14: (85) call bpf_iter_num_destroy{{.*}} ; use: fp0-24{{$}}")
__naked void kfunc_iter_stack_liveness(void)
@@ -1007,8 +1079,9 @@ __naked void four_byte_read_upper_half(void)
*/
SEC("socket")
__log_level(2)
-__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8")
-__msg("1: (6a) *(u16 *)(r10 -4) = 0{{$}}")
+__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8 may_def: fp0-8")
+/* 2-byte write only partially covers the upper half: may_def, but no def. */
+__msg("1: (6a) *(u16 *)(r10 -4) = 0 ; may_def: fp0-4h")
__msg("2: (61) r0 = *(u32 *)(r10 -4) ; use: fp0-4h")
__naked void two_byte_write_no_kill(void)
{
@@ -1355,9 +1428,12 @@ __naked void fp_spill_loses_precision_kills_liveness(void)
*/
SEC("socket")
__log_level(2)
-/* fp-8 live at call (callee conditionally writes → slot not killed) */
-__msg("1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8")
-__msg("4: (85) call pc+2{{$}}")
+/*
+ * fp-8 live at call: callee conditionally writes it, so the slot is not killed
+ * (no def), but the conditional write surfaces as may_def at the call site.
+ */
+__msg("1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8 may_def: fp0-8")
+__msg("4: (85) call pc+2 ; may_def: fp0-8")
__msg("5: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
__naked void conditional_stx_in_subprog(void)
{
@@ -2385,8 +2461,27 @@ __flag(BPF_F_TEST_STATE_FREQ)
__msg("subprog#2 write_first_read_second:")
__msg("17: (7a) *(u64 *)(r1 +0) = 42{{$}}")
__msg("18: (79) r0 = *(u64 *)(r2 +0) // r1=fp0-8 r2=fp0-16{{$}}")
+/*
+ * The callee's write into the caller frame is summarized as may_def at the
+ * call sites, transitively across both frames (depth 2 -> 1 -> 0). The two
+ * call sites differ because the shared write_first_read_second instance
+ * accumulates the cross-pass union ({fp-8, fp-16}) at different points
+ * relative to each forwarding_rw's summarization.
+ */
+__msg("stack use/def subprog#0 shared_instance_must_write_overwrite (d0,cs0):")
+__msg("7: (85) call pc+7 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16")
+__msg("12: (85) call pc+2 ; use: fp0-8 may_def: fp0-16")
+__msg("stack use/def subprog#1 forwarding_rw (d1,cs7):")
+__msg("15: (85) call pc+1 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16")
+__msg("stack use/def subprog#1 forwarding_rw (d1,cs12):")
+__msg("15: (85) call pc+1 ; use: fp0-8 may_def: fp0-16")
__msg("stack use/def subprog#2 write_first_read_second (d2,cs15):")
-__msg("17: (7a) *(u64 *)(r1 +0) = 42{{$}}")
+/*
+ * Shared across two callsites with swapped args (r1 is fp-8 on one pass,
+ * fp-16 on the other): must_write intersects to empty (no def), may_write
+ * unions to both slots.
+ */
+__msg("17: (7a) *(u64 *)(r1 +0) = 42 ; may_def: fp0-8 fp0-16")
__msg("18: (79) r0 = *(u64 *)(r2 +0) ; use: fp0-8 fp0-16")
__naked void shared_instance_must_write_overwrite(void)
{
@@ -2428,6 +2523,65 @@ static __used __naked void write_first_read_second(void)
::: __clobber_all);
}
+/*
+ * merge_instances() must preserve may_write when one pass doesn't touch a frame.
+ * mvs_leaf is reached through a single callsite (mvs_mid) from two outer chains,
+ * so it is one shared (depth,callsite) instance analyzed twice and merged:
+ * - chain A passes r2 = map value, mvs_leaf's doesn't touch stack;
+ * - chain B passes r2 = caller stack slot fp-8.
+ * The merge must keep the stack pass's may_write even though the map pass left
+ * frame 0 untouched.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("stack use/def subprog#2 mvs_leaf (d2,cs19):")
+__msg("21: (7a) *(u64 *)(r2 +0) = 42 ; may_def: fp0-8")
+__naked void merge_preserves_may_write(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 24) = r1;" /* map key */
+ "r1 = %[map] ll;"
+ "r2 = r10;"
+ "r2 += -24;"
+ "call %[bpf_map_lookup_elem];"
+ "if r0 == 0 goto 1f;"
+ /* chain A: r2 = map value (ARG_NONE, not stack) */
+ "r1 = r10;"
+ "r1 += -16;" /* unused fp anchor */
+ "r2 = r0;"
+ "call mvs_mid;"
+ /* chain B: r2 = caller stack slot fp-8 */
+ "r1 = r10;"
+ "r1 += -16;"
+ "r2 = r10;"
+ "r2 += -8;"
+ "call mvs_mid;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ : : __imm(bpf_map_lookup_elem), __imm_addr(map)
+ : __clobber_all);
+}
+
+static __used __naked void mvs_mid(void)
+{
+ asm volatile (
+ "call mvs_leaf;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void mvs_leaf(void)
+{
+ asm volatile (
+ "*(u64 *)(r2 + 0) = 42;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
/*
* Shared must_write when (callsite, depth) instance is reused.
* Main calls fwd_to_stale_wr at two sites. fwd_to_stale_wr calls
@@ -2512,6 +2666,32 @@ __naked void load_acquire_dont_clear_dst(void)
#endif /* CAN_USE_LOAD_ACQ_STORE_REL */
+SEC("socket")
+__log_level(2)
+__success
+__msg("lock *(u64 *)(r10 -8) += r1{{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__naked void atomic_rmw(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ ".8byte %[atomic_add];"
+ ".8byte %[atomic_fetch_add];"
+ ".8byte %[atomic_xchg];"
+ "r0 = 0;"
+ ".8byte %[atomic_cmpxchg];"
+ "exit;"
+ :
+ : __imm_insn(atomic_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_fetch_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD | BPF_FETCH, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_xchg, BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_cmpxchg, BPF_ATOMIC_OP(BPF_DW, BPF_CMPXCHG, BPF_REG_10, BPF_REG_1, -8))
+ : __clobber_all);
+}
+
SEC("socket")
__success
__naked void imprecise_fill_loses_cross_frame(void)
@@ -2848,8 +3028,9 @@ static __used __naked void imprecise_dst_spill_join_sub(void)
SEC("socket")
__log_level(2)
__msg("0: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
-__msg("1: (73) *(u8 *)(r10 -1) = r0{{$}}")
-__msg("2: (6b) *(u16 *)(r10 -4) = r0{{$}}")
+/* narrow stores define nothing, but they may write the half-slot they touch */
+__msg("1: (73) *(u8 *)(r10 -1) = r0 ; may_def: fp0-4h")
+__msg("2: (6b) *(u16 *)(r10 -4) = r0 ; may_def: fp0-4h")
__msg("3: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
__naked void narrow_store_defines_nothing(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c
new file mode 100644
index 0000000000000..5c5bf5b445290
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c
@@ -0,0 +1,317 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+/*
+ * kernel/bpf/loops.c:compute_loops() distinguish between
+ * the following cases:
+ * - B: backedge -> simple loop
+ * - C: cross edge to non-loop node -> no-op
+ * - D: edge to node whose header is in DFS path -> nested loop
+ * - E: edge to node whose header is NOT in DFS path -> irreducible
+ *
+ * Below test cases cover the above branches in various combinations.
+ */
+
+/* Case B: single bounded loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg(" 2 3: {{.*}} (95) exit")
+__naked void loop_single(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case B: two independent loops at the same nesting level. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 4{{$}}")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 2 0 1: {{.*}} (07) r0 += 1")
+__msg(" 2 1 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg(" 2 3: {{.*}} (b7) r1 = 0")
+__msg(" 1 3 4: {{.*}} (07) r1 += 1")
+__msg(" 1 4 4 5: {{.*}} (a5) if r1 < 0xa goto pc-2")
+__msg(" 5 6: {{.*}} (95) exit")
+__naked void loop_two_independent(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 10 goto 2b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case B + D: nested loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1") /* outer loop header */
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0") /* outer loop insn */
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1") /* inner loop header */
+__msg(" 1 3 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2") /* inner loop insn */
+__msg(" 1 1 4 5: {{.*}} (a5) if r0 < 0xa goto pc-5") /* outer loop insn */
+__msg(" 5 6: {{.*}} (95) exit")
+__naked void loop_nested(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case C: forward edges, no loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (85) call bpf_get_prandom_u32")
+__msg(" 0 1: {{.*}} (25) if r0 > 0x0 goto pc+2")
+__msg(" 1 2: {{.*}} (b7) r0 = 2")
+__msg(" 2 3: {{.*}} (05) goto pc+1")
+__msg(" 1 4: {{.*}} (b7) r0 = 3")
+__msg(" 1 5: {{.*}} (95) exit")
+__naked void fwd_edges_no_loop(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r0 = 2; \
+ goto 2f; \
+1: r0 = 3; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* Case B + D: two sibling inner loops within one outer loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("loop at 6, nested in 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0")
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1")
+__msg(" 1 3 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2")
+__msg(" 1 1 4 5: {{.*}} (b7) r2 = 0")
+__msg(" 1 1 5 6: {{.*}} (07) r2 += 1")
+__msg(" 1 6 6 7: {{.*}} (a5) if r2 < 0x5 goto pc-2")
+__msg(" 1 1 7 8: {{.*}} (a5) if r0 < 0xa goto pc-8")
+__msg(" 8 9: {{.*}} (95) exit")
+__naked void loop_nested_siblings(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 5 goto 3b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Three levels of nesting. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("loop at 5, nested in 3")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0")
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1")
+__msg(" 1 3 3 4: {{.*}} (b7) r2 = 0")
+__msg(" 1 3 4 5: {{.*}} (07) r2 += 1")
+__msg(" 1 5 5 6: {{.*}} (a5) if r2 < 0x3 goto pc-2")
+__msg(" 1 3 6 7: {{.*}} (a5) if r1 < 0x5 goto pc-5")
+__msg(" 1 1 7 8: {{.*}} (a5) if r0 < 0xa goto pc-8")
+__msg(" 8 9: {{.*}} (95) exit")
+__naked void loop_three_levels(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 3 goto 3b; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Loop with an if-else body (forward branch inside loop, Case C). */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (bf) r1 = r0")
+__msg(" 1 1 2 3: {{.*}} (25) if r1 > 0x5 goto pc+1")
+__msg(" 1 1 3 4: {{.*}} (b7) r1 = 1")
+__msg(" 1 1 3 5: {{.*}} (0f) r0 += r1")
+__msg(" 1 1 5 6: {{.*}} (a5) if r0 < 0x64 goto pc-6")
+__msg(" 6 7: {{.*}} (95) exit")
+__naked void loop_with_if_else(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = r0; \
+ if r1 > 5 goto 2f; \
+ r1 = 1; \
+2: r0 += r1; \
+ if r0 < 100 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case E: irreducible loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 3, irreducible")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg(" 0 1: {{.*}} (b7) r1 = 0")
+__msg(" 1 2: {{.*}} (25) if r0 > 0x5 goto pc+2")
+__msg(" 1 2 3: {{.*}} (b7) r1 = 1")
+__msg(" 1 3 3 4: {{.*}} (05) goto pc+1")
+__msg(" 2 5: {{.*}} (b7) r1 = 2")
+__msg(" 1 3 2 6: {{.*}} (0f) r0 += r1")
+__msg(" 1 3 6 7: {{.*}} (a5) if r0 < 0x10 goto pc-5")
+__msg(" 7 8: {{.*}} (95) exit")
+__naked void loop_irreducible(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+ if r0 > 5 goto 2f; \
+1: r1 = 1; \
+ goto 3f; \
+2: r1 = 2; \
+3: r0 += r1; \
+ if r0 < 16 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__failure
+__log_level(2)
+__msg("loop at 1")
+__msg("infinite loop detected at insn 1")
+__naked void loop_self(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+1: if r0 < 10 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Loops at 5 and 7 are nested inside loops at 3 and 1.
+ * The edge 6 -> 7 exits loop at 5 and enters loop at 7.
+ * Check that it is logged only as an exit from loop at 5.
+ *
+ * 0: r0 = 0;
+ * do {
+ * 1: r0++;
+ * 2: r1 = 0;
+ * do {
+ * 3: r1++;
+ * 4: r2 = 0;
+ * do {
+ * 5: r2++;
+ * 6: } while (r2 < 3);
+ * do {
+ * 7: r2--;
+ * 8: } while (r2 != 0);
+ * 9: } while (r1 < 4);
+ * 10: } while (r0 < 5);
+ * 11: return r0;
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg_next(" backedge from 10, latch at 10")
+__msg_next(" exit from 10 to 11")
+__msg_next("loop at 3, nested in 1")
+__msg_next(" backedge from 9, latch at 9")
+__msg_next(" exit from 9 to 10")
+__msg_next("loop at 5, nested in 3")
+__msg_next(" backedge from 6, latch at 6")
+__msg_next(" exit from 6 to 7")
+__msg_next("loop at 7, nested in 3")
+__msg_next(" backedge from 8, latch at 8")
+__msg_next(" exit from 8 to 9")
+__naked void loop_nested_siblings_common_ancestors(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 3 goto 3b; \
+4: r2 += -1; \
+ if r2 != 0 goto 4b; \
+ if r1 < 4 goto 2b; \
+ if r0 < 5 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c
new file mode 100644
index 0000000000000..69e9062870acb
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c
@@ -0,0 +1,1108 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <stdbool.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "bpf_kfuncs.h"
+
+struct map_val {
+ char foo[1024];
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 1);
+ __type(key, int);
+ __type(value, struct map_val);
+} map SEC(".maps");
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__naked void simple_loop1(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+loop_%=: \
+ if r0 == 10 goto exit_%=; \
+ r0 += 1; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> ?")
+__naked void indirect_write_invalidates_scev(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 8) = r0; \
+loop_%=: \
+ r0 = *(u64 *)(r10 - 8); \
+ if r0 == 10 goto exit_%=; \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ r1 = r10; \
+ r1 += -8; \
+ *(u64 *)(r1 + 0) = r0; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 2:")
+__msg_next(" *fp-8=(+ *fp-8 1) / (linear *fp-8 1)")
+__msg_next(" scev at latch 3:")
+__msg_next(" r0=*fp-8 / (linear *fp-8 1)")
+__msg_next(" *fp-8=*fp-8 / (linear *fp-8 1)")
+__naked void simple_loop2(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 8) = r0; \
+loop_%=: \
+ r0 = *(u64 *)(r10 - 8); \
+ if r0 == 10 goto exit_%=; \
+ r0 = *(u64 *)(r10 - 8); \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 2:")
+__msg_next(" r1=(+ r1 1) / (linear r1 1)")
+__naked void meet_agrees(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+1: \
+ if r1 == 2 goto 3f; \
+ if r0 == 7 goto 2f; \
+ r1 += 1; \
+ goto 1b; \
+2: \
+ r1 += 1; \
+ goto 1b; \
+3: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__failure
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(any r6 (+ r6 1)) / ?")
+__naked void meet_disagrees(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 3f; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 7 goto 1b; \
+ r6 += 1; \
+ goto 1b; \
+3: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(bswap32 (bswap32 (zext32 (- (- (zext32 (+ (>>...) 1))))))) / ?")
+__naked void expr_chain(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 2f; \
+ r6 += 1; \
+ r6 <<= 32; \
+ r6 >>= 32; \
+ w6 += 1; \
+ r6 = -r6; \
+ w6 = -w6; \
+ r6 = bswap32 r6; \
+ r6 = bswap32 r6; \
+ goto 1b; \
+2: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next(" scev at latch 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next("scev at header 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__naked void nested_loop1(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 2f; \
+ r6 += 1; \
+ r7 = 0; \
+3: \
+ if r7 == 2 goto 4f; \
+ r7 += 1; \
+ goto 3b; \
+4: \
+ goto 1b; \
+2: \
+ r0 = r7; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__msg_next("scev at header 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next("scev at header 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg("loop header at 1, can't widen r7, expr is ?")
+__msg("loop header at 4, widening r7 to 0..2 step 1")
+__log_level(2)
+__naked void nested_loop_hdr_backedge1(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 3f; \
+ r6 += 1; \
+ r7 = 0; \
+2: \
+ if r7 == 2 goto 1b; \
+ r7 += 1; \
+ goto 2b; \
+3: \
+ r0 = r7; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 10 post-cond")
+__msg("loop header at 1, widening r0 to 0..9 step 1")
+__msg("processed 5 insns")
+__naked void post_cond_jlt(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 3, header_count is 8")
+__msg("loop header at 3, widening r0 to 2..9 step 1")
+__msg("3: R0=scalar(smin=umin=smin32=umin32=2,smax=umax=smax32=umax32=9,{{.*}})")
+__msg("processed 6 insns")
+__naked void post_cond_jlt_with_base(void)
+{
+ asm volatile (" \
+ r7 = 10 ll; /* ldimm64 for a twist */ \
+ r0 = 2; \
+1: r0 += 1; \
+ if r0 < r7 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 11")
+__msg("loop header at 1, widening r0 to 0..10 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})")
+__msg("processed 5 insns")
+__naked void post_cond_jle(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 <= 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 10")
+__msg("loop header at 1, widening r0 to 0..9 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=9,{{.*}})")
+__msg("processed 6 insns")
+__naked void post_cond_jge(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 >= 10 goto 2f; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 11")
+__msg("loop header at 1, widening r0 to 0..10 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})")
+__msg("processed 6 insns")
+__naked void pre_cond_jge(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: if r0 >= 10 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 2 post-cond")
+__naked void post_cond_jgt(void)
+{
+ asm volatile (" \
+ r0 = 2; \
+1: r0 += -1; \
+ if r0 > 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" scev at latch 2:")
+__msg_next(" r0=(+ r0 1) / (linear (+ r0 1) 1)")
+__msg("loop header at 1, widening r0")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})")
+__msg("1: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("2: (55) if r0 != 0x3 goto pc-2")
+__msg("3: (95) exit")
+__msg("loop header at 1, clamping r0")
+__msg("from 2 to 1: safe")
+__msg("processed 5 insns")
+__naked void post_cond_jne(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 != 3 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 -1) / (linear r0 -1)")
+__msg_next(" scev at latch 2:")
+__msg_next(" r0=(+ r0 -1) / (linear (+ r0 -1) -1)")
+__msg("loop header at 1, header_count is 3 post-cond")
+__msg("loop header at 1, widening r0 to 1..3 step 1")
+__msg("1: R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,var_off=(0x0; 0x3)) loop_stack=1")
+__msg("loop header at 1, clamping r0 to 1..2 step 1")
+__msg("processed 5 insns")
+__naked void post_cond_jne_neg_step(void)
+{
+ asm volatile (" \
+ r0 = 3; \
+1: r0 += -1; \
+ if r0 != 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" scev at latch 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg("loop header at 1, widening r0")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("1: (15) if r0 == 0x3 goto pc+2 ; R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})")
+__msg("2: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("3: (05) goto pc-3")
+__msg("loop header at 1, clamping r0")
+__msg("1: safe")
+__msg("from 1 to 4: R0=3")
+__msg("4: R0=3")
+__msg("4: (95) exit")
+__msg("processed 6 insns")
+__naked void pre_cond_je1(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: if r0 == 3 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is [0..3] post-cond")
+__naked void one_backedge_two_exits(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: call %[bpf_get_prandom_u32]; \
+ if r0 == 0 goto 2f; \
+ r6 += 1; \
+ if r6 != 3 goto 1b; \
+2: r0 = r6; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 11:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" r1=(+ r1 2) / (linear r1 2)")
+__msg_next(" scev at latch 16:")
+__msg_next(" r0=(+ r0 1) / (linear (+ r0 1) 1)")
+__msg_next(" r1=(+ r1 2) / (linear (+ r1 2) 2)")
+__msg("loop header at 11, widening r0")
+__msg("loop header at 11, widening r1")
+__msg("11: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=7,var_off=(0x0; 0x7)) R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=14,var_off=(0x0; 0xe),step=0+2)")
+/* loop exit */
+__msg("16: (a5) if r0 < 0x8 goto pc-6")
+__msg("exiting loop 11")
+__msg("17: (95) exit")
+/* second iteration */
+__msg("loop header at 11, clamping r0")
+__msg("loop header at 11, clamping r1")
+/* iteration convergence */
+__msg("from 16 to 11: safe")
+__not_msg("{{^}}11:")
+/* map lookup error path */
+__msg("from 7 to 17: safe")
+__naked void correlated_regs(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ *(u64*)(r10 - 8) = r1; \
+ r2 = r10; \
+ r2 += -8; \
+ r1 = %[map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto 2f; \
+ r6 = r0; \
+ r0 = 0; \
+ r1 = 0; \
+1: r2 = r6; \
+ r2 += r1; \
+ *(u8 *)(r2 + 0) = 1; \
+ r0 += 1; \
+ r1 += 2; \
+ if r0 < 8 goto 1b; \
+2: exit; \
+" :
+ : __imm(bpf_map_lookup_elem),
+ __imm_addr(map)
+ : __clobber_all);
+}
+
+/*
+ * k = 0
+ * for (i = 0; i < 4; i++):
+ * for (j = 0; j < 4; j++):
+ * k += 1
+ * k <<= 1 // make SCEV construction not possible
+ * k >>= 1
+ * map[k] = 1 // make k precise
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("19: (72) *(u8 *)(r4 +0) = 1 ; R4=map_value(id={{.*}},map=map,ks=4,vs=1024,imm=16)")
+__not_msg("19: ")
+__msg("processed 106 insns")
+__naked void nested_loops_precise_var1(void)
+{
+ asm volatile (" \
+ *(u64*)(r10 - 8) = 0; \
+ r1 = %[map] ll; \
+ r2 = r10; \
+ r2 += -8; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto 3f; \
+ r1 = 0; \
+ r3 = 0; \
+ /* outer loop */ \
+1: r2 = 0; \
+ /* inner loop */ \
+2: r2 += 1; \
+ r3 += 1; \
+ r3 <<= 1; \
+ r3 >>= 1; \
+ if r2 < 4 goto 2b; \
+ r1 += 1; \
+ if r1 < 4 goto 1b; \
+ r4 = r0; \
+ r4 += r3; \
+ *(u8 *)(r4 + 0) = 1; \
+ r0 = 0; \
+3: exit; \
+" :
+ : __imm(bpf_map_lookup_elem),
+ __imm_addr(map)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 1 pre-cond")
+__naked void pre_cond_jgt(void)
+{
+ asm volatile (" \
+ r0 = -1; \
+1: if r0 > 1 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 2 post-cond")
+__naked void loop_jslt_latch_post(void)
+{
+ asm volatile (" \
+ r0 = -2; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 1 post-cond")
+__naked void loop_jslt_latch_post1(void)
+{
+ asm volatile (" \
+ r0 = -1; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, 0 iterations count")
+__naked void loop_jslt_latch_post2(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 3 post-cond")
+__naked void loop_jsle_latch_post(void)
+{
+ asm volatile (" \
+ r0 = -2; \
+1: r0 += 1; \
+ if r0 s<= 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop header at 2, header_count is 100 post-cond")
+__msg("loop header at 4, header_count is [0..100] post-cond")
+__msg("loop header at 6, header_count is [0..100] post-cond")
+__msg("processed 20 insns")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void nested_loop_with_two_exits(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = 0; \
+1: r6 += 1; \
+ r7 = 0; \
+2: r7 += 1; \
+ r8 = 0; \
+3: r8 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 42 goto +1; \
+ goto 4f; \
+ if r8 < 100 goto 3b; \
+ if r7 < 100 goto 2b; \
+4: if r6 < 100 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__naked void exit_loop_into_loop_header(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ r2 = 0; \
+loop_a_%=: \
+ r1 += 1; \
+ if r1 < 10 goto loop_a_%=; \
+loop_b_%=: \
+ r2 += 1; \
+ if r2 < 10 goto loop_b_%=; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * This exercises verifier.c:loop_stack_{pop,push}() implementation,
+ * at 'goto d' loops 'b' and 'a' have to be popped from stack,
+ * while loops 'c' and 'd' have to be pushed to stack.
+ *
+ * loop a: // header 5
+ * loop b: // header 6
+ * if (rand) goto d; // 8 -> 12, side entry into inner loop d
+ * ...
+ * loop c: // header 11
+ * loop d: // header 12
+ * ...
+ */
+SEC("xdp")
+__log_level(2)
+__msg("loop at 5")
+__msg("loop at 6, nested in 5")
+__msg("loop at 11, irreducible")
+__msg("loop at 12, nested in 11")
+/* entry via if r0 == 5 goto d_%= false branch */
+__msg("loop header at 12, header_count is 3 post-cond")
+__msg("loop header at 12, widening r9 to 0..2 step 1")
+__msg("12: R8=1 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) loop_stack=11,12")
+/* entry via if r0 == 5 goto d_%= true branch */
+__msg("loop header at 12, header_count is 3 post-cond")
+__msg("loop header at 12, widening r9 to 0..2 step 1")
+__msg("from 8 to 12: R8=0 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) R10=fp0 loop_stack=11,12")
+__naked void enter_nested_loop_from_side(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = 0; \
+ r7 = 0; \
+ r8 = 0; \
+ r9 = 0; \
+a_%=: r6 += 1; \
+b_%=: r7 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 5 goto d_%=; \
+ if r7 < 3 goto b_%=; \
+ if r6 < 3 goto a_%=; \
+c_%=: r8 += 1; \
+d_%=: r9 += 1; \
+ if r9 < 3 goto d_%=; \
+ if r8 < 3 goto c_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Loop A (counter in r6) contains irreducible loop B (header 5),
+ * which contains C (counter in r9).
+ * Entering B at 'body' saves and restores r6, making it appear invariant.
+ * Entering B at 'alternate' skips the save and modifies r6 instead.
+ * Hence A must not infer a SCEV expression for r6.
+ * SCEV expression for r9 in C should still be computed.
+ *
+ * 0: r6 = 0;
+ * do { // A
+ * 1: r6++;
+ * 2: r0 = bpf_get_prandom_u32();
+ * 3: r7 = 0;
+ * 4: if (r0 > 5) goto alternate;
+ * 5: B: r8 = r6; // B
+ * 6: goto body;
+ * 7: alternate:
+ * r8 = r6;
+ * 8: r8++;
+ * 9: body:
+ * r6 = r8;
+ * 10: r9 = 0;
+ * do { // C
+ * 11: r9++;
+ * 12: } while (r9 < 3);
+ * 13: r7++;
+ * 14: if (r7 < 4) goto B;
+ * 15: } while (r6 < 4);
+ * 16: r0 = 0;
+ * 17: return r0;
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 5, nested in 1, irreducible")
+__msg("loop at 11, nested in 5")
+__msg("scev at header 1:")
+__msg_next(" r6=?")
+__msg("scev at header 11:")
+__msg_next(" r9=(+ r9 1) / (linear r9 1)")
+__msg("loop header at 11, widening r9 to 0..2 step 1")
+__not_msg("loop header at 1, widening r6")
+__naked void nested_irreducible_loop(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+a_%=: r6 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = 0; \
+ if r0 > 5 goto alternate_%=; \
+b_%=: r8 = r6; \
+ goto body_%=; \
+alternate_%=: \
+ r8 = r6; \
+ r8 += 1; \
+body_%=: \
+ r6 = r8; \
+ r9 = 0; \
+c_%=: r9 += 1; \
+ if r9 < 3 goto c_%=; \
+ r7 += 1; \
+ if r7 < 4 goto b_%=; \
+ if r6 < 4 goto a_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Induction variable seeded from a non-constant value. r7 enters the loop as a
+ * range aligned to 2 (prandom & 0x6 -> {0,2,4,6}) and is incremented by a
+ * non-power-of-2 slope of 6. Since the entry value is not a single point, only
+ * the power-of-two alignment shared by the entry value and the slope can be
+ * guaranteed, so the widened step is 2 - not |slope|=6, which would be unsound
+ * here (a constant entry value would have allowed step 6).
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 4, widening r7 to 0..18 step 2")
+__msg("R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=18,var_off=(0x0; 0x1e),step=0+2)")
+__naked void widen_nonconst_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ r7 &= 0x6; \
+ r6 = 0; \
+1: r7 += 6; \
+ r6 += 1; \
+ if r6 < 3 goto 1b; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Two nested loops with (1) exiting directly to (2):
+ *
+ * for (r6 = 0; r6 < 4; r6++) {
+ * r7 = 0;
+ * for (; r7 < 3; r7++) {} // (1)
+ * for (; r7 != 0; r7--) {} // (2)
+ * }
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop header at 1, widening r6 to 0..3 step 1")
+__msg("loop header at 2, widening r7 to 0..2 step 1")
+__msg("loop header at 4, widening r7 to 1..3 step 1")
+__naked void sibling_inner_loops(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: r7 = 0; \
+2: r7 += 1; \
+ if r7 < 3 goto 2b; \
+3: r7 += -1; \
+ if r7 != 0 goto 3b; \
+ r6 += 1; \
+ if r6 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop header at 0, can't compute iterations count")
+__naked void uninit_slot_counter(void)
+{
+ asm volatile (" \
+1: r0 = *(u64 *)(r10 - 8); \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ if r0 < 10 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * The assignment happens only on the second iteration:
+ *
+ * r7 = 5;
+ * for (r6 = 0; r6 < 3; r6++)
+ * if (r6 == 1)
+ * r7 = 10;
+ * if (r7 != 10)
+ * invalid_stack_read();
+ *
+ * R7 is always 10 at the real exit. Widening loses the correlation between
+ * R6 and R7, leaving R7 in [5, 10] both at the loop header and after the loop.
+ * The verifier therefore rejects the possible invalid stack read.
+ */
+SEC("xdp")
+__failure
+__log_level(2)
+__msg("2: {{.*}}R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
+__msg("7: R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
+__msg("invalid read from stack R10 off=0 size=8")
+__naked void conditional_assignment_on_second_iteration(void)
+{
+ asm volatile (" \
+ r7 = 5; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = 10; \
+2: r6 += 1; \
+ goto 1b; \
+3: if r7 == 10 goto 4f; \
+ r0 = *(u64 *)(r10 + 0); \
+4: r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Join two stack pointer offsets via (any r7 r8), with r8 loop-invariant.
+ * The joined range [-16, -8] still points to initialized stack memory,
+ * so dereferencing r7 after the loop is safe.
+ */
+SEC("xdp")
+__success __retval(0)
+__log_level(2)
+__msg("loop header at 7, widening r7 to -16..-8 step 1")
+__msg("7: {{.*}}R7=fp(smin=smin32=-16,smax=smax32=-8,")
+__msg("12: R7=fp(smin=smin32=-16,smax=smax32=-8,")
+__naked void conditional_stack_pointer_assignment(void)
+{
+ asm volatile (" \
+ *(u64 *)(r10 - 16) = 0; \
+ *(u64 *)(r10 - 8) = 0; \
+ r7 = r10; \
+ r7 += -16; \
+ r8 = r10; \
+ r8 += -8; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = r8; \
+2: r6 += 1; \
+ goto 1b; \
+3: r0 = *(u64 *)(r7 + 0); \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * r7 starts as 1 + 6*k and invariant r8 as 1 + 9*k (0 <= k <= 3).
+ * The (any r7 r8) union must preserve base 1 and step gcd(6, 9) = 3.
+ */
+SEC("xdp")
+__success __retval(1)
+__log_level(2)
+__msg("r7 += 1 {{.*}}step=1+6)")
+__msg("r8 += 1 {{.*}}step=1+9)")
+__msg("loop header at 9, widening r7 to 1..28 step 3")
+__msg("9: {{.*}}R7=scalar({{.*}},step=1+3)")
+__msg("14: R7=scalar({{.*}},step=1+3)")
+__naked void conditional_scalar_assignment_gcd(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r7 = r0; \
+ r7 *= 6; \
+ r7 += 1; \
+ r8 = r0; \
+ r8 *= 9; \
+ r8 += 1; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = r8; \
+2: r6 += 1; \
+ goto 1b; \
+3: r0 = r7; \
+ r0 %%= 3; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A loop induction variable used to compute the base address of a store to the
+ * stack must not be widened: the spill offset would become varying, which the
+ * verifier does not track.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__naked void no_widen_stack_spill(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u64 *)(r3 + 0) = r0; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+/*
+ * Same hazard across a loop nest: the outer induction variable r2 addresses a
+ * stack store performed inside the inner loop. The dependency is pulled up from
+ * the inner loop, so the outer loop must not widen r2.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__msg("loop header at 3, widening r1 to 0..1 step 1")
+__naked void no_widen_stack_spill_nested(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r1 = 0; \
+2: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u64 *)(r3 + 0) = r1; \
+ r1 += 1; \
+ if r1 < 2 goto 2b; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Complement of no_widen_stack_spill: a sub-register (1-byte) store to the stack
+ * lands as STACK_MISC and carries no tracked value, so the induction variable
+ * addressing it (r2) is still widened.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("widening r2 to 0..24 step 8")
+__naked void widen_byte_stack_store(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u8 *)(r3 + 0) = r0; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * A fill (BPF_LDX) at a varying stack offset loses precision just like a spill,
+ * so the induction variable computing the load base (r2) must not be widened.
+ * The slots are initialized up front so the fill itself is a valid read.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 6, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__naked void no_widen_stack_fill(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 64) = r0; \
+ *(u64 *)(r10 - 56) = r0; \
+ *(u64 *)(r10 - 48) = r0; \
+ *(u64 *)(r10 - 40) = r0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ r4 = *(u64 *)(r3 + 0); \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * A dynptr/iter/irq/res_spin_lock call initializes a stack object through a
+ * pointer argument, which acts like a spill base: the induction variable
+ * computing that argument's varying stack offset must not be widened, otherwise
+ * the slot can't be resolved. Here each iteration constructs an xdp dynptr at
+ * &dptrs[i].
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("can't widen {{.*}}, requires exact stack-offset tracking")
+int no_widen_dynptr_kfunc_arg(struct xdp_md *ctx)
+{
+ struct bpf_dynptr dptrs[4];
+ int i;
+
+#pragma clang loop unroll(disable)
+ for (i = 0; i < 4; i++)
+ bpf_dynptr_from_xdp(ctx, 0, &dptrs[i]);
+
+ return 0;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
index 3e0bea9819cab..5da8b9a6018cf 100644
--- a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
+++ b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
@@ -586,4 +586,37 @@ __naked void stack_check_size_512_with_may_goto(void)
}
#endif
+/* Verify that old PTR_TO_STACK state is considered a super-set of
+ * new PTR_TO_STACK state when new variable range is a sub-range
+ * of the old range, e.g. old [-72, -16] vs new [-64, -16].
+ */
+SEC("socket")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+/* r7 is widened to [-72, -16] at the loop header (insn 3),
+ * the loop body sees [-64, -8] after 'r7 += 8'
+ */
+__msg("loop header at 3, widening r7 to -72..-16 step 8")
+__msg("R7=fp(smin=smin32=-64,smax=smax32=-8")
+/* back-edge state is clamped to the remaining iterations and pruned
+ * at the header, because [-64, -16] is within the widened [-72, -16]
+ */
+__msg("loop header at 3, clamping r7 to -64..-16 step 8")
+__msg("from 5 to 3: safe")
+__msg("processed 9 insns")
+__naked void stack_ptr_subrange_in_loop(void)
+{
+ asm volatile (" \
+ r7 = r10; \
+ r7 += -72; \
+ r6 = 0; \
+ r7 += 8; \
+ r6 += 1; \
+ if r6 < 8 goto -3; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c
index 25eeb1c1248b3..edeeb244e693f 100644
--- a/tools/testing/selftests/bpf/test_loader.c
+++ b/tools/testing/selftests/bpf/test_loader.c
@@ -508,6 +508,16 @@ static int parse_test_spec(struct test_loader *tester,
if (err)
goto cleanup;
spec->mode_mask |= UNPRIV;
+ } else if ((msg = str_has_pfx(s, "test_expect_msg_next="))) {
+ err = __push_msg(msg, true, false, &spec->priv.expect_msgs);
+ if (err)
+ goto cleanup;
+ spec->mode_mask |= PRIV;
+ } else if ((msg = str_has_pfx(s, "test_expect_msg_next_unpriv="))) {
+ err = __push_msg(msg, true, false, &spec->unpriv.expect_msgs);
+ if (err)
+ goto cleanup;
+ spec->mode_mask |= UNPRIV;
} else if ((msg = str_has_pfx(s, "test_jited="))) {
if (arch_mask == 0) {
PRINT_FAIL("__jited used before __arch_*");
|
| 3/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 116804 output: 31 thoughts: 1066 Thoughts: **Analyzing the eBPF Verifier Scalar Evolution and Loop Analysis Patch** Okay, so this patch is a significant advancement for the eBPF verifier, introducing scalar evolution (SCEV) and loop widening/induction variable tracking. This is a big deal. Let's break down the implications and potential fuzzing targets. First, the scope: it touches a lot of files. The patch significantly expands the verifier's capabilities: includes data structures for SCEV, a loop stack, a min-heap, and other related helper functions; it also includes new data structures for `cnum` (constant numbers) and `tnum` (tracked numbers). We're seeing additions to the `Makefile` to include the new modules, and updates across a number of core files to support the new features, including precise tracking, BTF support, control flow graph modifications for postorder numbering, heap implementation for SCEV, liveness tracking, verifier state logging, loop analysis (dominator trees, loop identification), SCEV implementation itself (expression trees, widening, clamping!), state comparison with loop tracking, step tracking, and loop entry/exit handling within the verification process. The question then becomes: can we reach this functionality through standard fuzzing techniques like QEMU/syzkaller? The answer is yes. The BPF verifier is exercised via the `bpf(BPF_PROG_LOAD, ...)` syscall, which is a prime target for fuzzing. This is clearly a "WorthFuzzing" patch, especially considering the BPF subsystem's importance, and this patch's heavy touching of the verifier. Now, let's identify the key functions that are either new or have been heavily modified, and, more importantly, whether they're accessible. We're looking for our FocusSymbols. The patch introduces several new functions to implement SCEV. In `kernel/bpf/scev.c`, we see: `bpf_compute_scev`, `bpf_init_scev`, `bpf_compute_loop_iters`, `bpf_widen_scev_regs`, and `bpf_clamp_scev_regs`. Then in `kernel/bpf/loops.c`, we have `bpf_compute_idoms` and `bpf_compute_loops`. The main `kernel/bpf/verifier.c` has these new or modified functions: `handle_loop_entry_exit`, `bpf_set_reg_range`, `bpf_reg_union`, and `adjust_scalar_min_max_vals`, `adjust_ptr_min_max_vals` and `check_ptr_to_btf_access`. There are also some interesting functions in `kernel/bpf/states.c`: `bpf_split_cur_state`, `range_within` (though this one is static, so trickier to reach directly), and `bpf_is_state_visited`. We also want to look at `btf_struct_access` from `kernel/bpf/btf.c`, `bpf_compute_postorder` from `kernel/bpf/cfg.c`, and `cnum64_intersect_linear` from `kernel/bpf/cnum.c`. My next step is to verify the visibility and exact names of these symbols. Specifically, I'll need to check which of these functions are *non-static* and visible, and which are static but can be targeted via other means. This requires a precise and targeted approach, probably using `grepper` or `read-file` to confirm the function names and their visibility. This will determine which functions are truly the best targets for focused fuzzing. |
| 4/2 | 2026/09/28 01:35 | tool | grepper |
0mArgs:{
"Expression": "^int bpf_compute_",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/cfg.c=770=struct dfs_state {\n--\nkernel/bpf/cfg.c-779- */\nkernel/bpf/cfg.c:780:int bpf_compute_postorder(struct bpf_verifier_env *env)\nkernel/bpf/cfg.c-781-{\n--\nkernel/bpf/cfg.c-841- */\nkernel/bpf/cfg.c:842:int bpf_compute_scc(struct bpf_verifier_env *env)\nkernel/bpf/cfg.c-843-{\n--\nkernel/bpf/const_fold.c=213=static bool const_reg_join(struct const_arg_info *ci_target,\n--\nkernel/bpf/const_fold.c-235-\nkernel/bpf/const_fold.c:236:int bpf_compute_const_regs(struct bpf_verifier_env *env)\nkernel/bpf/const_fold.c-237-{\n--\nkernel/bpf/liveness.c=2225=static int analyze_subprog(struct bpf_verifier_env *env,\n--\nkernel/bpf/liveness.c-2381-\nkernel/bpf/liveness.c:2382:int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)\nkernel/bpf/liveness.c-2383-{\n--\nkernel/bpf/liveness.c=2460=static void compute_insn_live_regs(struct bpf_verifier_env *env,\n--\nkernel/bpf/liveness.c-2627- */\nkernel/bpf/liveness.c:2628:int bpf_compute_live_registers(struct bpf_verifier_env *env)\nkernel/bpf/liveness.c-2629-{\n--\nkernel/bpf/loops.c=101=static void compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarray **preds, int subprog_idx)\n--\nkernel/bpf/loops.c-136-\nkernel/bpf/loops.c:137:int bpf_compute_idoms(struct bpf_verifier_env *env)\nkernel/bpf/loops.c-138-{\n--\nkernel/bpf/loops.c=433=bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header)\n--\nkernel/bpf/loops.c-444-\nkernel/bpf/loops.c:445:int bpf_compute_loops(struct bpf_verifier_env *env)\nkernel/bpf/loops.c-446-{\n--\nkernel/bpf/scev.c=1449=static void log_scevs(struct bpf_verifier_env *env)\n--\nkernel/bpf/scev.c-1476-\nkernel/bpf/scev.c:1477:int bpf_compute_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-1478-{\n--\nkernel/bpf/scev.c=1927=static bool linear_bounds(struct bpf_reg_state *reg, struct bpf_loop_iters *iters, s64 slope,\n--\nkernel/bpf/scev.c-1958-\nkernel/bpf/scev.c:1959:int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\nkernel/bpf/scev.c-1960-\t\t\t struct bpf_loop_iters *iters)\n"
} |
| 5/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 119643 output: 41 thoughts: 103 Thoughts: Okay, let's dive into this `scev.c` file. My initial thought is to get a lay of the land, so I'll quickly enumerate the public-facing functions in my mind: **Initial Assessment of `scev.c`** Alright, from the looks of it, we have: `bpf_compute_scev`, `bpf_compute_loop_iters`, `bpf_widen_scev_regs`, `bpf_clamp_scev_regs`, `bpf_init_scev` and `bpf_free_scev`. These names are pretty descriptive. My immediate impression is that this is a BPF-specific implementation of Scalar Evolution, likely designed to handle things like loop analysis and invariant code motion within the BPF context. Now, I need to check the source file in `/kernel/bpf/scev.c` to confirm these observations. And, of course, I will focus on non-static functions for this overview. |
| 6/2 | 2026/09/28 01:35 | tool | grepper |
0mArgs:{
"Expression": "^(int|void|bool|struct) bpf_",
"PathPrefix": "kernel/bpf/scev.c"
}Results: {
"Output": "kernel/bpf/scev.c=1449=static void log_scevs(struct bpf_verifier_env *env)\n--\nkernel/bpf/scev.c-1476-\nkernel/bpf/scev.c:1477:int bpf_compute_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-1478-{\n--\nkernel/bpf/scev.c=1527=static int reverse_ranked_compare(int a, int b, void *arg)\n--\nkernel/bpf/scev.c-1533-\nkernel/bpf/scev.c:1534:void bpf_free_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-1535-{\n--\nkernel/bpf/scev.c-1560-\nkernel/bpf/scev.c:1561:int bpf_init_scev(struct bpf_verifier_env *env)\nkernel/bpf/scev.c-1562-{\n--\nkernel/bpf/scev.c=1927=static bool linear_bounds(struct bpf_reg_state *reg, struct bpf_loop_iters *iters, s64 slope,\n--\nkernel/bpf/scev.c-1958-\nkernel/bpf/scev.c:1959:int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\nkernel/bpf/scev.c-1960-\t\t\t struct bpf_loop_iters *iters)\n--\nkernel/bpf/scev.c=2098=static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,\n--\nkernel/bpf/scev.c-2131-\nkernel/bpf/scev.c:2132:int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,\nkernel/bpf/scev.c-2133-\t\t\tstruct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)\n--\nkernel/bpf/scev.c-2191-\nkernel/bpf/scev.c:2192:int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,\nkernel/bpf/scev.c-2193-\t\t\tstruct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters)\n"
} |
| 7/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 120698 output: 40 thoughts: 21 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Analyzing `kernel/bpf/loops.c`** Alright, let's dive in. My immediate thought is to examine `kernel/bpf/loops.c`. My focus is specifically honed in on identifying non-static functions within this file. The rationale, as always, is to understand potential external interfaces, entry points, or areas of interaction within the BPF loop implementation. I'm looking for anything that might be exposed beyond the module itself. This is critical for assessing the overall architecture and considering potential risks or integration points, and of course, where to look for areas for further optimization. Static functions, while important internally, are, by their nature, less likely to impact things beyond their immediate scope. Non-static ones demand closer scrutiny. |
| 8/2 | 2026/09/28 01:35 | tool | grepper |
0mArgs:{
"Expression": "^(int|void|bool|struct) bpf_",
"PathPrefix": "kernel/bpf/loops.c"
}Results: {
"Output": "kernel/bpf/loops.c=101=static void compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarray **preds, int subprog_idx)\n--\nkernel/bpf/loops.c-136-\nkernel/bpf/loops.c:137:int bpf_compute_idoms(struct bpf_verifier_env *env)\nkernel/bpf/loops.c-138-{\n--\nkernel/bpf/loops.c=265=static bool is_cond_jmp_insn(struct bpf_insn *insn)\n--\nkernel/bpf/loops.c-290-\nkernel/bpf/loops.c:291:int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx)\nkernel/bpf/loops.c-292-{\n--\nkernel/bpf/loops.c=328=static int compute_loops_in_subprog(struct bpf_verifier_env *env, struct loops_dfs *dfs,\n--\nkernel/bpf/loops.c-432-\nkernel/bpf/loops.c:433:bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header)\nkernel/bpf/loops.c-434-{\n--\nkernel/bpf/loops.c-444-\nkernel/bpf/loops.c:445:int bpf_compute_loops(struct bpf_verifier_env *env)\nkernel/bpf/loops.c-446-{\n"
} |
| 9/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 121344 output: 42 thoughts: 17 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, and delivered as a first-person summary: **Digging Deeper into BPF Heap Management** Alright, I need to make absolutely sure I've covered all the bases. I've been focusing on X, Y, and Z, but that nagging feeling persists... I can't be *completely* certain without a more thorough dive. My initial scan of the BPF core libraries was helpful, but I need to go beyond the obvious. It’s time to double-check my assumptions regarding memory allocation and potential edge cases within the BPF subsystem. I’ve reviewed the core components, but there's a good chance I’ve missed something related to heap management, particularly when dealing with concurrent accesses, or under heavy load. I want to be 100% sure that there aren't any subtle memory leaks, corruption issues, or unexpected interactions that could compromise stability. Specifically, I should really take a look at the code in `kernel/bpf/heap.c`. That's where I bet I'll find the details on the allocator implementation, object lifetimes, and potential vulnerabilities. I need to understand the exact mechanics of BPF program memory management from the ground up, so that I can anticipate and address any potential problems effectively. Let's start there. |
| 10/2 | 2026/09/28 01:35 | tool | grepper |
0mArgs:{
"Expression": "^(int|void|bool) bpf_min_heap_",
"PathPrefix": "kernel/bpf/heap.c"
}Results: {
"Output": "kernel/bpf/heap.c=11=static inline int greater(struct bpf_min_heap *heap, int a, int b)\n--\nkernel/bpf/heap.c-15-\nkernel/bpf/heap.c:16:void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg)\nkernel/bpf/heap.c-17-{\n--\nkernel/bpf/heap.c-22-\nkernel/bpf/heap.c:23:void bpf_min_heap_free(struct bpf_min_heap *heap)\nkernel/bpf/heap.c-24-{\n--\nkernel/bpf/heap.c-30-\nkernel/bpf/heap.c:31:int bpf_min_heap_push(struct bpf_min_heap *heap, int elt)\nkernel/bpf/heap.c-32-{\n--\nkernel/bpf/heap.c=59=static inline void sink_root(struct bpf_min_heap *heap)\n--\nkernel/bpf/heap.c-75-\nkernel/bpf/heap.c:76:bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt)\nkernel/bpf/heap.c-77-{\n"
} |
| 11/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 122031 output: 31 thoughts: 48 Thoughts: Okay, here's my thought process on this, from my perspective as someone well-versed in kernel configuration: **Investigating BPF Syscall Dependencies** Right, so I need to nail down the exact Kconfig options that are *required* for `CONFIG_BPF_SYSCALL` and, by extension, all the functionality it unlocks. No point in enabling one thing and missing a crucial dependency, resulting in a broken setup. My first port of call will be to grep through the source tree. Specifically, I'll be targeting the `kernel/bpf/Makefile` and the `init/Kconfig` files. That's usually where these sorts of dependencies are defined or referenced. I need to grep for `BPF_SYSCALL` itself. That should directly give me the necessary configuration options. It'll hopefully point me to the relevant `depends on` statements or other Kconfig relationships. I'm looking for a clear map of the landscape so I can make confident decisions. |
| 12/2 | 2026/09/28 01:35 | tool | grepper |
0mArgs:{
"Expression": "config BPF_SYSCALL",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/Kconfig=29=menu \"BPF subsystem\"\nkernel/bpf/Kconfig-30-\nkernel/bpf/Kconfig:31:config BPF_SYSCALL\nkernel/bpf/Kconfig-32-\tbool \"Enable bpf() system call\"\n"
} |
| 13/2 | 2026/09/28 01:35 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 122404 output: 34 thoughts: 25 Thoughts: Here's my summary, as though I'm thinking through this process: **Diving into the BPF Syscall Configuration** Alright, let's get down to brass tacks. I need to understand something about the BPF syscall configuration in the kernel, so my first step, as always, is to navigate to the source of truth: `kernel/bpf/Kconfig`. I'm going to zero in on the lines around `config BPF_SYSCALL`. That's where I expect to find the definitive documentation and perhaps some dependencies or considerations related to enabling or disabling the BPF syscall. Time to see what the Kconfig file has to reveal! |
| 14/2 | 2026/09/28 01:36 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/Kconfig",
"FirstLine": 30,
"LineCount": 40
}Results: {
"Contents": " 30:\t\n 31:\tconfig BPF_SYSCALL\n 32:\t\tbool \"Enable bpf() system call\"\n 33:\t\tselect BPF\n 34:\t\tselect IRQ_WORK\n 35:\t\tselect NEED_TASKS_RCU\n 36:\t\tselect TASKS_TRACE_RCU\n 37:\t\tselect BINARY_PRINTF\n 38:\t\tselect NET_SOCK_MSG if NET\n 39:\t\tselect NET_XGRESS if NET\n 40:\t\tselect PAGE_POOL if NET\n 41:\t\tdefault n\n 42:\t\thelp\n 43:\t\t Enable the bpf() system call that allows to manipulate BPF programs\n 44:\t\t and maps via file descriptors.\n 45:\t\n 46:\tconfig BPF_JIT\n 47:\t\tbool \"Enable BPF Just In Time compiler\"\n 48:\t\tdepends on BPF\n 49:\t\tdepends on HAVE_CBPF_JIT || HAVE_EBPF_JIT\n 50:\t\tselect EXECMEM\n 51:\t\thelp\n 52:\t\t BPF programs are normally handled by a BPF interpreter. This option\n 53:\t\t allows the kernel to generate native code when a program is loaded\n 54:\t\t into the kernel. This will significantly speed-up processing of BPF\n 55:\t\t programs.\n 56:\t\n 57:\t\t Note, an admin should enable this feature changing:\n 58:\t\t /proc/sys/net/core/bpf_jit_enable\n 59:\t\t /proc/sys/net/core/bpf_jit_harden (optional)\n 60:\t\t /proc/sys/net/core/bpf_jit_kallsyms (optional)\n 61:\t\n 62:\tconfig BPF_JIT_ALWAYS_ON\n 63:\t\tbool \"Permanently enable BPF JIT and remove BPF interpreter\"\n 64:\t\tdepends on BPF_SYSCALL \u0026\u0026 HAVE_EBPF_JIT \u0026\u0026 BPF_JIT\n 65:\t\thelp\n 66:\t\t Enables BPF JIT and removes BPF interpreter to avoid speculative\n 67:\t\t execution of BPF instructions by the interpreter.\n 68:\t\n 69:\t\t When CONFIG_BPF_JIT_ALWAYS_ON is enabled, /proc/sys/net/core/bpf_jit_enable\n"
} |
| 15/2 | 2026/09/28 01:36 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 123214 output: 28 thoughts: 201 Thoughts: **Investigating BPF Configuration Dependencies** Okay, so I need to make sure I've got all the necessary configurations in place, especially around BPF syscall support. It looks like `BPF_SYSCALL` is the crucial one, but I should also verify the BTF situation. Let's see... I'll dive into `btf.c` and check how it relates to `DEBUG_INFO_BTF`. Right, let's take a look at the `kernel/bpf/Makefile`. Ah, there it is! I can see that `loops.o`, `heap.o`, and `scev.o` get compiled when `CONFIG_BPF_SYSCALL` is enabled. That's good to know. And now I need to check where `btf.c` gets compiled in the Makefile. That'll give me a full picture of what depends on what. |
| 16/2 | 2026/09/28 01:36 | tool | grepper |
0mArgs:{
"Expression": "btf\\.o",
"PathPrefix": "kernel/bpf"
}Results: {
"Output": "kernel/bpf/Makefile=13=obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o\nkernel/bpf/Makefile:14:obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o backtrack.o check_btf.o\nkernel/bpf/Makefile-15-obj-${CONFIG_BPF_LSM}\t += bpf_inode_storage.o\n--\nkernel/bpf/Makefile=17=obj-$(CONFIG_BPF_JIT) += trampoline.o\nkernel/bpf/Makefile:18:obj-$(CONFIG_BPF_SYSCALL) += btf.o memalloc.o rqspinlock.o stream.o\nkernel/bpf/Makefile-19-ifeq ($(CONFIG_MMU)$(CONFIG_64BIT),yy)\n--\nkernel/bpf/Makefile=43=ifeq ($(CONFIG_SYSFS),y)\nkernel/bpf/Makefile:44:obj-$(CONFIG_DEBUG_INFO_BTF) += sysfs_btf.o\nkernel/bpf/Makefile-45-endif\n"
} |
| 17/2 | 2026/09/28 01:36 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 123925 output: 293 thoughts: 1784 Thoughts: **eBPF Verifier Focus for Fuzzing** Okay, so `btf.o` is indeed under `CONFIG_BPF_SYSCALL`, confirming the BPF syscall requirement. And `DEBUG_INFO_BTF` seems relevant for BTF features as well. I need to make sure I haven't missed any other config dependencies related to BPF or BTF. `BPF_SYSCALL` is a given, so the question now is `CONFIG_DEBUG_INFO_BTF`. It looks like this config is used by the `btf_struct_access`, `btf_struct_walk`, etc functions for kernel and program BTF (`bpf_obj_new`). Moreover, `DEBUG_INFO_BTF` enables `vmlinux` BTF, which is tested by `verifier_btf_array_access.c`. Now, let's nail down which functions are affected. I need to focus on the key changes. In `verifier.c`, `handle_loop_entry_exit` is there (static), but `bpf_set_reg_range`, `bpf_reg_union`, `bpf_check` (ubiquitous, so I'll avoid it), and `bpf_needs_fixed_stack_off` are also present. In `scev.c`, there are `bpf_compute_scev`, `bpf_compute_loop_iters`, `bpf_widen_scev_regs`, and `bpf_clamp_scev_regs`. Then, from `loops.c`, `bpf_compute_loops`, `bpf_compute_idoms`, `bpf_loop_at_index`, and `bpf_is_nested_loop` are impacted. And in `states.c`, `bpf_split_cur_state` and `bpf_is_state_visited` are key. Finally, in `cnum.c`, there is `cnum64_intersect_linear` and in `btf.c` there's `btf_struct_access`. Following the "FocusSymbols" guidance, I need to extract feature-specific logic. I need to avoid ubiquitous functions like the top-level verifier entrypoint, `bpf_check`. So, the following functions look like the best targets, given they implement the new feature logic: `bpf_compute_scev`, `bpf_compute_loop_iters`, `bpf_widen_scev_regs`, `bpf_clamp_scev_regs`, `bpf_compute_loops`, `bpf_compute_idoms`, `bpf_split_cur_state`, `bpf_set_reg_range`, `bpf_reg_union`, `cnum64_intersect_linear` and `btf_struct_access`. I've verified that `cnum64_intersect_linear` is a global symbol in `kernel/bpf/cnum.c` and declared in `include/linux/cnum.h`. In `kernel/bpf/cnum_defs.h`, `cnum64_union` is `cnum_t FN(union)(struct cnum_t a, struct cnum_t b)`, so it expands to both `cnum64_union` and `cnum32_union`. `btf_struct_access` is declared in `include/linux/bpf_verifier.h` and the same applies to `bpf_split_cur_state`, `bpf_compute_idoms`, `bpf_compute_loops`, `bpf_compute_scev`, `bpf_compute_loop_iters`, `bpf_widen_scev_regs`, and `bpf_clamp_scev_regs`. I also need to make sure to note that `bpf_min_heap_push` exists in `kernel/bpf/heap.c`. These are all core to the introduced changes. Now, regarding the configs, `CONFIG_BPF_SYSCALL` is essential, and `CONFIG_DEBUG_INFO_BTF` is also needed. The `bpf_get_current_task_btf()` function requires BTF in the kernel, so this solidifies the need for `CONFIG_DEBUG_INFO_BTF`. Thus, both `BPF_SYSCALL` and `DEBUG_INFO_BTF` are appropriate. The patch introduces Scalar Evolution and loop widening analysis to the eBPF verifier, which is crucial for safety. It enables termination and induction variable range analysis for loops, as well as tracking step/base congruences for scalar registers, and supports BTF struct array variable-offset accesses |
| 18/2 | 2026/09/28 01:36 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_compute_loops",
"bpf_compute_idoms",
"bpf_compute_loop_iters",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_split_cur_state",
"bpf_set_reg_range",
"bpf_reg_union",
"cnum64_intersect_linear",
"btf_struct_access"
],
"Reasoning": "The patch series implements Scalar Evolution (SCEV) and loop induction variable analysis in the eBPF verifier. It adds CFG dominator tree computation (idoms), natural loop and backedge/exit detection, symbolic expression tracking, loop bound calculation, register widening, and clamping to verify bounded loops. It also introduces linear step/base tracking for scalar registers and variable-offset access validation for BTF struct arrays. These changes modify core verifier logic reachable from userspace via the bpf(BPF_PROG_LOAD, ...) syscall, making fuzzing essential to uncover soundness bugs, safety regressions, and unexpected verifier crashes.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"BPF_SYSCALL",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"bpf_compute_scev",
"bpf_compute_loops",
"bpf_compute_idoms",
"bpf_compute_loop_iters",
"bpf_widen_scev_regs",
"bpf_clamp_scev_regs",
"bpf_split_cur_state",
"bpf_set_reg_range",
"bpf_reg_union",
"cnum64_intersect_linear",
"btf_struct_access"
],
"Reasoning": "The patch series implements Scalar Evolution (SCEV) and loop induction variable analysis in the eBPF verifier. It adds CFG dominator tree computation (idoms), natural loop and backedge/exit detection, symbolic expression tracking, loop bound calculation, register widening, and clamping to verify bounded loops. It also introduces linear step/base tracking for scalar registers and variable-offset access validation for BTF struct arrays. These changes modify core verifier logic reachable from userspace via the bpf(BPF_PROG_LOAD, ...) syscall, making fuzzing essential to uncover soundness bugs, safety regressions, and unexpected verifier crashes.",
"WorthFuzzing": true
} |
| 19/1 | 2026/09/28 01:36 | action | If |
5mArgs:{
"WorthFuzzing": true
}Results: null |
| 20/2 | 2026/09/28 01:36 | agent | kmsan-evaluator |
5mModel:core Args: null Results: {
"KMSANReasoning": "The patch series introduces loop analysis and Scalar Evolution (SCEV) to the eBPF verifier. It adds CFG algorithms (immediate dominator calculation, loop and latch detection), a binary min-heap for worklist processing, symbolic SCEV expression tracking, loop iteration estimation, register range widening/clamping, and support for variable-offset BTF struct array accesses.\n\nKMSAN vs KASAN applicability:\n- Uninitialized memory / Info-leaks (KMSAN): No kernel memory or structs are copied to user space (the verifier produces formatted log text and returns integer return codes). All newly introduced data structures (e.g., struct bpf_loop, struct bpf_loop_exit, struct scev, struct env, idoms, postorder arrays, heap buffers) are allocated using kzalloc, kvcalloc, kvzalloc, or with __GFP_ZERO. Local stack variables (such as struct bpf_loop_iters, struct linear_latch, struct bounds, struct array_access) are either explicitly zeroed or fully populated before their fields are read. No uninitialized memory is read or exposed.\n- Memory safety and logic correctness (KASAN): The risks in this patch are typical of compiler/verifier analysis passes: out-of-bounds indexing in instruction/graph arrays, heap buffer bounds in the worklist binary heap, memory leaks, and verifier soundness bugs (such as incorrect bounds widening that could permit out-of-bounds accesses during BPF execution). These failure modes are detected by KASAN, UBSAN, and standard kernel debugging facilities, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit d7942ef1185d903ecca00472af297f633f20d95d
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Sep 28 01:35:30 2026 +0000
syz-cluster: applied patch under review
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c775bd7577063..a5fa2b5cc0c0d 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -9,6 +9,20 @@
#include <linux/filter.h> /* for MAX_BPF_STACK */
#include <linux/tnum.h>
#include <linux/cnum.h>
+#include <linux/math64.h> /* for div_s64_rem() */
+
+/*
+ * Mathematical modulo, the residue of 'v' modulo 'step', normalized to [0, step).
+ * This differs from C's '%' operator, which truncates the quotient toward zero
+ * and so returns a remainder with the sign of the dividend (e.g. -1 % 3 == -1, not 2).
+ */
+static inline u16 imod(s64 v, u16 step)
+{
+ s32 rem;
+
+ div_s64_rem(v, step, &rem);
+ return rem < 0 ? rem + step : rem;
+}
/* Maximum variable offset umax_value permitted when resolving memory accesses.
* In practice this is far bigger than any realistic pointer offset; this limit
@@ -164,6 +178,13 @@ struct bpf_reg_state {
* during state comparisons.
*/
u32 map_uid;
+ /*
+ * The value described by this register is some point lying on
+ * a line described by a linear equation base + step * k.
+ * Invariant: base < step.
+ */
+ u16 base;
+ u16 step;
/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
bool precise;
};
@@ -307,6 +328,21 @@ struct bpf_retval_range {
bool return_32bit;
};
+struct bpf_loop_iters {
+ u32 min_header_count; /* min number of times header is executed */
+ u32 max_header_count; /* max number of times header is executed */
+ bool pre_cond;
+};
+
+struct loop_stack_entry {
+ struct bpf_verifier_state *entry_state;
+ struct bpf_loop_iters iters;
+ u32 loop_id:31;
+ u32 terminates:1;
+};
+
+#define LOOP_STACK_SIZE 16
+
/* state of the program:
* type of all registers and stack info
*/
@@ -352,6 +388,12 @@ struct bpf_func_state {
u32 callback_depth;
/* Instructions processed in this frame and callees on the current path. */
u32 insns_subtotal;
+ /*
+ * Control-flow loop nesting at the current insn within this frame's
+ * subprogram (loops never cross subprogram boundaries).
+ */
+ u32 loop_stack_cnt;
+ struct loop_stack_entry loop_stack[LOOP_STACK_SIZE];
/* The following fields should be last. See copy_func_state() */
/* The state of the stack. Each element of the array describes BPF_REG_SIZE
@@ -415,6 +457,7 @@ static_assert(MAX_BPF_STACK_SLOTS <= (1 << 12));
#define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS)
#define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \
MAX_CALL_FRAMES)
+
struct bpf_verifier_state {
/* call stack tracking */
struct bpf_func_state *frame[MAX_CALL_FRAMES];
@@ -481,7 +524,9 @@ struct bpf_verifier_state {
bool speculative;
bool in_sleepable;
- /* first and last insn idx of this verifier state */
+ /* First and last insn idx of this verifier state.
+ * last_insn_idx is -1 if no instructions have been executed yet.
+ */
u32 first_insn_idx;
u32 last_insn_idx;
/* if this state is a backedge state then equal_state
@@ -629,6 +674,44 @@ struct bpf_iarray {
u32 items[];
};
+#define iarray_for_each(item, arr) \
+ for (int ___idx = 0; \
+ ___idx < (arr)->cnt && ({ item = (arr)->items[___idx]; 1; }); \
+ ___idx++)
+
+#define MAX_BACKEDGES 16
+#define MAX_LOOP_EXITS 256
+
+struct bpf_backedge {
+ int from;
+ int latch; /* -1 if no latch can be found */
+};
+
+struct bpf_loop_exit {
+ int from; /* instruction inside the loop */
+ int to; /* instruction outside the loop */
+};
+
+/* SCEV/widening register space: r0..r10 plus every stack slot of a frame. */
+#define BPF_SCEV_REGS_NUM (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)
+
+struct bpf_loop {
+ struct bpf_backedge backedges[MAX_BACKEDGES];
+ /* edges exiting from this loop, includes edges from nested loops */
+ struct bpf_loop_exit *exits;
+ int backedges_cnt;
+ int exits_cnt;
+ bool irreducible;
+ bool backedges_overflow;
+ bool exits_overflow;
+ /*
+ * Loop-entry registers used to compute stack addresses for loads,
+ * stores and calls requiring fixed stack offsets, in this and nested
+ * loops.
+ */
+ unsigned long store_base_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
+};
+
struct bpf_insn_aux_data {
union {
enum bpf_reg_type ptr_type; /* pointer type for load/store insns */
@@ -662,6 +745,13 @@ struct bpf_insn_aux_data {
};
struct btf_struct_meta *kptr_struct_meta;
u64 map_key_state; /* constant (32 bit) key tracking for maps */
+ /*
+ * Per-instruction summary of stack slots in the current frame
+ * that this instruction may write to.
+ */
+ DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
+ DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
+ u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
bool nospec; /* do not execute this instruction speculatively */
@@ -672,6 +762,8 @@ struct bpf_insn_aux_data {
bool non_sleepable; /* helper/kfunc may be called from non-sleepable context */
bool is_iter_next; /* bpf_iter_<type>_next() kfunc call */
bool call_with_percpu_alloc_ptr; /* {this,per}_cpu_ptr() with prog percpu alloc */
+ bool bb_end;
+ bool need_scev;
u8 alu_state; /* used in combination with alu_limit */
/* true if STX or LDX instruction is a part of a spill/fill
* pattern for a bpf_fastcall call.
@@ -699,6 +791,13 @@ struct bpf_insn_aux_data {
u32 non_stack_access:1; /* instruction can access non-stack memory */
/* true if some jump or call instruction targets this instruction */
u32 jump_target:1;
+ /*
+ * True if this instruction is a loop entry. For loops with a single entry
+ * this bit will coincide with 'loop' pointer being non-NULL.
+ * Irreducible loops have multiple entries, all of them will be marked as 'loop_entry',
+ * but only the one at 'loop_header' will have a non-NULL 'loop' pointer.
+ */
+ u32 loop_entry:1;
/*
* CFG strongly connected component this instruction belongs to,
* zero if it is a singleton SCC.
@@ -718,6 +817,10 @@ struct bpf_insn_aux_data {
u16 const_reg_map_mask;
u16 const_reg_subprog_mask;
u32 const_reg_vals[10];
+ /* index of a loop header of the innermost loop containing this instruction, -1 if none */
+ s32 loop_header;
+ /* additional information about the loop if this instruction is a loop header */
+ struct bpf_loop *loop;
};
#define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
@@ -920,6 +1023,7 @@ struct bpf_scc_info {
};
struct bpf_liveness;
+struct scev;
struct bpf_fd_array {
union {
@@ -1005,6 +1109,7 @@ struct bpf_verifier_env {
* see bpf_subprog_info->postorder_start.
*/
int *insn_postorder;
+ int *postorder_nums;
int cur_stack;
/* current position in the insn_postorder vector */
int cur_postorder;
@@ -1080,6 +1185,10 @@ struct bpf_verifier_env {
u32 scc_cnt;
struct bpf_iarray *succ;
struct bpf_iarray *gotox_tmp_buf;
+ int *idoms;
+ struct scev *scev;
+ /* SCEV representation of stack slots not allocated yet. */
+ struct bpf_reg_state scev_not_init_reg;
};
static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1258,6 +1367,7 @@ void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
int mark_chain_precision(struct bpf_verifier_env *env, int regno);
int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx);
+int bpf_split_cur_state(struct bpf_verifier_env *env);
int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
void bpf_clear_jmp_history(struct bpf_verifier_state *state);
@@ -1272,6 +1382,7 @@ int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state
void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist);
void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
struct bpf_reg_state *reg);
+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg);
void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,
struct bpf_verifier_state *st);
@@ -1724,10 +1835,16 @@ s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env,
struct bpf_insn *insn, int arg,
int insn_idx);
int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);
+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
+ struct cnum64 range, u16 step);
+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
+ const struct bpf_reg_state *src);
int bpf_stack_liveness_init(struct bpf_verifier_env *env);
void bpf_stack_liveness_free(struct bpf_verifier_env *env);
int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
int bpf_compute_live_registers(struct bpf_verifier_env *env);
@@ -1819,6 +1936,7 @@ int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 bt
struct bpf_attach_target_info *tgt_info);
/* Functions in fixups.c, called from bpf_check() */
+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len);
int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env);
int bpf_optimize_bpf_loop(struct bpf_verifier_env *env);
void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);
@@ -1831,4 +1949,40 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env);
int bpf_do_misc_fixups(struct bpf_verifier_env *env);
int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
+int bpf_flip_opcode(u32 opcode);
+u8 bpf_rev_opcode(u8 opcode);
+
+int bpf_compute_idoms(struct bpf_verifier_env *env);
+int bpf_compute_loops(struct bpf_verifier_env *env);
+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
+
+/*
+ * Simple binary heap implementation as described by
+ * https://en.wikipedia.org/wiki/Binary_heap
+ */
+struct bpf_min_heap {
+ int (*compare)(int, int, void *); /* ordering function for @elements */
+ int *elements; /* min-heap ordered by @compare */
+ void *arg; /* 3rd argument passed to @compare */
+ int capacity;
+ int count;
+};
+
+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg);
+void bpf_min_heap_free(struct bpf_min_heap *heap);
+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt);
+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt);
+
+int bpf_init_scev(struct bpf_verifier_env *env);
+void bpf_free_scev(struct bpf_verifier_env *env);
+int bpf_compute_scev(struct bpf_verifier_env *env);
+
+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_loop_iters *iters);
+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters);
+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 insn_idx,
+ struct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters);
+
#endif /* _LINUX_BPF_VERIFIER_H */
diff --git a/include/linux/cnum.h b/include/linux/cnum.h
index 49b7d0c7645de..49160318adf90 100644
--- a/include/linux/cnum.h
+++ b/include/linux/cnum.h
@@ -39,6 +39,7 @@ u32 cnum32_umin(struct cnum32 cnum);
u32 cnum32_umax(struct cnum32 cnum);
s32 cnum32_smin(struct cnum32 cnum);
s32 cnum32_smax(struct cnum32 cnum);
+struct cnum32 cnum32_union(struct cnum32 a, struct cnum32 b);
struct cnum32 cnum32_intersect(struct cnum32 a, struct cnum32 b);
void cnum32_intersect_with(struct cnum32 *dst, struct cnum32 src);
void cnum32_intersect_with_urange(struct cnum32 *dst, u32 min, u32 max);
@@ -65,6 +66,7 @@ u64 cnum64_umin(struct cnum64 cnum);
u64 cnum64_umax(struct cnum64 cnum);
s64 cnum64_smin(struct cnum64 cnum);
s64 cnum64_smax(struct cnum64 cnum);
+struct cnum64 cnum64_union(struct cnum64 a, struct cnum64 b);
struct cnum64 cnum64_intersect(struct cnum64 a, struct cnum64 b);
void cnum64_intersect_with(struct cnum64 *dst, struct cnum64 src);
void cnum64_intersect_with_urange(struct cnum64 *dst, u64 min, u64 max);
@@ -78,5 +80,6 @@ bool cnum64_is_subset(struct cnum64 outer, struct cnum64 inner);
struct cnum32 cnum32_from_cnum64(struct cnum64 cnum);
struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b);
+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step);
#endif /* _LINUX_CNUM_H */
diff --git a/include/linux/tnum.h b/include/linux/tnum.h
index ca2cfec8de08a..16682248f963a 100644
--- a/include/linux/tnum.h
+++ b/include/linux/tnum.h
@@ -134,4 +134,6 @@ static inline bool tnum_subreg_is_const(struct tnum a)
/* Returns the smallest member of t larger than z */
u64 tnum_step(struct tnum t, u64 z);
+u32 tnum_alignment(struct tnum a);
+
#endif /* _LINUX_TNUM_H */
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index c1f9b0d3468d3..fdff31d962d6c 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -6,7 +6,7 @@ cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
endif
CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
-obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o
+obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o loops.o heap.o scev.o
obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
diff --git a/kernel/bpf/backtrack.c b/kernel/bpf/backtrack.c
index 0e38b9575328c..43d5740034c0f 100644
--- a/kernel/bpf/backtrack.c
+++ b/kernel/bpf/backtrack.c
@@ -888,6 +888,10 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,
}
if (last_idx < 0) {
+ /* Consecutive checkpoints can have no instructions between them. */
+ if (st->parent)
+ goto parent;
+
/* we are at the entry into subprog, which
* is expected for global funcs, but only if
* requested precise registers are R1-R5
@@ -952,6 +956,7 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env,
return -EFAULT;
}
}
+parent:
st = st->parent;
if (!st)
break;
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 9bcfefdfb7346..37437b93471d2 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -7496,6 +7496,14 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,
}
EXPORT_SYMBOL_GPL(btf_ctx_access);
+#define MAX_ARRAYS_WALK 16
+
+/* Description of an array crossed while walking a BTF access chain */
+struct array_access {
+ u32 id; /* BTF_KIND_ARRAY type id */
+ u32 off; /* offset of the access within the array */
+};
+
enum bpf_struct_walk_result {
/* < 0 error */
WALK_SCALAR = 0,
@@ -7504,10 +7512,43 @@ enum bpf_struct_walk_result {
WALK_STRUCT,
};
+static const struct btf_member *find_flex_member(const struct btf *btf, const struct btf_type *t)
+{
+ const struct btf_array *array;
+ const struct btf_type *mtype;
+ const struct btf_member *member;
+ u32 vlen = btf_type_vlen(t);
+
+ if (vlen == 0)
+ return NULL;
+
+ member = btf_type_member(t) + vlen - 1;
+ mtype = btf_type_skip_modifiers(btf, member->type, NULL);
+ if (!btf_type_is_array(mtype))
+ return NULL;
+
+ array = (const struct btf_array *)(mtype + 1);
+ if (array->nelems != 0)
+ return NULL;
+
+ return member;
+}
+
+static int push_array(struct array_access *arrays, u32 *arrays_cnt, struct array_access item)
+{
+ if (arrays == NULL)
+ return 0;
+ if (*arrays_cnt == MAX_ARRAYS_WALK)
+ return -1;
+ arrays[(*arrays_cnt)++] = item;
+ return 0;
+}
+
static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
const struct btf_type *t, int off, int size,
u32 *next_btf_id, enum bpf_type_flag *flag,
- const char **field_name, bool walk_flex_arrays)
+ const char **field_name, bool walk_flex_arrays,
+ struct array_access *arrays, u32 *arrays_cnt)
{
u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
const struct btf_type *mtype, *elem_type = NULL;
@@ -7542,22 +7583,19 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
/* If the last element is a variable size array, we may
* need to relax the rule.
*/
- if (vlen == 0)
+ member = find_flex_member(btf, t);
+ if (!member)
goto error;
- member = btf_type_member(t) + vlen - 1;
- mtype = btf_type_skip_modifiers(btf, member->type,
- NULL);
- if (!btf_type_is_array(mtype))
+ moff = __btf_member_bit_offset(t, member) / 8;
+ if (off < moff)
goto error;
+ mtype = btf_type_skip_modifiers(btf, member->type, &mid);
array_elem = (struct btf_array *)(mtype + 1);
- if (array_elem->nelems != 0)
- goto error;
- moff = __btf_member_bit_offset(t, member) / 8;
- if (off < moff)
- goto error;
+ if (push_array(arrays, arrays_cnt, (struct array_access){ mid, off - moff }))
+ return -E2BIG;
/* allow structure and integer */
t = btf_type_skip_modifiers(btf, array_elem->type,
@@ -7680,6 +7718,9 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
* the array's element as long as it is
* within the mtrue_end boundary.
*/
+ if (push_array(arrays, arrays_cnt,
+ (struct array_access){ mid, off - moff }))
+ return -E2BIG;
/* skip empty array */
if (moff == mtrue_end)
@@ -7772,15 +7813,29 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
int btf_struct_access(struct bpf_verifier_log *log,
const struct bpf_reg_state *reg,
- int off, int size, enum bpf_access_type atype __maybe_unused,
+ int _off, int size, enum bpf_access_type atype __maybe_unused,
u32 *next_btf_id, enum bpf_type_flag *flag,
const char **field_name)
{
const struct btf *btf = reg->btf;
enum bpf_type_flag tmp_flag = 0;
+ struct array_access arrays[MAX_ARRAYS_WALK];
+ const struct btf_member *member;
const struct btf_type *t;
+ u32 i, arrays_cnt = 0;
u32 id = reg->btf_id;
- int err;
+ s64 min_off, max_off, flex_off;
+ int err, off, ret;
+
+ if (check_add_overflow(reg_smin(reg), (s64)_off, &min_off) ||
+ check_add_overflow(reg_smax(reg), (s64)_off, &max_off) ||
+ min_off != (int)min_off) {
+ bpf_log(log,
+ "offset computation overflows: register offset range is [%lld, %lld], instruction offset is %d\n",
+ reg_smin(reg), reg_smax(reg), _off);
+ return -EINVAL;
+ }
+ off = min_off;
while (type_is_alloc(reg->type)) {
struct btf_struct_meta *meta;
@@ -7807,26 +7862,30 @@ int btf_struct_access(struct bpf_verifier_log *log,
t = btf_type_by_id(btf, id);
do {
err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag,
- field_name, !type_is_alloc(reg->type));
-
+ field_name, !type_is_alloc(reg->type), arrays, &arrays_cnt);
switch (err) {
case WALK_PTR:
/* For local types, the destination register cannot
* become a pointer again.
*/
- if (type_is_alloc(reg->type))
- return SCALAR_VALUE;
+ if (type_is_alloc(reg->type)) {
+ ret = SCALAR_VALUE;
+ goto check_variable_offset;
+ }
/* If we found the pointer or scalar on t+off,
* we're done.
*/
*next_btf_id = id;
*flag = tmp_flag;
- return PTR_TO_BTF_ID;
+ ret = PTR_TO_BTF_ID;
+ goto check_variable_offset;
case WALK_PTR_UNTRUSTED:
*flag = MEM_RDONLY | PTR_UNTRUSTED;
- return PTR_TO_MEM;
+ ret = PTR_TO_MEM;
+ goto check_variable_offset;
case WALK_SCALAR:
- return SCALAR_VALUE;
+ ret = SCALAR_VALUE;
+ goto check_variable_offset;
case WALK_STRUCT:
/* We found nested struct, so continue the search
* by diving in it. At this point the offset is
@@ -7846,6 +7905,54 @@ int btf_struct_access(struct bpf_verifier_log *log,
} while (t);
return -EINVAL;
+
+check_variable_offset:
+ if (min_off == max_off)
+ return ret;
+
+ /* Find an offset at which access would go to a flexible array tail (if any). */
+ t = btf_type_skip_modifiers(btf, reg->btf_id, NULL);
+ member = find_flex_member(btf, t);
+ flex_off = member ? __btf_member_bit_offset(t, member) / 8 : S64_MAX;
+
+ /*
+ * If this is a varying offset access, the step recorded within a register
+ * should correspond to one of the arrays visited while walking.
+ */
+ for (i = 0; i < arrays_cnt; i++) {
+ s64 array_start, array_end, access_end;
+ u32 asize, esize, elem_id;
+
+ /*
+ * 'arrays' records top-level arrays only, use __btf_resolve_size()
+ * to get flattened representation.
+ */
+ t = btf_type_by_id(btf, arrays[i].id);
+ if (IS_ERR(__btf_resolve_size(btf, t, &asize, NULL, &elem_id, NULL, NULL)) ||
+ IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, elem_id), &esize)))
+ continue;
+ /* Make sure every accessed offset lands on the same field of some element. */
+ if (esize == 0 || reg->step % esize != 0)
+ continue;
+
+ array_start = min_off - arrays[i].off;
+ /* An array within the flexible tail has no upper bound to exceed */
+ if (array_start >= flex_off)
+ return ret;
+
+ /* the 'size' bytes read at max_off must stay within the array */
+ if (check_add_overflow(array_start, (s64)asize, &array_end) ||
+ check_add_overflow(max_off, (s64)size, &access_end) ||
+ access_end > array_end)
+ continue;
+ return ret;
+ }
+
+ bpf_log(log,
+ "invalid variable offset access into struct %s: offsets [%lld, %lld] size %d step %d do not match any array\n",
+ btf_name_by_offset(btf, btf_type_by_id(btf, reg->btf_id)->name_off),
+ min_off, max_off, size, reg->step);
+ return -EINVAL;
}
/* Check that two BTF types, each specified as an BTF object + id, are exactly
@@ -7886,7 +7993,7 @@ bool btf_struct_ids_match(struct bpf_verifier_log *log,
if (!type)
return false;
err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL,
- walk_flex_arrays);
+ walk_flex_arrays, NULL, NULL);
if (err != WALK_STRUCT)
return false;
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index b0bd9ba951dfb..bd771efec66a3 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -767,6 +767,11 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
return ret;
}
+struct dfs_state {
+ u32 traversed:1;
+ u32 next_succ:31;
+};
+
/*
* For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
* [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
@@ -774,43 +779,52 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
*/
int bpf_compute_postorder(struct bpf_verifier_env *env)
{
- u32 cur_postorder, i, top, stack_sz, s;
- int *stack = NULL, *postorder = NULL, *state = NULL;
- struct bpf_iarray *succ;
+ int *stack = NULL, *postorder = NULL, *postorder_nums = NULL;
+ int subprog_idx, stack_sz, cur, s, cur_postorder, start;
+ struct dfs_state *state = NULL;
+ struct bpf_iarray *succ = NULL;
+ postorder_nums = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
postorder = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
- state = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
stack = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT);
- if (!postorder || !state || !stack) {
+ state = kvzalloc_objs(struct dfs_state, env->prog->len, GFP_KERNEL_ACCOUNT);
+ if (!postorder_nums || !postorder || !stack || !state) {
+ kvfree(postorder_nums);
kvfree(postorder);
- kvfree(state);
kvfree(stack);
+ kvfree(state);
return -ENOMEM;
}
cur_postorder = 0;
- for (i = 0; i < env->subprog_cnt; i++) {
- env->subprog_info[i].postorder_start = cur_postorder;
- stack[0] = env->subprog_info[i].start;
+ for (subprog_idx = 0; subprog_idx < env->subprog_cnt; subprog_idx++) {
+ start = env->subprog_info[subprog_idx].start;
+ env->subprog_info[subprog_idx].postorder_start = cur_postorder;
+ stack[0] = start;
stack_sz = 1;
+ state[start].traversed = true;
do {
- top = stack[stack_sz - 1];
- state[top] |= DISCOVERED;
- if (state[top] & EXPLORED) {
- postorder[cur_postorder++] = top;
+ cur = stack[stack_sz - 1];
+ succ = bpf_insn_successors(env, cur);
+ if (state[cur].next_succ == succ->cnt) {
+ postorder_nums[cur] = cur_postorder;
+ postorder[cur_postorder] = cur;
+ cur_postorder++;
stack_sz--;
continue;
}
- succ = bpf_insn_successors(env, top);
- for (s = 0; s < succ->cnt; ++s) {
- if (!state[succ->items[s]]) {
- stack[stack_sz++] = succ->items[s];
- state[succ->items[s]] |= DISCOVERED;
- }
+ s = succ->items[state[cur].next_succ];
+ if (!state[s].traversed) {
+ state[s].traversed = true;
+ state[s].next_succ = 0;
+ stack[stack_sz] = s;
+ stack_sz++;
+ continue;
}
- state[top] |= EXPLORED;
+ state[cur].next_succ++;
} while (stack_sz);
}
- env->subprog_info[i].postorder_start = cur_postorder;
+ env->subprog_info[subprog_idx].postorder_start = cur_postorder;
+ env->cfg.postorder_nums = postorder_nums;
env->cfg.insn_postorder = postorder;
env->cfg.cur_postorder = cur_postorder;
kvfree(stack);
diff --git a/kernel/bpf/cnum.c b/kernel/bpf/cnum.c
index 86142cb2aee5f..2bff2c7e0cdf5 100644
--- a/kernel/bpf/cnum.c
+++ b/kernel/bpf/cnum.c
@@ -2,6 +2,7 @@
/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
#include <linux/bits.h>
+#include <linux/bpf_verifier.h> /* for imod() */
#define T 32
#include "cnum_defs.h"
@@ -118,3 +119,38 @@ struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b)
}
return t;
}
+
+/* Intersect 'in' with the set of integers defined by equation 'base + step * k'. */
+struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step)
+{
+ s64 smin = cnum64_smin(in);
+ s64 smax = cnum64_smax(in);
+ s64 lo, hi;
+ u16 d;
+
+ if (step <= 1 || cnum64_is_empty(in))
+ return in;
+ /*
+ * Round smin up to the next value congruent to 'base' modulo 'step',
+ * i.e. increase smin by d = (base - smin) mod step:
+ *
+ * |<---- d ---->|
+ * |-----------|=============|...
+ * base+step*k smin base+step*(k+1)
+ */
+ d = imod(base - imod(smin, step), step);
+ if ((u64)smax - (u64)smin < d)
+ return CNUM64_EMPTY;
+ lo = smin + d;
+ /*
+ * Round smax down to the previous value congruent to 'base' modulo 'step',
+ * i.e. decrease smax by d = (smax - base) mod step:
+ *
+ * |<--- d --->|
+ * ...|===========|-------------|
+ * base+step*k smax base+step*(k+1)
+ */
+ d = imod(imod(smax, step) - base, step);
+ hi = smax - d;
+ return cnum64_from_srange(lo, hi);
+}
diff --git a/kernel/bpf/cnum_defs.h b/kernel/bpf/cnum_defs.h
index 30685e43de049..05b17a8b4814f 100644
--- a/kernel/bpf/cnum_defs.h
+++ b/kernel/bpf/cnum_defs.h
@@ -198,6 +198,50 @@ static inline struct cnum_t FN(normalize)(struct cnum_t cnum)
return cnum;
}
+/*
+ * Return a smallest arc containing both 'a' and 'b'.
+ * Break equal-size ties by choosing the smaller base.
+ */
+struct cnum_t FN(union)(struct cnum_t a, struct cnum_t b)
+{
+ struct cnum_t b1, ab, ba;
+ ut end;
+
+ if (FN(is_empty)(a))
+ return b;
+ if (FN(is_empty)(b))
+ return a;
+
+ /*
+ * Rotate so that a1.base == 0 and a1.end == a.size.
+ * Normalize b1 to preserve the full-circle representation.
+ */
+ b1 = FN(normalize)((struct cnum_t){ b.base - a.base, b.size });
+ end = max(a.size, (ut)(b1.base + b1.size));
+
+ if (FN(urange_overflow)(b1)) {
+ /* a1 reaches b1's main arc: together they cover the circle. */
+ if (b1.base <= a.size)
+ return (struct cnum_t){ 0, UT_MAX };
+
+ /* Extend b1's tail through a1's end, then rotate back. */
+ return FN(normalize)((struct cnum_t){ b.base, end - b1.base });
+ }
+
+ /* ab, rotated back, covers both nonwrapping arcs. */
+ ab = (struct cnum_t){ a.base, end };
+ if (b1.base <= a.size)
+ return FN(normalize)(ab);
+
+ /* The arcs are disjoint; ba is the other possible covering arc. */
+ ba = (struct cnum_t){ b.base, a.size - b1.base };
+ if (ba.size < ab.size ||
+ (ba.size == ab.size && ba.base < ab.base))
+ ab = ba;
+
+ return FN(normalize)(ab);
+}
+
struct cnum_t FN(add)(struct cnum_t a, struct cnum_t b)
{
if (FN(is_empty)(a) || FN(is_empty)(b))
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 37cf130ebb57b..ecea117f2848f 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -614,6 +614,22 @@ static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
return 0;
}
+/* Clean up dynamically allocated fields of aux data for instructions [start, ...] */
+void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
+{
+ struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
+ int end = start + len;
+ int i;
+
+ for (i = start; i < end; i++) {
+ if (aux_data[i].loop) {
+ kvfree(aux_data[i].loop->exits);
+ kvfree(aux_data[i].loop);
+ aux_data[i].loop = NULL;
+ }
+ }
+}
+
static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
@@ -626,6 +642,8 @@ static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
if (bpf_prog_is_offloaded(env->prog->aux))
bpf_prog_offload_remove_insns(env, off, cnt);
+ bpf_clear_insn_aux_data(env, off, cnt);
+
err = bpf_remove_insns(env->prog, off, cnt);
if (err)
return err;
diff --git a/kernel/bpf/heap.c b/kernel/bpf/heap.c
new file mode 100644
index 0000000000000..029f9217b8726
--- /dev/null
+++ b/kernel/bpf/heap.c
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf_verifier.h>
+
+/* Indexes for binary tree encoded as an array */
+static inline int left_child(int i) { return 2 * i + 1; }
+static inline int right_child(int i) { return 2 * i + 2; }
+static inline int parent(int i) { return (i - 1) / 2; }
+
+static inline int greater(struct bpf_min_heap *heap, int a, int b)
+{
+ return heap->compare(a, b, heap->arg) > 0;
+}
+
+void bpf_min_heap_init(struct bpf_min_heap *heap, int (*compare)(int, int, void *), void *arg)
+{
+ memset(heap, 0, sizeof(*heap));
+ heap->compare = compare;
+ heap->arg = arg;
+}
+
+void bpf_min_heap_free(struct bpf_min_heap *heap)
+{
+ kfree(heap->elements);
+ heap->elements = NULL;
+ heap->capacity = 0;
+ heap->count = 0;
+}
+
+int bpf_min_heap_push(struct bpf_min_heap *heap, int elt)
+{
+ int new_capacity, i;
+ int *elements;
+ void *tmp;
+
+ if (heap->count == heap->capacity) {
+ new_capacity = heap->capacity ? heap->capacity * 2 : 16;
+ tmp = krealloc(heap->elements,
+ sizeof(*heap->elements) * new_capacity,
+ GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ heap->elements = tmp;
+ heap->capacity = new_capacity;
+ }
+
+ elements = heap->elements;
+ i = heap->count;
+ elements[i] = elt;
+ heap->count++;
+ while (i != 0 && greater(heap, elements[parent(i)], elements[i])) {
+ swap(elements[i], elements[parent(i)]);
+ i = parent(i);
+ }
+ return 0;
+}
+
+static inline void sink_root(struct bpf_min_heap *heap)
+{
+ int *elements = heap->elements;
+ int i = 0;
+
+ while ((left_child(i) < heap->count && greater(heap, elements[i], elements[left_child(i)])) ||
+ (right_child(i) < heap->count && greater(heap, elements[i], elements[right_child(i)]))) {
+ if (right_child(i) >= heap->count || greater(heap, elements[right_child(i)], elements[left_child(i)])) {
+ swap(elements[i], elements[left_child(i)]);
+ i = left_child(i);
+ } else {
+ swap(elements[i], elements[right_child(i)]);
+ i = right_child(i);
+ }
+ }
+}
+
+bool bpf_min_heap_pop(struct bpf_min_heap *heap, int *elt)
+{
+ if (heap->count == 0)
+ return false;
+
+ int *elements = heap->elements;
+ *elt = elements[0];
+ elements[0] = elements[heap->count - 1];
+ --heap->count;
+ sink_root(heap);
+ return true;
+}
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index cd9523f69298e..cba3a6c021b49 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -23,6 +23,7 @@ enum {
FM_MAY_READ, /* stack slots that may be read by this instruction */
FM_MUST_WRITE, /* stack slots written by this instruction */
FM_LIVE_BEFORE, /* stack slots that may be read by this insn and its successors */
+ FM_MAY_WRITE, /* stack slots that may be written by this instruction */
FM_MASK_CNT,
};
@@ -262,6 +263,12 @@ static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_
return mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi);
}
+static int mark_stack_may_write(struct func_instance *instance, u32 frame, u32 insn_idx,
+ s32 lo, s32 hi)
+{
+ return mark_stack_range(instance, frame, insn_idx, FM_MAY_WRITE, lo, hi);
+}
+
/*
* Mark every half-slot of @frame as possibly read by @insn_idx. This widens
* the masks to the program's stack budget: a full read recorded at a narrower
@@ -277,9 +284,16 @@ static int mark_stack_read_all(struct bpf_verifier_env *env, struct func_instanc
env->stack_limit / BPF_HALF_REG_SIZE - 1);
}
-/* Accumulate @src, a mask @src_words wide, into may_read of @frame at @insn_idx */
-static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,
- const unsigned long *src, u32 src_words)
+static int mark_stack_may_write_all(struct bpf_verifier_env *env, struct func_instance *instance,
+ u32 frame, u32 insn_idx)
+{
+ return mark_stack_may_write(instance, frame, insn_idx, 0,
+ env->stack_limit / BPF_HALF_REG_SIZE - 1);
+}
+
+/* Accumulate @src, a mask @src_words wide, into @kind mask of @frame at @insn_idx */
+static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_idx, u32 kind,
+ const unsigned long *src, u32 src_words)
{
u32 nbits = src_words * BITS_PER_LONG;
struct frame_masks *fm;
@@ -292,7 +306,7 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i
fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1));
if (!fm)
return -ENOMEM;
- dst = rel_mask(fm, relative_idx(instance, insn_idx), FM_MAY_READ);
+ dst = rel_mask(fm, relative_idx(instance, insn_idx), kind);
/* @src has no bits set past @last, hence none past @fm->words either */
src_words = min(src_words, fm->words);
for (w = 0; w < src_words; w++)
@@ -300,6 +314,12 @@ static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 i
return 0;
}
+static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,
+ const unsigned long *src, u32 src_words)
+{
+ return mark_stack_mask(instance, frame, insn_idx, FM_MAY_READ, src, src_words);
+}
+
int bpf_jmp_offset(struct bpf_insn *insn)
{
u8 code = insn->code;
@@ -624,16 +644,41 @@ static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first,
return env->tmp_str_buf;
}
+/* Print mask @kind of the instruction at relative index @i for every frame, if any bit is set. */
+static bool print_mask(struct bpf_verifier_env *env, struct func_instance *instance, int i,
+ const char *name, u32 kind)
+{
+ struct frame_masks *fm;
+ bool printed = false;
+ unsigned long *mask;
+ int frame;
+ u64 pos;
+
+ pos = env->log.end_pos;
+ verbose(env, "%s", name);
+ for (frame = instance->depth; frame >= 0; --frame) {
+ fm = instance->frames[frame];
+ if (!fm)
+ continue;
+ mask = rel_mask(fm, i, kind);
+ if (bitmap_empty(mask, frame_mask_bits(fm)))
+ continue;
+ verbose(env, "%s", fmt_spis_mask(env, frame, !printed, mask, fm->words));
+ printed = true;
+ }
+ if (!printed)
+ bpf_vlog_reset(&env->log, pos);
+ return printed;
+}
+
static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance)
{
int start = env->subprog_info[instance->subprog].start;
struct bpf_insn *insns = env->prog->insnsi;
- struct frame_masks *fm;
- unsigned long *mask;
int len = instance->insn_cnt;
- int insn_idx, frame, i;
- bool has_use, has_def;
u64 pos, insn_pos;
+ int insn_idx, i;
+ bool printed;
if (!(env->log.level & BPF_LOG_LEVEL2))
return;
@@ -642,41 +687,17 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i
verbose(env, "%s:\n", fmt_instance(env, instance));
for (i = 0; i < len; i++) {
insn_idx = start + i;
- has_use = false;
- has_def = false;
pos = env->log.end_pos;
verbose(env, "%3d: ", insn_idx);
bpf_verbose_insn(env, &insns[insn_idx]);
insn_pos = env->log.end_pos;
verbose(env, "%*c;", bpf_vlog_alignment(insn_pos - pos), ' ');
- pos = env->log.end_pos;
- verbose(env, " use: ");
- for (frame = instance->depth; frame >= 0; --frame) {
- fm = instance->frames[frame];
- if (!fm)
- continue;
- mask = rel_mask(fm, i, FM_MAY_READ);
- if (bitmap_empty(mask, frame_mask_bits(fm)))
- continue;
- verbose(env, "%s", fmt_spis_mask(env, frame, !has_use, mask, fm->words));
- has_use = true;
- }
- if (!has_use)
- bpf_vlog_reset(&env->log, pos);
- pos = env->log.end_pos;
- verbose(env, " def: ");
- for (frame = instance->depth; frame >= 0; --frame) {
- fm = instance->frames[frame];
- if (!fm)
- continue;
- mask = rel_mask(fm, i, FM_MUST_WRITE);
- if (bitmap_empty(mask, frame_mask_bits(fm)))
- continue;
- verbose(env, "%s", fmt_spis_mask(env, frame, !has_def, mask, fm->words));
- has_def = true;
- }
- if (!has_def)
- bpf_vlog_reset(&env->log, has_use ? pos : insn_pos);
+ printed = false;
+ printed |= print_mask(env, instance, i, " use: ", FM_MAY_READ);
+ printed |= print_mask(env, instance, i, " def: ", FM_MUST_WRITE);
+ printed |= print_mask(env, instance, i, " may_def: ", FM_MAY_WRITE);
+ if (!printed)
+ bpf_vlog_reset(&env->log, insn_pos);
verbose(env, "\n");
if (bpf_is_ldimm64(&insns[insn_idx]))
i++;
@@ -697,6 +718,49 @@ static int cmp_instances(const void *pa, const void *pb)
return 0;
}
+/* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */
+static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)
+{
+ u32 slot;
+
+ for (slot = 0; slot < MAX_BPF_STACK_SLOTS && slot * 2 + 1 < nbits; slot++)
+ if (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask))
+ __set_bit(slot, slots);
+}
+
+/*
+ * Precompute, for each instruction, the OR of may_write and live_before masks
+ * over its top frame across all func_instances reaching it, stash them in the
+ * insn_aux_data.
+ */
+static void compute_may_write_masks(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_liveness *liveness = env->liveness;
+ struct func_instance *instance;
+ struct frame_masks *fm;
+ u32 nbits;
+ int bkt, i;
+
+ hash_for_each(liveness->func_instances, bkt, instance, hl_node) {
+ fm = instance->frames[instance->depth];
+ if (!fm)
+ continue;
+ nbits = frame_mask_bits(fm);
+ for (i = 0; i < instance->insn_cnt; i++) {
+ half_spis_to_slots(aux[instance->subprog_start + i].may_write_mask,
+ rel_mask(fm, i, FM_MAY_WRITE), nbits);
+ half_spis_to_slots(aux[instance->subprog_start + i].live_stack_before,
+ rel_mask(fm, i, FM_LIVE_BEFORE), nbits);
+ }
+ }
+}
+
+const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
+{
+ return env->insn_aux_data[insn_idx].may_write_mask;
+}
+
/* print use/def slots for all instances ordered by callsite first, then by depth */
static int print_instances(struct bpf_verifier_env *env)
{
@@ -1444,10 +1508,12 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn,
* access_bytes == 0: no access
*
*/
-static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
- s64 access_bytes, u32 frame, u32 insn_idx)
+static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg,
+ u32 off_idx, s64 access_bytes, u32 frame, u32 insn_idx)
{
+ s64 fp_off = arg->off[off_idx];
s32 slot_hi, slot_lo;
+ int err;
if (fp_off >= 0)
/*
@@ -1459,7 +1525,8 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
if (access_bytes == S64_MIN) {
/* helper/kfunc read unknown amount of bytes from fp_off until fp+0 */
slot_hi = (-fp_off - 1) / STACK_SLOT_SZ;
- return mark_stack_read(instance, frame, insn_idx, 0, slot_hi);
+ err = mark_stack_read(instance, frame, insn_idx, 0, slot_hi);
+ return err ?: mark_stack_may_write(instance, frame, insn_idx, 0, slot_hi);
}
if (access_bytes > 0) {
/* Mark any touched slot as use */
@@ -1471,7 +1538,15 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
access_bytes = -access_bytes;
slot_hi = (-fp_off) / STACK_SLOT_SZ - 1;
slot_lo = max_t(s32, (-fp_off - access_bytes + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0);
- return mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);
+ if (arg->off_cnt == 1) {
+ err = mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);
+ if (err)
+ return err;
+ }
+ /* Mark partially covered slots as may_def */
+ slot_hi = (-fp_off - 1) / STACK_SLOT_SZ;
+ slot_lo = max_t(s32, (-fp_off - access_bytes) / STACK_SLOT_SZ, 0);
+ return mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi);
}
return 0;
}
@@ -1480,25 +1555,31 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off,
* 'arg' is FP-derived argument to helper/kfunc or load/store that
* reads (positive) or writes (negative) 'access_bytes' into 'use' or 'def'.
*/
-static int record_stack_access(struct bpf_verifier_env *env, struct func_instance *instance,
- const struct arg_track *arg,
- s64 access_bytes, u32 frame, u32 insn_idx)
+static int record_precise(struct bpf_verifier_env *env,
+ struct func_instance *instance,
+ const struct arg_track *arg,
+ s64 access_bytes, u32 frame, u32 insn_idx)
{
int i, err;
if (access_bytes == 0)
return 0;
if (arg->off_cnt == 0) {
- if (access_bytes > 0 || access_bytes == S64_MIN)
- return mark_stack_read_all(env, instance, frame, insn_idx);
+ if (access_bytes > 0 || access_bytes == S64_MIN) {
+ err = mark_stack_read_all(env, instance, frame, insn_idx);
+ if (err)
+ return err;
+ }
+ if (access_bytes < 0 || access_bytes == S64_MIN) {
+ err = mark_stack_may_write_all(env, instance, frame, insn_idx);
+ if (err)
+ return err;
+ }
return 0;
}
- if (access_bytes != S64_MIN && access_bytes < 0 && arg->off_cnt != 1)
- /* multi-offset write cannot set stack_def */
- return 0;
for (i = 0; i < arg->off_cnt; i++) {
- err = record_stack_access_off(instance, arg->off[i], access_bytes, frame, insn_idx);
+ err = record_stack_access_off(instance, arg, i, access_bytes, frame, insn_idx);
if (err)
return err;
}
@@ -1507,10 +1588,11 @@ static int record_stack_access(struct bpf_verifier_env *env, struct func_instanc
/*
* When a pointer is ARG_IMPRECISE, conservatively mark every frame in
- * the bitmask as fully used.
+ * the bitmask as fully used. Same as in record_stack_access(),
+ * negative 'access_bytes' means stack write.
*/
static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *instance,
- u32 mask, u32 insn_idx)
+ s64 access_bytes, u32 mask, u32 insn_idx)
{
int depth = instance->depth;
int f, err;
@@ -1519,25 +1601,45 @@ static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *
if (!(mask & 1))
continue;
if (f <= depth) {
- err = mark_stack_read_all(env, instance, f, insn_idx);
- if (err)
- return err;
+ if (access_bytes > 0 || access_bytes == S64_MIN) {
+ err = mark_stack_read_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
+ }
+ if (access_bytes < 0) {
+ err = mark_stack_may_write_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
+ }
}
}
return 0;
}
+static int record_stack_access(struct bpf_verifier_env *env,
+ struct func_instance *instance,
+ const struct arg_track *ptr,
+ s64 access_bytes, u32 insn_idx)
+{
+ if (ptr->frame >= 0 && ptr->frame <= instance->depth)
+ return record_precise(env, instance, ptr, access_bytes, ptr->frame, insn_idx);
+ if (ptr->frame == ARG_IMPRECISE)
+ return record_imprecise(env, instance, access_bytes, ptr->mask, insn_idx);
+ /* ARG_NONE: not derived from any frame pointer, skip */
+ return 0;
+}
+
/* Record load/store access for a given 'at' state of 'insn'. */
static int record_load_store_access(struct bpf_verifier_env *env,
struct func_instance *instance,
struct arg_track *at, int insn_idx)
{
struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
- int depth = instance->depth;
s32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code));
u8 class = BPF_CLASS(insn->code);
struct arg_track resolved, *ptr;
- int oi;
+ bool rmw = false; /* atomic read-modify-write: both read and write */
+ int oi, err;
/*
* Stack arg insns use dst_reg/src_reg=BPF_REG_PARAMS(11). Since at[]
@@ -1555,12 +1657,20 @@ static int record_load_store_access(struct bpf_verifier_env *env,
break;
case BPF_STX:
if (BPF_MODE(insn->code) == BPF_ATOMIC) {
- if (insn->imm == BPF_STORE_REL)
- sz = -sz;
- if (insn->imm == BPF_LOAD_ACQ)
+ switch (insn->imm) {
+ case BPF_LOAD_ACQ:
ptr = &at[insn->src_reg];
- else
+ break;
+ case BPF_STORE_REL:
+ ptr = &at[insn->dst_reg];
+ sz = -sz;
+ break;
+ default:
+ /* ADD/AND/OR/XOR(+FETCH), XCHG, CMPXCHG */
ptr = &at[insn->dst_reg];
+ rmw = true;
+ break;
+ }
} else {
ptr = &at[insn->dst_reg];
sz = -sz;
@@ -1587,12 +1697,10 @@ static int record_load_store_access(struct bpf_verifier_env *env,
ptr = &resolved;
}
- if (ptr->frame >= 0 && ptr->frame <= depth)
- return record_stack_access(env, instance, ptr, sz, ptr->frame, insn_idx);
- if (ptr->frame == ARG_IMPRECISE)
- return record_imprecise(env, instance, ptr->mask, insn_idx);
- /* ARG_NONE: not derived from any frame pointer, skip */
- return 0;
+ err = record_stack_access(env, instance, ptr, sz, insn_idx);
+ if (!err && rmw) /* also record the write half */
+ err = record_stack_access(env, instance, ptr, -sz, insn_idx);
+ return err;
}
static int record_arg_access(struct bpf_verifier_env *env,
@@ -1602,7 +1710,6 @@ static int record_arg_access(struct bpf_verifier_env *env,
int insn_idx)
{
int depth = instance->depth;
- int frame = at->frame;
int err = 0;
s64 bytes;
@@ -1618,17 +1725,16 @@ static int record_arg_access(struct bpf_verifier_env *env,
err = mark_stack_read_all(env, instance, f, insn_idx);
if (err)
return err;
+ err = mark_stack_may_write_all(env, instance, f, insn_idx);
+ if (err)
+ return err;
}
return 0;
}
if (bytes == 0)
return 0;
- if (frame >= 0 && frame <= depth)
- err = record_stack_access(env, instance, at, bytes, frame, insn_idx);
- else if (frame == ARG_IMPRECISE)
- err = record_imprecise(env, instance, at->mask, insn_idx);
- return err;
+ return record_stack_access(env, instance, at, bytes, insn_idx);
}
/* Record stack access for a given 'at' state of helper/kfunc 'insn' */
@@ -1808,6 +1914,17 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env,
}
}
+static void record_stack_ptrs(struct bpf_verifier_env *env, int idx, struct arg_track *at_in)
+{
+ u16 r, mask = 0;
+
+ for (r = 0; r < MAX_BPF_REG; r++)
+ if (arg_is_fp(&at_in[r]))
+ mask |= BIT(r);
+
+ env->insn_aux_data[idx].stack_ptrs |= mask;
+}
+
/*
* Compute arg tracking dataflow for a single subprog.
* Runs forward fixed-point with arg_track_xfer(), then records
@@ -1957,6 +2074,8 @@ static int compute_subprog_args(struct bpf_verifier_env *env,
snap->slots = nslots;
memcpy(snap->at, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap->at));
}
+
+ record_stack_ptrs(env, idx, at_in[i]);
}
info->at_in = at_in;
@@ -1987,6 +2106,7 @@ static bool has_fp_args(struct arg_track *args)
/*
* Merge a freshly analyzed instance into the original.
* may_read: union (any pass might read the slot).
+ * may_write: union (slots written on ANY pass).
* must_write: intersection (only slots written on ALL passes are guaranteed).
* live_before is recomputed by a subsequent update_instance() on @dst.
*
@@ -2025,18 +2145,50 @@ static int merge_instances(struct func_instance *dst, struct func_instance *src)
for (i = 0; i < dst->insn_cnt; i++) {
unsigned long *dst_read = rel_mask(d, i, FM_MAY_READ);
unsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE);
+ unsigned long *dst_may_write = rel_mask(d, i, FM_MAY_WRITE);
unsigned long *src_read = rel_mask(s, i, FM_MAY_READ);
unsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE);
+ unsigned long *src_may_write = rel_mask(s, i, FM_MAY_WRITE);
for (w = 0; w < d->words; w++) {
dst_read[w] |= w < s->words ? src_read[w] : 0;
dst_write[w] &= w < s->words ? src_write[w] : 0;
+ dst_may_write[w] |= w < s->words ? src_may_write[w] : 0;
}
}
}
return 0;
}
+/*
+ * Fold a fully analyzed callee instance writes to upper frames as
+ * may_write marks at callsite in caller's frames.
+ */
+static int merge_may_write(struct func_instance *caller, struct func_instance *callee)
+{
+ DECLARE_BITMAP(acc, FRAME_HALF_SPIS);
+ u32 call_idx = callee->callsite;
+ struct frame_masks *fm;
+ u32 f, i, nbits;
+ int err;
+
+ for (f = 0; f < callee->depth; f++) {
+ fm = callee->frames[f];
+ if (!fm)
+ continue;
+ nbits = frame_mask_bits(fm);
+ bitmap_zero(acc, nbits);
+ for (i = 0; i < callee->insn_cnt; i++)
+ bitmap_or(acc, acc, rel_mask(fm, i, FM_MAY_WRITE), nbits);
+ if (bitmap_empty(acc, nbits))
+ continue;
+ err = mark_stack_mask(caller, f, call_idx, FM_MAY_WRITE, acc, fm->words);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
static struct func_instance *fresh_instance(struct func_instance *src)
{
struct func_instance *f;
@@ -2204,6 +2356,11 @@ static int analyze_subprog(struct bpf_verifier_env *env,
goto out_free;
}
}
+
+ /* Summarize callee's writes to ancestor frames onto the callsite */
+ err = merge_may_write(instance, callee_instance);
+ if (err)
+ goto out_free;
}
if (prev_instance) {
@@ -2266,6 +2423,8 @@ int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)
goto out;
}
+ compute_may_write_masks(env);
+
if (env->log.level & BPF_LOG_LEVEL2)
err = print_instances(env);
@@ -2472,8 +2631,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
struct bpf_insn *insns = env->prog->insnsi;
struct insn_live_regs *state;
int insn_cnt = env->prog->len;
- u64 pos, insn_pos;
- int err = 0, i, j, subprog, start, end;
+ int err = 0, i, subprog, start, end;
bool changed, ret_reg_pair;
/* Use the following algorithm:
@@ -2552,31 +2710,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32));
}
- if (env->log.level & BPF_LOG_LEVEL2) {
- verbose(env, "Live regs before insn:\n");
- for (i = 0; i < insn_cnt; ++i) {
- if (env->insn_aux_data[i].scc)
- verbose(env, "%3d ", env->insn_aux_data[i].scc);
- else
- verbose(env, " ");
- verbose(env, "%3d: ", i);
- for (j = BPF_REG_0; j < BPF_REG_10; ++j)
- if (insn_aux[i].live_regs_before & BIT(j))
- verbose(env, "%d", j);
- else
- verbose(env, ".");
- verbose(env, " ");
- pos = env->log.end_pos;
- bpf_verbose_insn(env, &insns[i]);
- insn_pos = env->log.end_pos;
- if (insn_aux[i].zext_dst)
- verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
- verbose(env, "\n");
- if (bpf_is_ldimm64(&insns[i]))
- i++;
- }
- }
-
out:
kvfree(state);
return err;
diff --git a/kernel/bpf/log.c b/kernel/bpf/log.c
index d850a7863d2ed..6a5564f626693 100644
--- a/kernel/bpf/log.c
+++ b/kernel/bpf/log.c
@@ -692,6 +692,8 @@ static void print_reg_state(struct bpf_verifier_env *env,
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose_a("var_off=%s", tn_buf);
+ if (reg->base != 0 || reg->step != 1)
+ verbose_a("step=%d+%d", reg->base, reg->step);
}
}
verbose(env, ")");
@@ -790,6 +792,11 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
verbose(env, " cb");
if (state->in_async_callback_fn)
verbose(env, " async_cb");
+ if (state->loop_stack_cnt) {
+ verbose(env, " loop_stack=");
+ for (i = 0; i < state->loop_stack_cnt; i++)
+ verbose(env, "%s%d", i ? "," : "", state->loop_stack[i].loop_id);
+ }
verbose(env, "\n");
if (!print_all)
mark_verifier_state_clean(env);
diff --git a/kernel/bpf/loops.c b/kernel/bpf/loops.c
new file mode 100644
index 0000000000000..5f52a88d52837
--- /dev/null
+++ b/kernel/bpf/loops.c
@@ -0,0 +1,576 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/slab.h>
+#include <linux/bpf_verifier.h>
+
+static bool is_cfg_jump(struct bpf_insn *insn)
+{
+ u8 class = BPF_CLASS(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+
+ switch (class) {
+ case BPF_JMP:
+ case BPF_JMP32:
+ return opcode != BPF_CALL;
+ default:
+ return false;
+ }
+}
+
+static struct bpf_iarray **compute_predecessors(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_iarray *succ, *preds, **result;
+ struct bpf_prog *prog = env->prog;
+ u32 *num_preds, i, s, sz, len = prog->len;
+ struct bpf_insn *insn;
+ void *tmp;
+
+ num_preds = kvcalloc(prog->len, sizeof(u32), GFP_KERNEL_ACCOUNT);
+ if (!num_preds)
+ return NULL;
+
+ /*
+ * 'result' layout:
+ * - array of pointers (struct bpf_iarray *)[len]
+ * - struct bpf_iarray one after another
+ */
+ sz = sizeof(struct bpf_iarray) * len;
+ sz += sizeof(struct bpf_iarray *) * len;
+ for (i = 0; i < len; i++) {
+ insn = env->prog->insnsi + i;
+ succ = bpf_insn_successors(env, i);
+ sz += sizeof(u32) * succ->cnt;
+ iarray_for_each(s, succ) {
+ num_preds[s]++;
+ }
+ if (bpf_is_ldimm64(insn))
+ i++;
+ }
+
+ result = kvzalloc(sz, GFP_KERNEL_ACCOUNT);
+ if (!result) {
+ kvfree(num_preds);
+ return NULL;
+ }
+
+ tmp = (void *)&result[len];
+ for (i = 0; i < len; i++) {
+ result[i] = tmp;
+ tmp += sizeof(struct bpf_iarray);
+ tmp += sizeof(u32) * num_preds[i];
+ }
+
+ for (i = 0; i < len; i++) {
+ insn = env->prog->insnsi + i;
+ succ = bpf_insn_successors(env, i);
+ iarray_for_each(s, succ) {
+ preds = result[s];
+ preds->items[preds->cnt++] = i;
+ }
+ if (succ->cnt > 1 ||
+ (succ->cnt == 1 && num_preds[succ->items[0]] > 1) ||
+ is_cfg_jump(insn))
+ aux[i].bb_end = true;
+ if (bpf_is_ldimm64(insn))
+ i++;
+ }
+
+ kvfree(num_preds);
+ return result;
+}
+
+static int idoms_intersect(struct bpf_verifier_env *env, int a, int b)
+{
+ int *postorder_nums = env->cfg.postorder_nums;
+ int *idoms = env->idoms;
+
+ while (a != b) {
+ while (postorder_nums[a] < postorder_nums[b]) {
+ a = idoms[a];
+ }
+ while (postorder_nums[b] < postorder_nums[a]) {
+ b = idoms[b];
+ }
+ }
+ return a;
+}
+
+/* See "A Simple, Fast Dominance Algorithm" by Cooper et al. for details. */
+static void compute_subprog_idoms(struct bpf_verifier_env *env, struct bpf_iarray **preds, int subprog_idx)
+{
+ struct bpf_subprog_info *subprog = &env->subprog_info[subprog_idx];
+ int start = subprog->start;
+ int po_first = subprog->postorder_start;
+ int po_last = (subprog + 1)->postorder_start - 1;
+ int *idoms = env->idoms;
+ int po_num, pred;
+ bool changed;
+
+ idoms[start] = 0;
+ changed = true;
+ do {
+ changed = false;
+ /* iterate in reverse postorder */
+ for (po_num = po_last; po_num >= po_first; po_num--) {
+ int idx = env->cfg.insn_postorder[po_num];
+ int new_idom = -1;
+
+ iarray_for_each(pred, preds[idx]) {
+ if (idoms[pred] == -1)
+ continue;
+ if (new_idom == -1)
+ new_idom = pred;
+ else
+ new_idom = idoms_intersect(env, pred, new_idom);
+ }
+ if (new_idom != -1 && idoms[idx] != new_idom) {
+ idoms[idx] = new_idom;
+ changed = true;
+ }
+ }
+ } while (changed);
+ idoms[start] = -1;
+}
+
+int bpf_compute_idoms(struct bpf_verifier_env *env)
+{
+ struct bpf_iarray **preds;
+ u32 len = env->prog->len;
+ int *idoms, i;
+
+ preds = compute_predecessors(env);
+ if (!preds)
+ return -ENOMEM;
+
+ idoms = kvcalloc(len, sizeof(*idoms), GFP_KERNEL_ACCOUNT);
+ if (!idoms) {
+ kvfree(preds);
+ return -ENOMEM;
+ }
+
+ env->idoms = idoms;
+ for (i = 0; i < len; i++)
+ idoms[i] = -1;
+
+ for (i = 0; i < env->subprog_cnt; i++)
+ compute_subprog_idoms(env, preds, i);
+
+ kvfree(preds);
+ return 0;
+}
+
+struct dfs_state {
+ u32 traversed:1;
+ u32 next_succ:31;
+};
+
+struct loops_dfs {
+ struct dfs_state *state;
+ int *dfs_pos;
+ int *stack;
+};
+
+static void mark_irreducible(struct bpf_verifier_env *env, int h)
+{
+ env->insn_aux_data[h].loop->irreducible = true;
+}
+
+static void mark_entry(struct bpf_verifier_env *env, int s)
+{
+ env->insn_aux_data[s].loop_entry = true;
+}
+
+static void add_backedge(struct bpf_verifier_env *env, int from, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop = aux[h].loop;
+ int cnt = loop->backedges_cnt;
+
+ if (cnt == MAX_BACKEDGES) {
+ loop->backedges_overflow = true;
+ return;
+ }
+ loop->backedges[cnt].from = from;
+ loop->backedges[cnt].latch = -1;
+ loop->backedges_cnt++;
+}
+
+static int add_exit(struct bpf_loop *loop, int from, int to)
+{
+ if (loop->exits_overflow)
+ return 0;
+ if (loop->exits_cnt == MAX_LOOP_EXITS) {
+ loop->exits_overflow = true;
+ return 0;
+ }
+ if (!loop->exits) {
+ loop->exits = kvcalloc(MAX_LOOP_EXITS, sizeof(*loop->exits), GFP_KERNEL_ACCOUNT);
+ if (!loop->exits)
+ return -ENOMEM;
+ }
+ loop->exits[loop->exits_cnt] = (struct bpf_loop_exit) {
+ .from = from,
+ .to = to,
+ };
+ loop->exits_cnt++;
+ return 0;
+}
+
+static int mark_as_header(struct bpf_verifier_env *env, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+
+ if (!aux[h].loop) {
+ mark_entry(env, h);
+ aux[h].loop = kvzalloc_obj(struct bpf_loop, GFP_KERNEL_ACCOUNT);
+ if (!aux[h].loop)
+ return -ENOMEM;
+ }
+ return 0;
+}
+
+static int assign_header(struct bpf_verifier_env *env, struct loops_dfs *dfs, int n, int h)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int *dfs_pos = dfs->dfs_pos;
+ int err, nh;
+
+ err = mark_as_header(env, h);
+ if (err)
+ return err;
+
+ /* Don't encode self-loops, otherwise can't reflect loops nesting structure. */
+ if (n == h)
+ return 0;
+
+ /* Make sure that loop headers up the chain are sorted by dfs_pos. */
+ while (aux[n].loop_header != -1) {
+ nh = aux[n].loop_header;
+ if (nh == h)
+ return 0;
+ if (dfs_pos[nh] < dfs_pos[h]) {
+ aux[n].loop_header = h;
+ n = h;
+ h = nh;
+ } else {
+ n = nh;
+ }
+ }
+ aux[n].loop_header = h;
+ return 0;
+}
+
+static bool is_cond_jmp_insn(struct bpf_insn *insn)
+{
+ u8 class = BPF_CLASS(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+
+ if (class != BPF_JMP && class != BPF_JMP32)
+ return false;
+
+ switch (opcode) {
+ case BPF_JEQ:
+ case BPF_JGE:
+ case BPF_JGT:
+ case BPF_JLE:
+ case BPF_JLT:
+ case BPF_JNE:
+ case BPF_JSET:
+ case BPF_JSGE:
+ case BPF_JSGT:
+ case BPF_JSLE:
+ case BPF_JSLT:
+ return true;
+ default:
+ return false;
+ }
+}
+
+int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+
+ return aux[idx].loop ? idx : aux[idx].loop_header;
+}
+
+static int find_dominating_condition(struct bpf_verifier_env *env, int n, int top)
+{
+ struct bpf_insn *insns = env->prog->insnsi;
+ int common_dom, n_loop, t_loop, f_loop;
+ int *idoms = env->idoms;
+
+ n_loop = bpf_loop_at_index(env, n);
+ common_dom = idoms_intersect(env, n, top);
+ if (common_dom != top)
+ return -1;
+ while (n >= 0) {
+ if (is_cond_jmp_insn(&insns[n]) && bpf_loop_at_index(env, n) == n_loop) {
+ t_loop = bpf_loop_at_index(env, n + insns[n].off + 1);
+ f_loop = bpf_loop_at_index(env, n + 1);
+ if (f_loop != n_loop && !bpf_is_nested_loop(env, f_loop, n_loop))
+ return n;
+ if (t_loop != n_loop && !bpf_is_nested_loop(env, t_loop, n_loop))
+ return n;
+ }
+ if (n == top)
+ break;
+ n = idoms[n];
+ }
+ return -1;
+}
+
+/*
+ * As described in "A New Algorithm for Identifying Loops in Decompilation" by Wei et al,
+ * adapted to be non-recursive.
+ */
+static int compute_loops_in_subprog(struct bpf_verifier_env *env, struct loops_dfs *dfs,
+ int subprog_idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct dfs_state *state = dfs->state;
+ int start = env->subprog_info[subprog_idx].start;
+ int *dfs_pos = dfs->dfs_pos;
+ int *stack = dfs->stack;
+ int s, h, err, cur, stack_sz;
+ struct bpf_iarray *succ;
+ u32 i;
+
+ stack[0] = start;
+ state[start].traversed = true;
+ state[start].next_succ = 0;
+ dfs_pos[start] = 1;
+ stack_sz = 1;
+ i = 0;
+ do {
+ /*
+ * The algorithm should be very fast in practice,
+ * guard against pathological inputs, just in case.
+ */
+ if ((++i % 1024) == 0) {
+ if (signal_pending(current))
+ return -EAGAIN;
+ cond_resched();
+ }
+
+ cur = stack[stack_sz - 1];
+ succ = bpf_insn_successors(env, cur);
+ if (state[cur].next_succ == succ->cnt) {
+ dfs_pos[cur] = 0;
+ stack_sz--;
+ continue;
+ }
+ s = succ->items[state[cur].next_succ];
+ if (!state[s].traversed) {
+ /* Case A: start -> ... -> cur -> s [unexplored] */
+ state[s].traversed = true;
+ state[s].next_succ = 0;
+ stack[stack_sz] = s;
+ dfs_pos[s] = stack_sz + 1;
+ stack_sz++;
+ continue;
+ }
+ /* 's' is fully explored at this point */
+ if (dfs_pos[s]) {
+ /*
+ * start -> ... -> s -> cur --.
+ * ^ |
+ * '----------'
+ * Case B: 's' is in the current DFS path.
+ */
+ err = assign_header(env, dfs, cur, s);
+ if (err)
+ return err;
+ add_backedge(env, cur, s);
+ } else if (aux[s].loop_header == -1) {
+ /*
+ * start -> ... -> ... -> s -> ... -> end
+ * | ^
+ * '---> cur ---'
+ * Case C: 's' is explored, not in the current DFS path,
+ * and not a part of any loop.
+ */
+ } else if (dfs_pos[aux[s].loop_header]) {
+ /*
+ * .----------------------.
+ * v |
+ * start -> ... -> h -> ... -> ... -> s --'
+ * | ^
+ * '---> cur ---'
+ * Case D: 's' is explored, not in current DFS path,
+ * but its innermost loop header is.
+ */
+ err = assign_header(env, dfs, cur, aux[s].loop_header);
+ if (err)
+ return err;
+ } else {
+ /*
+ * case E: 's' is explored, not in current DFS path,
+ * its innermost loop header is not in current DFS path,
+ * hence 's' is another entry into the same loop.
+ */
+ h = aux[s].loop_header;
+ mark_irreducible(env, h);
+ mark_entry(env, s);
+ while (aux[h].loop_header != -1) {
+ h = aux[h].loop_header;
+ if (dfs_pos[h]) {
+ err = assign_header(env, dfs, cur, h);
+ if (err)
+ return err;
+ break;
+ }
+ mark_irreducible(env, h);
+ }
+ }
+ state[cur].next_succ++;
+ } while (stack_sz);
+
+ return 0;
+}
+
+bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int idx;
+
+ for (idx = inner_header; idx >= 0; idx = aux[idx].loop_header)
+ if (aux[idx].loop_header == outer_header)
+ return true;
+
+ return false;
+}
+
+int bpf_compute_loops(struct bpf_verifier_env *env)
+{
+ int i, j, s, t, iloop, sloop, err = 0, len = env->prog->len;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct bpf_backedge *backedge;
+ struct loops_dfs dfs = {};
+ struct bpf_iarray *succ;
+ struct bpf_loop *loop;
+
+ dfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+ dfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);
+ dfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+ if (!dfs.dfs_pos || !dfs.state || !dfs.stack) {
+ err = -ENOMEM;
+ goto out;
+ }
+ for (i = 0; i < len; i++)
+ aux[i].loop_header = -1;
+ for (i = 0; i < env->subprog_cnt; i++) {
+ err = compute_loops_in_subprog(env, &dfs, i);
+ if (err)
+ goto out;
+ }
+ /* find latches */
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ backedge = &loop->backedges[j];
+ backedge->latch = find_dominating_condition(env, backedge->from, i);
+ }
+ }
+ /* find exits */
+ for (i = 0; i < len; i++) {
+ iloop = aux[i].loop ? i : aux[i].loop_header;
+ if (iloop < 0)
+ continue;
+ succ = bpf_insn_successors(env, i);
+ iarray_for_each(s, succ) {
+ /*
+ * Nothing left to record once the innermost loop of 'i'
+ * overflowed: the walk below would stop at it right away.
+ */
+ if (aux[iloop].loop->exits_overflow)
+ break;
+ sloop = aux[s].loop ? s : aux[s].loop_header;
+ if (iloop == sloop)
+ continue;
+ if (bpf_is_nested_loop(env, sloop, iloop))
+ continue;
+ /*
+ * At this point 'sloop' is either -1, an outer loop,
+ * or a loop in another branch of the loop hierarchy.
+ */
+ for (t = iloop; t >= 0 && t != sloop; t = aux[t].loop_header) {
+ /*
+ * Account for the following configuration:
+ *
+ * tloop {
+ * iloop {
+ * ... i: goto s;
+ * }
+ * sloop {
+ * s:
+ * ...
+ * }
+ * }
+ */
+ if (bpf_is_nested_loop(env, sloop, t))
+ break;
+ /*
+ * Record edges i -> s as exits from tloop when:
+ *
+ * sloop {
+ * tloop {
+ * iloop {
+ * ... i: goto s;
+ * }
+ * }
+ * s: ...
+ * }
+ */
+ /* Enclosing loops inherit the overflow, see below */
+ if (aux[t].loop->exits_overflow)
+ break;
+ err = add_exit(aux[t].loop, i, s);
+ if (err)
+ goto out;
+ }
+ }
+ if (bpf_is_ldimm64(env->prog->insnsi + i))
+ i++;
+ }
+ /* A nested loop with a truncated exit list can't be abstracted by SCEV */
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop || !loop->exits_overflow)
+ continue;
+ for (t = aux[i].loop_header; t >= 0; t = aux[t].loop_header)
+ aux[t].loop->exits_overflow = true;
+ }
+
+ if (env->log.level & BPF_LOG_LEVEL2) {
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ bpf_log(log, "loop at %d", i);
+ if (aux[i].loop_header >= 0)
+ bpf_log(log, ", nested in %d", aux[i].loop_header);
+ if (loop->irreducible)
+ bpf_log(log, ", irreducible");
+ if (loop->exits_overflow)
+ bpf_log(log, ", too many exits");
+ bpf_log(log, "\n");
+ for (j = 0; j < loop->backedges_cnt; j++)
+ bpf_log(log, " backedge from %d, latch at %d\n",
+ loop->backedges[j].from, loop->backedges[j].latch);
+ for (j = 0; j < loop->exits_cnt; j++)
+ bpf_log(log, " exit from %d to %d\n",
+ loop->exits[j].from, loop->exits[j].to);
+ }
+ }
+
+out:
+ kvfree(dfs.dfs_pos);
+ kvfree(dfs.stack);
+ kvfree(dfs.state);
+ return err;
+}
diff --git a/kernel/bpf/scev.c b/kernel/bpf/scev.c
new file mode 100644
index 0000000000000..1fa6b25a4f291
--- /dev/null
+++ b/kernel/bpf/scev.c
@@ -0,0 +1,2246 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
+
+#include "linux/cnum.h"
+#include <linux/bpf_verifier.h>
+#include <linux/jhash.h>
+#include <linux/bug.h>
+#include <linux/tnum.h>
+#include <linux/overflow.h>
+
+#define REGS_NUM BPF_SCEV_REGS_NUM
+#define UNKNOWN_EXPR_ID 0
+#define OPAQUE_EXPR_ID 1
+
+/*
+ * BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.
+ * For scalar evolution purpose we want to reuse most of the opcode definitions,
+ * but also add a few custom operations (REG and IMM).
+ * Use the enum below to uniformly represent all operations relevant for SCEV.
+ */
+enum expr_op {
+ /* leave range 0..255 for standard bpf opcodes */
+ UNKNOWN = 256, /* start custom opcodes from the second byte */
+ REG,
+ IMM,
+ SDIV, SMOD,
+ SEXT8, SEXT16, SEXT32,
+ ZEXT8, ZEXT16, ZEXT32,
+ BSWAP16, BSWAP32, BSWAP64,
+ /* during the loop body execution the value can be either of param[0] or param[1] */
+ ANY,
+ /* some value that verifier is not going to track precisely */
+ OPAQUE,
+ /* '*(u8/16/32 *)(r10 + X) = Y' writes define slot contents only partially */
+ SPILL8, SPILL16, SPILL32,
+ /*
+ * SCEV expression corresponding to linear equation 'param[0] + param[1] * k',
+ * where k is a loop iteration number. Loop here refers to innermost loop
+ * containing instruction associated with this expression, as returned by
+ * bpf_loop_at_index().
+ */
+ LINEAR_SCEV,
+};
+
+struct expr {
+ u32 op;
+ union {
+ u32 params[2];
+ s64 imm;
+ };
+};
+
+struct expr_bucket {
+ u32 cnt;
+ u32 cap;
+ u32 ids[];
+};
+
+struct env {
+ bool empty;
+ u32 reg2expr[REGS_NUM];
+ u32 reg2scev[REGS_NUM];
+};
+
+struct insn_envs {
+ u32 cnt;
+ struct {
+ int loop_header;
+ struct env *env;
+ } entries[];
+};
+
+#define NUM_BUCKETS 256
+#define EXPR_STACK_DEPTH 8
+
+struct expr_stack_elt {
+ u32 id:28;
+ u32 pre:1;
+ u32 next_param:2;
+};
+
+struct scev {
+ /*
+ * Expressions are identified by id, exprs_ht ensures that
+ * each expression exists as a unique instance.
+ * This allows for fast equivalence check: id1 === id2.
+ */
+ struct expr_bucket *exprs_ht[NUM_BUCKETS]; // Don't want to add struct hlist_node to expr
+ struct bpf_min_heap worklist;
+ struct insn_envs **envs;
+ struct expr *exprs;
+ /*
+ * Loops are analyzed one by one, this array keeps track if a particular
+ * instruction was visited on a current pass.
+ */
+ u32 *discovered;
+ int exprs_cnt;
+ int exprs_cap;
+ int envs_cnt;
+ int stack_sz;
+ struct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];
+ u32 ids_buf[EXPR_STACK_DEPTH];
+};
+
+static u32 expr_hash(struct expr *e)
+{
+ return jhash_3words(e->op, e->params[0], e->params[1], 0);
+}
+
+static int expr_eq(struct expr *a, struct expr *b)
+{
+ return a->op == b->op && a->imm == b->imm;
+}
+
+static int add_expr(struct scev *scev, struct expr e)
+{
+ struct expr_bucket *bucket;
+ u32 i, id, hash, new_cap;
+ void *tmp;
+
+ hash = expr_hash(&e) % NUM_BUCKETS;
+ bucket = scev->exprs_ht[hash];
+
+ if (bucket) {
+ for (i = 0; i < bucket->cnt; i++) {
+ id = bucket->ids[i];
+ if (expr_eq(&e, &scev->exprs[id]))
+ return id;
+ }
+ }
+
+ if (!bucket || bucket->cap == bucket->cnt) {
+ new_cap = bucket ? bucket->cap * 2 : 32;
+ bucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+ if (!bucket)
+ return -ENOMEM;
+ scev->exprs_ht[hash] = bucket;
+ bucket->cap = new_cap;
+ }
+
+ if (scev->exprs_cnt == scev->exprs_cap) {
+ new_cap = scev->exprs_cap + 256;
+ tmp = kvrealloc(scev->exprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);
+ if (!tmp)
+ return -ENOMEM;
+ scev->exprs = tmp;
+ scev->exprs_cap = new_cap;
+ }
+
+ id = scev->exprs_cnt++;
+ scev->exprs[id] = e;
+ bucket->ids[bucket->cnt++] = id;
+ return id;
+}
+
+static int expr2(struct scev *scev, u32 op, int a, int b)
+{
+ if (a < 0)
+ return a;
+ if (b < 0)
+ return b;
+ return add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
+}
+
+static int expr1(struct scev *scev, u32 op, int a)
+{
+ if (a < 0)
+ return a;
+ return expr2(scev, op, a, 0);
+}
+
+static int expr0(struct scev *scev, u32 op)
+{
+ return expr2(scev, op, 0, 0);
+}
+
+static bool is_expr1(struct expr *expr, u32 op, int a)
+{
+ return expr->op == op && expr->params[0] == a;
+}
+
+static int imm_expr(struct scev *scev, s64 value)
+{
+ return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
+}
+
+static bool same_exprs(struct scev *scev, int id_a, int id_b)
+{
+ return id_a == id_b;
+}
+
+static bool is_imm(struct scev *scev, int id, s64 *imm)
+{
+ if (scev->exprs[id].op != IMM)
+ return false;
+ *imm = scev->exprs[id].imm;
+ return true;
+}
+
+static bool is_op(struct scev *scev, int id, u32 op)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ return true;
+}
+
+static bool is_unop(struct scev *scev, enum expr_op op, int id, u32 *p0)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ *p0 = scev->exprs[id].params[0];
+ return true;
+}
+
+static bool is_binop(struct scev *scev, enum expr_op op, int id, u32 *p0, u32 *p1)
+{
+ if (scev->exprs[id].op != op)
+ return false;
+ *p0 = scev->exprs[id].params[0];
+ *p1 = scev->exprs[id].params[1];
+ return true;
+}
+
+static bool is_reg(struct scev *scev, int id, u32 *reg)
+{
+ return is_unop(scev, REG, id, reg);
+}
+
+static bool is_add(struct scev *scev, int id, u32 *left, u32 *right)
+{
+ return is_binop(scev, BPF_ADD, id, left, right);
+}
+
+static bool is_zext32(struct scev *scev, int id, u32 *left)
+{
+ return is_unop(scev, ZEXT32, id, left);
+}
+
+static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
+{
+ return is_binop(scev, ANY, id, left, right);
+}
+
+static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
+{
+ return is_binop(scev, LINEAR_SCEV, id, base, slope);
+}
+
+static bool is_opaque(struct scev *scev, int id)
+{
+ return is_op(scev, id, OPAQUE);
+}
+
+static void log_reg(struct bpf_verifier_env *env, u32 reg)
+{
+ if (reg < MAX_BPF_REG)
+ bpf_log(&env->log, "r%d", reg);
+ else
+ bpf_log(&env->log, "*fp%d", (MAX_BPF_REG - reg - 1) * 8);
+}
+
+static const char *op_str(u32 op)
+{
+ switch (op) {
+ case BPF_ADD: return "+";
+ case BPF_SUB: return "-";
+ case BPF_MUL: return "*";
+ case BPF_DIV: return "/";
+ case SDIV: return "s/";
+ case BPF_OR: return "|";
+ case BPF_AND: return "&";
+ case BPF_LSH: return "<<";
+ case BPF_RSH: return ">>";
+ case BPF_NEG: return "-";
+ case BPF_MOD: return "%";
+ case SMOD: return "s%";
+ case BPF_XOR: return "^";
+ case BPF_ARSH: return "s>>";
+ case SEXT8: return "sext8";
+ case SEXT16: return "sext16";
+ case SEXT32: return "sext32";
+ case ZEXT8: return "zext8";
+ case ZEXT16: return "zext16";
+ case ZEXT32: return "zext32";
+ case BSWAP16: return "bswap16";
+ case BSWAP32: return "bswap32";
+ case BSWAP64: return "bswap64";
+ case SPILL8: return "spill8";
+ case SPILL16: return "spill16";
+ case SPILL32: return "spill32";
+ case ANY: return "any";
+ case LINEAR_SCEV: return "linear";
+ }
+ return NULL;
+}
+
+static u32 op_params_num(u32 op)
+{
+ switch (op) {
+ case BPF_ADD:
+ case BPF_SUB:
+ case BPF_MUL:
+ case BPF_DIV:
+ case BPF_MOD:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_AND:
+ case BPF_LSH:
+ case BPF_RSH:
+ case BPF_ARSH:
+ case SDIV:
+ case SMOD:
+ case ANY:
+ case LINEAR_SCEV:
+ return 2;
+ case BPF_NEG:
+ case SEXT8:
+ case SEXT16:
+ case SEXT32:
+ case ZEXT8:
+ case ZEXT16:
+ case ZEXT32:
+ case BSWAP16:
+ case BSWAP32:
+ case BSWAP64:
+ case SPILL8:
+ case SPILL16:
+ case SPILL32:
+ return 1;
+ case REG:
+ case IMM:
+ case OPAQUE:
+ return 0;
+ default:
+ return 0;
+ }
+}
+
+static bool expr_stack_push(struct scev *scev, u32 id)
+{
+ if (scev->stack_sz >= EXPR_STACK_DEPTH)
+ return false;
+ scev->expr_stack[scev->stack_sz].id = id;
+ scev->expr_stack[scev->stack_sz].pre = true;
+ scev->expr_stack[scev->stack_sz].next_param = 0;
+ scev->stack_sz++;
+ return true;
+}
+
+enum {
+ PRE = BIT(1), POST = BIT(2), DEPTH_LIMIT = BIT(3)
+};
+
+static bool expr_next(struct scev *scev, u32 *id, u32 *order)
+{
+ struct expr_stack_elt *elt;
+ struct expr *expr;
+ u32 num_params;
+
+ if (scev->stack_sz == 0)
+ return false;
+
+ elt = &scev->expr_stack[scev->stack_sz - 1];
+ *id = elt->id;
+ *order = 0;
+ expr = &scev->exprs[elt->id];
+ num_params = op_params_num(expr->op);
+ if (elt->pre) {
+ elt->pre = false;
+ *order = PRE;
+ return true;
+ }
+ if (elt->next_param == num_params) {
+ *order = POST;
+ scev->stack_sz--;
+ return true;
+ }
+ if (scev->stack_sz == EXPR_STACK_DEPTH) {
+ *order = POST | DEPTH_LIMIT;
+ scev->stack_sz--;
+ return true;
+ }
+ expr_stack_push(scev, expr->params[elt->next_param]);
+ elt->next_param++;
+ return expr_next(scev, id, order);
+}
+
+static void log_expr(struct bpf_verifier_env *env, u32 id)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct expr *expr;
+ const char *str;
+ u32 order;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if ((order & PRE) && scev->stack_sz > 1)
+ bpf_log(log, " ");
+ expr = &scev->exprs[id];
+ switch (expr->op) {
+ case UNKNOWN:
+ if (order & PRE)
+ bpf_log(log, "?");
+ break;
+ case OPAQUE:
+ if (order & PRE)
+ bpf_log(log, "_");
+ break;
+ case REG:
+ if (order & PRE)
+ log_reg(env, expr->params[0]);
+ break;
+ case IMM:
+ if (order & PRE)
+ bpf_log(log, "%lld", expr->imm);
+ break;
+ default:
+ if (order & PRE) {
+ str = op_str(expr->op);
+ bpf_log(log, "(");
+ if (str)
+ bpf_log(log, "%s", str);
+ else
+ bpf_log(log, "bad-expr-op %x", expr->op);
+ }
+ if (order & DEPTH_LIMIT)
+ bpf_log(log, "...");
+ if (order & POST)
+ bpf_log(log, ")");
+ }
+ }
+}
+
+enum print_env_flags {
+ PRINT_SCEV = BIT(1)
+};
+
+static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ u16 live_regs = aux[insn_idx].live_regs_before;
+
+ return reg < MAX_BPF_REG
+ ? (BIT(reg) & live_regs)
+ : test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);
+}
+
+static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx, u32 flags)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ bool printed_some = false;
+ bool print_scev = flags & PRINT_SCEV;
+ bool is_self_scev;
+ bool is_self_reg;
+ int i, r;
+
+ if (e->empty) {
+ bpf_log(log, " <empty>\n");
+ return;
+ }
+
+ for (i = 0; i < REGS_NUM; i++) {
+ if (!reg_alive_at(env, i, insn_idx))
+ continue;
+ is_self_reg = is_reg(scev, e->reg2expr[i], &r) && i == r;
+ is_self_scev = is_reg(scev, e->reg2scev[i], &r) && i == r;
+ if (is_self_reg && (!print_scev || is_self_scev))
+ continue;
+ printed_some = true;
+ bpf_log(log, " ");
+ log_reg(env, i);
+ bpf_log(log, "=");
+ log_expr(env, e->reg2expr[i]);
+ if (print_scev && e->reg2expr[i] != UNKNOWN_EXPR_ID) {
+ bpf_log(log, " / ");
+ log_expr(env, e->reg2scev[i]);
+ }
+ bpf_log(log, "\n");
+ }
+ if (!printed_some)
+ bpf_log(log, " <all regs unchanged>\n");
+}
+static struct env *find_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 i;
+
+ if (!envs)
+ return NULL;
+ for (i = 0; i < envs->cnt; i++)
+ if (envs->entries[i].loop_header == loop_header)
+ return envs->entries[i].env;
+ return NULL;
+}
+
+static struct env *find_header_env(struct scev *scev, int header)
+{
+ return find_loop_env(scev, header, header);
+}
+
+static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx)
+{
+ struct insn_envs *envs = scev->envs[insn_idx];
+ u32 cnt = envs ? envs->cnt : 0;
+ struct insn_envs *tmp;
+ struct env *e;
+
+ e = find_loop_env(scev, loop_header, insn_idx);
+ if (e)
+ return e;
+
+ e = kzalloc(sizeof(*e), GFP_KERNEL_ACCOUNT);
+ if (!e)
+ return NULL;
+
+ tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);
+ if (!tmp) {
+ kfree(e);
+ return NULL;
+ }
+
+ e->empty = true;
+ tmp->entries[cnt].loop_header = loop_header;
+ tmp->entries[cnt].env = e;
+ tmp->cnt = cnt + 1;
+ scev->envs[insn_idx] = tmp;
+ return e;
+}
+
+static void setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)
+{
+ struct scev *scev = env->scev;
+ int i;
+
+ for (i = 0; i < REGS_NUM; i++)
+ e->reg2expr[i] = expr1(scev, REG, i);
+}
+
+static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
+{
+ if (id < 0)
+ return id;
+ e->reg2expr[reg] = id;
+ return 0;
+}
+
+static void forget_call_regs(struct env *e)
+{
+ int i;
+
+ for (i = BPF_REG_0; i <= BPF_REG_5; i++)
+ e->reg2expr[i] = UNKNOWN_EXPR_ID;
+}
+
+static u32 spill_spi(struct bpf_insn *insn)
+{
+ return -insn->off / BPF_REG_SIZE - 1;
+}
+
+static u32 off_to_reg(struct bpf_insn *insn)
+{
+ return spill_spi(insn) + MAX_BPF_REG;
+}
+
+static bool is_spill_off(int off)
+{
+ return off % BPF_REG_SIZE == 0 &&
+ off <= -BPF_REG_SIZE &&
+ off >= -MAX_BPF_STACK_JIT;
+}
+
+static void mark_opaque(struct env *e, int off, int size)
+{
+ int b, spi;
+
+ for (b = off; b < off + size; b++) {
+ if (b >= 0 || b < -MAX_BPF_STACK_JIT)
+ continue;
+ spi = (-b - 1) / BPF_REG_SIZE;
+ e->reg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;
+ }
+}
+
+static int mk_spill(struct scev *scev, u8 size, int id)
+{
+ switch (size) {
+ case BPF_B: return expr1(scev, SPILL8, id);
+ case BPF_H: return expr1(scev, SPILL16, id);
+ case BPF_W: return expr1(scev, SPILL32, id);
+ case BPF_DW: return id;
+ }
+ return UNKNOWN_EXPR_ID;
+}
+
+static int mk_fill(struct scev *scev, int id, u8 code)
+{
+ bool sx = BPF_MODE(code) == BPF_MEMSX;
+
+ switch (BPF_SIZE(code)) {
+ case BPF_B: return expr1(scev, sx ? SEXT8 : ZEXT8, id);
+ case BPF_H: return expr1(scev, sx ? SEXT16 : ZEXT16, id);
+ case BPF_W: return expr1(scev, sx ? SEXT32 : ZEXT32, id);
+ case BPF_DW: return sx ? UNKNOWN_EXPR_ID : id; /* DW sign-extended load is invalid */
+ }
+ return UNKNOWN_EXPR_ID;
+}
+
+static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)
+{
+ u8 size = BPF_SIZE(insn->code);
+
+ if (insn->dst_reg != BPF_REG_FP)
+ return 0;
+ if (is_spill_off(insn->off))
+ return replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));
+ mark_opaque(e, insn->off, bpf_size_to_bytes(size));
+ return 0;
+}
+
+static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)
+{
+ int id;
+
+ if (insn->src_reg == BPF_REG_FP && is_spill_off(insn->off))
+ id = mk_fill(scev, e->reg2expr[off_to_reg(insn)], insn->code);
+ else
+ id = OPAQUE_EXPR_ID;
+ return replace_reg(scev, e, insn->dst_reg, id);
+}
+
+static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
+{
+ const bool little_endian = htons(0x3412) == 0x1234;
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct scev *scev = env->scev;
+ u32 *reg2expr = e->reg2expr;
+ u8 class = BPF_CLASS(insn->code);
+ u8 x_or_k = BPF_SRC(insn->code);
+ u8 opcode = BPF_OP(insn->code);
+ u8 mode = BPF_MODE(insn->code);
+ u32 dst = insn->dst_reg;
+ u32 src = insn->src_reg;
+ u32 op, sext;
+ int i, id;
+ s64 imm;
+
+ switch (class) {
+ case BPF_ALU:
+ case BPF_ALU64:
+ switch (opcode) {
+ case BPF_MOV:
+ switch (insn->off) {
+ case 0: sext = 0; break;
+ case 8: sext = SEXT8; break;
+ case 16: sext = SEXT16; break;
+ case 32: sext = SEXT32; break;
+ default:
+ goto mark_dst_unknown;
+ }
+
+ if (x_or_k == BPF_X && insn->imm == 0)
+ id = reg2expr[src];
+ else if (x_or_k == BPF_K && src == 0 && insn->off == 0)
+ id = imm_expr(scev, insn->imm);
+ else
+ goto mark_dst_unknown;
+
+ if (sext)
+ id = expr1(scev, sext, id);
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_ADD:
+ case BPF_SUB:
+ case BPF_MUL:
+ case BPF_DIV:
+ case BPF_MOD:
+ case BPF_OR:
+ case BPF_XOR:
+ case BPF_AND:
+ case BPF_LSH:
+ case BPF_RSH:
+ case BPF_ARSH:
+ if (opcode == BPF_DIV && insn->off == 1)
+ op = SDIV;
+ else if (opcode == BPF_MOD && insn->off == 1)
+ op = SMOD;
+ else if (insn->off == 0)
+ op = opcode;
+ else
+ goto mark_dst_unknown;
+
+ if (x_or_k == BPF_X && insn->imm == 0)
+ id = reg2expr[src];
+ else if (x_or_k == BPF_K && src == 0)
+ id = imm_expr(scev, insn->imm);
+ else
+ goto mark_dst_unknown;
+
+ id = expr2(scev, op, reg2expr[dst], id);
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_NEG:
+ if (src == 0 && insn->off == 0 && insn->imm == 0)
+ id = expr1(scev, BPF_NEG, reg2expr[dst]);
+ else
+ goto mark_dst_unknown;
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+
+ case BPF_END:
+ switch (insn->imm) {
+ case 16: op = BSWAP16; break;
+ case 32: op = BSWAP32; break;
+ case 64: op = BSWAP64; break;
+ default:
+ goto mark_dst_unknown;
+ }
+
+ if (class == BPF_ALU && x_or_k == BPF_TO_LE && insn->off == 0 && little_endian)
+ op = 0; /* little-endian to little-endian is noop */
+ else if (class == BPF_ALU && x_or_k == BPF_TO_BE && insn->off == 0 && !little_endian)
+ op = 0; /* big-endian to big-endian is noop */
+ else if (class == BPF_ALU64 && x_or_k == 0 && insn->off == 0)
+ /* always swap */;
+ else
+ goto mark_dst_unknown;
+
+ id = reg2expr[dst];
+ if (op)
+ id = expr1(scev, op, reg2expr[dst]);
+
+ if (class == BPF_ALU)
+ id = expr1(scev, ZEXT32, id);
+
+ return replace_reg(scev, e, dst, id);
+ default:
+ goto mark_dst_unknown;
+ }
+ break;
+ case BPF_LDX:
+ switch (mode) {
+ case BPF_MEM:
+ case BPF_MEMSX:
+ return maybe_load_fp(scev, e, insn);
+ default:
+ goto mark_dst_unknown;
+ }
+ case BPF_STX:
+ switch (mode) {
+ case BPF_MEM:
+ return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ case BPF_ATOMIC:
+ if (insn->imm == BPF_LOAD_ACQ)
+ return maybe_load_fp(scev, e, insn);
+ if (insn->imm == BPF_STORE_REL) {
+ return maybe_store_fp(scev, e, insn, reg2expr[src]);
+ }
+ /*
+ * verifier does not track other atomic ops precisely,
+ * hence mark the results as opaque.
+ */
+ if (insn->dst_reg == BPF_REG_FP)
+ mark_opaque(e, insn->off, bpf_size_to_bytes(BPF_SIZE(insn->code)));
+ if (insn->imm == BPF_CMPXCHG)
+ return replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);
+ if (insn->imm & BPF_FETCH)
+ return replace_reg(scev, e, src, OPAQUE_EXPR_ID);
+ break;
+ }
+ break;
+ case BPF_ST:
+ if (insn->dst_reg == BPF_REG_FP) {
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ return maybe_store_fp(scev, e, insn, id);
+ }
+ break;
+ case BPF_JMP:
+ case BPF_JMP32:
+ if (opcode == BPF_CALL)
+ forget_call_regs(e);
+ /* for non-CALL there are no changes in register states */
+ break;
+ case BPF_LD:
+ switch (mode) {
+ case BPF_IMM:
+ /* rX = imm ll */
+ if (BPF_SIZE(insn->code) == BPF_DW && insn->src_reg == 0) {
+ imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
+ return replace_reg(scev, e, dst, imm_expr(scev, imm));
+ }
+ /* map, map value, BTF id, function */
+ if (BPF_SIZE(insn->code) == BPF_DW)
+ return replace_reg(scev, e, dst, OPAQUE_EXPR_ID);
+ goto mark_dst_unknown;
+ case BPF_ABS:
+ case BPF_IND:
+ forget_call_regs(e);
+ break;
+ default:
+ goto mark_dst_unknown;
+ }
+ break;
+ default:
+ /* unknown instruction, nuke state */
+ for (i = 0; i < REGS_NUM; i++)
+ reg2expr[i] = UNKNOWN_EXPR_ID;
+ break;
+ }
+ return 0;
+
+mark_dst_unknown:
+ reg2expr[dst] = UNKNOWN_EXPR_ID;
+ return 0;
+}
+
+/*
+ * Construct minimal 'ANY' expression by traversing 'a' and 'b'
+ * and accumulating non-duplicated non-ANY entries.
+ */
+static int mk_any(struct scev *scev, u32 a, u32 b)
+{
+ struct expr_stack_elt *elt;
+ struct expr *expr;
+ u32 i, j, ids_buf_sz;
+ u32 roots[2] = {a, b};
+ int id;
+
+ ids_buf_sz = 0;
+ for (i = 0; i < ARRAY_SIZE(roots); i++) {
+ scev->stack_sz = 0;
+ expr_stack_push(scev, roots[i]);
+ while (scev->stack_sz) {
+ elt = &scev->expr_stack[--scev->stack_sz];
+ id = elt->id;
+ expr = &scev->exprs[elt->id];
+ if (expr->op == ANY) {
+ if (!expr_stack_push(scev, expr->params[0]) ||
+ !expr_stack_push(scev, expr->params[1]))
+ return UNKNOWN_EXPR_ID;
+ } else {
+ for (j = 0; j < ids_buf_sz; j++) {
+ if (same_exprs(scev, scev->ids_buf[j], id))
+ goto next;
+ }
+ if (ids_buf_sz == ARRAY_SIZE(scev->ids_buf))
+ return UNKNOWN_EXPR_ID;
+ scev->ids_buf[ids_buf_sz++] = id;
+ }
+next:;
+ }
+ }
+ if (WARN_ON(ids_buf_sz == 0))
+ return -EFAULT;
+ id = scev->ids_buf[0];
+ for (i = 1; i < ids_buf_sz; i++) {
+ id = expr2(scev, ANY, id, scev->ids_buf[i]);
+ if (id < 0)
+ return id;
+ }
+ return id;
+}
+
+static int join(struct scev *scev, struct env *acc, struct env *cur)
+{
+ int i, id;
+
+ if (acc->empty) {
+ memcpy(acc, cur, sizeof(*acc));
+ acc->empty = false;
+ return 0;
+ }
+
+ for (i = 0; i < REGS_NUM; i++) {
+ if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[i])) {
+ id = mk_any(scev, acc->reg2expr[i], cur->reg2expr[i]);
+ if (id < 0)
+ return id;
+ acc->reg2expr[i] = id;
+ }
+ }
+ return 0;
+}
+
+/* Mark any register modified in 'header_env' as unknown in 'acc'. */
+static void forget_non_invariants(struct scev *scev, struct env *acc, struct env *header_env)
+{
+ struct expr *header_expr;
+ int i;
+
+ if (acc->empty)
+ acc->empty = false;
+
+ for (i = 0; i < REGS_NUM; i++) {
+ header_expr = &scev->exprs[header_env->reg2expr[i]];
+ if (is_expr1(header_expr, REG, i))
+ continue;
+ acc->reg2expr[i] = UNKNOWN_EXPR_ID;
+ }
+}
+
+static int worklist_push(struct scev *scev, int loop_header, int idx)
+{
+ u32 tag = (u32)loop_header + 1;
+ int err;
+
+ if (scev->discovered[idx] == tag)
+ return 0;
+
+ err = bpf_min_heap_push(&scev->worklist, idx);
+ if (err)
+ return err;
+
+ scev->discovered[idx] = tag;
+ return 0;
+}
+
+static bool reg_alive_at_succ(struct bpf_verifier_env *env, u32 r, u32 insn_idx)
+{
+ struct bpf_iarray *succ = bpf_insn_successors(env, insn_idx);
+ u32 i;
+
+ for (i = 0; i < succ->cnt; i++)
+ if (reg_alive_at(env, r, succ->items[i]))
+ return true;
+ return false;
+}
+
+enum changes_at {
+ LOG_AT_TRANSFER,
+ LOG_AT_JOIN,
+};
+
+static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
+ struct env *old, struct env *new, int insn_idx)
+{
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ u64 null_pos = log->end_pos;
+ bool any_changes = false;
+ u32 old_id, new_id;
+ u64 len;
+ int r;
+
+ bpf_log(log, "%s %4d: ", at == LOG_AT_TRANSFER ? "t" : "j", insn_idx);
+ bpf_verbose_insn(env, &env->prog->insnsi[insn_idx]);
+ len = log->end_pos - null_pos;
+ bpf_log(log, "%*s", max(37 - (int)len, 1), " ");
+ bpf_log(log, " ; ");
+ for (r = 0; r < REGS_NUM; r++) {
+ old_id = old->reg2expr[r];
+ new_id = new->reg2expr[r];
+ if (at == LOG_AT_TRANSFER && !reg_alive_at_succ(env, r, insn_idx))
+ continue;
+ if (at == LOG_AT_JOIN && !reg_alive_at(env, r, insn_idx))
+ continue;
+ if (same_exprs(scev, old_id, new_id))
+ continue;
+ if (any_changes)
+ bpf_log(log, ", ");
+ log_reg(env, r);
+ bpf_log(log, " ");
+ log_expr(env, old_id);
+ bpf_log(log, " -> ");
+ log_expr(env, new_id);
+ any_changes = true;
+ }
+ bpf_log(log, "\n");
+ if (!any_changes)
+ bpf_vlog_reset(log, null_pos);
+}
+
+static bool is_probe_read_helper(u32 func_id)
+{
+ return func_id == BPF_FUNC_probe_read ||
+ func_id == BPF_FUNC_probe_read_kernel ||
+ func_id == BPF_FUNC_probe_read_user ||
+ func_id == BPF_FUNC_probe_read_str ||
+ func_id == BPF_FUNC_probe_read_kernel_str ||
+ func_id == BPF_FUNC_probe_read_user_str;
+}
+
+/*
+ * If instruction is an indirect write to stack, invalidate SCEVs for spi's
+ * that this instruction can touch.
+ */
+static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct scev *scev = env->scev;
+ u8 class = BPF_CLASS(insn->code);
+ const unsigned long *mask;
+ u32 spi, reg;
+ bool opaque;
+
+ /* Direct fp stores are fine. */
+ if ((class == BPF_ST || class == BPF_STX) && insn->dst_reg == BPF_REG_FP)
+ return;
+
+ mask = bpf_may_write_mask(env, idx);
+ opaque = bpf_helper_call(insn) && is_probe_read_helper(insn->imm);
+ for_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {
+ reg = MAX_BPF_REG + spi;
+ if (cur_env->reg2expr[reg] == UNKNOWN_EXPR_ID)
+ continue;
+ replace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);
+ }
+}
+
+/* OR the loop-entry registers referenced by expr 'id' into 'mask'. */
+static void or_expr_regs(struct bpf_verifier_env *env, u32 id, unsigned long *mask)
+{
+ struct scev *scev = env->scev;
+ u32 order;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if ((order & PRE) && scev->exprs[id].op == REG)
+ __set_bit(scev->exprs[id].params[0], mask);
+ }
+}
+
+/* Mask of argument registers (R1..R5) a call at 'idx' passes by register. */
+static u16 call_params_mask(struct bpf_verifier_env *env, int idx)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ struct bpf_call_summary cs;
+ int n = bpf_get_call_summary(env, insn, &cs) ? cs.arg_slot_cnt : MAX_BPF_FUNC_REG_ARGS;
+
+ return n ? GENMASK(BPF_REG_1 + n - 1, BPF_REG_1) : 0;
+}
+
+/*
+ * For instructions like:
+ * - *(u64 *)(rBase + off) = rX
+ * - rX = *(u64 *)(rBase + off)
+ * - calls that construct objects on stack (e.g. dynptr_from_mem(rBase, ...))
+ * When 'rBase' can be a stack pointer and is derived from some registers Rs
+ * defined at loop entry, record Rs into 'mask'.
+ */
+static void collect_store_base_regs(struct bpf_verifier_env *env,
+ struct env *cur_env, int idx, unsigned long *mask)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_insn *insn = &env->prog->insnsi[idx];
+ u8 class = BPF_CLASS(insn->code);
+ u8 size = BPF_SIZE(insn->code);
+ u16 base_regs = 0;
+ u32 r;
+
+ if (size == BPF_W || size == BPF_DW) {
+ if ((class == BPF_STX || class == BPF_ST) && insn->dst_reg != BPF_REG_FP)
+ base_regs |= BIT(insn->dst_reg);
+ else if (class == BPF_LDX && insn->src_reg != BPF_REG_FP)
+ base_regs |= BIT(insn->src_reg);
+ }
+
+ if (class == BPF_JMP && BPF_OP(insn->code) == BPF_CALL &&
+ bpf_needs_fixed_stack_off(env, idx))
+ base_regs |= call_params_mask(env, idx);
+
+ base_regs &= aux[idx].stack_ptrs;
+ for (r = 0; r < MAX_BPF_REG; r++)
+ if (base_regs & BIT(r))
+ or_expr_regs(env, cur_env->reg2expr[r], mask);
+}
+
+/* Find the topmost loop header containing idx inside cur_header, or -1 if none. */
+static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_header)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int header;
+
+ for (header = bpf_loop_at_index(env, idx); header >= 0;
+ header = aux[header].loop_header)
+ if (aux[header].loop_header == cur_header)
+ return header;
+
+ return -1;
+}
+
+/*
+ * Join cur_env into the successor's environment and schedule their traversal.
+ * Map successors in nested loops to their topmost nested header.
+ * Ignore successors outside the current loop and its nested loops.
+ */
+static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
+ struct env *old_env, struct env *cur_env)
+{
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ struct scev *scev = env->scev;
+ int err, nested_header;
+ struct env *succ_env;
+
+ /*
+ * There are several possibilities for a successor:
+ * - succ_idx can be a part of a loop outside of the cur_header's loop,
+ * such edges are ignored.
+ * - succ_idx can be a part of the same loop as cur_header,
+ * for such edges succ_idx environment is updated:
+ * e[succ_idx] = join(e[succ_idx], cur_env)
+ * - succ_idx can be a part of some loop inner to cur_header,
+ * in such a case there exists some loop header H,
+ * such that H.loop_header == cur_header
+ * and H is the same as succ_idx's loop or contains it.
+ */
+ if (bpf_loop_at_index(env, succ_idx) != cur_header) {
+ /*
+ * topmost_nested_loop() either finds H or returns -1,
+ * in case if succ_idx is a part of a loop outer to cur_header.
+ */
+ nested_header = topmost_nested_loop(env, succ_idx, cur_header);
+ if (nested_header < 0)
+ return 0;
+ succ_idx = nested_header;
+ }
+ succ_env = get_loop_env(scev, cur_header, succ_idx);
+ if (!succ_env)
+ return -ENOMEM;
+ if (log_level2)
+ memcpy(old_env, succ_env, sizeof(*old_env));
+ err = join(scev, succ_env, cur_env);
+ if (err)
+ return err;
+ err = worklist_push(scev, cur_header, succ_idx);
+ if (err)
+ return err;
+ if (log_level2)
+ log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
+ return 0;
+}
+
+static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
+{
+ struct bpf_min_heap *worklist = &env->scev->worklist;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *cur_loop = aux[cur_header].loop;
+ struct env *header_env, *nested_header_env;
+ struct scev *scev = env->scev;
+ struct bpf_loop *nested_loop;
+ struct env *cur_env = NULL;
+ struct env *old_env = NULL;
+ struct bpf_iarray *succ;
+ bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
+ int s, i, err, idx, succ_idx;
+ u32 r;
+
+ if (log_level2)
+ bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
+
+ /*
+ * For irreducible loops, and for loops nesting a loop with a truncated
+ * exit list, just assume that everything is clobbered for now.
+ */
+ if (cur_loop->irreducible || cur_loop->exits_overflow) {
+ header_env = get_loop_env(scev, cur_header, cur_header);
+ if (!header_env)
+ return -ENOMEM;
+ /* The freshly allocated environment has all expressions unknown. */
+ bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
+ header_env->empty = false;
+ return 0;
+ }
+
+ cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
+ if (!cur_env)
+ goto nomem;
+ if (log_level2) {
+ old_env = kzalloc(sizeof(*old_env), GFP_KERNEL_ACCOUNT);
+ if (!old_env)
+ goto nomem;
+ }
+ header_env = get_loop_env(scev, cur_header, cur_header);
+ if (!header_env)
+ goto nomem;
+ setup_initial_loop_env(env, header_env, cur_header);
+ err = worklist_push(scev, cur_header, cur_header);
+ if (err)
+ goto out;
+
+ for (;;) {
+ if (!bpf_min_heap_pop(worklist, &idx))
+ break;
+
+ /* join_successor() maps nested-loop entries to their representative header. */
+ nested_loop = idx != cur_header ? aux[idx].loop : NULL;
+ memcpy(cur_env, find_loop_env(scev, cur_header, idx), sizeof(*cur_env));
+ if (nested_loop) {
+ /*
+ * Process nested loop as a single instruction by
+ * forgetting anything non-invariant in the nested loop
+ */
+ if (log_level2)
+ memcpy(old_env, cur_env, sizeof(*old_env));
+ /* Pull the nested loop's stack-store base dependencies up. */
+ for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
+ or_expr_regs(env, cur_env->reg2expr[r], cur_loop->store_base_regs);
+ nested_header_env = find_header_env(scev, idx);
+ forget_non_invariants(scev, cur_env, nested_header_env);
+ if (log_level2)
+ log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
+ /*
+ * Treat nested loop exits as successors,
+ * join cur_env into successor's envs.
+ */
+ for (i = 0; i < nested_loop->exits_cnt; i++) {
+ s = nested_loop->exits[i].to;
+ err = join_successor(env, cur_header, s, old_env, cur_env);
+ if (err)
+ goto out;
+ }
+ } else {
+ /*
+ * Iterate instructions within a single basic block
+ * starting at 'idx' mutating 'cur_env'.
+ */
+ for (;;) {
+ if (log_level2)
+ memcpy(old_env, cur_env, sizeof(*old_env));
+ collect_store_base_regs(env, cur_env, idx, cur_loop->store_base_regs);
+ err = transfer(env, cur_env, idx);
+ if (err)
+ goto out;
+ reset_scevs_at_indirect_writes(env, cur_env, idx);
+ if (log_level2)
+ log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
+ succ = bpf_insn_successors(env, idx);
+ if (succ->cnt != 1)
+ break;
+ succ_idx = succ->items[0];
+ if (aux[idx].bb_end || aux[succ_idx].need_scev ||
+ bpf_loop_at_index(env, succ_idx) != cur_header)
+ break;
+ idx = succ_idx;
+ }
+ /* Join cur_env into basic block successor's envs. */
+ iarray_for_each(s, succ) {
+ err = join_successor(env, cur_header, s, old_env, cur_env);
+ if (err)
+ goto out;
+ }
+ }
+ }
+
+ err = 0;
+out:
+ kfree(cur_env);
+ kfree(old_env);
+ return err;
+nomem:
+ err = -ENOMEM;
+ goto out;
+}
+
+static void mark_latches(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop;
+ int len = env->prog->len;
+ int i, j, latch;
+
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ aux[i].need_scev = true;
+ if (loop->irreducible)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ latch = loop->backedges[j].latch;
+ if (latch >= 0)
+ aux[latch].need_scev = true;
+ }
+ }
+}
+
+static bool is_any_imm_reg_opaque(struct scev *scev, u32 id)
+{
+ u32 l, r, reg, order;
+ s64 imm;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT)
+ return false;
+ if (!(order & PRE) ||
+ is_imm(scev, id, &imm) ||
+ is_reg(scev, id, ®) ||
+ is_opaque(scev, id) ||
+ is_any(scev, id, &l, &r))
+ continue;
+ return false;
+ }
+ return true;
+}
+
+/*
+ * Can implement explicit stack version, but it is harder to read.
+ * Stick with recursive version for now.
+ */
+static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
+ int (*fn)(struct scev *scev, u32 id, void *priv))
+{
+ struct expr expr;
+ int p0, p1, id;
+
+ if (lvl >= EXPR_STACK_DEPTH)
+ return UNKNOWN_EXPR_ID;
+
+ expr = scev->exprs[root]; /* snapshot the expr before potential realloc */
+ switch (op_params_num(expr.op)) {
+ case 0:
+ id = root;
+ break;
+ case 1:
+ p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
+ id = expr1(scev, expr.op, p0);
+ break;
+ case 2:
+ p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
+ p1 = transform_expr_once(scev, lvl + 1, expr.params[1], priv, fn);
+ id = expr2(scev, expr.op, p0, p1);
+ break;
+ }
+ return id < 0 ? id : fn(scev, id, priv);
+}
+
+static int transform_expr(struct scev *scev, u32 root, void *priv,
+ int (*fn)(struct scev *scev, u32 id, void *priv))
+{
+ int id_old, id_new = root;
+
+ do {
+ id_old = id_new;
+ id_new = transform_expr_once(scev, 0, id_old, priv, fn);
+ if (id_new < 0)
+ return id_new;
+ } while (id_old != id_new);
+ return id_new;
+}
+
+static int simplify(struct scev *scev, u32 id, void *priv)
+{
+ u32 l, r, base, slope;
+ s64 imm1, imm2;
+
+ /* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
+ if (is_add(scev, id, &l, &r) &&
+ is_linear(scev, l, &base, &slope) &&
+ is_imm(scev, r, &imm1))
+ return expr2(scev, LINEAR_SCEV, expr2(scev, BPF_ADD, base, r), slope);
+
+ /* (+ imm imm) -> imm */
+ if (is_add(scev, id, &l, &r) &&
+ is_imm(scev, l, &imm1) &&
+ is_imm(scev, r, &imm2))
+ return imm_expr(scev, imm1 + imm2);
+
+ if (is_zext32(scev, id, &l) && is_imm(scev, l, &imm1))
+ return imm_expr(scev, (u64)(u32)imm1);
+
+ return id;
+}
+
+static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
+{
+ struct scev *scev = env->scev;
+ u32 ra, rb, l, r, ra_expr;
+ s64 imm;
+ int id;
+
+ for (ra = 0; ra < REGS_NUM; ra++) {
+ id = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
+ if (id < 0)
+ return id;
+ header_env->reg2expr[ra] = id;
+ ra_expr = header_env->reg2expr[ra];
+ /* rA = (+ rA IMM) */
+ if (is_add(scev, ra_expr, &l, &r) &&
+ is_reg(scev, l, &rb) &&
+ is_imm(scev, r, &imm) &&
+ ra == rb) {
+ id = expr2(scev, LINEAR_SCEV, l, r);
+ if (id < 0)
+ return id;
+ header_env->reg2scev[ra] = id;
+ continue;
+ }
+ /* rA = rA */
+ if (is_reg(scev, ra_expr, &rb) && ra == rb) {
+ header_env->reg2scev[ra] = ra_expr;
+ continue;
+ }
+ /* rA = (any 1 2 3 4 ...) */
+ if (is_any_imm_reg_opaque(scev, ra_expr)) {
+ header_env->reg2scev[ra] = ra_expr;
+ continue;
+ }
+
+ }
+ return 0;
+}
+static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
+{
+ u32 reg, base, slope, *reg2scev = priv;
+
+ /* (reg r) -> (linear ...), where r is a LINEAR_SCEV in the header */
+ if (is_reg(scev, id, ®) &&
+ is_linear(scev, reg2scev[reg], &base, &slope))
+ return reg2scev[reg];
+ return id;
+}
+
+static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
+{
+ struct scev *scev = env->scev;
+ int id, reg;
+
+ for (reg = 0; reg < REGS_NUM; reg++) {
+ id = einsn->reg2expr[reg];
+ id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
+ if (id < 0)
+ return id;
+ id = transform_expr(scev, id, NULL, simplify);
+ if (id < 0)
+ return id;
+ einsn->reg2scev[reg] = id;
+ }
+
+ return 0;
+}
+
+static void log_scevs(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct bpf_loop *loop;
+ int i, j, len, latch;
+
+ len = env->prog->len;
+ for (i = 0; i < len; i++) {
+ loop = aux[i].loop;
+ if (!loop)
+ continue;
+ bpf_log(log, "scev at header %d:\n", i);
+ print_env(env, find_header_env(scev, i), i, PRINT_SCEV);
+ if (loop->irreducible)
+ continue;
+ for (j = 0; j < loop->backedges_cnt; j++) {
+ latch = loop->backedges[j].latch;
+ if (latch < 0)
+ continue;
+ bpf_log(log, " scev at latch %d:\n", latch);
+ print_env(env, find_loop_env(scev, bpf_loop_at_index(env, latch), latch),
+ latch, PRINT_SCEV);
+ }
+ }
+}
+
+int bpf_compute_scev(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct scev *scev = env->scev;
+ int *postorder = env->cfg.insn_postorder;
+ int cnt = env->cfg.cur_postorder;
+ int i, idx, err, header;
+
+ mark_latches(env);
+ /*
+ * Visit loop headers in postorder, to guarantee that scevs
+ * for innermost loops are computed first.
+ */
+ for (i = 0; i < cnt; i++) {
+ idx = postorder[i];
+ if (!aux[idx].loop)
+ continue;
+ err = compute_scev_for_loop(env, idx);
+ if (err)
+ return err;
+ }
+
+ /*
+ * Compute scevs from exprs collected on a previous step. Iterate instructions in
+ * reverse post-order so that each loop header is processed before instructions
+ * reachable from it.
+ */
+ for (i = cnt - 1; i >= 0; i--) {
+ idx = postorder[i];
+ if (!aux[idx].need_scev)
+ continue;
+ header = bpf_loop_at_index(env, idx);
+ err = aux[idx].loop
+ ? compute_header_scevs(env, find_header_env(scev, header))
+ : compute_insn_scevs(env, find_header_env(scev, header),
+ find_loop_env(scev, header, idx));
+ if (err)
+ return err;
+ }
+
+ for (i = 0; i < env->prog->len; i++)
+ if (aux[i].loop)
+ aux[i].prune_point = true;
+
+ if (env->log.level & BPF_LOG_LEVEL2)
+ log_scevs(env);
+
+ return 0;
+}
+
+static int reverse_ranked_compare(int a, int b, void *arg)
+{
+ int *rank = arg;
+
+ return rank[b] - rank[a];
+}
+
+void bpf_free_scev(struct bpf_verifier_env *env)
+{
+ struct scev *scev = env->scev;
+ struct insn_envs *envs;
+ int i;
+ u32 j;
+
+ if (!scev)
+ return;
+ for (i = 0; i < scev->envs_cnt; i++) {
+ envs = scev->envs[i];
+ if (!envs)
+ continue;
+ for (j = 0; j < envs->cnt; j++)
+ kfree(envs->entries[j].env);
+ kfree(envs);
+ }
+ for (i = 0; i < ARRAY_SIZE(scev->exprs_ht); i++)
+ kvfree(scev->exprs_ht[i]);
+ bpf_min_heap_free(&scev->worklist);
+ kvfree(scev->envs);
+ kvfree(scev->exprs);
+ kvfree(scev->discovered);
+ kfree(scev);
+ env->scev = NULL;
+}
+
+int bpf_init_scev(struct bpf_verifier_env *env)
+{
+ struct scev *scev;
+
+ scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
+ if (!scev)
+ return -ENOMEM;
+ env->scev = scev;
+ bpf_mark_reg_not_init(env, &env->scev_not_init_reg);
+ /* Order worklist in reverse post-order. */
+ bpf_min_heap_init(&scev->worklist, reverse_ranked_compare, env->cfg.postorder_nums);
+ if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE) < 0)
+ goto nomem;
+ scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
+ scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
+ if (!scev->envs || !scev->discovered)
+ goto nomem;
+ /*
+ * Remember original program length, in case bpf_free_scev()
+ * is called after bpf program rewrites that increase program
+ * length.
+ */
+ scev->envs_cnt = env->prog->len;
+ return 0;
+nomem:
+ bpf_free_scev(env);
+ return -ENOMEM;
+}
+
+static struct bpf_reg_state *scev_regno_to_reg(struct bpf_verifier_env *env,
+ struct bpf_func_state *st, u32 r)
+{
+ int spi, slots_available;
+
+ if (r < MAX_BPF_REG)
+ return &st->regs[r];
+
+ slots_available = st->allocated_stack / BPF_REG_SIZE;
+ spi = r - MAX_BPF_REG;
+ if (spi < slots_available)
+ return &st->stack[spi].spilled_ptr;
+
+ return &env->scev_not_init_reg;
+}
+
+static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 r)
+{
+ int insn_idx = bpf_frame_insn_idx(st, st->curframe);
+ u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
+ int spi;
+
+ if (r < MAX_BPF_REG) {
+ return BIT(r) & live_regs;
+ } else {
+ spi = r - MAX_BPF_REG;
+ return bpf_stack_slot_alive(env, st->curframe, spi * 2) ||
+ bpf_stack_slot_alive(env, st->curframe, spi * 2 + 1);
+ }
+}
+
+/*
+ * Latch is a condition deciding if execution remains inside a loop.
+ * Linear latch represents a condition 'if <reg> <op> <loop invariant> goto <loop-header>',
+ * where equation '<base> + i * <step> <op> <bound>' describes values taken by register <reg>,
+ * 'i' is the loop iteration number, starting from 0.
+ */
+struct linear_latch {
+ u32 insn_idx;
+ u32 base_expr;
+ u32 step_expr;
+ u32 bound_expr;
+ u32 reg_expr;
+ u32 reg;
+ u32 op;
+};
+
+static bool loop_invariant(struct scev *scev, u32 id)
+{
+ s64 imm;
+ u32 reg;
+
+ return is_reg(scev, id, ®) || is_imm(scev, id, &imm);
+}
+
+static int match_linear_latch(struct bpf_verifier_env *env,
+ u32 latch_idx,
+ struct linear_latch *latch)
+{
+ struct bpf_insn *insn = &env->prog->insnsi[latch_idx];
+ struct scev *scev = env->scev;
+ struct env *latch_env = find_loop_env(scev, bpf_loop_at_index(env, latch_idx), latch_idx);
+ u32 true_branch_tgt;
+ u32 l, r, op, base;
+ u32 src_reg_scev;
+ u32 dst_reg_scev;
+ int id;
+
+ /* 32-bit arithmetic is not handled yet */
+ if (BPF_CLASS(insn->code) != BPF_JMP)
+ return false;
+ op = BPF_OP(insn->code);
+ /* Flip the condition if true branch jumps out of the loop */
+ true_branch_tgt = latch_idx + bpf_jmp_offset(insn) + 1;
+ if (bpf_loop_at_index(env, true_branch_tgt) != bpf_loop_at_index(env, latch_idx))
+ op = bpf_rev_opcode(op);
+ switch (op) {
+ case BPF_JSLT:
+ case BPF_JSLE:
+ case BPF_JSGT:
+ case BPF_JSGE:
+ case BPF_JLT:
+ case BPF_JLE:
+ case BPF_JGT:
+ case BPF_JGE:
+ case BPF_JNE:
+ break;
+ default:
+ return false;
+ }
+
+ latch->op = op;
+ latch->insn_idx = latch_idx;
+
+ dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
+ src_reg_scev = latch_env->reg2scev[insn->src_reg];
+ if (!is_linear(scev, dst_reg_scev, &base, &latch->step_expr))
+ return false;
+
+ if (BPF_SRC(insn->code) == BPF_K) {
+ id = imm_expr(scev, insn->imm);
+ if (id < 0)
+ return id;
+ latch->bound_expr = id;
+ } else {
+ latch->bound_expr = src_reg_scev;
+ }
+
+ if (is_reg(scev, base, &latch->reg)) {
+ id = imm_expr(scev, 0);
+ if (id < 0)
+ return id;
+ latch->base_expr = id;
+ latch->reg_expr = base;
+ } else if (is_add(scev, base, &l, &r) &&
+ is_reg(scev, l, &latch->reg)) {
+ latch->base_expr = r;
+ latch->reg_expr = l;
+ } else {
+ return false;
+ }
+
+ if (!loop_invariant(scev, latch->base_expr) ||
+ !loop_invariant(scev, latch->step_expr) ||
+ !loop_invariant(scev, latch->bound_expr))
+ return false;
+
+ return true;
+}
+
+static bool eval_expr(struct bpf_verifier_env *env, struct scev *scev, struct bpf_func_state *st, u32 id, u64 *result)
+{
+ struct bpf_reg_state *reg;
+ u32 regno;
+ s64 imm;
+
+ if (is_reg(scev, id, ®no)) {
+ reg = scev_regno_to_reg(env, st, regno);
+ if (reg->type == NOT_INIT)
+ return false;
+ if (tnum_is_const(reg->var_off)) {
+ *result = reg->var_off.value;
+ return true;
+ }
+ } else if (is_imm(scev, id, &imm)) {
+ *result = imm;
+ return true;
+ }
+ return false;
+}
+
+/* Like DIV_ROUND_UP() but overflow safe */
+static u64 div_round_up(u64 a, u64 b)
+{
+ return a / b + (a % b != 0);
+}
+
+/*
+ * Loop with post-condition:
+ *
+ * r0 = 0
+ * l: ... r0 ∈ [0,1,2] header executed 3 times
+ * r0 += 1 r0 ∈ [0,1,2]
+ * ... r0 ∈ [1,2,3]
+ * if r0 != 3 goto l r0 ∈ [1,2,3] backedge taken 2 times
+ * ... r0 ∈ [3]
+ *
+ * SCEV at header: r0 = k
+ * SCEV at latch: r0 = 1 + k
+ *
+ * Loop with pre-condition:
+ *
+ * r0 = 0
+ * l: ... r0 ∈ [0,1,2,3] header executed 4 times
+ * if r0 == 3 goto e r0 ∈ [0,1,2,3] backedge taken 3 times
+ * r0 += 1 r0 ∈ [0,1,2]
+ * ... r0 ∈ [1,2,3]
+ * goto l r0 ∈ [1,2,3]
+ * e: ... r0 ∈ [3]
+ *
+ * SCEV at header: r0 = k
+ * SCEV at latch: r0 = k
+ */
+static bool compute_max_iters(struct bpf_verifier_env *env,
+ struct bpf_func_state *st,
+ struct linear_latch *latch,
+ struct bpf_loop_iters *iters)
+{
+ u64 base, step, diff, bound, initial, max_iters;
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_loop *loop = aux[bpf_loop_at_index(env, latch->insn_idx)].loop;
+ struct scev *scev = env->scev;
+ u8 op = latch->op;
+
+ if (!eval_expr(env, scev, st, latch->base_expr, &base) ||
+ !eval_expr(env, scev, st, latch->step_expr, &step) ||
+ !eval_expr(env, scev, st, latch->bound_expr, &bound) ||
+ !eval_expr(env, scev, st, latch->reg_expr, &initial))
+ return false;
+
+ if (step == 0)
+ return false;
+ if ((s64)step == S64_MIN)
+ return false;
+ if ((s64)step < 0) {
+ /* Multiply both sides of the equation by -1, e.g. -2*i > -3 becomes 2*i < 3 */
+ op = bpf_flip_opcode(op);
+ step = -step;
+ swap(bound, initial);
+ }
+ diff = bound - initial;
+ if (diff / step == U64_MAX)
+ return false;
+ switch (op) {
+ case BPF_JLT:
+ max_iters = (u64)initial >= (u64)bound ? 0 : div_round_up(diff, step);
+ break;
+ case BPF_JLE:
+ max_iters = (u64)initial > (u64)bound ? 0 : diff / step + 1;
+ break;
+ case BPF_JSLT:
+ max_iters = (s64)initial >= (s64)bound ? 0 : div_round_up(diff, step);
+ break;
+ case BPF_JSLE:
+ max_iters = (s64)initial > (s64)bound ? 0 : diff / step + 1;
+ break;
+ case BPF_JNE:
+ max_iters = diff % step ? U32_MAX : div_round_up(diff, step);
+ break;
+ default:
+ return false;
+ }
+
+ if (max_iters > U32_MAX)
+ return false;
+
+ /*
+ * The latch is a conditional jump with one jump target exiting the loop.
+ * Linear latch is matched only if the loop has a single backedge.
+ * The loop still, however can have multiple exits.
+ * In such case, conservatively assume that non-latch exit can happen
+ * at any iteration, thus setting minimal number of iterations as 0.
+ */
+ iters->max_header_count = max_iters + (base == 0 ? 1 : 0);
+ iters->min_header_count = loop->exits_cnt == 1 ? iters->max_header_count : 0;
+ iters->pre_cond = base == 0;
+ return true;
+}
+
+static void mark_scev_reg_scratched(struct bpf_verifier_env *env, u32 r)
+{
+ if (r < MAX_BPF_REG)
+ mark_reg_scratched(env, r);
+ else
+ mark_stack_slot_scratched(env, r - __MAX_BPF_REG);
+}
+
+/* Main logic in verifier.c forbids varying offsets for certain register types. */
+static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
+{
+ switch (base_type(reg->type)) {
+ case SCALAR_VALUE:
+ case PTR_TO_MAP_VALUE:
+ case PTR_TO_MAP_KEY:
+ case PTR_TO_STACK:
+ case PTR_TO_PACKET:
+ case PTR_TO_PACKET_META:
+ case PTR_TO_MEM:
+ case PTR_TO_BUF:
+ case PTR_TO_BTF_ID:
+ return true;
+ default:
+ return false;
+ }
+}
+
+/* Check that ANY leaves can be unioned with r's loop-entry value. */
+static bool is_any_imm_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
+ struct env *header_env, u32 r, u32 id)
+{
+ struct scev *scev = env->scev;
+ struct bpf_reg_state *reg, *leaf_reg;
+ u32 l, rr, leaf, ra, order;
+ s64 imm;
+
+ if (!is_any(scev, id, &l, &rr))
+ return false;
+ reg = scev_regno_to_reg(env, loop_entry, r);
+ if (!is_widenable_reg_type(reg))
+ return false;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT)
+ return false;
+ if (!(order & PRE) || is_any(scev, id, &l, &rr))
+ continue;
+ if (is_imm(scev, id, &imm)) {
+ if (reg->type != SCALAR_VALUE)
+ return false;
+ } else if (is_reg(scev, id, &leaf)) {
+ /* Other leaves must denote loop-invariant registers. */
+ if (leaf != r &&
+ !(is_reg(scev, header_env->reg2scev[leaf], &ra) && ra == leaf))
+ return false;
+ leaf_reg = scev_regno_to_reg(env, loop_entry, leaf);
+ if (leaf_reg->type != reg->type)
+ return false;
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
+struct bounds {
+ struct cnum64 range;
+ u16 step;
+};
+
+static bool is_simple_linear(struct scev *scev, u32 id, u32 *base_reg, s64 *slope_imm)
+{
+ u32 base, slope;
+
+ return is_linear(scev, id, &base, &slope) &&
+ is_reg(scev, base, base_reg) &&
+ is_imm(scev, slope, slope_imm) &&
+ *slope_imm <= S16_MAX &&
+ *slope_imm >= S16_MIN &&
+ *slope_imm != 0;
+}
+
+/*
+ * Compute the range an induction variable in `reg` spans over the loop.
+ * Returns false if the computation overflows s64.
+ */
+static bool linear_bounds(struct bpf_reg_state *reg, struct bpf_loop_iters *iters, s64 slope,
+ struct bounds *out)
+{
+ s64 slope_abs = slope < 0 ? -slope : slope;
+ s64 min_val = reg_smin(reg);
+ s64 max_val = reg_smax(reg);
+ s64 total_change;
+ u16 step;
+
+ if (check_mul_overflow(slope, (s64)iters->max_header_count - 1, &total_change))
+ return false;
+ if (slope > 0) {
+ if (check_add_overflow(max_val, total_change, &max_val))
+ return false;
+ } else {
+ if (check_add_overflow(min_val, total_change, &min_val))
+ return false;
+ }
+ /*
+ * If the entry value is a single point the value set is 'v + slope * k',
+ * so the step is |slope|. Otherwise, only the power-of-two alignment
+ * shared by the entry value and the slope.
+ */
+ if (cnum64_is_const(reg->r64))
+ step = slope_abs;
+ else
+ step = 1u << min_t(u32, tnum_alignment(reg->var_off), __ffs(slope_abs));
+ out->range = cnum64_from_srange(min_val, max_val);
+ out->step = step;
+ return true;
+}
+
+int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *cur_func = st->frame[st->curframe];
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct env *header_env;
+ struct linear_latch latch;
+ struct bpf_loop *loop;
+ struct bounds bounds;
+ int insn_idx = st->insn_idx;
+ int linear_latch;
+ u32 r, base_reg;
+ int latch_idx;
+ s64 slope_imm;
+ int err;
+
+ /*
+ * If insn_idx is a loop header for a reducible loop with a single backedge.
+ * loop is NULL for secondary entries to irreducible loops.
+ */
+ loop = aux[insn_idx].loop;
+ if (!loop || loop->irreducible || loop->backedges_cnt != 1 || loop->backedges_overflow ||
+ loop->exits_overflow) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, unsupported loop:%s%s%s\n", insn_idx,
+ !loop || loop->irreducible ? " irreducible" : "",
+ loop && loop->backedges_cnt > 1 ? " multiple backedges" : "",
+ loop && loop->exits_overflow ? " too many exits" : "");
+ return 0;
+ }
+
+ /* If this backedge has a latch */
+ latch_idx = loop->backedges[0].latch;
+ if (latch_idx < 0)
+ return 0;
+
+ linear_latch = match_linear_latch(env, latch_idx, &latch);
+ if (linear_latch < 0)
+ return linear_latch;
+
+ if (!linear_latch) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, non-linear latch at %d\n",
+ insn_idx, latch_idx);
+ return 0;
+ }
+
+ if (!compute_max_iters(env, cur_func, &latch, iters)) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, can't compute iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (iters->max_header_count == 0) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, 0 iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (iters->max_header_count == U32_MAX) {
+ if (log->level & BPF_LOG_LEVEL2)
+ bpf_log(log, "loop header at %d, inf iterations count\n", insn_idx);
+ return 0;
+ }
+
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, header_count is ", insn_idx);
+ if (iters->min_header_count == iters->max_header_count)
+ bpf_log(log, "%u ", iters->max_header_count);
+ else
+ bpf_log(log, "[%u..%u] ", iters->min_header_count, iters->max_header_count);
+ bpf_log(log, "%s\n", iters->pre_cond ? "pre-cond" : "post-cond");
+ }
+
+ err = bpf_live_stack_query_init(env, st);
+ if (err)
+ return err;
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ struct bpf_reg_state *reg;
+ u32 ra, r_scev, r_expr;
+ bool spill_base = false;
+
+ if (!scev_reg_alive(env, st, r))
+ continue;
+
+ r_scev = header_env->reg2scev[r];
+ reg = scev_regno_to_reg(env, cur_func, r);
+ /* If SCEV for r is (linear <reg> <slope>) */
+ if (is_simple_linear(scev, r_scev, &base_reg, &slope_imm) &&
+ is_widenable_reg_type(reg)) {
+ if (base_reg == r) {
+ /* Can't widen if the iteration range overflows */
+ if (!linear_bounds(reg, iters, slope_imm, &bounds))
+ goto cant_widen;
+ /* Spills at varying offsets lose precision */
+ if (test_bit(r, loop->store_base_regs)) {
+ spill_base = true;
+ goto cant_widen;
+ }
+ }
+ continue;
+ }
+
+ /* rA = rA, loop does not change this reg */
+ if (is_reg(scev, r_scev, &ra) && r == ra)
+ continue;
+
+ /* (any 1 (any 2 (any 3 4))) */
+ if (is_any_imm_reg(env, cur_func, header_env, r, r_scev))
+ continue;
+
+cant_widen:
+ if (log->level & BPF_LOG_LEVEL2) {
+ r_expr = header_env->reg2expr[r];
+ bpf_log(log, "loop header at %d, can't widen ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, ", expr is ");
+ log_expr(env, r_expr);
+ if (spill_base)
+ bpf_log(log, ", requires exact stack-offset tracking");
+ bpf_log(log, "\n");
+ }
+ return 0;
+ }
+
+ return 1;
+}
+
+static void scratch_scalar_id(struct bpf_reg_state *reg)
+{
+ if (reg->type == SCALAR_VALUE)
+ reg->id = 0;
+}
+
+/* The filtering pass has checked that every leaf can be unioned into acc. */
+static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
+ struct bpf_reg_state *acc, u32 id)
+{
+ struct bpf_reg_state *tmp = &env->fake_reg[0], *leaf_reg;
+ struct scev *scev = env->scev;
+ u32 l, r, leaf, order;
+ s64 imm;
+ int err;
+
+ scev->stack_sz = 0;
+ expr_stack_push(scev, id);
+ while (expr_next(scev, &id, &order)) {
+ if (order & DEPTH_LIMIT) {
+ verifier_bug(env, "scev ANY union exceeds expression depth limit");
+ return -EFAULT;
+ }
+ if (!(order & PRE) || is_any(scev, id, &l, &r))
+ continue;
+ if (is_imm(scev, id, &imm)) {
+ bpf_mark_reg_known_scalar(tmp, imm);
+ leaf_reg = tmp;
+ } else if (is_reg(scev, id, &leaf)) {
+ leaf_reg = scev_regno_to_reg(env, loop_entry, leaf);
+ } else {
+ verifier_bug(env, "scev ANY union has an unsupported leaf");
+ return -EFAULT;
+ }
+ err = bpf_reg_union(env, acc, leaf_reg);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
+int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+ struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *cur_func = st->frame[st->curframe];
+ struct bpf_func_state *entry_func = loop_entry->frame[loop_entry->curframe];
+ struct bpf_verifier_log *log = &env->log;
+ struct scev *scev = env->scev;
+ struct bpf_reg_state *reg;
+ struct env *header_env;
+ struct bounds bounds;
+ u32 r, base_reg, r_expr, a, b;
+ int insn_idx = st->insn_idx;
+ s64 slope_imm;
+ int err;
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ if (!scev_reg_alive(env, st, r))
+ continue;
+
+ r_expr = header_env->reg2scev[r];
+ /* If SCEV for r is (linear <reg> <slope>)*/
+ if (is_simple_linear(scev, r_expr, &base_reg, &slope_imm) &&
+ base_reg == r) {
+ reg = scev_regno_to_reg(env, cur_func, r);
+ /* Feasibility was checked in the filtering pass above. */
+ if (!linear_bounds(reg, iters, slope_imm, &bounds)) {
+ verifier_bug(env, "scev widen bounds overflow for r%d", r);
+ return -EFAULT;
+ }
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, widening ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ cnum64_smin(bounds.range), cnum64_smax(bounds.range),
+ bounds.step);
+ }
+ scratch_scalar_id(reg);
+ err = bpf_set_reg_range(env, reg, bounds.range, bounds.step);
+ if (err)
+ return err;
+ mark_scev_reg_scratched(env, r);
+ } else if (is_any(scev, r_expr, &a, &b)) {
+ reg = scev_regno_to_reg(env, cur_func, r);
+ err = union_any_reg(env, entry_func, reg, r_expr);
+ if (err)
+ return err;
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, widening ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ reg_smin(reg), reg_smax(reg), reg->step);
+ }
+ scratch_scalar_id(reg);
+ mark_scev_reg_scratched(env, r);
+ }
+ }
+ return 1;
+}
+
+int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,
+ struct bpf_verifier_state *entry_state, struct bpf_loop_iters *iters)
+{
+ struct bpf_func_state *entry_st = entry_state->frame[entry_state->curframe];
+ struct bpf_verifier_log *log = &env->log;
+ struct bpf_reg_state *reg, *entry_reg;
+ struct scev *scev = env->scev;
+ struct env *header_env;
+ struct bounds bounds;
+ u32 r, base_reg;
+ s64 slope_imm;
+ int err;
+
+ if (entry_state->curframe != cur_func_state->frameno) {
+ verifier_bug(env, "clamping registers for a wrong frame: %d vs %d\n",
+ entry_state->curframe, cur_func_state->frameno);
+ return -EFAULT;
+ }
+
+ header_env = find_header_env(scev, insn_idx);
+ for (r = 0; r < REGS_NUM; r++) {
+ /* If SCEV for r is (linear <reg> <slope>)*/
+ if (!is_simple_linear(scev, header_env->reg2scev[r], &base_reg, &slope_imm) ||
+ base_reg != r)
+ continue;
+
+ entry_reg = scev_regno_to_reg(env, entry_st, r);
+ reg = scev_regno_to_reg(env, cur_func_state, r);
+ if (entry_reg->type == NOT_INIT || reg->type == NOT_INIT)
+ continue;
+
+ if (!linear_bounds(entry_reg, iters, slope_imm, &bounds)) {
+ verifier_bug(env, "scev clamp bounds overflow for r%d", r);
+ return -EFAULT;
+ }
+ bounds.range = cnum64_intersect(reg->r64, bounds.range);
+ if (cnum64_is_empty(bounds.range)) {
+ verifier_bug(env, "scev clamp produced empty range for r%d", r);
+ return -EFAULT;
+ }
+ if (log->level & BPF_LOG_LEVEL2) {
+ bpf_log(log, "loop header at %d, clamping ", insn_idx);
+ log_reg(env, r);
+ bpf_log(log, " to %lld..%lld step %u\n",
+ cnum64_smin(bounds.range), cnum64_smax(bounds.range),
+ bounds.step);
+ }
+ scratch_scalar_id(reg);
+ err = bpf_set_reg_range(env, reg, bounds.range, bounds.step);
+ if (err)
+ return err;
+ mark_scev_reg_scratched(env, r);
+ }
+ return 0;
+}
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 18bf7b660c2f6..c1771a355e4e4 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -302,8 +302,30 @@ int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_s
static bool range_within(const struct bpf_reg_state *old,
const struct bpf_reg_state *cur)
{
- return cnum64_is_subset(old->r64, cur->r64) &&
- cnum32_is_subset(old->r32, cur->r32);
+ if (!cnum64_is_subset(old->r64, cur->r64) ||
+ !cnum32_is_subset(old->r32, cur->r32))
+ return false;
+
+ if (old->step <= 1)
+ return true;
+
+ if (cnum64_is_const(cur->r64))
+ return imod((s64)cnum64_smin(cur->r64), old->step) == old->base;
+
+ /*
+ * Both `old` and `cur` define some sets of points.
+ * Return true, if points defined by `cur` are a subset of points defined by `old`:
+ * - bounds for `cur` should be within bounds for `old`;
+ * - cur->step should be dividable by old->step;
+ * - cur->base should start at integer number of old->step
+ * steps from old->base.
+ *
+ * E.g. the following ranges are compatible:
+ * - old [0, 10] step 2
+ * - new [2, 10] step 4
+ */
+ return cur->step % old->step == 0 &&
+ (cur->base - old->base) % old->step == 0;
}
/* If in the old state two registers had the same id, then they need to have
@@ -610,6 +632,7 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
case PTR_TO_MEM:
case PTR_TO_BUF:
case PTR_TO_TP_BUFFER:
+ case PTR_TO_BTF_ID:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
*/
@@ -644,7 +667,12 @@ static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_STACK:
- return regs_exact(rold, rcur, idmap);
+ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
+ range_within(rold, rcur) &&
+ tnum_in(rold->var_off, rcur->var_off) &&
+ check_ids(rold->id, rcur->id, idmap) &&
+ check_ids(rold->parent_id, rcur->parent_id, idmap) &&
+ rold->frameno == rcur->frameno;
case PTR_TO_ARENA:
return true;
case PTR_TO_INSN:
@@ -914,6 +942,28 @@ static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *c
return true;
}
+static bool loop_stack_safe(struct bpf_verifier_env *env, struct bpf_func_state *old,
+ struct bpf_func_state *cur)
+{
+ struct loop_stack_entry *old_stack = old->loop_stack;
+ struct loop_stack_entry *cur_stack = cur->loop_stack;
+ u32 i;
+
+ if (old->loop_stack_cnt != cur->loop_stack_cnt)
+ return false;
+
+ for (i = 0; i < old->loop_stack_cnt; i++) {
+ if (old_stack[i].loop_id == cur_stack[i].loop_id &&
+ old_stack[i].iters.max_header_count == cur_stack[i].iters.max_header_count &&
+ old_stack[i].iters.pre_cond == cur_stack[i].iters.pre_cond &&
+ old_stack[i].terminates == cur_stack[i].terminates)
+ continue;
+ return false;
+ }
+
+ return true;
+}
+
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
@@ -964,6 +1014,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat
if (!stack_arg_safe(env, old, cur, &env->idmap_scratch, exact))
return false;
+ if (!loop_stack_safe(env, old, cur))
+ return false;
+
return true;
}
@@ -1010,6 +1063,7 @@ static bool states_equal(struct bpf_verifier_env *env,
if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
return false;
}
+
return true;
}
@@ -1240,16 +1294,82 @@ static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_
}
}
-int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
+int bpf_split_cur_state(struct bpf_verifier_env *env)
{
+ struct bpf_verifier_state *cur = env->cur_state, *new;
struct bpf_verifier_state_list *new_sl;
+ struct list_head *head;
+ int insn_idx = cur->insn_idx;
+ int err;
+
+ head = bpf_explored_state(env, insn_idx);
+ new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
+ if (!new_sl)
+ return -ENOMEM;
+ env->total_states++;
+ env->explored_states_size++;
+ update_peak_states(env);
+ env->prev_jmps_processed = env->jmps_processed;
+ env->prev_insn_processed = env->insn_processed;
+
+ /* forget precise markings we inherited, see __mark_chain_precision */
+ if (env->bpf_capable)
+ mark_all_scalars_imprecise(env, cur);
+
+ bpf_clear_singular_ids(env, cur);
+
+ /* add new state to the head of linked list */
+ new = &new_sl->state;
+ err = bpf_copy_verifier_state(new, cur);
+ if (err) {
+ bpf_free_verifier_state(new, false);
+ kfree(new_sl);
+ return err;
+ }
+ new->insn_idx = insn_idx;
+ verifier_bug_if(new->branches != 1, env,
+ "%s:branches_to_explore=%d insn %d",
+ __func__, new->branches, insn_idx);
+ err = maybe_enter_scc(env, new);
+ if (err) {
+ bpf_free_verifier_state(new, false);
+ kfree(new_sl);
+ return err;
+ }
+
+ cur->parent = new;
+ cur->last_insn_idx = -1;
+ cur->first_insn_idx = insn_idx;
+ cur->dfs_depth = new->dfs_depth + 1;
+ bpf_clear_jmp_history(cur);
+ list_add(&new_sl->node, head);
+ return 0;
+}
+
+/* Force a checkpoint upon reaching a loop header for a terminating loop. */
+static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)
+{
+ struct bpf_verifier_state *cur = env->cur_state;
+ struct bpf_func_state *frame = cur->frame[cur->curframe];
+ struct loop_stack_entry *top;
+
+ if (bpf_loop_at_index(env, insn_idx) != insn_idx || !frame->loop_stack_cnt)
+ return false;
+ top = &frame->loop_stack[frame->loop_stack_cnt - 1];
+ return top->loop_id == insn_idx && top->terminates;
+}
+
+int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
+{
struct bpf_verifier_state_list *sl;
- struct bpf_verifier_state *cur = env->cur_state, *new;
- bool force_new_state, add_new_state, loop;
+ struct bpf_verifier_state *cur = env->cur_state;
+ bool force_new_state, add_new_state, loop, loop_checkpoint;
int n, err, states_cnt = 0;
struct list_head *pos, *tmp, *head;
+ loop_checkpoint = need_loop_checkpoint(env, insn_idx);
force_new_state = env->test_state_freq || bpf_is_force_checkpoint(env, insn_idx) ||
+ loop_checkpoint ||
/* Avoid accumulating infinitely long jmp history */
cur->jmp_history_cnt > 40;
@@ -1280,10 +1400,11 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
continue;
if (sl->state.branches) {
- struct bpf_func_state *frame = sl->state.frame[0];
+ struct bpf_func_state *old_top_frame = sl->state.frame[0];
+ struct bpf_func_state *old_cur_frame = sl->state.frame[sl->state.curframe];
- if (frame->in_async_callback_fn &&
- frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
+ if (old_top_frame->in_async_callback_fn &&
+ old_top_frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) {
/* Different async_entry_cnt means that the verifier is
* processing another entry into async callback.
* Seeing the same state is not an indication of infinite
@@ -1382,6 +1503,20 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
}
goto skip_inf_loop_check;
}
+
+ /*
+ * If old state belongs to a control flow loop that we know terminates,
+ * it should be safe to prune current state.
+ */
+ if (old_cur_frame->loop_stack_cnt &&
+ old_cur_frame->loop_stack[old_cur_frame->loop_stack_cnt - 1].terminates) {
+ if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
+ loop = true;
+ goto hit;
+ }
+ goto skip_inf_loop_check;
+ }
+
/* attempt to detect infinite loop to avoid unnecessary doomed work */
if (states_maybe_looping(&sl->state, cur) &&
states_equal(env, &sl->state, cur, EXACT) &&
@@ -1540,7 +1675,8 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
* Use bigger 'n' for checkpoints because evicting checkpoint states
* too early would hinder iterator convergence.
*/
- n = bpf_is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
+ n = (bpf_is_force_checkpoint(env, insn_idx) || loop_checkpoint) &&
+ sl->state.branches > 0 ? 64 : 3;
if (sl->miss_cnt > sl->hit_cnt * n + n) {
/* the state is unlikely to be useful. Remove it to
* speed up verification
@@ -1572,44 +1708,5 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
* When looping the sl->state.branches will be > 0 and this state
* will not be considered for equivalence until branches == 0.
*/
- new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT);
- if (!new_sl)
- return -ENOMEM;
- env->total_states++;
- env->explored_states_size++;
- update_peak_states(env);
- env->prev_jmps_processed = env->jmps_processed;
- env->prev_insn_processed = env->insn_processed;
-
- /* forget precise markings we inherited, see __mark_chain_precision */
- if (env->bpf_capable)
- mark_all_scalars_imprecise(env, cur);
-
- bpf_clear_singular_ids(env, cur);
-
- /* add new state to the head of linked list */
- new = &new_sl->state;
- err = bpf_copy_verifier_state(new, cur);
- if (err) {
- bpf_free_verifier_state(new, false);
- kfree(new_sl);
- return err;
- }
- new->insn_idx = insn_idx;
- verifier_bug_if(new->branches != 1, env,
- "%s:branches_to_explore=%d insn %d",
- __func__, new->branches, insn_idx);
- err = maybe_enter_scc(env, new);
- if (err) {
- bpf_free_verifier_state(new, false);
- kfree(new_sl);
- return err;
- }
-
- cur->parent = new;
- cur->first_insn_idx = insn_idx;
- cur->dfs_depth = new->dfs_depth + 1;
- bpf_clear_jmp_history(cur);
- list_add(&new_sl->node, head);
- return 0;
+ return bpf_split_cur_state(env);
}
diff --git a/kernel/bpf/tnum.c b/kernel/bpf/tnum.c
index ec9c310cf5d7f..1f620facd1b7e 100644
--- a/kernel/bpf/tnum.c
+++ b/kernel/bpf/tnum.c
@@ -317,3 +317,14 @@ u64 tnum_step(struct tnum t, u64 z)
inc = (filled + 1) & t.mask;
return t.value | inc;
}
+
+/*
+ * Return the number of trailing bits known to be zero in a tnum.
+ * Return 64 for a tnum representing zero.
+ */
+u32 tnum_alignment(struct tnum a)
+{
+ u64 v = a.value | a.mask;
+
+ return v ? __ffs64(v) : 64;
+}
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 03dbc0e003986..327bfc00da5f5 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -5,6 +5,7 @@
*/
#include <uapi/linux/btf.h>
#include <linux/bpf-cgroup.h>
+#include <linux/count_zeros.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
@@ -30,6 +31,7 @@
#include <linux/module.h>
#include <linux/cpumask.h>
#include <linux/cnum.h>
+#include <linux/gcd.h>
#include <linux/bpf_mem_alloc.h>
#include <net/xdp.h>
#include <linux/trace_events.h>
@@ -1910,12 +1912,19 @@ static void bpf_diag_record_caller_saved(struct bpf_verifier_env *env,
}
}
+static void reg_step_reset(struct bpf_reg_state *reg)
+{
+ reg->base = 0;
+ reg->step = 1;
+}
+
/* This helper doesn't clear reg->id */
static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->var_off = tnum_const(imm);
reg->r64 = cnum64_from_urange(imm, imm);
reg->r32 = cnum32_from_urange((u32)imm, (u32)imm);
+ reg_step_reset(reg);
}
/* Mark the unknown part of a register (variable offset or scalar value) as
@@ -1932,6 +1941,12 @@ static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
___mark_reg_known(reg, imm);
}
+void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm)
+{
+ __mark_reg_known(reg, imm);
+ reg->type = SCALAR_VALUE;
+}
+
static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
{
reg->var_off = tnum_const_subreg(reg->var_off, imm);
@@ -2158,10 +2173,16 @@ static void deduce_bounds_64_from_32(struct bpf_reg_state *reg)
reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32);
}
+static void deduce_bounds_64_from_step(struct bpf_reg_state *reg)
+{
+ reg->r64 = cnum64_intersect_linear(reg->r64, reg->base, reg->step);
+}
+
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
deduce_bounds_32_from_64(reg);
deduce_bounds_64_from_32(reg);
+ deduce_bounds_64_from_step(reg);
}
/* Attempts to improve var_off based on unsigned min/max information */
@@ -2173,8 +2194,18 @@ static void __reg_bound_offset(struct bpf_reg_state *reg)
struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
tnum_range(reg_u32_min(reg),
reg_u32_max(reg)));
+ u32 trailing_zero_bits;
+ u16 base = reg->base;
+ u16 step = reg->step;
reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
+
+ if (base == 0)
+ trailing_zero_bits = count_trailing_zeros(step);
+ else
+ trailing_zero_bits = min(count_trailing_zeros(base),
+ count_trailing_zeros(step));
+ reg->var_off = tnum_and(reg->var_off, tnum_const(~0ULL << trailing_zero_bits));
}
static bool range_bounds_violation(struct bpf_reg_state *reg);
@@ -2250,6 +2281,7 @@ static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
if (env->test_reg_invariants)
return -EFAULT;
__mark_reg_unbounded(reg);
+ reg_step_reset(reg);
return 0;
}
@@ -2260,6 +2292,7 @@ void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
reg->type = SCALAR_VALUE;
reg->var_off = tnum_unknown;
__mark_reg_unbounded(reg);
+ reg_step_reset(reg);
}
/* Mark a register as having a completely unknown (scalar) value,
@@ -6339,6 +6372,7 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
const char *field_name = NULL;
enum bpf_type_flag flag = 0;
u32 btf_id = 0;
+ s64 min_off;
int ret;
if (!env->allow_ptr_leaks) {
@@ -6354,36 +6388,31 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
return -EINVAL;
}
- if (!tnum_is_const(reg->var_off)) {
- char tn_buf[48];
-
- tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
+ if (check_add_overflow(reg_smin(reg), off, &min_off)) {
verbose(env,
- "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
- reg_arg_name(env, argno), tname, off, tn_buf);
+ "%s is ptr_%s access, offset computation overflows: register's minimal offset is %lld, instruction offset is %d\n",
+ reg_arg_name(env, argno), tname, reg_smin(reg), off);
return -EACCES;
}
- off += reg->var_off.value;
-
- if (off < 0) {
+ if (min_off < 0) {
verbose(env,
- "%s is ptr_%s invalid negative access: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s invalid negative access: off=%lld\n",
+ reg_arg_name(env, argno), tname, min_off);
return -EACCES;
}
if (reg->type & MEM_USER) {
verbose(env,
- "%s is ptr_%s access user memory: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s access user memory\n",
+ reg_arg_name(env, argno), tname);
return -EACCES;
}
if (reg->type & MEM_PERCPU) {
verbose(env,
- "%s is ptr_%s access percpu memory: off=%d\n",
- reg_arg_name(env, argno), tname, off);
+ "%s is ptr_%s access percpu memory\n",
+ reg_arg_name(env, argno), tname);
return -EACCES;
}
@@ -6393,6 +6422,18 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
}
if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
+ if (!tnum_is_const(reg->var_off)) {
+ char tn_buf[48];
+
+ tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
+ verbose(env,
+ "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
+ reg_arg_name(env, argno), tname, off, tn_buf);
+ return -EACCES;
+ }
+
+ off += reg->var_off.value;
+
if (!btf_is_kernel(reg->btf)) {
verifier_bug(env, "reg->btf must be kernel btf");
return -EFAULT;
@@ -14046,6 +14087,46 @@ static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 of
return *kfunc.flags & KF_SPINLOCK_SAFE;
}
+/*
+ * True if insn calls a helper/kfunc that requires one of its arguments to
+ * be a stack pointer with a constant offset.
+ */
+bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx)
+{
+ const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
+ u32 *flags, btf_id;
+
+ if (bpf_helper_call(insn)) {
+ return insn->imm == BPF_FUNC_dynptr_from_mem ||
+ insn->imm == BPF_FUNC_ringbuf_reserve_dynptr;
+ }
+
+ /* vmlinux kfuncs only */
+ if (!bpf_pseudo_kfunc_call(insn) || insn->off != 0)
+ return false;
+ btf_id = insn->imm;
+
+ flags = btf_kfunc_flags(btf_vmlinux, btf_id, env->prog);
+ if (flags && (*flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)))
+ return true;
+
+ if (btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
+ btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore] ||
+ btf_id == special_kfunc_list[KF_bpf_local_irq_save] ||
+ btf_id == special_kfunc_list[KF_bpf_local_irq_restore])
+ return true;
+
+ if (btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_xdp] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta] ||
+ btf_id == special_kfunc_list[KF_bpf_dynptr_from_file])
+ return true;
+
+ return false;
+}
+
static bool is_sync_callback_calling_kfunc(u32 btf_id)
{
return is_bpf_rbtree_add_kfunc(btf_id);
@@ -15582,6 +15663,50 @@ static int sanitize_check_bounds(struct bpf_verifier_env *env,
return 0;
}
+static void scalar_step_add(struct bpf_reg_state *dst_reg,
+ const struct bpf_reg_state *a,
+ const struct bpf_reg_state *b)
+{
+ u16 base, step;
+
+ /* If either 'a' or 'b' is a constant, update the base/step for the counterpart. */
+ if (tnum_is_const(b->var_off)) {
+ step = a->step;
+ base = imod((s64)a->base + (s64)b->var_off.value, step);
+ } else if (tnum_is_const(a->var_off)) {
+ step = b->step;
+ base = imod((s64)b->base + (s64)a->var_off.value, step);
+ } else {
+ step = 1;
+ base = 0;
+ }
+ dst_reg->base = base;
+ dst_reg->step = step;
+}
+
+static void scalar_step_mul(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+{
+ u64 amount = src_reg->var_off.value;
+
+ if (tnum_is_const(src_reg->var_off) && (s64)amount >= 0 &&
+ !check_mul_overflow(dst_reg->step, amount, &dst_reg->step) &&
+ dst_reg->step != 0)
+ dst_reg->base = (dst_reg->base * amount) % dst_reg->step;
+ else
+ reg_step_reset(dst_reg);
+}
+
+static void scalar_step_lsh(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg)
+{
+ u64 amount = src_reg->var_off.value;
+
+ if (tnum_is_const(src_reg->var_off) && amount < 64 &&
+ !check_mul_overflow(dst_reg->step, 1ull << amount, &dst_reg->step))
+ dst_reg->base = (dst_reg->base * (1ull << amount)) % dst_reg->step;
+ else
+ reg_step_reset(dst_reg);
+}
+
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
@@ -15739,6 +15864,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
+ scalar_step_add(dst_reg, ptr_reg, off_reg);
dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64);
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->raw = ptr_reg->raw;
@@ -15800,6 +15926,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
if ((!known && smin_val < 0) || dst_reg->range < 0)
memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
}
+ reg_step_reset(dst_reg);
break;
case BPF_AND:
case BPF_OR:
@@ -16499,6 +16626,7 @@ static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *ins
* Bounds will be re-derived from the new tnum later.
*/
__mark_reg_unbounded(dst_reg);
+ reg_step_reset(dst_reg);
}
/* For bswap16/32, truncate dst register to match the swapped size */
if (insn->imm == 16 || insn->imm == 32)
@@ -16625,6 +16753,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
*/
switch (opcode) {
case BPF_ADD:
+ scalar_step_add(dst_reg, dst_reg, &src_reg);
scalar32_min_max_add(dst_reg, &src_reg);
scalar_min_max_add(dst_reg, &src_reg);
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
@@ -16633,6 +16762,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar32_min_max_sub(dst_reg, &src_reg);
scalar_min_max_sub(dst_reg, &src_reg);
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
+ reg_step_reset(dst_reg);
break;
case BPF_NEG:
env->fake_reg[0] = *dst_reg;
@@ -16640,11 +16770,13 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
+ reg_step_reset(dst_reg);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_mul(dst_reg, &src_reg);
scalar_min_max_mul(dst_reg, &src_reg);
+ scalar_step_mul(dst_reg, &src_reg);
break;
case BPF_DIV:
/* BPF div specification: x / 0 = 0 */
@@ -16662,6 +16794,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar_min_max_sdiv(dst_reg, &src_reg);
else
scalar_min_max_udiv(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_MOD:
/* BPF mod specification: x % 0 = x */
@@ -16677,6 +16810,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
scalar_min_max_smod(dst_reg, &src_reg);
else
scalar_min_max_umod(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_AND:
if (tnum_is_const(src_reg.var_off)) {
@@ -16687,6 +16821,7 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_and(dst_reg, &src_reg);
scalar_min_max_and(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_OR:
if (tnum_is_const(src_reg.var_off)) {
@@ -16697,32 +16832,38 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_or(dst_reg, &src_reg);
scalar_min_max_or(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_XOR:
dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
scalar32_min_max_xor(dst_reg, &src_reg);
scalar_min_max_xor(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_LSH:
if (alu32)
scalar32_min_max_lsh(dst_reg, &src_reg);
else
scalar_min_max_lsh(dst_reg, &src_reg);
+ scalar_step_lsh(dst_reg, &src_reg);
break;
case BPF_RSH:
if (alu32)
scalar32_min_max_rsh(dst_reg, &src_reg);
else
scalar_min_max_rsh(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_ARSH:
if (alu32)
scalar32_min_max_arsh(dst_reg, &src_reg);
else
scalar_min_max_arsh(dst_reg, &src_reg);
+ reg_step_reset(dst_reg);
break;
case BPF_END:
scalar_byte_swap(dst_reg, insn);
+ reg_step_reset(dst_reg);
break;
default:
break;
@@ -16934,6 +17075,45 @@ static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
return 0;
}
+int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
+ struct cnum64 range, u16 step)
+{
+ reg->r64 = range;
+ reg->r32 = CNUM32_UNBOUNDED;
+ reg->step = step;
+ reg->base = imod(cnum64_smin(range), step);
+ reg->var_off = tnum_unknown;
+ reg_bounds_sync(reg); /* this should infer the tnum alignment */
+ return reg_bounds_sanity_check(env, reg, "bpf_set_reg_range");
+}
+
+/* acc := acc U src, matching types only. Caller must clear acc's scalar ID. */
+int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
+ const struct bpf_reg_state *src)
+{
+ u16 base, step;
+
+ if (acc->type != src->type) {
+ verifier_bug(env, "union of registers with different types");
+ return -EFAULT;
+ }
+ acc->r64 = cnum64_union(acc->r64, src->r64);
+ acc->r32 = cnum32_union(acc->r32, src->r32);
+ acc->var_off = tnum_union(acc->var_off, src->var_off);
+
+ /* Retain a common congruence if the bases agree modulo the gcd. */
+ step = gcd(acc->step, src->step);
+ base = acc->base % step;
+ if (base != src->base % step) {
+ reg_step_reset(acc);
+ } else {
+ acc->base = base;
+ acc->step = step;
+ }
+ reg_bounds_sync(acc);
+ return reg_bounds_sanity_check(env, acc, "bpf_reg_union");
+}
+
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
@@ -17203,8 +17383,6 @@ static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
u8 opcode, bool is_jmp32);
-static u8 rev_opcode(u8 opcode);
-
/*
* Learn more information about live branches by simulating refinement on both branches.
* regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means
@@ -17213,7 +17391,7 @@ static u8 rev_opcode(u8 opcode);
static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32)
{
/* Fallthrough (FALSE) branch */
- regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32);
+ regs_refine_cond_op(&env->false_reg1, &env->false_reg2, bpf_rev_opcode(opcode), is_jmp32);
reg_bounds_sync(&env->false_reg1);
reg_bounds_sync(&env->false_reg2);
/*
@@ -17399,7 +17577,7 @@ static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_s
return simulate_both_branches_taken(env, opcode, is_jmp32);
}
-static int flip_opcode(u32 opcode)
+int bpf_flip_opcode(u32 opcode)
{
/* How can we transform "a <op> b" into "b <op> a"? */
static const u8 opcode_flip[16] = {
@@ -17430,7 +17608,7 @@ static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
pkt = dst_reg;
} else if (dst_reg->type == PTR_TO_PACKET_END) {
pkt = src_reg;
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
} else {
return -1;
}
@@ -17485,7 +17663,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r
/* arrange that reg2 is a scalar, and reg1 is a pointer */
if (!is_reg_const(reg2, is_jmp32)) {
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
swap(reg1, reg2);
}
/* and ensure that reg2 is a constant */
@@ -17519,7 +17697,7 @@ static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *r
/* Opcode that corresponds to a *false* branch condition.
* E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
*/
-static u8 rev_opcode(u8 opcode)
+u8 bpf_rev_opcode(u8 opcode)
{
switch (opcode) {
case BPF_JEQ: return BPF_JNE;
@@ -17554,7 +17732,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state
case BPF_JGT:
case BPF_JSGE:
case BPF_JSGT:
- opcode = flip_opcode(opcode);
+ opcode = bpf_flip_opcode(opcode);
swap(reg1, reg2);
break;
default:
@@ -17631,6 +17809,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state
* violations if we're on a dead branch.
*/
__mark_reg_unbounded(reg1);
+ reg_step_reset(reg1);
if (is_jmp32) {
t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
reg1->var_off = tnum_with_subreg(reg1->var_off, t);
@@ -19465,6 +19644,204 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
return -EFAULT;
}
+static bool has_entered_loop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+
+ return aux[insn_idx].loop_entry &&
+ (prev_insn_idx == -1 ||
+ bpf_loop_at_index(env, prev_insn_idx) != bpf_loop_at_index(env, insn_idx));
+}
+
+static bool is_next_loop_iteration(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+
+ return aux[insn_idx].loop_entry &&
+ (prev_insn_idx != -1 &&
+ bpf_loop_at_index(env, prev_insn_idx) == bpf_loop_at_index(env, insn_idx));
+}
+
+static bool has_exited_loop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ int prev_insn_idx = env->prev_insn_idx;
+ int insn_idx = env->insn_idx;
+ int prev_loop_idx, h;
+
+ if (prev_insn_idx == -1)
+ return false;
+
+ prev_loop_idx = bpf_loop_at_index(env, prev_insn_idx);
+ if (prev_loop_idx < 0)
+ return false;
+
+ /* Still inside the previous instruction's loop if that loop encloses insn_idx */
+ for (h = bpf_loop_at_index(env, insn_idx); h >= 0; h = aux[h].loop_header)
+ if (h == prev_loop_idx)
+ return false;
+
+ return true;
+}
+
+/*
+ * Push the loop entered at insn_idx onto the stack. Usually this adds a single
+ * entry on top of its enclosing loop. However, an edge may enter an inner loop
+ * directly, bypassing the header(s) of its enclosing loop(s), e.g.:
+ *
+ * 1: for (...): // enclosing loop, header at 1
+ * 2: for (...): // inner loop, header at 2
+ * ...
+ * 3: if ...:
+ * goto 2b; // enters loop 2 without going through header 1
+ *
+ * Such a bypass makes the enclosing loop irreducible, so its header is missing
+ * from the stack and both headers (1) and (2) need to be pushed onto stack.
+ * Only the innermost loop (the one actually entered at insn_idx) carries SCEV bounds;
+ * the bypassed ancestors are irreducible and pushed as non-terminating.
+ *
+ * Assumes loop_stack_pop() has already truncated the stack to the common ancestor
+ * of the bpf_loop_at_index(env->prev_insn_idx) and bpf_loop_at_index(env->insn_idx).
+ */
+static int loop_stack_push(struct bpf_verifier_env *env,
+ struct bpf_verifier_state *entry_state,
+ bool terminates,
+ struct bpf_loop_iters *iters)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_func_state *frame = cur_func(env);
+ struct loop_stack_entry *loop_stack = frame->loop_stack;
+ u32 missing_headers[LOOP_STACK_SIZE];
+ u32 cnt = frame->loop_stack_cnt;
+ u32 num_missing = 0;
+ int h;
+
+ for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header, num_missing++) {
+ if (cnt && loop_stack[cnt - 1].loop_id == h)
+ break;
+ if (num_missing == LOOP_STACK_SIZE)
+ goto e2big;
+ missing_headers[num_missing] = h;
+ }
+
+ for (; num_missing; num_missing--, cnt++) {
+ if (cnt == LOOP_STACK_SIZE)
+ goto e2big;
+ loop_stack[cnt].loop_id = missing_headers[num_missing - 1];
+ if (num_missing == 1) {
+ loop_stack[cnt].iters = terminates ? *iters : (struct bpf_loop_iters){};
+ loop_stack[cnt].terminates = terminates;
+ loop_stack[cnt].entry_state = entry_state;
+ } else {
+ loop_stack[cnt].iters = (struct bpf_loop_iters){};
+ loop_stack[cnt].terminates = false;
+ loop_stack[cnt].entry_state = NULL;
+ }
+ }
+ frame->loop_stack_cnt = cnt;
+ return 0;
+
+e2big:
+ verbose(env, "Too many nested loops (%d/%d) at %d\n", cnt, num_missing, env->insn_idx);
+ return -E2BIG;
+}
+
+/*
+ * An exit from a loop can cross several nested loops, e.g.:
+ *
+ * 1: for (...):
+ * 2: for (...):
+ * 3: for (...):
+ * if ...: // before goto the loop stack is [1, 2, 3 <top>]
+ * goto 1b; // after goto it should become [1]
+ */
+static int loop_stack_pop(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *aux = env->insn_aux_data;
+ struct bpf_func_state *frame = cur_func(env);
+ int h, i;
+
+ /*
+ * Walk the loop nest of insn_idx outwards (innermost first) and stop at
+ * the first loop that is present on the stack - that loop is the common
+ * ancestor and becomes the new top. If no enclosing loop is on the
+ * stack, drop all loops.
+ */
+ for (h = bpf_loop_at_index(env, env->insn_idx); h >= 0; h = aux[h].loop_header) {
+ for (i = frame->loop_stack_cnt - 1; i >= 0; i--) {
+ if (frame->loop_stack[i].loop_id == h) {
+ frame->loop_stack_cnt = i + 1;
+ return 0;
+ }
+ }
+ }
+
+ frame->loop_stack_cnt = 0;
+ return 0;
+}
+
+static int maybe_clamp_scev_regs(struct bpf_verifier_env *env)
+{
+ struct bpf_func_state *frame = cur_func(env);
+ struct loop_stack_entry *entry;
+
+ if (frame->loop_stack_cnt == 0) {
+ verifier_bug(env, "%s: loop stack empty at %d", __FUNCTION__, env->insn_idx);
+ return -EFAULT;
+ }
+
+ entry = &frame->loop_stack[frame->loop_stack_cnt - 1];
+ if (!entry->terminates)
+ return 0;
+
+ return bpf_clamp_scev_regs(env, frame, env->insn_idx, entry->entry_state, &entry->iters);
+}
+
+static int handle_loop_entry_exit(struct bpf_verifier_env *env)
+{
+ struct bpf_verifier_state *cur = env->cur_state;
+ struct bpf_loop_iters iters;
+ bool terminates;
+ int err;
+
+ if (is_next_loop_iteration(env)) {
+ err = maybe_clamp_scev_regs(env);
+ if (err)
+ return err;
+ }
+ if (has_exited_loop(env)) {
+ if (env->log.level & BPF_LOG_LEVEL2)
+ verbose(env, "exiting loop %d\n", bpf_loop_at_index(env, env->prev_insn_idx));
+ err = loop_stack_pop(env);
+ if (err)
+ return err;
+ }
+ if (has_entered_loop(env)) {
+ if (env->log.level & BPF_LOG_LEVEL2)
+ verbose(env, "entering loop %d\n", bpf_loop_at_index(env, env->insn_idx));
+ err = bpf_compute_loop_iters(env, env->cur_state, &iters);
+ if (err < 0)
+ return err;
+ terminates = err == 1;
+ if (terminates) {
+ err = bpf_split_cur_state(env);
+ if (err)
+ return err;
+ err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
+ if (err < 0)
+ return err;
+ }
+ err = loop_stack_push(env, env->cur_state->parent, terminates, &iters);
+ if (err)
+ return err;
+ }
+ return 0;
+}
+
static int do_check(struct bpf_verifier_env *env)
{
bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
@@ -19479,6 +19856,12 @@ static int do_check(struct bpf_verifier_env *env)
struct bpf_insn_aux_data *insn_aux;
int err;
+ if (signal_pending(current))
+ return -EAGAIN;
+
+ if (need_resched())
+ cond_resched();
+
/* reset current history entry on each new instruction */
env->cur_hist_ent = NULL;
@@ -19525,6 +19908,15 @@ static int do_check(struct bpf_verifier_env *env)
}
}
+ /*
+ * Possibly widen the registers before creating a checkpoint
+ * in bpf_is_state_visited(). The next loop iteration will
+ * have a chance to hit this checkpoint and converge.
+ */
+ err = handle_loop_entry_exit(env);
+ if (err)
+ return err;
+
if (bpf_is_prune_point(env, env->insn_idx)) {
err = bpf_is_state_visited(env, env->insn_idx);
if (err < 0)
@@ -19550,12 +19942,6 @@ static int do_check(struct bpf_verifier_env *env)
return err;
}
- if (signal_pending(current))
- return -EAGAIN;
-
- if (need_resched())
- cond_resched();
-
if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
verbose(env, "\nfrom %d to %d%s:",
env->prev_insn_idx, env->insn_idx,
@@ -19565,6 +19951,13 @@ static int do_check(struct bpf_verifier_env *env)
do_print_state = false;
}
+ if (bpf_loop_at_index(env, env->insn_idx) >= 0 &&
+ cur_func(env)->loop_stack_cnt == 0) {
+ verifier_bug(env, "loop stack empty at %d, while inside the loop %d\n",
+ env->insn_idx, bpf_loop_at_index(env, env->insn_idx));
+ return -EFAULT;
+ }
+
if (env->log.level & BPF_LOG_LEVEL) {
if (verifier_state_scratched(env))
print_insn_state(env, state, state->curframe);
@@ -22441,6 +22834,45 @@ static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog)
return false;
}
+/* Various log level 2 information about the program */
+static void log_program(struct bpf_verifier_env *env)
+{
+ struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
+ struct bpf_insn *insns = env->prog->insnsi;
+ u32 insn_cnt = env->prog->len;
+ u64 pos, insn_pos;
+ u32 i, j;
+
+ verbose(env, "Program dump (scc? loop_header? idom insn#: live_regs_before):\n");
+ for (i = 0; i < insn_cnt; ++i) {
+ verbose_linfo(env, i, " ; ");
+ if (env->insn_aux_data[i].scc)
+ verbose(env, "%3d ", env->insn_aux_data[i].scc);
+ else
+ verbose(env, " ");
+ if (env->insn_aux_data[i].loop_header >= 0)
+ verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
+ else
+ verbose(env, " ");
+ verbose(env, "%3d ", env->idoms[i]);
+ verbose(env, "%3d: ", i);
+ for (j = BPF_REG_0; j < BPF_REG_10; ++j)
+ if (insn_aux[i].live_regs_before & BIT(j))
+ verbose(env, "%d", j);
+ else
+ verbose(env, ".");
+ verbose(env, " ");
+ pos = env->log.end_pos;
+ bpf_verbose_insn(env, &insns[i]);
+ insn_pos = env->log.end_pos;
+ if (insn_aux[i].zext_dst)
+ verbose(env, "%*c; zext", bpf_vlog_alignment(insn_pos - pos), ' ');
+ verbose(env, "\n");
+ if (bpf_is_ldimm64(&insns[i]))
+ i++;
+ }
+}
+
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
struct bpf_log_attr *attr_log)
{
@@ -22642,10 +23074,29 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
if (ret < 0)
goto skip_full_check;
+ ret = bpf_compute_idoms(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ ret = bpf_compute_loops(env);
+ if (ret < 0)
+ goto skip_full_check;
+
ret = bpf_compute_live_registers(env);
if (ret < 0)
goto skip_full_check;
+ if (env->log.level & BPF_LOG_LEVEL2)
+ log_program(env);
+
+ ret = bpf_init_scev(env);
+ if (ret < 0)
+ goto skip_full_check;
+
+ ret = bpf_compute_scev(env);
+ if (ret < 0)
+ goto skip_full_check;
+
ret = mark_fastcall_patterns(env);
if (ret < 0)
goto skip_full_check;
@@ -22791,9 +23242,13 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
release_btfs(env);
err_free_env:
bpf_free_subprog_jts(env);
+ if (env->insn_aux_data)
+ bpf_clear_insn_aux_data(env, 0, env->insn_aux_data_len);
vfree(env->insn_aux_data);
kvfree(env->fd_array);
+ bpf_free_scev(env);
bpf_stack_liveness_free(env);
+ kvfree(env->cfg.postorder_nums);
kvfree(env->cfg.insn_postorder);
kvfree(env->scc_info);
kvfree(env->succ);
@@ -22801,6 +23256,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
kvfree(env->callx_edges);
kvfree(env->func_ptrs);
bpf_diag_free(env);
+ kvfree(env->idoms);
kvfree(env);
return ret;
}
diff --git a/tools/testing/selftests/bpf/prog_tests/verifier.c b/tools/testing/selftests/bpf/prog_tests/verifier.c
index 8a6d341b754ac..2bc1ef910c16d 100644
--- a/tools/testing/selftests/bpf/prog_tests/verifier.c
+++ b/tools/testing/selftests/bpf/prog_tests/verifier.c
@@ -19,12 +19,14 @@
#include "verifier_basic_stack.skel.h"
#include "verifier_bitfield_write.skel.h"
#include "verifier_bounds.skel.h"
+#include "verifier_bounds_step.skel.h"
#include "verifier_bounds_deduction.skel.h"
#include "verifier_bounds_deduction_non_const.skel.h"
#include "verifier_bounds_mix_sign_unsign.skel.h"
#include "verifier_bpf_get_stack.skel.h"
#include "verifier_bpf_trap.skel.h"
#include "verifier_bswap.skel.h"
+#include "verifier_btf_array_access.skel.h"
#include "verifier_btf_ctx_access.skel.h"
#include "verifier_btf_flex_array.skel.h"
#include "verifier_btf_unreliable_prog.skel.h"
@@ -55,6 +57,7 @@
#include "verifier_helper_packet_access.skel.h"
#include "verifier_helper_restricted.skel.h"
#include "verifier_helper_value_access.skel.h"
+#include "verifier_idoms.skel.h"
#include "verifier_int_ptr.skel.h"
#include "verifier_iterating_callbacks.skel.h"
#include "verifier_jeq_infer_not_null.skel.h"
@@ -71,6 +74,7 @@
#include "verifier_live_stack.skel.h"
#include "verifier_liveness_exp.skel.h"
#include "verifier_load_acquire.skel.h"
+#include "verifier_loop_hierarchy.skel.h"
#include "verifier_loops1.skel.h"
#include "verifier_lwt.skel.h"
#include "verifier_map_in_map.skel.h"
@@ -103,6 +107,7 @@
#include "verifier_ringbuf.skel.h"
#include "verifier_runtime_jit.skel.h"
#include "verifier_scalar_ids.skel.h"
+#include "verifier_scev.skel.h"
#include "verifier_sdiv.skel.h"
#include "verifier_search_pruning.skel.h"
#include "verifier_sock.skel.h"
@@ -203,12 +208,14 @@ void test_verifier_arena_globals2(void) { RUN(verifier_arena_globals2); }
void test_verifier_basic_stack(void) { RUN(verifier_basic_stack); }
void test_verifier_bitfield_write(void) { RUN(verifier_bitfield_write); }
void test_verifier_bounds(void) { RUN(verifier_bounds); }
+void test_verifier_bounds_step(void) { RUN(verifier_bounds_step); }
void test_verifier_bounds_deduction(void) { RUN(verifier_bounds_deduction); }
void test_verifier_bounds_deduction_non_const(void) { RUN(verifier_bounds_deduction_non_const); }
void test_verifier_bounds_mix_sign_unsign(void) { RUN(verifier_bounds_mix_sign_unsign); }
void test_verifier_bpf_get_stack(void) { RUN(verifier_bpf_get_stack); }
void test_verifier_bpf_trap(void) { RUN(verifier_bpf_trap); }
void test_verifier_bswap(void) { RUN(verifier_bswap); }
+void test_verifier_btf_array_access(void) { RUN(verifier_btf_array_access); }
void test_verifier_btf_ctx_access(void) { RUN(verifier_btf_ctx_access); }
void test_verifier_btf_flex_array(void) { RUN(verifier_btf_flex_array); }
void test_verifier_btf_unreliable_prog(void) { RUN(verifier_btf_unreliable_prog); }
@@ -239,6 +246,7 @@ void test_verifier_helper_access_var_len(void) { RUN(verifier_helper_access_var_
void test_verifier_helper_packet_access(void) { RUN(verifier_helper_packet_access); }
void test_verifier_helper_restricted(void) { RUN(verifier_helper_restricted); }
void test_verifier_helper_value_access(void) { RUN(verifier_helper_value_access); }
+void test_verifier_idoms(void) { RUN(verifier_idoms); }
void test_verifier_int_ptr(void) { RUN(verifier_int_ptr); }
void test_verifier_iterating_callbacks(void) { RUN(verifier_iterating_callbacks); }
void test_verifier_jeq_infer_not_null(void) { RUN(verifier_jeq_infer_not_null); }
@@ -255,6 +263,7 @@ void test_verifier_leak_ptr(void) { RUN(verifier_leak_ptr); }
void test_verifier_linked_scalars(void) { RUN(verifier_linked_scalars); }
void test_verifier_live_stack(void) { RUN(verifier_live_stack); }
void test_verifier_liveness_exp(void) { RUN(verifier_liveness_exp); }
+void test_verifier_loop_hierarchy(void) { RUN(verifier_loop_hierarchy); }
void test_verifier_loops1(void) { RUN(verifier_loops1); }
void test_verifier_lwt(void) { RUN(verifier_lwt); }
void test_verifier_map_in_map(void) { RUN(verifier_map_in_map); }
@@ -286,6 +295,7 @@ void test_verifier_regalloc(void) { RUN(verifier_regalloc); }
void test_verifier_ringbuf(void) { RUN(verifier_ringbuf); }
void test_verifier_runtime_jit(void) { RUN(verifier_runtime_jit); }
void test_verifier_scalar_ids(void) { RUN(verifier_scalar_ids); }
+void test_verifier_scev(void) { RUN(verifier_scev); }
void test_verifier_sdiv(void) { RUN(verifier_sdiv); }
void test_verifier_search_pruning(void) { RUN(verifier_search_pruning); }
void test_verifier_sock(void) { RUN(verifier_sock); }
diff --git a/tools/testing/selftests/bpf/progs/bpf_misc.h b/tools/testing/selftests/bpf/progs/bpf_misc.h
index f3dbc3b59bff2..d7f706c3bc4af 100644
--- a/tools/testing/selftests/bpf/progs/bpf_misc.h
+++ b/tools/testing/selftests/bpf/progs/bpf_misc.h
@@ -43,6 +43,10 @@
* __msg_unpriv Same as __msg but for unprivileged mode.
* __not_msg_unpriv Same as __not_msg but for unprivileged mode.
*
+ * __msg_next Same as __msg but expects the match to be on the next
+ * __msg_next_unpriv log line compared to the last match, not just some line
+ * after the last match.
+ *
* __stderr Message expected to be found in bpf stderr stream. The
* same regex rules apply like __msg.
* __stderr_unpriv Same as __stderr but for unpriveleged mode.
@@ -145,6 +149,7 @@
#define __msg(msg) __test_tag("test_expect_msg=" msg)
#define __not_msg(msg) __test_tag("test_expect_not_msg=" msg)
+#define __msg_next(msg) __test_tag("test_expect_msg_next=" msg)
#define __xlated(msg) __test_tag("test_expect_xlated=" msg)
#define __jited(msg) __test_tag("test_jited=" msg)
#define __failure __test_tag("test_expect_failure")
@@ -153,6 +158,7 @@
#define __skip(reason) __test_tag("test_skip=" reason)
#define __msg_unpriv(msg) __test_tag("test_expect_msg_unpriv=" msg)
#define __not_msg_unpriv(msg) __test_tag("test_expect_not_msg_unpriv=" msg)
+#define __msg_next_unpriv(msg) __test_tag("test_expect_msg_next_unpriv=" msg)
#define __xlated_unpriv(msg) __test_tag("test_expect_xlated_unpriv=" msg)
#define __jited_unpriv(msg) __test_tag("test_jited_unpriv=" msg)
#define __failure_unpriv __test_tag("test_expect_failure_unpriv")
diff --git a/tools/testing/selftests/bpf/progs/verifier_bounds_step.c b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
new file mode 100644
index 0000000000000..cb55fc216bc8a
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_bounds_step.c
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+/*
+ * Tests for the linear "base + step * k" description tracked per scalar
+ * register.
+ *
+ * The base/step computed by scalar arithmetic is observed directly in the
+ * level-2 register dump, printed as "step=<base>+<step>" when the register is
+ * not the trivial base=0, step=1. Range inference that depends on the line
+ * (e.g. a sign-crossing range with a non-power-of-2 step) is checked via the
+ * resulting smin/smax, which feed ordinary signed branch decisions.
+ *
+ * Note: eq/neq branch checks do not consult base/step, so impossible-value
+ * pruning is intentionally not relied upon here; the register dump is the
+ * reliable signal.
+ */
+
+/* a &= 0xff; a *= 3 => multiples of 3, step=0+3 (not representable as tnum) */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 *= 3 {{.*}}step=0+3)")
+__naked void step_mul_non_pow2(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 *= 3; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* a &= 0xff; a <<= 2 => step=0+4 */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 <<= 2 {{.*}}step=0+4)")
+__naked void step_lsh(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 <<= 2; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* a &= 0xff; a *= 4; a += 1 => base shifts to 1, step=1+4 */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 += 1 {{.*}}step=1+4)")
+__naked void step_add_const_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 0xff; \
+ r0 *= 4; \
+ r0 += 1; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Sign-crossing range with a non-power-of-2 step. After "*= 3; += -3" the value
+ * set is {-3, 0, 3, 6}. The line description is tracked in signed space, so the
+ * intersection keeps smax=6. A u64-modular intersection would mis-place the
+ * line for the negative values and wrongly narrow smax to 4.
+ */
+SEC("socket")
+__success __log_level(2)
+__msg("r0 += -3 {{.*}}smax=smax32=6)")
+__naked void step_neg_value_range(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r0 *= 3; \
+ r0 += -3; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Same {-3, 0, 3, 6} value set: 6 is reachable, so "if r0 s> 4" can be taken
+ * and the illegal scalar dereference behind it must be rejected. Guards against
+ * the unsound narrowing (smax=4) that would prune the branch and accept the
+ * program. This rides on the signed comparison, which uses smin/smax.
+ */
+SEC("socket")
+__failure __msg("invalid mem access 'scalar'")
+__naked void step_neg_value_sound(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r0 *= 3; \
+ r0 += -3; \
+ if r0 s> 4 goto l_bad_%=; \
+ r0 = 0; \
+ exit; \
+l_bad_%=: \
+ r1 = *(u8 *)(r0 + 0); \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+struct step_val {
+ __u8 data[1024];
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_ARRAY);
+ __uint(max_entries, 1);
+ __type(key, __u32);
+ __type(value, struct step_val);
+} step_map SEC(".maps");
+
+/* Old register [4..130, step 2] should prune cur register [8..64, step 4]. */
+SEC("socket")
+__success __log_level(2)
+__msg("7: (27) r6 *= 4 ; R6=scalar({{.*}}umin32=8,{{.*}}umax32=68,{{.*}},step=0+4)")
+__msg("10: (27) r7 *= 2 ; R7=scalar({{.*}}umin32=4,{{.*}}umax32=130,{{.*}},step=0+2)")
+__msg("11: (25) if r0 > 0x2a goto pc+1")
+__msg("from 11 to 13: safe")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void step_prune_hit_multiple(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r6 &= 0x0f; \
+ r6 += 2; \
+ r6 *= 4; \
+ r7 &= 0x3f; \
+ r7 += 2; \
+ r7 *= 2; \
+ if r0 > 42 goto 1f; /* can't predict */ \
+ r6 = r7; /* step=2 explored first, step=4 explored next */ \
+1: r0 = r10; \
+ r6 = -r6; \
+ r0 += r6; \
+ *(u8 *)(r0 + 0) = 7; /* force r6 precise */ \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+/* Old register [0..126, step 2] should not prune cur register [0..45, step 3]. */
+SEC("socket")
+__failure __log_level(2)
+__msg("6: (27) r6 *= 3 ; R6=scalar({{.*}}smin32=0,{{.*}}umax32=45,{{.*}},step=0+3)")
+__msg("8: (27) r7 *= 2 ; R7=scalar({{.*}}smin32=0,{{.*}}umax32=126,{{.*}},step=0+2)")
+__msg("9: (25) if r0 > 0x2a goto pc+1")
+__msg("11: (15) if r6 == 0x3 goto pc+2")
+__msg("11: R6=scalar({{.*}},step=0+2)")
+__msg("13: (95) exit")
+__msg("from 9 to 11: {{.*}} R6=scalar({{.*}},step=0+3)")
+__msg("from 11 to 14")
+__msg("div by zero")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void step_prune_miss_non_multiple(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ call %[bpf_get_prandom_u32]; \
+ r6 &= 0x0f; \
+ r6 *= 3; \
+ r7 &= 0x3f; \
+ r7 *= 2; \
+ if r0 > 42 goto 1f; /* can't predict */ \
+ r6 = r7; /* step=2 explored first, step=3 explored next */ \
+1: \
+ if r6 == 3 goto 2f; /* false if step=2, should not prune step=3 */ \
+ r0 = 0; \
+ exit; \
+2: \
+ r0 /= 0; /* trap */ \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Constant current register lying on the cached line: cached is {0,3,6,...}
+ * (step 3, base 0), current is the constant 6. range_within() takes the
+ * constant branch: imod(6, 3) == base 0, so cur is on the line and the
+ * (precise) state is pruned -> "safe".
+ */
+SEC("socket")
+__success __log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("14: (27) r1 *= 3") /* cached path: step 3 line */
+__msg("16: (b7) r1 = 6") /* current path: const 6, on the line */
+__msg("17: safe") /* pruned at join: imod(6, 3) == 0 */
+__naked void step_prune_hit_const_on_line(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r1 = 0; \
+ *(u32*)(r10 - 4) = r1; \
+ r2 = r10; \
+ r2 += -4; \
+ r1 = %[step_map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto l_out_%=; \
+ r7 = r0; \
+ r1 = r6; \
+ r1 &= 0xff; \
+ if r6 > 0 goto l_cur_%=; \
+ r1 *= 3; /* old: step 3 */ \
+ goto l_join_%=; \
+l_cur_%=: \
+ r1 = 6; /* cur: const on line */ \
+l_join_%=: \
+ r0 = r7; \
+ r0 += r1; /* r1 forced precise */ \
+ r2 = *(u8 *)(r0 + 0); \
+l_out_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+/*
+ * Constant current register NOT on the cached line: cached is {0,3,6,...}
+ * (step 3, base 0), current is the constant 7. imod(7, 3) == 1 != base 0,
+ * so range_within() fails and the join is traversed again. A power-of-two
+ * step is avoided on purpose: with step 3 the tnum is loose enough to admit
+ * 7, so imod() is
+ * the sole check that rejects it. No failure shape is possible here: 7 is
+ * within the line's bounds and tnum, and the cached line path already
+ * verifies the whole outro, so an eager prune could not miss an error.
+ */
+SEC("socket")
+__success __log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("14: (27) r1 *= 3") /* cached path: step 3 line */
+__msg("16: (b7) r1 = 7") /* current path: const 7, off the line */
+/* not pruned: current continues past the join with the constant offset 7 */
+__msg("19: R0=map_value({{.*}}imm=7) R1=7")
+__naked void step_prune_miss_const_off_line(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = r0; \
+ r1 = 0; \
+ *(u32*)(r10 - 4) = r1; \
+ r2 = r10; \
+ r2 += -4; \
+ r1 = %[step_map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto l_out_%=; \
+ r7 = r0; \
+ r1 = r6; \
+ r1 &= 0xff; \
+ if r6 > 0 goto l_cur_%=; \
+ r1 *= 3; /* old: step 3 */ \
+ goto l_join_%=; \
+l_cur_%=: \
+ r1 = 7; /* cur: const off line */ \
+l_join_%=: \
+ r0 = r7; \
+ r0 += r1; /* r1 forced precise */ \
+ r2 = *(u8 *)(r0 + 0); \
+l_out_%=: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32),
+ __imm(bpf_map_lookup_elem),
+ __imm_addr(step_map)
+ : __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c
new file mode 100644
index 0000000000000..ab6b744573657
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_btf_array_access.c
@@ -0,0 +1,506 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <vmlinux.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_core_read.h>
+#include "bpf_experimental.h"
+#include "bpf_misc.h"
+
+/*
+ * Variable-offset access into arrays within a BTF access chain, e.g. a[i].b,
+ * where 'i' is a register with a varying offset. The register's step has to
+ * match the stride of one of the arrays crossed while walking the access
+ * chain, and the maximal possible offset has to stay within that array.
+ *
+ * A program-allocated object (bpf_obj_new) is used as the source of a
+ * PTR_TO_BTF_ID with a shape we fully control.
+ */
+struct inner {
+ int a;
+ int b;
+};
+
+struct outer {
+ struct inner arr[8]; /* off 0, stride 8, size 64 */
+ char bytes[32]; /* off 64, stride 1, size 32 */
+ long longs[8]; /* off 96, stride 8, size 64 */
+ int grid[4][4]; /* off 160, 16 ints, size 64 */
+};
+
+/* arr[i].b, i in [0, 7], 4-byte read: stays within arr. */
+SEC("syscall")
+__success
+int arr_field_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* arr[i].b, i in [0, 15]: max offset runs past the end of arr. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int arr_field_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* longs[i], i in [0, 7], 8-byte read: scalar array with stride 8. */
+SEC("syscall")
+__success
+int long_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 96); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * bytes[i], i in [0, 31], read as 4 bytes: min_off is valid within the array,
+ * but the 4-byte read at max_off runs past the array end. Exercises the
+ * size-aware bound in btf_struct_access().
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int byte_array_size_spanning(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 64); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* bytes[i], i in [0, 31], 1-byte read: step 1 matches the char array stride. */
+SEC("syscall")
+__success
+int byte_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 64); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * arr[] accessed with step 4 (half of sizeof(struct inner)): the step is not
+ * a whole number of elements, so no crossed array has a matching stride.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct outer")
+int arr_unaligned_step(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * grid[i][0], i in [0, 3]: steps along the outer dimension of a 2D array
+ * (stride 16). __btf_resolve_size() linearizes the array; the step is a
+ * multiple of the innermost element size (4).
+ */
+SEC("syscall")
+__success
+int grid_outer_dim(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 3; \
+ r2 *= 16; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 160); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * grid[0][i], i in [0, 3]: steps along the inner dimension of a 2D array
+ * (stride 4, the innermost element size).
+ */
+SEC("syscall")
+__success
+int grid_inner_dim(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct outer *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 3; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 160); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * An array of pointers within a program-allocated object. Reading a pointer
+ * member of a local object yields a SCALAR_VALUE, but the varying offset still
+ * has to be validated against the array bounds.
+ */
+struct with_ptrs {
+ struct inner *parr[8]; /* off 0, stride 8 (sizeof ptr), size 64 */
+};
+
+/* parr[i], i in [0, 7], 8-byte read: stays within parr. */
+SEC("syscall")
+__success
+int ptr_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct with_ptrs *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * parr[i], i in [0, 15]: max offset runs past the end of parr. Without the
+ * variable-offset check on the WALK_PTR path this would be wrongly accepted.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct with_ptrs")
+int ptr_array_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct with_ptrs *o;
+ long val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u64 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * The cases above all use bpf_obj_new() (PTR_TO_BTF_ID | MEM_ALLOC). Exercise
+ * the trusted kernel-BTF path too, using a task_struct from
+ * bpf_get_current_task_btf() and its embedded char comm[] array. The comm
+ * offset is folded into the pointer as a constant before the varying index.
+ */
+
+/* task->comm[i], i in [0, 15], 1-byte read: stays within comm. */
+SEC("syscall")
+__success
+int kernel_btf_array_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct task_struct *task;
+ int val = 0;
+
+ task = bpf_get_current_task_btf();
+ asm volatile (" \
+ r1 = %[task]; \
+ r1 += %[off]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [task] "r"(task), [i] "r"(i),
+ [off] "i"(offsetof(struct task_struct, comm))
+ : "r1", "r2");
+ return val;
+}
+
+/* task->comm[i], i in [0, 31]: max offset runs past comm. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct task_struct")
+int kernel_btf_array_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct task_struct *task;
+ int val = 0;
+
+ task = bpf_get_current_task_btf();
+ asm volatile (" \
+ r1 = %[task]; \
+ r1 += %[off]; \
+ r2 = %[i]; \
+ r2 &= 31; \
+ r1 += r2; \
+ %[val] = *(u8 *)(r1 + 0); \
+" : [val] "=r"(val)
+ : [task] "r"(task), [i] "r"(i),
+ [off] "i"(offsetof(struct task_struct, comm))
+ : "r1", "r2");
+ return val;
+}
+
+/*
+ * Array nested below a struct member at a non-zero offset. The walk descends
+ * through 'm' (resetting the running offset) before reaching 'arr', exercising
+ * the array_start = min_off - arrays[i].off telescoping across a WALK_STRUCT
+ * dive.
+ */
+struct mid {
+ struct inner arr[8]; /* stride 8, size 64 */
+};
+
+struct nest {
+ long pad; /* off 0 */
+ struct mid m; /* off 8 */
+};
+
+/* m.arr[i].b, i in [0, 7], 4-byte read: stays within m.arr. */
+SEC("syscall")
+__success
+int nested_struct_in_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct nest *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 12); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/* m.arr[i].b, i in [0, 15]: max offset runs past the end of m.arr. */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct nest")
+int nested_struct_out_of_bounds(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct nest *o;
+ int val = 0;
+
+ o = bpf_obj_new(typeof(*o));
+ if (!o)
+ return 0;
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 15; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 12); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ bpf_obj_drop(o);
+ return val;
+}
+
+/*
+ * A trailing flexible array member makes the struct tail an unbounded region,
+ * so a varying access into it has no upper bound to exceed (mirrors how
+ * unix_address.name[] is accessed via sun_path[i]).
+ *
+ * A custom (program) BTF struct can only be reached as a PTR_TO_BTF_ID through
+ * bpf_obj_new(), which does not allow flexible array members. So use a kernel
+ * type via an untrusted PTR_TO_BTF_ID (bpf_core_cast()). struct vring_used ends
+ * with a flexible array 'ring[]' of struct vring_used_elem { __virtio32 id, len; },
+ * mirroring a 'struct foo { int a; int b; }' flexible array.
+ */
+
+/* ring[i].len, i in [0, 63], 4-byte read: the flexible array has no upper bound. */
+SEC("syscall")
+__success
+int flex_array_field(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct vring_used *o;
+ int val = 0;
+
+ o = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 63; \
+ r2 *= 8; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 8); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ return val;
+}
+
+/*
+ * ring[] accessed with step 4 (half of sizeof(struct vring_used_elem)): the
+ * step is not a whole number of elements, so the flexible array stride does
+ * not match.
+ */
+SEC("syscall")
+__failure
+__msg("invalid variable offset access into struct vring_used")
+int flex_array_unaligned_step(void *ctx)
+{
+ unsigned long i = bpf_get_prandom_u32();
+ struct vring_used *o;
+ int val = 0;
+
+ o = bpf_core_cast(bpf_get_current_task_btf(), struct vring_used);
+ asm volatile (" \
+ r1 = %[o]; \
+ r2 = %[i]; \
+ r2 &= 7; \
+ r2 *= 4; \
+ r1 += r2; \
+ %[val] = *(u32 *)(r1 + 4); \
+" : [val] "=r"(val)
+ : [o] "r"(o), [i] "r"(i)
+ : "r1", "r2");
+ return val;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_gotox.c b/tools/testing/selftests/bpf/progs/verifier_gotox.c
index f5a9878c7b8d4..03a3bee212361 100644
--- a/tools/testing/selftests/bpf/progs/verifier_gotox.c
+++ b/tools/testing/selftests/bpf/progs/verifier_gotox.c
@@ -509,7 +509,7 @@ __naked void too_many_gotox_edges(void)
SEC("socket")
__description("gotox-edges-at-limit")
-__success __retval(0)
+__failure __msg("Too many nested loops")
__naked void gotox_edges_at_limit(void)
{
asm volatile (
@@ -517,6 +517,10 @@ __naked void gotox_edges_at_limit(void)
* 1000 gotox * 1000 targets = 1,000,000 CFG edges. At run
* time, each block loads the next table entry and jumps to
* the following block, so the program terminates.
+ *
+ * Every block can jump to every later block, so the CFG is
+ * a nest of ~1000 irreducible loops, deeper than the
+ * verifier's loop stack; the program is rejected.
*/
GOTOX_TABLE_BEGIN(1000)
".rept 1000;"
diff --git a/tools/testing/selftests/bpf/progs/verifier_idoms.c b/tools/testing/selftests/bpf/progs/verifier_idoms.c
new file mode 100644
index 0000000000000..a29d6332baa4f
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_idoms.c
@@ -0,0 +1,390 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "../../../include/linux/filter.h"
+
+/*
+ * kernel/bpf/loops.c:bpf_compute_idoms() computes the immediate dominator
+ * of every instruction (Cooper et al, "A Simple, Fast Dominance Algorithm").
+ *
+ * The immediate dominator is printed by log_program() as the numeric column
+ * immediately before the "<insn#>:" field of every "Program dump" line:
+ *
+ * Program dump (scc? loop_header? idom insn#: live_regs_before):
+ * -1 0: ....... (b7) r0 = 0 <- idom(0) = -1 (subprog entry)
+ * 0 1: ....... (07) r0 += 1 <- idom(1) = 0
+ * ^^^^^^
+ * idom insn#
+ *
+ * The __msg() patterns below wildcard the scc/loop_header/live_regs columns and
+ * anchor on "<idom> <insn#>:" followed by the disassembled instruction, so
+ * they assert the idom value of each instruction.
+ */
+
+/*
+ * Straight-line code, with an ldimm64 in the middle. Instruction index 2 is
+ * the second half of the ldimm64 at index 1 and is not a CFG node; the idom of
+ * index 3 must be 1, not 2. Exercises the bpf_is_ldimm64() skip in both passes
+ * of compute_predecessors().
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (18) r1 = 0x1122334455667788")
+__msg("{{.*}} 1 3: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 3 4: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 4 5: {{.*}} (95) exit")
+__naked void straight_line_ldimm64(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r1 = 0x1122334455667788 ll; \
+ r0 += 1; \
+ r0 += r1; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Asymmetric if-then-else diamond: the "then" arm is 5 instructions long, the
+ * "else" arm is a single instruction. The merge point (insn 8) is dominated by
+ * the branch (insn 1), not by either arm. This forces idoms_intersect() to walk
+ * the two predecessors up unequal postorder depths before they meet.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (25) if r0 > 0x0 goto pc+5")
+__msg("{{.*}} 1 2: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 2 3: {{.*}} (b7) r1 = 2")
+__msg("{{.*}} 3 4: {{.*}} (b7) r1 = 3")
+__msg("{{.*}} 4 5: {{.*}} (b7) r1 = 4")
+__msg("{{.*}} 5 6: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 1 7: {{.*}} (b7) r1 = 9")
+__msg("{{.*}} 1 8: {{.*}} (95) exit")
+__naked void asymmetric_diamond(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r1 = 1; \
+ r1 = 2; \
+ r1 = 3; \
+ r1 = 4; \
+ goto 2f; \
+1: r1 = 9; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Simple loop: the header (insn 1) is dominated by the pre-header (insn 0). The
+ * back edge (insn 2 -> insn 1) must not change idom(1); the back-edge
+ * predecessor folds up via idoms_intersect().
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg("{{.*}} 2 3: {{.*}} (95) exit")
+__naked void simple_loop(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Loop with an if-else in its body. The in-loop merge point (insn 5) is
+ * dominated by the in-loop branch (insn 3), combining a back-edge intersect
+ * with a forward-diamond intersect.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (bf) r1 = r0")
+__msg("{{.*}} 2 3: {{.*}} (25) if r1 > 0x5 goto pc+1")
+__msg("{{.*}} 3 4: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 3 5: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 5 6: {{.*}} (a5) if r0 < 0x64 goto pc-6")
+__msg("{{.*}} 6 7: {{.*}} (95) exit")
+__naked void loop_with_if_else_body(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = r0; \
+ if r1 > 5 goto 2f; \
+ r1 = 1; \
+2: r0 += r1; \
+ if r0 < 100 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Nested loops: the idom chain runs inner-header -> outer-body -> outer-header
+ * -> pre-header. Exercises intersect across back edges at two nesting depths.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r0 += 1")
+__msg("{{.*}} 1 2: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 2 3: {{.*}} (07) r1 += 1")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2")
+__msg("{{.*}} 4 5: {{.*}} (a5) if r0 < 0xa goto pc-5")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__naked void nested_loops(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Loop header (insn 1) with two back edges (from insn 4 and insn 5), i.e. three
+ * predecessors. Both back edges route through the incrementing header, so the
+ * loop is bounded and verifies. Repeated idoms_intersect() at the header must
+ * stay stable and keep idom(1) at the pre-header (insn 0).
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r6 = 0")
+__msg("{{.*}} 0 1: {{.*}} (07) r6 += 1")
+__msg("{{.*}} 1 2: {{.*}} (25) if r6 > 0xa goto pc+3")
+__msg("{{.*}} 2 3: {{.*}} (bf) r7 = r6")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r7 < 0x5 goto pc-4")
+__msg("{{.*}} 4 5: {{.*}} (05) goto pc-5")
+__msg("{{.*}} 2 6: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 6 7: {{.*}} (95) exit")
+__naked void multi_backedge_header(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: r6 += 1; \
+ if r6 > 10 goto 2f; \
+ r7 = r6; \
+ if r7 < 5 goto 1b; \
+ goto 1b; \
+2: r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Irreducible CFG (loop with two entries, insn 3 and insn 5, reached from the
+ * insn 2 branch). Dominators remain well-defined; this is a convergence test
+ * for the fixpoint under irreducibility. Note insn 6 is dominated by the branch
+ * (insn 2), not by either arm.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 1 2: {{.*}} (25) if r0 > 0x5 goto pc+2")
+__msg("{{.*}} 2 3: {{.*}} (b7) r1 = 1")
+__msg("{{.*}} 3 4: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 2 5: {{.*}} (b7) r1 = 2")
+__msg("{{.*}} 2 6: {{.*}} (0f) r0 += r1")
+__msg("{{.*}} 6 7: {{.*}} (a5) if r0 < 0x10 goto pc-5")
+__msg("{{.*}} 7 8: {{.*}} (95) exit")
+__naked void irreducible(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+ if r0 > 5 goto 2f; \
+1: r1 = 1; \
+ goto 3f; \
+2: r1 = 2; \
+3: r0 += r1; \
+ if r0 < 16 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Idoms are computed per subprog. Layout (libbpf preorder) is:
+ * main: 0..1, sub: 2..7
+ * The callee entry (insn 2) must have idom -1 (subprog reset), and idoms inside
+ * the callee must reference only the callee's instructions, never main's. The
+ * in-callee merge (insn 7) is dominated by the in-callee branch (insn 3). The
+ * branch is on a prandom value so it is not constant-folded away.
+ */
+static __naked __noinline __used
+unsigned long idoms_diamond_sub(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r0 = 1; \
+ goto 2f; \
+1: r0 = 2; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call pc+1")
+__msg("{{.*}} 0 1: {{.*}} (95) exit")
+__msg("{{.*}} -1 2: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 2 3: {{.*}} (25) if r0 > 0x0 goto pc+2")
+__msg("{{.*}} 3 4: {{.*}} (b7) r0 = 1")
+__msg("{{.*}} 4 5: {{.*}} (05) goto pc+1")
+__msg("{{.*}} 3 6: {{.*}} (b7) r0 = 2")
+__msg("{{.*}} 3 7: {{.*}} (95) exit")
+__naked void multi_subprog(void)
+{
+ asm volatile (" \
+ call idoms_diamond_sub; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * The first instruction of a subprog (insn 3) is itself a loop header, i.e. it
+ * has an incoming back edge. Its idom must still be -1 (the subprog entry has no
+ * dominator). Exercises the idoms[start]=0 ... idoms[start]=-1 handling in
+ * compute_subprog_idoms().
+ */
+static __naked __noinline __used
+unsigned long idoms_entry_header_sub(void)
+{
+ asm volatile (" \
+1: r1 += 1; \
+ if r1 < 10 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (b7) r1 = 0")
+__msg("{{.*}} 0 1: {{.*}} (85) call pc+1")
+__msg("{{.*}} 1 2: {{.*}} (95) exit")
+__msg("{{.*}} -1 3: {{.*}} (07) r1 += 1")
+__msg("{{.*}} 3 4: {{.*}} (a5) if r1 < 0xa goto pc-2")
+__msg("{{.*}} 4 5: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__naked void entry_is_loop_header(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ call idoms_entry_header_sub; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Self-loop: insn 1 is its own predecessor. idom(1) must be the pre-header
+ * (insn 0); the self-edge is ignored (idoms[pred] == -1 on the first pass, then
+ * idoms_intersect(a == b) short-circuits). Program is rejected later for an
+ * infinite loop, but the dump (and idoms) are printed before that.
+ */
+SEC("socket")
+__failure
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg("{{.*}} 0 1: {{.*}} (a5) if r0 < 0xa goto pc-1")
+__msg("{{.*}} 1 2: {{.*}} (95) exit")
+__msg("infinite loop detected")
+__naked void self_loop(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+1: if r0 < 10 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+#if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) || defined(__TARGET_ARCH_powerpc)
+/*
+ * Indirect jump (gotox) with a two-entry jump table. The gotox (insn 4) has two
+ * successors (insn 5 and insn 7), so both targets have the gotox as their only
+ * predecessor and idom. Also re-exercises the ldimm64 skip: insn 2's idom is 0,
+ * the ldimm64 at index 0 (index 1 is its second half).
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg("{{.*}} -1 0: {{.*}} (18) r0 = {{0x[0-9a-f]+}}")
+__msg("{{.*}} 0 2: {{.*}} (07) r0 += 8")
+__msg("{{.*}} 2 3: {{.*}} (79) r0 = *(u64 *)(r0 +0)")
+__msg("{{.*}} 3 4: {{.*}} (0d) gotox r0")
+__msg("{{.*}} 4 5: {{.*}} (b7) r0 = 0")
+__msg("{{.*}} 5 6: {{.*}} (95) exit")
+__msg("{{.*}} 4 7: {{.*}} (b7) r0 = 1")
+__msg("{{.*}} 7 8: {{.*}} (95) exit")
+__naked void gotox_jump_table(void)
+{
+ asm volatile (" \
+ .pushsection .jumptables,\"\",@progbits; \
+jt0_%=: \
+ .quad ret0_%= - socket; \
+ .quad ret1_%= - socket; \
+ .size jt0_%=, 16; \
+ .global jt0_%=; \
+ .popsection; \
+ \
+ r0 = jt0_%= ll; \
+ r0 += 8; \
+ r0 = *(u64 *)(r0 + 0); \
+ .8byte %[gotox_r0]; \
+ret0_%=: \
+ r0 = 0; \
+ exit; \
+ret1_%=: \
+ r0 = 1; \
+ exit; \
+" :
+ : __imm_insn(gotox_r0, BPF_RAW_INSN(BPF_JMP | BPF_JA | BPF_X, BPF_REG_0, 0, 0, 0))
+ : __clobber_all);
+}
+#endif
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_live_stack.c b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
index 16b2b1e575342..496229a9b284c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_live_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_live_stack.c
@@ -61,8 +61,12 @@ __naked void read_write_join(void)
SEC("socket")
__log_level(2)
__msg("stack use/def subprog#0 must_write_not_same_slot (d0,cs0):")
-__msg("6: (7b) *(u64 *)(r2 +0) = r0{{$}}")
-__msg("Live regs before insn:")
+/*
+ * 'r2 += r1' adds a scalar, so the offset is lost (off_cnt == 0): no def,
+ * but the write conservatively marks the whole frame as may_def.
+ */
+__msg("6: (7b) *(u64 *)(r2 +0) = r0 ; may_def: fp0-8..-{{(512|2048)}}")
+__msg("Program dump")
__naked void must_write_not_same_slot(void)
{
asm volatile (
@@ -79,6 +83,31 @@ __naked void must_write_not_same_slot(void)
: __clobber_all);
}
+SEC("socket")
+__log_level(2)
+__msg("stack use/def subprog#0 may_write_two_precise_offsets (d0,cs0):")
+/*
+ * r1 is fp-8 or fp-16, with both offsets tracked precisely (off_cnt == 2).
+ * A write through it cannot set def, but marks both candidate slots as may_def.
+ */
+__msg("6: (7b) *(u64 *)(r1 +0) = r0 ; may_def: fp0-8 fp0-16")
+__naked void may_write_two_precise_offsets(void)
+{
+ asm volatile (
+ "call %[bpf_get_prandom_u32];"
+ "r1 = r10;"
+ "if r0 > 42 goto 1f;"
+ "r1 += -8;"
+ "goto 2f;"
+"1:"
+ "r1 += -16;"
+"2:"
+ "*(u64 *)(r1 + 0) = r0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__log_level(2)
__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8")
@@ -106,11 +135,11 @@ __naked void must_write_not_same_type(void)
SEC("socket")
__log_level(2)
-/* Callee writes fp[0]-8: stack_use at call site has slots 0,1 live */
+/* Callee writes fp[0]-8: the def is summarized as may_def at the call site */
__msg("stack use/def subprog#0 caller_stack_write (d0,cs0):")
-__msg("2: (85) call pc+1{{$}}")
+__msg("2: (85) call pc+1 ; may_def: fp0-8")
__msg("stack use/def subprog#1 write_first_param (d1,cs2):")
-__msg("4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8")
+__msg("4: (7a) *(u64 *)(r1 +0) = 7 ; def: fp0-8 may_def: fp0-8")
__naked void caller_stack_write(void)
{
asm volatile (
@@ -130,6 +159,49 @@ static __used __naked void write_first_param(void)
::: __clobber_all);
}
+/*
+ * Cross-frame imprecise write: imprecise_frame_writer() receives a pointer
+ * into the caller's frame (frame 0) but conditionally replaces it with a
+ * pointer into its own frame (frame 1). At the store the two are joined into
+ * ARG_IMPRECISE (frame is unknown, mask = {0,1}), so the offset is dropped and
+ * the whole of both candidate frames is conservatively marked as may_def.
+ */
+SEC("socket")
+__log_level(2)
+/* The callee's write into the caller frame is summarized at the call site. */
+__msg("stack use/def subprog#0 imprecise_frame_write (d0,cs0):")
+__msg("2: (85) call pc+2 ; may_def: fp0-8..-{{(512|2048)}}")
+__msg("stack use/def subprog#1 imprecise_frame_writer (d1,cs2):")
+__msg("12: (7b) *(u64 *)(r1 +0) = r2 ; may_def: fp1-8..-{{(512|2048)}} fp0-8..-{{(512|2048)}}")
+__naked void imprecise_frame_write(void)
+{
+ asm volatile (
+ "r1 = r10;"
+ "r1 += -8;"
+ "call imprecise_frame_writer;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void imprecise_frame_writer(void)
+{
+ asm volatile (
+ "r6 = r1;" /* save arg: pointer into frame 0 */
+ "call %[bpf_get_prandom_u32];"
+ "r1 = r6;" /* r1 = frame0-8 (arg) */
+ "if r0 == 0 goto 1f;"
+ "r1 = r10;"
+ "r1 += -8;" /* r1 = frame1-8 (own frame) */
+"1:"
+ "r2 = 0;"
+ "*(u64 *)(r1 + 0) = r2;" /* join frame0-8 | frame1-8 -> imprecise */
+ "r0 = 0;"
+ "exit;"
+ :: __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
SEC("socket")
__log_level(2)
__msg("stack use/def subprog#0 caller_stack_read (d0,cs0):")
@@ -804,7 +876,7 @@ void __kfunc_btf_root(void)
*/
SEC("socket")
__success __log_level(2)
-__msg(" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24{{$}}")
+__msg(" 6: (85) call bpf_iter_num_new{{.*}} ; def: fp0-24 may_def: fp0-24{{$}}")
__msg(" 9: (85) call bpf_iter_num_next{{.*}} ; use: fp0-24{{$}}")
__msg("14: (85) call bpf_iter_num_destroy{{.*}} ; use: fp0-24{{$}}")
__naked void kfunc_iter_stack_liveness(void)
@@ -1007,8 +1079,9 @@ __naked void four_byte_read_upper_half(void)
*/
SEC("socket")
__log_level(2)
-__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8")
-__msg("1: (6a) *(u16 *)(r10 -4) = 0{{$}}")
+__msg("0: (7a) *(u64 *)(r10 -8) = 0 ; def: fp0-8 may_def: fp0-8")
+/* 2-byte write only partially covers the upper half: may_def, but no def. */
+__msg("1: (6a) *(u16 *)(r10 -4) = 0 ; may_def: fp0-4h")
__msg("2: (61) r0 = *(u32 *)(r10 -4) ; use: fp0-4h")
__naked void two_byte_write_no_kill(void)
{
@@ -1355,9 +1428,12 @@ __naked void fp_spill_loses_precision_kills_liveness(void)
*/
SEC("socket")
__log_level(2)
-/* fp-8 live at call (callee conditionally writes → slot not killed) */
-__msg("1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8")
-__msg("4: (85) call pc+2{{$}}")
+/*
+ * fp-8 live at call: callee conditionally writes it, so the slot is not killed
+ * (no def), but the conditional write surfaces as may_def at the call site.
+ */
+__msg("1: (7b) *(u64 *)(r10 -8) = r1 ; def: fp0-8 may_def: fp0-8")
+__msg("4: (85) call pc+2 ; may_def: fp0-8")
__msg("5: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
__naked void conditional_stx_in_subprog(void)
{
@@ -2385,8 +2461,27 @@ __flag(BPF_F_TEST_STATE_FREQ)
__msg("subprog#2 write_first_read_second:")
__msg("17: (7a) *(u64 *)(r1 +0) = 42{{$}}")
__msg("18: (79) r0 = *(u64 *)(r2 +0) // r1=fp0-8 r2=fp0-16{{$}}")
+/*
+ * The callee's write into the caller frame is summarized as may_def at the
+ * call sites, transitively across both frames (depth 2 -> 1 -> 0). The two
+ * call sites differ because the shared write_first_read_second instance
+ * accumulates the cross-pass union ({fp-8, fp-16}) at different points
+ * relative to each forwarding_rw's summarization.
+ */
+__msg("stack use/def subprog#0 shared_instance_must_write_overwrite (d0,cs0):")
+__msg("7: (85) call pc+7 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16")
+__msg("12: (85) call pc+2 ; use: fp0-8 may_def: fp0-16")
+__msg("stack use/def subprog#1 forwarding_rw (d1,cs7):")
+__msg("15: (85) call pc+1 ; use: fp0-8 fp0-16 may_def: fp0-8 fp0-16")
+__msg("stack use/def subprog#1 forwarding_rw (d1,cs12):")
+__msg("15: (85) call pc+1 ; use: fp0-8 may_def: fp0-16")
__msg("stack use/def subprog#2 write_first_read_second (d2,cs15):")
-__msg("17: (7a) *(u64 *)(r1 +0) = 42{{$}}")
+/*
+ * Shared across two callsites with swapped args (r1 is fp-8 on one pass,
+ * fp-16 on the other): must_write intersects to empty (no def), may_write
+ * unions to both slots.
+ */
+__msg("17: (7a) *(u64 *)(r1 +0) = 42 ; may_def: fp0-8 fp0-16")
__msg("18: (79) r0 = *(u64 *)(r2 +0) ; use: fp0-8 fp0-16")
__naked void shared_instance_must_write_overwrite(void)
{
@@ -2428,6 +2523,65 @@ static __used __naked void write_first_read_second(void)
::: __clobber_all);
}
+/*
+ * merge_instances() must preserve may_write when one pass doesn't touch a frame.
+ * mvs_leaf is reached through a single callsite (mvs_mid) from two outer chains,
+ * so it is one shared (depth,callsite) instance analyzed twice and merged:
+ * - chain A passes r2 = map value, mvs_leaf's doesn't touch stack;
+ * - chain B passes r2 = caller stack slot fp-8.
+ * The merge must keep the stack pass's may_write even though the map pass left
+ * frame 0 untouched.
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("stack use/def subprog#2 mvs_leaf (d2,cs19):")
+__msg("21: (7a) *(u64 *)(r2 +0) = 42 ; may_def: fp0-8")
+__naked void merge_preserves_may_write(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 24) = r1;" /* map key */
+ "r1 = %[map] ll;"
+ "r2 = r10;"
+ "r2 += -24;"
+ "call %[bpf_map_lookup_elem];"
+ "if r0 == 0 goto 1f;"
+ /* chain A: r2 = map value (ARG_NONE, not stack) */
+ "r1 = r10;"
+ "r1 += -16;" /* unused fp anchor */
+ "r2 = r0;"
+ "call mvs_mid;"
+ /* chain B: r2 = caller stack slot fp-8 */
+ "r1 = r10;"
+ "r1 += -16;"
+ "r2 = r10;"
+ "r2 += -8;"
+ "call mvs_mid;"
+"1:"
+ "r0 = 0;"
+ "exit;"
+ : : __imm(bpf_map_lookup_elem), __imm_addr(map)
+ : __clobber_all);
+}
+
+static __used __naked void mvs_mid(void)
+{
+ asm volatile (
+ "call mvs_leaf;"
+ "exit;"
+ ::: __clobber_all);
+}
+
+static __used __naked void mvs_leaf(void)
+{
+ asm volatile (
+ "*(u64 *)(r2 + 0) = 42;"
+ "r0 = 0;"
+ "exit;"
+ ::: __clobber_all);
+}
+
/*
* Shared must_write when (callsite, depth) instance is reused.
* Main calls fwd_to_stale_wr at two sites. fwd_to_stale_wr calls
@@ -2512,6 +2666,32 @@ __naked void load_acquire_dont_clear_dst(void)
#endif /* CAN_USE_LOAD_ACQ_STORE_REL */
+SEC("socket")
+__log_level(2)
+__success
+__msg("lock *(u64 *)(r10 -8) += r1{{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r1 = atomic64_fetch_add((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r1 = atomic64_xchg((u64 *)(r10 -8), r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__msg("r0 = atomic64_cmpxchg((u64 *)(r10 -8), r0, r1){{.*}}use: fp0-8{{.*}}may_def: fp0-8")
+__naked void atomic_rmw(void)
+{
+ asm volatile (
+ "r1 = 0;"
+ "*(u64 *)(r10 - 8) = r1;"
+ ".8byte %[atomic_add];"
+ ".8byte %[atomic_fetch_add];"
+ ".8byte %[atomic_xchg];"
+ "r0 = 0;"
+ ".8byte %[atomic_cmpxchg];"
+ "exit;"
+ :
+ : __imm_insn(atomic_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_fetch_add, BPF_ATOMIC_OP(BPF_DW, BPF_ADD | BPF_FETCH, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_xchg, BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_10, BPF_REG_1, -8)),
+ __imm_insn(atomic_cmpxchg, BPF_ATOMIC_OP(BPF_DW, BPF_CMPXCHG, BPF_REG_10, BPF_REG_1, -8))
+ : __clobber_all);
+}
+
SEC("socket")
__success
__naked void imprecise_fill_loses_cross_frame(void)
@@ -2848,8 +3028,9 @@ static __used __naked void imprecise_dst_spill_join_sub(void)
SEC("socket")
__log_level(2)
__msg("0: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
-__msg("1: (73) *(u8 *)(r10 -1) = r0{{$}}")
-__msg("2: (6b) *(u16 *)(r10 -4) = r0{{$}}")
+/* narrow stores define nothing, but they may write the half-slot they touch */
+__msg("1: (73) *(u8 *)(r10 -1) = r0 ; may_def: fp0-4h")
+__msg("2: (6b) *(u16 *)(r10 -4) = r0 ; may_def: fp0-4h")
__msg("3: (79) r0 = *(u64 *)(r10 -8) ; use: fp0-8")
__naked void narrow_store_defines_nothing(void)
{
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c
new file mode 100644
index 0000000000000..5c5bf5b445290
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c
@@ -0,0 +1,317 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+
+/*
+ * kernel/bpf/loops.c:compute_loops() distinguish between
+ * the following cases:
+ * - B: backedge -> simple loop
+ * - C: cross edge to non-loop node -> no-op
+ * - D: edge to node whose header is in DFS path -> nested loop
+ * - E: edge to node whose header is NOT in DFS path -> irreducible
+ *
+ * Below test cases cover the above branches in various combinations.
+ */
+
+/* Case B: single bounded loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg(" 2 3: {{.*}} (95) exit")
+__naked void loop_single(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case B: two independent loops at the same nesting level. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 4{{$}}")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 2 0 1: {{.*}} (07) r0 += 1")
+__msg(" 2 1 1 2: {{.*}} (a5) if r0 < 0xa goto pc-2")
+__msg(" 2 3: {{.*}} (b7) r1 = 0")
+__msg(" 1 3 4: {{.*}} (07) r1 += 1")
+__msg(" 1 4 4 5: {{.*}} (a5) if r1 < 0xa goto pc-2")
+__msg(" 5 6: {{.*}} (95) exit")
+__naked void loop_two_independent(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 10 goto 2b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case B + D: nested loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1") /* outer loop header */
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0") /* outer loop insn */
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1") /* inner loop header */
+__msg(" 1 3 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2") /* inner loop insn */
+__msg(" 1 1 4 5: {{.*}} (a5) if r0 < 0xa goto pc-5") /* outer loop insn */
+__msg(" 5 6: {{.*}} (95) exit")
+__naked void loop_nested(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case C: forward edges, no loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (85) call bpf_get_prandom_u32")
+__msg(" 0 1: {{.*}} (25) if r0 > 0x0 goto pc+2")
+__msg(" 1 2: {{.*}} (b7) r0 = 2")
+__msg(" 2 3: {{.*}} (05) goto pc+1")
+__msg(" 1 4: {{.*}} (b7) r0 = 3")
+__msg(" 1 5: {{.*}} (95) exit")
+__naked void fwd_edges_no_loop(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ if r0 > 0 goto 1f; \
+ r0 = 2; \
+ goto 2f; \
+1: r0 = 3; \
+2: exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/* Case B + D: two sibling inner loops within one outer loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("loop at 6, nested in 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0")
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1")
+__msg(" 1 3 3 4: {{.*}} (a5) if r1 < 0x5 goto pc-2")
+__msg(" 1 1 4 5: {{.*}} (b7) r2 = 0")
+__msg(" 1 1 5 6: {{.*}} (07) r2 += 1")
+__msg(" 1 6 6 7: {{.*}} (a5) if r2 < 0x5 goto pc-2")
+__msg(" 1 1 7 8: {{.*}} (a5) if r0 < 0xa goto pc-8")
+__msg(" 8 9: {{.*}} (95) exit")
+__naked void loop_nested_siblings(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ if r1 < 5 goto 2b; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 5 goto 3b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Three levels of nesting. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 3, nested in 1")
+__msg("loop at 5, nested in 3")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (b7) r1 = 0")
+__msg(" 1 1 2 3: {{.*}} (07) r1 += 1")
+__msg(" 1 3 3 4: {{.*}} (b7) r2 = 0")
+__msg(" 1 3 4 5: {{.*}} (07) r2 += 1")
+__msg(" 1 5 5 6: {{.*}} (a5) if r2 < 0x3 goto pc-2")
+__msg(" 1 3 6 7: {{.*}} (a5) if r1 < 0x5 goto pc-5")
+__msg(" 1 1 7 8: {{.*}} (a5) if r0 < 0xa goto pc-8")
+__msg(" 8 9: {{.*}} (95) exit")
+__naked void loop_three_levels(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 3 goto 3b; \
+ if r1 < 5 goto 2b; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Loop with an if-else body (forward branch inside loop, Case C). */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (b7) r0 = 0")
+__msg(" 1 0 1: {{.*}} (07) r0 += 1")
+__msg(" 1 1 1 2: {{.*}} (bf) r1 = r0")
+__msg(" 1 1 2 3: {{.*}} (25) if r1 > 0x5 goto pc+1")
+__msg(" 1 1 3 4: {{.*}} (b7) r1 = 1")
+__msg(" 1 1 3 5: {{.*}} (0f) r0 += r1")
+__msg(" 1 1 5 6: {{.*}} (a5) if r0 < 0x64 goto pc-6")
+__msg(" 6 7: {{.*}} (95) exit")
+__naked void loop_with_if_else(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = r0; \
+ if r1 > 5 goto 2f; \
+ r1 = 1; \
+2: r0 += r1; \
+ if r0 < 100 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/* Case E: irreducible loop. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 3, irreducible")
+__msg("Program dump")
+__msg(" -1 0: {{.*}} (85) call bpf_get_prandom_u32#7")
+__msg(" 0 1: {{.*}} (b7) r1 = 0")
+__msg(" 1 2: {{.*}} (25) if r0 > 0x5 goto pc+2")
+__msg(" 1 2 3: {{.*}} (b7) r1 = 1")
+__msg(" 1 3 3 4: {{.*}} (05) goto pc+1")
+__msg(" 2 5: {{.*}} (b7) r1 = 2")
+__msg(" 1 3 2 6: {{.*}} (0f) r0 += r1")
+__msg(" 1 3 6 7: {{.*}} (a5) if r0 < 0x10 goto pc-5")
+__msg(" 7 8: {{.*}} (95) exit")
+__naked void loop_irreducible(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+ if r0 > 5 goto 2f; \
+1: r1 = 1; \
+ goto 3f; \
+2: r1 = 2; \
+3: r0 += r1; \
+ if r0 < 16 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("socket")
+__failure
+__log_level(2)
+__msg("loop at 1")
+__msg("infinite loop detected at insn 1")
+__naked void loop_self(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+1: if r0 < 10 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Loops at 5 and 7 are nested inside loops at 3 and 1.
+ * The edge 6 -> 7 exits loop at 5 and enters loop at 7.
+ * Check that it is logged only as an exit from loop at 5.
+ *
+ * 0: r0 = 0;
+ * do {
+ * 1: r0++;
+ * 2: r1 = 0;
+ * do {
+ * 3: r1++;
+ * 4: r2 = 0;
+ * do {
+ * 5: r2++;
+ * 6: } while (r2 < 3);
+ * do {
+ * 7: r2--;
+ * 8: } while (r2 != 0);
+ * 9: } while (r1 < 4);
+ * 10: } while (r0 < 5);
+ * 11: return r0;
+ */
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg_next(" backedge from 10, latch at 10")
+__msg_next(" exit from 10 to 11")
+__msg_next("loop at 3, nested in 1")
+__msg_next(" backedge from 9, latch at 9")
+__msg_next(" exit from 9 to 10")
+__msg_next("loop at 5, nested in 3")
+__msg_next(" backedge from 6, latch at 6")
+__msg_next(" exit from 6 to 7")
+__msg_next("loop at 7, nested in 3")
+__msg_next(" backedge from 8, latch at 8")
+__msg_next(" exit from 8 to 9")
+__naked void loop_nested_siblings_common_ancestors(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ r1 = 0; \
+2: r1 += 1; \
+ r2 = 0; \
+3: r2 += 1; \
+ if r2 < 3 goto 3b; \
+4: r2 += -1; \
+ if r2 != 0 goto 4b; \
+ if r1 < 4 goto 2b; \
+ if r0 < 5 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_scev.c b/tools/testing/selftests/bpf/progs/verifier_scev.c
new file mode 100644
index 0000000000000..69e9062870acb
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/verifier_scev.c
@@ -0,0 +1,1108 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/bpf.h>
+#include <stdbool.h>
+#include <bpf/bpf_helpers.h>
+#include "bpf_misc.h"
+#include "bpf_kfuncs.h"
+
+struct map_val {
+ char foo[1024];
+};
+
+struct {
+ __uint(type, BPF_MAP_TYPE_HASH);
+ __uint(max_entries, 1);
+ __type(key, int);
+ __type(value, struct map_val);
+} map SEC(".maps");
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__naked void simple_loop1(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+loop_%=: \
+ if r0 == 10 goto exit_%=; \
+ r0 += 1; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg("8: (7b) *(u64 *)(r1 +0) = r0 ; *fp-8 (+ *fp-8 1) -> ?")
+__naked void indirect_write_invalidates_scev(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 8) = r0; \
+loop_%=: \
+ r0 = *(u64 *)(r10 - 8); \
+ if r0 == 10 goto exit_%=; \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ r1 = r10; \
+ r1 += -8; \
+ *(u64 *)(r1 + 0) = r0; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 2:")
+__msg_next(" *fp-8=(+ *fp-8 1) / (linear *fp-8 1)")
+__msg_next(" scev at latch 3:")
+__msg_next(" r0=*fp-8 / (linear *fp-8 1)")
+__msg_next(" *fp-8=*fp-8 / (linear *fp-8 1)")
+__naked void simple_loop2(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 8) = r0; \
+loop_%=: \
+ r0 = *(u64 *)(r10 - 8); \
+ if r0 == 10 goto exit_%=; \
+ r0 = *(u64 *)(r10 - 8); \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ goto loop_%=; \
+exit_%=: \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 2:")
+__msg_next(" r1=(+ r1 1) / (linear r1 1)")
+__naked void meet_agrees(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r1 = 0; \
+1: \
+ if r1 == 2 goto 3f; \
+ if r0 == 7 goto 2f; \
+ r1 += 1; \
+ goto 1b; \
+2: \
+ r1 += 1; \
+ goto 1b; \
+3: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__failure
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(any r6 (+ r6 1)) / ?")
+__naked void meet_disagrees(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 3f; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 7 goto 1b; \
+ r6 += 1; \
+ goto 1b; \
+3: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(bswap32 (bswap32 (zext32 (- (- (zext32 (+ (>>...) 1))))))) / ?")
+__naked void expr_chain(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 2f; \
+ r6 += 1; \
+ r6 <<= 32; \
+ r6 >>= 32; \
+ w6 += 1; \
+ r6 = -r6; \
+ w6 = -w6; \
+ r6 = bswap32 r6; \
+ r6 = bswap32 r6; \
+ goto 1b; \
+2: \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg_next("scev at header 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next(" scev at latch 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next("scev at header 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__naked void nested_loop1(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 2f; \
+ r6 += 1; \
+ r7 = 0; \
+3: \
+ if r7 == 2 goto 4f; \
+ r7 += 1; \
+ goto 3b; \
+4: \
+ goto 1b; \
+2: \
+ r0 = r7; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__msg_next("scev at header 1:")
+__msg_next(" r6=(+ r6 1) / (linear r6 1)")
+__msg_next(" r7=?")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next("scev at header 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg_next(" scev at latch 4:")
+__msg_next(" r7=(+ r7 1) / (linear r7 1)")
+__msg("loop header at 1, can't widen r7, expr is ?")
+__msg("loop header at 4, widening r7 to 0..2 step 1")
+__log_level(2)
+__naked void nested_loop_hdr_backedge1(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: \
+ if r6 == 2 goto 3f; \
+ r6 += 1; \
+ r7 = 0; \
+2: \
+ if r7 == 2 goto 1b; \
+ r7 += 1; \
+ goto 2b; \
+3: \
+ r0 = r7; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 10 post-cond")
+__msg("loop header at 1, widening r0 to 0..9 step 1")
+__msg("processed 5 insns")
+__naked void post_cond_jlt(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 < 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 3, header_count is 8")
+__msg("loop header at 3, widening r0 to 2..9 step 1")
+__msg("3: R0=scalar(smin=umin=smin32=umin32=2,smax=umax=smax32=umax32=9,{{.*}})")
+__msg("processed 6 insns")
+__naked void post_cond_jlt_with_base(void)
+{
+ asm volatile (" \
+ r7 = 10 ll; /* ldimm64 for a twist */ \
+ r0 = 2; \
+1: r0 += 1; \
+ if r0 < r7 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 11")
+__msg("loop header at 1, widening r0 to 0..10 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})")
+__msg("processed 5 insns")
+__naked void post_cond_jle(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 <= 10 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 10")
+__msg("loop header at 1, widening r0 to 0..9 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=9,{{.*}})")
+__msg("processed 6 insns")
+__naked void post_cond_jge(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 >= 10 goto 2f; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 11")
+__msg("loop header at 1, widening r0 to 0..10 step 1")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=10,{{.*}})")
+__msg("processed 6 insns")
+__naked void pre_cond_jge(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: if r0 >= 10 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 2 post-cond")
+__naked void post_cond_jgt(void)
+{
+ asm volatile (" \
+ r0 = 2; \
+1: r0 += -1; \
+ if r0 > 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" scev at latch 2:")
+__msg_next(" r0=(+ r0 1) / (linear (+ r0 1) 1)")
+__msg("loop header at 1, widening r0")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})")
+__msg("1: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("2: (55) if r0 != 0x3 goto pc-2")
+__msg("3: (95) exit")
+__msg("loop header at 1, clamping r0")
+__msg("from 2 to 1: safe")
+__msg("processed 5 insns")
+__naked void post_cond_jne(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 != 3 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 -1) / (linear r0 -1)")
+__msg_next(" scev at latch 2:")
+__msg_next(" r0=(+ r0 -1) / (linear (+ r0 -1) -1)")
+__msg("loop header at 1, header_count is 3 post-cond")
+__msg("loop header at 1, widening r0 to 1..3 step 1")
+__msg("1: R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,var_off=(0x0; 0x3)) loop_stack=1")
+__msg("loop header at 1, clamping r0 to 1..2 step 1")
+__msg("processed 5 insns")
+__naked void post_cond_jne_neg_step(void)
+{
+ asm volatile (" \
+ r0 = 3; \
+1: r0 += -1; \
+ if r0 != 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" scev at latch 1:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg("loop header at 1, widening r0")
+__msg("1: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("1: (15) if r0 == 0x3 goto pc+2 ; R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,{{.*}})")
+__msg("2: (07) r0 += 1 ; R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,{{.*}})")
+__msg("3: (05) goto pc-3")
+__msg("loop header at 1, clamping r0")
+__msg("1: safe")
+__msg("from 1 to 4: R0=3")
+__msg("4: R0=3")
+__msg("4: (95) exit")
+__msg("processed 6 insns")
+__naked void pre_cond_je1(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: if r0 == 3 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is [0..3] post-cond")
+__naked void one_backedge_two_exits(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: call %[bpf_get_prandom_u32]; \
+ if r0 == 0 goto 2f; \
+ r6 += 1; \
+ if r6 != 3 goto 1b; \
+2: r0 = r6; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg_next("scev at header 11:")
+__msg_next(" r0=(+ r0 1) / (linear r0 1)")
+__msg_next(" r1=(+ r1 2) / (linear r1 2)")
+__msg_next(" scev at latch 16:")
+__msg_next(" r0=(+ r0 1) / (linear (+ r0 1) 1)")
+__msg_next(" r1=(+ r1 2) / (linear (+ r1 2) 2)")
+__msg("loop header at 11, widening r0")
+__msg("loop header at 11, widening r1")
+__msg("11: R0=scalar(smin=smin32=0,smax=umax=smax32=umax32=7,var_off=(0x0; 0x7)) R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=14,var_off=(0x0; 0xe),step=0+2)")
+/* loop exit */
+__msg("16: (a5) if r0 < 0x8 goto pc-6")
+__msg("exiting loop 11")
+__msg("17: (95) exit")
+/* second iteration */
+__msg("loop header at 11, clamping r0")
+__msg("loop header at 11, clamping r1")
+/* iteration convergence */
+__msg("from 16 to 11: safe")
+__not_msg("{{^}}11:")
+/* map lookup error path */
+__msg("from 7 to 17: safe")
+__naked void correlated_regs(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ *(u64*)(r10 - 8) = r1; \
+ r2 = r10; \
+ r2 += -8; \
+ r1 = %[map] ll; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto 2f; \
+ r6 = r0; \
+ r0 = 0; \
+ r1 = 0; \
+1: r2 = r6; \
+ r2 += r1; \
+ *(u8 *)(r2 + 0) = 1; \
+ r0 += 1; \
+ r1 += 2; \
+ if r0 < 8 goto 1b; \
+2: exit; \
+" :
+ : __imm(bpf_map_lookup_elem),
+ __imm_addr(map)
+ : __clobber_all);
+}
+
+/*
+ * k = 0
+ * for (i = 0; i < 4; i++):
+ * for (j = 0; j < 4; j++):
+ * k += 1
+ * k <<= 1 // make SCEV construction not possible
+ * k >>= 1
+ * map[k] = 1 // make k precise
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("19: (72) *(u8 *)(r4 +0) = 1 ; R4=map_value(id={{.*}},map=map,ks=4,vs=1024,imm=16)")
+__not_msg("19: ")
+__msg("processed 106 insns")
+__naked void nested_loops_precise_var1(void)
+{
+ asm volatile (" \
+ *(u64*)(r10 - 8) = 0; \
+ r1 = %[map] ll; \
+ r2 = r10; \
+ r2 += -8; \
+ call %[bpf_map_lookup_elem]; \
+ if r0 == 0 goto 3f; \
+ r1 = 0; \
+ r3 = 0; \
+ /* outer loop */ \
+1: r2 = 0; \
+ /* inner loop */ \
+2: r2 += 1; \
+ r3 += 1; \
+ r3 <<= 1; \
+ r3 >>= 1; \
+ if r2 < 4 goto 2b; \
+ r1 += 1; \
+ if r1 < 4 goto 1b; \
+ r4 = r0; \
+ r4 += r3; \
+ *(u8 *)(r4 + 0) = 1; \
+ r0 = 0; \
+3: exit; \
+" :
+ : __imm(bpf_map_lookup_elem),
+ __imm_addr(map)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 1 pre-cond")
+__naked void pre_cond_jgt(void)
+{
+ asm volatile (" \
+ r0 = -1; \
+1: if r0 > 1 goto 2f; \
+ r0 += 1; \
+ goto 1b; \
+2: exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 2 post-cond")
+__naked void loop_jslt_latch_post(void)
+{
+ asm volatile (" \
+ r0 = -2; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 1 post-cond")
+__naked void loop_jslt_latch_post1(void)
+{
+ asm volatile (" \
+ r0 = -1; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, 0 iterations count")
+__naked void loop_jslt_latch_post2(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+1: r0 += 1; \
+ if r0 s< 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 1, header_count is 3 post-cond")
+__naked void loop_jsle_latch_post(void)
+{
+ asm volatile (" \
+ r0 = -2; \
+1: r0 += 1; \
+ if r0 s<= 0 goto 1b; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop header at 2, header_count is 100 post-cond")
+__msg("loop header at 4, header_count is [0..100] post-cond")
+__msg("loop header at 6, header_count is [0..100] post-cond")
+__msg("processed 20 insns")
+__flag(BPF_F_TEST_STATE_FREQ)
+__naked void nested_loop_with_two_exits(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = 0; \
+1: r6 += 1; \
+ r7 = 0; \
+2: r7 += 1; \
+ r8 = 0; \
+3: r8 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 42 goto +1; \
+ goto 4f; \
+ if r8 < 100 goto 3b; \
+ if r7 < 100 goto 2b; \
+4: if r6 < 100 goto 1b; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+SEC("xdp")
+__success
+__log_level(2)
+__naked void exit_loop_into_loop_header(void)
+{
+ asm volatile (" \
+ r1 = 0; \
+ r2 = 0; \
+loop_a_%=: \
+ r1 += 1; \
+ if r1 < 10 goto loop_a_%=; \
+loop_b_%=: \
+ r2 += 1; \
+ if r2 < 10 goto loop_b_%=; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * This exercises verifier.c:loop_stack_{pop,push}() implementation,
+ * at 'goto d' loops 'b' and 'a' have to be popped from stack,
+ * while loops 'c' and 'd' have to be pushed to stack.
+ *
+ * loop a: // header 5
+ * loop b: // header 6
+ * if (rand) goto d; // 8 -> 12, side entry into inner loop d
+ * ...
+ * loop c: // header 11
+ * loop d: // header 12
+ * ...
+ */
+SEC("xdp")
+__log_level(2)
+__msg("loop at 5")
+__msg("loop at 6, nested in 5")
+__msg("loop at 11, irreducible")
+__msg("loop at 12, nested in 11")
+/* entry via if r0 == 5 goto d_%= false branch */
+__msg("loop header at 12, header_count is 3 post-cond")
+__msg("loop header at 12, widening r9 to 0..2 step 1")
+__msg("12: R8=1 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) loop_stack=11,12")
+/* entry via if r0 == 5 goto d_%= true branch */
+__msg("loop header at 12, header_count is 3 post-cond")
+__msg("loop header at 12, widening r9 to 0..2 step 1")
+__msg("from 8 to 12: R8=0 R9=scalar(smin=smin32=0,smax=umax=smax32=umax32=2,var_off=(0x0; 0x3)) R10=fp0 loop_stack=11,12")
+__naked void enter_nested_loop_from_side(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r6 = 0; \
+ r7 = 0; \
+ r8 = 0; \
+ r9 = 0; \
+a_%=: r6 += 1; \
+b_%=: r7 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ if r0 == 5 goto d_%=; \
+ if r7 < 3 goto b_%=; \
+ if r6 < 3 goto a_%=; \
+c_%=: r8 += 1; \
+d_%=: r9 += 1; \
+ if r9 < 3 goto d_%=; \
+ if r8 < 3 goto c_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Loop A (counter in r6) contains irreducible loop B (header 5),
+ * which contains C (counter in r9).
+ * Entering B at 'body' saves and restores r6, making it appear invariant.
+ * Entering B at 'alternate' skips the save and modifies r6 instead.
+ * Hence A must not infer a SCEV expression for r6.
+ * SCEV expression for r9 in C should still be computed.
+ *
+ * 0: r6 = 0;
+ * do { // A
+ * 1: r6++;
+ * 2: r0 = bpf_get_prandom_u32();
+ * 3: r7 = 0;
+ * 4: if (r0 > 5) goto alternate;
+ * 5: B: r8 = r6; // B
+ * 6: goto body;
+ * 7: alternate:
+ * r8 = r6;
+ * 8: r8++;
+ * 9: body:
+ * r6 = r8;
+ * 10: r9 = 0;
+ * do { // C
+ * 11: r9++;
+ * 12: } while (r9 < 3);
+ * 13: r7++;
+ * 14: if (r7 < 4) goto B;
+ * 15: } while (r6 < 4);
+ * 16: r0 = 0;
+ * 17: return r0;
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop at 1{{$}}")
+__msg("loop at 5, nested in 1, irreducible")
+__msg("loop at 11, nested in 5")
+__msg("scev at header 1:")
+__msg_next(" r6=?")
+__msg("scev at header 11:")
+__msg_next(" r9=(+ r9 1) / (linear r9 1)")
+__msg("loop header at 11, widening r9 to 0..2 step 1")
+__not_msg("loop header at 1, widening r6")
+__naked void nested_irreducible_loop(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+a_%=: r6 += 1; \
+ call %[bpf_get_prandom_u32]; \
+ r7 = 0; \
+ if r0 > 5 goto alternate_%=; \
+b_%=: r8 = r6; \
+ goto body_%=; \
+alternate_%=: \
+ r8 = r6; \
+ r8 += 1; \
+body_%=: \
+ r6 = r8; \
+ r9 = 0; \
+c_%=: r9 += 1; \
+ if r9 < 3 goto c_%=; \
+ r7 += 1; \
+ if r7 < 4 goto b_%=; \
+ if r6 < 4 goto a_%=; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Induction variable seeded from a non-constant value. r7 enters the loop as a
+ * range aligned to 2 (prandom & 0x6 -> {0,2,4,6}) and is incremented by a
+ * non-power-of-2 slope of 6. Since the entry value is not a single point, only
+ * the power-of-two alignment shared by the entry value and the slope can be
+ * guaranteed, so the widened step is 2 - not |slope|=6, which would be unsound
+ * here (a constant entry value would have allowed step 6).
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 4, widening r7 to 0..18 step 2")
+__msg("R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=18,var_off=(0x0; 0x1e),step=0+2)")
+__naked void widen_nonconst_base(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r7 = r0; \
+ r7 &= 0x6; \
+ r6 = 0; \
+1: r7 += 6; \
+ r6 += 1; \
+ if r6 < 3 goto 1b; \
+ r0 = 0; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * Two nested loops with (1) exiting directly to (2):
+ *
+ * for (r6 = 0; r6 < 4; r6++) {
+ * r7 = 0;
+ * for (; r7 < 3; r7++) {} // (1)
+ * for (; r7 != 0; r7--) {} // (2)
+ * }
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__msg("loop header at 1, widening r6 to 0..3 step 1")
+__msg("loop header at 2, widening r7 to 0..2 step 1")
+__msg("loop header at 4, widening r7 to 1..3 step 1")
+__naked void sibling_inner_loops(void)
+{
+ asm volatile (" \
+ r6 = 0; \
+1: r7 = 0; \
+2: r7 += 1; \
+ if r7 < 3 goto 2b; \
+3: r7 += -1; \
+ if r7 != 0 goto 3b; \
+ r6 += 1; \
+ if r6 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+SEC("socket")
+__success
+__log_level(2)
+__msg("loop header at 0, can't compute iterations count")
+__naked void uninit_slot_counter(void)
+{
+ asm volatile (" \
+1: r0 = *(u64 *)(r10 - 8); \
+ r0 += 1; \
+ *(u64 *)(r10 - 8) = r0; \
+ if r0 < 10 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * The assignment happens only on the second iteration:
+ *
+ * r7 = 5;
+ * for (r6 = 0; r6 < 3; r6++)
+ * if (r6 == 1)
+ * r7 = 10;
+ * if (r7 != 10)
+ * invalid_stack_read();
+ *
+ * R7 is always 10 at the real exit. Widening loses the correlation between
+ * R6 and R7, leaving R7 in [5, 10] both at the loop header and after the loop.
+ * The verifier therefore rejects the possible invalid stack read.
+ */
+SEC("xdp")
+__failure
+__log_level(2)
+__msg("2: {{.*}}R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
+__msg("7: R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
+__msg("invalid read from stack R10 off=0 size=8")
+__naked void conditional_assignment_on_second_iteration(void)
+{
+ asm volatile (" \
+ r7 = 5; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = 10; \
+2: r6 += 1; \
+ goto 1b; \
+3: if r7 == 10 goto 4f; \
+ r0 = *(u64 *)(r10 + 0); \
+4: r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Join two stack pointer offsets via (any r7 r8), with r8 loop-invariant.
+ * The joined range [-16, -8] still points to initialized stack memory,
+ * so dereferencing r7 after the loop is safe.
+ */
+SEC("xdp")
+__success __retval(0)
+__log_level(2)
+__msg("loop header at 7, widening r7 to -16..-8 step 1")
+__msg("7: {{.*}}R7=fp(smin=smin32=-16,smax=smax32=-8,")
+__msg("12: R7=fp(smin=smin32=-16,smax=smax32=-8,")
+__naked void conditional_stack_pointer_assignment(void)
+{
+ asm volatile (" \
+ *(u64 *)(r10 - 16) = 0; \
+ *(u64 *)(r10 - 8) = 0; \
+ r7 = r10; \
+ r7 += -16; \
+ r8 = r10; \
+ r8 += -8; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = r8; \
+2: r6 += 1; \
+ goto 1b; \
+3: r0 = *(u64 *)(r7 + 0); \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * r7 starts as 1 + 6*k and invariant r8 as 1 + 9*k (0 <= k <= 3).
+ * The (any r7 r8) union must preserve base 1 and step gcd(6, 9) = 3.
+ */
+SEC("xdp")
+__success __retval(1)
+__log_level(2)
+__msg("r7 += 1 {{.*}}step=1+6)")
+__msg("r8 += 1 {{.*}}step=1+9)")
+__msg("loop header at 9, widening r7 to 1..28 step 3")
+__msg("9: {{.*}}R7=scalar({{.*}},step=1+3)")
+__msg("14: R7=scalar({{.*}},step=1+3)")
+__naked void conditional_scalar_assignment_gcd(void)
+{
+ asm volatile (" \
+ call %[bpf_get_prandom_u32]; \
+ r0 &= 3; \
+ r7 = r0; \
+ r7 *= 6; \
+ r7 += 1; \
+ r8 = r0; \
+ r8 *= 9; \
+ r8 += 1; \
+ r6 = 0; \
+1: if r6 >= 3 goto 3f; \
+ if r6 != 1 goto 2f; \
+ r7 = r8; \
+2: r6 += 1; \
+ goto 1b; \
+3: r0 = r7; \
+ r0 %%= 3; \
+ exit; \
+" :
+ : __imm(bpf_get_prandom_u32)
+ : __clobber_all);
+}
+
+/*
+ * A loop induction variable used to compute the base address of a store to the
+ * stack must not be widened: the spill offset would become varying, which the
+ * verifier does not track.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__naked void no_widen_stack_spill(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u64 *)(r3 + 0) = r0; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+/*
+ * Same hazard across a loop nest: the outer induction variable r2 addresses a
+ * stack store performed inside the inner loop. The dependency is pulled up from
+ * the inner loop, so the outer loop must not widen r2.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 2, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__msg("loop header at 3, widening r1 to 0..1 step 1")
+__naked void no_widen_stack_spill_nested(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r1 = 0; \
+2: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u64 *)(r3 + 0) = r1; \
+ r1 += 1; \
+ if r1 < 2 goto 2b; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * Complement of no_widen_stack_spill: a sub-register (1-byte) store to the stack
+ * lands as STACK_MISC and carries no tracked value, so the induction variable
+ * addressing it (r2) is still widened.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("widening r2 to 0..24 step 8")
+__naked void widen_byte_stack_store(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ *(u8 *)(r3 + 0) = r0; \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * A fill (BPF_LDX) at a varying stack offset loses precision just like a spill,
+ * so the induction variable computing the load base (r2) must not be widened.
+ * The slots are initialized up front so the fill itself is a valid read.
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("loop header at 6, can't widen r2, expr is (+ r2 8), requires exact stack-offset tracking")
+__naked void no_widen_stack_fill(void)
+{
+ asm volatile (" \
+ r0 = 0; \
+ *(u64 *)(r10 - 64) = r0; \
+ *(u64 *)(r10 - 56) = r0; \
+ *(u64 *)(r10 - 48) = r0; \
+ *(u64 *)(r10 - 40) = r0; \
+ r2 = 0; \
+1: r3 = r10; \
+ r3 += -64; \
+ r3 += r2; \
+ r4 = *(u64 *)(r3 + 0); \
+ r0 += 1; \
+ r2 += 8; \
+ if r0 < 4 goto 1b; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
+/*
+ * A dynptr/iter/irq/res_spin_lock call initializes a stack object through a
+ * pointer argument, which acts like a spill base: the induction variable
+ * computing that argument's varying stack offset must not be widened, otherwise
+ * the slot can't be resolved. Here each iteration constructs an xdp dynptr at
+ * &dptrs[i].
+ */
+SEC("xdp")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+__msg("can't widen {{.*}}, requires exact stack-offset tracking")
+int no_widen_dynptr_kfunc_arg(struct xdp_md *ctx)
+{
+ struct bpf_dynptr dptrs[4];
+ int i;
+
+#pragma clang loop unroll(disable)
+ for (i = 0; i < 4; i++)
+ bpf_dynptr_from_xdp(ctx, 0, &dptrs[i]);
+
+ return 0;
+}
+
+char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
index 3e0bea9819cab..5da8b9a6018cf 100644
--- a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
+++ b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
@@ -586,4 +586,37 @@ __naked void stack_check_size_512_with_may_goto(void)
}
#endif
+/* Verify that old PTR_TO_STACK state is considered a super-set of
+ * new PTR_TO_STACK state when new variable range is a sub-range
+ * of the old range, e.g. old [-72, -16] vs new [-64, -16].
+ */
+SEC("socket")
+__success
+__log_level(2)
+__flag(BPF_F_TEST_STATE_FREQ)
+/* r7 is widened to [-72, -16] at the loop header (insn 3),
+ * the loop body sees [-64, -8] after 'r7 += 8'
+ */
+__msg("loop header at 3, widening r7 to -72..-16 step 8")
+__msg("R7=fp(smin=smin32=-64,smax=smax32=-8")
+/* back-edge state is clamped to the remaining iterations and pruned
+ * at the header, because [-64, -16] is within the widened [-72, -16]
+ */
+__msg("loop header at 3, clamping r7 to -64..-16 step 8")
+__msg("from 5 to 3: safe")
+__msg("processed 9 insns")
+__naked void stack_ptr_subrange_in_loop(void)
+{
+ asm volatile (" \
+ r7 = r10; \
+ r7 += -72; \
+ r6 = 0; \
+ r7 += 8; \
+ r6 += 1; \
+ if r6 < 8 goto -3; \
+ r0 = 0; \
+ exit; \
+" ::: __clobber_all);
+}
+
char _license[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/test_loader.c b/tools/testing/selftests/bpf/test_loader.c
index 25eeb1c1248b3..edeeb244e693f 100644
--- a/tools/testing/selftests/bpf/test_loader.c
+++ b/tools/testing/selftests/bpf/test_loader.c
@@ -508,6 +508,16 @@ static int parse_test_spec(struct test_loader *tester,
if (err)
goto cleanup;
spec->mode_mask |= UNPRIV;
+ } else if ((msg = str_has_pfx(s, "test_expect_msg_next="))) {
+ err = __push_msg(msg, true, false, &spec->priv.expect_msgs);
+ if (err)
+ goto cleanup;
+ spec->mode_mask |= PRIV;
+ } else if ((msg = str_has_pfx(s, "test_expect_msg_next_unpriv="))) {
+ err = __push_msg(msg, true, false, &spec->unpriv.expect_msgs);
+ if (err)
+ goto cleanup;
+ spec->mode_mask |= UNPRIV;
} else if ((msg = str_has_pfx(s, "test_jited="))) {
if (arch_mask == 0) {
PRINT_FAIL("__jited used before __arch_*");
|
| 21/3 | 2026/09/28 01:36 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 116016 output: 36 thoughts: 1976 Thoughts: **KMSAN Determination for eBPF Verifier Patch** Okay, so I need to assess whether this eBPF verifier patch series warrants a dedicated KMSAN fuzzing session. Let's break this down systematically. First, I need to understand what this patch actually *does*. Looks like it's introducing scalar evolution (SCEV) and loop handling into the eBPF verifier. A bunch of files are touched, including header files with new structures like `bpf_reg_state` (with `base` and `step`), and various source files in `kernel/bpf/`. There are also new files related to loops, heaps, and SCEV. The target architecture is amd64. Now, the critical question: does this touch uninitialized memory in a way that *only* KMSAN would catch? KASAN, LOCKDEP, and other bug detectors cover most of the common issues like out-of-bounds accesses and use-after-free bugs. A KMSAN session is expensive, so it's a last resort if it truly exposes uninitialized memory leaks. My internal checklist: Does this patch modify or introduce: 1. Kernel structures sent to user space? 2. Conditional logic or branching dependent on uninitialized variables? 3. Allocation of complex data structures with potentially uninitialized fields? 4. Bounds checks that could lead to reading uninitialized parts of existing buffers? If the answer to *any* of those is "yes," then KMSAN is likely needed. Otherwise, if allocations are zeroed or initialized, and there are no info-leaks, then it is not. Crucially, I have to consider the eBPF verifier. Does this change affect uninitialized stack reads in the BPF programs themselves, within the verifier's own memory, or in kernel memory exposed to user space? I need to focus on allocations and initializations within the patch itself, as the patch may use uninitialized memory, but this memory may not be relevant to KMSAN if it is not exposed to the user space. So, let's dive into the code. Looking at the allocations in `kernel/bpf/cfg.c`, `kernel/bpf/heap.c`, `kernel/bpf/loops.c`, and `kernel/bpf/scev.c`, I see a lot of `kzalloc`, `kvzalloc`, and `kvcalloc`. These functions are good, right? They zero the memory, so that's a positive sign. `krealloc` is used, and in some cases with `__GFP_ZERO`, which I'll need to double-check: `kvrealloc` also zeroes new allocation if `__GFP_ZERO`. Wait, in `scev.c`, there's a `bpf_reg_state` with new fields, `base` and `step`. This is a *critical* point. Where is this initialized? Is it zeroed before use? I see in the verifier, `___mark_reg_known` and `bpf_mark_reg_unknown_imprecise` and it's resetting the `reg` and then sets the new fields. I'll need to trace all uses of `bpf_reg_state` and these new fields, and `bpf_mark_reg_not_init`. I need to be *absolutely* sure that these new fields are properly initialized *before* any reads or copies occur, and particularly that they are not read in any code path that could be triggered by a BPF program. Based on my analysis of the allocations and initializations, it looks like most, if not all, of the data structures introduced or modified by this patch are properly initialized with `kzalloc`, `kvzalloc`, etc. But, the addition of `base` and `step` fields to the `bpf_reg_state` struct is a critical area that requires a *very* careful review, specifically focusing on `bpf_mark_reg_not_init` and whether or not there are any uninitialized reads. That's where I need to focus my detailed examination. |
| 22/3 | 2026/09/28 01:36 | tool | grepper |
0mArgs:{
"Expression": "void bpf_mark_reg_not_init",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=2314=static int __mark_reg_s32_range(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2333-\nkernel/bpf/verifier.c:2334:void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-2335-\t\t\t struct bpf_reg_state *reg)\n"
} |
| 23/3 | 2026/09/28 01:36 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 119039 output: 37 thoughts: 34 Thoughts: Here's my summary, as if I were thinking these thoughts: **Analyzing `bpf_mark_reg_not_init`** Alright, let's dive into this. The verifier in BPF is a critical component, and this `bpf_mark_reg_not_init` function, specifically around line 2334 in `kernel/bpf/verifier.c`, is likely tied to initialization checks. My guess is it handles marking registers as uninitialized, which is a crucial aspect of ensuring that BPF programs don't read from potentially garbage or uninitialized memory, which could lead to vulnerabilities. I need to understand how the verifier's state is managed. How does it track which registers have been set, and what conditions trigger this particular function to be called? I'll probably be looking at data flow and conditional logic within the verifier to fully grasp the rationale behind this function. Time to dig in and understand its contribution to the overall soundness of BPF program execution. |
| 24/3 | 2026/09/28 01:36 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 2330,
"LineCount": 30
}Results: {
"Contents": "2330:\t\n2331:\t\treturn reg_bounds_sanity_check(env, reg, \"s32_range\");\n2332:\t}\n2333:\t\n2334:\tvoid bpf_mark_reg_not_init(const struct bpf_verifier_env *env,\n2335:\t\t\t\t struct bpf_reg_state *reg)\n2336:\t{\n2337:\t\t__mark_reg_unknown(env, reg);\n2338:\t\treg-\u003etype = NOT_INIT;\n2339:\t}\n2340:\t\n2341:\tstatic int mark_btf_ld_reg(struct bpf_verifier_env *env,\n2342:\t\t\t\t struct bpf_reg_state *regs, u32 regno,\n2343:\t\t\t\t enum bpf_reg_type reg_type,\n2344:\t\t\t\t struct btf *btf, u32 btf_id,\n2345:\t\t\t\t enum bpf_type_flag flag)\n2346:\t{\n2347:\t\tswitch (reg_type) {\n2348:\t\tcase SCALAR_VALUE:\n2349:\t\t\tmark_reg_unknown(env, regs, regno);\n2350:\t\t\treturn 0;\n2351:\t\tcase PTR_TO_BTF_ID:\n2352:\t\t\tmark_reg_known_zero(env, regs, regno);\n2353:\t\t\tregs[regno].type = PTR_TO_BTF_ID | flag;\n2354:\t\t\tregs[regno].btf = btf;\n2355:\t\t\tregs[regno].btf_id = btf_id;\n2356:\t\t\tif (type_may_be_null(flag))\n2357:\t\t\t\tregs[regno].id = ++env-\u003eid_gen;\n2358:\t\t\treturn 0;\n2359:\t\tcase PTR_TO_MEM:\n"
} |
| 25/3 | 2026/09/28 01:36 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 119831 output: 33 thoughts: 17 Thoughts: Here's a summary of my thought process: **Investigating the Purpose of `__mark_reg_unknown`** Okay, so I've come across this function, `__mark_reg_unknown`, and it's got me curious. I need to understand its role within the larger system. My immediate instinct is to delve in and examine its implementation. What specific operations does it perform? What data structures does it manipulate? I need to understand how it's used within this context to grasp its ultimate purpose and potential implications. Is this about register allocation? Optimization? Handling of undefined behavior? I'm going to dig deeper to find out. |
| 26/3 | 2026/09/28 01:36 | tool | grepper |
0mArgs:{
"Expression": "void __mark_reg_unknown\\(",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=810=static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\n--\nkernel/bpf/verifier.c-829-\nkernel/bpf/verifier.c:830:static void __mark_reg_unknown(const struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-831-\t\t\t struct bpf_reg_state *reg);\n--\nkernel/bpf/verifier.c=2289=void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg)\n--\nkernel/bpf/verifier.c-2300- */\nkernel/bpf/verifier.c:2301:static void __mark_reg_unknown(const struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-2302-\t\t\t struct bpf_reg_state *reg)\n"
} |
| 27/3 | 2026/09/28 01:36 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 120272 output: 37 thoughts: 30 Thoughts: Here's my summary, as if I were thinking these thoughts: **Analyzing `__mark_reg_unknown` in the BPF Verifier** Alright, let's dive into the guts of the BPF verifier. I need to get a clear picture of how it handles register state, especially when things get ambiguous. The place to start is line 2300 of `kernel/bpf/verifier.c` – specifically, `__mark_reg_unknown`. This function is likely crucial for the verifier's safety checks. I'm guessing it's responsible for marking a register as having an undefined or unknown value/state when the program flow hits a point where the value cannot be definitively determined through static analysis. This could be due to indirect jumps, conditional execution, or other complexities. I'm keen to see the exact logic. Is it a simple reset to a "unknown" state, or does it involve more sophisticated propagation of uncertainty? Is there any tracking of the origin of that unknown state? Understanding this function's exact behavior is essential for predicting the verifier's limitations and, potentially, exploiting weaknesses if they exist. |
| 28/3 | 2026/09/28 01:37 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 2295,
"LineCount": 35
}Results: {
"Contents": "2295:\t\treg_step_reset(reg);\n2296:\t}\n2297:\t\n2298:\t/* Mark a register as having a completely unknown (scalar) value,\n2299:\t * initialize .precise as true when not bpf capable.\n2300:\t */\n2301:\tstatic void __mark_reg_unknown(const struct bpf_verifier_env *env,\n2302:\t\t\t\t struct bpf_reg_state *reg)\n2303:\t{\n2304:\t\tbpf_mark_reg_unknown_imprecise(reg);\n2305:\t\treg-\u003eprecise = !env-\u003ebpf_capable;\n2306:\t}\n2307:\t\n2308:\tstatic void mark_reg_unknown(struct bpf_verifier_env *env,\n2309:\t\t\t\t struct bpf_reg_state *regs, u32 regno)\n2310:\t{\n2311:\t\t__mark_reg_unknown(env, regs + regno);\n2312:\t}\n2313:\t\n2314:\tstatic int __mark_reg_s32_range(struct bpf_verifier_env *env,\n2315:\t\t\t\t\tstruct bpf_reg_state *regs,\n2316:\t\t\t\t\tu32 regno,\n2317:\t\t\t\t\ts32 s32_min,\n2318:\t\t\t\t\ts32 s32_max)\n2319:\t{\n2320:\t\tstruct bpf_reg_state *reg = regs + regno;\n2321:\t\n2322:\t\treg_set_srange32(reg,\n2323:\t\t\t\t max_t(s32, reg_s32_min(reg), s32_min),\n2324:\t\t\t\t min_t(s32, reg_s32_max(reg), s32_max));\n2325:\t\treg_set_srange64(reg,\n2326:\t\t\t\t max_t(s64, reg_smin(reg), s32_min),\n2327:\t\t\t\t min_t(s64, reg_smax(reg), s32_max));\n2328:\t\n2329:\t\treg_bounds_sync(reg);\n"
} |
| 29/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 121174 output: 38 thoughts: 318 Thoughts: **My Analysis of Register State Reset** Okay, so `__mark_reg_unknown` clearly kicks off a register reset via `bpf_mark_reg_unknown_imprecise(reg)`, which in turn uses `reg_step_reset(reg)`. Seems straightforward, right? That means `base` and `step` *should* be properly reset at that point. But wait... what about the `regsafe` field? I need to make sure that's also being handled correctly. Let's dive into the kernel code, specifically `kernel/bpf/states.c`. I need to understand how register states are compared, especially to confirm `regsafe` is properly handled during the reset. Alright, here's what the code says about comparison: ```c case PTR_TO_STACK: return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off) && check_ids(rold->id, rcur->id, idmap) && check_ids(rold->parent_id, rcur->parent_id, idmap) && rold->frameno == rcur->frameno; ``` Ah, here's the crucial part: `memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off))`. That means it's comparing the register states up to the `var_off` member. But *where* are `base` and `step` within `struct bpf_reg_state`? Is this comparison enough to reset everything correctly, or is it missing parts? I need to know where they are relative to `var_off` and if that `memcmp` will properly reset them. Okay, let's go straight to the source. Time to look at the definition of `struct bpf_reg_state` in `include/linux/bpf_verifier.h`. That's where I'll find the structure layout and confirm that `regsafe` is, or isn't, implicitly handled by the code. I need to make sure the reset is complete, and this comparison isn't inadvertently skipping something. |
| 30/3 | 2026/09/28 01:37 | tool | read-file |
0mArgs:{
"File": "include/linux/bpf_verifier.h",
"FirstLine": 155,
"LineCount": 45
}Results: {
"Contents": " 155:\t\t/*\n 156:\t\t * Upper bit of ID is used to remember relationship between \"linked\"\n 157:\t\t * registers. Example:\n 158:\t\t * r1 = r2; both will have r1-\u003eid == r2-\u003eid == N\n 159:\t\t * r1 += 10; r1-\u003eid == N | BPF_ADD_CONST and r1-\u003edelta == 10\n 160:\t\t * r3 = r2; both will have r3-\u003eid == r2-\u003eid == N\n 161:\t\t * w3 += 10; r3-\u003eid == N | BPF_ADD_CONST32 and r3-\u003edelta == 10\n 162:\t\t */\n 163:\t#define BPF_ADD_CONST64 (1U \u003c\u003c 31)\n 164:\t#define BPF_ADD_CONST32 (1U \u003c\u003c 30)\n 165:\t#define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)\n 166:\t\tu32 id;\n 167:\t\t/*\n 168:\t\t * Tracks the parent object this register was derived from.\n 169:\t\t * Used for cascading invalidation: when the parent object is\n 170:\t\t * released or invalidated, all registers with matching parent_id\n 171:\t\t * are also invalidated. For example, a slice from bpf_dynptr_data()\n 172:\t\t * gets parent_id set to the dynptr's id.\n 173:\t\t */\n 174:\t\tu32 parent_id;\n 175:\t\t/*\n 176:\t\t * Distinguishes inner-map lookups and their keys and values. Zero for\n 177:\t\t * other registers. Kept outside the metadata union for ID remapping\n 178:\t\t * during state comparisons.\n 179:\t\t */\n 180:\t\tu32 map_uid;\n 181:\t\t/*\n 182:\t\t * The value described by this register is some point lying on\n 183:\t\t * a line described by a linear equation base + step * k.\n 184:\t\t * Invariant: base \u003c step.\n 185:\t\t */\n 186:\t\tu16 base;\n 187:\t\tu16 step;\n 188:\t\t/* if (!precise \u0026\u0026 SCALAR_VALUE) min/max/tnum don't affect safety */\n 189:\t\tbool precise;\n 190:\t};\n 191:\t\n 192:\tstatic inline s64 reg_smin(const struct bpf_reg_state *reg)\n 193:\t{\n 194:\t\treturn cnum64_smin(reg-\u003er64);\n 195:\t}\n 196:\t\n 197:\tstatic inline s64 reg_smax(const struct bpf_reg_state *reg)\n 198:\t{\n 199:\t\treturn cnum64_smax(reg-\u003er64);\n"
} |
| 31/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 122842 output: 38 thoughts: 22 Thoughts: Okay, let's dive into this. Here's my perspective on understanding that `struct bpf_reg_state`: **Understanding the `bpf_reg_state` Structure** Alright, I need to get a handle on what this `bpf_reg_state` struct is all about. The starting point for that should be around line 50. Let me see where this leads, that'll be my starting point. From there, I'll be able to work through the relevant definitions and likely be able to map that information to the broader context of BPF program analysis. |
| 32/3 | 2026/09/28 01:37 | tool | read-file |
0mArgs:{
"File": "include/linux/bpf_verifier.h",
"FirstLine": 50,
"LineCount": 100
}Results: {
"Contents": " 50:\t\tBPF_ITER_STATE_DRAINED,\n 51:\t};\n 52:\t\n 53:\tstruct bpf_reg_state {\n 54:\t\t/* Ordering of fields matters. See states_equal() */\n 55:\t\tenum bpf_reg_type type;\n 56:\t\t/*\n 57:\t\t * Constant delta between \"linked\" scalars with the same ID.\n 58:\t\t */\n 59:\t\ts32 delta;\n 60:\t\tunion {\n 61:\t\t\t/* valid when type == PTR_TO_PACKET */\n 62:\t\t\tint range;\n 63:\t\t\t/*\n 64:\t\t\t * Valid when type == PTR_TO_STACK. Inside the callee two registers\n 65:\t\t\t * can be both PTR_TO_STACK like R1=fp-8 and R2=fp-8, but one of them\n 66:\t\t\t * points to this function stack while another to the caller's stack.\n 67:\t\t\t * To differentiate them 'frameno' is used which is an index in\n 68:\t\t\t * bpf_verifier_state-\u003eframe[] array pointing to bpf_func_state.\n 69:\t\t\t */\n 70:\t\t\tu8 frameno;\n 71:\t\n 72:\t\t\t/*\n 73:\t\t\t * For CONST_PTR_TO_MAP, PTR_TO_MAP_KEY, PTR_TO_MAP_VALUE and\n 74:\t\t\t * PTR_TO_INSN.\n 75:\t\t\t */\n 76:\t\t\tstruct bpf_map *map_ptr;\n 77:\t\n 78:\t\t\t/* for PTR_TO_BTF_ID */\n 79:\t\t\tstruct {\n 80:\t\t\t\tstruct btf *btf;\n 81:\t\t\t\tu32 btf_id;\n 82:\t\t\t};\n 83:\t\n 84:\t\t\tstruct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */\n 85:\t\t\t\tu32 mem_size;\n 86:\t\t\t};\n 87:\t\n 88:\t\t\t/* For dynptr stack slots */\n 89:\t\t\tstruct {\n 90:\t\t\t\tenum bpf_dynptr_type type;\n 91:\t\t\t\t/* A dynptr is 16 bytes so it takes up 2 stack slots.\n 92:\t\t\t\t * We need to track which slot is the first slot\n 93:\t\t\t\t * to protect against cases where the user may try to\n 94:\t\t\t\t * pass in an address starting at the second slot of the\n 95:\t\t\t\t * dynptr.\n 96:\t\t\t\t */\n 97:\t\t\t\tbool first_slot;\n 98:\t\t\t} dynptr;\n 99:\t\n 100:\t\t\t/* For bpf_iter stack slots */\n 101:\t\t\tstruct {\n 102:\t\t\t\t/* BTF container and BTF type ID describing\n 103:\t\t\t\t * struct bpf_iter_\u003ctype\u003e of an iterator state\n 104:\t\t\t\t */\n 105:\t\t\t\tstruct btf *btf;\n 106:\t\t\t\tu32 btf_id;\n 107:\t\t\t\t/* packing following two fields to fit iter state into 16 bytes */\n 108:\t\t\t\tenum bpf_iter_state state:2;\n 109:\t\t\t\tint depth:30;\n 110:\t\t\t} iter;\n 111:\t\n 112:\t\t\t/* For irq stack slots */\n 113:\t\t\tstruct {\n 114:\t\t\t\tenum {\n 115:\t\t\t\t\tIRQ_NATIVE_KFUNC,\n 116:\t\t\t\t\tIRQ_LOCK_KFUNC,\n 117:\t\t\t\t} kfunc_class;\n 118:\t\t\t} irq;\n 119:\t\n 120:\t\t\t/* Max size from any of the above. */\n 121:\t\t\tstruct {\n 122:\t\t\t\tunsigned long raw1;\n 123:\t\t\t\tunsigned long raw2;\n 124:\t\t\t} raw;\n 125:\t\n 126:\t\t\tu32 subprogno; /* for PTR_TO_FUNC */\n 127:\t\t};\n 128:\t\t/* For scalar types (SCALAR_VALUE), this represents our knowledge of\n 129:\t\t * the actual value.\n 130:\t\t * For pointer types, this represents the variable part of the offset\n 131:\t\t * from the pointed-to object, and is shared with all bpf_reg_states\n 132:\t\t * with the same id as us.\n 133:\t\t */\n 134:\t\tstruct tnum var_off;\n 135:\t\t/* Used to determine if any memory access using this register will\n 136:\t\t * result in a bad access.\n 137:\t\t * These refer to the same value as var_off, not necessarily the actual\n 138:\t\t * contents of the register.\n 139:\t\t */\n 140:\t\tstruct cnum64 r64; /* 64-bit range as circular number */\n 141:\t\tstruct cnum32 r32; /* 32-bit range as circular number */\n 142:\t\t/* For PTR_TO_PACKET, used to find other pointers with the same variable\n 143:\t\t * offset, so they can share range knowledge.\n 144:\t\t * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we\n 145:\t\t * came from, when one is tested for != NULL.\n 146:\t\t * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation\n 147:\t\t * for the purpose of tracking that it's freed.\n 148:\t\t * For PTR_TO_SOCKET this is used to share which pointers retain the\n 149:\t\t * same reference to the socket, to determine proper reference freeing.\n"
} |
| 33/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 124492 output: 28 thoughts: 340 Thoughts: **Analyzing BPF Register State and PTR_TO_STACK Comparison** Okay, let's break this down. I'm looking at the `struct bpf_reg_state` and need to understand the implications of the comparison within the `PTR_TO_STACK` case. I see the key members: `type`, `delta`, the union, `var_off`, `r64`, `r32`, `id`, `parent_id`, `map_uid`, `base`, `step`, and `precise`. The current logic for `PTR_TO_STACK` involves a `memcmp` up to `var_off`, a `range_within` check, a `tnum_in` check on `var_off`, and `check_ids` for `id` and `parent_id`, and a comparison of `frameno`. My immediate thought is that `offsetof(struct bpf_reg_state, var_off)` is a crucial point here. That `offsetof` covers `type`, `delta`, and the union preceding `var_off`, meaning that `memcmp` checks the equality of those three fields. Now, the important question is: what did this `PTR_TO_STACK` case *used* to do before this patch? That's critical for understanding the change. I recall it simply calling `regs_exact(rold, rcur, idmap)`. Right, so I need to go look up the definition of `regs_exact` in `kernel/bpf/states.c` to see how that function worked and understand the functional differences between this new comparison and the older one. |
| 34/3 | 2026/09/28 01:37 | tool | grepper |
0mArgs:{
"Expression": "regs_exact",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/states.c=493=static int clean_verifier_state(struct bpf_verifier_env *env,\n--\nkernel/bpf/states.c-509-\nkernel/bpf/states.c:510:static bool regs_exact(const struct bpf_reg_state *rold,\nkernel/bpf/states.c-511-\t\t const struct bpf_reg_state *rcur,\n--\nkernel/bpf/states.c=527=static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,\n--\nkernel/bpf/states.c-531-\tif (exact == EXACT)\nkernel/bpf/states.c:532:\t\treturn regs_exact(rold, rcur, idmap);\nkernel/bpf/states.c-533-\n--\nkernel/bpf/states.c-681-\tdefault:\nkernel/bpf/states.c:682:\t\treturn regs_exact(rold, rcur, idmap);\nkernel/bpf/states.c-683-\t}\n--\nkernel/bpf/verifier.c=8418=static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-8443- * Check if scalar registers are exact for the purpose of not widening.\nkernel/bpf/verifier.c:8444: * More lenient than regs_exact()\nkernel/bpf/verifier.c-8445- */\n"
} |
| 35/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 125614 output: 36 thoughts: 20 Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person: **Diving into the BPF States Code** Alright, time to get my hands dirty. My instinct is telling me to go straight to `regs_exact` within `kernel/bpf/states.c`. I need to understand precisely how register state is handled, and `regs_exact` likely provides the core logic for ensuring exact register values are tracked, or at least provides the building blocks. I'm guessing this function is central to any kind of precise dataflow analysis or optimizations the BPF verifier might be performing related to register content. I'm expecting to find details around how values are propagated, possibly constraints applied, and maybe how undefined values are represented. Knowing this, I expect I can understand how BPF performs and optimises register states. I anticipate there will be a rich understanding here. Let's see what gems we can find in there! |
| 36/3 | 2026/09/28 01:37 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/states.c",
"FirstLine": 505,
"LineCount": 25
}Results: {
"Contents": " 505:\t\t\t__clean_func_state(env, st-\u003eframe[i], live_regs, i);\n 506:\t\t}\n 507:\t\treturn 0;\n 508:\t}\n 509:\t\n 510:\tstatic bool regs_exact(const struct bpf_reg_state *rold,\n 511:\t\t\t const struct bpf_reg_state *rcur,\n 512:\t\t\t struct bpf_idmap *idmap)\n 513:\t{\n 514:\t\treturn memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 \u0026\u0026\n 515:\t\t check_ids(rold-\u003eid, rcur-\u003eid, idmap) \u0026\u0026\n 516:\t\t check_ids(rold-\u003eparent_id, rcur-\u003eparent_id, idmap) \u0026\u0026\n 517:\t\t check_ids(rold-\u003emap_uid, rcur-\u003emap_uid, idmap);\n 518:\t}\n 519:\t\n 520:\tenum exact_level {\n 521:\t\tNOT_EXACT,\n 522:\t\tEXACT,\n 523:\t\tRANGE_WITHIN\n 524:\t};\n 525:\t\n 526:\t/* Returns true if (rold safe implies rcur safe) */\n 527:\tstatic bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,\n 528:\t\t\t struct bpf_reg_state *rcur, struct bpf_idmap *idmap,\n 529:\t\t\t enum exact_level exact)\n"
} |
| 37/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 126313 output: 33 thoughts: 203 Thoughts: **Analyzing `bpf_reg_state` for Potential Padding and Initialization Quirks** Okay, so I'm digging into this `regs_exact` comparison, specifically this `memcmp` call. It's looking at `rold` and `rcur` up to `offsetof(struct bpf_reg_state, id)`. Hold on a second... are there any hidden landmines in this structure? I need to quickly verify that there's *no* padding between offset 0 and the start of the `id` field within `bpf_reg_state`, or this comparison is going to be fundamentally flawed. I *think* it's clean, but I can't assume. Alright, let's break down `bpf_reg_state` and double-check. I know the type member (`enum bpf_reg_type type;`) is 4 bytes, and `s32 delta;` is also 4 bytes. That gets us to 8 bytes already. Now, there's that union, which I'm familiar with, that's 16 bytes. Inside the union, `u8 frameno;` is only 1 byte, so I'm worried about potential uninitialized data within this union, especially if it relates to `PTR_TO_STACK`. Does `PTR_TO_STACK` actually initialize the *entire* 16 bytes of that union, or just a subset? This is critical! If only a portion is initialized, then the `memcmp` will behave erratically. I need to trace back where `PTR_TO_STACK` is set in the verifier. So, I need to check where `PTR_TO_STACK` is set or initialized in `verifier.c` and confirm that it takes care of the full 16 bytes. |
| 38/3 | 2026/09/28 01:37 | tool | grepper |
0mArgs:{
"Expression": "-\u003etype = PTR_TO_STACK",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=999=static int mark_stack_slots_iter(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1019-\t\t__mark_reg_known_zero(st);\nkernel/bpf/verifier.c:1020:\t\tst-\u003etype = PTR_TO_STACK; /* we don't have dedicated reg type */\nkernel/bpf/verifier.c-1021-\t\tif (is_kfunc_rcu_protected(meta)) {\n--\nkernel/bpf/verifier.c=1132=static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1153-\t__mark_reg_known_zero(st);\nkernel/bpf/verifier.c:1154:\tst-\u003etype = PTR_TO_STACK; /* we don't have dedicated reg type */\nkernel/bpf/verifier.c-1155-\tst-\u003eid = id;\n"
} |
| 39/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 127208 output: 33 thoughts: 18 Thoughts: Here's a summary of my thought process, as requested: **Tracing Register Initialization** Okay, so I need to figure out where the `R10` or `PTR_TO_STACK` registers are being initialized. My immediate goal is to understand their initial state, which is crucial for tracing execution and debugging. I'm focusing on their first assignment. Knowing this will give me a base to work from. Let's see how they come to be. |
| 40/3 | 2026/09/28 01:37 | tool | grepper |
0mArgs:{
"Expression": "PTR_TO_STACK",
"PathPrefix": "kernel/bpf/verifier.c"
}Results: {
"Output": "kernel/bpf/verifier.c=61=static bool bpf_global_percpu_ma_set;\n--\nkernel/bpf/verifier.c-98- * that it wants to construct a pointer to some element within stack.\nkernel/bpf/verifier.c:99: * So after 2nd insn, the register R1 has type PTR_TO_STACK\nkernel/bpf/verifier.c-100- * (and -20 constant is saved for further stack bounds checking).\n--\nkernel/bpf/verifier.c-107- * When verifier sees load or store instructions the type of base register\nkernel/bpf/verifier.c:108: * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are\nkernel/bpf/verifier.c-109- * four pointer types recognized by check_mem_access() function.\n--\nkernel/bpf/verifier.c-118- * It means that the register type passed to this function must be\nkernel/bpf/verifier.c:119: * PTR_TO_STACK and it will be used inside the function as\nkernel/bpf/verifier.c-120- * 'pointer to map element key'\n--\nkernel/bpf/verifier.c-145- * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR\nkernel/bpf/verifier.c:146: * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK\nkernel/bpf/verifier.c-147- * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP\n--\nkernel/bpf/verifier.c-152- *\nkernel/bpf/verifier.c:153: * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2-\u003etype == PTR_TO_STACK, ok so far,\nkernel/bpf/verifier.c-154- * Now verifier checks that [R2, R2 + map's key_size) are within stack limits\n--\nkernel/bpf/verifier.c=999=static int mark_stack_slots_iter(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1019-\t\t__mark_reg_known_zero(st);\nkernel/bpf/verifier.c:1020:\t\tst-\u003etype = PTR_TO_STACK; /* we don't have dedicated reg type */\nkernel/bpf/verifier.c-1021-\t\tif (is_kfunc_rcu_protected(meta)) {\n--\nkernel/bpf/verifier.c=1132=static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1153-\t__mark_reg_known_zero(st);\nkernel/bpf/verifier.c:1154:\tst-\u003etype = PTR_TO_STACK; /* we don't have dedicated reg type */\nkernel/bpf/verifier.c-1155-\tst-\u003eid = id;\n--\nkernel/bpf/verifier.c=2370=static void init_reg_state(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2380-\t/* frame pointer */\nkernel/bpf/verifier.c:2381:\tregs[BPF_REG_FP].type = PTR_TO_STACK;\nkernel/bpf/verifier.c-2382-\tmark_reg_known_zero(env, regs, BPF_REG_FP);\n--\nkernel/bpf/verifier.c=3689=static int check_stack_write_fixed_off(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-3774-\t\t}\nkernel/bpf/verifier.c:3775:\t\tif (state != cur \u0026\u0026 reg-\u003etype == PTR_TO_STACK) {\nkernel/bpf/verifier.c-3776-\t\t\tverbose(env, \"cannot spill pointers to stack into stack frame of the caller\\n\");\n--\nkernel/bpf/verifier.c=5407=static int check_ptr_alignment(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-5434-\t\tbreak;\nkernel/bpf/verifier.c:5435:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-5436-\t\tpointer_desc = \"stack \";\n--\nkernel/bpf/verifier.c=6922=static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno,\n--\nkernel/bpf/verifier.c-7061-\nkernel/bpf/verifier.c:7062:\t} else if (reg-\u003etype == PTR_TO_STACK) {\nkernel/bpf/verifier.c-7063-\t\t/* Basic bounds checks. */\n--\nkernel/bpf/verifier.c-7177-\nkernel/bpf/verifier.c:7178:\tif (!err \u0026\u0026 bpf_is_mem_insn(\u0026env-\u003eprog-\u003einsnsi[insn_idx]) \u0026\u0026 ptr_type != PTR_TO_STACK)\nkernel/bpf/verifier.c-7179-\t\tmark_non_stack_access(env, insn_idx);\n--\nkernel/bpf/verifier.c=7570=static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-7628-\t\t\t\t\t max_access);\nkernel/bpf/verifier.c:7629:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-7630-\t\treturn check_stack_range_initialized(\n--\nkernel/bpf/verifier.c-7658-\t\t\treg_type_str(env, reg-\u003etype));\nkernel/bpf/verifier.c:7659:\t\tverbose(env, \"expected=%s\\n\", reg_type_str(env, PTR_TO_STACK));\nkernel/bpf/verifier.c-7660-\t\treturn -EACCES;\n--\nkernel/bpf/verifier.c=7747=static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-7767-\t */\nkernel/bpf/verifier.c:7768:\tsize = (!meta \u0026\u0026 base_type(reg-\u003etype) == PTR_TO_STACK) ? -(int)mem_size : mem_size;\nkernel/bpf/verifier.c-7769-\n--\nkernel/bpf/verifier.c=8144=__printf(6, 7) static void bpf_diag_call_arg_fmt(struct bpf_verifier_env *env, u32 insn_idx,\n--\nkernel/bpf/verifier.c-8156- *\nkernel/bpf/verifier.c:8157: * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK\nkernel/bpf/verifier.c-8158- * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.\n--\nkernel/bpf/verifier.c-8160- * In both cases we deal with the first 8 bytes, but need to mark the next 8\nkernel/bpf/verifier.c:8161: * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of\nkernel/bpf/verifier.c-8162- * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.\n--\nkernel/bpf/verifier.c=8171=static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-8176-\nkernel/bpf/verifier.c:8177:\tif (reg-\u003etype != PTR_TO_STACK \u0026\u0026 reg-\u003etype != CONST_PTR_TO_DYNPTR) {\nkernel/bpf/verifier.c-8178-\t\tverbose(env,\n--\nkernel/bpf/verifier.c-8191-\t *\nkernel/bpf/verifier.c:8192:\t *\t\t Currently, this is only possible with PTR_TO_STACK\nkernel/bpf/verifier.c-8193-\t *\t\t pointing to a region of at least 16 bytes which doesn't\n--\nkernel/bpf/verifier.c-8225-\t} else /* OBJ_RELEASE and None case from above */ {\nkernel/bpf/verifier.c:8226:\t\t/* For the reg-\u003etype == PTR_TO_STACK case, bpf_dynptr is never const */\nkernel/bpf/verifier.c-8227-\t\tif (reg-\u003etype == CONST_PTR_TO_DYNPTR \u0026\u0026 (arg_type \u0026 OBJ_RELEASE)) {\n--\nkernel/bpf/verifier.c=8308=static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx,\n--\nkernel/bpf/verifier.c-8315-\nkernel/bpf/verifier.c:8316:\tif (reg-\u003etype != PTR_TO_STACK) {\nkernel/bpf/verifier.c-8317-\t\tverbose(env, \"%s expected pointer to an iterator on stack\\n\",\n--\nkernel/bpf/verifier.c=8641=static bool arg_type_is_raw_mem(enum bpf_arg_type type)\n--\nkernel/bpf/verifier.c-8645-\t * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be\nkernel/bpf/verifier.c:8646:\t * passed as a PTR_TO_STACK that reaches check_stack_range_initialized().\nkernel/bpf/verifier.c-8647-\t */\n--\nkernel/bpf/verifier.c=8797=static const struct bpf_reg_types mem_types = {\nkernel/bpf/verifier.c-8798-\t.types = {\nkernel/bpf/verifier.c:8799:\t\tPTR_TO_STACK,\nkernel/bpf/verifier.c-8800-\t\tPTR_TO_PACKET,\n--\nkernel/bpf/verifier.c=8838=static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };\nkernel/bpf/verifier.c:8839:static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };\nkernel/bpf/verifier.c-8840-static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };\n--\nkernel/bpf/verifier.c=8876=static const struct bpf_reg_types dynptr_types = {\nkernel/bpf/verifier.c-8877-\t.types = {\nkernel/bpf/verifier.c:8878:\t\tPTR_TO_STACK,\nkernel/bpf/verifier.c-8879-\t\tCONST_PTR_TO_DYNPTR,\n--\nkernel/bpf/verifier.c=8883=static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {\n--\nkernel/bpf/verifier.c-8902-\t[ARG_PTR_TO_FUNC]\t\t= \u0026func_ptr_types,\nkernel/bpf/verifier.c:8903:\t[ARG_PTR_TO_STACK]\t\t= \u0026stack_ptr_types,\nkernel/bpf/verifier.c-8904-\t[ARG_PTR_TO_CONST_STR]\t\t= \u0026const_str_ptr_types,\n--\nkernel/bpf/verifier.c=9137=static int check_func_arg_reg_off(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-9155-\t\t */\nkernel/bpf/verifier.c:9156:\t\tif (arg_type_is_dynptr(arg_type) \u0026\u0026 type == PTR_TO_STACK)\nkernel/bpf/verifier.c-9157-\t\t\treturn 0;\n--\nkernel/bpf/verifier.c-9171-\t/* Pointer types where both fixed and variable offset is explicitly allowed: */\nkernel/bpf/verifier.c:9172:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-9173-\tcase PTR_TO_PACKET:\n--\nkernel/bpf/verifier.c=9286=static int get_constant_map_key(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-9302-\t\treturn -EOPNOTSUPP;\nkernel/bpf/verifier.c:9303:\tif (key-\u003etype != PTR_TO_STACK)\nkernel/bpf/verifier.c-9304-\t\treturn -EOPNOTSUPP;\n--\nkernel/bpf/verifier.c=11656=static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)\n--\nkernel/bpf/verifier.c-11668-\tfor (i = 0; i \u003c nregs; i++) {\nkernel/bpf/verifier.c:11669:\t\tif (callee-\u003eregs[ret_regs[i]].type != PTR_TO_STACK)\nkernel/bpf/verifier.c-11670-\t\t\tcontinue;\n--\nkernel/bpf/verifier.c=14434=s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-14529-\t\tbreak;\nkernel/bpf/verifier.c:14530:\tcase ARG_PTR_TO_STACK:\nkernel/bpf/verifier.c-14531-\t\t/*\n--\nkernel/bpf/verifier.c=15362=static int retrieve_ptr_limit(const struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-15368-\tswitch (ptr_reg-\u003etype) {\nkernel/bpf/verifier.c:15369:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-15370-\t\t/* Offset 0 is out-of-bounds, but acceptable start for the\n--\nkernel/bpf/verifier.c=15634=static int sanitize_check_bounds(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-15646-\tswitch (dst_reg-\u003etype) {\nkernel/bpf/verifier.c:15647:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-15648-\t\tif (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,\n--\nkernel/bpf/verifier.c=15715=static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-15776-\tcase PTR_TO_MAP_KEY:\nkernel/bpf/verifier.c:15777:\tcase PTR_TO_STACK:\nkernel/bpf/verifier.c-15778-\tcase PTR_TO_PACKET_META:\n--\nkernel/bpf/verifier.c-15901-\t\t */\nkernel/bpf/verifier.c:15902:\t\tif (ptr_reg-\u003etype == PTR_TO_STACK) {\nkernel/bpf/verifier.c-15903-\t\t\tverbose(env, \"R%d subtraction from stack pointer prohibited\\n\",\n--\nkernel/bpf/verifier.c=18149=static int check_cond_jmp_op(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-18207-\nkernel/bpf/verifier.c:18208:\t\tif (src_reg-\u003etype == PTR_TO_STACK)\nkernel/bpf/verifier.c-18209-\t\t\tinsn_flags |= INSN_F_SRC_REG_STACK;\nkernel/bpf/verifier.c:18210:\t\tif (dst_reg-\u003etype == PTR_TO_STACK)\nkernel/bpf/verifier.c-18211-\t\t\tinsn_flags |= INSN_F_DST_REG_STACK;\n--\nkernel/bpf/verifier.c-18217-\nkernel/bpf/verifier.c:18218:\t\tif (dst_reg-\u003etype == PTR_TO_STACK)\nkernel/bpf/verifier.c-18219-\t\t\tinsn_flags |= INSN_F_DST_REG_STACK;\n"
} |
| 41/3 | 2026/09/28 01:37 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 131731 output: 43 thoughts: 1250 Thoughts: **Deep Dive into BPF Verifier State and BTF Struct Access** Okay, let's break this down. First, I noticed that `regs_exact` already uses `memcmp` up to `offsetof(struct bpf_reg_state, id)` to check if two `bpf_reg_state` structures are identical. And hey, `offsetof(struct bpf_reg_state, var_off)` is *before* `offsetof(struct bpf_reg_state, id)`. Then, I questioned the specific check used by `regsafe` for `PTR_TO_STACK`. It seems a bit redundant, doesn't it? Diving deeper into `struct bpf_reg_state`, I needed to understand what's inside the union starting at `offsetof(struct bpf_reg_state, var_off)`. Lines 53 to 134 reveal: `type`, `delta`, and a union containing `frameno`. Wait a second! `frameno` is just a byte (`u8`) within this union at offset 8, after the `enum bpf_reg_type type` (4 bytes) and `s32 delta` (4 bytes). The union, in total, is 16 bytes. My next question: if `frameno` is set (e.g., when a register is `PTR_TO_STACK`), are the other parts of the union zeroed? I believe the answer is yes, because `bpf_verifier_state` instances are zeroed during allocation via `kzalloc`. And, considering that `regs_exact` has been using `memcmp` up to `offsetof(struct bpf_reg_state, id)` for years in the BPF verifier, I can see that it's an even larger area that it has been matching for a long time. Now, let's shift to the `btf_struct_access` function in `kernel/bpf/btf.c`. I saw it uses `struct array_access arrays[MAX_ARRAYS_WALK];` on the stack. The critical thing here is how this array is initialized and used. It's initialized by `u32 arrays_cnt = 0;`. Then in `push_array`, it increments arrays_cnt to store data into the array. Examining the code, `arrays` is only read up to `arrays_cnt`. So, it seems like the uninitialized elements of `arrays` are never actually read! Lastly, let's think about `check_add_overflow`. I need to confirm that `asize` and `esize` are always initialized on success within `__btf_resolve_size`. Let's dig into `kernel/bpf/btf.c` and make sure. It should be written in such a way that if there is a success, then it must be initialized. |
| 42/3 | 2026/09/28 01:38 | tool | grepper |
0mError:no matches Args: {
"Expression": "const struct btf_type \\*__btf_resolve_size",
"PathPrefix": "kernel/bpf/btf.c"
}Results: {
"error": "no matches"
} |
| 43/3 | 2026/09/28 01:38 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 133658 output: 36 thoughts: 24 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person: **Navigating the BTF Landscape: Pinpointing `__btf_resolve_size`** Right, let's get down to brass tacks. I need to dig into the guts of BTF, and specifically, I'm after `__btf_resolve_size`. It's a key function, likely involved in resolving sizes within BTF type definitions. My hunch is it's handling the translation of type information or the calculation of sizes based on the BTF metadata. Given its name, it’s almost certainly nestled within the `kernel/bpf/btf.c` file. Time to crack open the source and see what's what. Let's see how it handles the details of the size resolution process. I'm expecting to find intricate logic for handling various BTF type codes and their associated size calculation methods. Understanding this function will shed a lot of light on how the BPF infrastructure interprets and uses BTF information. I am expecting to find within this function some complex recursion, or pointer dereferencing, and probably some careful handling of error conditions and undefined behaviour. |
| 44/3 | 2026/09/28 01:38 | tool | grepper |
0mArgs:{
"Expression": "__btf_resolve_size",
"PathPrefix": "kernel/bpf/btf.c"
}Results: {
"Output": "kernel/bpf/btf.c=2101=static const struct btf_type *\nkernel/bpf/btf.c:2102:__btf_resolve_size(const struct btf *btf, const struct btf_type *type,\nkernel/bpf/btf.c-2103-\t\t u32 *type_size, const struct btf_type **elem_type,\n--\nkernel/bpf/btf.c=2172=btf_resolve_size(const struct btf *btf, const struct btf_type *type,\n--\nkernel/bpf/btf.c-2174-{\nkernel/bpf/btf.c:2175:\treturn __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);\nkernel/bpf/btf.c-2176-}\n--\nkernel/bpf/btf.c=7547=static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,\n--\nkernel/bpf/btf.c-7665-\nkernel/bpf/btf.c:7666:\t\tmtype = __btf_resolve_size(btf, mtype, \u0026msize,\nkernel/bpf/btf.c-7667-\t\t\t\t\t \u0026elem_type, \u0026elem_id, \u0026total_nelems,\n--\nkernel/bpf/btf.c-7681-\nkernel/bpf/btf.c:7682:\t\t\t/* __btf_resolve_size() above helps to\nkernel/bpf/btf.c-7683-\t\t\t * linearize a multi-dimensional array.\n--\nkernel/bpf/btf.c=7814=int btf_struct_access(struct bpf_verifier_log *log,\n--\nkernel/bpf/btf.c-7926-\t\t/*\nkernel/bpf/btf.c:7927:\t\t * 'arrays' records top-level arrays only, use __btf_resolve_size()\nkernel/bpf/btf.c-7928-\t\t * to get flattened representation.\n--\nkernel/bpf/btf.c-7930-\t\tt = btf_type_by_id(btf, arrays[i].id);\nkernel/bpf/btf.c:7931:\t\tif (IS_ERR(__btf_resolve_size(btf, t, \u0026asize, NULL, \u0026elem_id, NULL, NULL)) ||\nkernel/bpf/btf.c-7932-\t\t IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, elem_id), \u0026esize)))\n"
} |
| 45/3 | 2026/09/28 01:38 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 134671 output: 38 thoughts: 22 Thoughts: Okay, let's dive into this. Here's my thought process: **Diving into `__btf_resolve_size`** Alright, time to get down to brass tacks. I need to get a handle on what's happening, so my focus is immediately shifting to line 2101 and the `__btf_resolve_size` implementation. It's the key to understanding the underlying behavior, so I need to analyze its code. From that, I will be able to form some meaningful thoughts. |
| 46/3 | 2026/09/28 01:38 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 2101,
"LineCount": 40
}Results: {
"Contents": "2101:\tstatic const struct btf_type *\n2102:\t__btf_resolve_size(const struct btf *btf, const struct btf_type *type,\n2103:\t\t\t u32 *type_size, const struct btf_type **elem_type,\n2104:\t\t\t u32 *elem_id, u32 *total_nelems, u32 *type_id)\n2105:\t{\n2106:\t\tconst struct btf_type *array_type = NULL;\n2107:\t\tconst struct btf_array *array = NULL;\n2108:\t\tu32 i, size, nelems = 1, id = 0;\n2109:\t\n2110:\t\tfor (i = 0; i \u003c MAX_RESOLVE_DEPTH; i++) {\n2111:\t\t\tswitch (BTF_INFO_KIND(type-\u003einfo)) {\n2112:\t\t\t/* type-\u003esize can be used */\n2113:\t\t\tcase BTF_KIND_INT:\n2114:\t\t\tcase BTF_KIND_STRUCT:\n2115:\t\t\tcase BTF_KIND_UNION:\n2116:\t\t\tcase BTF_KIND_ENUM:\n2117:\t\t\tcase BTF_KIND_FLOAT:\n2118:\t\t\tcase BTF_KIND_ENUM64:\n2119:\t\t\t\tsize = type-\u003esize;\n2120:\t\t\t\tgoto resolved;\n2121:\t\n2122:\t\t\tcase BTF_KIND_PTR:\n2123:\t\t\t\tsize = sizeof(void *);\n2124:\t\t\t\tgoto resolved;\n2125:\t\n2126:\t\t\t/* Modifiers */\n2127:\t\t\tcase BTF_KIND_TYPEDEF:\n2128:\t\t\tcase BTF_KIND_VOLATILE:\n2129:\t\t\tcase BTF_KIND_CONST:\n2130:\t\t\tcase BTF_KIND_RESTRICT:\n2131:\t\t\tcase BTF_KIND_TYPE_TAG:\n2132:\t\t\t\tid = type-\u003etype;\n2133:\t\t\t\ttype = btf_type_by_id(btf, type-\u003etype);\n2134:\t\t\t\tbreak;\n2135:\t\n2136:\t\t\tcase BTF_KIND_ARRAY:\n2137:\t\t\t\tif (!array_type)\n2138:\t\t\t\t\tarray_type = type;\n2139:\t\t\t\tarray = btf_type_array(type);\n2140:\t\t\t\tif (nelems \u0026\u0026 array-\u003enelems \u003e U32_MAX / nelems)\n"
} |
| 47/3 | 2026/09/28 01:38 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 135518 output: 38 thoughts: 39 Thoughts: Okay, let's break this down. **Diving into `__btf_resolve_size` and the 'resolved:' Label** Alright, so I'm focusing on the `__btf_resolve_size` function. The key line that's grabbing my attention is where it sets `*type_size = size;` at the `resolved:` label. Now, before I jump to any conclusions, I need to make sure I completely understand what's happening at that `resolved:` point. I need to refresh my understanding of the local context to ensure I haven't missed a crucial detail, especially since I'm trying to determine the correct size of a BTF type. I'll take a quick scan to make sure I'm capturing all the relevant state. Let's see what's leading up to that assignment. |
| 48/3 | 2026/09/28 01:39 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 2140,
"LineCount": 40
}Results: {
"Contents": "2140:\t\t\t\tif (nelems \u0026\u0026 array-\u003enelems \u003e U32_MAX / nelems)\n2141:\t\t\t\t\treturn ERR_PTR(-EINVAL);\n2142:\t\t\t\tnelems *= array-\u003enelems;\n2143:\t\t\t\ttype = btf_type_by_id(btf, array-\u003etype);\n2144:\t\t\t\tbreak;\n2145:\t\n2146:\t\t\t/* type without size */\n2147:\t\t\tdefault:\n2148:\t\t\t\treturn ERR_PTR(-EINVAL);\n2149:\t\t\t}\n2150:\t\t}\n2151:\t\n2152:\t\treturn ERR_PTR(-EINVAL);\n2153:\t\n2154:\tresolved:\n2155:\t\tif (nelems \u0026\u0026 size \u003e U32_MAX / nelems)\n2156:\t\t\treturn ERR_PTR(-EINVAL);\n2157:\t\n2158:\t\t*type_size = nelems * size;\n2159:\t\tif (total_nelems)\n2160:\t\t\t*total_nelems = nelems;\n2161:\t\tif (elem_type)\n2162:\t\t\t*elem_type = type;\n2163:\t\tif (elem_id)\n2164:\t\t\t*elem_id = array ? array-\u003etype : 0;\n2165:\t\tif (type_id \u0026\u0026 id)\n2166:\t\t\t*type_id = id;\n2167:\t\n2168:\t\treturn array_type ? : type;\n2169:\t}\n2170:\t\n2171:\tconst struct btf_type *\n2172:\tbtf_resolve_size(const struct btf *btf, const struct btf_type *type,\n2173:\t\t\t u32 *type_size)\n2174:\t{\n2175:\t\treturn __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);\n2176:\t}\n2177:\t\n2178:\tstatic u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)\n2179:\t{\n"
} |
| 49/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 136352 output: 30 thoughts: 1102 Thoughts: **Deep Dive into Loop Iteration Handling**
Okay, so `__btf_resolve_size` successfully sets `*type_size` and `*elem_id` when it's not NULL, good.
Now, let's look at `imod()`. It's pretty straightforward; it just computes the modulo operation using `div_s64_rem`. No surprises there.
The real interest lies in `bpf_loop_iters`. I need to figure out how its members are initialized. It looks like `min_header_count`, `max_header_count`, and `pre_cond` are all the key fields. From the code, it's used in `handle_loop_entry_exit`. Specifically, `bpf_compute_loop_iters` is called, and that's the crucial function. I need to be sure the function initializes `iters` when it returns 1.
Let's dig into `bpf_compute_loop_iters`. Several conditions can cause it to return early, usually 0. However, when it does proceed, `linear_latch` becomes the key, leading to a call to `compute_max_iters`. Ah, here's where the magic happens! `compute_max_iters` definitely initializes all the fields of `iters` with these lines:
```c
iters->max_header_count = max_iters + (base == 0 ? 1 : 0);
iters->min_header_count = loop->exits_cnt == 1 ? iters->max_header_count : 0;
iters->pre_cond = base == 0;
return true;
```
Excellent! `iters` is fully initialized when `compute_max_iters` returns true. Now, back to `handle_loop_entry_exit`. After the call to `bpf_compute_loop_iters`, there's a check for `terminates`. If it's true (meaning `err == 1`), the state is split and widened, and `iters` is passed to `loop_stack_push`.
But, what happens when `terminates` is false? That's the important point. The call to `loop_stack_push` still occurs. Inside `loop_stack_push`, if `terminates` is false, `loop_stack[cnt].iters` is set to `(struct bpf_loop_iters){}` - a zero-initialized struct. Therefore, the function's argument `iters` is not read when the loop does not terminate!
So, the values from `iters` *are* used when the loop *does* terminate, or `terminates` is true, because in that case, the fields of `iters` have been correctly initialized.
Now I need to remember `bpf_func_state`. It contains `loop_stack_cnt` and `loop_stack[LOOP_STACK_SIZE]`, which I need to understand. I need to see *how* it's allocated, copied, and initialized. I'll search for calls to `copy_func_state` or look at how `bpf_func_state` is copied or initialized in `verifier.c` or `states.c`. I have more questions to answer here!
|
| 50/3 | 2026/09/28 01:39 | tool | grepper |
0mArgs:{
"Expression": "copy_func_state",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=1684=void bpf_free_verifier_state(struct bpf_verifier_state *state,\n--\nkernel/bpf/verifier.c-1701- */\nkernel/bpf/verifier.c:1702:static int copy_func_state(struct bpf_func_state *dst,\nkernel/bpf/verifier.c-1703-\t\t\t const struct bpf_func_state *src)\n--\nkernel/bpf/verifier.c=1711=int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n--\nkernel/bpf/verifier.c-1752-\t\t}\nkernel/bpf/verifier.c:1753:\t\terr = copy_func_state(dst, src-\u003eframe[i]);\nkernel/bpf/verifier.c-1754-\t\tif (err)\n"
} |
| 51/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 138430 output: 37 thoughts: 30 Thoughts: Okay, here's my summary, taking on the persona you requested: **Diving into `copy_func_state` in `kernel/bpf/verifier.c`** Alright, let's pull up that code. I need to refresh my memory on how the verifier handles state copying, specifically that `copy_func_state` function. It's in `kernel/bpf/verifier.c`, and I believe it's around line 1702, though I'll double-check once I'm there. I remember it being critical for proper function call handling and ensuring the caller's state is correctly propagated to and from the callee. Understanding this function is going to be key to whatever I'm troubleshooting or analyzing – either it's an optimization question, a potential bug, or perhaps I'm trying to improve the verifier's overall efficiency. I need to see how it's handling registers, stack variables, and any other relevant state data. Time to dig in! |
| 52/3 | 2026/09/28 01:39 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 1695,
"LineCount": 40
}Results: {
"Contents": "1695:\t\tif (free_self)\n1696:\t\t\tkfree(state);\n1697:\t}\n1698:\t\n1699:\t/* copy verifier state from src to dst growing dst stack space\n1700:\t * when necessary to accommodate larger src stack\n1701:\t */\n1702:\tstatic int copy_func_state(struct bpf_func_state *dst,\n1703:\t\t\t\t const struct bpf_func_state *src)\n1704:\t{\n1705:\t\tmemcpy(dst, src, offsetof(struct bpf_func_state, stack));\n1706:\t\t/* Instruction accounting is path-local, not part of verifier state. */\n1707:\t\tdst-\u003einsns_subtotal = 0;\n1708:\t\treturn copy_stack_state(dst, src);\n1709:\t}\n1710:\t\n1711:\tint bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n1712:\t\t\t\t const struct bpf_verifier_state *src)\n1713:\t{\n1714:\t\tstruct bpf_func_state *dst;\n1715:\t\tint i, err;\n1716:\t\n1717:\t\tdst_state-\u003ejmp_history = copy_array(dst_state-\u003ejmp_history, src-\u003ejmp_history,\n1718:\t\t\t\t\t\t src-\u003ejmp_history_cnt, sizeof(*dst_state-\u003ejmp_history),\n1719:\t\t\t\t\t\t GFP_KERNEL_ACCOUNT);\n1720:\t\tif (!dst_state-\u003ejmp_history)\n1721:\t\t\treturn -ENOMEM;\n1722:\t\tdst_state-\u003ejmp_history_cnt = src-\u003ejmp_history_cnt;\n1723:\t\n1724:\t\t/* if dst has more stack frames then src frame, free them, this is also\n1725:\t\t * necessary in case of exceptional exits using bpf_throw.\n1726:\t\t */\n1727:\t\tfor (i = src-\u003ecurframe + 1; i \u003c= dst_state-\u003ecurframe; i++) {\n1728:\t\t\tfree_func_state(dst_state-\u003eframe[i]);\n1729:\t\t\tdst_state-\u003eframe[i] = NULL;\n1730:\t\t}\n1731:\t\terr = copy_reference_state(dst_state, src);\n1732:\t\tif (err)\n1733:\t\t\treturn err;\n1734:\t\tdst_state-\u003especulative = src-\u003especulative;\n"
} |
| 53/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 139379 output: 34 thoughts: 320 Thoughts: **Analyzing `copy_func_state` and Potential Data Corruption** Okay, let's break this down. I'm looking at `copy_func_state` and, specifically, that `memcpy` call: `memcpy(dst, src, offsetof(struct bpf_func_state, stack));`. This is the crux of the issue. The goal is to copy some of the contents of the `bpf_func_state` structure from `src` to `dst`. I need to ensure that the correct fields are being copied. Now, glancing at the `struct bpf_func_state` definition, I see the critical comment: `/* The following fields should be last. See copy_func_state() */`. This comment is a red flag. It suggests that the order of the structure members is carefully considered in relation to how `copy_func_state` works. Looking closer, I see `loop_stack_cnt` and `loop_stack` declared *before* the comment and before `stack`, which is the starting point for the copy. This raises a concern because `memcpy(dst, src, offsetof(struct bpf_func_state, stack));` is copying up to the `stack` member, it looks like it is going to copy `loop_stack_cnt` and the `loop_stack` array as well! So, this `memcpy` is including more data than intended. Hold on a second... are those loop structures initialized when `bpf_func_state` is allocated? If they aren't, this could lead to a serious vulnerability. That `memcpy` is copying potentially uninitialized data. Time to backtrack and trace where `bpf_func_state` is actually allocated. I need to understand the memory context to gauge the severity of this potential issue. |
| 54/3 | 2026/09/28 01:39 | tool | grepper |
0mArgs:{
"Expression": "kzalloc.*bpf_func_state",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=21082=static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sleepable)\n--\nkernel/bpf/verifier.c-21102-\tstate-\u003ein_sleepable = is_sleepable;\nkernel/bpf/verifier.c:21103:\tstate-\u003eframe[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT);\nkernel/bpf/verifier.c-21104-\tif (!state-\u003eframe[0]) {\n"
} |
| 55/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 140274 output: 35 thoughts: 16 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person: **Analyzing `struct bpf_func_state` Allocations** Right, so I'm thinking about the `struct bpf_func_state`. My immediate focus is on understanding *where* this struct is allocated within the system. I need to get a comprehensive view of all its instances. This isn't just a casual curiosity; I need to track its lifecycle and understand how it's used and potentially abused in order to find any underlying issues with its usage. I need to map the code. Therefore, my thought process zeroes in on tracking all allocations of this struct. I want to see every single call to `kmalloc`, `kzalloc`, or any other memory allocation function that returns a `struct bpf_func_state*`. I'm going to have to do a deep dive through the kernel code to find all of them. I'll need to consider how these instances are freed, too, and what kind of potential memory safety issues might be present if the allocations aren't done correctly. I need to think about potential memory leaks, double-frees, or any other related allocation issues. |
| 56/3 | 2026/09/28 01:39 | tool | grepper |
0mArgs:{
"Expression": "struct bpf_func_state",
"PathPrefix": "kernel/bpf/verifier.c"
}Results: {
"Output": "\nFull output is too long, showing 500 out of 576 lines.\nUse more precise expression if possible.\n\nkernel/bpf/verifier.c=596=bool bpf_is_may_goto_insn(struct bpf_insn *insn)\n--\nkernel/bpf/verifier.c-600-\nkernel/bpf/verifier.c:601:static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)\nkernel/bpf/verifier.c-602-{\n--\nkernel/bpf/verifier.c=725=static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:726:\t\t\t\t struct bpf_func_state *state, int spi);\nkernel/bpf/verifier.c-727-\nkernel/bpf/verifier.c=728=static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-731-{\nkernel/bpf/verifier.c:732:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-733-\tint spi, i, err, parent_id = 0;\n--\nkernel/bpf/verifier.c=810=static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-811-{\nkernel/bpf/verifier.c:812:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-813-\tint spi;\n--\nkernel/bpf/verifier.c=841=static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id)\n--\nkernel/bpf/verifier.c-843-\tstruct bpf_stack_state *stack;\nkernel/bpf/verifier.c:844:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-845-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=860=static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:861:\t\t\t\t struct bpf_func_state *state, int spi)\nkernel/bpf/verifier.c-862-{\n--\nkernel/bpf/verifier.c=933=static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-934-{\nkernel/bpf/verifier.c:935:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-936-\tstruct bpf_stack_state *slot;\n--\nkernel/bpf/verifier.c=964=static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-965-{\nkernel/bpf/verifier.c:966:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-967-\tint spi;\n--\nkernel/bpf/verifier.c=999=static int mark_stack_slots_iter(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1003-{\nkernel/bpf/verifier.c:1004:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1005-\tint spi, i, j, id;\n--\nkernel/bpf/verifier.c=1042=static int unmark_stack_slots_iter(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1044-{\nkernel/bpf/verifier.c:1045:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1046-\tint spi, i, j;\n--\nkernel/bpf/verifier.c=1070=static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1072-{\nkernel/bpf/verifier.c:1073:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1074-\tint spi, i, j;\n--\nkernel/bpf/verifier.c=1097=static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-1099-{\nkernel/bpf/verifier.c:1100:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1101-\tint spi, i, j;\n--\nkernel/bpf/verifier.c=1132=static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-1136-{\nkernel/bpf/verifier.c:1137:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1138-\tstruct bpf_stack_state *slot;\n--\nkernel/bpf/verifier.c=1165=static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-1167-{\nkernel/bpf/verifier.c:1168:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1169-\tstruct bpf_stack_state *slot;\n--\nkernel/bpf/verifier.c=1230=static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-1231-{\nkernel/bpf/verifier.c:1232:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1233-\tstruct bpf_stack_state *slot;\n--\nkernel/bpf/verifier.c=1254=static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)\nkernel/bpf/verifier.c-1255-{\nkernel/bpf/verifier.c:1256:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-1257-\tstruct bpf_stack_state *slot;\n--\nkernel/bpf/verifier.c=1393=static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)\n--\nkernel/bpf/verifier.c-1409-\nkernel/bpf/verifier.c:1410:static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)\nkernel/bpf/verifier.c-1411-{\n--\nkernel/bpf/verifier.c=1435=static int resize_reference_state(struct bpf_verifier_state *state, size_t n)\n--\nkernel/bpf/verifier.c-1448- */\nkernel/bpf/verifier.c:1449:static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)\nkernel/bpf/verifier.c-1450-{\n--\nkernel/bpf/verifier.c=1473=static int grow_stack_arg_slots(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:1474:\t\t\t\tstruct bpf_func_state *state, int cnt)\nkernel/bpf/verifier.c-1475-{\n--\nkernel/bpf/verifier.c=1651=static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,\n--\nkernel/bpf/verifier.c-1667-\nkernel/bpf/verifier.c:1668:static void free_func_state(struct bpf_func_state *state)\nkernel/bpf/verifier.c-1669-{\n--\nkernel/bpf/verifier.c=1684=void bpf_free_verifier_state(struct bpf_verifier_state *state,\n--\nkernel/bpf/verifier.c-1701- */\nkernel/bpf/verifier.c:1702:static int copy_func_state(struct bpf_func_state *dst,\nkernel/bpf/verifier.c:1703:\t\t\t const struct bpf_func_state *src)\nkernel/bpf/verifier.c-1704-{\nkernel/bpf/verifier.c:1705:\tmemcpy(dst, src, offsetof(struct bpf_func_state, stack));\nkernel/bpf/verifier.c-1706-\t/* Instruction accounting is path-local, not part of verifier state. */\n--\nkernel/bpf/verifier.c=1711=int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,\n--\nkernel/bpf/verifier.c-1713-{\nkernel/bpf/verifier.c:1714:\tstruct bpf_func_state *dst;\nkernel/bpf/verifier.c-1715-\tint i, err;\n--\nkernel/bpf/verifier.c=1765=struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx)\n--\nkernel/bpf/verifier.c-1767-\tstruct bpf_verifier_state *cur = env-\u003ecur_state;\nkernel/bpf/verifier.c:1768:\tstruct bpf_func_state *state = cur-\u003eframe[cur-\u003ecurframe];\nkernel/bpf/verifier.c-1769-\n--\nkernel/bpf/verifier.c=2370=static void init_reg_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:2371:\t\t\t struct bpf_func_state *state)\nkernel/bpf/verifier.c-2372-{\n--\nkernel/bpf/verifier.c=2395=static void init_func_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:2396:\t\t\t struct bpf_func_state *state,\nkernel/bpf/verifier.c-2397-\t\t\t int callsite, int frameno, int subprogno)\n--\nkernel/bpf/verifier.c=2409=static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-2413-\tstruct bpf_verifier_stack_elem *elem;\nkernel/bpf/verifier.c:2414:\tstruct bpf_func_state *frame;\nkernel/bpf/verifier.c-2415-\n--\nkernel/bpf/verifier.c=3397=static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,\n--\nkernel/bpf/verifier.c-3400-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:3401:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-3402-\n--\nkernel/bpf/verifier.c=3617=static void save_register_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:3618:\t\t\t\tstruct bpf_func_state *state,\nkernel/bpf/verifier.c-3619-\t\t\t\tint spi, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c=3649=static void check_fastcall_stack_contract(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:3650:\t\t\t\t\t struct bpf_func_state *state, int insn_idx, int off)\nkernel/bpf/verifier.c-3651-{\n--\nkernel/bpf/verifier.c-3672-\nkernel/bpf/verifier.c:3673:static void scrub_special_slot(struct bpf_func_state *state, int spi)\nkernel/bpf/verifier.c-3674-{\n--\nkernel/bpf/verifier.c=3689=static int check_stack_write_fixed_off(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-3690-\t\t\t\t /* stack frame we're writing to */\nkernel/bpf/verifier.c:3691:\t\t\t\t struct bpf_func_state *state,\nkernel/bpf/verifier.c-3692-\t\t\t\t int off, int size, int value_regno,\n--\nkernel/bpf/verifier.c-3694-{\nkernel/bpf/verifier.c:3695:\tstruct bpf_func_state *cur; /* state of the current function */\nkernel/bpf/verifier.c-3696-\tint i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;\n--\nkernel/bpf/verifier.c=3833=static int check_stack_write_var_off(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-3834-\t\t\t\t /* func where register points to */\nkernel/bpf/verifier.c:3835:\t\t\t\t struct bpf_func_state *state,\nkernel/bpf/verifier.c-3836-\t\t\t\t struct bpf_reg_state *ptr_reg, int off, int size,\n--\nkernel/bpf/verifier.c-3838-{\nkernel/bpf/verifier.c:3839:\tstruct bpf_func_state *cur; /* state of the current function */\nkernel/bpf/verifier.c-3840-\tint min_off, max_off;\n--\nkernel/bpf/verifier.c=3965=static int mark_reg_stack_read(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-3966-\t\t\t /* func where src register points to */\nkernel/bpf/verifier.c:3967:\t\t\t struct bpf_func_state *ptr_state,\nkernel/bpf/verifier.c-3968-\t\t\t int min_off, int max_off, int dst_regno)\n--\nkernel/bpf/verifier.c-3970-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:3971:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-3972-\tint i, slot, spi;\n--\nkernel/bpf/verifier.c=4067=static int check_stack_read_fixed_off(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-4068-\t\t\t\t /* func where src register points to */\nkernel/bpf/verifier.c:4069:\t\t\t\t struct bpf_func_state *reg_state,\nkernel/bpf/verifier.c-4070-\t\t\t\t int off, int size, int dst_regno)\n--\nkernel/bpf/verifier.c-4072-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:4073:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-4074-\tint i, slot = -off - 1, spi = slot / BPF_REG_SIZE;\n--\nkernel/bpf/verifier.c=4255=static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-4257-{\nkernel/bpf/verifier.c:4258:\tstruct bpf_func_state *ptr_state = bpf_func(env, reg);\nkernel/bpf/verifier.c-4259-\tint err;\n--\nkernel/bpf/verifier.c=4287=static int check_stack_read(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-4290-{\nkernel/bpf/verifier.c:4291:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-4292-\tint err;\n--\nkernel/bpf/verifier.c=4349=static int check_stack_write(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-4352-{\nkernel/bpf/verifier.c:4353:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-4354-\tint err;\n--\nkernel/bpf/verifier.c-4374- */\nkernel/bpf/verifier.c:4375:static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state,\nkernel/bpf/verifier.c-4376-\t\t\t\t int off, struct bpf_reg_state *value_reg)\n--\nkernel/bpf/verifier.c-4417- */\nkernel/bpf/verifier.c:4418:static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state,\nkernel/bpf/verifier.c-4419-\t\t\t\tint off, int dst_regno)\n--\nkernel/bpf/verifier.c-4423-\tint spi = off / BPF_REG_SIZE - 1;\nkernel/bpf/verifier.c:4424:\tstruct bpf_func_state *caller, *cur;\nkernel/bpf/verifier.c-4425-\tstruct bpf_reg_state *arg;\n--\nkernel/bpf/verifier.c=4448=static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx)\nkernel/bpf/verifier.c-4449-{\nkernel/bpf/verifier.c:4450:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-4451-\tint spi = arg_idx - MAX_BPF_FUNC_REG_ARGS;\n--\nkernel/bpf/verifier.c=4457=static int mark_arg_precision(struct bpf_verifier_env *env, argno_t argno)\n--\nkernel/bpf/verifier.c-4465-\nkernel/bpf/verifier.c:4466:static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller,\nkernel/bpf/verifier.c-4467-\t\t\t\t int nargs, const char *callee_name, const struct btf *btf,\n--\nkernel/bpf/verifier.c-4490-\nkernel/bpf/verifier.c:4491:static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller,\nkernel/bpf/verifier.c-4492-\t\t\t\t\t struct bpf_reg_state *regs, int arg)\n--\nkernel/bpf/verifier.c=6614=static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-6615- s64 off,\nkernel/bpf/verifier.c:6616: struct bpf_func_state *state,\nkernel/bpf/verifier.c-6617- enum bpf_access_type t)\n--\nkernel/bpf/verifier.c=6636=static int check_stack_access_within_bounds(\n--\nkernel/bpf/verifier.c-6640-{\nkernel/bpf/verifier.c:6641:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-6642-\ts64 min_off, max_off;\n--\nkernel/bpf/verifier.c=7187=static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-7191-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:7192:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-7193-\tstruct bpf_reg_state *regs = cur_regs(env);\n--\nkernel/bpf/verifier.c=7234=static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-7237-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:7238:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-7239-\tstruct bpf_reg_state *regs = cur_regs(env);\n--\nkernel/bpf/verifier.c=7438=static int check_stack_range_initialized(\n--\nkernel/bpf/verifier.c-7442-{\nkernel/bpf/verifier.c:7443:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-7444-\tint err, min_off, max_off, i, j, slot, spi;\n--\nkernel/bpf/verifier.c=8171=static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg,\n--\nkernel/bpf/verifier.c-8261-\t\tif (reg-\u003etype != CONST_PTR_TO_DYNPTR) {\nkernel/bpf/verifier.c:8262:\t\t\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-8263-\n--\nkernel/bpf/verifier.c=8308=static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx,\n--\nkernel/bpf/verifier.c-8310-{\nkernel/bpf/verifier.c:8311:\tstruct bpf_func_state *state = bpf_func(env, reg);\nkernel/bpf/verifier.c-8312-\tconst struct btf_type *t;\n--\nkernel/bpf/verifier.c=8464=static int widen_imprecise_scalars(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-8467-{\nkernel/bpf/verifier.c:8468:\tstruct bpf_func_state *fold, *fcur;\nkernel/bpf/verifier.c-8469-\tint i, fr, num_slots;\n--\nkernel/bpf/verifier.c=8581=static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,\n--\nkernel/bpf/verifier.c-8584-\tstruct bpf_verifier_state *cur_st = env-\u003ecur_state, *queued_st, *prev_st;\nkernel/bpf/verifier.c:8585:\tstruct bpf_func_state *cur_fr = cur_st-\u003eframe[cur_st-\u003ecurframe], *queued_fr;\nkernel/bpf/verifier.c-8586-\tstruct bpf_reg_state *cur_iter, *queued_iter;\n--\nkernel/bpf/verifier.c=9286=static int get_constant_map_key(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-9290-{\nkernel/bpf/verifier.c:9291:\tstruct bpf_func_state *state = bpf_func(env, key);\nkernel/bpf/verifier.c-9292-\tstruct bpf_stack_state *ss;\n--\nkernel/bpf/verifier.c=9403=static int check_func_arg(struct bpf_verifier_env *env, u32 arg, u32 slot, u32 prev_slot,\n--\nkernel/bpf/verifier.c-9408-\tconst struct bpf_func_proto *fn = meta-\u003efn;\nkernel/bpf/verifier.c:9409:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-9410-\tstruct bpf_reg_state *regs = cur_regs(env);\n--\nkernel/bpf/verifier.c=9982=static u32 kfunc_proto_slots(const struct btf *btf, const struct btf_type *func_proto)\n--\nkernel/bpf/verifier.c-9993-/* The argument slot @slot holds an eightbyte of a by-value argument. */\nkernel/bpf/verifier.c:9994:static int check_arg_extra_slot(struct bpf_verifier_env *env, struct bpf_func_state *caller,\nkernel/bpf/verifier.c-9995-\t\t\t\tu32 slot, struct bpf_call_arg_meta *meta)\n--\nkernel/bpf/verifier.c=10011=static int check_func_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-10014-\tu32 slot = 0, prev_slot = 0, proto_slots, nslots;\nkernel/bpf/verifier.c:10015:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-10016-\tconst struct btf_param *args = NULL;\n--\nkernel/bpf/verifier.c=10071=static int mark_raw_stack(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-10073-{\nkernel/bpf/verifier.c:10074:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-10075-\tu32 slot;\n--\nkernel/bpf/verifier.c=10532=static void clear_all_pkt_pointers(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-10533-{\nkernel/bpf/verifier.c:10534:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-10535-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=10550=static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)\nkernel/bpf/verifier.c-10551-{\nkernel/bpf/verifier.c:10552:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-10553-\tstruct bpf_reg_state *reg = \u0026state-\u003eregs[regn];\n--\nkernel/bpf/verifier.c=10623=static int release_reference(struct bpf_verifier_env *env, int id)\n--\nkernel/bpf/verifier.c-10628-\tstruct bpf_stack_state *stack;\nkernel/bpf/verifier.c:10629:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-10630-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=10694=static void invalidate_non_owning_refs(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-10695-{\nkernel/bpf/verifier.c:10696:\tstruct bpf_func_state *unused;\nkernel/bpf/verifier.c-10697-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=10707=static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-10709-\tstruct bpf_stack_state *stack;\nkernel/bpf/verifier.c:10710:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-10711-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=10724=static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)\nkernel/bpf/verifier.c-10725-{\nkernel/bpf/verifier.c:10726:\tstruct bpf_func_state *state;\nkernel/bpf/verifier.c-10727-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=10764=static void invalidate_outgoing_stack_args(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:10765:\t\t\t\t\t struct bpf_func_state *state)\nkernel/bpf/verifier.c-10766-{\n--\nkernel/bpf/verifier.c=10775=typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:10776:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:10777:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-10778-\t\t\t\t int insn_idx);\n--\nkernel/bpf/verifier.c=10780=static int set_callee_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:10781:\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:10782:\t\t\t struct bpf_func_state *callee, int insn_idx);\nkernel/bpf/verifier.c-10783-\nkernel/bpf/verifier.c=10784=static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,\n--\nkernel/bpf/verifier.c-10787-{\nkernel/bpf/verifier.c:10788:\tstruct bpf_func_state *caller, *callee;\nkernel/bpf/verifier.c-10789-\tint err;\n--\nkernel/bpf/verifier.c=10832=static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,\n--\nkernel/bpf/verifier.c-10836-\tstruct bpf_subprog_info *sub = subprog_info(env, subprog);\nkernel/bpf/verifier.c:10837:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-10838-\tstruct bpf_verifier_log *log = \u0026env-\u003elog;\n--\nkernel/bpf/verifier.c=11010=static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-11014-\tstruct bpf_verifier_state *state = env-\u003ecur_state, *callback_state;\nkernel/bpf/verifier.c:11015:\tstruct bpf_func_state *caller, *callee;\nkernel/bpf/verifier.c-11016-\tint err;\n--\nkernel/bpf/verifier.c=11096=static int check_static_func_call(struct bpf_verifier_env *env, int subprog,\n--\nkernel/bpf/verifier.c-11101-\tu16 callee_incoming, stack_arg_cnt;\nkernel/bpf/verifier.c:11102:\tstruct bpf_func_state *caller;\nkernel/bpf/verifier.c-11103-\tint err;\n--\nkernel/bpf/verifier.c=11141=static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-11144-\tstruct bpf_verifier_state *state = env-\u003ecur_state;\nkernel/bpf/verifier.c:11145:\tstruct bpf_func_state *caller;\nkernel/bpf/verifier.c-11146-\tint err, subprog, target_insn;\n--\nkernel/bpf/verifier.c=11253=static int check_func_callx(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-11255-{\nkernel/bpf/verifier.c:11256:\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-11257-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=11304=int map_set_for_each_callback_args(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11305:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11306:\t\t\t\t struct bpf_func_state *callee)\nkernel/bpf/verifier.c-11307-{\n--\nkernel/bpf/verifier.c=11334=static int set_callee_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11335:\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11336:\t\t\t struct bpf_func_state *callee, int insn_idx)\nkernel/bpf/verifier.c-11337-{\n--\nkernel/bpf/verifier.c=11348=static int set_map_elem_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11349:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11350:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11351-\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11374=static int set_loop_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11375:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11376:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11377-\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11396=static int set_timer_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11397:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11398:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11399-\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11431=static int set_find_vma_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11432:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11433:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11434-\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11459=static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11460:\t\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11461:\t\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11462-\t\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11482=static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11483:\t\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11484:\t\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11485-\t\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11515=static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11516:\t\t\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11517:\t\t\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11518-\t\t\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11550=static int set_rcu_callback_state(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11551:\t\t\t\t struct bpf_func_state *caller,\nkernel/bpf/verifier.c:11552:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c-11553-\t\t\t\t int insn_idx)\n--\nkernel/bpf/verifier.c=11586=static void account_processed_insn(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-11587-{\nkernel/bpf/verifier.c:11588:\tstruct bpf_func_state *frame = cur_func(env);\nkernel/bpf/verifier.c-11589-\n--\nkernel/bpf/verifier.c=11595=static void account_processed_insns(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c:11596:\t\t\t\t struct bpf_func_state *callee,\nkernel/bpf/verifier.c:11597:\t\t\t\t struct bpf_func_state *caller)\nkernel/bpf/verifier.c-11598-{\n--\nkernel/bpf/verifier.c=11627=static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-11630-\tstruct bpf_insn *insn = env-\u003eprog-\u003einsnsi;\nkernel/bpf/verifier.c:11631:\tstruct bpf_func_state *callee;\nkernel/bpf/verifier.c-11632-\tint kfunc_btf_id;\n--\nkernel/bpf/verifier.c=11656=static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)\n--\nkernel/bpf/verifier.c-11658-\tstruct bpf_verifier_state *state = env-\u003ecur_state, *prev_st;\nkernel/bpf/verifier.c:11659:\tstruct bpf_func_state *caller, *callee;\nkernel/bpf/verifier.c-11660-\tstruct bpf_reg_state *r0;\n--\nkernel/bpf/verifier.c=13947=static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)\nkernel/bpf/verifier.c-13948-{\nkernel/bpf/verifier.c:13949:\tstruct bpf_func_state *unused;\nkernel/bpf/verifier.c-13950-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=14808=static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-15270-\tif (proto_slots \u003e MAX_BPF_FUNC_REG_ARGS) {\nkernel/bpf/verifier.c:15271:\t\tstruct bpf_func_state *caller = cur_func(env);\nkernel/bpf/verifier.c-15272-\t\tstruct bpf_subprog_info *caller_info = \u0026env-\u003esubprog_info[caller-\u003esubprogno];\n--\nkernel/bpf/verifier.c=15715=static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-15719-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:15720:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-15721-\tstruct bpf_reg_state *regs = state-\u003eregs, *dst_reg;\n--\nkernel/bpf/verifier.c=16890=static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-16893-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\nkernel/bpf/verifier.c:16894:\tstruct bpf_func_state *state = vstate-\u003eframe[vstate-\u003ecurframe];\nkernel/bpf/verifier.c-16895-\tstruct bpf_reg_state *regs = state-\u003eregs, *dst_reg, *src_reg;\n\n"
} |
| 57/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 151739 output: 38 thoughts: 44 Thoughts: Okay, let's dive into this. Here's how I'd approach this, thinking aloud: **Digging into `setup_func_entry` and `callee` Allocation** Alright, I need to understand where `callee` is allocated and how `setup_func_entry` works in relation to it. The key here is to trace the memory allocation. Given the context, I suspect it's done in the verifier. So, my instinct is to immediately jump to the `verifier.c` file and zero in on that crucial section of the code. Let's start with lines 10780-10800 in `verifier.c`. Hopefully, the allocation process of `callee` is handled in this region, or at least the function call is present that I need to find to trace the flow. This should provide the necessary clues. |
| 58/3 | 2026/09/28 01:39 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 10780,
"LineCount": 35
}Results: {
"Contents": "10780:\tstatic int set_callee_state(struct bpf_verifier_env *env,\n10781:\t\t\t\t struct bpf_func_state *caller,\n10782:\t\t\t\t struct bpf_func_state *callee, int insn_idx);\n10783:\t\n10784:\tstatic int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,\n10785:\t\t\t\t set_callee_state_fn set_callee_state_cb,\n10786:\t\t\t\t struct bpf_verifier_state *state)\n10787:\t{\n10788:\t\tstruct bpf_func_state *caller, *callee;\n10789:\t\tint err;\n10790:\t\n10791:\t\tif (state-\u003ecurframe + 1 \u003e= MAX_CALL_FRAMES) {\n10792:\t\t\tverbose(env, \"the call stack of %d frames is too deep\\n\",\n10793:\t\t\t\tstate-\u003ecurframe + 2);\n10794:\t\t\treturn -E2BIG;\n10795:\t\t}\n10796:\t\n10797:\t\tif (state-\u003eframe[state-\u003ecurframe + 1]) {\n10798:\t\t\tverifier_bug(env, \"Frame %d already allocated\", state-\u003ecurframe + 1);\n10799:\t\t\treturn -EFAULT;\n10800:\t\t}\n10801:\t\n10802:\t\tcaller = state-\u003eframe[state-\u003ecurframe];\n10803:\t\tcallee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT);\n10804:\t\tif (!callee)\n10805:\t\t\treturn -ENOMEM;\n10806:\t\tstate-\u003eframe[state-\u003ecurframe + 1] = callee;\n10807:\t\n10808:\t\t/* callee cannot access r0, r6 - r9 for reading and has to write\n10809:\t\t * into its own stack before reading from it.\n10810:\t\t * callee can read/write into caller's stack\n10811:\t\t */\n10812:\t\tinit_func_state(env, callee,\n10813:\t\t\t\t/* remember the callsite, it will be used by bpf_exit */\n10814:\t\t\t\tcallsite,\n"
} |
| 59/3 | 2026/09/28 01:39 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 152643 output: 27 thoughts: 2436 Thoughts: **KMSAN Consideration for BPF Verifier Changes** Okay, let's break this down systematically. I'm focusing on whether this patch series introduces any *new* risks of uninitialized memory access detectable only by KMSAN, as per the guidelines. First, I see that `bpf_func_state` is always `kzalloc`'d. This means the `loop_stack` and `loop_stack_cnt` are initialized to zero, which is good. I then quickly check the `loop_stack_safe` function in `states.c` to confirm that the `loop_stack` is correctly handled, which it appears to be. The verifier tracks the count and doesn't read out of bounds. Next, I look at `range_within` to see if there are any potential issues related to uninitialized data in its logic. The crucial point here is `old->step`. I confirm that `old->step` is >= 1 due to the logic in `reg_step_reset`, `scalar_step_add`, `scalar_step_mul`, `scalar_step_lsh`, `bpf_reg_union` and `bpf_set_reg_range`. It looks like if `old->step` is 1 or greater, the conditional in `range_within` is safe. The conditions for `range_within` all seem reasonable. Now, the core question: does this series touch any of the key KMSAN risk areas? Let's walk through the KMSAN rules and relate them to BPF: 1. **Kernel structures to user space:** Not directly, I don't see anything explicitly copying new structures to user space. However, this doesn't mean that uninitialized data can't propagate to a user-visible structure if there's a bug in the code. I must keep this in mind! 2. **Conditional logic on uninitialized variables:** The code doesn't seem to have direct conditional logic on potentially uninitialized variables. 3. **Allocation/Initialization of complex data structures:** The code does not introduce new data structure allocations. 4. **Bounds checks/Lengths:** This is the critical area. The code *could* alter bounds checks, lengths, or logic in a way that *allows* surrounding code to access uninitialized bytes. This is where the BPF verifier comes in. Here's the key question: Does the BPF verifier *itself* track uninitialized stack memory? YES, it does! There are functions like `check_stack_read_fixed_off`, `check_stack_read_var_off`, `check_stack_range_initialized`, etc. The verifier explicitly prevents BPF programs from reading their own uninitialized stack memory. But here is where my concerns kick in. The BPF program stack *is* kernel memory. This is allocated in the kernel as part of the execution frame or on the kernel stack during JIT execution. Therefore, if there's a *verifier bug* that *allows* a BPF program to read uninitialized stack memory and then pass that data to a kernel helper (or, heaven forbid, user space), this *could* be a KMSAN issue! So, the issue is not necessarily the direct presence of uninitialized data *in the code*, but the *possibility* that changes in this series could create a *verifier bug* that permits a read of uninitialized *kernel* memory (that happens to be a BPF stack location). If the BPF program reads kernel memory that is not initialized, then the KMSAN could be triggered! I need to search for examples of KMSAN-related BPF bugs. I'll search syzkaller and the kernel's git repository for "kmsan bpf" to see if there are known issues in this area. If there are, I should then verify the impact of this code to KMSAN. If I don't see any, then this code series should not expose any vulnerabilities. |
| 60/3 | 2026/09/28 01:40 | tool | grepper |
0mArgs:{
"Expression": "kmsan",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/core.c=2412=static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \\\n--\nkernel/bpf/core.c-2416-\\\nkernel/bpf/core.c:2417:\tkmsan_unpoison_memory(stack, sizeof(stack)); \\\nkernel/bpf/core.c-2418-\tFP = (u64) (unsigned long) \u0026stack[ARRAY_SIZE(stack)]; \\\n--\nkernel/bpf/core.c=2425=static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \\\n--\nkernel/bpf/core.c-2430-\\\nkernel/bpf/core.c:2431:\tkmsan_unpoison_memory(stack, sizeof(stack)); \\\nkernel/bpf/core.c-2432-\tFP = (u64) (unsigned long) \u0026stack[ARRAY_SIZE(stack)]; \\\n"
} |
| 61/3 | 2026/09/28 01:40 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 156250 output: 33 thoughts: 1843 Thoughts: **Analyzing BPF Verifier for Uninitialized Memory**
Okay, so I'm looking at this BPF code and my initial thought is, "Ah, `kmsan_unpoison_memory` unpoisons the BPF stack! That's good". And, JIT code isn't even instrumented by KMSAN, so that's another thing I don't have to worry about. But, the next question is the verifier itself. Let's see if this patch introduces any new uninitialized memory issues within the verifier.
First, I need to check if this patch is returning anything to user space. It looks like the patch modifies BPF verifier logic within a few files, but `bpf_check` just returns an integer error code or 0. Log messages are generated using `bpf_log` which uses format strings. So no immediate concerns there.
Next I need to make sure that the patch uses initialized memory when it allocates kernel structs. I'll need to double check any allocations:
* `struct dfs_state *state` in `bpf_compute_postorder`: `kvzalloc_objs`
* `postorder_nums`, `postorder`: `kvzalloc_objs`
* `num_preds` in `compute_predecessors`: `kvcalloc`
* `result` in `compute_predecessors`: `kvzalloc`
* `idoms` in `bpf_compute_idoms`: `kvcalloc`
* `dfs.dfs_pos`, `dfs.state`, `dfs.stack` in `bpf_compute_loops`: `kvcalloc`
* `loop->exits` in `add_exit`: `kvcalloc`
* `aux[h].loop` in `mark_as_header`: `kvzalloc_obj`
* `heap->elements` in `bpf_min_heap_push`: initialized at index `heap->count`
* `scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);`
* `scev->envs = kvcalloc(...)`
* `scev->discovered = kvcalloc(...)`
* `e = kzalloc(...)` in `get_loop_env`
* `tmp = krealloc(envs, ...)` in `get_loop_env` -> explicitly initialized `tmp->entries[cnt]`
* `cur_env = kzalloc(...)` in `compute_scev_for_loop`
* `old_env = kzalloc(...)` in `compute_scev_for_loop`
* `new_sl = kzalloc_obj(...)` in `bpf_split_cur_state`
* `bpf_copy_verifier_state` copies fields.
Okay, everything there looks good, it's all initialized.
Now I need to drill down into `bpf_loop_iters`. Let's see... it's used in `handle_loop_entry_exit`:
```c
struct bpf_loop_iters iters;
err = bpf_compute_loop_iters(env, env->cur_state, &iters);
```
I need to make sure `iters` is never used uninitialized. Let's see how `iters` is handled in `handle_loop_entry_exit`:
```c
if (has_entered_loop(env)) {
if (env->log.level & BPF_LOG_LEVEL2)
verbose(env, "entering loop %d\n", bpf_loop_at_index(env, env->insn_idx));
err = bpf_compute_loop_iters(env, env->cur_state, &iters);
if (err < 0)
return err;
terminates = err == 1;
if (terminates) {
err = bpf_split_cur_state(env);
if (err)
return err;
err = bpf_widen_scev_regs(env, cur, cur->parent, &iters);
if (err < 0)
return err;
}
err = loop_stack_push(env, env->cur_state->parent, terminates, &iters);
if (err)
return err;
}
```
So, if `bpf_compute_loop_iters` returns 1, then it assigns `1` to `err`. Then it assigns `err == 1` to `terminates`. If `terminates` is
|
| 62/3 | 2026/09/28 01:41 | tool | grepper |
0mArgs:{
"Expression": "insn_aux_data = ",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/fixups.c=360=static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,\n--\nkernel/bpf/fixups.c-380-\nkernel/bpf/fixups.c:381:\t\tenv-\u003einsn_aux_data = new_data;\nkernel/bpf/fixups.c-382-\t}\n"
} |
| 63/3 | 2026/09/28 01:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 159274 output: 34 thoughts: 19 Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience: **Tracing the Genesis of `env->insn_aux_data`** Okay, so I'm diving into this code, and the first thing I need to pin down is the initial allocation of `env->insn_aux_data`. Understanding where this memory gets conjured is critical; it's the foundation upon which so much else is built. I'm going to follow the trail from the very beginning. I'll need to know whether it's statically allocated, dynamically allocated via `malloc` or its kin, or maybe even mapped from a specific region. Identifying the allocation strategy will significantly inform my assumptions about its lifecycle, potential for aliasing issues, and, of course, the implications for debugging any related problems down the line. Knowing where it comes from is the first step. |
| 64/3 | 2026/09/28 01:41 | tool | grepper |
0mArgs:{
"Expression": "insn_aux_data",
"PathPrefix": "kernel/bpf/verifier.c"
}Results: {
"Output": "kernel/bpf/verifier.c=224=static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg);\nkernel/bpf/verifier.c-225-\nkernel/bpf/verifier.c:226:static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,\nkernel/bpf/verifier.c-227-\t\t\t struct bpf_map *map,\n--\nkernel/bpf/verifier.c-235-\nkernel/bpf/verifier.c:236:static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)\nkernel/bpf/verifier.c-237-{\n--\nkernel/bpf/verifier.c=3406=static void mark_indirect_target(struct bpf_verifier_env *env, int idx)\nkernel/bpf/verifier.c-3407-{\nkernel/bpf/verifier.c:3408:\tenv-\u003einsn_aux_data[idx].indirect_target = true;\nkernel/bpf/verifier.c-3409-}\n--\nkernel/bpf/verifier.c=3411=static void mark_non_stack_access(struct bpf_verifier_env *env, int idx)\nkernel/bpf/verifier.c-3412-{\nkernel/bpf/verifier.c:3413:\tenv-\u003einsn_aux_data[idx].non_stack_access = true;\nkernel/bpf/verifier.c-3414-}\n--\nkernel/bpf/verifier.c=3649=static void check_fastcall_stack_contract(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-3652-\tstruct bpf_subprog_info *subprog = \u0026env-\u003esubprog_info[state-\u003esubprogno];\nkernel/bpf/verifier.c:3653:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-3654-\tint i;\n--\nkernel/bpf/verifier.c=3689=static int check_stack_write_fixed_off(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-3740-\t\tif (sanitize)\nkernel/bpf/verifier.c:3741:\t\t\tenv-\u003einsn_aux_data[insn_idx].nospec_result = true;\nkernel/bpf/verifier.c-3742-\t}\n--\nkernel/bpf/verifier.c=5103=static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,\n--\nkernel/bpf/verifier.c-5122-\t\t} else {\nkernel/bpf/verifier.c:5123:\t\t\tenv-\u003einsn_aux_data[insn_idx].ctx_field_size = info-\u003ectx_field_size;\nkernel/bpf/verifier.c-5124-\t\t}\n--\nkernel/bpf/verifier.c=5185=static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,\n--\nkernel/bpf/verifier.c-5215-\tif (valid) {\nkernel/bpf/verifier.c:5216:\t\tenv-\u003einsn_aux_data[insn_idx].ctx_field_size =\nkernel/bpf/verifier.c-5217-\t\t\tinfo.ctx_field_size;\n--\nkernel/bpf/verifier.c=8746=static int get_bpf_res_spin_lock_kfunc_flags(const struct bpf_call_arg_meta *meta);\nkernel/bpf/verifier.c:8747:static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env);\nkernel/bpf/verifier.c-8748-static int process_irq_flag(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c=11348=static int set_map_elem_callback_state(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-11352-{\nkernel/bpf/verifier.c:11353:\tstruct bpf_insn_aux_data *insn_aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-11354-\tstruct bpf_map *map;\n--\nkernel/bpf/verifier.c=11818=record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-11820-{\nkernel/bpf/verifier.c:11821:\tstruct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-11822-\tstruct bpf_map *map = meta-\u003emap.ptr;\n--\nkernel/bpf/verifier.c=11864=record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\n--\nkernel/bpf/verifier.c-11866-{\nkernel/bpf/verifier.c:11867:\tstruct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-11868-\tstruct bpf_reg_state *reg;\n--\nkernel/bpf/verifier.c=12008=static int check_get_func_ip(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-12028-\nkernel/bpf/verifier.c:12029:static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-12030-{\nkernel/bpf/verifier.c:12031:\treturn \u0026env-\u003einsn_aux_data[env-\u003einsn_idx];\nkernel/bpf/verifier.c-12032-}\n--\nkernel/bpf/verifier.c=12145=static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-12230-\tif (!in_sleepable_context(env))\nkernel/bpf/verifier.c:12231:\t\tenv-\u003einsn_aux_data[insn_idx].non_sleepable = true;\nkernel/bpf/verifier.c-12232-\n--\nkernel/bpf/verifier.c-12394-\t\t\treturns_cpu_specific_alloc_ptr = true;\nkernel/bpf/verifier.c:12395:\t\t\tenv-\u003einsn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;\nkernel/bpf/verifier.c-12396-\t\t}\n--\nkernel/bpf/verifier.c=14434=s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-14436-{\nkernel/bpf/verifier.c:14437:\tstruct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-14438-\tconst struct bpf_func_proto *fn;\n--\nkernel/bpf/verifier.c=14560=s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-14562-{\nkernel/bpf/verifier.c:14563:\tstruct bpf_insn_aux_data *aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-14564-\tstruct bpf_call_arg_meta meta;\n--\nkernel/bpf/verifier.c=14637=static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,\nkernel/bpf/verifier.c:14638:\t\t\t struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,\nkernel/bpf/verifier.c-14639-\t\t\t const struct btf_type *ptr_type, struct btf *desc_btf)\n--\nkernel/bpf/verifier.c=14808=static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-14816-\tstruct bpf_call_arg_meta meta;\nkernel/bpf/verifier.c:14817:\tstruct bpf_insn_aux_data *insn_aux;\nkernel/bpf/verifier.c-14818-\tconst char *operation;\n--\nkernel/bpf/verifier.c-14840-\tfunc_name = meta.func_name;\nkernel/bpf/verifier.c:14841:\tinsn_aux = \u0026env-\u003einsn_aux_data[insn_idx];\nkernel/bpf/verifier.c-14842-\n--\nkernel/bpf/verifier.c=15392=static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-15399-\nkernel/bpf/verifier.c:15400:static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,\nkernel/bpf/verifier.c-15401-\t\t\t\t u32 alu_state, u32 alu_limit)\n--\nkernel/bpf/verifier.c=15417=static int sanitize_val_alu(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-15419-{\nkernel/bpf/verifier.c:15420:\tstruct bpf_insn_aux_data *aux = cur_aux(env);\nkernel/bpf/verifier.c-15421-\n--\nkernel/bpf/verifier.c=15433=struct bpf_sanitize_info {\nkernel/bpf/verifier.c:15434:\tstruct bpf_insn_aux_data aux;\nkernel/bpf/verifier.c-15435-\tbool mask_to_left;\n--\nkernel/bpf/verifier.c=15458=static int sanitize_ptr_alu(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-15465-{\nkernel/bpf/verifier.c:15466:\tstruct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : \u0026info-\u003eaux;\nkernel/bpf/verifier.c-15467-\tstruct bpf_verifier_state *vstate = env-\u003ecur_state;\n--\nkernel/bpf/verifier.c=15554=static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-15563-\tif (!vstate-\u003especulative)\nkernel/bpf/verifier.c:15564:\t\tenv-\u003einsn_aux_data[env-\u003einsn_idx].seen = env-\u003epass_cnt;\nkernel/bpf/verifier.c-15565-}\n--\nkernel/bpf/verifier.c=16890=static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-16897-\tbool alu32 = (BPF_CLASS(insn-\u003ecode) != BPF_ALU64);\nkernel/bpf/verifier.c:16898:\tstruct bpf_insn_aux_data *aux = cur_aux(env);\nkernel/bpf/verifier.c-16899-\tu8 opcode = BPF_OP(insn-\u003ecode);\n--\nkernel/bpf/verifier.c=18059=static void collect_linked_regs(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-18063-{\nkernel/bpf/verifier.c:18064:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-18065-\tstruct bpf_func_state *func;\n--\nkernel/bpf/verifier.c=18407=static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)\nkernel/bpf/verifier.c-18408-{\nkernel/bpf/verifier.c:18409:\tstruct bpf_insn_aux_data *aux = cur_aux(env);\nkernel/bpf/verifier.c-18410-\tstruct bpf_reg_state *regs = cur_regs(env);\n--\nkernel/bpf/verifier.c=18935=bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,\n--\nkernel/bpf/verifier.c-19022- * - look for such patterns;\nkernel/bpf/verifier.c:19023: * - mark spill and fill instructions in env-\u003einsn_aux_data[*].fastcall_pattern;\nkernel/bpf/verifier.c:19024: * - mark set env-\u003einsn_aux_data[*].fastcall_spills_num for call instruction;\nkernel/bpf/verifier.c-19025- * - update env-\u003esubprog_info[*]-\u003efastcall_stack_off to find an offset\n--\nkernel/bpf/verifier.c=19053=static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-19114-\t\texpected_regs_mask \u0026= ~BIT(stx-\u003esrc_reg);\nkernel/bpf/verifier.c:19115:\t\tenv-\u003einsn_aux_data[insn_idx - i].fastcall_pattern = 1;\nkernel/bpf/verifier.c:19116:\t\tenv-\u003einsn_aux_data[insn_idx + i].fastcall_pattern = 1;\nkernel/bpf/verifier.c-19117-\t}\n--\nkernel/bpf/verifier.c-19137-\tif (cs.fastcall)\nkernel/bpf/verifier.c:19138:\t\tenv-\u003einsn_aux_data[insn_idx].fastcall_spills_num = i - 1;\nkernel/bpf/verifier.c-19139-\telse\n--\nkernel/bpf/verifier.c=19304=static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,\n--\nkernel/bpf/verifier.c-19306-{\nkernel/bpf/verifier.c:19307:\tenum bpf_reg_type *prev_type = \u0026env-\u003einsn_aux_data[env-\u003einsn_idx].ptr_type;\nkernel/bpf/verifier.c-19308-\n--\nkernel/bpf/verifier.c=19647=static bool has_entered_loop(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-19648-{\nkernel/bpf/verifier.c:19649:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-19650-\tint prev_insn_idx = env-\u003eprev_insn_idx;\n--\nkernel/bpf/verifier.c=19658=static bool is_next_loop_iteration(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-19659-{\nkernel/bpf/verifier.c:19660:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-19661-\tint prev_insn_idx = env-\u003eprev_insn_idx;\n--\nkernel/bpf/verifier.c=19669=static bool has_exited_loop(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-19670-{\nkernel/bpf/verifier.c:19671:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-19672-\tint prev_insn_idx = env-\u003eprev_insn_idx;\n--\nkernel/bpf/verifier.c=19710=static int loop_stack_push(struct bpf_verifier_env *env,\n--\nkernel/bpf/verifier.c-19714-{\nkernel/bpf/verifier.c:19715:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-19716-\tstruct bpf_func_state *frame = cur_func(env);\n--\nkernel/bpf/verifier.c=19762=static int loop_stack_pop(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-19763-{\nkernel/bpf/verifier.c:19764:\tstruct bpf_insn_aux_data *aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-19765-\tstruct bpf_func_state *frame = cur_func(env);\n--\nkernel/bpf/verifier.c=19845=static int do_check(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-19855-\t\tstruct bpf_insn *insn;\nkernel/bpf/verifier.c:19856:\t\tstruct bpf_insn_aux_data *insn_aux;\nkernel/bpf/verifier.c-19857-\t\tint err;\n--\nkernel/bpf/verifier.c-19875-\t\tinsn = \u0026insns[env-\u003einsn_idx];\nkernel/bpf/verifier.c:19876:\t\tinsn_aux = \u0026env-\u003einsn_aux_data[env-\u003einsn_idx];\nkernel/bpf/verifier.c-19877-\n--\nkernel/bpf/verifier.c=20150=static int __check_pseudo_btf_id(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-20151-\t\t\t\t struct bpf_insn *insn,\nkernel/bpf/verifier.c:20152:\t\t\t\t struct bpf_insn_aux_data *aux,\nkernel/bpf/verifier.c-20153-\t\t\t\t struct btf *btf)\n--\nkernel/bpf/verifier.c=20233=static int check_pseudo_btf_id(struct bpf_verifier_env *env,\nkernel/bpf/verifier.c-20234-\t\t\t struct bpf_insn *insn,\nkernel/bpf/verifier.c:20235:\t\t\t struct bpf_insn_aux_data *aux)\nkernel/bpf/verifier.c-20236-{\n--\nkernel/bpf/verifier.c=20734=static int check_and_resolve_insns(struct bpf_verifier_env *env)\n--\nkernel/bpf/verifier.c-20754-\t\tif (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {\nkernel/bpf/verifier.c:20755:\t\t\tstruct bpf_insn_aux_data *aux;\nkernel/bpf/verifier.c-20756-\t\t\tstruct bpf_map *map;\n--\nkernel/bpf/verifier.c-20776-\t\t\tif (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {\nkernel/bpf/verifier.c:20777:\t\t\t\taux = \u0026env-\u003einsn_aux_data[i];\nkernel/bpf/verifier.c-20778-\t\t\t\terr = check_pseudo_btf_id(env, insn, aux);\n--\nkernel/bpf/verifier.c-20784-\t\t\tif (insn[0].src_reg == BPF_PSEUDO_FUNC) {\nkernel/bpf/verifier.c:20785:\t\t\t\taux = \u0026env-\u003einsn_aux_data[i];\nkernel/bpf/verifier.c-20786-\t\t\t\taux-\u003eptr_type = PTR_TO_FUNC;\n--\nkernel/bpf/verifier.c-20824-\nkernel/bpf/verifier.c:20825:\t\t\taux = \u0026env-\u003einsn_aux_data[i];\nkernel/bpf/verifier.c-20826-\t\t\taux-\u003emap_index = map_idx;\n--\nkernel/bpf/verifier.c=21023=static void sanitize_dead_code(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-21024-{\nkernel/bpf/verifier.c:21025:\tstruct bpf_insn_aux_data *aux_data = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-21026-\tstruct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);\n--\nkernel/bpf/verifier.c=22405=static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)\n--\nkernel/bpf/verifier.c-22440-\t} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {\nkernel/bpf/verifier.c:22441:\t\tif (!env-\u003einsn_aux_data[insn_idx].non_sleepable)\nkernel/bpf/verifier.c-22442-\t\t\taddr = (unsigned long)bpf_dynptr_from_file_sleepable;\nkernel/bpf/verifier.c-22443-\t} else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) {\nkernel/bpf/verifier.c:22444:\t\tif (env-\u003einsn_aux_data[insn_idx].non_sleepable)\nkernel/bpf/verifier.c-22445-\t\t\taddr = (unsigned long)bpf_arena_alloc_pages_non_sleepable;\nkernel/bpf/verifier.c-22446-\t} else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) {\nkernel/bpf/verifier.c:22447:\t\tif (env-\u003einsn_aux_data[insn_idx].non_sleepable)\nkernel/bpf/verifier.c-22448-\t\t\taddr = (unsigned long)bpf_arena_free_pages_non_sleepable;\n--\nkernel/bpf/verifier.c-22453-\nkernel/bpf/verifier.c:22454:static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,\nkernel/bpf/verifier.c-22455-\t\t\t\t\t u16 struct_meta_reg,\n--\nkernel/bpf/verifier.c=22471=int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,\n--\nkernel/bpf/verifier.c-22502-\tif (is_bpf_obj_new_kfunc(desc-\u003efunc_id) || is_bpf_percpu_obj_new_kfunc(desc-\u003efunc_id)) {\nkernel/bpf/verifier.c:22503:\t\tstruct btf_struct_meta *kptr_struct_meta = env-\u003einsn_aux_data[insn_idx].kptr_struct_meta;\nkernel/bpf/verifier.c-22504-\t\tstruct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };\nkernel/bpf/verifier.c:22505:\t\tu64 obj_new_size = env-\u003einsn_aux_data[insn_idx].obj_new_size;\nkernel/bpf/verifier.c-22506-\n--\nkernel/bpf/verifier.c-22520-\t\t is_bpf_refcount_acquire_kfunc(desc-\u003efunc_id)) {\nkernel/bpf/verifier.c:22521:\t\tstruct btf_struct_meta *kptr_struct_meta = env-\u003einsn_aux_data[insn_idx].kptr_struct_meta;\nkernel/bpf/verifier.c-22522-\t\tstruct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };\n--\nkernel/bpf/verifier.c-22541-\t\t is_bpf_rbtree_add_kfunc(desc-\u003efunc_id)) {\nkernel/bpf/verifier.c:22542:\t\tstruct btf_struct_meta *kptr_struct_meta = env-\u003einsn_aux_data[insn_idx].kptr_struct_meta;\nkernel/bpf/verifier.c-22543-\t\tint struct_meta_reg = BPF_REG_3;\n--\nkernel/bpf/verifier.c-22560-\nkernel/bpf/verifier.c:22561:\t\t__fixup_collection_insert_kfunc(\u0026env-\u003einsn_aux_data[insn_idx], struct_meta_reg,\nkernel/bpf/verifier.c-22562-\t\t\t\t\t\tnode_offset_reg, insn, insn_buf, cnt);\n--\nkernel/bpf/verifier.c-22646-\nkernel/bpf/verifier.c:22647:\tif (env-\u003einsn_aux_data[insn_idx].arg_prog) {\nkernel/bpf/verifier.c:22648:\t\tu32 regno = env-\u003einsn_aux_data[insn_idx].arg_prog;\nkernel/bpf/verifier.c-22649-\t\tstruct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env-\u003eprog-\u003eaux) };\n--\nkernel/bpf/verifier.c=22838=static void log_program(struct bpf_verifier_env *env)\nkernel/bpf/verifier.c-22839-{\nkernel/bpf/verifier.c:22840:\tstruct bpf_insn_aux_data *insn_aux = env-\u003einsn_aux_data;\nkernel/bpf/verifier.c-22841-\tstruct bpf_insn *insns = env-\u003eprog-\u003einsnsi;\n--\nkernel/bpf/verifier.c-22848-\t\tverbose_linfo(env, i, \" ; \");\nkernel/bpf/verifier.c:22849:\t\tif (env-\u003einsn_aux_data[i].scc)\nkernel/bpf/verifier.c:22850:\t\t\tverbose(env, \"%3d \", env-\u003einsn_aux_data[i].scc);\nkernel/bpf/verifier.c-22851-\t\telse\nkernel/bpf/verifier.c-22852-\t\t\tverbose(env, \" \");\nkernel/bpf/verifier.c:22853:\t\tif (env-\u003einsn_aux_data[i].loop_header \u003e= 0)\nkernel/bpf/verifier.c:22854:\t\t\tverbose(env, \"%3d \", env-\u003einsn_aux_data[i].loop_header);\nkernel/bpf/verifier.c-22855-\t\telse\n--\nkernel/bpf/verifier.c=22876=int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,\n--\nkernel/bpf/verifier.c-22951-\nkernel/bpf/verifier.c:22952:\tlen = env-\u003einsn_aux_data_len = env-\u003eprog-\u003elen;\nkernel/bpf/verifier.c:22953:\tenv-\u003einsn_aux_data =\nkernel/bpf/verifier.c:22954:\t\t__vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len),\nkernel/bpf/verifier.c-22955-\t\t\t GFP_KERNEL_ACCOUNT | __GFP_ZERO);\nkernel/bpf/verifier.c-22956-\tret = -ENOMEM;\nkernel/bpf/verifier.c:22957:\tif (!env-\u003einsn_aux_data)\nkernel/bpf/verifier.c-22958-\t\tgoto skip_full_check;\nkernel/bpf/verifier.c-22959-\tfor (i = 0; i \u003c len; i++)\nkernel/bpf/verifier.c:22960:\t\tenv-\u003einsn_aux_data[i].orig_idx = i;\nkernel/bpf/verifier.c-22961-\tenv-\u003esucc = bpf_iarray_realloc(NULL, 2);\n--\nkernel/bpf/verifier.c-23244-\tbpf_free_subprog_jts(env);\nkernel/bpf/verifier.c:23245:\tif (env-\u003einsn_aux_data)\nkernel/bpf/verifier.c:23246:\t\tbpf_clear_insn_aux_data(env, 0, env-\u003einsn_aux_data_len);\nkernel/bpf/verifier.c:23247:\tvfree(env-\u003einsn_aux_data);\nkernel/bpf/verifier.c-23248-\tkvfree(env-\u003efd_array);\n"
} |
| 65/3 | 2026/09/28 01:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 167384 output: 34 thoughts: 2665 Thoughts: **Deep Dive into Potential BPF Verifier Issues**
Alright, let's dissect this BPF verifier code and see if we can shake out any lurking nasties. First, `env->insn_aux_data` is allocated with `__vmalloc` using `__GFP_ZERO`. Good, that takes care of a huge class of initialization problems. We initialize `loop_header` in `bpf_compute_loops`, and the later cleanup in `bpf_clear_insn_aux_data` seems clean. Specifically, the cleanup logic looks good, and deallocates memory associated with the `loop` field of `bpf_insn_aux_data`.
Now, let's dig into potential uninitialized memory issues. We're looking at various data structures and functions, so let's check:
1. `cnum_defs.h`: Returns a `struct cnum_t` value. Looks fine at first glance.
2. `cnum64_intersect_linear`: Returns a `struct cnum64`. Also, no obvious issues so far.
3. `tnum_alignment`: Returns a `u32` value, seems correct too.
4. `liveness.c`:
* `merge_may_write` properly zeroes `acc` with `bitmap_zero`.
* `compute_may_write_masks`: `half_spis_to_slots` sets bits, and those bitmaps are all zeroed initially.
5. `scev.c`: This is interesting. The `add_expr` function creates a `struct expr`.
* The `struct expr` has padding. On a 64-bit system, the union introduces 4 bytes of padding.
* `expr_hash` uses `e->op`, `e->params[0]`, and `e->params[1]`. `expr_eq` uses `e->op` and `e->imm`. We're not reading the padding.
* When the struct is created, all fields are initialized.
* In `transform_expr_once`, `expr` is snapshotted before the call; the return value `id` is always assigned. So, no problems in this function either.
6. `bpf_split_cur_state`: `kzalloc_obj` is used, so it's initialized.
Finally, we need to make sure `bpf_get_call_summary` correctly initializes members. The function `call_params_mask` uses the function `bpf_get_call_summary` which appears to initialize the `cs.arg_slot_cnt`. And that seems to be the case.
Okay, after this deep dive, things look pretty solid. I don't see any obvious memory safety or initialization bugs.
|
| 66/3 | 2026/09/28 01:41 | tool | grepper |
0mArgs:{
"Expression": "bool bpf_get_call_summary",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/verifier.c=18916=bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)\n--\nkernel/bpf/verifier.c-18934- */\nkernel/bpf/verifier.c:18935:bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,\nkernel/bpf/verifier.c-18936-\t\t\t struct bpf_call_summary *cs)\n"
} |
| 67/3 | 2026/09/28 01:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 170850 output: 38 thoughts: 33 Thoughts: Okay, let's dive into this. Here's my take on those instructions, as if they're my internal thought process: **Diving into the BPF Verifier: A Quick Scan** Alright, I'm going to take a look at `bpf_get_call_summary`. I know it's probably related to how the BPF verifier handles function calls. Line 18935 of `kernel/bpf/verifier.c` is the precise location, so I'll jump there directly. I'm expecting this to be a crucial function for understanding how the verifier assesses the safety and validity of BPF programs that are making function calls, likely to track the different options. It could be parsing arguments, checking the target function, performing some kind of symbolic execution, or simply summarizing the call's effects on program state, and how it is expected to behave. Let's see what the function does exactly. |
| 68/3 | 2026/09/28 01:41 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/verifier.c",
"FirstLine": 18935,
"LineCount": 50
}Results: {
"Contents": "18935:\tbool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,\n18936:\t\t\t\t struct bpf_call_summary *cs)\n18937:\t{\n18938:\t\tstruct bpf_call_arg_meta meta;\n18939:\t\tconst struct bpf_func_proto *fn;\n18940:\t\tint i;\n18941:\t\n18942:\t\tif (bpf_helper_call(call)) {\n18943:\t\t\tif (bpf_get_helper_proto(env, call-\u003eimm, \u0026fn) \u003c 0)\n18944:\t\t\t\t/* error would be reported later */\n18945:\t\t\t\treturn false;\n18946:\t\t\tcs-\u003efastcall = fn-\u003eallow_fastcall \u0026\u0026\n18947:\t\t\t\t (bpf_verifier_inlines_helper_call(env, call-\u003eimm) ||\n18948:\t\t\t\t\tbpf_jit_inlines_helper_call(call-\u003eimm));\n18949:\t\t\tcs-\u003eis_void = fn-\u003eret_type == RET_VOID;\n18950:\t\t\tcs-\u003earg_slot_cnt = 0;\n18951:\t\t\tfor (i = 0; i \u003c ARRAY_SIZE(fn-\u003earg_type); ++i) {\n18952:\t\t\t\tif (fn-\u003earg_type[i] == ARG_UNUSED)\n18953:\t\t\t\t\tbreak;\n18954:\t\t\t\tcs-\u003earg_slot_cnt++;\n18955:\t\t\t}\n18956:\t\t\treturn true;\n18957:\t\t}\n18958:\t\n18959:\t\tif (bpf_pseudo_kfunc_call(call)) {\n18960:\t\t\tint err;\n18961:\t\n18962:\t\t\terr = bpf_fetch_kfunc_arg_meta(env, call-\u003eimm, call-\u003eoff, \u0026meta);\n18963:\t\t\tif (err \u003c 0)\n18964:\t\t\t\t/* error would be reported later */\n18965:\t\t\t\treturn false;\n18966:\t\t\tcs-\u003earg_slot_cnt = kfunc_proto_slots(meta.btf, meta.func_proto);\n18967:\t\t\tcs-\u003efastcall = meta.kfunc_flags \u0026 KF_FASTCALL;\n18968:\t\t\tcs-\u003eis_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto-\u003etype));\n18969:\t\t\treturn true;\n18970:\t\t}\n18971:\t\n18972:\t\treturn false;\n18973:\t}\n18974:\t\n18975:\t/* LLVM define a bpf_fastcall function attribute.\n18976:\t * This attribute means that function scratches only some of\n18977:\t * the caller saved registers defined by ABI.\n18978:\t * For BPF the set of such registers could be defined as follows:\n18979:\t * - R0 is scratched only if function is non-void;\n18980:\t * - R1-R5 are scratched only if corresponding parameter type is defined\n18981:\t * in the function prototype.\n18982:\t *\n18983:\t * The contract between kernel and clang allows to simultaneously use\n18984:\t * such functions and maintain backwards compatibility with old\n"
} |
| 69/3 | 2026/09/28 01:41 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 172031 output: 377 thoughts: 1280 Thoughts: **KMSAN Assessment: eBPF Verifier Scalar Evolution and Loop Analysis** Okay, so the `cs->arg_slot_cnt` is consistently initialized when `bpf_get_call_summary` returns true, that's good. Now, let me systematically review this patch series and make sure we're not introducing any uninitialized memory reads or leaks. First, let's address the most obvious concerns: 1. **Kernel structures to userspace:** Nope. The patch doesn't touch any kernel structures that get sent to userspace via `copy_to_user`, `put_user`, netlink, ioctls, socket options, or BPF buffers. No risk there. 2. **Conditional logic on uninitialized data:** No dice. All local variables and struct fields involved in conditional checks are definitely initialized. We're safe there. 3. **Complex data structures, uninitialized fields:** Everything's zero-initialized. I'm using `kzalloc`, `kvcalloc`, `kvzalloc`, or explicit initialization for all allocations. This is crucial for avoiding any unexpected behavior later on. 4. **Bounds checks and buffer accesses:** The bounds checks and SCEV tracking are purely internal to the BPF verifier for validating BPF programs. They aren't exposing any uninitialized bytes of existing buffers to surrounding code. Next, I need to confirm whether it fits the criteria for `NeedsKMSAN=false`. Let's see: * Does this patch primarily risk out-of-bounds accesses, overflows, NULL pointer dereferences, deadlocks, or use-after-free bugs? Yes, but these are already well-covered by KASAN. * Are all stack and heap structures fully zeroed or initialized before being read or copied? Absolutely. `kzalloc`, `kvzalloc`, etc., are heavily utilized. * Does it introduce any risk of uninitialized memory usage or info-leaks? No, not at all. Alright, what are the *real* risks of this patch series? This is where the complexity comes in: it's all about scalar evolution (SCEV) and loop handling within the eBPF verifier. I'm talking about CFG analysis (immediate dominators, loop identification), min-heap implementation, symbolic expressions, register bounds widening/clamping across loop iterations, BTF struct access with variable offsets, and state pruning for loops. The potential bugs here are mainly related to algorithm logic: * **Verifier Soundness:** Underestimating register bounds or loop iterations, leading to out-of-bounds memory accesses or safety violations in BPF programs when they *run* (detected by KASAN). * **Out-of-Bounds in Verifier Logic:** Out-of-bounds accesses and buffer overflows during CFG operations or heap manipulation (like array indexing). Again, KASAN will catch those. * **Infinite Loops:** Infinite loops or recursion within expression transformations or DFS. This would be caught by timeouts or the standard watchdog. * **Memory Errors:** Potential memory leaks or use-after-free conditions in allocated structs. KASAN is the tool of choice. But the key point is this: none of this involves uninitialized memory reads or leaks *to* user space. All new allocations in things like `loops.c`, `scev.c`, etc., are zeroed. Stack variables are either initialized or fully written to before they're read. KMSAN would be useless here. It's designed to find *uninitialized* reads and kernel-to-user info leaks. This patch is about algorithmic complexity within the verifier and that's precisely what KASAN is designed to do. So, I'm confident in saying that a dedicated KMSAN fuzzing session is not warranted. Standard KASAN fuzzing is the right approach. Let me double-check one more time, and then I will call `set-results`. Everything checks out: * `NeedsKMSAN=false` * **KMSAN Reasoning**: Patch series implements loop detection (using dominator trees / idoms), scalar evolution (SCEV) analysis, register widening/clamping, and variable-offset BTF struct array access in the eBPF verifier. Memory allocations and initializations: All dynamically allocated structures are zero-initialized. Stack variables are either zeroed or completely initialized before their fields are accessed. User-space copies / info-leaks: No kernel structures or data buffers are copied to user space. Applicability of KASAN vs KMSAN: The risks introduced by this patch are algorithmic in nature (CFG graph traversal, binary min-heap manipulation, array indexing, and BPF verifier soundness). KMSAN only tracks reads of uninitialized kernel memory and kernel-to-user info- |
| 70/3 | 2026/09/28 01:41 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series introduces loop analysis and Scalar Evolution (SCEV) to the eBPF verifier. It adds CFG algorithms (immediate dominator calculation, loop and latch detection), a binary min-heap for worklist processing, symbolic SCEV expression tracking, loop iteration estimation, register range widening/clamping, and support for variable-offset BTF struct array accesses.\n\nKMSAN vs KASAN applicability:\n- Uninitialized memory / Info-leaks (KMSAN): No kernel memory or structs are copied to user space (the verifier produces formatted log text and returns integer return codes). All newly introduced data structures (e.g., struct bpf_loop, struct bpf_loop_exit, struct scev, struct env, idoms, postorder arrays, heap buffers) are allocated using kzalloc, kvcalloc, kvzalloc, or with __GFP_ZERO. Local stack variables (such as struct bpf_loop_iters, struct linear_latch, struct bounds, struct array_access) are either explicitly zeroed or fully populated before their fields are read. No uninitialized memory is read or exposed.\n- Memory safety and logic correctness (KASAN): The risks in this patch are typical of compiler/verifier analysis passes: out-of-bounds indexing in instruction/graph arrays, heap buffer bounds in the worklist binary heap, memory leaks, and verifier soundness bugs (such as incorrect bounds widening that could permit out-of-bounds accesses during BPF execution). These failure modes are detected by KASAN, UBSAN, and standard kernel debugging facilities, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series introduces loop analysis and Scalar Evolution (SCEV) to the eBPF verifier. It adds CFG algorithms (immediate dominator calculation, loop and latch detection), a binary min-heap for worklist processing, symbolic SCEV expression tracking, loop iteration estimation, register range widening/clamping, and support for variable-offset BTF struct array accesses.\n\nKMSAN vs KASAN applicability:\n- Uninitialized memory / Info-leaks (KMSAN): No kernel memory or structs are copied to user space (the verifier produces formatted log text and returns integer return codes). All newly introduced data structures (e.g., struct bpf_loop, struct bpf_loop_exit, struct scev, struct env, idoms, postorder arrays, heap buffers) are allocated using kzalloc, kvcalloc, kvzalloc, or with __GFP_ZERO. Local stack variables (such as struct bpf_loop_iters, struct linear_latch, struct bounds, struct array_access) are either explicitly zeroed or fully populated before their fields are read. No uninitialized memory is read or exposed.\n- Memory safety and logic correctness (KASAN): The risks in this patch are typical of compiler/verifier analysis passes: out-of-bounds indexing in instruction/graph arrays, heap buffer bounds in the worklist binary heap, memory leaks, and verifier soundness bugs (such as incorrect bounds widening that could permit out-of-bounds accesses during BPF execution). These failure modes are detected by KASAN, UBSAN, and standard kernel debugging facilities, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|