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