xref: /linux/kernel/bpf/scev.c (revision 6ccf49f7932781f441e1e52459a4053bbfd19ddb)
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 (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)
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 /* Find the topmost loop header containing idx inside cur_header, or -1 if none. */
1104 static int topmost_nested_loop(struct bpf_verifier_env *env, int idx, int cur_header)
1105 {
1106 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1107 	int header;
1108 
1109 	for (header = bpf_loop_at_index(env, idx); header >= 0;
1110 	     header = aux[header].loop_header)
1111 		if (aux[header].loop_header == cur_header)
1112 			return header;
1113 
1114 	return -1;
1115 }
1116 
1117 /*
1118  * Join cur_env into the successor's environment and schedule their traversal.
1119  * Map successors in nested loops to their topmost nested header.
1120  * Ignore successors outside the current loop and its nested loops.
1121  */
1122 static int join_successor(struct bpf_verifier_env *env, int cur_header, int succ_idx,
1123 			  struct env *old_env, struct env *cur_env)
1124 {
1125 	bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
1126 	struct scev *scev = env->scev;
1127 	int err, nested_header;
1128 	struct env *succ_env;
1129 
1130 	/*
1131 	 * There are several possibilities for a successor:
1132 	 * - succ_idx can be a part of a loop outside of the cur_header's loop,
1133 	 *   such edges are ignored.
1134 	 * - succ_idx can be a part of the same loop as cur_header,
1135 	 *   for such edges succ_idx environment is updated:
1136 	 *     e[succ_idx] = join(e[succ_idx], cur_env)
1137 	 * - succ_idx can be a part of some loop inner to cur_header,
1138 	 *   in such a case there exists some loop header H,
1139 	 *   such that H.loop_header == cur_header
1140 	 *   and H is the same as succ_idx's loop or contains it.
1141 	 */
1142 	if (bpf_loop_at_index(env, succ_idx) != cur_header) {
1143 		/*
1144 		 * topmost_nested_loop() either finds H or returns -1,
1145 		 * in case if succ_idx is a part of a loop outer to cur_header.
1146 		 */
1147 		nested_header = topmost_nested_loop(env, succ_idx, cur_header);
1148 		if (nested_header < 0)
1149 			return 0;
1150 		succ_idx = nested_header;
1151 	}
1152 	succ_env = get_loop_env(scev, cur_header, succ_idx);
1153 	if (!succ_env)
1154 		return -ENOMEM;
1155 	if (log_level2)
1156 		memcpy(old_env, succ_env, sizeof(*old_env));
1157 	err = join(scev, succ_env, cur_env);
1158 	if (err)
1159 		return err;
1160 	err = worklist_push(env, cur_header, succ_idx);
1161 	if (err)
1162 		return err;
1163 	if (log_level2)
1164 		log_env_changes(env, LOG_AT_JOIN, old_env, succ_env, succ_idx);
1165 	return 0;
1166 }
1167 
1168 /* Unsupported loops get only an unknown header environment. */
1169 static bool can_compute_loop_scev(const struct bpf_loop *loop)
1170 {
1171 	return !loop->irreducible && !loop->exits_overflow;
1172 }
1173 
1174 static int compute_scev_for_loop(struct bpf_verifier_env *env, int cur_header)
1175 {
1176 	struct scev_worklist *worklist = &env->scev->worklist;
1177 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1178 	struct bpf_loop *cur_loop = aux[cur_header].loop;
1179 	struct env *header_env;
1180 	struct scev *scev = env->scev;
1181 	struct bpf_loop *nested_loop;
1182 	struct env *cur_env = NULL;
1183 	struct env *old_env = NULL;
1184 	struct bpf_iarray *succ;
1185 	bool log_level2 = env->log.level & BPF_LOG_LEVEL2;
1186 	int s, i, err, idx, succ_idx;
1187 
1188 	if (log_level2)
1189 		bpf_log(&env->log, "Computing SCEV for loop at %d:\n", cur_header);
1190 
1191 	/*
1192 	 * For irreducible loops, and for loops nesting a loop with a truncated
1193 	 * exit list, just assume that everything is clobbered for now.
1194 	 */
1195 	if (!can_compute_loop_scev(cur_loop)) {
1196 		header_env = get_loop_env(scev, cur_header, cur_header);
1197 		if (!header_env)
1198 			return -ENOMEM;
1199 		/* The freshly allocated environment has all expressions unknown. */
1200 		header_env->empty = false;
1201 		return 0;
1202 	}
1203 
1204 	cur_env = kzalloc(sizeof(*cur_env), GFP_KERNEL_ACCOUNT);
1205 	if (!cur_env)
1206 		goto nomem;
1207 	if (log_level2) {
1208 		old_env = kzalloc(sizeof(*old_env), GFP_KERNEL_ACCOUNT);
1209 		if (!old_env)
1210 			goto nomem;
1211 	}
1212 	header_env = get_loop_env(scev, cur_header, cur_header);
1213 	if (!header_env)
1214 		goto nomem;
1215 	err = setup_initial_loop_env(env, header_env, cur_header);
1216 	if (err)
1217 		goto out;
1218 	err = worklist_push(env, cur_header, cur_header);
1219 	if (err)
1220 		goto out;
1221 
1222 	while (worklist->nr) {
1223 		idx = *min_heap_peek_inline(worklist);
1224 		min_heap_pop_inline(worklist, &worklist_cb, env->cfg.postorder_nums);
1225 
1226 		/* join_successor() maps nested-loop entries to their representative header. */
1227 		nested_loop = idx != cur_header ? aux[idx].loop : NULL;
1228 		memcpy(cur_env, find_loop_env(scev, cur_header, idx), sizeof(*cur_env));
1229 		if (nested_loop) {
1230 			/*
1231 			 * Process nested loop as a single instruction by
1232 			 * forgetting anything non-invariant in the nested loop
1233 			 */
1234 			if (log_level2)
1235 				memcpy(old_env, cur_env, sizeof(*old_env));
1236 			forget_non_invariants(env, cur_env, idx);
1237 			if (log_level2)
1238 				log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
1239 			/*
1240 			 * Treat nested loop exits as successors,
1241 			 * join cur_env into successor's envs.
1242 			 */
1243 			for (i = 0; i < nested_loop->exits_cnt; i++) {
1244 				s = nested_loop->exits[i].to;
1245 				err = join_successor(env, cur_header, s, old_env, cur_env);
1246 				if (err)
1247 					goto out;
1248 			}
1249 		} else {
1250 			/*
1251 			 * Iterate instructions within a single basic block
1252 			 * starting at 'idx' mutating 'cur_env'.
1253 			 */
1254 			for (;;) {
1255 				if (log_level2)
1256 					memcpy(old_env, cur_env, sizeof(*old_env));
1257 				err = transfer(env, cur_env, idx);
1258 				if (err)
1259 					goto out;
1260 				reset_scevs_at_indirect_writes(env, cur_env, idx);
1261 				if (log_level2)
1262 					log_env_changes(env, LOG_AT_TRANSFER, old_env, cur_env, idx);
1263 				succ = bpf_insn_successors(env, idx);
1264 				if (succ->cnt != 1)
1265 					break;
1266 				succ_idx = succ->items[0];
1267 				if (aux[idx].bb_end || aux[succ_idx].need_scev ||
1268 				    bpf_loop_at_index(env, succ_idx) != cur_header)
1269 					break;
1270 				idx = succ_idx;
1271 			}
1272 			/* Join cur_env into basic block successor's envs. */
1273 			iarray_for_each(s, succ) {
1274 				err = join_successor(env, cur_header, s, old_env, cur_env);
1275 				if (err)
1276 					goto out;
1277 			}
1278 		}
1279 	}
1280 
1281 	err = 0;
1282 out:
1283 	kfree(cur_env);
1284 	kfree(old_env);
1285 	return err;
1286 nomem:
1287 	err = -ENOMEM;
1288 	goto out;
1289 }
1290 
1291 static void mark_latches(struct bpf_verifier_env *env)
1292 {
1293 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1294 	struct bpf_loop *loop;
1295 	int len = env->prog->len;
1296 	int i, j, k, from;
1297 
1298 	for (i = 0; i < len; i++) {
1299 		loop = aux[i].loop;
1300 		if (!loop)
1301 			continue;
1302 		aux[i].need_scev = true;
1303 		if (!can_compute_loop_scev(loop))
1304 			continue;
1305 		/*
1306 		 * Make sure to only set .need_scev for exits and latches
1307 		 * belonging to the loop at `i`. If can_compute_loop_scev()
1308 		 * fails for a loop, it should hide it's instructions from
1309 		 * compute_insn_scevs().
1310 		 */
1311 		for (j = 0; j < loop->backedges_cnt; j++)
1312 			for (k = 0; k < loop->backedges[j].latches_cnt; k++)
1313 				aux[loop->backedges[j].latches[k]].need_scev = true;
1314 		for (j = 0; j < loop->exits_cnt; j++) {
1315 			from = loop->exits[j].from;
1316 			if (bpf_loop_at_index(env, from) == i)
1317 				aux[from].need_scev = true;
1318 		}
1319 	}
1320 }
1321 
1322 static bool is_any_imm_reg_opaque(struct scev *scev, u32 id)
1323 {
1324 	u32 l, r, reg, order;
1325 	s64 imm;
1326 
1327 	scev->stack_sz = 0;
1328 	expr_stack_push(scev, id);
1329 	while (expr_next(scev, &id, &order)) {
1330 		if (order & DEPTH_LIMIT)
1331 			return false;
1332 		if (!(order & PRE) ||
1333 		    is_imm(scev, id, &imm) ||
1334 		    is_reg(scev, id, &reg) ||
1335 		    is_opaque(scev, id) ||
1336 		    is_any(scev, id, &l, &r))
1337 			continue;
1338 		return false;
1339 	}
1340 	return true;
1341 }
1342 
1343 /*
1344  * Can implement explicit stack version, but it is harder to read.
1345  * Stick with recursive version for now.
1346  */
1347 static int transform_expr_once(struct scev *scev, u32 lvl, u32 root, void *priv,
1348 			       int (*fn)(struct scev *scev, u32 id, void *priv))
1349 {
1350 	struct expr expr;
1351 	int p0, p1, id;
1352 
1353 	if (lvl >= EXPR_STACK_DEPTH)
1354 		return UNKNOWN_EXPR_ID;
1355 
1356 	expr = scev->exprs[root]; /* snapshot the expr before potential realloc */
1357 	switch (op_params_num(expr.op)) {
1358 	case 0:
1359 		id = root;
1360 		break;
1361 	case 1:
1362 		p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
1363 		id = expr1(scev, expr.op, p0);
1364 		break;
1365 	case 2:
1366 		p0 = transform_expr_once(scev, lvl + 1, expr.params[0], priv, fn);
1367 		p1 = transform_expr_once(scev, lvl + 1, expr.params[1], priv, fn);
1368 		id = expr2(scev, expr.op, p0, p1);
1369 		break;
1370 	}
1371 	return id < 0 ? id : fn(scev, id, priv);
1372 }
1373 
1374 static int transform_expr(struct scev *scev, u32 root, void *priv,
1375 			  int (*fn)(struct scev *scev, u32 id, void *priv))
1376 {
1377 	int i = 0, id_old, id_new = root;
1378 
1379 	do {
1380 		/*
1381 		 * The depth limit is somewhat arbitrary and is essentially a failsafe.
1382 		 * oscillation should not really happen. Still, it seems harsh to error out.
1383 		 */
1384 		if (i++ == 4 * EXPR_STACK_DEPTH)
1385 			return UNKNOWN_EXPR_ID;
1386 		id_old = id_new;
1387 		id_new = transform_expr_once(scev, 0, id_old, priv, fn);
1388 		if (id_new < 0)
1389 			return id_new;
1390 	} while (id_old != id_new);
1391 	return id_new;
1392 }
1393 
1394 static int simplify(struct scev *scev, u32 id, void *priv)
1395 {
1396 	u32 l, r, base, slope;
1397 	s64 imm1, imm2;
1398 
1399 	/* (+ (linear base slope) imm) -> (linear (+ base imm) slope) */
1400 	if (is_add(scev, id, &l, &r) &&
1401 	    is_linear(scev, l, &base, &slope) &&
1402 	    is_imm(scev, r, &imm1))
1403 		return expr2(scev, LINEAR_SCEV, expr2(scev, BPF_ADD, base, r), slope);
1404 
1405 	/* (+ imm imm) -> imm */
1406 	if (is_add(scev, id, &l, &r) &&
1407 	    is_imm(scev, l, &imm1) &&
1408 	    is_imm(scev, r, &imm2))
1409 		return imm_expr(scev, imm1 + imm2);
1410 
1411 	/* (zext32 (imm X)) -> (imm (u32)X) */
1412 	if (is_zext32(scev, id, &l) && is_imm(scev, l, &imm1))
1413 		return imm_expr(scev, (u64)(u32)imm1);
1414 
1415 	return id;
1416 }
1417 
1418 static int compute_header_scevs(struct bpf_verifier_env *env, struct env *header_env)
1419 {
1420 	struct scev *scev = env->scev;
1421 	int l, r, id, ra, rb, ra_expr;
1422 	s64 imm;
1423 
1424 	/*
1425 	 * Note:
1426 	 * reg2expr[ra] describes a change in rA's value over a single loop iteration.
1427 	 * It does not account for rA's entry value. However, the SCEV constructed for rA
1428 	 * must include an additional rA entry edge. For example:
1429 	 *
1430 	 *      r0 = ..., r1 = 7
1431 	 *   l: if r0 == 10 goto e // reg2expr[r1] == (imm 42) => reg2scev[r1] == (any r1 42)
1432 	 *      r0 += 1
1433 	 *      r1 = 42
1434 	 *      goto l
1435 	 *   e:
1436 	 *      ... at exit r1 is in {7,42} ...
1437 	 */
1438 	for (ra = 0; ra < REGS_NUM; ra++) {
1439 		ra_expr = transform_expr(scev, header_env->reg2expr[ra], NULL, simplify);
1440 		if (ra_expr < 0)
1441 			return ra_expr;
1442 		header_env->reg2expr[ra] = ra_expr;
1443 		/* rA = (+ rA IMM) -> (linear rA IMM) */
1444 		if (is_add(scev, ra_expr, &l, &r) &&
1445 		    is_reg(scev, l, &rb) &&
1446 		    is_imm(scev, r, &imm) &&
1447 		    ra == rb) {
1448 			id = expr2(scev, LINEAR_SCEV, l, r);
1449 			if (id < 0)
1450 				return id;
1451 			header_env->reg2scev[ra] = id;
1452 			continue;
1453 		}
1454 		/* rA = rA -> rA*/
1455 		if (is_reg(scev, ra_expr, &rb) && ra == rb) {
1456 			header_env->reg2scev[ra] = ra_expr;
1457 			continue;
1458 		}
1459 		/* rA = (any 1 2 3 4 ...) -> (any rA 1 2 3 4 ...) */
1460 		if (is_any_imm_reg_opaque(scev, ra_expr)) {
1461 			id = mk_any(scev, expr1(scev, REG, ra), ra_expr);
1462 			if (id < 0)
1463 				return id;
1464 			header_env->reg2scev[ra] = id;
1465 			continue;
1466 		}
1467 
1468 	}
1469 	return 0;
1470 }
1471 static int instantiate_header_scevs(struct scev *scev, u32 id, void *priv)
1472 {
1473 	u32 reg, *reg2scev = priv;
1474 
1475 	/* (reg r) -> ... equation at header ... */
1476 	if (is_reg(scev, id, &reg))
1477 		return reg2scev[reg];
1478 	/* keep expression shapes */
1479 	return id;
1480 }
1481 
1482 static int compute_insn_scevs(struct bpf_verifier_env *env, struct env *eheader, struct env *einsn)
1483 {
1484 	struct scev *scev = env->scev;
1485 	int id, reg;
1486 
1487 	for (reg = 0; reg < REGS_NUM; reg++) {
1488 		id = einsn->reg2expr[reg];
1489 		id = transform_expr_once(scev, 0, id, eheader->reg2scev, instantiate_header_scevs);
1490 		if (id < 0)
1491 			return id;
1492 		id = transform_expr(scev, id, NULL, simplify);
1493 		if (id < 0)
1494 			return id;
1495 		einsn->reg2scev[reg] = id;
1496 	}
1497 
1498 	return 0;
1499 }
1500 
1501 static int log_scevs(struct bpf_verifier_env *env)
1502 {
1503 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1504 	struct bpf_verifier_log *log = &env->log;
1505 	struct env *header_env, *latch_env;
1506 	struct scev *scev = env->scev;
1507 	struct bpf_loop *loop;
1508 	int i, j, k, len, latch;
1509 
1510 	len = env->prog->len;
1511 	for (i = 0; i < len; i++) {
1512 		loop = aux[i].loop;
1513 		if (!loop)
1514 			continue;
1515 		header_env = find_header_env(scev, i);
1516 		bpf_log(log, "scev at header %d:\n", i);
1517 		print_env(env, header_env, i);
1518 		if (!can_compute_loop_scev(loop))
1519 			continue;
1520 		for (j = 0; j < loop->backedges_cnt; j++) {
1521 			for (k = 0; k < loop->backedges[j].latches_cnt; k++) {
1522 				latch = loop->backedges[j].latches[k];
1523 				bpf_log(log, " scev at %s %d:\n", k ? "exit" : "latch", latch);
1524 				latch_env = find_loop_env(scev, i, latch);
1525 				if (verifier_bug_if(!latch_env, env, "i=%d, latch=%d", i, latch))
1526 					return -EFAULT;
1527 				print_env(env, latch_env, latch);
1528 			}
1529 		}
1530 	}
1531 	return 0;
1532 }
1533 
1534 int bpf_compute_scev(struct bpf_verifier_env *env)
1535 {
1536 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
1537 	struct scev *scev = env->scev;
1538 	int *postorder = env->cfg.insn_postorder;
1539 	int cnt = env->cfg.cur_postorder;
1540 	int i, idx, err, header;
1541 
1542 	mark_latches(env);
1543 	/*
1544 	 * Visit loop headers in postorder, to guarantee that scevs
1545 	 * for innermost loops are computed first.
1546 	 */
1547 	for (i = 0; i < cnt; i++) {
1548 		idx = postorder[i];
1549 		if (!aux[idx].loop)
1550 			continue;
1551 		err = compute_scev_for_loop(env, idx);
1552 		if (err)
1553 			return err;
1554 	}
1555 
1556 	/*
1557 	 * Compute scevs from exprs collected on a previous step. Iterate instructions in
1558 	 * reverse post-order so that each loop header is processed before instructions
1559 	 * reachable from it.
1560 	 */
1561 	for (i = cnt - 1; i >= 0; i--) {
1562 		idx = postorder[i];
1563 		if (!aux[idx].need_scev)
1564 			continue;
1565 		header = bpf_loop_at_index(env, idx);
1566 		err = aux[idx].loop
1567 		      ? compute_header_scevs(env, find_header_env(scev, header))
1568 		      : compute_insn_scevs(env,
1569 					   find_header_env(scev, header),
1570 					   find_loop_env(scev, header, idx));
1571 		if (err)
1572 			return err;
1573 	}
1574 
1575 	for (i = 0; i < env->prog->len; i++)
1576 		if (aux[i].loop)
1577 			aux[i].prune_point = true;
1578 
1579 	if (env->log.level & BPF_LOG_LEVEL2) {
1580 		err = log_scevs(env);
1581 		if (err)
1582 			return err;
1583 	}
1584 
1585 	return 0;
1586 }
1587 
1588 void bpf_free_scev(struct bpf_verifier_env *env)
1589 {
1590 	struct scev *scev = env->scev;
1591 	struct insn_envs *envs;
1592 	int i;
1593 	u32 j;
1594 
1595 	if (!scev)
1596 		return;
1597 	for (i = 0; i < scev->envs_cnt; i++) {
1598 		envs = scev->envs[i];
1599 		if (!envs)
1600 			continue;
1601 		for (j = 0; j < envs->cnt; j++)
1602 			kfree(envs->entries[j].env);
1603 		kfree(envs);
1604 	}
1605 	if (scev->exprs_ht)
1606 		for (i = 0; i < scev->exprs_ht_cnt; i++)
1607 			kvfree(scev->exprs_ht[i]);
1608 	kvfree(scev->exprs_ht);
1609 	kvfree(scev->worklist.data);
1610 	kvfree(scev->envs);
1611 	kvfree(scev->exprs);
1612 	kvfree(scev->discovered);
1613 	kfree(scev);
1614 	env->scev = NULL;
1615 }
1616 
1617 int bpf_init_scev(struct bpf_verifier_env *env)
1618 {
1619 	struct scev *scev;
1620 
1621 	scev = kzalloc(sizeof(struct scev), GFP_KERNEL_ACCOUNT);
1622 	if (!scev)
1623 		return -ENOMEM;
1624 	env->scev = scev;
1625 	bpf_mark_reg_known_scalar(&scev->zero_reg, 0);
1626 	bpf_mark_reg_unknown_imprecise(&scev->unknown_reg);
1627 	/* A power of two for hash & (exprs_ht_cnt - 1)` indexing. */
1628 	scev->exprs_ht_cnt = roundup_pow_of_two(max(256U, DIV_ROUND_UP(env->prog->len, 4)));
1629 	scev->exprs_ht = kvcalloc(scev->exprs_ht_cnt, sizeof(*scev->exprs_ht), GFP_KERNEL_ACCOUNT);
1630 	if (!scev->exprs_ht)
1631 		goto nomem;
1632 	if (expr0(scev, UNKNOWN) < 0 || expr0(scev, OPAQUE)  < 0)
1633 		goto nomem;
1634 	scev->envs = kvcalloc(env->prog->len, sizeof(*scev->envs), GFP_KERNEL_ACCOUNT);
1635 	scev->discovered = kvcalloc(env->prog->len, sizeof(*scev->discovered), GFP_KERNEL_ACCOUNT);
1636 	if (!scev->envs || !scev->discovered)
1637 		goto nomem;
1638 	/*
1639 	 * Remember original program length, in case bpf_free_scev()
1640 	 * is called after bpf program rewrites that increase program
1641 	 * length.
1642 	 */
1643 	scev->envs_cnt = env->prog->len;
1644 	return 0;
1645 nomem:
1646 	bpf_free_scev(env);
1647 	return -ENOMEM;
1648 }
1649 
1650 static struct bpf_stack_state *scev_regno_to_stack(const struct bpf_func_state *st, u32 r)
1651 {
1652 	int spi, slots_available;
1653 
1654 	if (r < MAX_BPF_REG)
1655 		return NULL;
1656 
1657 	slots_available = st->allocated_stack / BPF_REG_SIZE;
1658 	spi = r - MAX_BPF_REG;
1659 	if (spi < slots_available)
1660 		return &st->stack[spi];
1661 
1662 	return NULL;
1663 }
1664 
1665 static struct bpf_reg_state *scev_regno_to_reg(struct bpf_func_state *st, u32 r)
1666 {
1667 	return r < MAX_BPF_REG ? &st->regs[r] : NULL;
1668 }
1669 
1670 /* Linear widening requires a physical register or a full spill. */
1671 static struct bpf_reg_state *scev_reg_for_linear(struct bpf_func_state *st, u32 r)
1672 {
1673 	struct bpf_stack_state *stack;
1674 
1675 	if (r < MAX_BPF_REG)
1676 		return scev_regno_to_reg(st, r);
1677 	stack = scev_regno_to_stack(st, r);
1678 	if (!stack || bpf_spill_size(stack) != BPF_REG_SIZE)
1679 		return NULL;
1680 	return &stack->spilled_ptr;
1681 }
1682 
1683 /*
1684  * Return a borrowed value; never use it as a widening destination.
1685  * NULL denotes no readable value.
1686  */
1687 static const struct bpf_reg_state *
1688 scev_reg_for_read(struct bpf_verifier_env *env, const struct bpf_func_state *st, u32 r)
1689 {
1690 	const struct bpf_stack_state *stack;
1691 	bool zero = true;
1692 	int i;
1693 
1694 	if (r < MAX_BPF_REG)
1695 		return st->regs[r].type == NOT_INIT ? NULL : &st->regs[r];
1696 	if (r >= REGS_NUM || r - MAX_BPF_REG >= env->stack_limit / BPF_REG_SIZE)
1697 		return NULL;
1698 
1699 	stack = scev_regno_to_stack(st, r);
1700 	if (!stack)
1701 		return &env->scev->unknown_reg;
1702 	if (bpf_spill_size(stack) == BPF_REG_SIZE)
1703 		return &stack->spilled_ptr;
1704 
1705 	/* Partial spills do not describe the value of the whole slot. */
1706 	for (i = 0; i < BPF_REG_SIZE; i++) {
1707 		switch (stack->slot_type[i]) {
1708 		case STACK_ZERO:
1709 			break;
1710 		case STACK_INVALID:
1711 		case STACK_POISON:
1712 		case STACK_MISC:
1713 			zero = false;
1714 			break;
1715 		case STACK_SPILL:
1716 			if (!bpf_is_spilled_scalar_reg(stack))
1717 				return NULL;
1718 			zero = false;
1719 			break;
1720 		default:
1721 			return NULL;
1722 		}
1723 	}
1724 	return zero ? &env->scev->zero_reg : &env->scev->unknown_reg;
1725 }
1726 
1727 /* Materialize a writable value in the current state, growing its stack if needed. */
1728 static int scev_reg_for_write(struct bpf_verifier_env *env, struct bpf_func_state *st,
1729 			      u32 r, struct bpf_reg_state **out)
1730 {
1731 	const struct bpf_reg_state *value;
1732 	struct bpf_stack_state *stack;
1733 	u32 spi;
1734 	int err;
1735 
1736 	*out = scev_regno_to_reg(st, r);
1737 	if (*out)
1738 		return 0;
1739 	if (r >= REGS_NUM || r - MAX_BPF_REG >= env->stack_limit / BPF_REG_SIZE)
1740 		return -EINVAL;
1741 
1742 	spi = r - MAX_BPF_REG;
1743 	err = bpf_grow_stack_state(env, st, (spi + 1) * BPF_REG_SIZE);
1744 	if (err)
1745 		return err;
1746 
1747 	/* Resolve pointers after growth, which may relocate the stack. */
1748 	value = scev_reg_for_read(env, st, r);
1749 	if (!value)
1750 		return -EINVAL;
1751 	stack = scev_regno_to_stack(st, r);
1752 	stack->spilled_ptr = *value;
1753 	memset(stack->slot_type, STACK_SPILL, sizeof(stack->slot_type));
1754 	*out = &stack->spilled_ptr;
1755 	return 0;
1756 }
1757 
1758 static bool scev_reg_alive(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 r)
1759 {
1760 	int insn_idx = bpf_frame_insn_idx(st, st->curframe);
1761 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
1762 	int spi;
1763 
1764 	if (r < MAX_BPF_REG) {
1765 		return BIT(r) & live_regs;
1766 	} else {
1767 		spi = r - MAX_BPF_REG;
1768 		return bpf_stack_slot_alive(env, st->curframe, spi * 2) ||
1769 		       bpf_stack_slot_alive(env, st->curframe, spi * 2 + 1);
1770 	}
1771 }
1772 
1773 /*
1774  * Latch is a condition deciding if execution remains inside a loop.
1775  * Linear latch represents a condition 'if <reg> <op> <loop invariant> goto <loop-header>',
1776  * where equation '<base> + i * <step> <op> <bound>' describes values taken by register <reg>,
1777  * 'i' is the loop iteration number, starting from 0.
1778  */
1779 struct linear_latch {
1780 	u32 insn_idx;
1781 	u32 base_expr;
1782 	u32 step_expr;
1783 	u32 bound_expr;
1784 	u32 op;
1785 };
1786 
1787 static bool loop_invariant(struct scev *scev, u32 id)
1788 {
1789 	s64 imm;
1790 	u32 reg;
1791 
1792 	return is_reg(scev, id, &reg) || is_imm(scev, id, &imm);
1793 }
1794 
1795 static int match_linear_latch(struct bpf_verifier_env *env,
1796 			      u32 header,
1797 			      u32 latch_idx,
1798 			      struct linear_latch *latch)
1799 {
1800 	struct bpf_insn *insn = &env->prog->insnsi[latch_idx];
1801 	struct scev *scev = env->scev;
1802 	struct env *latch_env;
1803 	u32 true_branch_loop;
1804 	u32 true_branch_tgt;
1805 	u32 src_reg_scev;
1806 	u32 dst_reg_scev;
1807 	u32 t, l, r, op;
1808 	int id;
1809 
1810 	/* 32-bit arithmetic is not handled yet */
1811 	if (BPF_CLASS(insn->code) != BPF_JMP)
1812 		return false;
1813 	op = BPF_OP(insn->code);
1814 	/* Flip the condition if true branch jumps out of the loop. */
1815 	true_branch_tgt = latch_idx + bpf_jmp_offset(insn) + 1;
1816 	true_branch_loop = bpf_loop_at_index(env, true_branch_tgt);
1817 	if (true_branch_loop != header &&
1818 	    !bpf_is_nested_loop(env, true_branch_loop, header))
1819 		op = bpf_rev_opcode(op);
1820 	switch (op) {
1821 	case BPF_JSLT:
1822 	case BPF_JSLE:
1823 	case BPF_JSGT:
1824 	case BPF_JSGE:
1825 	case BPF_JLT:
1826 	case BPF_JLE:
1827 	case BPF_JGT:
1828 	case BPF_JGE:
1829 	case BPF_JNE:
1830 		break;
1831 	default:
1832 		return false;
1833 	}
1834 
1835 	latch->insn_idx = latch_idx;
1836 
1837 	latch_env = find_loop_env(scev, header, latch_idx);
1838 	if (verifier_bug_if(!latch_env, env, "header_idx=%d, latch_idx=%d\n", header, latch_idx))
1839 		return -EFAULT;
1840 	dst_reg_scev = latch_env->reg2scev[insn->dst_reg];
1841 	src_reg_scev = latch_env->reg2scev[insn->src_reg];
1842 	/*
1843 	 * Make sure (linear ...) is in dst_reg_scev:
1844 	 *   'if <invariant> <op> <linear>' ⇔
1845 	 * 'if <linear> <flip(op)> <invariant>'.
1846 	 */
1847 	if (BPF_SRC(insn->code) == BPF_X && is_linear(scev, src_reg_scev, &l, &r)) {
1848 		swap(dst_reg_scev, src_reg_scev);
1849 		op = bpf_flip_opcode(op);
1850 	}
1851 	latch->op = op;
1852 	/*
1853 	 * simplify() produces two shapes for linear latches:
1854 	 * - (linear register step)
1855 	 *           ^----------------------------+-- base_expr
1856 	 *           base_expr                    |
1857 	 * - (linear (+ register imm) step)       |
1858 	 *           ^----------------------------'
1859 	 */
1860 	if (!is_linear(scev, dst_reg_scev, &latch->base_expr, &latch->step_expr))
1861 		return false;
1862 
1863 	if (BPF_SRC(insn->code) == BPF_K) {
1864 		id = imm_expr(scev, insn->imm);
1865 		if (id < 0)
1866 			return id;
1867 		latch->bound_expr = id;
1868 	} else {
1869 		latch->bound_expr = src_reg_scev;
1870 	}
1871 
1872 	if (!loop_invariant(scev, latch->step_expr) ||
1873 	    !loop_invariant(scev, latch->bound_expr))
1874 		return false;
1875 
1876 	/* (linear register step) */
1877 	if (is_reg(scev, latch->base_expr, &t))
1878 		return true;
1879 
1880 	/* (linear (+ register imm) step) */
1881 	if (is_add(scev, latch->base_expr, &l, &r) &&
1882 	    is_reg(scev, l, &t) &&
1883 	    loop_invariant(scev, r))
1884 		return true;
1885 
1886 	return false;
1887 }
1888 
1889 struct scev_value {
1890 	u64 value;	/* scalar value or a pointer offset */
1891 	int ptr_reg;	/* SCEV register identifying the pointer origin, or -1. */
1892 };
1893 
1894 static void log_scev_value(struct bpf_verifier_env *env, struct bpf_func_state *st,
1895 			   const struct scev_value *v)
1896 {
1897 	const struct bpf_reg_state *reg;
1898 
1899 	if (v->ptr_reg >= 0) {
1900 		reg = scev_reg_for_read(env, st, v->ptr_reg);
1901 		log_reg(env, v->ptr_reg);
1902 		bpf_log(&env->log, " (%s)", reg ? reg_type_str(env, reg->type) : "unavailable");
1903 	} else {
1904 		bpf_log(&env->log, "scalar %llu", v->value);
1905 	}
1906 }
1907 
1908 static void log_incompatible_scev_values(struct bpf_verifier_env *env, const char *reason,
1909 					struct bpf_func_state *st,
1910 					const struct scev_value *a, const struct scev_value *b)
1911 {
1912 	bpf_log(&env->log, "scev: %s ", reason);
1913 	log_scev_value(env, st, a);
1914 	bpf_log(&env->log, ", ");
1915 	log_scev_value(env, st, b);
1916 	bpf_log(&env->log, "\n");
1917 }
1918 
1919 static bool scev_value_compatible(struct bpf_verifier_env *env, struct bpf_func_state *st,
1920 				  const struct scev_value *a, const struct scev_value *b)
1921 {
1922 	const struct bpf_reg_state *ra, *rb;
1923 
1924 	if (a->ptr_reg < 0 || b->ptr_reg < 0) {
1925 		if (a->ptr_reg < 0 && b->ptr_reg < 0)
1926 			return true;
1927 		goto incompatible;
1928 	}
1929 	ra = scev_reg_for_read(env, st, a->ptr_reg);
1930 	rb = scev_reg_for_read(env, st, b->ptr_reg);
1931 	if (ra && rb && bpf_same_memory_origin(ra, rb))
1932 		return true;
1933 
1934 incompatible:
1935 	if (env->log.level & BPF_LOG_LEVEL2)
1936 		log_incompatible_scev_values(env, "incompatible latch operands", st, a, b);
1937 	return false;
1938 }
1939 
1940 static bool scev_value_add(struct bpf_verifier_env *env, struct bpf_func_state *st,
1941 			   const struct scev_value *a, const struct scev_value *b,
1942 			   struct scev_value *result)
1943 {
1944 	if (a->ptr_reg >= 0 && b->ptr_reg >= 0) {
1945 		if (env->log.level & BPF_LOG_LEVEL2)
1946 			log_incompatible_scev_values(env, "can't add two pointers", st, a, b);
1947 		return false;
1948 	}
1949 	result->value = a->value + b->value;
1950 	result->ptr_reg = a->ptr_reg >= 0 ? a->ptr_reg : b->ptr_reg;
1951 	return true;
1952 }
1953 
1954 static bool eval_expr(struct bpf_verifier_env *env, struct scev *scev,
1955 		      struct bpf_func_state *st, u32 id, struct scev_value *result)
1956 {
1957 	struct scev_value lval, rval;
1958 	const struct bpf_reg_state *reg;
1959 	u32 l, r, regno;
1960 	s64 imm;
1961 
1962 	if (is_reg(scev, id, &regno)) {
1963 		reg = scev_reg_for_read(env, st, regno);
1964 		if (!reg || reg->type == NOT_INIT || !tnum_is_const(reg->var_off))
1965 			return false;
1966 		result->value = reg->var_off.value;
1967 		result->ptr_reg = reg->type == SCALAR_VALUE ? -1 : (int)regno;
1968 		return true;
1969 	} else if (is_imm(scev, id, &imm)) {
1970 		result->value = imm;
1971 		result->ptr_reg = -1;
1972 		return true;
1973 	} else if (is_add(scev, id, &l, &r) &&
1974 		   eval_expr(env, scev, st, l, &lval) &&
1975 		   eval_expr(env, scev, st, r, &rval)) {
1976 		return scev_value_add(env, st, &lval, &rval, result);
1977 	}
1978 	return false;
1979 }
1980 
1981 /*
1982  * Loop with post-condition:
1983  *
1984  *    r0 = 0
1985  * l: ...                r0 ∈ [0,1,2] header executed 3 times
1986  *    r0 += 1            r0 ∈ [0,1,2]
1987  *    ...                r0 ∈ [1,2,3]
1988  *    if r0 != 3 goto l  r0 ∈ [1,2,3] backedge taken 2 times
1989  *    ...                r0 ∈ [3]
1990  *
1991  * SCEV at header: r0 = k
1992  * SCEV at latch:  r0 = 1 + k
1993  *
1994  * Loop with pre-condition:
1995  *
1996  *    r0 = 0
1997  * l: ...                r0 ∈ [0,1,2,3] header executed 4 times
1998  *    if r0 == 3 goto e  r0 ∈ [0,1,2,3] backedge taken 3 times
1999  *    r0 += 1            r0 ∈ [0,1,2]
2000  *    ...                r0 ∈ [1,2,3]
2001  *    goto l             r0 ∈ [1,2,3]
2002  * e: ...                r0 ∈ [3]
2003  *
2004  * SCEV at header: r0 = k
2005  * SCEV at latch:  r0 = k
2006  */
2007 static bool compute_max_iters(struct bpf_verifier_env *env,
2008 			      struct bpf_func_state *st,
2009 			      struct linear_latch *latch,
2010 			      struct bpf_loop_iters *iters)
2011 {
2012 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
2013 	struct bpf_loop *loop = aux[bpf_loop_at_index(env, latch->insn_idx)].loop;
2014 	struct scev *scev = env->scev;
2015 	struct scev_value initial_val, step_val, bound_val;
2016 	u64 step, diff, bound, initial, backedge_taken_count;
2017 	u8 op = latch->op;
2018 	bool up, down;
2019 
2020 	if (!eval_expr(env, scev, st, latch->base_expr, &initial_val) ||
2021 	    !eval_expr(env, scev, st, latch->step_expr, &step_val) ||
2022 	    !eval_expr(env, scev, st, latch->bound_expr, &bound_val))
2023 		return false;
2024 
2025 	if (step_val.ptr_reg >= 0) {
2026 		if (env->log.level & BPF_LOG_LEVEL2) {
2027 			bpf_log(&env->log, "scev: latch step is a pointer ");
2028 			log_scev_value(env, st, &step_val);
2029 			bpf_log(&env->log, "\n");
2030 		}
2031 		return false;
2032 	}
2033 	if (!scev_value_compatible(env, st, &initial_val, &bound_val))
2034 		return false;
2035 
2036 	initial = initial_val.value;
2037 	step = step_val.value;
2038 	bound = bound_val.value;
2039 
2040 	if (step == 0)
2041 		return false;
2042 	down = (s64)step < 0;
2043 	up = (s64)step > 0;
2044 	diff = bound - initial;
2045 	switch (op) {
2046 	case BPF_JLT:
2047 		/*
2048 		 * E.g.: 3 + 2*i < 7 ⇔ 2*i < 4 ⇔ i ∈ [0,1].
2049 		 * Here the inequality describes a set of values `i` might take
2050 		 * while the latch condition remains true (the backedge is taken).
2051 		 * The backedge_taken_count is the size of this set.
2052 		 */
2053 		if (/*
2054 		     * If the condition is initially true, decreasing values won't
2055 		     * change that without underflow. If the condition is initially false,
2056 		     * the main pass would do a single iteration anyway.
2057 		     */
2058 		    down ||
2059 		    /* Is the latch condition false on the first iteration? */
2060 		    initial >= bound ||
2061 		    /* Count iterations satisfying the strict inequality, including i=0. */
2062 		    check_add_overflow((diff - 1) / step, 1, &backedge_taken_count) ||
2063 		    /*
2064 		     * Check if the last iteration overflows the counter:
2065 		     *   initial + backedge_taken_count * step > U64_MAX
2066 		     */
2067 		    backedge_taken_count > (U64_MAX - initial) / step)
2068 			return false;
2069 		break;
2070 	case BPF_JLE:
2071 		/* E.g.: 3 + 2*i ≤ 7 ⇔ 2*i ≤ 4 ⇔ i ∈ [0,1,2]. */
2072 		if (down || initial > bound ||
2073 		    /* Count iterations satisfying the non-strict inequality. */
2074 		    check_add_overflow(diff / step, 1, &backedge_taken_count) ||
2075 		    backedge_taken_count > (U64_MAX - initial) / step)
2076 			return false;
2077 		break;
2078 	case BPF_JGT:
2079 		/* E.g.: 7 - 2*i > 3 ⇔ 2*i < 4 ⇔ i ∈ [0,1]. */
2080 		if (up || initial <= bound ||
2081 		    check_add_overflow((-diff - 1) / -step, 1, &backedge_taken_count) ||
2082 		    /*
2083 		     * The last iteration underflows the counter if:
2084 		     *   initial + backedge_taken_count * step < 0 ⇔
2085 		     *             backedge_taken_count * step < -initial ⇔
2086 		     *                    backedge_taken_count > initial / -step
2087 		     * (direction flips because step < 0)
2088 		     */
2089 		    backedge_taken_count > initial / -step)
2090 			return false;
2091 		break;
2092 	case BPF_JGE:
2093 		/* E.g.: 7 - 2*i ≥ 3 ⇔ 2*i ≤ 4 ⇔ i ∈ [0,1,2]. */
2094 		if (up || initial < bound ||
2095 		    check_add_overflow(-diff / -step, 1, &backedge_taken_count) ||
2096 		    backedge_taken_count > initial / -step)
2097 			return false;
2098 		break;
2099 	case BPF_JSLT:
2100 		if (down || (s64)initial >= (s64)bound ||
2101 		    check_add_overflow((diff - 1) / step, 1, &backedge_taken_count) ||
2102 		    /*
2103 		     * Check if the last iteration overflows the signed counter:
2104 		     *   (s64)initial + backedge_taken_count * step > S64_MAX
2105 		     */
2106 		    backedge_taken_count > ((u64)S64_MAX - initial) / step)
2107 			return false;
2108 		break;
2109 	case BPF_JSLE:
2110 		if (down || (s64)initial > (s64)bound ||
2111 		    check_add_overflow(diff / step, 1, &backedge_taken_count) ||
2112 		    backedge_taken_count > ((u64)S64_MAX - initial) / step)
2113 			return false;
2114 		break;
2115 	case BPF_JSGT:
2116 		if (up || (s64)initial <= (s64)bound ||
2117 		    check_add_overflow((-diff - 1) / -step, 1, &backedge_taken_count) ||
2118 		    /*
2119 		     * The last iteration underflows the signed counter if:
2120 		     *   (s64)initial + backedge_taken_count * step < S64_MIN ⇔
2121 		     *                  backedge_taken_count * step < S64_MIN - (s64)initial ⇔
2122 		     *                         backedge_taken_count > initial - (u64)S64_MIN / -step
2123 		     *	 (direction flips because step < 0)
2124 		     */
2125 		    backedge_taken_count > (initial - (u64)S64_MIN) / -step)
2126 			return false;
2127 		break;
2128 	case BPF_JSGE:
2129 		if (up || (s64)initial < (s64)bound ||
2130 		    check_add_overflow(-diff / -step, 1, &backedge_taken_count) ||
2131 		    backedge_taken_count > (initial - (u64)S64_MIN) / -step)
2132 			return false;
2133 		break;
2134 	case BPF_JNE:
2135 		/*
2136 		 * For a decreasing counter flip the diff and step:
2137 		 *   7 - 2*i ≠ 3 ⇔ 2*i ≠ 7 - 3.
2138 		 */
2139 		diff = down ? -diff : diff;
2140 		step = down ? -step : step;
2141 		if (diff == 0 || diff % step)
2142 			return false;
2143 		backedge_taken_count = diff / step;
2144 		break;
2145 	default:
2146 		return false;
2147 	}
2148 
2149 	/*
2150 	 * max_header_count is u32 and U32_MAX means "infinite",
2151 	 * check to avoid overflow below.
2152 	 */
2153 	if (backedge_taken_count >= U32_MAX - 1)
2154 		return false;
2155 
2156 	/* The header executes once on entry and once for each taken backedge, hence +1. */
2157 	iters->max_header_count = backedge_taken_count + 1;
2158 	/*
2159 	 * The latch is a conditional jump with one jump target exiting the loop.
2160 	 * Linear latch is matched only if the loop has a single backedge.
2161 	 * The loop still, however can have multiple exits.
2162 	 * In such case, conservatively assume that non-latch exit can happen
2163 	 * at any iteration, thus setting minimal number of iterations as 0.
2164 	 */
2165 	iters->min_header_count = loop->exits_cnt == 1 ? iters->max_header_count : 0;
2166 	return true;
2167 }
2168 
2169 static void mark_scev_reg_scratched(struct bpf_verifier_env *env, u32 r)
2170 {
2171 	if (r < MAX_BPF_REG)
2172 		mark_reg_scratched(env, r);
2173 	else
2174 		mark_stack_slot_scratched(env, r - __MAX_BPF_REG);
2175 }
2176 
2177 /*
2178  * An unknown scalar is its own widening.
2179  * Stack bytes without a value are represented by scev->unknown_reg.
2180  */
2181 static bool is_unbound_scev_reg(struct bpf_verifier_env *env, const struct bpf_func_state *st,
2182 				u32 r)
2183 {
2184 	const struct bpf_reg_state *reg = scev_reg_for_read(env, st, r);
2185 
2186 	return reg && reg->type == SCALAR_VALUE && !reg->id && reg->step <= 1 &&
2187 	       tnum_is_unknown(reg->var_off) &&
2188 	       reg->r64.size == U64_MAX && reg->r32.size == U32_MAX;
2189 }
2190 
2191 /* Main logic in verifier.c forbids varying offsets for certain register types. */
2192 static bool is_widenable_reg_type(const struct bpf_reg_state *reg)
2193 {
2194 	if (type_may_be_null(reg->type))
2195 		return false;
2196 
2197 	switch (base_type(reg->type)) {
2198 	case SCALAR_VALUE:
2199 	case PTR_TO_MAP_VALUE:
2200 	case PTR_TO_MAP_KEY:
2201 	case PTR_TO_STACK:
2202 	case PTR_TO_PACKET:
2203 	case PTR_TO_PACKET_META:
2204 	case PTR_TO_MEM:
2205 	case PTR_TO_BUF:
2206 	case PTR_TO_BTF_ID:
2207 		return true;
2208 	default:
2209 		return false;
2210 	}
2211 }
2212 
2213 static void scratch_widened_reg_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2214 {
2215 	switch (base_type(reg->type)) {
2216 	case SCALAR_VALUE:
2217 		reg->id = 0;
2218 		break;
2219 	case PTR_TO_PACKET:
2220 	case PTR_TO_PACKET_META:
2221 		reg->id = ++env->id_gen;
2222 		break;
2223 	default:
2224 		break;
2225 	}
2226 }
2227 
2228 /* Check that ANY leaves can be unioned with r's loop-entry value. */
2229 static bool is_widenable_any(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
2230 			     struct env *header_env, u32 r, u32 id)
2231 {
2232 	const struct bpf_reg_state *reg, *leaf_reg;
2233 	struct scev *scev = env->scev;
2234 	u32 l, ra, rr, leaf, order;
2235 	s64 imm;
2236 
2237 	if (!is_any(scev, id, &l, &rr))
2238 		return false;
2239 	reg = scev_reg_for_read(env, loop_entry, r);
2240 	if (!reg || !is_widenable_reg_type(reg))
2241 		return false;
2242 
2243 	scev->stack_sz = 0;
2244 	expr_stack_push(scev, id);
2245 	while (expr_next(scev, &id, &order)) {
2246 		if (order & DEPTH_LIMIT)
2247 			return false;
2248 		if (!(order & PRE) || is_any(scev, id, &l, &rr))
2249 			continue;
2250 		if (is_imm(scev, id, &imm)) {
2251 			if (reg->type != SCALAR_VALUE)
2252 				return false;
2253 		} else if (is_reg(scev, id, &leaf)) {
2254 			/* Other leaves must denote loop-invariant registers. */
2255 			if (leaf != r &&
2256 			    !(is_reg(scev, header_env->reg2scev[leaf], &ra) && ra == leaf))
2257 				return false;
2258 			leaf_reg = scev_reg_for_read(env, loop_entry, leaf);
2259 			if (!leaf_reg || !bpf_reg_union_compatible(reg, leaf_reg))
2260 				return false;
2261 		} else {
2262 			return false;
2263 		}
2264 	}
2265 	return true;
2266 }
2267 
2268 struct bounds {
2269 	struct cnum64 range;
2270 	u16 base;
2271 	u16 step;
2272 };
2273 
2274 static bool is_simple_linear(struct scev *scev, u32 id, u32 *base_reg, s64 *slope_imm)
2275 {
2276 	u32 base, slope;
2277 
2278 	return is_linear(scev, id, &base, &slope) &&
2279 	       is_reg(scev, base, base_reg) &&
2280 	       is_imm(scev, slope, slope_imm) &&
2281 	       *slope_imm <= S16_MAX &&
2282 	       *slope_imm >= S16_MIN &&
2283 	       *slope_imm != 0;
2284 }
2285 
2286 /*
2287  * Compute the range an induction variable in `reg` spans over the loop.
2288  * If the computation overflows s64 the range is unbounded, only the
2289  * power-of-two alignment survives the wraparound.
2290  */
2291 static void linear_bounds(struct bpf_reg_state *reg, u32 max_header_count, s64 slope,
2292 			  struct bounds *out)
2293 {
2294 	s64 slope_abs = slope < 0 ? -slope : slope;
2295 	s64 min_val = reg_smin(reg);
2296 	s64 max_val = reg_smax(reg);
2297 	s64 total_change;
2298 	bool overflow;
2299 
2300 	overflow = check_mul_overflow(slope, (s64)max_header_count - 1, &total_change) ||
2301 		   (slope > 0 && check_add_overflow(max_val, total_change, &max_val)) ||
2302 		   (slope < 0 && check_add_overflow(min_val, total_change, &min_val));
2303 	/*
2304 	 * If the entry value is a single point the value set is 'v + slope * k',
2305 	 * so the step is |slope|. Otherwise, only the power-of-two alignment
2306 	 * shared by the entry value and the slope.
2307 	 */
2308 	if (cnum64_is_const(reg->r64) && !overflow) {
2309 		out->step = slope_abs;
2310 		out->base = imod(min_val, out->step);
2311 	} else {
2312 		out->step = 1u << min_t(u32, tnum_alignment(reg->var_off), __ffs(slope_abs));
2313 		out->base = 0;
2314 	}
2315 	out->range = overflow ? CNUM64_UNBOUNDED : cnum64_from_srange(min_val, max_val);
2316 }
2317 
2318 static int mark_expr_precise(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 id,
2319 			     unsigned long *precise_regs)
2320 {
2321 	struct scev *scev = env->scev;
2322 	struct bpf_reg_state *reg;
2323 	u32 r, order;
2324 
2325 	scev->stack_sz = 0;
2326 	expr_stack_push(scev, id);
2327 	while (expr_next(scev, &id, &order)) {
2328 		if (order & DEPTH_LIMIT) {
2329 			verifier_bug(env, "scev precision marking exceeds expression depth limit");
2330 			return -EFAULT;
2331 		}
2332 		if (!(order & PRE) || !is_reg(scev, id, &r))
2333 			continue;
2334 		/* Synthetic values have no spilled register to mark precise. */
2335 		reg = scev_reg_for_linear(st, r);
2336 		if (reg && reg->type == SCALAR_VALUE)
2337 			__set_bit(r, precise_regs);
2338 	}
2339 	return 0;
2340 }
2341 
2342 int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2343 			   struct bpf_loop_iters *iters)
2344 {
2345 	struct bpf_func_state *cur_func = st->frame[st->curframe];
2346 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
2347 	struct bpf_verifier_log *log = &env->log;
2348 	struct scev *scev = env->scev;
2349 	struct env *header_env;
2350 	struct linear_latch latch, best;
2351 	struct bpf_backedge *backedge;
2352 	struct bpf_loop_iters tmp;
2353 	struct bpf_loop *loop;
2354 	int insn_idx = st->insn_idx;
2355 	bool found = false;
2356 	int linear_latch;
2357 	u32 r, base_reg;
2358 	int latch_idx;
2359 	s64 slope_imm;
2360 	int err, j;
2361 
2362 	if (!env->allow_uninit_stack)
2363 		return 0;
2364 
2365 	/*
2366 	 * If insn_idx is a loop header for a reducible loop with a single backedge.
2367 	 * loop is NULL for secondary entries to irreducible loops.
2368 	 */
2369 	loop = aux[insn_idx].loop;
2370 	if (!loop || loop->irreducible || loop->backedges_cnt != 1 || loop->backedges_overflow ||
2371 	    loop->exits_overflow) {
2372 		if (log->level & BPF_LOG_LEVEL2)
2373 			bpf_log(log, "loop header at %d, unsupported loop:%s%s%s\n", insn_idx,
2374 				!loop || loop->irreducible ? " irreducible" : "",
2375 				loop && loop->backedges_cnt > 1 ? " multiple backedges" : "",
2376 				loop && loop->exits_overflow ? " too many exits" : "");
2377 		return 0;
2378 	}
2379 
2380 	/* If this backedge has a latch */
2381 	backedge = &loop->backedges[0];
2382 	if (!backedge->latches_cnt) {
2383 		if (log->level & BPF_LOG_LEVEL2)
2384 			bpf_log(log, "loop header at %d, latch not identified\n", insn_idx);
2385 		return 0;
2386 	}
2387 
2388 	/*
2389 	 * Every condition dominating the backedge bounds the number of
2390 	 * iterations from above, keep the smallest bound.
2391 	 */
2392 	for (j = 0; j < backedge->latches_cnt; j++) {
2393 		latch_idx = backedge->latches[j];
2394 		linear_latch = match_linear_latch(env, insn_idx, latch_idx, &latch);
2395 		if (linear_latch < 0)
2396 			return linear_latch;
2397 		if (!linear_latch) {
2398 			if (log->level & BPF_LOG_LEVEL2)
2399 				bpf_log(log, "loop header at %d, non-linear %s at %d\n",
2400 					insn_idx, j ? "exit" : "latch", latch_idx);
2401 			continue;
2402 		}
2403 		if (!compute_max_iters(env, cur_func, &latch, &tmp)) {
2404 			if (log->level & BPF_LOG_LEVEL2)
2405 				bpf_log(log,
2406 					"loop header at %d, can't compute iterations count at %d\n",
2407 					insn_idx, latch_idx);
2408 			continue;
2409 		}
2410 		if (!found || tmp.max_header_count < iters->max_header_count) {
2411 			iters->max_header_count = tmp.max_header_count;
2412 			best = latch;
2413 		}
2414 		iters->min_header_count = found ? min(iters->min_header_count, tmp.min_header_count)
2415 						: tmp.min_header_count;
2416 		found = true;
2417 	}
2418 	if (!found) {
2419 		if (log->level & BPF_LOG_LEVEL2)
2420 			bpf_log(log, "loop header at %d, can't compute iterations count\n", insn_idx);
2421 		return 0;
2422 	}
2423 	latch = best;
2424 
2425 	if (iters->max_header_count == 0) {
2426 		if (log->level & BPF_LOG_LEVEL2)
2427 			bpf_log(log, "loop header at %d, 0 iterations count\n", insn_idx);
2428 		return 0;
2429 	}
2430 
2431 	if (iters->max_header_count == U32_MAX) {
2432 		if (log->level & BPF_LOG_LEVEL2)
2433 			bpf_log(log, "loop header at %d, inf iterations count\n", insn_idx);
2434 		return 0;
2435 	}
2436 
2437 	if (log->level & BPF_LOG_LEVEL2) {
2438 		bpf_log(log, "loop header at %d, header_count is ", insn_idx);
2439 		if (iters->min_header_count == iters->max_header_count)
2440 			bpf_log(log, "%u ", iters->max_header_count);
2441 		else
2442 			bpf_log(log, "[%u..%u] ", iters->min_header_count, iters->max_header_count);
2443 		bpf_log(log, "\n");
2444 	}
2445 
2446 	err = bpf_live_stack_query_init(env, st);
2447 	if (err)
2448 		return err;
2449 
2450 	header_env = find_header_env(scev, insn_idx);
2451 	for (r = 0; r < REGS_NUM; r++) {
2452 		struct bpf_reg_state *reg;
2453 		u32 ra, r_scev, r_expr;
2454 
2455 		if (!scev_reg_alive(env, st, r))
2456 			continue;
2457 		/*
2458 		 * A heuristic:
2459 		 * Ignore SCEVs computed for unbound values and treat those as widened.
2460 		 * This is poor man's modelling of e.g. bpf_probe_read_kernel() effect
2461 		 * on stack, when called from a subprogram. Currently this would produce
2462 		 * an unknown ('?') SCEV as a summary of a subprogram call effects.
2463 		 * Ideally, this should be computed as an OPAQUE value.
2464 		 * However, that would require tracking STACK_MISC writes in the
2465 		 * liveness analysis. Not implemented yet.
2466 		 */
2467 		if (is_unbound_scev_reg(env, cur_func, r))
2468 			continue;
2469 
2470 		r_scev = header_env->reg2scev[r];
2471 		reg = scev_reg_for_linear(cur_func, r);
2472 		/* If SCEV for r is (linear <reg> <slope>) */
2473 		if (is_simple_linear(scev, r_scev, &base_reg, &slope_imm) &&
2474 		    reg && is_widenable_reg_type(reg)) {
2475 			continue;
2476 		}
2477 
2478 		/* rA = rA, loop does not change this reg */
2479 		if (is_reg(scev, r_scev, &ra) && r == ra)
2480 			continue;
2481 
2482 		/* (any 1 (any 2 (any 3 4))) */
2483 		if (is_widenable_any(env, cur_func, header_env, r, r_scev)) {
2484 			continue;
2485 		}
2486 
2487 		if (log->level & BPF_LOG_LEVEL2) {
2488 			r_expr = header_env->reg2expr[r];
2489 			bpf_log(log, "loop header at %d, can't widen ", insn_idx);
2490 			log_reg(env, r);
2491 			bpf_log(log, ", expr is ");
2492 			log_expr(env, r_expr);
2493 			bpf_log(log, "\n");
2494 		}
2495 		return 0;
2496 	}
2497 
2498 	bitmap_zero(iters->precise_regs, REGS_NUM);
2499 	err = mark_expr_precise(env, cur_func, latch.base_expr, iters->precise_regs);
2500 	if (err)
2501 		return err;
2502 	err = mark_expr_precise(env, cur_func, latch.step_expr, iters->precise_regs);
2503 	if (err)
2504 		return err;
2505 	err = mark_expr_precise(env, cur_func, latch.bound_expr, iters->precise_regs);
2506 	if (err)
2507 		return err;
2508 
2509 	return 1;
2510 }
2511 
2512 /* bpf_compute_loop_iters() checked that every leaf can be unioned into acc. */
2513 static int union_any_reg(struct bpf_verifier_env *env, struct bpf_func_state *loop_entry,
2514 			 struct bpf_reg_state *acc, u32 id)
2515 {
2516 	struct bpf_reg_state *tmp = &env->fake_reg[0];
2517 	const struct bpf_reg_state *leaf_reg;
2518 	struct scev *scev = env->scev;
2519 	u32 l, r, leaf, order;
2520 	s64 imm;
2521 	int err;
2522 
2523 	scev->stack_sz = 0;
2524 	expr_stack_push(scev, id);
2525 	while (expr_next(scev, &id, &order)) {
2526 		if (order & DEPTH_LIMIT) {
2527 			verifier_bug(env, "scev ANY union exceeds expression depth limit");
2528 			return -EFAULT;
2529 		}
2530 		if (!(order & PRE) || is_any(scev, id, &l, &r))
2531 			continue;
2532 		if (is_imm(scev, id, &imm)) {
2533 			bpf_mark_reg_known_scalar(tmp, imm);
2534 			leaf_reg = tmp;
2535 		} else if (is_reg(scev, id, &leaf)) {
2536 			leaf_reg = scev_reg_for_read(env, loop_entry, leaf);
2537 			if (verifier_bug_if(!leaf_reg, env, "unreadable SCEV ANY leaf %u", leaf))
2538 				return -EFAULT;
2539 		} else {
2540 			verifier_bug(env, "scev ANY union has an unsupported leaf");
2541 			return -EFAULT;
2542 		}
2543 		err = bpf_reg_union(env, acc, leaf_reg);
2544 		if (err)
2545 			return err;
2546 	}
2547 	return 0;
2548 }
2549 
2550 int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2551 			struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters)
2552 {
2553 	struct bpf_func_state *cur_func = st->frame[st->curframe];
2554 	struct bpf_func_state *entry_func = loop_entry->frame[loop_entry->curframe];
2555 	struct bpf_verifier_log *log = &env->log;
2556 	struct scev *scev = env->scev;
2557 	struct bpf_reg_state *reg;
2558 	struct env *header_env;
2559 	struct bounds bounds;
2560 	u32 r, base_reg, r_expr, a, b;
2561 	int insn_idx = st->insn_idx;
2562 	s64 slope_imm;
2563 	int err;
2564 
2565 	for_each_set_bit(r, iters->precise_regs, REGS_NUM) {
2566 		if (r < MAX_BPF_REG)
2567 			bpf_bt_set_frame_reg(&env->bt, st->curframe, r);
2568 		else
2569 			bpf_bt_set_frame_slot(&env->bt, st->curframe, r - MAX_BPF_REG);
2570 	}
2571 	err = bpf_mark_chain_precision(env, st, -1, NULL);
2572 	if (err)
2573 		return err;
2574 
2575 	header_env = find_header_env(scev, insn_idx);
2576 	for (r = 0; r < REGS_NUM; r++) {
2577 		if (!scev_reg_alive(env, st, r) || is_unbound_scev_reg(env, cur_func, r))
2578 			continue;
2579 
2580 		r_expr = header_env->reg2scev[r];
2581 		/* If SCEV for r is (linear <reg> <slope>)*/
2582 		if (is_simple_linear(scev, r_expr, &base_reg, &slope_imm) &&
2583 		    base_reg == r) {
2584 			err = scev_reg_for_write(env, cur_func, r, &reg);
2585 			if (err)
2586 				return err;
2587 			linear_bounds(reg, iters->max_header_count, slope_imm, &bounds);
2588 			if (log->level & BPF_LOG_LEVEL2) {
2589 				bpf_log(log, "loop header at %d, widening ", insn_idx);
2590 				log_reg(env, r);
2591 				bpf_log(log, " to ");
2592 				bpf_verbose_snum(env, cnum64_smin(bounds.range));
2593 				bpf_log(log, "..");
2594 				bpf_verbose_snum(env, cnum64_smax(bounds.range));
2595 				bpf_log(log, " step %u\n", bounds.step);
2596 			}
2597 			scratch_widened_reg_id(env, reg);
2598 			err = bpf_set_reg_range(env, reg, bounds.range, bounds.base, bounds.step);
2599 			if (err)
2600 				return err;
2601 			mark_scev_reg_scratched(env, r);
2602 		} else if (is_any(scev, r_expr, &a, &b)) {
2603 			err = scev_reg_for_write(env, cur_func, r, &reg);
2604 			if (err)
2605 				return err;
2606 			err = union_any_reg(env, entry_func, reg, r_expr);
2607 			if (err)
2608 				return err;
2609 			if (log->level & BPF_LOG_LEVEL2) {
2610 				bpf_log(log, "loop header at %d, widening ", insn_idx);
2611 				log_reg(env, r);
2612 				bpf_log(log, " to ");
2613 				bpf_verbose_snum(env, reg_smin(reg));
2614 				bpf_log(log, "..");
2615 				bpf_verbose_snum(env, reg_smax(reg));
2616 				bpf_log(log, " step %u\n", reg->step);
2617 			}
2618 			scratch_widened_reg_id(env, reg);
2619 			mark_scev_reg_scratched(env, r);
2620 		}
2621 	}
2622 	return 1;
2623 }
2624 
2625 int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *cur_func_state, u32 insn_idx,
2626 			struct bpf_verifier_state *entry_state, u32 max_header_count)
2627 {
2628 	struct bpf_func_state *entry_st = entry_state->frame[entry_state->curframe];
2629 	struct bpf_verifier_log *log = &env->log;
2630 	struct bpf_reg_state *reg, *entry_reg;
2631 	struct scev *scev = env->scev;
2632 	struct env *header_env;
2633 	struct bounds bounds;
2634 	u32 r, base_reg;
2635 	s64 slope_imm;
2636 	int err;
2637 
2638 	if (entry_state->curframe != cur_func_state->frameno) {
2639 		verifier_bug(env, "clamping registers for a wrong frame: %d vs %d\n",
2640 			     entry_state->curframe, cur_func_state->frameno);
2641 		return -EFAULT;
2642 	}
2643 
2644 	header_env = find_header_env(scev, insn_idx);
2645 	for (r = 0; r < REGS_NUM; r++) {
2646 		/* If SCEV for r is (linear <reg> <slope>)*/
2647 		if (!is_simple_linear(scev, header_env->reg2scev[r], &base_reg, &slope_imm) ||
2648 		    base_reg != r)
2649 			continue;
2650 
2651 		entry_reg = scev_reg_for_linear(entry_st, r);
2652 		reg = scev_reg_for_linear(cur_func_state, r);
2653 		if (!entry_reg || !reg || entry_reg->type == NOT_INIT || reg->type == NOT_INIT ||
2654 		    is_unbound_scev_reg(env, entry_st, r))
2655 			continue;
2656 
2657 		linear_bounds(entry_reg, max_header_count, slope_imm, &bounds);
2658 		bounds.range = cnum64_intersect(reg->r64, bounds.range);
2659 		if (cnum64_is_empty(bounds.range)) {
2660 			verifier_bug(env, "scev clamp produced empty range for r%d", r);
2661 			return -EFAULT;
2662 		}
2663 		if (log->level & BPF_LOG_LEVEL2) {
2664 			bpf_log(log, "loop header at %d, clamping ", insn_idx);
2665 			log_reg(env, r);
2666 			bpf_log(log, " to ");
2667 			bpf_verbose_snum(env, cnum64_smin(bounds.range));
2668 			bpf_log(log, "..");
2669 			bpf_verbose_snum(env, cnum64_smax(bounds.range));
2670 			bpf_log(log, " step %u\n", bounds.step);
2671 		}
2672 		scratch_widened_reg_id(env, reg);
2673 		err = bpf_set_reg_range(env, reg, bounds.range, bounds.base, bounds.step);
2674 		if (err)
2675 			return err;
2676 		mark_scev_reg_scratched(env, r);
2677 	}
2678 	return 0;
2679 }
2680