xref: /linux/include/linux/bpf_verifier.h (revision 32e962577d2d8a09fb09d4be2ddf96b82ae447c6)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #ifndef _LINUX_BPF_VERIFIER_H
5 #define _LINUX_BPF_VERIFIER_H 1
6 
7 #include <linux/bpf.h> /* for enum bpf_reg_type */
8 #include <linux/btf.h> /* for struct btf and btf_id() */
9 #include <linux/filter.h> /* for MAX_BPF_STACK */
10 #include <linux/tnum.h>
11 #include <linux/cnum.h>
12 #include <linux/math64.h> /* for div_s64_rem() */
13 
14 /*
15  * Mathematical modulo, the residue of 'v' modulo 'step', normalized to [0, step).
16  * This differs from C's '%' operator, which truncates the quotient toward zero
17  * and so returns a remainder with the sign of the dividend (e.g. -1 % 3 == -1, not 2).
18  */
19 static inline u16 imod(s64 v, u16 step)
20 {
21 	s32 rem;
22 
23 	div_s64_rem(v, step, &rem);
24 	return rem < 0 ? rem + step : rem;
25 }
26 
27 /* Maximum variable offset umax_value permitted when resolving memory accesses.
28  * In practice this is far bigger than any realistic pointer offset; this limit
29  * ensures that umax_value + (int)off + (int)size cannot overflow a u64.
30  */
31 #define BPF_MAX_VAR_OFF	(1 << 29)
32 /* Maximum variable size permitted for ARG_MEM_SIZE[_OR_ZERO].  This ensures
33  * that converting umax_value to int cannot overflow.
34  */
35 #define BPF_MAX_VAR_SIZ	(1 << 29)
36 /*
37  * size of tmp_str_buf in bpf_verifier.
38  * we need at least 1399 bytes to fit full stack mask representation
39  * (in the "-8,-16,...,-2048" form)
40  */
41 #define TMP_STR_BUF_LEN 1408
42 /* Patch buffer size */
43 #define INSN_BUF_SIZE 32
44 
45 #define ITER_PREFIX "bpf_iter_"
46 
47 enum bpf_iter_state {
48 	BPF_ITER_STATE_INVALID, /* for non-first slot */
49 	BPF_ITER_STATE_ACTIVE,
50 	BPF_ITER_STATE_DRAINED,
51 };
52 
53 struct bpf_reg_state {
54 	/* Ordering of fields matters.  See states_equal() */
55 	enum bpf_reg_type type;
56 	/*
57 	 * Constant delta between "linked" scalars with the same ID.
58 	 */
59 	s32 delta;
60 	union {
61 		/* valid when type == PTR_TO_PACKET */
62 		int range;
63 		/*
64 		 * Valid when type == PTR_TO_STACK. Inside the callee two registers
65 		 * can be both PTR_TO_STACK like R1=fp-8 and R2=fp-8, but one of them
66 		 * points to this function stack while another to the caller's stack.
67 		 * To differentiate them 'frameno' is used which is an index in
68 		 * bpf_verifier_state->frame[] array pointing to bpf_func_state.
69 		 */
70 		u8 frameno;
71 
72 		/*
73 		 * For CONST_PTR_TO_MAP, PTR_TO_MAP_KEY, PTR_TO_MAP_VALUE and
74 		 * PTR_TO_INSN.
75 		 */
76 		struct bpf_map *map_ptr;
77 
78 		/* for PTR_TO_BTF_ID */
79 		struct {
80 			struct btf *btf;
81 			u32 btf_id;
82 		};
83 
84 		struct { /* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */
85 			u32 mem_size;
86 		};
87 
88 		/* For dynptr stack slots */
89 		struct {
90 			enum bpf_dynptr_type type;
91 			/* A dynptr is 16 bytes so it takes up 2 stack slots.
92 			 * We need to track which slot is the first slot
93 			 * to protect against cases where the user may try to
94 			 * pass in an address starting at the second slot of the
95 			 * dynptr.
96 			 */
97 			bool first_slot;
98 		} dynptr;
99 
100 		/* For bpf_iter stack slots */
101 		struct {
102 			/* BTF container and BTF type ID describing
103 			 * struct bpf_iter_<type> of an iterator state
104 			 */
105 			struct btf *btf;
106 			u32 btf_id;
107 			/* packing following two fields to fit iter state into 16 bytes */
108 			enum bpf_iter_state state:2;
109 			int depth:30;
110 		} iter;
111 
112 		/* For irq stack slots */
113 		struct {
114 			enum {
115 				IRQ_NATIVE_KFUNC,
116 				IRQ_LOCK_KFUNC,
117 			} kfunc_class;
118 		} irq;
119 
120 		/* Max size from any of the above. */
121 		struct {
122 			unsigned long raw1;
123 			unsigned long raw2;
124 		} raw;
125 
126 		u32 subprogno; /* for PTR_TO_FUNC */
127 	};
128 	/* For scalar types (SCALAR_VALUE), this represents our knowledge of
129 	 * the actual value.
130 	 * For pointer types, this represents the variable part of the offset
131 	 * from the pointed-to object, and is shared with all bpf_reg_states
132 	 * with the same id as us.
133 	 */
134 	struct tnum var_off;
135 	/* Used to determine if any memory access using this register will
136 	 * result in a bad access.
137 	 * These refer to the same value as var_off, not necessarily the actual
138 	 * contents of the register.
139 	 */
140 	struct cnum64 r64; /* 64-bit range as circular number */
141 	struct cnum32 r32; /* 32-bit range as circular number */
142 	/*
143 	 * The value described by this register, interpreted as s64, lies on
144 	 * a line described by a linear equation base + step * k.
145 	 * Invariant: base < step.
146 	 */
147 	u16 base;
148 	u16 step;
149 	/* For PTR_TO_PACKET, used to find other pointers with the same variable
150 	 * offset, so they can share range knowledge.
151 	 * For PTR_TO_MAP_VALUE_OR_NULL this is used to share which map value we
152 	 * came from, when one is tested for != NULL.
153 	 * For PTR_TO_MEM_OR_NULL this is used to identify memory allocation
154 	 * for the purpose of tracking that it's freed.
155 	 * For PTR_TO_SOCKET this is used to share which pointers retain the
156 	 * same reference to the socket, to determine proper reference freeing.
157 	 * For stack slots that are dynptrs, this is used to track references to
158 	 * the dynptr to determine proper reference freeing.
159 	 * Similarly to dynptrs, we use ID to track "belonging" of a reference
160 	 * to a specific instance of bpf_iter.
161 	 */
162 	/*
163 	 * Upper bit of ID is used to remember relationship between "linked"
164 	 * registers. Example:
165 	 * r1 = r2;    both will have r1->id == r2->id == N
166 	 * r1 += 10;   r1->id == N | BPF_ADD_CONST and r1->delta == 10
167 	 * r3 = r2;    both will have r3->id == r2->id == N
168 	 * w3 += 10;   r3->id == N | BPF_ADD_CONST32 and r3->delta == 10
169 	 */
170 #define BPF_ADD_CONST64 (1U << 31)
171 #define BPF_ADD_CONST32 (1U << 30)
172 #define BPF_ADD_CONST (BPF_ADD_CONST64 | BPF_ADD_CONST32)
173 	u32 id;
174 	/*
175 	 * Tracks the parent object this register was derived from.
176 	 * Used for cascading invalidation: when the parent object is
177 	 * released or invalidated, all registers with matching parent_id
178 	 * are also invalidated. For example, a slice from bpf_dynptr_data()
179 	 * gets parent_id set to the dynptr's id.
180 	 */
181 	u32 parent_id;
182 	/*
183 	 * Distinguishes inner-map lookups and their keys and values. Zero for
184 	 * other registers. Kept outside the metadata union for ID remapping
185 	 * during state comparisons.
186 	 */
187 	u32 map_uid:31;
188 	/* if (!precise && SCALAR_VALUE) min/max/tnum don't affect safety */
189 	u32 precise:1;
190 };
191 
192 static inline s64 reg_smin(const struct bpf_reg_state *reg)
193 {
194 	return cnum64_smin(reg->r64);
195 }
196 
197 static inline s64 reg_smax(const struct bpf_reg_state *reg)
198 {
199 	return cnum64_smax(reg->r64);
200 }
201 
202 static inline u64 reg_umin(const struct bpf_reg_state *reg)
203 {
204 	return cnum64_umin(reg->r64);
205 }
206 
207 static inline u64 reg_umax(const struct bpf_reg_state *reg)
208 {
209 	return cnum64_umax(reg->r64);
210 }
211 
212 static inline s32 reg_s32_min(const struct bpf_reg_state *reg)
213 {
214 	return cnum32_smin(reg->r32);
215 }
216 
217 static inline s32 reg_s32_max(const struct bpf_reg_state *reg)
218 {
219 	return cnum32_smax(reg->r32);
220 }
221 
222 static inline u32 reg_u32_min(const struct bpf_reg_state *reg)
223 {
224 	return cnum32_umin(reg->r32);
225 }
226 
227 static inline u32 reg_u32_max(const struct bpf_reg_state *reg)
228 {
229 	return cnum32_umax(reg->r32);
230 }
231 
232 static inline void reg_set_srange32(struct bpf_reg_state *reg, s32 smin, s32 smax)
233 {
234 	reg->r32 = cnum32_from_srange(smin, smax);
235 }
236 
237 static inline void reg_set_urange32(struct bpf_reg_state *reg, u32 umin, u32 umax)
238 {
239 	reg->r32 = cnum32_from_urange(umin, umax);
240 }
241 
242 static inline void reg_set_srange64(struct bpf_reg_state *reg, s64 smin, s64 smax)
243 {
244 	reg->r64 = cnum64_from_srange(smin, smax);
245 }
246 
247 static inline void reg_set_urange64(struct bpf_reg_state *reg, u64 umin, u64 umax)
248 {
249 	reg->r64 = cnum64_from_urange(umin, umax);
250 }
251 
252 enum bpf_stack_slot_type {
253 	STACK_INVALID,    /* nothing was stored in this stack slot */
254 	STACK_SPILL,      /* register spilled into stack */
255 	STACK_MISC,	  /* BPF program wrote some data into this slot */
256 	STACK_ZERO,	  /* BPF program wrote constant zero */
257 	/* A dynptr is stored in this stack slot. The type of dynptr
258 	 * is stored in bpf_stack_state->spilled_ptr.dynptr.type
259 	 */
260 	STACK_DYNPTR,
261 	STACK_ITER,
262 	STACK_IRQ_FLAG,
263 	STACK_POISON,
264 };
265 
266 #define BPF_REG_SIZE 8	/* size of eBPF register in bytes */
267 
268 /*
269  * Largest number of BPF_REG_SIZE stack slots a single frame can have, sized
270  * for the largest stack budget any JIT supports. A frame may use any part of
271  * its program's budget; check_max_stack_depth() enforces the budget on the
272  * combined depth of frames sharing the kernel stack and on each frame using
273  * a private stack.
274  */
275 #define MAX_BPF_STACK_SLOTS	(MAX_BPF_STACK_JIT / BPF_REG_SIZE)
276 
277 /* 4-byte stack slot granularity for liveness analysis */
278 #define BPF_HALF_REG_SIZE	4
279 #define STACK_SLOT_SZ		4
280 
281 #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \
282 			  (1 << BPF_REG_3) | (1 << BPF_REG_4) | \
283 			  (1 << BPF_REG_5))
284 
285 #define BPF_MAIN_FUNC (-1)
286 
287 #define BPF_DYNPTR_SIZE		sizeof(struct bpf_dynptr_kern)
288 #define BPF_DYNPTR_NR_SLOTS		(BPF_DYNPTR_SIZE / BPF_REG_SIZE)
289 
290 struct bpf_stack_state {
291 	struct bpf_reg_state spilled_ptr;
292 	u8 slot_type[BPF_REG_SIZE];
293 };
294 
295 struct bpf_reference_state {
296 	/* Each reference object has a type. Ensure REF_TYPE_PTR is zero to
297 	 * default to pointer reference on zero initialization of a state.
298 	 */
299 	enum ref_state_type {
300 		REF_TYPE_PTR		= (1 << 1),
301 		REF_TYPE_IRQ		= (1 << 2),
302 		REF_TYPE_LOCK		= (1 << 3),
303 		REF_TYPE_RES_LOCK 	= (1 << 4),
304 		REF_TYPE_RES_LOCK_IRQ	= (1 << 5),
305 		REF_TYPE_LOCK_MASK	= REF_TYPE_LOCK | REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ,
306 	} type;
307 	/* Track each reference created with a unique id, even if the same
308 	 * instruction creates the reference multiple times (eg, via CALL).
309 	 */
310 	int id;
311 	/* Instruction where the allocation of this reference occurred. This
312 	 * is used purely to inform the user of a reference leak.
313 	 */
314 	int insn_idx;
315 	union {
316 		/* For REF_TYPE_PTR */
317 		int parent_id;
318 		/* Use to keep track of the source object of a lock, to ensure
319 		 * it matches on unlock.
320 		 */
321 		void *ptr;
322 	};
323 };
324 
325 struct bpf_retval_range {
326 	s32 minval;
327 	s32 maxval;
328 	bool return_32bit;
329 };
330 
331 /* SCEV/widening register space: r0..r10 plus every stack slot of a frame. */
332 #define BPF_SCEV_REGS_NUM (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)
333 
334 struct bpf_loop_iters {
335 	u32 min_header_count;   /* min number of times header is executed */
336 	u32 max_header_count;   /* max number of times header is executed */
337 	unsigned long precise_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
338 };
339 
340 struct loop_stack_entry {
341 	struct bpf_verifier_state *entry_state;
342 	u32 min_header_count;
343 	u32 max_header_count;
344 	u32 loop_id:31;
345 	u32 terminates:1;
346 };
347 
348 #define LOOP_STACK_SIZE 16
349 
350 /* state of the program:
351  * type of all registers and stack info
352  */
353 struct bpf_func_state {
354 	struct bpf_reg_state regs[MAX_BPF_REG];
355 	/* index of call instruction that called into this func */
356 	int callsite;
357 	/* stack frame number of this function state from pov of
358 	 * enclosing bpf_verifier_state.
359 	 * 0 = main function, 1 = first callee.
360 	 */
361 	u32 frameno;
362 	/*
363 	 * Unique diagnostic identity for this function invocation. Frame depth is
364 	 * reused after returns, while this ID is preserved across state clones.
365 	 */
366 	u32 diag_frame_id;
367 	/* subprog number == index within subprog_info
368 	 * zero == main subprog
369 	 */
370 	u32 subprogno;
371 	/* Every bpf_timer_start will increment async_entry_cnt.
372 	 * It's used to distinguish:
373 	 * void foo(void) { for(;;); }
374 	 * void foo(void) { bpf_timer_set_callback(,foo); }
375 	 */
376 	u32 async_entry_cnt;
377 	struct bpf_retval_range callback_ret_range;
378 	bool in_callback_fn;
379 	bool in_async_callback_fn;
380 	bool in_exception_callback_fn;
381 	bool no_stack_arg_load;
382 	/*
383 	 * The helper invokes this callback under rcu_read_lock(), so the
384 	 * callback and its callees run in an RCU read-side critical section.
385 	 */
386 	bool in_rcu_callback_fn;
387 	/* For callback calling functions that limit number of possible
388 	 * callback executions (e.g. bpf_loop) keeps track of current
389 	 * simulated iteration number.
390 	 * Value in frame N refers to number of times callback with frame
391 	 * N+1 was simulated, e.g. for the following call:
392 	 *
393 	 *   bpf_loop(..., fn, ...); | suppose current frame is N
394 	 *                           | fn would be simulated in frame N+1
395 	 *                           | number of simulations is tracked in frame N
396 	 */
397 	u32 callback_depth;
398 	/* Instructions processed in this frame and callees on the current path. */
399 	u32 insns_subtotal;
400 	/*
401 	 * Control-flow loop nesting at the current insn within this frame's
402 	 * subprogram (loops never cross subprogram boundaries).
403 	 */
404 	u32 loop_stack_cnt;
405 
406 	/* The following fields should be last. See copy_func_state() */
407 	/* The state of the stack. Each element of the array describes BPF_REG_SIZE
408 	 * (i.e. 8) bytes worth of stack memory.
409 	 * stack[0] represents bytes [*(r10-8)..*(r10-1)]
410 	 * stack[1] represents bytes [*(r10-16)..*(r10-9)]
411 	 * ...
412 	 * stack[allocated_stack/8 - 1] represents [*(r10-allocated_stack)..*(r10-allocated_stack+7)]
413 	 */
414 	struct bpf_stack_state *stack;
415 	/* Size of the current stack, in bytes. The stack state is tracked below, in
416 	 * `stack`. allocated_stack is always a multiple of BPF_REG_SIZE.
417 	 */
418 	int allocated_stack;
419 
420 	u16 out_stack_arg_cnt; /* Number of outgoing on-stack argument slots */
421 	struct bpf_reg_state *stack_arg_regs; /* Outgoing on-stack arguments */
422 	struct loop_stack_entry *loop_stack;
423 };
424 
425 #define MAX_CALL_FRAMES 16
426 
427 /* instruction history flags, used in bpf_jmp_history_entry.flags field.
428  * Frame number and SPI are stored in dedicated fields of bpf_jmp_history_entry.
429  */
430 enum {
431 	INSN_F_STACK_ACCESS = BIT(0),
432 
433 	INSN_F_DST_REG_STACK = BIT(1), /* dst_reg is PTR_TO_STACK */
434 	INSN_F_SRC_REG_STACK = BIT(2), /* src_reg is PTR_TO_STACK */
435 
436 	INSN_F_STACK_ARG_ACCESS = BIT(3),
437 };
438 
439 /* Registers linked to one jump condition that a history entry can record */
440 #define BPF_LINKED_REGS_MAX	5
441 
442 struct bpf_jmp_history_entry {
443 	/* insn idx can't be bigger than 1 million */
444 	u32 idx : 20;
445 	u32 frame : 4;	/* stack access frame number */
446 	/* special INSN_F_xxx flags */
447 	u32 flags : 4;
448 	u32 : 4;
449 	u32 prev_idx : 20;
450 	u32 spi : 12;	/* stack slot index */
451 	/*
452 	 * Scalar registers and spilled scalars linked to the condition of
453 	 * this jump, which need precision tracking together when the jump is
454 	 * backtracked. Each is packed as 4 bits of frame number, one bit
455 	 * telling a register from a stack slot and 11 bits of register or
456 	 * slot index, see linked_regs_pack().
457 	 */
458 	u16 linked_regs[BPF_LINKED_REGS_MAX];
459 	u8 linked_regs_cnt;
460 };
461 
462 static_assert(MAX_CALL_FRAMES <= (1 << 4));
463 static_assert(MAX_BPF_STACK_SLOTS <= (1 << 12));
464 
465 /* Maximum number of bpf_reg_state objects that can exist at once */
466 #define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS)
467 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \
468 			 MAX_CALL_FRAMES)
469 
470 struct bpf_verifier_state {
471 	/* call stack tracking */
472 	struct bpf_func_state *frame[MAX_CALL_FRAMES];
473 	struct bpf_verifier_state *parent;
474 	/* Acquired reference states */
475 	struct bpf_reference_state *refs;
476 	/*
477 	 * 'branches' field is the number of branches left to explore:
478 	 * 0 - all possible paths from this state reached bpf_exit or
479 	 * were safely pruned
480 	 * 1 - at least one path is being explored.
481 	 * This state hasn't reached bpf_exit
482 	 * 2 - at least two paths are being explored.
483 	 * This state is an immediate parent of two children.
484 	 * One is fallthrough branch with branches==1 and another
485 	 * state is pushed into stack (to be explored later) also with
486 	 * branches==1. The parent of this state has branches==1.
487 	 * The verifier state tree connected via 'parent' pointer looks like:
488 	 * 1
489 	 * 1
490 	 * 2 -> 1 (first 'if' pushed into stack)
491 	 * 1
492 	 * 2 -> 1 (second 'if' pushed into stack)
493 	 * 1
494 	 * 1
495 	 * 1 bpf_exit.
496 	 *
497 	 * Once do_check() reaches bpf_exit, it calls update_branch_counts()
498 	 * and the verifier state tree will look:
499 	 * 1
500 	 * 1
501 	 * 2 -> 1 (first 'if' pushed into stack)
502 	 * 1
503 	 * 1 -> 1 (second 'if' pushed into stack)
504 	 * 0
505 	 * 0
506 	 * 0 bpf_exit.
507 	 * After pop_stack() the do_check() will resume at second 'if'.
508 	 *
509 	 * If is_state_visited() sees a state with branches > 0 it means
510 	 * there is a loop. If such state is exactly equal to the current state
511 	 * it's an infinite loop. Note states_equal() checks for states
512 	 * equivalency, so two states being 'states_equal' does not mean
513 	 * infinite loop. The exact comparison is provided by
514 	 * states_maybe_looping() function. It's a stronger pre-check and
515 	 * much faster than states_equal().
516 	 *
517 	 * This algorithm may not find all possible infinite loops or
518 	 * loop iteration count may be too high.
519 	 * In such cases BPF_COMPLEXITY_LIMIT_INSNS limit kicks in.
520 	 */
521 	u32 branches;
522 	u32 insn_idx;
523 	u32 curframe;
524 
525 	u32 acquired_refs;
526 	u32 active_locks;
527 	u32 active_preempt_locks;
528 	u32 active_irq_id;
529 	u32 active_lock_id;
530 	void *active_lock_ptr;
531 	u32 active_rcu_locks;
532 
533 	bool speculative;
534 	bool in_sleepable;
535 	/* The callee left with unwind_exit. Next insn is unwind_goto. */
536 	bool unwound;
537 
538 	/*
539 	 * First and last insn idx of this verifier state.
540 	 * last_insn_idx is -1 if no instructions have been executed yet.
541 	 */
542 	u32 first_insn_idx;
543 	u32 last_insn_idx;
544 	/* if this state is a backedge state then equal_state
545 	 * records cached state to which this state is equal.
546 	 */
547 	struct bpf_verifier_state *equal_state;
548 	/* jmp history recorded from first to last.
549 	 * backtracking is using it to go from last to first.
550 	 * For most states jmp_history_cnt is [0-3].
551 	 * For loops can go up to ~40.
552 	 */
553 	struct bpf_jmp_history_entry *jmp_history;
554 	u32 jmp_history_cnt;
555 	u32 dfs_depth;
556 	u32 callback_unroll_depth;
557 	u32 may_goto_depth;
558 };
559 
560 /* Number of BPF_REG_SIZE stack slots tracked for the frame so far. */
561 static inline u32 bpf_stack_nr_slots(const struct bpf_func_state *frame)
562 {
563 	return frame->allocated_stack / BPF_REG_SIZE;
564 }
565 
566 /*
567  * Stack slot @spi of @frame, covering bytes [fp - (spi + 1) * 8, fp - spi * 8).
568  * The caller must ensure spi < bpf_stack_nr_slots(frame), see bpf_grow_stack_state().
569  */
570 static inline struct bpf_stack_state *bpf_stack_slot(const struct bpf_func_state *frame, u32 spi)
571 {
572 	return &frame->stack[spi];
573 }
574 
575 static inline struct bpf_reg_state *
576 bpf_get_spilled_reg(int slot, struct bpf_func_state *frame, u32 mask)
577 {
578 	struct bpf_stack_state *ss;
579 
580 	if (slot >= bpf_stack_nr_slots(frame))
581 		return NULL;
582 	ss = bpf_stack_slot(frame, slot);
583 	if ((1 << ss->slot_type[BPF_REG_SIZE - 1]) & mask)
584 		return &ss->spilled_ptr;
585 	return NULL;
586 }
587 
588 static inline struct bpf_reg_state *
589 bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame)
590 {
591 	if (slot < frame->out_stack_arg_cnt &&
592 	    frame->stack_arg_regs[slot].type != NOT_INIT)
593 		return &frame->stack_arg_regs[slot];
594 	return NULL;
595 }
596 
597 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
598 #define bpf_for_each_spilled_reg(iter, frame, reg, mask)			\
599 	for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask);		\
600 	     iter < bpf_stack_nr_slots(frame);				\
601 	     iter++, reg = bpf_get_spilled_reg(iter, frame, mask))
602 
603 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled stack arg. */
604 #define bpf_for_each_spilled_stack_arg(iter, frame, reg)               \
605 	for (iter = 0, reg = bpf_get_spilled_stack_arg(iter, frame);   \
606 	     iter < frame->out_stack_arg_cnt;                          \
607 	     iter++, reg = bpf_get_spilled_stack_arg(iter, frame))
608 
609 #define bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, __stack, __mask, __expr)   \
610 	({                                                               \
611 		struct bpf_verifier_state *___vstate = __vst;            \
612 		int ___i, ___j;                                          \
613 		for (___i = 0; ___i <= ___vstate->curframe; ___i++) {    \
614 			struct bpf_reg_state *___regs;                   \
615 			__state = ___vstate->frame[___i];                \
616 			___regs = __state->regs;                         \
617 			__stack = NULL;                                  \
618 			for (___j = 0; ___j < MAX_BPF_REG; ___j++) {     \
619 				__reg = &___regs[___j];                  \
620 				(void)(__expr);                          \
621 			}                                                \
622 			bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \
623 				if (!__reg)                              \
624 					continue;                        \
625 				__stack = bpf_stack_slot(__state, ___j); \
626 				(void)(__expr);                          \
627 			}                                                \
628 			__stack = NULL;                                  \
629 			bpf_for_each_spilled_stack_arg(___j, __state, __reg) { \
630 				if (!__reg)                              \
631 					continue;                        \
632 				(void)(__expr);                          \
633 			}						 \
634 		}                                                        \
635 		(void)__stack;                                           \
636 	})
637 
638 /* Invoke __expr over regsiters in __vst, setting __state and __reg */
639 #define bpf_for_each_reg_in_vstate(__vst, __state, __reg, __expr)		\
640 	({									\
641 		struct bpf_stack_state * ___stack;                        	\
642 		(void)___stack;							\
643 		bpf_for_each_reg_in_vstate_mask(__vst, __state, __reg, ___stack,\
644 						1 << STACK_SPILL, __expr);	\
645 	})
646 
647 /* linked list of verifier states used to prune search */
648 struct bpf_verifier_state_list {
649 	struct bpf_verifier_state state;
650 	struct list_head node;
651 	u32 miss_cnt;
652 	u32 hit_cnt:31;
653 	u32 in_free_list:1;
654 };
655 
656 struct bpf_loop_inline_state {
657 	unsigned int initialized:1; /* set to true upon first entry */
658 	unsigned int fit_for_inline:1; /* true if callback function is the same
659 					* at each call and flags are always zero
660 					*/
661 	u32 callback_subprogno; /* valid when fit_for_inline is true */
662 };
663 
664 /* pointer and state for maps */
665 struct bpf_map_ptr_state {
666 	struct bpf_map *map_ptr;
667 	bool poison;
668 	bool unpriv;
669 };
670 
671 /* Possible states for alu_state member. */
672 #define BPF_ALU_SANITIZE_SRC		(1U << 0)
673 #define BPF_ALU_SANITIZE_DST		(1U << 1)
674 #define BPF_ALU_NEG_VALUE		(1U << 2)
675 #define BPF_ALU_NON_POINTER		(1U << 3)
676 #define BPF_ALU_IMMEDIATE		(1U << 4)
677 #define BPF_ALU_SANITIZE		(BPF_ALU_SANITIZE_SRC | \
678 					 BPF_ALU_SANITIZE_DST)
679 
680 /*
681  * An array of BPF instructions.
682  * Primary usage: return value of bpf_insn_successors.
683  */
684 struct bpf_iarray {
685 	int cnt;
686 	u32 items[];
687 };
688 
689 #define iarray_for_each(item, arr)						\
690 	for (int ___idx = 0;							\
691 	     ___idx < (arr)->cnt && ({ item = (arr)->items[___idx]; 1; });	\
692 	     ___idx++)
693 
694 #define MAX_BACKEDGES 16
695 #define MAX_LOOP_EXITS 256
696 
697 /* Number of exit conditions dominating a backedge. */
698 #define MAX_LATCHES 4
699 
700 struct bpf_backedge {
701 	int from;
702 	/*
703 	 * Conditional jumps within the loop that dominate 'from' and have
704 	 * a successor outside the loop, nearest first. latches[0] is the
705 	 * latch; the remaining entries are additional exit conditions.
706 	 * Each usable condition gives an upper bound on the iteration count,
707 	 * so keeping only a subset is sound.
708 	 */
709 	int latches[MAX_LATCHES];
710 	u8 latches_cnt;
711 };
712 
713 struct bpf_loop_exit {
714 	int from; /* instruction inside the loop */
715 	int to; /* instruction outside the loop */
716 };
717 
718 struct bpf_loop {
719 	struct bpf_backedge backedges[MAX_BACKEDGES];
720 	/* edges exiting from this loop, includes edges from nested loops */
721 	struct bpf_loop_exit *exits;
722 	int backedges_cnt;
723 	int exits_cnt;
724 	bool irreducible;
725 	bool backedges_overflow;
726 	bool exits_overflow;
727 	/*
728 	 * Loop-entry registers used to compute stack addresses for loads,
729 	 * stores and calls requiring fixed stack offsets, in this and nested
730 	 * loops.
731 	 */
732 	unsigned long store_base_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
733 };
734 
735 struct bpf_insn_aux_data {
736 	union {
737 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
738 		struct bpf_map_ptr_state map_ptr_state;
739 		s32 call_imm;			/* saved imm field of call insn */
740 		u32 alu_limit;			/* limit for add/sub register with pointer */
741 		struct {
742 			u32 map_index;		/* index into used_maps[] */
743 			u32 map_off;		/* offset from value base address */
744 		};
745 		struct {
746 			enum bpf_reg_type reg_type;	/* type of pseudo_btf_id */
747 			union {
748 				struct {
749 					struct btf *btf;
750 					u32 btf_id;	/* btf_id for struct typed var */
751 				};
752 				u32 mem_size;	/* mem_size for non-struct typed var */
753 			};
754 		} btf_var;
755 		/* if instruction is a call to bpf_loop this field tracks
756 		 * the state of the relevant registers to make decision about inlining
757 		 */
758 		struct bpf_loop_inline_state loop_inline_state;
759 	};
760 	union {
761 		/* remember the size of type passed to bpf_obj_new to rewrite R1 */
762 		u64 obj_new_size;
763 		/* remember the offset of node field within type to rewrite */
764 		u64 insert_off;
765 	};
766 	struct btf_struct_meta *kptr_struct_meta;
767 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
768 	/*
769 	 * Per-instruction summary of stack slots in the current frame
770 	 * that this instruction may write to.
771 	 */
772 	DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
773 	DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
774 	u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
775 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
776 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
777 	u64 nospec:1; /* do not execute this instruction speculatively */
778 	u64 nospec_result:1; /* result is unsafe under speculation, nospec must follow */
779 	u64 zext_dst:1; /* this insn zero extends dst reg */
780 	u64 needs_zext:1; /* alu op needs to clear upper bits */
781 	u64 prevent_zext:1; /* alu op cannot be zext (already used with 64-bit scalars) */
782 	u64 non_sleepable:1; /* helper/kfunc may be called from non-sleepable context */
783 	u64 is_iter_next:1; /* bpf_iter_<type>_next() kfunc call */
784 	u64 call_with_percpu_alloc_ptr:1; /* {this,per}_cpu_ptr() with prog percpu alloc */
785 	u64 arena_scalar:1; /* ldx/stx/st/atomic through a number, it's an address in arena */
786 	u64 bb_end:1; /* last instruction of a basic block */
787 	u64 need_scev:1;
788 	u64 alu_state:5; /* used in combination with alu_limit */
789 	/* true if STX or LDX instruction is a part of a spill/fill
790 	 * pattern for a bpf_fastcall call.
791 	 */
792 	u64 fastcall_pattern:1;
793 	/* for CALL instructions, a number of spill/fill pairs in the
794 	 * bpf_fastcall pattern.
795 	 */
796 	u64 fastcall_spills_num:3;
797 	u64 arg_prog:4;
798 	/*
799 	 * What a load found, on any path: an __arena pointer member of a
800 	 * kernel struct, which arena_member_fixup() rewrites, one that is
801 	 * __nullable as well, or anything else through any pointer.
802 	 */
803 	u64 arena_member:1;
804 	u64 arena_member_nullable:1;
805 	u64 non_arena_load:1;
806 
807 	/* below flags are initialized once */
808 	u64 jmp_point:1;
809 	u64 prune_point:1;
810 	/* ensure we check state equivalence and save state checkpoint and
811 	 * this instruction, regardless of any heuristics
812 	 */
813 	u64 force_checkpoint:1;
814 	/* true if instruction is a call to a helper function that
815 	 * accepts callback function as a parameter.
816 	 */
817 	u64 calls_callback:1;
818 	u64 indirect_target:1; /* if it is an indirect jump target */
819 	u64 non_stack_access:1; /* instruction can access non-stack memory */
820 	/* true if some jump or call instruction targets this instruction */
821 	u64 jump_target:1;
822 
823 	unsigned int orig_idx; /* original instruction index, initialized once */
824 	/*
825 	 * CFG strongly connected component this instruction belongs to,
826 	 * zero if it is a singleton SCC.
827 	 */
828 	u32 scc;
829 	/* registers alive before this instruction. */
830 	u16 live_regs_before;
831 	/*
832 	 * Bitmask of R0-R9 that hold known values at this instruction.
833 	 * const_reg_mask: scalar constants that fit in 32 bits.
834 	 * const_reg_map_mask: map pointers, val is map_index into used_maps[].
835 	 * const_reg_subprog_mask: subprog pointers, val is subprog number.
836 	 * const_reg_vals[i] holds the 32-bit value for register i.
837 	 * Populated by compute_const_regs() pre-pass.
838 	 */
839 	u16 const_reg_mask;
840 	u16 const_reg_map_mask;
841 	u16 const_reg_subprog_mask;
842 	u32 const_reg_vals[10];
843 	/*
844 	 * Header index of the innermost loop containing this instruction, -1 if none.
845 	 * For a loop header, identifies the parent loop instead.
846 	 */
847 	s32 loop_header;
848 	/* additional information about the loop if this instruction is a loop header */
849 	struct bpf_loop *loop;
850 };
851 
852 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
853 #define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */
854 
855 /*
856  * Longest line the verifier log can carry: a full stack mask of
857  * MAX_BPF_STACK_SLOTS slots, see TMP_STR_BUF_LEN, plus its prefix.
858  */
859 #define BPF_VERIFIER_TMP_LOG_SIZE	2048
860 
861 struct bpf_verifier_log {
862 	/* Logical start and end positions of a "log window" of the verifier log.
863 	 * start_pos == 0 means we haven't truncated anything.
864 	 * Once truncation starts to happen, start_pos + len_total == end_pos,
865 	 * except during log reset situations, in which (end_pos - start_pos)
866 	 * might get smaller than len_total (see bpf_vlog_reset()).
867 	 * Generally, (end_pos - start_pos) gives number of useful data in
868 	 * user log buffer.
869 	 */
870 	u64 start_pos;
871 	u64 end_pos;
872 	char __user *ubuf;
873 	u32 level;
874 	u32 len_total;
875 	u32 len_max;
876 	char kbuf[BPF_VERIFIER_TMP_LOG_SIZE];
877 };
878 
879 #define BPF_LOG_LEVEL1	1
880 #define BPF_LOG_LEVEL2	2
881 #define BPF_LOG_STATS	4
882 #define BPF_LOG_FIXED	8
883 #define BPF_LOG_LEVEL	(BPF_LOG_LEVEL1 | BPF_LOG_LEVEL2)
884 #define BPF_LOG_MASK	(BPF_LOG_LEVEL | BPF_LOG_STATS | BPF_LOG_FIXED)
885 #define BPF_LOG_KERNEL	(BPF_LOG_MASK + 1) /* kernel internal flag */
886 #define BPF_LOG_MIN_ALIGNMENT 8U
887 #define BPF_LOG_ALIGNMENT 40U
888 
889 static inline bool bpf_verifier_log_needed(const struct bpf_verifier_log *log)
890 {
891 	return log && log->level;
892 }
893 
894 struct bpf_log_attr {
895 	char __user *ubuf;
896 	u32 size;
897 	u32 level;
898 	u32 offsetof_true_size;
899 	bpfptr_t uattr;
900 };
901 
902 int bpf_log_attr_init(struct bpf_log_attr *log, u64 log_buf, u32 log_size, u32 log_level,
903 		      u32 offsetof_log_true_size, bpfptr_t uattr, struct bpf_common_attr *common,
904 		      bpfptr_t uattr_common, u32 size_common);
905 struct bpf_verifier_log *bpf_log_attr_create_vlog(struct bpf_log_attr *attr_log,
906 						  struct bpf_common_attr *common, bpfptr_t uattr,
907 						  u32 size);
908 int bpf_log_attr_finalize(struct bpf_log_attr *attr, struct bpf_verifier_log *log);
909 
910 #define BPF_MAX_SUBPROGS 256
911 
912 /*
913  * A pointer to a static subprog in the value of a frozen read-only array map:
914  * a 64-bit value that is the offset in bytes of the first instruction of
915  * the subprog in the program.
916  */
917 struct bpf_func_ptr {
918 	struct bpf_map *map;
919 	u32 map_off;		/* offset of the pointer in the value of the map */
920 	u32 orig_off;		/* what the map has: the first instruction of the subprog */
921 	u32 xlated_off;		/* the same after instructions were patched and removed */
922 };
923 
924 /* the subprog that a bpf_func_ptr pointed to was removed as dead code */
925 #define BPF_FUNC_PTR_DELETED ((u32)-1)
926 
927 struct bpf_subprog_arg_info {
928 	enum bpf_arg_type arg_type;
929 	union {
930 		u32 mem_size;
931 		u32 btf_id;
932 	};
933 };
934 
935 enum priv_stack_mode {
936 	PRIV_STACK_UNKNOWN,
937 	NO_PRIV_STACK,
938 	PRIV_STACK_ADAPTIVE,
939 };
940 
941 struct bpf_subprog_info {
942 	const char *name; /* name extracted from BTF */
943 	u32 start; /* insn idx of function entry point */
944 	u32 linfo_idx; /* The idx to the main_prog->aux->linfo */
945 	u32 postorder_start; /* The idx to the env->cfg.insn_postorder */
946 	/*
947 	 * Index of one of the BPF_EXIT instructions in this subprogram, or
948 	 * U32_MAX when it has none.
949 	 */
950 	u32 exit_idx;
951 	struct bpf_iarray *jt; /* jump table shared by all gotox of this subprogram */
952 	u16 stack_depth; /* max. stack depth used by this function */
953 	u16 stack_extra;
954 	u32 insns_total;
955 	u32 insns_self;
956 	/* offsets in range [stack_depth .. fastcall_stack_off)
957 	 * are used for bpf_fastcall spills and fills.
958 	 */
959 	s16 fastcall_stack_off;
960 	bool has_tail_call: 1;
961 	bool might_throw: 1;
962 	bool can_unwind: 1; /* has unwind_exit */
963 	bool tail_call_reachable: 1;
964 	bool has_ld_abs: 1;
965 	bool is_cb: 1;
966 	bool is_async_cb: 1;
967 	bool is_exception_cb: 1;
968 	bool args_cached: 1;
969 	/* true if the return value is passed in the R0:R2 register pair */
970 	bool ret_reg_pair: 1;
971 	/* true if bpf_fastcall stack region is used by functions that can't be inlined */
972 	bool keep_fastcall_stack: 1;
973 	bool changes_pkt_data: 1;
974 	bool might_sleep: 1;
975 	u8 arg_slot_cnt:4;
976 
977 	enum priv_stack_mode priv_stack_mode;
978 	struct bpf_subprog_arg_info args[MAX_BPF_FUNC_ARGS];
979 	u16 stack_arg_cnt; /* incoming + max outgoing */
980 	u16 max_out_stack_arg_cnt;
981 };
982 
983 static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
984 {
985 	if (sub->arg_slot_cnt > MAX_BPF_FUNC_REG_ARGS)
986 		return sub->arg_slot_cnt - MAX_BPF_FUNC_REG_ARGS;
987 	return 0;
988 }
989 
990 struct bpf_diag;
991 struct bpf_verifier_env;
992 
993 struct backtrack_state {
994 	struct bpf_verifier_env *env;
995 	u32 frame;
996 	u32 reg_masks[MAX_CALL_FRAMES];
997 	unsigned long stack_masks[MAX_CALL_FRAMES][BITS_TO_LONGS(MAX_BPF_STACK_SLOTS)];
998 	u8 stack_arg_masks[MAX_CALL_FRAMES];
999 };
1000 
1001 struct bpf_id_pair {
1002 	u32 old;
1003 	u32 cur;
1004 };
1005 
1006 struct bpf_idmap {
1007 	u32 tmp_id_gen;
1008 	u32 cnt;
1009 	struct bpf_id_pair map[BPF_ID_MAP_SIZE];
1010 };
1011 
1012 struct bpf_idset {
1013 	u32 num_ids;
1014 	struct {
1015 		u32 id;
1016 		u32 cnt;
1017 	} entries[BPF_ID_MAP_SIZE];
1018 };
1019 
1020 /* see verifier.c:compute_scc_callchain() */
1021 struct bpf_scc_callchain {
1022 	/* call sites from bpf_verifier_state->frame[*]->callsite leading to this SCC */
1023 	u32 callsites[MAX_CALL_FRAMES - 1];
1024 	/* last frame in a chain is identified by SCC id */
1025 	u32 scc;
1026 };
1027 
1028 /* verifier state waiting for propagate_backedges() */
1029 struct bpf_scc_backedge {
1030 	struct bpf_scc_backedge *next;
1031 	struct bpf_verifier_state state;
1032 };
1033 
1034 struct bpf_scc_visit {
1035 	struct bpf_scc_callchain callchain;
1036 	/* first state in current verification path that entered SCC
1037 	 * identified by the callchain
1038 	 */
1039 	struct bpf_verifier_state *entry_state;
1040 	struct bpf_scc_backedge *backedges; /* list of backedges */
1041 	u32 num_backedges;
1042 };
1043 
1044 /* An array of bpf_scc_visit structs sharing tht same bpf_scc_callchain->scc
1045  * but having different bpf_scc_callchain->callsites.
1046  */
1047 struct bpf_scc_info {
1048 	u32 num_visits;
1049 	struct bpf_scc_visit visits[];
1050 };
1051 
1052 struct bpf_liveness;
1053 struct scev;
1054 
1055 struct bpf_fd_array {
1056 	union {
1057 		struct bpf_map *map;
1058 		struct btf *btf;
1059 		unsigned long val;
1060 	};
1061 };
1062 
1063 /* single container for all structs
1064  * one verifier_env per bpf_check() call
1065  */
1066 struct bpf_verifier_env {
1067 	u32 insn_idx;
1068 	u32 prev_insn_idx;
1069 	struct bpf_prog *prog;		/* eBPF program being verified */
1070 	const struct bpf_verifier_ops *ops;
1071 	struct module *attach_btf_mod;	/* The owner module of prog->aux->attach_btf */
1072 	struct bpf_verifier_stack_elem *head; /* stack of verifier states to be processed */
1073 	int stack_size;			/* number of states to be processed */
1074 	bool strict_alignment;		/* perform strict pointer alignment checks */
1075 	bool test_state_freq;		/* test verifier with different pruning frequency */
1076 	bool test_reg_invariants;	/* fail verification on register invariants violations */
1077 	bool arena_scalar;		/* load and store through a number is arena access */
1078 	struct bpf_verifier_state *cur_state; /* current verifier state */
1079 	/* Search pruning optimization, array of list_heads for
1080 	 * lists of struct bpf_verifier_state_list.
1081 	 */
1082 	struct list_head *explored_states;
1083 	struct list_head free_list;	/* list of struct bpf_verifier_state_list */
1084 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
1085 	struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
1086 	struct bpf_map *insn_array_maps[MAX_USED_MAPS]; /* array of INSN_ARRAY map's to be relocated */
1087 	u32 used_map_cnt;		/* number of used maps */
1088 	u32 used_btf_cnt;		/* number of used BTF objects */
1089 	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
1090 	u32 id_gen;			/* used to generate unique reg IDs */
1091 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
1092 	int exception_callback_subprog;
1093 	bool explore_alu_limits;
1094 	bool allow_ptr_leaks;
1095 	/* Allow access to uninitialized stack memory. Writes with fixed offset are
1096 	 * always allowed, so this refers to reads (with fixed or variable offset),
1097 	 * to writes with variable offset and to indirect (helper) accesses.
1098 	 */
1099 	bool allow_uninit_stack;
1100 	bool bpf_capable;
1101 	bool bypass_spec_v1;
1102 	bool bypass_spec_v4;
1103 	bool seen_direct_write;
1104 	/* a global function is verified for BPF_FUNC_CTX_NO_RCU_LOCK */
1105 	bool no_rcu_read_lock;
1106 	bool seen_exception;
1107 	bool signature;
1108 	u32 insn_aux_data_len;
1109 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
1110 	const struct bpf_line_info *prev_linfo;
1111 	struct bpf_verifier_log log;
1112 	struct bpf_diag *diag;
1113 	struct bpf_func_proto bpf_subprog_scratch;
1114 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
1115 	/* subprog indices sorted in topological order: leaves first, callers last */
1116 	int subprog_topo_order[BPF_MAX_SUBPROGS + 2];
1117 	/*
1118 	 * Pointers to static subprogs found in frozen read-only maps of the
1119 	 * program, see resolve_func_ptrs(). Sorted by map and map_off.
1120 	 */
1121 	struct bpf_func_ptr *func_ptrs;
1122 	u32 func_ptr_cnt;
1123 	bool has_callx;
1124 	/*
1125 	 * Call graph edges created by callx instructions. A bitmap of
1126 	 * subprog_cnt * subprog_cnt bits, where bit (caller * subprog_cnt + callee)
1127 	 * is set when the main verification pass sees 'caller' calling 'callee'
1128 	 * via callx. Allocated when the first such edge is recorded.
1129 	 */
1130 	unsigned long *callx_edges;
1131 	union {
1132 		struct bpf_idmap idmap_scratch;
1133 		struct bpf_idset idset_scratch;
1134 	};
1135 	struct {
1136 		int *insn_state;
1137 		int *insn_stack;
1138 		/*
1139 		 * vector of instruction indexes sorted in post-order, grouped by subprogram,
1140 		 * see bpf_subprog_info->postorder_start.
1141 		 */
1142 		int *insn_postorder;
1143 		int *postorder_nums;
1144 		int cur_stack;
1145 		/* current position in the insn_postorder vector */
1146 		int cur_postorder;
1147 		u32 gotox_edges;
1148 		bool subprog_jts_ready;
1149 	} cfg;
1150 	struct backtrack_state bt;
1151 	struct bpf_jmp_history_entry *cur_hist_ent;
1152 	/* Per-callsite snapshot of the parent's tracked spill slots for cross-frame fills. */
1153 	struct spill_snapshot **callsite_at_stack;
1154 	u32 pass_cnt; /* number of times do_check() was called */
1155 	u32 subprog_cnt;
1156 	/* number of instructions analyzed by the verifier */
1157 	u32 prev_insn_processed, insn_processed;
1158 	/* number of jmps, calls, exits analyzed so far */
1159 	u32 prev_jmps_processed, jmps_processed;
1160 	/* maximum combined stack depth */
1161 	u32 max_stack_depth;
1162 	/* stack budget of the program, see bpf_prog_stack_limit() */
1163 	u32 stack_limit;
1164 	/* total verification time */
1165 	u64 verification_time;
1166 	/* maximum number of verifier states kept in 'branching' instructions */
1167 	u32 max_states_per_insn;
1168 	/* total number of allocated verifier states */
1169 	u32 total_states;
1170 	/* some states are freed during program analysis.
1171 	 * this is peak number of states. this number dominates kernel
1172 	 * memory consumption during verification
1173 	 */
1174 	u32 peak_states;
1175 	/* longest register parentage chain walked for liveness marking */
1176 	u32 longest_mark_read_walk;
1177 	u32 free_list_size;
1178 	u32 explored_states_size;
1179 	u32 num_backedges;
1180 	/*
1181 	 * The program's fd_array comes in two shapes, told apart by whether
1182 	 * the caller passed fd_array_cnt. They are mutually exclusive:
1183 	 *  - continuous (fd_array_cnt given): ->fd_array holds every entry
1184 	 *    resolved to its object up front, indexed by fd_array position,
1185 	 *    with ->fd_array_cnt slots; ->fd_array_raw is unused.
1186 	 *  - sparse (no fd_array_cnt): ->fd_array is NULL, and entries are
1187 	 *    read from ->fd_array_raw (the caller's fd_array) and resolved
1188 	 *    on the spot at each reference.
1189 	 */
1190 	struct bpf_fd_array *fd_array;
1191 	u32 fd_array_cnt;
1192 	bpfptr_t fd_array_raw;
1193 
1194 	/* bit mask to keep track of whether a register has been accessed
1195 	 * since the last time the function state was printed
1196 	 */
1197 	u32 scratched_regs;
1198 	/* Same as scratched_regs but for stack slots */
1199 	DECLARE_BITMAP(scratched_stack_slots, MAX_BPF_STACK_SLOTS);
1200 	u64 prev_log_pos, prev_insn_print_pos;
1201 	/* buffer used to temporary hold constants as scalar registers */
1202 	struct bpf_reg_state fake_reg[1];
1203 	/* buffers used to save updated reg states while simulating branches */
1204 	struct bpf_reg_state true_reg1, true_reg2, false_reg1, false_reg2;
1205 	/* buffer used to generate temporary string representations,
1206 	 * e.g., in reg_type_str() to generate reg_type string
1207 	 */
1208 	char tmp_str_buf[TMP_STR_BUF_LEN];
1209 	char tmp_arg_name[32];
1210 	struct bpf_insn insn_buf[INSN_BUF_SIZE];
1211 	struct bpf_insn epilogue_buf[INSN_BUF_SIZE];
1212 	struct bpf_scc_callchain callchain_buf;
1213 	struct bpf_liveness *liveness;
1214 	/* array of pointers to bpf_scc_info indexed by SCC id */
1215 	struct bpf_scc_info **scc_info;
1216 	u32 scc_cnt;
1217 	struct bpf_iarray *succ;
1218 	struct bpf_iarray *gotox_tmp_buf;
1219 	int *idoms;
1220 	struct scev *scev;
1221 };
1222 
1223 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
1224 {
1225 	return &env->prog->aux->func_info_aux[subprog];
1226 }
1227 
1228 static inline struct bpf_subprog_info *subprog_info(struct bpf_verifier_env *env, int subprog)
1229 {
1230 	return &env->subprog_info[subprog];
1231 }
1232 
1233 static inline bool bpf_ret_reg_pair(struct bpf_verifier_env *env, int subprog)
1234 {
1235 	return subprog_info(env, subprog)->ret_reg_pair;
1236 }
1237 
1238 struct bpf_call_summary {
1239 	u8 arg_slot_cnt;
1240 	bool is_void;
1241 	bool fastcall;
1242 };
1243 
1244 static inline bool bpf_helper_call(const struct bpf_insn *insn)
1245 {
1246 	return insn->code == (BPF_JMP | BPF_CALL) &&
1247 	       insn->src_reg == 0;
1248 }
1249 
1250 static inline bool bpf_pseudo_call(const struct bpf_insn *insn)
1251 {
1252 	return insn->code == (BPF_JMP | BPF_CALL) &&
1253 	       insn->src_reg == BPF_PSEUDO_CALL;
1254 }
1255 
1256 static inline bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
1257 {
1258 	return insn->code == (BPF_JMP | BPF_CALL) &&
1259 	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
1260 }
1261 
1262 /* callx: indirect call of a bpf subprog whose address is in insn->dst_reg */
1263 static inline bool bpf_is_callx(const struct bpf_insn *insn)
1264 {
1265 	return insn->code == (BPF_JMP | BPF_CALL | BPF_X);
1266 }
1267 
1268 __printf(2, 0) void bpf_verifier_vlog(struct bpf_verifier_log *log,
1269 				      const char *fmt, va_list args);
1270 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
1271 					   const char *fmt, ...);
1272 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
1273 			    const char *fmt, ...);
1274 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
1275 		  char __user *log_buf, u32 log_size);
1276 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos);
1277 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
1278 
1279 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
1280 				  u32 insn_off,
1281 				  const char *prefix_fmt, ...);
1282 void bpf_verbose_snum(struct bpf_verifier_env *env, s64 num);
1283 
1284 #define verifier_bug_if(cond, env, fmt, args...)						\
1285 	({											\
1286 		bool __cond = (cond);								\
1287 		if (unlikely(__cond))								\
1288 			verifier_bug(env, fmt " (" #cond ")", ##args);				\
1289 		(__cond);									\
1290 	})
1291 #define verifier_bug(env, fmt, args...)								\
1292 	({											\
1293 		BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args);				\
1294 		bpf_log(&env->log, "verifier bug: " fmt "\n", ##args);				\
1295 	})
1296 
1297 static inline void mark_prune_point(struct bpf_verifier_env *env, int idx)
1298 {
1299 	env->insn_aux_data[idx].prune_point = true;
1300 }
1301 
1302 static inline bool bpf_is_prune_point(struct bpf_verifier_env *env, int insn_idx)
1303 {
1304 	return env->insn_aux_data[insn_idx].prune_point;
1305 }
1306 
1307 static inline void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
1308 {
1309 	env->insn_aux_data[idx].force_checkpoint = true;
1310 }
1311 
1312 static inline bool bpf_is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
1313 {
1314 	return env->insn_aux_data[insn_idx].force_checkpoint;
1315 }
1316 
1317 static inline void mark_calls_callback(struct bpf_verifier_env *env, int idx)
1318 {
1319 	env->insn_aux_data[idx].calls_callback = true;
1320 }
1321 
1322 static inline bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
1323 {
1324 	return env->insn_aux_data[insn_idx].calls_callback;
1325 }
1326 
1327 static inline void mark_jmp_point(struct bpf_verifier_env *env, int idx)
1328 {
1329 	env->insn_aux_data[idx].jmp_point = true;
1330 }
1331 
1332 static inline void mark_jump_target(struct bpf_verifier_env *env, int idx)
1333 {
1334 	env->insn_aux_data[idx].jump_target = true;
1335 }
1336 
1337 static inline bool bpf_is_jump_target(struct bpf_verifier_env *env, int insn_idx)
1338 {
1339 	return env->insn_aux_data[insn_idx].jump_target;
1340 }
1341 
1342 static inline struct bpf_func_state *cur_func(struct bpf_verifier_env *env)
1343 {
1344 	struct bpf_verifier_state *cur = env->cur_state;
1345 
1346 	return cur->frame[cur->curframe];
1347 }
1348 
1349 static inline struct bpf_reg_state *cur_regs(struct bpf_verifier_env *env)
1350 {
1351 	return cur_func(env)->regs;
1352 }
1353 
1354 int bpf_prog_offload_verifier_prep(struct bpf_prog *prog);
1355 int bpf_prog_offload_verify_insn(struct bpf_verifier_env *env,
1356 				 int insn_idx, int prev_insn_idx);
1357 int bpf_prog_offload_finalize(struct bpf_verifier_env *env);
1358 void
1359 bpf_prog_offload_replace_insn(struct bpf_verifier_env *env, u32 off,
1360 			      struct bpf_insn *insn);
1361 void
1362 bpf_prog_offload_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt);
1363 
1364 /* this lives here instead of in bpf.h because it needs to dereference tgt_prog */
1365 static inline u64 bpf_trampoline_compute_key(const struct bpf_prog *tgt_prog,
1366 					     struct btf *btf, u32 btf_id)
1367 {
1368 	if (tgt_prog)
1369 		return ((u64)tgt_prog->aux->id << 32) | btf_id;
1370 	else
1371 		return ((u64)btf_obj_id(btf) << 32) | 0x80000000 | btf_id;
1372 }
1373 
1374 /* unpack the IDs from the key as constructed above */
1375 static inline void bpf_trampoline_unpack_key(u64 key, u32 *obj_id, u32 *btf_id)
1376 {
1377 	if (obj_id)
1378 		*obj_id = key >> 32;
1379 	if (btf_id)
1380 		*btf_id = key & 0x7FFFFFFF;
1381 }
1382 
1383 int bpf_prepare_btf_info(struct bpf_verifier_env *env,
1384 			 const union bpf_attr *attr, bpfptr_t uattr);
1385 int bpf_check_core_relo(struct bpf_verifier_env *env,
1386 			const union bpf_attr *attr, bpfptr_t uattr);
1387 int bpf_check_btf_info(struct bpf_verifier_env *env,
1388 		       const union bpf_attr *attr, bpfptr_t uattr);
1389 
1390 int bpf_check_attach_target(struct bpf_verifier_log *log,
1391 			    const struct bpf_prog *prog,
1392 			    const struct bpf_prog *tgt_prog,
1393 			    u32 btf_id,
1394 			    struct bpf_attach_target_info *tgt_info);
1395 int bpf_check_ext_prologue(struct bpf_verifier_log *log,
1396 			   const struct bpf_prog *tgt_prog, u32 btf_id);
1397 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
1398 
1399 int mark_chain_precision(struct bpf_verifier_env *env, int regno);
1400 
1401 int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx);
1402 int bpf_split_cur_state(struct bpf_verifier_env *env);
1403 int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1404 
1405 void bpf_clear_jmp_history(struct bpf_verifier_state *state);
1406 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
1407 			    const struct bpf_verifier_state *src);
1408 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx);
1409 void bpf_free_verifier_state(struct bpf_verifier_state *state, bool free_self);
1410 void bpf_free_backedges(struct bpf_scc_visit *visit);
1411 int bpf_push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
1412 			 int insn_flags, int spi, int frame, const u16 *linked_regs,
1413 			 u8 linked_regs_cnt);
1414 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist);
1415 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
1416 			   struct bpf_reg_state *reg);
1417 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
1418 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg);
1419 int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size);
1420 void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env,
1421 				  struct bpf_verifier_state *st);
1422 void bpf_clear_singular_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1423 int bpf_mark_chain_precision(struct bpf_verifier_env *env,
1424 			     struct bpf_verifier_state *starting_state,
1425 			     int regno, bool *changed);
1426 
1427 static inline int bpf_get_spi(s32 off)
1428 {
1429 	return (-off - 1) / BPF_REG_SIZE;
1430 }
1431 
1432 /*
1433  * Stack a program may use in total: combined over the frames of a call
1434  * chain on the kernel stack, or per frame on a private stack. Any single
1435  * frame may reach that deep. Only a JIT that lays out such frames may go
1436  * beyond MAX_BPF_STACK, the interpreter's frame size, and only one whose
1437  * tail calls let the target set up its own frame: without subprogram
1438  * tail calls, do_misc_fixups() gives every program with tail calls a
1439  * MAX_BPF_STACK frame, which a deeper frame would overrun.
1440  */
1441 static inline u32 bpf_prog_stack_limit(const struct bpf_prog *prog)
1442 {
1443 	/* an offloaded program never runs on the host JIT, whatever it supports */
1444 	if (prog->jit_requested && !bpf_prog_is_offloaded(prog->aux) &&
1445 	    bpf_jit_supports_large_stack() && bpf_jit_supports_subprog_tailcalls())
1446 		return MAX_BPF_STACK_JIT;
1447 	return MAX_BPF_STACK;
1448 }
1449 
1450 /*
1451  * Return the function state a stack pointer register refers to. frameno
1452  * shares storage with other pointer metadata, so return NULL for any
1453  * other register type instead of indexing frame[] with aliased bytes.
1454  */
1455 static inline struct bpf_func_state *bpf_func(struct bpf_verifier_env *env,
1456 					      const struct bpf_reg_state *reg)
1457 {
1458 	struct bpf_verifier_state *cur = env->cur_state;
1459 
1460 	if (reg->type != PTR_TO_STACK)
1461 		return NULL;
1462 	return cur->frame[reg->frameno];
1463 }
1464 
1465 /* Return IP for a given frame in a call stack */
1466 static inline u32 bpf_frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1467 {
1468 	return frame == st->curframe
1469 	       ? st->insn_idx
1470 	       : st->frame[frame + 1]->callsite;
1471 }
1472 
1473 static inline bool bpf_is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
1474 {
1475 	return env->insn_aux_data[insn_idx].jmp_point;
1476 }
1477 
1478 static inline bool bpf_is_spilled_reg(const struct bpf_stack_state *stack)
1479 {
1480 	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1481 }
1482 
1483 static inline int bpf_spill_size(const struct bpf_stack_state *stack)
1484 {
1485 	int i, spill_size = 0;
1486 
1487 	for (i = BPF_REG_SIZE - 1; i >= 0 && stack->slot_type[i] == STACK_SPILL; i--)
1488 		spill_size++;
1489 	return spill_size;
1490 }
1491 
1492 static inline bool bpf_is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1493 {
1494 	return bpf_is_spilled_reg(stack) && stack->spilled_ptr.type == SCALAR_VALUE;
1495 }
1496 
1497 static inline bool bpf_register_is_null(struct bpf_reg_state *reg)
1498 {
1499 	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1500 }
1501 
1502 static inline void bpf_bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
1503 {
1504 	bt->reg_masks[frame] |= 1 << reg;
1505 }
1506 
1507 static inline void bpf_bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
1508 {
1509 	__set_bit(slot, bt->stack_masks[frame]);
1510 }
1511 
1512 static inline void bt_set_frame_stack_arg_slot(struct backtrack_state *bt, u32 frame, u32 slot)
1513 {
1514 	bt->stack_arg_masks[frame] |= 1 << slot;
1515 }
1516 
1517 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
1518 {
1519 	return bt->reg_masks[frame] & (1 << reg);
1520 }
1521 
1522 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
1523 {
1524 	return test_bit(slot, bt->stack_masks[frame]);
1525 }
1526 
1527 bool bpf_map_is_rdonly(const struct bpf_map *map);
1528 struct bpf_func_ptr *bpf_map_func_ptrs(struct bpf_verifier_env *env,
1529 				       const struct bpf_map *map, u32 *cnt);
1530 struct bpf_func_ptr *bpf_map_range_func_ptrs(struct bpf_verifier_env *env,
1531 					     const struct bpf_map *map,
1532 					     u64 off, u64 size, u32 *cnt);
1533 void bpf_adjust_func_ptrs(struct bpf_verifier_env *env, u32 off, u32 len);
1534 void bpf_adjust_func_ptrs_after_remove(struct bpf_verifier_env *env, u32 off, u32 len);
1535 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
1536 			bool is_ldsx);
1537 
1538 #define BPF_BASE_TYPE_MASK	GENMASK(BPF_BASE_TYPE_BITS - 1, 0)
1539 
1540 /* extract base type from bpf_{arg, return, reg}_type. */
1541 static inline u32 base_type(u32 type)
1542 {
1543 	return type & BPF_BASE_TYPE_MASK;
1544 }
1545 
1546 /* extract flags from an extended type. See bpf_type_flag in bpf.h. */
1547 static inline u32 type_flag(u32 type)
1548 {
1549 	return type & ~BPF_BASE_TYPE_MASK;
1550 }
1551 
1552 static inline bool bpf_is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
1553 {
1554 	switch (base_type(type)) {
1555 	case PTR_TO_MEM:
1556 	case PTR_TO_BTF_ID:
1557 		return true;
1558 	default:
1559 		return false;
1560 	}
1561 }
1562 
1563 static inline bool bpf_may_fault_on_deref(enum bpf_reg_type type)
1564 {
1565 	/*
1566 	 * The pointer types which must not be dereferenced without fault
1567 	 * protection, that is, the ones bpf_convert_ctx_accesses() has to
1568 	 * turn a BPF_LDX into a BPF_PROBE_MEM one for.
1569 	 */
1570 	return type == PTR_TO_BTF_ID || (type_flag(type) & PTR_UNTRUSTED);
1571 }
1572 
1573 static inline bool bpf_prog_has_arena_ctx_arg(const struct bpf_prog *prog)
1574 {
1575 	int i;
1576 
1577 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++)
1578 		if (base_type(prog->aux->ctx_arg_info[i].reg_type) == PTR_TO_ARENA)
1579 			return true;
1580 	return false;
1581 }
1582 
1583 static inline enum bpf_prog_type resolve_prog_type(const struct bpf_prog *prog)
1584 {
1585 	return (prog->type == BPF_PROG_TYPE_EXT && prog->aux->saved_dst_prog_type) ?
1586 		prog->aux->saved_dst_prog_type : prog->type;
1587 }
1588 
1589 static inline bool bpf_prog_check_recur(const struct bpf_prog *prog)
1590 {
1591 	switch (resolve_prog_type(prog)) {
1592 	case BPF_PROG_TYPE_TRACING:
1593 		return prog->expected_attach_type != BPF_TRACE_ITER;
1594 	case BPF_PROG_TYPE_STRUCT_OPS:
1595 		return prog->aux->jits_use_priv_stack;
1596 	case BPF_PROG_TYPE_LSM:
1597 	case BPF_PROG_TYPE_SYSCALL:
1598 		return false;
1599 	default:
1600 		return true;
1601 	}
1602 }
1603 
1604 #define BPF_REG_TRUSTED_MODIFIERS (MEM_ALLOC | PTR_TRUSTED | NON_OWN_REF)
1605 
1606 static inline bool bpf_type_has_unsafe_modifiers(u32 type)
1607 {
1608 	return type_flag(type) & ~BPF_REG_TRUSTED_MODIFIERS;
1609 }
1610 
1611 static inline bool type_is_ptr_alloc_obj(u32 type)
1612 {
1613 	return base_type(type) == PTR_TO_BTF_ID &&
1614 	       type_flag(type) & MEM_ALLOC &&
1615 	       !(type_flag(type) & PTR_UNTRUSTED);
1616 }
1617 
1618 static inline bool type_is_non_owning_ref(u32 type)
1619 {
1620 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
1621 }
1622 
1623 static inline bool type_is_map_ptr(enum bpf_reg_type type)
1624 {
1625 	switch (base_type(type)) {
1626 	case CONST_PTR_TO_MAP:
1627 	case PTR_TO_MAP_KEY:
1628 	case PTR_TO_MAP_VALUE:
1629 		return true;
1630 	default:
1631 		return false;
1632 	}
1633 }
1634 
1635 static inline bool type_is_pkt_pointer(enum bpf_reg_type type)
1636 {
1637 	type = base_type(type);
1638 	return type == PTR_TO_PACKET ||
1639 	       type == PTR_TO_PACKET_META;
1640 }
1641 
1642 static inline bool type_is_sk_pointer(enum bpf_reg_type type)
1643 {
1644 	return type == PTR_TO_SOCKET ||
1645 		type == PTR_TO_SOCK_COMMON ||
1646 		type == PTR_TO_TCP_SOCK ||
1647 		type == PTR_TO_XDP_SOCK;
1648 }
1649 
1650 static inline bool type_may_be_null(u32 type)
1651 {
1652 	return type & PTR_MAYBE_NULL;
1653 }
1654 
1655 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
1656 {
1657 	env->scratched_regs |= 1U << regno;
1658 }
1659 
1660 static inline void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
1661 {
1662 	__set_bit(spi, env->scratched_stack_slots);
1663 }
1664 
1665 static inline bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
1666 {
1667 	return (env->scratched_regs >> regno) & 1;
1668 }
1669 
1670 static inline bool stack_slot_scratched(const struct bpf_verifier_env *env, u32 spi)
1671 {
1672 	return test_bit(spi, env->scratched_stack_slots);
1673 }
1674 
1675 static inline bool verifier_state_scratched(const struct bpf_verifier_env *env)
1676 {
1677 	return env->scratched_regs ||
1678 	       !bitmap_empty(env->scratched_stack_slots, MAX_BPF_STACK_SLOTS);
1679 }
1680 
1681 static inline void mark_verifier_state_clean(struct bpf_verifier_env *env)
1682 {
1683 	env->scratched_regs = 0U;
1684 	bitmap_zero(env->scratched_stack_slots, MAX_BPF_STACK_SLOTS);
1685 }
1686 
1687 /* Used for printing the entire verifier state. */
1688 static inline void mark_verifier_state_scratched(struct bpf_verifier_env *env)
1689 {
1690 	env->scratched_regs = ~0U;
1691 	bitmap_fill(env->scratched_stack_slots, MAX_BPF_STACK_SLOTS);
1692 }
1693 
1694 static inline bool bpf_stack_narrow_access_ok(int off, int fill_size, int spill_size)
1695 {
1696 #ifdef __BIG_ENDIAN
1697 	off -= spill_size - fill_size;
1698 #endif
1699 
1700 	return !(off % BPF_REG_SIZE);
1701 }
1702 
1703 static inline bool insn_is_gotox(struct bpf_insn *insn)
1704 {
1705 	return BPF_CLASS(insn->code) == BPF_JMP &&
1706 	       BPF_OP(insn->code) == BPF_JA &&
1707 	       BPF_SRC(insn->code) == BPF_X;
1708 }
1709 
1710 const char *reg_type_str(struct bpf_verifier_env *env, enum bpf_reg_type type);
1711 const char *dynptr_type_str(enum bpf_dynptr_type type);
1712 const char *iter_type_str(const struct btf *btf, u32 btf_id);
1713 const char *iter_state_str(enum bpf_iter_state state);
1714 
1715 void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate,
1716 			  u32 frameno, bool print_all);
1717 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate,
1718 		      u32 frameno);
1719 u32 bpf_vlog_alignment(u32 pos);
1720 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn);
1721 
1722 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
1723 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
1724 int bpf_jmp_offset(struct bpf_insn *insn);
1725 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
1726 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, const unsigned long *stack_mask);
1727 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
1728 
1729 /* Kinds of member a by-value struct or union may be composed of. */
1730 enum btf_member_kind {
1731 	BTF_MEMBER_SCALAR	= BIT(0), /* an int or an enum */
1732 	BTF_MEMBER_ARENA_PTR	= BIT(1), /* a pointer carrying the "arena" type tag */
1733 };
1734 
1735 bool btf_struct_is_composed_of(struct bpf_verifier_env *env, const struct btf *btf,
1736 			       const struct btf_type *t, u32 member_kinds);
1737 u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
1738 
1739 int bpf_find_subprog(struct bpf_verifier_env *env, int off);
1740 bool bpf_is_throw_kfunc(struct bpf_insn *insn);
1741 int bpf_compute_const_regs(struct bpf_verifier_env *env);
1742 int bpf_prune_dead_branches(struct bpf_verifier_env *env);
1743 int bpf_check_cfg(struct bpf_verifier_env *env);
1744 void bpf_free_subprog_jts(struct bpf_verifier_env *env);
1745 int bpf_compute_postorder(struct bpf_verifier_env *env);
1746 int bpf_compute_scc(struct bpf_verifier_env *env);
1747 
1748 struct bpf_map_desc {
1749 	struct bpf_map *ptr;
1750 	int uid;
1751 };
1752 
1753 /* The last initialized dynptr; Populated by process_dynptr_func() */
1754 struct bpf_dynptr_desc {
1755 	enum bpf_dynptr_type type;
1756 	u32 id;
1757 	u32 parent_id;
1758 };
1759 
1760 /*
1761  * The last seen rereferenced object; Updated by update_ref_obj() when a register refers to a
1762  * referenced object. Used when the helper or kfunc is casting a referenced object, returning
1763  * allocated memory derived from referenced object or creating a dynptr with a referenced
1764  * object as parent.
1765  */
1766 struct ref_obj_desc {
1767 	u32 id;
1768 	u32 parent_id;
1769 	u8 cnt;
1770 };
1771 
1772 /*
1773  * Generic MEM_UNINIT arguments, indexed by ABI slot. var_size_mask excludes
1774  * variable-sized buffers from raw mode without losing the output annotation.
1775  * size records constant ranges to mark initialized after checking all arguments,
1776  * only when the caller is allowed to read uninitialized stack memory.
1777  */
1778 struct arg_raw_mem_desc {
1779 	u16 mask;
1780 	u16 var_size_mask;
1781 	int size[MAX_BPF_FUNC_ARGS];
1782 };
1783 
1784 /* Size of PTR_TO_MEM returned, taken from a constant allocation-size argument */
1785 struct ret_mem_desc {
1786 	u32 size;
1787 	bool found;
1788 };
1789 
1790 /* A constant scalar argument; Populated by process_const_arg() */
1791 struct arg_constant_desc {
1792 	u64 value;
1793 	bool found;
1794 };
1795 
1796 struct bpf_call_arg_meta {
1797 	/* Common */
1798 	struct btf *btf;
1799 	u32 func_id;
1800 	const struct bpf_func_proto *fn;
1801 	const struct btf_type *func_proto;
1802 	u8 release_regno;
1803 	u32 ret_btf_id;
1804 	u32 subprogno;
1805 	struct bpf_map_desc map;
1806 	struct bpf_dynptr_desc dynptr;
1807 	struct ref_obj_desc ref_obj;
1808 	struct ret_mem_desc ret_mem;
1809 	struct arg_raw_mem_desc arg_raw_mem;
1810 
1811 	/* Only set by subprog */
1812 	bool subprog_may_change_pkt;
1813 
1814 	/* Only set by kfunc */
1815 	bool r0_rdonly;
1816 	u32 kfunc_flags;
1817 	const char *func_name;
1818 	struct arg_constant_desc arg_constant;
1819 	/* The type of the dynptr that the kfunc writes through */
1820 	enum bpf_dynptr_type dynptr_write_type;
1821 
1822 	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
1823 	 * generally to pass info about user-defined local kptr types to later
1824 	 * verification logic
1825 	 *   bpf_obj_drop/bpf_percpu_obj_drop
1826 	 *     Record the local kptr type to be drop'd
1827 	 *   bpf_refcount_acquire (via ARG_PTR_TO_REFCOUNTED_KPTR arg type)
1828 	 *     Record the local kptr type to be refcount_incr'd and use
1829 	 *     arg_owning_ref to determine whether refcount_acquire should be
1830 	 *     fallible
1831 	 */
1832 	struct btf *arg_btf;
1833 	u32 arg_btf_id;
1834 	bool arg_owning_ref;
1835 
1836 	struct {
1837 		struct btf_field *field;
1838 	} arg_list_head;
1839 	struct {
1840 		struct btf_field *field;
1841 	} arg_rbtree_root;
1842 	struct {
1843 		u8 spi;
1844 		u8 frameno;
1845 	} iter;
1846 
1847 	/* Only set by helper */
1848 	u64 msize_max_value;
1849 	s64 const_map_key;
1850 	struct btf *ret_btf;
1851 	struct btf_field *kptr_field;
1852 };
1853 
1854 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id,
1855 			 const struct bpf_func_proto **ptr);
1856 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, s32 func_id,
1857 			     s16 offset, struct bpf_call_arg_meta *meta);
1858 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn);
1859 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn);
1860 static inline bool bpf_is_iter_next_kfunc(struct bpf_call_arg_meta *meta)
1861 {
1862 	return meta->kfunc_flags & KF_ITER_NEXT;
1863 }
1864 
1865 static inline bool bpf_is_kfunc_sleepable(struct bpf_call_arg_meta *meta)
1866 {
1867 	return meta->kfunc_flags & KF_SLEEPABLE;
1868 }
1869 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta);
1870 struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem);
1871 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off);
1872 bool bpf_insn_is_cond_jump(u8 code);
1873 bool bpf_is_may_goto_insn(struct bpf_insn *insn);
1874 
1875 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn);
1876 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
1877 			  struct bpf_call_summary *cs);
1878 /* Stack effects used for state pruning; must_write implies may_write. */
1879 struct arg_access_info {
1880 	u32 size;		/* Maximum extent; U32_MAX if unknown. */
1881 	u8 may_read:1;		/* Incoming contents or initialization may be needed. */
1882 	u8 may_write:1;
1883 	u8 must_write:1;	/* Prior verifier state is destroyed throughout size. */
1884 };
1885 
1886 struct arg_access_info
1887 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env,
1888 			      struct bpf_insn *insn, int arg, int insn_idx);
1889 struct arg_access_info
1890 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env,
1891 			     struct bpf_insn *insn, int arg, int insn_idx);
1892 struct arg_access_info
1893 bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env,
1894 				      struct bpf_insn *insn, int arg, int insn_idx);
1895 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);
1896 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
1897 			    const struct bpf_reg_state *reg_b);
1898 int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1899 		      struct cnum64 r64, struct cnum32 r32, u16 base, u16 step);
1900 bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b);
1901 int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
1902 		  const struct bpf_reg_state *src);
1903 
1904 int bpf_stack_liveness_init(struct bpf_verifier_env *env);
1905 void bpf_stack_liveness_free(struct bpf_verifier_env *env);
1906 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
1907 const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
1908 bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
1909 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
1910 int bpf_compute_live_registers(struct bpf_verifier_env *env);
1911 
1912 #define BPF_MAP_KEY_POISON	(1ULL << 63)
1913 #define BPF_MAP_KEY_SEEN	(1ULL << 62)
1914 
1915 static inline bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
1916 {
1917 	return aux->map_ptr_state.poison;
1918 }
1919 
1920 static inline bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
1921 {
1922 	return aux->map_ptr_state.unpriv;
1923 }
1924 
1925 static inline bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
1926 {
1927 	return aux->map_key_state & BPF_MAP_KEY_POISON;
1928 }
1929 
1930 static inline bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
1931 {
1932 	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
1933 }
1934 
1935 static inline u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
1936 {
1937 	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
1938 }
1939 
1940 static inline bool bpf_is_mem_insn(struct bpf_insn *insn)
1941 {
1942 	if (BPF_CLASS(insn->code) != BPF_ST &&
1943 	    BPF_CLASS(insn->code) != BPF_STX &&
1944 	    BPF_CLASS(insn->code) != BPF_LDX)
1945 		return false;
1946 
1947 	if (insn->code == (BPF_ST | BPF_NOSPEC))
1948 		return false;
1949 
1950 	return (BPF_MODE(insn->code) == BPF_MEM ||
1951 		BPF_MODE(insn->code) == BPF_MEMSX ||
1952 		BPF_MODE(insn->code) == BPF_ATOMIC);
1953 }
1954 
1955 #define MAX_PACKET_OFF 0xffff
1956 #define CALLER_SAVED_REGS 6
1957 
1958 enum bpf_reg_arg_type {
1959 	SRC_OP,		/* register is used as source operand */
1960 	DST_OP,		/* register is used as destination operand */
1961 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
1962 };
1963 
1964 #define MAX_KFUNC_DESCS 256
1965 /* Each kfunc can have its canonical and one specialized call target. */
1966 #define MAX_KFUNC_CALL_DESCS (MAX_KFUNC_DESCS * 2)
1967 static_assert(MAX_KFUNC_CALL_DESCS <= S16_MAX + 1);
1968 
1969 struct bpf_kfunc_desc {
1970 	struct btf_func_model func_model;
1971 	struct bpf_func_proto proto;
1972 	u32 func_id;
1973 	u16 offset;
1974 	unsigned long addr;
1975 };
1976 
1977 struct bpf_kfunc_desc_tab {
1978 	u32 nr_descs;
1979 	u32 nr_base_descs;
1980 	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
1981 	 * verification. JITs use the descriptor index stored in the finalized
1982 	 * call's off field. The first nr_base_descs entries are the canonical
1983 	 * descriptors used for verifier lookups. Call specialization may append
1984 	 * immutable descriptors for additional targets.
1985 	 *
1986 	 * Grown one entry at a time by bpf_add_kfunc_call() and during
1987 	 * call specialization.
1988 	 */
1989 	struct bpf_kfunc_desc descs[];
1990 };
1991 
1992 /* Functions exported from verifier.c, used by fixups.c */
1993 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog);
1994 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env);
1995 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm);
1996 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset);
1997 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
1998 			 struct bpf_insn *insn_buf, int insn_idx, int *cnt);
1999 
2000 /* Functions exported from verifier.c, used by trampoline.c */
2001 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id,
2002 				  struct bpf_attach_target_info *tgt_info);
2003 
2004 /* Functions in fixups.c, called from bpf_check() */
2005 void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len);
2006 int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env);
2007 int bpf_optimize_bpf_loop(struct bpf_verifier_env *env);
2008 void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env);
2009 int bpf_opt_remove_dead_code(struct bpf_verifier_env *env);
2010 int bpf_opt_remove_nops(struct bpf_verifier_env *env);
2011 int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, const union bpf_attr *attr);
2012 int bpf_convert_ctx_accesses(struct bpf_verifier_env *env);
2013 int bpf_jit_subprogs(struct bpf_verifier_env *env);
2014 int bpf_fixup_call_args(struct bpf_verifier_env *env);
2015 int bpf_do_misc_fixups(struct bpf_verifier_env *env);
2016 int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn);
2017 
2018 int bpf_flip_opcode(u32 opcode);
2019 u8 bpf_rev_opcode(u8 opcode);
2020 
2021 int bpf_compute_idoms(struct bpf_verifier_env *env);
2022 int bpf_compute_loops(struct bpf_verifier_env *env);
2023 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
2024 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
2025 
2026 int bpf_init_scev(struct bpf_verifier_env *env);
2027 void bpf_free_scev(struct bpf_verifier_env *env);
2028 int bpf_compute_scev(struct bpf_verifier_env *env);
2029 
2030 int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2031 			   struct bpf_loop_iters *iters);
2032 int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
2033 			struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters);
2034 int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 insn_idx,
2035 			struct bpf_verifier_state *entry_state, u32 max_header_count);
2036 
2037 #endif /* _LINUX_BPF_VERIFIER_H */
2038