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