xref: /linux/kernel/bpf/scev.c (revision 088a5477a9bdb410169ff158a581bc2585db546c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
3 
4 #include "linux/cnum.h"
5 #include <linux/bpf_verifier.h>
6 #include <linux/jhash.h>
7 #include <linux/log2.h>
8 #include <linux/min_heap.h>
9 #include <linux/bug.h>
10 #include <linux/tnum.h>
11 #include <linux/overflow.h>
12 
13 #define REGS_NUM BPF_SCEV_REGS_NUM
14 #define UNKNOWN_EXPR_ID 0
15 #define OPAQUE_EXPR_ID  1
16 
17 /*
18  * BPF instructions use 'code', 'src_reg', 'off' and 'imm' fields for instruction encoding.
19  * For scalar evolution purpose we want to reuse most of the opcode definitions,
20  * but also add a few custom operations (REG and IMM).
21  * Use the enum below to uniformly represent all operations relevant for SCEV.
22  */
23 enum expr_op {
24 	/* leave range 0..255 for standard bpf opcodes */
25 	UNKNOWN = 256, /* start custom opcodes from the second byte */
26 	REG,
27 	IMM,
28 	SDIV, SMOD,
29 	SEXT8, SEXT16, SEXT32,
30 	ZEXT8, ZEXT16, ZEXT32,
31 	BSWAP16, BSWAP32, BSWAP64,
32 	/* during the loop body execution the value can be either of param[0] or param[1] */
33 	ANY,
34 	/* some value that verifier is not going to track precisely */
35 	OPAQUE,
36 	/* '*(u8/16/32 *)(r10 + X) = Y' writes define slot contents only partially */
37 	SPILL8, SPILL16, SPILL32,
38 	/*
39 	 * SCEV expression corresponding to linear equation 'param[0] + param[1] * k',
40 	 * where k is a loop iteration number. Loop here refers to innermost loop
41 	 * containing instruction associated with this expression, as returned by
42 	 * bpf_loop_at_index().
43 	 */
44 	LINEAR_SCEV,
45 };
46 
47 struct expr {
48 	u32 op;
49 	union {
50 		u32 params[2];
51 		s64 imm;
52 	};
53 };
54 
55 struct expr_bucket {
56 	u32 cnt;
57 	u32 cap;
58 	u32 ids[];
59 };
60 
61 struct env {
62 	bool empty;
63 	u32 reg2expr[REGS_NUM];
64 	u32 reg2scev[REGS_NUM];
65 };
66 
67 struct insn_envs {
68 	u32 cnt;
69 	struct {
70 		int loop_header;
71 		struct env *env;
72 	} entries[];
73 };
74 
75 #define EXPR_STACK_DEPTH 8
76 
77 struct expr_stack_elt {
78 	u32 id:28;
79 	u32 pre:1;
80 	u32 next_param:2;
81 };
82 
83 DEFINE_MIN_HEAP(int, scev_worklist);
84 
85 struct scev {
86 	/* Read-only representatives for stack slots without a saved register. */
87 	struct bpf_reg_state zero_reg;
88 	struct bpf_reg_state unknown_reg;
89 	/*
90 	 * Expressions are identified by id, exprs_ht ensures that
91 	 * each expression exists as a unique instance.
92 	 * This allows for fast equivalence check: id1 === id2.
93 	 */
94 	struct expr_bucket **exprs_ht;
95 	struct scev_worklist worklist;
96 	struct insn_envs **envs;
97 	struct expr *exprs;
98 	/*
99 	 * Loops are analyzed one by one, this array keeps track if a particular
100 	 * instruction was visited on a current pass.
101 	 */
102 	u32 *discovered;
103 	u32 exprs_ht_cnt;
104 	int exprs_cnt;
105 	int exprs_cap;
106 	int envs_cnt;
107 	int stack_sz;
108 	struct expr_stack_elt expr_stack[EXPR_STACK_DEPTH];
109 	u32 ids_buf[EXPR_STACK_DEPTH];
110 };
111 
112 static u32 expr_hash(struct expr *e)
113 {
114 	return jhash_3words(e->op, e->params[0], e->params[1], 0);
115 }
116 
117 static int expr_eq(struct expr *a, struct expr *b)
118 {
119 	return a->op == b->op && a->imm == b->imm;
120 }
121 
122 static int add_expr(struct scev *scev, struct expr e)
123 {
124 	struct expr_bucket *bucket;
125 	u32 i, id, hash, new_cap;
126 	void *tmp;
127 
128 	hash = expr_hash(&e) & (scev->exprs_ht_cnt - 1);
129 	bucket = scev->exprs_ht[hash];
130 
131 	if (bucket) {
132 		for (i = 0; i < bucket->cnt; i++) {
133 			id = bucket->ids[i];
134 			if (expr_eq(&e, &scev->exprs[id]))
135 				return id;
136 		}
137 	}
138 
139 	if (!bucket || bucket->cap == bucket->cnt) {
140 		new_cap = bucket ? bucket->cap * 2 : 4;
141 		bucket = kvrealloc(bucket, sizeof(*bucket) + sizeof(u32) * new_cap, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
142 		if (!bucket)
143 			return -ENOMEM;
144 		scev->exprs_ht[hash] = bucket;
145 		bucket->cap = new_cap;
146 	}
147 
148 	if (scev->exprs_cnt == scev->exprs_cap) {
149 		new_cap = scev->exprs_cap ? scev->exprs_cap * 2 : 256;
150 		tmp = kvrealloc(scev->exprs, sizeof(struct expr) * new_cap, GFP_KERNEL_ACCOUNT);
151 		if (!tmp)
152 			return -ENOMEM;
153 		scev->exprs = tmp;
154 		scev->exprs_cap = new_cap;
155 	}
156 
157 	id = scev->exprs_cnt++;
158 	scev->exprs[id] = e;
159 	bucket->ids[bucket->cnt++] = id;
160 	return id;
161 }
162 
163 static int expr2(struct scev *scev, u32 op, int a, int b)
164 {
165 	if (a < 0)
166 		return a;
167 	if (b < 0)
168 		return b;
169 	return add_expr(scev, (struct expr){ .op = op, .params = {a, b} });
170 }
171 
172 static int expr1(struct scev *scev, u32 op, int a)
173 {
174 	if (a < 0)
175 		return a;
176 	return expr2(scev, op, a, 0);
177 }
178 
179 static int expr0(struct scev *scev, u32 op)
180 {
181 	return expr2(scev, op, 0, 0);
182 }
183 
184 static int imm_expr(struct scev *scev, s64 value)
185 {
186 	return add_expr(scev, (struct expr){ .op = IMM, .imm = value });
187 }
188 
189 static bool same_exprs(struct scev *scev, int id_a, int id_b)
190 {
191 	return id_a == id_b;
192 }
193 
194 static bool is_imm(struct scev *scev, int id, s64 *imm)
195 {
196 	if (scev->exprs[id].op != IMM)
197 		return false;
198 	*imm = scev->exprs[id].imm;
199 	return true;
200 }
201 
202 static bool is_op(struct scev *scev, int id, u32 op)
203 {
204 	if (scev->exprs[id].op != op)
205 		return false;
206 	return true;
207 }
208 
209 static bool is_unop(struct scev *scev, enum expr_op op, int id, u32 *p0)
210 {
211 	if (scev->exprs[id].op != op)
212 		return false;
213 	*p0 = scev->exprs[id].params[0];
214 	return true;
215 }
216 
217 static bool is_binop(struct scev *scev, enum expr_op op, int id, u32 *p0, u32 *p1)
218 {
219 	if (scev->exprs[id].op != op)
220 		return false;
221 	*p0 = scev->exprs[id].params[0];
222 	*p1 = scev->exprs[id].params[1];
223 	return true;
224 }
225 
226 static bool is_reg(struct scev *scev, int id, u32 *reg)
227 {
228 	return is_unop(scev, REG, id, reg);
229 }
230 
231 static bool is_add(struct scev *scev, int id, u32 *left, u32 *right)
232 {
233 	return is_binop(scev, BPF_ADD, id, left, right);
234 }
235 
236 static bool is_zext32(struct scev *scev, int id, u32 *left)
237 {
238 	return is_unop(scev, ZEXT32, id, left);
239 }
240 
241 static bool is_any(struct scev *scev, int id, u32 *left, u32 *right)
242 {
243 	return is_binop(scev, ANY, id, left, right);
244 }
245 
246 static bool is_linear(struct scev *scev, int id, u32 *base, u32 *slope)
247 {
248 	return is_binop(scev, LINEAR_SCEV, id, base, slope);
249 }
250 
251 static bool is_opaque(struct scev *scev, int id)
252 {
253 	return is_op(scev, id, OPAQUE);
254 }
255 
256 static void log_reg(struct bpf_verifier_env *env, u32 reg)
257 {
258 	if (reg < MAX_BPF_REG)
259 		bpf_log(&env->log, "r%d", reg);
260 	else
261 		bpf_log(&env->log, "*fp%d", (MAX_BPF_REG - reg - 1) * 8);
262 }
263 
264 static const char *op_str(u32 op)
265 {
266 	switch (op) {
267 	case BPF_ADD:  return "+";
268 	case BPF_SUB:  return "-";
269 	case BPF_MUL:  return "*";
270 	case BPF_DIV:  return "/";
271 	case SDIV:     return "s/";
272 	case BPF_OR:   return "|";
273 	case BPF_AND:  return "&";
274 	case BPF_LSH:  return "<<";
275 	case BPF_RSH:  return ">>";
276 	case BPF_NEG:  return "-";
277 	case BPF_MOD:  return "%";
278 	case SMOD:     return "s%";
279 	case BPF_XOR:  return "^";
280 	case BPF_ARSH: return "s>>";
281 	case SEXT8:    return "sext8";
282 	case SEXT16:   return "sext16";
283 	case SEXT32:   return "sext32";
284 	case ZEXT8:    return "zext8";
285 	case ZEXT16:   return "zext16";
286 	case ZEXT32:   return "zext32";
287 	case BSWAP16:  return "bswap16";
288 	case BSWAP32:  return "bswap32";
289 	case BSWAP64:  return "bswap64";
290 	case SPILL8:   return "spill8";
291 	case SPILL16:  return "spill16";
292 	case SPILL32:  return "spill32";
293 	case ANY:      return "any";
294 	case LINEAR_SCEV:  return "linear";
295 	}
296 	return NULL;
297 }
298 
299 static u32 op_params_num(u32 op)
300 {
301 	switch (op) {
302 	case BPF_ADD:
303 	case BPF_SUB:
304 	case BPF_MUL:
305 	case BPF_DIV:
306 	case BPF_MOD:
307 	case BPF_OR:
308 	case BPF_XOR:
309 	case BPF_AND:
310 	case BPF_LSH:
311 	case BPF_RSH:
312 	case BPF_ARSH:
313 	case SDIV:
314 	case SMOD:
315 	case ANY:
316 	case LINEAR_SCEV:
317 		return 2;
318 	case BPF_NEG:
319 	case SEXT8:
320 	case SEXT16:
321 	case SEXT32:
322 	case ZEXT8:
323 	case ZEXT16:
324 	case ZEXT32:
325 	case BSWAP16:
326 	case BSWAP32:
327 	case BSWAP64:
328 	case SPILL8:
329 	case SPILL16:
330 	case SPILL32:
331 		return 1;
332 	case REG:
333 	case IMM:
334 	case OPAQUE:
335 		return 0;
336 	default:
337 		return 0;
338 	}
339 }
340 
341 static bool expr_stack_push(struct scev *scev, u32 id)
342 {
343 	if (scev->stack_sz >= EXPR_STACK_DEPTH)
344 		return false;
345 	scev->expr_stack[scev->stack_sz].id = id;
346 	scev->expr_stack[scev->stack_sz].pre = true;
347 	scev->expr_stack[scev->stack_sz].next_param = 0;
348 	scev->stack_sz++;
349 	return true;
350 }
351 
352 enum {
353 	PRE = BIT(1), POST = BIT(2), DEPTH_LIMIT = BIT(3)
354 };
355 
356 static bool expr_next(struct scev *scev, u32 *id, u32 *order)
357 {
358 	struct expr_stack_elt *elt;
359 	struct expr *expr;
360 	u32 num_params;
361 
362 	if (scev->stack_sz == 0)
363 		return false;
364 
365 	elt = &scev->expr_stack[scev->stack_sz - 1];
366 	*id = elt->id;
367 	*order = 0;
368 	expr = &scev->exprs[elt->id];
369 	num_params = op_params_num(expr->op);
370 	if (elt->pre) {
371 		elt->pre = false;
372 		*order = PRE;
373 		return true;
374 	}
375 	if (elt->next_param == num_params) {
376 		*order = POST;
377 		scev->stack_sz--;
378 		return true;
379 	}
380 	if (scev->stack_sz == EXPR_STACK_DEPTH) {
381 		*order = POST | DEPTH_LIMIT;
382 		scev->stack_sz--;
383 		return true;
384 	}
385 	expr_stack_push(scev, expr->params[elt->next_param]);
386 	elt->next_param++;
387 	return expr_next(scev, id, order);
388 }
389 
390 static void log_expr(struct bpf_verifier_env *env, u32 id)
391 {
392 	struct bpf_verifier_log *log = &env->log;
393 	struct scev *scev = env->scev;
394 	struct expr *expr;
395 	const char *str;
396 	u32 order;
397 
398 	scev->stack_sz = 0;
399 	expr_stack_push(scev, id);
400 	while (expr_next(scev, &id, &order)) {
401 		if ((order & PRE) && scev->stack_sz > 1)
402 			bpf_log(log, " ");
403 		expr = &scev->exprs[id];
404 		switch (expr->op) {
405 		case UNKNOWN:
406 			if (order & PRE)
407 				bpf_log(log, "?");
408 			break;
409 		case OPAQUE:
410 			if (order & PRE)
411 				bpf_log(log, "_");
412 			break;
413 		case REG:
414 			if (order & PRE)
415 				log_reg(env, expr->params[0]);
416 			break;
417 		case IMM:
418 			if (order & PRE)
419 				bpf_log(log, "%lld", expr->imm);
420 			break;
421 		default:
422 			if (order & PRE) {
423 				str = op_str(expr->op);
424 				bpf_log(log, "(");
425 				if (str)
426 					bpf_log(log, "%s", str);
427 				else
428 					bpf_log(log, "bad-expr-op %x", expr->op);
429 			}
430 			if (order & DEPTH_LIMIT)
431 				bpf_log(log, "...");
432 			if (order & POST)
433 				bpf_log(log, ")");
434 		}
435 	}
436 }
437 
438 static bool reg_alive_at(struct bpf_verifier_env *env, u32 reg, u32 insn_idx)
439 {
440 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
441 	u16 live_regs = aux[insn_idx].live_regs_before;
442 
443 	return reg < MAX_BPF_REG
444 	       ? (BIT(reg) & live_regs)
445 	       : test_bit(reg - MAX_BPF_REG, aux[insn_idx].live_stack_before);
446 }
447 
448 static void print_env(struct bpf_verifier_env *env, struct env *e, u32 insn_idx)
449 {
450 	struct bpf_verifier_log *log = &env->log;
451 	struct scev *scev = env->scev;
452 	bool printed_some = false;
453 	bool is_self_scev;
454 	bool is_self_reg;
455 	int i, r;
456 
457 	if (e->empty) {
458 		bpf_log(log, "  <empty>\n");
459 		return;
460 	}
461 
462 	for (i = 0; i < REGS_NUM; i++) {
463 		if (!reg_alive_at(env, i, insn_idx))
464 			continue;
465 		is_self_reg = is_reg(scev, e->reg2expr[i], &r) && i == r;
466 		is_self_scev = is_reg(scev, e->reg2scev[i], &r) && i == r;
467 		if (is_self_reg && is_self_scev)
468 			continue;
469 		printed_some = true;
470 		bpf_log(log, "  ");
471 		log_reg(env, i);
472 		bpf_log(log, "=");
473 		log_expr(env, e->reg2expr[i]);
474 		if (e->reg2expr[i] != UNKNOWN_EXPR_ID) {
475 			bpf_log(log, " / ");
476 			log_expr(env, e->reg2scev[i]);
477 		}
478 		bpf_log(log, "\n");
479 	}
480 	if (!printed_some)
481 		bpf_log(log, "  <all regs unchanged>\n");
482 }
483 static struct env *find_loop_env(struct scev *scev, int loop_header, int insn_idx)
484 {
485 	struct insn_envs *envs = scev->envs[insn_idx];
486 	u32 i;
487 
488 	if (!envs)
489 		return NULL;
490 	for (i = 0; i < envs->cnt; i++)
491 		if (envs->entries[i].loop_header == loop_header)
492 			return envs->entries[i].env;
493 	return NULL;
494 }
495 
496 static struct env *find_header_env(struct scev *scev, int header)
497 {
498 	return find_loop_env(scev, header, header);
499 }
500 
501 static struct env *get_loop_env(struct scev *scev, int loop_header, int insn_idx)
502 {
503 	struct insn_envs *envs = scev->envs[insn_idx];
504 	u32 cnt = envs ? envs->cnt : 0;
505 	struct insn_envs *tmp;
506 	struct env *e;
507 
508 	e = find_loop_env(scev, loop_header, insn_idx);
509 	if (e)
510 		return e;
511 
512 	e = kzalloc(sizeof(*e), GFP_KERNEL_ACCOUNT);
513 	if (!e)
514 		return NULL;
515 
516 	tmp = krealloc(envs, struct_size(envs, entries, cnt + 1), GFP_KERNEL_ACCOUNT);
517 	if (!tmp) {
518 		kfree(e);
519 		return NULL;
520 	}
521 
522 	e->empty = true;
523 	tmp->entries[cnt].loop_header = loop_header;
524 	tmp->entries[cnt].env = e;
525 	tmp->cnt = cnt + 1;
526 	scev->envs[insn_idx] = tmp;
527 	return e;
528 }
529 
530 static int replace_reg(struct scev *scev, struct env *e, u32 reg, int id)
531 {
532 	if (id < 0)
533 		return id;
534 	e->reg2expr[reg] = id;
535 	return 0;
536 }
537 
538 static int setup_initial_loop_env(struct bpf_verifier_env *env, struct env *e, int insn_idx)
539 {
540 	struct scev *scev = env->scev;
541 	int i, err;
542 
543 	/*
544 	 * Initial assignments are of form rX -> rX are needed as seeds for subsequent
545 	 * work queue pop / transfer() calls. Because e->empty is true, the first backedge
546 	 * join() will overwrite the them. compute_header_scevs() accounts for register
547 	 * states at loop entry.
548 	 */
549 	for (i = 0; i < REGS_NUM; i++) {
550 		err = replace_reg(scev, e, i, expr1(scev, REG, i));
551 		if (err)
552 			return err;
553 	}
554 	return 0;
555 }
556 
557 static void forget_call_regs(struct env *e)
558 {
559 	int i;
560 
561 	for (i = BPF_REG_0; i <= BPF_REG_5; i++)
562 		e->reg2expr[i] = UNKNOWN_EXPR_ID;
563 }
564 
565 static u32 spill_spi(struct bpf_insn *insn)
566 {
567 	return -insn->off / BPF_REG_SIZE - 1;
568 }
569 
570 static u32 off_to_reg(struct bpf_insn *insn)
571 {
572 	return spill_spi(insn) + MAX_BPF_REG;
573 }
574 
575 static bool is_spill_off(int off)
576 {
577 	return off % BPF_REG_SIZE == 0 &&
578 	       off <= -BPF_REG_SIZE &&
579 	       off >= -MAX_BPF_STACK_JIT;
580 }
581 
582 static void mark_opaque(struct env *e, int off, int size)
583 {
584 	int b, spi;
585 
586 	for (b = off; b < off + size; b++) {
587 		if (b >= 0 || b < -MAX_BPF_STACK_JIT)
588 			continue;
589 		spi = (-b - 1) / BPF_REG_SIZE;
590 		e->reg2expr[MAX_BPF_REG + spi] = OPAQUE_EXPR_ID;
591 	}
592 }
593 
594 static int mk_spill(struct scev *scev, u8 size, int id)
595 {
596 	switch (size) {
597 	case BPF_B:  return expr1(scev, SPILL8,  id);
598 	case BPF_H:  return expr1(scev, SPILL16, id);
599 	case BPF_W:  return expr1(scev, SPILL32, id);
600 	case BPF_DW: return id;
601 	}
602 	return UNKNOWN_EXPR_ID;
603 }
604 
605 static int mk_fill(struct scev *scev, int id, u8 code)
606 {
607 	bool sx = BPF_MODE(code) == BPF_MEMSX;
608 
609 #ifdef __BIG_ENDIAN
610 	/* A narrow fill from a DW spill reads high bits on big-endian. */
611 	if (BPF_SIZE(code) != BPF_DW)
612 		return OPAQUE_EXPR_ID;
613 #endif
614 
615 	switch (BPF_SIZE(code)) {
616 	case BPF_B:  return expr1(scev, sx ? SEXT8  : ZEXT8,  id);
617 	case BPF_H:  return expr1(scev, sx ? SEXT16 : ZEXT16, id);
618 	case BPF_W:  return expr1(scev, sx ? SEXT32 : ZEXT32, id);
619 	case BPF_DW: return sx ? UNKNOWN_EXPR_ID : id; /* DW sign-extended load is invalid */
620 	}
621 	return UNKNOWN_EXPR_ID;
622 }
623 
624 static int maybe_store_fp(struct scev *scev, struct env *e, struct bpf_insn *insn, int id)
625 {
626 	u8 size = BPF_SIZE(insn->code);
627 
628 	if (insn->dst_reg != BPF_REG_FP)
629 		return 0;
630 	if (is_spill_off(insn->off))
631 		return replace_reg(scev, e, off_to_reg(insn), mk_spill(scev, size, id));
632 	mark_opaque(e, insn->off, bpf_size_to_bytes(size));
633 	return 0;
634 }
635 
636 static int maybe_load_fp(struct scev *scev, struct env *e, struct bpf_insn *insn)
637 {
638 	int id;
639 
640 	if (insn->src_reg == BPF_REG_FP && is_spill_off(insn->off))
641 		id = mk_fill(scev, e->reg2expr[off_to_reg(insn)], insn->code);
642 	else
643 		id = OPAQUE_EXPR_ID;
644 	return replace_reg(scev, e, insn->dst_reg, id);
645 }
646 
647 static int transfer(struct bpf_verifier_env *env, struct env *e, int idx)
648 {
649 	const bool little_endian = htons(0x3412) == 0x1234;
650 	struct bpf_insn *insn = &env->prog->insnsi[idx];
651 	struct scev *scev = env->scev;
652 	u32 *reg2expr = e->reg2expr;
653 	u8 class = BPF_CLASS(insn->code);
654 	u8 x_or_k = BPF_SRC(insn->code);
655 	u8 opcode = BPF_OP(insn->code);
656 	u8 mode = BPF_MODE(insn->code);
657 	u32 dst = insn->dst_reg;
658 	u32 src = insn->src_reg;
659 	u32 op, sext;
660 	bool need_bswap;
661 	int i, id;
662 	s64 imm;
663 
664 	switch (class) {
665 	case BPF_ALU:
666 	case BPF_ALU64:
667 		switch (opcode) {
668 		case BPF_MOV:
669 			switch (insn->off) {
670 			case 0: sext = 0; break;
671 			case 8: sext = SEXT8; break;
672 			case 16: sext = SEXT16; break;
673 			case 32: sext = SEXT32; break;
674 			default:
675 				goto mark_dst_unknown;
676 			}
677 
678 			if (x_or_k == BPF_X && insn->imm == 0)
679 				id = reg2expr[src];
680 			else if (x_or_k == BPF_K && src == 0 && insn->off == 0)
681 				id = imm_expr(scev, insn->imm);
682 			else
683 				goto mark_dst_unknown;
684 
685 			if (sext)
686 				id = expr1(scev, sext, id);
687 			if (class == BPF_ALU)
688 				id = expr1(scev, ZEXT32, id);
689 
690 			return replace_reg(scev, e, dst, id);
691 
692 		case BPF_ADD:
693 		case BPF_SUB:
694 		case BPF_MUL:
695 		case BPF_DIV:
696 		case BPF_MOD:
697 		case BPF_OR:
698 		case BPF_XOR:
699 		case BPF_AND:
700 		case BPF_LSH:
701 		case BPF_RSH:
702 		case BPF_ARSH:
703 			if (opcode == BPF_DIV && insn->off == 1)
704 				op = SDIV;
705 			else if (opcode == BPF_MOD && insn->off == 1)
706 				op = SMOD;
707 			else if (insn->off == 0)
708 				op = opcode;
709 			else
710 				goto mark_dst_unknown;
711 
712 			if (x_or_k == BPF_X && insn->imm == 0)
713 				id = reg2expr[src];
714 			else if (x_or_k == BPF_K && src == 0)
715 				id = imm_expr(scev, insn->imm);
716 			else
717 				goto mark_dst_unknown;
718 
719 			id = expr2(scev, op, reg2expr[dst], id);
720 
721 			if (class == BPF_ALU)
722 				id = expr1(scev, ZEXT32, id);
723 
724 			return replace_reg(scev, e, dst, id);
725 
726 		case BPF_NEG:
727 			if (src == 0 && insn->off == 0 && insn->imm == 0)
728 				id = expr1(scev, BPF_NEG, reg2expr[dst]);
729 			else
730 				goto mark_dst_unknown;
731 
732 			if (class == BPF_ALU)
733 				id = expr1(scev, ZEXT32, id);
734 
735 			return replace_reg(scev, e, dst, id);
736 
737 		case BPF_END:
738 			if (src != 0 || insn->off != 0 || (class == BPF_ALU64 && x_or_k != 0))
739 				goto mark_dst_unknown;
740 
741 			need_bswap = class == BPF_ALU64 || ((x_or_k == BPF_TO_LE) != little_endian);
742 			switch (insn->imm) {
743 			case 16: op = need_bswap ? BSWAP16 : ZEXT16; break;
744 			case 32: op = need_bswap ? BSWAP32 : ZEXT32; break;
745 			case 64: op = need_bswap ? BSWAP64 : 0; break;
746 			default:
747 				goto mark_dst_unknown;
748 			}
749 
750 			id = reg2expr[dst];
751 			if (op)
752 				id = expr1(scev, op, reg2expr[dst]);
753 
754 			return replace_reg(scev, e, dst, id);
755 		default:
756 			goto mark_dst_unknown;
757 		}
758 		break;
759 	case BPF_LDX:
760 		switch (mode) {
761 		case BPF_MEM:
762 		case BPF_MEMSX:
763 			return maybe_load_fp(scev, e, insn);
764 		default:
765 			goto mark_dst_unknown;
766 		}
767 	case BPF_STX:
768 		switch (mode) {
769 		case BPF_MEM:
770 			return maybe_store_fp(scev, e, insn, reg2expr[src]);
771 		case BPF_ATOMIC:
772 			if (insn->imm == BPF_LOAD_ACQ)
773 				return maybe_load_fp(scev, e, insn);
774 			if (insn->imm == BPF_STORE_REL) {
775 				return maybe_store_fp(scev, e, insn, reg2expr[src]);
776 			}
777 			/*
778 			 * verifier does not track other atomic ops precisely,
779 			 * hence mark the results as opaque.
780 			 */
781 			if (insn->dst_reg == BPF_REG_FP)
782 				mark_opaque(e, insn->off, bpf_size_to_bytes(BPF_SIZE(insn->code)));
783 			if (insn->imm == BPF_CMPXCHG)
784 				return replace_reg(scev, e, BPF_REG_0, OPAQUE_EXPR_ID);
785 			if (insn->imm & BPF_FETCH)
786 				return replace_reg(scev, e, src, OPAQUE_EXPR_ID);
787 			break;
788 		}
789 		break;
790 	case BPF_ST:
791 		if (insn->dst_reg == BPF_REG_FP) {
792 			id = imm_expr(scev, insn->imm);
793 			if (id < 0)
794 				return id;
795 			return maybe_store_fp(scev, e, insn, id);
796 		}
797 		break;
798 	case BPF_JMP:
799 	case BPF_JMP32:
800 		if (opcode == BPF_CALL)
801 			forget_call_regs(e);
802 		/* for non-CALL there are no changes in register states */
803 		break;
804 	case BPF_LD:
805 		switch (mode) {
806 		case BPF_IMM:
807 			/* rX = imm ll */
808 			if (BPF_SIZE(insn->code) == BPF_DW && insn->src_reg == 0) {
809 				imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
810 				return replace_reg(scev, e, dst, imm_expr(scev, imm));
811 			}
812 			/* map, map value, BTF id, function */
813 			if (BPF_SIZE(insn->code) == BPF_DW)
814 				return replace_reg(scev, e, dst, OPAQUE_EXPR_ID);
815 			goto mark_dst_unknown;
816 		case BPF_ABS:
817 		case BPF_IND:
818 			forget_call_regs(e);
819 			break;
820 		default:
821 			goto mark_dst_unknown;
822 		}
823 		break;
824 	default:
825 		/* unknown instruction, nuke state */
826 		for (i = 0; i < REGS_NUM; i++)
827 			reg2expr[i] = UNKNOWN_EXPR_ID;
828 		break;
829 	}
830 	return 0;
831 
832 mark_dst_unknown:
833 	reg2expr[dst] = UNKNOWN_EXPR_ID;
834 	return 0;
835 }
836 
837 /*
838  * Construct minimal 'ANY' expression by traversing 'a' and 'b'
839  * and accumulating non-duplicated non-ANY entries.
840  */
841 static int mk_any(struct scev *scev, int a, int b)
842 {
843 	struct expr_stack_elt *elt;
844 	struct expr *expr;
845 	u32 i, j, ids_buf_sz;
846 	u32 roots[2] = {a, b};
847 	int id;
848 
849 	if (a < 0)
850 		return a;
851 	if (b < 0)
852 		return b;
853 	ids_buf_sz = 0;
854 	for (i = 0; i < ARRAY_SIZE(roots); i++) {
855 		scev->stack_sz = 0;
856 		expr_stack_push(scev, roots[i]);
857 		while (scev->stack_sz) {
858 			elt = &scev->expr_stack[--scev->stack_sz];
859 			id = elt->id;
860 			expr = &scev->exprs[elt->id];
861 			if (expr->op == ANY) {
862 				if (!expr_stack_push(scev, expr->params[1]) ||
863 				    !expr_stack_push(scev, expr->params[0]))
864 					return UNKNOWN_EXPR_ID;
865 			} else {
866 				for (j = 0; j < ids_buf_sz; j++) {
867 					if (same_exprs(scev, scev->ids_buf[j], id))
868 						goto next;
869 				}
870 				if (ids_buf_sz == ARRAY_SIZE(scev->ids_buf))
871 					return UNKNOWN_EXPR_ID;
872 				scev->ids_buf[ids_buf_sz++] = id;
873 			}
874 next:;
875 		}
876 	}
877 	if (WARN_ON(ids_buf_sz == 0))
878 		return -EFAULT;
879 	id = scev->ids_buf[0];
880 	for (i = 1; i < ids_buf_sz; i++) {
881 		id = expr2(scev, ANY, id, scev->ids_buf[i]);
882 		if (id < 0)
883 			return id;
884 	}
885 	return id;
886 }
887 
888 static int join(struct scev *scev, struct env *acc, struct env *cur)
889 {
890 	int i, id;
891 
892 	if (acc->empty) {
893 		memcpy(acc, cur, sizeof(*acc));
894 		acc->empty = false;
895 		return 0;
896 	}
897 
898 	for (i = 0; i < REGS_NUM; i++) {
899 		if (!same_exprs(scev, acc->reg2expr[i], cur->reg2expr[i])) {
900 			id = mk_any(scev, acc->reg2expr[i], cur->reg2expr[i]);
901 			if (id < 0)
902 				return id;
903 			acc->reg2expr[i] = id;
904 		}
905 	}
906 	return 0;
907 }
908 
909 /* Mark any register modified in 'e' as unknown in 'acc'. */
910 static void forget_modified_regs(struct scev *scev, struct env *acc, struct env *e)
911 {
912 	u32 i, reg;
913 
914 	for (i = 0; i < REGS_NUM; i++) {
915 		if (e && is_reg(scev, e->reg2expr[i], &reg) && reg == i)
916 			continue;
917 		acc->reg2expr[i] = UNKNOWN_EXPR_ID;
918 	}
919 }
920 
921 /* For a loop H at `header`, mark any register modified as a result of H execution as unknown. */
922 static void forget_non_invariants(struct bpf_verifier_env *env, struct env *acc, int header)
923 {
924 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
925 	struct bpf_loop *loop = aux[header].loop;
926 	struct scev *scev = env->scev;
927 	int i, idx, h;
928 
929 	acc->empty = false;
930 	forget_modified_regs(scev, acc, find_header_env(scev, header));
931 	for (i = 0; i < loop->exits_cnt; i++) {
932 		idx = loop->exits[i].from;
933 		h = bpf_loop_at_index(env, idx);
934 		/*
935 		 * In order to account for situations like this:
936 		 *
937 		 * header:
938 		 *   do {
939 		 *	saved = rX;
940 		 *	rX = -1000;
941 		 *	do {				// H
942 		 *		if (random())
943 		 *			goto out;	// E
944 		 *	} while (inner_again);
945 		 *	rX = saved;
946 		 *    } while (outer_again);
947 		 *  out:
948 		 *
949 		 * For exits originating in nested loops check that rX is invariant
950 		 * both at the header (H) and at exit (E).
951 		 */
952 		while (h != header) {
953 			forget_modified_regs(scev, acc, find_header_env(scev, h));
954 			forget_modified_regs(scev, acc, find_loop_env(scev, h, idx));
955 			idx = h;
956 			h = aux[h].loop_header;
957 		}
958 		/*
959 		 * For exits originating at the same loop the header is already accounted for,
960 		 * check only the exit environment.
961 		 */
962 		forget_modified_regs(scev, acc, find_loop_env(scev, header, idx));
963 	}
964 }
965 
966 /* Order worklist in reverse post-order. */
967 static bool reverse_postorder_less(const void *a, const void *b, void *arg)
968 {
969 	const int *rank = arg;
970 
971 	return rank[*(const int *)a] > rank[*(const int *)b];
972 }
973 
974 static const struct min_heap_callbacks worklist_cb = {
975 	.less = reverse_postorder_less,
976 };
977 
978 static int worklist_push(struct bpf_verifier_env *env, int loop_header, int idx)
979 {
980 	struct scev *scev = env->scev;
981 	struct scev_worklist *worklist = &scev->worklist;
982 	u32 tag = (u32)loop_header + 1;
983 
984 	if (scev->discovered[idx] == tag)
985 		return 0;
986 
987 	if (min_heap_full_inline(worklist)) {
988 		size_t size = worklist->size ? worklist->size * 2 : 16;
989 		int *data;
990 
991 		data = kvrealloc(worklist->data, array_size(size, sizeof(*data)),
992 				GFP_KERNEL_ACCOUNT);
993 		if (!data)
994 			return -ENOMEM;
995 		worklist->data = data;
996 		worklist->size = size;
997 	}
998 	if (!min_heap_push_inline(worklist, &idx, &worklist_cb, env->cfg.postorder_nums))
999 		return -EFAULT;
1000 
1001 	scev->discovered[idx] = tag;
1002 	return 0;
1003 }
1004 
1005 static bool reg_alive_at_succ(struct bpf_verifier_env *env, u32 r, u32 insn_idx)
1006 {
1007 	struct bpf_iarray *succ = bpf_insn_successors(env, insn_idx);
1008 	u32 i;
1009 
1010 	for (i = 0; i < succ->cnt; i++)
1011 		if (reg_alive_at(env, r, succ->items[i]))
1012 			return true;
1013 	return false;
1014 }
1015 
1016 enum changes_at {
1017 	LOG_AT_TRANSFER,
1018 	LOG_AT_JOIN,
1019 };
1020 
1021 static void log_env_changes(struct bpf_verifier_env *env, enum changes_at at,
1022 			    struct env *old, struct env *new, int insn_idx)
1023 {
1024 	struct bpf_verifier_log *log = &env->log;
1025 	struct scev *scev = env->scev;
1026 	u64 null_pos = log->end_pos;
1027 	u32 old_id, new_id, regno;
1028 	bool any_changes = false;
1029 	bool is_self_scev;
1030 	u64 len;
1031 	int r;
1032 
1033 	bpf_log(log, "%s %4d: ", at == LOG_AT_TRANSFER ? "t" : "j", insn_idx);
1034 	bpf_verbose_insn(env, &env->prog->insnsi[insn_idx]);
1035 	len = log->end_pos - null_pos;
1036 	bpf_log(log, "%*s", max(37 - (int)len, 1), " ");
1037 	bpf_log(log, " ; ");
1038 	for (r = 0; r < REGS_NUM; r++) {
1039 		old_id = old->reg2expr[r];
1040 		new_id = new->reg2expr[r];
1041 		if (at == LOG_AT_TRANSFER && !reg_alive_at_succ(env, r, insn_idx))
1042 			continue;
1043 		if (at == LOG_AT_JOIN && !reg_alive_at(env, r, insn_idx))
1044 			continue;
1045 		if (same_exprs(scev, old_id, new_id))
1046 			continue;
1047 		is_self_scev = is_reg(scev, new_id, &regno) && r == regno;
1048 		if (old->empty && is_self_scev)
1049 			continue;
1050 		if (any_changes)
1051 			bpf_log(log, ", ");
1052 		log_reg(env, r);
1053 		bpf_log(log, " ");
1054 		log_expr(env, old_id);
1055 		bpf_log(log, " -> ");
1056 		log_expr(env, new_id);
1057 		any_changes = true;
1058 	}
1059 	if (old->empty && !any_changes)
1060 		bpf_log(log, "<empty join>");
1061 	bpf_log(log, "\n");
1062 	if (!old->empty && !any_changes)
1063 		bpf_vlog_reset(log, null_pos);
1064 }
1065 
1066 static bool is_probe_read_helper(u32 func_id)
1067 {
1068 	return func_id == BPF_FUNC_probe_read ||
1069 	       func_id == BPF_FUNC_probe_read_kernel ||
1070 	       func_id == BPF_FUNC_probe_read_user ||
1071 	       func_id == BPF_FUNC_probe_read_str ||
1072 	       func_id == BPF_FUNC_probe_read_kernel_str ||
1073 	       func_id == BPF_FUNC_probe_read_user_str;
1074 }
1075 
1076 /*
1077  * If instruction is an indirect write to stack, invalidate SCEVs for spi's
1078  * that this instruction can touch.
1079  */
1080 static void reset_scevs_at_indirect_writes(struct bpf_verifier_env *env, struct env *cur_env, int idx)
1081 {
1082 	struct bpf_insn *insn = &env->prog->insnsi[idx];
1083 	struct scev *scev = env->scev;
1084 	u8 class = BPF_CLASS(insn->code);
1085 	const unsigned long *mask;
1086 	u32 spi, reg;
1087 	bool opaque;
1088 
1089 	/* Direct fp stores are fine. */
1090 	if ((class == BPF_ST || class == BPF_STX) && insn->dst_reg == BPF_REG_FP)
1091 		return;
1092 
1093 	mask = bpf_may_write_mask(env, idx);
1094 	opaque = bpf_helper_call(insn) && is_probe_read_helper(insn->imm);
1095 	for_each_set_bit(spi, mask, MAX_BPF_STACK_SLOTS) {
1096 		reg = MAX_BPF_REG + spi;
1097 		if (cur_env->reg2expr[reg] == UNKNOWN_EXPR_ID)
1098 			continue;
1099 		replace_reg(scev, cur_env, reg, opaque ? OPAQUE_EXPR_ID : UNKNOWN_EXPR_ID);
1100 	}
1101 }
1102 
1103 /*
1104  * Collect loop-entry registers referenced by expr 'id', best effort.
1105  * DEPTH_LIMIT may leave dependencies unrecorded. This mask only avoids
1106  * widening that would lose stack-access precision; missing dependencies
1107  * may cause false rejections, but this is not a soundness issue.
1108  */
1109 static void or_expr_regs(struct bpf_verifier_env *env, u32 id, unsigned long *mask)
1110 {
1111 	struct scev *scev = env->scev;
1112 	u32 order;
1113 
1114 	scev->stack_sz = 0;
1115 	expr_stack_push(scev, id);
1116 	while (expr_next(scev, &id, &order)) {
1117 		if ((order & PRE) && scev->exprs[id].op == REG)
1118 			__set_bit(scev->exprs[id].params[0], mask);
1119 	}
1120 }
1121 
1122 /* Mask of argument registers (R1..R5) a call at 'idx' passes by register. */
1123 static u16 call_params_mask(struct bpf_verifier_env *env, int idx)
1124 {
1125 	struct bpf_insn *insn = &env->prog->insnsi[idx];
1126 	struct bpf_call_summary cs;
1127 	int n = bpf_get_call_summary(env, insn, &cs) ? cs.arg_slot_cnt : MAX_BPF_FUNC_REG_ARGS;
1128 
1129 	return n ? GENMASK(BPF_REG_1 + n - 1, BPF_REG_1) : 0;
1130 }
1131 
1132 /*
1133  * For instructions like:
1134  * - *(u64 *)(rBase + off) = rX
1135  * - rX = *(u64 *)(rBase + off)
1136  * - calls that construct objects on stack (e.g. dynptr_from_mem(rBase, ...))
1137  * When 'rBase' can be a stack pointer and is derived from some registers Rs
1138  * defined at loop entry, record Rs into 'mask'.
1139  */
1140 static void collect_store_base_regs(struct bpf_verifier_env *env,
1141 				    struct env *cur_env, int idx, unsigned long *mask)
1142 {
1143 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1144 	struct bpf_insn *insn = &env->prog->insnsi[idx];
1145 	u8 class = BPF_CLASS(insn->code);
1146 	u8 size = BPF_SIZE(insn->code);
1147 	u16 base_regs = 0;
1148 	u32 r;
1149 
1150 	if (size == BPF_W || size == BPF_DW) {
1151 		if ((class == BPF_STX || class == BPF_ST) && insn->dst_reg != BPF_REG_FP)
1152 			base_regs |= BIT(insn->dst_reg);
1153 		else if (class == BPF_LDX && insn->src_reg != BPF_REG_FP)
1154 			base_regs |= BIT(insn->src_reg);
1155 	}
1156 
1157 	if (class == BPF_JMP && BPF_OP(insn->code) == BPF_CALL &&
1158 	    bpf_needs_fixed_stack_off(env, idx))
1159 		base_regs |= call_params_mask(env, idx);
1160 
1161 	base_regs &= aux[idx].stack_ptrs;
1162 	for (r = 0; r < MAX_BPF_REG; r++)
1163 		if (base_regs & BIT(r))
1164 			or_expr_regs(env, cur_env->reg2expr[r], mask);
1165 }
1166 
1167 /* Find the topmost loop header containing idx inside cur_header, or -1 if none. */
1168 static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_header)
1169 {
1170 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1171 	int header;
1172 
1173 	for (header = bpf_loop_at_index(env, idx); header >= 0;
1174 	     header = aux[header].loop_header)
1175 		if (aux[header].loop_header == cur_header)
1176 			return header;
1177 
1178 	return -1;
1179 }
1180 
1181 /*
1182  * Join cur_env into the successor's environment and schedule their traversal.
1183  * Map successors in nested loops to their topmost nested header.
1184  * Ignore successors outside the current loop and its nested loops.
1185  */
1186 static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
1187 			  struct env *old_env, struct env *cur_env)
1188 {
1189 	bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
1190 	struct scev *scev = env->scev;
1191 	int err, nested_header;
1192 	struct env *succ_env;
1193 
1194 	/*
1195 	 * There are several possibilities for a successor:
1196 	 * - succ_idx can be a part of a loop outside of the cur_header's loop,
1197 	 *   such edges are ignored.
1198 	 * - succ_idx can be a part of the same loop as cur_header,
1199 	 *   for such edges succ_idx environment is updated:
1200 	 *     e[succ_idx] = join(e[succ_idx], cur_env)
1201 	 * - succ_idx can be a part of some loop inner to cur_header,
1202 	 *   in such a case there exists some loop header H,
1203 	 *   such that H.loop_header == cur_header
1204 	 *   and H is the same as succ_idx's loop or contains it.
1205 	 */
1206 	if (bpf_loop_at_index(env, succ_idx) != cur_header) {
1207 		/*
1208 		 * topmost_nested_loop() either finds H or returns -1,
1209 		 * in case if succ_idx is a part of a loop outer to cur_header.
1210 		 */
1211 		nested_header = topmost_nested_loop(env, succ_idx, cur_header);
1212 		if (nested_header < 0)
1213 			return 0;
1214 		succ_idx = nested_header;
1215 	}
1216 	succ_env = get_loop_env(scev, cur_header, succ_idx);
1217 	if (!succ_env)
1218 		return -ENOMEM;
1219 	if (log_level2)
1220 		memcpy(old_env, succ_env, sizeof(*old_env));
1221 	err = join(scev, succ_env, cur_env);
1222 	if (err)
1223 		return err;
1224 	err = worklist_push(env, cur_header, succ_idx);
1225 	if (err)
1226 		return err;
1227 	if (log_level2)
1228 		log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
1229 	return 0;
1230 }
1231 
1232 /* Unsupported loops get only an unknown header environment. */
1233 static bool can_compute_loop_scev(const struct bpf_loop *loop)
1234 {
1235 	return !loop->irreducible && !loop->exits_overflow;
1236 }
1237 
1238 static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
1239 {
1240 	struct scev_worklist *worklist = &env->scev->worklist;
1241 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1242 	struct bpf_loop *cur_loop = aux[cur_header].loop;
1243 	struct env *header_env;
1244 	struct scev *scev = env->scev;
1245 	struct bpf_loop *nested_loop;
1246 	struct env *cur_env = NULL;
1247 	struct env *old_env = NULL;
1248 	struct bpf_iarray *succ;
1249 	bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
1250 	int s, i, err, idx, succ_idx;
1251 	u32 r;
1252 
1253 	if (log_level2)
1254 		bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
1255 
1256 	/*
1257 	 * For irreducible loops, and for loops nesting a loop with a truncated
1258 	 * exit list, just assume that everything is clobbered for now.
1259 	 */
1260 	if (!can_compute_loop_scev(cur_loop)) {
1261 		header_env = get_loop_env(scev, cur_header, cur_header);
1262 		if (!header_env)
1263 			return -ENOMEM;
1264 		/* The freshly allocated environment has all expressions unknown. */
1265 		bitmap_fill(cur_loop->store_base_regs, REGS_NUM);
1266 		header_env->empty = false;
1267 		return 0;
1268 	}
1269 
1270 	cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
1271 	if (!cur_env)
1272 		goto nomem;
1273 	if (log_level2) {
1274 		old_env = kzalloc(sizeof(*old_env), GFP_KERNEL_ACCOUNT);
1275 		if (!old_env)
1276 			goto nomem;
1277 	}
1278 	header_env = get_loop_env(scev, cur_header, cur_header);
1279 	if (!header_env)
1280 		goto nomem;
1281 	err = setup_initial_loop_env(env, header_env, cur_header);
1282 	if (err)
1283 		goto out;
1284 	err = worklist_push(env, cur_header, cur_header);
1285 	if (err)
1286 		goto out;
1287 
1288 	while (worklist->nr) {
1289 		idx = *min_heap_peek_inline(worklist);
1290 		min_heap_pop_inline(worklist, &worklist_cb, env->cfg.postorder_nums);
1291 
1292 		/* join_successor() maps nested-loop entries to their representative header. */
1293 		nested_loop = idx != cur_header ? aux[idx].loop : NULL;
1294 		memcpy(cur_env, find_loop_env(scev, cur_header, idx), sizeof(*cur_env));
1295 		if (nested_loop) {
1296 			/*
1297 			 * Process nested loop as a single instruction by
1298 			 * forgetting anything non-invariant in the nested loop
1299 			 */
1300 			if (log_level2)
1301 				memcpy(old_env, cur_env, sizeof(*old_env));
1302 			/* Pull the nested loop's stack-store base dependencies up. */
1303 			for_each_set_bit(r, nested_loop->store_base_regs, BPF_SCEV_REGS_NUM)
1304 				or_expr_regs(env, cur_env->reg2expr[r], cur_loop->store_base_regs);
1305 			forget_non_invariants(env, cur_env, idx);
1306 			if (log_level2)
1307 				log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
1308 			/*
1309 			 * Treat nested loop exits as successors,
1310 			 * join cur_env into successor's envs.
1311 			 */
1312 			for (i = 0; i < nested_loop->exits_cnt; i++) {
1313 				s = nested_loop->exits[i].to;
1314 				err = join_successor(env, cur_header, s, old_env, cur_env);
1315 				if (err)
1316 					goto out;
1317 			}
1318 		} else {
1319 			/*
1320 			 * Iterate instructions within a single basic block
1321 			 * starting at 'idx' mutating 'cur_env'.
1322 			 */
1323 			for (;;) {
1324 				if (log_level2)
1325 					memcpy(old_env, cur_env, sizeof(*old_env));
1326 				collect_store_base_regs(env, cur_env, idx, cur_loop->store_base_regs);
1327 				err = transfer(env, cur_env, idx);
1328 				if (err)
1329 					goto out;
1330 				reset_scevs_at_indirect_writes(env, cur_env, idx);
1331 				if (log_level2)
1332 					log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
1333 				succ = bpf_insn_successors(env, idx);
1334 				if (succ->cnt != 1)
1335 					break;
1336 				succ_idx = succ->items[0];
1337 				if (aux[idx].bb_end || aux[succ_idx].need_scev ||
1338 				    bpf_loop_at_index(env, succ_idx) != cur_header)
1339 					break;
1340 				idx = succ_idx;
1341 			}
1342 			/* Join cur_env into basic block successor's envs. */
1343 			iarray_for_each(s, succ) {
1344 				err = join_successor(env, cur_header, s, old_env, cur_env);
1345 				if (err)
1346 					goto out;
1347 			}
1348 		}
1349 	}
1350 
1351 	err = 0;
1352 out:
1353 	kfree(cur_env);
1354 	kfree(old_env);
1355 	return err;
1356 nomem:
1357 	err = -ENOMEM;
1358 	goto out;
1359 }
1360 
1361 static void mark_latches(struct bpf_verifier_env *env)
1362 {
1363 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1364 	struct bpf_loop *loop;
1365 	int len = env->prog->len;
1366 	int i, j, k, from;
1367 
1368 	for (i = 0; i < len; i++) {
1369 		loop = aux[i].loop;
1370 		if (!loop)
1371 			continue;
1372 		aux[i].need_scev = true;
1373 		if (!can_compute_loop_scev(loop))
1374 			continue;
1375 		/*
1376 		 * Make sure to only set .need_scev for exits and latches
1377 		 * belonging to the loop at `i`. If can_compute_loop_scev()
1378 		 * fails for a loop, it should hide it's instructions from
1379 		 * compute_insn_scevs().
1380 		 */
1381 		for (j = 0; j < loop->backedges_cnt; j++)
1382 			for (k = 0; k < loop->backedges[j].latches_cnt; k++)
1383 				aux[loop->backedges[j].latches[k]].need_scev = true;
1384 		for (j = 0; j < loop->exits_cnt; j++) {
1385 			from = loop->exits[j].from;
1386 			if (bpf_loop_at_index(env, from) == i)
1387 				aux[from].need_scev = true;
1388 		}
1389 	}
1390 }
1391 
1392 static bool is_any_imm_reg_opaque(struct scev *scev, u32 id)
1393 {
1394 	u32 l, r, reg, order;
1395 	s64 imm;
1396 
1397 	scev->stack_sz = 0;
1398 	expr_stack_push(scev, id);
1399 	while (expr_next(scev, &id, &order)) {
1400 		if (order & DEPTH_LIMIT)
1401 			return false;
1402 		if (!(order & PRE) ||
1403 		    is_imm(scev, id, &imm) ||
1404 		    is_reg(scev, id, &reg) ||
1405 		    is_opaque(scev, id) ||
1406 		    is_any(scev, id, &l, &r))
1407 			continue;
1408 		return false;
1409 	}
1410 	return true;
1411 }
1412 
1413 /*
1414  * Can implement explicit stack version, but it is harder to read.
1415  * Stick with recursive version for now.
1416  */
1417 static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
1418 			       int (*fn)(struct scev *scev, u32 id, void *priv))
1419 {
1420 	struct expr expr;
1421 	int p0, p1, id;
1422 
1423 	if (lvl >= EXPR_STACK_DEPTH)
1424 		return UNKNOWN_EXPR_ID;
1425 
1426 	expr = scev->exprs[root]; /* snapshot the expr before potential realloc */
1427 	switch (op_params_num(expr.op)) {
1428 	case 0:
1429 		id = root;
1430 		break;
1431 	case 1:
1432 		p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
1433 		id = expr1(scev, expr.op, p0);
1434 		break;
1435 	case 2:
1436 		p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
1437 		p1 = transform_expr_once(scev, lvl + 1, expr.params[1], priv, fn);
1438 		id = expr2(scev, expr.op, p0, p1);
1439 		break;
1440 	}
1441 	return id < 0 ? id : fn(scev, id, priv);
1442 }
1443 
1444 static int transform_expr(struct scev *scev, u32 root, void *priv,
1445 			  int (*fn)(struct scev *scev, u32 id, void *priv))
1446 {
1447 	int i = 0, id_old, id_new = root;
1448 
1449 	do {
1450 		/*
1451 		 * The depth limit is somewhat arbitrary and is essentially a failsafe.
1452 		 * oscillation should not really happen. Still, it seems harsh to error out.
1453 		 */
1454 		if (i++ == 4 * EXPR_STACK_DEPTH)
1455 			return UNKNOWN_EXPR_ID;
1456 		id_old = id_new;
1457 		id_new = transform_expr_once(scev, 0, id_old, priv, fn);
1458 		if (id_new < 0)
1459 			return id_new;
1460 	} while (id_old != id_new);
1461 	return id_new;
1462 }
1463 
1464 static int simplify(struct scev *scev, u32 id, void *priv)
1465 {
1466 	u32 l, r, base, slope;
1467 	s64 imm1, imm2;
1468 
1469 	/* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
1470 	if (is_add(scev, id, &l, &r) &&
1471 	    is_linear(scev, l, &base, &slope) &&
1472 	    is_imm(scev, r, &imm1))
1473 		return expr2(scev, LINEAR_SCEV, expr2(scev, BPF_ADD, base, r), slope);
1474 
1475 	/* (+ imm imm) -> imm */
1476 	if (is_add(scev, id, &l, &r) &&
1477 	    is_imm(scev, l, &imm1) &&
1478 	    is_imm(scev, r, &imm2))
1479 		return imm_expr(scev, imm1 + imm2);
1480 
1481 	/* (zext32 (imm X)) -> (imm (u32)X) */
1482 	if (is_zext32(scev, id, &l) && is_imm(scev, l, &imm1))
1483 		return imm_expr(scev, (u64)(u32)imm1);
1484 
1485 	return id;
1486 }
1487 
1488 static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
1489 {
1490 	struct scev *scev = env->scev;
1491 	int l, r, id, ra, rb, ra_expr;
1492 	s64 imm;
1493 
1494 	/*
1495 	 * Note:
1496 	 * reg2expr[ra] describes a change in rA's value over a single loop iteration.
1497 	 * It does not account for rA's entry value. However, the SCEV constructed for rA
1498 	 * must include an additional rA entry edge. For example:
1499 	 *
1500 	 *      r0 = ..., r1 = 7
1501 	 *   l: if r0 == 10 goto e // reg2expr[r1] == (imm 42) => reg2scev[r1] == (any r1 42)
1502 	 *      r0 += 1
1503 	 *      r1 = 42
1504 	 *      goto l
1505 	 *   e:
1506 	 *      ... at exit r1 is in {7,42} ...
1507 	 */
1508 	for (ra = 0; ra < REGS_NUM; ra++) {
1509 		ra_expr = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
1510 		if (ra_expr < 0)
1511 			return ra_expr;
1512 		header_env->reg2expr[ra] = ra_expr;
1513 		/* rA = (+ rA IMM) -> (linear rA IMM) */
1514 		if (is_add(scev, ra_expr, &l, &r) &&
1515 		    is_reg(scev, l, &rb) &&
1516 		    is_imm(scev, r, &imm) &&
1517 		    ra == rb) {
1518 			id = expr2(scev, LINEAR_SCEV, l, r);
1519 			if (id < 0)
1520 				return id;
1521 			header_env->reg2scev[ra] = id;
1522 			continue;
1523 		}
1524 		/* rA = rA -> rA*/
1525 		if (is_reg(scev, ra_expr, &rb) && ra == rb) {
1526 			header_env->reg2scev[ra] = ra_expr;
1527 			continue;
1528 		}
1529 		/* rA = (any 1 2 3 4 ...) -> (any rA 1 2 3 4 ...) */
1530 		if (is_any_imm_reg_opaque(scev, ra_expr)) {
1531 			id = mk_any(scev, expr1(scev, REG, ra), ra_expr);
1532 			if (id < 0)
1533 				return id;
1534 			header_env->reg2scev[ra] = id;
1535 			continue;
1536 		}
1537 
1538 	}
1539 	return 0;
1540 }
1541 static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
1542 {
1543 	u32 reg, *reg2scev = priv;
1544 
1545 	/* (reg r) -> ... equation at header ... */
1546 	if (is_reg(scev, id, &reg))
1547 		return reg2scev[reg];
1548 	/* keep expression shapes */
1549 	return id;
1550 }
1551 
1552 static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
1553 {
1554 	struct scev *scev = env->scev;
1555 	int id, reg;
1556 
1557 	for (reg = 0; reg < REGS_NUM; reg++) {
1558 		id = einsn->reg2expr[reg];
1559 		id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
1560 		if (id < 0)
1561 			return id;
1562 		id = transform_expr(scev, id, NULL, simplify);
1563 		if (id < 0)
1564 			return id;
1565 		einsn->reg2scev[reg] = id;
1566 	}
1567 
1568 	return 0;
1569 }
1570 
1571 static int log_scevs(struct bpf_verifier_env *env)
1572 {
1573 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1574 	struct bpf_verifier_log *log = &env->log;
1575 	struct env *header_env, *latch_env;
1576 	struct scev *scev = env->scev;
1577 	struct bpf_loop *loop;
1578 	int i, j, k, len, latch;
1579 
1580 	len = env->prog->len;
1581 	for (i = 0; i < len; i++) {
1582 		loop = aux[i].loop;
1583 		if (!loop)
1584 			continue;
1585 		header_env = find_header_env(scev, i);
1586 		bpf_log(log, "scev at header %d:\n", i);
1587 		print_env(env, header_env, i);
1588 		if (!can_compute_loop_scev(loop))
1589 			continue;
1590 		for (j = 0; j < loop->backedges_cnt; j++) {
1591 			for (k = 0; k < loop->backedges[j].latches_cnt; k++) {
1592 				latch = loop->backedges[j].latches[k];
1593 				bpf_log(log, " scev at %s %d:\n", k ? "exit" : "latch", latch);
1594 				latch_env = find_loop_env(scev, i, latch);
1595 				if (verifier_bug_if(!latch_env, env, "i=%d, latch=%d", i, latch))
1596 					return -EFAULT;
1597 				print_env(env, latch_env, latch);
1598 			}
1599 		}
1600 	}
1601 	return 0;
1602 }
1603 
1604 int bpf_compute_scev(struct bpf_verifier_env *env)
1605 {
1606 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1607 	struct scev *scev = env->scev;
1608 	int *postorder = env->cfg.insn_postorder;
1609 	int cnt = env->cfg.cur_postorder;
1610 	int i, idx, err, header;
1611 
1612 	mark_latches(env);
1613 	/*
1614 	 * Visit loop headers in postorder, to guarantee that scevs
1615 	 * for innermost loops are computed first.
1616 	 */
1617 	for (i = 0; i < cnt; i++) {
1618 		idx = postorder[i];
1619 		if (!aux[idx].loop)
1620 			continue;
1621 		err = compute_scev_for_loop(env, idx);
1622 		if (err)
1623 			return err;
1624 	}
1625 
1626 	/*
1627 	 * Compute scevs from exprs collected on a previous step. Iterate instructions in
1628 	 * reverse post-order so that each loop header is processed before instructions
1629 	 * reachable from it.
1630 	 */
1631 	for (i = cnt - 1; i >= 0; i--) {
1632 		idx = postorder[i];
1633 		if (!aux[idx].need_scev)
1634 			continue;
1635 		header = bpf_loop_at_index(env, idx);
1636 		err = aux[idx].loop
1637 		      ? compute_header_scevs(env, find_header_env(scev, header))
1638 		      : compute_insn_scevs(env,
1639 					   find_header_env(scev, header),
1640 					   find_loop_env(scev, header, idx));
1641 		if (err)
1642 			return err;
1643 	}
1644 
1645 	for (i = 0; i < env->prog->len; i++)
1646 		if (aux[i].loop)
1647 			aux[i].prune_point = true;
1648 
1649 	if (env->log.level & BPF_LOG_LEVEL2) {
1650 		err = log_scevs(env);
1651 		if (err)
1652 			return err;
1653 	}
1654 
1655 	return 0;
1656 }
1657 
1658 void bpf_free_scev(struct bpf_verifier_env *env)
1659 {
1660 	struct scev *scev = env->scev;
1661 	struct insn_envs *envs;
1662 	int i;
1663 	u32 j;
1664 
1665 	if (!scev)
1666 		return;
1667 	for (i = 0; i < scev->envs_cnt; i++) {
1668 		envs = scev->envs[i];
1669 		if (!envs)
1670 			continue;
1671 		for (j = 0; j < envs->cnt; j++)
1672 			kfree(envs->entries[j].env);
1673 		kfree(envs);
1674 	}
1675 	if (scev->exprs_ht)
1676 		for (i = 0; i < scev->exprs_ht_cnt; i++)
1677 			kvfree(scev->exprs_ht[i]);
1678 	kvfree(scev->exprs_ht);
1679 	kvfree(scev->worklist.data);
1680 	kvfree(scev->envs);
1681 	kvfree(scev->exprs);
1682 	kvfree(scev->discovered);
1683 	kfree(scev);
1684 	env->scev = NULL;
1685 }
1686 
1687 int bpf_init_scev(struct bpf_verifier_env *env)
1688 {
1689 	struct scev *scev;
1690 
1691 	scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
1692 	if (!scev)
1693 		return -ENOMEM;
1694 	env->scev = scev;
1695 	bpf_mark_reg_known_scalar(&scev->zero_reg, 0);
1696 	bpf_mark_reg_unknown_imprecise(&scev->unknown_reg);
1697 	/* A power of two for hash & (exprs_ht_cnt - 1)` indexing. */
1698 	scev->exprs_ht_cnt = roundup_pow_of_two(max(256U, DIV_ROUND_UP(env->prog->len, 4)));
1699 	scev->exprs_ht = kvcalloc(scev->exprs_ht_cnt, sizeof(*scev->exprs_ht), GFP_KERNEL_ACCOUNT);
1700 	if (!scev->exprs_ht)
1701 		goto nomem;
1702 	if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE)  < 0)
1703 		goto nomem;
1704 	scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
1705 	scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
1706 	if (!scev->envs || !scev->discovered)
1707 		goto nomem;
1708 	/*
1709 	 * Remember original program length, in case bpf_free_scev()
1710 	 * is called after bpf program rewrites that increase program
1711 	 * length.
1712 	 */
1713 	scev->envs_cnt = env->prog->len;
1714 	return 0;
1715 nomem:
1716 	bpf_free_scev(env);
1717 	return -ENOMEM;
1718 }
1719 
1720 static struct bpf_stack_state *scev_regno_to_stack(const struct bpf_func_state *st, u32 r)
1721 {
1722 	int spi, slots_available;
1723 
1724 	if (r < MAX_BPF_REG)
1725 		return NULL;
1726 
1727 	slots_available = st->allocated_stack / BPF_REG_SIZE;
1728 	spi = r - MAX_BPF_REG;
1729 	if (spi < slots_available)
1730 		return &st->stack[spi];
1731 
1732 	return NULL;
1733 }
1734 
1735 static struct bpf_reg_state *scev_regno_to_reg(struct bpf_func_state *st, u32 r)
1736 {
1737 	return r < MAX_BPF_REG ? &st->regs[r] : NULL;
1738 }
1739 
1740 /* Linear widening requires a physical register or a full spill. */
1741 static struct bpf_reg_state *scev_reg_for_linear(struct bpf_func_state *st, u32 r)
1742 {
1743 	struct bpf_stack_state *stack;
1744 
1745 	if (r < MAX_BPF_REG)
1746 		return scev_regno_to_reg(st, r);
1747 	stack = scev_regno_to_stack(st, r);
1748 	if (!stack || bpf_spill_size(stack) != BPF_REG_SIZE)
1749 		return NULL;
1750 	return &stack->spilled_ptr;
1751 }
1752 
1753 /*
1754  * Return a borrowed value; never use it as a widening destination.
1755  * NULL denotes no readable value.
1756  */
1757 static const struct bpf_reg_state *
1758 scev_reg_for_read(struct bpf_verifier_env *env, const struct bpf_func_state *st, u32 r)
1759 {
1760 	const struct bpf_stack_state *stack;
1761 	bool zero = true;
1762 	int i;
1763 
1764 	if (r < MAX_BPF_REG)
1765 		return st->regs[r].type == NOT_INIT ? NULL : &st->regs[r];
1766 	if (r >= REGS_NUM || r - MAX_BPF_REG >= env->stack_limit / BPF_REG_SIZE)
1767 		return NULL;
1768 
1769 	stack = scev_regno_to_stack(st, r);
1770 	if (!stack)
1771 		return &env->scev->unknown_reg;
1772 	if (bpf_spill_size(stack) == BPF_REG_SIZE)
1773 		return &stack->spilled_ptr;
1774 
1775 	/* Partial spills do not describe the value of the whole slot. */
1776 	for (i = 0; i < BPF_REG_SIZE; i++) {
1777 		switch (stack->slot_type[i]) {
1778 		case STACK_ZERO:
1779 			break;
1780 		case STACK_INVALID:
1781 		case STACK_POISON:
1782 		case STACK_MISC:
1783 			zero = false;
1784 			break;
1785 		case STACK_SPILL:
1786 			if (!bpf_is_spilled_scalar_reg(stack))
1787 				return NULL;
1788 			zero = false;
1789 			break;
1790 		default:
1791 			return NULL;
1792 		}
1793 	}
1794 	return zero ? &env->scev->zero_reg : &env->scev->unknown_reg;
1795 }
1796 
1797 /* Materialize a writable value in the current state, growing its stack if needed. */
1798 static int scev_reg_for_write(struct bpf_verifier_env *env, struct bpf_func_state *st,
1799 			      u32 r, struct bpf_reg_state **out)
1800 {
1801 	const struct bpf_reg_state *value;
1802 	struct bpf_stack_state *stack;
1803 	u32 spi;
1804 	int err;
1805 
1806 	*out = scev_regno_to_reg(st, r);
1807 	if (*out)
1808 		return 0;
1809 	if (r >= REGS_NUM || r - MAX_BPF_REG >= env->stack_limit / BPF_REG_SIZE)
1810 		return -EINVAL;
1811 
1812 	spi = r - MAX_BPF_REG;
1813 	err = bpf_grow_stack_state(env, st, (spi + 1) * BPF_REG_SIZE);
1814 	if (err)
1815 		return err;
1816 
1817 	/* Resolve pointers after growth, which may relocate the stack. */
1818 	value = scev_reg_for_read(env, st, r);
1819 	if (!value)
1820 		return -EINVAL;
1821 	stack = scev_regno_to_stack(st, r);
1822 	stack->spilled_ptr = *value;
1823 	memset(stack->slot_type, STACK_SPILL, sizeof(stack->slot_type));
1824 	*out = &stack->spilled_ptr;
1825 	return 0;
1826 }
1827 
1828 static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 r)
1829 {
1830 	int insn_idx = bpf_frame_insn_idx(st, st->curframe);
1831 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
1832 	int spi;
1833 
1834 	if (r < MAX_BPF_REG) {
1835 		return BIT(r) & live_regs;
1836 	} else {
1837 		spi = r - MAX_BPF_REG;
1838 		return bpf_stack_slot_alive(env, st->curframe, spi * 2) ||
1839 		       bpf_stack_slot_alive(env, st->curframe, spi * 2 + 1);
1840 	}
1841 }
1842 
1843 /*
1844  * Latch is a condition deciding if execution remains inside a loop.
1845  * Linear latch represents a condition 'if <reg> <op> <loop invariant> goto <loop-header>',
1846  * where equation '<base> + i * <step> <op> <bound>' describes values taken by register <reg>,
1847  * 'i' is the loop iteration number, starting from 0.
1848  */
1849 struct linear_latch {
1850 	u32 insn_idx;
1851 	u32 base_expr;
1852 	u32 step_expr;
1853 	u32 bound_expr;
1854 	u32 op;
1855 };
1856 
1857 static bool loop_invariant(struct scev *scev, u32 id)
1858 {
1859 	s64 imm;
1860 	u32 reg;
1861 
1862 	return is_reg(scev, id, &reg) || is_imm(scev, id, &imm);
1863 }
1864 
1865 static int match_linear_latch(struct bpf_verifier_env *env,
1866 			      u32 header,
1867 			      u32 latch_idx,
1868 			      struct linear_latch *latch)
1869 {
1870 	struct bpf_insn *insn = &env->prog->insnsi[latch_idx];
1871 	struct scev *scev = env->scev;
1872 	struct env *latch_env;
1873 	u32 true_branch_loop;
1874 	u32 true_branch_tgt;
1875 	u32 src_reg_scev;
1876 	u32 dst_reg_scev;
1877 	u32 t, l, r, op;
1878 	int id;
1879 
1880 	/* 32-bit arithmetic is not handled yet */
1881 	if (BPF_CLASS(insn->code) != BPF_JMP)
1882 		return false;
1883 	op = BPF_OP(insn->code);
1884 	/* Flip the condition if true branch jumps out of the loop. */
1885 	true_branch_tgt = latch_idx + bpf_jmp_offset(insn) + 1;
1886 	true_branch_loop = bpf_loop_at_index(env, true_branch_tgt);
1887 	if (true_branch_loop != header &&
1888 	    !bpf_is_nested_loop(env, true_branch_loop, header))
1889 		op = bpf_rev_opcode(op);
1890 	switch (op) {
1891 	case BPF_JSLT:
1892 	case BPF_JSLE:
1893 	case BPF_JSGT:
1894 	case BPF_JSGE:
1895 	case BPF_JLT:
1896 	case BPF_JLE:
1897 	case BPF_JGT:
1898 	case BPF_JGE:
1899 	case BPF_JNE:
1900 		break;
1901 	default:
1902 		return false;
1903 	}
1904 
1905 	latch->insn_idx = latch_idx;
1906 
1907 	latch_env = find_loop_env(scev, header, latch_idx);
1908 	if (verifier_bug_if(!latch_env, env, "header_idx=%d, latch_idx=%d\n", header, latch_idx))
1909 		return -EFAULT;
1910 	dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
1911 	src_reg_scev = latch_env->reg2scev[insn->src_reg];
1912 	/*
1913 	 * Make sure (linear ...) is in dst_reg_scev:
1914 	 *   'if <invariant> <op> <linear>' ⇔
1915 	 * 'if <linear> <flip(op)> <invariant>'.
1916 	 */
1917 	if (BPF_SRC(insn->code) == BPF_X && is_linear(scev, src_reg_scev, &l, &r)) {
1918 		swap(dst_reg_scev, src_reg_scev);
1919 		op = bpf_flip_opcode(op);
1920 	}
1921 	latch->op = op;
1922 	/*
1923 	 * simplify() produces two shapes for linear latches:
1924 	 * - (linear register step)
1925 	 *           ^----------------------------+-- base_expr
1926 	 *           base_expr                    |
1927 	 * - (linear (+ register imm) step)       |
1928 	 *           ^----------------------------'
1929 	 */
1930 	if (!is_linear(scev, dst_reg_scev, &latch->base_expr, &latch->step_expr))
1931 		return false;
1932 
1933 	if (BPF_SRC(insn->code) == BPF_K) {
1934 		id = imm_expr(scev, insn->imm);
1935 		if (id < 0)
1936 			return id;
1937 		latch->bound_expr = id;
1938 	} else {
1939 		latch->bound_expr = src_reg_scev;
1940 	}
1941 
1942 	if (!loop_invariant(scev, latch->step_expr) ||
1943 	    !loop_invariant(scev, latch->bound_expr))
1944 		return false;
1945 
1946 	/* (linear register step) */
1947 	if (is_reg(scev, latch->base_expr, &t))
1948 		return true;
1949 
1950 	/* (linear (+ register imm) step) */
1951 	if (is_add(scev, latch->base_expr, &l, &r) &&
1952 	    is_reg(scev, l, &t) &&
1953 	    loop_invariant(scev, r))
1954 		return true;
1955 
1956 	return false;
1957 }
1958 
1959 struct scev_value {
1960 	u64 value;	/* scalar value or a pointer offset */
1961 	int ptr_reg;	/* SCEV register identifying the pointer origin, or -1. */
1962 };
1963 
1964 static void log_scev_value(struct bpf_verifier_env *env, struct bpf_func_state *st,
1965 			   const struct scev_value *v)
1966 {
1967 	const struct bpf_reg_state *reg;
1968 
1969 	if (v->ptr_reg >= 0) {
1970 		reg = scev_reg_for_read(env, st, v->ptr_reg);
1971 		log_reg(env, v->ptr_reg);
1972 		bpf_log(&env->log, " (%s)", reg ? reg_type_str(env, reg->type) : "unavailable");
1973 	} else {
1974 		bpf_log(&env->log, "scalar %llu", v->value);
1975 	}
1976 }
1977 
1978 static void log_incompatible_scev_values(struct bpf_verifier_env *env, const char *reason,
1979 					struct bpf_func_state *st,
1980 					const struct scev_value *a, const struct scev_value *b)
1981 {
1982 	bpf_log(&env->log, "scev: %s ", reason);
1983 	log_scev_value(env, st, a);
1984 	bpf_log(&env->log, ", ");
1985 	log_scev_value(env, st, b);
1986 	bpf_log(&env->log, "\n");
1987 }
1988 
1989 static bool scev_value_compatible(struct bpf_verifier_env *env, struct bpf_func_state *st,
1990 				  const struct scev_value *a, const struct scev_value *b)
1991 {
1992 	const struct bpf_reg_state *ra, *rb;
1993 
1994 	if (a->ptr_reg < 0 || b->ptr_reg < 0) {
1995 		if (a->ptr_reg < 0 && b->ptr_reg < 0)
1996 			return true;
1997 		goto incompatible;
1998 	}
1999 	ra = scev_reg_for_read(env, st, a->ptr_reg);
2000 	rb = scev_reg_for_read(env, st, b->ptr_reg);
2001 	if (ra && rb && bpf_same_memory_origin(ra, rb))
2002 		return true;
2003 
2004 incompatible:
2005 	if (env->log.level & BPF_LOG_LEVEL2)
2006 		log_incompatible_scev_values(env, "incompatible latch operands", st, a, b);
2007 	return false;
2008 }
2009 
2010 static bool scev_value_add(struct bpf_verifier_env *env, struct bpf_func_state *st,
2011 			   const struct scev_value *a, const struct scev_value *b,
2012 			   struct scev_value *result)
2013 {
2014 	if (a->ptr_reg >= 0 && b->ptr_reg >= 0) {
2015 		if (env->log.level & BPF_LOG_LEVEL2)
2016 			log_incompatible_scev_values(env, "can't add two pointers", st, a, b);
2017 		return false;
2018 	}
2019 	result->value = a->value + b->value;
2020 	result->ptr_reg = a->ptr_reg >= 0 ? a->ptr_reg : b->ptr_reg;
2021 	return true;
2022 }
2023 
2024 static bool eval_expr(struct bpf_verifier_env *env, struct scev *scev,
2025 		      struct bpf_func_state *st, u32 id, struct scev_value *result)
2026 {
2027 	struct scev_value lval, rval;
2028 	const struct bpf_reg_state *reg;
2029 	u32 l, r, regno;
2030 	s64 imm;
2031 
2032 	if (is_reg(scev, id, &regno)) {
2033 		reg = scev_reg_for_read(env, st, regno);
2034 		if (!reg || reg->type == NOT_INIT || !tnum_is_const(reg->var_off))
2035 			return false;
2036 		result->value = reg->var_off.value;
2037 		result->ptr_reg = reg->type == SCALAR_VALUE ? -1 : (int)regno;
2038 		return true;
2039 	} else if (is_imm(scev, id, &imm)) {
2040 		result->value = imm;
2041 		result->ptr_reg = -1;
2042 		return true;
2043 	} else if (is_add(scev, id, &l, &r) &&
2044 		   eval_expr(env, scev, st, l, &lval) &&
2045 		   eval_expr(env, scev, st, r, &rval)) {
2046 		return scev_value_add(env, st, &lval, &rval, result);
2047 	}
2048 	return false;
2049 }
2050 
2051 /*
2052  * Loop with post-condition:
2053  *
2054  *    r0 = 0
2055  * l: ...                r0 ∈ [0,1,2] header executed 3 times
2056  *    r0 += 1            r0 ∈ [0,1,2]
2057  *    ...                r0 ∈ [1,2,3]
2058  *    if r0 != 3 goto l  r0 ∈ [1,2,3] backedge taken 2 times
2059  *    ...                r0 ∈ [3]
2060  *
2061  * SCEV at header: r0 = k
2062  * SCEV at latch:  r0 = 1 + k
2063  *
2064  * Loop with pre-condition:
2065  *
2066  *    r0 = 0
2067  * l: ...                r0 ∈ [0,1,2,3] header executed 4 times
2068  *    if r0 == 3 goto e  r0 ∈ [0,1,2,3] backedge taken 3 times
2069  *    r0 += 1            r0 ∈ [0,1,2]
2070  *    ...                r0 ∈ [1,2,3]
2071  *    goto l             r0 ∈ [1,2,3]
2072  * e: ...                r0 ∈ [3]
2073  *
2074  * SCEV at header: r0 = k
2075  * SCEV at latch:  r0 = k
2076  */
2077 static bool compute_max_iters(struct bpf_verifier_env *env,
2078 			      struct bpf_func_state *st,
2079 			      struct linear_latch *latch,
2080 			      struct bpf_loop_iters *iters)
2081 {
2082 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
2083 	struct bpf_loop *loop = aux[bpf_loop_at_index(env, latch->insn_idx)].loop;
2084 	struct scev *scev = env->scev;
2085 	struct scev_value initial_val, step_val, bound_val;
2086 	u64 step, diff, bound, initial, backedge_taken_count;
2087 	u8 op = latch->op;
2088 	bool up, down;
2089 
2090 	if (!eval_expr(env, scev, st, latch->base_expr, &initial_val) ||
2091 	    !eval_expr(env, scev, st, latch->step_expr, &step_val) ||
2092 	    !eval_expr(env, scev, st, latch->bound_expr, &bound_val))
2093 		return false;
2094 
2095 	if (step_val.ptr_reg >= 0) {
2096 		if (env->log.level & BPF_LOG_LEVEL2) {
2097 			bpf_log(&env->log, "scev: latch step is a pointer ");
2098 			log_scev_value(env, st, &step_val);
2099 			bpf_log(&env->log, "\n");
2100 		}
2101 		return false;
2102 	}
2103 	if (!scev_value_compatible(env, st, &initial_val, &bound_val))
2104 		return false;
2105 
2106 	initial = initial_val.value;
2107 	step = step_val.value;
2108 	bound = bound_val.value;
2109 
2110 	if (step == 0)
2111 		return false;
2112 	down = (s64)step < 0;
2113 	up = (s64)step > 0;
2114 	diff = bound - initial;
2115 	switch (op) {
2116 	case BPF_JLT:
2117 		/*
2118 		 * E.g.: 3 + 2*i < 7 ⇔ 2*i < 4 ⇔ i ∈ [0,1].
2119 		 * Here the inequality describes a set of values `i` might take
2120 		 * while the latch condition remains true (the backedge is taken).
2121 		 * The backedge_taken_count is the size of this set.
2122 		 */
2123 		if (/*
2124 		     * If the condition is initially true, decreasing values won't
2125 		     * change that without underflow. If the condition is initially false,
2126 		     * the main pass would do a single iteration anyway.
2127 		     */
2128 		    down ||
2129 		    /* Is the latch condition false on the first iteration? */
2130 		    initial >= bound ||
2131 		    /* Count iterations satisfying the strict inequality, including i=0. */
2132 		    check_add_overflow((diff - 1) / step, 1, &backedge_taken_count) ||
2133 		    /*
2134 		     * Check if the last iteration overflows the counter:
2135 		     *   initial + backedge_taken_count * step > U64_MAX
2136 		     */
2137 		    backedge_taken_count > (U64_MAX - initial) / step)
2138 			return false;
2139 		break;
2140 	case BPF_JLE:
2141 		/* E.g.: 3 + 2*i ≤ 7 ⇔ 2*i ≤ 4 ⇔ i ∈ [0,1,2]. */
2142 		if (down || initial > bound ||
2143 		    /* Count iterations satisfying the non-strict inequality. */
2144 		    check_add_overflow(diff / step, 1, &backedge_taken_count) ||
2145 		    backedge_taken_count > (U64_MAX - initial) / step)
2146 			return false;
2147 		break;
2148 	case BPF_JGT:
2149 		/* E.g.: 7 - 2*i > 3 ⇔ 2*i < 4 ⇔ i ∈ [0,1]. */
2150 		if (up || initial <= bound ||
2151 		    check_add_overflow((-diff - 1) / -step, 1, &backedge_taken_count) ||
2152 		    /*
2153 		     * The last iteration underflows the counter if:
2154 		     *   initial + backedge_taken_count * step < 0 ⇔
2155 		     *             backedge_taken_count * step < -initial ⇔
2156 		     *                    backedge_taken_count > initial / -step
2157 		     * (direction flips because step < 0)
2158 		     */
2159 		    backedge_taken_count > initial / -step)
2160 			return false;
2161 		break;
2162 	case BPF_JGE:
2163 		/* E.g.: 7 - 2*i ≥ 3 ⇔ 2*i ≤ 4 ⇔ i ∈ [0,1,2]. */
2164 		if (up || initial < bound ||
2165 		    check_add_overflow(-diff / -step, 1, &backedge_taken_count) ||
2166 		    backedge_taken_count > initial / -step)
2167 			return false;
2168 		break;
2169 	case BPF_JSLT:
2170 		if (down || (s64)initial >= (s64)bound ||
2171 		    check_add_overflow((diff - 1) / step, 1, &backedge_taken_count) ||
2172 		    /*
2173 		     * Check if the last iteration overflows the signed counter:
2174 		     *   (s64)initial + backedge_taken_count * step > S64_MAX
2175 		     */
2176 		    backedge_taken_count > ((u64)S64_MAX - initial) / step)
2177 			return false;
2178 		break;
2179 	case BPF_JSLE:
2180 		if (down || (s64)initial > (s64)bound ||
2181 		    check_add_overflow(diff / step, 1, &backedge_taken_count) ||
2182 		    backedge_taken_count > ((u64)S64_MAX - initial) / step)
2183 			return false;
2184 		break;
2185 	case BPF_JSGT:
2186 		if (up || (s64)initial <= (s64)bound ||
2187 		    check_add_overflow((-diff - 1) / -step, 1, &backedge_taken_count) ||
2188 		    /*
2189 		     * The last iteration underflows the signed counter if:
2190 		     *   (s64)initial + backedge_taken_count * step < S64_MIN ⇔
2191 		     *                  backedge_taken_count * step < S64_MIN - (s64)initial ⇔
2192 		     *                         backedge_taken_count > initial - (u64)S64_MIN / -step
2193 		     *	 (direction flips because step < 0)
2194 		     */
2195 		    backedge_taken_count > (initial - (u64)S64_MIN) / -step)
2196 			return false;
2197 		break;
2198 	case BPF_JSGE:
2199 		if (up || (s64)initial < (s64)bound ||
2200 		    check_add_overflow(-diff / -step, 1, &backedge_taken_count) ||
2201 		    backedge_taken_count > (initial - (u64)S64_MIN) / -step)
2202 			return false;
2203 		break;
2204 	case BPF_JNE:
2205 		/*
2206 		 * For a decreasing counter flip the diff and step:
2207 		 *   7 - 2*i ≠ 3 ⇔ 2*i ≠ 7 - 3.
2208 		 */
2209 		diff = down ? -diff : diff;
2210 		step = down ? -step : step;
2211 		if (diff == 0 || diff % step)
2212 			return false;
2213 		backedge_taken_count = diff / step;
2214 		break;
2215 	default:
2216 		return false;
2217 	}
2218 
2219 	/*
2220 	 * max_header_count is u32 and U32_MAX means "infinite",
2221 	 * check to avoid overflow below.
2222 	 */
2223 	if (backedge_taken_count >= U32_MAX - 1)
2224 		return false;
2225 
2226 	/* The header executes once on entry and once for each taken backedge, hence +1. */
2227 	iters->max_header_count = backedge_taken_count + 1;
2228 	/*
2229 	 * The latch is a conditional jump with one jump target exiting the loop.
2230 	 * Linear latch is matched only if the loop has a single backedge.
2231 	 * The loop still, however can have multiple exits.
2232 	 * In such case, conservatively assume that non-latch exit can happen
2233 	 * at any iteration, thus setting minimal number of iterations as 0.
2234 	 */
2235 	iters->min_header_count = loop->exits_cnt == 1 ? iters->max_header_count : 0;
2236 	return true;
2237 }
2238 
2239 static void mark_scev_reg_scratched(struct bpf_verifier_env *env, u32 r)
2240 {
2241 	if (r < MAX_BPF_REG)
2242 		mark_reg_scratched(env, r);
2243 	else
2244 		mark_stack_slot_scratched(env, r - __MAX_BPF_REG);
2245 }
2246 
2247 /*
2248  * An unknown scalar is its own widening.
2249  * Stack bytes without a value are represented by scev->unknown_reg.
2250  */
2251 static bool is_unbound_scev_reg(struct bpf_verifier_env *env, const struct bpf_func_state *st,
2252 				u32 r)
2253 {
2254 	const struct bpf_reg_state *reg = scev_reg_for_read(env, st, r);
2255 
2256 	return reg && reg->type == SCALAR_VALUE && !reg->id && reg->step <= 1 &&
2257 	       tnum_is_unknown(reg->var_off) &&
2258 	       reg->r64.size == U64_MAX && reg->r32.size == U32_MAX;
2259 }
2260 
2261 /* Main logic in verifier.c forbids varying offsets for certain register types. */
2262 static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
2263 {
2264 	if (type_may_be_null(reg->type))
2265 		return false;
2266 
2267 	switch (base_type(reg->type)) {
2268 	case SCALAR_VALUE:
2269 	case PTR_TO_MAP_VALUE:
2270 	case PTR_TO_MAP_KEY:
2271 	case PTR_TO_STACK:
2272 	case PTR_TO_PACKET:
2273 	case PTR_TO_PACKET_META:
2274 	case PTR_TO_MEM:
2275 	case PTR_TO_BUF:
2276 	case PTR_TO_BTF_ID:
2277 		return true;
2278 	default:
2279 		return false;
2280 	}
2281 }
2282 
2283 static void scratch_widened_reg_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2284 {
2285 	switch (base_type(reg->type)) {
2286 	case SCALAR_VALUE:
2287 		reg->id = 0;
2288 		break;
2289 	case PTR_TO_PACKET:
2290 	case PTR_TO_PACKET_META:
2291 		reg->id = ++env->id_gen;
2292 		break;
2293 	default:
2294 		break;
2295 	}
2296 }
2297 
2298 /* Check that ANY leaves can be unioned with r's loop-entry value. */
2299 static bool is_widenable_any(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
2300 			     struct env *header_env, u32 r, u32 id)
2301 {
2302 	const struct bpf_reg_state *reg, *leaf_reg;
2303 	struct scev *scev = env->scev;
2304 	u32 l, ra, rr, leaf, order;
2305 	s64 imm;
2306 
2307 	if (!is_any(scev, id, &l, &rr))
2308 		return false;
2309 	reg = scev_reg_for_read(env, loop_entry, r);
2310 	if (!reg || !is_widenable_reg_type(reg))
2311 		return false;
2312 
2313 	scev->stack_sz = 0;
2314 	expr_stack_push(scev, id);
2315 	while (expr_next(scev, &id, &order)) {
2316 		if (order & DEPTH_LIMIT)
2317 			return false;
2318 		if (!(order & PRE) || is_any(scev, id, &l, &rr))
2319 			continue;
2320 		if (is_imm(scev, id, &imm)) {
2321 			if (reg->type != SCALAR_VALUE)
2322 				return false;
2323 		} else if (is_reg(scev, id, &leaf)) {
2324 			/* Other leaves must denote loop-invariant registers. */
2325 			if (leaf != r &&
2326 			    !(is_reg(scev, header_env->reg2scev[leaf], &ra) && ra == leaf))
2327 				return false;
2328 			leaf_reg = scev_reg_for_read(env, loop_entry, leaf);
2329 			if (!leaf_reg || !bpf_reg_union_compatible(reg, leaf_reg))
2330 				return false;
2331 		} else {
2332 			return false;
2333 		}
2334 	}
2335 	return true;
2336 }
2337 
2338 struct bounds {
2339 	struct cnum64 range;
2340 	u16 base;
2341 	u16 step;
2342 };
2343 
2344 static bool is_simple_linear(struct scev *scev, u32 id, u32 *base_reg, s64 *slope_imm)
2345 {
2346 	u32 base, slope;
2347 
2348 	return is_linear(scev, id, &base, &slope) &&
2349 	       is_reg(scev, base, base_reg) &&
2350 	       is_imm(scev, slope, slope_imm) &&
2351 	       *slope_imm <= S16_MAX &&
2352 	       *slope_imm >= S16_MIN &&
2353 	       *slope_imm != 0;
2354 }
2355 
2356 /*
2357  * Compute the range an induction variable in `reg` spans over the loop.
2358  * If the computation overflows s64 the range is unbounded, only the
2359  * power-of-two alignment survives the wraparound.
2360  */
2361 static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count, s64 slope,
2362 			  struct bounds *out)
2363 {
2364 	s64 slope_abs = slope < 0 ? -slope : slope;
2365 	s64 min_val = reg_smin(reg);
2366 	s64 max_val = reg_smax(reg);
2367 	s64 total_change;
2368 	bool overflow;
2369 
2370 	overflow = check_mul_overflow(slope, (s64)max_header_count - 1, &total_change) ||
2371 		   (slope > 0 && check_add_overflow(max_val, total_change, &max_val)) ||
2372 		   (slope < 0 && check_add_overflow(min_val, total_change, &min_val));
2373 	/*
2374 	 * If the entry value is a single point the value set is 'v + slope * k',
2375 	 * so the step is |slope|. Otherwise, only the power-of-two alignment
2376 	 * shared by the entry value and the slope.
2377 	 */
2378 	if (cnum64_is_const(reg->r64) && !overflow) {
2379 		out->step = slope_abs;
2380 		out->base = imod(min_val, out->step);
2381 	} else {
2382 		out->step = 1u << min_t(u32, tnum_alignment(reg->var_off), __ffs(slope_abs));
2383 		out->base = 0;
2384 	}
2385 	out->range = overflow ? CNUM64_UNBOUNDED : cnum64_from_srange(min_val, max_val);
2386 }
2387 
2388 static int mark_expr_precise(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 id,
2389 			     unsigned long *precise_regs)
2390 {
2391 	struct scev *scev = env->scev;
2392 	struct bpf_reg_state *reg;
2393 	u32 r, order;
2394 
2395 	scev->stack_sz = 0;
2396 	expr_stack_push(scev, id);
2397 	while (expr_next(scev, &id, &order)) {
2398 		if (order & DEPTH_LIMIT) {
2399 			verifier_bug(env, "scev precision marking exceeds expression depth limit");
2400 			return -EFAULT;
2401 		}
2402 		if (!(order & PRE) || !is_reg(scev, id, &r))
2403 			continue;
2404 		/* Synthetic values have no spilled register to mark precise. */
2405 		reg = scev_reg_for_linear(st, r);
2406 		if (reg && reg->type == SCALAR_VALUE)
2407 			__set_bit(r, precise_regs);
2408 	}
2409 	return 0;
2410 }
2411 
2412 int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2413 			   struct bpf_loop_iters *iters)
2414 {
2415 	struct bpf_func_state *cur_func = st->frame[st->curframe];
2416 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
2417 	struct bpf_verifier_log *log = &env->log;
2418 	struct scev *scev = env->scev;
2419 	struct env *header_env;
2420 	struct linear_latch latch, best;
2421 	struct bpf_backedge *backedge;
2422 	struct bpf_loop_iters tmp;
2423 	struct bpf_loop *loop;
2424 	int insn_idx = st->insn_idx;
2425 	bool found = false;
2426 	int linear_latch;
2427 	u32 r, base_reg;
2428 	int latch_idx;
2429 	s64 slope_imm;
2430 	int err, j;
2431 
2432 	if (!env->allow_uninit_stack)
2433 		return 0;
2434 
2435 	/*
2436 	 * If insn_idx is a loop header for a reducible loop with a single backedge.
2437 	 * loop is NULL for secondary entries to irreducible loops.
2438 	 */
2439 	loop = aux[insn_idx].loop;
2440 	if (!loop || loop->irreducible || loop->backedges_cnt != 1 || loop->backedges_overflow ||
2441 	    loop->exits_overflow) {
2442 		if (log->level & BPF_LOG_LEVEL2)
2443 			bpf_log(log, "loop header at %d, unsupported loop:%s%s%s\n", insn_idx,
2444 				!loop || loop->irreducible ? " irreducible" : "",
2445 				loop && loop->backedges_cnt > 1 ? " multiple backedges" : "",
2446 				loop && loop->exits_overflow ? " too many exits" : "");
2447 		return 0;
2448 	}
2449 
2450 	/* If this backedge has a latch */
2451 	backedge = &loop->backedges[0];
2452 	if (!backedge->latches_cnt) {
2453 		if (log->level & BPF_LOG_LEVEL2)
2454 			bpf_log(log, "loop header at %d, latch not identified\n", insn_idx);
2455 		return 0;
2456 	}
2457 
2458 	/*
2459 	 * Every condition dominating the backedge bounds the number of
2460 	 * iterations from above, keep the smallest bound.
2461 	 */
2462 	for (j = 0; j < backedge->latches_cnt; j++) {
2463 		latch_idx = backedge->latches[j];
2464 		linear_latch = match_linear_latch(env, insn_idx, latch_idx, &latch);
2465 		if (linear_latch < 0)
2466 			return linear_latch;
2467 		if (!linear_latch) {
2468 			if (log->level & BPF_LOG_LEVEL2)
2469 				bpf_log(log, "loop header at %d, non-linear %s at %d\n",
2470 					insn_idx, j ? "exit" : "latch", latch_idx);
2471 			continue;
2472 		}
2473 		if (!compute_max_iters(env, cur_func, &latch, &tmp)) {
2474 			if (log->level & BPF_LOG_LEVEL2)
2475 				bpf_log(log,
2476 					"loop header at %d, can't compute iterations count at %d\n",
2477 					insn_idx, latch_idx);
2478 			continue;
2479 		}
2480 		if (!found || tmp.max_header_count < iters->max_header_count) {
2481 			iters->max_header_count = tmp.max_header_count;
2482 			best = latch;
2483 		}
2484 		iters->min_header_count = found ? min(iters->min_header_count, tmp.min_header_count)
2485 						: tmp.min_header_count;
2486 		found = true;
2487 	}
2488 	if (!found) {
2489 		if (log->level & BPF_LOG_LEVEL2)
2490 			bpf_log(log, "loop header at %d, can't compute iterations count\n", insn_idx);
2491 		return 0;
2492 	}
2493 	latch = best;
2494 
2495 	if (iters->max_header_count == 0) {
2496 		if (log->level & BPF_LOG_LEVEL2)
2497 			bpf_log(log, "loop header at %d, 0 iterations count\n", insn_idx);
2498 		return 0;
2499 	}
2500 
2501 	if (iters->max_header_count == U32_MAX) {
2502 		if (log->level & BPF_LOG_LEVEL2)
2503 			bpf_log(log, "loop header at %d, inf iterations count\n", insn_idx);
2504 		return 0;
2505 	}
2506 
2507 	if (log->level & BPF_LOG_LEVEL2) {
2508 		bpf_log(log, "loop header at %d, header_count is ", insn_idx);
2509 		if (iters->min_header_count == iters->max_header_count)
2510 			bpf_log(log, "%u ", iters->max_header_count);
2511 		else
2512 			bpf_log(log, "[%u..%u] ", iters->min_header_count, iters->max_header_count);
2513 		bpf_log(log, "\n");
2514 	}
2515 
2516 	err = bpf_live_stack_query_init(env, st);
2517 	if (err)
2518 		return err;
2519 
2520 	header_env = find_header_env(scev, insn_idx);
2521 	for (r = 0; r < REGS_NUM; r++) {
2522 		struct bpf_reg_state *reg;
2523 		u32 ra, r_scev, r_expr;
2524 		bool spill_base = false;
2525 
2526 		if (!scev_reg_alive(env, st, r))
2527 			continue;
2528 		/*
2529 		 * A heuristic:
2530 		 * Ignore SCEVs computed for unbound values and treat those as widened.
2531 		 * This is poor man's modelling of e.g. bpf_probe_read_kernel() effect
2532 		 * on stack, when called from a subprogram. Currently this would produce
2533 		 * an unknown ('?') SCEV as a summary of a subprogram call effects.
2534 		 * Ideally, this should be computed as an OPAQUE value.
2535 		 * However, that would require tracking STACK_MISC writes in the
2536 		 * liveness analysis. Not implemented yet.
2537 		 */
2538 		if (is_unbound_scev_reg(env, cur_func, r))
2539 			continue;
2540 
2541 		r_scev = header_env->reg2scev[r];
2542 		reg = scev_reg_for_linear(cur_func, r);
2543 		/* If SCEV for r is (linear <reg> <slope>) */
2544 		if (is_simple_linear(scev, r_scev, &base_reg, &slope_imm) &&
2545 		    reg && is_widenable_reg_type(reg)) {
2546 			/* Spills at varying offsets lose precision */
2547 			if (test_bit(r, loop->store_base_regs)) {
2548 				spill_base = true;
2549 				goto cant_widen;
2550 			}
2551 			continue;
2552 		}
2553 
2554 		/* rA = rA, loop does not change this reg */
2555 		if (is_reg(scev, r_scev, &ra) && r == ra)
2556 			continue;
2557 
2558 		/* (any 1 (any 2 (any 3 4))) */
2559 		if (is_widenable_any(env, cur_func, header_env, r, r_scev)) {
2560 			if (test_bit(r, loop->store_base_regs)) {
2561 				spill_base = true;
2562 				goto cant_widen;
2563 			}
2564 			continue;
2565 		}
2566 cant_widen:
2567 		if (log->level & BPF_LOG_LEVEL2) {
2568 			r_expr = header_env->reg2expr[r];
2569 			bpf_log(log, "loop header at %d, can't widen ", insn_idx);
2570 			log_reg(env, r);
2571 			bpf_log(log, ", expr is ");
2572 			log_expr(env, r_expr);
2573 			if (spill_base)
2574 				bpf_log(log, ", requires exact stack-offset tracking");
2575 			bpf_log(log, "\n");
2576 		}
2577 		return 0;
2578 	}
2579 
2580 	bitmap_zero(iters->precise_regs, REGS_NUM);
2581 	err = mark_expr_precise(env, cur_func, latch.base_expr, iters->precise_regs);
2582 	if (err)
2583 		return err;
2584 	err = mark_expr_precise(env, cur_func, latch.step_expr, iters->precise_regs);
2585 	if (err)
2586 		return err;
2587 	err = mark_expr_precise(env, cur_func, latch.bound_expr, iters->precise_regs);
2588 	if (err)
2589 		return err;
2590 
2591 	return 1;
2592 }
2593 
2594 /* bpf_compute_loop_iters() checked that every leaf can be unioned into acc. */
2595 static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
2596 			 struct bpf_reg_state *acc, u32 id)
2597 {
2598 	struct bpf_reg_state *tmp = &env->fake_reg[0];
2599 	const struct bpf_reg_state *leaf_reg;
2600 	struct scev *scev = env->scev;
2601 	u32 l, r, leaf, order;
2602 	s64 imm;
2603 	int err;
2604 
2605 	scev->stack_sz = 0;
2606 	expr_stack_push(scev, id);
2607 	while (expr_next(scev, &id, &order)) {
2608 		if (order & DEPTH_LIMIT) {
2609 			verifier_bug(env, "scev ANY union exceeds expression depth limit");
2610 			return -EFAULT;
2611 		}
2612 		if (!(order & PRE) || is_any(scev, id, &l, &r))
2613 			continue;
2614 		if (is_imm(scev, id, &imm)) {
2615 			bpf_mark_reg_known_scalar(tmp, imm);
2616 			leaf_reg = tmp;
2617 		} else if (is_reg(scev, id, &leaf)) {
2618 			leaf_reg = scev_reg_for_read(env, loop_entry, leaf);
2619 			if (verifier_bug_if(!leaf_reg, env, "unreadable SCEV ANY leaf %u", leaf))
2620 				return -EFAULT;
2621 		} else {
2622 			verifier_bug(env, "scev ANY union has an unsupported leaf");
2623 			return -EFAULT;
2624 		}
2625 		err = bpf_reg_union(env, acc, leaf_reg);
2626 		if (err)
2627 			return err;
2628 	}
2629 	return 0;
2630 }
2631 
2632 int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2633 			struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)
2634 {
2635 	struct bpf_func_state *cur_func = st->frame[st->curframe];
2636 	struct bpf_func_state *entry_func = loop_entry->frame[loop_entry->curframe];
2637 	struct bpf_verifier_log *log = &env->log;
2638 	struct scev *scev = env->scev;
2639 	struct bpf_reg_state *reg;
2640 	struct env *header_env;
2641 	struct bounds bounds;
2642 	u32 r, base_reg, r_expr, a, b;
2643 	int insn_idx = st->insn_idx;
2644 	s64 slope_imm;
2645 	int err;
2646 
2647 	for_each_set_bit(r, iters->precise_regs, REGS_NUM) {
2648 		if (r < MAX_BPF_REG)
2649 			bpf_bt_set_frame_reg(&env->bt, st->curframe, r);
2650 		else
2651 			bpf_bt_set_frame_slot(&env->bt, st->curframe, r - MAX_BPF_REG);
2652 	}
2653 	err = bpf_mark_chain_precision(env, st, -1, NULL);
2654 	if (err)
2655 		return err;
2656 
2657 	header_env = find_header_env(scev, insn_idx);
2658 	for (r = 0; r < REGS_NUM; r++) {
2659 		if (!scev_reg_alive(env, st, r) || is_unbound_scev_reg(env, cur_func, r))
2660 			continue;
2661 
2662 		r_expr = header_env->reg2scev[r];
2663 		/* If SCEV for r is (linear <reg> <slope>)*/
2664 		if (is_simple_linear(scev, r_expr, &base_reg, &slope_imm) &&
2665 		    base_reg == r) {
2666 			err = scev_reg_for_write(env, cur_func, r, &reg);
2667 			if (err)
2668 				return err;
2669 			linear_bounds(reg, iters->max_header_count, slope_imm, &bounds);
2670 			if (log->level & BPF_LOG_LEVEL2) {
2671 				bpf_log(log, "loop header at %d, widening ", insn_idx);
2672 				log_reg(env, r);
2673 				bpf_log(log, " to ");
2674 				bpf_verbose_snum(env, cnum64_smin(bounds.range));
2675 				bpf_log(log, "..");
2676 				bpf_verbose_snum(env, cnum64_smax(bounds.range));
2677 				bpf_log(log, " step %u\n", bounds.step);
2678 			}
2679 			scratch_widened_reg_id(env, reg);
2680 			err = bpf_set_reg_range(env, reg, bounds.range, bounds.base, bounds.step);
2681 			if (err)
2682 				return err;
2683 			mark_scev_reg_scratched(env, r);
2684 		} else if (is_any(scev, r_expr, &a, &b)) {
2685 			err = scev_reg_for_write(env, cur_func, r, &reg);
2686 			if (err)
2687 				return err;
2688 			err = union_any_reg(env, entry_func, reg, r_expr);
2689 			if (err)
2690 				return err;
2691 			if (log->level & BPF_LOG_LEVEL2) {
2692 				bpf_log(log, "loop header at %d, widening ", insn_idx);
2693 				log_reg(env, r);
2694 				bpf_log(log, " to ");
2695 				bpf_verbose_snum(env, reg_smin(reg));
2696 				bpf_log(log, "..");
2697 				bpf_verbose_snum(env, reg_smax(reg));
2698 				bpf_log(log, " step %u\n", reg->step);
2699 			}
2700 			scratch_widened_reg_id(env, reg);
2701 			mark_scev_reg_scratched(env, r);
2702 		}
2703 	}
2704 	return 1;
2705 }
2706 
2707 int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,
2708 			struct bpf_verifier_state *entry_state, u32 max_header_count)
2709 {
2710 	struct bpf_func_state *entry_st = entry_state->frame[entry_state->curframe];
2711 	struct bpf_verifier_log *log = &env->log;
2712 	struct bpf_reg_state *reg, *entry_reg;
2713 	struct scev *scev = env->scev;
2714 	struct env *header_env;
2715 	struct bounds bounds;
2716 	u32 r, base_reg;
2717 	s64 slope_imm;
2718 	int err;
2719 
2720 	if (entry_state->curframe != cur_func_state->frameno) {
2721 		verifier_bug(env, "clamping registers for a wrong frame: %d vs %d\n",
2722 			     entry_state->curframe, cur_func_state->frameno);
2723 		return -EFAULT;
2724 	}
2725 
2726 	header_env = find_header_env(scev, insn_idx);
2727 	for (r = 0; r < REGS_NUM; r++) {
2728 		/* If SCEV for r is (linear <reg> <slope>)*/
2729 		if (!is_simple_linear(scev, header_env->reg2scev[r], &base_reg, &slope_imm) ||
2730 		    base_reg != r)
2731 			continue;
2732 
2733 		entry_reg = scev_reg_for_linear(entry_st, r);
2734 		reg = scev_reg_for_linear(cur_func_state, r);
2735 		if (!entry_reg || !reg || entry_reg->type == NOT_INIT || reg->type == NOT_INIT ||
2736 		    is_unbound_scev_reg(env, entry_st, r))
2737 			continue;
2738 
2739 		linear_bounds(entry_reg, max_header_count, slope_imm, &bounds);
2740 		bounds.range = cnum64_intersect(reg->r64, bounds.range);
2741 		if (cnum64_is_empty(bounds.range)) {
2742 			verifier_bug(env, "scev clamp produced empty range for r%d", r);
2743 			return -EFAULT;
2744 		}
2745 		if (log->level & BPF_LOG_LEVEL2) {
2746 			bpf_log(log, "loop header at %d, clamping ", insn_idx);
2747 			log_reg(env, r);
2748 			bpf_log(log, " to ");
2749 			bpf_verbose_snum(env, cnum64_smin(bounds.range));
2750 			bpf_log(log, "..");
2751 			bpf_verbose_snum(env, cnum64_smax(bounds.range));
2752 			bpf_log(log, " step %u\n", bounds.step);
2753 		}
2754 		scratch_widened_reg_id(env, reg);
2755 		err = bpf_set_reg_range(env, reg, bounds.range, bounds.base, bounds.step);
2756 		if (err)
2757 			return err;
2758 		mark_scev_reg_scratched(env, r);
2759 	}
2760 	return 0;
2761 }
2762